协议定义了一个蓝图 规定了用来实现某一特定工作或者功能所必需的方法和属性
类 结构体 枚举类型都可以遵循协议 并提供具体实现来完成定义的方法和功能
<code>protocol FullyName {
var fullName: String {get}
}
struct Person: FullyName {
var fullName: String
}
let john = Person(fullName: "John Appleseed")
print(john)
class Starship: FullyName{
var prefix1: String?
var name: String
init(name: String, prefix1: String){
self.name = name
self.prefix1 = prefix1
}
var fullName: String{
return (prefix1 == nil ?"" :prefix1!) + name
}
}
var ncc1701 = Starship(name: "Enterprise", prefix1: "USS")
print(ncc1701.fullName)
protocol RandomNumberGenerator {
func random() -> Double
}
class LinearcingryebntialGenerator: 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 = LinearcingryebntialGenerator()
print("Here's a random number (generator.random())")
//协议类型
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
}
}
var d6 = Dice(sides: 6, generator: LinearcingryebntialGenerator())
for _ in 1...5{
print("Random dice roll is (d6.roll())")
}
//代理模式
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: LinearcingryebntialGenerator())
var square = 0
var board: [Int]
init(){
board = [Int](count: finalSquare + 1, repeatedValue: 0)
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)-sides 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")
}
}
let tracker = DiceGameTracker()
let game = SnakesAndLadders()
game.delegate = tracker
game.play()
protocol TextRepresentable {
var textualDescription: String{get}
}
extension SnakesAndLadders: TextRepresentable {
var textualDescription: String{
return "A game of Snakes and Ladders with (finalSquare) squares"
}
}
//在扩展中添加协议成员
extension Dice: TextRepresentable {
var textualDescription: String{
return "A (sides)-sided dice"
}
}
let d12 = Dice(sides: 12, generator: LinearcingryebntialGenerator())
print(d12.textualDescription)
//通过扩展补充协议声明
struct Hamster {
var name: String
var textualDescription: String{
return "A hamster named (name)"
}
}
extension Hamster: TextRepresentable {}
let simonTheHamster = Hamster(name: "Simon")
let somethingTextRepresentable: TextRepresentable = simonTheHamster
print(somethingTextRepresentable.textualDescription)
//协议类型的集合
let things: [TextRepresentable] = [game, d12, simonTheHamster]
for thing in things{
print(thing.textualDescription)
}
//协议的继承
protocol PrettyTextRepresentable: TextRepresentable{
var prettyTextualDescription: String{get}
}
extension SnakesAndLadders {
var prettyTextualDescription: String{
var output = textualDescription + ":\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
}
}
print(game.prettyTextualDescription)
</code>
类专属协议
添加class关键字 限制协议只能适配到class类型 不能适用到枚举或者结构体类型
协议合成
protocol<SomeProtocol, Anotherprotocol>
协议合成并不会生成一个新的协议 而是将多个协议合成为一个临时的协议 超出范围后立即失效
检查协议的一致性
使用is和as操作符来检查是否遵循某一协议或强制转化为某一类型
可选协议
增加@objc标识符 使用optional关键字
协议扩展
使用extension 关键字 扩展协议 并实现方法 所有协议都会拥有此方法
extension someProtocol{func A(){}}
为协议扩展添加限制条件
使用where关键字进行限制条件判断