Swift语法基础:6

前面我们知道了枚举类型和结构体的声明, 嵌套, 以及基本的使用, 现在让我们来看看Swift中的另外两个, 一个是Protocol(协议), 一个是Extensions(类别):


1.声明Protocol

protocol ExampleProtocol{
    var simpleDescription: String {get}
    mutating func adjust()
}

PS: 在声明协议的时候, 如果你要修改某个方法属性, 你必须的在该方法前加上mutating这个关键字, 否则不能修改.


2.使用Protocol

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
println(aDescription)
// 打印出来的结果是: A very simple class. Now 100% adjusted.

同样的, 在结构体里一样可以使用, 但是必须的加上mutating:

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

var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription
println(bDescription)
// 打印出来的结果是: A simple structure. (adjusted)

Protocol也可以这么使用:

let protocolValue:ExampleProtocol = a
println(protocolValue.simpleDescription)
// 打印出来的结果:A very simple class. Now 100% adjusted.

PS: 这里的a是前面例子里面的a.


3.声明Extensions

extension Int: ExampleProtocol {
    var simpleDescription: String {
        return "The number (self)"
    }
    mutating func adjust() {
        self += 42
    }
}
var ext = 7.simpleDescription
println(ext)
// 打印出来的结果: The number 7

好了, 这次我们就讲到这里, 下次我们继续~~

原文地址:https://www.cnblogs.com/iOSCain/p/4333132.html