¿ªÔÆÌåÓý

ctrl + shift + ? for shortcuts
© 2025 Groups.io

Re: Swift Extension on Array - not working ... hmmm


 

¿ªÔÆÌåÓý

Per?, "Extensions can add new functionality to a type, but they can¡¯t override existing functionality."

I'm surprised the compiler doesn't complain.

Quality Coding logo
JON REID / Quality Coding, Inc.

On Feb 26, 2021, at 2:24 PM, David Koontz <david@...> wrote:

Help an old timer out... I don't know why this does NOT work...

I want to redefine the subscript method... in Swift ...?

var str = "Hello, playground"

?

//

// Extensions can add new subscripts to an existing type.

?

class Inning {

?? ? var array = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth"]

}

?

let inning = Inning()

?

print ("\(inning.array[1]) inning")

// prints "second inning"

?

extension Array {

? ? subscript(digitIndex: Int) -> Int {

? ? ? ? let decimalBase = 1

? ? ? ? return digitIndex - decimalBase

? ? }

}

?

//print("\(Inning[1]) inning")

let x = inning.array[1]

?

print ("\(x) inning") ? ? // expect first inning via use of extension



Much like the document does here:
Subscripts

Extensions can add new subscripts to an existing type. This example adds an integer subscript to Swift¡¯s built-in?Int?type. This subscript?[n]?returns the decimal digit?n?places in from the right of the number:

  • 123456789[0]?returns?9
  • 123456789[1]?returns?8

¡­and so on:

  1. extension Int {
  2. subscript(digitIndex: Int) -> Int {
  3. var decimalBase = 1
  4. for _ in 0..<digitIndex {
  5. decimalBase *= 10
  6. }
  7. return (self / decimalBase) % 10
  8. }
  9. }
  10. 746381295[0]
  11. // returns 5
  12. 746381295[1]
  13. // returns 9
  14. 746381295[2]
  15. // returns 2
  16. 746381295[8]
  17. // returns 7

Join [email protected] to automatically receive all group messages.