Last active
August 29, 2015 14:26
-
-
Save patricklynch/ff63661a4f7248cb629b to your computer and use it in GitHub Desktop.
CoreData Set Utils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Some extensions with overloaded operators for easily adding and removing | |
/// objects to sets when working with CoreData | |
import Foundation | |
import CoreData | |
protocol ManagedSet { | |
var allObjects: [AnyObject] { get } | |
init( array: [AnyObject] ) | |
} | |
extension NSOrderedSet : ManagedSet { | |
var allObjects: [AnyObject] { return self.array } | |
} | |
extension NSSet : ManagedSet {} | |
func += <T: ManagedSet>(inout lhs: T, rhs: NSManagedObject) -> T { | |
var array = lhs.allObjects as? [NSManagedObject] ?? [NSManagedObject]() | |
array.append( rhs ) | |
lhs = T(array: array) | |
return lhs | |
} | |
func -= <T: ManagedSet>(inout lhs: T, rhs: NSManagedObject) -> T { | |
var array = lhs.allObjects as? [NSManagedObject] ?? [NSManagedObject]() | |
array = array.filter { $0 != rhs } | |
lhs = T(array: array) | |
return lhs | |
} | |
func += <T: ManagedSet>(inout lhs: T, rhs: [NSManagedObject]) -> T { | |
var array = lhs.allObjects as! [NSManagedObject] | |
array = array + rhs | |
lhs = T(array: array) | |
return lhs | |
} | |
func -= <T: ManagedSet>(inout lhs: T, rhs: [NSManagedObject]) -> T { | |
var array = lhs.allObjects as! [NSManagedObject] | |
array = array.filter { !rhs.contains( $0 ) } | |
lhs = T(array: array) | |
return lhs | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment