我想象类似这样的代码:
var someDict: [Int:Bool] = { (0...100).map { someInt -> [Int: String] in (someInt:false) } }
,但它不工作:(
如何正确映射数组的一些值字典?
您可以使用的最少的语法包括AnyIterator
来无限地重复一个值。
Dictionary(uniqueKeysWithValues: zip(0...100, AnyIterator { false }))
您可以这样使用reduce
:
let someDict = (0...100).reduce(into: [Int: Bool]()) { $0[$1] = false }
基于 jesse的答案的答案, dillon-mce and Joakim Danielson非常感谢!
这是必要的,因为init的语法很糟糕,默认值
extension Dictionary {
init<S: Sequence>(_ keys: S, withVal defaultVal: Value) where S.Element == Key {
self = Dictionary( uniqueKeysWithValues: zip(keys, AnyIterator { defaultVal }) )
}
}
用法:
//enum FileFilterMode: CaseIterable
let a = Dictionary(FileFilterMode.allCases, withVal: false)
let b = Dictionary(0...100, withVal: false)
<标题>的另一种方式:public extension Sequence {
func toDict<Key: Hashable, Value>(block: (Element)->(Value)) -> [Key:Value] where Key == Self.Element {
self.toDict(key: .self, block: block)
}
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 keys 0...100 will have value "false"
let a = (0...100).toDict() { _ in false }
// set of tuples -> dict[ $0.0 : $0.1 ]
let b = setOfTuples.toDict( key: .0 ) { _ in $0.1 }
标题>