Locating paragraph breaks in Swift: Objective-C in Translation


Apple provides us with advice and code for finding paragraph breaks using Objective-C in its documentation. In the translation of this code into Swift it is necessary to take into account the difference between a Range and an NSRange. In an NSRange the work is done with simple integers, but with Range<String.Index> integers cannot replace indexes.
let string = "my string\n of paragraphs \r is \u{2029} pretty wacky!"
let length = string.endIndex
var paraStart = string.startIndex, paraEnd = string.startIndex, contentsEnd = string.startIndex
var array = [String]()

while (paraEnd < length) {
    
    string.getParagraphStart(&paraStart, end: &paraEnd, contentsEnd:&contentsEnd, forRange:Range(start: paraEnd,end:paraEnd))
    
    let r = Range(start: paraStart, end: contentsEnd)
    array.append(string.substringWithRange(r))
}
So where Apple initializes the paraStart, paraEnd and contentsEnd variables with 0 in Objective-C, it is necessary in Swift to initialize with string.startIndex (which provides an index of zero).

Note: Had we wished to begin the string search at some other point then we could use advance() to achieve this, but in this case it isn't necessary.

For convenience the constant length instead of taking a count of the string elements, uses .endIndex because this means it can then be compared to paraEnd without first transforming the value into an Int using distance().

The end result is that a string with a range of different paragraph indicators is broken into an array of strings with those paragraph indicators removed.

Endorse on Coderwall

Comments