GuravS
GuravS

Reputation: 27

Cannot invoke initializer for type 'URL' with no arguments - Swift 3

Receive error:

Cannot invoke initializer for type 'URL' with no arguments

Following is the code -

 var databasePath = URL()

I have declare this variable globally. Also tried for

 var databasePath: URL!
 if let url = NSURL().absoluteURL { //error 1- Consecutive declarations on a line must be separated by ';'
 databasePath = url //error2 - Variable used within its own initial value
 }

Receive above 2 errors if write above code as replacement of var databasePath = URL() .

I am beginner in Swift. Please let me know the solution.

Upvotes: 0

Views: 4121

Answers (3)

user11803319
user11803319

Reputation:

Declare url in this way

var url: URL = NSURL() as URL

Upvotes: 1

Shakeel Ahmed
Shakeel Ahmed

Reputation: 6023

Swift- 5 Easy way

var fileDownloadedURL = URL(string: "")

Upvotes: 1

vadian
vadian

Reputation: 285082

The URL initializer must have an argument.

Basically there are two types:

  • An URL in the file system

    let databaseURL = URL(fileURLWithPath:"/path/to/file.ext")
    
  • An URL with an explicit scheme (e.g. http, ftp etc)

    let databaseURL = URL(string:"http://myserver/path/to/file.ext")!
    

    If the URL is guaranteed to be valid it can be unwrapped (!) otherwise use optical bindings (if let)

Upvotes: 2

Related Questions