Vik Singh
Vik Singh

Reputation: 1603

Swift Protocol as a Type

I am trying to use Swift Protocol as a Type. I have following code:

protocol STCMultipeerProtocol {
 typealias ErrorBlock = (NSError?)->();

 func start();
 func stop();
 func retryConnecting();
 func disconnect();
}

class STCConnectivityManager: NSObject {

 typealias VoidBlock = ()->();

 private var roleManager: STCMultipeerProtocol?
 private var completionBlock: VoidBlock?
 ....
}

Now, the problem is Compiler is giving me error:

Protocol 'STCMultipeerProtocol' can only be used as a generic constraint because it has Self or associated type requirements.

I see that a lot of other people have seen this error but I am not able to understand the proper cause and solution for this issue.

I would really appreciate if anyone could help me with this issue

Upvotes: 1

Views: 695

Answers (1)

Brian Nickel
Brian Nickel

Reputation: 27550

When a typealias is used inside a protocol, it is referred to as a Protocol Associated Type Declaration and are associated with the "eventual type that conforms to the protocol" aka Self. You'll see these a lot in the core Swift library for things like Sequences or basic types. The compiler needs that Self information to do its job and is therefore failing.

The good thing is that you don't need that typealias inside your protocol and can move it out as a global definition inside your namespace:

typealias ErrorBlock = (NSError?)->();

protocol STCMultipeerProtocol {

 func start();
 func stop();
 func retryConnecting();
 func disconnect();
}

If you have a lot of error types, you could call it a MultipeerErrorBlock.

Upvotes: 5

Related Questions