//
//  AppDelegate.swift
//  Habits
//
//  Created by Julian Grosshauser on 26/09/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow? = {
        let window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window.backgroundColor = .whiteColor()
        return window
    }()

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        let navigationController = UINavigationController(rootViewController: HabitsController(viewModel: HabitsViewModel()))

        window?.rootViewController = navigationController
        window?.makeKeyAndVisible()

        return true
    }
}

Update initialization of root view controller

//
//  AppDelegate.swift
//  Habits
//
//  Created by Julian Grosshauser on 26/09/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow? = {
        let window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window.backgroundColor = .whiteColor()
        return window
    }()

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        let habitsViewModel = HabitsViewModel()
        let habitsDataSource = HabitsDataSource(viewModel: habitsViewModel)
        let habitsController = HabitsController(viewModel: habitsViewModel, dataSource: habitsDataSource)
        let navigationController = UINavigationController(rootViewController: habitsController)

        window?.rootViewController = navigationController
        window?.makeKeyAndVisible()

        return true
    }
}


import Foundation

public func haveCount<T: Equatable>(expectedValue: Int) -> MatcherFunc<[T]> {
    return MatcherFunc { actualExpression, failureMessage in
        if let actualValue = try actualExpression.evaluate() {
            failureMessage.postfixMessage = "have \(actualValue) with count \(actualValue.count)"
            let result = expectedValue == actualValue.count
            failureMessage.actualValue = "\(expectedValue)"
            return result
        } else {
            return false
        }
    }
}

extension NMBObjCMatcher {
    public class func haveCountMatcher(expected: NSNumber) -> NMBObjCMatcher {
        return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
            let expr = actualExpression.cast({ $0 as? [NSObject] })
            return try! haveCount(expected.integerValue).matches(expr, failureMessage: failureMessage)
        }
    }
}

Add comment to haveCount matcher

import Foundation

/// A Nimble matcher that succeeds when the actual array's count equals
/// the expected value
public func haveCount<T: Equatable>(expectedValue: Int) -> MatcherFunc<[T]> {
    return MatcherFunc { actualExpression, failureMessage in
        if let actualValue = try actualExpression.evaluate() {
            failureMessage.postfixMessage = "have \(actualValue) with count \(actualValue.count)"
            let result = expectedValue == actualValue.count
            failureMessage.actualValue = "\(expectedValue)"
            return result
        } else {
            return false
        }
    }
}

extension NMBObjCMatcher {
    public class func haveCountMatcher(expected: NSNumber) -> NMBObjCMatcher {
        return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
            let expr = actualExpression.cast({ $0 as? [NSObject] })
            return try! haveCount(expected.integerValue).matches(expr, failureMessage: failureMessage)
        }
    }
}


import XCTest
@testable import gattaca

class TMSessionLoader:XCTestCase
{
    private let kWaitExpectation:TimeInterval = 3

    func testCreate()
    {
        let currentBundle:Bundle = Bundle(for:TDManager.self)
        let sessionExpectation:XCTestExpectation = expectation(
            description:"session created")

        guard

            let manager:DManager = DManager(bundle:currentBundle)

        else
        {
            return
        }

        XCTAssertNotNil(
            manager,
            "failed creating manager")

        let session:MSession = MSession()
        session.create(manager:manager)
        { (session:DSession) in

            sessionExpectation.fulfill()
        }

        waitForExpectations(timeout:kWaitExpectation)
        { (error:Error?) in

            let hasChanges:Bool = manager.managedObjectContext.hasChanges

            XCTAssertFalse(
                hasChanges,
                "failed to save changes")
        }
    }
}

Add test for session load

import XCTest
@testable import gattaca

class TMSessionLoader:XCTestCase
{
    private let kWaitExpectation:TimeInterval = 3

    func testCreate()
    {
        let currentBundle:Bundle = Bundle(for:TDManager.self)
        let sessionExpectation:XCTestExpectation = expectation(
            description:"session created")

        guard

            let manager:DManager = DManager(bundle:currentBundle)

        else
        {
            return
        }

        XCTAssertNotNil(
            manager,
            "failed creating manager")

        let session:MSession = MSession()
        session.create(manager:manager)
        { (session:DSession) in

            sessionExpectation.fulfill()
        }

        waitForExpectations(timeout:kWaitExpectation)
        { (error:Error?) in

            let hasChanges:Bool = manager.managedObjectContext.hasChanges

            XCTAssertFalse(
                hasChanges,
                "failed to save changes")
        }
    }

    func testLoad()
    {
        let currentBundle:Bundle = Bundle(for:TDManager.self)
        let sessionExpectation:XCTestExpectation = expectation(
            description:"session loaded")

        guard

            let manager:DManager = DManager(bundle:currentBundle)

        else
        {
            return
        }

        XCTAssertNotNil(
            manager,
            "failed creating manager")

        let session:MSession = MSession()
        session.load(manager:manager)
        { (session:DSession) in

            sessionExpectation.fulfill()
        }

        waitForExpectations(timeout:kWaitExpectation)
        { (error:Error?) in
        }
    }
}


//
//  Sequence+Extension.swift
//  SwiftUtilities
//
//  Created by Rodrigo Ruiz on 4/25/17.
//  Copyright © 2017 Rodrigo Ruiz. All rights reserved.
//

extension Sequence {

    public func reduce(_ combine: (Self.Iterator.Element, Self.Iterator.Element) -> Self.Iterator.Element) -> Self.Iterator.Element {
        let initial: Self.Iterator.Element? = nil
        return reduce(initial, { (result, element) in
            guard let result = result else { return element }

            return combine(result, element)
        })!
    }

    public func take(_ numberOfElements: Int) -> Self.SubSequence {
        return prefix(numberOfElements)
    }

}

public func take<S: Sequence>(_ numberOfElements: Int) -> (S) -> S.SubSequence {
    return { $0.take(numberOfElements) }
}

public func map<S: Sequence, E>(_ transform: @escaping (S.Element) -> E) -> (S) -> [E] {
    return { $0.map(transform) }
}

Add 'filter' function to Sequence.

//
//  Sequence+Extension.swift
//  SwiftUtilities
//
//  Created by Rodrigo Ruiz on 4/25/17.
//  Copyright © 2017 Rodrigo Ruiz. All rights reserved.
//

extension Sequence {

    public func reduce(_ combine: (Self.Iterator.Element, Self.Iterator.Element) -> Self.Iterator.Element) -> Self.Iterator.Element {
        let initial: Self.Iterator.Element? = nil
        return reduce(initial, { (result, element) in
            guard let result = result else { return element }

            return combine(result, element)
        })!
    }

    public func take(_ numberOfElements: Int) -> Self.SubSequence {
        return prefix(numberOfElements)
    }

}

public func take<S: Sequence>(_ numberOfElements: Int) -> (S) -> S.SubSequence {
    return { $0.take(numberOfElements) }
}

public func map<S: Sequence, E>(_ transform: @escaping (S.Element) -> E) -> (S) -> [E] {
    return { $0.map(transform) }
}

public func filter<S: Sequence>(_ isIncluded: @escaping (S.Element) -> Bool) -> (S) -> [S.Element] {
    return { $0.filter(isIncluded) }
}


//
//  AppDelegate.swift
//  xkcd
//
//  Created by Paul Rehkugler on 1/24/16.
//
//

import UIKit

/// This class acts as the UIApplicationDelegate of the application.
final class AppDelegate: NSObject, UIApplicationDelegate {

    // MARK: - UIApplicationDelegate

    var window: UIWindow?

	func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]?) -> Bool {

		let listViewController = ComicListViewController(style: .plain)

        if let launchURL = launchOptions?[.url] as? NSURL {
            guard launchURL.scheme == "xkcd" else {
                return false
            }

            if
                let host = launchURL.host,
                let launchedComicNumber = Int(host),
                 launchedComicNumber > 0
            {
                listViewController.requestedLaunchComic = launchedComicNumber
            }
        }

        let navigationController = TLNavigationController(rootViewController: listViewController)

		window = UIWindow(frame: UIScreen.main.bounds)

        window?.rootViewController = navigationController
        window?.makeKeyAndVisible()

        return true
    }

	func applicationDidBecomeActive(_ application: UIApplication) {
        Comic.synchronizeDownloadedImages()
    }
}

Fix bug where download icons will always be shown on app launch

//
//  AppDelegate.swift
//  xkcd
//
//  Created by Paul Rehkugler on 1/24/16.
//
//

import UIKit

/// This class acts as the UIApplicationDelegate of the application.
final class AppDelegate: NSObject, UIApplicationDelegate {

    // MARK: - UIApplicationDelegate

    var window: UIWindow?

	func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]?) -> Bool {
		Comic.synchronizeDownloadedImages()

		let listViewController = ComicListViewController(style: .plain)

        if let launchURL = launchOptions?[.url] as? NSURL {
            guard launchURL.scheme == "xkcd" else {
                return false
            }

            if
                let host = launchURL.host,
                let launchedComicNumber = Int(host),
                 launchedComicNumber > 0
            {
                listViewController.requestedLaunchComic = launchedComicNumber
            }
        }

        let navigationController = TLNavigationController(rootViewController: listViewController)

		window = UIWindow(frame: UIScreen.main.bounds)

        window?.rootViewController = navigationController
        window?.makeKeyAndVisible()

        return true
    }

	func applicationDidBecomeActive(_ application: UIApplication) {
        Comic.synchronizeDownloadedImages()
    }
}


//
//  GTProgressBar.swift
//  Pods
//
//  Created by Grzegorz Tatarzyn on 19/09/2016.
//
//

import UIKit

public class GTProgressBar: UIView {
    private let backgroundView = UIView()
    private let fillView = UIView()
    private let backgroundViewBorder: CGFloat = 2
    private let backgroundViewBorderColor: UIColor = UIColor.black
    private let backgroundViewBackgroundColor: UIColor = UIColor.white
    private let fillViewInset: CGFloat = 2
    private let fillViewBackgroundColor = UIColor.black

    public override init(frame: CGRect) {
        super.init(frame: frame)
        prepareSubviews()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        prepareSubviews()
    }

    private func prepareSubviews() {
        addSubview(backgroundView)
        addSubview(fillView)
    }

    public override func layoutSubviews() {
        backgroundView.frame = CGRect(origin: CGPoint.zero, size: frame.size)
        backgroundView.backgroundColor = backgroundViewBackgroundColor
        backgroundView.layer.borderWidth = backgroundViewBorder
        backgroundView.layer.borderColor = backgroundViewBorderColor.cgColor

        let offset = backgroundViewBorder + fillViewInset
        fillView.frame = backgroundView.frame.insetBy(dx: offset, dy: offset)
        fillView.backgroundColor = fillViewBackgroundColor
    }
}

Move setup of each of the child views to separate methods.

//
//  GTProgressBar.swift
//  Pods
//
//  Created by Grzegorz Tatarzyn on 19/09/2016.
//
//

import UIKit

public class GTProgressBar: UIView {
    private let backgroundView = UIView()
    private let fillView = UIView()
    private let backgroundViewBorder: CGFloat = 2
    private let backgroundViewBorderColor: UIColor = UIColor.black
    private let backgroundViewBackgroundColor: UIColor = UIColor.white
    private let fillViewInset: CGFloat = 2
    private let fillViewBackgroundColor = UIColor.black

    public override init(frame: CGRect) {
        super.init(frame: frame)
        prepareSubviews()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        prepareSubviews()
    }

    private func prepareSubviews() {
        addSubview(backgroundView)
        addSubview(fillView)
    }

    public override func layoutSubviews() {
        setupBackgroundView()
        setupFillView()
    }

    private func setupBackgroundView() {
        backgroundView.frame = CGRect(origin: CGPoint.zero, size: frame.size)
        backgroundView.backgroundColor = backgroundViewBackgroundColor
        backgroundView.layer.borderWidth = backgroundViewBorder
        backgroundView.layer.borderColor = backgroundViewBorderColor.cgColor
    }

    private func setupFillView() {
        let offset = backgroundViewBorder + fillViewInset
        fillView.frame = backgroundView.frame.insetBy(dx: offset, dy: offset)
        fillView.backgroundColor = fillViewBackgroundColor
    }
}


// Copyright (c) 2016 Stefan van den Oord. All rights reserved.

import Quick
import Nimble

class SecKey_KeychainTests: QuickSpec {
    override func spec() {
        it("can return the keychain tag of a key") {
            let keys = testKeyPair()
            expect(keys.privateKey.keychainTag) != ""
            expect(keys.publicKey.keychainTag) != ""
        }

        it("can retrieve a key by tag") {
            let keys = testKeyPair()
            let privTag = keys.privateKey.keychainTag
            let pubTag = keys.publicKey.keychainTag
            expect(privTag).toNot(beNil())
            expect(pubTag).toNot(beNil())
            if let privTag = privTag, let pubTag = pubTag {
                let retrievedPrivKey = SecKey.loadFromKeychain(tag: privTag)
                let retrievedPubKey = SecKey.loadFromKeychain(tag: pubTag)
                expect(retrievedPrivKey?.keyData) == keys.privateKey.keyData
                expect(retrievedPubKey?.keyData) == keys.publicKey.keyData
            }
        }
    }
}

Add missing import to test file.

// Copyright (c) 2016 Stefan van den Oord. All rights reserved.

import Quick
import Nimble
import SecurityExtensions

class SecKey_KeychainTests: QuickSpec {
    override func spec() {
        it("can return the keychain tag of a key") {
            let keys = testKeyPair()
            expect(keys.privateKey.keychainTag) != ""
            expect(keys.publicKey.keychainTag) != ""
        }

        it("can retrieve a key by tag") {
            let keys = testKeyPair()
            let privTag = keys.privateKey.keychainTag
            let pubTag = keys.publicKey.keychainTag
            expect(privTag).toNot(beNil())
            expect(pubTag).toNot(beNil())
            if let privTag = privTag, let pubTag = pubTag {
                let retrievedPrivKey = SecKey.loadFromKeychain(tag: privTag)
                let retrievedPubKey = SecKey.loadFromKeychain(tag: pubTag)
                expect(retrievedPrivKey?.keyData) == keys.privateKey.keyData
                expect(retrievedPubKey?.keyData) == keys.publicKey.keyData
            }
        }
    }
}


//  Copyright © 2016 Gavan Chan. All rights reserved.

import Foundation
import RxCocoa
import RxSwift

fileprivate let cities: Array<City> = [
  (7839805, "Melbourne"),
  (2147714, "Sydney"),
  (2063523, "Perth"),
  (2078025, "Adelaide"),
  (7839562, "Brisbane"),
  (2163355, "Hobart"),
  (7839402, "Darwin"),
].map(City.init)

final class WeatherClient {

  enum Metric {
    case celsius
    case fahrenheit
    case kelvin

    var requestParameter: String? {
      let value: String?
      switch self {
      case .celsius: value = "metric"
      case .fahrenheit: value = "imperial"
      case .kelvin: value = nil
      }
      return value.flatMap { "units=\($0)" }
    }
  }

  var metric: Metric = .celsius

  func weather(for cityID: City.Identifier) -> Observable<Weather> {
    return .empty()
  }

}

Implement base data fetching in weather client

//  Copyright © 2016 Gavan Chan. All rights reserved.

import Argo
import Foundation
import RxCocoa
import RxSwift

fileprivate let cities: Array<City> = [
  (7839805, "Melbourne"),
  (2147714, "Sydney"),
  (2063523, "Perth"),
  (2078025, "Adelaide"),
  (7839562, "Brisbane"),
  (2163355, "Hobart"),
  (7839402, "Darwin"),
].map(City.init)

final class WeatherClient: ClientProtocol {

  enum Metric {
    case celsius
    case fahrenheit
    case kelvin

    var requestParameter: String? {
      let value: String?
      switch self {
      case .celsius: value = "metric"
      case .fahrenheit: value = "imperial"
      case .kelvin: value = nil
      }
      return value.flatMap { "units=\($0)" }
    }
  }

  enum Endpoint: String {
    case weather = "weather"
  }

  let session: URLSession = .shared
  var base: URL { return URL(string: baseURL)! }

  private let baseURL: String = "http://api.openweathermap.org/data/2.5"

  var metric: Metric = .celsius

  func weather(for cityID: City.Identifier) -> Observable<Weather> {
    let query: Dictionary<String, String> = [
      "id": "7839805",
      "APPID": "402c2de16506bb59c7a6afc8b60778c2",
      "units": "metric",
    ]
    let weather: Observable<Weather> = json(for: .weather, via: .get, withQuery: query)
      .map(Weather.decode)
      .map { $0.value! }

    return weather
  }

}


//
//  Prephirencable.swift
//  PrephirencesiOS
//
//  Created by Eric Marchand on 19/03/2019.
//  Copyright © 2019 phimage. All rights reserved.
//

import Foundation

/// Protocol to create preferences from Struct hierarchy
/// by creating keypath using the Struct name.
protocol Prephirencable {
    static var key: String {get}
    static var parent: PreferencesType {get}
}

extension Prephirencable {
    static var key: String {
        return "\(self)".lowercasingFirst + UserDefaultsKeySeparator
    }
    static var parent: PreferencesType {
        return Prephirences.sharedInstance
    }
    static var instance: PreferencesType {
        return ProxyPreferences(preferences: parent, key: key)
    }
    static var mutableInstance: MutablePreferencesType? {
        guard let parent = parent as? MutablePreferencesType else {
            return nil
        }
        return MutableProxyPreferences(preferences: parent, key: key)
    }
}
extension String {

    fileprivate var lowercasingFirst: String {
        return prefix(1).lowercased() + dropFirst()
    }
}

Fix compilation without all module

//
//  Prephirencable.swift
//  PrephirencesiOS
//
//  Created by Eric Marchand on 19/03/2019.
//  Copyright © 2019 phimage. All rights reserved.
//

import Foundation

/// Protocol to create preferences from Struct hierarchy
/// by creating keypath using the Struct name.
protocol Prephirencable {
    static var key: String {get}
    static var parent: PreferencesType {get}
}

extension Prephirencable {
    static var key: String {
        return "\(self)".lowercasingFirst + "."
    }
    static var parent: PreferencesType {
        return Prephirences.sharedInstance
    }
    static var instance: PreferencesType {
        return ProxyPreferences(preferences: parent, key: key)
    }
    static var mutableInstance: MutablePreferencesType? {
        guard let parent = parent as? MutablePreferencesType else {
            return nil
        }
        return MutableProxyPreferences(preferences: parent, key: key)
    }
}
extension String {

    fileprivate var lowercasingFirst: String {
        return prefix(1).lowercased() + dropFirst()
    }
}


import UIKit
import Lightbox

class MainViewController: UIViewController {

  lazy var galleryButton: UIButton = { [unowned self] in
    let button = UIButton()
    button.setTitle("Show the gallery", forState: .Normal)
    button.setTitleColor(UIColor(red:0.98, green:0.18, blue:0.36, alpha:1), forState: .Normal)
    button.titleLabel!.font = UIFont(name: "AvenirNextCondensed-DemiBold", size: 24)
    button.addTarget(self, action: "galleryButtonDidPress:", forControlEvents: .TouchUpInside)
    button.frame = CGRectMake(0, 0,
      UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height)

    return button
    }()

  lazy var lightboxController: LightboxController = { [unowned self] in
    let controller = LightboxController(images: self.images)
    controller.dismissalDelegate = self

    return controller
    }()

  let images = ["photo1", "photo2", "photo3"]

  override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(galleryButton)
  }

  // MARK: Action handlers

  func galleryButtonDidPress(button: UIButton) {
    presentViewController(lightboxController, animated: true, completion: nil)
  }
}

// MARK: Lightbox delegate methods

extension MainViewController : LightboxControllerDismissalDelegate {

  func lightboxControllerDidDismiss(controller: LightboxController) {
    lightboxController.dismissViewControllerAnimated(true, completion: nil)
  }
}

Refactor Demo to observe leaks

import UIKit
import Lightbox

class MainViewController: UIViewController {

  lazy var galleryButton: UIButton = { [unowned self] in
    let button = UIButton()
    button.setTitle("Show the gallery", forState: .Normal)
    button.setTitleColor(UIColor(red:0.98, green:0.18, blue:0.36, alpha:1), forState: .Normal)
    button.titleLabel!.font = UIFont(name: "AvenirNextCondensed-DemiBold", size: 24)
    button.addTarget(self, action: "galleryButtonDidPress:", forControlEvents: .TouchUpInside)
    button.frame = CGRectMake(0, 0,
      UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height)

    return button
    }()

  override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(galleryButton)
  }

  // MARK: Action handlers

  func galleryButtonDidPress(button: UIButton) {
    let controller = LightboxController(images: ["photo1", "photo2", "photo3"])
    controller.dismissalDelegate = self
    presentViewController(controller, animated: true, completion: nil)
  }
}

// MARK: Lightbox delegate methods

extension MainViewController : LightboxControllerDismissalDelegate {

  func lightboxControllerDidDismiss(controller: LightboxController) {
    controller.dismissViewControllerAnimated(true, completion: nil)
  }
}


//
//  CKContainer+Extensions.swift
//  Account
//
//  Created by Maurice Parker on 4/4/20.
//  Copyright © 2020 Ranchero Software, LLC. All rights reserved.
//

import Foundation
import CloudKit

extension CKContainer {

	private static let userRecordIDKey = "cloudkit.server.userRecordID"

    var userRecordID: String? {
        get {
			return UserDefaults.standard.string(forKey: Self.userRecordIDKey)
        }
        set {
            guard let userRecordID = newValue else {
                UserDefaults.standard.removeObject(forKey: Self.userRecordIDKey)
                return
            }
            UserDefaults.standard.set(userRecordID, forKey: Self.userRecordIDKey)
        }
    }

	func fetchUserRecordID() {
		guard userRecordID == nil else { return }
		fetchUserRecordID { recordID, error in
			guard let recordID = recordID, error == nil else {
				return
			}
			self.userRecordID = recordID.recordName
		}
	}

}

Put update to UserDefaults on main thread.

//
//  CKContainer+Extensions.swift
//  Account
//
//  Created by Maurice Parker on 4/4/20.
//  Copyright © 2020 Ranchero Software, LLC. All rights reserved.
//

import Foundation
import CloudKit

extension CKContainer {

	private static let userRecordIDKey = "cloudkit.server.userRecordID"

    var userRecordID: String? {
        get {
			return UserDefaults.standard.string(forKey: Self.userRecordIDKey)
        }
        set {
            guard let userRecordID = newValue else {
                UserDefaults.standard.removeObject(forKey: Self.userRecordIDKey)
                return
            }
            UserDefaults.standard.set(userRecordID, forKey: Self.userRecordIDKey)
        }
    }

	func fetchUserRecordID() {
		guard userRecordID == nil else { return }
		fetchUserRecordID { recordID, error in
			guard let recordID = recordID, error == nil else {
				return
			}
			DispatchQueue.main.async {
				self.userRecordID = recordID.recordName
			}
		}
	}

}


import Foundation

struct MVitaPtpMessageOutSendResult:MVitaPtpMessageOutProtocol
{
    let data:Data

    init(
        event:MVitaPtpMessageInEvent,
        result:MVitaPtpResult)
    {
        let builder:MVitaPtpMessageOutBuilder = MVitaPtpMessageOutBuilder()
        builder.append(value:MVitaPtpType.command.rawValue)
        builder.append(value:MVitaPtpDataPhase.none.rawValue)
        builder.append(value:MVitaPtpCommand.sendResult.rawValue)
        builder.appendTransactionId()
        builder.append(value:event.eventId)
        builder.append(value:result.rawValue)

        data = builder.export()
    }
}

Update send result with parameters

import Foundation

struct MVitaPtpMessageOutSendResult:MVitaPtpMessageOutProtocol
{
    let data:Data

    init(
        event:MVitaPtpMessageInEvent,
        result:MVitaPtpResult,
        parameters:[UInt32])
    {
        let builder:MVitaPtpMessageOutBuilder = MVitaPtpMessageOutBuilder()
        builder.append(value:MVitaPtpType.command.rawValue)
        builder.append(value:MVitaPtpDataPhase.none.rawValue)
        builder.append(value:MVitaPtpCommand.sendResult.rawValue)
        builder.appendTransactionId()
        builder.append(value:event.eventId)
        builder.append(value:result.rawValue)

        for parameter:UInt32 in parameters
        {
            builder.append(value:parameter)
        }

        data = builder.export()
    }
}


//
// SwiftyUserDefaults
//
// Copyright (c) 2015-present Radosław Pietruszewski, Łukasz Mróz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

import Foundation

public extension UserDefaults {

    public func observe<T: DefaultsSerializable>(key: DefaultsKey<T>, options: NSKeyValueObservingOptions = [.initial, .old, .new], handler: @escaping (DefaultsObserver<T>.Update) -> Void) -> DefaultsDisposable {
        return DefaultsObserver(key: key, userDefaults: self, options: options, handler: handler)
    }
}

Remove redundant public modifier to observe function

//
// SwiftyUserDefaults
//
// Copyright (c) 2015-present Radosław Pietruszewski, Łukasz Mróz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

import Foundation

public extension UserDefaults {

    func observe<T: DefaultsSerializable>(key: DefaultsKey<T>, options: NSKeyValueObservingOptions = [.initial, .old, .new], handler: @escaping (DefaultsObserver<T>.Update) -> Void) -> DefaultsDisposable {
        return DefaultsObserver(key: key, userDefaults: self, options: options, handler: handler)
    }
}


//
//  AppInfoScreen.swift
//  StudyBox_iOS
//
//  Created by Kacper Cz on 28.05.2016.
//  Copyright © 2016 BLStream. All rights reserved.
//

import UIKit

class AppInfoScreen: StudyBoxViewController, UITextViewDelegate {

    @IBOutlet weak var infoTextView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.infoTextView.contentOffset = CGPoint(x: infoTextView.contentInset.left, y: infoTextView.contentInset.top)
    }
}

Fix content offset and scrolling

//
//  AppInfoScreen.swift
//  StudyBox_iOS
//
//  Created by Kacper Cz on 28.05.2016.
//  Copyright © 2016 BLStream. All rights reserved.
//

import UIKit

class AppInfoScreen: StudyBoxViewController, UITextViewDelegate {

    @IBOutlet weak var infoTextView: UITextView!

    private var navbarHeight: CGFloat  {
        return self.navigationController?.navigationBar.frame.height ?? 0
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let navBarAndStatus = navbarHeight + UIApplication.sharedApplication().statusBarFrame.height
        self.infoTextView.setContentOffset(CGPoint(x: 0, y: -navBarAndStatus), animated: false)
    }
}


public struct Card: CustomStringConvertible {
    public enum Suit: Int {
        case Spade = 0
        case Club
        case Heart
        case Diamond
    }
    public enum FaceValue: Int {
        case Ace = 1
        case Two = 2
        case Three = 3
        case Four = 4
        case Five = 5
        case Six = 6
        case Seven = 7
        case Eight = 8
        case Nine = 9
        case Ten = 10
        case Jack = 11
        case Queen = 12
        case King = 13
    }

    private(set) public var suit: Suit
    private(set) public var value: FaceValue

    public var description: String {
        return "\(value) of \(suit)"
    }
}
public struct Deck: CustomStringConvertible {
    private var deck: [Card]

    public init() {
        deck = [Card]()
        for s in 0..<4 {
            for v in 1...13 {
                deck.append(Card(suit: Card.Suit(rawValue: s)!, value: Card.FaceValue(rawValue: v)!))
            }
        }
    }

    public mutating func shuffle() {
        deck = deck.sorted { (_, _) -> Bool in
            return arc4random() % 2 == 0
        }
    }

    public var description: String {
        var deckString = ""
        for (i, card) in deck.enumerated() {
            deckString.append(card.description)
            if (i % 4 == 3) {
                deckString.append("\n")
            } else {
                deckString.append("\t")
            }
        }
        return deckString
    }
}

Optimize deck shuffling in Swift

import Foundation

public struct Card: CustomStringConvertible {
    public enum Suit: Int {
        case Spade = 0
        case Club
        case Heart
        case Diamond
    }
    public enum FaceValue: Int {
        case Ace = 1
        case Two = 2
        case Three = 3
        case Four = 4
        case Five = 5
        case Six = 6
        case Seven = 7
        case Eight = 8
        case Nine = 9
        case Ten = 10
        case Jack = 11
        case Queen = 12
        case King = 13
    }

    private(set) public var suit: Suit
    private(set) public var value: FaceValue

    public var description: String {
        return "\(value) of \(suit)"
    }
}
public struct Deck: CustomStringConvertible {
    private var deck: [Card]

    public init() {
        deck = [Card]()
        for s in 0..<4 {
            for v in 1...13 {
                deck.append(Card(suit: Card.Suit(rawValue: s)!, value: Card.FaceValue(rawValue: v)!))
            }
        }
    }

    public mutating func shuffle() {
        deck.sort { (_, _) -> Bool in
            return arc4random() % 2 == 0
        }
    }

    public var description: String {
        var deckString = ""
        for (i, card) in deck.enumerated() {
            deckString.append(card.description)
            if (i % 4 == 3) {
                deckString.append("\n")
            } else {
                deckString.append("\t")
            }
        }
        return deckString
    }
}


//
//  VIMUploadQuota.swift
//  VimeoNetworking
//
//  Created by Lim, Jennifer on 3/26/18.
//

import Foundation

public class VIMUploadQuota: VIMModelObject
{
    /// The values within `VIMSpace` reflect the lowest of lifetime or period for free and max.
    @objc dynamic public private(set) var space: VIMSpace?

    /// Represents the current quota perio
    @objc dynamic public private(set) var periodic: VIMPeriodic?

    /// Represents the lifetime quota period
    @objc dynamic public private(set) var lifetime: VIMSizeQuota?

    public override func getClassForObjectKey(_ key: String!) -> AnyClass!
    {
        if key == "space"
        {
            return VIMSpace.self
        }
        else if key == "periodic"
        {
            return VIMPeriodic.self
        }
        else if key == "lifetime"
        {
            return VIMSizeQuota.self
        }

        return nil
    }
}

public class VIMSpace: VIMSizeQuota
{
    /// Whether the values of the upload_quota.space fields are for the lifetime quota or the periodic quota.
    @objc dynamic public private(set) var showing: String?
}

public class VIMPeriodic: VIMSizeQuota
{
    /// The time in ISO 8601 format when your upload quota resets.
    @objc dynamic public private(set) var resetDate: Date?

    // MARK: - VIMMappable

    public override func getObjectMapping() -> Any
    {
        return ["reset_date" : "resetDate"]
    }
}

Update access control of space property

//
//  VIMUploadQuota.swift
//  VimeoNetworking
//
//  Created by Lim, Jennifer on 3/26/18.
//

import Foundation

public class VIMUploadQuota: VIMModelObject
{
    /// The values within `VIMSpace` reflect the lowest of lifetime or period for free and max.
    @objc dynamic public var space: VIMSpace?

    /// Represents the current quota perio
    @objc dynamic public private(set) var periodic: VIMPeriodic?

    /// Represents the lifetime quota period
    @objc dynamic public private(set) var lifetime: VIMSizeQuota?

    public override func getClassForObjectKey(_ key: String!) -> AnyClass!
    {
        if key == "space"
        {
            return VIMSpace.self
        }
        else if key == "periodic"
        {
            return VIMPeriodic.self
        }
        else if key == "lifetime"
        {
            return VIMSizeQuota.self
        }

        return nil
    }
}

public class VIMSpace: VIMSizeQuota
{
    /// Whether the values of the upload_quota.space fields are for the lifetime quota or the periodic quota.
    @objc dynamic public private(set) var showing: String?
}

public class VIMPeriodic: VIMSizeQuota
{
    /// The time in ISO 8601 format when your upload quota resets.
    @objc dynamic public private(set) var resetDate: Date?

    // MARK: - VIMMappable

    public override func getObjectMapping() -> Any
    {
        return ["reset_date" : "resetDate"]
    }
}


// RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test

// CHECK-NOT: Reallocations exceeded 30
func testReallocation() {
  var x = "The quick brown fox jumped over the lazy dog\n"._split(separator: " ")

  var story = "Let me tell you a story:"
  var laps = 1000

  var reallocations = 0
  for i in 0..<laps {
    for s in x {
      var lastBase = story._core._baseAddress
      story += " "
      story += s
      if lastBase != story._core._baseAddress {
        reallocations += 1

        // To avoid dumping a vast string here, just write the first
        // part of the story out each time there's a reallocation.
        var intro = story._split(":")[0]
        print("reallocation \(reallocations), with intro \(intro)")

        if reallocations >= 30 {
          print("Reallocations exceeded 30")
          return
        }
      }
    }
    story += "."
  }
  print("total reallocations = \(reallocations)")
}

testReallocation()
print("done!")

Add missing separator label that escaped previous audit.

// RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test

// CHECK-NOT: Reallocations exceeded 30
func testReallocation() {
  var x = "The quick brown fox jumped over the lazy dog\n"._split(separator: " ")

  var story = "Let me tell you a story:"
  var laps = 1000

  var reallocations = 0
  for i in 0..<laps {
    for s in x {
      var lastBase = story._core._baseAddress
      story += " "
      story += s
      if lastBase != story._core._baseAddress {
        reallocations += 1

        // To avoid dumping a vast string here, just write the first
        // part of the story out each time there's a reallocation.
        var intro = story._split(separator: ":")[0]
        print("reallocation \(reallocations), with intro \(intro)")

        if reallocations >= 30 {
          print("Reallocations exceeded 30")
          return
        }
      }
    }
    story += "."
  }
  print("total reallocations = \(reallocations)")
}

testReallocation()
print("done!")


//  Copyright (c) 2014 Rob Rix. All rights reserved.

import Traversal
import XCTest

class StreamTests: XCTestCase {
	func testStreams() {
		let sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9]
		let reducible = ReducibleOf(sequence: sequence)
		let stream = Stream(reducible)

		XCTAssertEqual(first(stream)!, 1)
		XCTAssertEqual(first(stream)!, 1)
		XCTAssertEqual(first(dropFirst(stream))!, 2)
		XCTAssertEqual(first(dropFirst(stream))!, 2)
		XCTAssertEqual(first(dropFirst(dropFirst(dropFirst(stream))))!, 4)

		var n = 0
		for (a, b) in Zip2(stream, sequence) {
			XCTAssertEqual(a, b)
			n++
		}
		XCTAssertEqual(n, sequence.count)
	}
}

Test equality against the sequence directly.

//  Copyright (c) 2014 Rob Rix. All rights reserved.

import Traversal
import XCTest

class StreamTests: XCTestCase {
	func testStreams() {
		let sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9]
		let reducible = ReducibleOf(sequence: sequence)
		let stream = Stream(reducible)

		XCTAssertEqual(first(stream)!, 1)
		XCTAssertEqual(first(stream)!, 1)
		XCTAssertEqual(first(dropFirst(stream))!, 2)
		XCTAssertEqual(first(dropFirst(stream))!, 2)
		XCTAssertEqual(first(dropFirst(dropFirst(dropFirst(stream))))!, 4)

		var n = 0
		for (a, b) in Zip2(stream, sequence) {
			XCTAssertEqual(a, b)
			n++
		}
		XCTAssertEqual(Array(stream), sequence)
		XCTAssertEqual(n, sequence.count)
	}
}


// RUN: %swift -parse %s -verify -D FOO -D BAR -target x86_64-freebsd10 -disable-objc-interop -D FOO -parse-stdlib
// RUN: %swift-ide-test -test-input-complete -source-filename=%s -target x86_64-freebsd10

#if arch(x86_64) && os(FreeBSD) && _runtime(_Native)
class C {}
var x = C()
#endif
var y = x

Apply patch provided by gribozavr; swift -target requires a proper triple.

// RUN: %swift -parse %s -verify -D FOO -D BAR -target x86_64-unknown-freebsd10 -disable-objc-interop -D FOO -parse-stdlib
// RUN: %swift-ide-test -test-input-complete -source-filename=%s -target x86_64-unknown-freebsd10

#if arch(x86_64) && os(FreeBSD) && _runtime(_Native)
class C {}
var x = C()
#endif
var y = x


//  Copyright © 2015 Rob Rix. All rights reserved.

extension Module {
	public static var boolean: Module {
		return Module("Boolean", [
			.Datatype("Boolean", [
				"true": .End,
				"false": .End
			])
		])
	}
}

import Prelude

Add boolean functions to the datatype Boolean module.

//  Copyright © 2015 Rob Rix. All rights reserved.

extension Module {
	public static var boolean: Module {
		let Boolean = Declaration<Recur>.Datatype("Boolean", [
			"true": .End,
			"false": .End
		])

		let `true`: Recur = "true"
		let `false`: Recur = "false"

		let not = Declaration("not",
			type: Recur.FunctionType(Boolean.ref, Boolean.ref),
			value: Recur.lambda(Boolean.ref, .Type) { b, A in Recur.lambda(A, A) { t, f in b[A, f, t] } })

		let `if` = Declaration("if",
			type: Recur.lambda(.Type, Boolean.ref) { A, condition in Recur.lambda(A, A, const(A)) },
			value: Recur.lambda(.Type, Boolean.ref) { A, condition in Recur.lambda(A, A) { condition[A, $0, $1] } })

		let and = Declaration("and",
			type: Recur.FunctionType(Boolean.ref, Boolean.ref, Boolean.ref),
			value: Recur.lambda(Boolean.ref, Boolean.ref) { p, q in p[Boolean.ref, q, `false`] })

		let or = Declaration("or",
			type: Recur.FunctionType(Boolean.ref, Boolean.ref, Boolean.ref),
			value: Recur.lambda(Boolean.ref, Boolean.ref) { p, q in p[Boolean.ref, `true`, q] })

		let xor = Declaration("xor",
			type: Recur.FunctionType(Boolean.ref, Boolean.ref, Boolean.ref),
			value: Recur.lambda(Boolean.ref, Boolean.ref, { p, q in p[Boolean.ref, not.ref[q], q] }))

		return Module("Boolean", [ Boolean, `if`, `and`, `or`, `xor` ])
	}
}

import Prelude


//
//  ObjectValidator.swift
//  Drift
//
//  Created by Brian McDonald on 25/07/2016.
//  Copyright © 2016 Drift. All rights reserved.
//

import UIKit
import ObjectMapper

private var failures = 0

extension Map{

    func validNotEmpty<T>() -> T {
        if let value: T = value() {
            if value as? String == ""{
                failures += 1
                return dummyObject()
            }
            return value
        }else {
            // Collects failed count
            failures += 1
            return dummyObject()
        }
    }

    fileprivate func dummyObject<T>() -> T{
        let pointer = UnsafeMutablePointer<T>.allocate(capacity: 0)
        pointer.deallocate(capacity: 0)
        return pointer.pointee
    }

    var isValidNotEmpty: Bool{
        return failures == 0
    }

}

Remove object validation dummy object in favor of returning nil

//
//  ObjectValidator.swift
//  Drift
//
//  Created by Brian McDonald on 25/07/2016.
//  Copyright © 2016 Drift. All rights reserved.
//

import UIKit
import ObjectMapper

private var failures = 0

extension Map{

    func validNotEmpty<T>() -> T? {
        if let value: T = value() {
            if value as? String == ""{
                failures += 1
                return nil
            }
            return value
        }else {
            // Collects failed count
            failures += 1
            return nil
        }
    }

    var isValidNotEmpty: Bool{
        return failures == 0
    }

}


//
//  AutocompleteParser.swift
//  DuckDuckGo
//
//  Created by Mia Alexiou on 09/03/2017.
//  Copyright © 2017 DuckDuckGo. All rights reserved.
//

import Foundation

class AutocompleteParser {

    enum ParsingError: Error {
        case noData
        case invalidJson
    }

    func parse(data: Data?) throws -> [Suggestion] {

        guard let data = data else {
            throw ParsingError.noData
        }

        guard let json = try JSONSerialization.jsonObject(with: data) as? [[String: String]] else {
            throw ParsingError.invalidJson
        }

        var suggestions = [Suggestion]()
        for element in json {
            if let type = element.keys.first, let suggestion = element[type] {
                NSLog("\(type): \(suggestion)")
                suggestions.append(Suggestion(type: type, suggestion: suggestion))
            }
        }
        return suggestions
    }
}

Switch slog statement to in app logger

//
//  AutocompleteParser.swift
//  DuckDuckGo
//
//  Created by Mia Alexiou on 09/03/2017.
//  Copyright © 2017 DuckDuckGo. All rights reserved.
//

import Foundation
import Core

class AutocompleteParser {

    enum ParsingError: Error {
        case noData
        case invalidJson
    }

    func parse(data: Data?) throws -> [Suggestion] {

        guard let data = data else {
            throw ParsingError.noData
        }

        guard let json = try JSONSerialization.jsonObject(with: data) as? [[String: String]] else {
            throw ParsingError.invalidJson
        }

        var suggestions = [Suggestion]()
        for element in json {
            if let type = element.keys.first, let suggestion = element[type] {
                Logger.log(text: "\(type): \(suggestion)")
                suggestions.append(Suggestion(type: type, suggestion: suggestion))
            }
        }
        return suggestions
    }
}


// RUN: %target-typecheck-verify-swift -diagnostics-editor-mode

protocol P1 {
  @available(iOS, unavailable)
  func foo1()
  func foo2()
}

protocol P2 {
  func bar1()
  func bar2()
}

class C1 : P1, P2 {} // expected-error{{type 'C1' does not conform to protocol 'P1'}} expected-error{{type 'C1' does not conform to protocol 'P2'}} expected-note{{do you want to add protocol stubs?}}{{20-20=\n    func foo1() {\n        <#code#>\n    \}\n\n    func foo2() {\n        <#code#>\n    \}\n\n    func bar1() {\n        <#code#>\n    \}\n\n    func bar2() {\n        <#code#>\n    \}\n}}

protocol P3 {
  associatedtype T1
  associatedtype T2
  associatedtype T3
}

protocol P4 : P3 {
  associatedtype T4 = T1
  associatedtype T5 = T2
  associatedtype T6 = T3
}

class C2 : P4 {} // expected-error{{type 'C2' does not conform to protocol 'P4'}} expected-error{{type 'C2' does not conform to protocol 'P3'}} expected-note{{do you want to add protocol stubs?}}{{16-16=\n    typealias T1 = <#type#>\n\n    typealias T2 = <#type#>\n\n    typealias T3 = <#type#>\n}}

Build fix: Update fix-it stub editor test

// RUN: %target-typecheck-verify-swift -diagnostics-editor-mode
// REQUIRES: objc_interop

import Foundation

@objc protocol P1 {
  @available(iOS, unavailable)
  func foo1()
  func foo2()
}

protocol P2 {
  func bar1()
  func bar2()
}

class C1 : P1, P2 {}
// expected-error@-1 {{type 'C1' does not conform to protocol 'P1'}}
// expected-error@-2 {{type 'C1' does not conform to protocol 'P2'}}
// expected-note@-3 {{do you want to add protocol stubs?}} {{20-20=\n    func foo2() {\n        <#code#>\n    \}\n\n    func bar1() {\n        <#code#>\n    \}\n\n    func bar2() {\n        <#code#>\n    \}\n}}

protocol P3 {
  associatedtype T1
  associatedtype T2
  associatedtype T3
}

protocol P4 : P3 {
  associatedtype T4 = T1
  associatedtype T5 = T2
  associatedtype T6 = T3
}

class C2 : P4 {} // expected-error{{type 'C2' does not conform to protocol 'P4'}} expected-error{{type 'C2' does not conform to protocol 'P3'}} expected-note{{do you want to add protocol stubs?}}{{16-16=\n    typealias T1 = <#type#>\n\n    typealias T2 = <#type#>\n\n    typealias T3 = <#type#>\n}}


import Foundation

// MARK: - Logger

public class Logger {

  public enum Level {
    case Debug, Info, Error, Disabled
  }

  public var level: Level = .Disabled
  public var errorLogger: ErrorLogging = ErrorLogger()
  public var infoLogger: InfoLogging = InfoLogger()

  var logErrors: Bool {
    return level == .Error || level == .Debug
  }

  var logInfo: Bool {
    return level == .Info || level == .Debug
  }
}

// MARK: - Errors

public protocol ErrorLogging {
  func logError(error: ErrorType)
}

public struct ErrorLogger: ErrorLogging {

  public func logError(error: ErrorType) {
    NSLog("\(error)")
  }
}

// MARK: - Info

public protocol InfoLogging {
  func logRequest(request: NSURLRequest)
}

public struct InfoLogger: InfoLogging {

  public func logRequest(request: NSURLRequest) {
    guard let URLString = request.URL?.absoluteString else {
      return
    }

    NSLog("\(URLString)")
  }
}

Use print in logging by default

import Foundation

// MARK: - Logger

public class Logger {

  public enum Level {
    case Debug, Info, Error, Disabled
  }

  public var level: Level = .Disabled
  public var errorLogger: ErrorLogging = ErrorLogger()
  public var infoLogger: InfoLogging = InfoLogger()

  var logErrors: Bool {
    return level == .Error || level == .Debug
  }

  var logInfo: Bool {
    return level == .Info || level == .Debug
  }
}

// MARK: - Errors

public protocol ErrorLogging {
  func logError(error: ErrorType)
}

public struct ErrorLogger: ErrorLogging {

  public func logError(error: ErrorType) {
    print("\(error)")
  }
}

// MARK: - Info

public protocol InfoLogging {
  func logRequest(request: NSURLRequest)
}

public struct InfoLogger: InfoLogging {

  public func logRequest(request: NSURLRequest) {
    guard let URLString = request.URL?.absoluteString else {
      return
    }

    print("\(URLString)")
  }
}


import XCTest
import Umbrella
import UmbrellaAppboy
import Appboy_iOS_SDK

final class AppboyProviderTests: XCTestCase {
  private enum Swizzle {
    static let UNUserNotificationCenterInitializer: Void = {
      let oldMethod = class_getInstanceMethod(
        UNUserNotificationCenter.self,
        NSSelectorFromString("initWithBundleIdentifier:")
      )
      let newMethod = class_getInstanceMethod(
        UNUserNotificationCenter.self,
        #selector(UNUserNotificationCenter.swizzled_init(bundleIdentifier:))
      )
      method_exchangeImplementations(oldMethod, newMethod)
    }()
  }

  override func setUp() {
    super.setUp()
    Swizzle.UNUserNotificationCenterInitializer
    Appboy.start(withApiKey: "TEST_TOKEN", in: UIApplication.shared, withLaunchOptions: [:], withAppboyOptions: [:])
  }

  func testAppboyProvider() {
    let provider = AppboyProvider()
    XCTAssertTrue(provider.cls === Appboy.self)
    XCTAssertNotNil(provider.instance)
    XCTAssertTrue(provider.instance === Appboy.sharedInstance())
    XCTAssertEqual(provider.selector, #selector(Appboy.logCustomEvent(_:withProperties:)))
    XCTAssertTrue(provider.responds)
  }
}

extension UNUserNotificationCenter {
  func swizzled_init(bundleIdentifier: String?) -> UNUserNotificationCenter {
    return self.swizzled_init(bundleIdentifier: "com.umbrella.test")
  }
}

Update to Swift 4 api changes

import XCTest
import Umbrella
import UmbrellaAppboy
import Appboy_iOS_SDK

final class AppboyProviderTests: XCTestCase {
  private enum Swizzle {
    static let UNUserNotificationCenterInitializer: Void = {
      guard let oldMethod = class_getInstanceMethod(
        UNUserNotificationCenter.self,
        NSSelectorFromString("initWithBundleIdentifier:")
      ) else { return }
      guard let newMethod = class_getInstanceMethod(
        UNUserNotificationCenter.self,
        #selector(UNUserNotificationCenter.swizzled_init(bundleIdentifier:))
      ) else { return }
      method_exchangeImplementations(oldMethod, newMethod)
    }()
  }

  override func setUp() {
    super.setUp()
    Swizzle.UNUserNotificationCenterInitializer
    Appboy.start(withApiKey: "TEST_TOKEN", in: UIApplication.shared, withLaunchOptions: [:], withAppboyOptions: [:])
  }

  func testAppboyProvider() {
    let provider = AppboyProvider()
    XCTAssertTrue(provider.cls === Appboy.self)
    XCTAssertNotNil(provider.instance)
    XCTAssertTrue(provider.instance === Appboy.sharedInstance())
    XCTAssertEqual(provider.selector, #selector(Appboy.logCustomEvent(_:withProperties:)))
    XCTAssertTrue(provider.responds)
  }
}

extension UNUserNotificationCenter {
  @objc func swizzled_init(bundleIdentifier: String?) -> UNUserNotificationCenter {
    return self.swizzled_init(bundleIdentifier: "com.umbrella.test")
  }
}


import ReactiveCocoa
import Moya
import ObjectMapper

/// Extension for processing Responses into Mappable objects through ObjectMapper
extension SignalProducerType where Value == Moya.Response, Error == Moya.Error {

  /// Maps data received from the signal into an object which implements the Mappable protocol.
  /// If the conversion fails, the signal errors.
  public func mapObject<T: Mappable>(type: T.Type) -> SignalProducer<T, Error> {
    return producer.flatMap(.Latest) { response -> SignalProducer<T, Error> in
      return unwrapThrowable { try response.mapObject(T) }
    }
  }

  /// Maps data received from the signal into an array of objects which implement the Mappable
  /// protocol.
  /// If the conversion fails, the signal errors.
  public func mapArray<T: Mappable>(type: T.Type) -> SignalProducer<[T], Error> {
    return producer.flatMap(.Latest) { response -> SignalProducer<[T], Error> in
      return unwrapThrowable { try response.mapArray(T) }
    }
  }
}

/// Maps throwable to SignalProducer
private func unwrapThrowable<T>(throwable: () throws -> T) -> SignalProducer<T, Moya.Error> {
  do {
    return SignalProducer(value: try throwable())
  } catch {
    return SignalProducer(error: error as! Moya.Error)
  }
}

Use BaseMappable as the expected protocol

import ReactiveCocoa
import Moya
import ObjectMapper

/// Extension for processing Responses into Mappable objects through ObjectMapper
extension SignalProducerType where Value == Moya.Response, Error == Moya.Error {

  /// Maps data received from the signal into an object which implements the Mappable protocol.
  /// If the conversion fails, the signal errors.
  public func mapObject<T: BaseMappable>(type: T.Type) -> SignalProducer<T, Error> {
    return producer.flatMap(.Latest) { response -> SignalProducer<T, Error> in
      return unwrapThrowable { try response.mapObject(T) }
    }
  }

  /// Maps data received from the signal into an array of objects which implement the Mappable
  /// protocol.
  /// If the conversion fails, the signal errors.
  public func mapArray<T: BaseMappable>(type: T.Type) -> SignalProducer<[T], Error> {
    return producer.flatMap(.Latest) { response -> SignalProducer<[T], Error> in
      return unwrapThrowable { try response.mapArray(T) }
    }
  }
}

/// Maps throwable to SignalProducer
private func unwrapThrowable<T>(throwable: () throws -> T) -> SignalProducer<T, Moya.Error> {
  do {
    return SignalProducer(value: try throwable())
  } catch {
    return SignalProducer(error: error as! Moya.Error)
  }
}


// Copyright © 2019 Flinesoft. All rights reserved.

import CoreGraphics

/// A type which conforms to DivisibleArithmetic provides the basic arithmetic operations: additon, subtraction, multiplication and division.
public protocol DivisibleArithmetic: Numeric {
    init(_ value: Int)
    static func / (lhs: Self, rhs: Self) -> Self
}

extension Double: DivisibleArithmetic {}
extension Float: DivisibleArithmetic {}
extension CGFloat: DivisibleArithmetic {}

Fix linux support by excluding `CGFloat` extension there

// Copyright © 2019 Flinesoft. All rights reserved.

/// A type which conforms to DivisibleArithmetic provides the basic arithmetic operations: additon, subtraction, multiplication and division.
public protocol DivisibleArithmetic: Numeric {
    init(_ value: Int)
    static func / (lhs: Self, rhs: Self) -> Self
}

extension Double: DivisibleArithmetic {}
extension Float: DivisibleArithmetic {}

#if canImport(CoreGraphics)
    import CoreGraphics

    extension CGFloat: DivisibleArithmetic {}
#endif


// RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -import-objc-header %S/Inputs/rdar29694978.h -emit-module -o %t/Library.swiftmodule
// RUN: %target-swift-ide-test -print-module -module-to-print=Library -source-filename=x -I %S/Inputs/ -I %t | %FileCheck %s

// REQUIRES: objc_interop

// This would be wonderful to fold into a larger test, but I'm worried that
// trying to do so would perturb the original conditions that cause it to
// crash: deserializing a typealias (1) to an imported Objective-C type (2)
// that has a protocol (3) that refines another protocol (4) which causes us
// to load all extensions, including one defined in this file (5) in terms of
// the original typealias (1).
//
// It's probably best to just leave this test about that.

import Foundation

// CHECK-DAG: typealias MyNonGenericType = NonGenericType
typealias MyNonGenericType = NonGenericType
// CHECK-DAG: extension NonGenericType
extension MyNonGenericType {}

// CHECK-DAG: typealias MyGenericType<T> = GenericType<T>
typealias MyGenericType<T: NSObject> = GenericType<T>
// CHECK-DAG: extension GenericType where Element : AnyObject
extension MyGenericType {}
// CHECK-DAG: extension GenericType where Element == NSObject
extension MyGenericType where Element == NSObject {}

Update one last test for extensions of generic typealiases.

// RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -import-objc-header %S/Inputs/rdar29694978.h -emit-module -o %t/Library.swiftmodule
// RUN: %target-swift-ide-test -print-module -module-to-print=Library -source-filename=x -I %S/Inputs/ -I %t | %FileCheck %s

// REQUIRES: objc_interop

// This would be wonderful to fold into a larger test, but I'm worried that
// trying to do so would perturb the original conditions that cause it to
// crash: deserializing a typealias (1) to an imported Objective-C type (2)
// that has a protocol (3) that refines another protocol (4) which causes us
// to load all extensions, including one defined in this file (5) in terms of
// the original typealias (1).
//
// It's probably best to just leave this test about that.

import Foundation

// CHECK-DAG: typealias MyNonGenericType = NonGenericType
typealias MyNonGenericType = NonGenericType
// CHECK-DAG: extension NonGenericType
extension MyNonGenericType {}

// CHECK-DAG: typealias MyGenericType<T> = GenericType<T>
typealias MyGenericType<T: NSObject> = GenericType<T>
// CHECK-DAG: extension GenericType where Element : NSObject
extension MyGenericType {}
// CHECK-DAG: extension GenericType where Element == NSObject
extension MyGenericType where Element == NSObject {}


import XCTest
#if USING_SQLCIPHER
    import GRDBCipher
#elseif USING_CUSTOMSQLITE
    import GRDBCustomSQLite
#else
    import GRDB
#endif

class NSDataTests: GRDBTestCase {

    func testDatabaseValueCanNotStoreEmptyData() {
        // SQLite can't store zero-length blob.
        let databaseValue = NSData().databaseValue
        XCTAssertEqual(databaseValue, DatabaseValue.Null)
    }
}

Increase test coverage of NSData.swift

import XCTest
#if USING_SQLCIPHER
    import GRDBCipher
#elseif USING_CUSTOMSQLITE
    import GRDBCustomSQLite
#else
    import GRDB
#endif

class NSDataTests: GRDBTestCase {

    func testDatabaseValueCanNotStoreEmptyData() {
        // SQLite can't store zero-length blob.
        let databaseValue = NSData().databaseValue
        XCTAssertEqual(databaseValue, DatabaseValue.Null)
    }

    func testNSDataDatabaseValueRoundTrip() {

        func roundTrip(value: NSData) -> Bool
        {
            let databaseValue = value.databaseValue
            guard let back = NSData.fromDatabaseValue(databaseValue) else
            {
                XCTFail("Failed to convert from DatabaseValue to NSData")
                return false
            }
            return back.isEqual(value)
        }

        XCTAssertTrue(roundTrip("bar".dataUsingEncoding(NSUTF8StringEncoding)!))
    }

    func testNSDataFromDatabaseValueFailure() {
        let databaseValue_Null = DatabaseValue.Null
        let databaseValue_Int64 = Int64(1).databaseValue
        let databaseValue_Double = Double(100000.1).databaseValue
        let databaseValue_String = "foo".databaseValue
        XCTAssertNil(NSData.fromDatabaseValue(databaseValue_Null))
        XCTAssertNil(NSData.fromDatabaseValue(databaseValue_Int64))
        XCTAssertNil(NSData.fromDatabaseValue(databaseValue_Double))
        XCTAssertNil(NSData.fromDatabaseValue(databaseValue_String))
    }
}


//
//  TableViewFetchedResultsDisplayer.swift
//  V
//
//  Created by Dulio Denis on 7/8/16.
//  Copyright © 2016 Dulio Denis. All rights reserved.
//

import UIKit

// Conforming to this protocol will require implementing the configure cell method

protocol TableViewFetchedResultsDisplayer {

    // the Configure Cell Helper Method takes a UITableViewCell and an indexPath
    func configureCell(cell: UITableViewCell, atIndexPath: NSIndexPath)
}

Add indexPath parameter name to configureCell protocol function

//
//  TableViewFetchedResultsDisplayer.swift
//  V
//
//  Created by Dulio Denis on 7/8/16.
//  Copyright © 2016 Dulio Denis. All rights reserved.
//

import UIKit

// Conforming to this protocol will require implementing the configure cell method

protocol TableViewFetchedResultsDisplayer {

    // the Configure Cell Helper Method takes a UITableViewCell and an indexPath
    func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath)
}


//
//  AppDelegate.swift
//  FTMobileCoreSample
//
//  Created by Praveen Prabhakar on 15/06/17.
//  Copyright © 2017 Praveen Prabhakar. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: FTAppDelegate {

    public override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        FTReflection.registerModuleIdentifier([AppDelegate.self,FTBaseView.self])

        if
            let resource = Bundle.main.path(forResource: "MobileCodeSampleBundle", ofType: "bundle"),
            let theme = Bundle(path: resource)?.path(forResource: "Themes", ofType: "json"),
            let themeContent: FTThemeDic = try! theme.jsonContentAtPath() {

            FTThemesManager.setupThemes(themes: themeContent, imageSourceBundle: [AppDelegate.self])
        }

        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

}

Update Demo application's themeManger imagesource.

//
//  AppDelegate.swift
//  FTMobileCoreSample
//
//  Created by Praveen Prabhakar on 15/06/17.
//  Copyright © 2017 Praveen Prabhakar. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: FTAppDelegate {

    public override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        FTReflection.registerModuleIdentifier([AppDelegate.self,FTBaseView.self])

        if
            let resource = Bundle.main.path(forResource: "MobileCodeSampleBundle", ofType: "bundle"),
            let theme = Bundle(path: resource)?.path(forResource: "Themes", ofType: "json"),
            let themeContent: FTThemeDic = try! theme.jsonContentAtPath() {

            FTThemesManager.setupThemes(themes: themeContent, imageSourceBundle: [Bundle(for: AppDelegate.self)])
        }

        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

}


import XCTest
import CoreLocation
@testable import columbus

final class UTMCreateLocationDelegate:XCTestCase
{
    private let kAccuracy:CLLocationAccuracy = kCLLocationAccuracyBestForNavigation

    //MARK: tests

    func testAskAuthorization()
    {
        let model:MCreateLocationDelegate = MCreateLocationDelegate()
        model.askAuthorization()

        XCTAssertNotNil(
            model.locationManager,
            "failed creating location manager")

        XCTAssertNotNil(
            model.locationManager?.delegate,
            "failed assigning delegate to location manager")

        XCTAssertEqual(
            model.locationManager?.desiredAccuracy,
            kAccuracy,
            "failed assigning maximum accuracy for location manager")
    }

    func testClean()
    {
        let model:MCreateLocationDelegate = MCreateLocationDelegate()
        model.askAuthorization()
        model.clean()

        XCTAssertNil(
            model.locationManager?.delegate,
            "failed removing delegate from location manager")
    }
}

Use setup in test to init models

import XCTest
import CoreLocation
@testable import columbus

final class UTMCreateLocationDelegate:XCTestCase
{
    private var modelLocation:MCreateLocationDelegate?
    private var modelCreate:MCreate?
    private let kAccuracy:CLLocationAccuracy = kCLLocationAccuracyBestForNavigation

    override func setUp()
    {
        super.setUp()

        modelLocation = MCreateLocationDelegate()
        modelCreate = MCreate()
        modelLocation?.model = modelCreate
        modelLocation?.askAuthorization()
    }

    //MARK: tests

    func testAskAuthorization()
    {
        XCTAssertNotNil(
            modelLocation?.locationManager,
            "failed creating location manager")

        XCTAssertNotNil(
            modelLocation?.locationManager?.delegate,
            "failed assigning delegate to location manager")

        XCTAssertEqual(
            modelLocation?.locationManager?.desiredAccuracy,
            kAccuracy,
            "failed assigning maximum accuracy for location manager")
    }

    func testClean()
    {
        modelLocation?.clean()

        XCTAssertNil(
            modelLocation?.locationManager?.delegate,
            "failed removing delegate from location manager")
    }
}


//
//  SocialRadarRestAPI.swift
//  SocialRadar
//
//  Created by DSTRS TRAC Web on 10/31/2557 BE.
//  Copyright (c) 2557 dsthackathon. All rights reserved.
//

import Foundation
import AlamoFire

class SocialRadarRestAPI: NSObject {
//    var data : NSMutableData = NSMutableData();
//    var delegate :

    func getQuestion() {

//        https://api.flickr.com/services/rest/?method=flickr.test.echo&api_key=7080b3a250ac855dcb96395939b61e57&format=json&nojsoncallback=1

        var parameter = ["method":"flickr.test.echo",
            "api_key":"https://api.flickr.com/services/rest/?method=flickr.test.echo&api_key=7080b3a250ac855dcb96395939b61e57&format=json&nojsoncallback=1",
            "format":"json","nojsoncallback":"1"
        ];

        Alamofire.request(.GET, "https://api.flickr.com/services/rest/", parameters: parameter)
            .response { (request, response, data, error) in
                println(request)
                println(response)
                println(error)
        }

//        var resp = AlamoFire.request(.GET, "https://api.flickr.com/services/rest/", parameters: parameter).responseJSON { (_, _, JSON, _) in
//            println(JSON)
//        }

//        return resp;
    }
}

Change to real question api

//
//  SocialRadarRestAPI.swift
//  SocialRadar
//
//  Created by DSTRS TRAC Web on 10/31/2557 BE.
//  Copyright (c) 2557 dsthackathon. All rights reserved.
//

import Foundation
import AlamoFire

class SocialRadarRestAPI: NSObject {

    func getQuestion() {
//        var questionJSON : String;

        var request2 = Alamofire.request(.GET, "http://api.radar.codedeck.com/questions").responseJSON {
            (_,_,json,_) in
             println(json)
        }

//        return questionJSON;
    }

    func logIn() {

    }

    func submitAnswer() {

    }
}


//
//  ChartAxisValuesGeneratorFixed.swift
//  SwiftCharts
//
//  Created by ischuetz on 27/06/16.
//  Copyright © 2016 ivanschuetz. All rights reserved.
//

import Foundation

/// Generates a fixed axis values array
public class ChartAxisValuesGeneratorFixed: ChartAxisValuesGenerator {

    public var first: Double? {
        return values.first
    }

    public var last: Double? {
        return values.last
    }

    var values: [Double]

    public convenience init(values: [ChartAxisValue]) {
        self.init(values: values.map{$0.scalar})
    }

    public init(values: [Double]) {
        self.values = values
    }

    public func axisInitialized(axis: ChartAxis) {}

    public func generate(axis: ChartAxis) -> [Double] {
        return values.filter{$0 >= axis.firstVisible && $0 <= axis.lastVisible}
    }
}

Allow to invert fixed axis values

//
//  ChartAxisValuesGeneratorFixed.swift
//  SwiftCharts
//
//  Created by ischuetz on 27/06/16.
//  Copyright © 2016 ivanschuetz. All rights reserved.
//

import Foundation

/// Generates a fixed axis values array
public class ChartAxisValuesGeneratorFixed: ChartAxisValuesGenerator {

    public var first: Double? {
        return values.first
    }

    public var last: Double? {
        return values.last
    }

    var values: [Double]

    public convenience init(values: [ChartAxisValue]) {
        self.init(values: values.map{$0.scalar})
    }

    public init(values: [Double]) {
        self.values = values
    }

    public func axisInitialized(axis: ChartAxis) {}

    public func generate(axis: ChartAxis) -> [Double] {
        let (first, last) = axis.firstVisible > axis.lastVisible ? (axis.lastVisible, axis.firstVisible) : (axis.firstVisible, axis.lastVisible)
        return values.filter{$0 >= first && $0 <= last}
    }
}


//
//  ViewController.swift
//  AwesomeButtonExample
//
//  Created by Панов Андрей on 26.12.15.
//  Copyright © 2015 Панов Андрей. All rights reserved.
//

import UIKit
import AwesomeButton

class ViewController: UIViewController {

    @IBOutlet weak var buttonNew: AwesomeButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        // image only
        let button = AwesomeButton(type: .Custom)
        button.frame = CGRectMake(10, 200, 200, 40)
        button.buttonWithIcon(UIImage(named: "example-arrow")!, highlightedImage: UIImage(named: "arrowNextDark"), title: "loadadl")
        self.view.addSubview(button)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Fix example to function as expected

//
//  ViewController.swift
//  AwesomeButtonExample
//
//  Created by Панов Андрей on 26.12.15.
//  Copyright © 2015 Панов Андрей. All rights reserved.
//

import UIKit
import AwesomeButton

class ViewController: UIViewController {

    @IBOutlet weak var buttonNew: AwesomeButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        // image only
        let button = AwesomeButton(type: .custom)
        button.frame = CGRect(x: 10, y: 200, width: 200, height: 40)
        button.buttonWithIcon(UIImage(named: "example-arrow")!, highlightedImage: UIImage(named: "arrowNextDark"), title: "loadadl")
        self.view.addSubview(button)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}


import UIKit

class Controller<V:ViewMain, M:Model<V>>:UIViewController
{
    let model:M

    var parentController:ControllerParent?
    {
        get
        {
            guard

                let parent:ControllerParent = self.parent as? ControllerParent

            else
            {
                return nil
            }

            return parent
        }
    }

    init()
    {
        model = M()

        super.init(nibName:nil, bundle:nil)
    }

    required init?(coder:NSCoder)
    {
        return nil
    }

    override var shouldAutorotate:Bool
    {
        get
        {
            return true
        }
    }

    override func loadView()
    {
        let view:V = V(controller:self)
        model.view = view
        self.view = view
    }

    override func viewWillAppear(_ animated:Bool)
    {
        super.viewWillAppear(animated)

        parent?.setNeedsStatusBarAppearanceUpdate()
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()
        edgesForExtendedLayout = UIRectEdge()
        extendedLayoutIncludesOpaqueBars = false
        automaticallyAdjustsScrollViewInsets = false
    }

    override var preferredStatusBarStyle:UIStatusBarStyle
    {
        return UIStatusBarStyle.default
    }

    override var prefersStatusBarHidden:Bool
    {
        return false
    }
}

Update generics to swift 4

import UIKit

class Controller<V, M:Model<V>>:UIViewController
{
    let model:M

    var parentController:ControllerParent?
    {
        get
        {
            guard

                let parent:ControllerParent = self.parent as? ControllerParent

            else
            {
                return nil
            }

            return parent
        }
    }

    init()
    {
        model = M()

        super.init(nibName:nil, bundle:nil)
    }

    required init?(coder:NSCoder)
    {
        return nil
    }

    override var shouldAutorotate:Bool
    {
        get
        {
            return true
        }
    }

    override func loadView()
    {
        let view:V = V(controller:self)
        model.view = view
        self.view = view
    }

    override func viewWillAppear(_ animated:Bool)
    {
        super.viewWillAppear(animated)

        parent?.setNeedsStatusBarAppearanceUpdate()
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()
        edgesForExtendedLayout = UIRectEdge()
        extendedLayoutIncludesOpaqueBars = false
        automaticallyAdjustsScrollViewInsets = false
    }

    override var preferredStatusBarStyle:UIStatusBarStyle
    {
        return UIStatusBarStyle.default
    }

    override var prefersStatusBarHidden:Bool
    {
        return false
    }
}


//
//  Droplet+VaporJsonApi.swift
//  VaporJsonApi
//
//  Created by Koray Koska on 10/05/2017.
//
//

import Vapor
import HTTP

public extension Droplet {

    public func jsonApiResource<C: JsonApiResourceController>(controller: C) {
        let resourceType = controller.resourceType.parse()
        // Get routes
        get(resourceType, handler: controller.getResources)
        get(resourceType, String.self, handler: controller.getResource)
        get(resourceType, String.self, String.self, handler: controller.getRelatedResource)

        // Post routes
        post(resourceType, handler: controller.postResource)
    }
}

Add route for get relationships

//
//  Droplet+VaporJsonApi.swift
//  VaporJsonApi
//
//  Created by Koray Koska on 10/05/2017.
//
//

import Vapor
import HTTP

public extension Droplet {

    public func jsonApiResource<C: JsonApiResourceController>(controller: C) {
        let resourceType = controller.resourceType.parse()
        // Get routes
        group(resourceType) { resourceType in
            resourceType.get(handler: controller.getResources)
            get(String.self, handler: controller.getResource)
            get(String.self, String.self, handler: controller.getRelatedResource)
            get(String.self, "relationships", String.self, handler: controller.getRelationships)
        }

        // Post routes
        post(resourceType, handler: controller.postResource)
    }
}


// Created by Cihat Gündüz on 07.11.18.

import Foundation
import SwiftCLI

public enum GlobalOptions {
    static let verbose = Flag("-v", "--verbose", description: "Prints more detailed information about the executed command")
    static let xcodeOutput = Flag("-x", "--xcode-output", description: "Prints warnings & errors in Xcode compatible format")

    public static var all: [Option] {
        return [verbose]
    }
}

Add xcode output global command option

// Created by Cihat Gündüz on 07.11.18.

import Foundation
import SwiftCLI

public enum GlobalOptions {
    static let verbose = Flag("-v", "--verbose", description: "Prints more detailed information about the executed command")
    static let xcodeOutput = Flag("-x", "--xcode-output", description: "Prints warnings & errors in Xcode compatible format")

    public static var all: [Option] {
        return [verbose, xcodeOutput]
    }
}


//
//  CollectionViewDataSource.swift
//  TraktTopTen
//
//  Created by Paul Williamson on 05/04/2015.
//  Copyright (c) 2015 Paul Williamson. All rights reserved.
//

import UIKit

class CollectionViewDataSource : NSObject, UICollectionViewDataSource {

    private var items = [MediaItem]()
    private var collectionView: UICollectionView

    init(collectionView: UICollectionView) {
        self.collectionView = collectionView
    }

    func updateData(items: [MediaItem]) {
        self.items = items;
        collectionView.reloadData()
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.items.count
    }

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as MediaItemCell
        let movie = self.items[indexPath.row]
        cell.textLabel.text = "\(movie.title)"

        if let url = NSURL(string: movie.banner) {
            cell.imageView.hnk_setImageFromURL(url)
        }

        return cell
    }

}

Add early return for movie banner image

//
//  CollectionViewDataSource.swift
//  TraktTopTen
//
//  Created by Paul Williamson on 05/04/2015.
//  Copyright (c) 2015 Paul Williamson. All rights reserved.
//

import UIKit

class CollectionViewDataSource : NSObject, UICollectionViewDataSource {

    private var items = [MediaItem]()
    private var collectionView: UICollectionView

    init(collectionView: UICollectionView) {
        self.collectionView = collectionView
    }

    func updateData(items: [MediaItem]) {
        self.items = items;
        collectionView.reloadData()
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.items.count
    }

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as MediaItemCell
        let movie = self.items[indexPath.row]
        cell.textLabel.text = "\(movie.title)"

        if movie.banner.isEmpty {
            return cell
        }

        if let url = NSURL(string: movie.banner) {
            cell.imageView.hnk_setImageFromURL(url)
        }

        return cell
    }

}


//
//  HTMLMetadataDownloader.swift
//  NetNewsWire
//
//  Created by Brent Simmons on 11/26/17.
//  Copyright © 2017 Ranchero Software. All rights reserved.
//

import Foundation
import RSWeb
import RSParser

struct HTMLMetadataDownloader {

	static let serialDispatchQueue = DispatchQueue(label: "HTMLMetadataDownloader")

	static func downloadMetadata(for url: String, _ completion: @escaping (RSHTMLMetadata?) -> Void) {
		guard let actualURL = URL(string: url) else {
			completion(nil)
			return
		}

		downloadUsingCache(actualURL) { (data, response, error) in
			if let data = data, !data.isEmpty, let response = response, response.statusIsOK, error == nil {
				let urlToUse = response.url ?? actualURL
				let parserData = ParserData(url: urlToUse.absoluteString, data: data)
				parseMetadata(with: parserData, completion)
				return
			}

			if let error = error {
				appDelegate.logMessage("Error downloading metadata at \(url): \(error)", type: .warning)
			}

			completion(nil)
		}
	}

	private static func parseMetadata(with parserData: ParserData, _ completion: @escaping (RSHTMLMetadata?) -> Void) {
		serialDispatchQueue.async {
			let htmlMetadata = RSHTMLMetadataParser.htmlMetadata(with: parserData)
			DispatchQueue.main.async {
				completion(htmlMetadata)
			}
		}
	}
}

Remove an error log that’s just noise.

//
//  HTMLMetadataDownloader.swift
//  NetNewsWire
//
//  Created by Brent Simmons on 11/26/17.
//  Copyright © 2017 Ranchero Software. All rights reserved.
//

import Foundation
import RSWeb
import RSParser

struct HTMLMetadataDownloader {

	static let serialDispatchQueue = DispatchQueue(label: "HTMLMetadataDownloader")

	static func downloadMetadata(for url: String, _ completion: @escaping (RSHTMLMetadata?) -> Void) {
		guard let actualURL = URL(string: url) else {
			completion(nil)
			return
		}

		downloadUsingCache(actualURL) { (data, response, error) in
			if let data = data, !data.isEmpty, let response = response, response.statusIsOK, error == nil {
				let urlToUse = response.url ?? actualURL
				let parserData = ParserData(url: urlToUse.absoluteString, data: data)
				parseMetadata(with: parserData, completion)
				return
			}

			completion(nil)
		}
	}

	private static func parseMetadata(with parserData: ParserData, _ completion: @escaping (RSHTMLMetadata?) -> Void) {
		serialDispatchQueue.async {
			let htmlMetadata = RSHTMLMetadataParser.htmlMetadata(with: parserData)
			DispatchQueue.main.async {
				completion(htmlMetadata)
			}
		}
	}
}


// Copyright (c) 2017 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information

import Foundation

class BurrowsWheeler {

    static func transform(bytes: [UInt8]) -> ([UInt8], Int) {
        let suffixArray = SuffixArray.make(from: bytes, with: 256)
        var bwt = [UInt8]()
        var pointer = 0
        for i in 1..<suffixArray.count {
            if suffixArray[i] > 0 {
                bwt.append(bytes[suffixArray[i] - 1])
            } else {
                bwt.append(bytes.last!)
                pointer = i - 1
            }
        }
        return (bwt, pointer)
    }

}

Fix bw transformation from suffix array

// Copyright (c) 2017 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information

import Foundation

class BurrowsWheeler {

    static func transform(bytes: [UInt8]) -> ([UInt8], Int) {
        let doubleBytes = bytes + bytes
        let suffixArray = SuffixArray.make(from: doubleBytes.map { $0.toInt() }, with: 256)
        var bwt = [UInt8]()
        var pointer = 0
        for i in 1..<suffixArray.count {
            if suffixArray[i] < bytes.count {
                if suffixArray[i] > 0 {
                    bwt.append(bytes[suffixArray[i] - 1])
                } else {
                    bwt.append(bytes.last!)
                }
            } else if suffixArray[i] == bytes.count {
                pointer = (i - 1) / 2
            }
        }
        return (bwt, pointer)
    }

}


//
//  ElloToggleButton.swift
//  Ello
//
//  Created by Tony DiPasquale on 4/13/15.
//  Copyright (c) 2015 Ello. All rights reserved.
//

import UIKit

public class ElloToggleButton: UIButton {
    private let attributes = [NSFontAttributeName: UIFont.typewriterFont(14.0)]

    public var value: Bool = false {
        didSet {
            toggleButton()
        }
    }

    override public func awakeFromNib() {
        super.awakeFromNib()
        layer.borderColor = UIColor.greyA().CGColor
        layer.borderWidth = 1

        setTitleColor(UIColor.greyA(), forState: .Normal)
    }

    public func setText(text: String, color: UIColor = UIColor.greyA()) {
        let string = NSMutableAttributedString(string: text, attributes: attributes)
        string.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location: 0, length: string.length))
        setAttributedTitle(string, forState: .Normal)
    }

    private func toggleButton() {
        backgroundColor = value ? UIColor.greyA() : UIColor.whiteColor()
        setText(value ? "Yes" : "No", color: value ? .whiteColor() : .greyA())
    }
}

Reduce the font size on the toggle button

//
//  ElloToggleButton.swift
//  Ello
//
//  Created by Tony DiPasquale on 4/13/15.
//  Copyright (c) 2015 Ello. All rights reserved.
//

import UIKit

public class ElloToggleButton: UIButton {
    private let attributes = [NSFontAttributeName: UIFont.typewriterFont(12.0)]

    public var value: Bool = false {
        didSet {
            toggleButton()
        }
    }

    override public func awakeFromNib() {
        super.awakeFromNib()
        layer.borderColor = UIColor.greyA().CGColor
        layer.borderWidth = 1

        setTitleColor(UIColor.greyA(), forState: .Normal)
    }

    public func setText(text: String, color: UIColor = UIColor.greyA()) {
        let string = NSMutableAttributedString(string: text, attributes: attributes)
        string.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location: 0, length: string.length))
        setAttributedTitle(string, forState: .Normal)
    }

    private func toggleButton() {
        backgroundColor = value ? UIColor.greyA() : UIColor.whiteColor()
        setText(value ? "Yes" : "No", color: value ? .whiteColor() : .greyA())
    }
}


//
//  FakeMessageSender.swift
//  Runtime
//
//  Created by Paul Young on 05/09/2014.
//  Copyright (c) 2014 CocoaFlow. All rights reserved.
//

import Foundation
import MessageTransfer
import JSONLib

struct FakeMessageSender: MessageSenderWithReceiver {

    typealias Verification = (channel: String, topic: String, payload: JSON) -> Void

    private let verify: Verification
    var messageReceiver: MessageReceiver?

    init(_ verify: Verification = { (channel, topic, payload) in }) {
        self.verify = verify
    }

    func send(channel: String, _ topic: String, _ payload: JSON) {
        self.verify(channel: channel, topic: topic, payload: payload)
    }
}

Update fake message sender for optional payload.

//
//  FakeMessageSender.swift
//  Runtime
//
//  Created by Paul Young on 05/09/2014.
//  Copyright (c) 2014 CocoaFlow. All rights reserved.
//

import Foundation
import MessageTransfer
import JSONLib

struct FakeMessageSender: MessageSenderWithReceiver {

    typealias Verification = (channel: String, topic: String, payload: JSON?) -> Void

    private let verify: Verification
    var messageReceiver: MessageReceiver?

    init(_ verify: Verification = { (channel, topic, payload) in }) {
        self.verify = verify
    }

    func send(channel: String, _ topic: String, _ payload: JSON?) {
        self.verify(channel: channel, topic: topic, payload: payload)
    }
}


import Foundation

public class Mock<Interaction: Equatable> {
    public var interactions: [Interaction] = []

    public init() {}
}

// MARK: - Basics

public func record<Interaction: Equatable>(mock: Mock<Interaction>, interaction: Interaction) {
    mock.interactions.append(interaction)
}

// MARK: - Verification

public func verify<Interaction: Equatable, C: CollectionType where C.Generator.Element == Interaction>(mock: Mock<Interaction>, interactions: C) -> Bool {
    var index = interactions.startIndex
    for interaction in mock.interactions {
        if interaction == interactions[index] {
            index = advance(index, 1)
            if index == interactions.endIndex {
                return true
            }
        }
    }

    return false
}

Verify sequences instead of collections

import Foundation

public class Mock<Interaction: Equatable> {
    public var interactions: [Interaction] = []

    public init() {}
}

// MARK: - Basics

public func record<Interaction: Equatable>(mock: Mock<Interaction>, interaction: Interaction) {
    mock.interactions.append(interaction)
}

// MARK: - Verification

public func verify<Interaction: Equatable, S: SequenceType where S.Generator.Element == Interaction>(mock: Mock<Interaction>, interactions: S) -> Bool {
    var generator = interactions.generate()
    var element = generator.next()

    for interaction in mock.interactions {
        if interaction == element {
            element = generator.next()
        }
    }

    return element == nil
}


// RUN: %target-swift-frontend -enable-experimental-feature BuiltinMacros -dump-ast %s -module-name MacrosTest 2>&1 | %FileCheck %s
// REQUIRES: OS=macosx

// CHECK: macro_expansion_expr implicit type='String'
// CHECK-NEXT: magic_identifier_literal_expr{{.*}}kind=#function
// CHECK-NEXT: string_literal_expr{{.*}}Macro expansion of #function in{{.*}}value="MacrosTest"
print(#function)

func f(a: Int, b: Int) {
  print(#function, #line, #column)
  // CHECK: macro_expansion_expr implicit type='String'
  // CHECK-NEXT: magic_identifier_literal_expr{{.*}}kind=#function
  // CHECK-NEXT: string_literal_expr{{.*}}Macro expansion of #function in{{.*}}value="f(a:b:)"

  // CHECK: macro_expansion_expr implicit type='Int'
  // CHECK-NEXT: magic_identifier_literal_expr{{.*}}kind=#line
  // CHECK-NEXT: integer_literal_expr{{.*}}Macro expansion of #line in{{.*}}value=10

  // CHECK: macro_expansion_expr implicit type='Int'
  // CHECK-NEXT: magic_identifier_literal_expr{{.*}}kind=#column
  // CHECK-NEXT: integer_literal_expr{{.*}}Macro expansion of #column in{{.*}}value=27
}

Enable this test only when assertions are available.

// RUN: %target-swift-frontend -enable-experimental-feature BuiltinMacros -dump-ast %s -module-name MacrosTest 2>&1 | %FileCheck %s
// REQUIRES: OS=macosx
// REQUIRES: asserts

// CHECK: macro_expansion_expr implicit type='String'
// CHECK-NEXT: magic_identifier_literal_expr{{.*}}kind=#function
// CHECK-NEXT: string_literal_expr{{.*}}Macro expansion of #function in{{.*}}value="MacrosTest"
print(#function)

func f(a: Int, b: Int) {
  print(#function, #line, #column)
  // CHECK: macro_expansion_expr implicit type='String'
  // CHECK-NEXT: magic_identifier_literal_expr{{.*}}kind=#function
  // CHECK-NEXT: string_literal_expr{{.*}}Macro expansion of #function in{{.*}}value="f(a:b:)"

  // CHECK: macro_expansion_expr implicit type='Int'
  // CHECK-NEXT: magic_identifier_literal_expr{{.*}}kind=#line
  // CHECK-NEXT: integer_literal_expr{{.*}}Macro expansion of #line in{{.*}}value=10

  // CHECK: macro_expansion_expr implicit type='Int'
  // CHECK-NEXT: magic_identifier_literal_expr{{.*}}kind=#column
  // CHECK-NEXT: integer_literal_expr{{.*}}Macro expansion of #column in{{.*}}value=27
}


// RUN: %target-typecheck-verify-swift

protocol P {
    associatedtype A : P where A.X == Self
    // expected-error@-1{{'X' is not a member type of type 'Self.A'}}
    associatedtype X : P where P.A == Self
    // expected-error@-1{{associated type 'A' can only be used with a concrete type or generic parameter base}}
}

Update error message in validation test.

// RUN: %target-typecheck-verify-swift

protocol P {
    associatedtype A : P where A.X == Self
    // expected-error@-1{{'X' is not a member type of type 'Self.A'}}
    associatedtype X : P where P.A == Self
    // expected-error@-1{{cannot access associated type 'A' from 'P'; use a concrete type or generic parameter base instead}}
}


import Foundation

extension MHomeStrategy
{
    //MARK: private

    private class func strategyMap() -> [MSession.Status:MHomeStrategy.Type]
    {
        let map:[MSession.Status:MHomeStrategy.Type] = [
            MSession.Status.new:MHomeStrategyNew.self,
            MSession.Status.loading:MHomeStrategyLoading.self,
            MSession.Status.sync:MHomeStrategySync.self,
            MSession.Status.authLocation:MHomeStrategyAuthLocation.self,
            MSession.Status.waitingLocation:MHomeStrategyWaitingLocation.self,
            MSession.Status.loaded:MHomeStrategyLoaded.self,
            MSession.Status.ready:MHomeStrategyReady.self]

        return map
    }

    //MARK: internal

    class func factoryStrategy(controller:CHome) -> MHomeStrategy?
    {
         let map:[MSession.Status:MHomeStrategy.Type] = strategyMap()
         let currentStatus:MSession.Status = controller.model.session.status

         guard

             let strategyType:MHomeStrategy.Type = map[currentStatus]

         else
         {
             return nil
         }

         let strategy:MHomeStrategy = strategyType.init(
            controller:controller)

         return strategy
    }
}

Add sync location to factory

import Foundation

extension MHomeStrategy
{
    //MARK: private

    private class func strategyMap() -> [MSession.Status:MHomeStrategy.Type]
    {
        let map:[MSession.Status:MHomeStrategy.Type] = [
            MSession.Status.new:MHomeStrategyNew.self,
            MSession.Status.loading:MHomeStrategyLoading.self,
            MSession.Status.sync:MHomeStrategySync.self,
            MSession.Status.loaded:MHomeStrategyLoaded.self,
            MSession.Status.authLocation:MHomeStrategyAuthLocation.self,
            MSession.Status.waitingLocation:MHomeStrategyWaitingLocation.self,
            MSession.Status.syncLocation:MHomeStrategySyncLocation.self,
            MSession.Status.ready:MHomeStrategyReady.self]

        return map
    }

    //MARK: internal

    class func factoryStrategy(controller:CHome) -> MHomeStrategy?
    {
         let map:[MSession.Status:MHomeStrategy.Type] = strategyMap()
         let currentStatus:MSession.Status = controller.model.session.status

         guard

             let strategyType:MHomeStrategy.Type = map[currentStatus]

         else
         {
             return nil
         }

         let strategy:MHomeStrategy = strategyType.init(
            controller:controller)

         return strategy
    }
}


//
//  QueuedPrint.swift
//  SwiftLint
//
//  Created by JP Simard on 2015-11-17.
//  Copyright © 2015 Realm. All rights reserved.
//

import Foundation

private let outputQueue: dispatch_queue_t = {
    let queue = dispatch_queue_create("io.realm.swiftlint.outputQueue", DISPATCH_QUEUE_SERIAL)
    dispatch_set_target_queue(queue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0))

    atexit_b {
        dispatch_barrier_sync(queue) {}
    }

    return queue
}()

/**
 A thread-safe version of Swift's standard print().

 - parameter object: Object to print.
*/
public func queuedPrint<T>(object: T) {
    dispatch_async(outputQueue) {
        print(object)
    }
}

/**
A thread-safe, newline-terminated version of fputs(..., stderr).

- parameter string: String to print.
*/
public func queuedPrintError(string: String) {
    dispatch_async(outputQueue) {
        fputs(string + "\n", stderr)
    }
}

Add `fflush(stdout)` before `fputs(…, stderr)`

//
//  QueuedPrint.swift
//  SwiftLint
//
//  Created by JP Simard on 2015-11-17.
//  Copyright © 2015 Realm. All rights reserved.
//

import Foundation

private let outputQueue: dispatch_queue_t = {
    let queue = dispatch_queue_create("io.realm.swiftlint.outputQueue", DISPATCH_QUEUE_SERIAL)
    dispatch_set_target_queue(queue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0))

    atexit_b {
        dispatch_barrier_sync(queue) {}
    }

    return queue
}()

/**
 A thread-safe version of Swift's standard print().

 - parameter object: Object to print.
*/
public func queuedPrint<T>(object: T) {
    dispatch_async(outputQueue) {
        print(object)
    }
}

/**
A thread-safe, newline-terminated version of fputs(..., stderr).

- parameter string: String to print.
*/
public func queuedPrintError(string: String) {
    dispatch_async(outputQueue) {
        fflush(stdout)
        fputs(string + "\n", stderr)
    }
}


// Playground - noun: a place where people can play

import UIKit
import DFImageManagerKit
import XCPlayground

var str = "Hello, playground"

let manager = DFImageManager.sharedManager()

let imageURL = NSURL(string: "https://raw.githubusercontent.com/kean/DFImageManager/master/DFImageManager/Tests/Resources/Image.jpg")
manager.requestImageForAsset(imageURL, targetSize: DFImageManagerMaximumSize, contentMode: DFImageContentMode.AspectFit, options: nil) { (image: UIImage!, [NSObject : AnyObject]!) -> Void in
    var fetchedImage = image
}

manager.requestImageForAsset(imageURL, targetSize: CGSize(width: 100, height: 100), contentMode: DFImageContentMode.AspectFit, options: nil) { (image: UIImage!, [NSObject : AnyObject]!) -> Void in
    var fetchedImage = image
}

XCPSetExecutionShouldContinueIndefinitely()

Add Swift-related warning in Playground

// Playground - noun: a place where people can play

import UIKit
import DFImageManagerKit
import XCPlayground

// WARNING: DFImageManager Swift interfaces are automatically generated by Xcode.

let manager = DFImageManager.sharedManager()

let imageURL = NSURL(string: "https://raw.githubusercontent.com/kean/DFImageManager/master/DFImageManager/Tests/Resources/Image.jpg")

// Request fullsize image
manager.requestImageForAsset(imageURL, targetSize: DFImageManagerMaximumSize, contentMode: DFImageContentMode.AspectFit, options: nil) { (image: UIImage!, [NSObject : AnyObject]!) -> Void in
    var fetchedImage = image
}

// Request scaled image
manager.requestImageForAsset(imageURL, targetSize: CGSize(width: 100, height: 100), contentMode: DFImageContentMode.AspectFit, options: nil) { (image: UIImage!, [NSObject : AnyObject]!) -> Void in
    var fetchedImage = image
}

XCPSetExecutionShouldContinueIndefinitely()


//
//  UIViewController.swift
//  SwiftyPress iOS
//
//  Created by Basem Emara on 2018-10-08.
//  Copyright © 2019 Zamzam Inc. All rights reserved.
//

import UIKit
import ZamzamCore
import ZamzamUI

public extension UIViewController {

    /**
     Open Safari view controller overlay.

     - parameter url: URL to display in the browser.
     - parameter theme: The style of the Safari view controller.
     */
    func present(
        safari url: String,
        theme: Theme,
        animated: Bool = true,
        completion: (() -> Void)? = nil
    ) {
        present(
            safari: url,
            barTintColor: theme.backgroundColor,
            preferredControlTintColor: theme.tint,
            animated: animated,
            completion: completion
        )
    }

    /**
     Open Safari view controller overlay.

     - parameter url: URL to display in the browser.
     - parameter theme: The style of the Safari view controller.
     */
    func show(
        safari url: String,
        theme: Theme,
        animated: Bool = true,
        completion: (() -> Void)? = nil
    ) {
        show(
            safari: url,
            barTintColor: theme.backgroundColor,
            preferredControlTintColor: theme.tint,
            animated: animated,
            completion: completion
        )
    }
}

Fix safari controller for iOS 13

//
//  UIViewController.swift
//  SwiftyPress iOS
//
//  Created by Basem Emara on 2018-10-08.
//  Copyright © 2019 Zamzam Inc. All rights reserved.
//

import UIKit
import ZamzamCore
import ZamzamUI

public extension UIViewController {

    /**
     Open Safari view controller overlay.

     - parameter url: URL to display in the browser.
     - parameter theme: The style of the Safari view controller.
     */
    func present(
        safari url: String,
        theme: Theme,
        animated: Bool = true,
        completion: (() -> Void)? = nil
    ) {
        present(
            safari: url,
            barTintColor: theme.backgroundColor,
            preferredControlTintColor: theme.tint,
            animated: animated,
            completion: completion
        )
    }
}