查找项目并更改自定义对象数组中的值

查找项目并更改自定义对象数组中的值

本文介绍了查找项目并更改自定义对象数组中的值-Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这堂课

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

    }
}

我这样使用它

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

添加项目

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

我想通过eventID键找到索引,并更改同一索引中added键的值

I want to find the index by eventID key and change the value of added key in the same index

那怎么可能?

推荐答案

由于您使用的是 class ,因此请使用过滤器并首先查找值:

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

array.filter({$0.eventID == id}).first?.added = value

在此您:

  1. 将数组过滤为与事件ID匹配的元素
  2. 选择第一个结果(如果有)
  3. 然后设置值

这是有效的,因为类是通过引用传递的.当您从array.filter({$0.eventID == id}).first?编辑返回值时,您将编辑基础值.如果您使用的是结构

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

在Swift 3中,您可以保存几个字符

In Swift 3 you can save yourself a couple of characters

array.first({$0.eventID == id})?.added = value

Swift 4.2:

array.first(where: { $0.eventID == id })?.added = value
array.filter {$0.eventID == id}.first?.added = value

这篇关于查找项目并更改自定义对象数组中的值-Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 14:31