本文介绍了如何将对象从其基类转换为其子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类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.

这篇关于如何将对象从其基类转换为其子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 14:15