ios 在数组中查找对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28727845/
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 04:59:53  来源:igfitidea点击:

Find an object in array?

iosswift

提问by Sahat Yalkabov

Does Swift have something like _.findWherein Underscore.js?

Swift 在Underscore.js中有类似_.findWhere 的东西吗?

I have an array of structs of type Tand would like to check if array contains a struct object whose nameproperty is equal to Foo.

我有一个类型的结构数组,T想检查数组是否包含一个name属性等于的结构对象Foo

Tried to use find()and filter()but they only work with primitive types, e.g. Stringor Int. Throws an error about not conforming to Equitableprotocol or something like that.

尝试使用find()andfilter()但它们只适用于原始类型,例如Stringor Int。抛出关于不符合Equitable协议或类似错误的错误。

采纳答案by rintaro

FWIW, if you don't want to use custom function or extension, you can:

FWIW,如果您不想使用自定义功能或扩展,您可以:

let array = [ .... ]
if let found = find(array.map({ 
if let found = find(lazy(array).map({ 
if let found = find(lazy(array).map({ 
if array.contains(where: {
if let foo = array.first(where: {
if let foo = array.enumerated().first(where: {
if let fooOffset = array.firstIndex(where: {
func index(where predicate: (Element) throws -> Bool) rethrows -> Int?
.name == "foo"}) { // do something with fooOffset } else { // item could not be found }
.element.name == "foo"}) { // do something with foo.offset and foo.element } else { // item could not be found }
.name == "foo"}) { // do something with foo } else { // item could not be found }
.name == "foo"}) { // it exists, do something } else { //item could not be found }
.name == "Foo" }), true) { let obj = array[found] }
.name }), "Foo") { let obj = array[found] }
.name }), "Foo") { let obj = array[found] }

This generates namearray first, then findfrom it.

name首先生成数组,然后find从它生成。

If you have huge array, you might want to do:

如果你有庞大的数组,你可能想要这样做:

if let i = array.firstIndex(where: { 
if let i = array.index(where: { 
if let i = array.indexOf({ 
array.first{
extension Array {

    // Returns the first element satisfying the predicate, or `nil`
    // if there is no matching element.
    func findFirstMatching<L : BooleanType>(predicate: T -> L) -> T? {
        for item in self {
            if predicate(item) {
                return item // found
            }
        }
        return nil // not found
    }
}
.name == "Foo"}
.name == Foo }) { return array[i] }
.name == Foo }) { return array[i] }
.name == "Foo" }) { return array[i] }

or maybe:

或者可能:

struct T {
    var name : String
}

let array = [T(name: "bar"), T(name: "baz"), T(name: "foo")]

if let item = array.findFirstMatching( { 
if let item = array.first(where: { 
if let index = array.index(where: { 
for myObj in myObjList where myObj.name == "foo" {
 //object with name is foo
}
.name == "Foo" }) { return array[index] }
.name == "foo" }) { // item is the first matching array element } else { // not found }
.name == "foo" } ) { // item is the first matching array element } else { // not found }

回答by Daniel

SWIFT 5

快速 5

Check if the element exists

检查元素是否存在

for myObj in myObjList where myObj.Id > 10 {
 //objects with Id is greater than 10
}

Get the element

获取元素

if let object = elements.filter({ 
func index(where predicate: @noescape Element throws -> Bool) rethrows -> Int?
.title == "title" }).first { print("found") } else { print("not found") }

Get the element and its offset

获取元素及其偏移量

if let i = theArray.index(where: {
if yourArray.contains(item) {
   //item found, do what you want
}
else{
   //item not found 
   yourArray.append(item)
}
.name == "Foo"}) { return theArray[i] }

Get the offset

获取偏移量

let array = [T(name: "foo"), T(name: "Foo"), T(name: "FOO")]
let foundValue = array.indexOf { ##代码##.name == "Foo" }.map { array[##代码##] }
print(foundValue) // Prints "T(name: "Foo")"

回答by user3799504

You can use the indexmethod available on Arraywith a predicate (see Apple's documentation here).

您可以将index可用的方法Array与谓词一起使用(请参阅此处的 Apple 文档)。

##代码##

For your specific example this would be:

对于您的具体示例,这将是:

Swift 5.0

斯威夫特 5.0

##代码##

Swift 3.0

斯威夫特 3.0

##代码##

Swift 2.0

斯威夫特 2.0

##代码##

回答by Brett

Swift 3

斯威夫特 3

If you need the object use:

如果您需要对象使用:

##代码##

(If you have more than one object named "Foo" then firstwill return the first object from an unspecified ordering)

(如果您有多个名为“Foo”first的对象,则将从未指定的顺序返回第一个对象)

回答by Martin R

You can filterthe array and then just pick the first element, as shown in Find Object with Property in Array.

您可以过滤数组,然后只选择第一个元素,如Find Object with Property in Array 所示

Or you define a custom extension

或者你定义一个自定义扩展

##代码##

Usage example:

用法示例:

##代码##

In Swift 3you can use the existing first(where:)method (as mentioned in a comment):

Swift 3 中,您可以使用现有first(where:)方法(如评论中所述):

##代码##

回答by Muhammad Saifullah

Swift 3.0

斯威夫特 3.0

##代码##

Swift 2.1

斯威夫特 2.1

Filtering in object properties is now supported in swift 2.1. You can filter your array based on any value of the struct or class here is an example

swift 2.1 现在支持在对象属性中过滤。您可以根据结构或类的任何值过滤数组,这里是一个示例

##代码##

OR

或者

##代码##

回答by Pramod More

Swift 4,

斯威夫特 4,

Another way to achieve this using filter function,

使用过滤器功能实现此目的的另一种方法,

##代码##

回答by Deokhyun Ko

Swift 3

斯威夫特 3

you can use index(where:) in Swift 3

你可以在 Swift 3 中使用 index(where:)

##代码##

example

例子

##代码##

回答by yonlau

Swift 3

斯威夫特 3

##代码##

回答by Yoichi Tagaya

Swift 2 or later

Swift 2 或更高版本

You can combine indexOfand mapto write a "find element" function in a single line.

您可以在一行中组合indexOfmap编写“查找元素”函数。

##代码##

Using filter+ firstlooks cleaner, but filterevaluates all the elements in the array. indexOf+ maplooks complicated, but the evaluation stops when the first match in the array is found. Both the approaches have pros and cons.

使用filter+first看起来更干净,但会filter评估数组中的所有元素。indexOf+map看起来很复杂,但是当找到数组中的第一个匹配项时,评估就会停止。这两种方法各有利弊。