【发布时间】:2016-12-27 19:44:02
【问题描述】:
我正在尝试构建一个公开静态属性的协议,然后在该协议的扩展中使用该静态属性,但它似乎只有在我也在协议扩展中定义此静态属性时才有效。 基本上我要开始工作的代码:
protocol NibInstantiable: class {
static var bundle: Bundle? { get }
static var nibName: String { get }
}
extension NibInstantiable where Self: UIViewController {
// static var nibName: String {
// return ""
// }
static func instantiate() -> Self {
return Self(nibName: Self.nibName, bundle: Self.bundle ?? Bundle.main)
}
}
这曾经在 Swift 2 中基本上按原样工作,但在 Swift 3 中不再是这种情况。我可以通过取消协议扩展中的 nibName 属性的注释来使其工作,但这会抑制编译器警告,如果我忘记在实现此协议的类中定义此属性。
知道我缺少什么吗? 谢谢!
编辑:作为参考,这里是该代码的 Swift 2.3 版本,它编译和工作没有任何问题:
protocol Instantiable {
static var bundle: NSBundle? { get }
static func instantiate() -> Self
}
extension Instantiable {
static var bundle: NSBundle? {
return NSBundle.mainBundle()
}
}
// MARK: With Nib
protocol NibInstantiable: Instantiable {
static var nibName: String { get }
}
extension NibInstantiable where Self: UIViewController {
static func instantiate() -> Self {
return Self(nibName: Self.nibName, bundle: Self.bundle ?? NSBundle.mainBundle())
}
}
【问题讨论】:
-
您确定静态变量
bundle具有String类型吗?尝试添加实际代码,这将有助于我们帮助您解决问题。任何更改都可能引入额外的错误。 -
我的错,类型是
Bundle?(现已修复)。实际上,这里没有比 sn-p 更多的东西。 -
这对我来说似乎是一个错误——编译器认为
UIViewController的nibName实例属性和您的静态nibName属性要求之间存在冲突。请参阅this related bug report - 一个简单的解决方案就是重命名您的静态nibName要求。 -
就是这样,谢谢!不知道为什么另一个答案被删除了,但是如果您想将您的评论转换为答案,我会将其标记为已接受
-
@axelcdv 没问题 :)
标签: swift swift3 swift-extensions