Created
July 3, 2015 23:07
-
-
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)
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
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