Converting switch-as from Switch to Objective-C

Viewed 106

My question is regarding this sample code from Apple.

How do I convert this switch statement using the as keyword to an Objective-C equivalent? I'm just interested in the case statements.

func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
    switch authorization.credential {
    case let appleIDCredential as ASAuthorizationAppleIDCredential:
        
        // Create an account in your system.
        let userIdentifier = appleIDCredential.user
        let fullName = appleIDCredential.fullName
        let email = appleIDCredential.email
        
        // For the purpose of this demo app, store the `userIdentifier` in the keychain.
        self.saveUserInKeychain(userIdentifier)
        
        // For the purpose of this demo app, show the Apple ID credential information in the `ResultViewController`.
        self.showResultViewController(userIdentifier: userIdentifier, fullName: fullName, email: email)
    
    case let passwordCredential as ASPasswordCredential:
    
        // Sign in using an existing iCloud Keychain credential.
        let username = passwordCredential.user
        let password = passwordCredential.password
        
        // For the purpose of this demo app, show the password credential as an alert.
        DispatchQueue.main.async {
            self.showPasswordCredentialAlert(username: username, password: password)
        }
        
    default:
        break
    }
}
1 Answers

In ObjC, the equivalent of this kind of as is -isKindOfClass:. You'll need to use if statements, since there's no equivalent version of switch. It would be something along these lines:

id<ASAuthorizationCredential> credential = authorization.credential;
if ([credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) { 
    ASAuthorizationAppleIDCredential *appleIDCredential = (ASAuthorizationAppleIDCredential *)credential;
    // ...
}
else if ([credential isKindOfClass:[ASPasswordCredential class]]) {
    ASPasswordCredential *passwordCredential = (ASPasswordCredential *)credential;
    // ...
}

ObjC has two class-checking methods, -isKindOfClass: and -isMemberOfClass:. The "kind" version checks for the given class and all subclasses. The "member" version checks the exact class, so it can differentiate between superclasses and their subclasses if needed.

Related