我正在将一些Obj代码转换为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,即为零。
但是,我不能按以下方式执行零检查:
if identifier != nil {
println("Boundary contact occurred - \(boundaryName)")
}因为!=运算符不是为NSCopying定义的。有谁知道我如何检查零,或者是否有一个'to string‘操作,当它遇到一个零值时,我可以执行这个操作不会失败?
发布于 2014-11-18 14:09:00
我假设您可以对返回值被错误地视为非空的方法、属性或初始化器使用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)")
}
}https://stackoverflow.com/questions/26995918
复制相似问题