Say I have a dictionary of type [String : String]
which I want to transform to type [String : URL]
. I can use map
or flatMap
to transform the dictionary, but due to the failable URL(string:)
initializer, my values are optional:
let source = ["google" : "http://google.com", "twitter" : "http://twitter.com"]
let result = source.flatMap { ($0, URL(string: $1)) }
This returns a value of type [(String, URL?)]
and not [String : URL]
. Is there a one-liner to transform this dictionary with a single method? My first thought was something like:
source.filter { $1 != nil }.flatMap { ($0, URL(string: $1)!) }
But I don't need to check if the value is nil
(values
will never return nil
on a dictionary concrete values), I need to check if the return value of URL(string:)
is nil
.
I could use filter
to remove the nil
values, but this doesn't change the return type:
source.flatMap { ($0, URL(string: $1)) }.filter { $1 != nil }