Skip to content

Instantly share code, notes, and snippets.

@stoeckley
Last active January 1, 2018 14:47
Show Gist options
  • Save stoeckley/a51669e6140490ab5590dce24762ddbf to your computer and use it in GitHub Desktop.
Save stoeckley/a51669e6140490ab5590dce24762ddbf to your computer and use it in GitHub Desktop.
different ways of creating a default item in a dictionary if doesn't exist
var dict = [String: [String: Int]]()
if dict["foo"] == nil {
dict["foo"] = [:]
}
dict["foo"]?["bar"] = 5 // safe way to access dictionaries in general
dict["foo"]!["bar"] = 6 // we already tested for nil in the if statement, so force unwrap is safe, and maybe faster?
dict["baz", default: [:]]["boo"] = 7 // avoid if statement completely; no need to first test for "baz" in an if statement
// which of these is best? which has best performance? which is idiomatic swift?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment