准备好迎接 Swift 3.0 API 变化

398183216 8年前
   <p>据 Chris Lattner 所说,即将发布的 Swift 3 将在我们熟悉的 Cocoa 和 CocoaTouch 上做出重大改变。</p>    <blockquote>     <p>在 Swift 3 中, <code>.blackColor()</code> 变成了 <code>.black()</code>。</p>    </blockquote>    <p>这一变化包含在将 Objective-C API 转化成 Swift 的提案 <a href="/misc/goto?guid=4958973399623768393" rel="external">SE-0005</a> 中。由于属性名结尾的单词和属性类型已经包含了足够的信息,因此可以删掉 <code>Color</code>:</p>    <pre>  <code class="language-swift">  class func darkGrayColor() -> UIColor  // 因此  foregroundColor = .darkGrayColor()  // 变成了  foregroundColor = .darkGray()</code></pre>    <p>我简单总结了几条简化规则。记住,如果以下规则(进行简化)产生了一个不合法的结果(空的<code>selector</code>、<code>Swift</code>关键字等),那就不必遵循该规则。</p>    <p><strong>简化 #1</strong>:去除相同类型成员前边的类型名称:</p>    <pre>  <code class="language-swift">let c = myColor.colorWithAlphaComponent(0.5)  // 变为  let c = myColor.withAlphaComponent(0.5)</code></pre>    <p><strong>简化 #2</strong>:如果类型名后是 <em>by</em> + 现在分词 动名词 形式,则将 “by” 一同去掉。</p>    <pre>  <code class="language-swift">  let img = myImage.imageByApplyingOrientation(o)  // 变为  let img = myImage.applyingOrientation(o)</code></pre>    <p> </p>    <p><strong>简化 #3</strong>:当方法选择器中含有类型名并满足以下情况时,去掉类型名称:</p>    <table>     <thead>      <tr>       <th>尾部位于:</th>       <th>需精简部分:</th>      </tr>     </thead>     <tbody>      <tr>       <td>引入参数的选择器</td>       <td>参数类型名</td>      </tr>      <tr>       <td>属性名称</td>       <td>属性类型名</td>      </tr>      <tr>       <td>无参方法名</td>       <td>返回类型名</td>      </tr>     </tbody>    </table>    <pre>  <code class="language-swift">  documentForURL(_ url: NSURL)  var parentContext: NSManagedObjectContext?  class func darkGrayColor() -> UIColor  // 变为  documentFor(_ url: NSURL)  var parent: NSManagedObjectContext?  class func darkGray() -> UIColor</code></pre>    <p><strong>简化 #4</strong>:去掉方法名中动词后的类型名:</p>    <pre>  <code class="language-swift">  myVC.dismissViewControllerAnimated(...)  // 变为  myVC.dismissAnimated(...)</code></pre>    <p> </p>    <p>来自:http://swift.gg/2016/05/03/preparing-for-3-0-api-pruning/</p>