目前没有非包容性的suffix
方法用于Collection
stdlib 中的类型,但对于此用例,您可以通过组合轻松实现自己的类型suffix(from:)
with dropFirst(_:)
(恕我直言,这比from: idx+1
), e.g.
extension Collection where SubSequence == SubSequence.SubSequence {
public func suffix(after start: Index) -> SubSequence {
return suffix(from: start).dropFirst(1)
}
}
应用于您的示例(分别对给定分区号(或索引)之前和之后的数字求和,不包括分区号):
/* in this example, invalid indices will yield a full-array sum into
lo or hi, depending on high or low index out of bounds, respectively */
func splitSum(of arr: [Int], at: Int) -> (Int, Int) {
guard at < arr.count else { return (arr.reduce(0, +), 0) }
guard at >= 0 else { return (0, arr.reduce(0, +)) }
let lo = arr.prefix(upTo: at).reduce(0, +)
let hi = arr.suffix(after: at).reduce(0, +)
return (lo, hi)
}
// example usage
let arr = [Int](repeating: 1, count: 10)
print(splitSum(of: arr, at: 4)) // (4, 5)
留下非包容性的主题suffix
方法,分割总和计算的另一种方法是使用以下之一the split(...) methods https://developer.apple.com/reference/swift/collection/2297966-split for Collection
types:
func splitSum(of arr: [Int], at: Int) -> (Int, Int) {
guard at < arr.count else { return (arr.reduce(0, +), 0) }
guard at >= 0 else { return (0, arr.reduce(0, +)) }
let sums = arr.enumerated()
.split (omittingEmptySubsequences: false) { $0.0 == at }
.map { $0.reduce(0) { $0 + $1.1 } }
guard let lo = sums.first, let hi = sums.last else { fatalError() }
return (lo, hi)
}
// example: same as above
我相信split
然而,版本有点冗长,并且在语义上也不太能显示代码的意图。