Swift学习之路 -- 协议、扩展和泛型

来源:互联网 发布:linux安装压缩软件 编辑:程序博客网 时间:2024/04/30 00:03

本文学习自《 The Swift Programming Language-swift2.0官方手册 中文版》的电子版
是记录自己的Swift学习历程、整理相关资料便于查看


协议和扩展

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

练习:写一个实现这个协议的枚举
在网上找了好久,都不知道怎样实现,最后学习大神博客:(http://blog.csdn.net/duanyipeng/article/details/32338575),最终学会:

enum EnumConformToProtocol: ExampleProtocol {    case First(String), Second(String), Third(String)    var simpleDescription: String {        get {            switch self {            case let .First(text):                return text            case let .Second(text):                return text            case let .Third(text):                return text            }        }        set {            switch self {            case let .First(text):                self = .First(newValue)            case let .Second(text):                self = .Second(newValue)            case let .Third(text):                self = .Third(newValue)            }        }    }    mutating func adjust() {        switch self {        case let .First(text):            self = .First(text + " (first case adjusted)")        case let .Second(text):            self = .Second(text + " (second case adjusted)")        case let .Third(text):            self = .Third(text + " (third case adjusted)")        }    }}var enumTest = EnumConformToProtocol.First("FirstVal")enumTest.simpleDescriptionenumTest.adjust()enumTest.simpleDescriptionenumTest = EnumConformToProtocol.Third("ThirdVal")enumTest.simpleDescriptionenumTest.adjust()enumTest.simpleDescriptionvar e = EnumConformToProtocol.Second("Hello")var text = e.simpleDescriptione.simpleDescription = "Adios"text = e.simpleDescriptione.adjust()text = e.simpleDescription

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

使用extension 来为现有的类型添加功能,比如新的方法和参数。你可以使用扩展在别处修改定义,甚至是从外部库或者框架引入的一个类型,是的这个类型遵循某个协议

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

练习:给Double类型写一个扩展,添加absoluteValue功能 double fabs (double)绝对值
你可以像使用其他命名类型一样使用协议名 – 例如 创建一个有不同类型但是都实现一个协议的对象集合。当你处理类型是协议的值时,协议外定义的方法不可用。

let protocolValue : ExampleProtocol = a;protocolValue.simpleDescription

即使protocolValue变量运行时的类型是simpClass,编译器会把它的类型当做ExampleProtocol。这边是你不能调用类在它实现协议之外实现的方法或者属性


泛型

在尖括号里写一个名字来创建一个泛型函数或者类型

func repeatItem<Item>(item: Item,numberOfTimes :Int) ->[Item] {    var result = [Item]()    for _ in 0..<numberOfTimes {        result.append(item)    }    return result}repeatItem("knock", numberOfTimes: 4)

你也可以创建泛型函数、方法、类、枚举、结构体

enum OptionlValue<T> {    case None    case Some(T)}var possibleInteger: OptionlValue<Int> = .NonepossibleInteger = .Some(100)

在类型名后面使用where来指定对类型的需求,比如,限定类型实现某一个协议,限定两个类型是相同的,或者限定某个类必须有一个特定的父类
简单起见,你可以忽略where,只在冒号后面写协议或者类名。 和 是等价的

0 0
原创粉丝点击