Reputation: 9767
var countryCodes = [String]()
let codeIndex = countriesList.index(of: countryTextField.text!)
var chosenCountryCode? = countryCodes[codeIndex!]
that third line gives a compile error, saying it's a non-optional type. Documentation says index(of:
can return nil
.
How do I check for nil?
Upvotes: 0
Views: 37
Reputation: 86
Here's how a working code for similar scenario would look like:
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)
}
Will output: 1007
Upvotes: 5