如何在阵列从多个匹配对象中删除单个对象 [英] How to remove single object in array from multiple matching object

查看:419
本文介绍了如何在阵列从多个匹配对象中删除单个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var testarray = NSArray() 
testarray = [1,2,2,3,4,5,3] 
print(testarray) 
testarray.removeObject(2)

我要删除多个匹配对象单一的对象像

I want to remove single object from multiple matching object like

myArray = [1,2,2,3,4,3]

当我删除

myArray.removeObject(2) 

那么这两个对象被删除。我想只删除单个对象。

then both objects are deleted. I want remove only single object.

我尝试使用扩展功能,但没有一个是正常工作。我已经使用此链接

I tried to use many extension but no one is working properly. I have already used this link.

推荐答案

解决方案使用一个简单的雨燕阵列时:

Solution when using a simple Swift array:

var myArray = [1,2,2,3,4,3]

if let index = myArray.indexOf(2) {
    myArray.removeAtIndex(index)
}

它的工作原理,因为 .indexOf 只返回的第一个的找到对象occurence,作为一个可选的(这将是如果没有找到对象)。

It works because .indexOf only returns the first occurence of the found object, as an Optional (it will be nil if object not found).

这是不同的,如果你使用的NSMutableArray:

This is different if you're using NSMutableArray:

let nsarr = NSMutableArray(array: [1,2,2,3,4,3])
let index = nsarr.indexOfObject(2)
if index < Int.max {
    nsarr.removeObjectAtIndex(index)
}

下面 .indexOfObject 将返回 Int.max 未能找到该指数在一个物体的时候,所以我们检查除去对象之前此特定错误。

Here .indexOfObject will return Int.max when failing to find an object at this index, so we check for this specific error before removing the object.

这篇关于如何在阵列从多个匹配对象中删除单个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆