简体   繁体   中英

How to check conformance to protocol with associated type in Swift?

When I want to check if a type conforms to a simple protocol, I can use:

if let type = ValueType.self as? Codable.Type {}

When the protocol has associated type, for example RawRepresentable has RawValue , when I do:

if let type = ValueType.self as? RawRepresentable.Type {}

Compiler will show the following error:

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


So how to check conformance to protocol with associated type?

TL;DR
Compiler does not have enough information to compare the type until associated type is set .


When you refer to simple protocol, compiler knows its type from the beginning. But when you refer to protocol with associated type , compiler doesn't know its type until you declare it.

protocol ExampleProtocol {
    associatedtype SomeType
    func foo(param: SomeType)
}

At this moment for compiler it looks like this:

protocol ExampleProtocol {
    func foo(param: <I don't know it, so I'll wait until it's defined>)
}

When you declare a class conforming to the protocol

class A: ExampleProtocol {
    typealias SomeType = String
    func foo(param: SomeType) {

    }
}

Compiler starts to see it like this:

protocol ExampleProtocol {
    func foo(param: String)
}

And then it is able to compare types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM