Protocol conforming to type with associated value

前端 未结 1 857
我寻月下人不归
我寻月下人不归 2021-01-24 04:35

I\'ve got the following snippet:

protocol MyProtocol: Identifiable where ID == UUID {
    var id: UUID { get }
}


var          


        
相关标签:
1条回答
  • 2021-01-24 05:15

    Because this is not a current feature of Swift. Once there is an associated type, there is always an associated type. It doesn't go away just because you constrain it. And once it has an associated type, it is not concrete.

    There is no way to "inherit" protocols this way. What you mean is:

    protocol MyProtocol {
        var id: UUID { get }
    }
    

    And then you can attach Identifiable to structs that require it:

    struct X: MyProtocol, Identifiable {
        var id: UUID
    }
    

    (note that no where clause is required.)

    There is no Swift feature today that allows you to say "types that conform to X implicitly conform to Y." There is also no Swift feature today that allows for an Array of "things that conform to Identifiable with ID==UUID." (That's called a generalized existential, and it's not currently available.)

    Most likely you should go back to your calling code and explore why you require this. If you post the code that iterates over test and specifically requires the Identifiable conformance, then we may be able to help you find a design that doesn't require that.

    0 讨论(0)
提交回复
热议问题