Kodeco Forums

Building a Custom Collection in Swift

Have you ever used a Collection, Sequence, or Slice when working with Swift collection types such as Dictionary or Array? In this tutorial, learn how you can implement your own custom collection types in Swift!


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/867-building-a-custom-collection-in-swift

This was well thought out. The author isolated key concepts, presenting complex protocol relationships in a clear and understandable manner. In doing so, the author provided insight into these relationships that weren’t apparent from reviewing the API individually. Great job - thank you!

Thank you Eric for this very clear and interesting tutorial, which helps in understanding better the power of the swift language.
How do code for allowing another sequence to be added to a collection.? such as:
shoppingCart.add(dataArray)
or
shoppingCart.add(shoppingCart)
Sincerely yours,

Nice article, but one small thing, wouldn’t nil coalescing be cleaner in the Bag’s add function:

mutating func add(_ member: Element, occurences: Int = 1) {
    precondition(occurences > 0, "Can only add a positive number of occurrences")
    contents[member] = contents[member] ?? 0 + occurences
}

Sorry, should have checked code! Forgot the brackets:

mutating func add(_ member: Element, occurences: Int = 1) {
precondition(occurences > 0, “Can only add a positive number of occurrences”)
contents[member] = **(**contents[member] ?? 0 ) + occurences
}

Hey @slankerful,

Ya, what you added (with the parenthesis) would totally work. I think this is just a matter of opinion on what format you like. I’m going to leave the existing code, only because it’s more clear in a tutorial format to see what’s happening with the more verbose code. One could argue either way that one is more clear while the other is more confusing, but either way good code reducing technique there :thumbsup:

This tutorial is more than six months old so questions regarding it are no longer supported for the moment. We will update it as soon as possible. Thank you! :]