Reputation: 8461
Say I had the below api :
func paths() -> [String?] {
return ["test", nil, "Two"]
}
And I was using this in a method where I needed [String]
, hence I had to unwrap it using the simple map
function. I'm currently doing :
func cleanPaths() -> [String] {
return paths.map({$0 as! String})
}
Here, the force-cast will cause an error. So technically I need to unwrap the Strings in the paths
array. I'm having some trouble doing this and seem to be getting silly errors. Can someone help me out here?
Upvotes: 18
Views: 12133
Reputation: 170317
compactMap()
can do this for you in one step:
let paths:[String?] = ["test", nil, "Two"]
let nonOptionals = paths.compactMap{$0}
nonOptionals
will now be a String array containing ["test", "Two"]
.
Previously flatMap()
was the proper solution, but has been deprecated for this purpose in Swift 4.1
Upvotes: 46
Reputation: 72770
You should filter first, and map next:
return paths.filter { $0 != .None }.map { $0 as! String }
but using flatMap
as suggested by @BradLarson is a just better
Upvotes: 5
Reputation: 93181
Perhaps what you want to is a filter
followed by a map
:
func cleanPaths() -> [String] {
return paths()
.filter {$0 != nil}
.map {$0 as String!}
}
let x = cleanPaths()
println(x) // ["test", "two"]
Upvotes: 1