How to check conformance to protocol with associated type in Swift?
Asked Answered
A

1

7

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?

Abaddon answered 12/10, 2018 at 9:42 Comment(3)
Common sense... What is RawValue in your case of ValueType? :)Cadell
This kind of check smells quite objective-c-ish. In a strong type language like Swift the type should be checked at compile time.Hetrick
@DominikBucher I suppose it can be any typeAbaddon
I
6

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.

Indicative answered 12/10, 2018 at 10:3 Comment(7)
In SwiftUI, how do we check if Color is a View? Could you show me how to do that in Swift? Thanks.Martines
@lochiwei, A Color is a late-binding token: SwiftUI only resolves it to a concrete value just before using it in a given environment.Indicative
OK then, how do we check if a Rectangle is a View?Martines
@lochiwei, Rectangle is a shape inside the view.Indicative
I mean Rectangle conforms to InsettableShape, InsettableShape inherits from Shape, and Shape inherits from View, so how do we check in code that a Rectangle is-a View?Martines
@Martines is not inheritance since it's all structs not classes, better term would be "conforms"Euphonic
@Euphonic is there a way to write a test which will check if Rectangle conforms to View protocol?Amoebaean

© 2022 - 2024 — McMap. All rights reserved.