简体   繁体   English

如何将枚举数组转换为int数组

[英]How to convert array of enum to array of int's

I am using Core Data and one of my predicates retrieves data based on the following enum: 我正在使用Core Data,我的一个谓词根据以下枚举检索数据:

enum Period : Int {
   Daily
   Weekly
   Monthly
}

My predicates is like this: 我的谓词是这样的:

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

My problem is I don't want to use Int's when calling this predicate, I want to pass the Period enum, but inside the predicate is have to convert it to Int to make it work. 我的问题是我不想在调用这个谓词时使用Int's ,我想传递Period枚举,但在谓词内部必须将它转换为Int以使其工作。

Is there a quick way to convert it ? 有快速转换方法吗?

You can use the map() method (of the Sequence protocol) to map each enumeration to its integer raw value: 您可以使用map()方法( Sequence协议)将每个枚举映射到其整数原始值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM