Swift学习

Swift 协议(Protocol)⑩

2020-08-04  本文已影响0人  Aliv丶Zz

  协议可以用来定义方法、属性、下标的生命,协议可以被枚举、结构体、类遵守(多个协议之间用逗号,隔开)


示例:

protocol Drawable {
    func draw()
    var x: Int {get set}
    var y: Int {get }
    subscript(index: Int) -> Int{set get}
}

class Person : Drawable {
    var x: Int = 0
    let y: Int = 0
    func draw() {
        
    }
    subscript(index: Int) -> Int {
        set{}
        get{index}
    }
}

class Student: Drawable {
    var x: Int{
        get{10}
        set{/* 省略 */}
    }
    var y: Int{0}
    func draw() {
        
    }
    subscript(index: Int) -> Int {
        set{}
        get{index}
    }
}

static 、class

为了保证通用,协议中必须用static定义类型方法、类型属性、类型下标

mutating

class Car {
    var price : Double = 0
    var color : String = "white"
    
}
struct Person {
    var car = Car()
    var cars = [Car]()
    init() {
        cars.append(car)
    }
    func changeColor()  {
        self.car.color = "red"
    }
    mutating func addCar(_ newCar:Car)  {
        self.cars.append(newCar)
    }
}
var p = Person()
p.changeColor()
p.addCar(Car())
print(p.car.color)
print(p.cars.count)

init

协议的继承

一个协议可以继承其他协议

协议组合

协议组合,可以包含1个类类型(最多一个)

protocol Livable {}

protocol Runnable {}

class Person {
    
}
//接收Person或其子类的实例
func fun0(obj:Person)  {
    
}
//接收同时遵守Livable、Runnable协议、并且是Person或者其子类的实例
func fun1(obj: Person & Livable & Runnable){}

CaseIterable 协议(了解)

CustomStringConvertible 协议

class Person : CustomStringConvertible {
    var description: String{
        return "Person_description"
    }
}
var p = Person()
print(p)//Person_description

Any、AnyObject

Swift提供了2中特殊类型:AnyAnyObject

is、as?、as!、as

class Person : CustomStringConvertible {
    var name: String = "Jack"
    
    var description: String{
        return "Person_description"
    }
}
var stu: Any = 10
stu = Person()

if let n = (stu as? Person)?.name{
    print(n)
}else{
    print("stu is not Person")
}
var data = [Any]()
data.append(Int("123") as Any)

print(stu is Int)

print(stu is Person)

print(data)

【打印结果】

false
true
Jack
[Optional(123)]

X.self 、X.type、AnyClass

class Person {}
class Student: Person {}

var perType : Person.Type = Person.self
var stuType : Student.Type = Student.self
perType = Student.self

var anyType:AnyObject.Type = perType
anyType = stuType

public typealias AnyClsaa = AnyObject.Type
var anyType2:AnyClass = Person.self
anyType2 = Student.self

var typeObj = type(of: anyType2)
print(typeObj)//Student.Type

【元类型应用】

class Animal {
   required init() {
        
    }
}
class Cat: Animal {}
class Dog: Animal {}
class Pig: Animal {}

func creat(_ clas : [Animal.Type]) -> [Animal] {
    var arr = [Animal]()
    for cls in clas {
        arr.append(cls.init())
    }
    return arr
}

print(creat([Cat.self,Dog.self,Pig.self]))

Self 类似于OC中的instancetype

上一篇下一篇

猜你喜欢

热点阅读