Often times, we have optional String
objects on a model from which we would like to create an optional URL object of typeURL?
. This can be used to set an image asset or begin fetching network resources. Apple provides us with a few ways to do this. It does seem strange that Apple would not provide this initializer directly.
According to Apple's developer documentation, we shoud use the failable initializer for URL
with an empty string to produce a nil
invalid URL
object.
init?(string: String)
Returns
nil
if aURL
cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
This works alright, but looks strange.
https://gist.github.com/a6d227f19e3d27556e2ec857f9313b61
Shouldn't we just be able to transform the optional String?
object into an optional URL object URL?
driectly? Let's flatMap
the optional string to the failable URL initializer which takes a non optional string.
https://gist.github.com/e09ce4ebdeffc62fdd1067384f033b37
This above option well, but it's still alot of typing. Is there any way we could simplify this?
https://gist.github.com/a94e4b55a735c53807db6597d882c7ce
Perfect.