V1ru8
V1ru8

Reputation: 6147

Why can't a protocol not be used as a type for a generic type in swift?

Can anyone explain me why this is not possible in plane swift:

protocol ProtocolA {
    func a()
}

class B<T: ProtocolA> {
}

class ClassC {
    func c(value: B<ProtocolA>) {

    }
}

This yields the following error: error: protocol type 'ProtocolA' does not conform to protocol 'ProtocolA' because 'ProtocolA' is not declared @objc. I can fix this by declaring the protocol as @objc but I want to understand why because this looks like a very essential use case of generics to me.

Upvotes: 1

Views: 803

Answers (1)

Qbyte
Qbyte

Reputation: 13243

This seems like a bug in Swift 2 since this works in Swift 1.2

As workaround you can use a generic function instead:

class ClassC {
    func c<T: ProtocolA>(value: B<T>) {

    }
}

Edit

As of Xcode 7 beta 6 you get an error message:

using 'ProtocolA' as a concrete type conforming to protocol 'ProtocolA' is not supported

So this should be considered normal behavior.

Upvotes: 2

Related Questions