iOS-Swift

Swift是一门新的iOS系统的开发语言,其更轻量级,类似脚本语言,支持ARC以及Playground。Playground文件可以在修改代码时,立即看到结果。

Swift相比于OC有很多优势,例如,type-safe, 会做类型检查,避免类型转换异常;引入Optional类型,不用每次都用if语句判断一个值是否为nil;引入Tuples,可以在函数中一次返回多个不同类型的值。

下面是Swift的语法介绍。

Format

Print

无需导入输入输出或者字符串库:

1
print("Hello, world!")

如果想不自动换行:

1
print("nimei", terminator:"")

Comments

1
2
3
4
5
6
// This is a comment.
/* This is also a comment
but is written over multiple lines. */
/* This is the start of the first multiline comment.
/* This is the second, nested multiline comment. */
This is the end of the first multiline comment. */

注意,”/*”可以嵌套。

Semicolons

一般不需要加”;”号,除非多行写成一行:

1
let cat = "🐱"; print(cat)

Simple Values

用let定义常量,而var定义变量。不用定义类型:

1
2
3
var myVariable = 42
myVariable = 50
let myConstant = 42

如果需要显式定义,可以这样写:

1
let explicitDouble: Double = 70

没有隐式的类型转换,如果需要类型转换,需要显示定义:

1
let widthLabel = "The width is " + String(94)

如果是在字符串中,可以用“\“+”()”来转换:

1
2
3
4
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."

用”[]”来创建Array和Dictionary:

1
2
3
4
5
6
7
8
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"

var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"

定义一个空的需要用初始化函数:

1
2
let emptyArray = [String]()
let emptyDictionary = [String: Float]()

如果是已经知道类型的变量,可以直接这样写:

1
2
shoppingList = []
occupations = [:]

用”?”定义Optional类型,Optional类型可以有值,也可以为nil。用”??”可以给Optional类型赋值一个默认值:

1
2
3
let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"

Control Flow

if语句:必须是跟着Boolean类型,不能是数字,不会隐式跟0比较:

1
2
3
4
5
6
var score = 51
if score > 51 {
score = 100
} else {
score = 0
}

if-let语句:必须是跟着Optional类型,如果Optional类型有值,则直接赋值,进入if语句,如果没有,则进入else语句:

1
2
3
4
5
6
7
8
var optionalString: String? = "Hello"
print(optionalString == nil)

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}

switch:支持任意格式的数据和表达式,不止整形和等式.同时,可以用let进行局部赋值。

1
2
3
4
5
6
7
8
9
10
11
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}

for-in:

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

let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
print(largest)

while:

1
2
3
4
5
6
7
8
9
10
11
var n = 2
while n < 100 {
n = n * 2
}
print(n)

var m = 2
repeat {
m = m * 2
} while m < 100
print(m)

for:可以用”..<”来局部遍历索引。

1
2
3
4
5
var total = 0
for i in 0..<4 {
total += i
}
print(total)

Functions and Closures

func:

“->”来定义返回值:

1
2
3
4
func greet(person: String, day: String) -> String {
return "Hello \(person), today is \(day)."
}
greet(person: "Bob", day: "Tuesday")

参数前可以设置别名,或者用“_”表示别名为空:

1
2
3
4
func greet(_ person: String, on day: String) -> String {
return "Hello \(person), today is \(day)."
}
greet("John", on: "Wednesday")

参数可以定义成不定数的:

1
2
3
4
5
6
7
8
9
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(numbers: 42, 597, 12)

返回值可以用名称或者数字做索引:

1
2
3
4
5
6
7
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
...
return (min, max, sum)
}
let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9])
print(statistics.sum)
print(statistics.2)

Func可以嵌套

1
2
3
4
5
6
7
8
9
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
returnFifteen()

Func可以作为参数和返回值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(list: numbers, condition: lessThanTen)

func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)

Closure

Closure用“{}”包含,并用in分割参数返回值和具体实现:

1
2
3
4
5
{
(number: Int) -> Int in
let result = 3 * number
return result
}

如果Closure的类型已经确定,可以更精简地写:

1
2
let mappedNumbers = numbers.map({ number in 3 * number })
print(mappedNumbers)

除了用名字,也可以用数字索引来表示参数:

1
2
let sortedNumbers = numbers.sorted { $0 > $1 }
print(sortedNumbers)

Objects and Classes

Classes:

定义:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class NamedShape {
var numberOfSides: Int = 0
var name: String

init(name: String) {
self.name = name
}

deinit {
// Clean up
}

func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}

注意,Class的每个属性值都需要赋值,可以在定义时,也可以在构造函数中。

继承和重写:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Square: NamedShape {
var sideLength: Double

init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 4
}

func area() -> Double {
return sideLength * sideLength
}

override func simpleDescription() -> String {
return "A square with sides of length \(sideLength)."
}
}

let test = Square(sideLength: 5.2, name: "my test square")
test.area()
test.simpleDescription()

Get/Set:(可以用newValue指代参数值)

1
2
3
4
5
6
7
8
var perimeter: Double {
get {
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}

WillSet/DidSet:(在Set执行前后会被调用)

1
2
3
4
5
6
7
8
var square: Square {
willSet {
triangle.sideLength = newValue.sideLength
}
didSet {
print(oldValue.sideLength)
}
}

Objects:

对于是Optional类型的对象,可以用“?”来进行判断,如果值为nil,则结果直接为nil,否则为具体值。但是赋值式左边的类型是Optional类型。

1
2
let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")
let sideLength = optionalSquare?.sideLength

Enumerations and Structures

Enumerations:

Enum的Raw Values的类型,可以是Int, Float以及String。Int类型的默认从0开始,也可以强制设置为其他。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
enum Rank: Int {
case ace = 1
case two, three, four, five, six, seven, eight, nine, ten
case jack, queen, king
func simpleDescription() -> String {
switch self {
case .ace:
return "ace"
case .jack:
return "jack"
case .queen:
return "queen"
case .king:
return "king"
default:
return String(self.rawValue)
}
}
}
let ace = Rank.ace
let aceRawValue = ace.rawValue

Raw Values类型也可以不设置:

1
2
3
enum Suit {
case spades, hearts, diamonds, clubs
}

可以直接用init?(rawValue:)来创造一个实例:

1
2
3
if let convertedRank = Rank(rawValue: 3) {
let threeDescription = convertedRank.simpleDescription()
}

还可以添加参数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
enum ServerResponse {
case result(String, String)
case failure(String)
}

let success = ServerResponse.result("6:00 am", "8:09 pm")
let failure = ServerResponse.failure("Out of cheese.")

switch success {
case let .result(sunrise, sunset):
print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
case let .failure(message):
print("Failure... \(message)")
}

Structs

Structs跟Classes的区别在于:Structs都是值传递,Classes都是引用传递。

1
2
3
4
5
6
7
8
9
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
}
let threeOfSpades = Card(rank: .three, suit: .spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()

Protocols and Extensions

Protocols

1
2
3
4
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}

Classed,Enumerations, Structs都可以适配Protocols:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class."
var anotherProperty: Int = 69105
func adjust() {
simpleDescription += " Now 100% adjusted."
}
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription

struct SimpleStructure: ExampleProtocol {
var simpleDescription: String = "A simple structure"
mutating func adjust() {
simpleDescription += " (adjusted)"
}
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription

注意:mutating关键字在Structs中使用,用于标识会修改Structs元素,而Classes不用,Classes的方法本来就可以修改Classes。

Protocols可以当类型使用:

1
2
let protocolValue: ExampleProtocol = a
print(protocolValue.simpleDescription)

Extensions

Extensions用于给一个已有的类型添加功能,可以结合Extensions和Protocol一起使用:

1
2
3
4
5
6
7
8
9
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
print(7.simpleDescription)

Error Handling

Error定义:

1
2
3
4
5
enum PrinterError: Error {
case outOfPaper
case noToner
case onFire
}

throw来抛出异常,throws关键字来标识Func:

1
2
3
4
5
6
func send(job: Int, toPrinter printerName: String) throws -> String {
if printerName == "Never Has Toner" {
throw PrinterError.noToner
}
return "Job sent"
}

do-catch来捕获异常,在do中用try来标识可能抛出异常的地方:

1
2
3
4
5
6
do {
let printerResponse = try send(job: 1040, toPrinter: "Bi Sheng")
print(printerResponse)
} catch {
print(error)
}

多catch:

1
2
3
4
5
6
7
8
9
10
do {
let printerResponse = try send(job: 1440, toPrinter: "Gutenberg")
print(printerResponse)
} catch PrinterError.onFire {
print("I'll just put this over here, with the rest of the fire.")
} catch let printerError as PrinterError {
print("Printer error: \(printerError).")
} catch {
print(error)
}

try?来转换结果为Optional,如果有异常,则结果为nil,否则则为实际值:

1
2
let printerSuccess = try? send(job: 1884, toPrinter: "Mergenthaler")
let printerFailure = try? send(job: 1885, toPrinter: "Never Has Toner")

defer来定义在Func中其他代码都执行结束后,执行的代码(类似finally):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var fridgeIsOpen = false
let fridgeContent = ["milk", "eggs", "leftovers"]

func fridgeContains(_ food: String) -> Bool {
fridgeIsOpen = true
defer {
fridgeIsOpen = false
}

let result = fridgeContent.contains(food)
return result
}
fridgeContains("banana")
print(fridgeIsOpen)

Generics

来定义Generics类型:

1
2
3
4
5
6
7
8
func makeArray<Item>(repeating item: Item, numberOfTimes: Int) -> [Item] {
var result = [Item]()
for _ in 0..<numberOfTimes {
result.append(item)
}
return result
}
makeArray(repeating: "knock", numberOfTimes:4)

Classed,Enumerations, Structs都定义Generics类型:

1
2
3
4
5
6
enum OptionalValue<Wrapped> {
case none
case some(Wrapped)
}
var possibleInteger: OptionalValue<Int> = .none
possibleInteger = .some(100)

where关键字在Func后,来列出要求,例如,要求类型必须适配Protocol,要求两种类型必须相同,要求一个Class必须有一个指定的父类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func anyCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> Bool
where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
anyCommonElements([1, 2, 3], [3])

<T: Equatable> 等同于 <T> ... where T: Equatable>