arrays - 像购物 list 一样格式化数组

标签 arrays swift swift3 shopping-cart

我有一个格式如下的数组:

[“裤子:15.50”,“裤子:15.50”,“套头衫:12.99”,“鞋子:50.00”]

我想这样格式化:

[“2x 裤子:31.00”,“1x 套头衫:12.99”,“1x 鞋子:50.00”]

我试过用这个格式化:

 var counts: [String:Int] = [:]
 var shoppingList = ["Trousers : 15.50", "Trousers : 15.50", "Jumper : 12.99", "Shoes: 50.00"]
 var formattedShoppingList = [String]()

     for item in shoppingList {
         counts[item] = (counts[item] ?? 0) + 1
     }


     for (key, value) in counts {

         let display:String = String(value) + "x " + key
         formattedShoppingList.append(display)

     }

但是我明白了

[“2x 裤子:15.50”,“1x 套头衫:12.99”,“1x 鞋子:50.00”]

如果我使用字典,则不能有重复项。我该如何处理?

最佳答案

我会制作一个结构来表示商品名称/价格对(以及 future 可能的其他数据,例如库存数量)。

struct Item: Hashable {
    let name: String
    let price: Double

    public var hashValue: Int { return name.hashValue ^ price.hashValue }

    public static func ==(lhs: Item, rhs: Item) -> Bool {
        return lhs.name == rhs.name && rhs.price == rhs.price
    }
}

let shoppingList = [
    Item(name: "Trousers", price: 15.50),
    Item(name: "Trousers", price: 15.50),
    Item(name: "Jumper", price: 12.99),
    Item(name: "Shoes", price: 50),
]

let counts = shoppingList.reduce([Item: Int]()){counts, item in
    var counts = counts
    counts[item] = (counts[item] ?? 0) + 1
    return counts
}

let formattedShoppingList = counts.map{ item, count in "\(count)x \(item.name): £\(item.price)" }

print(formattedShoppingList)

["2x Trousers: £15.5", "1x Shoes: £50.0", "1x Jumper: £12.99"]

关于arrays - 像购物 list 一样格式化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41403537/

相关文章:

ruby-on-rails - 在 Rails 3.2 中从数组调用 ActiveRecord 关联方法

在数组中收集相同的单词,C

c++ - new >> 我如何将一个包含 3 列且每列包含 100 个数字的文件读取到一个数组中?

ios - 用户登录时 PopToRootViewController 不更新 collectionview

ios - 核心数据 : Can only use -performBlock: on an NSManagedObjectContext that was created with a queue

ios - 具有水平和垂直滚动的自定义 Collection View 的显示更改

ios - 如何向 Realm 对象添加新属性?

c - 使用临时变量或直接从数组更有效?

ios - 如何在 'doneButtonAction' 方法中获取 textField id,同时在 swift 中使用多个 numPad 键盘文本字段?

ios - 存储 UITextView 字符串/文本数据