I'm having trouble figuring out Swift 2's particular style of map
:
I'm reading in a dictionary (from a plist file), so I've got an [String: AnyObject]
:
let dictionary = NSDictionary(contentsOfFile: path) as? [String: AnyObject]
My goal is to transform from a dictionary of Strings
into a dictionary of logger instances. This would be [String: XCGLogger]
:
let loggers = dictionary
.map { (n, l) in [ n: newLogger(l.0, withLevel: level(l.1)) ] }
However, this is returning an [[String: XCGLogger]]
(which looks like an array of dictionaries to me). The question is how do I return a flattened dictionary. When I try to use flatMap
I start running in circles around errors about closures or not being able to call flatMap on a type (Key, Value) -> NSDictionary
.
The reason is that map
can return only arrays, and not dictionaries. To obtain a dictionary you have several strategies, for instance:
var loggers : [String: XCGLogger] = [:]
dictionary.map{(n, l) in loggers[n] = newLogger(l.0, withLevel: level(l.1))}
or perhaps:
var loggers : [String: XCGLogger] = [:]
for (n, l) in dictionary {
loggers[n] = newLogger(l.0, withLevel: level(l.1))
}
loggers
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments