dictionary์ value๋ฅผ ๋ฃ๋๋ฐ nil์ธ ๊ฒฝ์ฐ๋ ๋นผ๊ณ ์ถ๋ค. ๊น๋ํ ๋ฐฉ๋ฒ์ด ์์๊น?
compactMapValues
func compactMapValues<T>(_ transform: (Value) throws -> T?) rethrows -> Dictionary<Key, T>
- ์ผ๋จ ์ด๋ฆ์ด ์ง๊ด์ ์ด๋ค.
- compactMap์ ๊ฒฝ์ฐ ํน์ array์ ๋ํด ๋ณํ ๊ฒฐ๊ณผ์ค nil์ ์ ์ธํ ๊ฒ๋ค์ ๋ฐํํด์ค๋ค.
- ์ด๋ฅผ value์ ์ ์ฉํ๋ค๊ณ ๋ณด๋ฉด ๋ ๊ฒ ๊ฐ๋ค.
์์
let data = ["a": "1", "b": "three", "c": "///4///"]
let m: [String: Int?] = data.mapValues { str in Int(str) }
// ["a": Optional(1), "b": nil, "c": nil]
let c: [String: Int] = data.compactMapValues { str in Int(str) }
// ["a": 1]