在自定义对象数组中查找项目并更改值 - Swift [英] Find an item and change value in custom object array - Swift

查看:40
本文介绍了在自定义对象数组中查找项目并更改值 - 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

这怎么可能?

推荐答案

由于您使用的是,请使用过滤器并首先找到值:

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? 的返回值时,您编辑了基础值.如果您使用的是 struct

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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