How to make sure a string of pure whitespace is invalid with a succinct code in Swift

I am making a section with TextFields and Button("Continue") and then use .disable(isValidAddress) modifier to a whole section to disable the button. The code works well, but I am seeking any solution to make it more succinct with no need to write .hasPrefix() or .hasSuffix() to all parameters one by one.

var isValidAddress: Bool {
    if name.hasPrefix(" ") || street.hasPrefix(" ") || city.hasPrefix(" ") || country.hasPrefix(" ") {
        return false
    } else if name.hasSuffix(" ") || street.hasSuffix(" ") || city.hasSuffix(" ") || country.hasSuffix(" ") {
        return false
    }
        return true
    }

>Solution :

var isValidAddress: Bool {
[street, name, city, etc..].reduce(true, { result, text in
    if text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
        return false
    } else {
        return result
    }
})

}

Leave a Reply