我有一个像这样附加数组的问题:
var medicine = [(String, String?)]()
从Parse SDK我得到两个数组:
medicinesNames = ["Zyrtec", "medicine1", "medicine2"]
和
let amountName = ["2 times a day" , "in the morning", "after lunch"]
问题是如何在这些数组中附加带有字符串的属性数组?
我想将它附加到单独的函数中。第一乐趣的输出:
[("Zyrtec", nil), ("medicine1", nil)... ]
在第二次有趣之后我想得到这样的财产:
[("Zyrtec", "2 times a day"), ("Medicine1", "in the morning"),...]
答案 0 :(得分:1)
我建议通过两个函数更简洁:
let medicinesNames = ["Zyrtec", "medicine1", "medicine2"]
let amountName = ["2 times a day" , "in the morning", "after lunch"]
let medicine = Array(zip(medicinesNames, amountName))
medicine
的类型为[(String, String)]
,值为:
[("Zyrtec", "2 times a day"), ("medicine1", "in the morning"), ("medicine2", "after lunch")]
答案 1 :(得分:0)
使用重复循环
可以从两个独立的数组创建元组数组var medicine = [(String, String?)]()
let medicinesNames = ["Zyrtec", "medicine1", "medicine2"]
let amountName = ["2 times a day" , "in the morning", "after lunch"]
assert(medicinesNames.count == amountName.count, "both arrays must contain the same number of items")
for i in 0..<medicinesNames.count {
medicine.append((medicinesNames[i], amountName[i]))
}
实际上没有时间的药物是不可能的,我建议将数组声明为非可选的[(String, String)]