Subscripts (indexer methods) with multiple parameters in Swift
class Car {
var model: String
var year: Int
var price: Int
init(_ model: String, _ year: Int, _ price: Int) {
self.model = model
self.year = year
self.price = price
}
}
class ToyotaPrices {
private var cars: [Car] = [Car]()
subscript(model: String, year: Int) -> Int {
get {
if let car = getCar(model, year) {
return car.price
}
return 0
}
set {
if let car = getCar(model, year) {
car.price = newValue
}
let car = Car(model, year, newValue)
cars.append(car)
}
}
private func getCar(model: String, _ year: Int) -> Car? {
let arCars = cars.filter(
{$0.model == model && $0.year == year})
if arCars.count == 0 {
return nil
}
return arCars[0]
}
}
let prices = ToyotaPrices()
prices["Rush", 2012] = 16818;
prices["Land Cruiser", 2014] = 54988
let priceRAV4 = prices["RAV4", 2015]
//priceRAV4 is 0
let priceRush = prices["Rush", 2012]
//priceRush is 16818
- Log in to post comments