协议定义了用来实现某一特定功能所必需的方法和属性。
协议由类,结构或枚举实现,实现协议要求方法的行为称为遵
守协议。
1.协议的语法
定义协议:
protocol SomeProtocol {
// protocol definition goes here
}
实现协议:
struct SomeStructure: FirstProtocol, AnotherProtocol {
// structure definition goes here
}
当一个类有父类,又遵循协议时,要这样写:
class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {
// class definition goes here
}
2.协议中的实例属性和类属性
实例属性:
protocol SomeProtocol {
//可读可设置
var mustBeSettable: Int { get set }
//可读
var doesNotNeedToBeSettable: Int { get }
}
类属性:
protocol AnotherProtocol {
static var someTypeProperty: Int { get set }
}
3.协议中的方法
协议中声明的方法没有具体实现,也不能为方法参数指定默认值
protocol SomeProtocol {
static 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).truncatingRemainder(dividingBy:m))
return lastRandom / m
}
}
let generator = LinearCongruentialGenerator()
print("Here's a random number: \(generator.random())")
// Prints "Here's a random number: 0.3746499199817101"
print("And another one: \(generator.random())")
// Prints "And another one: 0.729023776863283"
网友评论