我想知道是否可以初始化嵌套类,例如初始化汽车时设定轮胎压力:
class Tyre {
var pressure : Double = 0.0
init() { }
init(withPressure p: Double) {
self.pressure = p
}
}
class Car {
var tyre = Tyre()
}
// should return 2.5
let myCar = Car().tyre(withPressure : 2.5).pressure
现在只有这个有效,使用默认的init():
let myCar = Car().tyre.pressure // return 0.0
提前感谢您的回复!
答案 0 :(得分:2)
你可以做到这一点,但你可以将自定义轮胎作为参数传递给你的汽车的初始值:
class Tyre {
var pressure : Double = 0.0
init() { }
init(withPressure p: Double) {
self.pressure = p
}
}
class Car {
var tyre: Tyre!
init(withTyre t: Tyre) {
self.tyre = t
}
}
let myCar = Car(withTyre: Tyre(withPressure : 2.5))
// should return 2.5
let pressure = myCar.tyre.pressure
答案 1 :(得分:1)
您必须单独初始化tyre
。你可以用两种方式做到这一点。 Car
可以采用类型压力参数:
class Car {
var tyre
init(withTyrePressure tyrePressure: Double) {
tyre = Tyre(withPressure: tyrePressure)
}
}
或Car
可以使用tyre
参数:
class Car {
var tyre
init(withTyre tyre: Tyre) {
self.tyre = tyre
}
}
let tyre = Tyre(withPressure: 2.5)
let car = Car(withTyre: tyre)
答案 2 :(得分:1)
class Tyre {
var pressure : Double = 0.0
init() { }
init(withPressure p: Double) {
self.pressure = p
}
}
class Car {
var tyre : Tyre
init(withPressure p:Double) { // <-- this is the only change from your code
self.tyre = Tyre(withPressure:p)
}
}
// should return 2.5
let myCar = Car(withPressure : 2.5)
myCar.tyre.pressure // 2.5
答案 3 :(得分:0)
class Tyre {
var pressure : Double = 0.0
init() { }
init(withPressure p: Double) {
self.pressure = p
}
}
class Car {
var tyre = Tyre()
}
// should return 2.5
let myCar = Car()
myCar.tyre = Tyre(withPressure: 2.5)
print(myCar.tyre.pressure)
答案 4 :(得分:0)
我找到了我的问题的答案但是必须通过使用返回Tire类而不是使用属性的函数轮胎来更改Car类。所以可以完成! ; - )
以下示例可能没有意义,但只是原理的证明......
class Tyre {
var pressure : Double = 0.0
init() { }
init(withPressure p: Double) {
self.pressure = p
}
}
class Car {
//var tyre = Tyre(withPressure: 2.5)
func tyre (withPressure p: Double) -> Tyre {
return Tyre(withPressure: p)
}
}
let myCar = Car().tyre(withPressure: 2.2).pressure