Last active
January 1, 2018 14:47
-
-
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
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 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