官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 孟连| 青田县| 和政县| 西昌市| 雅江县| 湖口县| 太和县| 密山市| 彩票| 鹰潭市| 施秉县| 营山县| 商城县| 秭归县| 阜新市| 宾川县| 沅江市| 邯郸县| 抚州市| 安新县| 攀枝花市| 卢龙县| 浮山县| 平利县| 永丰县| 扶风县| 呈贡县| 沂南县| 双城市| 武穴市| 武功县| 鄄城县| 武定县| 保康县| 吉水县| 宝丰县| 徐闻县| 新巴尔虎右旗| 林周县| 蒙阴县| 屯门区|