swift delegate 从开始到放弃

swift delegate 从开始到放弃,第1张

概述Delegate 由开始到放弃 这里是官网链接,毕竟官网更加权威 说说协议(protocal) 先来看一下官方的定义 A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The prot Delegate 由开始到放弃

这里是官网链接,毕竟官网更加权威

说说协议(protocal)

先来看一下官方的定义

A protocol defines a blueprint of methods,propertIEs,and other requirements that suit a particular task or pIEce of functionality. The protocol can then be adopted by a class,structure,or enumeration to provIDe an actual implementation of those requirements.

协议(protocal)定义了用于实现某个任务或功能的一系列方法,属性和其它的种种需求。然后这个协议被类(class)或结构体(struct)或枚举类(enum)实现。

熟悉java的开发者,在看完协议的定义以后,应该会觉得和java中的接口(interface)极为相似。java中接口用于定义类的实现,解耦调用类和被调用类,一个接口允许有多个实现。

总之,protocal就像是一纸合同,所有遵循(conform)了该合同的对象都必须实现该合同中的必须实现的内容

下面简单讲一下协议的使用

//声明一份协议protocol SomeProtocol {    //在这里定义协议的具体内容}//一个对象可以遵循多个协议struct SomeStructure: FirstProtocol,AnotherProtocol {}//如果类有父类,则父类在冒号后的第一个位置,然后才是协议,彼此用分号隔开class SomeClass: SomeSuperclass,FirstProtocol,AnotherProtocol {    // class deFinition goes here}

协议中属性的声明

必须声明属性的类型

属性可以为计算属性或存储属性

需要说明属性是读写均可或只读

//声明协议,该协议要求能够满足一个只读属性fullnameprotocol Fullynamed {    var fullname: String { get }}//简单的实现struct Person: Fullynamed {    var fullname: String}let john = Person(fullname: "John Appleseed")// john.fullname 是"John Appleseed"//稍复杂的实现,返回姓+名class Starship: Fullynamed {    var prefix: String?    var name: String    init(name: String,prefix: String? = nil) {        self.name = name        self.prefix = prefix    }    var fullname: String {        return (prefix != nil ? prefix! + " " : "") + name    }}var ncc1701 = Starship(name: "Enterprise",prefix: "USS")// ncc1701.fullname is "USS Enterprise"

协议中方法的声明

protocol RandomNumberGenerator {    //方法体,无需大括号    func random() -> Double}//实现类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).truncatingRemainder(divIDingBy:m))        return lastRandom / m    }}//若实现对象为enum或struct,则对对象内数据有修改的方法应该标注为为mutatingprotocol Togglable {    mutating func toggle()}enum OnOffSwitch: Togglable {    case off,on    mutating func toggle() {        switch self {        case .off:            self = .on        case .on:            self = .off        }    }}
进入Delegation

还是先看一下官方的定义

Delegation is a design pattern that enables a class or structure to hand off (or delegate) some of its responsibilitIEs to an instance of another type. This design pattern is implemented by defining a protocol that encapsulates the delegated responsibilitIEs,such that a conforming type (kNown as a delegate) is guaranteed to provIDe the functionality that has been delegated. Delegation can be used to respond to a particular action,or to retrIEve data from an external source without needing to kNow the underlying type of that source.

委托(delegation)是一种支持类或结构体将一部分职责委托给另一种类型的实例来完成的设计模式。这种设计模式是通过定义一个封装了委托职责的协议来实现的。然后被委托的实例通过遵从该协议来确保完成了委托的任务。委托可以用于回应某一个特定的动作(action),或者从不知其内部实现的外部源来获得数据。

下面我们举一个具体的例子来说明委托
最常见的委托应该是在视图(VIEw)和控制器(Controller)之间的,在这里先盗用一张老爷爷的图

.]
也就是说,vIEw将自己的一部分职责委托给controller来完成,例如textfIEld会将textDIDBeginEditing和textDIDEndEditing之类的职责交给controller,这样controller可以在textfIEld开始编辑或者结束编辑的时候进行一些 *** 作,比如高亮被选中的textfIEld,展开和收起键盘,检验输入的内容格式是否正确。controller还可以对数据进行 *** 作,并将结果返回给vIEw。vIEw根据返回的结果渲染界面。

具体的实现如下:

vIEw声明一个委托协议(即vIEw希望controller替它完成的工作)

vIEw的API持有一个weak委托协议的属性(如 weak var uiTextFIEldDelegate:UITextFIEldDelegate)

vIEw用这个协议来完成无法独自完成的功能。

controller声明自己遵循这个协议

controller把自己作为delegate对象(uiTextFIEld.delegate = self)

controller实现这个协议(协议为optional的属性或方法不一定需要实现)

因为委托是通过协议来实现的,所以一个委托可以有多个具体的实现,这样就降低了委托方和被委托方彼此之间的耦合。

这里在贴上官网上的代码例子

协议

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)}

实现第一个协议的委托类,委托另一个类来判断游戏是否结束了

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")    }}

delegate使用于需要回调的方法中。这样,被委托对象在不知道委托对象的情况下完成某些职责。委托对象根据被委托对象返回的信息选择后续如何执行。事实上,delegate在很大程度上类似于closure。只是delegate通过protocal的形式使结构更加清晰,可复用性更高,降低耦合度。

总结

以上是内存溢出为你收集整理的swift delegate 从开始到放弃全部内容,希望文章能够帮你解决swift delegate 从开始到放弃所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1063932.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存