0

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"
Kevlar
  • 8,804
  • 9
  • 55
  • 81
Michael
  • 573
  • 7
  • 24

2 Answers2

1

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?.

Community
  • 1
  • 1
p0lAris
  • 4,750
  • 8
  • 45
  • 80
1

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
Duncan C
  • 128,072
  • 22
  • 173
  • 272