Protocol func returning Self

后端 未结 9 1902
悲哀的现实
悲哀的现实 2020-11-22 15:11

I have a protocol P that returns a copy of the object:

protocol P {
    func copy() -> Self
}

and a class C that implements P:



        
9条回答
  •  余生分开走
    2020-11-22 15:45

    There is another way to do what you want that involves taking advantage of Swift's associated type. Here's a simple example:

    public protocol Creatable {
    
        associatedtype ObjectType = Self
    
        static func create() -> ObjectType
    }
    
    class MyClass {
    
        // Your class stuff here
    }
    
    extension MyClass: Creatable {
    
        // Define the protocol function to return class type
        static func create() -> MyClass {
    
             // Create an instance of your class however you want
            return MyClass()
        }
    }
    
    let obj = MyClass.create()
    

提交回复
热议问题