Skip to content

Instantly share code, notes, and snippets.

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 AndyIbanez/9bca75a482f4de206388 to your computer and use it in GitHub Desktop.
Save AndyIbanez/9bca75a482f4de206388 to your computer and use it in GitHub Desktop.
Code used for my tutorial "Embracing the Swift Standard Library" (https://www.andyibanez.com/embracing-the-swift-standard-library)
struct ShoppingItem {
let name: String
let price: Float
init(name: String, price: Float) {
self.name = name
self.price = price
}
}
struct ShoppingList : SequenceType, GeneratorType, ArrayLiteralConvertible {
private let items: [ShoppingItem]
var count: Int {
get {
return items.count
}
}
var total: Float {
get {
var total: Float = 0
for item in self.items {
total += item.price
}
return total
}
}
var average: Float {
get {
return self.total / Float(self.count)
}
}
subscript(index: Int) -> ShoppingItem {
return self.items[index]
}
/// MARK: - ArrayLiteralConvertible
init(arrayLiteral: ShoppingItem...) {
self.items = arrayLiteral
}
/// MARK: - SequenceType
typealias Generator = ShoppingList
func filter(includeElement: (ShoppingItem) -> Bool) -> [ShoppingItem] {
var fItems = [ShoppingItem]()
for itm in self.items where includeElement(itm) == true {
fItems += [itm]
}
return fItems
}
func generate() -> Generator {
return self
}
/// MARK: - GeneratorType
var currentElement = 0
mutating func next() -> ShoppingItem? {
if currentElement < self.items.count {
let curItem = currentElement
currentElement++
return self.items[curItem]
}
return nil
}
}
let apples = ShoppingItem(name: "Apples", price: 12.76)
let carrots = ShoppingItem(name: "Carrots", price: 15.43)
let bananas = ShoppingItem(name: "Bananas", price: 32.53)
let shoppingList: ShoppingList = [apples, carrots, bananas]
print("All items in my list:")
for item in shoppingList {
print("\(item.name) cost \(item.price)")
}
print("Only items that cost under 13:")
for item in shoppingList where item.price < 13 {
print("\(item.name) cost \(item.price)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment