Swift-structures 和 classes 初始化 - structure
structure
1. memberwise initializer
1.1 不需要default values和intializer
///-------------------------- structures --------------------------/// // only structures automatically generate a memberwise initializer // don't need default values and initializer struct StructA { let propertyA: Int let propertyB: Double } //------------------ memberwise initializer ----------------// // the memberwise initializer works well let a = StructA(propertyA: 1, propertyB: 1.0)
1.2 使用memberwise initializer注意参数的顺序,memberwise initializer的参数列表是自动镜像存储属性列表的,举例:
// the memberwise initializer doesn't work // the automatic memberwise initializer argument list's order mirrors that of the stored property list let b = StructA(propertyB: 1.0, propertyA: 1)
1.3 如果属性已经有default value,则
struct StructA { let propertyA: Int = 1 let propertyB: Double } let aa = StructA(propertyB: 1.0)
此时是不能 let aa = StructA(propertyA: 1, propertyB: 1.0) 的
如果想要,可以这么做,如下
2. 等价的 initializer
//equivalent initializer extension StructA { init(propertyB: Double) { self.propertyB = propertyB } } // works well let ab = StructA(propertyA: 1, propertyB: 1.0)
3. 添加default value
//-------------------------- custom initializer --------------------------// init(propertyA: Int = 1, propertyB: Double = 1.0) { // 处理初始值 }