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

final class DescriptionTests: XCTestCase {
	func testOneEmptyBranchProducesUnitType() {
		let UnitDescription: Description = [
			"unit": .End,
		]

		assert(UnitDescription.out, ==, .UnitType)
	}

	func testTwoEmptyBranchesProduceBooleanType() {
		let BooleanDescription: Description = [
			"true": .End,
			"false": .End,
		]

		assert(Term(term: BooleanDescription), ==, Term.lambda(.BooleanType) { .If($0, .UnitType, .UnitType) })
	}

	func testCaseConstruction() {
		assert(NaturalDescription, ==, Description.Argument(.BooleanType) { .If($0, .UnitType, .Argument(.Recursive, id)) })
	}
}

private let NaturalDescription: Description = [
	"zero": .End,
	"successor": .Argument(.Recursive, id),
]

import Assertions
@testable import Manifold
import Prelude
import XCTest

Correct the case construction test.

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

final class DescriptionTests: XCTestCase {
	func testOneEmptyBranchProducesUnitType() {
		let UnitDescription: Description = [
			"unit": .End,
		]

		assert(UnitDescription.out, ==, .UnitType)
	}

	func testTwoEmptyBranchesProduceBooleanType() {
		let BooleanDescription: Description = [
			"true": .End,
			"false": .End,
		]

		assert(Term(term: BooleanDescription), ==, Term.lambda(.BooleanType) { .If($0, .UnitType, .UnitType) })
	}

	func testCaseConstruction() {
		assert(NaturalDescription, ==, Description.Argument(.BooleanType) { .If($0, .End, .Argument(.Recursive, id)) })
	}
}

private let NaturalDescription: Description = [
	"zero": .End,
	"successor": .Argument(.Recursive, id),
]

import Assertions
@testable import Manifold
import Prelude
import XCTest


//
//  Created by Pierluigi Cifani on 16/08/16.
//  Copyright © 2018 TheLeftBit SL. All rights reserved.
//

import UIKit

public extension UIWindow {

    @objc(bsw_visibleViewController)
    public var visibleViewController: UIViewController? {
        return UIWindow.getVisibleViewControllerFrom(self.rootViewController)
    }

    @objc(bsw_getVisibleViewControllerFrom:)
    public static func getVisibleViewControllerFrom(_ vc: UIViewController?) -> UIViewController? {
        if let nc = vc as? UINavigationController {
            return UIWindow.getVisibleViewControllerFrom(nc.visibleViewController)
        } else if let tc = vc as? UITabBarController {
            return UIWindow.getVisibleViewControllerFrom(tc.selectedViewController)
        } else {
            if let pvc = vc?.presentedViewController {
                return UIWindow.getVisibleViewControllerFrom(pvc)
            } else {
                return vc
            }
        }
    }

    @objc(bsw_showErrorMessage:error:)
    public func showErrorMessage(_ message: String, error: Error) {
        guard let rootViewController = self.visibleViewController else { return }
        rootViewController.showErrorMessage(message, error: error)
    }
}

Add a method to transition to a new root vc

//
//  Created by Pierluigi Cifani on 16/08/16.
//  Copyright © 2018 TheLeftBit SL. All rights reserved.
//

import UIKit
import BSWFoundation

public extension UIWindow {

    func transition(toRootViewController rootVC: UIViewController, completion: VoidHandler?) {
        UIView.transition(
            with: self,
            duration: 0.45,
            options: [.transitionCrossDissolve],
            animations: {
                self.rootViewController = rootVC
        },
            completion: { (_) in
                completion?()
        })
    }

    @objc(bsw_visibleViewController)
    public var visibleViewController: UIViewController? {
        return UIWindow.getVisibleViewControllerFrom(self.rootViewController)
    }

    @objc(bsw_getVisibleViewControllerFrom:)
    public static func getVisibleViewControllerFrom(_ vc: UIViewController?) -> UIViewController? {
        if let nc = vc as? UINavigationController {
            return UIWindow.getVisibleViewControllerFrom(nc.visibleViewController)
        } else if let tc = vc as? UITabBarController {
            return UIWindow.getVisibleViewControllerFrom(tc.selectedViewController)
        } else {
            if let pvc = vc?.presentedViewController {
                return UIWindow.getVisibleViewControllerFrom(pvc)
            } else {
                return vc
            }
        }
    }

    @objc(bsw_showErrorMessage:error:)
    public func showErrorMessage(_ message: String, error: Error) {
        guard let rootViewController = self.visibleViewController else { return }
        rootViewController.showErrorMessage(message, error: error)
    }
}


//
//  SwiftIconFont+UIBarButtonItem.swift
//  SwiftIconFont
//
//  Created by Sedat Gökbek ÇİFTÇİ on 13.10.2017.
//  Copyright © 2017 Sedat Gökbek ÇİFTÇİ. All rights reserved.
//

import UIKit

public extension UIBarButtonItem {
    func icon(from font: Fonts, code: String, ofSize size: CGFloat){
        var textAttributes: [NSAttributedStringKey: AnyObject] = [NSAttributedStringKey.font: UIFont.icon(from: font, ofSize: size)]
        let currentTextAttributes: [String: AnyObject]? = self.titleTextAttributes(for: UIControlState()) as [String : AnyObject]?

        if currentTextAttributes != nil {
            for (rawKey, value) in currentTextAttributes! {
                let key = NSAttributedStringKey.init(rawKey)
                if key != NSAttributedStringKey.font {
                    textAttributes[key] = value
                }
            }
        }
        self.setTitleTextAttributes(textAttributes, for: UIControlState.normal)
        self.setTitleTextAttributes(textAttributes, for: UIControlState.highlighted)

        self.title = String.getIcon(from: font, code: code)
    }
}

Set TitleTextAttributes for disabled BarButtonItem

//
//  SwiftIconFont+UIBarButtonItem.swift
//  SwiftIconFont
//
//  Created by Sedat Gökbek ÇİFTÇİ on 13.10.2017.
//  Copyright © 2017 Sedat Gökbek ÇİFTÇİ. All rights reserved.
//

import UIKit

public extension UIBarButtonItem {
    func icon(from font: Fonts, code: String, ofSize size: CGFloat){
        var textAttributes: [NSAttributedStringKey: AnyObject] = [NSAttributedStringKey.font: UIFont.icon(from: font, ofSize: size)]
        let currentTextAttributes: [String: AnyObject]? = self.titleTextAttributes(for: UIControlState()) as [String : AnyObject]?

        if currentTextAttributes != nil {
            for (rawKey, value) in currentTextAttributes! {
                let key = NSAttributedStringKey.init(rawKey)
                if key != NSAttributedStringKey.font {
                    textAttributes[key] = value
                }
            }
        }
        self.setTitleTextAttributes(textAttributes, for: UIControlState.normal)
        self.setTitleTextAttributes(textAttributes, for: UIControlState.highlighted)
        self.setTitleTextAttributes(textAttributes, for: UIControlState.disabled)

        self.title = String.getIcon(from: font, code: code)
    }
}


//
//  FolderTreeControllerDelegate.swift
//  NetNewsWire
//
//  Created by Brent Simmons on 8/10/16.
//  Copyright © 2016 Ranchero Software, LLC. All rights reserved.
//

import Foundation
import RSCore
import RSTree
import Articles
import Account

final class FolderTreeControllerDelegate: TreeControllerDelegate {

	func treeController(treeController: TreeController, childNodesFor node: Node) -> [Node]? {

		return node.isRoot ? childNodesForRootNode(node) : childNodes(node)
	}
}

private extension FolderTreeControllerDelegate {

	func childNodesForRootNode(_ node: Node) -> [Node]? {

		let accountNodes: [Node] = AccountManager.shared.activeAccounts.map { account in
			let accountNode = Node(representedObject: account, parent: node)
			accountNode.canHaveChildNodes = true
			return accountNode
		}
		return accountNodes.sortedAlphabetically()

	}

	func childNodes(_ node: Node) -> [Node]? {

		guard let account = node.representedObject as? Account, let folders = account.folders else {
			return nil
		}

		let folderNodes: [Node] = folders.map { createNode($0, parent: node) }
		return folderNodes.sortedAlphabetically()

	}

	func createNode(_ folder: Folder, parent: Node) -> Node {
		let node = Node(representedObject: folder, parent: parent)
		node.canHaveChildNodes = false
		return node
	}

}

Put folder pop up menu for add feed in the correct order

//
//  FolderTreeControllerDelegate.swift
//  NetNewsWire
//
//  Created by Brent Simmons on 8/10/16.
//  Copyright © 2016 Ranchero Software, LLC. All rights reserved.
//

import Foundation
import RSCore
import RSTree
import Articles
import Account

final class FolderTreeControllerDelegate: TreeControllerDelegate {

	func treeController(treeController: TreeController, childNodesFor node: Node) -> [Node]? {

		return node.isRoot ? childNodesForRootNode(node) : childNodes(node)
	}
}

private extension FolderTreeControllerDelegate {

	func childNodesForRootNode(_ node: Node) -> [Node]? {

		let accountNodes: [Node] = AccountManager.shared.sortedActiveAccounts.map { account in
			let accountNode = Node(representedObject: account, parent: node)
			accountNode.canHaveChildNodes = true
			return accountNode
		}
		return accountNodes

	}

	func childNodes(_ node: Node) -> [Node]? {

		guard let account = node.representedObject as? Account, let folders = account.folders else {
			return nil
		}

		let folderNodes: [Node] = folders.map { createNode($0, parent: node) }
		return folderNodes.sortedAlphabetically()

	}

	func createNode(_ folder: Folder, parent: Node) -> Node {
		let node = Node(representedObject: folder, parent: parent)
		node.canHaveChildNodes = false
		return node
	}

}


// swift-tools-version:5.0
import PackageDescription

let package = Package(
  name: "ZeeQL3",

  products: [ // TBD: Use ZeeQL3 as library name?
    .library(name: "ZeeQL", targets: [ "ZeeQL" ])
  ],
  dependencies: [
    .package(url: "https://github.com/ZeeQL/CSQLite3.git",
             from: "2.0.0")
  ],
  targets: [
    .target(name: "ZeeQL"),
    .testTarget(name: "ZeeQLTests", dependencies: [ "ZeeQL" ])
  ]
)

Add proper deps on CSQlite3

// swift-tools-version:5.0
import PackageDescription

let package = Package(
  name: "ZeeQL3",

  products: [ // TBD: Use ZeeQL3 as library name?
    .library(name: "ZeeQL", targets: [ "ZeeQL" ])
  ],
  dependencies: [
    .package(url: "https://github.com/ZeeQL/CSQLite3.git",
             from: "2.0.0")
  ],
  targets: [
    .target(name: "ZeeQL"),
    .testTarget(name: "ZeeQLTests", dependencies: [ "ZeeQL", "CSQLite3" ])
  ]
)


//
//  PostPhotoCache.swift
//  Highball
//
//  Created by Ian Ynda-Hummel on 1/18/15.
//  Copyright (c) 2015 ianynda. All rights reserved.
//

import Foundation

struct AnimatedImageCache {
    private static var animatedImageCache = Dictionary<String, FLAnimatedImage>()

    static func setAnimatedImage(animatedImage: FLAnimatedImage, forKey key: String) {
        self.animatedImageCache[key] = animatedImage
    }

    static func animatedImageForKey(key: String) -> FLAnimatedImage? {
        return self.animatedImageCache[key]
    }
}

Use NSCache for gif cache

//
//  PostPhotoCache.swift
//  Highball
//
//  Created by Ian Ynda-Hummel on 1/18/15.
//  Copyright (c) 2015 ianynda. All rights reserved.
//

import Foundation

struct AnimatedImageCache {
    private static var animatedImageCache = NSCache()

    static func setAnimatedImage(animatedImage: FLAnimatedImage, forKey key: String) {
        self.animatedImageCache.setObject(animatedImage, forKey: key)
    }

    static func animatedImageForKey(key: String) -> FLAnimatedImage? {
        return self.animatedImageCache.objectForKey(key) as? FLAnimatedImage
    }
}


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

final class LocationTests: XCTestCase {
	func testTraversingAnExpressionReturnsALocationAtTheTraversedExpression() {
		assert(identity.explore().it, ==, identity)
	}

	func testTopLevelNodesHaveNoParents() {
		assert(Expression<Term>.Unit.explore().up?.it, ==, nil)
	}

	func testTopLevelNodesHaveNoSiblings() {
		assert(Expression<Term>.Unit.explore().left?.it, ==, nil)
		assert(Expression<Term>.Unit.explore().right?.it, ==, nil)
	}

	func testNullaryNodesHaveNoChildren() {
		assert(Expression<Term>.Unit.explore().down?.it, ==, nil)
	}
}

import Assertions
@testable import Manifold
import XCTest

Test deep navigation into an Expression.

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

final class LocationTests: XCTestCase {
	func testTraversingAnExpressionReturnsALocationAtTheTraversedExpression() {
		assert(identity.explore().it, ==, identity)
	}

	func testTopLevelNodesHaveNoParents() {
		assert(Expression<Term>.Unit.explore().up?.it, ==, nil)
	}

	func testTopLevelNodesHaveNoSiblings() {
		assert(Expression<Term>.Unit.explore().left?.it, ==, nil)
		assert(Expression<Term>.Unit.explore().right?.it, ==, nil)
	}

	func testNullaryNodesHaveNoChildren() {
		assert(Expression<Term>.Unit.explore().down?.it, ==, nil)
	}

	func testDeepNavigationExploresChildrenOfChildrenRecursively() {
		assert(identity.explore().down?.right?.down?.right?.it, ==, .Variable(.Local(0)))
	}
}

import Assertions
@testable import Manifold
import XCTest


//
//  gcd.swift
//  SignificantSpices
//
//  Created by Jan Nash on 8/15/17.
//  Copyright © 2017 resmio. All rights reserved.
//

// MARK: // Public
// MARK: SignedInteger Version
public func gcd<T: SignedInteger>(_ m: T, _ n: T) -> T {
    return _gcd(abs(m), n)
}

// MARK: UnsignedInteger Version
public func gcd<T: UnsignedInteger>(_ m: T, _ n: T) -> T {
    return _gcd(m, n)
}

// MARK: // Private
private func _gcd<T: BinaryInteger>(_ m: T, _ n: T) -> T {
    guard m != 0 && n != 0 else {
        return m + n
    }

    func __gcd(_ m: T, _ n: T) -> T {
        return m % n == 0 ? n : __gcd(n, m % n)
    }

    return __gcd(m, n)
}

Remove obsolete && from guard statement

//
//  gcd.swift
//  SignificantSpices
//
//  Created by Jan Nash on 8/15/17.
//  Copyright © 2017 resmio. All rights reserved.
//

// MARK: // Public
// MARK: SignedInteger Version
public func gcd<T: SignedInteger>(_ m: T, _ n: T) -> T {
    return _gcd(abs(m), n)
}

// MARK: UnsignedInteger Version
public func gcd<T: UnsignedInteger>(_ m: T, _ n: T) -> T {
    return _gcd(m, n)
}

// MARK: // Private
private func _gcd<T: BinaryInteger>(_ m: T, _ n: T) -> T {
    guard m != 0, n != 0 else {
        return m + n
    }

    func __gcd(_ m: T, _ n: T) -> T {
        return m % n == 0 ? n : __gcd(n, m % n)
    }

    return __gcd(m, n)
}


//
//  Environment.swift
//  breadwallet
//
//  Created by Adrian Corscadden on 2017-06-20.
//  Copyright © 2017 breadwallet LLC. All rights reserved.
//

import UIKit

struct E {
    static let isTestnet: Bool = {
        #if Testnet
            return true
        #else
            return false
        #endif
    }()
    static let isTestFlight: Bool = {
        #if Testflight
            return true
        #else
            return false
        #endif
    }()
    static let isSimulator: Bool = {
        #if arch(i386) || arch(x86_64)
            return true
        #else
            return false
        #endif
    }()
    static let isDebug: Bool = {
        #if Debug
            return true
        #else
            return false
        #endif
    }()
    static let isScreenshots: Bool = {
        #if Screenshots
            return true
        #else
            return false
        #endif
    }()
    static let isIPhone4: Bool = {
        return UIApplication.shared.keyWindow?.bounds.height == 480.0
    }()
    static let isIPhone5: Bool = {
        return (UIApplication.shared.keyWindow?.bounds.height == 568.0) && (E.is32Bit)
    }()
    static let is32Bit: Bool = {
        return MemoryLayout<Int>.size == MemoryLayout<UInt32>.size
    }()
}

Fix isIPhone4 getting initialized to nil on ipad

//
//  Environment.swift
//  breadwallet
//
//  Created by Adrian Corscadden on 2017-06-20.
//  Copyright © 2017 breadwallet LLC. All rights reserved.
//

import UIKit

struct E {
    static let isTestnet: Bool = {
        #if Testnet
            return true
        #else
            return false
        #endif
    }()
    static let isTestFlight: Bool = {
        #if Testflight
            return true
        #else
            return false
        #endif
    }()
    static let isSimulator: Bool = {
        #if arch(i386) || arch(x86_64)
            return true
        #else
            return false
        #endif
    }()
    static let isDebug: Bool = {
        #if Debug
            return true
        #else
            return false
        #endif
    }()
    static let isScreenshots: Bool = {
        #if Screenshots
            return true
        #else
            return false
        #endif
    }()
    static var isIPhone4: Bool {
        return UIApplication.shared.keyWindow?.bounds.height == 480.0
    }
    static var isIPhone5: Bool {
        return (UIApplication.shared.keyWindow?.bounds.height == 568.0) && (E.is32Bit)
    }
    static let is32Bit: Bool = {
        return MemoryLayout<Int>.size == MemoryLayout<UInt32>.size
    }()
}


// swift-tools-version:5.2

import PackageDescription

let pkgName = "gir2swift"
let libTarget = "lib\(pkgName)"

let package = Package(
    name: pkgName,
    products: [
        .executable(name: pkgName, targets: [pkgName]),
        .library(name: libTarget, targets: [libTarget]),
    ],
    dependencies: [
        .package(url: "https://github.com/rhx/SwiftLibXML.git", .branch("manual")),
        .package(url: "https://github.com/apple/swift-argument-parser", from: "0.4.0")
    ],
    targets: [
        .target(
            name: pkgName,
            dependencies: [
                .init(stringLiteral: libTarget)
            ]
        ),
        .target(
            name: libTarget,
            dependencies: [
                .init(stringLiteral: "SwiftLibXML"),
                .product(name: "ArgumentParser", package: "swift-argument-parser")
            ]
        ),
        .testTarget(name: "\(pkgName)Tests", dependencies: [.init(stringLiteral: libTarget)]),
    ]
)

Revert back to main branch of SwiftLibXML

// swift-tools-version:5.2

import PackageDescription

let pkgName = "gir2swift"
let libTarget = "lib\(pkgName)"

let package = Package(
    name: pkgName,
    products: [
        .executable(name: pkgName, targets: [pkgName]),
        .library(name: libTarget, targets: [libTarget]),
    ],
    dependencies: [
        .package(url: "https://github.com/rhx/SwiftLibXML.git", .branch("main")),
        .package(url: "https://github.com/apple/swift-argument-parser", from: "0.4.0")
    ],
    targets: [
        .target(
            name: pkgName,
            dependencies: [
                .init(stringLiteral: libTarget)
            ]
        ),
        .target(
            name: libTarget,
            dependencies: [
                .init(stringLiteral: "SwiftLibXML"),
                .product(name: "ArgumentParser", package: "swift-argument-parser")
            ]
        ),
        .testTarget(name: "\(pkgName)Tests", dependencies: [.init(stringLiteral: libTarget)]),
    ]
)


// swift-tools-version:5.0
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription
import class Foundation.ProcessInfo

let shouldTest = ProcessInfo.processInfo.environment["TEST"] == "1"

func resolveDependencies() -> [Package.Dependency] {
    guard shouldTest else { return [] }

    return [
        .package(url: "https://github.com/Quick/Quick.git", .upToNextMajor(from: "2.0.0")),
        .package(url: "https://github.com/Quick/Nimble.git", .upToNextMajor(from: "8.0.0")),
    ]
}

func resolveTargets() -> [Target] {
    let baseTarget = Target.target(name: "SwiftyUserDefaults", dependencies: [], path: "Sources")
    let testTarget = Target.testTarget(name: "SwiftyUserDefaultsTests", dependencies: ["SwiftyUserDefaults", "Quick", "Nimble"])

    return shouldTest ? [baseTarget, testTarget] : [baseTarget]
}

let package = Package(
    name: "SwiftyUserDefaults",
    platforms: [
        .macOS(.v10_11), .iOS(.v8), .tvOS(.v9), .watchOS(.v2)
    ],
    products: [
        .library(
            name: "SwiftyUserDefaults",
            targets: ["SwiftyUserDefaults"]),
    ],
    dependencies: resolveDependencies(),
    targets: resolveTargets(),
)

Fix parsing the SPM manifest

// swift-tools-version:5.0
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription
import class Foundation.ProcessInfo

let shouldTest = ProcessInfo.processInfo.environment["TEST"] == "1"

func resolveDependencies() -> [Package.Dependency] {
    guard shouldTest else { return [] }

    return [
        .package(url: "https://github.com/Quick/Quick.git", .upToNextMajor(from: "2.0.0")),
        .package(url: "https://github.com/Quick/Nimble.git", .upToNextMajor(from: "8.0.0")),
    ]
}

func resolveTargets() -> [Target] {
    let baseTarget = Target.target(name: "SwiftyUserDefaults", dependencies: [], path: "Sources")
    let testTarget = Target.testTarget(name: "SwiftyUserDefaultsTests", dependencies: ["SwiftyUserDefaults", "Quick", "Nimble"])

    return shouldTest ? [baseTarget, testTarget] : [baseTarget]
}

let package = Package(
    name: "SwiftyUserDefaults",
    platforms: [
        .macOS(.v10_11), .iOS(.v8), .tvOS(.v9), .watchOS(.v2)
    ],
    products: [
        .library(
            name: "SwiftyUserDefaults",
            targets: ["SwiftyUserDefaults"]),
    ],
    dependencies: resolveDependencies(),
    targets: resolveTargets()
)


// Copyright © 2020 Itty Bitty Apps. All rights reserved.

import UIKit

final class NewDataSource<Model: Decodable, Cell: UITableViewCell>: NSObject, UITableViewDataSource {
  typealias Models = [[Model]]
  typealias CellConfigurator = (Cell, _ object: Model) -> Void

  // MARK: - Properties
  private let data: Models
  private let cellIdentifier: String
  private let configureCell: CellConfigurator

  // MARK: - Init
  required init(collection: Models, cellIdentifier: String, configureCell: @escaping CellConfigurator) {
    self.data = collection
    self.cellIdentifier = cellIdentifier
    self.configureCell = configureCell

    super.init()
  }

  // MARK: UITableViewDataSource

  func numberOfSections(in tableView: UITableView) -> Int {
    return data.count
  }

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return data[section].count
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? Cell else {
      fatalError("Expecting to dequeue a `\(Cell.self)` from the tableView")
    }

    self.configureCell(cell, data[indexPath.section][indexPath.row])
    return cell
  }
}

Add description of the new custom data source class

// Copyright © 2020 Itty Bitty Apps. All rights reserved.

import UIKit

/// The purpose of this class is to eventually the current custom data source class (`DataSource`). The existing custom class is more complex and incompatible with models that extend `Decodable`.
final class NewDataSource<Model: Decodable, Cell: UITableViewCell>: NSObject, UITableViewDataSource {
  typealias Models = [[Model]]
  typealias CellConfigurator = (Cell, _ object: Model) -> Void

  // MARK: - Properties
  private let data: Models
  private let cellIdentifier: String
  private let configureCell: CellConfigurator

  // MARK: - Init
  required init(collection: Models, cellIdentifier: String, configureCell: @escaping CellConfigurator) {
    self.data = collection
    self.cellIdentifier = cellIdentifier
    self.configureCell = configureCell

    super.init()
  }

  // MARK: UITableViewDataSource

  func numberOfSections(in tableView: UITableView) -> Int {
    return data.count
  }

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return data[section].count
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? Cell else {
      fatalError("Expecting to dequeue a `\(Cell.self)` from the tableView")
    }

    self.configureCell(cell, data[indexPath.section][indexPath.row])
    return cell
  }
}


import UIKit
import SpriteKit

class GameViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func prefersStatusBarHidden() -> Bool {
        return true
    }
}

Create the new GameScene in the controller

import UIKit
import SpriteKit

class GameViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Configure the view.
        let skView = view as SKView
        skView.multipleTouchEnabled = false

        // Create and configure the scene.
        var scene = GameScene(size: skView.bounds.size)
        scene.scaleMode = .AspectFill

        // Present the scene.
        skView.presentScene(scene)
    }

    override func prefersStatusBarHidden() -> Bool {
        return true
    }
}


public class JSONDecoder {

    let json: JSON

    public init(json: JSON) {
        self.json = json
    }

    public init(jsonString: String) {
        json = JSON.jsonWithJSONString(jsonString)
    }

    public func readValue<T: FromJSON>(key: String) -> T? {
        if let value = json.object?[key] {
            return T.fromJSON(value)
        }

        return nil
    }

    public func readArray<T: FromJSON>(key: String) -> [T]? {
        if let value = json.object?[key] {
            switch value {
            case let .Array(array):
                var result = [T]()
                for item in array {
                    if let item = T.fromJSON(item) { result.append(item) }
                }
                return result
            default:
                return nil
            }
        }

        return nil
    }

    public func readDictionary<V: FromJSON>(key: String) -> [String: V]? {
        if let value = json.object?[key] {
            switch value {
            case let .Object(object):
                var result = Dictionary<String, V>()
                for (key, item) in object {
                    if let value = V.fromJSON(item) {
                        result[key as String] = value
                    }
                }
                return result
            default:
                return nil
            }
        }

        return nil
    }
}

Use stack based approach for JSONDecoder to increase decoder reusability

public class JSONDecoder {
    let json: JSON
    var stack: [JSON]

    public init(json: JSON) {
        self.json = json
        stack = [json]
    }

    public init(jsonString: String) {
        json = JSON.jsonWithJSONString(jsonString)
        stack = [json]
    }

    public func pop() -> JSON {
        return stack[stack.endIndex]
    }

    public func readValue<T: JSONDecodable>(key: String) -> T? {
        if let value = json.object?[key] {
            stack.append(value)
            return T.decode(self)
        }

        return nil
    }

    public func readArray<T: JSONDecodable>(key: String) -> [T]? {
        if let value = json.object?[key] {
            switch value {
            case let .Array(array):
                var result = [T]()
                for item in array {
                    stack.append(value)
                    if let item = T.decode(self) { result.append(item) }
                }
                return result
            default:
                return nil
            }
        }

        return nil
    }

    public func readDictionary<V: JSONDecodable>(key: String) -> [String: V]? {
        if let value = json.object?[key] {
            switch value {
            case let .Object(object):
                var result = Dictionary<String, V>()
                for (key, item) in object {
                    stack.append(item)
                    if let value = V.decode(self) {
                        result[key as String] = value
                    }
                }
                return result
            default:
                return nil
            }
        }

        return nil
    }
}


//
//  FutureDebugTests.swift
//  BrightFutures
//
//  Created by Oleksii on 23/09/2016.
//  Copyright © 2016 Thomas Visser. All rights reserved.
//

import XCTest
@testable import BrightFutures

class TestLogger: LoggerType {
    var lastLoggedMessage: String?

    func log(message: String) {
        lastLoggedMessage = message
    }
}

class FutureDebugTests: XCTestCase {

    func testStringLastPathComponent() {
        XCTAssertEqual("/tmp/scratch.tiff".lastPathComponent, "scratch.tiff")
        XCTAssertEqual("/tmp/scratch".lastPathComponent, "scratch")
        XCTAssertEqual("/tmp/".lastPathComponent, "tmp")
        XCTAssertEqual("scratch///".lastPathComponent, "scratch")
        XCTAssertEqual("/".lastPathComponent, "/")
    }

}

Cover with tests logging successful future with identifier

//
//  FutureDebugTests.swift
//  BrightFutures
//
//  Created by Oleksii on 23/09/2016.
//  Copyright © 2016 Thomas Visser. All rights reserved.
//

import XCTest
import Result
@testable import BrightFutures

class TestLogger: LoggerType {
    var lastLoggedMessage: String?

    func log(message: String) {
        lastLoggedMessage = message
    }
}

class FutureDebugTests: XCTestCase {
    let testIdentifier = "testFutureIdentifier"

    func testStringLastPathComponent() {
        XCTAssertEqual("/tmp/scratch.tiff".lastPathComponent, "scratch.tiff")
        XCTAssertEqual("/tmp/scratch".lastPathComponent, "scratch")
        XCTAssertEqual("/tmp/".lastPathComponent, "tmp")
        XCTAssertEqual("scratch///".lastPathComponent, "scratch")
        XCTAssertEqual("/".lastPathComponent, "/")
    }

    func testDebugFutureSuccessWithIdentifier() {
        let logger = TestLogger()

        let f = Future<Void, NoError>(value: ()).debug(testIdentifier, logger: logger)
        let debugExpectation = self.expectation(description: "debugLogged")

        f.onSuccess {
            XCTAssertEqual(logger.lastLoggedMessage, "Future \(self.testIdentifier) succeeded")
            debugExpectation.fulfill()
        }

        self.waitForExpectations(timeout: 2, handler: nil)
    }
}


// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// REQUIRES: OS=linux-gnu
// RUN: not --crash %target-swift-frontend %s -emit-ir
_&[i
-{$0

Disable compiler_crashes/28555... because it only crashes intermittently.

// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// FIXME: Disabled. This test does not always crash, which confuses CI.
// REQUIRES: y-u-not-crash-always

// REQUIRES: OS=linux-gnu
// RUN: not --crash %target-swift-frontend %s -emit-ir
_&[i
-{$0


import HandySwift

Add times method content to usage examples playground

import HandySwift

// MARK: -  IntegerTypeExtension

// .times method

//
// `n.times{ someCode }` – Calls someCode n times.
//
var array: [String] = []

3.times{ array.append("Hello World!") }
array

array = []
3.times{ array.append("Hello World #\($0)!") }
array


// main.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
func dofoo<T>(var x: T) {
  print("x") // break here
}

func main() {
  dofoo(1)
  dofoo("hi")
  dofoo(5)
}

main()

Fix another test case build failure due to outlawing var in func arguments.

// main.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
func dofoo<T>(x: T) {
  print("x") // break here
}

func main() {
  dofoo(1)
  dofoo("hi")
  dofoo(5)
}

main()


//
//  ProfileAPI.swift
//  FeedlyKit
//
//  Created by Hiroki Kumamoto on 1/20/15.
//  Copyright (c) 2015 Hiroki Kumamoto. All rights reserved.
//

import Alamofire
import SwiftyJSON

extension CloudAPIClient {
    /**
        Get the profile of the user
        GET /v3/profile
    */
    public func fetchProfile(completionHandler: (Response<Profile, NSError>) -> Void) -> Request {
        return manager.request(Router.FetchProfile(target)).validate().responseObject(completionHandler)
    }

    /**
        Update the profile of the user
        POST /v3/profile
    */
    public func updateProfile(params: [String:String], completionHandler: (Response<Profile, NSError>) -> Void) -> Request {
        return manager.request(Router.UpdateProfile(target, params)).validate().responseObject(completionHandler)
    }
}

Change parameter type of updateProfile: [String:String] to

//
//  ProfileAPI.swift
//  FeedlyKit
//
//  Created by Hiroki Kumamoto on 1/20/15.
//  Copyright (c) 2015 Hiroki Kumamoto. All rights reserved.
//

import Alamofire
import SwiftyJSON

extension CloudAPIClient {
    /**
        Get the profile of the user
        GET /v3/profile
    */
    public func fetchProfile(completionHandler: (Response<Profile, NSError>) -> Void) -> Request {
        return manager.request(Router.FetchProfile(target)).validate().responseObject(completionHandler)
    }

    /**
        Update the profile of the user
        POST /v3/profile
    */
    public func updateProfile(params: [String:AnyObject], completionHandler: (Response<Profile, NSError>) -> Void) -> Request {
        return manager.request(Router.UpdateProfile(target, params)).validate().responseObject(completionHandler)
    }
}


//
//  KeyboardAction+Deprecated.swift
//  KeyboardKit
//
//  Created by Daniel Saidi on 2020-05-05.
//  Copyright © 2020 Daniel Saidi. All rights reserved.
//

import UIKit

public extension KeyboardAction {

    @available(*, deprecated, renamed: "nextKeyboard")
    static var switchKeyboard: KeyboardAction { .nextKeyboard }

    @available(*, deprecated, renamed: "keyboardType")
    static func switchToKeyboard(_ type: KeyboardType) -> KeyboardAction { .keyboardType(type) }

    @available(*, deprecated, renamed: "standardTapAction")
    var standardInputViewControllerAction: ((KeyboardInputViewController?) -> Void)? {
        standardTapAction
    }

    @available(*, deprecated, renamed: "standardTapAction")
    var standardTextDocumentProxyAction: ((UITextDocumentProxy?) -> Void)? {
        switch self {
        case .backspace: return { $0?.deleteBackward() }
        case .character(let char): return { $0?.insertText(char) }
        case .moveCursorBackward: return { $0?.adjustTextPosition(byCharacterOffset: -1) }
        case .moveCursorForward: return { $0?.adjustTextPosition(byCharacterOffset: 1) }
        case .newLine: return { $0?.insertText("\n") }
        case .space: return { $0?.insertText(" ") }
        case .tab: return { $0?.insertText("\t") }
        default: return nil
        }
    }
}

Make deprecated functions call the new ones

//
//  KeyboardAction+Deprecated.swift
//  KeyboardKit
//
//  Created by Daniel Saidi on 2020-05-05.
//  Copyright © 2020 Daniel Saidi. All rights reserved.
//

import UIKit

public extension KeyboardAction {

    @available(*, deprecated, renamed: "nextKeyboard")
    static var switchKeyboard: KeyboardAction { .nextKeyboard }

    @available(*, deprecated, renamed: "keyboardType")
    static func switchToKeyboard(_ type: KeyboardType) -> KeyboardAction { .keyboardType(type) }

    @available(*, deprecated, renamed: "standardTapActionForController")
    var standardInputViewControllerAction: ((KeyboardInputViewController?) -> Void)? {
        standardTapActionForController
    }

    @available(*, deprecated, renamed: "standardTapActionForProxy")
    var standardTextDocumentProxyAction: ((UITextDocumentProxy?) -> Void)? {
        standardTapActionForProxy
    }
}


//
//  AppDelegate.swift
//  Dictate Assist
//
//  Created by Kyle Carson on 9/1/15.
//  Copyright © 2015 Kyle Carson. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

	func applicationDidFinishLaunching(aNotification: NSNotification)
	{
		NSApp.servicesProvider = DictaterService()

		if !Dictater.hasBeenUsed
		{
			self.openHowToUseWindow()
		}

		let args = NSProcessInfo.processInfo().arguments
		var skip = false

		for arg in args[ 1 ..< args.count ]
		{
			if skip
			{
				skip = false
				continue
			}

			if arg.hasPrefix("-")
			{
				skip = true
				continue
			}

			Speech.sharedSpeech.speak( arg )
			break
		}
	}

	func applicationWillTerminate(aNotification: NSNotification) {
		// Insert code here to tear down your application
	}

	var howToUseController : NSWindowController?

	func openHowToUseWindow()
	{
		if let sb = NSApplication.sharedApplication().windows.first?.windowController?.storyboard,
		let controller = sb.instantiateControllerWithIdentifier("howToUse") as? NSWindowController
		{
			controller.showWindow(self)
			self.howToUseController = controller
		}
	}
}

Move window forward on launch

//
//  AppDelegate.swift
//  Dictate Assist
//
//  Created by Kyle Carson on 9/1/15.
//  Copyright © 2015 Kyle Carson. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

	func applicationDidFinishLaunching(aNotification: NSNotification)
	{
		NSApp.servicesProvider = DictaterService()

		if !Dictater.hasBeenUsed
		{
			self.openHowToUseWindow()
		}

		let args = NSProcessInfo.processInfo().arguments
		var skip = false

		for arg in args[ 1 ..< args.count ]
		{
			if skip
			{
				skip = false
				continue
			}

			if arg.hasPrefix("-")
			{
				skip = true
				continue
			}

			Speech.sharedSpeech.speak( arg )
			break
		}
	}

	func applicationWillTerminate(aNotification: NSNotification) {
		// Insert code here to tear down your application
	}

	var howToUseController : NSWindowController?

	func openHowToUseWindow()
	{
		if let sb = NSApplication.sharedApplication().windows.first?.windowController?.storyboard,
		let controller = sb.instantiateControllerWithIdentifier("howToUse") as? NSWindowController
		{
			controller.showWindow(self)
			self.howToUseController = controller
			controller.window?.becomeKeyWindow()
			controller.window?.becomeMainWindow()
		}
	}
}


//
//  Placement+Records.swift
//  AdButler
//
//  Created by Ryuichi Saito on 11/20/16.
//  Copyright © 2016 AdButler. All rights reserved.
//

import Foundation

public extension Placement {
    public func recordImpression() {
        if let accupixelUrl = self.accupixelUrl.map({ URL(string: $0) }), let url = accupixelUrl {
            AdButler.requestPixel(with: url)
        } else if let trackingPixel = self.trackingPixel.map({ URL(string: $0) }), let url = trackingPixel {
            AdButler.requestPixel(with: url)
        } else {
            print("Cannot construct a valid impression URL.")
        }
    }

    public func recordClick() {
        if let redirectUrl = self.redirectUrl.map({ URL(string: $0) }), let url = redirectUrl {
            AdButler.requestPixel(with: url)
        } else {
            print("Cannot construct a valid redirect URL.")
        }
    }
}

Use flatMap to avoid nested Optional types

//
//  Placement+Records.swift
//  AdButler
//
//  Created by Ryuichi Saito on 11/20/16.
//  Copyright © 2016 AdButler. All rights reserved.
//

import Foundation

public extension Placement {
    public func recordImpression() {
        if let accupixelUrl = self.accupixelUrl.flatMap({ URL(string: $0) }) {
            AdButler.requestPixel(with: accupixelUrl)
        } else if let trackingPixel = self.trackingPixel.flatMap({ URL(string: $0) }) {
            AdButler.requestPixel(with: trackingPixel)
        } else {
            print("Cannot construct a valid impression URL.")
        }
    }

    public func recordClick() {
        if let redirectUrl = self.redirectUrl.flatMap({ URL(string: $0) }) {
            AdButler.requestPixel(with: redirectUrl)
        } else {
            print("Cannot construct a valid redirect URL.")
        }
    }
}


//
//  ContextManager.swift
//  OctoPhone
//
//  Created by Josef Dolezal on 19/11/16.
//  Copyright © 2016 Josef Dolezal. All rights reserved.
//

import Foundation
import RealmSwift

/// Database connections manager
protocol ContextManagerType: class {
    /// Creates new connection to the database on specific thread
    ///
    /// - Returns: New database connection
    /// - Throws: RealmError
    func createContext() throws -> Realm
}

/// Preconfigured local database manager
final class ContextManager: ContextManagerType {
    public func createContext() throws -> Realm {
        var configuration = Realm.Configuration.defaultConfiguration

        configuration.deleteRealmIfMigrationNeeded = true

        return try Realm(configuration: configuration)
    }
}

/// In memory database manager - for test purposes
final class InMemoryContextManager: ContextManagerType {

    /// In memory realm identifier
    private let currentIdentifier: String

    init() {
        currentIdentifier = UUID().uuidString
    }

    public func createContext() throws -> Realm {
        var configuration = Realm.Configuration.defaultConfiguration

        configuration.inMemoryIdentifier = currentIdentifier

        return try Realm(configuration: configuration)
    }
}

Add reactive extension for context manager

//
//  ContextManager.swift
//  OctoPhone
//
//  Created by Josef Dolezal on 19/11/16.
//  Copyright © 2016 Josef Dolezal. All rights reserved.
//

import Foundation
import RealmSwift
import ReactiveSwift

/// Database connections manager
protocol ContextManagerType: class {
    /// Creates new connection to the database on specific thread
    ///
    /// - Returns: New database connection
    /// - Throws: RealmError
    func createContext() throws -> Realm

    /// Creates signal with realm connection as value
    ///
    /// - Returns: Realm connection signal producer
    func createObservableContext() -> SignalProducer<Realm, RealmError>
}

/// Preconfigured local database manager
class ContextManager: ContextManagerType {

    /// Default configuration for app realm
    ///
    /// - Returns: New default configuration
    public func configuration() -> Realm.Configuration {
        var configuration = Realm.Configuration.defaultConfiguration

        configuration.deleteRealmIfMigrationNeeded = true

        return configuration
    }

    public func createContext() throws -> Realm {
        return try Realm(configuration: configuration())
    }

    public func createObservableContext() -> SignalProducer<Realm, RealmError> {
        return SignalProducer({ observer, _ in
            do {
                let realm = try Realm(configuration: self.configuration())

                observer.send(value: realm)
            } catch {
                observer.send(error: .underlyingError(error))
            }
        })
    }
}

/// In memory database manager - for test purposes
class InMemoryContextManager: ContextManager {

    /// In memory realm identifier
    private let currentIdentifier = UUID().uuidString

    override func configuration() -> Realm.Configuration {
        var configuration = Realm.Configuration.defaultConfiguration

        configuration.inMemoryIdentifier = currentIdentifier

        return configuration
    }
}


import EurofurenceApplication
import UserNotifications

class AppNotificationDelegate: NSObject, UNUserNotificationCenterDelegate {

    // MARK: UNUserNotificationCenterDelegate

    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
    ) {
        completionHandler([.alert, .badge, .sound])
    }

    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void
    ) {
        Application.openNotification(
            response.notification.request.content.userInfo,
            completionHandler: completionHandler
        )
    }

    // MARK: Setup

    static let instance = AppNotificationDelegate()

    override private init() {

    }

    func prepare() {
        prepareNotificationHandler()
        requestNotificationPermissions()
    }

    private func prepareNotificationHandler() {
        UNUserNotificationCenter.current().delegate = self
        requestNotificationPermissions()
    }

    private func requestNotificationPermissions() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (_, error) in
            if let error = error {
                print("Failed to register for notifications with error: \(error)")
            }
        }
    }

}

Add time-sensitive authorization option in request

import EurofurenceApplication
import UserNotifications

class AppNotificationDelegate: NSObject, UNUserNotificationCenterDelegate {

    // MARK: UNUserNotificationCenterDelegate

    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
    ) {
        completionHandler([.alert, .badge, .sound])
    }

    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void
    ) {
        Application.openNotification(
            response.notification.request.content.userInfo,
            completionHandler: completionHandler
        )
    }

    // MARK: Setup

    static let instance = AppNotificationDelegate()

    override private init() {

    }

    func prepare() {
        prepareNotificationHandler()
        requestNotificationPermissions()
    }

    private func prepareNotificationHandler() {
        UNUserNotificationCenter.current().delegate = self
        requestNotificationPermissions()
    }

    private func requestNotificationPermissions() {
        var authorizationOptions: UNAuthorizationOptions = [.alert, .badge, .sound]

        if #available(iOS 15, *) {
            authorizationOptions.insert(.timeSensitive)
        }

        UNUserNotificationCenter.current().requestAuthorization(options: authorizationOptions) { (_, error) in
            if let error = error {
                print("Failed to register for notifications with error: \(error)")
            }
        }
    }

}


//
//  AnimationOption.swift
//  TransitionRouter
//
//  Created by Artem Novichkov on 10/12/2016.
//  Copyright © 2016 Artem Novichkov. All rights reserved.
//

import UIKit

public struct AnimationOptions {

    let duration: TimeInterval
    let option: UIViewAnimationOptions
    let delay: TimeInterval
    /// Max value for interactive transition finishing
    let percentage: CGFloat

    static var `default`: AnimationOptions {
        return AnimationOptions(duration: 0.3, option: .curveEaseOut, delay: 0, percentage: 0.3)
    }
}

Add public init for options

//
//  AnimationOption.swift
//  TransitionRouter
//
//  Created by Artem Novichkov on 10/12/2016.
//  Copyright © 2016 Artem Novichkov. All rights reserved.
//

import UIKit

public struct AnimationOptions {

    public let duration: TimeInterval
    public let option: UIViewAnimationOptions
    public let delay: TimeInterval
    /// Max value for interactive transition finishing
    public let percentage: CGFloat

    public init(duration: TimeInterval = 0.3,
                option: UIViewAnimationOptions = .curveEaseOut,
                delay: TimeInterval = 0,
                percentage: CGFloat = 0.3) {
        self.duration = duration
        self.option = option
        self.delay = delay
        self.percentage = percentage
    }
}


#if os(Linux)
import Glibc
#else
import Darwin
#endif

import Nest
import Commander
import Inquiline

extension Address : ArgumentConvertible {
  init(parser: ArgumentParser) throws {
    if let value = parser.shift() {
      let components = value.characters.split(":").map(String.init)
      if components.count != 2 {
        throw ArgumentError.InvalidType(value: value, type: "hostname and port separated by `:`.", argument: nil)
      }

      if let port = UInt16(components[1]) {
        self = .IP(hostname: components[0], port: port)
      } else {
        throw ArgumentError.InvalidType(value: components[1], type: "number", argument: "port")
      }
    } else {
      throw ArgumentError.MissingValue(argument: nil)
    }
  }
}

@noreturn public func serve(closure: RequestType -> ResponseType) {
  command(
    Option("workers", 1),
    Option("bind", Address.IP(hostname: "0.0.0.0", port: 8000)),
    Option("timeout", 30)
  ) { workers, address, timeout in
    let arbiter = Arbiter<SyncronousWorker>(application: closure, workers: workers, addresses: [address], timeout: timeout)
    try arbiter.run()
  }.run()
}

Add --help descriptions to options

#if os(Linux)
import Glibc
#else
import Darwin
#endif

import Nest
import Commander
import Inquiline

extension Address : ArgumentConvertible {
  init(parser: ArgumentParser) throws {
    if let value = parser.shift() {
      let components = value.characters.split(":").map(String.init)
      if components.count != 2 {
        throw ArgumentError.InvalidType(value: value, type: "hostname and port separated by `:`.", argument: nil)
      }

      if let port = UInt16(components[1]) {
        self = .IP(hostname: components[0], port: port)
      } else {
        throw ArgumentError.InvalidType(value: components[1], type: "number", argument: "port")
      }
    } else {
      throw ArgumentError.MissingValue(argument: nil)
    }
  }
}

@noreturn public func serve(closure: RequestType -> ResponseType) {
  command(
    Option("workers", 1, description: "The number of processes for handling requests."),
    Option("bind", Address.IP(hostname: "0.0.0.0", port: 8000), description: "The address to bind sockets."),
    Option("timeout", 30, description: "Amount of seconds to wait on a worker without activity before killing and restarting the worker.")
  ) { workers, address, timeout in
    let arbiter = Arbiter<SyncronousWorker>(application: closure, workers: workers, addresses: [address], timeout: timeout)
    try arbiter.run()
  }.run()
}


// RUN: %target-typecheck-verify-swift -target x86_64-apple-macosx10.15 -swift-version 5

// REQUIRES: objc_interop
// REQUIRES: OS=macosx

import SwiftUI

struct ContentView : View {
  @State var foo: [String] = Array(repeating: "", count: 5)

  var body: some View {
    VStack {
      HStack {
        Text("")
        TextFi // expected-error {{cannot find 'TextFi' in scope}}
      }

      ForEach(0 ... 4, id: \.self) { i in
        HStack {
          TextField("", text: self.$foo[i])
        }
      }
    }
  }
}

Adjust SwiftUI to use %target-cpu instead of x86_64

// RUN: %target-typecheck-verify-swift -target %target-cpu-apple-macosx10.15 -swift-version 5

// REQUIRES: objc_interop
// REQUIRES: OS=macosx

import SwiftUI

struct ContentView : View {
  @State var foo: [String] = Array(repeating: "", count: 5)

  var body: some View {
    VStack {
      HStack {
        Text("")
        TextFi // expected-error {{cannot find 'TextFi' in scope}}
      }

      ForEach(0 ... 4, id: \.self) { i in
        HStack {
          TextField("", text: self.$foo[i])
        }
      }
    }
  }
}


import Foundation

public enum Command {
    case search(String)
    case info(String)
    case home(String)
    case add(String)

    public static var exampleUsage: String {
        return """
        Commands:
          apo search <query>
              Search for the query on all available sources.
          apo info <package_name>
              Get additional info to a package.
          apo home <package_name>
              Open the homepage of a package in your browser.
          apo add <package_name>
              Add the given package to your Package.swift's dependencies.
        """
    }

    public init?(from strings: [String]) {
        guard strings.count > 0, let first = strings.first else { return nil }
        switch first.lowercased() {
        case "search", "s":
            guard strings.count >= 2 else { return nil }
            let package = strings.dropFirst().joined(separator: " ")
            self = .search(package)
        case "info", "i":
            guard strings.count >= 2 else { return nil }
            let package = strings.dropFirst().joined(separator: " ")
            self = .info(package)
        case "home", "h":
            guard strings.count >= 2 else { return nil }
            let package = strings.dropFirst().joined(separator: " ")
            self = .home(package)
        case "add", "a":
            guard strings.count >= 2 else { return nil }
            let package = strings.dropFirst().joined(separator: " ")
            self = .add(package)
        default:
            return nil
        }
    }
}

Update old `apo search` command helper

import Foundation

public enum Command {
    case search(String)
    case info(String)
    case home(String)
    case add(String)

    public static var exampleUsage: String {
        return """
        Commands:
          apo search <query>
              Search for packages matching query.
          apo info <package_name>
              Get additional info to a package.
          apo home <package_name>
              Open the homepage of a package in your browser.
          apo add <package_name>
              Add the given package to your Package.swift's dependencies.
        """
    }

    public init?(from strings: [String]) {
        guard strings.count > 0, let first = strings.first else { return nil }
        switch first.lowercased() {
        case "search", "s":
            guard strings.count >= 2 else { return nil }
            let package = strings.dropFirst().joined(separator: " ")
            self = .search(package)
        case "info", "i":
            guard strings.count >= 2 else { return nil }
            let package = strings.dropFirst().joined(separator: " ")
            self = .info(package)
        case "home", "h":
            guard strings.count >= 2 else { return nil }
            let package = strings.dropFirst().joined(separator: " ")
            self = .home(package)
        case "add", "a":
            guard strings.count >= 2 else { return nil }
            let package = strings.dropFirst().joined(separator: " ")
            self = .add(package)
        default:
            return nil
        }
    }
}


//
//  DeviceNameManager.swift
//
//
//  Created by Biso Shrestha on 2022-11-08.
//

public protocol DeviceNameManager {
    func setDeviceName(_ deviceName: String)
}

Update copyright in newly created file.

//
//  DeviceNameManager.swift
//
//
//  Created by Biso Shrestha on 2022-11-08.
//  Copyright © 2022 Rover Labs Inc. All rights reserved.
//

public protocol DeviceNameManager {
    func setDeviceName(_ deviceName: String)
}


//
//  AppDelegate.swift
//  <%= project_name %>
//
//  Created by <%= author %> on <%= Time.now.strftime("%-m/%-d/%y") %>
//  Copyright (c) <%= Time.now.strftime('%Y') %> <%= company %>. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
}

Update template for swift app delegate

//
//  AppDelegate.swift
//  <%= project_name %>
//
//  Created by <%= author %> on <%= Time.now.strftime("%-m/%-d/%y") %>
//  Copyright (c) <%= Time.now.strftime('%Y') %> <%= company %>. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
}


import UIKit

class ViewController: UIViewController {

    @IBOutlet fileprivate weak var tableView: UITableView!

    override func viewDidLoad() {
        view.backgroundColor = .blue
        super.viewDidLoad()
        setupTableView()
        tableView.reloadData()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    private func setupTableView() {
        tableView.dataSource = self
        tableView.register(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "CustomCell")
        let headerNib = UINib(nibName: "CustomTableViewHeader", bundle: nil)
        let headerView = headerNib.instantiate(withOwner: self, options: nil).first! as! UIView
        headerView.frame = CGRect(origin: headerView.frame.origin, size: CGSize(width: headerView.frame.width, height: 400))
        tableView.tableHeaderView = headerView
    }
}

extension ViewController: UITableViewDataSource {

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 50
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
        cell.label.text = "\(indexPath.row)"
        return cell
    }
}

Remove public from tableview datasource funcs

import UIKit

class ViewController: UIViewController {

    @IBOutlet fileprivate weak var tableView: UITableView!

    override func viewDidLoad() {
        view.backgroundColor = .blue
        super.viewDidLoad()
        setupTableView()
        tableView.reloadData()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    private func setupTableView() {
        tableView.dataSource = self
        tableView.register(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "CustomCell")
        let headerNib = UINib(nibName: "CustomTableViewHeader", bundle: nil)
        let headerView = headerNib.instantiate(withOwner: self, options: nil).first! as! UIView
        headerView.frame = CGRect(origin: headerView.frame.origin, size: CGSize(width: headerView.frame.width, height: 400))
        tableView.tableHeaderView = headerView
    }
}

extension ViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 50
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
        cell.label.text = "\(indexPath.row)"
        return cell
    }
}


//
//  FirebaseModel+Extension.swift
//  FirebaseCommunity
//
//  Created by Victor Alisson on 15/08/17.
//

import Foundation
import FirebaseCommunity

public extension FirebaseModel {
    typealias JSON = [String: Any]

    static var path: DatabaseReference {
        return reference.child(Self.className)
    }
    static var reference: DatabaseReference {
        return Database.database().reference()
    }
    static var className: String {
        return String(describing: self)
    }
    static var autoId: String {
        return Self.reference.childByAutoId().key
    }
    func toJSON() -> JSON {
        guard let jsonData = try? JSONEncoder().encode(self) else {
            return JSON()
        }
        guard let dictionary = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? JSON ?? JSON() else {
            return JSON()
        }
        return dictionary
    }
}

Update FirebaseModel with new serialization method

//
//  FirebaseModel+Extension.swift
//  FirebaseCommunity
//
//  Created by Victor Alisson on 15/08/17.
//

import Foundation
import FirebaseCommunity

public extension FirebaseModel {
    typealias JSON = [String: Any]

    internal static var classPath: DatabaseReference {
        return reference.child(Self.className)
    }
    static var reference: DatabaseReference {
        return Database.database().reference()
    }
    internal static var className: String {
        return String(describing: self)
    }
    internal static var autoId: String {
        return Self.reference.childByAutoId().key
    }
    func toJSON() -> JSON {
        return toJSON()
    }
}


/*
MIT License

Copyright (c) 2016 Ahmad M. Zawawi

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.
*/

// For now
import CZeroMQ

public enum ZMQError : Error {
    case invalidHandle
}

Use zmq_strerror and zmq_errno to return error description

/*
MIT License

Copyright (c) 2016 Ahmad M. Zawawi

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.
*/

// For now
import CZeroMQ

public enum ZMQError : Error {
    case invalidHandle

    //TODO exprimental... improve this function
    public func description() -> String? {
        let description: String? = String(validatingUTF8: zmq_strerror(zmq_errno()))
        print("Last error says '\(description)'")
        return description
    }
}


import XCTest
import Nimble

class HaveCountTest: XCTestCase {
    func testEquality() {
        expect([1, 2, 3]).to(haveCount(3))
        expect([1, 2, 3]).notTo(haveCount(1))
    }
}

Test failure cases of haveCount matcher

import XCTest
import Nimble

class HaveCountTest: XCTestCase {
    func testEquality() {
        expect([1, 2, 3]).to(haveCount(3))
        expect([1, 2, 3]).notTo(haveCount(1))

        failsWithErrorMessage("expected to have [1, 2, 3] with count 3, got 1") {
            expect([1, 2, 3]).to(haveCount(1))
        }

        failsWithErrorMessage("expected to not have [1, 2, 3] with count 3, got 3") {
            expect([1, 2, 3]).notTo(haveCount(3))
        }
    }
}


//
//  EurofurenceFCMDeviceRegistration.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 15/07/2017.
//  Copyright © 2017 Eurofurence. All rights reserved.
//

import Foundation

struct EurofurenceFCMDeviceRegistration: FCMDeviceRegistration {

    private var JSONSession: JSONSession

    init(JSONSession: JSONSession) {
        self.JSONSession = JSONSession
    }

    func registerFCM(_ fcm: String,
                     topics: [FirebaseTopic],
                     authenticationToken: String?,
                     completionHandler: @escaping (Error?) -> Void) {
        let formattedTopics = topics.map({ $0.description })
        let jsonDictionary: [String : Any] = ["DeviceId": fcm, "Topics": formattedTopics]
        let jsonData = try! JSONSerialization.data(withJSONObject: jsonDictionary, options: [])

        let loginURL = "https://app.eurofurence.org/api/v2/PushNotifications/FcmDeviceRegistration"
        var request = JSONRequest(url: loginURL, body: jsonData)

        if let token = authenticationToken {
            request.headers = ["Authorization": "Bearer \(token)"]
        }

        JSONSession.post(request, completionHandler: { _, error in completionHandler(error) })
    }

}

Use native JSON encoding for FCM registration

//
//  EurofurenceFCMDeviceRegistration.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 15/07/2017.
//  Copyright © 2017 Eurofurence. All rights reserved.
//

import Foundation

struct EurofurenceFCMDeviceRegistration: FCMDeviceRegistration {

    var JSONSession: JSONSession
    private let jsonEncoder = JSONEncoder()

    func registerFCM(_ fcm: String,
                     topics: [FirebaseTopic],
                     authenticationToken: String?,
                     completionHandler: @escaping (Error?) -> Void) {
        let registrationRequest = Request(DeviceId: fcm, Topics: topics.map({ $0.description }))
        let jsonData = try! jsonEncoder.encode(registrationRequest)

        let registrationURL = "https://app.eurofurence.org/api/v2/PushNotifications/FcmDeviceRegistration"
        var request = JSONRequest(url: registrationURL, body: jsonData)

        if let token = authenticationToken {
            request.headers = ["Authorization": "Bearer \(token)"]
        }

        JSONSession.post(request, completionHandler: { (_, error) in completionHandler(error) })
    }

    private struct Request: Encodable {
        var DeviceId: String
        var Topics: [String]
    }

}


//
//  String+M3U8Attributes.swift
//  M3U8
//
//  Created by Max Goedjen on 8/10/15.
//  Copyright © 2015 Max Goedjen. All rights reserved.
//

import Foundation

public extension String {

    public var m3u8Attributes: [String: String] {
        guard let firstLine = componentsSeparatedByString("\n").first else { return [:] }
        // Wooooooo string escapes
        // Reference Ruby-style regex: /([A-z-]+)\s*=\s*("[^"]*"|[^,]*)/
        do {
            let regex = try NSRegularExpression(pattern: "([A-z-]+)\\s*=\\s*(\"[^\"]*\"|[^,]*)", options: [])
            let matches = regex.matchesInString(firstLine, options: [], range: NSMakeRange(0, (firstLine as NSString).length))
            return matches.reduce([:] as [String: String]) { acc, next in
                let nsStrung = firstLine as NSString
                let key = nsStrung.substringWithRange(next.rangeAtIndex(1))
                let value = nsStrung.substringWithRange(next.rangeAtIndex(2)).stringByReplacingOccurrencesOfString("\"", withString: "")
                var modifiedAccum = acc
                modifiedAccum[key] = value
                return modifiedAccum
            }
        } catch _ {
            return [:]
        }
    }

}

public extension Bool {

    public init(string: String) {
        self = (string as NSString).boolValue
    }

}

Add nil initializer for m3u8 attributes

//
//  String+M3U8Attributes.swift
//  M3U8
//
//  Created by Max Goedjen on 8/10/15.
//  Copyright © 2015 Max Goedjen. All rights reserved.
//

import Foundation

public extension String {

    public var m3u8Attributes: [String: String] {
        guard let firstLine = componentsSeparatedByString("\n").first else { return [:] }
        // Wooooooo string escapes
        // Reference Ruby-style regex: /([A-z-]+)\s*=\s*("[^"]*"|[^,]*)/
        do {
            let regex = try NSRegularExpression(pattern: "([A-z-]+)\\s*=\\s*(\"[^\"]*\"|[^,]*)", options: [])
            let matches = regex.matchesInString(firstLine, options: [], range: NSMakeRange(0, (firstLine as NSString).length))
            return matches.reduce([:] as [String: String]) { acc, next in
                let nsStrung = firstLine as NSString
                let key = nsStrung.substringWithRange(next.rangeAtIndex(1))
                let value = nsStrung.substringWithRange(next.rangeAtIndex(2)).stringByReplacingOccurrencesOfString("\"", withString: "")
                var modifiedAccum = acc
                modifiedAccum[key] = value
                return modifiedAccum
            }
        } catch _ {
            return [:]
        }
    }

}

public extension Bool {

    public init?(string: String?) {
        guard let string = string else { return nil }
        self = (string as NSString).boolValue
    }

}


//
//  Twitter: @MartinRogalla
//  EmaiL: email@martinrogalla.com
//
//  Created by Martin Rogalla.
//

import UIKit

class Snowflake : UIView {
    override init (frame : CGRect) {
        super.init(frame : frame)
        self.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.7)
        self.layer.cornerRadius = CGFloat(self.frame.width/2)
        self.layer.borderWidth = 0.0
    }

    convenience init (position : CGPoint, minimumSize : Int, maximumSize : Int) {
        let randomSize = CGFloat(arc4random_uniform(UInt32(maximumSize - minimumSize)) + UInt32(minimumSize))
        self.init(frame: CGRect(x: position.x, y: position.y, width: randomSize, height: randomSize))
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("This class does not support NSCoding")
    }
}

Check that minimumSize is actually less than maximumSize

//
//  Twitter: @MartinRogalla
//  EmaiL: email@martinrogalla.com
//
//  Created by Martin Rogalla.
//

import UIKit

class Snowflake : UIView {
    override init (frame : CGRect) {
        super.init(frame : frame)
        self.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.7)
        self.layer.cornerRadius = CGFloat(self.frame.width/2)
        self.layer.borderWidth = 0.0
    }

    convenience init (position : CGPoint, minimumSize : Int, maximumSize : Int) {
        let randomSize: CGFloat!

        if minimumSize < maximumSize {
            randomSize = CGFloat(arc4random_uniform(UInt32(maximumSize - minimumSize)) + UInt32(minimumSize))
        } else {
            //If the parameters passed in were not correct, we should flip which is the min and max
            randomSize = CGFloat(arc4random_uniform(UInt32(minimumSize - maximumSize)) + UInt32(maximumSize))
        }
        self.init(frame: CGRect(x: position.x, y: position.y, width: randomSize, height: randomSize))
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("This class does not support NSCoding")
    }
}


import UIKit

extension UISwitch {
    public func flip() -> FleetError? {
        guard isEnabled else {
            return FleetError(message: "Cannot flip UISwitch: Control is not enabled")
        }
        guard !isHidden else {
            return FleetError(message: "Cannot flip UISwitch: Control is not visible")
        }

        setOn(!isOn, animated: false)
        sendActions(for: .valueChanged)
        return nil
    }
}

Add in-code documentation to `UISwitch.flip()`

import UIKit

extension UISwitch {
    /**
     Toggles the switch value and fires the `.valueChanged` control event.

     - returns:
     A `FleetError` if the switch is hidden or disabled.
    */
    public func flip() -> FleetError? {
        guard isEnabled else {
            return FleetError(message: "Cannot flip UISwitch: Control is not enabled")
        }
        guard !isHidden else {
            return FleetError(message: "Cannot flip UISwitch: Control is not visible")
        }

        setOn(!isOn, animated: false)
        sendActions(for: .valueChanged)
        return nil
    }
}


//
//  StatusBar.swift
//  Freetime
//
//  Created by Ryan Nystrom on 5/17/17.
//  Copyright © 2017 Ryan Nystrom. All rights reserved.
//

import Foundation
import JDStatusBarNotification

struct StatusBar {

    private static func provideHapticFeedback() {
        UINotificationFeedbackGenerator().notificationOccurred(.error)
    }

    static func showRevokeError() {
        JDStatusBarNotification.show(
            withStatus: NSLocalizedString("Your access token was revoked.", comment: ""),
            dismissAfter: 3,
            styleName: JDStatusBarStyleError
        )
        provideHapticFeedback()
    }

    static func showNetworkError() {
        JDStatusBarNotification.show(
            withStatus: NSLocalizedString("Network connection lost.", comment: ""),
            dismissAfter: 3,
            styleName: JDStatusBarStyleError
        )
        provideHapticFeedback()
    }

    static func showGenericError() {
        JDStatusBarNotification.show(
            withStatus: NSLocalizedString("Something went wrong.", comment: ""),
            dismissAfter: 3,
            styleName: JDStatusBarStyleError
        )
        provideHapticFeedback()
    }

}

Change struct with static funcs to enum

//
//  StatusBar.swift
//  Freetime
//
//  Created by Ryan Nystrom on 5/17/17.
//  Copyright © 2017 Ryan Nystrom. All rights reserved.
//

import Foundation
import JDStatusBarNotification

enum StatusBar {

    private static func provideHapticFeedback() {
        UINotificationFeedbackGenerator().notificationOccurred(.error)
    }

    static func showRevokeError() {
        JDStatusBarNotification.show(
            withStatus: NSLocalizedString("Your access token was revoked.", comment: ""),
            dismissAfter: 3,
            styleName: JDStatusBarStyleError
        )
        provideHapticFeedback()
    }

    static func showNetworkError() {
        JDStatusBarNotification.show(
            withStatus: NSLocalizedString("Network connection lost.", comment: ""),
            dismissAfter: 3,
            styleName: JDStatusBarStyleError
        )
        provideHapticFeedback()
    }

    static func showGenericError() {
        JDStatusBarNotification.show(
            withStatus: NSLocalizedString("Something went wrong.", comment: ""),
            dismissAfter: 3,
            styleName: JDStatusBarStyleError
        )
        provideHapticFeedback()
    }

}


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

public struct Binding<Recur> {
	public init(_ symbol: Name, _ value: Expression<Recur>, _ type: Expression<Recur>) {
		self.symbol = symbol
		self.value = value
		self.type = type
	}

	public let symbol: Name
	public let value: Expression<Recur>
	public let type: Expression<Recur>
}

extension Binding where Recur: FixpointType {
	public func typecheck(context: [Name: Expression<Recur>]) -> Either<Error, Expression<Recur>> {
		return type.checkIsType(context)
			>> value.checkType(type, context: context)
				.either(
					ifLeft: { Either.left($0.map { "\(self.symbol)\n\t: \(self.type)\n\t= \(self.value)\n: " + $0 }) },
					ifRight: Either.right)
	}
}

import Either

Use the typealias for the context.

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

public struct Binding<Recur> {
	public init(_ symbol: Name, _ value: Expression<Recur>, _ type: Expression<Recur>) {
		self.symbol = symbol
		self.value = value
		self.type = type
	}

	public let symbol: Name
	public let value: Expression<Recur>
	public let type: Expression<Recur>
}

extension Binding where Recur: FixpointType {
	public func typecheck(context: Expression<Recur>.Context) -> Either<Error, Expression<Recur>> {
		return type.checkIsType(context)
			>> value.checkType(type, context: context)
				.either(
					ifLeft: { Either.left($0.map { "\(self.symbol)\n\t: \(self.type)\n\t= \(self.value)\n: " + $0 }) },
					ifRight: Either.right)
	}
}

import Either


//
//  OrderedDictionary.swift
//  SwiftPlusPlus
//
//  Created by Andrew J Wagner on 11/20/15.
//  Copyright © 2015 Drewag LLC. All rights reserved.
//

import Foundation

public struct OrderedDictionary<Key: Hashable, Value> {
    private var valueStore = [Value?]()
    private var lookup = [Key:Int]()

    public subscript(key: Key) -> Value? {
        get {
            if let index = lookup[key] {
                return self.valueStore[index]
            }
            return nil
        }
        set {
            if let existingIndex = lookup[key] {
                valueStore[existingIndex] = nil
            }
            valueStore.append(newValue)
            lookup[key] = valueStore.count - 1
        }
    }

    public var values: [Value] {
        return self.valueStore.flatMap({$0})
    }
}

Allow getting index of value with key in ordered dictionary

//
//  OrderedDictionary.swift
//  SwiftPlusPlus
//
//  Created by Andrew J Wagner on 11/20/15.
//  Copyright © 2015 Drewag LLC. All rights reserved.
//

import Foundation

public struct OrderedDictionary<Key: Hashable, Value> {
    private var valueStore = [Value?]()
    private var lookup = [Key:Int]()

    public subscript(key: Key) -> Value? {
        get {
            if let index = lookup[key] {
                return self.valueStore[index]
            }
            return nil
        }
        set {
            if let existingIndex = lookup[key] {
                valueStore[existingIndex] = nil
            }
            valueStore.append(newValue)
            lookup[key] = valueStore.count - 1
        }
    }

    public var values: [Value] {
        return self.valueStore.flatMap({$0})
    }
}

extension OrderedDictionary where Value: Equatable {
    public func indexOfValueWithKey(key: Key) -> Int? {
        let object = self[key]
        return self.values.indexOfObjectPassingTest {$0 == object}
    }
}


//
//  RangeReplaceableCollection+Utils.swift
//  Reactant
//
//  Created by Filip Dolnik on 21.02.17.
//  Copyright © 2017 Brightify. All rights reserved.
//

import Foundation

extension RangeReplaceableCollection {

    public mutating func remove(until: (Iterator.Element) -> Bool) -> [Iterator.Element] {
        let result = take(until: until)
        removeFirst(result.count)
        return result
    }
}

Stop using deprecated method in Reactant.

//
//  RangeReplaceableCollection+Utils.swift
//  Reactant
//
//  Created by Filip Dolnik on 21.02.17.
//  Copyright © 2017 Brightify. All rights reserved.
//

import Foundation

extension RangeReplaceableCollection {

    public mutating func remove(until: (Iterator.Element) -> Bool) -> [Iterator.Element] {
        let result = Array(prefix(while: until))
        removeFirst(result.count)
        return result
    }
}


// RUN: %target-swift-frontend %s -S -g -o - | %FileCheck %s

func markUsed<T>(_ t: T) {}
// CHECK: {{_?}}main:
// CHECK-NEXT: Lfunc_begin0:
// Verify that the top-level function (main) begins at line 0 and then
// proceeds to the first line.
// CHECK: .loc    {{[0-9]}} 0 {{[0-9]}}
// CHECK-NOT: Lfunc_end0:
// CHECK: .loc    {{[0-9]}} [[@LINE+1]] {{[0-9]}} prologue_end
var a = 1
var b = 2
markUsed(a+b)

Update test for upstream codegen changes

// RUN: %target-swift-frontend %s -S -g -o - | %FileCheck %s

func markUsed<T>(_ t: T) {}
// CHECK: {{_?}}main:
// CHECK: Lfunc_begin0:
// Verify that the top-level function (main) begins at line 0 and then
// proceeds to the first line.
// CHECK: .loc    {{[0-9]}} 0 {{[0-9]}}
// CHECK-NOT: Lfunc_end0:
// CHECK: .loc    {{[0-9]}} [[@LINE+1]] {{[0-9]}} prologue_end
var a = 1
var b = 2
markUsed(a+b)


//
//  Hash.swift
//  NumericAnnex
//
//  Created by Xiaodi Wu on 4/1/17.
//

/// A namespace for hash utilities.
internal enum _Hash { }

extension _Hash {
  // @_versioned
  /// Returns the result of combining `seed` with the `hashValue` of the given
  /// `values`.
  ///
  /// Combining is performed using [a hash function][ref] described by T.C. Hoad
  /// and J. Zobel that is also adopted in the Boost C++ libraries.
  ///
  /// [ref]: http://goanna.cs.rmit.edu.au/~jz/fulltext/jasist-tch.pdf
  internal static func _combine(seed: Int = 0, _ values: AnyHashable...) -> Int {
    var x = UInt(bitPattern: seed)
    let magic = 0x9e3779b9 as UInt // Based on the golden ratio.
    for v in values {
      x ^= UInt(bitPattern: v.hashValue) &+ magic &+ (x &<< 6) &+ (x &>> 2)
    }
    return Int(bitPattern: x)
  }
}

Improve hash function in the same manner as was done for the standard library

//
//  Hash.swift
//  NumericAnnex
//
//  Created by Xiaodi Wu on 4/1/17.
//

/// A namespace for hash utilities.
internal enum _Hash { }

extension _Hash {
  // @_versioned
  /// Returns the result of combining `seed` with the `hashValue` of the given
  /// `values`.
  ///
  /// Combining is performed using [a hash function][ref] described by T.C. Hoad
  /// and J. Zobel that is also adopted in the Boost C++ libraries.
  ///
  /// [ref]: http://goanna.cs.rmit.edu.au/~jz/fulltext/jasist-tch.pdf
  internal static func _combine(seed: Int = 0, _ values: AnyHashable...) -> Int {
    // Use a magic number based on the golden ratio
    // (0x1.9e3779b97f4a7c15f39cc0605cedc8341082276bf3a27251f86c6a11d0c18e95p0).
#if arch(i386) || arch(arm)
    let magic = 0x9e3779b9 as UInt
#else
    let magic = 0x9e3779b97f4a7c15 as UInt
#endif
    var x = UInt(bitPattern: seed)
    for v in values {
      x ^= UInt(bitPattern: v.hashValue) &+ magic &+ (x &<< 6) &+ (x &>> 2)
    }
    return Int(bitPattern: x)
  }
}


import Foundation
import XCTest

// NOTE: This file is not intended to be included in the Xcode project or CocoaPods.
//       It is picked up by the Swift Package Manager during its build process.

#if SWIFT_PACKAGE

open class QuickConfiguration: NSObject {
    open class func configure(_ configuration: Configuration) {}
}

#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)

internal func qck_enumerateSubclasses<T: AnyObject>(_ klass: T.Type, block: (T.Type) -> Void) {
    var classesCount = objc_getClassList(nil, 0)

    guard classesCount > 0 else {
        return
    }

    let classes = UnsafeMutablePointer<AnyClass?>.allocate(capacity: Int(classesCount))
    classesCount = objc_getClassList(AutoreleasingUnsafeMutablePointer(classes), classesCount)

    var subclass, superclass: AnyClass!
    for i in 0..<classesCount {
        subclass = classes[Int(i)]

        guard let superclass = class_getSuperclass(subclass),
            superclass === klass else { return }

        block(subclass as! T.Type) // swiftlint:disable:this force_cast
    }

    free(classes)
}

#endif

#endif

Add missing changes to SPM fix

import Foundation
import XCTest

// NOTE: This file is not intended to be included in the Xcode project or CocoaPods.
//       It is picked up by the Swift Package Manager during its build process.

#if SWIFT_PACKAGE

open class QuickConfiguration: NSObject {
    open class func configure(_ configuration: Configuration) {}
}

#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)

internal func qck_enumerateSubclasses<T: AnyObject>(_ klass: T.Type, block: (T.Type) -> Void) {
    var classesCount = objc_getClassList(nil, 0)

    guard classesCount > 0 else {
        return
    }

    let classes = UnsafeMutablePointer<AnyClass?>.allocate(capacity: Int(classesCount))
    classesCount = objc_getClassList(AutoreleasingUnsafeMutablePointer(classes), classesCount)

    var subclass: AnyClass!
    for i in 0..<classesCount {
        subclass = classes[Int(i)]

        guard let superclass = class_getSuperclass(subclass),
            superclass === klass else { return }

        block(subclass as! T.Type) // swiftlint:disable:this force_cast
    }

    free(classes)
}

#endif

#endif


import XCTest
import SwiftUI
@testable import ViewInspector

final class TreeViewTests: XCTestCase {

    func testEnclosedView() throws {
        let sut = Text("Test").contextMenu(ContextMenu(menuItems: { Text("Menu") }))
        let text = try sut.inspect().text().string()
        XCTAssertEqual(text, "Test")
    }
}

Exclude a test for tvOS

import XCTest
import SwiftUI
@testable import ViewInspector

final class TreeViewTests: XCTestCase {

    #if !os(tvOS)
    func testEnclosedView() throws {
        let sut = Text("Test").contextMenu(ContextMenu(menuItems: { Text("Menu") }))
        let text = try sut.inspect().text().string()
        XCTAssertEqual(text, "Test")
    }
    #endif
}


import Foundation

enum DateUtils {
  private static let locale = Locale(identifier: "en_GB")

  static let individualDayFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .medium
    formatter.timeStyle = .none
    formatter.locale = locale

    return formatter
  }()

  static let individualTimeFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .none
    formatter.timeStyle = .short
    formatter.locale = locale

    return formatter
  }()
}

extension Date {
  static func from(year: Int, month: Int, day: Int, hour: Int, minute: Int, timezone: TimeZone? = nil) -> Date {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm"
    formatter.timeZone = timezone ?? TimeZone(identifier: "Europe/London")
    if let result = formatter.date(from: "\(year)-\(month)-\(day) \(hour):\(minute)") {
      return result
    } else {
      fatalError("Improper date given: \(year)-\(month)-\(day) \(hour):\(minute) does not exist")
    }
  }

  static func from(string dateString: String?) -> Date? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.zzz"
    return dateString != nil ? dateFormatter.date(from: dateString!) : nil
  }
}

Comment use of conditionals instead of map

import Foundation

enum DateUtils {
  private static let locale = Locale(identifier: "en_GB")

  static let individualDayFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .medium
    formatter.timeStyle = .none
    formatter.locale = locale

    return formatter
  }()

  static let individualTimeFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .none
    formatter.timeStyle = .short
    formatter.locale = locale

    return formatter
  }()
}

extension Date {
  static func from(year: Int, month: Int, day: Int, hour: Int, minute: Int, timezone: TimeZone? = nil) -> Date {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm"
    formatter.timeZone = timezone ?? TimeZone(identifier: "Europe/London")
    if let result = formatter.date(from: "\(year)-\(month)-\(day) \(hour):\(minute)") {
      return result
    } else {
      fatalError("Improper date given: \(year)-\(month)-\(day) \(hour):\(minute) does not exist")
    }
  }

  static func from(string dateString: String?) -> Date? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.zzz"
    // We don't use the map method here, because it returns a result of type Date??
    return dateString != nil ? dateFormatter.date(from: dateString!) : nil
  }
}


import Foundation
import CWebP

#if os(macOS) || os(iOS)
import CoreGraphics

extension WebPDecoder {

    public func decode(_ webPData: Data, options: WebPDecoderOptions) throws -> CGImage {

        let feature = try WebPImageInspector.inspect(webPData)
        let height: Int = options.useScaling ? options.scaledHeight : feature.height
        let width: Int = options.useScaling ? options.scaledWidth : feature.width

        let decodedData: Data = try decode(byrgbA: webPData, options: options)

        return try decodedData.withUnsafeBytes { rawPtr in
            guard let bindedBasePtr = rawPtr.baseAddress?.assumingMemoryBound(to: UInt8.self) else {
                throw WebPError.unexpectedPointerError
            }

            let provider = CGDataProvider(dataInfo: nil,
                                          data: bindedBasePtr,
                                          size: decodedData.count,
                                          releaseData: { (_, _, _) in  })!
            let bitmapInfo = CGBitmapInfo(
                rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue
            )
            let colorSpace = CGColorSpaceCreateDeviceRGB()
            let renderingIntent = CGColorRenderingIntent.defaultIntent
            let bytesPerPixel = 4

            return CGImage(width: width,
                           height: height,
                           bitsPerComponent: 8,
                           bitsPerPixel: 8 * bytesPerPixel,
                           bytesPerRow: bytesPerPixel * width,
                           space: colorSpace,
                           bitmapInfo: bitmapInfo,
                           provider: provider,
                           decode: nil,
                           shouldInterpolate: false,
                           intent: renderingIntent)!
        }
    }
}
#endif

Use CFData to instantiate CGDataProvider

import Foundation
import CWebP

#if os(macOS) || os(iOS)
import CoreGraphics

extension WebPDecoder {

    public func decode(_ webPData: Data, options: WebPDecoderOptions) throws -> CGImage {

        let feature = try WebPImageInspector.inspect(webPData)
        let height: Int = options.useScaling ? options.scaledHeight : feature.height
        let width: Int = options.useScaling ? options.scaledWidth : feature.width

        let decodedData: CFData = try decode(byrgbA: webPData, options: options) as CFData
        let provider = CGDataProvider(data: decodedData)!

        let bitmapInfo = CGBitmapInfo(
            rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue
        )
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let renderingIntent = CGColorRenderingIntent.defaultIntent
        let bytesPerPixel = 4

        let cgImage = CGImage(width: width,
                              height: height,
                              bitsPerComponent: 8,
                              bitsPerPixel: 8 * bytesPerPixel,
                              bytesPerRow: bytesPerPixel * width,
                              space: colorSpace,
                              bitmapInfo: bitmapInfo,
                              provider: provider,
                              decode: nil,
                              shouldInterpolate: false,
                              intent: renderingIntent)!
        return cgImage
    }
}
#endif


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

final class InferenceTests: XCTestCase {
	func testGraphsWithoutReturnsHaveUnitType() {
		assert(type(Graph()), ==, .Unit)
	}

	func testGraphsWithOneReturnHaveVariableType() {
		assert(type(Graph(nodes: [Identifier(): .Return((0, .Unit))])), ==, 0)
	}

	func testGraphsWithOneParameterAndNoReturnsHaveFunctionTypeReturningUnit() {
		assert(type(Graph(nodes: [Identifier(): .Parameter((0, .Unit))], edges: [])), ==, .function(0, .Unit))
	}

	func testGraphsWithOneParameterAndOneReturnHaveFunctionTypeFromVariableToDifferentVariable() {
		assert(type(Graph(nodes: [Identifier(): .Parameter((0, .Unit)), Identifier(): .Return((0, .Unit))], edges: [])), ==, .function(1, 0))
	}
}

private func type(graph: Graph<Node>) -> Term {
	return simplify(constraints(graph).0)
}

private func simplify(type: Term) -> Term {
	return Substitution(lazy(enumerate(type.freeVariables |> (flip(sorted) <| { $0.value < $1.value }))).map { ($1, Term(integerLiteral: $0)) }).apply(type)
}

import Assertions
import Manifold
import Prelude
import TesseractCore
import XCTest

Use default (empty) edge sets.

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

final class InferenceTests: XCTestCase {
	func testGraphsWithoutReturnsHaveUnitType() {
		assert(type(Graph()), ==, .Unit)
	}

	func testGraphsWithOneReturnHaveVariableType() {
		assert(type(Graph(nodes: [Identifier(): .Return((0, .Unit))])), ==, 0)
	}

	func testGraphsWithOneParameterAndNoReturnsHaveFunctionTypeReturningUnit() {
		assert(type(Graph(nodes: [Identifier(): .Parameter((0, .Unit))])), ==, .function(0, .Unit))
	}

	func testGraphsWithOneParameterAndOneReturnHaveFunctionTypeFromVariableToDifferentVariable() {
		assert(type(Graph(nodes: [Identifier(): .Parameter((0, .Unit)), Identifier(): .Return((0, .Unit))])), ==, .function(1, 0))
	}
}

private func type(graph: Graph<Node>) -> Term {
	return simplify(constraints(graph).0)
}

private func simplify(type: Term) -> Term {
	return Substitution(lazy(enumerate(type.freeVariables |> (flip(sorted) <| { $0.value < $1.value }))).map { ($1, Term(integerLiteral: $0)) }).apply(type)
}

import Assertions
import Manifold
import Prelude
import TesseractCore
import XCTest


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

final class InferenceTests: XCTestCase {
	func testGraphsWithoutReturnsHaveUnitType() {
		assert(constraints(Graph()).0, ==, .Unit)
	}
}

import Assertions
import Manifold
import TesseractCore
import XCTest

Add a helper to simplify the variables in a type.

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

final class InferenceTests: XCTestCase {
	func testGraphsWithoutReturnsHaveUnitType() {
		assert(constraints(Graph()).0, ==, .Unit)
	}
}

private func simplify(type: Term) -> Term {
	return Substitution(lazy(enumerate(type.freeVariables)).map { ($1, Term(integerLiteral: $0)) }).apply(type)
}

import Assertions
import Manifold
import TesseractCore
import XCTest


import Foundation
import AsyncDisplayKit
import Kingfisher

public class ImageCache: NSObject, ASImageDownloaderProtocol {
  public func downloadImageWithURL(URL: NSURL!,
    callbackQueue: dispatch_queue_t!,
    downloadProgressBlock: ((CGFloat) -> Void)!,
    completion: ((CGImage!, NSError!) -> Void)!) -> AnyObject! {

      let manager = KingfisherManager.sharedManager

      let task = manager.retrieveImageWithURL(URL,
        options: .None,
        progressBlock:
        { receivedSize, totalSize in
          if downloadProgressBlock != nil {
            let queue = callbackQueue != nil ?
              callbackQueue : dispatch_get_main_queue()
            dispatch_async(queue, {
              downloadProgressBlock(CGFloat(receivedSize / totalSize))
            })
          }
        })
        { image, error, cacheType, imageURL in
          if completion != nil {
            let queue = callbackQueue != nil ?
              callbackQueue : dispatch_get_main_queue()
            dispatch_async(queue, {
              completion(image!.CGImage, error)
            })
          }
      }
      return task
  }

  public func cancelImageDownloadForIdentifier(downloadIdentifier: AnyObject!) {
    if let task = downloadIdentifier as? RetrieveImageTask {
      task.cancel()
    }
  }
}

Add nil-check for image being retrieved

import Foundation
import AsyncDisplayKit
import Kingfisher

public class ImageCache: NSObject, ASImageDownloaderProtocol {
  public func downloadImageWithURL(URL: NSURL!,
    callbackQueue: dispatch_queue_t!,
    downloadProgressBlock: ((CGFloat) -> Void)!,
    completion: ((CGImage!, NSError!) -> Void)!) -> AnyObject! {

      let manager = KingfisherManager.sharedManager

      let task = manager.retrieveImageWithURL(URL,
        options: .None,
        progressBlock:
        { receivedSize, totalSize in
          if downloadProgressBlock != nil {
            let queue = callbackQueue != nil ?
              callbackQueue : dispatch_get_main_queue()
            dispatch_async(queue, {
              downloadProgressBlock(CGFloat(receivedSize / totalSize))
            })
          }
        })
        { image, error, cacheType, imageURL in
          if completion != nil &&
            image != nil {
              let queue = callbackQueue != nil ?
                callbackQueue : dispatch_get_main_queue()
              dispatch_async(queue, {
                completion(image!.CGImage, error)
              })
          }
      }
      return task
  }

  public func cancelImageDownloadForIdentifier(downloadIdentifier: AnyObject!) {
    if let task = downloadIdentifier as? RetrieveImageTask {
      task.cancel()
    }
  }
}