Swift protocol generic as function return type

前端 未结 2 922
无人及你
无人及你 2021-01-11 16:18

I want to use generic protocol type as a function return type like this:

protocol P {
  associatedtype T
  func get() -> T?
  func set(v: T)
}

class C<         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-11 16:33

    Swift 5.1 supports returning associated types using Opaque type. Using opaque type, your code builds successfully. Ref

    protocol P {
        associatedtype T
        func get() -> T?
        func set(v: T)
    }
    
    class C: P {
        private var v: T?
    
        func get() -> T? {
            return v
        }
        func set(v: T) {
            self.v = v
        }
    }
    
    class Factory {
        func createC() -> some P {
            return C()
    }
    

提交回复
热议问题