代码基于 swift 4.0
- 按值查找。
var indexOfX = 0
let arrayOne = [2, 1, 0, 5, 6]
indexOfX = arrayOne.firstIndex(of: 6) ?? 0 // 4
- 按条件查找
if let indexOfX = arrayOne.firstIndex(where: { (element) -> Bool in
element == 0
}) {
print(indexOfX) // 2
}
indexOfX = arrayOne.firstIndex(where: {$0 == 5}) ?? 0
print(indexOfX) // 3