【发布时间】:2018-05-10 19:13:24
【问题描述】:
Swift 数组的 index 函数根据 where 子句中的条件返回第一个元素。有没有办法在这种情况下获取最后一个元素?
例如,我想要这样的东西(我知道没有名为 lastIndex 的函数。我正在寻找这个函数或类似的函数):
let array = [1, 2, 3, 4, 5, 3, 6]
let indexOfLastElementEquals3 = array.lastIndex(where: { $0 == 3 })
print(indexOfLastElementEquals3) //5 (Optional)
【问题讨论】:
-
它是在 Swift 4.2 中添加的:github.com/apple/swift-evolution/blob/master/proposals/…。您可能需要最新的开发者快照。
-
array.index(of: 3, options: .backwards)
-
@Sh_Khan 这只是
String,不是吗? -
@Sh_Khan 在任何类/结构上都没有
index(of:options:)。也许你在想StringProtocol range(of:options:)。
标签: swift