如何减少Swift中的代码冗余?

时间:2016-09-06 23:21:58

标签: ios swift

我在Swift中编写一个应用程序,它涉及通过迭代数据库查询后附加的数组中的信息来填充表。我在tableView.reloadData()方法中有查询,追加和viewDidLoad()全部。它工作正常。我也有几乎完全相同的代码写入刷新功能,响应屏幕上的拉动。它也很好用。然而,问题在于它非常繁忙。有很多代码写了两次,我想知道解决这个问题的最佳方法是什么。以下是相关代码:

viewDidLoad()中的

override func viewDidLoad() {
        super.viewDidLoad(){
//run query, append arrays
self.tableView.reloadData()
}refreshControl = UIRefreshControl()
        refreshControl!.attributedTitle = NSAttributedString(string: "Pull to refresh")
        refreshControl!.addTarget(self, action: #selector(DisplayEventsTVC.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
}

刷新功能:

    func refresh(sender: AnyObject){{
    //exact same query and appending
}
    self.tableView.reloadData()
    self.refreshControl?.endRefreshing()
    }

查询和追加很长,所以我想要一个更好的方法来处理它,而不是简单地将代码从viewdidload()复制并粘贴到刷新函数中并添加.endRefreshing()。最好/最有效的方法是什么?

这都是在tableviewcontroller中完成的。

2 个答案:

答案 0 :(得分:2)

以协议为导向:

class ViewController: UIViewController, Refreshable {
    var refreshTitle: String = "Pull to refresh"
    override func viewDidLoad() {
        super.viewDidLoad()
        queryAndAppend(completion: {
             self.tableView.reloadData()
        })
        self.setupRefresh()//I don't want to name it
    }
}

//Somewhere else 
protocol Refreshable {
  var refreshTitle: String {get}
  var tableView: UITableView 
  var refreshControl: UIRefreshControl
}

extension Refreshable where Self: UIViewController {
func setupRefresh(){
refreshControl = UIRefreshControl()
    refreshControl!.attributedTitle = NSAttributedString(string: "Pull to refresh")
    refreshControl!.addTarget(self, action: #selector(DisplayEventsTVC.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
}

//copying from @Michael ans
func refresh(sender: AnyObject) {
    queryAndAppend(completion: {
        self.tableView.reloadData()
        self.refreshControl?.endRefreshing()
    })
}

func queryAndAppend(completion completion: (() -> Void)?) {
    // your existing code goes here
    if let completion = completion {
        completion()
    }
}

}

只是草稿片段,未经过测试

答案 1 :(得分:1)

正如我的评论中所讨论的,将公共代码拉出到具有完成处理程序的单独func中。我正在思考...... ...

override func viewDidLoad() {
    super.viewDidLoad()
    queryAndAppend(completion: {
        self.tableView.reloadData()
    })
    refreshControl = UIRefreshControl()
    refreshControl!.attributedTitle = NSAttributedString(string: "Pull to refresh")
    refreshControl!.addTarget(self, action: #selector(DisplayEventsTVC.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
}

func refresh(sender: AnyObject) {
    queryAndAppend(completion: {
        self.tableView.reloadData()
        self.refreshControl?.endRefreshing()
    })
}

func queryAndAppend(completion completion: (() -> Void)?) {
    // your existing code goes here
    if let completion = completion {
        completion()
    }
}