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 {}
protocol Drawable {
func draw()
var x: Int { get set }
var y: Int { get }
subscript(index: Int) -> Int { get set }
}
- 协议中定义属性时必须用 var 关键字
- 实现协议时的属性权限要 不小于 协议中定义的属性权限
- 协议定义 get、set,用 var 存储属性或 get、set 计算属性去实现
- 协议定义 get,用任何属性都可以实现
class Person: Drawable {
func draw() {
print("Person draw")
}
var x: Int = 0
var y: Int = 0
subscript(index: Int) -> Int {
get {
index
}
set {
}
}
}
class Person: Drawable {
var x: Int {
get { 0 }
set {}
}
var y: Int { 0 }
func draw() {
print("Person draw")
}
subscript(index: Int) -> Int {
get {
index
}
set {
}
}
}
protocol Drawable {
static func draw()
}
class Person1: Drawable {
static func draw() {
print("Person1 draw")
}
}
class Person2: Drawable {
static func draw() {
print("Person2 draw")
}
}
protocol Drawable {
mutating func draw()
}
class Size: Drawable {
var width: Int = 0
func draw() {
width = 10
}
}
struct Point: Drawable {
var x: Int = 10
mutating func draw() {
x = 10
}
}
-
init
- 协议中还可以定义初始化器 init
- 非 final 类实现时必须加上 required
- 如果从协议实现的初始化器,刚好是重写了父类的指定初始化器,那么这个初始化必须同时加 required、override
protocol Drawable {
init(x: Int, y: Int)
}
class Size: Drawable {
required init(x: Int, y: Int) {
}
}
final class Point: Drawable {
init(x: Int, y: Int) {
}
}
protocol Livable {
init()
init?(age: Int)
init!(no: Int)
}
class Person: Livable {
// required init() {}
required init!() {}
required init?(age: Int) {}
// required init!(age: Int) {}
// required init(age: Int) {}
required init!(no: Int) {}
// required init?(no: Int) {}
// required init(no: Int) {}
}
protocol Runnable {
func run()
}
protocol Livable: Runnable {
func breath()
}
class Person: Livable {
func breath() {}
func run() {}
}
protocol Livable {}
protocol Runnable {}
class Person {}
// 接收 Person 或者其子类的实例
func fn0(obj: Person) {}
// 接收遵循 Livable 协议的实例
func fn1(obj: Livable){}
// 接收同时遵守 Livable、Runnable 协议的实例
func fn2(obj: Livable & Runnable){}
// 接收同时遵守 Livable、Runnable 协议,并且是 Person 或者其子类的实例
func fn3(obj: Person & Livable & Runnable){}
typealias RealPerson = Person & Livable & Runnable
// 接收同时遵守 Livable、Runnable 协议,并且是 Person 或者其子类的实例
func fn4(obj: RealPerson){}
enum Season: CaseIterable {
case spring, summer, autumn, winter
}
let seasons = Season.allCases
print(seasons.count) // 4
for season in seasons {
print(season)
} // spring summer autumn winter
class Person: CustomStringConvertible, CustomDebugStringConvertible {
var age = 0
var description: String {"person_\(age)"}
var debugDescription: String {"debug_person_\(age)"}
}
var person = Person()
print(person) // person_0
debugPrint(person) // debug_person_0
-
print 调用的是 CustomStringConvertible 协议的 description
-
debugPrint、po 调用的是 CustomDebugStringConvertible 协议的 debugDescription
-
Any、AnyObject
-
Swift 提供了两种特殊的类型 Any、AnyObject
-
Any:可以代表任意类型(枚举、结构体、类,函数类型)
-
AnyObject:可以代表任意类 类型(在协议后面写上:AnyObject 代表只有类能遵守这个协议)
在协议后面写上:class 也代表只有类能遵守这个协议
class Student {}
var stu: Any = 10
stu = "Jack"
stu = Student()
// 创建 1 个能存放任意类型的数组
// var data = Array<Any>()
var data = [Any]()
data.append(1)
data.append(3.14)
data.append(Student())
data.append("Jack")
data.append({ 10 })
protocol Runnable {
func run()
}
class Person {}
class Student: Person, Runnable {
func run() {
print("Student run")
}
func study() {
print("Student study")
}
}
var stu: Any = 10
print(stu is Int) // true
stu = "jack"
print(stu is String) // true
stu = Student()
print(stu is Person) // true
print(stu is Student) // true
print(stu is Runnable) // true
var stu: Any = 10
(stu as? Student)?.study() // 没有调用 study
stu = Student()
(stu as? Student)?.study() // Student study
(stu as! Student).study() // Student study
(stu as? Runnable)?.run() // Student run
var data = [Any]()
data.append(Int("123") as Any)
var d = 10 as Double
print(d) // 10.0
class Person {}
class Student: Person {}
var perType: Person.Type = Person.self
var stuType: Student.Type = Student.self
perType = Student.self
var anyType: AnyObject.Type = Person.self
anyType = Student.self
public typealias AnyClass = AnyObject.Type
var anyType2: AnyClass = Person.self
anyType2 = Student.self
var per = Person()
var perType1 = type(of: per) // Person.self
print(Person.self == type(of: per))
class Animal { required init() {} }
class Cat: Animal {}
class Dog: Animal {}
class Pig: Animal {}
func create(_ clsse: [Animal.Type]) -> [Animal] {
var arr = [Animal]()
for cls in clsse {
arr.append(cls.init())
}
return arr
}
// [SwiftTest.Cat, SwiftTest.Dog, SwiftTest.Pig]
print(create([Cat.self, Dog.self, Pig.self]))
class Person {
var age: Int = 0
}
class Student: Person {
var no: Int = 0
}
print(class_getInstanceSize(Student.self)) // 32
print(class_getSuperclass(Student.self)!) // Person
print(class_getSuperclass(Person.self)!) // _TtCs12_SwiftObject
-
从结果可以看得出来,Swift 还有个隐藏的基类:Swift._SwiftObject
-
可以参考源码:https://github.com/apple/swift/blob/master/stdlib/public/runtime/SwiftObject.h
-
Self
-
Self 代表当前类型
class Person {
var age = 1
static var count = 2
func run() {
print(self.age) // 1
print(Self.count) // 2
}
}
- Self 一般用作返回值类型,限定返回值跟方法调用者必须是同一类型(也可作为参数类型)
protocol Runnable {
func test() -> Self
}
class Person: Runnable {
required init() {}
func test() -> Self {
type(of: self).init()
}
}
class Student: Person {}
var p = Person()
// Person
print(p.test())
var stu = Student()
// Student
print(stu.test())
本文章只是本人的学习笔记!