我想像這樣的代碼:
var someDict: [Int:Bool] = { (0...100).map { someInt -> [Int: String] in (someInt:false) } }
但它不起作用:(
如何正確地將某些值的陣列映射到字典?
uj5u.com熱心網友回復:
你可以這樣使用reduce:
let someDict = (0...100).reduce(into: [Int: Bool]()) { $0[$1] = false }
uj5u.com熱心網友回復:
您可以使用的最少語法涉及AnyIterator無限重復一個值。
Dictionary(uniqueKeysWithValues: zip(0...100, AnyIterator { false }))
uj5u.com熱心網友回復:
答案基于dillon-mce和Joakim Danielson的答案。
之所以需要它,是因為具有默認值的一組鍵的 init 語法很糟糕
非常感謝你們倆!
public extension Dictionary {
static func initFrom<S: Sequence>(_ keys: S, withVal defaultVal: Value) -> Self where S.Element == Key {
return keys.reduce(into: [Key: Value]()) { $0[$1] = defaultVal }
}
}
用法:
//enum FileFilterMode: CaseIterable
let a = Dictionary.initFrom(FileFilterMode.allCases, withVal: false)
let b = Dictionary.initFrom(0...100, withVal: false)
另一種方式:
public extension Sequence {
func toDict<Key: Hashable, Value>(key: KeyPath<Element, Key>, block: (Element)->(Value)) -> [Key:Value] {
var dict: [Key:Value] = [:]
for element in self {
let key = element[keyPath: key]
let value = block(element)
dict[key] = value
}
return dict
}
}
會給你做魔法的能力,比如:
// dict's each key(FileFilterMode) will have value "false"
let a = FileFilterMode.allCases.toDict(key: \.self ) { _ in false }
// set of tuples -> dict[ $0.0 : $0.1 ]
let b = setOfTuples.toDict( key: \.0 ) { _ in $0.1 }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528177.html
標籤:数组迅速字典
下一篇:如何實體化默認地圖?
