P Bosman P Bosman - 1 year ago 91
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
be if
text == ""
is the part that holds? But, since I'm only interested in the value of
inside the
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
blocks, but that's pretty hairy-looking.

Answer Source

The equivalent to your code example would be:

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

which yields

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download