0

I am very new to SWIFT and the following code is throwing an error

struct defaultIni{
    var name:String
    init() {
        name="default"
    }
}

defaultIni().name="hello"

but the following doesn't give any error

struct defaultIni{
    var name:String
    init() {
        name="default"
    }
}

//defaultIni().name="hello"
var def=defaultIni()
def.name
def.name="chsktg"

Any help is appreciated. Thank you

sumanth kumar
  • 21
  • 1
  • 4
  • 1
    Think about what your code `defaultIni().name="hello"` is doing. The part on the left `defaultIni()` calls the initializer for the defaultIni struct. You don't provide any storage for that instance, so it gets created as let constant on the stack. You then try to assign a new name to this let constant, which fails because constants are immutable. If your assignment worked, the newly created struct would be discarded at the next statement since you didn't provide any place to store it. By contrast, when you say `var def=defaultIni()`, you create a **variable** of that type, which is mutable. – Duncan C Jul 23 '23 at 12:36

0 Answers0