Avatar
let num = 10 let other = 12 // 🤔 網羅的に書けないし、くどいし、ロジックに不安がある if num < other { print("small") } else if num > other { print("great") } else { print("same") } こういう「<, ==, > それぞれのケースを網羅的に処理する」コードってどうやって書いてますか? import Foundation // 代替案1 extension Comparable { func comparisonResult(with other: Self) -> ComparisonResult { if self < other { return .orderedAscending } if self > other { return .orderedDescending } return .orderedSame } } // 🤔 網羅的なのはいいけど、非直感的… // asc, desc のどっちがどっちなのかいつも思考が止まる[IMO] switch num.comparisonResult(with: other) { case .orderedAscending: print("small") case .orderedSame: print("same") case .orderedDescending: print("great") } // 代替案2 // 新しいenumが欲しい enum Comparison { case greater, same, smaller } extension Comparable { func comparison(with other: Self) -> Comparison { if self < other { return .smaller } if self > other { return .greater } return .same } } // 👍 網羅的!直感的! switch num.comparison(with: other) { case .smaller: print("small") case .same: print("same") case .greater: print("great") } #swift-contrib に持っていきたいやつかなと思ったけど、 (ちゃんと読んでないですが)突き詰めるとComparableの設計そのものの話になってめんどくさそう…? https://forums.swift.org/t/proposal-formalized-ordering-take-2/3540 https://forums.swift.org/t/pitch-comparison-reform/5662/6 (edited)
Since we're running short on time, and the previous discussion thread diverged, here's my attempt to fix the Comparable protocol. Pull request: https://github.com/apple/swift-evolution/pull/464 TL;DR: 1. Equatable remains unchanged, while Comparable bloats a bit to support...
Getting this sorted out is definitely a worthwhile effort. I do have thoughts about this proposal: I continue to have reservations about an identical spelling (e.g. ==) giving two different answers with the same values of the same type, depending on the generic context....