serg_zhd
serg_zhd

Reputation: 1043

How to check the concrete type of associatedtype of a protocol inside generic class?

For example I have a protocol and some classes conforming to it:

protocol SomeProtocol {
    associatedtype SomeType: Encodable
}

class SomeInner: SomeProtocol {
    typealias SomeType = String
}

class SomeInner2: SomeProtocol {
    typealias SomeType = URL
}

class AnotherClass<Inner: SomeProtocol> {
    func someFunc() {
        if Inner.SomeType.self is String { // << warning
            print("it's a String")
        }
        if Inner.SomeType.self is URL { // << warning
            print("it's an URL")
        }
    }
}

let test1 = AnotherClass<SomeInner>()
test1.someFunc()

let test2 = AnotherClass<SomeInner2>()
test2.someFunc()

This gives me warnings:

Cast from 'Inner.SomeType.Type' (aka 'String.Type') to unrelated type 'String' always fails

Cast from 'Inner.SomeType.Type' to unrelated type 'URL' always fails

and if never succeeds.

Upvotes: 0

Views: 661

Answers (1)

olha
olha

Reputation: 2262

Just change String to String.Type as the warning recommends:

func someFunc() {
        if Inner.SomeType.self is String.Type { // << warning
            print("it's a String")
        }
        if Inner.SomeType.self is URL.Type { // << warning
            print("it's an URL")
        }
    }

It compiles and outputs

it's a String
it's an URL

Upvotes: 1

Related Questions