如何解决"类型Any没有下标成员"错误?

时间:2016-09-19 07:42:49

标签: ios swift

我已经在swift 2.3中编写了代码,同时转换为swift 3我得到的错误就像"类型Any没有下标成员"

let userDetail:Any = (GJCommon.sharedInstance.getUserInfo() as? NSDictionary)!

    print(userDetail)

    let userImage = (userDetail["Vehicle"]["bike_photo"] as? String)!

在这一行中,我收到错误"让userImage =(userDetail [" Vehicle"] [" bike_photo"]为?String)!"请帮忙。

2 个答案:

答案 0 :(得分:1)

试试这个:

if let userDetail = GJCommon.sharedInstance.getUserInfo() as? [String:AnyObject] {

    print(userDetail)

    let userImage = (userDetail["Vehicle"]["bike_photo"] as? String)!
}

答案 1 :(得分:1)

您正尝试将userDetail作为NSDictionary访问,但它的类型为Any。

正如#Mr.UB所说(打败我),将第一行更改为:

let userDetail = (GJCommon.sharedInstance.getUserInfo() as? NSDictionary)!

然后它应该编译,尽管代码的其他部分可能会反对。更多背景将是有用的。

然而你的使用!强行解开这个,后来的结果是一个坏主意。使用条件展开可以更优雅地捕获错误,并避免定期崩溃的应用程序。