
let NSHipsterTwo = URL(string: "", relativeTo: nil) //Returns valid NSHipster URL

If the baseURL is nil, it just makes the URL entirely from the URL String, which is probably what the first initializer does under the hood. Similar to the previous initializer, it is a failable one, and takes a similar URL Swift String, but it also takes an optional baseURL object, which is a URL object itself. init ?(string: String, relativeTo: URL ?) This is actually a convenience initializer which defers to the initializer below. Let invalidURL = URL(string: "is a sentence") //Returns nil let NSHipster = URL(string: "") //returns a valid URL If the string does have characters or anything that can’t be converted into a valid URL, this initializer will return nil. This initializer expects only valid characters, it will not percent encode for you. The one I personally have seen the most is %20, the “space” character.
#Iswift request app code#
There are some characters that cannot be used in URLs, and thus are percent encoded, meaning a code that CAN be sent in a URL is used in its place. It is a failable initializer, because not all strings can make valid URLS. This takes your Swift String version of a URL, and changes it into a URL object. This one is the most plain, and probably the most used. There are several initializers and factory methods to create a URL in Swift, but I’m going to cover some of the more useful ones. Stay tuned as we learn a thing or two about creating and using URL objects in your Swift app.


URL objects have many advantages over String paths, most notably that you can access different parts of the URL from properties, instead of having to write your own code to parse those components from the path String. Given the address bar right above you, or any use of a terminal, a Swift String would be a very understandable choice, I mean, that’s all that text is in the address bar, right? Many of the older APIs in the Cocoa and Cocoa Touch SDKs take URLs and Strings (referred to as a “path” in those APIs usually), but things are moving more and more towards just using URL objects everywhere. On Apple platforms, you basically have 2 choices, as a String or aURL. You need to have someway to refer to where they are in your code. They can be in your app bundle, on the file system, or even somewhere on the web. In many types of apps, you have to access files.
