Some times, when creating a new type using struct, I would like the code to be able to treat the instance as though it were a primitive variable (such as an Int, Double, etc.). For example:
var inst = SomeStructType()
inst = 5
print( inst ) // Output: 5
Note that I am not specifying any property or method fields after the name. SomeStructType would simply have a special getter/setting working at the type level that says "anytime you see an instance of this type by itself, use the appropriate getter or setter in the struct to obtain or store data.
Something like this:
struct TypeName [[ optional protocols ]] -> Type
{
get { code to fetch a value for SomeStructType instance }
set( newVal ) { code to set the instance value }
regular struct property and method declarations
}
Note that the "-> Type" clause would specify the type of an instance variable and trigger the need for the get/set entries at the beginning of the type declaration.
Of course, the question is now does one access the regular properties and methods from an instance identifier?
Something like inst.fieldname is ambiguous because inst could be returning some struct, enum, or class value that has a fieldname property. You could add additional syntax to the struct (after the get and set items), but I think I like the following syntax better:
inst.self.fieldname
This would naturally extend the concept of getters and setters to types, as well as properties.
Of course, if there is some other way to achieve this that I'm not aware of, I'd love to hear about it.
Not sure if I understand correctly, but if it's something like where the getter retrieves the value from some storage and the setter writes the new value back to storage, then as @Danny and @vanvoorden mentioned @propertyWrapper is what you want.
More examples of what you want to type/see, rather than an idea of how it might be achieved, might be helpful if this all did not answer your questions yet.
The wrappers wrap wrappedValue, not the variable which forwards it along. The variables do not, themselves, need to be properties, though they can be. The documentation unfortunately conflates these ideas, which may be the source of your confusion.
This is why wrappers can be used on parameters—the parameters are not "wrapped". The parameters are alternate ways to access properties of wrapper instances—those properties are the "wrapped" ones.
This looks a very similar to what I tried to pitch a while back. I think it's the same but with a different syntax. Object Wrappers (not implying any sort of plagarisim). And I remember someone pitching ExpressibleBy*. And a while back newtype was proposed. Maybe we should come up with a unionized name for this.