How can I check if the value of Any confirms the value of the general protocol, for example. Integertype

Is it possible to check a value that dynamically confirms a common protocol?

I would like to do something like this:

import func Darwin.atoll
func anyToInt(a: Any) -> IntMax {
    if let v = a as? IntegerType { // error!!
        return v.toIntMax()

    } else {
        return atoll("\(a)")
    }
}

This makes compilation errors with the message "error: IntegerType protocol" can only be used as a general restriction ... ".

If I used the correct static type, I would use overloading according to the restrictions of the type parameters:

func anyToInt<T where T: IntegerType>(a: T) -> IntMax {
    return a.toIntMax()
}
func anyToInt<T>(a: T) -> IntMax {
    return atoll("\(a)")
}

Unfortunately, however, there is no way to use static types instead of Any in my case.

+4
source share
1 answer

You cannot for two reasons:

-, Any , Any. , :

let i = 1
i as Printable  // works

let a: Any = i
a as? Printable  //  doesn’t work
let p = a as Int as Printable // works
// or, if you don’t want to crash if a isn’t an Int
let p = (a as? Int).map { $0 as Printable } 
// (is there a cleaner syntax than this?)

-, , . . Printable , . . . , Any , IntegerType.

, Any ? Any , . , ?

+2

Source: https://habr.com/ru/post/1569663/


All Articles