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?
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.
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.
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.
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.
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With