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

How to find the max value in a Swift object array?

假设我有一个包含 Usr 个对象的数组。 Usr 对象具有属性 age。除了一个一个读取Usr对象,一个一个比较age的值,有什么捷径吗?谢谢

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

class Usr {
    var age: Int

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

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

let maxAge = maxElement(users.map{[=10=].age}) // 8

其他方式:

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

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

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

Swift3 中的另一种方式:

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

Swift 3:

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

// max = 25

使用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: {[=10=].age < .age}){
    print(userWithMaxAge.age)
}

它将打印 8

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)
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