Search code examples
swiftcastingnsobject

Cast NSObject of Strings to [String]


I'm stuck trying to cast an NSObject of strings to [String]. I'm using coreData and my transformable is an NSObject. The annoying thing is that it is not enumerable. So my usual tricks do not work. Could anyone help me out?

Thanks

{(
  dried,
  stewed
)}

This should turn into this:

[dried, stewed].

Usual downcasting does not work:

  myObject as! [String] :(

Also I noticed that sometimes the error message says it cannot downcast the NSObject and sometimes it says:

Could not cast value of type '__NSSetI' (0x10f101138) to 'NSArray' (0x10f101598).

EDIT: I found a workaround:

let mySet = myObject as! NSSet
let myArr : [String] =  mySet.map { $0 as! String } . // yay!

I first cast it to a set to make it enumerable and then I cast it to [String]

What is interesting is that this does not work:

let mySet = myObject as! NSSet 
let myArr = mySet as! [String] // nope.

Solution

  • Set and Array are not the same type, you cannot just cast them to each other.

    Ideally, you should cast the Objective-C type NSSet to Swift Set:

    let mySet = myObject as! Set<String>
    

    If iteration is your only purpose, then this is all you need.

    If you really need an array, create a new array from the set:

    let myArray = Array(mySet)