协议
协议
1.协议语法
使用protocol关键字定义协议。
protocol SomeProtocol {
// 协议内容
}
// 实现多个协议时,各个协议之间用逗号分割
struct SomeStruct : FirstProtocol , AnotherProtocol {
// 结构体内容
}
//继承父类的同时,也才用了协议,应当把父类放在协议之前
class SomeClass : SomeSuperClas , FirstProtocol , AnotherProtocol {
//类的内容
}
2.对属性的规定
protocol SomeProtocol {
//定义读写计算属性
var mustBeSettable : Int { get set }
// 只读属性
var doesNotNeedToBeSettable : Int { get }
// 使用static表示属性为类成员
static var somTypeProperty : Int { get set }
}
3.对方法的规定
protocol SomeProtocol {
//类方法
static func someTypeMethod ()
// 实例方法
func random () -> Double
}
类在实现协议中的mutating方法时,不用写mutating关键字。用结构体,枚举实现协议中的mutating方法时,必须写mutating关键字。
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
4.对构造器的规定
protocol SomeProtocol {
init ( someParameter : Int )
}
你可以在遵循该协议的类中实现构造器,并指定其为类的特定构造器或者便利构造器。无论是什么构造器,都必须给构造器实现标上required修饰符
class SomeClass : SomeProtocol {
required init ( someParameter : Int ){
//实现
}
}
如果一个子类重写了父类的指定构造器,并且该构造器遵循了某个协议的规定,那么该构造器的实现需要同时标示为required和override修饰符
protocol SomeProtocol {
init ()
}
class SomeSuperClass {
init () {
//协议定义
}
}
class SomeSubClass : SomeSuperClass , SomeProtocol {
// "required" from SomeProtocol conformance; "override" from SomeSuperClass
required override init () {
// 构造器实现
}
如果在协议中定义一个可失败构造器,则在遵顼该协议的类型中必须添加同名同参数的可失败构造器或非可失败构造器。 如果在协议中定义一个非可失败构造器,则在遵循该协议的类型中必须添加同名同参数的非可失败构造器或隐式解析类型的可失败构造器(init!)。
September 28, 2026
May 18, 2015
GitHub