iOS Programming Cookbook
上QQ阅读APP看书,第一时间看更新

Define subscripts

One of features that extensions provide to us is the ability to define subscripts to a particular type. Subscripting allows you to get value by calling [n] to get information at index n. Like array, when you access item at that index, you can do the same with any type you want. In the following example, we will add subscripting support to the String type:

extension String{ 
   subscript(charIndex: Int) -> Character{ 
       let index = startIndex.advancedBy(charIndex) 
       return self[index] 
   } 
} 
let str = "Hello" 
str[0] // "H" 

To add subscript to type, just add the keyword subscript followed by index and the return type. In our preceding example, the subscript will return the character at a given index. We advanced the startIndex, which is a property in the String type and points to the first character by the input charIndex. Then, we return the character at that Index.