删除数组内部的项目,该数组是字典中的值 Swift 2

Remove item that is inside of an array which is the value in a dictionary Swift 2

我知道以前可能有人回答过这个问题,但我搜索时找不到任何东西。

所以我有一本看起来像这样的字典:

var dict = [String:[String]]()

我想做的是删除数组中的某个索引(字典的值)。假设我想从此代码中删除字符串 "Chair":

dict = ["Furniture": ["Table", "Chair", "Bed"], "Food": ["Pancakes"]]

如果已经回答,再次抱歉。

guard var furniture = dict["Furniture"] else {
    //oh shit, there was no "Furniture" key
}
furniture.removeAtIndex(1)
dict["Furniture"] = furniture

许多涵盖字典条目突变的答案往往集中在 remove value -> mutate value -> replace value 习语上,但请注意,移除不是必需的。您同样可以使用例如执行就地突变可选链接

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))
}  

最后,如果使用 remove/mutate/replace 习惯用法,另一个安全的替代方法是使用 flatMap 作为变异步骤,删除给定索引的元素,如果该索引存在于数组中。例如,对于通用方法(和 where 子句滥用 :)

func removeSubArrayElementInDict<T: Hashable, U>(inout dict: [T:[U]], forKey: T, atIndex: Int) {
    guard let value: [U] = dict[forKey] where
        { () -> Bool in dict[forKey] = value
            .enumerate().flatMap{ [=13=] != atIndex ?  : nil }
            return true }()
        else { print("Invalid key"); return }
}

/* Example usage */
var dict = [String:[String]]()
dict = ["Furniture": ["Table", "Chair", "Bed"], "Food": ["Pancakes"]]

removeSubArrayElementInDict(&dict, forKey: "Furniture", atIndex: 1)

print(dict)
    /* ["Furniture": ["Table", "Bed"], 
        "Food": ["Pancakes"]]          */

如果您想删除特定的 元素,您可以这样做:

var dict = ["Furniture": ["Table", "Chair", "Bed"], "Food": ["Pancakes"]]

extension Array where Element: Equatable {
    mutating func removeElement(element: Element) {
        if let index = indexOf ({ [=10=] == element }) {
            removeAtIndex(index)
        }
    }
}

dict["Furniture"]?.removeElement("Chair") //["Furniture": ["Table", "Bed"], "Food": ["Pancakes"]]