Last active
August 29, 2015 14:25
-
-
Save an0/0f5f0ab6e16f0b288182 to your computer and use it in GitHub Desktop.
Power of Default Associated Type
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
// Simplify code of http://martiancraft.com/blog/2015/07/objective-c-swift-core-data/ by using default associated type to eliminate the need of defining associated type in every subclass. | |
class ManagedObject {} | |
class Person: ManagedObject {} | |
class Thing: ManagedObject {} | |
let db: [ManagedObject] = [Person(), Thing()] | |
protocol Fetchable { | |
typealias FetchableType: ManagedObject = Self | |
static func objectInDB() -> FetchableType? | |
} | |
extension Fetchable where Self: ManagedObject { | |
static func objectInDB() -> FetchableType? | |
{ | |
return db.first as? FetchableType | |
} | |
} | |
extension Person: Fetchable {} | |
extension Thing: Fetchable {} | |
let person: Person? = Person.objectInDB() | |
print(person) | |
let thing: Thing? = Thing.objectInDB() | |
print(thing) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment