如何设置结构的属性值?

问题描述:

要设置multiplier的值,我认为我使用语法threeTimesTable.multiplier = 3。下面的工作如何?看起来好像我将一个参数传递给struct并初始化一个值,但在类中没有看到初始化器。我对这里发生的事情感到困惑。 struct中的参数是否可选?如何设置结构的属性值?

struct TimesTable { 
    let multiplier: Int 
    subscript(index: Int) -> Int { 
     return multiplier * index 
    } 
} 
let threeTimesTable = TimesTable(multiplier: 3) 
print("six times three is \(threeTimesTable[6])") 
// Prints "six times three is 18" 

因为这是一个结构,雨燕提供了一个默认按成员初始化(类没有此功能)。从Swift book

按成员初始化器的结构类型

所有结构具有自动生成按成员初始化,您可以使用它来初始化新的结构实例的成员属性。新实例的属性的初始值可以通过名字

传递给按成员初始化你的情况,这相当于:

struct TimesTable { 
    let multiplier: Int 

    // This is automatically provided by the compiler 
    init(multiplier: Int) { 
     self.multiplier = multiplier 
    } 

    subscript(index: Int) -> Int { 
     return multiplier * index 
    } 
} 
+0

谢谢。我在输入这个问题后在书中发现了这一点。但我相信这对某个人会有好处,所以我会离开它。 –