0

我遇到了一个我不理解的有趣行为。这是产生这种行为的代码:

import UIKit

protocol UIViewNibLoading {
    static var nibName: String { get }
}

extension UIView : UIViewNibLoading {

    static var nibName: String {
        return String(describing: self)
    }

}

extension UIViewNibLoading where Self : UIView {

    static func loadFromNib<T: UIViewNibLoading>() -> T {
        print(T.nibName)
        print(nibName)
        return UINib(nibName: nibName, bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! T
        // CRASH: return UINib(nibName: T.nibName, bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! T
    }

}

这是执行此代码时控制台的输出:

UIView
MyCustomViewSubclass

当我在我的自定义类上调用 thenloadFromNib方法时。它会产生两种不同的行为,具体取决于我如何获得nibName.

  1. T.nibName:返回字符串UIView
  2. nibName:返回字符串MyCustomViewSubclass

你知道这里发生了什么吗?为什么在运行selfT不是同一个对象?这是我发现的另一件有趣的事情。当您将断点放入nibNamegetter 时,您可以在调试器中看到以下内容:

T.nibName: T.nibName nibName: 笔尖名称

这被称为:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == WidgetAddTableViewController.SectionIndexRecent {
        return WidgetAddHeaderView.loadFromNib()
    } else if section == WidgetAddTableViewController.SectionIndexFreeAndPremium {
        return WidgetAddFilterHeaderView.loadFromNib()
    }
    return nil
}

感谢您的任何解释。

4

1 回答 1

1

self在运行时解决。T在编译时解决。因此,在编译时,您的代码行为如下:

let returnValue: UIView? = WidgetAddHeaderView.loadFromNib()
return returnValue

loadFromNib对其返回类型是通用的。鉴于此代码,唯一有效的返回类型是UIView. 同样,这是在 compile-time决定的。

self另一方面,只是一个变量。这是一个非常特殊的变量,但它实际上只是一个变量。它具有运行时值。所以type(of: self)在运行时评估。动态调度是在运行时处理的。

错误是您并不是真的要返回“一些符合 UIViewNibLoading 的未知 T”(这就是您所说的通过使返回类型泛型返回的内容)。您要返回的是Self静态函数所属的类(在编译时确定)。所以你这样说:

extension UIViewNibLoading where Self : UIView {

    static func loadFromNib() -> Self {
        print(nibName)
        return UINib(nibName: nibName, bundle: nil)
            .instantiate(withOwner: nil, options: nil)[0] as! Self
    }   
}

或者你可以承诺更少(因为你的来电者实际上并不关心)并这样做:

extension UIViewNibLoading where Self : UIView {

    static func loadFromNib() -> UIView {
        print(nibName)
        return UINib(nibName: nibName, bundle: nil)
            .instantiate(withOwner: nil, options: nil)[0]
    }
}

但是没有理由让这个方法通用,正如你所见,它实际上伤害了你。

于 2018-05-24T18:58:44.747 回答