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
随机推荐
- Mac OS X 快捷键(完整篇)
不少朋友提出要求,希望有个「高质量」的列表.其实这样的资源真是太多,平果官网就有 快捷键文档(多国语言版本).于是花了20分钟,浏览了一些网站,整理了点资源放过来供大家参考. 快捷键是通过按下键盘上的 ...
- KEIL MDK环境下uCOS-II在LPC17xx上的移植实例
1. 知识准备 要想对ucos-ii的移植有较深的理解,需要两方面知识: (1)目标芯片,这里是lpc17xx系列芯片,它们都是基于ARMv7 Cortex-M3内核,所以这一类芯片的ucos-ii移 ...
- python cmd 模块
command模块用于执行以字符串形式指定的简单系统命令,并将其输出以字符串形式返回.此模块尽在unix系统上有效.这个模型提供的功能与在unix shell脚本使用的反引号(就是~这个键下的那个反引 ...
- JQuery(上)
1.流行的JavaScript类库 -- 框架.插件 )为了简化 JavaScript 的开发, 一些 JavsScript 库诞生了. JavaScript 库封装了很多预定义的对象和实用函数 ...
- Fibonacci Tree(最小生成树,最大生成树)
Fibonacci Tree Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)To ...
- MVC中Json的使用:Controller中Json的处理【转】
一.当查询得到的数据符合前台要求,不需要做任何处理,直接DataList To Json 返回前台. 代码: , out recordCount); return Json(allEntities, ...
- HBASE学习笔记--配置信息
hbase的配置信息,在hbase-site.xml里面有详细说明. 可以按照需要查询相关的配置. <?xml version="1.0"?> <?xml-sty ...
- C# - 动态连接数据库字符串
String conStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|数据库文件.mdf;Integrated ...
- new String[0]的作用
返回包含此 collection 中所有元素的数组:返回数组的运行时类型与指定数组的运行时类型相同.如果指定的数组能容纳 该 collection,则返回包含此 collection 元素的数组.否则 ...
- c++标准库函数equal_range()
首先容器(vector)的中的元素是有序的.这里就不讲容器元素类型为内置的类型的用法,因为比较容易. 重点讲一下容器元素类型为自定义类型时的用法.当我们把自定义类型的数据成员的类型的值传给equal_ ...