iOS 8 Programming Fundamentals with Swift
Swift, Xcode, and Cocoa Basics
Move into iOS development by getting a firm grasp of its fundamentals, including the Xcode IDE, the Cocoa Touch framework, and Swift—Apple’s new programming language. With this thoroughly updated guide, you’ll learn Swift’s object-oriented concepts, understand how to use Apple’s development tools, and discover how Cocoa provides the underlying functionality iOS apps need to have.
|
self
An instance is an object, and an object is the recipient of messages. Thus, an instance
needs a way of sending a message to itself. This is made possible by the magic word self.
This word can be used wherever the name of an instance is expected (an instance of the
appropriate type, that is).
For example, let’s say I want to keep the thing that a Dog says when it barks — namely
"woof” — in a property. Then in my implementation of bark I need to refer to that
property. I can do it like this:
class Dog {
var name = ""
var whatADogSays = "woof"
func bark() {
println(self.whatADogSays)
}
}
Similarly, let’s say I want to write an instance method speak which is merely a synonym
for bark. My speak implementation can consist of simply calling my own bark method. I
can do it like this:
class Dog {
var name = ""
var whatADogSays = "woof"
func bark() {
println(self.whatADogSays)
}
func speak() {
self.bark()
}
}
Observe that the term self in that example appears only in instance methods. When an
instance’s code says self, it is referring to this instance. If the expression self.name
appears in a Dog instance method’s code, it means the name of this Dog instance, the one
whose code is running at that moment.
It turns out that every use of the word self I’ve just illustrated is completely optional. You
can omit it and all the same things will happen:
class Dog {
var name = ""
var whatADogSays = "woof"
func bark() {
println(whatADogSays)
}
func speak() {
bark()
}
}
The reason is that if you omit the message recipient and the message you’re sending can
be sent to self, the compiler supplies self as the message’s recipient under the hood.
However, I never do that (except by mistake). As a matter of style, I like to be explicit in
my use of self. I find code that omits self harder to read and understand. And there are
situations where you must say self, so I prefer to use it whenever I’m allowed to use it.
http://shop.oreilly.com/product/0636920034278.do
沒有留言:
張貼留言
歡迎網友的交流與分享,謝謝。