Created
July 27, 2017 15:42
-
-
Save glennposadas/7a5125a0caf5c5a0151d89f7697a28c6 to your computer and use it in GitHub Desktop.
A playground file that contains an example of making a protocol datasource in Swift.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import UIKit | |
// DATA SOURCE EXAMPLE: | |
/** This MyViewDataSource protocol is just like the UITableViewDataSource | |
*/ | |
protocol MyViewDataSource { | |
func increment(count: Int) -> Int | |
} | |
/** MyView is like the UITableView | |
*/ | |
class MyView { | |
var count = 0 | |
var dataSource: MyViewDataSource! | |
func reloadData() { | |
if let amount = dataSource?.increment(count: count) { | |
count += amount | |
print("COUNT: \(count)") | |
} | |
} | |
} | |
/** MainClass is your UIViewController | |
*/ | |
class MainClass { | |
let myView = MyView() | |
func load() { | |
self.myView.dataSource = self | |
self.myView.reloadData() | |
} | |
} | |
/** Just an extension of MainClass (your controller) conforming to the dataSource. | |
*/ | |
extension MainClass: MyViewDataSource { | |
/** Conform to the MyViewDataSource. | |
* This function is just like the CellForRow of the UITableViewDataSource | |
*/ | |
func increment(count: Int) -> Int { | |
return 5 | |
} | |
} | |
/** Now to execute this example, make a new instance of MainClass or your Controller and execute the load(). | |
* The load() function is just like your controller's viewDidLoad function. | |
*/ | |
let mainClass = MainClass() | |
mainClass.load() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment