Reputation: 591
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
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
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