在数组中查找具有属性的对象 [英] Find Object with Property in Array

查看:468
本文介绍了在数组中查找具有属性的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能从具有特定属性的数组中获取对象?或者我是否需要循环遍历我的数组中的所有对象并检查属性是否是我正在寻找的特定属性?

is there a possibility to get an object from an array with an specific property? Or do i need to loop trough all objects in my array and check if an property is the specific i was looking for?

编辑:感谢您给我正确的方向,但我有一个问题要转换它。

edit: Thanks for given me into the correct direction, but i have a problem to convert this.

//再次编辑:好的,如果只有一个特定的结果?这也是一种可行的方法吗?

// edit again: A ok, and if there is only one specific result? Is this also a possible method do to that?

let imageUUID = sender.imageUUID


let questionImageObjects = self.formImages[currentSelectedQuestion.qIndex] as [Images]!

    // this is working
    //var imageObject:Images!
    /*
    for (index, image) in enumerate(questionImageObjects) {

        if(image.imageUUID == imageUUID) {
            imageObject = image
        }

    }
    */

// this is not working - NSArray is not a subtype of Images- so what if there is only 1 possible result?
var imageObject = questionImageObjects.filter( { return $0.imageUUID == imageUUID } )


推荐答案


//这不起作用 - NSArray不是Images的子类型 - 那么如果只有1个可能的结果怎么办?

// this is not working - NSArray is not a subtype of Images- so what if there is only 1 possible result?

您无法在编译时证明阵列上只有一个可能的结果。您实际要求的是第一个匹配结果。最简单的(虽然不是最快)只是取过滤结果的第一个元素:

You have no way to prove at compile-time that there is only one possible result on an array. What you're actually asking for is the first matching result. The easiest (though not the fastest) is to just take the first element of the result of filter:

let imageObject = questionImageObjects.filter{ $0.imageUUID == imageUUID }.first

imageObject 现在将是一个可选项,因为它可能没有任何匹配。

imageObject will now be an optional of course, since it's possible that nothing matches.

如果搜索整个数组非常耗时,当然你可以轻松创建一个 firstMatching 函数将返回与闭包匹配的(可选)第一个元素,但对于短数组,这很简单。

If searching the whole array is time consuming, of course you can easily create a firstMatching function that will return the (optional) first element matching the closure, but for short arrays this is fine and simple.

正如查尔斯所说,在Swift 3中,这是内置的:

As charles notes, in Swift 3 this is built in:

questionImageObjects.first(where: { $0.imageUUID == imageUUID })

这篇关于在数组中查找具有属性的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆