Swift_Protocol_Base

2018-02-25  本文已影响4人  YoNotes

①Protocol语法

❶格式

class 类名 : 协议1 , 协议n{
}
class 类名:父类,协议1,协议n{
}

❷属性的要求

// 协议
protocol oneProtocol{
    // 定义变量,必须在属性声明后添加{get}或者{get set}
    var argumentOne:Int{get} // 只读
    var argumentTwo:Int{get set} // 读写
    static var argumentClass:Int{get}
}
// 类
class Person:oneProtocol{
    var argumentOne: Int
    var argumentTwo: Int
    static var argumentClass: Int{
        get{
            return 30
        }
    }
    init(argumentOne:Int,argumentTwo:Int) {
        self.argumentOne = argumentOne
        self.argumentTwo = argumentTwo
    }
}
var per = Person(argumentOne: 90, argumentTwo: 1)
print("\(per.argumentOne)") // 90
print("\(Person.argumentClass)") // 30

❸方法要求

protocol funcProtocol{
    func sayHello()
    static func sayBad()
}
class Person:funcProtocol{
    func sayHello() {
        print("Hello")
    }
    static func sayBad() {
        print("Bad")
    }
}

❹Mutating方法要求

protocol Togglable{
    mutating func toggle()
}
enum OnOffSwitch:Togglable{
    case On,Off
    mutating func toggle() {
        switch self {
        case .Off:
            self = .On
        case .On:
            self = .Off
        }
    }
}
var light = OnOffSwitch.Off //Off
light.toggle()  // On

struct OnOFF:Togglable{
    var one:Int
    var two:Int
    mutating func toggle() {
        if self.one > 10 {
            self.two = 30

        }else{
            self.two = 20
        }
    }
}
var LIGHT = OnOFF(one: 2, two: 3)
print("\(LIGHT.two)") // 3
LIGHT.toggle()
print("\(LIGHT.two)") // 20

❺使用协议规范构造函数

protocol TwoProtocol{
    init(twoArgument:Int)
}
class two:TwoProtocol{
    required init(twoArgument: Int) {
    }
}
protocol TwoProtocol{
    init()
}
class TwoSuperClass{
    init() {
    }
}
class Two:TwoSuperClass,TwoProtocol{
    required override init() {
    }
}
 protocol TwoProtocol{
    func say()
}
class TwoSuperClass{
    final func say(){
        print("Super Say Hello")
    }
}
class Two:TwoSuperClass,TwoProtocol{
    // 无法实现say方法
}

❻协议类型

②委托/代理设计模式

③协议的各种使用

❶在扩展中添加协议成员

protocol TextProtocol{
    func printSomeMessage(message:String)
}
class Dice{
}]
extension Dice:TextProtocol{
    func printSomeMessage(message: String) {
        print("\(message)")
    }
}
let dic = Dice()
dic.printSomeMessage(message: "hello");

❷通过扩展补充协议声明

protocol TextProtocol{
    func printSomeMessage(message:String)
}
struct Hamster{
    func printSomeMessage(message: String) {
        print("\(message)")
    }
}
extension Hamster:TextProtocol{
   // 此时,Hamster的实例也可以作为TextProtocol类型使用
}
let hamster = Hamster()

❸集合中的协议类型

let things:[TextProtocol] = [dic,hamster]
for thing in things {
    thing.printSomeMessage(message: "Hello Word")
}
// 由于thing被当作是TextProtocol类型,故都能调用printSomeMessage方法

❹仅在类中使用协议

 protocol SomeOnlyClassProtocol:class{
}
// 协议SomeOnlyClassProtocol实现者只能是类

⑤协议的继承

protocol OneProtocol{
    func sayOne()
}
// 协议的继承
protocol TwoProtocol:OneProtocol{
    func sayTwo()
}
class Person:TwoProtocol{
    func sayOne() {
        // 协议OneProtocol的方法
    }
    func sayTwo() {
        // 协议TwoProtocol的方法
    }
}

❶protocolComposition协议的合成

protocol NamedProtocol{
    var name:String{get set}
}

protocol GenderProtocol{
    var gender:String{get set}
}
protocol AgedProtocol{
    var age:Int{get}
}

struct Person:NamedProtocol,GenderProtocol,AgedProtocol{
    var name: String
    var gender: String
    var age: Int
}
func wishBirthday(celebrator:NamedProtocol & GenderProtocol){
    print("姓名:\(celebrator.name),性别:\(celebrator.gender)")
}

var per = Person(name: "wang", gender: "man",age:20)
wishBirthday(celebrator: per)
// 形参celebrator的类型为protocol<NamedProtocol,GenderProtocol>,可以传入任何实现这两个协议的实例。即使此实例不仅仅遵循这两个协议。
// swift3.0之后,protocol<NamedProtocol,GenderProtocol>被NamedProtocol & GenderProtocol替换。

❷检验协议的一致性

@objc protocol HasArea{
    var area:Double{get}

}
class Circle:HasArea{
    let pi = 3.1415927
    var radius:Double
    var area: Double{
        return pi * radius * radius
    }
    init(radius:Double) {
        self.radius = radius
    }
}
class Country:HasArea{
    var area: Double
    init(area:Double) {
        self.area = area
    }
}
class Animal{
    var legs:Int
    init(legs:Int) {
        self.legs = legs
    }
}
let objects:[AnyObject] = [
    Circle(radius: 20),
    Country(area: 200),
    Animal(legs: 10)
]
for object in objects {
    var objectWithArea = object as? HasArea
    if objectWithArea != nil {
        print("\(objectWithArea)")
        print("遵循了HasArea协议,\(object.area)")
    }else{
        print("没有遵循HasArea协议")
    }
}
print("--------------------")
for object in objects {
    // 返回值 true/false
    var objectWithArea = object is HasArea
    if objectWithArea {
        print("\(objectWithArea)")
        print("遵循了HasArea协议,\(object.area)")
    }else{
        print("没有遵循HasArea协议")
    }
}
/**
打印结果:
Optional(__lldb_expr_386.Circle)
遵循了HasArea协议,Optional(1256.63708)
Optional(__lldb_expr_386.Country)
遵循了HasArea协议,Optional(200.0)
没有遵循HasArea协议
--------------------
true
遵循了HasArea协议,Optional(1256.63708)
true
遵循了HasArea协议,Optional(200.0)
没有遵循HasArea协议
*/

❸可选协议要求

@objc protocol HasArea{
    @objc optional var area:Double{get}
    var width:Double{get}
}
class Circle:HasArea{
    let pi = 3.1415927
    var radius:Double = 10.0
    var width: Double = 20.0
}

参考01

上一篇 下一篇

猜你喜欢

热点阅读