迭代NSObject设置为某种类型

问题描述 投票:1回答:2

我有一个接收Set<NSObject>的函数,我需要迭代该集合作为Set<UITouch>。我究竟如何测试并打开套装?

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {

    for touch in touches {
        // ...
    }

}
swift casting
2个回答
2
投票

使用as运算符执行type casting

for touch in touches {
    if let aTouch = touch as? UITouch {
         // do something with aTouch
    } else {
         // touch is not an UITouch
    }
}

3
投票

通常,您将使用条件转换来检查每个元素的类型。但在这里,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中的“轻量级通用”),因此不再需要演员表。

© www.soinside.com 2019 - 2024. All rights reserved.