Created
April 10, 2015 01:10
-
-
Save kneath/507d631f213e21c8e8cd to your computer and use it in GitHub Desktop.
Clean example of using Swift 1.2's improved optional binding via http://nshipster.com/swift-1.2/
This file contains 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
var users: [User] = [] | |
// load and parse the JSON into an array | |
if let | |
path = NSBundle.mainBundle().pathForResource("users", ofType: "json"), | |
url = NSURL(fileURLWithPath: path), | |
data = NSData(contentsOfURL: url), | |
userList = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? [[String: AnyObject]] | |
{ | |
// extract individual users | |
for userDict in userList { | |
if let | |
id = userDict["id"] as? Int, | |
name = userDict["name"] as? String, | |
email = userDict["email"] as? String, | |
address = userDict["address"] as? [String: AnyObject] | |
{ | |
users.append(User(id: id, name: name, ...)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment