swift 袋定制系列
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 袋定制系列相关的知识,希望对你有一定的参考价值。
import UIKit
struct Bag<Element: Hashable>: CustomStringConvertible {
fileprivate var contents: [Element: Int] = [:]
var uniqueCount: Int {
return contents.count
}
var totalCount: Int {
return contents.values.reduce(0) { $0 + $1 }
}
init() { }
init<S: Sequence>(_ sequence: S) where S.Iterator.Element == Element {
for element in sequence {
add(element)
}
}
init<S: Sequence>(_ sequence: S) where S.Iterator.Element == (key: Element, value: Int) {
for (element, count) in sequence {
add(element, occurrences: count)
}
}
mutating func add(_ member: Element, occurrences: Int = 1) {
precondition(occurrences > 0, "Can only add a positive number of occurrences")
if let currentCount = contents[member] {
contents[member] = currentCount + occurrences
} else {
contents[member] = occurrences
}
}
mutating func remove(_ member: Element, occurrences: Int = 1) {
guard let currentCount = contents[member], currentCount >= occurrences else {
preconditionFailure("Removed non-existent elements")
}
precondition(occurrences > 0, "Can only remove a positive number of occurrences")
if currentCount > occurrences {
contents[member] = currentCount - occurrences
} else {
contents.removeValue(forKey: member)
}
}
var description: String {
return String(describing: contents)
}
}
extension Bag: ExpressibleByArrayLiteral {
init(arrayLiteral elements: Element...) {
self.init(elements)
}
}
extension Bag: ExpressibleByDictionaryLiteral {
init(dictionaryLiteral elements: (Element, Int)...) {
// The map converts elements to the "named" tuple the initializer expects.
self.init(elements.map { (key: $0.0, value: $0.1) })
}
}
extension Bag: Sequence {
// typealias Iterator = DictionaryIterator<Element, Int>
typealias Iterator = AnyIterator<(element: Element, count: Int)>
func makeIterator() -> Iterator {
// return contents.makeIterator()
var iterator = contents.makeIterator()
return AnyIterator {
return iterator.next()
}
}
}
extension Bag: Collection {
// typealias Index = DictionaryIndex<Element, Int>
typealias Index = BagIndex<Element>
var startIndex: Index {
return BagIndex(contents.startIndex)
}
var endIndex: Index {
return BagIndex(contents.endIndex)
}
subscript (position: Index) -> Iterator.Element {
precondition((startIndex ..< endIndex).contains(position), "out of bounds")
let dictionaryElement = contents[position.index]
return (element: dictionaryElement.key, count: dictionaryElement.value)
}
func index(after i: Index) -> Index {
return Index(contents.index(after: i.index))
}
}
struct BagIndex<Element: Hashable> {
fileprivate let index: DictionaryIndex<Element, Int>
fileprivate init(_ dictionaryIndex: DictionaryIndex<Element, Int>) {
self.index = dictionaryIndex
}
}
extension BagIndex: Comparable {
static func == (lhs: BagIndex, rhs: BagIndex) -> Bool {
return lhs.index == rhs.index
}
static func < (lhs: BagIndex, rhs: BagIndex) -> Bool {
return lhs.index < rhs.index
}
}
var shoppingCart = Bag<String>()
shoppingCart.add("Banana")
shoppingCart.add("Orange", occurrences: 2)
shoppingCart.add("Banana")
shoppingCart.remove("Orange")
let dataDictionary = ["Banana": 2, "Orange": 1]
var arrayLiteralBag: Bag = ["Banana", "Orange", "Banana"]
precondition(arrayLiteralBag.contents == dataDictionary, "Expected arrayLiteralBag contents to match \(dataDictionary)")
var dictionaryLiteralBag: Bag = ["Banana": 2, "Orange": 1]
precondition(dictionaryLiteralBag.contents == dataDictionary, "Expected dictionaryLiteralBag contents to match \(dataDictionary)")
for element in shoppingCart {
print(element)
}
for (element, count) in shoppingCart {
print("Element: \(element), Count: \(count)")
}
let firstItem = shoppingCart.first
precondition(firstItem!.element == "Orange" && firstItem!.count == 1, "Expected first item of shopping cart to be (\"Orange\", 1)")
// Check if the bag is empty
let isEmpty = shoppingCart.isEmpty
precondition(isEmpty == false, "Expected shopping cart to not be empty")
// Get the number of unique items in the bag
let uniqueItems = shoppingCart.count
precondition(uniqueItems == 2, "Expected shoppingCart to have 2 unique items")
// Find the first item with an element of "Banana"
let bananaIndex = shoppingCart.indices.first { shoppingCart[$0].element == "Banana" }!
let banana = shoppingCart[bananaIndex]
precondition(banana.element == "Banana" && banana.count == 2, "Expected banana to have value (\"Banana\", 2)")
以上是关于swift 袋定制系列的主要内容,如果未能解决你的问题,请参考以下文章