gpt4 book ai didi

Swift 协议(protocol)强制 Equatable 协议(protocol)

转载 作者:搜寻专家 更新时间:2023-10-31 19:31:12 30 4
gpt4 key购买 nike

我已经定义了 2 个协议(protocol)。我需要第一个 (NameProtocol) 来执行 Equatable 协议(protocol)。而另一个类 (BuilderProtocol) 有一个返回第一个类 (NameProtocol) 的方法。

public protocol NameProtocol : Equatable {
var name: String { get }
}

public protocol BuilderProtocol {
func build() -> NameProtocol? // Compiler error
init()
}

编译错误:“协议(protocol) 'NameProtocol' 只能用作泛型约束,因为它具有 Self 或关联类型要求”

我需要build()返回的对象返回一个符合NameProtocol的对象,我可以在上面定义==

我有什么办法可以让这项工作成功吗?

谢谢


如果在 BuilderProtocol 中使用类型别名,我怎样才能使数组声明起作用?

public protocol OtherRelatedProtocol {
var allNames : Array<NameProtocol> { get }
}

结论

我将删除 Equatable 并实现一个 isEqual 方法。

public protocol NameProtocol {
func isEqual(nameable: NameProtocol) -> Bool
var name: String { get }
}

最佳答案

如果您熟悉 Java 或 C#,就会发现 Swift 协议(protocol)大约介于泛型和接口(interface)之间。例如,您可以在协议(protocol)中做的一件事是:

protocol Foo {
func compareWith(foo: Self)
}

实现这个协议(protocol)的类将有一个方法compareWith接受一个对象他们自己的类型(而不是Foo类型的对象).

这就是编译器所说的“Self 或关联类型要求”,这就是 Equatable 的定义方式(它需要一个 operator== 来接受两个 Self 操作数).但是,这些协议(protocol)的缺点是您只能将它们用作通用约束:不能将它们用作表达式类型。

解决方案是使用泛型。在这种情况下,您可以使您的 ProtocolBuilder 协议(protocol)通用,并限制该类型实现 NameProtocol

public protocol NameProtocol : Equatable {
var name: String { get }
}

public protocol BuilderProtocol {
typealias T: NameProtocol
func build() -> T?
init()
}

关于Swift 协议(protocol)强制 Equatable 协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29838263/

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