swift - What the difference between function and subscript, particularly in below code? -
i read "the swift programming language" , subscript make me confused, there's example below subscript, implement function, subscript mean compared function?
there same output "6 times 3 18" below example.
struct timestable { let multiplier: int subscript(index: int) -> int { return multiplier * index } } let threetimestable = timestable(multiplier: 3) println("6 times 3 \(threetimestable[6])") struct timestable2 { let multiplier: int func times (index: int) -> int { return multiplier * index } } let threetimestable2 = timestable2(multiplier: 3) println("6 times 3 \(threetimestable2.times(6))")
subscripts subset of functions. can't quite things function can (they can't take inout
parameters, instance), other things well, convenient syntax (the square brackets [ ]
).
they used retrieve item collection index. instead of having write,
let array = [7, 3, 6, 8] let x = array.itematindex(0) // x == 7
we can write,
let x = array[0]
or instead of,
let dictionary = ["one": 1, "two": 2] let x = dictionary.objectforkey("one") // x == optional(1)
we can write,
let x = dictionary["one"] // x == optional(1)
the syntax short , intuitive. , okapi said, can act getters , setters variable properties, computed property.
the example in documentation non-traditional use of subscripts. think supposed illustrate point making - subscripts can used in place of function or computed property anywhere think [bracket]
syntax convenient , useful. use not limited accessing items in collection.
you refine own syntactic sugar.
Comments
Post a Comment