ios 在自定义对象数组中查找项目并更改值 - Swift

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

Find an item and change value in custom object array - Swift

iosarraysswift

提问by Utku Dalmaz

I have this class

我有这堂课

class InboxInterests {

    var title = ""
    var eventID = 0
    var count = ""
    var added = 0

    init(title : String, eventID : NSInteger, count: String, added : NSInteger) {
        self.title = title
        self.eventID = eventID
        self.count = count
        self.added = added

    }
}

And i use it like this

我像这样使用它

var array: [InboxInterests] = [InboxInterests]()

Add item

新增项目

let post = InboxInterests(title: "test",eventID : 1, count: "test", added: 0)
self.array.append(post)

I want to find the index by eventIDkey and change the value of addedkey in the same index

我想eventID按键查找索引并更改added同一索引中键的值

How is that possible?

这怎么可能?

回答by Jenel Ejercito Myers

For me, the above answer did not work. So, what I did was first find the index of the object that I want to replace then using the index replace it with the new value

对我来说,上面的答案不起作用。所以,我所做的是首先找到要替换的对象的索引,然后使用索引将其替换为新值

if let row = self.upcoming.index(where: {
if let row = self.upcoming.firstIndex(where: {
array.filter({
array.first({
array.first(where: { 
class Book {
    let id: Int
    var title = "default"

    init (id: Int) {
        self.id = id
    }
}
var arrayBook = [Book]()
arrayBook.append(Book(id: 0))
arrayBook.append(Book(id:1))
arrayBook.forEach { book in
    print(book.title)
}

arrayBook.filter{ 
struct Book {
    let id: Int
    var title = "default"

    init (id: Int) {
        self.id = id
    }
}
var arrayBook = [Book]()
arrayBook.append(Book(id: 0))
arrayBook.append(Book(id:1))
arrayBook.forEach { book in
    print(book.title)
}

arrayBook = arrayBook.map{
    var mutableBook = ##代码##
    if ##代码##.id == 1 {
        mutableBook.title = "modified"
    }
    return mutableBook
}

arrayBook.forEach { book in
    print(book.title)
}
.id == 1 }.first?.title = "modified" arrayBook.forEach { book in print(book.title) }
.eventID == id })?.added = value array.filter {##代码##.eventID == id}.first?.added = value
.eventID == id})?.added = value
.eventID == id}).first?.added = value
.eventID == id}) { array[row] = newValue }
.eventID == id}) { array[row] = newValue }

In Swift 5.0:

Swift 5.0 中:

##代码##

回答by Luke

Since you are using a class, use filter and first to find the value:

由于您使用的是class,请使用 filter 并首先找到该值:

##代码##

In this you:

在这方面你:

  1. filter the array down to elements that match the event ID
  2. pick the first result, if any
  3. then set the value
  1. 将数组过滤为与事件 ID 匹配的元素
  2. 选择第一个结果,如果有的话
  3. 然后设置值

This works since classes are pass by reference. When you edit the return value from array.filter({$0.eventID == id}).first?, you edit the underlying value. You'll need to see the answers below if you are using a struct

这是有效的,因为类是通过引用传递的。当您编辑来自 的返回值时array.filter({$0.eventID == id}).first?,您编辑了基础值。如果您使用结构体,则需要查看下面的答案

EDIT: In Swift 3 you can save yourself a couple of characters

编辑:在 Swift 3 中,您可以为自己节省几个字符

##代码##

EDIT: Swift 4.2:

编辑:斯威夫特 4.2:

##代码##

回答by Pablo Sanchez Gomez

The filter operator is not the best in this case, it works for some of you because classes are passed by reference.

在这种情况下,过滤器运算符并不是最好的,它适用于你们中的一些人,因为类是通过引用传递的。

Explanation: (You can copy the following code in a playground if you want to verify it).

说明:(如果想验证可以在playground复制以下代码)。

##代码##

Arrays are copied by value not reference, so when you are using filter you are creating a new array (different than the initial), but when you modify the new one, the initial one gets modified too because both are pointing to the same class (classed are passed by reference), so after the filter your array will have changed and the new one gets deallocated. So in this case it will print "default", "default"and then "default, "modified".

数组是按值而不是引用复制的,因此当您使用过滤器时,您正在创建一个新数组(与初始数组不同),但是当您修改新数组时,初始数组也会被修改,因为两者都指向同一个类( classed 通过引用传递),因此在过滤器之后,您的数组将发生更改,并且新的数组将被释放。所以在这种情况下,它会打印 " default", "default"然后是"default, "modified"

What happens if you change classfor struct, the value will be passed by value not reference so you will have 2 arrays in memory with different values, so if you go through arrayBooksagain it will print before the filter "default","default", and then "default", "default"again. Because when you are using the filter you are creating and modifying a new array that will get deallocated if you do not store it).

如果您更改classfor会发生什么struct,该值将通过值而不是引用传递,因此您将在内存中有 2 个具有不同值的数组,因此如果您arrayBooks再次通过,它将在过滤器"default","default"之前打印,然后再次“默认”,“默认”。因为当您使用过滤器时,您正在创建和修改一个新数组,如果您不存储它,它将被取消分配)。

The solution is using map, creating a new array with all the values but with the modified items or fields that we want and then replace our array with the new one. This will print "default", "default"before the map, and then "default", "modified"

解决方案是使用 map,创建一个包含所有值但具有我们想要的修改项或字段的新数组,然后用新数组替换我们的数组。这将在地图之前打印“default”、“default”,然后是“default”、“modified”

This will work with structs, classes and everything that you want :).

这将适用于结构、类和您想要的一切:)。

##代码##