Last active
May 13, 2018 18:24
-
-
Save phynet/4f1bb50229c9e267ec9d48b6a080bbb7 to your computer and use it in GitHub Desktop.
This file contains 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
//: 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