I'm working on a project in Swift 3 where I have a tuple array with duplicate values is there a way to save it to a NSSet or to avoid replicating the same value. The structure of my tuple array as follow.
var selectedSongList : [(title: String, healerName: String, trackUrl: String, trackID: String, imageUrl: String)] = []
Thus later I'm using this to poplate my UITableView
-
Take a look at this: stackoverflow.com/questions/25738817/…Hieu Dinh– Hieu Dinh2017年08月17日 04:02:10 +00:00Commented Aug 17, 2017 at 4:02
-
a code snippet would much appreciatedanu– danu2017年08月17日 04:03:01 +00:00Commented Aug 17, 2017 at 4:03
-
1make a struct that conforms to equatableLeo Dabus– Leo Dabus2017年08月17日 04:04:49 +00:00Commented Aug 17, 2017 at 4:04
-
how do you do it with the code. Can you share a code snippetdanu– danu2017年08月17日 04:07:10 +00:00Commented Aug 17, 2017 at 4:07
2 Answers 2
There are two ways to do it.
Solution 1
You can create a structure and it should confirm to Hashable and equatable some thing like this
struct Post: Hashable, Equatable {
let id: String
var hashValue: Int { get { return id.hashValue } }
}
func ==(left:Post, right:Post) -> Bool {
return left.id == right.id
}
and to remove your object you can do like this
let uniquePosts = Array(Set(posts))
Solution 2
Create a set out of your array and then make it back to array.
Comments
Edit func static func ==
in Song
struct if you have different definition about the same song
struct Song: Equatable {
var title: String?
var healerName: String?
var trackUrl:String?
var trackID:String?
var imageUrl: String?
init(_ title: String, _ healerName:String, _ trackUrl:String, _ trackID:String,_ imageUrl: String) {
self.title = title
self.healerName = healerName
self.trackUrl = trackUrl
self.trackID = trackID
self.imageUrl = imageUrl
}
static func == (lhs: Song, rhs: Song) -> Bool {
return lhs.title == rhs.title &&
lhs.healerName == rhs.healerName &&
lhs.trackUrl == rhs.trackUrl &&
lhs.trackID == rhs.trackID &&
lhs.imageUrl == rhs.imageUrl
}
}
extension Array where Element:Equatable {
func removeDuplicates() -> [Element] {
var result = [Element]()
for value in self {
if result.contains(value) == false {
result.append(value)
}
}
return result
}
}