Swift允許聲明變量但不初始化。我如何檢查變量是否在Swift中未初始化?如何檢查變量是否未在Swift中初始化?
class myClass {}
var classVariable: myClass // a variable of class type - not initialized and no errors!
//if classVariable == nil {} // doesn't work - so, how can I check it?
Swift允許聲明變量但不初始化。我如何檢查變量是否在Swift中未初始化?如何檢查變量是否未在Swift中初始化?
class myClass {}
var classVariable: myClass // a variable of class type - not initialized and no errors!
//if classVariable == nil {} // doesn't work - so, how can I check it?
你說的沒錯,你可能不是一個非可選變量比較nil
。當您爲非可選變量聲明但未提供值時,它是而不是設置爲nil
就像一個可選變量是。沒有辦法在運行時測試未初始化的非可選變量,因爲這種使用的任何可能性都是可怕的,編譯器檢查的程序員錯誤。唯一可編譯的代碼是確保每個變量在使用前都被初始化的代碼。如果您希望能夠將nil
分配給變量並在運行時檢查其值,那麼您必須使用可選的變量。
實施例1:正確使用
func pickThing(choice: Bool) {
let variable: String //Yes, we can fail to provide a value here...
if choice {
variable = "Thing 1"
} else {
variable = "Thing 2"
}
print(variable) //...but this is okay because the variable is definitely set by now.
}
實施例2:編譯錯誤
func pickThing2(choice: Bool) {
let variable: String //Yes, we can fail to provide a value here, but...
if choice {
variable = "Thing 1"
} else {
//Uh oh, if choice is false, variable will be uninitialized...
}
print(variable) //...that's why there's a compilation error. Variables ALWAYS must have a value. You may assume that they always do! The compiler will catch problems like these.
}
實施例3:允許零
func pickThing3(choice: Bool) {
let variable: String? //Optional this time!
if choice {
variable = "Thing 1"
} else {
variable = nil //Yup, this is allowed.
}
print(variable) //This works fine, although if choice is false, it'll print nil.
}
真實情況如下。您有可能在RUN-TIME中未初始化的類變量。所以你必須在使用前檢查它以防止應用程序崩潰。怎麼樣?只有將變量更改爲可選項? – Dmitry
是的,如果你試圖讓一個變量在運行時沒有任何值,那麼你必須聲明該變量是可選的。你不能聲明一個非可選變量,而不必爲它提供一個初始值。將變量未初始化在聲明的確切行上的功能只能讓您在稍後幾行提供初始值。編譯器將不允許您在代碼中包含變量,除非它肯定提供了值。 – andyvn22
但是Swift不是類型安全的語言。在語言概念上似乎有一個很大的問題。不僅編譯器不檢查代碼是否安全 - 甚至開發人員(!)都無法做到這一點!只有在任何情況下他使用可選項代替變量。 – Dmitry
這可能是編譯器的異常,你不會得到一個錯誤聲明一個變量這樣
class MyClass {}
var myClass : MyClass
,但在遊樂場你會得到一個運行時錯誤時,你剛纔讀的變量
myClass
variable 'myClass' used before being initialized
Swift最重要的功能之一是非可選變量永遠不會是零。如果你嘗試訪問這個變量,你會得到一個運行時錯誤,也就是崩潰。
請提供您的完整代碼,包括周圍的類定義:您發佈的代碼不會編譯。 – andyvn22
@ andyvn22你的意思是你在第三行發生錯誤?我已經修復了代碼,但還沒有檢查它。 – Dmitry
不是我倒下了,但最後一行拒絕編譯。錯誤:'二進制運算符'=='不能應用於類型'myClass'和'NilLiteralConvertible''的操作數 –