Skip to content

Instantly share code, notes, and snippets.

@sahara-ooga
Last active March 4, 2018 10:19
Show Gist options
  • Save sahara-ooga/fe26c53c46551f33a84661cf7a192549 to your computer and use it in GitHub Desktop.
Save sahara-ooga/fe26c53c46551f33a84661cf7a192549 to your computer and use it in GitHub Desktop.
Repositoryパターンの調査

Array とソート

SwiftのArrayのソート関連について調査。

Apple Documentation

一覧表

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:)

Reference

sort(by:) - Array | Apple Developer Documentation

Declaration

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なのに注意。

sort()

Reference

Declaration

特徴

sorted()

Reference

Declaration

特徴

reverse()

Reference

Declaration

特徴

partition(by:)

Reference

partition(by:) - Array | Apple Developer Documentation

Declaration

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