美文网首页
IOS In Swift Tips 1 协议使用小技巧

IOS In Swift Tips 1 协议使用小技巧

作者: Dreamer_做梦的人 | 来源:发表于2016-12-21 17:07 被阅读37次

英文原文地址

swift 是一门面向对象的语言

下面将介绍三个方面的具体例子
View (UITable)ViewController Networking

例子一:

我想实现一个效果,点击button/view, 这个效果就会晃动。
思路 1. 具体控件实现 func shake()
思路 2. UIView extension 实现 func shake()
思路 3. 实现协议 shakeAble{} 内部实现默认方法 func shake() 在定义view时添加协议,增加可读性。

例子二:

TableViewCell 中设计字符串的部分,分别实现 对应协议。
对于代码

let nib = UINib(NibName: "FoodTableViewCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "FoodTableViewCell")

在代码过程中反复使用了字符串,这样很容易导致字符串的拼写错误,并且若字符串过长,造成不便。

改进方式

protocol ReusableView: Class {}
extension ReusableView where Self: UIView {
    static var reuseIdentifier: String {
        return String(self)
    }
}
protocol NibLoadableView: class {}
extension NibLoadableView where Self: UIView {
    stativ var NibName: String {
        return String(self)
    }
}

extension UITableView {
    func register<T: UITableViewCell>(_: T.Type) where T: ReusableView, T: NibLoadableView {
        let nib = UINib(nibName: T.nibName, bundle: nil)
        register(nib, forCellReuseIdentifier: T.reuseIdentifier)
    }
    
    func dequeueReusableCell<T: UITableViewCell>(forIndexPath indexPath: IndexPath) -> T where T: ReusableView {
        guard let cell = dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
            fatalError("Could not dequeue cell with identifier: \(T.reuseIdentifier)")
        }
        return cell
    }
}

最后,在viewController进行使用时,只需要

tableView.register(FoodTableViewCell.self)
let cell = tableView.dequeueReusableCell(forIndexPath: indexPath) as FoodTableViewCell 

例子3 用于测试

protocol Gettable {
associatetype T
func get(completionHandler: Result<T> -> Void)
struct FoodService: Gettable {
 func get(completionHandler: Result<[Food]> -> Void]){
    }
}

相关文章

网友评论

      本文标题:IOS In Swift Tips 1 协议使用小技巧

      本文链接:https://www.haomeiwen.com/subject/kdiqvttx.html