Skip to content

Instantly share code, notes, and snippets.

@pedrocid
Created March 19, 2016 11:18
Show Gist options
  • Save pedrocid/6a7a3a2b49cc035ff501 to your computer and use it in GitHub Desktop.
Save pedrocid/6a7a3a2b49cc035ff501 to your computer and use it in GitHub Desktop.
Custom subscripts in Swift
import UIKit
class Thing {
var name: String
var quantity: Int
init(name: String, quantity: Int){
self.name = name
self.quantity = quantity
}
}
class MyCollection{
private var things: [Thing]
init(things: [Thing]){
self.things = things
}
subscript(index: Int) -> Thing{
get{
return things[index]
}
set{
things[index] = newValue
}
}
//Read-only subscript
subscript(name: String) -> Int{
let thingsFiltered = self.things.filter { return $0.name == name }
if let thing = thingsFiltered.first{
return thing.quantity
}
return 0
}
}
let things = [Thing(name: "Ball",quantity: 2),Thing(name: "Dog", quantity: 1)]
let collection = MyCollection(things: things)
print(collection[1].name)
print(collection["Ball"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment