0

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 starts and ends or ends that are less than starts. 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.

twharmon
  • 4,153
  • 5
  • 22
  • 48

1 Answers1

-1

You can deal with this yourself, but I would recommend looking here if you want an easier time dealing with Swift Strings.

Community
  • 1
  • 1
GetSwifty
  • 7,568
  • 1
  • 29
  • 46