Hello Swift Community. I started a conversation about this on the Using Swift Forum and some of the people there thought it might be a good idea to pitch the idea here.
Allow Property Wrappers with Multiple Arguments to Defer Initialization when wrappedValue is not Specified
- Proposal: SE-NNNNN
- Authors: @Andrew_Arnopoulos
- Review Manager: TBD
- Status: Proposed
Introduction
Swift's Property Wrappers allow for wrappers without arguments to defer specifying the wrappedValue until the initialization of the containing type. This proposal adds this feature to Property Wrappers that have multiple arguments by extending the current initializer synthesization.
Motivation
In the current implementation of Swift if you create a value type with a Property Wrapper that only takes the wrappedValue argument you are able to defer the initialization of the wrappedValue until the initialization of the containing value type. Take the following example:
@propertyWrapper
struct NOOP {
var wrappedValue: Int
}
struct Model {
@NOOP var property: Int
}
Model(property: 5)
The code above will build and run just fine but the following code will not:
@propertyWrapper
struct Argument {
var wrappedValue: Int
var argument: String
}
struct Model {
@Argument(argument: "hello") var property: Int //Error: Missing argument for parameter 'wrappedValue' in call
}
Model(property: 5) //Error: Cannot convert value of type 'Int' to expected argument type 'Argument'
You are able to get around this error by adding the following extension:
@propertyWrapper
struct Argument {
var wrappedValue: Int
var argument: String
}
struct Model {
@Argument var property: Int
}
extension Model {
init(property: Int) {
_property = Argument(wrappedValue: property, argument: "hello")
}
}
Model(property: 5)
This however has several draw backs:
- Instead of defining
Argument
's additional property at the declaration site you the programmer are now doing it manually inside of a custom non-synthesized initializer. This increases the probability of bugs being introduced. - If an framework designer only provides a propertyWrapper they are not able to add these custom initializers for the consumers of their framework.
Proposed solution
I propose that we extend propertyWrapper
's synthesized initializers to support propertyWrapper
s with multiple initializer arguments.
Source compatibility
This change is purely additive and should not affect source compatibility.
Effect on ABI stability
No known effect.
Effect on API resilience
No known effect.