Frankie
Frankie

Reputation: 185

Variable declaration with underscore

I have seen this in some videos on Youtube.

class Student {

    private var _name: String!
    private var _studentID: Int!

    var name: String {
        return _name
    }

    var studentID:Int {
        return _studentID
    }

    init(name: String, studentID: Int) {
        self._name = name
        self._studentID = studentID
    }
}

Any reason why they are doing this (adding _name and _studentID) instead of:

class Student {

    private var name: String!
    private var studentID: Int!

    init(name: String, studentID: Int) {
        self.name = name
        self.studentID = studentID
    }
}

Thank you very much.

Upvotes: 3

Views: 1391

Answers (1)

rmaddy
rmaddy

Reputation: 318794

The first examples are essentially creating properties that are publicly readable but privately writable.

The second set of code does not do the same thing as the first set.

The proper way to write this code is:

private (set) var name: String // no need for the !
private (set) var studentID: Int // no need for the !

init(name: String, studentID: Int) {
    self.name = name
    self.studentID = studentID
}

This makes the properties readable by outside users but only settable by the class. This is what the 1st set of code implements but in a much more verbose and needless manner.

The use of underscore is just a naming convention carried over from Objective-C when creating private instance variables.

Personally, I'd avoid videos and tutorials that use the 1st set of code.

Upvotes: 6

Related Questions