0
let array = [2,3,5,7,3,1,8,9,0,2,4,1]
var minvalue = array[0]
for values in array {
  values < minvalue ? minvalue = values : minvalue
}
print(minvalue)

This is the code i tried , I want the minimum value in the array, If I use if..else I can able to do but cant find using ternary operator.

3 Answers 3

4

You can use ternary operator this way.

for values in array {
    minvalue = values < minvalue ? values : minvalue
}

But in Swift instead of that simplest option is to use min().

print(array.min())
Sign up to request clarification or add additional context in comments.

Comments

0

To Get Min value SWIFT 3

array.min()

1 Comment

Hi, I would like to know how to find through looping and ternary operator.
0

You can do this by sorting the array:

let sortedArray = array.sorted()
var minvalue = sortedArray[0]

3 Comments

Technically correct, but inefficient way to solve the problem.
why? would you please inform me?
Sorts find not only the smallest value, but also determine the second smallest value, the third smallest, etc. It's a lot more work than is required if you only need to know what the minimum value was. Even good sort algorithms are, say, O(n log n) complexity. The min function is a trivial scan through the results, with O(n) time and O(1) memory.

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.