Jeroen Swets
Jeroen Swets

Reputation: 225

Swift 3 syntax issues with URL

I'm trying to convert a C# example to swift in Xcode 8, but I keep getting syntax problems. See small example of code:

public class ToonAPIClient {
    private var APIManagerBaseAddress: URL!
    private var APIBaseAddress: URL!

    public init() {
        APIManagerBaseAddress = URL(String: "https://path.to.baseurl/")
        APIBaseAddress = URL(String: APIManagerBaseAddress + "append/path/data/")
    }
}

APIManagerBaseAddress I get the error

Argument labels '(String:)' do not match any available overloads

And for APIManagerBaseAddress

Binary operator '+' cannot be applied to operands of type 'URL!' and 'String'

Any help is appreciated since I tried a sh*tload of syntax possibilities :)

-edit- Thanks all for the help and suggestions!

Upvotes: 0

Views: 216

Answers (4)

Vakas
Vakas

Reputation: 6452

Use string instead of String

public init() {
    APIManagerBaseAddress = URL(string: "https://path.to.baseurl/")
    APIBaseAddress = URL(string: APIManagerBaseAddress + "append/path/data/")
}

Upvotes: 0

Nirav D
Nirav D

Reputation: 72410

First it is init(string:) not init(String:) also use appendingPathComponent with APIManagerBaseAddress.

APIManagerBaseAddress = URL(string: "https://path.to.baseurl/")!

// you can add values like that in Swift
APIBaseAddress = APIManagerBaseAddress.appendingPathComponent("append/path/data/")

Upvotes: 5

user3534305
user3534305

Reputation: 31

Here you go. I stuck your path into a variable (change let to var if you intent to change the path programmatically) and shortened up your code.

Hope this helps.

public class ToonAPIClient {
    private var APIManagerBaseAddress: URL!
    private var APIBaseAddress: URL!

    let path = "append/path/data/"

    public init() {
        APIManagerBaseAddress = URL(string: "https://path.to.baseurl/\(path)")

    }
}

Upvotes: 0

Shabir jan
Shabir jan

Reputation: 2427

This is how you will write the code in Swift

public class ToonAPIClient {
    private var APIManagerBaseAddress: URL!
    private var APIBaseAddress: URL!
public init() {
    //It is string not String in here
    APIManagerBaseAddress = URL(string: "https://path.to.baseurl/")

    // you can add values like that in Swift
    APIBaseAddress = URL(string:  URL(string: "\(APIManagerBaseAddress)append/path/data/"))
    }
}

Upvotes: 0

Related Questions