如何使用Generic作为参数并返回特定对象而不进行强制转换?

时间:2016-10-14 09:36:04

标签: swift generics swift3

当我输入特定的类时,函数是否可以返回特定的对象。 我的问题: 我不知道如何归还物体。看一下代码,谢谢

class MyViewControler {     }

class MySplitViewController: NSSplitViewControler {
    override func viewDidLoad() {
        /* 
         * get specific object 
         */
        let vc = viewController(for: MyViewControler.self)
    }
}

extension NSSplitViewController {

    public func viewController<T>(for anClass: T) -> T.object {

        guard let tClass = anClass as? AnyClass else { return nil }
        var vc: NSViewController?
        if let idx = self.splitViewItems.index(where: { $0.viewController.classForCoder == tClass} ) {
            vc = self.splitViewItems[idx].viewController
        }
    }
    /*
     * I don't know how to return a specific object 
     */
    return vc
}

1 个答案:

答案 0 :(得分:1)

采取类型并返回的方法的签名 (可选)该类型的实例将是:

public func viewController<T>(for aClass: T.Type) -> T?

或者,如果您想将其限制为NSViewController的子类:

public func viewController<T: NSViewController>(for aClass: T.Type) -> T?

使用可选绑定可以简化实现:

extension NSSplitViewController {
    public func viewController<T: NSViewController>(for aClass: T.Type) -> T? {
        for item in self.splitViewItems {
            if let vc = item.viewController as? T {
                return vc
            }
        }
        return nil
    }
}

或者作为“一线”:

extension NSSplitViewController {
    public func viewController<T: NSViewController>(for aClass: T.Type) -> T? {
        return self.splitViewItems.lazy.flatMap { $0.viewController as? T }.first
    }
}