Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring URL in Swift 3

How can I declare a URL in swift 3?

This is my attempted code:

var messageURL: URL = URL()

OR

var messageURL: Foundation.URL = URL()

This is the error: Cannot invoke initializer for type 'URL' with no arguments

Here's some documentation (Swift 3.0) from Apple that I'm having trouble implementing:

Properties whose name conflicts with Foundation types after removing their NS prefix will lead to module-qualified type names. For example, if there is a var URL: NSURL, it will be rewritten as var URL: Foundation.URL

like image 565
Albert Ghar Avatar asked Sep 17 '16 05:09

Albert Ghar


3 Answers

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")
like image 141
Code Different Avatar answered Nov 16 '22 07:11

Code Different


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

like image 40
vijeesh Avatar answered Nov 16 '22 08:11

vijeesh


In Swift 3 URL has many initializers but all of them take an argument, either string or data.

like image 1
Mohsen Hossein pour Avatar answered Nov 16 '22 08:11

Mohsen Hossein pour