Skip to content

Instantly share code, notes, and snippets.

@scribblecat
Created November 24, 2017 22:03
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save scribblecat/83faafbaac04ceffbe8d1359656a4c1e to your computer and use it in GitHub Desktop.
Save scribblecat/83faafbaac04ceffbe8d1359656a4c1e to your computer and use it in GitHub Desktop.
Get Array from Optional NSSet. Especially useful for getting an Array of objects in a Core Data many relationship.
/*
* Returns Array from optional NSSet. Returns empty array if NSSet is nil.
* It's useful for when you want an Array of objects from a Core Data many relationship.
*
* Example usage with managed object `game` with 1-to-many relationship to `Goal` entity:
* let goalArray = game.goals.array(of: Goal.self)
*/
extension Optional where Wrapped == NSSet {
func array<T: Hashable>(of: T.Type) -> [T] {
if let set = self as? Set<T> {
return Array(set)
}
return [T]()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment