gpt4 book ai didi

arrays - FirstIndex :of: in an array of objects

转载 作者:行者123 更新时间:2023-11-28 09:39:08 25 4
gpt4 key购买 nike

我有这门课:

class ValueTimestamp {
let value: Double
let timestamp : Double
init(value:Double, timestamp:Double) {
self.value = value
self.timestamp = timestamp
}
}

然后我有一个这个类的对象数组。

现在我想扫描那个数组并找到具有最小值的 ValueTimestamp 类的对象。

假设数组有3个元素

  1. element1(值 = 12,时间戳 = 2)
  2. element2(值 = 5,时间戳 = 3)
  3. element3(值 = 10,时间戳 = 4)

let myArray = [element1, element2, element3]

现在我想找到具有最小值的元素。

我认为这会起作用

let min = myArray.map({$0.value}).min()
let minIndex = myArray.firstIndex(of: min)

但是第二行给了我这个错误

Incorrect argument label in call (have 'of:', expected 'where:')

有什么想法吗?

最佳答案

firstIndex:of: 查找第一个等于提供的参数的元素。但是您不是在寻找一个等于它的元素,而是在寻找一个 value 属性相等的元素。因此,您需要使用 where 并为此提供一个函数:

let minIndex = myArray.firstIndex(where: {$0.value == min})

你也可以让你的类符合 Comparable 并直接调用 min :

class ValueTimestamp: Comparable {
let value: Double
let timestamp : Double
init(value:Double, timestamp:Double) {
self.value = value
self.timestamp = timestamp
}

static func == (lhs: ValueTimestamp, rhs: ValueTimestamp) -> Bool {
return lhs.value == rhs.value
}
static func < (lhs: ValueTimestamp, rhs: ValueTimestamp) -> Bool {
return lhs.value < rhs.value
}
}

let minObject = myArray.min()

请注意,如果可能有两个对象具有相同的 value,您可能需要调整函数以确定在这种情况下哪个对象“较小”。

关于arrays - FirstIndex :of: in an array of objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55072463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com