LuidonVon
LuidonVon

Reputation: 453

Value type of "Any" has no member 'objectforKey' Swift 3 conversion

I am currently facing this problem (Value type of "Any" has no member 'objectforKey') due to swift 3 upgrade. Anybody knows why?

Here is my line of code that have the error

            let bookName:String  = (accounts[indexPath.row] as AnyObject).objectForKey("bookName") as! String

*accounts is an array.

Upvotes: 1

Views: 8412

Answers (2)

vadian
vadian

Reputation: 285072

As always, do not use NS(Mutable)Array / NS(Mutable)Dictionary in Swift. Both types lack type information and return Any which is the most unspecified type in Swift.

Declare accounts as Swift Array

var accounts = [[String:Any]]()

Then you can write

let bookName = accounts[indexPath.row]["bookName"] as! String

Another Dont: Do not annotate types that the compiler can infer.

Upvotes: 2

LuidonVon
LuidonVon

Reputation: 453

Okay basically it is the .objectForKey needs to be change as the following:

    let bookName:String  = (accounts[indexPath.row] as AnyObject).object(forKey:"bookName") as! String

Upvotes: 5

Related Questions