对象和类

创建类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Shape {
    var numberOfSides = 0
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()

init构造函数,deinit析构函数

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

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

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

}

类属性必须要设置一个值,要么在声明属性的时候指定,要么在init函数中指定。

继承类, 使用:, 覆写父类的方法必须使用override

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
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)."
    }
}

属性的gettersetter方法,set没有指定参数名时,默认用newValue

 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
class EquilateralTriangle: NamedShape {
    var sideLength: Double = 0.0

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

    var perimeter: Double {
        get {
            return 3.0 * sideLength
        }

        set {
            sideLength = newValue / 3.0
        }
    }

    //var perimeter: Double {
    //    get {
    //        return 3.0 * sideLength
    //    }

    //    set(newPerimeter) {
    //        sideLength = newPerimeter / 3.0
    //    }
    //}

    override func simpleDescription ()->String{
        return "An equilateral triangle with sides of length \(sideLength)"
    }
}

willSetdidSet实现属性观察

 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
class TriangleAndSquare {
    var triangle: EquilateralTriangle {
        willSet {
            square.sideLength = newValue.sideLength
        }
    }

    var square: Square {
        willSet {
            triangle.sideLength = newValue.sideLength

        }
    }

    init(size: Double, name: String){
        square = Square(sideLength: size, name: name)
        triangle = EquilateralTriangle(sideLength: size, name: name)
    }
}

var triganleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")

// 10.0
print(triganleAndSquare.square.sideLength)

// 10.0
print(triganleAndSquare.triangle.sideLength)
triganleAndSquare.square = Square(sideLength: 50, name: "Larger square")

// 50.0
print(triganleAndSquare.triangle.sideLength)

当使用可选值时,可以写个?在运行符前面,如果?前面的值是nil, 所有在?后面的值都是nil,

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

枚举enum

枚举enum类型跟类class一样也可以有方法

 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
enum Rank: Int {
    case ace = 1
    case two, three, four, five, sixe, 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"
        default:
            return String(self.rawValue)
        }
    }
}

let ace = Rank.ace

// 1
let aceRawValue = ace.rawValue

// 2
print(Rank.two.rawValue)

print(ace.simpleDescription())

默认情况下,枚举类型的原始值是从0开始的,然后依次加1,但是可以通过明确赋值,可以改变这个行为。 比如上面的例子,ace就是从1开始,后面的值也依次加1,同时,也可以给枚举类型赋值为字符串或浮点数。

使用init?(rawValue:)初始化一个枚举类型,当这个值是enum类型的值时,就返回枚举类型,否则返回nil

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// 13刚好对应king
if let convertedRank = Rank(rawValue: 13) {
    let threeDescription = convertedRank.simpleDescription() // 13
}


// convertedRank 为nil, if语句不会执行
if let convertedRank = Rank(rawValue: 14) {
    let threeDescription = convertedRank.simpleDescription() // 1
}

如果结构体有原始值的话,可以在初始化时决定它的类型

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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.")
print(success)

switch success {
case let .result(sunrise, sunset):
    print("Sun rise at \(sunrise), Sun set at \(sunset)")
case let .failure(message):
    print("Failure \(message)")
}

结构体struct

struct和类一样,支持初始化和方法,不同之处在于:

struct在代码里总是复制一份(值传参),而类是被引用的(引用传参)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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)
print(threeOfSpades.simpleDescription())

Protocols和Extensions

有点类似javainterface,但是也有不同之处.

1
2
3
4
5
protocol ExampleProtocol {
    var simpleDescription: String { get }
    // 注意关键字mutating
    mutating func adjust()
}

类,枚举和结构体都可以适配协议

 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
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()
print(a.simpleDescription)


struct SimpleStruct: ExampleProtocol {
    var simpleDescription: String = "A very simple struct."

    //注意 mutating 关键字
    mutating func adjust(){
        simpleDescription += " (adjusted)"
    }
}

var b = SimpleStruct()
b.adjust()
print(b.simpleDescription)

注意上面在结构体中声明adjust()方法时,使用了关键字mutating,而在类中并没有使用, 是因为在类中,方法是可以直接修改的。

使用extension可以往已经存在的类型添加方法和计算属性,哪怕是Swift内置的类

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

// 修改内置Int类的行为
print(7.simpleDescription)

我们也可以使用protocol名字来访问实现了这个protocol的方法,但是不在protocol里定义的就不能访问。

1
2
3
4
let protocolValue: ExampleProtocol = SimpleClass()
print(protocolValue.simpleDescription)
//anotherProperty属性虽然在SimpleClass里有,但是它不属于ExampleProtocol, protocolValue访问依然会报错
//print(protocolValue.anotherProperty)

异常处理

可以通过适配Error的protocol来定义错误, 通过throw抛出异常,通过throws标记可能产生异常的方法。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
enum PrinterError: Error {
    case outOfPaper
    case noToner
    case onFire
    case unKown
}


func send(job: Int, toPrinter printerName: String) throws -> String {
    if printerName == "Never Has Toner" {
        throw PrinterError.noToner
    } else if printerName == "outOfPaper" {
        throw PrinterError.outOfPaper
    } else if printerName == "OnFire" {
        throw PrinterError.onFire
    } else if printerName == "UnKown" {
        throw PrinterError.unKown
    }

    return "job sent"
}

有几种方式处理异常,一种是使用do-catch, try写在可能产生异常的代码前面,catch代码块里,如果不指定名字的话,默认用error代表错误。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
do {
    let printerResponse = try send(job:1040, toPrinter: "Never Has Toner")
    print(printerResponse)
} catch {
    print(error)
}


do {
    let printerResponse = try send(job:1440, toPrinter: "UnKown")
    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?。把结果转变为可选值,当有异常出现的时候,异常会被直接忽略,并把结果赋值为nil.

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

使用defer,可以在函数返回前,执行一段代码,无论函数是正常执行或抛出异常,可以在多个函数之间使用defer写一些初始化或清理工作的代码。

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

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

    let result = fridgeContent.contains(food)
    return result
}

fridgeContains("banana")
print(fridgeIsOpen)

泛型

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

print(makeArray(repeating: "knock", numberOfTimes: 4))

泛型不光可以用于函数和方法,还可以用在类,枚举,结构体上面,下面是利用泛型实现Swift标准库里的可选类型

1
2
3
4
5
6
7
enum OptionalValue<Wrapped>{
    case none
    case some(Wrapped)
}

var possibleInteger: OptionalValue<Int> = .none
possibleInteger = .some(100)

使用where关键字在语句前可以限定一些条件

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

anyCommonElements([1, 2, 3], [3])