swift3新路程10协议protocol和扩展extension

声明的关键字就是protocol

我们看一个官方例子

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

枚举、结构体和类都可以使用协议


类使用协议

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
print(aDescription)

类中的方法因为本身就可以改变类所以adjust方法不需要mutating关键字修饰


结构体使用协议
struct SimpleStructure: ExampleProtocol {
    var simpleDescription: String = "A simple structure"
    mutating func adjust() {
        simpleDescription += " (adjusted)"
    }
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription
print(bDescription)

结构体重的方法如果需要改变结构体本身 使用的方法需要使用mutating进行修饰,如果说我们在上面的adjust中不对结构体做任何修改的话,比如说单纯的打印一段文字,不加mutating也是可以的。


枚举使用协议
enum SimpleEnum:ExampleProtocol {
    case out
    mutating func adjust() {
        print(self.simpleDescription)
    }

    var simpleDescription: String{
        get {
            switch self {
            case .out:
                return "A simple enumeration"
            }
        }
    }
}
var c = SimpleEnum.out
c.adjust()
因为官方没看到enum的列子,就找个模照着谢了一个

生命扩展的关键字是extension

我们可以使用扩展为已有的类型添加属性或者方法,我们也可以使用扩展将协议使用在已有的类型中

protocol ProtocolForInt {
    var description:String {get}
    mutating func addOne()
}
extension Int:ProtocolForInt {
    mutating func addOne() {
        self += 1
    }

    var description: String {
        return "This number is \(self)"
    }
}
var a:Int = 4
a.addOne()
print(a.description)


我们声明一个变量,类型定义为上面我们声明的ProtocolForInt协议类型

我们写一个类,同样也是使用上面的协议

<pre name="code" class="plain">class SimpleClassForInt:ProtocolForInt {
    var number = 0
    var description: String = "这是一个描述"
    func addOne() {
        number += 1
    }
}
var simpleClassForInt:ProtocolForInt = SimpleClassForInt()
print(simpleClassForInt.description)
simpleClassForInt.addOne()
//print(simpleClassForInt.number)
 我们可以看到只有协议中定义的属性方法使我们可以访问的 
 

类中在协议中没有定义的属性,我们是无法访问的。 尽管simpleClassForInt的运行时(Runtime)类型是SimpleClassForInt,但是编译器还是会把它视为ProtocolForInt类型,所以在协议之外的属性方法在simpleClassForInt中是无法访问的。

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...