Swift2学习:Swift概览6-协议和扩展

协议和扩展

用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


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

var b = SimpleStructture()
b.adjust()
let bDescription = b.simpleDescription

练习

写一个实习该接口的枚举

注意声明SimpleStructture的时候mutating关键字用来标记可以修改结构体的方法。SimpleClass的声明不需要标记任何方法因为类中的方法经常会修改类。

使用extension为现有的类型添加功能,比如添加一个计算属性的方法。你可以使用扩展给任何类型添加协议,甚至是你从外部库或者框架中导入的类型。

extension Int: ExampleProtocol {
    var simpleDescription: String {
        return "The number \(self)"
    }
    
    mutating func adjust() {
        self += 42
    }
}

print(7.simpleDescription)
var t: Int = 6
t.adjust()

练习

给Double类型写一个扩展,添加absoluteValue功能。

你可以像使用其他命名类型一样使用协议名--例如,创建一个有不同类型但是都实现同一个接口。当你处理类型是协议的值时,接口的外部定义方法不可用。

let protocolValue: ExampleProtocol = a
print(protocolValue.simpleDescription)
//print(protocolValue.anotherProperty)  //Uncomment to see the error

即使protocolValue运行时的类型是SimpleClass,编译器会把他的类型当做ExampleProtocol。这意味着你不能调用类的属性和方法除非在协议中就有。



另外:发现github上已经有翻译好的了。链接 https://github.com/CocoaChina-editors/Welcome-to-Swift

我仍会继续翻译下去,做为自己学习的过程。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值