![](/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.