我正在尝试访问存储在数组中的对象的 url,但无论我使用什么方法,我都会遇到错误。
let userPhotos = currentUser?.photos
for var i = 0; i < userPhotos!.count ; ++i {
let url = userPhotos[i].url
}
我来了
Could not find member 'url'
还有一个foreach:
for photo in userPhotos {
Utils.getImageAsync(photo.url , completion: { (img: UIImage?) -> () in
})
}
我得到:
'[ModelAttachment]?' does not have a member named 'Generator'
我的数组是 var photos: Array<ModelAttachment>?
我的 ModelAttachment 看起来像这样:
class ModelAttachment :Model {
var id: String?
var url: String?
var thumb: String?
}
任何指向我做错了什么的指针都会很棒 :)
最佳答案
在使用简单的 for in
循环进行迭代之前,使用 if let
安全地将对象解包并向下转型为正确的类型。
if let currentUser = currentUser,
let photos = currentUser.photos as? [ModelAttachment]
{
for object in photos {
let url = object.url
}
}
如果您希望结果在范围内可用,还有 guard let else
而不是 if let
:
guard let currentUser = currentUser,
let photos = currentUser.photos as? [ModelAttachment] else
{
// break or return
}
// now 'photos' is available outside the guard
for object in photos {
let url = object.url
}
关于ios - 如何快速循环遍历一组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30596021/