Protocol for class method

后端 未结 1 995
梦谈多话
梦谈多话 2020-12-20 15:56

I want to declare in a protocol a class func, I intend to conform to this protocol from a class A, B and C.

B and C inherit from A.

Essentiall

相关标签:
1条回答
  • 2020-12-20 16:22

    In a class definition, static is an alias for class final, so it marks a type method (or property) which cannot be overridden in subclasses.

    Since you want to override the method in subclasses, all you have to do is to define the method as class instead of static:

    extension A: MyManagedObjectCoolStuff {
    
        class func entityName() -> String {
            return "Animal"
        }
    }
    
    extension B: MyManagedObjectCoolStuff {
    
        override class func entityName() -> String {
            return "Bat"
        }
    }
    
    extension C: MyManagedObjectCoolStuff {
    
        override class func entityName() -> String {
            return "Cat"
        }
    }
    

    Alternatively one could use the fact that for a Core Data entity, the class name is usually defined as <ModuleName>.<EntityName> so that the entity name is the last component of the class name.

    So you could define entityName() as an extension method of NSManagedObject (the superclass of all Core Data object classes) as in How can I create instances of managed object subclasses in a NSManagedObject Swift extension?:

    extension NSManagedObject {
    
        class func entityName() -> String {
            let classString = NSStringFromClass(self)
            // The entity is the last component of dot-separated class name:
            let components = split(classString) { $0 == "." }
            return components.last ?? classString
        }
    }
    

    and override it only where necessary:

    class A: NSManagedObject { }
    
    class B: A { }
    
    class C: A { }
    
    extension C {
    
        override class func entityName() -> String {
            return "Cat"
        }
    }
    
    println(A.entityName()) // A
    println(B.entityName()) // B
    println(C.entityName()) // Cat
    
    0 讨论(0)
提交回复
热议问题