将值传递到 class 中,以便在 Swift 中实例化 class 时使用

Passing a value into a class to be used when the class is instantiated in Swift

在创建自定义 class 的实例时,我想将一个值传递回 class 声明,以便在实例化时使用。

我尝试通过 属性 执行此操作,但这不起作用。实现这一目标的正确方法是什么?

(如果我对问题的措辞不正确,我深表歉意,但希望下面的代码能清楚地说明我的问题。)

class hello {
    let indexInArray: Int!
    override init(frame: CGRect) {
        super.init(frame: frame)
        println("This is hello number \(indexInArray).")
    }
}

for index in 0..<4 {
    let singleHello = hello()
    singleHello.indexInArray = index
}

期望的输出:

// This is hello number 0.
// This is hello number 1.
// This is hello number 2.
// This is hello number 3.

如果我没有正确理解你的问题,这就是你想要的:

class Hello : HelloSuperClass {
    // Note - this no longer has to be declared as an implicitly unwrapped optional.
    let index: Int

    // Create a new designated initialiser that takes the frame and index as arguments.
    init(frame: CGRect, index: Int) {
        self.index = index
        super.init(frame: frame)
        println("This is hello number \(self.index).")
    }
}

for i in 0..<4 {
    let singleHello = Hello(frame: CGRect(), index: i)
}

做一个指定的初始化器,例如:

init(#index: Int) {
    super.init()
    println("This is hello number \(index).")
}

然后...

for index in 0..<4 {
    let singleHello = hello(index: index)
}

以便在初始化时,可以将索引作为变量传入。如果你想要框架,你可以继续做 init(frame: CGRect, index: Int) {}