update new articles

This commit is contained in:
numbbbbb
2014-06-09 06:43:49 +08:00
parent 64348d1b2f
commit f29cbb70c4
41 changed files with 374 additions and 64 deletions

View File

@ -46,7 +46,7 @@
<div class="book" data-level="2.11" data-basepath=".." data-revision="1402238318316">
<div class="book" data-level="2.11" data-basepath=".." data-revision="1402267410054">
<div class="book-header">
<!-- Actions Left -->
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
@ -587,6 +587,209 @@
<div class="page-inner">
<section class="normal" id="section-gitbook_28">
<h1 id="-methods-">方法(Methods)</h1>
<p><strong>方法</strong>是与某些特定类型相关联的功能/函数。类、结构体、枚举都可以定义实例方法;实例方法为指定类型的实例封装了特定的任务与功能。类、结构体、枚举也可以定义类(型)方法(type itself)类型方法与类型自身相关联。类型方法与Objective-C中的类方法(class methods)相似。</p>
<p>在Swift中,结构体和枚举能够定义方法事实上这是Swift与C/Objective-C的主要区别之一。在Objective-C中,类是唯一能定义方法的类型。在Swift中你能够选择是否定义一个类/结构体/枚举,并且你仍然享有在你创建的类型(类/结构体/枚举)上定义方法的灵活性。</p>
<h3 id="-instance-methods-">实例方法(Instance Methods)</h3>
<p><strong>实例方法</strong>是某个特定类、结构体或者枚举类型的实例的方法。实例方法支撑实例的功能: 或者提供方法,以访问和修改实例属性;或者提供与实例的目的相关的功能。实例方法的语法与函数完全一致,参考<a href="functions.html" title="函数说明">函数说明</a></p>
<p>实例方法要写在它所属的类型的前后括号之间。实例方法能够访问他所属类型的所有的其他实例方法和属性。实例方法只能被它所属的类的特定实例调用。实例方法不能被孤立于现存的实例而被调用。</p>
<p>下面是定义一个很简单的类<code>Counter</code>的例子(<code>Counter</code>能被用来对一个动作发生的次数进行计数):</p>
<pre><code>class Counter {
var count = 0
func increment() {
count++
}
func incrementBy(amount: Int) {
count += amount
}
func reset() {
count = 0
}
}
</code></pre><p><code>Counter</code>类定理了三个实例方法:</p>
<ul>
<li><code>increment</code>让计数器按一递增;</li>
<li><code>incrementBy(amount: Int)</code>让计数器按一个指定的整数值递增;</li>
<li><code>reset</code>将计数器重置为0。</li>
</ul>
<p><code>Counter</code>这个类还声明了一个可变属性<code>count</code>,用它来保持对当前计数器值的追踪。</p>
<p>和调用属性一样,用点语法(dot syntax)调用实例方法:</p>
<pre><code> let counter = Counter()
// the initial counter value is 0
counter.increment()
// the counter&#39;s value is now 1
counter.incrementBy(5)
// the counter&#39;s value is now 6
counter.reset()
// the counter&#39;s value is now 0
</code></pre><h3 id="-local-and-external-parameter-names-for-methods-">方法的局部参数名称和外部参数名称(Local and External Parameter Names for Methods)</h3>
<p>函数参数有一个局部名称(在函数体内部使用)和一个外部名称(在调用函数时使用),参考<a href="external_parameter_names.html">External Parameter Names</a>。对于方法参数也是这样,因为方法就是函数(只是这个函数与某个类型相关联了)。但是,方法和函数的局部名称和外部名称的默认行为是不一样的。</p>
<p>Swift中的方法和Objective-C中的方法极其相似。像在Objective-C中一样Swift中方法的名称通常用一个介词指向方法的第一个参数比如<code>with</code>,<code>for</code>,<code>by</code>等等。前面的<code>Counter</code>类的例子中<code>incrementBy</code>方法就是这样的。介词的使用让方法在被调用时能像一个句子一样被解读。Swift这种方法命名约定很容易落实,因为它是用不同的默认处理方法参数的方式,而不是用函数参数(来实现的)。</p>
<p>具体来说Swift默认仅给方法的第一个参数名称一个局部参数名称;但是默认同时给第二个和后续的参数名称局部参数名称和外部参数名称。
这个约定与典型的命名和调用约定相匹配这与你在写Objective-C的方法时很相似。这个约定还让expressive method调用不需要再检查/限定参数名。</p>
<p>看看下面这个<code>Counter</code>的替换版本(它定义了一个更复杂的<code>incrementBy</code>方法):</p>
<pre><code>class Counter {
var count: Int = 0
func incrementBy(amount: Int, numberOfTimes: Int) {
count += amount * numberOfTimes
}
}
</code></pre><p><code>incrementBy</code>方法有两个参数: <code>amount</code><code>numberOfTimes</code>。默认地Swift只把<code>amount</code>当作一个局部名称,但是把<code>numberOfTimes</code>即看作本地名称又看作外部名称。下面调用这个方法:</p>
<pre><code>let counter = Counter()
counter.incrementBy(5, numberOfTimes: 3)
// counter value is now 15
</code></pre><p>你不必为第一个参数值再定义一个外部变量名:因为从函数名<code>incrementBy</code>已经能很清楚地看出它的目的/作用。但是第二个参数,就要被一个外部参数名称所限定,以便在方法被调用时让他目的/作用明确。</p>
<p>这种默认的行为能够有效的检查方法比如你在参数numberOfTimes前写了个井号( <code>#</code> )时:</p>
<pre><code>func incrementBy(amount: Int, #numberOfTimes: Int) {
count += amount * numberOfTimes
}
</code></pre><p>这种默认行为使上面代码意味着在Swift中定义方法使用了与Objective-C同样的语法风格并且方法将以自然表达式的方式被调用。</p>
<h3 id="-modifying-external-parameter-name-behavior-for-methods-">修改外部参数名称(Modifying External Parameter Name Behavior for Methods)</h3>
<p>有时为方法的第一个参数提供一个外部参数名称是非常有用的,尽管这不是默认的行为。你可以自己添加一个明确的外部名称;你也可以用一个hash符号作为第一个参数的前缀然后用这个局部名字作为外部名字。</p>
<p>相反,如果你不想为方法的第二个及后续的参数提供一个外部名称,你可以通过使用下划线(<code>_</code>)作为该参数的显式外部名称来覆盖默认行为。</p>
<h3 id="-self-the-self-property-"><code>self</code>属性(The self Property)</h3>
<p>类型的每一个实例都有一个隐含属性叫做<code>self</code>,它完全等同于这个实力变量本身。你可以在一个实例的实例方法中使用这个隐含的<code>self</code>属性来引用当前实例。</p>
<p>上面例子中的<code>increment</code>方法可以被写成这样:</p>
<pre><code>func increment() {
self.count++
}
</code></pre><p>实际上,你不必在你的代码里面经常写<code>self</code>。不论何时,在一个方法中使用一个已知的属性或者方法名称,如果你没有明确的写<code>self</code>Swift假定你是指当前实例的属性或者方法。这种假定在上面的<code>Counter</code>中已经示范了:<code>Counter</code>中的三个实例方法中都使用的是<code>count</code>(而不是<code>self.count</code>)</p>
<p>这条规则的主要例外发生在当实例方法的某个参数名称与实例的某个属性名称相同时。
在这种情况下,参数名称享有优先权,并且在引用属性时必须使用一种更恰当(被限定更严格)的方式。
你可以使用隐藏的<code>self</code>属性来区分参数名称和属性名称。</p>
<p>下面的例子演示了<code>self</code>消除方法参数<code>x</code>和实例属性<code>x</code>之间的歧义:</p>
<pre><code>struct Point {
var x = 0.0, y = 0.0
func isToTheRightOfX(x: Double) -&gt; Bool {
return self.x &gt; x
}
}
let somePoint = Point(x: 4.0, y: 5.0)
if somePoint.isToTheRightOfX(1.0) {
println(&quot;This point is to the right of the line where x == 1.0&quot;)
}
// prints &quot;This point is to the right of the line where x == 1.0&quot;
</code></pre><p>如果不使用<code>self</code>前缀Swift就认为两次使用的<code>x</code>都指的是名称为<code>x</code>的函数参数。</p>
<h3 id="-modifying-value-types-from-within-instance-methods-">在实例方法中修改值类型(Modifying Value Types from Within Instance Methods)</h3>
<p>结构体和枚举是<strong>值类型</strong><a href="&quot;#&quot;">Structures and Enumerations Are Value Types</a>。一般情况下,值类型的属性不能在他的实例方法中被修改。</p>
<p>但是,如果你确实需要在某个具体的方法中修改结构体或者枚举的属性,你可以选择<code>变异(mutating)</code>这个方法。方法可以从内部变异它的属性;并且它做的任何改变在方法结束时都会回写到原始结构。方法会给它隐含的<code>self</code>属性赋值一个全新的实例,这个新实例在方法结束后将替换原来的实例。</p>
<p><code>变异</code>方法, 将关键字<code>mutating</code> 放到方法的<code>func</code>关键字之前就可以了:</p>
<pre><code>struct Point {
var x = 0.0, y = 0.0
mutating func moveByX(deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
}
}
var somePoint = Point(x: 1.0, y: 1.0)
somePoint.moveByX(2.0, y: 3.0)
println(&quot;The point is now at (\(somePoint.x), \(somePoint.y))&quot;)
// prints &quot;The point is now at (3.0, 4.0)&quot;
</code></pre><p>上面的Point结构体定义了一个变异方法(mutating method)<code>moveByX</code><code>moveByX</code>用来移动一个point。<code>moveByX</code>方法在被调用时修改了这个point,而不是返回一个新的point。方法定义是加上那个了<code>mutating</code>关键字,所以方法可以修改值类型的属性了。</p>
<p>注意:不能在结构体类型的常量上调用变异方法,因为常量的属性不能被改变,就算你想改变的是常量的可变属性也不行,参考<a href="&quot;#&quot;">Stored Properties of Constant Structure Instances</a></p>
<pre><code>let fixedPoint = Point(x: 3.0, y: 3.0)
fixedPoint.moveByX(2.0, y: 3.0)
// this will report an error
</code></pre><h3 id="-self-assigning-to-self-within-a-mutating-method-">在变异方法中给self赋值(Assigning to self Within a Mutating Method)</h3>
<p>变异方法能够赋给隐含属性<code>self</code>一个全新的实例。上面<code>Point</code>的例子可以用下面的方式改写:</p>
<pre><code>struct Point {
var x = 0.0, y = 0.0
mutating func moveByX(deltaX: Double, y deltaY: Double) {
self = Point(x: x + deltaX, y: y + deltaY)
}
}
</code></pre><p>新版的变异方法<code>moveByX</code>创建了一个新的分支结构(他的x和y的值都被设定为目标值了)。调用这个版本的方法和调用上个版本的最终结果是一样的。</p>
<p>枚举的变异方法可以让<code>self</code>从相同的枚举设置为不同的成员。</p>
<pre><code>enum TriStateSwitch {
case Off, Low, High
mutating func next() {
switch self {
case Off:
self = Low
case Low:
self = High
case High:
self = Off
}
}
}
var ovenLight = TriStateSwitch.Low
ovenLight.next()
// ovenLight is now equal to .High
ovenLight.next()
// ovenLight is now equal to .Off
</code></pre><p>上面的例子中定义了一个三态开关的枚举。每次调用<code>next</code>方法时,开关在不同的电源状态(<code>Off</code>,<code>Low</code>,<code>High</code>)之前循环切换。</p>
<h3 id="-type-methods-">类型方法(Type Methods)</h3>
<p>实例方法是被类型的某个实例调用的方法。你也可以定义类列本身调用的方法,这种方法就叫做<strong>类型方法</strong>。声明类的类型方法,在方法的<code>func</code>关键字之前加上关键字<code>class</code>;声明结构体和枚举的类型方法,在方法的<code>func</code>关键字之前加上关键字<code>static</code></p>
<blockquote>
<p>注意:</p>
<p>在Objective-C里面你只能为Objective-C的类定义类型方法(type-level methods)。在Swift中你可以为所有的类、结构体和枚举定义类型方法Each type method is explicitly scoped to the type it supports.</p>
</blockquote>
<p>类型方法和实例方法一样用点语法调用。但是你是在类型上调用这个方法而不是在实例上调用。下面是如何在SomeClass类上调用类型方法的例子</p>
<pre><code>class SomeClass {
class func someTypeMethod() {
// type method implementation goes here
}
}
SomeClass.someTypeMethod()
</code></pre><p>在类型方法的方法体(body)中,<code>self</code>指向这个类型本身,而不是类型的某个实例。对于结构体和枚举来说,这意味着你可以用<code>self</code>来消除静态属性和静态方法参数之间的二意性(类似于我们在前面处理实例属性和实例方法参数时做的那样)。</p>
<p>一般地,在类型方法里面所使用的任何未限定的方法和属性名称,将会指向其他的类型级别的方法和属性。一个类型方法可以用另一个类型方法的名称调用踏,而无需在方法名称前面加上类型名称的前缀。同样,结构体和枚举的类型方法也能够直接通过静态属性的名称访问静态属性,而不需要类型名称前缀。</p>
<p>下面的例子定义了一个名为<code>LevelTracker</code>结构体。它监测玩家的发展情况(游戏的不同层次或阶段)。这是一个单人游戏,但也可以用作多玩家游戏中单个设备上的信息存储。</p>
<p>游戏初始时,所有的游戏等级(除了等级1)都被锁定。每次有玩家完成一个等级,这个等级就对这个设备上的所有玩家解锁。<code>LevelTracker</code>结构体用静态属性和方法监测游戏的哪个等级已经被解锁。他还监测每个玩家的当前等级。</p>
<pre><code>struct LevelTracker {
static var highestUnlockedLevel = 1
static func unlockLevel(level: Int) {
if level &gt; highestUnlockedLevel { highestUnlockedLevel = level }
}
static func levelIsUnlocked(level: Int) -&gt; Bool {
return level &lt;= highestUnlockedLevel
}
var currentLevel = 1
mutating func advanceToLevel(level: Int) -&gt; Bool {
if LevelTracker.levelIsUnlocked(level) {
currentLevel = level
return true
} else {
return false
}
}
}
</code></pre><p><code>LevelTracker</code>监测玩家的已解锁的最高等级。这个值被存储在静态属性<code>highestUnlockedLevel</code>中。</p>
<p><code>LevelTracker</code>还定义了两个类型方法与<code>highestUnlockedLevel</code>配合工作。第一个类型方法是<code>unlockLevel</code>:一旦新等级被解锁,它会更新<code>highestUnlockedLevel</code>的值。第二个类型方法是<code>levelIsUnlocked</code>:如果某个给定的等级已经被解锁,他返回<code>true</code>。(注意:我们没用使用<code>LevelTracker.highestUnlockedLevel</code>,这个类型方法还是能够访问静态属性<code>highestUnlockedLevel</code>)</p>
<p>除了静态属性和类型方法,<code>LevelTracker</code>还监测每个玩家的进度。它用实例属性<code>currentLevel</code>来监测玩家当前正在进行的等级。</p>
<p>为了便于管理<code>currentLevel</code>属性,<code>LevelTracker</code>定义了实例方法<code>advanceToLevel</code>。这个方法会在更新<code>currentLevel</code>之前检查所请求的新等级是否已经解锁。<code>advanceToLevel</code>方法返回布尔值以指示是否确实能够设置<code>currentLevel</code>了。</p>
<p>下面,<code>Player</code>类使用<code>LevelTracker</code>来监测和更新每个玩家的发展进度:</p>
<pre><code>class Player {
var tracker = LevelTracker()
let playerName: String
func completedLevel(level: Int) {
LevelTracker.unlockLevel(level + 1)
tracker.advanceToLevel(level + 1)
}
init(name: String) {
playerName = name
}
}
</code></pre><p><code>Player</code>类创建一个新的<code>LevelTracker</code>实例来检测这个用户的发展进度。他提供了<code>completedLevel</code>方法:一旦玩家完成某个指定等级就调用它。这个方法为所有玩家解锁下一等级,并且将当前玩家的进度更新为下一等级。(我们忽略了<code>advanceToLevel</code>返回的布尔值,因为之前调用<code>LevelTracker.unlockLevel</code>时就知道了这个等级已经被解锁了)</p>
<p>你还可以为一个新的玩家创建一个<code>Player</code>的实例,然后看这个玩家完成等级一时发生了什么:</p>
<pre><code>var player = Player(name: &quot;Argyrios&quot;)
player.completedLevel(1)
println(&quot;highest unlocked level is now \(LevelTracker.highestUnlockedLevel)&quot;)
// prints &quot;highest unlocked level is now 2&quot;
</code></pre><p>如果你创建了第二个玩家,并尝试让他开始一个没有被任何玩家解锁的等级,你试图去设置玩家当前等级时会失败的:</p>
<pre><code>player = Player(name: &quot;Beto&quot;)
if player.tracker.advanceToLevel(6) {
println(&quot;player is now on level 6&quot;)
} else {
println(&quot;level 6 has not yet been unlocked&quot;)
}
// prints &quot;level 6 has not yet been unlocked&quot;
</code></pre>
</section>
</div>
</div>
</div>