LoginSignup
1
0

More than 5 years have passed since last update.

Swift3 Dictionaryの値がnilの要素を削除する方法

Last updated at Posted at 2017-08-17

Ruby on Railsで言う所の Hash#compact のようなものは、Swiftにはなさそうなので、調べてみた。

ちなみに値のOptionalもunwrapする。

let nullableValueDict: [String : Any?] = [
    "a": 1,
    "b": "2",
    "c": nil,
    "d": nil,
    "e": 5
    ]
// ["b": Optional("2"), "e": Optional(5), "a": Optional(1), "d": nil, "c": nil]

let dict = nullableValueDict.reduce([String : Any]()) { (dict, e) in
    guard let value = e.1 else { return dict }
    var dict = dict
    dict[e.0] = value
    return dict
}
// ["b": "2", "e": 5, "a": 1]

reduceを使ったパターンがシンプルで良いかなと。ワンライナーで簡単にできないかなと思ったがそうはいかなかった。

頻繁にやる必要があれば、Dictionaryの extension を作った方が良さそう。

参考

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0