Ybr*_*rin 3 objective-c ios swift
我目前正在使用以客观c编写的cocoapod.在示例中,它们显示了类似的内容:
options.allowedSwipeDirections = MDCSwipeDirectionLeft | MDCSwipeDirectionRight;
Run Code Online (Sandbox Code Playgroud)
我甚至不知道调用这些变量是什么,但我已经在Swift中尝试了以下内容:
options.allowedSwipeDirections = MDCSwipeDirection.Left | MDCSwipeDirection.Right
Run Code Online (Sandbox Code Playgroud)
但编译说 No '|' candidates produce the expected contextual result type '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;
Run Code Online (Sandbox Code Playgroud)
就像这样使用:
_allowedSwipeDirections = MDCSwipeDirectionLeft | MDCSwipeDirectionRight;
Run Code Online (Sandbox Code Playgroud)
MDCSwipeDirection是(不幸的是)在Objective-C中定义为NS_ENUM而不是NS_OPTIONS:
typedef NS_ENUM(NSInteger, MDCSwipeDirection) {
MDCSwipeDirectionNone = 1,
MDCSwipeDirectionLeft = 2,
MDCSwipeDirectionRight = 4,
MDCSwipeDirectionUp = 8,
MDCSwipeDirectionDown = 16
};
Run Code Online (Sandbox Code Playgroud)
因此它作为一个简单的导入到Swift enum而不是OptionSetType:
public enum MDCSwipeDirection : Int {
case None = 1
case Left = 2
case Right = 4
case Up = 8
case Down = 16
}
Run Code Online (Sandbox Code Playgroud)
因此,你必须与兼顾rawValue的enum <-> Int
转换:
let allowedSwipeDirections = MDCSwipeDirection(rawValue: MDCSwipeDirection.Left.rawValue | MDCSwipeDirection.Right.rawValue)!
Run Code Online (Sandbox Code Playgroud)
请注意,强制解包不能失败,请参阅例如 如何使用Swift 1.2确定NS_ENUM的未记录值:
... 如果从定义中导入枚举,Swift 1.2现在允许使用任意原始值(基础整数类型)创建枚举变量.
NS_ENUM
如果将Objective-C定义更改为
typedef NS_OPTIONS(NSInteger, MDCSwipeDirection) {
MDCSwipeDirectionNone = 1,
MDCSwipeDirectionLeft = 2,
MDCSwipeDirectionRight = 4,
MDCSwipeDirectionUp = 8,
MDCSwipeDirectionDown = 16
};
Run Code Online (Sandbox Code Playgroud)
然后导入为
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 }
}
Run Code Online (Sandbox Code Playgroud)
你可以简单地写
let allowedDirections : MDCSwipeDirection = [ .Left, .Right ]
Run Code Online (Sandbox Code Playgroud)