In Python, it is a best practice to try and except errors, versus to check if a value exists. For example, it is considered bad practice if I was to do:
if my_dict['name']:
name = my_dict['name']
The best practice in Python is instead to try and except the assignment of the name variable above. It is more efficient in the Python language (faster). So this is the best practice:
try:
name = my_dict['name']
except KeyError:
name = ''
Is there a similar practice in Swift? I ask, because in the iOS Foundations, Module 2 Lesson 4 Challenge, my Preview crashes. It crashes, when I try to add 1 to every element in a List that is empty. So it crashes, when the second button is pressed; the method is called, and it tries to execute my for loop.
Here is the loop itself:
for i in 0...currentNumberArray.count-1 {
// Access the element in the array, then add 1 to it
currentNumberArray[i] += 1
}
I could solve this by checking to make sure my array has elements first like this:
if currentNumberArray.count > 0 {
for i in 0...currentNumberArray.count-1 {
// Access the element in the array, then add 1 to it
currentNumberArray[i] += 1
}
}
Otherwise, I tried to except it by following Swift 5 Try Catch Syntax and Error Handling (Code Examples), but havenât had much luck. In other words, it doesnât workâŚ
do {
// Loop through each element in the array, and add one.
for i in 0...currentNumberArray.count-1 {
// Access the element in the array, then add 1 to it
currentNumberArray[i] += 1
}
} catch {
print("Caught error. No numbers in array")
}
It gives a warning: âcatchâ block is unreachable because no errors are thrown in âdoâ block. Also, in Python, it is bad practice to blanked Except everything. So we should instead catch the specific error. For that, the error message from the debugger is this:
Swift/x86_64-apple-ios-simulator.swiftinterface:5670: Fatal error: Range requires lowerBound <= upperBound 2021-07-20 22:06:22.269136-0400 Lesson4-Challenge[51025:3177991] Swift/x86_64-apple-ios-simulator.swiftinterface:5670: Fatal error: Range requires lowerBound <= upperBound (lldb)
Also, in Python, I would want to log the full stack trace. So catch the particular error, even if it was a blanket Exception:
try:
name = my_dict['name']
Except as e:
print(f'Unexpected error occurred. Full stack: {e}')
The above would print out:
f'Unexpected error occurred. Full stack: KeyError: 'name'
Is there something similar in Swift?