如何将这个enum从objective-c翻译成swift?

时间:2014-12-16 08:14:54

标签: objective-c swift enums translate

我不明白为什么& << 不能在Swift中工作。请帮我将objective-c代码示例翻译成Swift。

示例1

UIViewController *viewController = [[UIViewController alloc] init];
viewController.edgesForExtendedLayout = UIRectEdgeBottom | UIRectEdgeTop;
if (viewController.edgesForExtendedLayout & UIRectEdgeBottom) {
    NSLog(@"got it!");
}

我正试图在Swift中翻译它但是出错了

let viewController = UIViewController()
viewController.edgesForExtendedLayout = .Bottom | .Top
if viewController.edgesForExtendedLayout & .Bottom {
    println("got it!")
}

示例2

typedef NS_OPTIONS(NSInteger, kViewControllerAnchoredGesture) {
    kViewControllerAnchoredGestureNone     = 0,
    kViewControllerAnchoredGesturePanning  = 1 << 0,
    kViewControllerAnchoredGestureTapping  = 1 << 1,
    kViewControllerAnchoredGestureCustom   = 1 << 2,
    kViewControllerAnchoredGestureDisabled = 1 << 3
};

我无法理解为什么&lt;&lt; 无法编译,我该如何解决?

enum kViewControllerAnchoredGesture: NSInteger {
    case None     = 0
    case Panning  = 1 << 0
    case Tapping  = 1 << 1
    case Custom   = 1 << 2
    case Disabled = 1 << 3
}

提前致谢!

3 个答案:

答案 0 :(得分:4)

首先:

let viewController = UIViewController()
viewController.edgesForExtendedLayout = .Bottom | .Top
if viewController.edgesForExtendedLayout & .Bottom == .Bottom {
    println("got it!")
}

第二

使用Swift RawOptionSetType代替NS_OPTIONS。 我找不到官方指南,但这里有一篇很好的文章:http://nshipster.com/rawoptionsettype/

答案 1 :(得分:1)

在示例1中,结果表达式不是boolean。使用

    if (viewController.edgesForExtendedLayout & .Bottom == .Bottom) {
        println("got it!")
    }

答案 2 :(得分:1)

if条件的结果在一秒内不符合BooleanType ...解决方案:

let viewController = UIViewController()
viewController.edgesForExtendedLayout = .Bottom | .Top
if (viewController.edgesForExtendedLayout & .Bottom) == .Bottom {
   println("got it!")
}

可能有更优雅的语法...

除非您正在进行条件绑定:if let x = optionalX { }所有条件必须符合BooleanType

的条件