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

本文学习自《 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.simpleDescription

struct SimpleStructure : ExampleProtocol {
    var simpleDescription :String = "A simple struture"
    mutating func adjust() {
        simpleDescription += "(adjusted)"
    }
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription

练习:写一个实现这个协议的枚举
在网上找了好久,都不知道怎样实现,最后学习大神博客:(http://blog.youkuaiyun.com/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.simpleDescription
enumTest.adjust()
enumTest.simpleDescription

enumTest = EnumConformToProtocol.Third("ThirdVal")
enumTest.simpleDescription
enumTest.adjust()
enumTest.simpleDescription


var e = EnumConformToProtocol.Second("Hello")
var text = e.simpleDescription
e.simpleDescription = "Adios"
text = e.simpleDescription
e.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> = .None
possibleInteger = .Some(100)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值