gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 05:02:42 26 4
gpt4 key购买 nike

对于我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com