简体   繁体   中英

Swift enum with default protocol implementation

I have multiple Core Data-related enums like:

enum ManagedItemProperties: String {
    case purchaseDate
    case productId
    case addons
}

I want to have a protocol for each of these enums to generate a NSSortDescriptor and NSPredicate s for fetching objects by their properties.

Is it possible to write a protocol like:

protocol ManagedProperty {
    func sortDescriptor(ascending: Bool) -> NSSortDescriptor
    func predicateEqual(to arg: CVarArg) -> NSPredicate
    func predicate(_ booleanValue: Bool) -> NSPredicate
}

And its default implementation similar to this:

extension ManagedProperty where ????? {
    func sortDescriptor(ascending: Bool = true) -> NSSortDescriptor {
        return NSSortDescriptor(key: ?????, ascending: ascending)
    }
    func predicateEqual(to arg: CVarArg) -> NSPredicate {
        return NSPredicate(format: "SELF.%@ == %@", ?????, arg)
    }
    func predicate(_ booleanValue: Bool) -> NSPredicate {
        return NSPredicate(format: "SELF.%@ == %d", ?????, booleanValue)
    }
}

Yes , protocol extensions allow you to provide default implementations of code to conforming types. However, with enums you are probably better off writing one protocol and writing an extension to each enum to implement that protocol, like

extension ManagedItemProperties: ManagedProperty {
    func sortDescriptor(ascending: Bool = true) -> NSSortDescriptor {
        return NSSortDescriptor(key: ?????, ascending: ascending)
    }
    func predicateEqual(to arg: CVarArg) -> NSPredicate {
        return NSPredicate(format: "SELF.%@ == %@", ?????, arg)
    }
    func predicate(_ booleanValue: Bool) -> NSPredicate {
        return NSPredicate(format: "SELF.%@ == %d", ?????, booleanValue)
    }
}

If the predicates returned differ by the enum case, use a switch statement in your functions and Swift will make sure you include a code path for every case.

Okay, I settled on an extension to String that returns NSPredicate s. Much easier to get the raw string value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM