O'Reilly logo

Learning Swift™ Programming by Jacob Schatz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required