Learn Courses My Dashboard

Struct Data Model, updating property on fly

Hi,
It might be basic, but I would like to change value of a property in a struct model on fly

here is an approximate definition of my struct:

enum CharStyle {
    case normal, box, strike, capsule
}



struct JChar : Identifiable, Equatable, Hashable{
    
    var id : UUID = UUID()
    var body : String
    var style : CharStyle = .normal.     // <----- I want this to be settable on fly
    var furigana : String = ""
    private var fontSize : CGFloat = 16
    var width : CGFloat = 0
    var height : CGFloat = 0
    
    
    init(body: String, fontSize : CGFloat? = 16) {
        
        if let fz = fontSize {
            self.fontSize = fz
        }
        
        let font = UIFont.systemFont(ofSize: self.fontSize)
        let attributes = [NSAttributedString.Key.font: font]
        let size = (body as NSString).size(withAttributes: attributes)
        
        self.body = body
        self.width = size.width
        self.height = size.height
    }
    
    
}

then when I execute the following:

let sampleJChar = JChar(body: "Sample")
        sampleJChar.style = .capsule

I receive an error:

I tried to explore like using state or published
but I got errors. I also don’t think @State is correct since my struct is not a view

Thank you in advance

You cannot change the properties of a struct declared as a let value. sampleJChar must be a var instead.

Thanks.