ありSTDLIBでCollection
タイプのためには非包括的suffix
方法は現在ありませんが、このユースケースのために、あなたは容易にdropFirst(_:)
(これは、from: idx+1
より私見、優れた番組の意図)とsuffix(from:)
を組み合わせることにより、独自のものを実装することができ、例えば
/* 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)
の主題を残す:あなたの例に適用
extension Collection where SubSequence == SubSequence.SubSequence {
public func suffix(after start: Index) -> SubSequence {
return suffix(from: start).dropFirst(1)
}
}
(別々にパーティショニングも含めない)のインデックスを与えられた分割数の前後数を合計(または)非包括的なsuffix
メソッドでは、分割合計計算の別のアプローチは、the split(...)
methodsタイプのCollection
タイプのいずれかを使用することです。
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
バージョンはもう少し冗長であり、コードの意図を示す意味的に貧弱だと思います。
非標準的な署名はSwift標準ライブラリリファレンスにはなく、接尾辞(_ :)と接尾辞(from:)の両方の参照は包括的な例を示しているので、このバージョンでは利用できません。私はまた、非包括的な接尾辞を参照する議論を見ていないので、すぐに利用可能になる可能性は低いです。 – gelliott181
ああ - 華麗な情報。決定的な答え、@ gelliott181として貼り付けるべきでしょうか? – Fattie
私は一過性の素早いユーザーですので、通常は@dfriと同じように詳細を伝える人に実際の答えを残したいと考えています。 – gelliott181