Per?, "Extensions can add new functionality to a type, but they can¡¯t override existing functionality."
I'm surprised the compiler doesn't complain.
 |
JON REID / Quality Coding, Inc.
|
toggle quoted message
Show quoted text
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:
SubscriptsExtensions 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:
- extension Int {
- subscript(digitIndex: Int) -> Int {
- var decimalBase = 1
- for _ in 0..<digitIndex {
- decimalBase *= 10
- }
- return (self / decimalBase) % 10
- }
- }
- 746381295[0]
- // returns 5
- 746381295[1]
- // returns 9
- 746381295[2]
- // returns 2
- 746381295[8]
- // returns 7