Reputation: 1375
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."
Upvotes: 1
Views: 6436
Reputation: 4909
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)
Upvotes: 6