你不告诉我们班级的items
对象。我想这是一个数组。如果没有,请告诉我们。
正如Artem在他的回答中指出的那样,removeAtIndex接受一个整数索引并删除该索引处的对象。索引必须在0到array.count-1
之间
对于Swift数组对象没有removeObject(:)
方法,因为数组可以在多个索引处包含相同的条目。您可以使用NSArray方法indexOfObject(:)
来查找对象的第一个实例的索引,然后使用removeAtIndex。
如果您使用斯威夫特2,你可以使用indexOf(:)方法,传递一个封闭检测相同的对象:
//First look for first occurrence of the button in the array.
//Use === to match the same object, since UIButton is not comparable
let indexOfButton = items.indexOf{$0 === sender}
//Use optional binding to unwrap the optional indexOfButton
if let indexOfButton = indexOfButton
{
items.removeAtIndex(indexOfButton)
}
else
{
print("The button was not in the array 'items'.");
}
(我还是习惯阅读斯威夫特功能定义包括可选项和参考协议(如Generator),因此上述语法可能不完美。)
在'removeAtIndex'中,您必须指定要删除的项目的索引。对于'sender'你可以通过'items.indexOf(sender)'找到索引。 – MirekE
@斯巴达克,请在将它们发送到stackoverflow之前自己阅读崩溃描述。 –