简体   繁体   中英

How to find minimum value in an array using ternary operator in swift

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.

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

获得最小值 SWIFT 3

array.min()

You can do this by sorting the array:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM