Swift - nil检查NSCopying函数参数

Col*_*inE 3 swift

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

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

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

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

  println("Boundary contact occurred - \(identifier)")
}
Run Code Online (Sandbox Code Playgroud)

EXC_BAD_ACCESS如果没有标识符的对象发生冲突,则上述操作失败.在这种情况下identifier有一个值0x0,即它是零.

但是,我不能执行如下的零检查:

if identifier != nil {
  println("Boundary contact occurred - \(boundaryName)")
}
Run Code Online (Sandbox Code Playgroud)

因为!=运营商没有定义NSCopying.有没有人知道我如何检查nil,或者是否有一个'to string'操作我可以执行它遇到nil值时不会失败?

Mar*_*n R 8

我假设您可以使用Xcode 6.1发行说明中记录的方法,属性或初始值设定项的相同解决 方法,其返回值被错误地视为不可为空:

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

}
Run Code Online (Sandbox Code Playgroud)

更好的是你可以实际更改方法签名替换NSCopyingNSCopying?:

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)")
  }
}
Run Code Online (Sandbox Code Playgroud)