Search code examples
objective-cswiftenumstranslate

How to translate this enum from objective-c to swift?


I don't understand why & and << don't work in Swift. Please help me to translate objective-c code examples to Swift.

Example 1

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

I'am trying to translate it in Swift but got an error

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

Example 2

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

Here I can't understand why << doesn't compile, how can I fix it?

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

Thanks in advance!


Solution

  • First:

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

    Second:

    In Swift RawOptionSetType is used instead of NS_OPTIONS. There no official guide I could find, but here is a nice into article: http://nshipster.com/rawoptionsettype/