【发布时间】:2021-09-20 01:41:34
【问题描述】:
我为 UnsignedInteger 协议添加了一个扩展,以添加一个以十六进制格式表示数字的十六进制方法。我还希望特定的符合结构具有参数的默认值。下面是我写的。
extension UnsignedInteger {
func hex(withFieldWidth fieldWidth: Int, andUseUppercase uppercase: Bool = true) -> String {
return String(format: "%0\(fieldWidth)\(uppercase ? "X" : "x")", self as! CVarArg)
}
}
extension UnsignedInteger where Self == UInt8 {
func hex(withFieldWidth fieldWidth: Int = 2, andUseUppercase uppercase: Bool = true) -> String {
// should call the UnsignedInteger implementation with the default parameters
return hex(withFieldWidth: fieldWidth, andUseUppercase: uppercase)
}
}
extension UnsignedInteger where Self == UInt16 {
func hex(withFieldWidth fieldWidth: Int = 4, andUseUppercase uppercase: Bool = true) -> String {
// should call the UnsignedInteger implementation with the default parameters
return hex(withFieldWidth: fieldWidth, andUseUppercase: uppercase)
}
}
但是,对于 UInt8 和 UInt16 特定的扩展,它似乎在调用自身而不是第一个扩展块中的十六进制,正如我收到的 UInt8 和 UInt16 块的警告消息所解释的那样:All paths through this function will call itself。
如果我从 UInt8 和 UInt16 块中删除 fieldWidh,调用十六进制(带有fieldWidth 的硬编码值)似乎编译得很好,我相信这种方式是从第一个扩展块调用十六进制方法。下面是编译好的代码。
extension UnsignedInteger {
func hex(withFieldWidth fieldWidth: Int, andUseUppercase uppercase: Bool = true) -> String {
return String(format: "%0\(fieldWidth)\(uppercase ? "X" : "x")", self as! CVarArg)
}
}
extension UnsignedInteger where Self == UInt8 {
func hex(andUseUppercase uppercase: Bool = true) -> String {
// should call the UnsignedInteger implementation with the default parameters
return hex(withFieldWidth: 2, andUseUppercase: uppercase)
}
}
extension UnsignedInteger where Self == UInt16 {
func hex(andUseUppercase uppercase: Bool = true) -> String {
// should call the UnsignedInteger implementation with the default parameters
return hex(withFieldWidth: 4, andUseUppercase: uppercase)
}
}
在进行协议扩展时,有没有办法为特定的符合结构的参数指定默认值?
【问题讨论】:
标签: swift protocols protocol-extension