【问题标题】:Abstract Access to Bitwise Shifts in Swift在 Swift 中对按位移位的抽象访问
【发布时间】:2016-01-15 10:11:27
【问题描述】:

所以不久前,我正在编写一些 Swift 代码,这将使我能够对二进制整数进行一些有用的额外操作,包括获取实际设置的最高位和最低位。

例如,这是我添加的一个基本属性,现在已损坏:

extension IntegerType {
    var hiBit:Self { return ~self.allZeroes << ((sizeof(Self) * 8) - 1) }
}

现在无法编译,因为 IntegerType 不再符合 BitwiseOperationsType 所以波浪号运算符和 allZeroes 属性不再可用。同样,实现IntegerTypeBitwiseOperationsType 的结构似乎不再需要具有移位运算符,它们现在似乎只是按惯例定义的,除非我错过了一些东西。这意味着我也不能将我的代码移植到 BitwiseOperationsType,即使它看起来更合乎逻辑。

所以我的问题是;我在哪里实现最高级别的代码?我不想为每个特定的整数类型复制它,这就是我扩展IntegerType 开始的原因。

顺便说一句,我最初将hiBit 实现为static 属性,但这些似乎不再受支持,这显然很奇怪,并且错误消息暗示它们将在未来出现,暗示它们已从规范中删除;但我没有运行 Xcode 测试版。

【问题讨论】:

    标签: swift polymorphism bitwise-operators bit-shift


    【解决方案1】:

    没有定义位移运算符的协议,所以你有 定义你自己的:

    protocol ShiftOperationsType : BitwiseOperationsType {
        func <<(lhs: Self, rhs: Self) -> Self
        func >>(lhs: Self, rhs: Self) -> Self
        init(_ value : Int)
    }
    

    不幸的是,你必须声明整数类型的一致性 明确地为每种类型的该协议(目前没有 更简单的解决方案,比较What protocol should be adopted by a Type for a generic function to take any number type as an argument in Swift?)。

    extension Int : ShiftOperationsType {}
    extension Int8 : ShiftOperationsType {}
    extension Int16 : ShiftOperationsType {}
    extension Int32: ShiftOperationsType {}
    extension Int64: ShiftOperationsType {}
    extension UInt : ShiftOperationsType {}
    extension UInt8 : ShiftOperationsType {}
    extension UInt16 : ShiftOperationsType {}
    extension UInt32 : ShiftOperationsType {}
    extension UInt64 : ShiftOperationsType {}
    

    但是您可以将hiBit 定义为通用静态属性:

    extension ShiftOperationsType {
        static var hiBit : Self {
            return (~allZeros) << Self(sizeof(Self) * 8 - 1)
        }
    }
    

    协议中的init方法是必须的,因为sizeof() 返回一个Int,并且必须转换为Self

    【讨论】:

    • 谢谢,这让我再次启动并运行!似乎真的应该在 BitwiseOperationsType 或其他东西下,哦,好吧,也许有一天 Apple 会停止搞乱数字协议,我们实际上可以开始使用它们;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2012-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多