在框架中声明结构的琐碎协议一致性 [英] Declare trivial protocol conformance for struct in a framework
问题描述
是否可以声明struct定义在框架中的struct符合我的应用程序中定义的协议?
Is it possible to declare that struct a struct, defined in a framework, trivially conforms to a protocol, defined in my app?
例如,我有一个API,用于为框架中建模的一些小部件声明结构:
Say, for example, I have an API that declares structs for a few widgets modelled in a framework:
public struct VagueWidget {
public let temperature: Float
}
public struct SpecificWidget {
public let calibratedTemperature: Float
public let movingAverageTemperature: Float
}
public struct SuperSpecificWidget {
public let surfaceTemperature: Float
public let inferredCoreTemperature: Int?
}
然后在我的应用程序中,我想通过协议来概括这些内容.
And then in my application I want to generalise these by way of a protocol.
protocol Widget {
var temperature: Float { get }
}
在我的应用程序中,我可以声明类似于API中的结构,并简单地声明它们符合协议.
In my application I can declare structs similar to those in the API, and trivially declare them as conforming to the protocol.
struct MockWidget {
let temperature: Float
}
extension MockWidget: Widget {}
然后我可以声明框架中结构的协议一致性.
And then I can declare protocol conformance for the structs in the framework.
extension SuperSpecificWidget: Widget {
var temperature: Float {
get {
return surfaceTemperature
}
}
}
extension SpecificWidget: Widget {
var temperature: Float {
get {
return calibratedTemperature
}
}
}
extension VagueWidget: Widget {}
此代码可以编译,但不会链接.与应用程序中的MockWidget
等效的框架中的VagueWidget
符合标准,导致缺少符号:
This code compiles, but doesn't link. The trivially conforming VagueWidget
in the framework which is equivalent to the MockWidget
in the application results in a missing symbol:
Undefined symbols for architecture x86_64:
"WidgetAPI.VagueWidget.temperature.getter : Swift.Float", referenced from:
protocol witness for WidgetApp.Widget.temperature.getter : Swift.Float in conformance WidgetAPI.VagueWidget : WidgetApp.Widget in WidgetApp in AppModel.o
注释VagueWidget
的琐碎协议一致性会生成可编译和运行的代码,但显然缺少所需的协议一致性.我在github上添加了示例项目.
Commenting out the trivial protocol conformance for the VagueWidget
produces code that compiles and runs, but obviously missing the desired protocol conformance. I've added an example project on github.
更新:这似乎是一个已知问题.我已经提交了雷达,并且已作为 20648441 的副本关闭.
Update: This appears to be a known issue. I have filed a radar, and it was closed as a duplicate of 20648441.
推荐答案
发现的有趣错误.您和Scott H完成了所有工作,但想通过一些解决方法来解决问题:
Interesting bug you found. You and Scott H did all the work, but wanted to chime in with some workarounds:
-
将模型从
struct
更改为class
.不知道为什么会这样.
Change your models from
struct
toclass
. No idea why this works.
功能也可以使用(即func temperature() -> Float
).
Functions also work (i.e. func temperature() -> Float
).
两者都不尽人意.
这篇关于在框架中声明结构的琐碎协议一致性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!