问题描述
我有一个类User
,它是类PFUser
的子类:
I have a class User
which is a subclass of class PFUser
:
class User: PFUser {
var isManager = false
}
在我的一种方法中,我收到一个PFUser
对象,我想将其强制转换为User
对象
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
}
这可能吗?
推荐答案
如果它是PFUser
的实例,而不是存储在PFUser
类型的变量中的User
的实例,则不可能.
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).
我建议在User
中实现一个初始化程序,并以PFUser
实例为参数-如果可能的话.
I suggest to implement an initializer in User
, taking a PFUser
instance as parameter - if that's possible.
但是,尽管我从未尝试过这样做,但我认为从PFUser
继承会遇到麻烦,因为我的理解是,此类并非旨在为PFObject
继承.我建议您考虑将PFUser
设置为User
的属性-这样,您就可以根据需要进行分配.
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.
这篇关于如何将对象从其基类转换为其子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!