SWIFT:"removeAtIndex" 不适用于(发件人:UIButton)

SWIFT: "removeAtIndex" don't work with (sender:UIButton)

@IBOutlet var items: [UIButton]
@IBAction func itemsHidden(sender: UIButton) {
    sender.hidden = true
    items.removeAtIndex(sender)
    }

你好

例如,我有一组项目。

代码有错误:"Cannot invoke 'removeAtIndex' with an argument list of type (UIButton)"。 我需要做什么,"removeAtIndex" 有效吗?

谢谢...

A removeAtIndex 方法需要获取索引作为参数。 如果要删除对象,请使用 func removeObject(_ anObject: AnyObject)

编辑

swift 的数组中没有 removeObject(仅在 NSMutableArray 中)。 为了删除一个元素,你需要先弄清楚它的索引:

if let index = find(items, sender) {
    items.removeAtIndex(index)
}

您没有告诉我们您的 items 对象的 class。

我假设它是一个数组。如果没有,请告诉我们。

正如 Artem 在他的回答中指出的那样,removeAtIndex 采用整数索引并删除该索引处的对象。索引必须介于零和 array.count-1

之间

Swift 数组对象没有 removeObject(:) 方法,因为数组可以在多个索引处包含相同的条目。您可以使用 NSArray 方法 indexOfObject(:) 找到对象的第一个实例的索引,然后 removeAtIndex.

如果你正在使用 Swift 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{[=10=] === 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'.");
}

(我仍然习惯于阅读 Swift 函数定义,其中包括可选项和参考协议,如 Generator,因此上述语法可能并不完美。)