I am a novice with Swift and iOS development and I have come across a weird situation.
I am trying to use a do-catch statement to prevent an error, but it seems like the do-catch is doing nothing at all.
Here’s my code:
extension String {
mutating func insert(string: String, ind: Int) {
do {
try self.insert(contentsOf: string, at: self.index(self.startIndex, offsetBy: ind))
// This do-catch is to make sure nothing happens if there is no √ in the equation.
} catch {
}
}
}
The ‘try’ statement does not seem to be doing anything either! I have searched and searched online forums and have not come up with anything useful.
I know Java well, and you can always catch a specific error like:
try {
} catch NameOfException {
}
But I have found nothing the like in Swift. The error code that is returned is this:
Swift/StringCharacterView.swift:60: Fatal error: String index is out of bounds
2022-03-19 17:37:04.234797-0600 iOS-App[18937:2984774] Swift/StringCharacterView.swift:60: Fatal error: String index is out of bounds
(lldb)
I interpret this to mean that the String
index is clearly out of bounds, but I cannot find a method (like Java) to catch this kind of expression, or if I can even handle errors like Java at all. But I want to catch it so that my app does not crash.
I’m using a function to try and locate all instances of ‘√’ inside of a String
; myString.insert()
ind is the Index
to insert the provided String
value.
2
Answers
I have found a relatively dirty way to fix the unhandled error, like @Alexander said.
You can just add throws to your method signature and throw a custom error. I would also make the method generic and extend
StringProtocol
instead ofString
to supportSubstring
as well. Note that constraining toRangeReplaceableCollection
is required to be able to usemutating func insert<S>(contentsOf newElements: S, at i: Index) where S: Collection, Element == S.Element
: