首页 > 解决方案 > 如何根据我们自己的逻辑实现 swift Dictionary

问题描述

我正在尝试实现 swift 字典的实际实现。我想知道如何忽略输出代码中的数组变量。这也正是字典的实际实现是什么?

struct Box<U,V> where U: Hashable {

    var que: U
    var ans:V

    fileprivate var boxes = [Box]()

    init(_ que: U,ans: V) {
        self.que = que
        self.ans = ans
    }

    mutating func addBox(with que: U, ans: V) {
        boxes.append(Box(que, ans: ans))
    }

    mutating func deleteBox(_ que: U) {
        for (index, value) in boxes.enumerated() {
            if value.que == que {
                boxes.remove(at: index)
            }
        }
    }
}

class Display {

    func show() {
        var dict = Box(1, ans: "One")
        print(dict)
    }
}

let obj = Display()
obj.show()

//输出: Box(que: 1, ans: "One", boxes: [] )

标签: iosswiftdictionarygeneric-programminggeneric-collections

解决方案


我想知道如何忽略输出代码中的数组变量框

使 Box 符合 CustomStringConvertible 并提供您自己的description实现。

这也正是字典的实际实现是什么?

不。


推荐阅读