0

I've researched this in Swift and am confused on where custom subscripts are useful compared to methods and functions. What is the power in using them rather than using a method/func?

Preet Sangha
  • 64,563
  • 18
  • 145
  • 216
Ali
  • 505
  • 4
  • 12

2 Answers2

3

It's purely stylistic. Use a subscript whenever you'd prefer this syntax:

myObject[mySubscript] = newValue

over this one:

myObject.setValue(newValue, forSubscript: mySubscript)

Subscripts are more concise and, when used in appropriate situations, clearer in intent.

andyvn22
  • 14,696
  • 1
  • 52
  • 74
  • So its best to write out a custom subscript when you want to access/alter elements in an array/dictionary but it wouldn't be useful to write a subscript that returns a multiplied number...correct? Also, can't I write a method or function that access and alters a specific element of an array/dictionary?.....that was my point....what would be the difference? Just the subscript keyword?......and the nonnamed closure? – Ali Sep 23 '15 at 19:20
  • Yes, the only difference between a subscript and a method is style and appearance of code. And yes, the best times to use subscripts are accessing/altering child elements of something. If you think of your operation as "looking something up", consider a subscript. – andyvn22 Sep 23 '15 at 19:26
  • so basically the `subscript` keyword is just for the sake of organization and the compiler doesn't do any calculation when seeing the `subscript` keyword, its just for me the programmer to organize my code better...? – Ali Sep 23 '15 at 19:30
  • All the subscript keyword does is change the syntax you must use when calling your method from `myObject.setValue(newValue, forSubscript: mySubscript)` to `myObject[mySubscript] = newValue`. – andyvn22 Sep 23 '15 at 19:31
  • okay, I see.....I really appreacitate your time and effort in helping me with this.....Im more familiar with the power of custom subscripts now, but I believe I might search programs and see them in effect to fully wrap my head around its difference from funcs/methods/closures.....but you helped a great deal, I've been studying this in a swift book but it doesnt really break down the details which is why I'm usually confused. – Ali Sep 23 '15 at 19:49
1

Which is an easier, clearer way to refer to an array element: myArray[1] or myArray.objectAtIndex(1)?

Would you like to saymyArray[1...3], or would it by just fine if you had to say something like myArray.sliceFromIndex(1).throughIndex(3) every time?

And hey, you know what? Arithmetic operators are also just functions. So don't we abandon them, so we'd have to say something like

let sum = a.addedTo(b.multipliedBy(c))

Wouldn't that be just the same really? What's the power in having arithmetic operators really?

matt
  • 515,959
  • 87
  • 875
  • 1,141