如何在Swift对象数组中找到最大值?

17

假设我有一个包含Usr对象的数组。而Usr对象具有属性age。除了逐个读取Usr对象并逐个比较age值之外,是否有任何捷径可以这样做?谢谢。


也许可以使用以下代码(来自Objective-C,但是Swift也可能有等效代码)得到数组中最大age的值:[yourArray valueForKeyPath:@"@max.age"]; 详情请见:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/CollectionOperators.html。 - Larme
1
可能是在Swift中查找数组最大值的正确方法的重复问题。 - Michał Ciuba
9个回答

37
struct User {
    var age: Int
}

let users = [ User(age: 10), User(age: 20), User(age: 30)]
let oldestUser = users.max { $0.age < $1.age }
oldestUser?.age  // 30

我认为应该更正为users.map,而不是users.max - toing_toing
4
为什么?map 方法单独返回一个数组,其中包含对每个元素应用给定转换后的结果。 max(by:) 方法根据给定谓词在序列中查找最大的元素。 - Hamish
抱歉,请忽略那个注释。 - toing_toing

24
你可以将用户数组映射为用户年龄的数组,然后找到最大年龄:
class Usr {
    var age: Int

    init(_ age: Int) {
        self.age = age
    }
}

let users = [Usr(1), Usr(8), Usr(5)]

let maxAge = maxElement(users.map{$0.age}) // 8

10
请注意 Swift 3 的新语法:let maxAge = users.map { $0.age }.max() - nontomatic
5
在Swift 3中,使用max()代替maxElement()。 - Kirsteins
max() 不是用于比较两个值吗,例如:let x = max(2, 4)?编译器只会接受 arrayOfInts.maxElement()。 - nontomatic
在Swift 3中,您必须使用arrayOfInts.max()而在Swift 2中是arrayOfInts.maxElement()max()对于2个或更多值是可变参数的。 - Kirsteins

23

Swift 3:

let users = [Usr(15), Usr(25), Usr(20)]
let max = users.map { $0.age }.max()

// 最大值 = 25


6

使用 max(by:) 函数

class Usr {
   var age: Int
   init(_ age: Int) {
       self.age = age
   }
}

let users = [Usr(3), Usr(8), Usr(6)]
if let userWithMaxAge : Usr = users.max(by: {$0.age < $1.age}){
    print(userWithMaxAge.age)
}

它将打印8


5

其他方法:

class Usr {
    var age: Int
    init(_ age: Int) {
        self.age = age
    }
}

let users = [Usr(1), Usr(8), Usr(5)]
let largestAge = users.map{ $0.age }.reduce(0) { $0 > $1 ? $0 : $1 } // 8

5

之前的答案有点混乱,不能准确地描述出我将采用的方法。所以,根据您的需求,有两种不同的方法。

如果这是您的模型:

struct Purchase {
   let id: String
   let amount: Double
}

以下是您的对象:

let iPhonePurchase = Purchase(id: "iPhone", amount: 999.00)
let iPadPurchase = Purchase(id: "iPad", amount: 1299.00)
let purchases = [iPhonePurchase, iPadPurchase]

如果您想要包含最高值的对象本身,请使用以下命令:
let highestPurchase = purchases.max { $0.amount < $1.amount }

这将返回对象。

另一方面,如果您不想获取整个对象,只需获取最高金额值:

let highestPurchase = purchases.map { $0.amount }.max()

在这里,您将获得最高价值为1299.00


1
另一种在Swift 3中的方法:

let users = [Usr(1), Usr(8), Usr(5)]    
let maxAge = users.map { $0.age }.max()
print(maxAge ?? "No users") // Optional(8)

-3
let array1 = [75,37,45,80,75,24,65,97,60,83]
var smallvalue = 0
        
for countindex in 0..<array1.count {
  let index1 = array1[countindex]
            
  if countindex == 0 {
    let index2 = array1[countindex + 1]
    if index1 < index2 {
      smallvalue = index1
    } else {
      smallvalue = index2
    }
  } else {
    if smallvalue > index1 {
      smallvalue = index1
    }
  }
}
print(smallvalue) //print 24

你的回答可以通过添加更多关于代码的功能和如何帮助提问者的信息来改进。 - Tyler2P
很多错误 - 在每个循环周期中单独检查第一个元素,如果数组只有0或1个元素,应用程序将失败等。 - Gargo

-4
var studentsAndScores = ["Amy": Int(readLine()!)!, "James": Int(readLine()!)!, "Helen": Int(readLine()!)!]

func highestScore(scores: [String: Int]) {

  let a = studentsAndScores["Amy"]!
  let b = studentsAndScores["James"]!
  let c = studentsAndScores["Helen"]!

  var temp = 0

  if a > temp {
    temp =  a 
  }
  if b > temp {
    temp = b
  }
  if c > temp {
    temp = c
  }

  print(temp)
}

highestScore(scores: studentsAndScores)

1
请提供一个解释,避免只给出代码的答案。 - Itération 122442

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接