Sorry guys, I'm new here and I'm learning iOS developing from scratch.
I know that in order to find the largest value in an array of Int, we can use the propertie ".max()". But I need to do this using a for-in loop. Would someone please help me? I know it's so easy, but I can't find it and can't find out how to do it on my own as well. Thanks.
CodePudding user response:
Well the complexity of array.max() of Swift is O(N) just like the for-in loop.
There are two ways to for-in in Swift.
First solution (for-in here like for each value)
let arr = [1, 4, 3]
var max = Int.min
// get each value
for val in arr {
if (max < val) {
max = val
}
}
Second solution (for-in here is for each index)
let arr = [1, 4, 3]
var max = Int.min
// get each index
for i in 0..<arr.count {
if (max < arr[i]) {
max = arr[i]
}
}
Two ways have the same output. Feel free when choosing which to use in your further code.