如何将对象从其基类转换为其子类

问题描述 投票:0回答:4

我有一个类

User
,它是类
PFUser
的子类:

class User: PFUser {
 var isManager = false
}

在我的一种方法中,我收到一个

PFUser
对象,我想将其转换为
User
对象

func signUpViewController(signUpController: PFSignUpViewController!, didSignUpUser user: PFUser!) {
 currentUser = user
}

这可能吗?

oop object swift
4个回答
15
投票

这种类型的选角是沮丧。给定某个 base 类的实例,您知道其中存在子类,您可以尝试使用类型转换运算符

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.
}

8
投票

这也可以通过使用以下方法来完成:

object_setClass(baseClass, derivedClass.self)

然而,这使用了 objc-runtime 库,如果使用不当,可能会导致奇怪的崩溃,这是毫无价值的。


7
投票

如果它是

PFUser
的实例,而不是存储在
User
类型变量中的
PFUser
实例,则不可能。

您可以将类的实例强制转换为其超类之一,但不能采用其他方式(除非强制转换类型是实际的实例类型)。

我建议在

User
中实现一个初始化程序,将
PFUser
实例作为参数 - 如果可能的话。

但是,虽然我从未尝试这样做,但我认为从

PFUser
继承你只会遇到麻烦,因为我的理解是这个类并不是像
PFObject
那样被设计为被继承的。我建议考虑将
PFUser
设为
User
的属性 - 这样您就可以根据需要进行分配。


0
投票

在 JavaScript(包括 ES6)中,不存在像 Java 或 C++ 等静态类型语言中那样的向上转型或向下转型的概念。但是,您可以通过将子类的对象视为其超类的对象来实现类似的效果。这是因为 JavaScript 对象基于原型,并且您始终可以从子类的实例访问超类的属性和方法。

这是一个例子:

class Animal {
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }
  
  speak() {
    console.log(`${this.name} barks.`);
  }
  
  fetch() {
    console.log(`${this.name} fetches.`);
  }
}

// Creating an instance of the subclass
const myDog = new Dog('Buddy', 'Golden Retriever');

// Upcasting to the superclass
const myAnimal = myDog; // No explicit casting needed, just assign the subclass instance to a superclass reference

// Accessing superclass methods and properties
myAnimal.speak(); // Outputs: Buddy barks.
console.log(myAnimal.name); // Outputs: Buddy

// You cannot access subclass-specific properties or methods
// myAnimal.fetch(); // This would throw an error since fetch is not a method of the superclass

在此示例中,Dog 是 Animal 的子类。当您将 Dog 的实例分配给 Animal 类型的变量时,您实际上将其视为 Animal 。但是,您将无法使用超类引用访问特定于子类的方法或属性。

© www.soinside.com 2019 - 2024. All rights reserved.