swift5

Would there be a syntactic sugar -like way in Swift to make a "default member" of a struct (as if "hidden fields" added to a type)?


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.


Solution

  • 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:

    In short, I would advise against adopting StringProtocol yourself.