如何创建一组自定义对象(Swift)?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何创建一组自定义对象(Swift)?相关的知识,希望对你有一定的参考价值。
对于我的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"))
}
}
我现在尝试todo是将people
阵列变成Set<Person>
所以它不会添加重复。这是可能做的还是我需要改变我的逻辑?
答案
要制作一组Person
,您需要使其符合Equatable和Hashable协议:
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"))
另一答案
使用Swift 2.0,Hashable和Equitable是NSObject的一部分。您需要做的就是为感兴趣的属性覆盖“isEqual”和“var hash:”。在这种情况下:“Id”,Set将排除具有相同ID的Person对象。
class Person: NSObject {
var Id: Int
var Name: String
init(id: Int, name: String?) {
self.Id = id
self.Name = name ?? ""
}
override var hash: Int {
return Id.hashValue
}
override func isEqual(object: AnyObject?) -> Bool {
guard let rhs = object as? Person else {
return false
}
let lhs = self
return lhs.Id == rhs.Id
}
}
func mergeArrays(){
let person1 = Person(id: 1, name: "Tom")
let person2 = Person (id: 2, name: "John")
let person3 = Person(id: 3, name: "Adam")
let downloadedPeople = [person1,person2] //[{NSObject, Id 1, Name "Tom"}, {NSObject, Id 2, Name "John"}]
let peopleStoredLocally = [person1,person3] //[{NSObject, Id 1, Name "Tom"}, {NSObject, Id 3, Name "Adam"}]
let downloadedPeopleSet = Set(downloadedPeople) //{{NSObject, Id 2, Name "John"}, {NSObject, Id 1, Name "Tom"}}
let mergedSet = downloadedPeopleSet.union(peopleStoredLocally) //{{NSObject, Id 2, Name "John"}, {NSObject, Id 3, Name "Adam"}, {NSObject, Id 1, Name "Tom"}}
let mergedArray = Array(mergedSet)//[{NSObject, Id 2, Name "John"}, {NSObject, Id 3, Name "Adam"}, {NSObject, Id 1, Name "Tom"}]
}
以上是关于如何创建一组自定义对象(Swift)?的主要内容,如果未能解决你的问题,请参考以下文章
IOS swift如何在tableView单元格内创建一条小水平线
如何在 Core Data 中存储一组自定义(和重复)对象?