如何从 Swift 中的数组中删除元素 [英] How to remove an element from an array in Swift

查看:231
本文介绍了如何从 Swift 中的数组中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Apple 的新语言 Swift 中取消设置/删除数组中的元素?

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

这是一些代码:

let animals = ["cats", "dogs", "chimps", "moose"]

如何从数组中删除元素animals[2]?

How could the element animals[2] be removed from the array?

推荐答案

let 关键字用于声明无法更改的常量.如果你想修改一个变量,你应该使用 var 代替,例如:

The let keyword is for declaring constants that can't be changed. If you want to modify a variable you should use var instead, e.g:

var animals = ["cats", "dogs", "chimps", "moose"]

animals.remove(at: 2)  //["cats", "dogs", "moose"]

保持原始集合不变的非变异替代方法是使用 filter 创建一个新集合,而不需要删除您想要删除的元素,例如:

A non-mutating alternative that will keep the original collection unchanged is to use filter to create a new collection without the elements you want removed, e.g:

let pets = animals.filter { $0 != "chimps" }

这篇关于如何从 Swift 中的数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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