Swift协议(Protocol)
2016-02-02 21:31
330 查看
协议是为方法、属性等定义一套规范。没有详细的实现。
协议可以被类、结构体等详细实现(或遵守)。
属性
1. set 和 get 訪问器
2.静态属性
3.仅仅读
实例:
方法
1.定义方法
2.定义静态方法
实例:
把协议作为类型使用
Swift交流讨论论坛论坛:http://www.cocoagame.net
欢迎增加Swift技术交流群:362298485
协议可以被类、结构体等详细实现(或遵守)。
protocol SomeProtocol { // protocoldefinition goes here } struct SomeStructure: FirstProtocol, AnotherProtocol { // structure definition goes here} class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol { // class definitiongoeshere }
属性
1. set 和 get 訪问器
protocol SomeProtocol { var mustBeSettable:Int { get set } var doesNotNeedToBeSettable: Int { get } }
2.静态属性
protocol AnotherProtocol { class var someTypeProperty: Int { get set } }
3.仅仅读
protocol FullyNamed { var fullName: String { get } }
实例:
struct Person: FullyNamed { varfullName: String } letjohn= Person(fullName: "John Appleseed") class Starship: FullyNamed { varprefix: String? varname: String init(name: String, prefix: String? = nil) { self.name = name self.prefix = prefix } varfullName: String { return (prefix ? prefix!+ " " :"")+ name } } varncc1701 = Starship(name: "Enterprise",prefix: "USS")
方法
1.定义方法
protocol RandomNumberGenerator{ func random() -> Double }
2.定义静态方法
protocolSomeProtocol { class func someTypeMethod() }
实例:
protocol RandomNumberGenerator{ funcrandom() -> Double } class LinearCongruentialGenerator:RandomNumberGenerator { var lastRandom= 42.0let m = 139968.0 let a = 3877.0 let c = 29573.0 funcrandom() -> Double { lastRandom = ((lastRandom * a + c) %m) returnlastRandom / m } } let generator= LinearCongruentialGenerator() println("Here's a random number: \(generator.random())") // prints "Here's a random number:0.37464991998171" println("And another one: \(generator.random())") //prints "And another one: 0.729023776863283"
把协议作为类型使用
protocol RandomNumberGenerator { func random() -> Double} class LinearCongruentialGenerator: RandomNumberGenerator { varlastRandom= 42.0 let m =139968.0 let a = 3877.0 letc = 29573.0 func random() -> Double { lastRandom = ((lastRandom * a + c) %m) return lastRandom / m } } class Dice { letsides: Int let generator: RandomNumberGenerator init(sides: Int, generator: RandomNumberGenerator) { self.sides = sidesself.generator = generator } func roll() -> Int{ return Int(generator.random() * Double(sides)) + 1 } } vard6 = Dice(sides: 6, generator: LinearCongruentialGenerator()) for_ in 1...5 { println("Randomdiceroll is \(d6.roll())") }
Swift交流讨论论坛论坛:http://www.cocoagame.net
欢迎增加Swift技术交流群:362298485
相关文章推荐
- swift接口的使用
- swift方法之URLForDirectory
- Swift中ViewController类与storyboard绑定报错
- Apple Swift 中文教程 高速參考 基本的语法
- Swift 特殊关键字 与符号
- Swift 引用计数总结 Strong,Weak, unowned 简单使用
- Swift - 操作SQLite数据库(引用SQLite3库)
- Swift 协议(Protocols)
- swift里的函数和闭包
- Swift解析JSON数据
- iOS8开发~Swift(一)入门
- 【引】swift是什么?
- swift-结构体和类创建的变量
- swift-setter&getter
- swift-类
- 弱引用?强引用?未持有?额滴神啊-- Swift 引用计数指导
- 11.Swift 中的类和结构体
- swift-比较运算符
- 用 Swift、Foursquare API 和 Realm 創建一個咖啡屋 App
- 游戏中的三角学——Sprite Kit 和 Swift 教程(2)