Last active
August 29, 2015 14:17
-
-
Save aral/f65d30da4aff818af3c4 to your computer and use it in GitHub Desktop.
AnyObject? to unwrapped value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let a = NSDictionary(object: NSNumber(bool: true), forKey: "boolKey") | |
let b: AnyObject? = a.objectForKey("boolKey") | |
if let b:AnyObject = b, c:NSNumber = (b as? NSNumber) where c.boolValue == true | |
{ | |
println("It’s true.") | |
} |
a.objectForKey("boolKey") as? Bool will always return a Bool if it's a NSNumber, even if that NSNumber is actually a double. You may want to ensure it is really a bool with:
let number = a.objectForKey("boolKey") as! NSNumber
if number.objCType == NSNumber( bool: true ).objCType {
// number is a Bool
}
It kinda sucks, but it's the only way to know for sure in Swift. In ObjC you can compare the pointers with the singletons @yES / @no.
The usual semantics of casting other types to bools are that 0 is NO/false and anything else is YES/true. This seems to be working correctly with casting directly to Bool even if the NSNumber originally contained a float.
If it’s important to find out more granularly what NSNumber contained originally and what type it was, then of course this shorthand is not sufficient and @fabrice’s solution should be used.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That’s one of the profound things of Swift for me. There is no distinction between “primitive/C” and “object” types, they behave much more similarly.