使用引數自定義初始化
struct MetricDistance {
var distanceInMeters: Double
init(fromCentimeters centimeters: Double) {
distanceInMeters = centimeters / 100
}
init(fromKilometers kilos: Double) {
distanceInMeters = kilos * 1000
}
}
let myDistance = MetricDistance(fromCentimeters: 42)
// myDistance.distanceInMeters is 0.42
let myOtherDistance = MetricDistance(fromKilometers: 42)
// myOtherDistance.distanceInMeters is 42000
請注意,你不能省略引數標籤:
let myBadDistance = MetricDistance(42) // error: argument labels do not match any available overloads
為了省略引數標籤,請使用下劃線 _
作為標籤:
struct MetricDistance {
var distanceInMeters: Double
init(_ meters: Double) {
distanceInMeters = meters
}
}
let myDistance = MetricDistance(42) // distanceInMeters = 42
如果引數標籤與一個或多個屬性共享名稱,請使用 self
顯式設定屬性值:
struct Color {
var red, green, blue: Double
init(red: Double, green: Double, blue: Double) {
self.red = red
self.green = green
self.blue = blue
}
}