gpt4 book ai didi

ios - Swift相当于给一个属性设置多个值

转载 作者:搜寻专家 更新时间:2023-10-31 22:02:26 24 4
gpt4 key购买 nike

我目前正在使用用 objective-c 编写的 cocoapod。在示例中,他们显示了类似的内容:

options.allowedSwipeDirections = MDCSwipeDirectionLeft | MDCSwipeDirectionRight;

我什至不知道这些变量叫什么,但我已经在 Swift 中尝试了以下内容:

options.allowedSwipeDirections = MDCSwipeDirection.Left | MDCSwipeDirection.Right

但是编译器说 No '|'候选人产生预期的上下文结果类型“MDCSwipeDirection”

我如何在 Swift 中执行此操作?

编辑:

看起来这不是某些答案中所述的OptionSet,她是声明:

/*!
* Contains the directions on which the swipe will be recognized
* Must be set using a OR operator (like MDCSwipeDirectionUp | MDCSwipeDirectionDown)
*/
@property (nonatomic, assign) MDCSwipeDirection allowedSwipeDirections;

它是这样使用的:

_allowedSwipeDirections = MDCSwipeDirectionLeft | MDCSwipeDirectionRight;

最佳答案

MDCSwipeDirection (不幸的是)在 Objective-C 中定义作为NS_ENUM而不是 NS_OPTIONS :

typedef NS_ENUM(NSInteger, MDCSwipeDirection) {
MDCSwipeDirectionNone = 1,
MDCSwipeDirectionLeft = 2,
MDCSwipeDirectionRight = 4,
MDCSwipeDirectionUp = 8,
MDCSwipeDirectionDown = 16
};

因此它作为简单的 enum 导入到 Swift 中并不是作为OptionSetType :

public enum MDCSwipeDirection : Int {

case None = 1
case Left = 2
case Right = 4
case Up = 8
case Down = 16
}

因此你必须兼顾 rawValue对于 enum <-> Int转换:

let allowedSwipeDirections =  MDCSwipeDirection(rawValue: MDCSwipeDirection.Left.rawValue | MDCSwipeDirection.Right.rawValue)!

注意强制解包不能失败,参见例子 How to determine if undocumented value for NS_ENUM with Swift 1.2 :

... Swift 1.2 does now allow the creation of enumeration variables with arbitrary raw values (of the underlying integer type), if the enumeration is imported from an NS_ENUM definition.


如果您将 Objective-C 定义更改为

typedef NS_OPTIONS(NSInteger, MDCSwipeDirection) {
MDCSwipeDirectionNone = 1,
MDCSwipeDirectionLeft = 2,
MDCSwipeDirectionRight = 4,
MDCSwipeDirectionUp = 8,
MDCSwipeDirectionDown = 16
};

然后它被导入为

public struct MDCSwipeDirection : OptionSetType {
public init(rawValue: Int)

public static var None: MDCSwipeDirection { get }
public static var Left: MDCSwipeDirection { get }
public static var Right: MDCSwipeDirection { get }
public static var Up: MDCSwipeDirection { get }
public static var Down: MDCSwipeDirection { get }
}

你可以简单地写

let allowedDirections : MDCSwipeDirection = [ .Left, .Right ]

关于ios - Swift相当于给一个属性设置多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36471716/

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