2017-10-21 412 views
0

我有WorkoutDifficulty財產如何通過枚舉值對對象進行排序?

enum Difficulty: String { 
    case easy = "easy" 
    case moderate = "moderate" 
    case hard = "hard" 
} 

class Workout { 
    var name: String? 
    var difficulty: Difficulty? 
    . 
    . 
    . 
} 

我想用難度屬性進行排序鍛鍊的數組。我知道我可以通過指定枚舉的原始值,以int值實現這一點,如下比較這些值:

data.sort { $0.workout.difficulty!.rawValue < $1.workout.difficulty!.rawValue } 

但我真的希望這個枚舉存儲字符串,因爲它的方便,它分配給標籤文本上下行沒有醜陋的開關箱黑客攻擊,並且在某種程度上具有可比性。

如何實現這一目標?

+0

您可以使用枚舉hashValue。順便說一句你應該使用結構而不是類。和Igor的建議類似,你可以讓你的結構具有可比性,而不是讓枚舉具有可比性。 –

+0

Btw定義一個字符串值與枚舉值相同是多餘的 –

+0

@LeoDabus感謝您的建議,能否提供完整的示例作爲答案? – DCDC

回答

0

你可以使用你的枚舉散列值,以你的鍛鍊排序。您應該使用結構而不是類,並且類似於Igor所建議的結構,您可以使結構與枚舉相媲美:

struct Workout: Comparable { 
    let name: String 
    let difficulty: Difficulty 
    enum Difficulty: String { 
     case easy, moderate, hard 
    } 
    static func ==(lhs: Workout, rhs: Workout) -> Bool { 
     return lhs.difficulty.hashValue == rhs.difficulty.hashValue 
    } 
    static func <(lhs: Workout, rhs: Workout) -> Bool { 
     return lhs.difficulty.hashValue < rhs.difficulty.hashValue 
    } 
} 

let wk1 = Workout(name: "night", difficulty: .hard) 
let wk2 = Workout(name: "morning", difficulty: .easy) 
let wk3 = Workout(name: "afternoon", difficulty: .moderate) 

let workouts = [wk1, wk2, wk3] // [{name "night", hard}, {name "morning", easy}, {name "afternoon", moderate}] 

let sorted = workouts.sorted() // [{name "morning", easy}, {name "afternoon", moderate}, {name "night", hard}] 
1

在您的enum上實施Comparable協議。它爲您提供了一個static func < (lhs: Difficulty, rhs: Difficulty) -> Bool方法,您可以在其中定義排序。

下面是一個使用屬性來簡化整個樣本訂貨

enum Difficulty: String, Comparable { 
    case easy = "easy" 
    case moderate = "moderate" 
    case hard(String) = "hard" 

    private var sortOrder: Int { 
     switch self { 
      case .easy: 
       return 0 
      case .moderate: 
       return 1 
      case .hard(_): 
       return 2 
     } 
    } 

    static func ==(lhs: Difficulty, rhs: Difficulty) -> Bool { 
     return lhs.sortOrder == rhs.sortOrder 
    } 

    static func <(lhs: Difficulty, rhs: Difficulty) -> Bool { 
     return lhs.sortOrder < rhs.sortOrder 
    } 
} 

使其能夠使用

data.sort { $0.workout.difficulty! < $1.workout.difficulty! } 
+0

你能提供完整的例子嗎? – DCDC

相關問題