2

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

Leo Dabus
237k61 gold badges512 silver badges621 bronze badges
asked Aug 17, 2017 at 3:56
4
  • Take a look at this: stackoverflow.com/questions/25738817/… Commented Aug 17, 2017 at 4:02
  • a code snippet would much appreciate Commented Aug 17, 2017 at 4:03
  • 1
    make a struct that conforms to equatable Commented Aug 17, 2017 at 4:04
  • how do you do it with the code. Can you share a code snippet Commented Aug 17, 2017 at 4:07

2 Answers 2

1

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.

answered Aug 17, 2017 at 4:29
Sign up to request clarification or add additional context in comments.

Comments

0

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
 }
}
answered Aug 17, 2017 at 4:17

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.