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
随机推荐
- 安装 Archlinux 小记
故事的背景 开始的时候装的 win8 + ubuntu 双系统,但是慢慢感觉只要有 windows 存在,在 Linux 上遇到问题了就想逃回去. 在一次 GDG 的演讲中听到的: 趁现在还年轻,还有 ...
- Ubuntu下Geary安装
sudo add-apt-repository ppa:yorba/ppasudo apt-get updatesudo apt-get install geary
- CC EAL认证
国际通用准则(CC) CC(Common Criteria)是国际标准化组织统一现有多种准则的结果,是目前最全面的评价准则.1996年6月,CC第一版发布:1998年5月,CC第二版发布:1999年 ...
- SWOT自我分析
个人信息: 大三学生 二本大学 软件工程专业 一:SWOT自我分析 Strenghs(优势): 1.有着良好的作息习惯,坚持锻炼 2.专注力强,能沉下心来学习 3.有着强烈的危机意思,明白不仅则退的道 ...
- linux(debian) 安装jdk
#vi /etc/profile 在里面添加如下内容 export JAVA_HOME=/usr/java/jdk1.6.0_27 export JAVA_BIN=/usr/java/jdk1.6.0 ...
- Spring流程
Spring Web Flow是Spring框架的子项目,作用是让程序按规定流程运行. 1 安装配置Spring Web Flow 虽然Spring Web Flow是Spring框架的子项目,但它并 ...
- Ubuntu12.04下eclipse提示框黑色背景色的修改方法
eclipse提示框的背景颜色使用的是系统的提示框颜色配置,在windows下为黄色,但在Ubuntu12.04(gnome)下却是黑色,造成提示内容很难看清. 在eclipse中我们是无法修改这个颜 ...
- 《github一天一道算法题》:插入排序
看书.思考.写代码! /*********************************************** * copyright@hustyangju * blog: http://bl ...
- jquery Ztree v3.5 实例2 自定义显示在节点前的图片
显示效果如下: 代码如下: <html> <head><title></title></head> <script type=&quo ...
- 自己主动更新--下载apk以及提示对话框的实现(3)
下载apk以及提示对话框的实现 一.步骤: 1. 确定有能够更新的版本号,对话框提醒用户是否进行更新. 2. 选择更新的话,显示下载对话框而且进行下载.否则关闭提示更新对话框. 3. Apk下载完毕后 ...