Skip to content

Instantly share code, notes, and snippets.

@creaaa
Last active March 6, 2017 19:33
Show Gist options
  • Save creaaa/bb3bb778d990ae5ba21fb0a87cccf13d to your computer and use it in GitHub Desktop.
Save creaaa/bb3bb778d990ae5ba21fb0a87cccf13d to your computer and use it in GitHub Desktop.
// 依頼する
class Game {
// weakにするのは、依頼「する」側(デリゲート元)のプロパティ。
// される側(デリゲート先)が weakプロパティを持つと、得てして落ちるので注意
weak var delegate: GameDelegate?
func start() {
print("Number of players is \(delegate?.numberOfPlayers ?? 1)")
delegate?.gameDidStart(self)
print("Playing")
delegate?.gameDidEnd(self)
}
}
// 「依頼される」者は、プロトコルに批准していなければならない
protocol GameDelegate: class {
var numberOfPlayers: Int { get } // プレイ人数
func gameDidStart(_ game: Game) // 開始処理
func gameDidEnd(_ game: Game)         // 終了処理
}
// 依頼される
class TwoPersonsGameDelegate: GameDelegate {
var numberOfPlayers: Int {
return 2
}
func gameDidStart(_ game: Game) {
print("Game start")
}
func gameDidEnd(_ game: Game) {
print("Game end")
}
}
// 依頼される
let delegate = TwoPersonsGameDelegate()
// 依頼する
let twoPersonsGame = Game()
twoPersonsGame.delegate = delegate
twoPersonsGame.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment