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]

Reference