28
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SwiftでRubyの宇宙船演算子を実装した

Last updated at Posted at 2015-08-31

宇宙船演算子 <=>

「<=>」は、その形状から「宇宙船演算子」と呼ばれる演算子で、「左辺 < 右辺」であれば-1を、「左辺 > 右辺」であれば1を、等しければ0を返す演算子です。

100 <=> 500 # -1
100 <=> 100 # 0
500 <=> 100 # 1

例えば、sort処理に使う1
JunkBox~主に個人的防備録~: RubyのUFO演算子を利用したソート処理について

swiftは演算子のオーバーライド、カスタム演算子を簡単に記述できるので、宇宙船演算子を実装してみた。

Operators.swift
infix operator <=> { associativity left }

public func <=> <T: Comparable>(lhs: T, rhs: T) -> Int {
    switch (lhs, rhs) {
    case let (l, r) where l < r:
        return -1
    case let (l, r) where l > r:
        return 1
    default: 
        return 0
    }
}
OperatorsTests.swift
func testSpacshipOperator() {
    XCTAssertEqual(1 <=> 2, -1)
    XCTAssertEqual(1 <=> 1, 0)
    XCTAssertEqual(2 <=> 1, 1)
}
  1. Rubyのarray.sort関数は、要素の順番比較として<=>演算子が使われています sort, sort! (Array) - Rubyリファレンス

28
27
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?