Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array of enum to array of int's

Tags:

ios

swift

I am using Core Data and one of my predicates retrieves data based on the following enum:

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.

Is there a quick way to convert it ?

like image 623
Adrian Avatar asked Sep 27 '16 17:09

Adrian


1 Answers

You can use the map() method (of the Sequence protocol) to map each enumeration to its integer raw value:

func byTypePredicate(periods: [Period]) -> NSPredicate {
    let intPeriods = periods.map { $0.rawValue } // [Int]
    return NSPredicate(format: "period IN %@", intPeriods)
}
like image 110
Martin R Avatar answered Sep 20 '22 19:09

Martin R