LoginSignup
0
1

More than 1 year has passed since last update.

Stringのenumの配列に優先順位をつけて優先度が一番高いものを取得する方法(Comparable使う)

Last updated at Posted at 2021-06-24

Comparable使えば良いよ

public enum Emoji: String, Comparable {

    case neko = "😺"
    case inu = "🐶"
    case usi = "🐮"

    var priority: Int {
        switch self {
        case .neko:
            return 0
        case .inu:
            return 1
        case .usi:
            return 2
        }
    }

    public static func <(_ lhs: Emoji, _ rhs: Emoji) -> Bool {
        return lhs.priority < rhs.priority
    }
}
let emojis: [Emoji] = [.neko, .inu, .usi, .inu]
let topPriorityEmoji = emojis.max()
topPriorityEmoji?.rawValue //"🐮"

Comparable使えば別にStringでなくてもいいし、enumでなくてもよい

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