1

I have a slice function which I got here. I was wondering how I can modify it so that if the to string is not found, but it found from it will return the end index of the entire string (.count-1). Right now it's obviously crashing if I call .slice and there is no to string found.

extension String {

    func slice(from: String, to: String) -> String? {

        return (range(of: from)?.upperBound).flatMap { substringFrom in
            (range(of: to, range: substringFrom..<endIndex)?.lowerBound).map { substringTo in
                String(self[substringFrom..<substringTo])
            }
        }
    }
}
Anters Bear
  • 1,816
  • 1
  • 15
  • 41

1 Answers1

3

Here's one possible solution:

extension String {
    func slice(from: String, to: String) -> String? {
        if let fromRng = range(of: from) {
            if let toRng = range(of: to, range: fromRng.upperBound..<endIndex) {
                // "from" and "to" found, get parts between
                return String(self[fromRng.upperBound..<toRng.lowerBound])
            } else {
                // "to" not found, return everything after "from"
                return String(self[fromRng.upperBound...])
            }
        } else {
            // "from" not found
            return nil
        }
    }
}

It's not as "fancy" as the original but personally I think the logic is much easier to read.

rmaddy
  • 314,917
  • 42
  • 532
  • 579