練習 — Protocol — Comparable, Equatable
Protocol — Comparable
用來比較自定struct/class兩者大小Protocol
Apple的介紹:
“Swift provides a protocol named Comparable, that allows you to define how to sort objects using the <, <=, >, or >= operators.
Comparable has two requirements: It requires that the type also adopt the Equatable protocol, and it requires the type to implement the < operator, which returns a Bool for whether the left-hand value is less than the right-hand value”
Excerpt From
Develop in Swift Data Collections
Apple Education
https://books.apple.com/hk/book/develop-in-swift-data-collections/id1581183203?l=en
This material may be protected by copyright.
Test:
當中Static func < 定義了struct Hero如何比較大小。
直接 return x < y 是個精簡寫法,
拆開來,比較好理解的寫法是:
Protocol — Equatable
用來比較自定struct/class兩者是否相等的Protocol
Test - when equal:
Test — when non-equal:
Swift 4.1 開始,如果只是一些簡單的比較,可以直接不定義 ==
但在複雜的情況下還是要自己定義
留給自己的未來擴展閱讀