gpt4 book ai didi

class - 在 Swift 中实例化类时将值传递给要使用的类

转载 作者:行者123 更新时间:2023-11-30 10:15:57 26 4
gpt4 key购买 nike

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

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

(如果我的问题措辞不太正确,请道歉,但希望下面的代码能让我的问题清楚。)

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

关于class - 在 Swift 中实例化类时将值传递给要使用的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29944770/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com