Swift基础部分

其实Swift也不是很难,只不过看起来有点吃力…一遍看不会,看两遍,两遍看不会,三遍…直到会背…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//
// main.swift
// base
//
// Created by Adrift on 16/5/28.
// Copyright © 2016年 Adrift. All rights reserved.
//

import Foundation

//声明变量跟常量
let maxNumberOfLoginAttempts = 10
var currentLoginAttempt = 0
var x = 0.0, y = "hello", z = 10

//类型标注
var welcomeMessage: String
welcomeMessage = "hello world"
var red, green, blue: Double

//常量和变量的命名
let π = 3.14159
let 你好 = "hello world"
let dogcow = "dogcow"
let `let` = "let"
print("\(`let`)")

//元组
let http404Error = (404, "Not fount")
let (statusCode, statusMessage) = http404Error
print("statusCode:\(statusCode),,,statusMessage:\(statusMessage)")
let (justTheStatusCode, _) = http404Error
print("\(http404Error.0)")
print("\(http404Error.1)")

let http200Status = (statusCode: 200, description: "OK")
print("\(http200Status.statusCode)")

var code: Int? = nil

//if语句以及强制解析
let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
if convertedNumber != nil {
print("\(convertedNumber!)")
}

//可选绑定
if let actualNumber = Int(possibleNumber) {
print("\(possibleNumber) has an integer value of \(actualNumber)")
} else {
print("\(possibleNumber) could not convert to integer")
}
if let firstNumber = Int("3"), secondNumber = Int("2") where firstNumber > secondNumber {
print("\(firstNumber) > \(secondNumber)")
}

//隐式解析可选绑定
let possibleString: String? = "An optional string."
let forcedString: String = possibleString!//需要感叹号获取值

let assumedString: String! = "An implicitly unwrapped option string"
let implicitString: String = assumedString//不需要感叹号获取值

if assumedString != nil {
print(assumedString)
}

if let definiteString = assumedString {
print(definiteString)
}

//错误处理
func canThrowAnError() throws {
//可能抛出错误
}
do {
try canThrowAnError()
//没有错误抛出
} catch {
//有一个错误消息抛出
}

enum Error: ErrorType {
case OutOfCleanDishes
case MissingIngredients
}
func makeASandwich() throws {
//...
}
do {
try makeASandwich()
} catch Error.OutOfCleanDishes{
//washDishes()
} catch Error.MissingIngredients(let ingredients) {
//buyGroceies(ingredients)
}

//使用断言进行调试
let age = -3
//当表达式结果为false时,结果被显示
assert(age >= 0, "A person's age cannot be less than zero")
assert(age >= 0)//不需要断言信息时,可以省略.

原文地址,非常感谢翻译者的持续更新.

–EOF–