Skip to content

Instantly share code, notes, and snippets.

@pedantix
Created October 9, 2016 16:51
Show Gist options
  • Save pedantix/0c6887de49bd5f656b0d4c0c349c7bd9 to your computer and use it in GitHub Desktop.
Save pedantix/0c6887de49bd5f656b0d4c0c349c7bd9 to your computer and use it in GitHub Desktop.
// copy and paste into play ground
import UIKit
protocol ListViewModel {
associatedtype T:Comparable
var items: [T] { get set }
mutating func clear()
func item(forIndex index: NSIndexPath) -> T
func indexOfItem(forId id: Int) -> Int?
}
// implementation of concrete helpers
extension ListViewModel {
var countOfContents: Int {
return items.count
}
var hasContent: Bool {
return countOfContents > 0
}
//sometimes count of contents is different
var numberOfRows:Int {
return countOfContents
}
}
// An example of a concrete Struct implementation
struct AViewModel : ListViewModel {
typealias T = Int
var items = Array(1..<5)
var countOfContents: Int {
return items.count
}
mutating func clear() {
items.removeAll()
}
func item(forIndex index: NSIndexPath) -> Int {
return items[index.row]
}
func indexOfItem(forId id: Int) -> Int? {
// does not apply to this list
return .none
}
}
// An example of a concrete Class implementation
class AViewModelClass : ListViewModel {
var hasContent: Bool {
return true
}
typealias T = Int
var items = Array(1..<5)
var countOfContents: Int {
return items.count
}
func clear() {
items.removeAll()
}
func item(forIndex index: NSIndexPath) -> Int {
return items[index.row]
}
func indexOfItem(forId id: Int) -> Int? {
// does not apply to this list
return .none
}
}
var strct = AViewModel()
print("Struct View model begins with having contents \(strct.hasContent)")
strct.clear()
print("Struct View model after clear has contents \(strct.hasContent)")
var clazz = AViewModelClass()
print("Class View model begins with having contents \(clazz.hasContent)")
clazz.clear()
print("Class View model after clear has contents \(clazz.hasContent)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment