Skip to content

Instantly share code, notes, and snippets.

@niwatako
Last active March 28, 2016 02:35
Show Gist options
  • Save niwatako/87a62c854c4c65fef6b8 to your computer and use it in GitHub Desktop.
Save niwatako/87a62c854c4c65fef6b8 to your computer and use it in GitHub Desktop.
Dictionary と nil, Optional Swift の Dictionary で nil を扱うhttps://ez-net.jp/article/1C/t1D5_SZN/hZ0evGOf9-uc/ #CodePiece
// Dictionary と nil
// nil を代入すると"hoge"キーは消える
var dic: [String: Int] = ["hoge": 1, "foo": 2]
dic["hoge"] = nil
dic // ["foo": 2]
// Valueの型を Int? にしても、nil を代入すると"hoge"キーは消える
var dic2: [String: Int?] = ["hoge": 1, "foo": 2]
dic2["hoge"] = nil
dic2 // ["foo": {Some 2}]
// Valueの型を Int? にして、Optional<Int>()を代入すると"hoge"キーは残る
var dic3: [String: Int?] = ["hoge": 1, "foo": 2]
dic3["hoge"] = Optional<Int>()
dic3 // ["hoge": nil, "foo": {Some 2}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment