Search code examples
arraysswiftparse-platformnsarrayeureka-forms

How to convert native Swift sets to NSArrays?


I have built a form(https://github.com/xmartlabs/Eureka) in my app and one of the input will obtain an Optional Set type. However,I need to push this set as an array to Parse for every user.But the array field in Parse only accepts NSArray as a valid data type.How do I convert it to an NSArray? I have already referred to this post (Convert native swift Set into array) but it does not seem to work in my case. Here's my code :

let user = PFUser()

print(form.rowByTag("Subjects")?.baseValue)

if let subjects = form.rowByTag("Subjects")?.baseValue
{
    let arr = Array(arrayLiteral: subjects)
    user["Subjects"] = arr as! AnyObject
}
else
{
    print("There is no subjects chosen")
}

The Subjects field is an array field in Parse. The result of the print statement and the error: enter image description here

enter image description here


Solution

  • The issue is that your objects inside the array are unwrapped optionals.

    But you can't use Array(arrayLiteral: ) because it would just create an array containing the set itself, not an array of the elements in the set.

    We are going to use flatMap instead, to safely unwrap the contents.

    if let subjects = form.rowByTag("Subjects")?.baseValue as? Set<String> {
        let arr = subjects.flatMap { $0 }
        user["Subjects"] = arr as! AnyObject
    
    }
    

    Of course, if it's possible, it would be better to address the source of the issue and have the optionals safely unwrapped earlier in the code flow, that way you would be able to use Array(subjects) as usual.