ios - 将不同的数组合并到另一个数组中

标签 ios arrays swift

struct Product {
    let id: String
    let quantity: Int
    let price: Double
}

class ProductPrices {

    internal static var PricesArray : [String:Double] = ["product1": 5.00,"product2": 5.00,"product3": 5.00]

}

class ProductNames {

    internal static var NamesArray : [String:String] = ["product1": "name1","product2": "name2","product3": "name3"]

}

我有这个数组

["product1","product1","product2,"product1","product3","product2"]

我的问题是如何将这些项目放入 Product

预期结果:

Product(id: "name1", quantity: 3, price: 15.00)
Product(id: "name2", quantity: 2, price: 10.00)
Product(id: "name3", quantity: 1, price: 5.00)

最佳答案

输入

所以我们有一个结构

struct Product {
    let id: String
    let quantity: Int
    let price: Double
}

我们还有 2 个字典和 1 个数组

let prices = ["product1": 5.00, "product2": 5.00, "product3": 5.00]
let names = ["product1": "name1","product2": "name2","product3": "name3"]
let elms = ["product1", "product1", "product2", "product1", "product3", "product2"]

输出

现在我们要使用以下逻辑构建一个 Product(s) 数组

  1. Product.idnames
  2. 中获取
  3. Product.quantityProduct.idelms
  4. 中出现的次数
  5. Product.price 是产品的价格 * 数量

我们可以这样写

let products = names.compactMap { elm -> Product? in
    let name = elm.value
    let id = name
    let quantity = elms.filter { $0 == elm.key }.count
    guard quantity > 0, let price = prices[elm.key] else { return nil }
    return Product(id: id, quantity: quantity, price: price * Double(quantity))
}

测试

[
    Product(id: "name2", quantity: 2, price: 10.0),
    Product(id: "name1", quantity: 3, price: 15.0),
    Product(id: "name3", quantity: 1, price: 5.0)
]

The compactMap method is available in Swift 4.1. For previous versions of Swift please use flatMap.

关于ios - 将不同的数组合并到另一个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49572220/

相关文章:

ios - 从头开始重写 iOS 应用程序 "Could not change executable permissions on the application."

python - 具有两个条件的 if 语句

java - 如何将类中的属性与字符串进行比较?

java - else 语句多次打印 - 数组循环

ios - 当 BLE 设备中的值更改时如何更新 BatteryLevel

ios - 如何从 App Store 上可用的 ipa 文件获取 dSYM 文件

ios - 将时间、日期和标题添加到 UITable 单元格 View

ios - 从另一个文件 Swift/Xcode 调用时函数不会完全执行

ios - 使用 RestKIt 在核心数据实体中映射 json 对象

swift - 当只有一个值时,Function Builder 不工作?