How to remove an element from an array in Swift

后端 未结 18 2161
灰色年华
灰色年华 2020-11-28 18:38

How can I unset/remove an element from an array in Apple\'s new language Swift?

Here\'s some code:

let animals = [\"cats\", \"dogs\", \"chimps\", \"m         


        
18条回答
  •  隐瞒了意图╮
    2020-11-28 19:03

    The above answers seem to presume that you know the index of the element that you want to delete.

    Often you know the reference to the object you want to delete in the array. (You iterated through your array and have found it, e.g.) In such cases it might be easier to work directly with the object reference without also having to pass its index everywhere. Hence, I suggest this solution. It uses the identity operator !==, which you use to test whether two object references both refer to the same object instance.

    func delete(element: String) {
        list = list.filter { $0 !== element }
    }
    

    Of course this doesn't just work for Strings.

提交回复
热议问题