许多答案往往把重点放在删除值 - >发生变异值 - >替换值成语,但要注意去除并不是必需的。您也可以使用例如可选的链接
dict["Furniture"]?.removeAtIndex(1)
print(dict)
/* ["Furniture": ["Table", "Bed"],
"Food": ["Pancakes"]] */
不过请注意,使用.removeAtIndex(...)
解决方案并非完全安全的,除非你执行数组边界检查,确保为我们试图删除一个元素的索引确实存在。
作为一种安全就地突变替代,使用可选的绑定语句的where
子句来检查我们要删除的索引不越界
let removeElementAtIndex = 1
if let idxs = dict["Furniture"]?.indices where removeElementAtIndex < idxs.endIndex {
dict["Furniture"]?.removeAtIndex(removeElementAtIndex)
}
另一种安全的替代正在使用的advancedBy(_:limit)
得到一个安全的索引使用在removeAtIndex(...)
。
let removeElementAtIndex = 1
if let idxs = dict["Furniture"]?.indices {
dict["Furniture"]?.removeAtIndex(
idxs.startIndex.advancedBy(removeElementAtIndex, limit: idxs.endIndex))
}
最后,如果使用删除/转变/替换成语,另一个安全的替代是使用flatMap
为突变步骤,对于给定的索引中删除的元素,如果阵列中存在的索引。例如,对于一个通用的方法(和where
条款滥用:)
正是我需要的。谢谢! –
@MarkusJohansson乐意帮忙。 – dfri