Created
August 26, 2020 05:59
-
-
Save focuspirit/ce2be1845d62bc26ba559e515bebac33 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum CurlyBracketsType: String { | |
case forwards = "{" | |
case backwards = "}" | |
private var opposite: String { | |
switch self { | |
case .forwards: | |
return CurlyBracketsType.backwards.rawValue | |
case .backwards: | |
return CurlyBracketsType.forwards.rawValue | |
} | |
} | |
private var options: NSString.CompareOptions { | |
switch self { | |
case .forwards: | |
return .literal | |
case .backwards: | |
return .backwards | |
} | |
} | |
private func indexStart(_ changeIndex: String.Index, text: String) -> String.Index { | |
switch self { | |
case .forwards: | |
return changeIndex | |
case .backwards: | |
return text.startIndex | |
} | |
} | |
private func indexLength(_ changeIndex: String.Index, text: String) -> String.Index { | |
switch self { | |
case .forwards: | |
return text.endIndex | |
case .backwards: | |
return changeIndex | |
} | |
} | |
func coverRange(_ startIndex:String.Index, text: String) -> (String.Index, String.Index)? { | |
let resultRange = text.range(of: opposite, options: options, range: indexStart(startIndex, text: text)..<indexLength(startIndex, text: text)) | |
if let resultRange = resultRange { | |
let oppositeIndex = resultRange.upperBound | |
switch self { | |
case .forwards: | |
return (startIndex, oppositeIndex) | |
case .backwards: | |
let index = text.index(before: oppositeIndex) | |
let end = text.index(after: startIndex) | |
return (index, end) | |
} | |
} | |
return nil | |
} | |
func substring(text: String, startIndex: String.Index, endIndex: String.Index) -> String { | |
let start = text.distance(from: text.startIndex, to: startIndex) | |
let length = text.distance(from: startIndex, to: endIndex) | |
return (text as NSString).substring(with: NSMakeRange(start, length)) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment