Reputation: 9858
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?
Upvotes: 5
Views: 206
Reputation: 299365
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.)
Upvotes: 7