-3

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.

Hemang
  • 26,840
  • 19
  • 119
  • 186

1 Answers1

-2

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.

hamed
  • 91
  • 5
  • Thanks, Hamed, you have cleared a deep doubt of Swift to me. I thought we can't change the member variables of a constant object of a class. – Hemang Apr 30 '17 at 07:10
  • 1
    @Hemang You can't change the properties of a constant struct, but you can for a class as long as you don't change the reference itself (that is, you can change any of the object's properties but you can't point it to a different object). That's one of the differences between value types and reference types. – John Montgomery Apr 30 '17 at 08:27