Language Guide --- The Basics

2017-10-20  本文已影响0人  岛主_changdao

在swift中的optional类型就像在OC中使用nil一样,但是它可以用于任何类型,而不仅仅是类。
swift是一种类型安全的语言,它甚至能够阻止你把一个optional string类型的变量传给一个需要string类型的代码块。

Constants and Variables

Declaring Constants and Variables

你可以在一行声明多个常量或变量,使用逗号分隔。

var x = 0.0, y = 0.0, z = 0.0

Type Annotations

在变量或常量后加一个冒号,然后跟着一个空格,空格之后是需要使用的类型。

var welcomeMessage: String

可以在一行声明多个同类型的变量(⚠️本文中的“变量” 指的是变量和常量两种,下同。注意根据语境区分。),只在最后做类型声明。

var red, green, blue: Double

如果声明变量时没有赋初值,必须做类型声明。

Naming Constants and Variables

变量的名字几乎可以包含任意字符。不能以数字开头。一旦使用一个名字声明了变量,就不能再使用了。也不能做常量变量之间的转换。

Printing Constants and Variables

print()
没有什么好说的。

Comments

单行注释 //
多行注释 /* */
与c语言不同的是,多行注释可以嵌套在多行注释中。

Semicolons

swift不需要在每行语句结束后加分好,你要是愿意写页没人管你。
但是,如果一行有多条语句,那就要加分号分隔了。

Integers

跟C语言类似,有8位、16位、32位、64位的有符号和无符号整型。例如 UInt8 、Int32。

Integer Bounds

使用 min 和 max 属性获得某个类型整型的最值。

let minValue = UInt8.min  // minValue is equal to 0, and is of type UInt8
let maxValue = UInt8.max  // maxValue is equal to 255, and is of type UInt8

Int

绝大多数情况下,你不需要去指定整型的大小。swift提供了一个Int类型,这个类型跟平台有关。
当然还有一个 UInt 类型。

Floating-Point Numbers

Double : 64 位, 至少15位小数
Float : 32位, 6位小数。

Type Safety and Type Inference

swift是一种类型安全的语言,它不意味着你声明变量的时候必须指定它的类型,因为编译器会推断出变量的类型。即使编译器可以为我们做一些类型判断的工作,但是变量是可变类型还是不可变的还是需要开发者指定的。

Numeric Literals

为了增强可读性,整型和浮点型的变量可以在前面加0、在数字间加下划线。

let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1

Numeric Type Conversion

通常使用整型就使用Int,即使这些数都是正数。这样的好处之一是,它能与编译器推断的类型匹配。而且指定整型的位数,会带来额外的开销。

Integer Conversion

let twoThousand: UInt16 = 2_000
let one: UInt8 = 1
let twoThousandAndOne = twoThousand + UInt16(one)

UInt16不能与UInt8相加。

Integer and Floating-Point Conversion

let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = Double(three) + pointOneFourOneFiveNine

let integerPi = Int(pi)

浮点型转整型,采用去尾法。

Type Aliases

为已经存在的类型声明一个别名,使用typealias关键字。

typealias AudioSample = UInt16

Booleans

swift的布尔类型是Bool,它有两种常量值:true 和 false。

Tuples

元组内的变量类型可以不相同。

let http404Error = (404, "Not Found")

可以把元组的内容分解成多个变量或常量。

let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
// Prints "The status code is 404"

如果你只需要元组的部分内容,把不关心的部分使用_代替。

let (justTheStatusCode, _) = http404Error

也可以使用index取得元组的某个内容。index start from 0。

print("The status message is \(http404Error.1)")
// Prints "The status message is Not Found"

当定义元组的时候,可以给元素命名。然后就可以通过命名取值了。

let http200Status = (statusCode: 200, description: "OK")
print("The status code is \(http200Status.statusCode)")

元组作函数的返回值特别好用。为了临时返回不同类型的值,不用组织一个复杂的数据结构。

Optionals

当可能没有值的时候需要使用optional。

let possibleNumber = "123a"
let convertedNumber = Int(possibleNumber)
// convertedNumber is inferred to be of type "Int?", or "optional Int"

nil

不能给一个非optioanl类型的变量赋值nil。
没有给optional类型的变量赋初值的时候,会被自动设置成nil。

If Statements and Forced Unwrapping

如果你已经知道了optional类型的变量有值,可以在变量后加上!来取它的值。

if convertedNumber != nil {
    print("convertedNumber has an integer value of \(convertedNumber!).")
}

Optional Binding

在 if 和 while 中可以检查optional变量是否有值,如果有值临时赋值给一个常量或变量。

if let actualNumber = Int(possibleNumber) {
    print("\"\(possibleNumber)\" has an integer value of \(actualNumber)")
} else {
    print("\"\(possibleNumber)\" could not be converted to an integer")
}

可以在 if 中判断多个条件,使用逗号分隔。只要一个为nil 或 false,整体就为false。

if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {
    print("\(firstNumber) < \(secondNumber) < 100")
}

Implicitly Unwrapped Optionals

如果能确定一个optional 的变量在某次赋值之后就不会变nil了,可以用隐式解析可选类型代替(String!)。

let possibleString: String? = "An optional string."
let forcedString: String = possibleString! // requires an exclamation mark

let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString // no need for an exclamation mark

隐式解析可选类型也是可选类型,也可以做 if let。它跟可选类型的区别是,每次使用不需要判断了。提高了效率。

如果一个 String!类型变量的值是nil,你去取它的值,会得到一个运行时的错误。

Assertions and Preconditions

断言和前提条件会在运行时检查,确保某些代码在满足条件执行。如果判断结果为true,代码能继续执行;如果为false,程序被中断。

断言只在debug模式下有效。
前提条件在debug和build模式下都只执行。

Debugging with Assertions

当断言的条件为false时,可以输出一条语句。

let age = -3
assert(age >= 0, "A person's age can't be less than zero.")

也可以省略输出语句

assert(age >= 0)

可以使用assertionFailure函数表明,断言已经失败了。

if age > 10 {
    print("You can ride the roller-coaster or the ferris wheel.")
} else if age > 0 {
    print("You can ride the ferris wheel.")
} else {
    assertionFailure("A person's age can't be less than zero.")
}

Enforcing Preconditions

例如,使用前提条件检查下表是否越界、函数的参数是否有效。

precondition(index > 0, "Index must be greater than zero.")

上一篇下一篇

猜你喜欢

热点阅读