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.
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.
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 .
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.
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 } } }
Typecasting along with a nice String extension and you're up and running
extension String { var boolValue: Bool { return (self as NSString).boolValue }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With