¿ªÔÆÌåÓý

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

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


 

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)

?

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