0
下面的代码工作:我可以使用具有指定关联类型的协议吗?
protocol GenericStorage {
associatedtype Value
func store(value: Value)
}
protocol DataStorage {
func store(value: Data)
}
struct StringStorage: GenericStorage {
typealias Value = String
let wrapped: DataStorage
func convert(_ str: String) -> Data {
return Data(str.utf8)
}
func store(value: String) {
wrapped.store(value: convert(value))
}
}
我可以以完全避免冗余DataStorage
协议使用GenericStorage
协议与相关联的类型的Data
为wrapped
论点StringStorage
?
我希望类似如下的代码(不工作):
protocol GenericStorage {
associatedtype Value
func store(value: Value)
}
struct StringStorage: GenericStorage {
typealias Value = String
let wrapped: GenericStorage where Value = Data
func convert(_ str: String) -> Data {
return Data(str.utf8)
}
func store(value: String) {
wrapped.store(value: convert(value))
}
}
没有更多的上下文,它很难给你一个确切的解决方案,因为很难判断你想要什么'wrapped.store(value:convert(value))'来做什么。但是,如果您删除typealias,'wrapped'声明并将'store'定义为'func store(value:String){convert(value) }',那么您的代码编译完全正常。但是从你的问题来看,'StringStorage'中'store'应该做什么并不是很清楚,我不知道这是你真正想要的。 –
@DávidPásztor我想要一个类型为'GenericStorage'的包装器,它调用另一个'GenericStorage'上的方法,尽管'Value'的实际关联类型可能不同。我对语言细节感兴趣。 – Max
为了一般工作,您需要提供'store'函数(可能是一个通用函数)的默认实现,否则编译器如何通过调用该类型的函数来推断您的意思是什么你之前没有指定符合'GenericStorage'。 –