当前位置 : 主页 > 手机开发 > ios >

ios – Swift相当于为属性设置多个值

来源:互联网 收集:自由互联 发布时间:2021-06-11
我目前正在使用以客观c编写的 cocoapod. 在示例中,它们显示了类似的内容: options.allowedSwipeDirections = MDCSwipeDirectionLeft | MDCSwipeDirectionRight; 我甚至不知道调用这些变量是什么,但我已经在
我目前正在使用以客观c编写的 cocoapod.
在示例中,它们显示了类似的内容:

options.allowedSwipeDirections = MDCSwipeDirectionLeft | MDCSwipeDirectionRight;

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

options.allowedSwipeDirections = MDCSwipeDirection.Left | MDCSwipeDirection.Right

但编译器说没有’|’候选者产生预期的上下文结果类型’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;
不幸的是,在Objective-C中定义了MDCSwipeDirection
作为NS_ENUM而不是NS_OPTIONS:

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

因此它作为一个简单的枚举导入到Swift而不是
作为OptionSetType:

public enum MDCSwipeDirection : Int {

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

因此,您必须使用rawValue来兼容enum< - >诠释
转换:

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 ]
网友评论