Skip to content

Instantly share code, notes, and snippets.

@andreamazz
Created March 26, 2018 07:20
Show Gist options
  • Save andreamazz/965c90bc7e95fb48242d95c377ffa562 to your computer and use it in GitHub Desktop.
Save andreamazz/965c90bc7e95fb48242d95c377ffa562 to your computer and use it in GitHub Desktop.
A series of extensions for future me.
import UIKit
import RxSwift
import Moya
import ObjectMapper
extension UIView {
func loadNib<T: UIView>() -> T {
guard let view = Bundle.main.loadNibNamed(String(describing: T.self), owner: self, options: [:])?.first as? T else {
fatalError("Could not init NIB named: \(String(describing: T.self))")
}
return view
}
}
extension UITableView {
func dequeueReusableCell<T: UITableViewCell>(forIndexPath indexPath: IndexPath) -> T {
guard let cell = dequeueReusableCell(withIdentifier: String(describing: T.self), for: indexPath) as? T else {
fatalError("Could not dequeue cell with identifier: \(String(describing: T.self))")
}
return cell
}
}
extension UICollectionView {
func dequeueReusableCell<T: UICollectionViewCell>(forIndexPath indexPath: IndexPath) -> T {
guard let cell = dequeueReusableCell(withReuseIdentifier: String(describing: T.self), for: indexPath) as? T else{
fatalError("Could not dequeue cell with identifier: \(String(describing: T.self))")
}
return cell
}
}
protocol StoryboardIdentifiable {
static var storyboardIdentifier: String { get }
}
extension StoryboardIdentifiable where Self: UIViewController {
static var storyboardIdentifier: String {
return String(describing: self)
}
}
extension UIViewController : StoryboardIdentifiable { }
extension ObservableType where E == Response {
func mapNestedArray<T: Mappable>(type: T.Type, in key: String) -> Observable<[T]> {
return map { response -> Response in
guard let json = try? response.mapJSON() as? NSDictionary,
let data = json?[key],
let newData = try? JSONSerialization.data(withJSONObject: data, options: JSONSerialization.WritingOptions.prettyPrinted) else {
return response
}
let newResponse = Response(statusCode: response.statusCode, data: newData, response: response.response)
return newResponse
}
.mapArray(type)
}
}
extension PrimitiveSequence where E == Response {
func mapNestedArray<T: Mappable>(type: T.Type, in key: String) -> Observable<[T]> {
return asObservable().map { response -> Response in
guard let json = try? response.mapJSON() as? NSDictionary,
let data = json?[key],
let newData = try? JSONSerialization.data(withJSONObject: data, options: JSONSerialization.WritingOptions.prettyPrinted) else {
return response
}
let newResponse = Response(statusCode: response.statusCode, data: newData, response: response.response)
return newResponse
}
.mapArray(type)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment