Swift 如何解决CustomStringConvertible的重叠一致性
基于John Sundell的这一点,我有以下结构:Swift 如何解决CustomStringConvertible的重叠一致性,swift,swift-protocols,customstringconvertible,Swift,Swift Protocols,Customstringconvertible,基于John Sundell的这一点,我有以下结构: protocol Identifiable { associatedtype RawIdentifier: Codable, Hashable = String var id: Identifier<Self> { get } } struct Identifier<Value: Identifiable>: Hashable { let rawValue: Value.RawIdentif
protocol Identifiable {
associatedtype RawIdentifier: Codable, Hashable = String
var id: Identifier<Self> { get }
}
struct Identifier<Value: Identifiable>: Hashable {
let rawValue: Value.RawIdentifier
init(stringLiteral value: Value.RawIdentifier) {
rawValue = value
}
}
extension Identifier: ExpressibleByIntegerLiteral
where Value.RawIdentifier == Int {
typealias IntegerLiteralType = Int
init(integerLiteral value: IntegerLiteralType) {
rawValue = value
}
}
问题是,它只适用于符合CustomStringConverable的扩展,而忽略了另一个扩展。我不能将一致性添加到另一个扩展中,因为它们会重叠
print(Identifier<A>(stringLiteral: "string")) // prints "string"
print(Identifier<B>(integerLiteral: 5)) // prints "Identifier<B>(rawValue: 5)"
您可以使用一个CustomStringConvertible扩展名,而不是目前使用的两个,无论其类型如何:
extension Identifier: CustomStringConvertible {
var description: String {
"\(rawValue)"
}
}
对于我来说,按照上一个代码示例,这将正确打印字符串5
这恰好是Sundell在其可识别/标识符的开源身份实现中所做的-
Point Free的“标记”实现也值得一看以供参考:一切正常,问题是您正在打印对象,not values try let obj1=IdentifierstringLiteral:string let obj2=IdentifierintegerLiteral:5 printobj1.description printobj2.description这就是CustomStringConvertible背后的理念-将任何类型的任何实例转换为字符串。检查第一次打印。这正是我想要的。如果我删除CustomStringValue,它将打印IdentifierrawValue:string。你的建议正是我想要避免的。。。同样基于文档,不鼓励直接访问描述。
extension Identifier: CustomStringConvertible {
var description: String {
"\(rawValue)"
}
}