Fabian Fabian - 19 days ago 5
Swift Question

Try to get Index of element in String[] with error handling

I use

self.stnIdData.index(of: self.itemAtDefaultPositionId)!
to get the index of an element in my String[]. If - for some reason - the element is not in the array, I need to throw an error.
I tried it with the following piece of code:

do {
var indexOfSelectedId = 0
try indexOfSelectedId = self.stnIdData.index(of: self.itemAtDefaultPositionId)!

var counter = 0
for currStn in self.pickerData {
if(counter == indexOfSelectedId){
self.itemAtDefaultPosition = currStn
}
counter += 1
}

print(" PV: itemAtDefaultPosition: \(self.itemAtDefaultPosition)")
var defaultRowIndex = self.pickerData.index(of: self.itemAtDefaultPosition!)
print(" PV: defaultRowIndex: \(defaultRowIndex)")
if(defaultRowIndex == nil)
{
defaultRowIndex = 0
}
self.stnPicker.selectRow(defaultRowIndex!, inComponent: 0, animated: true)

} catch let error{
print("Error while setting ID: \(error)")
}


But I get this warning in xCode in this line:
try indexOfSelectedId = self.stnIdData.index(of: self.itemAtDefaultPositionId)!
:


No calls to throwing functions occur within 'try' expression

Answer

try can only be used with a method that is declared to throw. index(of:) is not such a method. Since index(of:) returns an optional, just use normal optional unwrapping using if let.

if let indexOfSelectedId = self.stnIdData.index(of: self.itemAtDefaultPositionId) {
    var counter = 0
    for currStn in self.pickerData {
        if(counter == indexOfSelectedId){
            self.itemAtDefaultPosition = currStn
        }
        counter += 1
    }

    print(" PV: itemAtDefaultPosition: \(self.itemAtDefaultPosition)")
    var defaultRowIndex = self.pickerData.index(of: self.itemAtDefaultPosition!)
    print(" PV: defaultRowIndex: \(defaultRowIndex)")
    if(defaultRowIndex == nil)
    {
        defaultRowIndex = 0
    }
    self.stnPicker.selectRow(defaultRowIndex!, inComponent: 0, animated: true)
} else {
    // Not found - handle as needed.
}