Created
March 19, 2016 11:18
-
-
Save pedrocid/6a7a3a2b49cc035ff501 to your computer and use it in GitHub Desktop.
Custom subscripts in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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