Thomas Tempelmann
Thomas Tempelmann

Reputation: 12145

Swift 3: Converting numeric string to Bool, getting false for invalid values

I have to convert strings usually containing an integer number into values of type Bool. The rule would be to get true or any non-zero value. But invalid numbers shall lead to false.

If the strings were always valid numbers, the code would be like this:

let stringValue = "1"
let boolValue = Int(stringValue) != 0

However, that doesn't work if stringValue is empty, because then the Int() function returns nil, and that is unequal to 0, thus the result ends up being true when I want false.

What's an elegant way to solve this in Swift 3? I like to avoid extra lines with if clauses.

Note: If the string could only contain "1" for true values, testing for == 1 would be the answer. But I like to allow other non-zero values for true as well. In other words, I like to have any valid number other than 0 become true.

Upvotes: 1

Views: 2145

Answers (1)

Nirav D
Nirav D

Reputation: 72460

For that you can use Nil-Coalescing Operator.

let boolValue = (Int(stringValue) ?? 0) != 0

Upvotes: 7

Related Questions