Swift協議(Protocol)
阿新 • • 發佈:2019-01-09
協議是為方法、屬性等定義一套規範,沒有具體的實現。
協議能夠被類、結構體等具體實現(或遵守)。
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