【问题标题】:Access static property of protocol extension访问协议扩展的静态属性
【发布时间】: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 更多的东西。
  • 这对我来说似乎是一个错误——编译器认为UIViewControllernibName 实例属性和您的静态nibName 属性要求之间存在冲突。请参阅this related bug report - 一个简单的解决方案就是重命名您的静态 nibName 要求。
  • 就是这样,谢谢!不知道为什么另一个答案被删除了,但是如果您想将您的评论转换为答案,我会将其标记为已接受
  • @axelcdv 没问题 :)

标签: swift swift3 swift-extensions


【解决方案1】:

这对我来说似乎是一个错误(参见相关错误报告SR-2992)——编译器认为UIViewControllernibName 实例属性和您的NibInstantiable 协议的nibName 静态属性之间存在冲突要求。一个更简单的可重现示例是:

protocol Foo {
    static var bar : String { get }
}

class Bar {
    var bar = "" // commenting out this line allows the code to compile
}

extension Foo where Self : Bar {
    static func qux() {
        print(bar) // compiler error: Instance member 'bar' cannot be used on type 'Self'
    }
}

一个简单的解决方法是重命名协议的 nibName 静态属性要求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-02
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    • 2016-01-27
    • 1970-01-01
    相关资源
    最近更新 更多