对于协议,要求实例变量符合协议;而不是有一个特定的类型

发布于 2025-01-12 23:15:33 字数 998 浏览 2 评论 0原文

作为自定义 Coder 的一部分,我以完全相同的方式转换 FloatDouble

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 .bitPatternUInt64 ,而 Float.bitPatternUInt32

正确的语法是什么要求 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

听风吹 2025-01-19 23:15:33

您正在寻找的是关联类型。这正是您所描述的内容(所需的类型符合协议,而不是该协议的存在):

protocol CompatibleFloatingPoint {
    associatedtype BitPattern: FixedWidthInteger
    var bitPattern : BitPattern { get }
}

extension Float: CompatibleFloatingPoint {}
extension Double: CompatibleFloatingPoint {}

有关更多详细信息,请参阅 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):

protocol CompatibleFloatingPoint {
    associatedtype BitPattern: FixedWidthInteger
    var bitPattern : BitPattern { get }
}

extension Float: CompatibleFloatingPoint {}
extension Double: CompatibleFloatingPoint {}

For more details, see Associated Types in the Swift Programming Language.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文