1

I've just started working with Swift, and I need to convert an Array to an NSArray for the purpose of writing to a plist file. Here's my code:

func saveDataToFile() {
        var a:Array = [Any]()
    for thing in self.objects {
        var dictionary = [String:Any]()
        dictionary["name"] = thing.name
        dictionary["location"] = thing.location
        a.append(dictionary)
    }
    let arr: NSArray = a
    cocoaArray.writeToFile(filePath, atomically:true);
}

When I try to convert a into the NSArray arr, I get the error "Cannot convert value of type [Any] to specified type NSArray."

2
  • Can you show the declaration of self.objects. What exactly is it? Commented Mar 26, 2016 at 20:01
  • var objects = [AnyObject]() Commented Mar 26, 2016 at 20:46

1 Answer 1

6

You're getting Cannot convert value of type [Any] to specified type NSArray, because a is of type [Any] and you cannot bridge that to an NSArray. That's because an NSArray can only contain instances of Class-types and Any can represent an instance of any type.

If you were to declare a as [AnyObject], you'll probably be fine. But then you'll also need to change the type of the dictionary to [String:AnyObject].

Or you could use an NSMutableArray, and forego the bridging entirely:

var a = NSMutableArray()
for thing in objects {
    var dictionary = [String:AnyObject]()
    dictionary["name"] = thing.name
    dictionary["location"] = thing.location
    a.addObject(dictionary)
}
a.writeToFile(filePath, atomically: true)
Sign up to request clarification or add additional context in comments.

1 Comment

I think I'll use the NSMutableArray instead, that's much simpler, and eliminates my problem. Thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.