[英]Swift NSArray subscript a value of type AnyObject
This my my NSArray 这是我的NSArray
var RidesData:NSArray = []
It is used to store an JSON Array i have converted 它用于存储我已转换的JSON数组
RidesData = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as! NSArray
Sample of the Array 数组样本
Optional((
{
ContentType = USSShow;
Name = "Lake Hollywood Spectacular\U00ae (Seasonal Show)";
NextShowTime = "8:00pm";
NextTimeSlot = "";
QueueTime = "";
TimeSlot = "";
},
I am trying to get the Name value using this code 我试图使用此代码获取Name值
let RideName = RidesData[indexPath.section]["Data"][indexPath.row]["Name"]
cell.textLabel!.text = RideName
However i am getting this error 但是我收到了这个错误
Cannot subscript a value of type 'AnyObject?!' with an index type of 'int'
From what i have searched, i believe that i am unable to subscript because it is an optional but when i tried to unwrap it with !
从我搜索到的,我相信我无法下标,因为它是一个可选的,但当我试图解开它!
it gives me this error 它给了我这个错误
Operand of postfix "!" should have optional type; type is 'NSArray'
How can i solve this problem? 我怎么解决这个问题?
Try: 尝试:
let RideName = RidesData[indexPath.section]["Data"]??[indexPath.row]?["Name"] as? String
Since RidesData[indexPath.section]["Data"]
is AnyObject?!
由于RidesData[indexPath.section]["Data"]
是AnyObject?!
you have to unwrap it twice . 你必须打开两次 。
Why AnyObject?!
为何选择AnyObject?!
? ? Because RidesData[indexPath.section]
is AnyObject
, and AnyObject
may or may not have subscript
. 因为RidesData[indexPath.section]
是AnyObject
, AnyObject
可能有也可能没有subscript
。 So, the first ?
那么,第一个?
means, "If it has subscript
", and the second means "If subscript
returns non nil
". 装置“如果它有subscript
”,和第二装置“如果subscript
返回非nil
”。
Replace this line 替换此行
let RideName = RidesData[indexPath.section]["Data"][indexPath.row]["Name"]
with this 有了这个
let RideName = RidesData[indexPath.section]["Data"][indexPath.row]["Name"] as! String
The problem is with the cast , the array RidesData
is an optional array: [AnyObject]?.
问题在于 RidesData
,数组RidesData
是一个可选数组: [AnyObject]?.
So you must write it like this:- 所以你必须这样写: -
let RideName = RidesData[indexPath.section]["Data"][indexPath.row]["Name"] as! String
RidesData[indexPath.section]["Data"]
is of type AnyObject?!
RidesData[indexPath.section]["Data"]
的类型是AnyObject?!
and then you try to access the indexPath.row
element. 然后您尝试访问indexPath.row
元素。 You need to first unwrap this part. 你需要先解开这个部分。
Try this: 尝试这个:
let RideName = RidesData[indexPath.section]["Data"]?[indexPath.row]["Name"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.