课程来自慕课网liuyubobobo老师
面向协议的编程
- 扩展协议和默认实现
protocol Record: CustomStringConvertible {
var wins: Int {get}
var losses: Int {get}
func winningPercent() -> Double
}
extension Record {
var description: String {
return String(format: "Wins: %d Losses: %d", wins, losses)
}
var gamePlayed: Int {
return wins + losses
}
}
struct BasketballRecord: Record {
var wins: Int
var losses: Int
func winningPercent() -> Double {
return Double(wins) / Double (gamePlayed)
}
}
let teamRecord = BasketballRecord(wins: 2, losses: 10)
print(teamRecord)
- 面向协议编程
protocol Record: CustomStringConvertible {
var wins: Int {get}
var losses: Int {get}
func winningPercent() -> Double
}
extension Record {
var description: String {
return String(format: "Wins: %d Losses: %d", wins, losses)
}
var gamePlayed: Int {
return wins + losses
}
func winningPercent() -> Double {
return Double(wins) / Double (gamePlayed)
}
}
protocol Tieable {
var ties: Int{get}
}
extension Record where Self: Tieable {
var gamePlayed: Int {
return wins+ties+losses
}
func winningPercent() -> Double {
return Double(wins) / Double (gamePlayed)
}
}
struct BasketballRecord: Record {
var wins: Int
var losses: Int
}
struct FootballRecord: Record, Tieable {
var wins: Int
var ties: Int
var losses: Int
}
let footballTeamRecord: FootballRecord = FootballRecord(wins: 3, ties: 2, losses: 1)
footballTeamRecord.winningPercent() // 0.5
- 协议聚合
func award(one: Prizable & CustomStringConvertible) {
if one.isPrizable(){
print("Congratulate!")
}
}
- 范型约束
func topOne<T: Comparable>(seq: [T]) -> T {
assert(seq.count > 0)
return seq.reduce(seq[0]){ max( $0 , $1 ) }
}
func topPirzableOne<T: Comparable & Prizable> (seq: [T]) -> T? {
return seq.reduce(nil){ ( tmpTop: T? , contender: T) in
guard contender.isPrizable() else{
return tmpTop
}
guard let tmpTop = tmpTop else{
return contender
}
return max( tmpTop , contender )
}
}
- 委托模式
protocol TurnBasedGame {
var turn: Int {get set}
func play()
}
protocol TurnBasedGameDelegate {
func gameStart()
func playerMove()
func gameEnd()
func gameOver() -> Bool
}
class SinglePlayerTurnBasedGame: TurnBasedGame {
var turn: Int = 0
var delegate: TurnBasedGameDelegate!
func play() {
delegate.gameStart()
while !delegate.gameOver() {
print("Round ",self.turn)
delegate.playerMove()
turn += 1
}
delegate.gameEnd()
}
}
class RollNumberGame: SinglePlayerTurnBasedGame, TurnBasedGameDelegate {
var score = 0
override init() {
super.init()
delegate = self
}
func gameStart() {
score = 0
turn = 0
print("Game Start")
}
func playerMove() {
let rollNumber = Int(arc4random())%6 + 1
score += rollNumber
print("The score is ", score, "now.")
}
func gameEnd() {
print("You win the game in ", turn, "round!")
}
func gameOver() -> Bool {
return score >= 100
}
}
let game:RollNumberGame = RollNumberGame()
game.play()
- 可选的协议方法
@objc protocol TurnBasedGameDelegate {
func gameStart()
func playerMove()
func gameEnd()
@objc optional func turnStart()
func gameOver() -> Bool
}
网友评论