Swift-nil checks the argument to the NSCopying function

I am converting Obj-C code to Swift and got into a problem. Here's the ObjC code:

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

      

This implements the protocol method from UICollisionBehaviorDelegate

, and here is Swift:

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

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

      

The above fails with EXC_BAD_ACCESS

if a collision occurs for an object with no identifier. In this case, identifier

it matters 0x0

, that is, it is nil.

However, I cannot perform a nil check like this:

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

      

Since no operator !=

is defined for NSCopying

. Does anyone know how I can check for null, or is there a "string" operation that I can perform that doesn't fail when it encounters a null value?

+3


source to share


1 answer


I assume you can use the same workaround described in the Xcode 6.1 Release Notes for methods, properties, or initializers for which an invalid return value is considered invalid:

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

}

      



Better yet, you can change the replacement labels instead NSCopying

to 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)")
  }
}

      

+8


source







All Articles