我有一个类似于下面的类。它被简化了,但它说明了我的问题。我想用函数“square”初始化“number”变量。
class SomeClass {
let number: Int
func square (num: Int) -> Int {
return num * num
}
init(num: Int) {
number = square(num)
}
}
但是当我创建类的实例时。例如
let instance = SomeClass(num: 2)
它抛出错误:在初始化所有存储的属性之前,在方法调用“square”中使用“self”。
如何使用函数初始化数字?
最佳答案
在这种特殊情况下,您可以使用类方法:
class SomeClass {
let number: Int
class func square (num: Int) -> Int {
return num * num
}
init(num: Int) {
number = SomeClass.square(num)
}
}
关于swift - 使用类中的函数初始化变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34138000/