我有一个 User
类,它是 PFUser
类的子类:
class User: PFUser {
var isManager = false
}
在我的一个方法中,我收到一个 PFUser
对象,我想将它转换为一个 User
对象
func signUpViewController(signUpController: PFSignUpViewController!, didSignUpUser user: PFUser!) {
currentUser = user
}
这可能吗?
最佳答案
这种类型的转换是向下转换。给定一个您知道存在子类的基 类的实例,您可以尝试使用类型转换运算符as
进行向下转换:
class Base {}
class Derived : Base {}
let base : Base = Derived()
let derived = base as Derived
不过请记住,沮丧可能会失败:
class Base {}
class Derived : Base {}
class Other : Base {}
let base : Base = Other()
let derived = base as Derived // fails with a runtime exception
您可以尝试使用类型为运算符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.
}
关于oop - 如何将对象从其基类转换为子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27875297/