## The Basics
let聲明常量,var聲明變量
You can access the minimum and maximum values of each integer type with its min and max properties.
雖然有UInt,但能用Int的時候就用Int。
~~~
// 各種進制的字面量表示
let decimalInteger = 17
let binaryInteger = 0b10001 // 17 in binary notation
let octalInteger = 0o21 // 17 in octal notation
let hexadecimalInteger = 0x11 // 17 in hexadecimal notation
// 更易于閱讀的寫法
let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1
~~~
Floating-point values are always truncated when used to initialize a new integer value in this way. This means that 4.75 becomes 4, and -3.9 becomes -3.
~~~
// 定義類型別名 typealias
typealias AudioSample = UInt16
// optional binding,只有當yyy是optional的時候才可以這樣用。optional的yyy非空時為真,將yyy中的值取出賦給xxx,空時(nil)為假;
if let xxx = yyy {
// do something
} else {
// do other thing
}
// decompose一個tuple時,對于不想使用的元素用’_’接收
let http404Error = (404, "Not Found")
let (justTheStatusCode, _) = http404Error
println("The status code is \(justTheStatusCode)")
// prints "The status code is 404
let possibleNumber = "123"
let convertedNumber = possibleNumber.toInt()
// convertedNumber is inferred to be of type "Int?", or "optional Int”,因為toInt()可能會失敗(比如“123a”)導致返回nil
~~~
You can use an if statement to find out whether an optional contains a value. If an optional does have a value, it evaluates to true; if it has no value at all, it evaluates to false.
Once you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional’s name. The exclamation mark effectively says, “I know that this optional definitely has a value; please use it.” This is known as forced unwrapping of the optional’s value。
If you define an optional constant or variable without providing a default value, the constant or variable is automatically set to nil for you.
- About Swift
- The Basics
- Basic Operators
- String and Characters
- Collection Types
- Control Flow
- Functions
- Closures
- Enumerations
- Classes and Structures
- Properties
- Methods
- Subscripts
- Inheritance
- Initialization
- Deinitialization
- Automatic Reference Counting
- Optional Chaining
- Type Casting
- Nested Types
- Extensions
- Protocols
- Generics
- Advanced Operators
- A Swift Tour