技术文章分类(180)

技术随笔(11)

swift的语法小demo4(协议protocol)

 

//
//  main.swift
//  SwiftGrammarStudy
//
//  Created by dongway on 14-6-6.
//  Copyright (c) 2014年 dongway. All rights reserved.
//

import Foundation

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

/*
    结构体,方法实现需要加mutating标记(上面的class类不需要)
*/
struct SimpleStructure: ExampleProtocol {
    var simpleDescription: String = "A simple structure"
    mutating func adjust() {
        simpleDescription += " (adjusted)"
    }
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription

/*
    这个我也不明白怎么回事
    扩展用于在已有的类型上增加新的功能(比如新的方法或属性)
*/
extension Int: ExampleProtocol {
    var simpleDescription: String {
        return "The number \(self)"
    }
    mutating func adjust() {
        self += 42
    }
}

let protocolValue: ExampleProtocol = a
println("\(protocolValue.simpleDescription)")

 

posted @ 2014-06-12 11:12  坤哥MartinLi  阅读(173)  评论(0编辑  收藏  举报