19

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.

2

9 Answers 9

41
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
Sign up to request clarification or add additional context in comments.

1 Comment

@toing_toing Why? map alone returns an array of elements with a given transformation applied to them. max(by:) finds the maximum element in the sequence with a given predicate.
25

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

4 Comments

Please note the new syntax for Swift 3: let maxAge = users.map { $0.age }.maxElement()
Use max() instead of maxElement() in Swift 3.
Isn't max() for comparing 2 values as in: let x = max(2, 4)? The compiler will only accept arrayOfInts.maxElement().
In Swift 3 you must use arrayOfInts.max() in Swift 2 arrayOfInts.maxElement(). max() is variadic for 2 or more values.
23

Swift 3:

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

// max = 25

Comments

7

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

Comments

6

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.

Comments

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

Comments

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)

Comments

-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

2 Comments

Your answer could be improved by adding more information on what the code does and how it helps the OP.
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
-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 Comment

Avoid code only answer and provide an explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.