gpt4 book ai didi

swift - 如何在 BitwiseOperationsType 中实现运算符

转载 作者:行者123 更新时间:2023-11-30 10:22:04 24 4
gpt4 key购买 nike

开源代码 LogFlag 类(CocoaLumberjack.swift 不再编译,因为在 Xcode 6 Beta 7 RawOptionSetType 已更改为实现 BitwiseOperationsType。我不知道如何实现运算符功能。

下面的示例使用 CocoaLumberjack.swift 中的 LogFlag:

// RawOptionSetType implements BitwiseOperationsType, so LogFlag won't compile until it implements the operators there

struct LogFlag : RawOptionSetType, BooleanType {
private var value: Int32 = 0
init(_ value: Int32) { self.value = value }
var boolValue: Bool { return self.value != 0 }
func toRaw() -> Int32 { return self.value }
static func fromRaw(raw: Int32) -> LogFlag? { return self(raw) }
static func fromMask(raw: Int32) -> LogFlag { return self(raw) }
static func convertFromNilLiteral() -> LogFlag { return self(0) }

static var Error: LogFlag { return self(1 << 0) }
static var Warn: LogFlag { return self(1 << 1) }
static var Info: LogFlag { return self(1 << 2) }
static var Debug: LogFlag { return self(1 << 3) }
static var Verbose: LogFlag { return self(1 << 4) }
}

尝试:

func &(_: LogFlag, _:LogFlag) -> LogFlag { // What goes here? }

这是协议(protocol):

protocol BitwiseOperationsType {
func &(_: Self, _: Self) -> Self
func |(_: Self, _: Self) -> Self
func ^(_: Self, _: Self) -> Self
prefix func ~(_: Self) -> Self

/// The identity value for "|" and "^", and the fixed point for "&".
///
/// ::
///
/// x | allZeros == x
/// x ^ allZeros == x
/// x & allZeros == allZeros
/// x & ~allZeros == x
///
class var allZeros: Self { get }
}

最佳答案

添加就足够了

static var allZeros: LogFlag { return nil }

到结构定义。其余运算符 &|^~协议(protocol)已定义为通用函数,例如

func &<T : _RawOptionSetType>(a: T, b: T) -> T

如果您确实想要覆盖该运算符,请实现(作为示例)

func &(a: LogFlag, b: LogFlag) -> LogFlag {
return LogFlag(a.value & b.value)
}

关于swift - 如何在 BitwiseOperationsType 中实现运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25642260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com