Does a protocol exist that determines a type should be initializable with a String?

◇◆丶佛笑我妖孽 提交于 2019-12-12 11:33:32

问题


I have written the following code to assist converting text values from form fields into expected values:

protocol StringConvertableValueType {
    init?(_ string: String)
}

extension Int: StringConvertableValueType {
}

extension String: StringConvertableValueType {
}

extension Double: StringConvertableValueType {
}

extension Float: StringConvertableValueType {
}

As you see all of these primitive types support the same initializer by themselves already. However pouring over the documentation I cannot find any shared protocol that does this. Though it feels like I'm re-doing something that's already done by the people that built Foundation.

Does some kind of protocol already exist that takes care of this, or the people that built Foundation just made sure the API was really consistent but there's no protocol that enforces it?


回答1:


I believe what you're looking for is LosslessStringConvertible. Int inherits this from FixedWidthInteger. This transient protocol inheritance doesn't show up in the docs for conforming types. (That can be confusing, and if it's given you trouble you may want to open a radar to expand the docs.)



来源:https://stackoverflow.com/questions/55709921/does-a-protocol-exist-that-determines-a-type-should-be-initializable-with-a-stri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!