773 lines
33 KiB
HTML
773 lines
33 KiB
HTML
<!DOCTYPE HTML>
|
||
<html lang="en-US" manifest="../manifest.appcache">
|
||
|
||
<head prefix="og: http://ogp.me/ns# book: http://ogp.me/ns/book#">
|
||
|
||
|
||
<meta charset="UTF-8">
|
||
<title>Swift 初见 | Swift 编程语言</title>
|
||
|
||
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
||
<meta name="robots" content="index, follow">
|
||
<meta name="author" content="">
|
||
<meta name="description" content="Swift 是苹果在 WWDC 2014 上发布的一款全新的编程语言,本书译自苹果官方的 Swift 教程《The Swift Programming Language》。">
|
||
<meta name="keywords" content="gitbook,github" >
|
||
<meta name="generator" content="www.gitbook.io">
|
||
|
||
|
||
<link rel="next" href="../chapter2/the_basics.html" />
|
||
|
||
|
||
<link rel="prev" href="../chapter1/swift.html" />
|
||
|
||
|
||
<meta property="og:title" content="Swift 初见 | Swift 编程语言">
|
||
<meta property="og:site_name" content="Swift 编程语言">
|
||
<meta property="og:type" content="book">
|
||
<meta property="og:locale" content="en_US">
|
||
|
||
<meta property="book:author" content="https://github.com/">
|
||
<meta property="book:tag" content="GitBook">
|
||
|
||
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
|
||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||
<meta name="apple-mobile-web-app-status-bar-style" content="black">
|
||
|
||
<link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">
|
||
|
||
|
||
</head>
|
||
<body>
|
||
|
||
|
||
|
||
<link rel="stylesheet" href="../gitbook/style.css">
|
||
|
||
|
||
|
||
|
||
<div class="book" data-level="1.2" data-basepath=".." data-revision="1401881908280">
|
||
<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>
|
||
|
||
<a href="https://github.com/null" target="_blank" class="btn pull-left home-bookmark" aria-label="GitHub home"><i class="fa fa-bookmark-o"></i></a>
|
||
|
||
<a href="#" class="btn pull-left toggle-search" aria-label="Toggle search"><i class="fa fa-search"></i></a>
|
||
<span id="font-settings-wrapper">
|
||
<a href="#" class="btn pull-left toggle-font-settings" aria-label="Toggle font settings"><i class="fa fa-font"></i>
|
||
</a>
|
||
<div class="dropdown-menu font-settings">
|
||
<div class="dropdown-caret">
|
||
<span class="caret-outer"></span>
|
||
<span class="caret-inner"></span>
|
||
</div>
|
||
|
||
<div class="btn-group btn-block">
|
||
<button id="reduce-font-size" class="btn btn-default">A</button>
|
||
<button id="enlarge-font-size" class="btn btn-default">A</button>
|
||
</div>
|
||
|
||
<ul class="list-group font-family-list">
|
||
<li class="list-group-item" data-font="0">Serif</li>
|
||
<li class="list-group-item" data-font="1">Sans</li>
|
||
</ul>
|
||
|
||
<div class="btn-group btn-group-xs btn-block color-theme-list">
|
||
<button type="button" class="btn btn-default" id="color-theme-preview-0" data-theme="0">White</button>
|
||
<button type="button" class="btn btn-default" id="color-theme-preview-1" data-theme="1">Sepia</button>
|
||
<button type="button" class="btn btn-default" id="color-theme-preview-2" data-theme="2">Night</button>
|
||
</div>
|
||
</div>
|
||
|
||
</span>
|
||
|
||
<!-- Actions Right -->
|
||
|
||
<a href="#" target="_blank" class="btn pull-right google-plus-sharing-link sharing-link" data-sharing="google-plus" aria-label="Share on Google Plus"><i class="fa fa-google-plus"></i></a>
|
||
|
||
|
||
<a href="#" target="_blank" class="btn pull-right facebook-sharing-link sharing-link" data-sharing="facebook" aria-label="Share on Facebook"><i class="fa fa-facebook"></i></a>
|
||
|
||
|
||
<a href="#" target="_blank" class="btn pull-right twitter-sharing-link sharing-link" data-sharing="twitter" aria-label="Share on Twitter"><i class="fa fa-twitter"></i></a>
|
||
|
||
|
||
|
||
|
||
<!-- Title -->
|
||
<h1>
|
||
<i class="fa fa-spinner fa-spin"></i>
|
||
<a href="../" >Swift 编程语言</a>
|
||
</h1>
|
||
</div>
|
||
|
||
|
||
|
||
<div class="book-summary">
|
||
<div class="book-search">
|
||
<input type="text" placeholder="Search" class="form-control" />
|
||
</div>
|
||
<ul class="summary">
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
<li data-level="0" data-path="index.html">
|
||
<a href="../"><i class="fa fa-check"></i> Introduction</a>
|
||
</li>
|
||
|
||
|
||
<li class="chapter " data-level="1" data-path="chapter1/README.html">
|
||
|
||
<a href="../chapter1/README.html">
|
||
<i class="fa fa-check"></i> <b>1.</b> 欢迎使用 Swift
|
||
</a>
|
||
|
||
|
||
<ul class="articles">
|
||
|
||
|
||
<li class="chapter " data-level="1.1" data-path="chapter1/swift.html">
|
||
|
||
<a href="../chapter1/swift.html">
|
||
<i class="fa fa-check"></i> <b>1.1.</b> 关于 Swift
|
||
</a>
|
||
|
||
|
||
</li>
|
||
|
||
<li class="chapter " data-level="1.2" data-path="chapter1/a_swift_tour.html">
|
||
|
||
<a href="../chapter1/a_swift_tour.html">
|
||
<i class="fa fa-check"></i> <b>1.2.</b> Swift 初见
|
||
</a>
|
||
|
||
|
||
</li>
|
||
|
||
|
||
</ul>
|
||
|
||
</li>
|
||
|
||
<li class="chapter " data-level="2" data-path="chapter2/the_basics.html">
|
||
|
||
<a href="../chapter2/the_basics.html">
|
||
<i class="fa fa-check"></i> <b>2.</b> Swift 教程
|
||
</a>
|
||
|
||
|
||
<ul class="articles">
|
||
|
||
|
||
<li class="chapter " data-level="2.1" data-path="chapter2/article_1.html">
|
||
|
||
<a href="../chapter2/article_1.html">
|
||
<i class="fa fa-check"></i> <b>2.1.</b> 基础部分
|
||
</a>
|
||
|
||
|
||
</li>
|
||
|
||
|
||
</ul>
|
||
|
||
</li>
|
||
|
||
|
||
|
||
|
||
<li class="divider"></li>
|
||
<li>
|
||
<a href="http://www.gitbook.io/" target="blank" class="gitbook-link">Generated using GitBook</a>
|
||
</li>
|
||
|
||
</ul>
|
||
</div>
|
||
|
||
<div class="book-body">
|
||
<div class="body-inner">
|
||
<div class="page-wrapper" tabindex="-1">
|
||
<div class="book-progress">
|
||
<div class="bar">
|
||
<div class="inner" style="width: 60%;min-width: 40%;"></div>
|
||
</div>
|
||
<div class="chapters">
|
||
|
||
<a href="../index.html" title="Introduction" class="chapter done new-chapter" data-progress="0" style="left: 0%;"></a>
|
||
|
||
<a href="../chapter1/README.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 20%;"></a>
|
||
|
||
<a href="../chapter1/swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 40%;"></a>
|
||
|
||
<a href="../chapter1/a_swift_tour.html" title="Swift 初见" class="chapter done " data-progress="1.2" style="left: 60%;"></a>
|
||
|
||
<a href="../chapter2/the_basics.html" title="Swift 教程" class="chapter new-chapter" data-progress="2" style="left: 80%;"></a>
|
||
|
||
<a href="../chapter2/article_1.html" title="基础部分" class="chapter " data-progress="2.1" style="left: 100%;"></a>
|
||
|
||
</div>
|
||
</div>
|
||
|
||
<div class="page-inner">
|
||
|
||
<section class="normal" id="section-gitbook_142">
|
||
|
||
<h1 id="swift-">Swift 初见</h1>
|
||
<p>通常来说,编程语言教程中的第一个程序应该在屏幕上打印“Hello, world”。在 Swift 中,可以用一行代码实现:</p>
|
||
<pre><code>println("hello, world")
|
||
</code></pre><p>如果你写过 C 或者 Objective-C 代码,那你应该很熟悉这种形式——在 Swift 中,这行代码就是一个完整的程序。你不需要为了输入输出或者字符串处理导入一个单独的库。全局作用域中的代码会被自动当做程序的入口点,所以你也不需要<code>main</code>函数。你同样不需要在每个语句结尾写上分号。</p>
|
||
<p>这个教程会通过一系列编程例子来让你对 Swift 有初步了解,如果你有什么不理解的地方也不用担心——任何本章介绍的内容都会在后面的章节中详细讲解。</p>
|
||
<blockquote>
|
||
<p>注意:为了获得最好的体验,在 Xcode 当中使用代码预览功能。代码预览功能可以让你编辑代码并实时看到运行结果。</p>
|
||
</blockquote>
|
||
<h2 id="-">简单值</h2>
|
||
<p>使用<code>let</code>来声明常量,使用<code>var</code>来声明变量。一个常量的值在编译时并不需要获取,但是你只能为它赋值一次。也就是说你可以用常量来表示这样一个值:你只需要决定一次,但是需要使用很多次。</p>
|
||
<pre><code>var myVariable = 42
|
||
myVariable = 50
|
||
let myConstant = 42
|
||
</code></pre><p>常量或者变量的类型必须和你赋给它们的值一样。然而,声明时类型是可选的,声明的同时赋值的话,编译器会自动推断类型。在上面的例子中,编译器推断出<code>myVariable</code>是一个整数(integer)因为它的初始值是整数。</p>
|
||
<p>如果初始值没有提供足够的信息(或者没有初始值),那你需要在变量后面声明类型,用冒号分割。</p>
|
||
<pre><code>let implicitInteger = 70
|
||
let implicitDouble = 70.0
|
||
let explicitDouble: Double = 70
|
||
</code></pre><blockquote>
|
||
<p>练习:创建一个常量,显式指定类型为<code>Float</code>并指定初始值为4。</p>
|
||
</blockquote>
|
||
<p>值永远不会被隐式转换为其他类型。如果你需要把一个值转换成其他类型,请显式转换。</p>
|
||
<pre><code>let label = "The width is"
|
||
let width = 94
|
||
let widthLabel = label + String(width)
|
||
</code></pre><blockquote>
|
||
<p>练习:删除最后一行中的<code>String</code>,错误提示是什么?</p>
|
||
</blockquote>
|
||
<p>有一种更简单的把值转换成字符串的方法:把值写到括号中,并且在括号之前写一个反斜杠。例如:</p>
|
||
<pre><code>let apples = 3
|
||
let oranges = 5
|
||
let appleSummary = "I have \(apples) apples."
|
||
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
|
||
</code></pre><blockquote>
|
||
<p>练习:使用<code>\()</code>来把一个浮点计算转换成字符串,并加上某人的名字,和他打个招呼。</p>
|
||
</blockquote>
|
||
<p>使用方括号<code>[]</code>来创建数组和字典,并使用下标或者键(key)来访问元素。</p>
|
||
<pre><code>var shoppingList = ["catfish", "water", "tulips", "blue paint"]
|
||
shoppingList[1] = "bottle of water"
|
||
|
||
var occupations = [
|
||
"Malcolm": "Captain",
|
||
"Kaylee": "Mechanic",
|
||
]
|
||
occupations["Jayne"] = "Public Relations"
|
||
</code></pre><p>要创建一个空数组或者字典,使用初始化语法。</p>
|
||
<pre><code>let emptyArray = String[]()
|
||
let emptyDictionary = Dictionary<String, Float>()
|
||
</code></pre><p>如果类型信息可以被推断出来,你可以用<code>[]</code>和<code>[:]</code>来创建空数组和空字典——就像你声明变量或者给函数传参数的时候一样。</p>
|
||
<pre><code>shoppingList = [] // 去逛街并买点东西
|
||
</code></pre><h2 id="-">控制流</h2>
|
||
<p>使用<code>if</code>和<code>switch</code>来进行条件操作,使用<code>for-in</code>、<code>for</code>、<code>while</code>和<code>do-while</code>来进行循环。包裹条件和循环变量括号可以省略,但是语句体的大括号是必须的。</p>
|
||
<pre><code>let individualScores = [75, 43, 103, 87, 12]
|
||
var teamScore = 0
|
||
for score in individualScores {
|
||
if score > 50 {
|
||
teamScore += 3
|
||
} else {
|
||
teamScore += 1
|
||
}
|
||
}
|
||
teamScore
|
||
</code></pre><p>在<code>if</code>语句中,条件必须是一个布尔表达式——像<code>if score { ... }</code>这样的代码是错误的。</p>
|
||
<p>你可以一起使用<code>if</code>和<code>let</code>来处理值缺失的情况。有些变量的值是可选的。一个可选的值可能是一个具体的值或者是<code>nil</code>,表示值缺失。在类型后面加一个问号来标记这个变量的值是可选的。</p>
|
||
<pre><code>var optionalString: String? = "Hello"
|
||
optionalString == nil
|
||
|
||
var optionalName: String? = "John Appleseed"
|
||
var greeting = "Hello!"
|
||
if let name = optionalName {
|
||
greeting = "Hello, \(name)"
|
||
}
|
||
</code></pre><blockquote>
|
||
<p>练习:把<code>optionalName</code>改成<code>nil</code>,greeting会是什么?添加一个<code>else</code>语句,当<code>optionalName</code>是<code>nil</code>时给greeting赋一个不同的值。</p>
|
||
</blockquote>
|
||
<p>如果变量的可选值是<code>nil</code>,条件会判断为<code>false</code>,大括号中的代码会被跳过。如果不是<code>nil</code>,会将值赋给<code>let</code>后面的常量,这样代码块中就可以使用这个值了。</p>
|
||
<p><code>switch</code>支持任意类型的数据以及各种比较操作——不仅仅是整数以及测试相等。</p>
|
||
<pre><code>let vegetable = "red pepper"
|
||
switch vegetable {
|
||
case "celery":
|
||
let vegetableComment = "Add some raisins and make ants on a log."
|
||
case "cucumber", "watercress":
|
||
let vegetableComment = "That would make a good tea sandwich."
|
||
case let x where x.hasSuffix("pepper"):
|
||
let vegetableComment = "Is it a spicy \(x)?"
|
||
default:
|
||
let vegetableComment = "Everything tastes good in soup."
|
||
}
|
||
</code></pre><blockquote>
|
||
<p>练习:删除<code>default</code>语句,看看会有什么错误?</p>
|
||
</blockquote>
|
||
<p>运行<code>switch</code>中匹配到的子句之后,程序会退出<code>switch</code>语句,并不会继续向下运行,所以不需要在每个子句结尾写<code>break</code>。</p>
|
||
<p>你可以使用<code>for-in</code>来遍历字典,需要两个变量来表示每个键值对。</p>
|
||
<pre><code>let interestingNumbers = [
|
||
"Prime": [2, 3, 5, 7, 11, 13],
|
||
"Fibonacci": [1, 1, 2, 3, 5, 8],
|
||
"Square": [1, 4, 9, 16, 25],
|
||
]
|
||
var largest = 0
|
||
for (kind, numbers) in interestingNumbers {
|
||
for number in numbers {
|
||
if number > largest {
|
||
largest = number
|
||
}
|
||
}
|
||
}
|
||
largest
|
||
</code></pre><blockquote>
|
||
<p>练习:添加另一个变量来记录哪种类型的数字是最大的。</p>
|
||
</blockquote>
|
||
<p>使用<code>while</code>来重复运行一段代码直到不满足条件。循环条件可以在开头也可以在结尾。</p>
|
||
<pre><code>var n = 2
|
||
while n < 100 {
|
||
n = n * 2
|
||
}
|
||
n
|
||
|
||
var m = 2
|
||
do {
|
||
m = m * 2
|
||
} while m < 100
|
||
m
|
||
</code></pre><p>你可以在循环中使用<code>..</code>来表示范围,也可以使用传统的写法,两者是等价的:</p>
|
||
<pre><code>var firstForLoop = 0
|
||
for i in 0..3 {
|
||
firstForLoop += i
|
||
}
|
||
firstForLoop
|
||
|
||
var secondForLoop = 0
|
||
for var i = 0; i < 3; ++i {
|
||
secondForLoop += 1
|
||
}
|
||
secondForLoop
|
||
</code></pre><p>使用<code>..</code>创建的范围不包含上界,如果想包含的话需要使用<code>...</code>。</p>
|
||
<h2 id="-">函数和闭包</h2>
|
||
<p>使用<code>func</code>来声明一个函数,使用名字和参数来调用函数。使用<code>-></code>来指定函数返回值。</p>
|
||
<pre><code>func greet(name: String, day: String) -> String {
|
||
return "Hello \(name), today is \(day)."
|
||
}
|
||
greet("Bob", "Tuesday")
|
||
</code></pre><blockquote>
|
||
<p>练习:删除<code>day</code>参数,添加一个参数来表示今天吃了什么午饭。</p>
|
||
</blockquote>
|
||
<p>使用一个元组来返回多个值。</p>
|
||
<pre><code>func getGasPrices() -> (Double, Double, Double) {
|
||
return (3.59, 3.69, 3.79)
|
||
}
|
||
getGasPrices()
|
||
</code></pre><p>函数的参数数量是可变的,用一个数组来获取它们:</p>
|
||
<pre><code>func sumOf(numbers: Int...) -> Int {
|
||
var sum = 0
|
||
for number in numbers {
|
||
sum += number
|
||
}
|
||
return sum
|
||
}
|
||
sumOf()
|
||
sumOf(42, 597, 12)
|
||
</code></pre><blockquote>
|
||
<p>练习:写一个计算参数平均值的函数。</p>
|
||
</blockquote>
|
||
<p>函数可以嵌套。被嵌套的函数可以访问外侧函数的变量,你可以使用嵌套函数来重构一个太长或者太复杂的函数。</p>
|
||
<pre><code>func returnFifteen() -> Int {
|
||
var y = 10
|
||
func add() {
|
||
y += 5
|
||
}
|
||
add()
|
||
return y
|
||
}
|
||
returnFifteen()
|
||
</code></pre><p>函数是一等公民,这意味着函数可以作为另一个函数的返回值。</p>
|
||
<pre><code>func makeIncrementer() -> (Int -> Int) {
|
||
func addOne(number: Int) -> Int {
|
||
return 1 + number
|
||
}
|
||
return addOne
|
||
}
|
||
var increment = makeIncrementer()
|
||
increment(7)
|
||
</code></pre><p>函数也可以当做参数传入另一个函数。</p>
|
||
<pre><code>func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool {
|
||
for item in list {
|
||
if condition(item) {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
func lessThanTen(number: Int) -> Bool {
|
||
return number < 10
|
||
}
|
||
var numbers = [20, 19, 7, 12]
|
||
hasAnyMatches(numbers, lessThanTen)
|
||
</code></pre><p>函数实际上是一种特殊的闭包,你可以使用<code>{}</code>来创建一个匿名闭包。使用<code>in</code>来分割参数并返回类型。</p>
|
||
<pre><code>numbers.map({
|
||
(number: Int) -> Int in
|
||
let result = 3 * number
|
||
return result
|
||
})
|
||
</code></pre><blockquote>
|
||
<p>练习:重写闭包,对所有奇数返回0.</p>
|
||
</blockquote>
|
||
<p>有很多种创建闭包的方法。如果一个闭包的类型已知,比如作为一个回调函数,你可以忽略参数的类型和返回值。单个语句闭包会把它语句的值当做结果返回。</p>
|
||
<p>你可以获取参数的数量——这个方法在非常短的闭包中很有用。一个被作为最后一个参数传入函数的时候可以直接出现在括号后面。</p>
|
||
<pre><code>sort([1, 5, 3, 12, 2]) { $0 > $1 }
|
||
</code></pre><h2 id="-">对象和类</h2>
|
||
<p>使用<code>class</code>和类名来创建一个类。类中属性的声明和常量、变量声明一样,唯一的区别就是它们的上下文是类。同样,方法和函数声明也一样。</p>
|
||
<pre><code>class Shape {
|
||
var numberOfSides = 0
|
||
func simpleDescription() -> String {
|
||
return "A shape with \(numberOfSides) sides."
|
||
}
|
||
}
|
||
</code></pre><blockquote>
|
||
<p>练习:使用<code>let</code>添加一个常量属性,再添加一个接收一个参数的方法。</p>
|
||
</blockquote>
|
||
<p>要创建一个类的实例,在类名后面加上括号。使用点语法来访问实例的属性和方法。</p>
|
||
<pre><code>var shape = Shape()
|
||
shape.numberOfSides = 7
|
||
var shapeDescription = shape.simpleDescription()
|
||
</code></pre><p>这个版本的<code>Shape</code>类缺少了一些重要的东西:一个构造函数来初始化类实例。使用<code>init</code>来创建一个构造器。</p>
|
||
<pre><code>class NamedShape {
|
||
var numberOfSides: Int = 0
|
||
var name: String
|
||
|
||
init(name: String) {
|
||
self.name = name
|
||
}
|
||
|
||
func simpleDescription() -> String {
|
||
return "A shape with \(numberOfSides) sides."
|
||
}
|
||
}
|
||
</code></pre><p>注意<code>self</code>被用来区别实例变量。当你创建实例的时候,像传入函数参数一样给类传入构造器的参数。每个属性都需要赋值——无论是通过声明(就像<code>numberOfSides</code>)还是通过构造器(就像<code>name</code>)。</p>
|
||
<p>如果你需要在删除对象之前进行一些清理工作,使用<code>deinit</code>创建一个析构函数。</p>
|
||
<p>子类的定义方法是在它们的类名后面加上父类的名字,用冒号分割。创建类的时候并不需要一个标准的根类,所以你可以忽略父类。</p>
|
||
<p>子类如果要重写父类的方法的话,需要用<code>override</code>标记——如果没有添加<code>override</code>就重写父类方法的话编译器会报错。编译器同样会检测<code>override</code>标记的方法是否确实在父类中。</p>
|
||
<pre><code>class Square: NamedShape {
|
||
var sideLength: Double
|
||
|
||
init(sideLength: Double, name: String) {
|
||
self.sideLength = sideLength
|
||
super.init(name: name)
|
||
numberOfSides = 4
|
||
}
|
||
|
||
func area() -> Double {
|
||
return sideLength * sideLength
|
||
}
|
||
|
||
override func simpleDescription() -> String {
|
||
return "A square with sides of length \(sideLength)."
|
||
}
|
||
}
|
||
let test = Square(sideLength: 5.2, name: "my test square")
|
||
test.area()
|
||
test.simpleDescription()
|
||
</code></pre><blockquote>
|
||
<p>练习:创建<code>NamedShape</code>的另一个子类<code>Circle</code>,构造器接收两个参数,一个是半径一个是名称,实现<code>area</code>和<code>describe</code>方法。</p>
|
||
</blockquote>
|
||
<p>属性可以有 getter 和 setter 。</p>
|
||
<pre><code>class EquilateralTriangle: NamedShape {
|
||
var sideLength: Double = 0.0
|
||
|
||
init(sideLength: Double, name: String) {
|
||
self.sideLength = sideLength
|
||
super.init(name: name)
|
||
numberOfSides = 3
|
||
}
|
||
|
||
var perimeter: Double {
|
||
get {
|
||
return 3.0 * sideLength
|
||
}
|
||
set {
|
||
sideLength = newValue / 3.0
|
||
}
|
||
}
|
||
|
||
override func simpleDescription() -> String {
|
||
return "An equilateral triagle with sides of length \(sideLength)."
|
||
}
|
||
}
|
||
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
|
||
triangle.perimeter
|
||
triangle.perimeter = 9.9
|
||
triangle.sideLength
|
||
</code></pre><p>在<code>perimeter</code>的 setter 中,新值的名字是<code>newValue</code>。你可以在<code>set</code>之后显示的设置一个名字。</p>
|
||
<p>注意<code>EquilateralTriangle</code>类的构造器执行了三步:</p>
|
||
<ol>
|
||
<li>设置子类声明的属性值</li>
|
||
<li>调用父类的构造器</li>
|
||
<li>改变父类定义的属性值。其他的工作比如调用方法、getters和setters也可以在这个阶段完成。</li>
|
||
</ol>
|
||
<p>如果你不需要计算属性但是需要在设置一个新值之前运行一些代码,使用<code>willSet</code>和<code>didSet</code>。</p>
|
||
<p>比如,下面的类确保三角形的边长总是和正方形的边长相同。</p>
|
||
<pre><code>class TriangleAndSquare {
|
||
var triangle: EquilateralTriangle {
|
||
willSet {
|
||
square.sideLength = newValue.sideLength
|
||
}
|
||
}
|
||
var square: Square {
|
||
willSet {
|
||
triangle.sideLength = newValue.sideLength
|
||
}
|
||
}
|
||
init(size: Double, name: String) {
|
||
square = Square(sideLength: size, name: name)
|
||
triangle = EquilateralTriangle(sideLength: size, name: name)
|
||
}
|
||
}
|
||
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
|
||
triangleAndSquare.square.sideLength
|
||
triangleAndSquare.triangle.sideLength
|
||
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
|
||
triangleAndSquare.triangle.sideLength
|
||
</code></pre><p>类中的方法和一般的函数有一个重要的区别,函数的参数名只在函数内部使用,但是方法的参数名需要在调用的时候显式说明(除了第一个参数)。默认情况下,方法的参数名和它在方法内部的名字一样,不过你也可以定义第二个名字,这个名字被用在方法内部。</p>
|
||
<pre><code>class Counter {
|
||
var count: Int = 0
|
||
func incrementBy(amount: Int, numberOfTimes times: Int) {
|
||
count += amount * times
|
||
}
|
||
}
|
||
var counter = Counter()
|
||
counter.incrementBy(2, numberOfTimes: 7)
|
||
</code></pre><p>处理变量的可选值时,你可以在操作(比如方法、属性和子脚本)之前加<code>?</code>。如果<code>?</code>之前的值是<code>nil</code>,<code>?</code>后面的东西都会被忽略,并且整个表达式返回<code>nil</code>。否则,<code>?</code>之后的东西都会被运行。在这两种情况下,整个表达式的值也是一个可选值。</p>
|
||
<pre><code>let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")
|
||
let sideLength = optionalSquare?.sideLength
|
||
</code></pre><h2 id="-">枚举和结构体</h2>
|
||
<p>使用<code>enum</code>来创建一个枚举。就像类和其他所有命名类型一样,枚举可以包含方法。</p>
|
||
<pre><code>enum Rank: Int {
|
||
case Ace = 1
|
||
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
|
||
case Jack, Queen, King
|
||
func simpleDescription() -> String {
|
||
switch self {
|
||
case .Ace:
|
||
return "ace"
|
||
case .Jack:
|
||
return "jack"
|
||
case .Queen:
|
||
return "queen"
|
||
case .King:
|
||
return "king"
|
||
default:
|
||
return String(self.toRaw())
|
||
}
|
||
}
|
||
}
|
||
let ace = Rank.Ace
|
||
let aceRawValue = ace.toRaw()
|
||
</code></pre><blockquote>
|
||
<p>练习:写一个函数,通过比较它们的原始值来比较两个<code>Rank</code>值。</p>
|
||
</blockquote>
|
||
<p>在上面的例子中,枚举原始值的类型是<code>Int</code>,所以你只需要设置第一个原始值。剩下的原始值会按照顺序赋值。你也可以使用字符串或者浮点数作为枚举的原始值。</p>
|
||
<p>使用<code>toRaw</code>和<code>fromRaw</code>函数来在原始值和枚举值之间进行转换。</p>
|
||
<pre><code>if let convertedRank = Rank.fromRaw(3) {
|
||
let threeDescription = convertedRank.simpleDescription()
|
||
}
|
||
</code></pre><p>枚举的成员值是实际值,并不是原始值的另一种表达方法。实际上,如果原始值没有意义,你不需要设置。</p>
|
||
<pre><code>enum Suit {
|
||
case Spades, Hearts, Diamonds, Clubs
|
||
func simpleDescription() -> String {
|
||
switch self {
|
||
case .Spades:
|
||
return "spades"
|
||
case .Hearts:
|
||
return "hearts"
|
||
case .Diamonds:
|
||
return "diamonds"
|
||
case .Clubs:
|
||
return "clubs"
|
||
}
|
||
}
|
||
|
||
}
|
||
let hearts = Suit.Hearts
|
||
let heartsDescription = hearts.simpleDescription()
|
||
</code></pre><blockquote>
|
||
<p>练习:给<code>Suit</code>添加一个<code>color</code>方法,对<code>spades</code>和<code>clubs</code>返回“black”,对<code>hearts</code>和<code>diamonds</code>返回“red”。</p>
|
||
</blockquote>
|
||
<p>注意,有两种方式可以引用<code>Hearts</code>成员:给<code>hearts</code>常量赋值时,枚举成员<code>Suit.Hearts</code>需要用全名来引用,因为常量没有显式指定类型。在<code>switch</code>里,枚举成员使用缩写<code>.Hearts</code>来引用,因为<code>self</code>的值已经知道是一个<code>suit</code>。已知变量类型的情况下你可以使用缩写。</p>
|
||
<p>使用<code>struct</code>来创建一个结构体。结构体和类有很多相同的地方,比如方法和构造器。它们结构体之间最大的一个区别就是
|
||
结构体是传值,类是传引用。</p>
|
||
<pre><code>struct Card {
|
||
var rank: Rank
|
||
var suit: Suit
|
||
func simpleDescription() -> String {
|
||
return "The \(rank.simpleDescription()) of \
|
||
(suit.simpleDescription())"
|
||
}
|
||
}
|
||
let threeOfSpades = Card(rank: .Three, suit: .Spades)
|
||
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
|
||
</code></pre><blockquote>
|
||
<p>练习:给<code>Card</code>添加一个方法,创建一副完整的扑克牌并把每张牌的rank和suit对应起来。</p>
|
||
</blockquote>
|
||
<p>一个枚举成员的实例可以有实例值。相同枚举成员的实例可以有不同的值。创建实例的时候传入值即可。实例值和原始值是不同的:枚举成员的原始值对于所有实例都是相同的,而且你是在定义枚举的时候设置原始值。</p>
|
||
<p>例如,考虑从服务器获取日出和日落的时间。服务器会返回正常结果或者错误信息。</p>
|
||
<pre><code>enum ServerResponse {
|
||
case Result(String, String)
|
||
case Error(String)
|
||
}
|
||
|
||
let success = ServerResponse.Result("6:00 am", "8:09 pm")
|
||
let failure = ServerResponse.Error("Out of cheese.")
|
||
|
||
switch success {
|
||
case let .Result(sunrise, sunset):
|
||
let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."
|
||
case let .Error(error):
|
||
let serverResponse = "Failure... \(error)"
|
||
}
|
||
</code></pre><blockquote>
|
||
<p>练习:给<code>ServerResponse</code>和<code>switch</code>添加第三种情况。</p>
|
||
</blockquote>
|
||
<p>注意如何从<code>ServerResponse</code>中提取日升和日落时间。</p>
|
||
<h2 id="-">接口和扩展</h2>
|
||
<p>使用<code>protocol</code>来声明一个接口。</p>
|
||
<pre><code>protocol ExampleProtocol {
|
||
var simpleDescription: String { get }
|
||
mutating func adjust()
|
||
}
|
||
</code></pre><p>类、枚举和结构体都可以实现接口。</p>
|
||
<pre><code>class SimpleClass: ExampleProtocol {
|
||
var simpleDescription: String = "A very simple class."
|
||
var anotherProperty: Int = 69105
|
||
func adjust() {
|
||
simpleDescription += " Now 100% adjusted."
|
||
}
|
||
}
|
||
var a = SimpleClass()
|
||
a.adjust()
|
||
let aDescription = a.simpleDescription
|
||
|
||
struct SimpleStructure: ExampleProtocol {
|
||
var simpleDescription: String = "A simple structure"
|
||
mutating func adjust() {
|
||
simpleDescription += " (adjusted)"
|
||
}
|
||
}
|
||
var b = SimpleStructure()
|
||
b.adjust()
|
||
let bDescription = b.simpleDescription
|
||
</code></pre><blockquote>
|
||
<p>练习:写一个实现这个接口的枚举。</p>
|
||
</blockquote>
|
||
<p>注意声明<code>SimpleStructure</code>时候<code>mutating</code>关键字用来标记一个会修改结构体的方法。<code>SimpleClass</code>的声明不需要标记任何方法因为类中的方法经常会修改类。</p>
|
||
<p>使用<code>extension</code>来为现有的类型添加功能,比如添加一个计算属性的方法。你可以使用扩展来给任意类型添加协议,甚至是你从外部库或者框架中导入的类型。</p>
|
||
<pre><code>extension Int: ExampleProtocol {
|
||
var simpleDescription: String {
|
||
return "The number \(self)"
|
||
}
|
||
mutating func adjust() {
|
||
self += 42
|
||
}
|
||
}
|
||
7.simpleDescription
|
||
</code></pre><blockquote>
|
||
<p>练习:给<code>Double</code>类型写一个扩展,添加<code>absoluteValue</code>功能。</p>
|
||
</blockquote>
|
||
<p>你可以像使用其他命名类型一样使用接口名——例如,创建一个有不同类型但是都实现一个接口的对象集合。当你处理类型是接口的值时,接口外定义的方法不可用。</p>
|
||
<pre><code>let protocolValue: ExampleProtocol = a
|
||
protocolValue.simpleDescription
|
||
// protocolValue.anotherProperty // Uncomment to see the error
|
||
</code></pre><p>即使<code>protocolValue</code>变量运行时的类型是<code>simpleClass</code>,编译器会把它的类型当做<code>ExampleProtocol</code>。这表示你不能调用类在它实现的接口之外实现的方法或者属性。</p>
|
||
<h2 id="-">泛型</h2>
|
||
<p>在尖括号里写一个名字来创建一个泛型函数或者类型。</p>
|
||
<pre><code>func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] {
|
||
var result = ItemType[]()
|
||
for i in 0..times {
|
||
result += item
|
||
}
|
||
return result
|
||
}
|
||
repeat("knock", 4)
|
||
</code></pre><p>你也可以创建泛型类、枚举和结构体。</p>
|
||
<pre><code>// Reimplement the Swift standard library's optional type
|
||
enum OptionalValue<T> {
|
||
case None
|
||
case Some(T)
|
||
}
|
||
var possibleInteger: OptionalValue<Int> = .None
|
||
possibleInteger = .Some(100)
|
||
</code></pre><p>在类型名后面使用<code>where</code>来指定一个需求列表——例如,要限定实现一个协议的类型,需要限定两个类型要相同,或者限定一个类必须有一个特定的父类。</p>
|
||
<pre><code>func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool {
|
||
for lhsItem in lhs {
|
||
for rhsItem in rhs {
|
||
if lhsItem == rhsItem {
|
||
return true
|
||
}
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
anyCommonElements([1, 2, 3], [3])
|
||
</code></pre><blockquote>
|
||
<p>练习:修改<code>anyCommonElements</code>函数来创建一个函数,返回一个数组,内容是两个序列的共有元素。</p>
|
||
</blockquote>
|
||
<p>简单起见,你可以忽略<code>where</code>,只在冒号后面写接口或者类名。<code><T: Equatable></code>和<code><T where T: Equatable></code>是等价的。</p>
|
||
|
||
|
||
</section>
|
||
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
|
||
<a href="../chapter1/swift.html" class="navigation navigation-prev " aria-label="Previous page: 关于 Swift"><i class="fa fa-angle-left"></i></a>
|
||
|
||
|
||
<a href="../chapter2/the_basics.html" class="navigation navigation-next " aria-label="Next page: Swift 教程"><i class="fa fa-angle-right"></i></a>
|
||
|
||
</div>
|
||
</div>
|
||
|
||
|
||
|
||
<script src="http://cdn.bootcss.com/ace/1.1.3/ace.js"></script>
|
||
<script src="http://cdn.bootcss.com/ace/1.1.3/mode-javascript.js"></script>
|
||
<script src="../gitbook/jsrepl/jsrepl.js" id="jsrepl-script"></script>
|
||
<script src="../gitbook/app.js"></script>
|
||
|
||
|
||
|
||
<script src="../gitbook/plugins/gitbook-plugin-mixpanel/plugin.js"></script>
|
||
|
||
|
||
|
||
<script src="http://cdn.mathjax.org/mathjax/2.0-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
|
||
|
||
|
||
|
||
<script src="../gitbook/plugins/gitbook-plugin-mathjax/plugin.js"></script>
|
||
|
||
|
||
<script>
|
||
require(["gitbook"], function(gitbook) {
|
||
var config = {};
|
||
gitbook.start(config);
|
||
});
|
||
</script>
|
||
|
||
|
||
</body>
|
||
|
||
</html>
|