You have
typealias Stringish = String
var x: Stringish
func examp() {
x = "yo"
print(x)
}
and you have a zillion Stringish
in your code base. You suddenly realize you need something more like
struct StringBonus {
var value: String
var version: Int
}
typealias Stringish = StringBonus
which is fine but you have to replace "x" everywhere with "x.value", as it were.
x.value = "yo"
print(x.value)
etc etc etc
var x: Stringish = tedious default value
etc etc etc
It would be incredible if you could still refer to x normally,
x = 69
but also access the "hidden" fields,
x.version = 2
Can anyone think of a way to make a struct "default" to one of the fields, or indeed a trick approach that achieves the same result.
I guess the amazing @resultBuilder
would be impressive but I can't see a way to have a free-form resultBuilder inline (where the "x" is).
Maybe someone has a way.
This isn’t quite the answer you are looking for, but you can simplify the initialization of your object using ExpressibleByStringLiteral
:
struct Foo: ExpressibleByStringLiteral {
let value: String
let count: Int
init(value: String, count: Int = 0) {
self.value = value
self.count = count
}
init(stringLiteral value: StringLiteralType) {
self.init(value: value)
}
}
let foo: Foo = "bar"
print(foo) // Foo(value: "bar", count: 0)
print(foo.value) // bar
There is an equivalent ExpressibleByStringInterpolation
(but the implementation is a little more complicated, so I will not go down that rabbit hole).
The above tackles the initialization of your object. But, if we wanted to access the value without referencing the property, theoretically, we could implement our own type that conforms to StringProtocol
, but I would advise against it because:
that has a pretty extensive number of methods that you would need to implement, so that’s a pretty heavy lift;
to my eye, that is for something that is inherently a “string type” (like Substring
is), not just some random model type for which you want to enjoy String
-like behaviors; and
most importantly, Apple explicitly advises against doing so:
Do not declare new conformances to
StringProtocol
.
And when Apple advises against stuff like this, it sometimes is not only “this is generally not a good idea” but “things will break if you do this”.
In short, I would advise against adopting StringProtocol
yourself.