Swift使用参数自定义初始化
示例
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.distanceInMetersis 0.42
let myOtherDistance = MetricDistance(fromKilometers: 42)
//myOtherDistance.distanceInMetersis 42000
请注意,您不能省略参数标签:
let myBadDistance = MetricDistance(42) // 错误:参数标签与任何可用的重载都不匹配
为了允许省略参数标签,请使用下划线_作为标签:
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
}
}
以上是 Swift使用参数自定义初始化 的全部内容, 来源链接: utcz.com/z/330636.html