Search code examples
iosswiftswiftuiproperty-wrapper

Are Swift Property Wrappers attributes?


Using a propertyWrapperseems to have the same syntax as attribute. For instance, compare this custom propertyWrapper:

@propertyWrapper
struct Capitalize {
    private var value: String = ""
    
    var wrappedValue: String {
        get { return value.capitalized }
        set {
            value = newValue }
        
    }
    
    init(wrappedValue: String) {
        self.value = wrappedValue
    }
}

and when using it:

@Capitalize
var myProperty: String = "hello world"

Compare this to attributessuch as @IBOutlet or @available or even @propertyWrapper which are basically compiler information: they look the same. So my question is: Are propertyWrappers attributes or are they considered separare?

As mention above, propertyWrappers make use of an attribute: @propertyWrapper. But is the wrapper itself an attribute?

My own take on this is that this part:

@propertyWrapper
struct Capitalize {
    private var value: String = ""
...

is called propertWrapper, which creates your very own attribute to use on any property.

So, that would make this the attribute:

@Capitalize


Solution

  • Yes, property wrappers are attributes. If we consult the Swift grammar, we find this production:

    attribute@ attribute-name attribute-argument-clause?

    And that is the only @ in the grammar. So anything that starts with an @ (and is otherwise valid syntax) is, according to Swift's definitions, an “attribute”.

    You can read more in the “Attributes” section of The Swift Programming Language.