gpt4 book ai didi

swift - 类不符合协议(protocol),但结构符合

转载 作者:搜寻专家 更新时间:2023-10-31 08:28:01 26 4
gpt4 key购买 nike

结构和类都符合协议(protocol)。我使用带有 where 条件的 2 个协议(protocol)扩展来为类和结构添加 var 属性的实现。

我很惊讶地看到只有类的编译错误。

为什么这发生在类而不是结构上?

protocol MyProtocol {
var property:String { get }
}

extension MyProtocol where Self == MyStruct {
var property: String { return "" }
}

extension MyProtocol where Self == MyClass {
var property: String { return "" }
}

struct MyStruct : MyProtocol {}

class MyClass : MyProtocol {} //Type 'MyClass' does not conform to protocol 'MyProtocol'

最佳答案

它不会编译因为你的

extension MyProtocol where Self == MyClass

仅为 MyClass 本身提供默认方法,但不为可能的子类提供默认方法。将约束更改为

extension MyProtocol where Self: MyClass

使代码编译。 或者防止创建子类

final class MyClass : MyProtocol {}

这对 MyStruct 来说不是问题,因为在 Swift 中无法继承结构类型。

关于swift - 类不符合协议(protocol),但结构符合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57689534/

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