Swift protocol generic as function return type

前端 未结 2 923
无人及你
无人及你 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:22

    The problem is you cannot use the syntax P. P is a protocol, meaning it can't be treated as a generic type (Cannot specialize non-generic type 'P'), even though it may have a given associatedtype.

    In fact, because it has an associatedtype, you now can't even use the protocol type itself directly – you can only use it as a generic constraint.

    One solution to your problem is to simply change your function signature to createC() -> C, as that's exactly what it returns.

    class Factory {
        func createC() -> C {
            return C()
        }
    }
    

    I'm not entirely sure what you would gain from having the return type be a protocol here. Presumably your example is just a simplification of your actual code and you want to be able to return an arbitrary instance that conforms to P. In that case, you could use type erasure:

    class AnyP : P {
    
        private let _get : () -> T?
        private let _set : (T) -> ()
    
        init(_ base:U) {
            _get = base.get
            _set = base.set
        }
    
        func get() -> T? {return _get()}
        func set(v: T) {_set(v)}
    }
    

    class Factory {
        func createC() -> AnyP {
            return AnyP(C())
        }
    }
    

提交回复
热议问题