swift - 搜索与特定类型匹配的对象

标签 swift macos cocoa

我有一个 NSViewController 扩展,它遍历其所有后代 subview Controller ,寻找第一个通过特定测试(由用户定义的 block 指定)的 View Controller :

extension NSViewController {

    func descendantViewControllerPassingTest(test: (viewController: NSViewController) -> Bool) -> NSViewController? {
        var retval: NSViewController?
        for childViewController in childViewControllers {
            if test(viewController: childViewController) {
                retval = childViewController
            } else if let descendantViewController = viewController.descendantViewControllerPassingTest(test)  {
                retval = descendantViewController
            }
            if retval != nil { break }
        }
        return retval
    }
}

99% 的时间我的测试包括一个简单的类型检查...

contentViewController.descendantViewControllerPassingTest {$0 is OutlineViewController}

...所以我想创建一个简短的便利扩展来执行此操作:

extension NSViewController {
    func descendantViewControllerMatchingType(type: WHAT_HERE?) {
        return descendantViewControllerPassingTest({ $0 is WHAT_HERE? })
    }
}

但我不知道我的参数type 应该是什么type。我试过 AnyClassAnyObject 但编译器告诉我这些不是类型:

enter image description here

最佳答案

Closures是我会用的。将您的对象传递给返回类型为 BOOL 的闭包。使用闭包以递归方式匹配您的后代。

关于swift - 搜索与特定类型匹配的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38223485/

相关文章:

c - GNU/Linux下获取fgetc处理Mac OS CR

python - 用于 python 或其他编程语言的 Mac 词典到文档工具提示

cocoa - 在模态 NSWindow 中使用 WebView 不起作用?

objective-c - 如何在背景窗口上设置 [NSTextView selectedTextAttributes]?

swift - CocoaPods use_frameworks!原因 "Class X is implemented in both Y and Z"

ios - Swift UITest 无法访问呈现的 viewController 的 View 按钮

swift - 在 Swift 3 中制作下拉列表

ios - 计数对象解析 Swift + tableView 部分

c - 在 Swift 中格式化 Linphone SDK 的路径时出现问题

macos - 苹果电脑 : Saving information to file without modifying date stamp