Skip to content

Instantly share code, notes, and snippets.

@kneath
Created April 10, 2015 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kneath/507d631f213e21c8e8cd to your computer and use it in GitHub Desktop.
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/
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