码迷,mamicode.com
首页 > 编程语言 > 详细

Swift - Protocols and Extensions

时间:2014-12-21 23:27:04      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:

The Swift Programming Language中的代码加上部分EXPERIMENT

import UIKit

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 SimpleStructure: ExampleProtocol {
    var simpleDescription: String = "A simple structure"
    mutating func adjust() {
        simpleDescription += " (adjusted)"
    }
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription

enum SimpleEnum: ExampleProtocol {
    case SIMPLE(String)
    var simpleDescription: String {
        get {
            switch self {
            case let .SIMPLE(str):
                return str
            }
        }
    }
    mutating func adjust() {
        switch self {
        case let .SIMPLE(str):
            self = .SIMPLE(str + " (adjusted)")
        }
    }
}
var c = SimpleEnum.SIMPLE("A simple enum")
c.simpleDescription
c.adjust()
c.simpleDescription

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

let protocolValue: ExampleProtocol = a
protocolValue.simpleDescription

 

Swift - Protocols and Extensions

标签:

原文地址:http://www.cnblogs.com/duelsol/p/4177135.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!