Declaring URL in Swift 3 Declaring URL in Swift 3 xcode xcode

Declaring URL in Swift 3


Swift 3 has URL (a struct) and NSURL (a class, which it inherits from ObjC). The situation is like String and NSString. You have 2 options to approach this:

1: If you know the URL at the time of declaration:

let url = URL(string: "https://www.apple.com")

2: If you can only find out about the URL later:

var url: URL!// You can check if the variable is initialized by checking it against nil://     if url == nil { /* not initialized */ }// When you are ready to assign it a value:url = URL(string: "https://www.apple.com")


extension URL {    init(_ string: String) {        self.init(string: "\(string)")!    }}

Usage

var unwrappedURL = URL("https://www.google.com")

This will help us to avoid unwrapping the URL everywhere in the code base


I was running into the same issue when I migrated to Swift 3 but, after being stuck, I find realized that I made a class before migration called URL which was now interfering with Foundation's URL struct and making issues.