【问题标题】:Combining 3 Arrays into one custom line of text将 3 个数组组合成一个自定义文本行
【发布时间】:2020-08-07 13:09:47
【问题描述】:

我正在创建一个烘焙应用程序,但我被困在一个简单的任务中……但不知道如何解决它。

我基本上有 3 个数组:

let quantity = [200, 300, 400]
let value = ["g", "g", "kg"]
let ingredient = ["Flour", "Butter", "Chocolate"]

我想要的是在文本中显示这 3 个数组,如下所示:

200 g Flour - 300 g Butter - 400 kg Chocolate

我尝试了以下方法:

let arrays = [value, ingredient]
let merge = (0..<arrays.map{$0.count}.max()!).flatMap{i in arrays.filter{i<$0.count}.map{$0[i]}}
let text = merge.joined(separator: " - ")

导致:

g - Flour - g - Butter - kg - Chocolate 
 

有人知道如何实现吗? 这可能很简单,但我没有看到它……

【问题讨论】:

  • 最好为此创建一个顶级结构,而不是维护 3 个单独的数组。

标签: arrays swift merge


【解决方案1】:

我建议创建一个顶级结构来保存所有这些元素。处理数组及其索引是有风险的并且不是很干净。使用您当前的方法,您必须维护 3 个单独的数组 - 如果您忘记向其中一个数组添加元素怎么办?

您可以尝试以下方法:

struct Ingredient: CustomStringConvertible {
    let name: String
    let quantity: Int // may be Double as well
    let unit: Unit
    
    var description: String {
        "\(quantity) \(unit.rawValue) \(name)"
    }
}

enum Unit: String {
    case gram = "g"
    case kilogram = "kg"
}

let ingredients = [
    Ingredient(name: "Flour", quantity: 200, unit: .gram),
    Ingredient(name: "Butter", quantity: 300, unit: .gram),
    Ingredient(name: "Chocolate", quantity: 400, unit: .kilogram)
]

let description = ingredients.map(String.init).joined(separator: " - ")
print(description) 
// prints "200 g Flour - 300 g Butter - 400 kg Chocolate"

【讨论】:

  • 不鼓励使用描述map(String.init)
  • 顺便说一句let ingredients = [("Flour",200,.gram), ("Butter", 300, .gram), ("Chocolate", 400, .kilogram)].map(Ingredient.init)
  • @LeoDabus 很好,谢谢 :) 我不知道我能做到。
  • @pawello2222 非常感谢!实际上拥有所有元素,但无法弄清楚如何将它们组合在一起:)
【解决方案2】:

您可以执行以下操作:

let quantity = [200, 300, 400]
let value = ["g", "g", "kg"]
let ingredient = ["Flour", "Butter", "Chocolate"]

var str = ""
for index in quantity.indices {
    str += "\(quantity[index]) \(value[index]) \(ingredient[index]) - "
}

let result = str.dropLast(3)
print(result)

结果:
200 g Flour - 300 g Butter - 400 kg Chocolate

【讨论】:

    【解决方案3】:

    如果您必须以这种方式处理 3 个数组,那么最好使用嵌套的 Zip2Sequence,因为它在处理不同长度的数组时会更安全。
    理想情况下,您希望所有数组都具有相同的长度,但是如果……如果不是,该怎么办。

    let quantity = [200, 300, 400]
    let value = ["g", "g", "kg"]
    let ingredient = ["Flour", "Butter", "Chocolate"]
    
    let zippedQuantity = zip(quantity, value)
    let result = zip(zippedQuantity, ingredient).map { (quantityZip, ingredient) in
        "\(quantityZip.0) \(quantityZip.1) \(ingredient)"
    }
    
    let string = result.joined(separator: " - ")
    print(string)
    

    遗憾的是没有Zip3Sequence 可以让这个过程更快

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多