你不告訴我們班級的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之前自己閱讀崩潰描述。 –