Search code examples
swiftboolean

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


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.


Solution

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

    extension String {
    var boolValue: Bool {
        return (self as NSString).boolValue
    }}