どうも、ちょげ(@chogetarou)です。
配列(array)で最も大きい値のインデックスを取得する方法を紹介します。
方法

配列(array)で最大値のインデックスを取得するには、index()とmax()を使います。
まず、配列からindex()を呼び出します。
index()の引数「of」に、配列から呼び出したmax()の戻り値をアンラップした結果を指定します。
//arr=対象の配列, default=max()がnilを返した時のデフォルト値
let result = arr.index(of: arr.max() ?? default)
上記のindex()は、呼び出した配列の最大値のインデックスをOptional型で返します。

index(of:) | Apple Developer Documentation
Returns the first index where the specified value appears in the collection.

max() | Apple Developer Documentation
Returns the maximum element in the sequence.
使用例
import Foundation
var nums = [4, 2, 10, 8, 5]
let result = nums.index(of: nums.max() ?? 0)
print(result)
出力:
Optional(2)
コメント