【问题标题】:Swift - nil checking an NSCopying function argumentSwift - nil 检查 NSCopying 函数参数
【发布时间】:2014-11-19 04:14:52
【问题描述】:

我正在将一些 Obj-C 代码转换为 Swift 并遇到了问题。这是 ObjC 代码:

- (void)collisionBehavior:(UICollisionBehavior *)behavior 
               beganContactForItem:(id<UIDynamicItem>)item 
            withBoundaryIdentifier:(id<NSCopying>)identifier 
                           atPoint:(CGPoint)p {
    NSLog(@"Boundary contact occurred - %@", identifier);
}

这是从UICollisionBehaviorDelegate 实现一个协议方法,这里是 Swift:

func collisionBehavior(behavior: UICollisionBehavior,
  beganContactForItem item: UIDynamicItem,
  withBoundaryIdentifier identifier: NSCopying,
  atPoint p: CGPoint) {

  println("Boundary contact occurred - \(identifier)")
}

如果没有标识符的对象发生冲突,上述操作会失败并显示EXC_BAD_ACCESS。在这种情况下,identifier 的值为 0x0,即它为 nil。

但是,我无法执行如下的 nil 检查:

if identifier != nil {
  println("Boundary contact occurred - \(boundaryName)")
}

因为!= 运算符没有为NSCopying 定义。有谁知道我如何检查 nil,或者是否有我可以执行的“to string”操作在遇到 nil 值时不会失败?

【问题讨论】:

    标签: swift


    【解决方案1】:

    我假设您可以使用文档中记录的相同解决方法 Xcode 6.1 Release Notes 用于返回值被错误地认为不可为空的方法、属性或初始化程序:

    let identOpt : NSCopying? = identifier
    if let ident = identOpt {
    
    }
    

    更好的是,您实际上可以更改方法签名,将NSCopying 替换为NSCopying?

    func collisionBehavior(behavior: UICollisionBehavior,
      beganContactForItem item: UIDynamicItem,
      withBoundaryIdentifier identifier: NSCopying?,
      atPoint p: CGPoint) {
      if let unwrapedIdentifier = identifier {
        println("Boundary contact occurred - \(unwrapedIdentifier)")
      } else {
        println("Boundary contact occurred - (unidentified)")
      }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多