【问题标题】:How do I instanciate a class (stored in an Array) in Swift?如何在 Swift 中实例化一个类(存储在一个数组中)?
【发布时间】:2015-02-23 12:22:58
【问题描述】:

我想保留几个类的数组并按需实例化它们。下面是一些演示代码:

class AClass {
   func areYouThere() -> String {
      return "Yes, I am!"
   }
}

class FirstClass: AClass {
   override func areYouThere() -> String {
      return "Yes, I am #1!"
   }
}

class SecondClass: AClass {
   override func areYouThere() -> String {
      return "Yes, I am #2!"
   }
}

let className = FirstClass.self
let classReferences: [AClass.Type] = [FirstClass.self, SecondClass.self]

let instanceOfClass = classReferences[0].init()
let test = instanceOfClass.areYouThere()

代码确实可以编译,但是当我运行它时,“测试”将保持“是的,我是!” (没有#1),因为 instanceOfClass 是“AClass”的一个实例,而不是“FirstClass”。我猜,我的 Array 的类型 [AClass.Type] 是错误的。我也试过“AnyClass”,但编译器抱怨说,“init”没有在“AnyClass”中定义。有什么想法吗?

谢谢! 英戈。

【问题讨论】:

    标签: arrays class swift reference


    【解决方案1】:

    您的基类中需要 required init() 初始化器。

    class AClass {
        required init() {} // <- HERE
    
        func areYouThere() -> String {
            return "Yes, I am!"
        }
    }
    

    因为子类may not inherit init() initializer

    IMO,这是一个编译器错误。编译器应该报告classReferences[0] 可能没有init()

    顺便说一句,你可以:

    let instanceOfClass = classReferences[0]()
    

    不用写.init

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多