Skip to content

Instantly share code, notes, and snippets.

@aral
Last active August 29, 2015 14:17
Show Gist options
  • Save aral/f65d30da4aff818af3c4 to your computer and use it in GitHub Desktop.
Save aral/f65d30da4aff818af3c4 to your computer and use it in GitHub Desktop.
AnyObject? to unwrapped value
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.")
}
@jaanus
Copy link

jaanus commented Mar 20, 2015

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