Swift编程最佳体验之Generic + Protocol + Extension

关于Swift代码风格,能让绝大部分人的眼前一亮,WTF?还能这样写?今天就带来一段Swift常见的Generic + Protocol + Extension基础代码。
知识点介绍:
1.Generic,泛型便是拥有共同特性的类型的代表,定义特定的泛型去书写代码,免去了很多不必要的事情。
2.Protocol,不做很多解释,你遵守我的协议就要帮我去做规定的事情。
3.Extension,为我们的日常代码模块化提供了很大的便利,让代码拓展更加轻松。

今天用这种方式实现UITableView方法做一些封装。

比如这样的代码:

let cellIdentifier = "cellIdentifier"
let cell = tableView.dequeueReusableCell(withReuseIdentifier: cellIdentifier)

长此以往,你或许已经厌倦了这种方式。

今天的学习便是为此而开展的,Go!

在Swift中,可以给Extension去实现一些底层的代码,那么就意味着我们不用每次必须遵守协议、实现协议,因为你可以在Class的扩展中让它自己去实现。Excuse me?他自己都实现了,要我们何用?答案一会就知道。

1.首先声明一个协议,并利用自身的拓展去实现这个协议
protocol Reusable {
    /// 为cell准备的Identifier
    static var just_Idnentifier: String { get }
}
extension Reusable {
    /// 利用自己的扩展实现自己
    static var just_Idnentifier: String {
        return String(describing: self)
    }
}
2.然后让UITableViewCell遵守上面的协议
// MARK: - 遵守这个协议,且什么都不用操作,我们便有了just_Identifier这个属性
extension UITableViewCell: Reusable { }
3.准备工作到这里就结束了,接下来我们将用到泛型Generic,我们用一个UITableView的扩展去添加一些方法
extension UITableView {
    func just_dequeueReusableCell<T: UITableViewCell>(_: T.Type) -> T where T: Reusable {
        guard let cell = self.dequeueReusableCell(withIdentifier: T.just_Idnentifier) as? T else {
            fatalError("Could not dequeue cell with identifier: \(T.just_Idnentifier)")
        }
        return cell
    }
    func just_registerNib<T: UITableViewCell>(_: T.Type) {
        register(UINib(nibName: T.just_Idnentifier, bundle: nil), forCellReuseIdentifier: T.just_Idnentifier)
    }
}
最后:接下来让咱们去看一下使用
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.just_registerNib(DemoCell.self)
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.just_dequeueReusableCell(DemoCell.self)
        cell.textLabel?.text = "Swift 最佳编程体验之 \(indexPath.row)"
        return cell
    }

这种方式是不是清爽了不少,且代码更不容易出错,逼格也上去了,所以还等什么呢?

最后附上Demo

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 原文:Generics Manifesto -- Douglas Gregor 译者注 在我慢慢地深入使用 Swi...
    kemchenj阅读 2,118评论 0 6
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,262评论 4 61
  • 136.泛型 泛型代码让你可以写出灵活,可重用的函数和类型,它们可以使用任何类型,受你定义的需求的约束。你可以写出...
    无沣阅读 1,535评论 0 4
  • 《人间词话》的作者王国维,初名国桢,字静安,亦字伯隅,初号礼堂,晚号观堂,又号永观,谥忠悫。是中国近、现代相交时期...
    我是代鱼鱼阅读 917评论 8 9
  • 觉秋 /深山老林(千年桃妖) 北友频秋意 南岭终觉早 当空日正炽 不亚酷暑毒 今来汤汤雨 愕然绝蛙鸣 薄裙不胜凉...
    深山老林千年桃妖阅读 254评论 1 2