结构体初始化
如果结构体没有实现任何初始化函数,Swift 默认给生成一个包含所有成员变量的初始化构造器。
struct RocketConfiguration { let name: String = "Athena 9 Heavy" let numberOfFirstStageCores: Int let numberOfSecondStageCores: Int let numberOfStageReuseLandingLegs: Int }
如果使用如下的代码初始化这个结构体:
let athena9Heavy = RocketConfiguration()
将产生编译错误,如下图:
有两种做法可以消除错误,声明结构体成员时即赋值,如下:
struct RocketConfiguration { let name: String = "Athena 9 Heavy" let numberOfFirstStageCores: Int = 3 let numberOfSecondStageCores: Int = 1 let numberOfStageReuseLandingLegs: Int? = nil } let athena9Heavy = RocketConfiguration()
但这种情况下,成员变量无法再修改,除非将let
改成var
。或者使用默认的初始化构造器,给每个成员赋一个初始化的值:
struct RocketConfiguration { let name: String = "Athena 9 Heavy" let numberOfFirstStageCores: Int let numberOfSecondStageCores: Int let numberOfStageReuseLandingLegs: Int } let athena9Heavy = RocketConfiguration(numberOfFirstStageCores: 3, numberOfSecondStageCores: 1, nominalBurnTime: nil)