danu danu -3 years ago 135
Swift Question

Remove duplicate values in a tuple array

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download