![](/img/trans.png)
[英]How to initialize a class with a property that is constrained to a generic type and a protocol in Swift
[英]How to declare but not initialize a property in a Swift class
class car {
var oneWheel : Wheel
func run(inputWheel:Wheel){
oneWheel = inputWheel
....
}
}
我不想实现init(),我不想初始化轮子。
像这样......
class car {
var oneWheel : Wheel?
// with this version, in order to pass oneWheel into this function as an argument, you will need to unwrap the optional value first. (see below example)
func run(inputWheel:Wheel){
oneWheel = inputWheel
....
}
}
或者如果您希望该函数采用可选类型Wheel
作为参数
class car {
var oneWheel : Wheel?
func run(inputWheel:Wheel?){
//use conditional binding to safely unwrap the optional
if let wheel = inputWheel {
oneWheel = wheel
}
....
}
}
通过使用条件绑定,而不是隐式展开的可选,您可以避免由于... unexpectedly found nil while unwrapping an optional value
时unexpectedly found nil while unwrapping an optional value
导致崩溃的可能性,当编译器发现nil时,会发生非零值。
创建一个隐式展开的可选项 - 这将像一个普通变量,但它不需要初始化 - 它的初始值是nil
。 只需确保在使用之前设置该值,否则在解开nil时会出现致命错误。
class car {
var oneWheel: Wheel!
func run(inputWheel: Wheel) {
wheel = inputWheel
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.