gpt4 book ai didi

swift - Swift 中导入的 NS_OPTIONS (RawOptionSetType) 的 Switch 语句?

转载 作者:可可西里 更新时间:2023-11-01 01:43:55 26 4
gpt4 key购买 nike

Swift 中的 switch 语句更具表现力。我想知道这是否可能:

让我们以 UIViewAutoresizing 为例。它在 Objective-C 中定义如下:

typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
UIViewAutoresizingNone = 0,
UIViewAutoresizingFlexibleLeftMargin = 1 << 0,
UIViewAutoresizingFlexibleWidth = 1 << 1,
UIViewAutoresizingFlexibleRightMargin = 1 << 2,
UIViewAutoresizingFlexibleTopMargin = 1 << 3,
UIViewAutoresizingFlexibleHeight = 1 << 4,
UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};

我可以像枚举一样在 Swift 中使用它:

let foo = UIViewAutoresizing([.FlexibleHeight, .FlexibleTopMargin])

是否可以使用 switch 语句而不是多个 if 语句?

if foo & UIViewAutoresizing.FlexibleHeight != nil {

}

if foo & UIViewAutoresizing.FlexibleWidth != nil {

}

if foo & UIViewAutoresizing.FlexibleTopMargin != nil {

}

像这样的伪代码:

switch foo { // ** THIS IS PSEUDO CODE AND WILL NOT COMPILE **

case & .FlexibleHeight:
println("height")

case & .FlexibleWidth:
println("width")

case & .FlexibleTop:
println("top")

}

最佳答案

我对这个问题感到非常沮丧,所以我写了一个 Bitmask<T>可以处理这些用例的类。代码在 Github 上:brynbellomy/SwiftBitmask

它允许你用任何类型的对象作为你的底层类型来做这样的事情(我在这里使用 enum ):

enum MonsterAttributes : IBitmaskRepresentable, IAutoBitmaskable {
case Big, Ugly, Scary

static var autoBitmaskValues : [MonsterAttributes] = [.Big, .Ugly, .Scary,]
var bitmaskValue: UInt16 { return AutoBitmask..autoBitmaskValueFor(self) }
init(bitmaskValue: UInt16) { self = AutoBitmask.autoValueFromBitmask(bitmaskValue) }
}

// various ways to initialize
let option : MonsterAttributes = .Ugly

let bitmaskOfOption = Bitmask(option)
let anotherBitmaskOfOption = |MonsterAttributes.Ugly // same as bitmaskOfOption

let orWithVar = option | .Big // == Bitmask<MonsterAttributes> with a bitmaskValue of 1 | 2
let simpleOr = MonsterAttributes.Big | .Ugly // == Bitmask<MonsterAttributes> with a bitmaskValue of 1 | 2

// getting the raw integral bitmask value
let simpleOrValue = simpleOr.bitmaskValue // == UInt16(1 | 2)
let orValue = (MonsterAttributes.Big | .Ugly).bitmaskValue // == UInt16(1 | 2)

// implements BooleanType
if simpleOr & .Ugly { /* this code will execute */ }

// supports pattern matching operator
if simpleOr ~= .Ugly { /* this code will execute */ }
if simpleOr ~= (.Ugly | .Scary) { /* this code will execute */ }

...您所要做的就是实现一个单一属性协议(protocol)。

我真的很好奇是否有人对代码有任何反馈或想法,所以如果您有任何想法,请在队列中留下问题!

关于swift - Swift 中导入的 NS_OPTIONS (RawOptionSetType) 的 Switch 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25388065/

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