Search code examples
swiftvarlet

How to mute the warning of "never mutated" in Swift?


Regarding duplicate flag: This question is different from the flagged question as I am asking about how to mute the warnings as I was not aware of the concept of Swift. The provided below answer helps me understand the very basic nature of Swift. Thus this question should not flagged as duplicate.


I have a class name Person having following variables.

private var _id:String = ""
var id:String {
    get {
        return _id
    }
    set (newId) {
        _id = newId
    }
}

private var _name:String = ""
var name:String {
    get {
        return _name
    }
    set (newName) {
        _name = newName
    }
}

private var _signedDate:Date? = nil
var signedDate:Date {
    get {
        return _signedDate!
    }
    set(newDate) {
        _signedDate = newDate
    }
}

These private var's are going to update with a setter.

So while creating an object for the Person class, I am writing this code.

var p1 = Person()
p1.id = "1"
p1.name = "Hemang"

array.append(p1)

Maybe later, I will update the value of signedDate with a setter.

So I should not create this object with let.

However, it's showing me this warning:

Variable 'p1' was never mutated; consider changing to 'let' constant.

How to mute this warning?

Please let me know if you need more information on this.


Solution

  • Because actually you don't change the Person object, With let you can change the properties of the object. But you can't change the object it self.

    So change your code to what the warning lead you.

    And of course you can try before asking this question.