Skip to content

Instantly share code, notes, and snippets.

@phynet
Last active May 13, 2018 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phynet/4f1bb50229c9e267ec9d48b6a080bbb7 to your computer and use it in GitHub Desktop.
Save phynet/4f1bb50229c9e267ec9d48b6a080bbb7 to your computer and use it in GitHub Desktop.
//: 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