ios - 如何创建一组自定义对象 (Swift)?

标签 ios swift set equatable

对于我的 iOS 应用程序,我有一个类似的模型

class Person {
    var Id: Int
    var Name: String

    init(id: Int, name: String?) {
        self.Id = id
        self.Name = name ?? ""
    }
}

然后在我的 ViewController 中当我从服务器加载数据时,我将一些人添加到数组中

class ViewController: UIViewController {
    var people:[Person] = []

    override func viewDidLoad() {
        self.loadPeople()
    }

    func loadPeople() {
        // This data will be coming from a server request
        // so is just sample. It could have users which 
        // already exist in the people array

        self.people.append(Person(id: "1", name: "Josh"))
        self.people.append(Person(id: "2", name: "Ben"))
        self.people.append(Person(id: "3", name: "Adam"))
    }
}

我现在要做的是打开 people数组变成 Set<Person>所以它不会添加重复项。这是可能的还是我需要改变我的逻辑?

最佳答案

要创建 Person 集合,您需要使其符合 Equatable 和 Hashable 协议(protocol):

class Person: Equatable, Hashable {
    var Id: Int
    var Name: String

    init(id: Int, name: String?) {
        self.Id = id
        self.Name = name ?? ""
    }

    var hashValue: Int {
        get {
            return Id.hashValue << 15 + Name.hashValue
        }
    }
}

func ==(lhs: Person, rhs: Person) -> Bool {
    return lhs.Id == rhs.Id && lhs.Name == rhs.Name
}

然后你可以像这样使用一组人:

var set = Set<Person>()
set.insert(Person(id: 1, name: "name"))

关于ios - 如何创建一组自定义对象 (Swift)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32425886/

相关文章:

ios - 标签/按钮上的约束以显示标签的整个文本

python - 在没有重复值的 pandas 系列上使用 set 返回一个较小的对象

c# - 任何现有的 .Net 有序集?

ios - 运行时与 MPAndroidChart 的用户交互

ios - 以编程方式添加UIButton时不可单击

ios - UITextView 光标颜色不改变 iOS 7

ios - 加载的 Xib 总是在导出后立即崩溃

ios - hitTestboundingBoxOnly 不适用于 SCNPlane

ios - 长宽比限制没有改变

python - 我可以使用集合理解从更大的字典列表中创建字典列表吗?