我有一个接收Set<NSObject>
的函数,我需要迭代该集合作为Set<UITouch>
。我究竟如何测试并打开套装?
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch in touches {
// ...
}
}
使用as运算符执行type casting:
for touch in touches {
if let aTouch = touch as? UITouch {
// do something with aTouch
} else {
// touch is not an UITouch
}
}
通常,您将使用条件转换来检查每个元素的类型。但在这里,touches
参数是documented as
一组
UITouch
实例,表示在事件表示的事件期间移动的触摸。
因此你可以强制施放整个集合:
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch in touches as! Set<UITouch> {
// ...
}
}
请注意,在Swift 2中,函数声明已更改为
func touchesMoved(_ touches: Set<UITouch>, withEvent event: UIEvent?)
(由于Objective-C中的“轻量级通用”),因此不再需要演员表。