【Swift】2つの配列から辞書を作る
これまで(〜Swift3)
let romanStrs = ["M", "D", "C", "L", "X", "V", "I"]
let romanNums = [1000, 500, 100, 50, 10, 5, 1]
let strToNum = zip(romanStrs, romanNums).reduce([String: Int]()) { (dic, t) in
var dic = dic
dic[t.1] = t.0
return dic
}
print(strToNum)
// ["X": 10, "V": 5, "D": 500, "C": 100, "L": 50, "I": 1, "M": 1000]
let romanStrs = ["M", "D", "C", "L", "X", "V", "I"]
let romanNums = [1000, 500, 100, 50, 10, 5, 1]
let strToNum = zip(romanStrs, romanNums).reduce([String: Int]()) { (dic, t) in
var dic = dic
dic[t.1] = t.0
return dic
}
print(strToNum)
// ["X": 10, "V": 5, "D": 500, "C": 100, "L": 50, "I": 1, "M": 1000]
・var
がポイント。
これから(Swift4〜)
let romanStrs = ["M", "D", "C", "L", "X", "V", "I"]
let romanNums = [1000, 500, 100, 50, 10, 5, 1]
let strToNum = zip(romanStrs, romanNums).reduce(into: [String: Int]()) { $0[$1.0] = $1.1 }
print(strToNum)
// ["X": 10, "V": 5, "D": 500, "C": 100, "L": 50, "I": 1, "M": 1000]
let romanStrs = ["M", "D", "C", "L", "X", "V", "I"]
let romanNums = [1000, 500, 100, 50, 10, 5, 1]
let strToNum = zip(romanStrs, romanNums).reduce(into: [String: Int]()) { $0[$1.0] = $1.1 }
print(strToNum)
// ["X": 10, "V": 5, "D": 500, "C": 100, "L": 50, "I": 1, "M": 1000]
5行が1行になりました。
追記
@koher さんからのコメントを記事にも追記します。
let romanStrs = ["M", "D", "C", "L", "X", "V", "I"]
let romanNums = [1000, 500, 100, 50, 10, 5, 1]
let strToNum = Dictionary(uniqueKeysWithValues: zip(romanStrs, romanNums))
print(strToNum)
// ["M": 1000, "I": 1, "X": 10, "D": 500, "C": 100, "L": 50, "V": 5]
参考
Author And Source
この問題について(【Swift】2つの配列から辞書を作る), 我々は、より多くの情報をここで見つけました https://qiita.com/ken0nek/items/8e97692eeaeda6eb5770著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .