ios 如何快速遍历对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30596021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 06:10:42  来源:igfitidea点击:

How to loop through an array of objects in swift

iosarraysswift

提问by Kali Aney

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.

我正在尝试访问存储在数组中的对象的 url,但无论我使用什么方法,我都会遇到错误。

let userPhotos = currentUser?.photos

    for var i = 0; i < userPhotos!.count ; ++i {
        let url = userPhotos[i].url
    }

Here I get

在这里我得到

Could not find member 'url'

找不到成员“网址”

and with a foreach:

并使用 foreach:

for photo in userPhotos {

        Utils.getImageAsync(photo.url , completion: { (img: UIImage?) -> () in

        })
    }

I get:

我得到:

'[ModelAttachment]?' does not have a member named 'Generator'

“[模型附件]?” 没有名为“生成器”的成员

My array is var photos: Array<ModelAttachment>?and my ModelAttachment looks like this:

我的数组是var photos: Array<ModelAttachment>?,我的 ModelAttachment 看起来像这样:

class ModelAttachment :Model {
var id: String?
var url: String?
var thumb: String?
}

Any pointers to what I'm doing wrong would be great :)

任何指向我做错了什么的指针都会很棒:)

回答by Eric Aya

Unwrap and downcast the objects to the right type, safely, with if let, before doing the iteration with a simple for inloop.

if let在使用简单for in循环进行迭代之前,使用 安全地展开对象并将其向下转换为正确的类型。

if let currentUser = currentUser, 
    let photos = currentUser.photos as? [ModelAttachment] 
{
    for object in photos {
        let url = object.url
    }
}

There's also guard let elseinstead of if letif you prefer having the result available in scope:

如果您更喜欢在范围内提供结果guard let elseif 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
}

回答by Sergei Petunin

Your userPhotosarray is option-typed, you should retrieve the actual underlying object with !(if you want an error in case the object isn't there) or ?(if you want to receive nilin url):

您的userPhotos数组是选项类型的,您应该检索实际的底层对象!(如果您希望在对象不存在的情况下出错)或?(如果您想nil在 url 中接收):

let userPhotos = currentUser?.photos

for var i = 0; i < userPhotos!.count ; ++i {
    let url = userPhotos![i].url
}

But to preserve safe nil handling, you better use functional approach, for instance, with map, like this:

但是为了保持安全的 nil 处理,您最好使用函数式方法,例如, with map,如下所示:

let urls = userPhotos?.map{ 
class ModelAttachment {
    var id: String?
    var url: String?
    var thumb: String?
}

var modelAttachementObj = ModelAttachment()
modelAttachementObj.id = "1"
modelAttachementObj.url = "http://www.google.com"
modelAttachementObj.thumb = "thumb"

var imgs: Array<ModelAttachment> = [modelAttachementObj]

for img in imgs  {
    let url = img.url
    NSLog(url!)
}
.url }

回答by gskspurs

You can try using the simple NSArray insyntax for iterating over the array in swift which makes for shorter code. The following is working for me:

您可以尝试语法中使用简单的 NSArray来迭代 swift 中的数组,从而缩短代码。以下对我有用:

for var i = 0; i < userPhotos!.count ; ++i {
    let url = userPhotos![i].url
}

See docs here

在此处查看文档

回答by giorashc

The photosproperty is an optionalarray and must be unwrapped before accessing its elements (the same as you do to get the countproperty of the array):

photos属性是一个可选数组,必须在访问其元素之前展开(与获取count数组属性的操作相同):

##代码##