Protocol func returning Self

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

    Swift 5.1 now allow a forced cast to Self, as! Self

      1> protocol P { 
      2.     func id() -> Self 
      3. } 
      9> class D : P { 
     10.     func id() -> Self { 
     11.         return D()
     12.     } 
     13. } 
    error: repl.swift:11:16: error: cannot convert return expression of type 'D' to return type 'Self'
            return D()
                   ^~~
                       as! Self
    
    
      9> class D : P { 
     10.     func id() -> Self { 
     11.         return D() as! Self
     12.     } 
     13. } //works
    

提交回复
热议问题