17

Let say I got an array with Usr objects. And the Usr object have the attribute age. Except from reading the Usrobject one by one, and compare the age value one by one, is there any shortcuts to do so? Thx.

shim
  • 9,289
  • 12
  • 69
  • 108
DNB5brims
  • 29,344
  • 50
  • 131
  • 195
  • Maybe by using (from Objective-C, but there may be a Swift equivalent) `[yourArray valueForKeyPath:@"@max.age"];` https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/CollectionOperators.html – Larme Jan 10 '15 at 11:39
  • 1
    possible duplicate of [Correct way to find max in an Array in Swift](http://stackoverflow.com/questions/24036514/correct-way-to-find-max-in-an-array-in-swift) – Michał Ciuba Jan 10 '15 at 11:41

9 Answers9

35
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
Warif Akhand Rishi
  • 23,920
  • 8
  • 80
  • 107
24

You can simply map users array to array of user's age and the find max 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{$0.age}) // 8
Kirsteins
  • 27,065
  • 8
  • 76
  • 78
23

Swift 3:

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

// max = 25

Marcos Reboucas
  • 3,409
  • 1
  • 29
  • 35
6

Use max(by:) function

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

It will print 8

Ghulam Rasool
  • 3,996
  • 2
  • 27
  • 40
5

Other way:

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
Twitter khuong291
  • 11,328
  • 15
  • 80
  • 116
4

The previous answers are a little mixed and don't exactly describe what I will achieve with the respecting approach. So, there are two different approaches, based on what you want.

If this is your model:

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

And these are your objects:

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

If you want the object itself containing the highest value, use:

let highestPurchase = purchases.max { $0.amount < $1.amount }

This returns the object for iPadPurchase.

On the other hand, if you don't want to get the whole object, just the highest amount value:

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

Here you get 1299.00 as the highest value.

kaevinio
  • 351
  • 1
  • 7
1

Another way in Swift 3:

let users = [Usr(1), Usr(8), Usr(5)]    
let maxAge = users.map { $0.age }.max()
print(maxAge ?? "No users") // Optional(8)
ElegyD
  • 4,393
  • 3
  • 21
  • 37
-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
  • 2,324
  • 26
  • 22
  • 31
  • Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P May 31 '22 at 08:09
  • a lot of errors - separate check for a first element in each loop cycle, app will fail if you have an array with 0 or 1 element and etc – Gargo Jul 31 '23 at 07:15
-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)
Akainoto
  • 7
  • 6