working on it ...

Filters

snippets
13k
followers
45
Published by marksimon232

Swift

Swift is a programming language designed by Apple for creating iOS and OS X apps. Swift builds upon the foundation of C and Objective-C, but without the constraints of the C programming language.
Sort by

Found 13k snippets

    public by Santiago modified Aug 14, 2017  100  1  2  0

    CoreLocatonManager + Rx

    Reactive extension for Core Location manager
    class RxCLLocationManagerDelegateProxy: DelegateProxy, CLLocationManagerDelegate, DelegateProxyType {
      class func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject) {
        let locationManager: CLLocationManager = object as! CLLocationManager
        locationManager.delegate = delegate as? CLLocationManagerDelegate
      }
      class func currentDelegateFor(_ object: AnyObject) -> AnyObject? {
        let locationManager: CLLocationManager = object as! CLLocationManager
        return locationManager.delegate
      }
    }
    
    extension Reactive where Base: CLLocationManager {
      var delegate: DelegateProxy {
        return RxCLLocationManagerDelegateProxy.proxyForObject(base)
      }
    
      var didUpdateLocations: Observable<[CLLocation]> {
        return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didUpdateLocations:)))
          .map { parameters in
            return parameters[1] as! [CLLocation]
          }
      }
    }
    

    public by Santiago modified Aug 14, 2017  73  0  2  0

    MKMapView + Rx

    Reactive extension for map view
    class RxMKMapViewDelegateProxy: DelegateProxy, MKMapViewDelegate, DelegateProxyType {
      class func currentDelegateFor(_ object: AnyObject) -> AnyObject? {
        let mapView: MKMapView = (object as? MKMapView)!
        return mapView.delegate
      }
    
      class func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject) {
        let mapView: MKMapView = (object as? MKMapView)!
        mapView.delegate = delegate as? MKMapViewDelegate
      }
    }
    
    extension Reactive where Base: MKMapView {
      public var delegate: DelegateProxy {
        return RxMKMapViewDelegateProxy.proxyForObject(base)
      }
    
      public func setDelegate(_ delegate: MKMapViewDelegate) -> Disposable {
        return RxMKMapViewDelegateProxy.installForwardDelegate(
          delegate,
          retainDelegate: false,
          onProxyForObject: self.base
        )
      }
    
      var overlays: UIBindingObserver<Base, [MKOverlay]> {
        return UIBindingObserver(UIElement: self.base) { mapView, overlays in
          mapView.removeOverlays(mapView.overlays)
          mapView.addOverlays(overlays)
        }
      }
    
      public var regionDidChangeAnimated: ControlEvent<Bool> {
        let source = delegate
          .methodInvoked(#selector(MKMapViewDelegate.mapView(_:regionDidChangeAnimated:)))
          .map { parameters in
            return (parameters[1] as? Bool) ?? false
          }
        return ControlEvent(events: source)
      }
    }
    

    public by Santiago modified Aug 14, 2017  61  0  3  0

    BindableType protocol implementation

    protocol BindableType
    {
      associatedtype ViewModelType
    
      var viewModel: ViewModelType! { get set }
    
      func bindViewModel()
    }
    
    extension BindableType where Self: UIViewController 
    {
      mutating func bindViewModel(to model: Self.ViewModelType) {
        viewModel = model
        loadViewIfNeeded()
        bindViewModel()
      }
    }

    public by Santiago modified Aug 14, 2017  51  0  2  0

    UINavigationControllerDelegate + Rx

    Rx extension for navigation controller delegate
    class RxNavigationControllerDelegateProxy: DelegateProxy, DelegateProxyType, UINavigationControllerDelegate {
    
      static func currentDelegateFor(_ object: AnyObject) -> AnyObject? {
        guard let navigationController = object as? UINavigationController else {
          fatalError()
        }
        return navigationController.delegate
      }
    
      static func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject) {
        guard let navigationController = object as? UINavigationController else {
          fatalError()
        }
        if delegate == nil {
          navigationController.delegate = nil
        } else {
          guard let delegate = delegate as? UINavigationControllerDelegate else {
            fatalError()
          }
          navigationController.delegate = delegate
        }
      }
    }
    
    extension Reactive where Base: UINavigationController {
      /**
         Reactive wrapper for `delegate`.
         For more information take a look at `DelegateProxyType` protocol documentation.
         */
      public var delegate: DelegateProxy {
        return RxNavigationControllerDelegateProxy.proxyForObject(base)
      }
    }

    public by Santiago modified Aug 14, 2017  43  0  3  0

    SceneCoordinatorType protocol

    protocol SceneCoordinatorType 
    {
      init(window: UIWindow)
    
      /// transition to another scene
      @discardableResult
      func transition(to scene: Scene, type: SceneTransitionType) -> Observable<Void>
    
      /// pop scene from navigation stack or dismiss current modal
      @discardableResult
      func pop(animated: Bool) -> Observable<Void>
    }
    
    extension SceneCoordinatorType {
      @discardableResult
      func pop() -> Observable<Void> {
        return pop(animated: true)
      }
    }
    
    enum Scene {
      case tasks(TasksViewModel)
      case editTask(EditTaskViewModel)
    }
    
    enum SceneTransitionType {
      // you can extend this to add animated transition types,
      // interactive transitions and even child view controllers!
    
      case root       // make view controller the root view controller
      case push       // push view controller to navigation stack
      case modal      // present view controller modally
    }
    
    extension Scene {
      func viewController() -> UIViewController {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        switch self {
        case .tasks(let viewModel):
          let nc = storyboard.instantiateViewController(withIdentifier: "Tasks") as! UINavigationController
          var vc = nc.viewControllers.first as! TasksViewController
          vc.bindViewModel(to: viewModel)
          return nc
    
        case .editTask(let viewModel):
          let nc = storyboard.instantiateViewController(withIdentifier: "EditTask") as! UINavigationController
          var vc = nc.viewControllers.first as! EditTaskViewController
          vc.bindViewModel(to: viewModel)
          return nc
        }
      }
    }
    
    						

    public by Santiago modified Aug 14, 2017  32  0  3  0

    SceneCoordinator class implementation

    Initial descriptions
    class SceneCoordinator: SceneCoordinatorType {
    
      fileprivate var window: UIWindow
      fileprivate var currentViewController: UIViewController
    
      required init(window: UIWindow) {
        self.window = window
        currentViewController = window.rootViewController!
      }
    
      static func actualViewController(for viewController: UIViewController) -> UIViewController {
        if let navigationController = viewController as? UINavigationController {
          return navigationController.viewControllers.first!
        } else {
          return viewController
        }
      }
    
      @discardableResult
      func transition(to scene: Scene, type: SceneTransitionType) -> Observable<Void> {
        let subject = PublishSubject<Void>()
        let viewController = scene.viewController()
        switch type
        {
          case .root:
            currentViewController = SceneCoordinator.actualViewController(for: viewController)
            window.rootViewController = viewController
            subject.onCompleted()
    
          case .push:
            guard let navigationController = currentViewController.navigationController else {
              fatalError("Can't push a view controller without a current navigation controller")
            }
            // one-off subscription to be notified when push complete
            _ = navigationController.rx.delegate
              .sentMessage(#selector(UINavigationControllerDelegate.navigationController(_:didShow:animated:)))
              .map { _ in }
              .bind(to: subject)
            navigationController.pushViewController(viewController, animated: true)
            currentViewController = SceneCoordinator.actualViewController(for: viewController)
    
          case .modal:
            currentViewController.present(viewController, animated: true) {
              subject.onCompleted()
            }
            currentViewController = SceneCoordinator.actualViewController(for: viewController)
        }
        return subject.asObservable()
          .take(1)
          .ignoreElements()
      }
    
      @discardableResult
      func pop(animated: Bool) -> Observable<Void> {
        let subject = PublishSubject<Void>()
        if let presenter = currentViewController.presentingViewController {
          // dismiss a modal controller
          currentViewController.dismiss(animated: animated) {
            self.currentViewController = SceneCoordinator.actualViewController(for: presenter)
            subject.onCompleted()
          }
        } else if let navigationController = currentViewController.navigationController {
          // navigate up the stack
          // one-off subscription to be notified when pop complete
          _ = navigationController.rx.delegate
            .sentMessage(#selector(UINavigationControllerDelegate.navigationController(_:didShow:animated:)))
            .map { _ in }
            .bind(to: subject)
          guard navigationController.popViewController(animated: animated) != nil else {
            fatalError("can't navigate back from \(currentViewController)")
          }
          currentViewController = SceneCoordinator.actualViewController(for: navigationController.viewControllers.last!)
        } else {
          fatalError("Not a modal, no navigation controller: can't navigate back from \(currentViewController)")
        }
        return subject.asObservable().take(1).ignoreElements()
      }
    }
    

    public by marksimon232 modified Jul 6, 2015  3186  2  6  0

    Swift: .max and .min properties

    If you have code around that uses lots of F’s (e.g. 0xFFFFFFFF) or capital letters (e.g. UINT32_MAX), consider replacing these constants with built-in Swift versions.
    Swift offers .max and .min properties for many numeric types. For example:
    
    public func Random01() -> Double {
        return Double(arc4random()) / Double(UInt32.max)
    }

    public by marksimon232 modified Jul 6, 2015  3312  0  6  0

    Swift2: DebugPrint differentiation

    Find items that printed differently in debugPrint than they did in print.
    import Cocoa
    
    // Items to check
    //let x = "Snoop"
    //let x = 1...5
    let x = UnicodeScalar(0x1f601)
    
    // Build test cases
    var a = ""; print(x, &a, appendNewline:false); print(a)
    var b = ""; debugPrint(x, &b, appendNewline:false); print(b)
    
    // Compare and alert
    func ExitAfter(t: Double, _ status: Int32) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 
            numericCast(UInt64(t * Double(NSEC_PER_SEC)))), 
            dispatch_get_global_queue(
                DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), 
            {exit(status)})
    }
    
    if a != b {
        // Success
        print("YES!")
        NSSound(named: "Sosumi")?.play()
        ExitAfter(0.5, 0)
        CFRunLoopRun() // stick around to produce sound
    } else {print("No")}

    public by marksimon232 modified Jul 6, 2015  4239  1  6  1

    Swift 2: Creating the date Formatter

    internal func BuildSimpleTimeFormatter() -> NSDateFormatter {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("mm:ss:SSS", options: 0, locale: NSLocale.currentLocale())
        return dateFormatter
    }
    
    internal let dateFormatter = BuildSimpleTimeFormatter()
    
    public func SWLog(format: String, _ args: CVarArgType...) {
        #if DEBUG
            let timeString = dateFormatter.stringFromDate(NSDate())
            print("\(timeString): " + String(format: format, arguments: args), &errStream)
        #endif
    }

    public by marksimon232 modified Jul 6, 2015  2731  0  7  1

    Swift: Revisiting printing with string formats

    You pass NSLog a format string followed by a variadic list of Objective-C-compatible parameters. 
    The parameters map to specifiers embedded within the format string.
    
    NSLog("Dictionary: %@, Double: %0.2f", ["Hello":3], 2.7)            
    • Public Snippets
    • Channels Snippets