String to Bool

Hi,

I found out about SE because of a very simple coding issue, that seemed odd.

I found myself needing to convert a string representing a boolean to a Bool. It seemed straight-forward enough, and yet myBoolString.boolValue and Bool(myBoolString) were not available, and by searching on SO, I found that I needed to convert via NSString,

let myBool = (self as NSString).boolValue

This seemed rather odd to me, and I'm wondering why such a basic conversion isn't possible in Swift directly.

Any insights appreciated. Thanks.

Bool has an initializer that takes a String: Apple Developer Documentation

3 Likes

Thank you @suyashsrijan, that makes more sense than going via NSString.

Except that Bool only takes true or false. If the string contains 0 or 1, it returns nil. This is why I tend to use:

let myBool = (self as NSString).boolValue

It will allow you to convert these:

let myBool1 = ("0" as NSString).boolValue
let myBool2 = ("NO" as NSString).boolValue
let myBool3 = ("No" as NSString).boolValue
let myBool4 = ("False" as NSString).boolValue
let myBool5 = ("FALSE" as NSString).boolValue
let myBool6 = ("01" as NSString).boolValue
let myBool7 = ("YES" as NSString).boolValue
let myBool8 = ("Yes" as NSString).boolValue
let myBool9 = ("True" as NSString).boolValue
let myBool10 = ("TRUE" as NSString).boolValue

Something to keep in mind.

2 Likes

Are these any good?

// 1
extension Bool {
    init(from: String) {
        self = (from as NSString).boolValue
    }
}

let booboo = Bool(from: "01")

// 2
extension Bool: ExpressibleByStringLiteral {
    public init(stringLiteral value: String) {
        self = (value as NSString).boolValue
    }
}

let ural: Bool = "01"

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

let blah = "NO".boolValue

#2 + #3?