【发布时间】:2019-11-13 10:56:23
【问题描述】:
我有一个应用程序可以处理需要在表单中显示的大量可选数据
<Latest value formatted (units)> || "never updated"
很明显我的代码充满了类似的东西:
var pressureString: String {
(self.lastData != nil) ?
String(format: "%.2f kPa", self.lastData!.pressure.doubleValue)
:
Constants.neverUpdated // NSLocalizedString
}
所以我决定试着用这个来整理一下:
var pressureString: String {
(self.lastData?.pressure.doubleValue).format("%.2f kPa", or: Constants.neverUpdated)
}
并写format为:
extension Optional {
func format(_ formatString: String, or: String) -> String {
if let s = self {
return String(format: formatString, s)
} else {
return or
}
}
}
但是,我收到错误“参数类型 'Wrapped' 不符合预期的类型 'CVarArg'”,在 https://developer.apple.com/documentation/swift/cvararg 查找文档时,我看到了
为定义的类型声明符合 CVarArg 协议 不支持标准库之外的。
...那么有任何方法来格式化通用Wrapped吗?
【问题讨论】: