Ho do I get correct object using generic for a Type?

Could give me some advice? thx

let someVC = splitViewController.splitViewItemViewController(type: SomeViewController.self)

extension NSSplitViewController {
    public func splitViewItemViewController<T>(for type: T.Type) -> T? {
         *  error:
         *  Cannot find type 'type' in scope
         *  Type of expression is ambiguous without more context
        return splitViewItems.first { $0.viewController is type }

You're conflating static and dynamic types in this case: the type variable you pass as argument in the splitViewItemViewController function is dynamic and available only on runtime, while the is operator can only accept statically available types. You can solve your issue by using the dynamic type(of:) function:

func splitViewItemViewController<T>(for controllerType: T.Type) -> T? {
   return splitViewItems.first { type(of: $0.viewController) == controllerType } as? T

@xAlien95 thx. It works.

Terms of Service

Privacy Policy

Cookie Policy