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
随机推荐
- 帮助中心 7D-我的私家设计师 设计师品牌服饰集成网 7D服装定制!
帮助中心 7D-我的私家设计师 设计师品牌服饰集成网 7D服装定制! 关于我们
- BZOJ 3237([Ahoi2013]连通图-cdq图重构-连通性缩点)
3237: [Ahoi2013]连通图 Time Limit: 20 Sec Memory Limit: 512 MB Submit: 106 Solved: 31 [ Submit][ St ...
- Spring、实例化Bean的三种方法
1.使用类构造器进行实例化 <bean id="personIService" class="cn.server.impl.PersonServiceImpl&qu ...
- 配置php中的Oracle扩展
window 1. 从 OTN Instant Client page下载windows客户端安装包,安装包的位数(32/64位)必须和你所使用的操作系统类型.php版本一致.解压安装包至C:\ins ...
- 使用Cloudsim实现基于多维QoS的资源调度算法之中的一个:配置Cloudsim环境
Cloudsim是一款开源的云计算仿真软件,它继承了网格计算仿真软件Gridsim的编程模型,支持云计算的研究和开发.它是一个自足的支持数据中心.服务代理人.调度和分配策略的平台,支持大型云计算的基础 ...
- excel中匹配数据
=VLOOKUP(E6,BC:BD,2,0) E6就是要对应的那一列的一个单元格,BC就是对应的那一列,BD就是要取值的那一列
- M记单刷鸡盒副本
今天去M记单刷鸡盒副本,听说此副本掉落最新道具:黑暗之门.鸡翅区和鸡块区全通无压力,鸡腿区难度最大,老一是个灭团点.现在肚子很难受,刚去厕所吐了一把,看来有点高估自己,此副本最好还是组队前往,单刷压力 ...
- Oracle视图,序列及同义词、集合操作
一.视图(重点) 视同的功能:一个视图其实就是封装了一个复杂的查询语句.1.创建视图的语法:CREATE VIEW 视图名称 AS 子查询 范例:创建一个包含了20部门的视图CREATE VIEW e ...
- iOS7、iOS8推送通知的区别
iOS8版本以后的推送通知代码[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificati ...
- php curl_exec optimize
需求:前端过来一个请求,后台php要通过两次http请求,请求不同的地址得到资源后拼接返回给前端 请求A站: 请求B站: 同时请求A站和B站(php 串行 curl_exec ) 同时请求A站和B站( ...