Skip to content

Instantly share code, notes, and snippets.

@phynet

phynet/subscript.swift

Last active May 13, 2018
Embed
What would you like to do?
//: Playground - noun: a place where people can play
//Subscript: shortcut for accessing the member elements in a collection, list, or sequence.
import UIKit
//#1
struct TimesTable {
let multiplier: Int
subscript(index: Int) -> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
print("six times three is \(threeTimesTable[6])")
//#2
class Room {
let name: String
init(name: String) { self.name = name }
}
class Residence {
var rooms = [Room]()
var numberOfRooms: Int {
return rooms.count
}
subscript(i: Int) -> Room {
get {
return rooms[i]
}
set {
rooms[i] = newValue
}
}
func printNumberOfRooms() {
print("The number of rooms is \(numberOfRooms)")
}
}
let nrrooms = Residence()
nrrooms.rooms = [Room(name: "one"), Room(name: "two")]
nrrooms.printNumberOfRooms()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.