Protocol doesn't conform to itself?

前端 未结 3 1823
陌清茗
陌清茗 2020-11-21 04:30

Why doesn\'t this Swift code compile?

protocol P { }
struct S: P { }

let arr:[P] = [ S() ]

extension Array where Element : P {
    func test() -&g         


        
3条回答
  •  半阙折子戏
    2020-11-21 04:55

    If you extend CollectionType protocol instead of Array and constraint by protocol as a concrete type, you can rewrite the previous code as follows.

    protocol P { }
    struct S: P { }
    
    let arr:[P] = [ S() ]
    
    extension CollectionType where Generator.Element == P {
        func test() -> [T] {
            return []
        }
    }
    
    let result : [S] = arr.test()
    

提交回复
热议问题