-
Repository pattern in Swift // Speaker Deck
- AnyQuery
- SwiftTask
- ReactKit/SwiftTask: Promise + progress + pause + cancel + retry for Swift.
- Promise その概要 JSにPromiseが導入されたときの記事。
- ReactKit/SwiftTask: Promise + progress + pause + cancel + retry for Swift.
Last active
March 4, 2018 10:19
-
-
Save sahara-ooga/fe26c53c46551f33a84661cf7a192549 to your computer and use it in GitHub Desktop.
Repositoryパターンの調査
SwiftのArrayのソート関連について調査。
一覧表
Signature | Description |
---|---|
sort() | Sorts the collection in place. |
sorted() | Returns the elements of the collection or sequence, sorted. |
sorted(by: (Element, Element) -> Bool) | Returns the elements of the collection, sorted using the given predicate as the comparison between elements. |
reverse() | Reverses the elements of the collection in place. |
reversed() | Returns a view presenting the elements of the collection in reverse order. |
partition(by:) | Reorders the elements of the collection such that all the elements that match the given predicate are after all the elements that don’t match. |
swapAt(::) | Exchanges the values at the specified indices of the collection. |
sort(by:) - Array | Apple Developer Documentation
mutating func sort(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows
このメソッドは、ElementがComparable等に準拠していなくても使える。 言い換えると、ソートする時に条件を決める事ができる。
enum HTTPResponse {
case ok
case error(Int)
}
var responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)]
responses.sort {
switch ($0, $1) {
// Order errors by code
case let (.error(aCode), .error(bCode)):
return aCode < bCode
// All successes are equivalent, so none is before any other
case (.ok, .ok): return false
// Order errors before successes
case (.error, .ok): return true
case (.ok, .error): return false
}
}
print(responses)
// Prints "[.error(403), .error(404), .error(500), .ok, .ok]"
Comparableな場合は、比較演算子を用いて簡潔に書くことが出来る。
同じ規則で(何度も同じクロージャを渡して)ソートするようなら、その型に<
演算子を(同じクロージャを使って)定義して、Comparable
プロトコルに準拠することを検討すべき。
mutating
なのに注意。
partition(by:) - Array | Apple Developer Documentation
mutating func partition(by belongsInSecondPartition: (Element) throws -> Bool) rethrows -> Int
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]
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment