这是我的代码:
if let photosData = parsedResult as? NSDictionary {
var arrayOfPhotos = photosData.valueForKey("data")!
// i want to do something like let photo = arrayOfPhotos.random
}
其中photosData是
"data" =
(
{
"id"= 1234;
"name" = "Sam";
},
{
"id"= 4567;
"name" = "John";
},
{
"id"= 1234;
"name" = "Tony";
}
)
现在我留下了arrayOfPhotos,它取了" data"
的值问题:
如何访问arrayOfPhotos中的随机对象?
当我有一个变量,xcode没有立即告诉我其类型,我该如何获得该类型?
如何在调试时记录变量,对象?我只是使用打印吗?
EDIT2:因为问题写得不好而重编辑。
解决:
我添加了#34;作为? [AnyObject]"到arrayOfPhotos宣言
if let photosData = parsedResult as? NSDictionary {
var arrayOfPhotos = photosData.valueForKey("data")! as? [AnyObject]
// i want to do something like let photo = arrayOfPhotos.random
}
现在我可以通过arrayOfPhotos.first抓住一个对象或抓住一个索引
答案 0 :(得分:1)
arrayOfPhotos
将是NSArray
,其中包含NSDictionary
的有序集合。 NSArray
是一个固有的有序集合,它由一个整数索引,因为你按照它们放入它们的顺序从它们中获取东西。与NSDictionary
相反,if let photosData = parsedResult as? NSDictionary {
if let arrayOfPhotos = photosData.valueForKey as? [[String:AnyObject]] {
// At this point, arrayOfPhotos is an array of dictionaries, so we use direct int indexing:
let firstPhoto = arrayOfPhotos[0]
let nthPhoto = arrayOfPhotos[n]
// Both firstPhoto and nthPhoto now have the type [String:AnyObject], or in otherwords
// they map a String to anything, anything because "id" is an int, and "name" is a String
let firstId = firstPhoto["id"] as! Int
let firstName = firstPhoto["name"] as! String
}
}
是由(在本例中)NSString索引的无序集合。字典是无序的,因为事情不一定按照你放入它们的顺序出现,事实上,如果要迭代字典中的所有项目,则以不可预测的顺序出现。
要回答您提出的确切问题,您最好使用:
resources :photos
get "/photos/:slug/stats" => "photos#stats"
get "/photos/:slug/visitors" => "photos#visitors"