Search code examples
objective-cswiftcomparison

What is the equivalent of this Objective-C safe type casting expression in Swift?


What is the equivalent of this expression:

if ([stream isKindOfClass:[OWTRemoteMixedStream class]]) {
    _mixedStream = (OWTRemoteMixedStream *)stream;
}

in Swift?

if (stream is OWTRemoteMixedStream) {
    // mixedStream = stream OWTRemoteMixedStream  
}

Solution

  • The type checking operator is indeed is in Swift. However, if you want to check the type and also cast it in case the type is a match, you need to use optional casting, as?.

    if let mixedStream = stream as? OWTRemoteMixedStream {
        // use mixedStream, which has the type OWTRemoteMixedStream
    }