Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class ImmutableList<T> {
private let listItems: [T]
init() {
self.listItems = [T]()
}
init(listItems: [T]) {
self.listItems = listItems
}
func add(item: T) -> ImmutableList<T> {
var listWithAddedItem = self.listItems
listWithAddedItem.append(item)
return ImmutableList<T>(listItems: listWithAddedItem)
}
func add(items: [T]) -> ImmutableList<T> {
var listWithAddedItems = self.listItems
listWithAddedItems.appendContentsOf(items)
return ImmutableList<T>(listItems: listWithAddedItems)
}
func count() -> Int {
return self.listItems.count
}
func items() -> [T] {
return self.listItems
}
}
let firstList = ImmutableList<Int>(listItems: [1,2])
firstList.items() // [1, 2]
// Adding an item returns a new instance, firstList is untouched
let firstListWithAppended = firstList.add(10)
firstListWithAppended.items() // [1, 2, 10]
firstList.items() // [1, 2]
let firstListWithMultipleAdded = firstList.add(9).add([2,4]).add(11)
firstListWithMultipleAdded.items() // [1, 2, 9, 2, 4, 11]
firstList.items() // [1, 2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment