實例方法
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 UnsafeMutableRawBufferPointer prefix(_:)用法及代碼示例
- Swift UnsafeMutableRawBufferPointer prefix(upTo:)用法及代碼示例
- Swift UnsafeMutableRawBufferPointer prefix(through:)用法及代碼示例
- Swift UnsafeMutableRawBufferPointer shuffle()用法及代碼示例
- Swift UnsafeMutableRawBufferPointer compactMap(_:)用法及代碼示例
- Swift UnsafeMutableRawBufferPointer contains(where:)用法及代碼示例
- Swift UnsafeMutableRawBufferPointer allSatisfy(_:)用法及代碼示例
- Swift UnsafeMutableRawBufferPointer map(_:)用法及代碼示例
- Swift UnsafeMutableRawBufferPointer starts(with:)用法及代碼示例
- Swift UnsafeMutableRawBufferPointer isEmpty用法及代碼示例
- Swift UnsafeMutableRawBufferPointer sorted()用法及代碼示例
- Swift UnsafeMutableRawBufferPointer indices用法及代碼示例
- Swift UnsafeMutableRawBufferPointer randomElement(using:)用法及代碼示例
- Swift UnsafeMutableRawBufferPointer reduce(_:_:)用法及代碼示例
- Swift UnsafeMutableRawBufferPointer split(maxSplits:omittingEmptySubsequences:whereSeparator:)用法及代碼示例
- Swift UnsafeMutableRawBufferPointer sort(by:)用法及代碼示例
- Swift UnsafeMutableRawBufferPointer lexicographicallyPrecedes(_:)用法及代碼示例
- Swift UnsafeMutableRawBufferPointer forEach(_:)用法及代碼示例
- Swift UnsafeMutableRawBufferPointer suffix(from:)用法及代碼示例
- Swift UnsafeMutableRawBufferPointer first用法及代碼示例
- Swift UnsafeMutableRawBufferPointer flatMap(_:)用法及代碼示例
- Swift UnsafeMutableRawBufferPointer firstIndex(where:)用法及代碼示例
- Swift UnsafeMutableRawBufferPointer reversed()用法及代碼示例
- Swift UnsafeMutableRawBufferPointer min()用法及代碼示例
- Swift UnsafeMutableRawBufferPointer reverse()用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 UnsafeMutableRawBufferPointer partition(by:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。