leizh00701
leizh00701

Reputation: 1963

Downcast any to a more specific type in swift

I make a protocol:

protocol TestProtocol {
    func test() -> Int
}

and I extend the Int and Optional to conform the protocol:

extension Int: TestProtocol {
    func test() -> Int {
        return 1
    }
}

extension Optional where Wrapped: TestProtocol {
    func test() -> Int {
        switch self {
        case let value?:
            return value.test()
        default:
            return 0
        }
    }
}

I may also extend String, Double and other types conform this protocol.

If I give the specific type of variable, it works ok:

let fff: Int? = 2
print(fff.test())

But if the variable type is any:

let kkk: Any = fff
print(kkk.test())

How to check kkk's true type conforming protocol TestProtocol and get the result.

Upvotes: 1

Views: 842

Answers (1)

Code Different
Code Different

Reputation: 93151

Use optional binding:

let kkk: Any = 42   // Actually an Int
if let k = kkk as? TestProtocol {
    print(k.test())
} else {
    print("kkk does not conform to TestProtocol")
}

Upvotes: 2

Related Questions