Mar*_*n R 37
在Swift 2中,您可以将其作为具有功能样式编程的"单行":
let numbers = [ 1, 3, 7, 11]
let x = 6
let closest = numbers.enumerate().minElement( { abs($0.1 - x) < abs($1.1 - x)} )!
print(closest.element) // 7 = the closest element
print(closest.index) // 2 = index of the closest element
Run Code Online (Sandbox Code Playgroud)
enumerate()迭代所有数组元素以及相应的索引,并minElement()返回(index, element)关于闭包的"最小"
对.闭包将两个元素之差的绝对值进行比较x.
(这里假设数组不为空,因此minElement()
不会返回nil.)
请注意,这可能不是大型数组的最快解决方案,因为(几乎)所有数组元素的绝对差值计算两次.但对于小阵列而言,这无关紧要.
斯威夫特3:
let numbers = [ 1, 3, 7, 11]
let x = 6
let closest = numbers.enumerated().min( by: { abs($0.1 - x) < abs($1.1 - x) } )!
print(closest.element) // 7
print(closest.offset) // 2
Run Code Online (Sandbox Code Playgroud)
在雨燕1.2的版本可以在编辑历史中找到.
基于 Martin R 不久前的正确答案,这是我一直在使用的一个方便的扩展。目前使用的是 Swift 5。
extension Array where Element: (Comparable & SignedNumeric) {
func nearest(to value: Element) -> (offset: Int, element: Element)? {
self.enumerated().min(by: {
abs($0.element - value) < abs($1.element - value)
})
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
let numbers = [ 1, 3, 7, 11]
let x = 6
if let closest = numbers.nearest(to: x) {
print(closest)
}
// prints (offset: 2, element: 7)
Run Code Online (Sandbox Code Playgroud)
斯威夫特 4.2
不完全是OP所要求的,但您可以在排序数组上使用first(where:)和firstIndex(where:)array 方法来获取第一个大于x的值:
let numbers = [1, 3, 7, 11]
let x = 6
let index = numbers.firstIndex(where: { $0 >= x })!
let result = numbers.first(where: { $0 >= x })!
print(index, result) // 2 7
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7071 次 |
| 最近记录: |