问题
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:
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.
来源:https://stackoverflow.com/questions/50341541/modify-slice-from-string-to-string-function-to-return-last-index-if-to-string-no