Syed Ariff
Syed Ariff

Reputation: 732

How to convert NSArray to Set?

Most of the posts here are on about how to convert a set into an array.But I would like to know if I could convert an array to a set.I have downloaded my array from parse and want to convert it to a set because I want the user to edit their details and the form builder I used needs to accept a set data type only. This is what I got.The "Subjects" field is an NSArray in Parse.

let subjects = Set(currentuser?.objectForKey("Subjects"))

Upvotes: 0

Views: 563

Answers (1)

vadian
vadian

Reputation: 285079

Basically the syntax is correct, but the compiler (and me too) doesn't know that the object for key Subjects is supposed to be an array. Use optional binding to check at least for an array of NSObject to conform to the requirement that the items in the array are hashable (thanks to dan for pointing that out):

if let userSubjects = currentuser?.objectForKey("Subjects") as? [NSObject] {
    let subjects = Set(userSubjects)
}

If the real type of Subjects is more specific than [NSObject] use that instead

Upvotes: 3

Related Questions