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])
            }
        }
    }
}

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Or if let toRng = self[fromRng.upperBound...].range(of: to) { ... to save some keystrokes :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.