var countryCodes = [String]()
let codeIndex = countriesList.index(of: countryTextField.text!)
var chosenCountryCode? = countryCodes[codeIndex!]
是第三行給出一個編譯錯誤檢查時編譯錯誤,說這是一個非可選類型的文檔說index(of:
可以返回nil
Array.index(作者:可以回到零,但有一個爲可選值
如何檢查零
var countryCodes = [String]()
let codeIndex = countriesList.index(of: countryTextField.text!)
var chosenCountryCode? = countryCodes[codeIndex!]
是第三行給出一個編譯錯誤檢查時編譯錯誤,說這是一個非可選類型的文檔說index(of:
可以返回nil
Array.index(作者:可以回到零,但有一個爲可選值
如何檢查零
下面是類似的情景工作代碼是如何將看起來像:
var countryCodes = [String]()
countryCodes = ["1000","1001","1002","1003","1004","1005","1006","1007","1008","1009"]
let countryList = ["Afganistan", "Argentina", "Armenia","Belgium","Brunei", "Bulgaria","Cambodia","Egypt","Yemen","Zambia"]
// assuming we get this from UI:
let countryTextField_text = "Egypt"
if let codeIndex = countryList.index(of: countryTextField_text) {
let chosenCountryCode = countryCodes[codeIndex]
print(chosenCountryCode)
}
將輸出:1007
如果你嘗試了一個不在列表中的國家,該怎麼辦? – quantumpotato
由於我們使用'if let'語法,並且我們不提供'else',那麼它會忽略它。這是可選的目的。如果它在那裏使用它,如果沒有的話,繼續前進。順便說一句。你可以將我的代碼剪切並粘貼到Playground上,並使用任何你喜歡的變體。 – Laxus
你爲什麼使用「var chosenCountryCode?」? –
因爲我希望選擇的國家代碼是一個變量。 – quantumpotato
Swift不是Ruby,不要使用'?或!'作爲變量名稱的後綴。在Swift中,你只能把''?或''as'action'在'=' – Hange