Convert NSRange from Range before Swift 4
let str = "Hello, playground! Hello, world! Hello, earth!" let attributedString = NSAttributedString(string: str) attributedString.enumerateAttributes(in: NSRange(location: 0, length: str.characters.count), options: NSAttributedString.EnumerationOptions.longestEffectiveRangeNotRequired) { (attributes, range, stop) in }
In order to have a smoother migration from now to Swift 4. Let's create a grammar compatible function to convert NSRange from Range before Xcode 9 is released officially.
extension NSRange { init(_ range: Range<String.Index>, in string: String) { self.init() let startIndex = range.lowerBound.samePosition(in: string.utf16) let endIndex = range.upperBound.samePosition(in: string.utf16) self.location = string.distance(from: string.startIndex, to: range.lowerBound) self.length = startIndex.distance(to: endIndex) } }
And now, we are able to do conversion like this NSRange(range, in: "A string"). Let's do an experiment. The following processes are trying to convert range0: Range -> range1: Range -> range2: NSRange.
let str = "Hello, playground! Hello, world! Hello, earth!" let range0 = str.range(of: "playground") print(String(describing: type(of: range0))) let range1 = NSRange(range0!, in: str) print(String(describing: type(of: range1))) let start = range1.location let end = start + range1.length let range2 = Range(uncheckedBounds: (start, end)) print(String(describing: type(of: range2)))








