實例方法
partition(by:)
對集合的元素重新排序,使得與給定謂詞匹配的所有元素都在所有不匹配的元素之後。
必需的。提供的默認實現。
聲明
mutating func partition(by belongsInSecondPartition: (Self.Element) throws -> Bool) rethrows -> Self.Index
返回值
重新排序的集合中與 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 MutableCollection subscript(_:)用法及代碼示例
- Swift MutableCollection sort(by:)用法及代碼示例
- Swift MutableCollection shuffle()用法及代碼示例
- Swift MutableCollection reverse()用法及代碼示例
- Swift MutableCollection sort()用法及代碼示例
- Swift MutableCollection shuffle(using:)用法及代碼示例
- Swift MutableCollection用法及代碼示例
- Swift Mirror description用法及代碼示例
- Swift MemoryLayout alignment(ofValue:)用法及代碼示例
- Swift MemoryLayout用法及代碼示例
- Swift Mirror.Children用法及代碼示例
- Swift Mirror.AncestorRepresentation.customized(_:)用法及代碼示例
- Swift ManagedBufferPointer用法及代碼示例
- Swift MemoryLayout stride(ofValue:)用法及代碼示例
- Swift MemoryLayout offset(of:)用法及代碼示例
- Swift Mirror descendant(_:_:)用法及代碼示例
- Swift MemoryLayout size(ofValue:)用法及代碼示例
- Swift Mirror用法及代碼示例
- Swift KeyValuePairs flatMap(_:)用法及代碼示例
- Swift String.UTF8View first用法及代碼示例
- Swift Result.Publisher zip(_:_:_:)用法及代碼示例
- Swift Optional.Publisher reduce(_:_:)用法及代碼示例
- Swift Int8 ~(_:)用法及代碼示例
- Swift SetAlgebra isStrictSubset(of:)用法及代碼示例
- Swift UInt +(_:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 MutableCollection partition(by:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。