Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to Bool in Swift - via API or most Swift-like approach

Tags:

swift

boolean

Is there an API to convert most possible String representations of Boolean values (e.g. "True", "true", "False", "false", "yes", "no", "1", "0") into a Bool in Swift?

If not, what would be the most Swift-like approach to coding this from scratch? Would it be a functional map() operation? Or something else?

The original source data in this instance is JSON, but I'm interested in the crux of solving the problem in the most Swift-like way possible and hence learning more about the language in the process.

like image 739
Andrew Ebling Avatar asked Jan 23 '15 09:01

Andrew Ebling


People also ask

How do I convert a string to a number in Swift?

Using Int initializer Swift provides the function of integer initializers using which we can convert a string into an Int type. To handle non-numeric strings, we can use nil coalescing using which the integer initializer returns an optional integer.

How do you declare a boolean in Swift?

Swift recognizes a value as boolean if it sees true or false . You can implicitly declar a boolean variable let a = false or explicitly declare a boolean variable let i:Bool = true .

What does bool mean in Swift?

Bool represents Boolean values in Swift. Create instances of Bool by using one of the Boolean literals true or false , or by assigning the result of a Boolean method or operation to a variable or constant.


2 Answers

There is not built in way AFAIK. Similar method to standard toInt() could be:

extension String {     var bool: Bool? {         switch self.lowercased() {         case "true", "t", "yes", "y":             return true         case "false", "f", "no", "n", "":             return false         default:             if let int = Int(string) {                 return int != 0             }             return nil         }     } } 
like image 106
Kirsteins Avatar answered Nov 18 '22 16:11

Kirsteins


Typecasting along with a nice String extension and you're up and running

extension String { var boolValue: Bool {     return (self as NSString).boolValue }} 
like image 41
Nicolas Manzini Avatar answered Nov 18 '22 15:11

Nicolas Manzini