Swift协议static成员:class实现方法可行属性报错原因咨询
问题解答
问题1:协议中static方法为何可用class方法实现?
可正常运行示例
protocol SomeProtocol { static func someMethod() } class SomeType: SomeProtocol { class func someMethod() { print("someMethod called") } } SomeType.someMethod() // 输出"someMethod called"
原因很直接:Swift里协议用static定义的类型方法,核心要求是实现方提供属于类型本身的方法,并不强制限制方法是否可被子类重写。类中的class方法是可重写的类型方法,static方法是不可重写的类型方法——两者都满足协议对“类型方法”的约定,所以编译器允许用class方法来实现协议里的static方法。
问题2:协议中static属性为何不能用class属性实现?
编译报错示例
报错信息:Class stored properties not supported in classes; did you mean 'static'?
protocol SomeAnotherProtocol { static var someProperty: Int { get set } } class SomeAnotherType: SomeAnotherProtocol { class var someProperty: Int = 10 // 错误:Class stored properties not supported in classes; did you mean 'static'? } SomeAnotherType.someProperty
问题出在Swift的语法限制上:类不允许用class修饰存储属性,class关键字只能用来修饰类的计算属性(存储属性涉及内存分配,子类重写存储属性会引发内存布局冲突,Swift从设计上禁止了这种操作)。
协议里的static var { get set }要求的是可读写的类型属性,如果你想用class实现,只能写成计算属性的形式:
class SomeAnotherType: SomeAnotherProtocol { class var someProperty: Int { get { return 10 } set { /* 这里实现set逻辑 */ } } }
如果是存储属性,只能用static修饰——static存储属性是属于类本身的不可重写类型属性,这是Swift允许的语法。你示例中的错误本质是class不能修饰存储属性,和协议的static要求无关,只是刚好协议要求的是类型属性,而你用了不被允许的class存储属性写法。
内容的提问来源于stack exchange,提问作者Roshan Sah
相关产品推荐
相关产品推荐

