您的当前位置:首页正文

15-Swift中协议的使用

来源:要发发知识网

一、协议的基本使用:

  1. 协议的定义格式:协议的定义方式与类,结构体,枚举的定义都非常相似
protocol Study{
    //协议方法
    func test()
}
  1. 遵守协议的格式:
class Person:Study{
    func test() {
        print("好好学习")
    }
}
  1. 定义协议和遵守协议:
  2. 类、结构体、枚举都可以遵循协议
/***  类遵循Study协议  ***/
class Person:Study{
       func test() {
           print("好好学习")
       }
}
/***  枚举遵循Study协议  ***/
enum StudyType:Study{
       case study01
       func test() {
           print("学习方式")
       }
}
StudyType.study01.test()
/***  结构体遵循Study协议  ***/
struct Jiegouti:Study{
       func test() {
           print("结构体")
       }
}
  1. 注意区分类继承和遵循协议的写法。

    • 如果是冒号":"后面是接口就遵循接口,如果是类,就是继承。
  2. 协议之间的继承:

protocol StudyHard:Study{
    func test2()
}
class Person2:StudyHard{
    func test() {
        print("学习")
    }
    func test2() {
        print("好好学习")
    }
}

二、协议中代理的使用

  1. 协议继承用于代理设计模式
  2. 案例
protocol WPrint{
    func test()
}

class BlackPrint:WPrint{
    func test() {
        print("黑白打印机")
    }
}

class ColorPrint:WPrint{
    func test() {
        print("彩色打印机")
    }
}

class Person1{

    var delegate:WPrint?

    func work(){
        delegate?.test()
    }
}

let p = Person1()
let black = BlackPrint()
let color = ColorPrint()

p.delegate = black
p.work()    //黑白打印机
p.delegate = color
p.work()    //彩色打印机
  1. 注意点:代理属性,一般都是使用weak修饰
  • weak修饰的必须是类类型对象
  • 所以一般要求协议继承自NSObjectProtocol/class
  • 协议继承自class:
protocol WPrint:class{
    func test()
}

class BlackPrint:WPrint{
    func test() {
        print("黑白打印机")
    }
}

class ColorPrint:WPrint{
    func test() {
        print("彩色打印机")
    }
}

class Person1{

    weak var delegate:WPrint?

    func work(){
        delegate?.test()
    }
}

let p = Person1()
let black = BlackPrint()
let color = ColorPrint()

p.delegate = black
p.work()    //黑白打印机
p.delegate = color
p.work()    //彩色打印机
  • 协议继承自NSObjectProtocol
protocol WPrint:NSObjectProtocol{
    func test()
}

class BlackPrint:NSObject,WPrint{
    func test() {
        print("黑白打印机")
    }
}

class ColorPrint:NSObject,WPrint{
    func test() {
        print("彩色打印机")
    }
}

class Person1{

    weak var delegate:WPrint?

    func work(){
        delegate?.test()
    }
}

let p = Person1()
let black = BlackPrint()
let color = ColorPrint()

p.delegate = black
p.work()    //黑白打印机
p.delegate = color
p.work()    //彩色打印机

三、协议中的可选

  1. 注意点:
  2. 在Swift中,如果遵循了一个协议,必须要实现协议里面所有的方法;
  3. OC中协议里面的方法有可选。
  4. 使用:
  5. 使用@objc修饰协议;
  6. 使用@objc optional修饰方法。
    3.实践:
@objc
protocol Work{

    @objc optional func test()
}

class Person:Work{

}

let p = Person()
p.test()    //报错,找不到test方法