The Basics
Swift is a new programming language for iOS, OS X, and watchOS app development. Nonetheless(虽然如此), many parts of Swift will be familiar from your experience of developing in C and Objective-C.
Swift provides its own versions of all fundamental C and Objective-C types, including Int
for integers, Double
and Float
for floating-point values, Bool
for Boolean values, and String
for textual data. Swift also provides powerful versions of the three primary collection types, Array
, Set
, and Dictionary
, as described in Collection Types.
Like C, Swift uses variables to store(存储) and refer to(关联) values by an identifying name(标识符). Swift also makes extensive use of variables whose values cannot be changed. These are known as constants, and are much more powerful than constants in C. Constants are used throughout(至始至终) Swift to make code safer and clearer in intent(意图目的) when you work with values that do not need to change.
In addition to familiar types, Swift introduces advanced types(高阶类型) not found in Objective-C, such as tuples(元祖). Tuples enable you to create and pass around groupings of values. You can use a tuple to return multiple values(多个值) from a function as a single compound value.
Swift also introduces optional types, which handle the absence(缺失) of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Using optionals is similar to using nil with pointers(指针) in Objective-C, but they work for any type, not just classes. Not only are optionals safer and more expressive(更具表达能力) than nil pointers in Objective-C, they are at the heart of many of Swift’s most powerful features(强大的特性).
Swift is a type-safe language, which means the language helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents(预防,阻止) you from passing it an Int by mistake. Likewise(同样的), type safety prevents you from accidentally passing an optional String to a piece of code that expects a nonoptional String. Type safety helps you catch and fix errors as early as possible in the development process(开发阶段).
Constants and Variables
Constants and variables associate(使发生联系) a name (such as maximumNumberOfLoginAttempts
or welcomeMessage
) with a value of a particular type (such as the number 10
or the string "Hello"
). The value of a constant cannot be changed once it is set, whereas(但是) a variable can be set to a different value in the future.
Declaring(声明) Constants and Variables
Constants and variables must be declared before they are used. You declare constants with the let
keyword and variables with the var
keyword. Here’s an example of how constants and variables can be used to track(记录,踪迹) the number of login attempts(尝试,企图) a user has made:
1 | let maximumNumberOfLoginAttempts = 10 |
This code can be read as:
“Declare a new constant called maximumNumberOfLoginAttempts
, and give it a value of 10
. Then, declare a new variable called currentLoginAttempt
, and give it an initial value of 0
.”
In this example, the maximum(最大数) number of allowed(允许) login attempts is declared as a constant, because the maximum value never changes. The current login attempt counter is declared as a variable, because this value must be incremented(增长的) after each failed login attempt.
You can declare multiple(许多的) constants or multiple variables on a single line, separated by commas:
1 | var x = 0.0, y = 0.0, z = 0.0 |
NOTE
If a stored value in your code is not going to change, always declare it as a constant with the
let
keyword. Use variables only for storing values that need to be able to change.
Type Annotations(注解,注释)
You can provide a type annotation when you declare a constant or variable, to be clear about the kind of values the constant or variable can store. Write a type annotation by placing(设置) a colon(冒号) after the constant or variable name, followed by a space(空格), followed by the name of the type(类型名) to use.
This example provides a type annotation for a variable called welcomeMessage
, to indicate(指示) that the variable can store String
values:
1 | var welcomeMessage: String |
The colon in the declaration means “…of type…,” so the code above can be read as:
“Declare a variable called welcomeMessage
that is of type String
.
The phrase(短语) “of type String
” means “can store any String
value.” Think of it as meaning “the type of thing” (or “the kind of thing”) that can be stored.
The welcomeMessage
variable can now be set to any string value without error:
1 | welcomeMessage = "Hello" |
You can define(定义) multiple related(有关联的) variables of the same type on a single line(一行), separated(分隔) by commas(逗号), with a single type annotation after the final variable name(在最后一个变量名后面进行一次标注):
1 | var red, green, blue: Double |
NOTE
It is rare(很少) that you need to write type annotations in practice. If you provide an initial value for a constant or variable at the point(在定义时 ) that it is defined(定义), Swift can almost always infer(推断) the type to be used for that constant or variable, as described in Type Safety and Type Inference. In the
welcomeMessage
example above(上面的), no initial value is provided, and so the type of thewelcomeMessage
variable is specified(被指定) with a type annotation rather than being inferred(被推断) from an initial value.
上面例子中的welcomeMessage
没有初始值,所以welcomeMessage
变量是通过声明被指定类型,而不是由初始值推断类型的
Naming Constants and Variables
Constant and variable names can contain(包含) almost any character(字符), including Unicode characters:
1 | let π = 3.14159 |
Constant and variable names cannot contain whitespace(空格) characters, mathematical symbols(数学符号), arrows(箭头), private-use(私用) (or invalid(无效的)) Unicode code points(码位), or line- and box-drawing characters(画线、制表符). Nor can they begin with a number, although(但是) numbers may be included elsewhere within the name(数字可以在除了开头之外的其他地方).
Once you’ve declared a constant or variable of a certain type, you can’t redeclare(重新声明) it again with the same name(同一个变量名), or change it to store values of a different type(或者去存储其他类型的变量). Nor can you change a constant into a variable or a variable into a constant.
NOTE
If you need to give a constant or variable the same name as a reserved(被保留的) Swift keyword(swift关键字), surround the keyword with back ticks (`) when using it as a name. However, avoid using keywords as names unless you have absolutely no choice.
如果要用关键字做变量名,你可以用(`)包围的方式将其作为名字使用,然而,避免用关键字作为变量名除非你绝对没得选择
You can change the value of an existing variable to another value of a compatible type(同一个类型). In this example, the value of friendlyWelcome
is changed from "Hello!"
to "Bonjour!"
:
1 | var friendlyWelcome = "Hello!" |
Unlike a variable, the value of a constant cannot be changed once it is set(一旦它被设置). Attempting(试图) to do so is reported as an error(报错) when your code is compiled(编译):
1 | let languageName = "Swift" |
Printing Constants and Variables
You can print the current value of a constant or variable with the print(_:separator:terminator:)
function:
1 |
|
The print(_:separator:terminator:)
function is a global function(全局函数) that prints one or more values to an appropriate output(恰当的输出). In Xcode, for example, the print(_:separator:terminator:)
function prints its output in Xcode’s “console” pane(控制台面板). The separator(分隔符)
and terminator(终止符)
parameter have default values, so you can omit(省略) them when you call this function. By default, the function terminates the line it prints by adding a line break(默认换行). To print a value without a line break after it(为了打印一个值没有换行), pass an empty string as the terminator(传入一个空字符串作为终止)—for example, print(someValue, terminator: "")
. For information about parameters with default values, see Default Parameter Values.
1 | print("ssss", terminator: "") // 不会换行 |
Swift uses string interpolation to include the name of a constant or variable as a placeholder(占位符) in a longer string, and to prompt(匀速的) Swift to replace it with the current value of that constant or variable. Wrap(包裹) the name in parentheses(括号) and escape(转义) it with a backslash(反斜线符号) before the opening parenthesis(在括号前面):
1 | print("The current value of friendlyWelcome is \(friendlyWelcome)") |
NOTE
All options(选择) you can use with string interpolation(改写) are described in String Interpolation.
Comments(注释)
Use comments to include non-executable text(不执行文本) in your code, as a note(笔记) or reminder(提醒) to yourself. Comments are ignored by the Swift compiler(被编译器忽视) when your code is compiled.
Comments in Swift are very similar to comments in C. Single-line comments(单行注释) begin with two forward-slashes (//):
1 | // this is a comment |
Multiline comments(多文本注释) start with a forward-slash followed by an asterisk (/*
)
and end with an asterisk followed by a forward-slash (*/
):
1 | /* this is also a comment, |
Unlike multiline comments in C, multiline comments in Swift can be nested(嵌套) inside other multiline comments(多文本注释可以被嵌套). You write nested comments by starting a multiline comment block and then starting a second multiline comment within the first block. The second block is then closed, followed by the first block:
1 | /* this is the start of the first multiline comment |
Nested multiline comments enable you to comment out large blocks of code quickly and easily, even if the code already contains multiline comments.
通过多文本注释,你可以迅速注释掉一大块代码,即使代码中已经包含了其他多文本注释
Semicolons(分号)
Unlike many other languages, Swift does not require you to write a semicolon (;) after each statement in your code, although you can do so if you wish. However, semicolons are required if you want to write multiple separate statements on a single line:
1 | let cat = "🐱"; print(cat) |
Integers
Integers are whole numbers with no fractional component(不含分数), such as 42
and -23
. Integers are either signed(有符号) (positive(正), zero, or negative(负)) or unsigned(无符号) (positive or zero).
Swift provides signed and unsigned integers in 8, 16, 32, and 64 bit forms. These integers follow a naming convention(命名方式) similar to C, in that an 8-bit unsigned integer is of type UInt8, and a 32-bit signed integer is of type Int32. Like all types in Swift, these integer types have capitalized names(大写命名).
U表示无符号,Int32表示32位
Integer Bounds(整数范围)
You can access(访问) the minimum and maximum values of each integer type(每个整数类型) with its min and max properties(属性):
1 | let minValue = UInt8.min // minValue is equal to 0, and is of type UInt8 |
The values of these properties are of the appropriate-sized number type (such as UInt8 in the example above) and can therefore(因而) be used in expressions(表达式) alongside(在什么旁边) other values of the same type.
这些属性的值是一个合适的数字类型,比如上述例子中的UInt8,因而可以被用于表达式中,在其他同类型的值的旁边
Int
In most cases, you don’t need to pick a specific(明确的) size of integer to use in your code. Swift provides an additional(另外的) integer type(整数类型), Int
, which has the same size as the current platform’s native word size(其有着和当前平台的原生字长度相同的长度):
- On a 32-bit platform, Int is the same size as Int32.
- On a 64-bit platform, Int is the same size as Int64.
Unless you need to work with a specific size of integer, always use Int for integer values in your code. This aids(帮助) code consistency(一致性) and interoperability(协同能力). Even on 32-bit platforms(即使在32-bit平台上), Int can store(存储) any value between -2,147,483,648 and 2,147,483,647, and is large enough for many integer ranges(整数范围).
UInt
Swift also provides an unsigned integer type(无符号类型), UInt, which has the same size as the current platform’s native word size(当前平台的原生字长度):
- On a 32-bit platform, UInt is the same size as UInt32.
- On a 64-bit platform, UInt is the same size as UInt64.
NOTE
Use
UInt
only when you specifically need an unsigned integer type with the same size as the platform’s native word size. If this is not the case, Int is preferred(首选的), even when the values to be stored are known to be non-negative(即使存储的值已经知道是一个无符号类型). A consistent(一致性) use of Int for integer values aids(帮助) code interoperability(协调能力), avoids the need to convert between different number types(避免两个数字类型之间的转换), and matches integer type inference(整数类型推断), as described in Type Safety and Type Inference.
Floating-Point Numbers
Floating-point numbers(浮点数) are numbers with a fractional component(有分数部分的数), such as 3.14159
, 0.1
, and -273.15
.
Floating-point types can represent(表示) a much wider range(值域) of values than integer types, and can store numbers that are much larger or smaller than can be stored in an Int. Swift provides two signed(有符号的) floating-point number types:
- Double represents a 64-bit floating-point number.
- Float represents a 32-bit floating-point number.
NOTE
Double
has a precision(精确度) of at least 15 decimal digits(小数), whereas(但是) the precision of Float can be as little as 6 decimal digits(float只有6位小数). The appropriate(适当的) floating-point type to use depends on the nature and range of values you need to work with in your code. In situations where either type would be appropriate, Double is preferred(如光两种类型都是恰当的,Double类型将是首选的).