協(xié)議能夠要求其遵循者必備某些特定的實例方法和類方法。協(xié)議方法的聲明與普通方法聲明相似,但它不需要方法內(nèi)容。
注意: 協(xié)議方法支持變長參數(shù)(variadic parameter),不支持默認參數(shù)(default parameter)。
前置class關(guān)鍵字表示協(xié)議中的成員為類成員;當協(xié)議用于被枚舉或結(jié)構(gòu)體遵循時,則使用static關(guān)鍵字。如下所示:
protocol SomeProtocol {
class func someTypeMethod()
}
protocol RandomNumberGenerator {
func random() -> Double
}
RandomNumberGenerator協(xié)議要求其遵循者必須擁有一個名為random, 返回值類型為Double的實例方法。(我們假設(shè)隨機數(shù)在[0,1]區(qū)間內(nèi))。
LinearCongruentialGenerator類遵循了RandomNumberGenerator協(xié)議,并提供了一個叫做線性同余生成器(linear congruential generator)的偽隨機數(shù)算法。
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"