Swift - 在具有多个变量的自定义类数组中查找最高值



我想在我的数组中找到最高值。我在Apple文档中找到了方法.max()。

let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
let greatestHeight = heights.max()
print(greatestHeight)
// Prints "Optional(67.5)"

我的数组具有自定义数据类型。数据类型包含整数类型的两个变量。如何从其中一个变量中找到最大值?

这是我的课。

class Example: Codable {
// Variables
var value1: Int
var value2: Int
// Init
init(_value1: Int, _value2: Int) {
value1 = _value1
value2 = _value2
}    

}

正如您在评论中澄清的那样:

我想找出该数组中所有对象的 value1 的最高值

这可以通过将每个对象映射到其value1然后确定 最大值:

let maxValue1 = examples.map { $0.value1 }.max()

如果给定的数组真的很大,那么它可能是有利的 使用"惰性变体"来避免创建中间数组:

let maxValue1 = examples.lazy.map { $0.value1 }.max()

您可以通过遵守Comparable协议并实现func <来做到这一点(在这种情况下,我比较了 2 个值的总和)

struct Example: Codable, Comparable {
static func < (lhs: Example, rhs: Example) -> Bool {
return lhs.sum < rhs.sum
}
// Variables
var value1: Int
var value2: Int
// Init
init(_value1: Int, _value2: Int) {
value1 = _value1
value2 = _value2
}
var sum: Int {
return value1 + value2
}
}

let array = [Example(_value1: 1, _value2: 4), Example(_value1: 2, _value2: 3)]
print(array.max())
//Example(_value1: 1, _value2: 4)

好吧,Class实例不是Array,因此您无法访问Arrayfunctions但是您可以使用内部的自定义func来获取更大的值。

像这样的东西是一种选择。

class Example: Codable {
// Variables
var value1: Int
var value2: Int
// Init
init(_value1: Int, _value2: Int) {
value1 = _value1
value2 = _value2
}
func max() -> Int {
if value1 > value2 {
return value1
}
return value2
}
}
// USAGE
var example = Example(_value1: 10, _value2: 20)
example.max()

更新:正如OP指出的那样,他只需要比较第一个值。 编辑@Ashley答案,这将解决它

因为.max()将返回包含最高Value1object

struct Example: Codable, Comparable {
static func < (lhs: Example, rhs: Example) -> Bool {
return lhs.value1 < rhs.value1
}
// Variables
var value1: Int
var value2: Int
// Init
init(_ value1: Int, _ value2: Int) {
self.value1 = value1
self.value2 = value2
}
}

let array2 = [Example(1, 4), Example(2,3)]
print(array2.max()?.value1)

最新更新