I am using the following code to get a String
substring from an NSRange
:
func substring(with nsrange: NSRange) -> String? {
With Swift 4 we can get substrings this way.
Substring from index
let originStr = "Test"
let offset = 1
let str = String(originStr.suffix(from: String.Index.init(encodedOffset: offset)))
Substring to index
let originStr = "Test"
let offset = 1
String(self.prefix(index))
Use Range(_, in:) to convert an NSRange to a Range in Swift 4.
extension String {
func substring(with nsrange: NSRange) -> Substring? {
guard let range = Range(nsrange, in: self) else { return nil }
return self[range]
}
}