Swift 3通过upTo和通过
它们分别是非包容性的、包容性的
func前缀(upTo: Int) 返回从集合开始到指定位置(但不包括)的子序列。
。
func前缀(直通: Int) 从集合的开始到指定位置的返回子序列。
另一方面,它有来自的
函数后缀(从: Int) 从指定的位置返回子序列到集合的末尾。
这似乎是包容性的
远端那个不包括在内的电话是什么?
// sum the numbers before, and after, an index i...
let lo = A.prefix(upTo: i).reduce(0,+) // means noninclusive
let hi = A.suffix(from: i+1).reduce(0,+) // 'from' seems to mean inclusive我不知道什么电话?从+1开始写很糟糕。
发布于 2016-10-30 11:26:02
目前stdlib中还没有用于Collection类型的非包含Collection方法,但是对于这个用例,您可以很容易地通过将suffix(from:)与dropFirst(_:) ( imho,它比from: idx+1更好地显示意图)来实现自己的方法。
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方法的主题相比,拆分和计算的另一种方法是为Collection类型使用 methods之一:
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版本更冗长,而且在语义上也不足以显示代码的意图。
https://stackoverflow.com/questions/40312252
复制相似问题