LoginSignup
0
2

More than 5 years have passed since last update.

swift4で宇宙船演算子を実装してufo気分を味わう

Posted at

ソート処理を書いていたんですが、複雑なソートになると記述が非常にめんどくさくって。
rubyやphpにある宇宙船演算子が欲しいんですが……swiftにはない!
ないけれども、新しく実装することは出来る。ならやるしかない:thumbsup:

この記事でも参考があるんですが、swift4になると動かなくなるので。

実装例!

ufo.swift
infix operator <=>: UfoPrecedence

precedencegroup UfoPrecedence {
    associativity: left
}

public func <=> <T: Comparable>(lhs: T, rhs: T) -> Int {
    if (lhs == rhs) {
        return 0
    }

    return lhs > rhs ? 1 : -1
}

実行結果:cow2:

cattle_mutilation.swift
0 <=> 1 // -1
1 <=> 1 //  0
2 <=> 1 //  1

これで楽々ソート処理に!

0
2
0

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
0
2