Skip to content

Instantly share code, notes, and snippets.

@saniul
Created January 26, 2015 19:49
Show Gist options
  • Save saniul/1fcf55a33e1fca6109ea to your computer and use it in GitHub Desktop.
Save saniul/1fcf55a33e1fca6109ea to your computer and use it in GitHub Desktop.
// Playground - noun: a place where people can play
//Dynamic Casting in Swift
//http://blog.segiddins.me/2015/01/25/dynamic-casting-in-swift/
let json: NSDictionary = ["count":123,"name":"foobar"]
func id<U>(object: AnyObject?) -> U? {
if let typed = object as? U {
return typed
}
return nil
}
func doubleMaybe(i: Int?) -> Int? {
if let i = i {
return i * 2
}
return nil
}
let count1 = json["count"] as? Int
let doubleCount1 = doubleMaybe(count1)
let doubleCount2 = doubleMaybe(id(json["count"]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment