Protocol func returning Self

后端 未结 9 1811
悲哀的现实
悲哀的现实 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:42

    Actually, there is a trick that allows to easily return Self when required by a protocol (gist):

    /// Cast the argument to the infered function return type.
    func autocast(some: Any) -> T? {
        return some as? T
    }
    
    protocol Foo {
        static func foo() -> Self
    }
    
    class Vehicle: Foo {
        class func foo() -> Self {
            return autocast(Vehicle())!
        }
    }
    
    class Tractor: Vehicle {
        override class func foo() -> Self {
            return autocast(Tractor())!
        }
    }
    
    func typeName(some: Any) -> String {
        return (some is Any.Type) ? "\(some)" : "\(some.dynamicType)"
    }
    
    let vehicle = Vehicle.foo()
    let tractor = Tractor.foo()
    
    print(typeName(vehicle)) // Vehicle
    print(typeName(tractor)) // Tractor
    

提交回复
热议问题