The Swift Programming Language--语言指南--协议
- protocol SomeProtocol {
- // 协议内容
- }
- struct SomeStructure: FirstProtocol, AnotherProtocol {
- // 结构体内容
- }
- class SomeClass: SomeSuperClass, FirstProtocol, AnotherProtocol {
- // 类的内容
- }
- protocol SomeProtocol {
- var musBeSettable : Int { get set }
- var doesNotNeedToBeSettable: Int { get }
- }
- protocol AnotherProtocol {
- class var someTypeProperty: Int { get set }
- }
- protocol 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.anme = name
- self.prefix = prefix
- }
- var fullName: String {
- return (prefix ? prefix ! + " " : " ") + name
- }
- }
- var ncc1701 = Starship(name: "Enterprise", prefix: "USS")
- // ncc1701.fullName == "USS Enterprise"
- protocol SomeProtocol {
- class func someTypeMethod()
- }
- 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) % m)
- return lastRandom / m
- }
- }
- let generator = LinearCongruentialGenerator()
- println("Here's a random number: \(generator.random())")
- // 输出 : "Here's a random number: 0.37464991998171"
- println("And another one: \(generator.random())")
- // 输出 : "And another one: 0.729023776863283"
- protocol Togglable {
- mutating func toggle()
- }
- enum OnOffSwitch: Togglable {
- case Off, On
- mutating func toggle() {
- switch self {
- case Off:
- self = On
- case On:
- self = Off
- }
- }
- }
- var lightSwitch = OnOffSwitch.Off
- lightSwitch.toggle()
- //lightSwitch 现在的值为 .On
- 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: LinearCongruentialGenerator())
- for _ in 1...5 {
- println("Random dice roll is \(d6.roll())")
- }
- //输出结果
- //Random dice roll is 3
- //Random dice roll is 5
- //Random dice roll is 4
- //Random dice roll is 5
- //Random dice roll is 4
- 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 dic = Dice(sides: 6, generator: LinearCongruentialGenerator())
- var square = 0
- var board: Int[]
- init() {
- board = Int[](count: finalSquare + 1, repeatedValue: 0)
- board[03] = +08; board[06] = +11; borad[09] = +09; board[10] = +02
- borad[14] = -10; board[19] = -11; borad[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 {
- println("Started a new game of Snakes and Ladders")
- }
- println("The game is using a \(game.dice.sides)-sided dice")
- }
- func game(game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) {
- ++numberOfTurns
- println("Rolled a \(diceRoll)")
- }
- func gameDidEnd(game: DiceGame) {
- println("The game lasted for \(numberOfTurns) turns")
- }
- }
- “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”
- protocol TextRepresentable {
- func asText() -> String
- }
- extension Dice: TextRepresentable {
- cun asText() -> String {
- return "A \(sides)-sided dice"
- }
- }
- let d12 = Dice(sides: 12,generator: LinearCongruentialGenerator())
- println(d12.asText())
- // 输出 "A 12-sided dice"let d12 = Dice(sides: 12,generator: LinearCongruentialGenerator())
- println(d12.asText())
- // 输出 "A 12-sided dice"let d12 = Dice(sides: 12,generator: LinearCongruentialGenerator())
- println(d12.asText())
- // 输出 "A 12-sided dice"
- extension SnakeAndLadders: TextRepresentable {
- func asText() -> String {
- return "A game of Snakes and Ladders with \(finalSquare) squares"
- }
- }
- println(game.asText())
- // 输出 "A game of Snakes and Ladders with 25 squares"
- struct Hamster {
- var name: String
- func asText() -> String {
- return "A hamster named \(name)"
- }
- }
- extension Hamster: TextRepresentabl {}
- let simonTheHamster = Hamster(name: "Simon")
- let somethingTextRepresentable: TextRepresentabl = simonTheHamester
- println(somethingTextRepresentable.asText())
- // 输出 "A hamster named Simon"
- let things: TextRepresentable[] = [game,d12,simoTheHamster]
- for thing in things {
- println(thing.asText())
- }
- // A game of Snakes and Ladders with 25 squares
- // A 12-sided dice
- // A hamster named Simon
- protocol InheritingProtocol: SomeProtocol, AnotherProtocol {
- // 协议定义
- }
- 如下所示,PrettyTextRepresentable协议继承了TextRepresentable协议
- protocol PrettyTextRepresentable: TextRepresentable {
- func asPrettyText() -> String
- }
- extension SnakesAndLadders: PrettyTextRepresentable {
- func asPrettyText() -> String {
- var output = asText() + ":\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
- }
- }
- println(game.asPrettyText())
- // A game of Snakes and Ladders with 25 squares:
- // ○ ○ ▲ ○ ○ ▲ ○ ○ ▲ ▲ ○ ○ ○ ▼ ○ ○ ○ ○ ▼ ○ ○ ▼ ○ ▼ ○
- protocol Named {
- var name: String { get }
- }
- protocol Aged {
- var age: Int { get }
- }
- struct Person: Named, Aged {
- var name: String
- var age: Int
- }
- func wishHappyBirthday(celebrator: protocol) {
- println("Happy birthday \(celebrator.name) - you're \(celebrator.age)!")
- }
- let birthdayPerson = Person(name: "Malcolm", age: 21)
- wishHappyBirthday(birthdayPerson)
- // 输出 "Happy birthday Malcolm - you're 21!
- @objc protocol HasArea {
- var area: Double { get }
- }
- class Circle: HasArea {
- let pi = 3.1415927
- var radius: Double
- var area:≈radius }
- init(radius: Double) { self.radius = radius }
- }
- class Country: HasArea {
- var area: Double
- init(area: Double) { self.area = area }
- }
- class Animal {
- var legs: Int
- init(legs: Int) { self.legs = legs }
- }
- let objects: AnyObject[] = [
- Circle(radius: 2.0),
- Country(area: 243_610),
- Animal(legs: 4)
- ]
- for object in objects {
- if let objectWithArea = object as? HasArea {
- println("Area is \(objectWithArea.area)")
- } else {
- println("Something that doesn't have an area")
- }
- }
- // Area is 12.5663708
- // Area is 243610.0
- // Something that doesn't have an area
- @objc protocol CounterDataSource {
- @optional func incrementForCount(count: Int) -> Int
- @optional var fixedIncrement: Int { get }
- }
- @objc class Counter {
- var count = 0
- var dataSource: CounterDataSource?
- func increment() {
- if let amount = dataSource?.incrementForCount?(count) {
- count += amount
- } else if let amount = dataSource?.fixedIncrement? {
- count += amount
- }
- }
- }
- class ThreeSource: CounterDataSource {
- let fixedIncrement = 3
- }
- var counter = Counter()
- counter.dataSource = ThreeSource()
- for _ in 1...4 {
- counter.increment()
- println(counter.count)
- }
- // 3
- // 6
- // 9
- // 12
- class TowardsZeroSource: CounterDataSource {
- func incrementForCount(count: Int) -> Int {
- if count == 0 {
- return 0
- } else if count < 0 {
- return 1
- } else {
- return -1
- }
- }
- }
- counter.count = -4
- counter.dataSource = TowardsZeroSource()
- for _ in 1...5 {
- counter.increment()
- println(counter.count)
- }
- // -3
- // -2
- // -1
- // 0
- // 0
The Swift Programming Language--语言指南--协议的更多相关文章
- The Swift Programming Language 英文原版官方文档下载
The Swift Programming Language 英文原版官方文档下载 今天Apple公司发布了新的编程语言Swift(雨燕)将逐步代替Objective-C语言,大家肯定想学习这个语言, ...
- The Swift Programming Language 中文翻译版(个人翻新随时跟新)
The Swift Programming Language --lkvt 本人在2014年6月3日(北京时间)凌晨起来通过网络观看2014年WWDC 苹果公司的发布会有iOS8以及OS X 10.1 ...
- [iOS翻译]《The Swift Programming Language》系列:Welcome to Swift-01
注:CocoaChina翻译小组已着手此书及相关资料的翻译,楼主也加入了,多人协作后的完整译本将很快让大家看到. 翻译群:291864979,想加入的同学请进此群哦.(本系列不再更新,但协作翻译的进度 ...
- 《The Swift Programming Language》的笔记-第24页
The Swift Programming Language读书笔记学习笔记 第24页 本页主要内容有两个:打印输出和怎样在swift凝视代码 1 怎样打印变量和常量的值? 使用println函数,细 ...
- iOS Swift-元组tuples(The Swift Programming Language)
iOS Swift-元组tuples(The Swift Programming Language) 什么是元组? 元组(tuples)是把多个值组合成一个复合值,元组内的值可以使任意类型,并不要求是 ...
- iOS Swift-控制流(The Swift Programming Language)
iOS Swift-控制流(The Swift Programming Language) for-in 在Swift中for循环我们可以省略传统oc笨拙的条件和循环变量的括号,但是语句体的大括号使我 ...
- iOS Swift-简单值(The Swift Programming Language)
iOS Swift-简单值(The Swift Programming Language) 常量的声明:let 在不指定类型的情况下声明的类型和所初始化的类型相同. //没有指定类型,但是初始化的值为 ...
- The Swift Programming Language 中国版
iSwifting社会的 Swift 兴趣交流群:303868520 iOS 微信公众账号:iOSDevTip Swift 微信公众账号:SwiftDev iSwifting社区 假设你认为这个项目不 ...
- 下载The Swift Programming Language.mobi版
下载 The Swift Programming Language.mobi 下载 http://download.csdn.net/detail/swifttrain/7444501
随机推荐
- [Django] Windows 下安装 配置Pinax 工程
Pinax 是一个基于Django开发的脚手架,有一些现成的模板和功能模块可以使用,方便快速有效的开发一个Django项目.下面举个例子如何安装一个pinax项目到集成开发环境Aptana里面. 先从 ...
- Memcached简明介绍
官网介绍:http://memcached.org/ Free & open source, high-performance, distributed memory object cachi ...
- Linux学习笔记4-三种不同类型的软件的安装(绿色软件、rpm软件、源代码软件)
在Linux下软件分三种: 1.绿色软件:即不用安装直接就能用的软件 2.rpm安装包:以rpm结尾的可执行文件 3.源码文件:没有进行过编译和打包的文件,需要编译后再进行安装 一.绿色软件的安装 ...
- 任意给定一个正整数N,求一个最小的正整数M(M>1),使得N*M的十进制表示形式里只含有1和0。
题目:任意给定一个正整数N,求一个最小的正整数M(M>1),使得N*M的十进制表示形式里只含有1和0. 解法一:暴力求解.从1开始查找M,然后判断M*N=X这个数字是否只含有0,1. 解法二:由 ...
- 动画原理——绘画API
书籍名称:HTML5-Animation-with-JavaScript 书籍源码:https://github.com/lamberta/html5-animation 1.canvas的conte ...
- 通过自定义注解反射生成SQL语句
----------------------------------------Program.cs---------------------------------------- using Sys ...
- Linux命令之ifconfig
许多windows非常熟悉ipconfig命令行工具,它被用来获取网络接口配置信息并对此进行修改.Linux系统拥有一个类似的工具,也就是ifconfig(interfaces config).通常需 ...
- centos安装中文支持(转)
安装中文支持包. yum install fonts-chineseyum install fonts-ISO8859-2 -------- 一.安装中文支持方法1.在安装光盘中找到一下包进行安装.r ...
- Android minHeight/Width,maxHeight/Width
在layout文件中,设置IamgeView的最大(最小)高度(宽度)时,需要同时设置android:adjustViewBounds="true",这样设置才会生效.在代码中设置 ...
- MySQL AUTO_INCREMENT 简介
可使用复合索引在同一个数据表里创建多个相互独立的自增序列,具体做法是这样的:为数据表创建一个由多个数据列组成的PRIMARY KEY OR UNIQUE索引,并把AUTO_INCREMENT数据列包括 ...