Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What the difference between function and subscript, particularly in below code?

Tags:

swift

I read "The swift programming language" and the subscript make me confused, there's a example below with subscript, but I could also implement it with a function, so what the subscript exactly mean compared with function?

There were same output "6 times 3 is 18" with below example.

struct TimesTable {
    let multiplier: Int
    subscript(index: Int) -> Int {
        return multiplier * index
    }
}

let threeTimesTable = TimesTable(multiplier: 3)

println("6 times 3 is \(threeTimesTable[6])")


struct TimesTable2 {
    let multiplier: Int
    func times (index: Int) -> Int {
        return multiplier * index
    }
}

let threeTimesTable2 = TimesTable2(multiplier: 3)

println("6 times 3 is \(threeTimesTable2.times(6))")
like image 546
Jerry Zhao Avatar asked Feb 22 '26 15:02

Jerry Zhao


1 Answers

Subscripts are a subset of functions. They can't quite do all the things a function can do (they can't take inout parameters, for instance), but they do other things very well, with a very convenient syntax (the square brackets [ ]).

They are most often used to retrieve an item from a collection by its index. So instead of having to write,

let array = [7, 3, 6, 8]
let x = array.itemAtIndex(0)   // x == 7

we can just write,

let x = array[0]

Or instead of,

let dictionary = ["one": 1, "two": 2]
let x = dictionary.objectForKey("one")  // x == Optional(1)

we can just write,

let x = dictionary["one"]  // x == Optional(1)

The syntax is short and intuitive. And as Okapi said, they can act as getters and as setters for variable properties, just like a computed property.

The example in the documentation is a somewhat non-traditional use of subscripts. I think it is supposed to illustrate the very point that you are making - subscripts can be used in place of a function or a computed property just about anywhere that you think the [bracket] syntax would be convenient and useful. Their use is not limited to accessing items in a collection.

You get to refine your own syntactic sugar.

like image 103
letvargo Avatar answered Feb 24 '26 07:02

letvargo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!