Skip to content

Instantly share code, notes, and snippets.

@sergdort
sergdort / SwiftHeap
Last active August 29, 2015 14:16
Simple Swift Heap data structure
//
// SwiftHeap.swift
// SimpleAlgos
//
// Created by Sergey Shulga on 3/18/15.
// Copyright (c) 2015 Sergey Shulga. All rights reserved.
//
import Foundation
public class SwiftImport<Element:NSManagedObject> {
public class func importObject(context:NSManagedObjectContext)
-> (dict:JSONDictionary) throws -> Element {
// TODO
}
}
// Which will look like this in caller
public typealias JSON = AnyObject
public typealias JSONDictionary = Dictionary<String, JSON>
public typealias JSONArray = Array<JSON>
public func JSONObjectWithData(data: NSData) -> AnyObject? {
do { return try NSJSONSerialization.JSONObjectWithData(data, options: []) }
catch { return .None }
}
public func JSONString(object: JSON) -> String? {
let data:NSData = ...
let context:NSManagedObjectContext
do {
let user:User? = try SwiftImport<User>.importObject
<^> context
<*> JSONObject -<< JSONObjectWithData -<< data
} catch {
//handle error
}
extension SwiftImport {
public class func importObjects(context:NSManagedObjectContext) -> (array:[JSONDictionary]) throws -> [Element] {
return { array in
return try array.map(importObject(context))
}
}
}
public protocol JSONToEntityMapable {
static var map:[String:String] {get} //[entityKey : jsonKey]
static var relatedByAttribute:String {get} // entityKey which defines the uniqueness of object
static var relatedJsonKey:String {get} // jsonKey which defines the uniqueness of object
}
extension JSONToEntityMapable {
static var map:[String:String] {
return [:]
extension User {
@NSManaged var lastName: String?
@NSManaged var name: String?
@NSManaged var userId: NSNumber?
@NSManaged var createdEvents: NSSet?
@NSManaged var homeCity: City?
}
protocol BindableView {
typealias V
var rx_viewModel: AnyObserver<V> {get}
}
class RxTableViewCell<ViewModelType>: UITableViewCell, BindableView {
typealias V = ViewModelType
let onPrepareForReuse:Observable<Void> = PublishSubject()
var rx_viewModel: AnyObserver<V> {
return AnyObserver { event in
// This is base class implementation
}
}
}
// One way binding operators
func <~ <T>(property: AnyObserver<T>, variable: Variable<T>) -> Disposable {
return variable
.bindTo(property)
}
func ~> <T>(variable: Variable<T>, property: AnyObserver<T>) -> Disposable {
return variable
.bindTo(property)