自Swift 2(3?)以来,"正确的方式"从任何旧对象获取文本输出是使用.description
。我想在通用函数中使用.description
:
func checkNumeric<T>(_ value: T) -> Bool {
let nf = NumberFormatter()
nf.numberStyle = .decimal
return (nf.number(from:value.description) != nil)
}
但这不起作用,因为T不支持.description
(恕我直言,这是一件非常糟糕的事情)。无论如何,有没有办法做到这一点?有CustomStringConvertible
但没有StringConvertible
,我似乎无法找到其他相似内容。
是的,我知道我可以制作自己的协议并使用扩展程序添加类。但是,此函数的整点是为了避免必须知道并列出可能进入函数的每个可能的类。
答案 0 :(得分:3)
断言T
必须是任何CustomStringConvertible
,这会在.description
上公开T
属性。
func checkNumeric<T>(_ value: T) -> Bool
where T: CustomStringConvertible {
let nf = NumberFormatter()
nf.numberStyle = .decimal
return (nf.number(from:value.description) != nil)
}
如果要使用description属性创建自己的类,只需确保它们符合CustomStringConvertible
。然后就不需要创建自己的协议并扩展可能使用或不使用的每个类。