Search code examples
oopobjectswift

How to cast an object from its base class into its subclass


I have a class User which is a subclass of class PFUser:

class User: PFUser {
 var isManager = false
}

In one of my methods I receive a PFUser object and I want to cast it to a User object

func signUpViewController(signUpController: PFSignUpViewController!, didSignUpUser user: PFUser!) {
 currentUser = user
}

Is this possible?


Solution

  • If it's an instance of PFUser, and not an instance of User stored in a variable of PFUser type, no it's not possible.

    You can cast an instance of a class to one of its superclasses, but you cannot do the other way (unless the cast type is the actual instance type).

    I suggest to implement an initializer in User, taking a PFUser instance as parameter - if that's possible.

    However, although I never attempted to do so, I think inheriting from PFUser you'll just run into troubles, as my understanding is that this class is not designed to be inherited as it is for PFObject. I'd suggest looking into making PFUser a property of User - that way you can just assign as needed.