0

I have a function is that takes a dictionary, and I need to parse the information inside.

I can get an NSArray out of the dictionary, but shouldn't I be able to access a native swift array?

class func parseResults(resultsDict:Dictionary<String, AnyObject>) -> Array<Track>? {

        var results : NSArray = resultsDict["results"] as NSArray // This works
        //var results : Array = resultsDict["results"] as Array<AnyObject> // This doesnt work

        ...
    }

3 Answers 3

1

A native Swift array is implemented as a struct so it isn't an AnyObject. If you have your dictionary contain <String, Any> instead, it should work since Array does conform to Any.

Sign up to request clarification or add additional context in comments.

Comments

0

Array is struct, which is not object so it you can't convert it from AnyObject

On the other hand, NSArray is class, so you can convert it from AnyObject.

3 Comments

I see, thanks. If I am using NSJSONSerialization class to get an NSArray or NSDictionary should i continue parsing its contents using the foundation classes or their swift native equivalents? In other words, should I just change the resultsDict to be of type NSDictionary?
NSJSONSerialization is Foundation class, I suggest keep use Foundation classes with it to avoid unnecessary bridging. Dictionary<String, AnyObject> doesn't give you more type-safety anyway.
Sorry but this is incorrect, NSArray can be seamlessly bridged to Array class. Read my answer and developer.apple.com/library/prerelease/ios/documentation/Swift/…
0

You could wrap the array in a class and that will solve your problem

class WrappedArray<T> {
    var array = Array<T>()
}
var dict = Dictionary<Int, WrappedArray<Int>>()
dict[0] = WrappedArray<Int>()
dict[0].array.append(0)
dict[0].array.append(1)
...

You could also implement array methods in the wrapper class and forward them to the array

class WrappedArray<T> {
    var array = Array<T>()

    func append(_ newElement:T) {
        self.array.append(newObject)
    }
}

Then you can use it like a regular array.

dict[0].append(0)

instead of

dict[0].array.append(0)

Comments