我正在转换Swift 3中的代码,我收到了这个错误:
let dicArray = serviceProvicedListArray?.objectEnumerator().allObjects as? [[String:Any]]
let count = dicArray.map({ Int($0["lstActType"] as? String ?? "0")! }).first!
例外:Cannot subscript a value of type [[String:Any]] with an index of type 'String
'
请让我知道我哪里出错了,让我知道我是如何解决的。
此线路上也出现错误:
let user_id=String(((data as AnyObject).value(forKey: "UserLoginResult") as AnyObject).value(forKey: "UserID") as! Int)
Exception: Optional chain has no effect expression already produced Any?
不明白我出错的地方
错误3:
if(!((self.serviceProvided!.value(forKey: "Weekly")! as AnyObject).isKind(of: NSNull.self))){
let resultObject = self.serviceProvided!.value(forKey: "Weekly") as! NSDictionary
self.serviceProvicedListArray!.add(resultObject)
let resultObjectItems = self.serviceProvicedListArray!.value(forKey: "lstActType")
//print(resultObjectItems[0].count)
for i in 0..<resultObjectItems[0].count {
//for(var i=0; i<resultObjectItems[0].count; i += 1){
//let resultObjectItem = resultObjectItems[0][i] as! NSDictionary
let resultObjectItem = resultObjectItems[0][i] as AnyObject
self.serviceProvicedList!.add(resultObjectItem)
}
//print(self.serviceProvicedList)
self.serviceProvidedTableView.reloadData()
}
提前致谢。
答案 0 :(得分:1)
您的dicArray
是可选的,因此您需要使用?
(可选)或!
(强制)包装它,然后在其上调用地图。
let dicArray = serviceProvicedListArray?.objectEnumerator().allObjects as? [[String:Any]]
let count = dicArray?.map({ Int($0["lstActType"] as? String ?? "0")! }).first!
击球手方法是使用guard
或if let
并包裹dicArray
。
guard let dicArray = serviceProvicedListArray?.objectEnumerator().allObjects as? [[String:Any]] else {
print("Not array of dictionary")
return
}
guard let count = dicArray.map({ Int($0["lstActType"] as? String ?? "0")! }).first else {
return
}
print(count)
或者您可以在单guard let
语句中添加guard
语句,例如。
guard let dicArray = serviceProvicedListArray?.objectEnumerator().allObjects as? [[String:Any]],
let count = dicArray.map({ Int($0["lstActType"] as? String ?? "0")! }).first else {
return
}
print(count)
修改:您遇到此问题的原因是因为您可能正在使用NSDictionary
和NSArray
,如果您使用swift的原生类型,则会很容易为了获得/访问该值。您可以这样获得UserID
。
guard let dict = data as? [String:Any],
let loginDict = dict["UserLoginResult"] as? [String:Any],
let userId = loginDict["UserID"] as? Int else {
return
}
let strUserId = String(userId)
编辑:问题是您需要告诉编译器resultObjectItems
数组对象的类型,所以请尝试这种方式。
if let resultObjectItems = self.serviceProvicedListArray!.value(forKey: "lstActType") as? [[[String:Any]]] {
for i in 0..<resultObjectItems[0].count {
let resultObjectItem = resultObjectItems[0][i] as AnyObject
self.serviceProvicedList!.add(resultObjectItem)
}
}