Reputation: 1178
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
Upvotes: 2
Views: 1389
Reputation: 770
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.
Upvotes: 1
Reputation: 722
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
}
}
Upvotes: 0