2016-09-27 50 views
3

我使用的核心數據的陣列和我的一個謂詞獲取基於以下枚舉數據:如何枚舉的數組轉換爲INT的

enum Period : Int { 
    Daily 
    Weekly 
    Monthly 
} 

我的謂詞是這樣的:

public static func byTypePredicate(periods: [Int]) -> NSPredicate { 
    return NSPredicate(format: "period IN %@", periods) 
} 

我的問題是,我不想調用這個謂詞時使用Int's,我想通過Period枚舉,但謂詞中是必須將其轉換爲Int,使其工作。

是否有一個快速的方法來轉換呢?

+1

您是否嘗試過使用'periods.rawValue'? – Andrej

+1

備註:從Swift 3開始,約定將以小寫字母開始枚舉個案:「每日」,「每週」,「每月」。 –

回答

4

可以使用map()方法(Sequence協議),以每個枚舉到其整原始值映射:

func byTypePredicate(periods: [Period]) -> NSPredicate { 
    let intPeriods = periods.map { $0.rawValue } // [Int] 
    return NSPredicate(format: "period IN %@", intPeriods) 
} 
+0

那太優雅了。我喜歡。 – Kobe