如何允许能够转换为字符串的类型的通用功能

发布于 2025-01-30 17:23:21 字数 906 浏览 0 评论 0原文

我正在尝试使用通用函数使用类型(在我的特殊情况下,浮点和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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文