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

Swift语言中的协议

参考自 http://codecloud.net/swift-22-1228.html
Protocol(协议)用于统一方法属性名称,而不实现任何功能。协议能够被类,枚举,结构体实现,满足协议要求的类,枚举,结构体被称为协议的遵守者。

协议的语法:

protocol 协议名字 {
// 协议内容
}

协议的使用:

在类,结构体,枚举的名称加上协议名称,中间以冒号:分隔即可使用协议;使用多个协议时,各协议之间用逗号,分隔,如下所示:
struct SomeStructure: FirstProtocol,AnotherProtocol {
// 结构体内容
}

注:当某个类含有父类的同时还使用了协议,应当把父类放在所有的协议之前,如下所示:
class SomeClass: SomeSuperClass,FirstProtocol,AnotherProtocol {
// 类的内容
}

属性要求

协议能够要求其遵守者必须含有一些特定名称和类型的实例属性(instance property)或类属性 (type property),也能够要求属性的(设置权限)settable 和(访问权限)gettable,但它不要求属性是存储型属性(stored property)还是计算型属性(calculate property)。

通常前置var关键字将属性声明为变量。在属性声明后写上{ get set }表示属性为可读写的。{ get }用来表示属性为可读的。即使你为可读的属性实现了setter方法,它也不会出错。

protocol SomeProtocol {
var musBeSettable : Int { get set }
var doesNotNeedToBeSettable: Int { get }
}

用类来实现协议时,使用class关键字来表示该属性类成员;用结构体或枚举实现协议时,则使用static关键字来表示:

protocol AnotherProtocol {
class var someTypeProperty: Int { get set }
}

protocol FullyNamed {
var fullName: String { get }
}

FullyNamed协议含有fullName属性。因此其遵循者必须含有一个名为fullName,类型为String的可读属性

struct Person: FullyNamed{
var fullName: String
}
let john = Person(fullName: “John Appleseed”)
//john.fullName 为 “John Appleseed”

Person结构体含有一个名为fullName的存储型属性,完整的遵循了协议。(若协议未被完整遵循,编译时则会报错)。

如下所示,Startship类遵循了FullyNamed协议:

class Starship: FullyNamed {
var prefix: String?
var name: String
init(name: String,prefix: String? = nil ) {
self.anme = name
self.prefix = prefix
}
var fullName: String {
return (prefix ? prefix ! + ” ” : ” “) + name
}
}
var ncc1701 = Starship(name: “Enterprise”,prefix: “USS”)
// ncc1701.fullName == “USS Enterprise”

Starship类将fullName实现为可读的计算型属性。它的每一个实例都有一个名为name的必备属性一个名为prefix的可选属性。 当prefix存在时,将prefix插入到name之前来为Starship构建fullName。

方法要求

协议能够要求其遵循者必备某些特定的实例方法和类方法。协议方法的声明与普通方法声明相似,但它不需要方法内容

注意:

协议方法支持变长参数(variadic parameter),不支持认参数(default parameter)。

前置class关键字表示协议中的成员为类成员;当协议用于被枚举或结构体遵循时,则使用static关键字。如下所示:

protocol SomeProtocol {
class func someTypeMethod()
}

protocol RandomNumberGenerator {
func random() -> Double
}

RandomNumberGenerator协议要求其遵循者必须拥有一个名为random, 返回值类型为Double的实例方法。(我们假设随机数在[0,1]区间内)。

LinearCongruentialGenerator类遵循了RandomNumberGenerator协议,并提供了一个叫做线性同余生成器(linear congruential generator)的伪随机数算法。

class LinearCongruentialGenerator: RandomNumberGenerator {
var lastRandom = 42.0
let m = 139968.0
let a = 3877.0
let c = 29573.0
func random() -> Double {
lastRandom = ((lastRandom * a + c) % m)
return lastRandom / m
}
}
let generator = LinearCongruentialGenerator()
println(“Here’s a random number: (generator.random())”)
// 输出 : “Here’s a random number: 0.37464991998171”
println(“And another one: (generator.random())”)
// 输出 : “And another one: 0.729023776863283”

突变方法要求

能在方法函数内部改变实例类型的方法称为突变方法。在值类型(Value Type)(译者注:特指结构体和枚举)中的的函数前缀加上mutating关键字来表示该函数允许改变该实例和其属性的类型。 这一变换过程在实例方法(Instance Methods)章节中有详细描述。

(译者注:类中的成员为引用类型(Reference Type),可以方便的修改实例及其属性的值而无需改变类型;而结构体和枚举中的成员均为值类型(Value Type),修改变量的值就相当于修改变量的类型,而Swift认不允许修改类型,因此需要前置mutating关键字用来表示该函数中能够修改类型)

注意:

用class实现协议中的mutating方法时,不用写mutating关键字;用结构体,枚举实现协议中的mutating方法时,必须写mutating关键字。

如下所示,Togglable协议含有toggle函数。根据函数名称推测,toggle可能用于切换或恢复某个属性的状态。mutating关键字表示它为突变方法

protocol Togglable {
mutating func toggle()
}

当使用枚举或结构体来实现Togglabl协议时,必须在toggle方法加上mutating关键字。

如下所示,OnOffSwitch枚举遵循了Togglable协议,On,Off两个成员用于表示当前状态

enum OnOffSwitch: Togglable {
case Off,On
mutating func toggle() {
switch self {
case Off:
self = On
case On:
self = Off
}
}
}
var lightSwitch = OnOffSwitch.Off
lightSwitch.toggle()
//lightSwitch 现在的值为 .On

协议类型

协议本身不实现任何功能,但你可以将它当做类型来使用。

使用场景:

作为函数方法或构造器中的参数类型,返回值类型
作为常量,变量,属性的类型
作为数组,字典或其他容器中的元素类型

注意:

协议类型应与其他类型(Int,Double,String)的写法相同,使用驼峰式

class Dice {
let sides: Int
let generator: RandomNumberGenerator
init(sides: Int,generator: RandomNumberGenerator) {
self.sides = sides
self.generator = generator
}
func roll() -> Int {
return Int(generator.random() * Double(sides)) +1
}
}

这里定义了一个名为 Dice的类,用来代表桌游中的N个面的骰子。

Dice含有sides和generator两个属性,前者用来表示骰子有几个面,后者为骰子提供一个随机生成器。由于后者为RandomNumberGenerator的协议类型。所以它能够被赋值为任意遵循该协议的类型。

此外,使用构造器(init)来代替之前版本中的setup操作。构造器中含有一个名为generator,类型为RandomNumberGenerator的形参,使得它可以接收任意遵循RandomNumberGenerator协议的类型。

roll方法用来模拟骰子的面值。它先使用generator的random方法来创建一个[0-1]区间内的随机数种子,然后加工这个随机数种子生成骰子的面值。

如下所示,LinearCongruentialGenerator的实例作为随机生成器传入Dice的构造器

var d6 = Dice(sides: 6,generator: LinearCongruentialGenerator())
for _ in 1…5 {
println(“Random dice roll is (d6.roll())”)
}
//输出结果
//Random dice roll is 3
//Random dice roll is 5
//Random dice roll is 4
//Random dice roll is 5
//Random dice roll is 4

委托(代理)模式

委托是一种设计模式,它允许类或结构体将一些需要它们负责的功能交由(委托)给其他的类型。

委托模式的实现很简单: 定义协议来封装那些需要被委托的函数方法, 使其遵循者拥有这些被委托的函数方法

委托模式可以用来响应特定的动作或接收外部数据源提供的数据,而无需要知道外部数据源的类型。

下文是两个基于骰子游戏的协议:

protocol DiceGame {
var dice: Dice { get }
func play()
}
protocol DiceGameDelegate {
func gameDidStart(game: DiceGame)
func game(game: DiceGame,didStartNewTurnWithDiceRoll diceRoll:Int)
func gameDidEnd(game: DiceGame)
}

DiceGame协议可以在任意含有骰子的游戏中实现,DiceGameDelegate协议可以用来追踪DiceGame的游戏过程。

如下所示,SnakesAndLadders是Snakes and Ladders(译者注:控制流章节有该游戏的详细介绍)游戏的新版本。新版本使用Dice作为骰子,并且实现了DiceGame和DiceGameDelegate协议

class SnakesAndLadders: DiceGame {
let finalSquare = 25
let dic = Dice(sides: 6,generator: LinearCongruentialGenerator())
var square = 0
var board: Int[]
init() {
board = Int[](count: finalSquare + 1,repeatedValue: 0)
board[03] = +08; board[06] = +11; borad[09] = +09; board[10] = +02
borad[14] = -10; board[19] = -11; borad[22] = -02; board[24] = -08
}
var delegate: DiceGameDelegate?
func play() {
square = 0
delegate?.gameDidStart(self)
gameLoop: while square != finalSquare {
let diceRoll = dice.roll()
delegate?.game(self,didStartNewTurnWithDiceRoll: diceRoll)
switch square + diceRoll {
case finalSquare:
break gameLoop
case let newSquare where newSquare > finalSquare:
continue gameLoop
default:
square += diceRoll
square += board[square]
}
}
delegate?.gameDIdEnd(self)
}
}

游戏的初始化设置(setup)被SnakesAndLadders类的构造器(initializer)实现。所有的游戏逻辑被转移到了play方法中。

注意:

因为delegate并不是该游戏的必备条件,delegate被定义为遵循DiceGameDelegate协议的可选属性

DicegameDelegate协议提供了三个方法用来追踪游戏过程。被放置于游戏的逻辑中,即play()方法内。分别在游戏开始时,新一轮开始时,游戏结束时被调用

因为delegate是一个遵循DiceGameDelegate的可选属性,因此在play()方法中使用了可选链来调用委托方法。 若delegate属性为nil, 则委托调用优雅地失效。若delegate不为nil,则委托方法调用

如下所示,DiceGameTracker遵循了DiceGameDelegate协议

class DiceGameTracker: DiceGameDelegate {
var numberOfTurns = 0
func gameDidStart(game: DiceGame) {
numberOfTurns = 0
if game is SnakesAndLadders {
println(“Started a new game of Snakes and Ladders”)
}
println(“The game is using a (game.dice.sides)-sided dice”)
}
func game(game: DiceGame,didStartNewTurnWithDiceRoll diceRoll: Int) {
++numberOfTurns
println(“Rolled a (diceRoll)”)
}
func gameDidEnd(game: DiceGame) {
println(“The game lasted for (numberOfTurns) turns”)
}
}

DiceGameTracker实现了DiceGameDelegate协议的方法要求,用来记录游戏已经进行的轮数。 当游戏开始时,numberOfTurns属性被赋值为0;在每新一轮中递加;游戏结束后,输出打印游戏的总轮数。

gameDidStart方法从game参数获取游戏信息并输出。game在方法中被当做DiceGame类型而不是SnakeAndLadders类型,所以方法中只能访问DiceGame协议中的成员。

DiceGameTracker的运行情况,如下所示:

“let tracker = DiceGameTracker()
let game = SnakesAndLadders()
game.delegate = tracker
game.play()
// Started a new game of Snakes and Ladders
// The game is using a 6-sided dice
// Rolled a 3
// Rolled a 5
// Rolled a 4
// Rolled a 5
// The game lasted for 4 turns”

在扩展中添加协议成员

即便无法修改代码,依然可以通过扩展(Extension)来扩充已存在类型(译者注: 类,结构体,枚举等)。扩展可以为已存在的类型添加属性方法,下标,协议等成员。详情请在扩展章节中查看。

注意:

通过扩展为已存在的类型遵循协议时,该类型的所有实例也会随之添加协议中的方法

TextRepresentable协议含有一个asText,如下所示:

protocol TextRepresentable {
func asText() -> String
}

通过扩展为上一节中提到的Dice类遵循TextRepresentable协议

extension Dice: TextRepresentable {
cun asText() -> String {
return “A (sides)-sided dice”
}
}

从现在起,Dice类型的实例可被当作TextRepresentable类型:

let d12 = Dice(sides: 12,generator: LinearCongruentialGenerator())
println(d12.asText())
// 输出 “A 12-sided dice”

SnakesAndLadders类也可以通过扩展的方式来遵循协议:

extension SnakeAndLadders: TextRepresentable {
func asText() -> String {
return “A game of Snakes and Ladders with (finalSquare) squares”
}
}
println(game.asText())
// 输出 “A game of Snakes and Ladders with 25 squares”

通过延展补充协议声明

一个类型已经实现了协议中的所有要求,却没有声明时,可以通过扩展来补充协议声明:

struct Hamster {
var name: String
func asText() -> String {
return “A hamster named (name)”
}
}
extension Hamster: TextRepresentabl {}

从现在起,Hamster的实例可以作为TextRepresentable类型使用

let simonTheHamster = Hamster(name: “Simon”)
let somethingTextRepresentable: TextRepresentabl = simonTheHamester
println(somethingTextRepresentable.asText())
// 输出 “A hamster named Simon”

注意:

即时满足了协议的所有要求,类型也不会自动转变,因此你必须为它做出明显的协议声明

集合中的协议类型

协议类型可以被集合使用,表示集合中的元素均为协议类型:

let things: TextRepresentable[] = [game,d12,simoTheHamster]

如下所示,things数组可以被直接遍历,并调用其中元素的asText()函数

for thing in things {
println(thing.asText())
}
// A game of Snakes and Ladders with 25 squares
// A 12-sided dice
// A hamster named Simon

thing被当做是TextRepresentable类型而不是Dice,DiceGame,Hamster等类型。因此能且仅能调用asText方法

协议的继承

协议能够继承一到多个其他协议。语法与类的继承相似,多个协议间用逗号,分隔

protocol InheritingProtocol: SomeProtocol,AnotherProtocol {
// 协议定义
}

如下所示,PrettyTextRepresentable协议继承了TextRepresentable协议

protocol PrettyTextRepresentable: TextRepresentable {
func asPrettyText() -> String
}

遵循“PrettyTextRepresentable协议的同时,也需要遵循TextRepresentable`协议。

如下所示,用扩展为SnakesAndLadders遵循PrettyTextRepresentable协议:

extension SnakesAndLadders: PrettyTextRepresentable {
func asPrettyText() -> String {
var output = asText() + “:\n”
for index in 1…finalSquare {
switch board[index] {
case let ladder where ladder > 0:
output += “▲ ”
case let snake where snake < 0:
output += “▼ ”
default:
output += “○ ”
}
}
return output
}
}

在for in中迭代出了board数组中的每一个元素:

当从数组中迭代出的元素的值大于0时,用▲表示
当从数组中迭代出的元素的值小于0时,用▼表示
当从数组中迭代出的元素的值等于0时,用○表示

任意SankesAndLadders的实例都可以使用asPrettyText()方法

println(game.asPrettyText())
// A game of Snakes and Ladders with 25 squares:
// ○ ○ ▲ ○ ○ ▲ ○ ○ ▲ ▲ ○ ○ ○ ▼ ○ ○ ○ ○ ▼ ○ ○ ▼ ○ ▼ ○

协议合成

一个协议可由多个协议采用protocol

原文地址:https://www.jb51.cc/swift/324949.html

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

相关推荐