Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

object

oop

swift

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?

like image 749
grabury Avatar asked Jan 10 '15 10:01

grabury


People also ask

How do I cast a class to my subclass?

You can try to convert the super class variable to the sub class type by simply using the cast operator. But, first of all you need to create the super class reference using the sub class object and then, convert this (super) reference type to sub class type using the cast operator.

Can you cast object to subclass Java?

In java object typecasting one object reference can be type cast into another object reference. The cast can be to its own class type or to one of its subclass or superclass types or interfaces.

Can you type cast to a subclass?

You can use type casting with a hierarchy of classes and subclasses to check the type of a particular class instance and to cast that instance to another class within the same hierarchy.

Can we assign superclass object to subclass?

No. It makes zero sense to allow that. The reason is because subclasses generally define additional behavior. If you could assign a superclass object to a subclass reference, you would run into problems at runtime when you try to access class members that don't actually exist.


1 Answers

This type of casting is a downcast. Given an instance of a certain base class where you know there exist subclasses, you can try to downcast with the typecast operator as:

class Base {}
class Derived : Base {}

let base : Base = Derived()
let derived = base as Derived

Keep in mind though, that a downcast can fail:

class Base {}
class Derived : Base {}
class Other : Base {}

let base : Base = Other()
let derived = base as Derived  // fails with a runtime exception

You can try a downcast using the optional form of the type as operator as?.

class Base {}
class Derived : Base {}
class Other : Base {}

let base : Base = Other()

// The idiomatic implementation to perform a downcast:

if let derived = base as? Derived {
    println("base IS A Derived")
}
else {
    println("base IS NOT A Derived")  // <= this will be printed.
}
like image 54
CouchDeveloper Avatar answered Nov 15 '22 07:11

CouchDeveloper