LoginSignup
12
2

More than 5 years have passed since last update.

SwiftのDictionaryマージの挙動

Posted at

マージの挙動に自信がなかったのでplaygroundで実行したのをメモがてら記載

実行環境

  • Swift4.2
  • Xcode 10.1
sample.swift
let dictionary = ["apple": "OS X"]

// ダブったキーは上書き、新たなキーは挿入
let mergedDictionary = dictionary.merging(["apple": "macOS", "microsoft": "windows"]) { $1 }
print(mergedDictionary.description)
// ["apple": "macOS", "microsoft": "windows"]

// ダブったキーにuniquingKeysWithでしていした振る舞いが行なわれる(ここでは加算)
let combineDictionary = mergedDictionary.merging(["apple": " mojave", "microsoft": " 10", "google": "Android 9.0"], uniquingKeysWith: +)
print(combineDictionary.description)
//["apple": "macOS mojave", "microsoft": "windows 10", "google": "Android 9.0"]

12
2
0

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
12
2