¿ªÔÆÌåÓý

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

Swift Extension on Array - not working ... hmmm


 

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"

?

// https://docs.swift.org/swift-book/LanguageGuide/Extensions.html

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


 

¿ªÔÆÌåÓý

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


 

Figured it out ... with lots of help from the doc:??at Botton of page is Type Subscript with an example

?

?

var str = "Hello, playground"

?

// https://docs.swift.org/swift-book/LanguageGuide/Extensions.html

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

?

enum Inning: Int {

? ? case first = 1, second, third, fourth, fifth, sixth, seventh, eighth, ninth

? ? // using a Instance Subscript

? ? subscript(n: Int) -> Inning {

? ? ? ? return Inning(rawValue: n)!

? ? }

}

?

//let current = Inning[1]

let inning = Inning(rawValue: 1)!

let current = inning[8]

print("\(current) inning")

?

?

// Better technique

enum Inning2: Int {

? ? case first = 1, second, third, fourth, fifth, sixth, seventh, eighth, ninth

? ? // using a Type Subscript

? ? static subscript(n: Int) -> Inning2 {

? ? ? ? return Inning2(rawValue: n)!

? ? }

}

?

let current2 = Inning2[1]

print("\(current2) inning")

?

?

?

// Type Subscript from https://docs.swift.org/swift-book/LanguageGuide/Subscripts.html

enum Planet: Int {

? ? case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune

? ? static subscript(n: Int) -> Planet {

? ? ? ? return Planet(rawValue: n)!

? ? }

}

?

let home = Planet[3]

print(home)

?


 

OUCH! that black background - hurts the eyes...

?

var str = "Hello, playground"

?

// https://docs.swift.org/swift-book/LanguageGuide/Extensions.html

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

?

enum Inning: Int {

? ? case first = 1, second, third, fourth, fifth, sixth, seventh, eighth, ninth

? ? // using a Instance Subscript

? ? subscript(n: Int) -> Inning {

? ? ? ? return Inning(rawValue: n)!

? ? }

}

?

//let current = Inning[1]

let inning = Inning(rawValue: 1)!

let current = inning[8]

print("\(current) inning")

?

?

// Better technique

enum Inning2: Int {

? ? case first = 1, second, third, fourth, fifth, sixth, seventh, eighth, ninth

? ? // using a Type Subscript

? ? static subscript(n: Int) -> Inning2 {

? ? ? ? return Inning2(rawValue: n)!

? ? }

}

?

let current2 = Inning2[1]

print("\(current2) inning")

?

?

?

// Type Subscript from https://docs.swift.org/swift-book/LanguageGuide/Subscripts.html

enum Planet: Int {

? ? case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune

? ? static subscript(n: Int) -> Planet {

? ? ? ? return Planet(rawValue: n)!

? ? }

}

?

let home = Planet[3]

print(home)

?


 

// on? a slightly different note

class LineUp {

? ? var lineup = ["Bob", "Tony", "Iris", "Jane", "Nan", "Dave", "George", "Ringo", "Shannon" ]

?? ?

? ? subscript(n: Int) -> String {

? ? ? ? return lineup[n-1]

? ? }

}

?

let list = LineUp()

?

print("\(list[1]) batter")

?

list.lineup.append("Paul")

print("\(list[10]) battting last")

?


 

After making the LineUp class that can be iterated starting with 1 (Zero is for programmers) Customers start at ONE.

Now I want the iterator to wrap around... like a team that bats around the line up... ?so into the Modulo arithmetic...

I'm doing this experiment in a Swift Xcode Playground... so not to sure about how to do unit testing inside the Playground???

indexWrapped <= 0 ?? index = indexMax : index = indexWrapped - 1

give 2 errors:?
Cannot assign to value: result of conditional operator '? :' is never mutable. ?Result values in '? :' expression have mismatching types '()' and 'Int'

?

Now can anyone put this is simple caveman logic... seems like a perfectly good place to use my most hated ? :?operation. ?I don't GROK.

?

class LineUp {

? ? var lineup = ["Bob", "Tony", "Iris", "Jane", "Nan", "Dave", "George", "Ringo", "Shannon" ]

?? ?

? ? subscript(n: Int) -> String {

? ? ? ? var index = 0

? ? ? ? let indexMax = lineup.count

? ? ? ? let indexWrapped = n % indexMax

? ? ? ? indexWrapped <= 0 ?? index = indexMax : index = indexWrapped - 1

? ? ? ? return lineup[index]

? ? }

}

?

?


 

class LineUp {

? ? var lineup = ["Bob", "Tony", "Iris", "Jane", "Nan", "Dave", "George", "Ringo", "Shannon" ]

?? ?

? ? subscript(n: Int) -> String {

? ? ? ? var index = 0

? ? ? ? let indexMax = lineup.count

? ? ? ? let indexWrapped = n % indexMax

? ? ? ? //indexWrapped <= 0 ?? index = indexMax : index = indexWrapped - 1

? ? ? ? if ( indexWrapped <= 0 ) { index = indexMax - 1 } else { index = indexWrapped - 1 }

? ? ? ? return lineup[index]

? ? }

}

?

let list = LineUp()

?

print("\(list[1]) batter")

?

list.lineup.append("Paul")

print("\(list[17]) battting last")

print("\(list[18]) battting last")

print("\(list[19]) battting last")

print("\(list[20]) battting last")

print("\(list[21]) battting last")

?


 

I'm learning & sharing... if you have critique of this... I could learn more!


 

David,
If I understand what you're doing, you should just be able to say?
? return lineup[n % lineup.count]

The line you have:
? let?indexWrapped = n?%?indexMax
already sets the indexWrapped to a number from 0..<indexMax i.e. 0..<lineup.count, so there's no need for the "if" statement following.

(I'm assuming no negative indexes will happen.)

For the ?: operator, some other time:), you probably want to think of it as an expression:
? ? let variable = (condition) ? answer1 : answer2

You don't have to assign the result of ?: - you can use it directly in another expression, but it gets messy pretty quickly.

-- Bill