如何允许能够转换为字符串的类型的通用功能
我正在尝试使用通用函数使用类型(在我的特殊情况下,浮点和ints)可以从字符串创建。
我注意到两种类型(INT和Float)都有类似的初始方法: float:
@inlinable public init?<S>(_ text: S) where S : StringProtocol
int:
@inlinable public init?<S>(_ text: S, radix: Int = 10) where S : StringProtocol
所以我想创建一个协议:
protocol StringConvertable {
init?<S>(_ text: S) where S : StringProtocol
}
所以我可以使两种类型符合它们:
extension Float:StringConvertable { }
extension Int:StringConvertable { }
并在我的功能中使用它们:
static func readColum<T:StringConvertable>(row:[String:String], rowIndex:Int, columnName:String) -> T? {
令我惊讶的是,这不会编译,因为int
没有符合协议,是因为radix
参数,哪个是可选的?!?
有没有更好的方法来创建一个可以从String
创建的组类型的协议,似乎有点代码气味,并且可能我在这里缺少一些东西。
谢谢
I'm trying to use a generic function uses types (in my particular case Floats and Ints ) which are able to be created from a string.
I've noticed that both types (Int and Float) have similar init methods:
Float:
@inlinable public init?<S>(_ text: S) where S : StringProtocol
Int:
@inlinable public init?<S>(_ text: S, radix: Int = 10) where S : StringProtocol
So I thought to create a protocol:
protocol StringConvertable {
init?<S>(_ text: S) where S : StringProtocol
}
So I can make both types to conform them:
extension Float:StringConvertable { }
extension Int:StringConvertable { }
And use them in my function:
static func readColum<T:StringConvertable>(row:[String:String], rowIndex:Int, columnName:String) -> T? {
To my surprise, this doesn't compile because Int
doesn't conform the protocol, is that because of the radix
parameter, which is optional?!?
Is there a better way to do this, creating a protocol to group types that can be created from String
, seems a bit code smell and probably I'm missing something here.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论