[Swift] Currently, propertyWrapper cannot use Japanese for variable names.

Swift can use Japanese, emoji, and quite a lot of other characters in variable names. So I explained various things to acquaintances who are not good at English with variables of Japanese names, but since it became clear that "property Wrapper cannot use Japanese", I will share it.

The environment is Swift 5.3.

Experiment

Actually it happened while playing with Swift UI, but in the end the problem is property Wrapper, so it's the same. First, declare a simple wrapper and a structure that uses it. The point is the variable name "value".

@propertyWrapper
struct MyWrapper<T>{
    let wrappedValue: T
    let projectedValue: T

    init(wrappedValue value: T){
        self.wrappedValue = value
        self.projectedValue = value
    }
}

struct MyValue{
    @MyWrapper var value= 10

    func print(){
        //This is ok
        Swift.print(self._value)
        //Error: '$' is not an identifier; use backticks to escape it
        //Error: Value of type 'Value' has no member '$'
        Swift.print(self.$value)
    }
}

When I try to use projectedValue," $" causes some trouble and an error occurs. If you do not use it, no error will occur.

trial and error

At first, he said, "If it's not good to start with a Japanese name, it's okay to add an underscore," but it didn't work.

    func print(){
        Swift.print(self._value)
        Swift.print(self.__value)
        //Cannot find 'value' in scope
        Swift.print(self.$_value) 
    }

I changed my mind and added a, saying," Underscore is a special symbol, so it's certainly not good. ", But it didn't work.

    func print(){
        Swift.print(self.a value)
        Swift.print(self._a value)
        //Cannot find 'value' in scope
        Swift.print(self.$a value)
    }

After that, I repeated trial and error, but the conclusion was that ** it was useless if even one character was included **. This is a restriction that applies to almost all characters except alphanumeric characters, not limited to Japanese.

Cause

There is no particular restriction that these characters cannot be used as the characters after $. Developer Forums pointed out that it seems to be a compiler bug.

It seems that the bug itself has been fixed in this PR, but as of Swift 5.3, the fix has not been included yet, and it seems that it will be fixed in a future release. It's been a while since I was patient.

Recommended Posts

[Swift] Currently, propertyWrapper cannot use Japanese for variable names.
[Swift / Beginner] Use Enum for maintainable coding