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

SwiftBoolean

Swift Problem Overview


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.

Swift Solutions


Solution 1 - Swift

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
        }
    }
}

Solution 2 - Swift

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

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

Solution 3 - Swift

In objective-C, we have boolValue for a String. You can convert your string to NSString then use it, if it doesn't exist in Swift

var aString = NSString(string: "tRue")
        
var b = aString.boolValue

b should return true if aString.upperCase == "TRUE"

Update: for Info (just seen in apple API):

var boolValue: Bool { get } // Skips initial space characters (whitespaceSet), or optional -/+ sign followed by zeroes. Returns YES on encountering one of "Y", "y", "T", "t", or a digit 1-9. It ignores any trailing characters.

Update 2: I did a performance test of this method with extension method. The performance of this method is impressional. Here is the code of my test, I've called these functions in a GCD thread, using simulator, one after other.

dispatch_async(dispatch_queue_create("com.haduyenhoa.test", nil), {
            self.test1()
            self.test2()
        })
 

func test1() {
    let testTrue: String = "TRue"
    let testFalse: String = "faLse"
    
    let testNil: String = "whoops!"

    let begin : NSDate = NSDate()
    
    NSLog("BEGIN native")
    var testTrueObjC: NSString
    var testFalseObjC : NSString
    var testNilObjC:NSString
    
    for index in 1...100000 {
        testTrueObjC = NSString(string:testTrue)
         testFalseObjC = NSString(string:testFalse)
        testNilObjC = NSString(string:testNil)
        
        var b1 = testTrueObjC.boolValue // {Some true}
        
        var b2 = testFalseObjC.boolValue // {Some false}
        var b3 = testNilObjC.boolValue // nil
    }
    let end : NSDate = NSDate()
    let interval = end.timeIntervalSinceDate(begin)
   NSLog("DURATION native: \(interval)")
}

func test2() {
    let testTrue: String = "TRue"
    let testFalse: String = "faLse"
    
    let testNil: String = "whoops!"
    
    let begin : NSDate = NSDate()
    NSLog("BEGIN extension")
    for index in 1...100000 {
        var b1 = testTrue.boolValue() // {Some true}
        var b2 = testFalse.boolValue() // {Some false}
        var b3 = testNil.boolValue() // nil
    }
    let end : NSDate = NSDate()
    let interval = end.timeIntervalSinceDate(begin)
    NSLog("DURATION extension: \(interval)")
    
}

The console log:

2015-03-12 14:16:23.238 testSwift3[2343:298787] BEGIN native
2015-03-12 14:16:23.543 testSwift3[2343:298787] DURATION native: 0.305041968822479
2015-03-12 14:16:23.543 testSwift3[2343:298787] BEGIN extension
2015-03-12 14:16:35.360 testSwift3[2343:298787] DURATION extension: 11.8166469931602

We can improve the performance of the extension solution by simplify the rule. The performance is depend on how we implement the rule.

Solution 4 - Swift

Use this,

self.boolType = NSString(string:stringType!).boolValue

Solution 5 - Swift

As already suggested, I would build an extension to String, listing only the string literals you would like to convert to true and false, keeping a nil case for what doesn't convert (or returning false in that case as well? Your choice!). You probably don't want your method to be case sensitive, by the way.

For example:

extension String {
    func boolValue() -> Bool? {
        let trueValues = ["true", "yes", "1"]
        let falseValues = ["false", "no", "0"]
    
        let lowerSelf = self.lowercaseString
    
        if contains(trueValues, lowerSelf) {
            return true
        } else if contains(falseValues, lowerSelf) {
            return false
        } else {
            return nil
        }
    }
}

let testTrue: String = "TRue"
testTrue.boolValue() // {Some true}
let testFalse: String = "faLse"
testFalse.boolValue() // {Some false}
let testNil: String = "whoops!"
testNil.boolValue() // nil

Be careful if you use an NSString object and its boolValue() method, as it returns true if it encounters "Y", "y", "T", "t", or a digit 1-9 (See docs here).

As an example:

let nsString = NSString(string: "tFalse")
nsString.boolValue // true

Solution 6 - Swift

I took Nicolas Manzini's solution and modified it slightly. I recommend using the cast operator because it is bridged between String and NSString. It is unknown if it is a toll-free bridge, but it should have better performance than blindly creating a new object.

extension String {

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

Solution 7 - Swift

No other answers deal with the potential of full or mixed caps strings. So why not take Kirsteins answer, mix it with some computed property magic and shazam:

extension String {
    var bool: Bool? {
	    let lowercaseSelf = self.lowercased()
	
	    switch lowercaseSelf {
	    case "true", "yes", "1":
		    return true
	    case "false", "no", "0":
		    return false
	    default:
		    return nil
	    }
    }
}

Usage would be:

let trueBoolString = "TRUE"   // or "True", "true", "YES", "yEs", and so on
print(trueBoolString.bool)    // true

Solution 8 - Swift

I think easiest way is:

let someString = "true"
let convertedBool = Bool(someString) ?? false

Solution 9 - Swift

Conclusion from above answers:

You Can right simple one line extension and use.

Swift 3

extension String {
    func boolValueFromString() -> Bool {
        return NSString(string: self).boolValue
    }
}

Usage

 if (dictCardData.value(forKey: "isadmin") as! String).boolValueFromString() {
    // Stuff
}

Solution 10 - Swift

 var st = "false"

 extension String {
   func toBool() -> Bool{
    if self == "false" {
        return false
    }else{
        return true
    }
}
}

 if st.toBool() == false {
     println("its ok")
 }

Solution 11 - Swift

I refactored @Kirsteins code as Bool initializer with String value

extension Bool {
    
    init?(string: String) {
        switch string {
        case "True", "true", "yes", "1":
            self = true
        case "False", "false", "no", "0":
            self = false
        default:
            return nil
        }
    }
    
}


// tests
let one = Bool(string: "SDASD") // nil
let two = Bool(string: "0") // false
let three = Bool(string: "true") // true
let four = Bool(string: "null") // nil

Solution 12 - Swift

// Bool to String
var bool = true                         // true
var string = String(describing: bool)   // "true"

// String to Bool
bool = Bool(string) ?? false            // true
string = String(describing: bool)       // "true"

Solution 13 - Swift

If you use once, try this.

let str:String = "1"

var boo:Bool = str == "1" || str == "true" || str == "True" || str == "yes"

Solution 14 - Swift

I prefer this implementation that handles optional strings and has a default value of false

extension Bool {
    init(_ string: String?) {
        guard let string = string else { self = false; return }
    
        switch string.lowercased() {
        case "true", "yes", "1":
            self = true
        default:
            self = false
        }
    }
}

Solution 15 - Swift

one line solution for optional string

let value:String? = "put some string or even just nil here"
let trueOrFalse = NSString(string: value ?? "").boolValue

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrew EblingView Question on Stackoverflow
Solution 1 - SwiftKirsteinsView Answer on Stackoverflow
Solution 2 - SwiftNicolas ManziniView Answer on Stackoverflow
Solution 3 - SwiftDuyen-HoaView Answer on Stackoverflow
Solution 4 - SwiftAlex MilousseView Answer on Stackoverflow
Solution 5 - SwiftParaView Answer on Stackoverflow
Solution 6 - SwiftjangelsbView Answer on Stackoverflow
Solution 7 - SwiftadamjanschView Answer on Stackoverflow
Solution 8 - SwiftIvan PorkolabView Answer on Stackoverflow
Solution 9 - SwiftChetan PrajapatiView Answer on Stackoverflow
Solution 10 - SwiftMuhammad RazaView Answer on Stackoverflow
Solution 11 - SwiftbuxikView Answer on Stackoverflow
Solution 12 - SwiftUladzimirView Answer on Stackoverflow
Solution 13 - SwiftPaco_BBView Answer on Stackoverflow
Solution 14 - SwiftdooversView Answer on Stackoverflow
Solution 15 - SwiftNikolay ShubenkovView Answer on Stackoverflow