skip to Main Content

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

2

Answers


  1. Attributes provide metadata about a program construct and give the compiler additional information or directives for compilation. Some commonly used attributes are @available, @discardableResult, @IBAction, and @IBOutlet.

    They don’t contain business logic like property wrappers. Instead, they annotate code elements to affect their behavior or provide hints to the compiler.

    For example, @IBOutlet is an attribute that tells the compiler that a property is an "Interface Builder outlet", enabling you to connect it to Interface Builder.

    So while property wrappers are declared using an attribute (@propertyWrapper), they themselves are not considered attributes. They are a way to create custom behaviors around property access, whereas attributes are more like annotations for the compiler.

    So mainly

    Property Wrappers are more like templates for how to manage the getting and setting of a property value. They encapsulate behavior and can be reused.

    On the other hand

    Attributes provide additional metadata or directives to the compiler but don’t encapsulate behavior in the same way property wrappers do.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search