Skip to content

Instantly share code, notes, and snippets.

@valeriomazzeo
Last active August 10, 2016 14:07
Show Gist options
  • Save valeriomazzeo/ac0c270134ff24353f74e197cf7fc0f4 to your computer and use it in GitHub Desktop.
Save valeriomazzeo/ac0c270134ff24353f74e197cf7fc0f4 to your computer and use it in GitHub Desktop.
Easy way to populate UIView properties with data.
//
// ViewAdapter.swift
//
// Created by Valerio Mazzeo on 10/08/2016.
// Copyright © 2016 Valerio Mazzeo. All rights reserved.
//
import UIKit
/**
Types adopting the `ViewAdapter` protocol provides a way to feed data from a `Model` to a `View`.
This is particularly useful for `UITableViewCell` and `UICollectionViewCell` cells which have to be populated by a data source.
Adapter as struct:
```
struct MyCellStoreAdapter: ViewAdapter {
func configure(view: MyCell, with element: Store) -> Void {
view.textLabel?.text = element.name
}
}
```
Adapter as nested struct in the cell
```
extension MyCell {
public struct StoreAdapter: ViewAdapter {
public func configure(view: MyCell, with element: Store) -> Void {
view.textLabel?.text = element.name
}
}
}
```
Adapter as computed cell static property using `AnyViewAdapter`
```
extension MyCell {
public static var storeAdapter: AnyViewAdapter<MyCell, Store> {
return AnyViewAdapter { view, element in
view.textLabel?.text = element.name
}
}
}
```
Adapter as nested computed cell static property using `AnyViewAdapter`
```
extension MyCell {
public struct Adapter {
public static var store: AnyViewAdapter<MyCell, Store> {
return AnyViewAdapter { view, element in
view.textLabel?.text = element.name
}
}
}
}
```
*/
public protocol ViewAdapter {
associatedtype ViewType: UIView
associatedtype Model
func configure(view: ViewType, with element: Model) -> Void
}
public struct AnyViewAdapter<V: UIView, M>: ViewAdapter {
public typealias ViewType = V
public typealias Model = M
private let body: (view: ViewType, element: Model) -> Void
/**
Creates a `ViewAdapter` instance whose `configure` method invokes
`body`.
*/
public init(body: (view: ViewType, element: Model) -> Void) {
self.body = body
}
public func configure(view: ViewType, with element: Model) -> Void {
self.body(view: view, element: element)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment