Michael
Michael

Reputation: 591

Is this the proper way to use the self attribute for a property?

I know that Swift assumes that you are referencing a property or method of the current instance whenever you use a known property or method name; however, I want to make sure I understand the use of self given that it's in heavy use in code prior to Swift.

class School {
  var numberOfBooks = 0
  var numberofPens = 0

  func buyBooks() {
    self.numberOfBooks++
  }

  func buyPens() {
    self.numberOfPens++
  }

  func readyForSchool() {
    if self.numberOfBooks && self.numberOfPens >= 1 {
      println("I am ready for school")
    } else {
      println("I need to buy school materials")
    }
  }
}

var preparedForSchool = School()
preparedForSchool.buyBooks()
preparedForSchool.buyPens()
preparedForSchool.readyForSchool() \\returns "I am ready for school"

Upvotes: 0

Views: 83

Answers (2)

Duncan C
Duncan C

Reputation: 131418

It's reasonable, but I do see one error. This statement

if self.numberOfBooks && self.numberOfPens >= 1

...Is not valid. Swift doesn't let you treat integer values as if they are booleans.

if self.numberOfBooks 

Is not legal, like it is in C. In C, Objective-C, C++, and various other C-like languages, that would be interpreted as `if self.numberOfBooks != 0". Swift forces you to be explicit however. You must write

if self.numberOfBooks != 0

or

if self.numberOfBooks >= 1 && self.numberOfPens >= 1

or

if self.numberOfBooks != 0 && self.numberOfPens >= 1

Upvotes: 1

p0lAris
p0lAris

Reputation: 4820

That's looks just fine (IMO). To get a more reasonable understanding of self in Swift, refer to this question: What is "self" used for in Swift?.

Upvotes: 1

Related Questions