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

时间:2015-01-10 11:34:27

标签: arrays swift

假设我有一个包含Usr个对象的数组。 Usr对象具有属性age。除了逐个阅读Usr对象,并逐个比较age值之外,是否有任何快捷方式可以执行此操作? THX。

7 个答案:

答案 0 :(得分:25)

您可以简单地将用户数组映射到用户年龄数组和查找最大年龄:

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

答案 1 :(得分:11)

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

答案 2 :(得分:6)

斯威夫特3:

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

// max = 25

答案 3 :(得分:1)

其他方式:

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

答案 4 :(得分:0)

Swift 3中的另一种方式:

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

答案 5 :(得分:0)

使用 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

答案 6 :(得分:0)

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)