Search code examples
swifteureka-forms

Convert Optional(Set(["6", "14"])) to [String]


I am having trouble trying to convert a Set to a [String]. I am using the Eureka form and getting my values as:

let values = form.values()

which is a [String:Any].

My field is:

values["field_name"]

If I use the following, I get nil:

var incidents : [String]?

if let incidentRow = values["field_name"]! {
    incidents = incidentRow as? [String]
}

Solution

  • If you really have a Set, as the output Optional(Set(["6", "14"])) suggests, then it is not an Array (which is what [String]) is. Your test as? [String] is thus doomed to failure, and so you get nil. You cannot cast (using as) a thing of one type to a different type that it is not.

    Instead, you must coerce from Set to Array. Do it like this:

    if let theSet = values["field_name"] as? Set<String> {
        incidents = Array(theSet)
    }