Search code examples
swiftanyobject

Looking for a fix for Swift "ambiguous use of 'object(forKey:)'"


I've inherited some Swift code that I'm trying to compile.

The following two lines generate an "Ambiguous use of object(forKey:)" error.

let selectorString: String = (req as AnyObject).object(forKey: "selectorString") as! String
let args = (req as AnyObject).object(forKey: "arguments") as! NSArray

The error highlights req as AnyObject as the culprit.

I've found similar issues on S.O., but none seemed to address this particular issue. I may have missed something in the search results.

I'm hoping this is a simple fix, so any help is appreciated.


Solution

  • Everything depends on what req is. If it is something that can be cast as AnyObject and that responds to object(forKey:), your code compiles and runs. For example:

    let req : [String:Any] = ["selectorString":"hey", "arguments":["ho"]]
    let selectorString: String = (req as AnyObject).object(forKey: "selectorString") as! String
    let args = (req as AnyObject).object(forKey: "arguments") as! NSArray
    

    However, if req cannot be cast to AnyObject, you'll get a compile error.