Writing Your First Subscript

To create a subscript, you use the keyword subscript in your class, struct, or enum. A basic subscript looks like this:

class Hand {    let fingers = ["thumb","index","middle","ring","pinky"]    subscript(i:Int) -> String{        return fingers[i]    }}let hand = Hand()println("I had to use my \(hand[2]) finger to on the way into work today.")

Here you are creating a class called Hand, which has five fingers. You can access each finger by index. After you create a new instance hand, you can access the thumb by using hand[0]. This directly accesses the fingers array. You can read and write to subscripts. You can mark them as read-only or read-write. Currently the hand/fingers access is ...

Get Learning Swift™ Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.