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
随机推荐
- Android开发:自定义GridView/ListView数据源
http://mobile.51cto.com/android-259861.htm 在开发中,我们常常会遇到比较复杂的GridView/ListView的布局,重新实现BaseAdapter不但能帮 ...
- Epipe
http://www.cnblogs.com/carekee/articles/2904603.html http://blog.chinaunix.net/uid-10716167-id-30805 ...
- 鼠标拖放div 实现
Javascript的mousemove事件类型是一个实时响应的事件,当鼠标指针的位置发生变化时(至少移动1个像素),就会触发mousemove事件.该事件响应的灵敏度主要参考鼠标指针移动速度的快慢, ...
- CC++初学者编程教程(6) 配置WindowsXP虚拟机与VC6.0
1.我们安装需要下列文件. 2.新建一个虚拟机. 3. 选择默认的 Vmware Work Station10.0 4. 我们选择这个WindowsXP镜像. 5. 我们复制一个WindowsXPSP ...
- 普林斯顿大学算法课 Algorithm Part I Week 3 求第K大数 Selection
问题 给定N个元素的数组,求第k大的数. 特例当k=0时,就是求最大值,当k=N-1时,就是求最小值. 应用顺序统计求top N排行榜 基本思想 使用快速排序方法中的分区思想,使得a[k]左侧没有更小 ...
- aix Mysql安装 Oracle官方教程
http://dev.mysql.com/doc/refman/5.1/en/aix-installation.html (aix Mysql安装 Oracle官方教程)
- GCDAsyncUdpSocket的使用
tips: 要注意服务器端口与客户端端口的区别,如果客户端绑定的是服务器的端口,那么服务器发送的消息就会一直发送给服务器.
- java中文乱码解决之道(三)—–编码详情:伟大的创想—Unicode编码
原文出处:http://cmsblogs.com/?p=1458 随着计算机的发展.普及,世界各国为了适应本国的语言和字符都会自己设计一套自己的编码风格,正是由于这种乱,导致存在很多种编码方式,以至于 ...
- Java学习笔记---继承和super的用法
自从换了个视频教学,感觉比原来那个好多了,就是学校网速太渣,好多视频看一会卡半天,只能先看看已经下载的了. 不过也好,虽然不能从开始开始重新开,但是已经看过一次,在看一次也是好的,就当巩固学习了. 继 ...
- 记录下url拼接的多条件筛选js
本着为提高工作效率百度或者google这些代码发现拿过来的都不好用,然后自己写了个,写的一般但记录下以后再优化 <html> <head> <script> $(f ...