如何在swift中循环遍历一个对象数组 [英] How to loop through an array of objects in swift
问题描述
我正在尝试访问存储在数组中的对象的url,但是我收到的错误无论我使用的是什么方法。
I'm trying to access the url of an object stored in an array, but I'm getting errors no matters what methods I'm using.
let userPhotos = currentUser?.photos
for var i = 0; i < userPhotos!.count ; ++i {
let url = userPhotos[i].url
}
我在这里
找不到会员'url'
Could not find member 'url'
并使用foreach:
and with a foreach:
for photo in userPhotos {
Utils.getImageAsync(photo.url , completion: { (img: UIImage?) -> () in
})
}
我得到:
'[ModelAttachment]?'没有名为'Generator'的成员
'[ModelAttachment]?' does not have a member named 'Generator'
我的数组是 var photos:Array< ModelAttachment>?
和我的ModelAttachment看起来像这样:
My array is var photos: Array<ModelAttachment>?
and my ModelAttachment looks like this:
class ModelAttachment :Model {
var id: String?
var url: String?
var thumb: String?
}
任何关于我做错的指示都会很棒:)
Any pointers to what I'm doing wrong would be great :)
推荐答案
如果让安全地将对象打包并向下传播到正确的类型>,在用循环中的简单进行迭代之前。
Unwrap and downcast the objects to the right type, safely, with if let
, before doing the iteration with a simple for in
loop.
if let currentUser = currentUser,
let photos = currentUser.photos as? [ModelAttachment]
{
for object in photos {
let url = object.url
}
}
如果让后卫让其他人而不是 >如果您希望结果在范围内可用:
There's also guard let else
instead of if let
if you prefer having the result available in scope:
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
}
这篇关于如何在swift中循环遍历一个对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!