[swift-users] wishing I could cast (sort of) to protocol with associated type

Robert Nikander robert.nikander at icloud.com
Wed Nov 2 14:31:51 CDT 2016


Hi,

In the following code, I want to test if x is a `SpecialController`. If it is, I want to get the `currentValue` as a `SpecialValue`. How do you do this? If not with a cast, then some other technique.

I understand the error, and that SpecialController by itself is not a simple type to cast to. But it seems like what I’m saying is logically consistent and not that complicated. Is there really no way to *say* it in Swift?

    protocol SpecialController {
        associated type SpecialValueType : SpecialValue
        var currentValue: SpecialValueType? { get }
    }
    ...
    var x: AnyObject = ...
    if let sc = x as? SpecialController {  // does not compile

Rob


More information about the swift-users mailing list