In the following code, I get an error on the line indicated (4th from the 
bottom) that "Protocol 'APIEndPoint' can only be used as a generic constraint 
because it has Self or associated type requirements” I understand this is 
because the APIEndPoint protocol contains a type alias. However I don’t 
understand why this means it can’t be used as a type? I simply want the init 
method I’m defining to be able to accept any object/enum that conforms to the 
APIEndPoint protocol.

protocol API {
    static var baseUrl : String { get };
}

protocol APIEndPoint {
    typealias ParentAPI : API
    var path: String { get }
    func urlString() -> String
}
extension APIEndPoint {
    func urlString() -> String {
        return ParentAPI.baseUrl + path;
    }
}

extension NSURL {
    convenience init(instance:APIEndPoint) { //error here
        self.init(string:instance.urlString())!
    }
}

If I change that line to `convenience init<T:APIEndPoint>(instance:T) {`then 
there is no problem.

Also if I split the APIEndPoint protocol in 2, like so:

protocol APIEndPointBase {
    var path: String { get }
    func urlString() -> String
}
protocol APIEndPoint : APIEndPointBase {
    typealias ParentAPI : API
}


Then the change the line with the error to:

convenience init(instance:APIEndPointBase) {

then there is also no error.

The ability to work around this error makes it seem like the error is 
pointless. Even if I used the ParentAPI typealias with the protocol definition, 
I don’t see why I can’t use it as I have in the first code segment. Why does 
having Self or associated type requirements mean that the protocol can only be 
used as a generic constraint?

Apologies if I have posted this incorrectly, this is the first time I’ve used a 
mailing list

Jonathan
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to