微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift语法基础:6 - Swift的Protocol和Extensions

前面我们知道了枚举类型和结构体的声明,嵌套,以及基本的使用,现在让我们来看看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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐