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.