官文:从今天开始开发iOS应用(Swift)第一章1~3节中英对照

《Start developing iOS APPs today:官文iOS开发新手引导》

————————————————————————————————————————————————————————————

第一章 Learn the Essentials of Swift:Swift概述

Your first lesson is presented in the form of a guided Swift playground, a type of file that lets you change and interact with the code directly in Xcode and see the result immediately. Playgrounds are great for learning and experimenting, and this one helps get you up to speed on fundamental Swift concepts.

文档中的所有代码都使用XCode的Playground工具进行演示。

Playground允许用户同自己的代码进行实时交互。通过Playground,用户可以快速对自己的代码功能进行验证。

并且,利用它可以快速掌握Swift的基本概念。

1.1 Learning Objectives:要点一览

At the end of the lesson, you’ll be able to:

  1. Differentiate between a constant and a variable
  2. Know when to use implicit and when to use explicit type declarations
  3. Understand the advantage of using optionals and optional binding
  4. Differentiate between optionals and implicitly unwrapped optionals
  5. Understand the purpose of conditional statements and loops
  6. Use switch statements for conditional branching beyond a binary condition
  7. Use where clauses to impose additional constraints in conditional statements
  8. Differentiate between functions, methods, and initializers
  9. Differentiate between classes, structures, and enumerations
  10. Understand syntax for (and basic concepts behind) inheritance and protocol conformance
  11. Determine implicit types and find additional information using Xcode’s quick help shortcut (Option-click)
  12. Import and use UIKit

经过本文的学习,您将能够:

  1. 区分Swift中的常量(Constant)和变量(Variable);
  2. 知道何时需要进行显式类型声明;
  3. 了解使用optional以及optional binding的优势之处;
  4. 知道optional隐式解包optional的区别;
  5. 明白条件语句和循环语句的作用;
  6. 知道switch语句的用法,以及它同二元选择的不同;
  7. 使用where语句为条件语句增加额外的条件限制;
  8. 知道函数、方法及初始化器的不同之处;
  9. 知道类、结构体和枚举之间的不同;
  10. 知道如何使用继承(inheritance)和协议(protocol),以及它们背后的基本原理;
  11. 知道如何使用Xcode的快速帮助来确定变量隐式类型以及额外信息;
  12. 了解如何导入和使用UIKit框架。

1.2 Basic Types:基本数据类型

A constant is a value that stays the same after it’s declared the first time, while a variable is a value that can change. A constant is referred to as immutable, meaning that it can’t be changed, and a variable is mutable. If you know that a value won’t need to be changed in your code, declare it as a constant instead of a variable.
Use let to make a constant and var to make a variable.

1.2.1 常量和变量:

常量:指的是值在定义时指定,并且运行时保持不变的量。

变量:指的是值可以随意改变的量。

一个常量也被称为不可变量(immutable),即它的值在运行时不能被改变;而变量则被称为可变量。

如果确定一个值在代码中不会被改变,则可以将它定义为一个常量。

1.2.2 常量和变量的定义

在Swift中,用let关键字来定义常量,用var关键字来定义变量:

var myVariable = 42     //定义一个变量myVariable,值为42
myVariable = 50         //改变myVariable的值成50
let myConstant = 42     //定义一个常量myConstant,值为42

Every constant and variable in Swift has a type, but you don’t always have to write the type explicitly. Providing a value when you create a constant or variable lets the compiler infer its type. In the example above, the compiler infers that myVariable is an integer because its initial value is an integer. This is called type inference. Once a constant or variable has a type, that type can’t be changed.
If the initial value doesn’t provide enough information (or if there is no initial value), specify the type by writing it after the variable, separated by a colon.

1.2.3 类型推断

Swift中所有的常量或变量都有自己的数据类型,但并不是每次都需要进行显式类型声明。在实际中,可以直接为变量或常量提供一个值,然后由编译器来推断它的数据类型。上面的代码中,编译器推断myVariable的类型为integer,因为它是由一个整型数据初始化而来的,这个由编译器确定量值类型的过程被称为类型推断(type inference)。并且一旦常量或变量拥有类型,便无法再次修改。

如果用于初始化的值无法提供足够的类型信息(或者没有在定义变量的时候对其进行初始化),此时就必须显式指定类型:

let implicitInteger = 70    //常量类型为integer
let implicitDouble = 70.0   //常量类型为double
let explicitDouble: Double = 70     //显式指定类型为double,即使用于初始化这个常量的数为一个整型数

1.2.4 类型转换

Values are never implicitly converted to another type. If you need to convert a value to a different type, explicitly make an instance of the desired type. Here, you convert an Int to a String.

Swift中不会进行隐式类型转换。如果你想将一个值转换为其他类型,需要显式地进行类型转换。下面的代码中将一个整型转换为一个字符串类型:

let label = "The width is "
let width = 94
let widthLabel = label + String(width)  //将width转换为字符串类型,并连接到label字符串的尾部

There’s an even simpler way to include values in strings: Write the value in parentheses, and write a backslash () before the parentheses. This is known as string interpolation.

还有一种简单的方法可以实现上面代码中的功能:将数值写在括号内,然后再加上“\”前导。这个方法被称为字符串插值法(string interpolation):

let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."   //I have 3 apples.
let fruitSummary = "I have \(apples + oranges) pieces of fruit."    //I have 8 pieces of fruit.

1.2.5 可选类型(optionals)

Use optionals to work with values that might be missing. An optional value either contains a value or contains nil (no value) to indicate that a value is missing. Write a question mark (?) after the type of a value to mark the value as optional.

使用可选类型来表示那些值可能是nil的量。可选类型量或含有值,或包含nil(即无值)。在变量类型之后添加一个问号“?”表示可选类型:

let optionalInt: Int? = 9

1.2.6 可选类型解包(unwrap)

To get the underlying type from an optional, you unwrap it. You’ll learn unwrapping optionals later, but the most straightforward way to do it involves the force unwrap operator (!). Only use the unwrap operator if you’re sure the underlying value isn’t nil.

为获取可选类型量的值,需要对其进行解包(unwrap,对应封包wrap),在后面将学习如何对可选类型量进行解包操作(unwrapping)。这里有一个最为直接的解包办法,就是使用强制解包操作符“!”,需要注意被解包的可选类型量值必须非空:

let actualInt: Int = optionalInt!   //对optionalInt解包后,将其赋值给actualInt

Optionals are pervasive in Swift, and are very useful for many situations where a value may or may not be present. They’re especially useful for attempted type conversions.

可选类型在Swift中使用十分普遍,尤其是在尝试类型转换时:

var myString = "7"
//possibleInt的声明自动为:var possibleInt : Int?
var possibleInt = Int(myString)     //possibleInt值为7
//若将myString改变为无法转换成整型的值,则possibleInt为nil
myString = "banana"
possibleInt = Int(myString)     //possibleInt值为nil

In this code, the value of possibleInt is 7, because myString contains the value of an integer. But if you change myString to be something that can’t be converted to an integer, possibleInt becomes nil.

代码中,possibleInt的值为7,因为myString字符串里为“7”。但是如果你改变myString的值,让它无法转换为整型,那么possibleInt的值就会是nil。(这样的好处是不用考虑myString是否可以转换为整型,编程更加灵活)

1.2.7 数组(Array)

An array is a data type that keeps track of an ordered collection of items. Create arrays using brackets ([]), and access their elements by writing the index in brackets. Arrays start at index 0.

数组:是一个包含多个元素的有序集合。

数组可以对自己内部的所有元素进行追踪。使用方括号“[]”建立数组,如果想访问数组中某个元素,则在方括号内指定元素下标进行访问,并且,数组起始下标为0:

//定义数组ratingList
var ratingList = ["Poor", "Fine", "Good", "Excellent"]
//修改第二个元素为OK
ratingList[1] = "OK"
//打印数组
ratingList

To create an empty array, use the initializer syntax. You’ll learn more about initializers in a little while.

可以使用初始化器(initializer)语法建立一个空数组(之后会学习更多关于初始化器的相关内容):

// 建立一个空数组,元素类型为String
let emptyArray = [String]()

1.2.7 隐式已解包可选类型(implicitly unwrapped optional)

An implicitly unwrapped optional is an optional that can also be used like a nonoptional value, without the need to unwrap the optional value each time it’s accessed. This is because an implicitly unwrapped optional is assumed to always have a value after that value is initially set, although the value can change. Implicitly unwrapped optional types are indicated with an exclamation mark (!) instead of a question mark (?).

隐式已解包可选类型:指的是不需要每次访问都进行解包操作的可选类型。

隐式已解包可选类型假定该类型量的值一旦初始化后就一直都是非空。

使用“!”代替”?”进行定义:

var implicitlyUnwrappedOptionalInt: Int!

You’ll rarely need to create implicitly unwrapped optionals in your own code. More often, you’ll see them used to keep track of outlets between an interface and source code (which you’ll learn about in a later lesson) and in the APIs you’ll see throughout the lessons.

实际使用时很少自定义隐式已解包可选类型,它们更多地被用在界面接口和源代码之间的连接追踪中。

1.3 Control Flow:流程控制

Swift has two types of control flow statements. Conditional statements, like if and switch, check whether a condition is true—that is, if its value evaluates to the Boolean true—before executing a piece of code. Loops, like for-in and while, execute the same piece of code multiple times.
An if statement checks whether a certain condition is true, and if it is, the if statement evaluates the code inside the statement. You can add an else clause to an if statement to define more complex behavior. An else clause can be used to chain if statements together, or it can stand on its own, in which case the else clause is executed if none of the chained if statements evaluate to true.

Swift中有两类流程控制语句:条件语句,如if或switch。循环语句,如for in以及while。(废话未翻)

1.3.1 条件语句:

let number = 23

if number < 10
{
    print("The number is small")
}
else if number > 100
{
    print("The number is pretty big")
}
else
{
    print("The number is between 10 and 100")
}

Statements can be nested to create complex, interesting behavior in a program. Here’s an example of an if statement with an else clause nested inside a for-in statement (which iterates through each item in a collection in order, one-by-one).

1.3.2 语句嵌套

下面代码中在if-else中嵌套了一个for-in语句(for in 语句按顺序遍历集合中每一个元素):

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores
{
    if score > 50
    {
        teamScore += 3
    }
    else
    {
        teamScore += 1
    }
}
print(teamScore)

1.3.3 可选绑定

Use optional binding in an if statement to check whether an optional contains a value.

在if中使用可选绑定(optional binding)来判断可选类型量中是否包含有值:

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
//let name = optionalName,若optionalName不空,则条件为真
if let name = optionalName
{
    greeting = "Hello, \(name)"
}

If the optional value is nil, the conditional is false, and the code in braces is skipped. Otherwise, the optional value is unwrapped and assigned to the constant after let, which makes the unwrapped value available inside the block of code.

如果可选类型的值为nil,则条件为假。反之,则将可选类型变量optionalName解包并赋值给常量name。

1.3.4 where语句

You can use a single if statement to bind multiple values. A where clause can be added to a case to further scope the conditional statement. In this case, the if statement executes only if the binding is successful for all of these values and all conditions are met.

利用where语句,可以在单一if条件判断中绑定多个值,即利用where可以扩展条件语句的判断范围。下面的例子中,只有当绑定的所有值和所有条件都真时才执行if后面的语句块内容:

var optionalHello: String? = "Hello"
//当optionalHello非空,且hello的前缀为H,并且optionalName非空,才为真
if let hello = optionalHello where hello.hasPrefix("H"), let name = optionalName
{
    greeting = "\(hello), \(name)"
}

1.3.5 switch语句

Switches in Swift are quite powerful. A switch statement supports any kind of data and a wide variety of comparison operations—it isn’t limited to integers and tests for equality. In this example, the switch statement switches on the value of the vegetable string, comparing the value to each of its cases and executing the one that matches.

switch语句支持任意类型数据的判断,以及多种比较操作:并不局限于整型和判等测试。下面的例子中对vegetable字符串进行判断,匹配相应条件:

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."
}

需要注意的是:每一个switch都必须有一个default。

Notice how let can be used in a pattern to assign the value that matched that part of a pattern to a constant. Just like in an if statement, a where clause can be added to a case to further scope the conditional statement. However, unlike in an if statement, a switch case that has multiple conditions separated by commas executes when any of the conditions are met.

After executing the code inside the switch case that matched, the program exits from the switch statement. Execution doesn’t continue to the next case, so you don’t need to explicitly break out of the switch statement at the end of each case’s code.

Switch statements must be exhaustive. A default case is required, unless it’s clear from the context that every possible case is satisfied, such as when the switch statement is switching on an enumeration. This requirement ensures that one of the switch cases always executes.

在switch语句中同样可以使用where来添加更多判断条件。并且不同于if,如果有逗号分隔的多个条件,则只要任意一个条件满足,就执行对于语句。

当执行完匹配的case后,程序会自动退出switch语句(不用再break了)。

另外,switch语句必须拥有一个default分支。
>
You can keep an index in a loop by using a Range. Use the half-open range operator ( ..<) to make a range of indexes.

1.3.6 循环区间

可以使用区间(Range)来表示循环下标。使用半开区间操作符“..<”指定下标范围:

var firstForLoop = 0
for i in 0..<4 {
    firstForLoop += i
}
print(firstForLoop)

The half-open range operator (..<) doesn’t include the upper number, so this range goes from 0 to 3 for a total of four loop iterations. Use the closed range operator ( …) to make a range that includes both values.

半开区间操作符中不包含上界,即上面的例子中0..<4,实际是从0到3循环4次。如果需要包含范围的上界,则可以使用闭区间操作符“…”。

var secondForLoop = 0
for _ in 0...4 {
    secondForLoop += 1
}
print(secondForLoop)

This range goes from 0 to 4 for a total of five loop iterations. The underscore (_) represents a wildcard, which you can use when you don’t need to know which iteration of the loop is currently executing.

上面的代码中循环区间为0到4,共5次循环。下划线“_”表示一个通配符,即当你不需要使用特定循环变量的时候,就可以用下划线代替特定循环变量。

你可能感兴趣的:(swift,ios开发,可选类型,隐式可选)