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.
2
Answers
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)
Second solution (for-in here is for each index)
Two ways have the same output. Feel free when choosing which to use in your further code.
If your array is empty, then returning
Int.min
as the maximum value is not correct.Returning an optional is more correct:
Though you might prefer to write it as an extension to Collection, like:
Or perhaps more generally, so it’s not tied to the ‘>’ function, like: