gpt4 book ai didi

swift - 访问协议(protocol)扩展的静态属性

转载 作者:行者123 更新时间:2023-11-28 06:27:50 25 4
gpt4 key购买 nike

我正在尝试构建一个暴露静态属性的协议(protocol),然后在该协议(protocol)的扩展中使用该静态属性,但它似乎只有在我也在协议(protocol)扩展中定义该静态属性时才有效。基本上我要开始工作的代码:

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 中不再如此。我可以通过取消注释协议(protocol)扩展中的 nibName 属性来让它工作,但是如果我忘记在实现此协议(protocol)的类中定义此属性,将会抑制编译器警告。

知道我错过了什么吗?谢谢!

编辑:作为引用,这里是该代码的 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())
}
}

最佳答案

这对我来说像是一个错误(参见相关错误报告 SR-2992 )——编译器认为 UIViewControllernibName 之间存在冲突实例属性和您的 NibInstantiable 协议(protocol)的 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'
}
}

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

关于swift - 访问协议(protocol)扩展的静态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41329940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com