Swift struct adopting protocol with static read-write property doesn't conform?

末鹿安然 提交于 2019-12-11 01:59:13

问题


Why doesn't this compile in Swift 1.2?

protocol Proto {
    static var name : String {get set}
}
struct Struct : Proto {
    static var name : String = "name"
}

(In Swift 1.1, just substitute class for static inside the protocol declaration. Same problem.)

The compiler complains that I'm not conforming to the protocol. But why am I not? It's easy to prove that the static property name in Struct is both readable and writable, so I've satisfied the spirit of the protocol, surely.

I have some additional observations:

  • If I remove the set from the protocol requirement, the issue goes away.

  • If I leave the set in place, but I remove the static (or class) from the protocol requirement and the static from the Struct implementation, the issue goes away.

  • If I leave the static in place and turn the stored variable into a computed variable, the issue goes away.

  • If I change the struct to a class, the issue goes away.

But I'm no closer to understanding what the compiler doesn't like about what I've got. Why doesn't a static stored property satisfy the protocol requirement?


回答1:


The mothership fixeth in 6.3 (6D543q):

protocol Proto {
    static var name : String {get set}
}

struct Struct : Proto {
    static var name : String = "name"
}

Struct.name = "Frodo"

println(Struct.name)

now works:

-> "Frodo"

(tested in Playgrounds) It really does seem like static was treated as a let / const variable, but your case now works in 6.3 Beta 3. I'm just happy that lldb symbols are unbroken.




回答2:


At this point I'm persuaded by Nate Cook's example that this is nothing but a bug in the Swift compiler. As he points out, merely adding an empty didSet observer on the static variable allows the code to compile. The fact that this could make a difference, even though it makes no functional difference, has "bug" written all over it.



来源:https://stackoverflow.com/questions/28597490/swift-struct-adopting-protocol-with-static-read-write-property-doesnt-conform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!