Search code examples
swiftprotocols

Is there a way to use the 'is' type check operator with RandomAccessCollection?


I'm getting the following error on the 'if' condition:

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

let str = "mystring"

let v = str.utf8

if v is RandomAccessCollection {
    print("YES")
} else {
    print("NO")
}

Out of curiosity, is there a way to use the "is" type check operator to check if an object/instance conforms to RandomAccessCollection?


Solution

  • These type checks at runtime are unswifty. Don't do that.

    A possible way is method overloading, the check is performed at compile time for example

    func checkType<T>(obj: T) {
        print("NO")
    }
    
    func checkType<T:RandomAccessCollection>(obj: T) {
        print("YES")
    }
    
    let str = "mystring"
    let v = str.utf8
    checkType(obj: v) // prints NO
    
    let x = Data(v)
    checkType(obj: x)  // prints YES
    

    If the object conforms to the protocol the second method is called otherwise the first.