使用关联类型和自身的Swift协议?
根据本协议:使用关联类型和自身的Swift协议?,swift,Swift,根据本协议: protocol SomeProtocol { associatedtype MyCustomType static func someCustomStaticFunction(with customTypeData: MyCustomType) -> Self? } 为什么会这样: extension MyClass: SomeProtocol { static func someCustomStaticFunction(with custom
protocol SomeProtocol {
associatedtype MyCustomType
static func someCustomStaticFunction(with customTypeData: MyCustomType) -> Self?
}
为什么会这样:
extension MyClass: SomeProtocol {
static func someCustomStaticFunction(with customTypeData: MyCustomType) -> Self? {
return MyClass()
}
}
不编译?错误是:无法将“MyClass”类型的返回表达式转换为返回类型“Self”
。这到底为什么不管用?如果不是这样,那么一开始使用Swift还有什么意义呢?如果我不能建立类型安全协议,而我被迫将其全部删除,那又有什么意义呢?有人能帮我吗
编辑:
问题不是相关类型,而是返回
Self?
您需要将MyClass
设置为final,并将MyClass
扩展中返回的Self
替换为MyClass
protocol SomeProtocol {
static func someCustomStaticFunction() -> Self?
}
final class MyClass {
}
extension MyClass: SomeProtocol {
static func someCustomStaticFunction() -> MyClass? {
return MyClass()
}
}
Self
,不能使用类扩展MyClass
设置为final。如果没有,假设您有一个名为MySubclass
的子类,它还必须确认将SomeProtocol
作为其父类。因此MySubclass
必须具有someCustomStaticFunction()->MySubclass
。但是,MyClass
已经实现了此函数,但返回类型不同。Swift目前不支持重载返回类型,因此,我们不能子类MyClass
,这是最终的您需要将
MyClass
设置为final,并将MyClass
中返回的Self
扩展名更改为MyClass
可能会在协议中创建一个必需的初始值设定项,并调用该初始值设定项,以便在派生MyClass的情况下返回Self。这在@ukim!你可以把答案贴出来,我会接受的。如果您知道为什么会这样,并且可以提供一个解释,那也太好了:)似乎问题与关联类型无关。如果你愿意,你可以编辑这个问题。