我目前有两个不同阵列的问题:
1) 在我的Xcode项目中,我有一个包含用于tableView的用户的数组。每个用户都是名为users的类的一部分:
class Users {
let userObjectID : String
let profilePhoto : UIImage
let fullname : String
let username : String
init(userObjectID : String, profilePhoto : UIImage, fullname : String, username : String) {
self.userObjectID = userObjectID
self.profilePhoto = profilePhoto
self.fullname = fullname
self.username = username
}
}
当我查找一个对象时,1个用户可能有两次相同的对象,因此它会将该用户两次附加到该数组,当该数组被放入tableView时,用户会显示两次。如何根据userObjectID取出重复的用户?我相信在获取数据后我将不得不对其进行排序,但我不知道该怎么做。
2) 第二个问题是在将其加载到tableView之前,按日期排序另一个包含类的数组。这是我的班级:
class Object {
var id: String?
var date: Date? //want to use for tableView order
var owner : String?
var ownerFullname : String?
var ownerProfilePic : UIImage?
var name: String?
}
我想按每个'对象'中的'日期'对数组进行排序,但我不知道该怎么做。
非常感谢对这两个问题或其中一个问题的任何指导。提前谢谢。
答案 0 :(得分:1)
创建和使用此功能:
func removeDuplicates(_ array: [User]) -> [User] {
var result: User = []
for user in users {
if result.contains(user) == false {
result.append(user)
}
}
return result
}
2.为了对你可以做的数组进行排序:
array.sort {
$0.date.compare($1.date) == .orderedDescending // it depends the order you want to use
}
答案 1 :(得分:0)
class Users : Hashable, Equatable {
let userObjectID : String
let fullname : String
var date: Date
let username : String
var hashValue: Int { get{
return Int(self.userObjectID)!
}
}
init(_ userObjectID : String, fullname : String, date:Date, username : String) {
self.userObjectID = userObjectID
self.fullname = fullname
self.date = date
self.username = username
}
static func ==(lhs: Users, rhs: Users) -> Bool {
return lhs.userObjectID == rhs.userObjectID
}
}
let u1 = Users("1", fullname: "ssd", date: Date(), username: "3232")
let u2 = Users("2", fullname: "ssd", date: Date().addingTimeInterval(10), username: "3232")
let u3 = Users("2", fullname: "ssd", date: Date().addingTimeInterval(10), username: "3232")
let u4 = Users("2", fullname: "ssd", date: Date().addingTimeInterval(10), username: "3232")
let u5 = Users("5", fullname: "ssd", date: Date().addingTimeInterval(10), username: "3232")
let u6 = Users("6", fullname: "ssd", date: Date().addingTimeInterval(-100), username: "3232")
let arr = [u1, u2, u3, u4,u5,u6]
let postsSet = Set(arr)
print(postsSet.map{$0.userObjectID})
//date..
let results = arr.map {$0}.sorted { (u1, u2) -> Bool in
return Calendar.current.compare(u1.date, to: u2.date, toGranularity: .second) == .orderedSame
}
print(results.map{$0.userObjectID})
答案 2 :(得分:0)
let unique = Set(allUsers)
objects.sort { $0.date.compare($1.date) == .orderedDescending }