Skip to content

Instantly share code, notes, and snippets.

@raheelahmad
Created January 29, 2016 04:44
Show Gist options
  • Save raheelahmad/e61bf32926ea4daf540c to your computer and use it in GitHub Desktop.
Save raheelahmad/e61bf32926ea4daf540c to your computer and use it in GitHub Desktop.
Using RangeReplaceableCollectionType
//: Playground - noun: a place where people can play
struct Room: IntegerLiteralConvertible {
let number: Int
init(integerLiteral value: Int) {
number = value
}
}
extension Room: CustomStringConvertible {
var description: String { return "#\(number)" }
}
struct Hotel {
private var rooms: [Room] = []
}
extension Hotel: CollectionType {
var startIndex: Int { return 0 }
var endIndex: Int { return rooms.count }
subscript (index: Int) -> Room {
precondition(index >= 0 && index < endIndex, "No room at \(index)")
return rooms[index]
}
}
extension Hotel: RangeReplaceableCollectionType {
mutating func reserveCapacity(n: Int.Distance) { }
mutating func replaceRange<C : CollectionType where C.Generator.Element == Room>(subRange: Range<Int>, with newElements: C) {
rooms.replaceRange(subRange, with: newElements)
}
}
var hotel = Hotel(rooms: [2, 4, 12])
hotel.append(4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment