I have two similar functions to get a substring of a string in swift (I only need one):
func substring(start: Int, end: Int) -> String {
let c = self.characters
let r = c.index(c.startIndex, offsetBy: start)..<c.index(c.startIndex, offsetBy: end)
let substring = self[r]
return substring
}
and:
func substring(start: Int, end: Int) -> String {
let startIndex = self.index(self.startIndex, offsetBy: start)
let endIndex = self.index(self.startIndex, offsetBy: end)
return self[startIndex..<endIndex]
}
How can I properly guard this? Here is the main error I can get here:
fatal error: cannot decrement before startIndex
I need to be able to send in all types of bad values into this function, such as negative start
s and end
s or end
s that are less than start
s. For the purpose of learning, let's assume there is a good reason to allow nonsense parameters in the function.
I have tried a few things, like:
func substring(start: Int, end: Int) -> String {
guard end > 0 else {
return "something"
}
let startIndex = self.index(self.startIndex, offsetBy: start)
let endIndex = self.index(self.startIndex, offsetBy: end)
return self[startIndex..<endIndex]
}
but these either don't work or cause my app to freeze.