lufei's Studio.

Kingfisher源码阅读:命名空间

字数统计: 349阅读时长: 1 min
2019/12/16 Share

前言

拜读喵神的Kingfisher,学习Swift,第一个就是这个kf命名空间的实现,好酷。

以前写OC的时候,给系统方法扩展,官方都是推荐使用增加前缀_的方式,swift的推出,改变了这种情况,因为语言特性和苹果力荐的面向协议编程,有了更酷的实现。

思路

实现一个包裹泛型Base类的Struct或者Class,实现Protocol 和你想要的命名空间,将 Protocol 加载到所需的 Base 类并通过Extension + where Base实现 Base 类的特定代码

实现

参考上面的源码和思路,我自己试着写了一遍,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/// 包裹NJBase的struct
struct NijieWrapper<NJBase> {

let base:NJBase

init(_ base: NJBase) {

self.base = base

}

}

/// 实现协议
protocol NijieCompatible: AnyObject {}
extension NijieCompatible {

var nj:NijieWrapper<Self> {

get { return NijieWrapper(self) }
set {}

}

}

/// 为UIImageView添加扩展
extension UIImageView: NijieCompatible {}
extension NijieWrapper where NJBase: UIImageView {

func setNijieImage(image:UIImage? = nil) {

base.image = image

}

}

实现协议的时候,之所以使用扩展,是因为需要给所有遵守协议的类型提供默认实现。

使用:

1
2
3
let imageView = UIImageView()
imageView.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
imageView.nj.setNijieImage(image: UIImage(named: "test123"))

结尾

这样子,命名空间就实现了,感恩swift

CATALOG
  1. 1. 前言
  2. 2. 思路
  3. 3. 实现
  4. 4. 结尾