2017-06-22 18 views
0
var countryCodes = [String]() 

let codeIndex = countriesList.index(of: countryTextField.text!) 
     var chosenCountryCode? = countryCodes[codeIndex!] 

是第三行給出一個編譯錯誤檢查時編譯錯誤,說這是一個非可選類型的文檔說index(of:可以返回nilArray.index(作者:可以回到零,但有一個爲可選值

如何檢查零

+0

你爲什麼使用「var chosenCountryCode?」? –

+0

因爲我希望選擇的國家代碼是一個變量。 – quantumpotato

+0

Swift不是Ruby,不要使用'?或!'作爲變量名稱的後綴。在Swift中,你只能把''?或''as'action'在'=' – Hange

回答

5

下面是類似的情景工作代碼是如何將看起來像:

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

+0

如果你嘗試了一個不在列表中的國家,該怎麼辦? – quantumpotato

+0

由於我們使用'if let'語法,並且我們不提供'else',那麼它會忽略它。這是可選的目的。如果它在那裏使用它,如果沒有的話,繼續前進。順便說一句。你可以將我的代碼剪切並粘貼到Playground上,並使用任何你喜歡的變體。 – Laxus

相關問題