Search code examples
xcodestringformatswiftnsurl

String issue in Swift


I keep getting an error when I try to pass a string to NSURL. A regular string without format works fine but the code below keeps giving me the following error: "could not find an overload for init that accepts the supplied arguments" Any advice appreciated thanks.

var str = (format: "%@send?x=%d&y=%d2&z=%d", URL, x, y, z)
var url = NSURL(String: str)

or

var url = NSURL(format: "%@send?x=%d&y=%d2&z=%d", URL, x, y, z)

Solution

  • You're missing the String type name in your string initializer:

    let URL = "http://example.com/"
    let (x, y, z) = (1, 2, 3)
    let str = String(format: "%@send?x=%d&y=%d2&z=%d", URL, x, y, z)
    // str is now "http://example.com/send?x=1&y=22&z=3"
    
    let url = NSURL(string: str)