實例方法
partition(by:)
對集合的元素重新排序,使得與給定謂詞匹配的所有元素都在所有不匹配的元素之後。
聲明
mutating func partition(by belongsInSecondPartition: (Self.Element) throws -> Bool) rethrows -> Self.Index
當
Self 符合 BidirectionalCollection 時可用。返回值
重新排序的集合中與 belongsInSecondPartition 匹配的第一個元素的索引。如果集合中沒有元素匹配 belongsInSecondPartition ,則返回的索引等於集合的 endIndex 。
參數
belongsInSecondPartition用於對集合進行分區的謂詞。所有滿足這個謂詞的元素都排在所有不滿足它的元素之後。
詳述
對集合進行分區後,有一個樞軸索引 p ,其中 p 之前的任何元素都不滿足 belongsInSecondPartition 謂詞,而 p 或之後的每個元素都滿足 belongsInSecondPartition 。此操作不能保證穩定,因此分區內元素的相對順序可能會發生變化。
在以下示例中,數字數組由匹配大於 30 的元素的謂詞進行分區。
var numbers = [30, 40, 20, 30, 30, 60, 10]
let p = numbers.partition(by: { $0 > 30 })
// p == 5
// numbers == [30, 10, 20, 30, 30, 60, 40]
numbers 數組現在排列在兩個分區中。第一個分區 numbers[..<p] 由不大於 30 的元素組成。第二個分區 numbers[p...] 由 are 大於 30 的元素組成。
let first = numbers[..<p]
// first == [30, 10, 20, 30, 30]
let second = numbers[p...]
// second == [60, 40]
請注意,兩個分區中元素的順序發生了變化。也就是說,40 在原始集合中出現在 60 之前,但是在調用 partition(by:) 之後,60 出現在 40 之前。
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相關用法
- Swift UnsafeMutableBufferPointer prefix(through:)用法及代碼示例
- Swift UnsafeMutableBufferPointer prefix(upTo:)用法及代碼示例
- Swift UnsafeMutableBufferPointer prefix(_:)用法及代碼示例
- Swift UnsafeMutableBufferPointer allocate(capacity:)用法及代碼示例
- Swift UnsafeMutableBufferPointer map(_:)用法及代碼示例
- Swift UnsafeMutableBufferPointer filter(_:)用法及代碼示例
- Swift UnsafeMutableBufferPointer elementsEqual(_:)用法及代碼示例
- Swift UnsafeMutableBufferPointer reduce(into:_:)用法及代碼示例
- Swift UnsafeMutableBufferPointer min(by:)用法及代碼示例
- Swift UnsafeMutableBufferPointer indices用法及代碼示例
- Swift UnsafeMutableBufferPointer enumerated()用法及代碼示例
- Swift UnsafeMutableBufferPointer shuffled()用法及代碼示例
- Swift UnsafeMutableBufferPointer shuffle(using:)用法及代碼示例
- Swift UnsafeMutableBufferPointer contains(_:)用法及代碼示例
- Swift UnsafeMutableBufferPointer compactMap(_:)用法及代碼示例
- Swift UnsafeMutableBufferPointer split(maxSplits:omittingEmptySubsequences:whereSeparator:)用法及代碼示例
- Swift UnsafeMutableBufferPointer firstIndex(where:)用法及代碼示例
- Swift UnsafeMutableBufferPointer isEmpty用法及代碼示例
- Swift UnsafeMutableBufferPointer init(rebasing:)用法及代碼示例
- Swift UnsafeMutableBufferPointer reversed()用法及代碼示例
- Swift UnsafeMutableBufferPointer firstIndex(of:)用法及代碼示例
- Swift UnsafeMutableBufferPointer max()用法及代碼示例
- Swift UnsafeMutableBufferPointer index(_:offsetBy:limitedBy:)用法及代碼示例
- Swift UnsafeMutableBufferPointer flatMap(_:)用法及代碼示例
- Swift UnsafeMutableBufferPointer forEach(_:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 UnsafeMutableBufferPointer partition(by:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
