我有一个函数,它接收到Set<NSObject>
,我需要遍历集合作为Set<UITouch>
。我如何测试这个并解开这个集合?NSObject设置为特定类型
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch in touches {
// ...
}
}
我有一个函数,它接收到Set<NSObject>
,我需要遍历集合作为Set<UITouch>
。我如何测试这个并解开这个集合?NSObject设置为特定类型
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch in touches {
// ...
}
}
使用的运营商进行type casting:
for touch in touches {
if let aTouch = touch as? UITouch {
// do something with aTouch
} else {
// touch is not an UITouch
}
}
通常你会使用条件铸检查每个元素 其类型。但在这里,touches
参数是 documented 作为
一组
UITouch
实例表示由事件代表的事件期间移动 的触摸。
因此您可以强制铸造整套:
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch in touches as! Set<UITouch> {
// ...
}
}
注意,在斯威夫特2函数声明改为
func touchesMoved(_ touches: Set<UITouch>, withEvent event: UIEvent?)
(由于“轻量仿制药”在Objective-C中),以便不再需要演员。
准确地说,在这种情况下,你可以“承受”一种力量。你的代码将是安全的。 –