避免在Swift中复制元组

时间:2015-11-14 11:43:21

标签: ios swift watchkit watch-os-2

在我的watchOS2应用中,我array of tuples喜欢这样:

var medicines = [(String, String?, String?)]()

在刷新功能中,我想清除这个元组数组,用新的String项附加它。我怎样才能做到这一点 ?我想避免在我的数组中使用相同的东西。或者也许有更好的主意?

我的刷新功能:

let iNeedCoreData = ["Value": "CoreData"]
    session.sendMessage(iNeedCoreData, replyHandler: { (content: [String: AnyObject]) -> Void in

        if let meds = content["reply"] as? [String: [String]] {

             self.medicines = [(String, String?, String?)]()


            if let medicineNames = meds["medicines"], amountNames = meds["amount"], timeNames = meds["time"] {
                if medicineNames.count != 0 {
                    self.addMedicines(medicineNames)
                    self.addQuantities(amountNames)
                    self.addTime(timeNames)
                    self.table.setHidden(false)
                    self.reloadTable()
                } else {
                    self.alertLabel.setHidden(false)
                }
            }
        }
        }) { (error) -> Void in
            print("We got an error from our watch device:" + error.domain)
    }

添加到元组功能:

func reloadTable() {
    self.table.setNumberOfRows(medicines.count, withRowType: "tableRowController")
    var rowIndex = 0
    for item in medicines {
        if let row = self.table.rowControllerAtIndex(rowIndex) as? tableRowController {
            row.medicineLabel.setText(item.0)
            if let quantity = item.1, time = item.2 {
                row.amountLabel.setText(quantity)
                row.timeLabel.setText(time)

            }
            rowIndex++
        }
    }
}

func addMedicines(medicineNames: [String]) {
    for name in medicineNames {
        medicines.append((name, nil, nil))

    }
}

func addQuantities(quantities: [String]) {
    guard medicines.count == quantities.count else { return }
    for i in 0..<medicines.count {
        medicines[i].1 = quantities[i]
    }
}

func addTime(timeNames: [String]) {
    guard medicines.count == timeNames.count else { return }
    for i in 0..<medicines.count {

        medicines[i].2 = timeNames[i]
    }
}

1 个答案:

答案 0 :(得分:1)

声明var后,不再需要输入提示。

self.medicines = []

我试图想出几种方法来克服你的问题,但你的代码非常不灵活,需要重构。

您处于元组效用的极限,需要将医学转化为支持Equatable的类或结构(使用结构)。

此外,您需要创建一个新对象数组,这些对象可以合并到现有self.medicines中,直接在self.medicines中构建新对象是非常有限的。

这是元组作为结构

struct Medicine: Equatable {
    let name: String
    let amount: String
    let time: String
}

func == (lhs: Medicine, rhs: Medicine) -> Bool {
    return lhs.name == rhs.name && lhs.amount == rhs.amount && lhs.time == rhs.time
}

这是添加新值而不删除旧值或重复

if let names = meds["medicines"], amounts = meds["amount"], times = meds["time"]
    where names.count == amounts.count && names.count == times.count
{
    for i in 0..<names.count {
        let medicine = Medicine(name: names[i], amount: amounts[i], time: times[i])

        if !medicines.contains(medicine) {
            medicines.append(medicine)
        }
    }
}