在这一天上花了一整天。我有一系列费用填充我的tableview。用户可以从tableview中选择一行来编辑费用,其中包括姓名,金额,截止日期等。
我不希望用户能够输入重复的名称。我的意思是,我想检查他们对数组的输入,以确保名称不存在。这对我来说听起来很简单,但由于某种原因,我无法让它发挥作用。
这是我尝试过的:
代码#1:
var duplicateCount = 0
for item in Expense.expensesArray.filter({ $0.ownerName == currentUserName }).filter({ $0.category == expense?.category }) {
if item.expenseName != expense?.expenseName {
print("no duplicates found in \(item.expenseName). moving on")
} else if item.expenseName == expense?.expenseName {
duplicateCount += 1
print("duplicate found in \(item.expenseName)")
}
}
代码#2:(与#1非常相似)
var duplicatesAmount: Int = 0
for expense in Expense.expensesArray.filter({ return $0.ownerName == currentUserName }).filter({ $0.category == expense?.category }) {
if expense.expenseName.lowercased() == expenseNameTextField.text?.lowercased() {
duplicatesAmount += 1
print("POTENTIAL DUPLICATE #\(duplicatesAmount): ",expense.expenseName)
}
}
// if there is more than one expense in the array with the same name, return true
if duplicatesAmount > 1 {
return true
} else {
return false
}
编辑:代码运行是否有重复。它永远不会看到重复,即使我故意把它放进去。
更新:这有效。
if expense?.expenseName == expenseNameTextField.text {
updateExpenseInfo()
} else {
// iterate over the array and see if new name is found anywhere
let dupArray = Expense.expensesArray.filter({ $0.ownerName == currentUserName && $0.category == expense?.category && $0.expenseName == expenseNameTextField.text })
if dupArray.isEmpty {
updateExpenseInfo()
} else {
duplicateNameAlert()
}
}
答案 0 :(得分:2)
你可以这样做:
struct Object {
let name: String
let amount: Int
init(name: String = "", amount: Int = 0) {
self.name = name
self.amount = amount
}
}
let a = Object(name: "Foo", amount: 10)
let b = Object(name: "Bar", amount: 20)
let array = [a, b]
func contains(value: String) -> Bool {
return array.filter({ $0.name == value }).isEmpty
}
print(contains(value: "Foo")) // true
print(contains(value: "Test")) // false
所以你基本上只需添加contains
函数并返回array.filter({ $0.name == value }).isEmpty
。如果它返回true则保存否则不保存。您传递输入值的值。