P Bosman P Bosman - 7 months ago 25
Swift Question

Swift: Combine condition and if-let with logical or

I am trying to do something that would logically look like this:

if text == "" || let i = Int(text) where i < 2 {
// do something; don't care about the value of i
}


Of course this isn't a valid condition -- what would the value of
i
be if
text == ""
is the part that holds? But, since I'm only interested in the value of
i
inside the
where
clause, I was hoping there is a nice way of achieving the same effect, namely executing the same closure if either condition holds. My current solution is to extract the closure and call it from two separate
if
blocks, but that's pretty hairy-looking.

Answer

The equivalent to your code example would be:

if text == "" || Int(text) ?? 2 < 2 {
    print("valid")
    // do your previous "something
} else {
    print("invalid")
}

which yields

"" -> valid
"1" -> valid
"2" -> invalid
"abc" -> invalid