简体   繁体   English

如何快速使用三元运算符在数组中查找最小值

[英]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. 这是我尝试过的代码,我想要数组中的最小值,如果我使用if..else我可以做,但找不到使用三元运算符。

You can use ternary operator this way. 您可以通过这种方式使用ternary operator

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

But in Swift instead of that simplest option is to use min() . 但是在Swift中,最简单的选择是使用min()

print(array.min())

获得最小值 SWIFT 3

array.min()

You can do this by sorting the array: 您可以通过对数组进行排序来做到这一点:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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