我曾经在我的类NSObject构造函数中使用以下代码使用Objective-c:
- (id)init {
self = [super init] ;
return self;
}
如何在Swift中使用它?
我试着这样做:
override init() {
self = super.init()
return self;
}
我遇到两个错误:
cannot assign value self is immutable
nil is the only return value permitted in this initializer
答案 0 :(得分:16)
您无法在Swift中分配给self
。只需使用
super.init()
你也没有退货。构造函数类型为void(在C lingo中)。
答案 1 :(得分:8)
Swift初始化序列与Objective-C,
略有不同class BaseClass {
var value : String
init () {
value = "hello"
}
}
下面的子类。
class SubClass : BaseClass {
var subVar : String
let subInt : Int
override init() {
subVar = "world"
subInt = 2015
super.init()
value = "hello world 2015" // optional, change the value of superclass
}
}
初始化序列是:
我认为你的代码:
override init() {
self = super.init() //just call super.init(), do not assign it to self
return self; //it is unnecessary to return self
}
我们必须记住初始化类中的所有var或let。
答案 2 :(得分:1)
在Swift中,您不能分配或返回self
。此外,您需要在自定义初始化后调用super.init()
。即,如果您的Objective-C代码看起来像:
- (instancetype)init {
if (self = [super init]) {
someProperty = 42;
}
}
那么Swift中的等价物就是
init() {
self.someProperty = 42
super.init()
}
中说明
安全检查1 指定的初始化程序必须确保所有的 其类引入的属性在委托之前初始化 一个超类初始化器。
如上所述,只考虑对象的内存 一旦所有存储属性的初始状态为,就初始化 众所周知。为了满足这条规则,指定 初始化程序必须确保它自己的所有属性都是 在它交出链之前初始化。
答案 3 :(得分:0)
Apple document, the Swift Programming Language, about initialization。文档中的一个例子。
class Bicycle: Vehicle {
override init() {
super.init()
numberOfWheels = 2
}
}