Discussion 解説
To find the position that corresponds with this index in the original, underlying collection, use that collection’s index(before:)
method with the base
property.
オリジナル、基盤コレクションでのこのインデックスに相当する位置を見つけるには、そのコレクションのindex(before:)
メソッドをbase
プロパティとともに使ってください。
The following example declares a function that returns the index of the last even number in the passed array, if one is found. First, the function finds the position of the last even number as a Reversed
in a reversed view of the array of numbers. Next, the function calls the array’s index(before:)
method to return the correct position in the passed array.
以下の例は、ある関数を宣言します、それは渡された配列の中の最後の偶数のインデックスを返します、それが見つけられるならば。最初に、この関数は最後の偶数の位置を、数からなる配列の逆にされたビューにおけるReversed
として捜します。次に、関数は配列のindex(before:)
メソッドを呼び出すことで渡された配列での正しい位置を返します。
func indexOfLastEven(_ numbers: [Int]) -> Int? {
let reversedNumbers = numbers.reversed()
guard let i = reversedNumbers.firstIndex(where: { $0 % 2 == 0 })
else { return nil }
return numbers.index(before: i.base)
}
let numbers = [10, 20, 13, 19, 30, 52, 17, 40, 51]
if let lastEven = indexOfLastEven(numbers) {
print("Last even number: \(numbers[lastEven])")
}
// Prints "Last even number: 40"