首先我创建了一个自定义类:
class TVInfo {
var cast : [String]
var name : String
var charecterName : String
init (cast: [String], name: String, charecterName: String){
self.cast = cast
self.name = name
self.charecterName = charecterName
}
}
然后我尝试解析 JSON 数据
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as!
NSDictionary
let cast = jsonResult.objectForKey("cast") as! NSArray
for item in cast
{
let name = item["name"] as! String
let charecterName = item["character_name"] as! String
}
let TV = TVInfo(cast: cast as! [String], name: cast[0].name, charecterName: cast[0].charecterName)
但我不断收到错误“‘AnyObject’类型的值没有成员‘charecterName’”。这很奇怪,因为第一个常量“name”似乎具有值,但它与“characterName”位于同一数组中。如何正确地为characterName常量赋值?
最佳答案
您正在从 item
中提取 name
并从 jsonResult
中提取 character_name
,但您尝试忽略结果通过点符号访问属性失败。
我猜你想实现这样的目标
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as!
NSDictionary
var infoArray = [TVInfo]()
let cast = jsonResult.objectForKey("cast") as! [[String:String]]
for item in cast {
let name = item["name"]!
let charecterName = item["character_name"]!
let TV = TVInfo(cast: cast, name: name, charecterName: charecterName)
infoArray.append(TV)
}
关于arrays - "Value of type ' AnyObject ' has no member."..尝试在 Swift 中为数组中的对象赋值时发生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33134098/