Sometimes, you want to display a string that has certain attributes for a range of characters. For example, suppose that you want to display the string “Big Nerd Ranch” and want the letters 0 through 2 to be bold, the letters 4 through 7 to be orange, and the letters 9 through 13 to be subscripts.

When dealing with a range of numbers, Cocoa uses the struct NSRange. NSRange has two members, location and length, which are both integers. The location is the index of the first item, and the length is the number of items in the range. You can use the function NSMakeRange() to create an NSRange, but in Swift it is more expedient to use the range expression initializer: NSRange(0...4).

To create strings with attributes ...

Get Cocoa Programming for OS X: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.