如何理解swift中的delegate
Delegation翻译为代理或者委托,是一种设计模式。顾名思义,使class或struct能够将某些职责移交给其他类型的实例。
该设计模式通过定义一个封装(包含)delegate的protocol(协议)来实现,从而保证这个代理囊括所定义的功能。Delegation可用于响应特定操作,或者从外部源检索数据,而不需要知道该源的基础类型。
(一)这里举一个dice-based(摇骰子)的游戏作为例子:
定义两个protocol:
DiceGame:被所有需要骰子的游戏采用;
DiceGameDelegate:被所有需要track(跟踪)游戏过程的类型所采用;
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)
}
(二)这里有一个Snakes and Ladders(蛇与梯子)的游戏,使用了筛子所以采用DiceGame协议(protocol),并且设置了一个DiceGameDelegate的代理来track游戏的过程。想具体了解Snakes and ladders这个游戏过程的可以参考[Control flow 中的break]。(https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-ID137)
class SnakesAndLadders: DiceGame {
let finalSquare = 25
let dice = Dice(sides: 6, generator: LinearCongruentialGenerator())
var square = 0
var board: [Int]
init() {
board = Array(repeating: 0, count: finalSquare + 1)
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[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)
}
}
(三)
class DiceGameTracker: DiceGameDelegate {
var numberOfTurns = 0
func gameDidStart(_ game: DiceGame) {
numberOfTurns = 0
if game is SnakesAndLadders {
print("Started a new game of Snakes and Ladders")
}
print("The game is using a \(game.dice.sides)-sided dice")
}
func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) {
numberOfTurns += 1
print("Rolled a \(diceRoll)")
}
func gameDidEnd(_ game: DiceGame) {
print("The game lasted for \(numberOfTurns) turns")
}
}
DiceGameTracker实现了所有DiceGameDelegate中所要求的三个方法,从而达到记录整个游戏过程的目的。
(四)下面是整个游戏实际运行的过程:
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
分别定义了一个实现DiceGameDelegate的tracker和一个游戏game,将game的代理设置为tracker,当game调用play函数的时候,track会代理地记录下游戏的整个过程。
参考:
The swift programming language
如何理解swift中的delegate的更多相关文章
- [翻译]理解Swift中的Optional
原文出处:Understanding Optionals in Swift 苹果新的Swift编程语言带来了一些新的技巧,能使软件开发比以往更方便.更安全.然而,一个很有力的特性Optional,在你 ...
- 理解Swift中map 和 flatMap对集合的作用
map和flatMap是函数式编程中常见的概念,python等语言中都有.借助于 map和flapMap 函数可以非常轻易地将数组转换成另外一个新数组. map函数可以被数组调用,它接受一个闭包作为參 ...
- swift中第三方网络请求库Alamofire的安装与使用
swift中第三方网络请求库Alamofire的安装与使用 Alamofire是swift中一个比较流行的网络请求库:https://github.com/Alamofire/Alamofire.下面 ...
- swift 中delegate的使用
今天写了delegate,遇到以下问题: 这里protocol的写法有问题,如果delegate指向一个实现了某个协议对象的引用,在oc里是这样写delegate的类型 id<protocol& ...
- 在OC中调用Swift类中定义delegate出现:Property 'delegate' not found on object of type ...
找了许久没找到答案, 在下面的链接中, 我解决了这个问题: http://stackoverflow.com/questions/26366082/cannot-access-property-of- ...
- swift中的?和!理解
本文转载至 http://www.cnblogs.com/dugulong/p/3770367.html 首先贴cocoachina上某位大大的帖子: Swift语言使用var定义变量,但和别 ...
- [Swift]UIAlertController 以及 Swift 中的闭包和枚举
原文地址:http://blog.callmewhy.com/2014/10/08/uialertcontroller-swift-closures-enum/ 在 iOS8 的 SDK 中, UIK ...
- 怎么理解js中的事件委托
怎么理解js中的事件委托 时间 2015-01-15 00:59:59 SegmentFault 原文 http://segmentfault.com/blog/sunchengli/119000 ...
- 窥探Swift之使用Web浏览器编译Swift代码以及Swift中的泛型
有的小伙伴会问:博主,没有Mac怎么学Swift语言呢,我想学Swift,但前提得买个Mac.非也,非也.如果你想了解或者初步学习Swift语言的话,你可以登录这个网站:http://swiftstu ...
随机推荐
- 移动端适配(手机端rem布局详解)
1. 问题的引出 如果html5要适应各种分辨率的移动设备,应该使用rem这样的尺寸单位,同时给出了一段针对各个分辨率范围在html上设置font-size的代码: html{font-size:10 ...
- TensorFlow2.0(四):填充与复制
.caret, .dropup > .btn > .caret { border-top-color: #000 !important; } .label { border: 1px so ...
- Yii2 前后台登陆退出分离、登陆验证
这里用的yii2高级模板, 基本模板的配置文件在一个文件里,方法基本没什么区别, 1.用户表要有两个用户表, 当然一个也行,分开是省得麻烦,既然是分离了就彻底分开, 前台表user,后台表user_b ...
- SpringBoot-ElasticJob封装快速上手使用(分布式定时器)
elastic-job-spring-boot qq交流群:812321371 1 简介 Elastic-Job是一个分布式调度解决方案,由两个相互独立的子项目Elastic-Job-Lite和Ela ...
- Spring 源码阅读 二
程序入口: 接着上一篇博客中看完了在AnnotationConfigApplicationContext的构造函数中的register(annotatedClasses);将我们传递进来的主配置类添加 ...
- MIPI CSI2-TX接口基于FPGA实现
MIPI CSI2-TX用途: 跟海思的3559A芯片进行图像数据传输: MIPI CSI2-TX接口特性: xilinx 7系列芯片最大支持1.25Gbps: 最大支持lanes数量为4: 支持的图 ...
- js构造函数的浅薄理解
任何函数,只要通过 new 操作符来调用,那它就可以作为构造函数 如:任何函数,只要通过 new 操作符来调用,那它就可以作为构造函数 : fuction Preson(){...} var pres ...
- Spring bean的作用域以及生命周期
一.request与session的区别 request简介 request范围较小一些,只是一个请求. request对象的生命周期是针对一个客户端(说确切点就是一个浏览器应用程序)的一次请求,当请 ...
- C--二分搜索
//二分搜索 //时间复杂度小 log2 n int search(int key, int a[], int len) { ; ; ; int mid; while(left<right) { ...
- unittest生成测试报告
1.先导入HTMLTestRunner模块 2.实例一脚本如下 #coding=utf-8 import unittest import HTMLTestRunner #封装批量执行用例 def al ...