Skip to content

Instantly share code, notes, and snippets.

@thexande

thexande/blog.md Secret

Created December 16, 2018 06:13
Show Gist options
  • Save thexande/12a89cb386d04cfc4f51a965533975e4 to your computer and use it in GitHub Desktop.
Save thexande/12a89cb386d04cfc4f51a965533975e4 to your computer and use it in GitHub Desktop.

The mysterious case of the missing failable URL.init?(string: String?) initializer 

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.

Declaration

init?(string: String)

Discussion

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment