Swift-OOP-Protocol
2020-11-25 本文已影响0人
守护地中海的花

protocol Drawable {
func draw()
var x: Int {
get set
}
var y: Int {get}
subscript(index: Int) -> Int {get set}
}
protocol Test1 {
}
protocol Test2 {
}
protocol Test3 {
}
class TestClass: Test1,Test2,Test3 {
}
- 协议可以用来定义方法、属性、下标的声明、协议可以被枚举、结构体、类遵守(多个协议之间用逗号隔开)
- 协议中定义方法时不能有默认参数值
- 默认情况下,协议中定义的内容必须全部都实现
- 也有方法搬到只实现部分内容
协议中的属性
class Person : Drawable {
var x: Int = 0
let y: Int = 0
func draw() {
print("Person draw")
}
subscript(index: Int) -> Int {
set {
}
get {
index
}
}
}
class Student: Drawable {
var x: Int {
get{0}
set{}
}
var y: Int{0}
func draw() {
print("")
}
subscript(index: Int) -> Int {
set{}
get{index}
}
}
- 协议中定义属性时必须要var 关键字
- 实现协议时的属性权限要不小于协议中定义的属性权限
- 协议定义get、set,用var存储属性或get、set计算属性去实现
- 协议定义get,用任何属性都可以实现
协议中static、class
/**
* 为了保证通用,协议中必须用static定义类型方法、类型属性、类型下标
*/
protocol Drawablex {
static func draw()
}
class Personx: Drawablex {
// static func draw() {
// print("Personx Draw")
// }
class func draw() {
print("Personx Draw")
}
//class static 都可以
}
- 为了保证通用,协议中必须用static定义类型方法、类型属性、类型下标
协议中mutating
protocol Drawablem {
mutating func draw()
}
class Size: Drawablem {
var width = 10
func draw() {
width = 20
}
}
struct Point:Drawablem {
var width = 10
mutating func draw() {
width = 20 + width
}
}
- 只有将协议中的实例方法标记为mutating
- 才允许结构体、枚举的具体实现修改自身内存
- 类在实现方法时不用加mutating,枚举、结构体才需要加mutating
协议中的init
protocol Drawablei {
init(x: Int,y: Int)
}
class Pointi: Drawablei {
required init(x: Int, y: Int) {
}
}
final class Sizei: Drawablei {
init(x: Int, y: Int) {
}
}
class originPointi {
init(x: Int, y: Int) {
}
}
class subPointi: originPointi,Drawablei {
required override init(x: Int, y: Int) {
super.init(x: x, y: y)
}
}
- 下面其实有的语法无需记忆 因为实现协议 编译器会自动提醒你
- 协议中还可以定义初始化器init
- 非final类实现时必须加上required
- 如果从协议实现的初始化器,刚好是重写了父类的指定初始化器那么这个初始化器必须同时加required,override
init、init?、init! 不知道用处多不多
protocol Liveable {
init ()
init?(age: Int)
init!(no: Int)
}
class Persona: Liveable {
required init() {
}
required init!(no: Int) {
}
required init?(age: Int) {
}
}
- 协议中定义的init?、init!,可以用init、init?、init!去实现
- 协议中定义的init,可以用init、init!去实现
协议的继承
protocol Runnaable {
func run()
}
protocol Playnaable : Runnaable {
func breath()
}
class Dog: Playnaable {
func run() {
}
func breath() {
}
}
- 一个协议可以继承其他协议
协议的组合
func fn0 (obj: Runnaable & Playnaable) {
}
CustomStringConvertible
class Personz: CustomStringConvertible,CustomDebugStringConvertible {
var age = 0
var description: String{"person\(age)"}
var debugDescription: String{"debugPerson\(age)"}
}
let pz = Personz()
print(pz)
debugPrint(pz)
- 遵守CustomStringConvertible,CustomDebugStringConvertible协议,都可以自定义实例的打印字符串