Swift NSArray 下标一个 AnyObject 类型的值

Swift NSArray subscript a value of type AnyObject

这是我的 NSArray

var RidesData:NSArray = []

用于存放我转换过的JSON数组

RidesData = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as! NSArray

阵列样本

Optional((
    {
    ContentType = USSShow;
    Name = "Lake Hollywood Spectacular\U00ae (Seasonal Show)";
    NextShowTime = "8:00pm";
    NextTimeSlot = "";
    QueueTime = "";
    TimeSlot = "";
},

我正在尝试使用此代码获取名称值

let RideName = RidesData[indexPath.section]["Data"][indexPath.row]["Name"]
cell.textLabel!.text = RideName

但是我收到了这个错误

Cannot subscript a value of type 'AnyObject?!' with an index type of 'int'

根据我的搜索,我认为我无法下标,因为它是可选的,但是当我尝试用 ! 展开它时,它给了我这个错误

Operand of postfix "!" should have optional type; type is 'NSArray'

我该如何解决这个问题?

替换此行

let RideName = RidesData[indexPath.section]["Data"][indexPath.row]["Name"]

有了这个

let RideName = RidesData[indexPath.section]["Data"][indexPath.row]["Name"] as! String

问题在于转换,数组RidesData是一个可选数组:[AnyObject]?.

所以一定要这样写:-

let RideName = RidesData[indexPath.section]["Data"][indexPath.row]["Name"] as! String

RidesData[indexPath.section]["Data"]AnyObject?! 类型,然后您尝试访问 indexPath.row 元素。您需要先打开这部分。

试试这个:

let RideName = RidesData[indexPath.section]["Data"]?[indexPath.row]["Name"]

尝试:

let RideName = RidesData[indexPath.section]["Data"]??[indexPath.row]?["Name"] as? String

因为 RidesData[indexPath.section]["Data"]AnyObject?! 你必须将它展开 两次.

为什么 AnyObject?!?因为RidesData[indexPath.section]AnyObject,而AnyObject可能有也可能没有subscript。所以,第一个 ? 表示 "If it has subscript",第二个表示 "If subscript returns non nil".