【问题标题】:How to translate this enum from objective-c to swift?如何将此枚举从objective-c转换为swift?
【发布时间】:2015-02-14 12:05:20
【问题描述】:

我不明白为什么 & 在 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
};

这里我不明白为什么无法编译,我该如何解决?

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

提前致谢!

【问题讨论】:

  • 您也可以尝试设置正确的值而不进行位移。 IE。 0、1、2、4、8、16

标签: objective-c swift enums translate


【解决方案1】:

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

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

【讨论】:

  • UIRectEdge 符合 RawOptionSetType 这意味着您可以使用&amp; ...但结果必须与 UIRectEdge.None 或 nil 进行比较:if viewController.edgesForExtendedLayout &amp; .Bottom != nil { ... } 。跨度>
  • 正确,@MartinR。更新了答案。
  • 不知道这是怎么回事!
  • let kp = 1
  • 对不起。以为我已经测试过了,但显然没有编译它。已删除该部分。
【解决方案2】:

第一:

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

第二:

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

【讨论】:

    【解决方案3】:

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

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

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

    除非你在做条件绑定:if let x = optionalX { } all if 条件必须导致符合BooleanType的东西

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      相关资源
      最近更新 更多