Here’s How to Construct a Swift Type from a String

Here’s How to Construct a Swift Type from a String

The transcript of the video

If we need a URL, we initialize it using the following syntax:

var url = URL(string: “”)

That’s pretty straightforward, but wouldn’t it be cool to create a url just like this:

var url = “” ?

If we tried that, we’d get a compiler error. Actually, we can make it work with just a little bit of coding. And here’s how!

Swift has a protocol called ExpressibleByStringLiteral. If we make a type adapt it, we can create instances of that type from a string.

Here’s the official documentation: 


A type that can be initialized with a string literal.

All right, so all we need to do is to make the URL type adopt the ExpressibleByStringLiteral protocol. We can’t modify the URL type directly since we do not own its source. However, thank to type extensions, we can make any type adopt a protocol, even if we can’t modify its source code.

Let’s create a URL extension. I’ll make it conform to the ExpressibleByStringLiteral. 

extension URL: ExpressibleByStringLiteral {


Now we get a compiler error. What’s missing? We have to implement the public initializer.
The value argument should be of type String. And we initialize ‘self’, which represents the URL instance through the usual URL initializer. The initialiazer needs to return a valid URL so I force-unwrap the result.

extension URL: ExpressibleByStringLiteral {

    public init(stringLiteral value: String) {

        self = URL(string: value)!



Now we can create URLs out of plain strings. Just like this:

var url: URL = “”

I marked the url variable explicitely as being of type URL. Otherwise, Swift’s type inference engine would assume it’s a String.

Notice that we have some more similar protocols: 

  • ExpressibleByArrayLiteral, 
  • ExpressibleByNilLiteral, 
  • ExpressibleByIntegerLiteral, 
  • ExpressibleByFloatLiteral, 
  • ExpressibleByBooleanLiteral, 
  • ExpressibleByDictionaryLiteral

That’s it for today! Don’t forget to press like if you enjoyed this video, and also hit subscribe if you haven’t done so already.

Thanks for watching!

By | 2018-07-09T08:08:56+00:00 July 9th, 2018|iOS Programming, Swift, Swift 4, Swift Programming, Videos|0 Comments

About the Author:

Leave A Comment