﻿ 迅速 – 是否有可能缩短对更高级别功能的评估？ - 代码日志

#### 迅速 – 是否有可能缩短对更高级别功能的评估？

``````func firstAbove100(a:[Int]) -> Int? {
if a.count < 2 {
return nil
}
for i in 0..<a.count-1 {
if a[i]+a[i+1] > 100 {
return i
}
}
return nil
}
``````

``````func firstAbove100(a:[Int]) -> Int? {
if a.count < 2 {
return nil
}
return (0..<a.count-1).reduce(nil) { prev, i in
prev ?? (a[i]+a[i+1] > 100 ? i : nil)
}
}
``````

``````func firstAbove100(_ a:[Int]) -> Int? {
guard a.count > 1 else {return nil}

return (0..<a.count-1).first { i in
a[i]+a[i+1] > 100
}
}
``````

``````extension SequenceType {

func find<T>(@noescape predicate: (Self.Generator.Element) throws -> T?) rethrows -> T? {
for element in self {
if let c = try predicate(element) {return c}
}
return nil
}
}
``````

``````func firstAbove100(a:[Int]) -> Int? {
if a.count < 2 {
return nil
}
return (0..<a.count-1).find { i in
a[i]+a[i+1] > 100 ? i : nil
}
}
``````

``````func sumOfFirstAbove100(a:[Int]) -> Int? {
guard a.count > 1 else {return nil}
return (0..<a.count-1).find { i in
let sum = a[i]+a[i+1]
return sum > 100 ? sum : nil
}
}
``````
``````let a = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(sumOfFirstAbove100(a)) // prints: Optional(110)
``````

find函数将遍历数组,将谓词应用于每个元素(在本例中为数组的索引).如果谓词返回nil,那么它将继续迭代.如果谓词返回非nil,那么它将返回该结果并停止迭代.