Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How we can get the Element from Set in Swift 2.2

Tags:

ios

swift

set

This is my object FTContent

class FTContent: NSManagedObject { 
    @NSManaged var content_id: String // Primary key
    @NSManaged var title: String
}

in my class i have an Set which hold FTContent element

var mySet: Set<FTContent>

After some operation mySet contains 5 element of FTContent

Now i want element(FTContent) from mySet How can get the Element from Set?

like image 636
jignesh Vadadoriya Avatar asked Jan 05 '23 21:01

jignesh Vadadoriya


1 Answers

A Set is a Collection and you can simply iterate over its elements:

for elem in mySet {
    print(elem)
}

or access by subscripting:

for idx in mySet.indices {
    let elem = mySet[idx]
    print(elem)
}

But note that the order of elements in a set is unspecified (and can change if elements are inserted or deleted). So you might want to sort it into an array, for example:

// Swift 2.2:
let allElements = mySet.sort({ $0.content_id < $1.content_id })

// Swift 3:
let allElements = mySet.sorted(by: { $0.content_id < $1.content_id } )
like image 108
Martin R Avatar answered Jan 13 '23 14:01

Martin R