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中是无法访问的。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值