Home > Enterprise >  Swift - how to map array to dictionary values?
Swift - how to map array to dictionary values?

Time:11-07

I imagine code similar to this:

var someDict: [Int:Bool] = { (0...100).map { someInt -> [Int: String] in (someInt:false) } }

but it does not work :(

How to properly map array of some value to dictionary?

CodePudding user response:

You could use reduce like this:

let someDict = (0...100).reduce(into: [Int: Bool]()) { $0[$1] = false }

CodePudding user response:

Answer based on answer of dillon-mce and Joakim Danielson.

It's needed because of horrible syntax of init of set of keys with default values

Thanks a lot for both of you!

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 }
    }
}

usage:

//enum FileFilterMode: CaseIterable
let a = Dictionary.initFrom(FileFilterMode.allCases, withVal: false)

let b = Dictionary.initFrom(0...100, withVal: false)

Another way:

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
    }
}

will give you ability to do magic like:

// 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 }
  • Related