对于协议,要求实例变量符合协议;而不是有一个特定的类型
作为自定义 Coder
的一部分,我以完全相同的方式转换 Float
和 Double
:
static func encode(_ value : Double) -> Data {
withUnsafeBytes(of: value.bitPattern.bigEndian) { Data($0) }
}
static func encode(_ value : Float) -> Data {
withUnsafeBytes(of: value.bitPattern.bigEndian) { Data($0) }
}
我认为我可以要求 >value
将符合协议,并且由于 FloatingPoint
协议不保证 bitPattern
的存在,我想我会自己制作:
protocol CompatibleFloatingPoint {
var bitPattern : FixedWidthInteger { get }
}
但是,给出以下错误: 协议“FixedWidthInteger”只能用作通用约束,因为它具有 Self 或关联的类型要求
但是,我无法将 FixedWidthInteger
替换为特定类型,如 Double .bitPattern
是 UInt64
,而 Float.bitPattern
是 UInt32
正确的语法是什么要求 bitPattern
符合 FixedWidthInteger
协议而不强制其具有特定类型?
As part of a custom Coder
, I convert both Float
and Double
in the exact same way :
static func encode(_ value : Double) -> Data {
withUnsafeBytes(of: value.bitPattern.bigEndian) { Data($0) }
}
static func encode(_ value : Float) -> Data {
withUnsafeBytes(of: value.bitPattern.bigEndian) { Data($0) }
}
I thought that instead I could require that value
would conform to a protocol, and since the FloatingPoint
protocol does not guarantee the presence of bitPattern
, I thought I would make my own :
protocol CompatibleFloatingPoint {
var bitPattern : FixedWidthInteger { get }
}
This, however, gives the following error :Protocol 'FixedWidthInteger' can only be used as a generic constraint because it has Self or associated type requirements
However, I cannot replace FixedWidthInteger
with a specific type, as Double.bitPattern
is a UInt64
and Float.bitPattern
is a UInt32
What is the proper syntax to require that bitPattern
conform to the FixedWidthInteger
protocol without forcing it to have a specific type ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在寻找的是关联类型。这正是您所描述的内容(所需的类型符合协议,而不是该协议的存在):
有关更多详细信息,请参阅 Swift 编程语言中的关联类型。
What you're looking for is an associated type. This means exactly what you've described (the required type conforms to a protocol rather than being the existential of that protocol):
For more details, see Associated Types in the Swift Programming Language.