Swift struct 采用具有静态读写属性的协议不符合? [英] Swift struct adopting protocol with static read-write property doesn't conform?

查看:62
本文介绍了Swift struct 采用具有静态读写属性的协议不符合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这不能在 Swift 1.2 中编译?

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"
}

(在 Swift 1.1 中,只需将协议声明中的 class 替换为 static.同样的问题.)

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

编译器抱怨我不符合协议.但为什么我不是?很容易证明Struct中的静态属性name可读可写的,所以我肯定满足了协议的精神.

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.

我有一些额外的观察:

  • 如果我从协议要求中删除 set,问题就会消失.

如果我保留 set,但我从协议要求中删除了 static(或 class),并且static 来自 Struct 实现,问题消失了.

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.

如果我保留 static 并将存储的变量转换为计算变量,问题就会消失.

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?

推荐答案

此时我被 Nate Cook 的例子说服了,这只不过是 Swift 编译器中的一个错误.正如他所指出的,只要在静态变量上添加一个空的 didSet 观察者就可以编译代码.事实上,这可能会有所作为,即使它没有功能差异,但到处都写着错误".

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.

这篇关于Swift struct 采用具有静态读写属性的协议不符合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆