Using Standard Types 使用标准类型
Using Standard Types 使用标准类型
In this section, you are going to experiment with standard types in an Xcode playground. A playground 在本节中,你将使用<code>Xcode</code>的<code>游乐场</code>来实验标准类型。游乐
lets you write code and see the results without the overhead of creating an application and checking the 场让你能够编写代码并查看结果,而无需创建应用程序和检查输出的额外开销。
output.
In Xcode, select File → New → Playground... (or, from the welcome screen, choose Get started with a 在 Xcode 中,选择 文件 → 新建 → 游乐场... (或者,从欢迎屏幕中选择 使用游乐场开始)。确保平台是
playground). Make sure the platform is iOS and the template is Blank (Figure 2.2). After clicking Next, iOS,模板是 空白(图 2.2)。点击 下一步 后,您可以接受此文件的默认名称;您将在这里停留很短时间。
you can accept the default name for this file; you will only be here briefly.
Figure 2.2 Configuring a playground 图 2.2 配置游乐场
37 37
Chapter 2 The Swift Language 第2章 Swift 语言
When the file opens, notice that the playground is divided into two sections (Figure 2.3). The larger 当文件打开时,请注意游乐场分为两个章节(图 2.3)。左侧较大的白色区域是编辑器,您
white area to the left is the editor, where you write code. The gray column on the right is the sidebar, 在那里编写代码。右侧的灰色列是 侧边栏,显示每行代码的结果。
where the results of each line of code are shown.
Figure 2.3 A playground 图 2.3 一个游乐场
In the example code, the var keyword denotes a variable, as you saw in your Quiz app, so the value of 在示例代码中,var关键字表示变量,正如你在你的 Quiz 应用程序中所看到的,因此 str 的
str can be changed. Type in the code below to change the value of str. When you are done, click the 值可以更改。输入下面的代码来更改 str 的值。完成后,点击出现在最后一行代码旁边或下
run button that appears next to or under the last line of code, and you will see the results for each line
方的运行按钮,你将在右侧的侧边栏中看到每行代码的结果。(你也可以点击任何其他代码
appear in the sidebar to the right. (You can also click the run button next to any other line to run the
code only up to that point.) 行旁边的运行按钮,仅运行到该点。)
var str = "Hello, playground" "Hello, playground" var str = "Hello, playground" "Hello, playground"
str = "Hello, Swift" "Hello, Swift" str = "Hello, Swift" "Hello, Swift"
(We are showing sidebar results to the right of the code for the benefit of readers who are not actively (我们为不主动进行练习的读者在代码右侧显示侧边栏结果。)
doing the exercise.)
As you saw in Chapter 1, the let keyword denotes a constant value, which cannot be changed. In 如第一章所述,let 关键字表示一个常量值,不可更改。在你的 Swift 代码中,除非你期望
your Swift code, you should use let unless you expect the value will need to change. Add a constant 值会变化,否则应使用 let。添加一个常量并点击运行按钮以查看结果。(从现在起,假设
to the mix and click the run button to see the result. (From now on, assume that you should run new
你应该在输入新游乐场代码时运行它。)
playground code as you enter it.)
var str = "Hello, playground" "Hello, playground" var str = "Hello, playground" "Hello, playground"
str = "Hello, Swift" "Hello, Swift" str = "Hello, Swift" "Hello, Swift"
let constStr = str "Hello, Swift" let constStr = str "Hello, Swift"
Because constStr is a constant, attempting to change its value will cause an error. Because constStr 是一个常数,尝试改变它的值将导致错误。
var str = "Hello, playground" "Hello, playground" var str = "Hello, playground" "Hello, playground"
str = "Hello, Swift" "Hello, Swift" str = "Hello, Swift" "Hello, Swift"
let constStr = str "Hello, Swift" let constStr = str "Hello, Swift"
constStr = "Hello, world" constStr = "Hello, world"
An error appears, indicated by the red symbol and error message on the offending line. In this case, the 出现错误,由违规行上的红色符号和错误消息指示。在这种情况下,错误显示为无法分配给值:'constStr' 是一个 '
error reads Cannot assign to value: 'constStr' is a 'let' constant. let' 常量。
An error in the playground code will prevent you from seeing any further results in the sidebar, so you 游乐场代码中的错误将阻止您在侧边栏中看到任何进一步的结果,因此您通常希望立即处理它。删除尝试更改
usually want to address it right away. Remove the line that attempts to change the value of constStr. constStr 值的行。
var str = "Hello, playground" "Hello, playground" var str = "Hello, playground" "Hello, playground"
str = "Hello, Swift" "Hello, Swift" str = "Hello, Swift" "Hello, Swift"
let constStr = str "Hello, Swift" let constStr = str "Hello, Swift"
constStr = "Hello, world" constStr = "Hello, world"
38 38
Inferring types 推断类型
Inferring types 推断类型
At this point, you may have noticed that neither the constStr constant nor the str variable has a 此时,您可能已经注意到,constStr 常数和 str 变量都没有指定类型。但这并不意味着它们
specified type. This does not mean they are untyped! Instead, the compiler infers their types from the 是无类型的!相反,编译器从初始值中推断它们的类型。这称为 类型推断。
initial values. This is called type inference.
You can find out what type was inferred using Xcode’s Quick Help. Option-click constStr in the 您可以使用 Xcode 的快速帮助来了解推断的类型。在游乐场中选项单击 constStr,即可查看此常数的快
playground to see the Quick Help information for this constant, shown in Figure 2.4. 速帮助信息,如图 2.4 所示。
Figure 2.4 constStr is of type String 图 2.4 constStr 是 String 类型
Option-clicking to reveal Quick Help will work for any symbol. 选项单击以显示快速帮助将适用于任何符号。
Specifying types 指定类型
If your constant or variable has an initial value, you can rely on type inference. If a constant or variable 如果你的常量或变量有初始值,你可以依赖类型推断。如果常量或变量没有初始值,或者你想
does not have an initial value or if you want to ensure that it is a certain type, you can specify the type 确保它是某种特定类型,你可以在声明中指定类型。
in the declaration.
Add more variables with specified types: 添加更多指定类型的变量:
var str = "Hello, playground" "Hello, playground" var str = "Hello, playground" "Hello, playground"
str = "Hello, Swift" "Hello, Swift" str = "Hello, Swift" "Hello, Swift"
let constStr = str "Hello, Swift" let constStr = str "Hello, Swift"
var nextYear: Int = 0 0 var nextYear: Int = 0 0
var bodyTemp: Float = 0 0 var 体温: Float = 0 0
var hasPet: Bool = true true var 有宠物: Bool = true true
Let’s go over these new types and how they are used. 让我们来了解一下这些新的类型以及它们是如何使用的。
Number and Boolean types 数字和布尔值类型
The most common type for integers is Int. There are additional integer types based on word size and 整数最常见的类型是 Int。基于字大小和有符号性,还有其他整数类型,但苹果建议使用 Int,除非你真的有
signedness, but Apple recommends using Int unless you really have a reason to use something else. 使用其他类型的原因。
For floating-point numbers, Swift provides three types with different levels of precision: Float for 对于浮点数,Swift 提供了三种具有不同精度级别的类型:Float 用于 32 位数字,Double 用于 64 位数字,
32-bit numbers, Double for 64-bit numbers, and Float80 for 80-bit numbers. 以及 Float80 用于 80 位数字。
A Boolean value is expressed in Swift using the type Bool. A Bool’s value is either true or false. 布尔值在 Swift 中使用 Bool 类型表示。一个 Bool 的值要么是 true,要么是 false。
39 39
Chapter 2 The Swift Language 第2章 Swift 语言
Collection types 集合类型
The Swift standard library offers three collections: arrays, dictionaries, and sets. Swift 标准库提供了三种集合:数组、字典 和 集合。
An array is an ordered collection of elements. The array type is written as Array<T>, where T is the 数组是一个有序的元素集合。数组类型写作 Array<T>,其中 T 是数组将要包含的元素的类型。
type of element that the array will contain. Arrays can contain elements of any type: a standard type, a 数组可以包含任何类型的元素:标准类型、结构体或类。
structure, or a class.
Add a variable for an array of integers: 为整数数组添加一个变量:
var hasPet: Bool = true true var 有宠物: Bool = true true
var arrayOfInts: Array<Int> = [] [] var arrayOfInts: Array<整数> = [] []
Arrays are strongly typed. Once you declare an array as containing elements of, say, Int, you cannot 数组是强类型的。一旦你声明一个数组包含,比如 Int 类型的元素,你就不能向其中添加 String 类型的元素。
add a String to it.
There is a shorthand syntax for declaring arrays: You can simply use square brackets around the type 声明数组有一种简写语法:你可以简单地用方括号将数组将要包含的类型括起来。使用这种简写声明一个字
that the array will contain. Declare an array of strings using this shorthand: 符串数组:
var hasPet: Bool = true true var 有宠物: Bool = true true
var arrayOfInts: Array<Int> = [] [] var arrayOfInts: Array<整数> = [] []
var arrayOfStrings: [String] = [] [] var arrayOfStrings: [字符串] = [] []
A dictionary is an unordered collection of key-value pairs. The values can be of any type, including 字典是一个无序的键值对集合。值可以是任何类型,包括结构体和类。键也可以是任何类型,
structures and classes. The keys can be of any type as well, but they must be unique. Specifically, 但它们必须是唯一的。具体来说,键必须是 hashable 的,这使得字典能够保证键的唯一性,并
the keys must be hashable, which allows the dictionary to guarantee that the keys are unique and to
且更高效地访问给定键的值。基本的 Swift 类型,如 Int、Float、Character 和String,都是
access the value for a given key more efficiently. Basic Swift types such as Int, Float, Character, and
String are all hashable. 可哈希的。
Like Swift arrays, Swift dictionaries are strongly typed and can only contain keys and values of the 与 Swift 数组类似,Swift 字典是强类型的,并且只能包含声明的键和值。例如,您可能有一
declared type. For example, you might have a dictionary that stores capital cities by country. The keys 个字典,按国家存储首都城市。该字典的键将是国家名称,值将是城市名称。键和值都将是字
for this dictionary would be the country names, and the values would be the city names. Both keys and
符串,您将无法添加任何其他类型的键或值。
values would be strings, and you would not be able to add a key or value of any other type.
Add a variable for such a dictionary. (We have split the declaration onto two lines to fit on the printed 为这样的字典添加一个变量。(我们将声明分成两行以适应打印页面;您应该在一行中输入它。)
page; you should enter it on one line.)
var arrayOfStrings: [String] = [] [] var arrayOfStrings: [字符串] = [] []
var dictionaryOfCapitalsByCountry: var dictionaryOfCapitalsByCountry:
Dictionary<String,String> = [:] [:] 字典<字符串,字符串> = [:] [:]
There is a shorthand syntax for declaring dictionaries, too. Update dictionaryOfCapitalsByCountry 字典的声明也有简写语法。更新 dictionaryOfCapitalsByCountry 以使用简写:
to use the shorthand:
var arrayOfStrings: [String] = [] [] var arrayOfStrings: [字符串] = [] []
var dictionaryOfCapitalsByCountry: var dictionaryOfCapitalsByCountry:
Dictionary<String,String> = [:] Dictionary<字符串,字符串> = [:]
[String:String] = [:] [:] [字符串:字符串] = [:] [:]
40 40
Literals and subscripting 字面量与下标
A set is similar to an array in that it contains a number of elements of a certain type. However, sets 集合与数组类似,它包含了一定类型的多个元素。然而,集合是无序的,其成员必须是唯一
are unordered, and the members must be unique as well as hashable. The unorderedness of sets makes 的且可哈希。集合的无序性使得在您只需要确定某个元素是否属于集合时,它们处理速度更
them faster when you simply need to determine whether something is a member of a set. Add a
快。为集合添加一个变量:
variable for a set:
var winningLotteryNumbers: Set<Int> = [] Set([]) var winningLotteryNumbers: 集合<Int> = [] 集合([])
Unlike arrays and dictionaries, sets do not have a shorthand syntax. 与数组和字典不同,集合没有简写语法。
Literals and subscripting 字面量与下标
Standard types can be assigned literal values, or literals. For example, str is assigned the value of a 标准类型可以分配字面量值,或 字面量。例如,str 被分配字符串字面量的值。字符串字
string literal. A string literal is formed with double quotes. Contrast the literal value assigned to str 面量使用双引号形成。对比分配给 str 的字面量值与分配给 constStr 的值:
with the value assigned to constStr:
var str = "Hello, playground" "Hello, playground" var str = "Hello, playground" "Hello, playground"
str = "Hello, Swift" "Hello, Swift" str = "Hello, Swift" "Hello, Swift"
let constStr = str "Hello, Swift" let constStr = str "Hello, Swift"
Add two number literals to your playground: 向您的游乐场添加两个数字字面量:
let number = 42 42 let number = 42 42
let fmStation = 91.2 91.2 let fmStation = 91.2 91.2
Arrays and dictionaries can be assigned literal values as well. The syntax for creating literal arrays and 数组和字典也可以分配字面量值。创建字面量数组和字典的语法类似于指定这些类型的简写语法。
dictionaries resembles the shorthand syntax for specifying these types.
let countingUp = ["one", "two"] ["one", "two"] let countingUp = ["一", "二"] ["一", "二"]
let nameByParkingSpace = [13: "Alice", 27: "Bob"] [13: "Alice", 27: "Bob"] let 按停车位命名的字典 = [13: "Alice", 27: "Bob"] [13: "Alice", 27: "Bob"]
Swift also provides subscripting as shorthand for accessing arrays. To retrieve an element in an array, Swift 还提供了 下标 作为访问数组的简写。要检索数组中的元素,您需要在数组名称后用方括号提供该元素
you provide the element’s index in square brackets after the array name. 的索引。
let countingUp = ["one", "two"] ["one", "two"] let countingUp = ["一", "二"] ["一", "二"]
let secondElement = countingUp[1] "two" let secondElement = 数量[1] "二"
... ...
Notice that index 1 retrieves the second element; an array’s index always starts at 0. 请注意,索引 1 会检索第二个元素;数组的索引始终从 0 开始。
When subscripting an array, be sure that you are using a valid index. Attempting to access an 当对数组进行下标操作时,请确保您使用的是有效的索引。尝试访问超出边界的索引会导致
out-of-bounds index results in a trap. A trap is a runtime error that stops the program before it gets into 陷阱。陷阱是一种运行时错误,它会在程序进入未知状态之前停止程序。
an unknown state.
Subscripting also works with dictionaries – more on that later in this chapter. 下标也适用于字典——关于这一点,本章后面会详细介绍。
41 41
Chapter 2 The Swift Language 第2章 Swift 语言
Initializers 初始化器
So far, you have initialized your constants and variables using literal values. In doing so, you created 到目前为止,您已经使用字面量值初始化了您的常量和变量。在此过程中,您创建了实例特定
instances of a specific type. An instance is a particular embodiment of a type. Historically, this term 类型的对象。一个实例是类型的特定体现。从历史上看,这个术语仅用于类,但在Swift中,
has been used only with classes, but in Swift it is used to describe structures and enumerations, too. For
它也用于描述结构体和枚举。例如,常量secondElement持有一个String类型的实例。
example, the constant secondElement holds an instance of String.
Another way of creating instances is by using an initializer on the type. Initializers are responsible 另一种创建实例的方式是使用类型上的 初始化器。初始化器负责准备类型新实例的内容。当
for preparing the contents of a new instance of a type. When an initializer is finished, the instance is 初始化器完成后,实例就准备好可以动作了。要使用初始化器创建新实例,你需要使用类型名
ready for action. To create a new instance using an initializer, you use the type name followed by a pair
称后跟一对括号,如果需要的话,还可以提供参数。这种签名——类型和参数的组合——对应
of parentheses and, if required, arguments. This signature – the combination of type and arguments –
corresponds to a specific initializer. 于特定的初始化器。
Some standard types have initializers that return empty literals when no arguments are supplied. Add 一些标准类型在未提供参数时,其初始化器会返回空字面量。将一个空字符串、一个空数组和一个空集合添
an empty string, an empty array, and an empty set to your playground. 加到你的游乐场中。
let emptyString = String() "" let 字符串 = 字符串() ""
let emptyArrayOfInts = [Int]() [] let emptyArrayOfInts = [整数]() []
let emptySetOfFloats = Set<Float>() Set([]) let emptySetOfFloats = 集合<Float>() 集合([])
Other types have default values: 其他类型有默认值:
let defaultNumber = Int() 0 let defaultNumber = Int() 0
let defaultBool = Bool() false let defaultBool = Bool() false
Types can have multiple initializers. For example, String has an initializer that accepts an Int and 类型可以有多个初始化器。例如,String 有一个初始化器,它接受一个 Int 并根据该值创建一个字符串。
creates a string based on that value.
let number = 42 42 let number = 42 42
let meaningOfLife = String(number) "42" let 生命的意义 = 字符串(数字) "42"
To create a set, you can use the Set initializer that accepts an array literal: 要创建一个集合,您可以使用接受数组字面量的 集合 初始化器:
let availableRooms = Set([205, 411, 412]) {412, 205, 411} let 可用房间 = 集合([205, 411, 412]) {412, 205, 411}
Float has several initializers. The parameter-less initializer returns an instance of Float with the 浮点数有多个初始化器。无参数的初始化器返回一个 浮点数 实例,其值为默认值。还有一个接受浮点数
default value. There is also an initializer that accepts a floating-point literal. 字面量的初始化器。
let defaultFloat = Float() 0 let 默认浮点数 = 浮点数() 0
let floatFromLiteral = Float(3.14) 3.14 let 从字面量创建的浮点数 = 浮点数(3.14) 3.14
If you use type inference for a floating-point literal, the type defaults to Double. Create the following 如果你对浮点数字面量使用类型推断,则类型默认为 双精度浮点数。使用浮点数字面量创建以下常量:
constant with a floating-point literal:
let easyPi = 3.14 3.14 let 易派 = 3.14 3.14
Use the Float initializer that accepts a Double to create a Float from this Double: 使用接受 双精度浮点数 的 Float 初始化器,从这个 双精度浮点数 创建一个 Float:
let easyPi = 3.14 3.14 let 易派 = 3.14 3.14
let floatFromDouble = Float(easyPi) 3.14 let floatFromDouble = Float(easyPi) 3.14
You can achieve the same result by specifying the type in the declaration. 您可以通过在声明中指定类型来达到相同的结果。
let easyPi = 3.14 3.14 let 易派 = 3.14 3.14
let floatFromDouble = Float(easyPi) 3.14 let floatFromDouble = Float(easyPi) 3.14
let floatingPi: Float = 3.14 3.14 let 浮点派: Float = 3.14 3.14
42 42