swift中extension的应用
http://blog.ios-developers.io/view-controller-extensions/ Say you are trying to make an iOS app that uses a // ViewController.swift class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Extra view initializations go here... } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // DataSource func numberOfSectionsInTableView(tableview: UITableView) -> Int { return 1 } func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int { return Data.dataStore.count } func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell",forIndexPath: indexPath) let row = indexPath.row cell.textLabel?.text = Data.dataStore[row] return cell } // Delegate func tableView(tableView: UITableView,didSelectRowAtIndexPath indexPath: NSIndexPath) { let row = indexPath.row print(Data.dataStore[row]) } } Phew,there's a lot of code cluttering up the view controller,and it's really just there to conform to the protocols! Of course you can always just use some Welcome to the Extension ZoneExtensions allow you to extend the functionality of a class,structure,enumeration,or protocol type. Say you wanted to add a custom method to the NSString class. Extensions let you do that. Or maybe you want to separate out some code,say in a view controller,into a different file. Extensions let you do that! Just take the code from before and bring it out into it's own file. This is demonstrated as follows. ViewController.swiftclass ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Extra view initializations go here... } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } ViewController+DataSource.swiftextension ViewController: UITableViewDataSource { func numberOfSectionsInTableView(tableview: UITableView) -> Int { return 1 } func tableView(tableView: UITableView,forIndexPath: indexPath) let row = indexPath.row cell.textLabel?.text = Data.dataStore[row] return cell } } ViewController+Delegate.swiftextension ViewController: UITableViewDelegate { func tableView(tableView: UITableView,sans-serif; font-size:18px; letter-spacing:0.12px; line-height:31.5px"> Voilà. Now all of the code related to the DataSource and Delegate protocols are contained within their own files. These methods are isolated from the rest of your view controller,yet they still provide the essential capabilities to your program. Just look at how clean that view controller is now! |