Home > Software design >  PropertyWrapper initialization with custom type initialization
PropertyWrapper initialization with custom type initialization

Time:02-05

I want propertyWrapper initialization with custom type initialization, here is my propertyWrapper:

@propertyWrapper struct Round {

    var roundDigits: Int
    var wrappedValue: Double
    
    var projectedValue: String? {
        get { return String(format: "%0.\(roundDigits)f", wrappedValue) }
    }

    init(wrappedValue: Double, roundDigits: Int) {
        self.wrappedValue = wrappedValue
        self.roundDigits = roundDigits
    }

    init(roundDigits: Int) {
        self.wrappedValue = 0
        self.roundDigits = roundDigits
    }
 
}

and this is my struct:

I cannot make the this part build because i am using self before initialization. How can I solve this issue?

struct CustomType {

    var name: String
    var roundDigits: Int
    // I want use roundDigits for feeding @Round
    @Round(roundDigits: 2) var value: Double

    init(name: String, roundDigits: Int, value: Double) {
        self.name = name
        self.roundDigits = roundDigits
        self.value = value
    // some other work that must be done here ...
    }

}

finally this is my use case:

let test: CustomType = CustomType(name: "Hello", roundDigits: 4, value: Double.pi)
print(test.name, test.$value!)

let test2: CustomType = CustomType(name: "World", roundDigits: 6, value: Double.pi)
print(test2.name, test2.$value!)

CodePudding user response:

One solution is to have a property of type Round in CustomType that is declared as a normal property

struct CustomType {
    var name: String
    var value: Round

And then initialize it by injecting a Round instance or creating it in the init

init(name: String, value: Round) {
    self.name = name
    self.value = value
}

init(name: String, roundDigits: Int, value: Double) {
    self.name = name
    self.value = Round(wrappedValue: value, roundDigits:  roundDigits)
}
  •  Tags:  
  • Related