该文章翻译自apple官方文档:The Swift Programming Language(Swift 4.1)
A Swift Tour -- 一个Swift 旅行
Tradition suggests that the first program in a new language should print the words “Hello, world!” on the screen. In Swift, this can be done in a single line:print("Hello, world!")
译:传统认为,一种新语言的第一个程序应该打印“Hello world!”在屏幕上。 用Swift,它可以用简单的一行代码搞定。
If you have written code in C or Objective-C, this syntax looks familiar to you—in Swift, this line of code is a complete program. You don’t need to import a separate library for functionality like input/output or string handling. Code written at global scope is used as the entry point for the program, so you don’t need a main()function. You also don’t need to write semicolons at the end of every statement.
译:如果你用C或 OC写代码,这语法看起来很熟悉 —— 在 Swift里,这行代码就是一个完整的程序。你不需要为输入/输出或字符串处理之类的功能导入单独的库。在全局范围内编写的代码用作程序的入口点,所以你不需要一个主函数功能。你也不需要在每一个语句的末尾写分号。
This tour gives you enough information to start writing code in Swift by showing you how to accomplish a variety of programming tasks. Don’t worry if you don’t understand something—everything introduced in this tour is explained in detail in the rest of this book.
译:这个旅行给你足够的信息可以开始用Swift写代码,它展示给你怎样完成各项编程任务。不要担心如果你不理解一些部分 ——这个旅行里每一项在本书的其他部分都有详细的介绍。
NOTE
For the best experience, open this chapter as a playground in Xcode. Playgrounds allow you to edit the code listings and see the result immediately.
Download Playground
提示:
为了一个更好的体验,在Xcode的里用一个playground打开本章内容,Playgrounds 允许你编辑代码列表并且立马看结果。
Simple Values -- 简单的值
Use let to make a constant and var to make a variable. The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once. This means you can use constants to name a value that you determine once but use in many places.
1. var myVariable = 42
2. myVariable = 50
3. let myConstant = 42
译:用 let 表示常量,用 var 表示变量,这个常量的值在编译时不需要知道,但是你必须马上赋给它一个确切的值。这意味着你可以用常量去为一个你定义的值命名,这个值可以在多处使用。 A constant or variable must have the same type as the value you want to assign to it. However, 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. 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. let implicitInteger = 70
2. let implicitDouble = 70.0
3. let explicitDouble: Double = 70
EXPERIMENT
Create a constant with an explicit type of Float and a value of 4.
译:常量或变量必须与你赋给它的值有同样的类型.然而,然而你并不必须写出具体的类型.当你创建一个常量或变量时提供一个值可以让编译器判断它的类型,在上面的例子中,编译器判断 myVarible 是一个整数因为它的初始化值是一个整数.
如果这个初始化的值没有提供足够的信息(或者如果没有初始化的值),可以通过在变量后面写下指定的类型,用冒号隔开
尝试1 创建一个有明确类型为Float的常量,值为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.
1. let label = "The width is "
2. let width = 94
3. let widthLabel = label + String(width)
EXPERIMENT
Try removing the conversion to String from the last line. What error do you get?
译:这个值是绝不能换成其他类型的,如果你需要将值转换为不同的类型,明确地做一个期望类型的实例 实验 试着从最后一行移除String转换,你得到什么错误?
There’s an even simpler way to include values in strings: Write the value in parentheses, and write a backslash (\) before the parentheses. For example:
1. let apples = 3
2. let oranges = 5
3. let appleSummary = "I have \(apples) apples."
4. let fruitSummary = "I have \(apples + oranges) pieces of fruit."
EXPERIMENT
Use \() to include a floating-point calculation in a string and to include someone’s name in a greeting.
译:这里有一个更简单的方式去在字符串里包含值:将这个值写进圆括号()里,并且在原括号前写一个反斜杠(\),例如:code 实验 用\()去在字符串里包含一个浮点值的计算并且在问候语里包含某个人的名字
Use three double quotation marks (""") for strings that take up multiple lines. Indentation at the start of each quoted line is removed, as long as it matches the indentation of the closing quotation marks. For example:
let quotation = """
I said "I have \(apples) apples."
And then I said "I have \(apples + oranges) pieces of fruit."
"""
译:用三个双引号(" " ")来表示多行字符串。只要它匹配上结束引用标记的缩格,在每个引用行行头的缩格就是被删除的,例如:code Create arrays and dictionaries using brackets ([]), and access their elements by writing the index or key in brackets. A comma is allowed after the last element.
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
To create an empty array or dictionary, use the initializer syntax.
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
If type information can be inferred, you can write an empty array as [] and an empty dictionary as [:]—for example, when you set a new value for a variable or pass an argument to a function.
- shoppingList
- occupations
译: 1.用([]) 方括号创建数组和字典,通过元素的索引或字典的key值访问到方括号中的元素。最后一个元素后面允许逗号.ex: code
2. 用初始化语法创建一个空数组或字典
3.如果类型信息可以被判断,你可以写一个空数组[],或空字典[:] -- 例如,当你设置一个值为一个变量或传一个参数给函数时.