5

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 ?

2
  • 1
    Have you tried to use periods.rawValue? Commented Sep 27, 2016 at 18:01
  • 1
    Side note: As of Swift 3, the convention is to start enumeration cases with a lowercase letter: daily, weekly, monthly. Commented Sep 27, 2016 at 18:23

1 Answer 1

5

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's so elegant. I like it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.