Reputation: 623
I'm running into a very interesting error message today:
Cannot invoke 'map' with an argument list of type '(AnyObject)'
I don't even know there is an type in Swift called (AnyObject)!
the context is, I'm using a closure as a callback after an http request:
dataHandler: ((AnyObject) -> ())?,
and trying to get implement the dataHandler in this piece of code:
dataHandler: { (obj: AnyObject) -> () in ...}
at this moment, swift take "obj" as type: (Anyobject)...
Thanks for @sketchyTech's inspiring answer, ObjectMapper seems need concrete type of "AnyObject", like cast it into Array or Dictionary. Now my code works:
if let dic = res as? [String: AnyObject], res = Mapper<MappableType>().map(dic) {
...
}
Upvotes: 0
Views: 261
Reputation: 5906
When used as a concrete type, rather than a generic type, AnyObject
enables you to call any ObjC method (but of course it must be able to respond to the method at runtime to avoid crashing).
When used as a concrete type, all known
@objc
methods and properties are available, as implicitly-unwrapped-optional methods and properties respectively, on each instance ofAnyObject
. (Swift header file)
Its primary role is to help with passing objects between ObjC and the strongly-typed language of Swift.
For an instance of type AnyObject
to be used with higher order Swift functions it must first be cast to a type to which they can be applied, e.g.
dataHandler: {arr in
if let a = arr as? [Int] {
a.map{$0+1}
}}
Upvotes: 2