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

Swift学习——A Swift Tour 协议和扩展

Protocols and Extensions


Protocols  协议的使用

使用keyword 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 structure"
    mutating func adjust() {
        simpleDescription += " (adjusted)"
    }
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription

在结构体中须要使用 mutating keyword来标记实现的协议方法,在类中不须要这个keyword

协议基本的使用场合:

1. 须要由别的类实现的方法

2. 声明位置类的接口

3. 两个类之间通信



Extensions  扩展的使用

能够使用 extension keyword为一个类型拓展协议,添加方法属性

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

能够使用协议的名称作为数据类型(具体怎么用。没看明确。能够看官方英文版)

let protocolValue: ExampleProtocol = a
protocolValue.simpleDescription
// protocolValue.anotherProperty  // Uncomment to see the error



Generics   泛型的使用

使用   < >  声明泛型函数或者泛型类型

func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] {
    var result = ItemType[]()
    for i in 0..times {
        result += item
    }
    return result
}
repeat("knock", 4)

也能够在类。枚举,结构体中使用泛型

// Reimplement the Swift standard library's optional type
enum OptionalValue<T> {
    case None
    case Some(T)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .some(100)

有的时候须要对函数的參数类型进行具体的定义。对泛型实现某个接口。继承自某个特定类型。两个泛型属于同一个类型等要求,使用  where keyword进行定义

func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool {
    for lhsItem in lhs {
        for rhsItem in rhs {
            if lhsItem == rhsItem {
                return true
            }
        }
    }
    return false
}
anyCommonElements([1, 2, 3], [3])

假设条件简单,还能够简化写,比方<T: Equatable>和“<T where T: Equatable>是一样的


入门就讲到这,下一节我们说说 Language Guide

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

相关推荐