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

extension Term {
	public func evaluate(environment: [Name:Term] = [:]) throws -> Term {
		switch out {
		case let .Variable(i):
			guard let found = environment[i] else { throw "Illegal free variable \(i)" }
			return found

		case let .Application(a, b):
			let aʹ = try a.evaluate(environment)
			guard case let .Lambda(i, _, body) = aʹ.out else { throw "Illegal application of non-lambda term \(a)↓\(aʹ) to \(b)" }
			return try body.substitute(i, b.evaluate(environment)).evaluate(environment)

		default:
			return self
		}
	}
}

Rephrase Application evaluation as a nested switch.

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

extension Term {
	public func evaluate(environment: [Name:Term] = [:]) throws -> Term {
		switch out {
		case let .Variable(i):
			guard let found = environment[i] else { throw "Illegal free variable \(i)" }
			return found

		case let .Application(a, b):
			let aʹ = try a.evaluate(environment)
			switch aʹ.out {
			case let .Lambda(i, _, body):
				return try body.substitute(i, b.evaluate(environment)).evaluate(environment)
			default:
				throw "Illegal application of non-lambda term \(a)↓\(aʹ) to \(b)"
			}

		default:
			return self
		}
	}
}


import XCPlayground
import KsApi
import ReactiveCocoa
import Alamofire
import struct Models.Category
import enum Result.NoError

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

let service = Service.shared

let categories = service.fetchCategories()
  .flatMap(FlattenStrategy.Concat) { SignalProducer<Category, ErrorEnvelope>(values: $0) }
  .filter { c in c.isRoot }
  .replayLazily(1)

categories
  .map { c in c.name }
  .startWithNext { c in
    print("Root category ----> \(c)")
}

categories
  .map { c in DiscoveryParams(category: c, sort: .Popular, perPage: 1) }
  .flatMap(.Merge, transform: service.fetchProject)
  .map { p in (p.name, p.category.name) }
  .startWithNext { data in
    print("Project -----> \(data)")
}

Use fully specified imports in playground too.

import XCPlayground
import KsApi
import struct ReactiveCocoa.SignalProducer
import enum ReactiveCocoa.FlattenStrategy
import struct Models.Category
import enum Result.NoError

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

let service = Service.shared

let categories = service.fetchCategories()
  .flatMap(.Concat) { SignalProducer<Category, ErrorEnvelope>(values: $0) }
  .filter { c in c.isRoot }
  .replayLazily(1)

categories
  .map { c in c.name }
  .startWithNext { c in
    print("Root category ----> \(c)")
}

categories
  .map { c in DiscoveryParams(category: c, sort: .Popular, perPage: 1) }
  .flatMap(.Merge, transform: service.fetchProject)
  .map { p in (p.name, p.category.name) }
  .startWithNext { data in
    print("Project -----> \(data)")
}


struct Card {
  var rank: Rank
  var suit: Suit
}

extension Card: Equatable { }
func == (lhs: Card, rhs: Card) -> Bool {
    return lhs.rank == rhs.rank && lhs.suit == rhs.suit
}

Use let instead of var

struct Card {
  let rank: Rank
  let suit: Suit
}

extension Card: Equatable { }
func == (lhs: Card, rhs: Card) -> Bool {
    return lhs.rank == rhs.rank && lhs.suit == rhs.suit
}


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

import UIKit

class WebViewController: UIViewController {
    let webView = UIWebView()

    convenience init(URL: NSURL) {
        self.init()

        let request = NSURLRequest(URL: URL)
        self.webView.loadRequest(request)
    }

    convenience init(HTML: String) {
        self.init()

        self.webView.loadHTMLString(HTML, baseURL: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.addFillingSubview(self.webView)
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        self.webView.scrollView.scrollEnabled = self.webView.scrollView.contentSize.height > self.webView.bounds.height
    }
}

Make web view controller public

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

import UIKit

public class WebViewController: UIViewController {
    let webView = UIWebView()

    public convenience init(URL: NSURL) {
        self.init()

        let request = NSURLRequest(URL: URL)
        self.webView.loadRequest(request)
    }

    public convenience init(HTML: String) {
        self.init()

        self.webView.loadHTMLString(HTML, baseURL: nil)
    }

    override public func viewDidLoad() {
        super.viewDidLoad()

        self.view.addFillingSubview(self.webView)
    }

    override public func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        self.webView.scrollView.scrollEnabled = self.webView.scrollView.contentSize.height > self.webView.bounds.height
    }
}


//
//  AspectRatioConstrainedImageView.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 24/06/2018.
//  Copyright © 2018 Eurofurence. All rights reserved.
//

import UIKit

class AspectRatioConstrainedImageView: UIImageView {

    override var image: UIImage? {
        didSet {
            if let size = image?.size {
                applyAspectRatioImageConstraints(size: size)
            }
        }
    }

    private func applyAspectRatioImageConstraints(size: CGSize) {
        let aspectRatio = size.width / size.height
        let aspectRatioConstraint = widthAnchor.constraint(equalTo: heightAnchor, multiplier: aspectRatio)
        aspectRatioConstraint.priority = UILayoutPriority(999)
        aspectRatioConstraint.isActive = true
    }

}

Fix aspect ratio when changing image

//
//  AspectRatioConstrainedImageView.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 24/06/2018.
//  Copyright © 2018 Eurofurence. All rights reserved.
//

import UIKit

class AspectRatioConstrainedImageView: UIImageView {

    private var aspectRatioConstraint: NSLayoutConstraint?

    override var image: UIImage? {
        didSet {
            aspectRatioConstraint.let(removeConstraint)
            aspectRatioConstraint = nil

            image.let { (image) in
                let size = image.size
                let constraint = NSLayoutConstraint(item: self,
                                                    attribute: .width,
                                                    relatedBy: .equal,
                                                    toItem: self,
                                                    attribute: .height,
                                                    multiplier: size.width / size.height,
                                                    constant: 0)
                addConstraint(constraint)
                aspectRatioConstraint = constraint
            }
        }
    }

}


import ReSwift

func appReducer(action: Action, state: AppState?) -> AppState {
    var state = state ?? AppState()

    switch action {
    case let action as FetchAction:
        guard var itemList = state.tabs[action.itemType] else {
            return state
        }
        switch action.action {
        case .fetch:
            itemList.fetchingMore = true
        case let .fetchedIds(ids):
            itemList.ids = ids
            itemList.fetchingMore = false
        case .fetchItems(_):
            itemList.fetchingMore = true
        case let .fetchedItems(items):
            itemList.items += items
            itemList.fetchingMore = false
        }
        state.tabs[action.itemType] = itemList
    case let action as ItemListAction:
        switch action {
        case let .view(item):
            state.selectedItem = ItemDetails(item)
        case .dismiss(_):
            state.selectedItem = .none
        }
    case let action as CommentFetchAction:
        switch action {
        case .fetch(comments: _):
            state.selectedItem?.fetchingMore = true
        case let .fetched(comments: comments):
            state.selectedItem?.comments += comments
            state.selectedItem?.fetchingMore = false
        }
    default:
        break
    }

    return state
}

Stop spinner flashing on first load of items

import ReSwift

func appReducer(action: Action, state: AppState?) -> AppState {
    var state = state ?? AppState()

    switch action {
    case let action as FetchAction:
        guard var itemList = state.tabs[action.itemType] else {
            return state
        }
        switch action.action {
        case .fetch:
            itemList.fetchingMore = true
        case let .fetchedIds(ids):
            itemList.ids = ids
            itemList.fetchingMore = true
        case .fetchItems(_):
            itemList.fetchingMore = true
        case let .fetchedItems(items):
            itemList.items += items
            itemList.fetchingMore = false
        }
        state.tabs[action.itemType] = itemList
    case let action as ItemListAction:
        switch action {
        case let .view(item):
            state.selectedItem = ItemDetails(item)
        case .dismiss(_):
            state.selectedItem = .none
        }
    case let action as CommentFetchAction:
        switch action {
        case .fetch(comments: _):
            state.selectedItem?.fetchingMore = true
        case let .fetched(comments: comments):
            state.selectedItem?.comments += comments
            state.selectedItem?.fetchingMore = false
        }
    default:
        break
    }

    return state
}


import Foundation

public final class Observable<T> {

    public typealias Observer = (T) -> Void

    private var observers: [Int: Observer] = [:]
    private var uniqueID = (0...).makeIterator()

    public var value: T {
        didSet {
            observers.values.forEach { $0(value) }
        }
    }

    public init(_ value: T) {
        self.value = value
    }

    public func observe(_ observer: @escaping Observer) -> Disposable {
        guard let id = uniqueID.next() else { fatalError("There should always be a next unique id") }

        observers[id] = observer
        observer(value)

        let disposable = Disposable {
            self.observers[id] = nil
        }

        return disposable
    }

    public func removeAllObservers() {
        observers.removeAll()
    }
}

Add old value to observers.

import Foundation

public final class Observable<T> {

    public typealias Observer = (T, T?) -> Void

    private var observers: [Int: Observer] = [:]
    private var uniqueID = (0...).makeIterator()

    public var value: T {
        didSet {
            observers.values.forEach { $0(value, oldValue) }
        }
    }

    public init(_ value: T) {
        self.value = value
    }

    public func observe(_ observer: @escaping Observer) -> Disposable {
        guard let id = uniqueID.next() else { fatalError("There should always be a next unique id") }

        observers[id] = observer
        observer(value, nil)

        let disposable = Disposable {
            self.observers[id] = nil
        }

        return disposable
    }

    public func removeAllObservers() {
        observers.removeAll()
    }
}


//
//  NuimoTests.swift
//  NuimoTests
//
//  Created by Lars Blumberg on 12/11/15.
//  Copyright © 2015 senic. All rights reserved.
//

import XCTest
@testable import Nuimo

class NuimoTests: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }

    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measureBlock {
            // Put the code you want to measure the time of here.
        }
    }

}

Test nuimo controller is discovered

//
//  NuimoTests.swift
//  NuimoTests
//
//  Created by Lars Blumberg on 12/11/15.
//  Copyright © 2015 senic. All rights reserved.
//

import XCTest
@testable import Nuimo

class NuimoTests: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testDiscoveryManagerDiscoversNuimoController() {
        let expectation = expectationWithDescription("Discovery manager should discover nuimo controller")
        let discovery = NuimoDiscoveryManager()
        let testDelegate = NuimoDiscoveryTestDelegate()
        testDelegate.onDiscoverController = { _ in
            discovery.stopDiscovery()
            expectation.fulfill()
        }
        discovery.delegate = testDelegate
        discovery.startDiscovery()
        waitForExpectationsWithTimeout(10.0, handler: { (error) in
            if let _ = error {
                XCTFail("Nuimo controller not discovered before timeout")
            }
        })
    }
}

class NuimoDiscoveryTestDelegate : NuimoDiscoveryDelegate {
    var onDiscoverController: ((NuimoController) -> Void)? = nil

    func nuimoDiscoveryManager(discovery: NuimoDiscoveryManager, didDiscoverNuimoController controller: NuimoController) {
        onDiscoverController?(controller)
    }
}


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

final class ChurchSumTests: XCTestCase {}

import Manifold
import XCTest

Test that the church-encoded sum module typechecks.

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

final class ChurchSumTests: XCTestCase {
	func testModuleTypechecks() {
		module.typecheck().forEach { XCTFail($0.description) }
	}
}

private let module = Module<Term>.churchSum

import Manifold
import XCTest


//
//  Date.swift
//  ZXFoundation
//
//  Created by Wyatt McBain on 10/12/16.
//  Copyright © 2016 ZX Ventures. All rights reserved.
//

import Foundation

extension Date {

    /**
     Represents the date as a String in HH:mm format.
     */
    public var hourMinute: String {
        return DateFormatter.usLocale(with: "HH:mm").string(from: self)
    }

    /**
     Represents the date in MMMM d, yyyy format.
     */
    public var monthDayYear: String {
        return DateFormatter.usLocale(with: "MMMM d, yyyy").string(from: self)
    }
}

extension Date {

    /**
     Creates a Date from a IOS8601 formatted String. Will return
     a full date including a timezone.

     - parameter from: The ISO8601 date string: `yyyy-MM-dd'T'HH:mm:ssZZZZZ`
     - throws: Error if date can't be created from the string.
     - returns: The date formatted from the string.
     */
    public static func iso8601Date(from dateString: String) throws -> Date {
        let formatter = DateFormatter.usLocale(with: "yyyy-MM-dd'T'HH:mm:ssZZZZZ")
        guard let date = formatter.date(from: dateString) else { throw BaseError.unexpectedNil }
        return date
    }
}

Add fallback for non-timezone ISO8601 date

//
//  Date.swift
//  ZXFoundation
//
//  Created by Wyatt McBain on 10/12/16.
//  Copyright © 2016 ZX Ventures. All rights reserved.
//

import Foundation

extension Date {

    /**
     Represents the date as a String in HH:mm format.
     */
    public var hourMinute: String {
        return DateFormatter.usLocale(with: "HH:mm").string(from: self)
    }

    /**
     Represents the date in MMMM d, yyyy format.
     */
    public var monthDayYear: String {
        return DateFormatter.usLocale(with: "MMMM d, yyyy").string(from: self)
    }
}

extension Date {

    /**
     Creates a Date from a IOS8601 formatted String. Will return
     a full date including a timezone.

     - parameter from: The ISO8601 date string: `yyyy-MM-dd'T'HH:mm:ssZZZZZ`
     - throws: Error if date can't be created from the string.
     - returns: The date formatted from the string.
     */
    public static func iso8601Date(from dateString: String) throws -> Date {

        let formatter = DateFormatter.usLocale(with: "yyyy-MM-dd'T'HH:mm:ssZZZZZ")
        guard let date = formatter.date(from: dateString) else {

            // Attempt to fall back before throwing error
            let formatter = DateFormatter.usLocale(with: "yyyy-MM-dd'T'HH:mm:ss")
            guard let date = formatter.date(from: dateString) else {

                throw BaseError.unexpectedNil
            }
            return date
        }
        return date
    }
}


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

import Foundation

var kvoContext = 0

class Model : NSObject {
  dynamic var name = ""
  dynamic var number = 0
}

class Observer : NSObject {
  let model = Model()

  override init() {
    super.init()
    model.addObserver(self, forKeyPath: "name", options: nil, context: &kvoContext)
    self.addObserver(self, forKeyPath: "model.number", options: nil, context: &kvoContext)
  }

  deinit {
    self.removeObserver(self, forKeyPath: "model.number")
    model.removeObserver(self, forKeyPath: "name")
  }

  func test() {
    model.name = "abc"
    model.number = 42
  }

  override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafeMutablePointer<Void>) {
    if context != &kvoContext {
      return super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
    }

    println(object.valueForKeyPath(keyPath))
  }
}

// CHECK: abc
// CHECK-NEXT: 42
Observer().test()

class Foo: NSObject {
  let foo = 0
}

let foo = Foo()
foo.addObserver(foo, forKeyPath: "foo", options: nil, context: &kvoContext)
let bar = foo.foo
// CHECK-NEXT: 0
println(bar)

Fix signature of observeValueForKeyPath(_:ofObject:change:context:) to match SDK changes.

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

import Foundation

var kvoContext = 0

class Model : NSObject {
  dynamic var name = ""
  dynamic var number = 0
}

class Observer : NSObject {
  let model = Model()

  override init() {
    super.init()
    model.addObserver(self, forKeyPath: "name", options: nil, context: &kvoContext)
    self.addObserver(self, forKeyPath: "model.number", options: nil, context: &kvoContext)
  }

  deinit {
    self.removeObserver(self, forKeyPath: "model.number")
    model.removeObserver(self, forKeyPath: "name")
  }

  func test() {
    model.name = "abc"
    model.number = 42
  }

  override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
    if context != &kvoContext {
      return super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
    }

    println(object.valueForKeyPath(keyPath))
  }
}

// CHECK: abc
// CHECK-NEXT: 42
Observer().test()

class Foo: NSObject {
  let foo = 0
}

let foo = Foo()
foo.addObserver(foo, forKeyPath: "foo", options: nil, context: &kvoContext)
let bar = foo.foo
// CHECK-NEXT: 0
println(bar)


//
//  Blocks.swift
//  ledger-wallet-ios
//
//  Created by Nicolas Bigot on 22/01/2015.
//  Copyright (c) 2015 Ledger. All rights reserved.
//

import Foundation

func deferOnMainQueue(closure: () -> ()) {
    delayOnMainQueue(0, closure)
}

func delayOnMainQueue(delay: Double, closure: () -> ()) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), closure)
}

func dispatchAsyncOnMainQueue(closure: () -> ()) {
    dispatch_async(dispatch_get_main_queue(), closure)
}

func dispatchSyncOnMainQueue(closure: () -> ()) {
    dispatch_sync(dispatch_get_main_queue(), closure)
}

Revert "Add `deferOnMainQueue` blocks method"

//
//  Blocks.swift
//  ledger-wallet-ios
//
//  Created by Nicolas Bigot on 22/01/2015.
//  Copyright (c) 2015 Ledger. All rights reserved.
//

import Foundation

func delayOnMainQueue(delay: Double, closure: () -> ()) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), closure)
}

func dispatchAsyncOnMainQueue(closure: () -> ()) {
    dispatch_async(dispatch_get_main_queue(), closure)
}

func dispatchSyncOnMainQueue(closure: () -> ()) {
    dispatch_sync(dispatch_get_main_queue(), closure)
}


//
//  Uploadable.swift
//  FirebaseCommunity
//
//  Created by David Sanford on 15/08/17.
//

import Foundation

public protocol Uploadable {

    var path: String? { get set }
    var data: Data? { get }

    func upload(fileName: String, path: String)
}

Add progress method to uploadable protocol

//
//  Uploadable.swift
//  FirebaseCommunity
//
//  Created by David Sanford on 15/08/17.
//

import Foundation

public typealias ProgressObserver = (_ progress: Double) -> Void

public protocol Uploadable {

    var path: String? { get set }
    var data: Data? { get }

    func upload(fileName: String, path: String, onProgress: ProgressObserver?)
    func observeUploadProgress(onProgress: @escaping (_ progress: Double) -> Void)
}


//
//  ActivityDataTests.swift
//  NVActivityIndicatorViewDemo
//
//  Created by Nguyen Vinh on 9/7/16.
//  Copyright © 2016 Nguyen Vinh. All rights reserved.
//

import XCTest
@testable import NVActivityIndicatorView

class ActivityDataTests: XCTestCase {

    func testInitWithoutParams() {
        let activityData = ActivityData()

        XCTAssertEqual(activityData.size, NVActivityIndicatorView.DEFAULT_BLOCKER_SIZE)
        XCTAssertNil(activityData.message)
        XCTAssertEqual(activityData.type, NVActivityIndicatorView.DEFAULT_TYPE)
        XCTAssertEqual(activityData.color, NVActivityIndicatorView.DEFAULT_COLOR)
        XCTAssertEqual(activityData.padding, NVActivityIndicatorView.DEFAULT_PADDING)
        XCTAssertEqual(activityData.displayTimeThreshold, NVActivityIndicatorView.DEFAULT_BLOCKER_DISPLAY_TIME_THRESHOLD)
        XCTAssertEqual(activityData.minimumDisplayTime, NVActivityIndicatorView.DEFAULT_BLOCKER_MINIMUM_DISPLAY_TIME)
    }
}

Test init ActivityData with params

//
//  ActivityDataTests.swift
//  NVActivityIndicatorViewDemo
//
//  Created by Nguyen Vinh on 9/7/16.
//  Copyright © 2016 Nguyen Vinh. All rights reserved.
//

import XCTest
@testable import NVActivityIndicatorView

class ActivityDataTests: XCTestCase {

    func testInitWithoutParams() {
        let activityData = ActivityData()

        XCTAssertEqual(activityData.size, NVActivityIndicatorView.DEFAULT_BLOCKER_SIZE)
        XCTAssertNil(activityData.message)
        XCTAssertEqual(activityData.type, NVActivityIndicatorView.DEFAULT_TYPE)
        XCTAssertEqual(activityData.color, NVActivityIndicatorView.DEFAULT_COLOR)
        XCTAssertEqual(activityData.padding, NVActivityIndicatorView.DEFAULT_PADDING)
        XCTAssertEqual(activityData.displayTimeThreshold, NVActivityIndicatorView.DEFAULT_BLOCKER_DISPLAY_TIME_THRESHOLD)
        XCTAssertEqual(activityData.minimumDisplayTime, NVActivityIndicatorView.DEFAULT_BLOCKER_MINIMUM_DISPLAY_TIME)
    }

    func testInitWithParams() {
        let size = CGSize(width: 100, height: 100)
        let message = "Loading..."
        let type = NVActivityIndicatorType.BallBeat
        let color = UIColor.redColor()
        let padding: CGFloat = 10
        let displayTimeThreshold = 100
        let minimumDisplayTime = 150
        let activityData = ActivityData(size: size,
                                        message: message,
                                        type: type,
                                        color: color,
                                        padding: padding,
                                        displayTimeThreshold: displayTimeThreshold,
                                        minimumDisplayTime: minimumDisplayTime)

        XCTAssertEqual(activityData.size, size)
        XCTAssertEqual(activityData.message, message)
        XCTAssertEqual(activityData.type, type)
        XCTAssertEqual(activityData.color, color)
        XCTAssertEqual(activityData.padding, padding)
        XCTAssertEqual(activityData.displayTimeThreshold, displayTimeThreshold)
        XCTAssertEqual(activityData.minimumDisplayTime, minimumDisplayTime)
    }
}


//  Copyright © 2017 Compass. All rights reserved.

import Foundation
import XCTest
@testable import Snail

class UniqueTests: XCTestCase {
    func testVariableChanges() {
        var events: [String?] = []
        let subject = Unique<String?>(nil)
        subject.asObservable().subscribe(
            onNext: { string in events.append(string) }
        )
        subject.value = nil
        subject.value = "1"
        subject.value = "2"
        subject.value = "2"
        subject.value = "2"
        XCTAssert(events[0] == "1")
        XCTAssert(events[1] == "2")
        XCTAssert(subject.value == "2")
        XCTAssert(events.count == 2)
    }

    func testVariableNotifiesOnSubscribe() {
        let subject = Unique("initial")
        subject.value = "new"
        var result: String?

        subject.asObservable().subscribe(onNext: { string in
            result = string
        })

        XCTAssertEqual("new", result)
    }

    func testVariableNotifiesInitialOnSubscribe() {
        let subject = Unique<String?>(nil)
        var result: String?

        subject.asObservable().subscribe(onNext: { string in
            result = string
        })

        XCTAssertEqual(nil, result)
    }
}

Test Unique handles Equatable Arrays.

//  Copyright © 2017 Compass. All rights reserved.

import Foundation
import XCTest
@testable import Snail

class UniqueTests: XCTestCase {
    func testVariableChanges() {
        var events: [String?] = []
        let subject = Unique<String?>(nil)
        subject.asObservable().subscribe(
            onNext: { string in events.append(string) }
        )
        subject.value = nil
        subject.value = "1"
        subject.value = "2"
        subject.value = "2"
        subject.value = "2"
        XCTAssert(events[0] == "1")
        XCTAssert(events[1] == "2")
        XCTAssert(subject.value == "2")
        XCTAssert(events.count == 2)
    }

    func testVariableNotifiesOnSubscribe() {
        let subject = Unique("initial")
        subject.value = "new"
        var result: String?

        subject.asObservable().subscribe(onNext: { string in
            result = string
        })

        XCTAssertEqual("new", result)
    }

    func testVariableNotifiesInitialOnSubscribe() {
        let subject = Unique<String?>(nil)
        var result: String?

        subject.asObservable().subscribe(onNext: { string in
            result = string
        })

        XCTAssertEqual(nil, result)
    }

    func testVariableHandlesEquatableArrays() {
        var events: [[String]] = []
        let subject = Unique<[String]>(["1", "2"])
        subject.asObservable().subscribe(
            onNext: { array in events.append(array) }
        )
        subject.value = ["1", "2"]
        subject.value = ["2", "1"]
        subject.value = ["2", "1"]
        subject.value = ["1", "2"]
        XCTAssert(events[0] == ["2", "1"])
        XCTAssert(events[1] == ["1", "2"])
    }
}


// Vuckt
// @author: Slipp Douglas Thompson
// @license: Public Domain per The Unlicense.  See accompanying LICENSE file or <http://unlicense.org/>.

import Foundation

#if !swift(>=4.2)
	internal extension Float
	{
		static func random(in range:Range<Float>) -> Float {
			let delta = range.upperBound - range.lowerBound
			return Float(arc4random_uniform(UInt32.max)) / Float(UInt32.max - 1) * delta + range.lowerBound
		}
		static func random(in range:ClosedRange<Float>) -> Float {
			let delta = range.upperBound - range.lowerBound
			return Float(arc4random_uniform(UInt32.max)) / Float(UInt32.max) * delta + range.lowerBound
		}
	}

	internal extension Int32
	{
		static func random(in range:Range<Int32>) -> Int32 {
			let delta = UInt32(range.upperBound - range.lowerBound)
			return Int32(arc4random_uniform(delta)) + range.lowerBound
		}
		static func random(in range:ClosedRange<Int32>) -> Int32 {
			let delta = UInt32(range.upperBound - range.lowerBound)
			return Int32(arc4random_uniform(delta + 1)) + range.lowerBound
		}
	}
#endif

Fix for Swift 4.0 compat re `range(in:)`

// Vuckt
// @author: Slipp Douglas Thompson
// @license: Public Domain per The Unlicense.  See accompanying LICENSE file or <http://unlicense.org/>.

import Foundation

#if !swift(>=4.2)
	internal extension Float
	{
		@inlinable static func random(in range:Range<Float>) -> Float {
			let delta = range.upperBound - range.lowerBound
			return Float(arc4random_uniform(UInt32.max)) / Float(UInt32.max - 1) * delta + range.lowerBound
		}
		@inlinable static func random(in range:ClosedRange<Float>) -> Float {
			let delta = range.upperBound - range.lowerBound
			return Float(arc4random_uniform(UInt32.max)) / Float(UInt32.max) * delta + range.lowerBound
		}
	}

	internal extension Int32
	{
		@inlinable static func random(in range:Range<Int32>) -> Int32 {
			let delta = UInt32(range.upperBound - range.lowerBound)
			return Int32(arc4random_uniform(delta)) + range.lowerBound
		}
		@inlinable static func random(in range:ClosedRange<Int32>) -> Int32 {
			let delta = UInt32(range.upperBound - range.lowerBound)
			return Int32(arc4random_uniform(delta + 1)) + range.lowerBound
		}
	}
#endif


// https://github.com/Quick/Quick

import Quick
import Nimble
import SwiftVersionUtils

class TableOfContentsSpec: QuickSpec {
    override func spec() {
        describe("Version Info file") {

            it("has build 'number'") {
                expect("1 Test") == SwiftVersionUtils.getBuildNumber()
            }

            it("has version name") {
                expect("1.0 Test") == SwiftVersionUtils.getVersion()
            }
        }
    }
}

Add fail test for travis error check

// https://github.com/Quick/Quick

import Quick
import Nimble
import SwiftVersionUtils

class TableOfContentsSpec: QuickSpec {
    override func spec() {
        describe("Version Info file") {

            it("has build 'number'") {
                expect("1 Test") == SwiftVersionUtils.getBuildNumber()
            }

            it("has version name") {
                expect("1.0 Test") == SwiftVersionUtils.getVersion()
            }

            it("will fail for travis test") {
                expect("TestFail") == "TestPass"
            }
        }
    }
}


// RUN: %empty-directory(%t)
// RUN: %validate-incrparse %s --test-case STRING

// SR-8995 rdar://problem/45259469

self = <<STRING<|||_                            _>>>foo(1)[object1, object2] + o bar(1)

Migrate test suite to GH issues: incrParse

// RUN: %empty-directory(%t)
// RUN: %validate-incrparse %s --test-case STRING

// rdar://problem/45259469
// https://github.com/apple/swift/issues/51498

self = <<STRING<|||_                            _>>>foo(1)[object1, object2] + o bar(1)


/*
 This source file is part of the Swift.org open source project

 Copyright (c) 2014 - 2017 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 Swift project authors
*/

import XCTest
import SPMTestSupport

import TSCBasic

class ResourcesTests: XCTestCase {
    func testSimpleResources() {
        fixture(name: "Resources/Simple") { prefix in
            var executables = ["SwiftyResource"]

            // Objective-C module requires macOS
            #if os(macOS)
            executables.append("SeaResource")
            #endif

            for execName in executables {
                let (output, _) = try executeSwiftRun(prefix, execName)
                XCTAssertTrue(output.contains("foo"), output)
            }
        }
    }

    func testLocalizedResources() {
        fixture(name: "Resources/Localized") { prefix in
            try executeSwiftBuild(prefix)

            let exec = prefix.appending(RelativePath(".build/debug/exe"))
            let output = try Process.checkNonZeroExit(args: exec.pathString)
            XCTAssertEqual(output, """
                ¡Hola Mundo!
                Hallo Welt!
                Bonjour le monde !

                """)
        }
    }
}

Make localization test more robust

/*
 This source file is part of the Swift.org open source project

 Copyright (c) 2014 - 2017 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 Swift project authors
*/

import XCTest
import SPMTestSupport

import TSCBasic

class ResourcesTests: XCTestCase {
    func testSimpleResources() {
        fixture(name: "Resources/Simple") { prefix in
            var executables = ["SwiftyResource"]

            // Objective-C module requires macOS
            #if os(macOS)
            executables.append("SeaResource")
            #endif

            for execName in executables {
                let (output, _) = try executeSwiftRun(prefix, execName)
                XCTAssertTrue(output.contains("foo"), output)
            }
        }
    }

    func testLocalizedResources() {
        fixture(name: "Resources/Localized") { prefix in
            try executeSwiftBuild(prefix)

            let exec = prefix.appending(RelativePath(".build/debug/exe"))
            // Note: <rdar://problem/59738569> Source from LANG and -AppleLanguages on command line for Linux resources
            let output = try Process.checkNonZeroExit(args: exec.pathString, "-AppleLanguages", "(en_US)")
            XCTAssertEqual(output, """
                ¡Hola Mundo!
                Hallo Welt!
                Bonjour le monde !

                """)
        }
    }
}


import Foundation

class MockFunc<Input, Output> {
    typealias MockedFunc = (Input) -> (Output)
    var calls: [(Input)] = []
    var result: (Output)!

    func call(input: Input) -> (Output) {
        calls.append(input)
        return result
    }
}

Add when() method to replace result field

import Foundation

class MockFunc<Input, Output> {
    typealias MockedFunc = (Input) -> (Output)
    typealias Callback = (Input) -> (Output)

    var calls: [(Input)] = []
    var callback: Callback!

    func call(input: Input) -> (Output) {
        calls.append(input)
        return callback(input)
    }

    func when(callback: Callback) {
        self.callback = callback
    }
}


import Foundation

public class Playback: UIBaseObject {
    public internal(set) var url: NSURL

    public required init(url: NSURL) {
        self.url = url
        super.init(frame: CGRect.zero)
    }

    public required init?(coder aDecoder: NSCoder) {
        fatalError("Use init(url: NSURL) instead")
    }

    public func destroy() {
        self.removeFromSuperview()
        self.stopListening()
    }

    public class func canPlay(url: NSURL) -> Bool {
        return false
    }

    public func settings() -> [String : AnyObject] {
        return [:]
    }

    public func duration() -> Double {
        return 0
    }

    public func type() -> PlaybackType {
        return .Unknown
    }

    public func isPlaying() -> Bool {
        return false
    }

    public func isHighDefinitionInUse() -> Bool {
        return false
    }

    internal func trigger(event: PlaybackEvent) {
        trigger(event.rawValue)
    }

    internal func trigger(event: PlaybackEvent, userInfo: EventUserInfo) {
        trigger(event.rawValue, userInfo: userInfo)
    }

    public func play() {}
    public func pause() {}
    public func stop() {}
    public func seekTo(timeInterval: NSTimeInterval) {}
}

Remove user interaction with playback

import Foundation

public class Playback: UIBaseObject {
    public internal(set) var url: NSURL

    public required init(url: NSURL) {
        self.url = url
        super.init(frame: CGRect.zero)
        userInteractionEnabled = false
    }

    public required init?(coder aDecoder: NSCoder) {
        fatalError("Use init(url: NSURL) instead")
    }

    public func destroy() {
        self.removeFromSuperview()
        self.stopListening()
    }

    public class func canPlay(url: NSURL) -> Bool {
        return false
    }

    public func settings() -> [String : AnyObject] {
        return [:]
    }

    public func duration() -> Double {
        return 0
    }

    public func type() -> PlaybackType {
        return .Unknown
    }

    public func isPlaying() -> Bool {
        return false
    }

    public func isHighDefinitionInUse() -> Bool {
        return false
    }

    internal func trigger(event: PlaybackEvent) {
        trigger(event.rawValue)
    }

    internal func trigger(event: PlaybackEvent, userInfo: EventUserInfo) {
        trigger(event.rawValue, userInfo: userInfo)
    }

    public func play() {}
    public func pause() {}
    public func stop() {}
    public func seekTo(timeInterval: NSTimeInterval) {}
}


import ReactiveCocoa

struct AppState {
    let todos = MutableProperty([
        Todo(name: "Create example app", completed: true),
        Todo(name: "Celebrate", completed: false),
    ])

    let filter = MutableProperty(TodoFilter.All)
}

Increase amount of initial todos

import ReactiveCocoa

private let initialTodos = [
    Todo(name: "Have tea with the Queen", completed: true),
    Todo(name: "Circumnavigate the globe", completed: false),
    Todo(name: "Race a cheetah", completed: false),
    Todo(name: "Climb Mount Everest", completed: true),
    Todo(name: "Jump out of a plane", completed: false),
    Todo(name: "Read a book", completed: false),
]

struct AppState {
    let todos = MutableProperty(initialTodos)
    let filter = MutableProperty(TodoFilter.All)
}


func main() -> Int {
  let names = ["foo", "patatino"]

  var reversedNames = names.sorted(by: {
    $0 > $1 } //%self.expect('p $0', substrs=['patatino'])
              //%self.expect('p $1', substrs=['foo'])
              //%self.expect('frame var $0', substrs=['patatino'])
              //%self.expect('frame var $1', substrs=['foo'])
  )

  return 0
}

_ = main()

Add tests for the fixed closure behaviour.

func main() -> Int {
  let names = ["foo", "patatino"]

  var reversedNames = names.sorted(by: {
    $0 > $1 } //%self.expect('p $0', substrs=['patatino'])
              //%self.expect('p $1', substrs=['foo'])
              //%self.expect('frame var $0', substrs=['patatino'])
              //%self.expect('frame var $1', substrs=['foo'])
  )

  var tinky = [1,2].map({$0 * 2})

  return 0 //%self.expect('expr tinky.map({$0 * 2})', substrs=['[0] = 2', '[1] = 4'])
           //%self.expect('expr [2,4].map({$0 * 2})', substrs=['[0] = 4', '[1] = 8'])
           //%self.expect('expr $0', substrs=['unresolved identifier \'$0\''], error=True)
}

_ = main()


/*
 |  _   ____   ____   _
 | | |‾|  ⚈ |-| ⚈  |‾| |
 | | |  ‾‾‾‾| |‾‾‾‾  | |
 |  ‾        ‾        ‾
 */

import UIKit

@IBDesignable open class CustomTableView: UITableView, BackgroundColorNameable {

    // MARK: - Inspectable properties

    @IBInspectable open var backgroundColorName: String? {
        didSet {
            applyBackgroundColorName()
        }
    }

    @IBInspectable open var separatorColorName: String? {
        didSet {
            updateSeparatorColor()
        }
    }

    // MARK: - Initializers

    override public init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame: frame, style: style)
        registerForNotifications()
    }

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

    // MARK: - Functions

    func registerForNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(updateColors), name: Notification.Name.AppearanceColorsUpdated, object: nil)
    }

    func updateColors() {
        applyBackgroundColorName()
        updateSeparatorColor()
    }

    func updateSeparatorColor() {
        separatorColor = UIColor(named: separatorColorName)
    }

}

Fix issue with separator color override

/*
 |  _   ____   ____   _
 | | |‾|  ⚈ |-| ⚈  |‾| |
 | | |  ‾‾‾‾| |‾‾‾‾  | |
 |  ‾        ‾        ‾
 */

import UIKit

@IBDesignable open class CustomTableView: UITableView, BackgroundColorNameable {

    // MARK: - Inspectable properties

    @IBInspectable open var backgroundColorName: String? {
        didSet {
            applyBackgroundColorName()
        }
    }

    @IBInspectable open var separatorColorName: String? {
        didSet {
            updateSeparatorColor()
        }
    }

    // MARK: - Initializers

    override public init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame: frame, style: style)
        registerForNotifications()
    }

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

    open override func awakeFromNib() {
        super.awakeFromNib()
        updateSeparatorColor()
    }

    // MARK: - Functions

    func registerForNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(updateColors), name: Notification.Name.AppearanceColorsUpdated, object: nil)
    }

    func updateColors() {
        applyBackgroundColorName()
        updateSeparatorColor()
    }

    func updateSeparatorColor() {
        separatorColor = UIColor(named: separatorColorName)
    }

}


// 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 {{use of unresolved identifier 'TextFi'}}
      }

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

Update a test case's expected output

// 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 { // expected-error{{type of expression is ambiguous without more context}}
      HStack {
        Text("")
        TextFi // expected-error {{use of unresolved identifier 'TextFi'}}
      }

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


//
//  ChartAxisValueDate.swift
//  swift_charts
//
//  Created by ischuetz on 01/03/15.
//  Copyright (c) 2015 ivanschuetz. All rights reserved.
//

import UIKit

public class ChartAxisValueDate: ChartAxisValue {

    private let formatter: (NSDate) -> String

    public var date: NSDate {
        return ChartAxisValueDate.dateFromScalar(self.scalar)
    }

    public init(date: NSDate, formatter: (NSDate) -> String, labelSettings: ChartLabelSettings = ChartLabelSettings()) {
        self.formatter = formatter
        super.init(scalar: ChartAxisValueDate.scalarFromDate(date), labelSettings: labelSettings)
    }

    convenience public init(date: NSDate, formatter: NSDateFormatter, labelSettings: ChartLabelSettings = ChartLabelSettings()) {
        self.init(date: date, formatter: { formatter.stringFromDate($0) }, labelSettings: labelSettings)
    }

    public class func dateFromScalar(scalar: Double) -> NSDate {
        return NSDate(timeIntervalSince1970: NSTimeInterval(scalar))
    }

    public class func scalarFromDate(date: NSDate) -> Double {
        return Double(date.timeIntervalSince1970)
    }

    // MARK: CustomStringConvertible

    override public var description: String {
        return self.formatter(self.date)
    }
}

Implement copy for date axis value

//
//  ChartAxisValueDate.swift
//  swift_charts
//
//  Created by ischuetz on 01/03/15.
//  Copyright (c) 2015 ivanschuetz. All rights reserved.
//

import UIKit

public class ChartAxisValueDate: ChartAxisValue {

    private let formatter: (NSDate) -> String

    public var date: NSDate {
        return ChartAxisValueDate.dateFromScalar(self.scalar)
    }

    public init(date: NSDate, formatter: (NSDate) -> String, labelSettings: ChartLabelSettings = ChartLabelSettings()) {
        self.formatter = formatter
        super.init(scalar: ChartAxisValueDate.scalarFromDate(date), labelSettings: labelSettings)
    }

    convenience public init(date: NSDate, formatter: NSDateFormatter, labelSettings: ChartLabelSettings = ChartLabelSettings()) {
        self.init(date: date, formatter: { formatter.stringFromDate($0) }, labelSettings: labelSettings)
    }

    public class func dateFromScalar(scalar: Double) -> NSDate {
        return NSDate(timeIntervalSince1970: NSTimeInterval(scalar))
    }

    public class func scalarFromDate(date: NSDate) -> Double {
        return Double(date.timeIntervalSince1970)
    }

    // MARK: CustomStringConvertible

    override public var description: String {
        return self.formatter(self.date)
    }

    public override func copy(scalar: Double) -> ChartAxisValue {
        return ChartAxisValueDate(date: ChartAxisValueDate.dateFromScalar(scalar), formatter: formatter, labelSettings: labelSettings)
    }
}


//
//  ViewController.swift
//  tvOS
//
//  Created by Isaac Overacker on 4/15/16.
//
//

import UIKit
import Moya

class ViewController: UIViewController {

    @IBOutlet weak var zenLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

    @IBAction func zenButtonTriggered(sender: UIButton) {
        GitHubProvider.request(.Zen) { result in
            switch result {
            case let .Success(response):
                do {
                    try response.filterSuccessfulStatusCodes()
                    self.zenLabel.text = try response.mapString()
                } catch {
                    print("Non-success status code returned from zen.")
                }
            case let .Failure(error):
                print("Failed to fetch zen from GitHub: \(error)")
            }
        }
    }
}

Fix build error in tvOS project.

//
//  ViewController.swift
//  tvOS
//
//  Created by Isaac Overacker on 4/15/16.
//
//

import UIKit
import Moya

class ViewController: UIViewController {

    var gitHubAPI: MoyaProvider<GitHub>!

    @IBOutlet weak var zenLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        gitHubAPI = MoyaProvider<GitHub>(plugins: [
            NetworkLoggerPlugin(verbose: true, responseDataFormatter: JSONResponseDataFormatter)
            ])
    }

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

    @IBAction func zenButtonTriggered(sender: UIButton) {
        gitHubAPI.request(.Zen) { result in
            switch result {
            case let .Success(response):
                do {
                    try response.filterSuccessfulStatusCodes()
                    self.zenLabel.text = try response.mapString()
                } catch {
                    print("Non-success status code returned from zen.")
                }
            case let .Failure(error):
                print("Failed to fetch zen from GitHub: \(error)")
            }
        }
    }
}


//
//  Created by Pierluigi Cifani on 18/02/2019.
//  Copyright © 2019 TheLeftBit. All rights reserved.
//

#if canImport(UIKit)
#if canImport(MessageUI)

import UIKit
import MessageUI

final public class MailComposerBehavior: NSObject, MFMailComposeViewControllerDelegate {
    public static let composer = MailComposerBehavior()

    public func mailViewController(email: String) -> UIViewController? {
        guard MFMailComposeViewController.canSendMail() else {
            return nil
        }
        let mailVC = MFMailComposeViewController()
        mailVC.mailComposeDelegate = self
        mailVC.setToRecipients([email])
        return mailVC
    }

    public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        controller.dismiss(animated: true, completion: nil)
    }
}

#endif
#endif

Rename MailComposerBehavior to MessageComposerBehavior and add SMS compose

//
//  Created by Pierluigi Cifani on 18/02/2019.
//  Copyright © 2019 TheLeftBit. All rights reserved.
//

#if canImport(UIKit)
#if canImport(MessageUI)

import UIKit
import MessageUI

final public class MessageComposerBehavior: NSObject, MFMailComposeViewControllerDelegate, MFMessageComposeViewControllerDelegate {
    public static let composer = MessageComposerBehavior()

    public func mailViewController(email: String) -> UIViewController? {
        guard MFMailComposeViewController.canSendMail() else {
            return nil
        }
        let mailVC = MFMailComposeViewController()
        mailVC.mailComposeDelegate = self
        mailVC.setToRecipients([email])
        return mailVC
    }

    public func smsViewController(phoneNumber: String) -> UIViewController? {
        guard MFMessageComposeViewController.canSendText() else {
            return nil
        }
        let smsVC = MFMessageComposeViewController()
        smsVC.messageComposeDelegate = self
        smsVC.recipients = [phoneNumber]
        return smsVC
    }

    public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        controller.dismiss(animated: true, completion: nil)
    }

    public func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {

        controller.dismiss(animated: true, completion: nil)
    }
}

#endif
#endif


import PeerKit
import MultipeerConnectivity

public class Node : Hashable, Equatable {

    // MARK: Properties
    public var displayName: String
    public var uniqueId: String

    init(uniqueId:String, displayName:String) {
        self.displayName = displayName
        self.uniqueId = uniqueId
    }

    convenience init(mcPeerId: MCPeerID) {
        self.init(uniqueId: mcPeerId.displayName.componentsSeparatedByString(PeerKit.delimiter)[1],
                  displayName: mcPeerId.displayName.componentsSeparatedByString(PeerKit.delimiter)[0])
    }

    convenience init(uniquePeerKitName: String) {
        self.init(uniqueId: uniquePeerKitName.componentsSeparatedByString(PeerKit.delimiter)[1],
                  displayName: uniquePeerKitName.componentsSeparatedByString(PeerKit.delimiter)[0])
    }

    public var hashValue: Int { return uniqueId.hash }
}

public func ==(lhs: Node, rhs: Node) -> Bool {
    return lhs.uniqueId == rhs.uniqueId
}

Update Id delimiter for PeerKit

import PeerKit
import MultipeerConnectivity

public class Node : Hashable, Equatable {

    // MARK: Properties
    public var displayName: String
    public var uniqueId: String

    init(uniqueId:String, displayName:String) {
        self.displayName = displayName
        self.uniqueId = uniqueId
    }

    convenience init(mcPeerId: MCPeerID) {
        self.init(uniqueId: mcPeerId.displayName.componentsSeparatedByString(PeerKit.ID_DELIMITER)[1],
                  displayName: mcPeerId.displayName.componentsSeparatedByString(PeerKit.ID_DELIMITER)[0])
    }

    convenience init(uniquePeerKitName: String) {
        self.init(uniqueId: uniquePeerKitName.componentsSeparatedByString(PeerKit.ID_DELIMITER)[1],
                  displayName: uniquePeerKitName.componentsSeparatedByString(PeerKit.ID_DELIMITER)[0])
    }

    public var hashValue: Int { return uniqueId.hash }
}

public func ==(lhs: Node, rhs: Node) -> Bool {
    return lhs.uniqueId == rhs.uniqueId
}


//
//  ObjectIdentityProvider.swift
//  Mixpanel
//
//  Created by Yarden Eitan on 8/29/16.
//  Copyright © 2016 Mixpanel. All rights reserved.
//

import Foundation

class ObjectIdentityProvider {
    let objectToIdentifierMap: NSMapTable<AnyObject, NSString>
    let sequenceGenerator = SequenceGenerator()

    init() {
        objectToIdentifierMap = NSMapTable(keyOptions: .weakMemory, valueOptions: .strongMemory)
    }

    func getIdentifier(for object: AnyObject) -> String {
        if let object = object as? String {
            return object
        }
        if let identifier = objectToIdentifierMap.object(forKey: object) {
            return identifier as String
        } else {
            let identifier = "$\(sequenceGenerator.next())" as NSString
            objectToIdentifierMap.setObject(identifier, forKey: object)
            return identifier as String
        }
    }

}

class SequenceGenerator {
    var value: Int32 = 0

    init() {
        value = 0
    }

    func next() -> Int32 {
        return OSAtomicAdd32(1, &value)
    }
}

Fix OSAtomicAdd32 deprecated warning in iOS 10

//
//  ObjectIdentityProvider.swift
//  Mixpanel
//
//  Created by Yarden Eitan on 8/29/16.
//  Copyright © 2016 Mixpanel. All rights reserved.
//

import Foundation

class ObjectIdentityProvider {
    let objectToIdentifierMap: NSMapTable<AnyObject, NSString>
    let sequenceGenerator = SequenceGenerator()

    init() {
        objectToIdentifierMap = NSMapTable(keyOptions: .weakMemory, valueOptions: .strongMemory)
    }

    func getIdentifier(for object: AnyObject) -> String {
        if let object = object as? String {
            return object
        }
        if let identifier = objectToIdentifierMap.object(forKey: object) {
            return identifier as String
        } else {
            let identifier = "$\(sequenceGenerator.next())" as NSString
            objectToIdentifierMap.setObject(identifier, forKey: object)
            return identifier as String
        }
    }

}

class SequenceGenerator {
    private var queue = DispatchQueue(label: "com.mixpanel.sequence.generator")
    private(set) var value: Int32 = 0

    init() {
        value = 0
    }

    func next() -> Int32 {
        queue.sync {
            value += 1
        }
        return value;
    }
}


//
//  TVMLBridging.swift
//  TVMLKitchen
//
//  Created by toshi0383 on 12/11/15.
//  Copyright © 2015 toshi0383. All rights reserved.
//

internal func openTVMLTemplateFromXMLString(xmlString: String, type: PresentationType = .Default) {
    let js = "openTemplateFromXMLString(`\(xmlString)`, \(type.rawValue));"
    evaluateInTVMLContext(js)
}

internal func openTVMLTemplateFromXMLFile(xmlFile: String,
    type: PresentationType = .Default) throws
{
    let path = NSBundle.mainBundle().pathForResource(xmlFile, ofType: nil)!
    let xmlString = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String
    openTVMLTemplateFromXMLString(xmlString, type: type)
}

internal func dismissTVMLModal() {
    let js = "dismissModal()"
    evaluateInTVMLContext(js)
}

private func evaluateInTVMLContext(js: String, completion: (Void->Void)? = nil) {
    Kitchen.appController.evaluateInJavaScriptContext({context in
        context.evaluateScript(js)
    }, completion: {_ in completion?()})
}

Replace ((MAIN_BUNDLE_URL)) keyword with mainBundle path

//
//  TVMLBridging.swift
//  TVMLKitchen
//
//  Created by toshi0383 on 12/11/15.
//  Copyright © 2015 toshi0383. All rights reserved.
//

internal func openTVMLTemplateFromXMLString(xmlString: String, type: PresentationType = .Default) {
    let js = "openTemplateFromXMLString(`\(xmlString)`, \(type.rawValue));"
    evaluateInTVMLContext(js)
}

internal func openTVMLTemplateFromXMLFile(xmlFile: String,
    type: PresentationType = .Default) throws
{
    let mainBundle = NSBundle.mainBundle()
    let path = mainBundle.pathForResource(xmlFile, ofType: nil)!
    let xmlString = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String
    let mainBundlePath = mainBundle.bundleURL.absoluteString
    let replaced = xmlString
        .stringByReplacingOccurrencesOfString("((MAIN_BUNDLE_URL))", withString: mainBundlePath)
    openTVMLTemplateFromXMLString(replaced, type: type)
}

internal func dismissTVMLModal() {
    let js = "dismissModal()"
    evaluateInTVMLContext(js)
}

private func evaluateInTVMLContext(js: String, completion: (Void->Void)? = nil) {
    Kitchen.appController.evaluateInJavaScriptContext({context in
        context.evaluateScript(js)
    }, completion: {_ in completion?()})
}


import Foundation

struct MVitaDevice
{
    let identifier:String
    let ipAddress:String
    let dataPort:UInt16
}

Rename data port as port

import Foundation

struct MVitaDevice
{
    let ipAddress:String
    let identifier:String
    let port:UInt16
}


import UIKit

// This file is for running developer specific swift code, either when
// the app is loaded, or when you have injected fresh code in via
// InjectionForXcode (which you can install via Alcatraz.)

// There is also an ARTopMenuViewController+DeveloperExtras extension, which is used in the same manner for code that is
// written in or compatible with Objective-C

// It is put in gitignore as the current state of what you see now,
// any changes you make will be erased when you switch branches.

// If you're seeing changes to this file, run this two commands
/*
 git checkout Artsy/View_Controllers/App_Navigation/ARTopMenuViewController+SwiftDeveloperExtras.swift
 git update-index --assume-unchanged Artsy/View_Controllers/App_Navigation/ARTopMenuViewController+SwiftDeveloperExtras.swift
 */

extension ARTopMenuViewController {

    func runSwiftDeveloperExtras() {
        // run swift code here at startup
    }
}

Add @objc to the swift dev extras

import UIKit

// This file is for running developer specific swift code, either when
// the app is loaded, or when you have injected fresh code in via
// InjectionForXcode (which you can install via Alcatraz.)

// There is also an ARTopMenuViewController+DeveloperExtras extension, which is used in the same manner for code that is
// written in or compatible with Objective-C

// It is put in gitignore as the current state of what you see now,
// any changes you make will be erased when you switch branches.

// If you're seeing changes to this file, run this two commands
/*
 git checkout Artsy/View_Controllers/App_Navigation/ARTopMenuViewController+SwiftDeveloperExtras.swift
 git update-index --assume-unchanged Artsy/View_Controllers/App_Navigation/ARTopMenuViewController+SwiftDeveloperExtras.swift
 */

extension ARTopMenuViewController {

    @objc func runSwiftDeveloperExtras() {
        // run swift code here at startup
    }
}


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

import Foundation

public protocol Initializable {
    init()
}

/// Extension for initializing an array of instances
extension Initializable {

    static func instantiateArray(count: Int) -> [Self] {
        var array: [Self] = []
        (0..<count).forEach { _ in
            array.append(Self())
        }
        return array
    }
}

Make extension public as well

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

import Foundation

public protocol Initializable {
    init()
}

/// Extension for initializing an array of instances
public extension Initializable {

    static func instantiateArray(count: Int) -> [Self] {
        var array: [Self] = []
        (0..<count).forEach { _ in
            array.append(Self())
        }
        return array
    }
}


extension Node {
    public final class Text: Vector {
        /// Text contained within a text box.
        public let characters: String
        /// Style of text including font family and weight.
        public let style: TypeStyle
        /// Array with same number of elements as characeters in text box.
        ///
        /// Each element is a reference to the styleOverrideTable and maps to the
        /// corresponding character in the characters field.
        ///
        /// Elements with value 0 have the default type style.
        public let characterStyleOverrides: [Int]
        /// Map from ID to TypeStyle for looking up style overrides.
        public let styleOverrideTable: [Int: Style]

        private enum CodingKeys: String, CodingKey {
            case characters
            case style
            case characterStyleOverrides
            case styleOverrideTable
        }

        public required init(from decoder: Decoder) throws {
            let keyedDecoder = try decoder.container(keyedBy: Self.CodingKeys)

            self.characters = try keyedDecoder.decode(String.self, forKey: .characters)
            self.style = try keyedDecoder.decode(TypeStyle.self, forKey: .style)
            self.characterStyleOverrides = try keyedDecoder.decode([Int].self, forKey: .characterStyleOverrides)
            self.styleOverrideTable = try keyedDecoder.decode([Int: Style].self, forKey: .styleOverrideTable)

            try super.init(from: decoder)
        }

        override var contentDescription: String {
            return super.contentDescription + """

                - characters: \(characters)
                - style: \(style)
                - characterStyleOverrides: \(characterStyleOverrides)
                - styleOverrideTable: \(styleOverrideTable)
                """
        }
    }
}

Allow styleOverrideTable to be optional

extension Node {
    public final class Text: Vector {
        /// Text contained within a text box.
        public let characters: String
        /// Style of text including font family and weight.
        public let style: TypeStyle
        /// Array with same number of elements as characeters in text box.
        ///
        /// Each element is a reference to the styleOverrideTable and maps to the
        /// corresponding character in the characters field.
        ///
        /// Elements with value 0 have the default type style.
        public let characterStyleOverrides: [Int]
        /// Map from ID to TypeStyle for looking up style overrides.
        public let styleOverrideTable: [Int: Style]

        private enum CodingKeys: String, CodingKey {
            case characters
            case style
            case characterStyleOverrides
            case styleOverrideTable
        }

        public required init(from decoder: Decoder) throws {
            let keyedDecoder = try decoder.container(keyedBy: Self.CodingKeys)

            self.characters = try keyedDecoder.decode(String.self, forKey: .characters)
            self.style = try keyedDecoder.decode(TypeStyle.self, forKey: .style)
            self.characterStyleOverrides = try keyedDecoder.decode([Int].self, forKey: .characterStyleOverrides)
            self.styleOverrideTable = try keyedDecoder.decodeIfPresent([Int: Style].self, forKey: .styleOverrideTable) ?? [:]

            try super.init(from: decoder)
        }

        override var contentDescription: String {
            return super.contentDescription + """

                - characters: \(characters)
                - style: \(style)
                - characterStyleOverrides: \(characterStyleOverrides)
                - styleOverrideTable: \(styleOverrideTable)
                """
        }
    }
}


//
//  BaseNibView.swift
//  ZamzamKit
//
//  Created by Basem Emara on 2/21/17.
//  Copyright © 2017 Zamzam. All rights reserved.
//

import UIKit

/// The UIView class with a .xib file by the same name wired up.
open class BaseNibView: UIView {

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

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

    /// Process common code on initialization.
    public func commonInit() {
        loadFromNib()
    }
}

Use more conventional setup function name (like XCTestCase)

//
//  BaseNibView.swift
//  ZamzamKit
//
//  Created by Basem Emara on 2/21/17.
//  Copyright © 2017 Zamzam. All rights reserved.
//

import UIKit

/// The UIView class with a .xib file by the same name wired up.
open class BaseNibView: UIView {

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

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

    /// Process common code on initialization.
    public func setUp() {
        loadFromNib()
    }
}


import XCTest
@testable import Euler

final class LogicTests: XCTestCase {
    func testLogicalNegation() {
        XCTAssertEqual(¬true, !true)
        XCTAssertEqual(~true, !true)
    }

    func testLogicalConjunction() {
        XCTAssertEqual(true ∧ false, true && false)
    }

    func testLogicalDisjunction() {
        XCTAssertEqual(true ∨ false, true || false)
    }

//    func testLogicalXOR() {
//        XCTAssertEqual(true ⊻ false, true ^ false)
//        XCTAssertEqual(true ⊕ false, true ^ false)
//        XCTAssertEqual(true ↮ false, true ^ false)
//        XCTAssertEqual(true ≢ false, true ^ false)
//    }

//    func testLogicalNAND() {
//        XCTAssertEqual(true ⊼ false, !(true ^ false))
//        XCTAssertEqual(true ↑ false, !(true ^ false))
//    }

    func testLogicalNOR() {
        XCTAssertEqual(true ⊽ false, !(true || false))
        XCTAssertEqual(true ↓ false, !(true || false))
    }

    static var allTests = [
        ("testLogicalNegation", testLogicalNegation),
        ("testLogicalConjunction", testLogicalConjunction),
        ("testLogicalDisjunction", testLogicalDisjunction),
//        ("testLogicalXOR", testLogicalXOR),
//        ("testLogicalNAND", testLogicalNAND),
        ("testLogicalNOR", testLogicalNOR)
    ]
}

Enable logical XOR and logical NAND test

import XCTest
@testable import Euler

final class LogicTests: XCTestCase {
    func testLogicalNegation() {
        XCTAssertEqual(¬true, !true)
        XCTAssertEqual(~true, !true)
    }

    func testLogicalConjunction() {
        XCTAssertEqual(true ∧ false, true && false)
    }

    func testLogicalDisjunction() {
        XCTAssertEqual(true ∨ false, true || false)
    }

    func testLogicalXOR() {
        XCTAssertEqual(true ⊻ false, true != false)
        XCTAssertEqual(true ⊕ false, true != false)
        XCTAssertEqual(true ↮ false, true != false)
        XCTAssertEqual(true ≢ false, true != false)
    }

    func testLogicalNAND() {
        XCTAssertEqual(true ⊼ false, !(true && false))
        XCTAssertEqual(true ↑ false, !(true && false))
    }

    func testLogicalNOR() {
        XCTAssertEqual(true ⊽ false, !(true || false))
        XCTAssertEqual(true ↓ false, !(true || false))
    }

    static var allTests = [
        ("testLogicalNegation", testLogicalNegation),
        ("testLogicalConjunction", testLogicalConjunction),
        ("testLogicalDisjunction", testLogicalDisjunction),
        ("testLogicalXOR", testLogicalXOR),
        ("testLogicalNAND", testLogicalNAND),
        ("testLogicalNOR", testLogicalNOR)
    ]
}


import Foundation

struct Cassette {
    let name: String
    let interactions: [Interaction]

    init(name: String, interactions: [Interaction]) {
        self.name = name
        self.interactions = interactions
    }

    func interactionForRequest(request: NSURLRequest) -> Interaction? {
        for interaction in interactions {
            let r = interaction.request

            // Note: We don't check headers right now
            if r.HTTPMethod == request.HTTPMethod && r.URL == request.URL && r.HTTPBody == request.HTTPBody {
                return interaction
            }
        }
        return nil
    }
}

extension Cassette {
    var dictionary: [String: AnyObject] {
        return [
            "name": name,
            "interactions": interactions.map { $0.dictionary }
        ]
    }

    init?(dictionary: [String: AnyObject]) {
        guard let name = dictionary["name"] as? String else { return nil }

        self.name = name

        var interactions = [Interaction]()
        if let array = dictionary["interactions"] as? [[String: AnyObject]] {
            for dictionary in array {
                if let interaction = Interaction(dictionary: dictionary) {
                    interactions.append(interaction)
                }
            }
        }
        self.interactions = interactions
    }
}

Use flatMap to avoid mutability

import Foundation

struct Cassette {
    let name: String
    let interactions: [Interaction]

    init(name: String, interactions: [Interaction]) {
        self.name = name
        self.interactions = interactions
    }

    func interactionForRequest(request: NSURLRequest) -> Interaction? {
        for interaction in interactions {
            let r = interaction.request

            // Note: We don't check headers right now
            if r.HTTPMethod == request.HTTPMethod && r.URL == request.URL && r.HTTPBody == request.HTTPBody {
                return interaction
            }
        }
        return nil
    }
}

extension Cassette {
    var dictionary: [String: AnyObject] {
        return [
            "name": name,
            "interactions": interactions.map { $0.dictionary }
        ]
    }

    init?(dictionary: [String: AnyObject]) {
        guard let name = dictionary["name"] as? String else { return nil }

        self.name = name

        if let array = dictionary["interactions"] as? [[String: AnyObject]] {
            interactions = array.flatMap { Interaction(dictionary: $0) }
        } else {
            interactions = []
        }
    }
}


// swift-tools-version:3.1

import PackageDescription

let package = Package(
    name: "Drift",
    targets: [
        Target(name: "DriftTransform", dependencies: ["DriftRuntime"]),
        Target(name: "DriftRuntime", dependencies: [])
    ],
    dependencies: [
        .Package(url: "/private/tmp/Antlr4-tmp-1499401188", majorVersion: 4)
    ]
)

Change Antlr4 dependency location to non-temporary directory.

// swift-tools-version:3.1

import PackageDescription

let package = Package(
    name: "Drift",
    targets: [
        Target(name: "DriftTransform", dependencies: ["DriftRuntime"]),
        Target(name: "DriftRuntime", dependencies: [])
    ],
    dependencies: [
        .Package(url: "Antlr4", majorVersion: 4)
    ]
)


//
//  AVSTaggedAttributedString.swift
//  AVSTaggedAttributedString
//
//  Created by Andrei Sherstniuk on 8/8/16.
//
//

import Foundation

extension NSMutableAttributedString {
    func avs_addAttributes(attributes: [String: AnyObject], tag: String) {
        let openTag = "<\(tag)>"
        let closeTag = "</\(tag)>"
        let string = self.mutableString
        let openRange = string.rangeOfString(openTag)
        let closeRange = string.rangeOfString(closeTag)
        if openRange.location != NSNotFound && closeRange.location != NSNotFound {
            if openRange.location + openRange.length <= closeRange.location {
                var innerLocation = openRange.location + openRange.length
                let innerLength = closeRange.location - openRange.location - openRange.length
                innerLocation -= openRange.length;
                self.replaceCharactersInRange(closeRange, withString: "")
                self.replaceCharactersInRange(openRange, withString: "")
                let innerRange = NSRange(location: innerLocation, length: innerLength)
                self.addAttributes(attributes, range: innerRange)
            }
        }
    }
}

Implement several ranges of the same tag.

//
//  AVSTaggedAttributedString.swift
//  AVSTaggedAttributedString
//
//  Created by Andrei Sherstniuk on 8/8/16.
//
//

import Foundation

extension NSMutableAttributedString {
    func avs_addAttributes(attributes: [String: AnyObject], tag: String) {
        let openTag = "<\(tag)>"
        let closeTag = "</\(tag)>"
        var string = self.mutableString
        var openRange = string.rangeOfString(openTag)
        var closeRange = string.rangeOfString(closeTag)
        while openRange.location != NSNotFound && closeRange.location != NSNotFound && openRange.location + openRange.length <= closeRange.location {
            var innerLocation = openRange.location + openRange.length
            let innerLength = closeRange.location - openRange.location - openRange.length
            innerLocation -= openRange.length;

            self.replaceCharactersInRange(closeRange, withString: "")
            self.replaceCharactersInRange(openRange, withString: "")

            let innerRange = NSRange(location: innerLocation, length: innerLength)
            self.addAttributes(attributes, range: innerRange)

            string = self.mutableString
            openRange = string.rangeOfString(openTag)
            closeRange = string.rangeOfString(closeTag)
        }
    }
}


//
//  VerifiedResult.swift
//  Bits
//
//  Created by mono on 2017/08/03.
//

import Foundation
import JWT

public struct Firebase {
    public let identities: [String: [String]]
    public let signInProvider: String

    init(json: JSON) {
        identities = json["identities"]!.object!
            .reduce([String: [String]]()) { sum, e in
                var sum = sum
                sum[e.key] = e.value.array!.map { $0.string! }
                return sum
        }
        signInProvider = json["sign_in_provider"]!.string!
    }
}

public struct User {
    public let id: String
    public let authTime: Date
    public let issuedAtTime: Date
    public let expirationTime: Date
    public let email: String?
    public let emailVerified: Bool?
    public let firebase: Firebase

    public init(jwt: JWT) {
        id = jwt.userId!
        authTime = jwt.authTime!
        issuedAtTime = jwt.issuedAtTime!
        expirationTime = jwt.expirationTime!
        email = jwt.email
        emailVerified = jwt.emailVerified
        firebase = Firebase(json: jwt.payload["firebase"]!)
    }
}

Add result user type initializer

//
//  VerifiedResult.swift
//  Bits
//
//  Created by mono on 2017/08/03.
//

import Foundation
import JWT

public struct Firebase {
    public let identities: [String: [String]]
    public let signInProvider: String

    init(json: JSON) {
        identities = json["identities"]!.object!
            .reduce([String: [String]]()) { sum, e in
                var sum = sum
                sum[e.key] = e.value.array!.map { $0.string! }
                return sum
        }
        signInProvider = json["sign_in_provider"]!.string!
    }

    public init(identities: [String: [String]], signInProvider: String) {
        self.identities = identities
        self.signInProvider = signInProvider
    }
}

public struct User {
    public let id: String
    public let authTime: Date
    public let issuedAtTime: Date
    public let expirationTime: Date
    public let email: String?
    public let emailVerified: Bool?
    public let firebase: Firebase

    public init(id: String,
                authTime: Date,
                issuedAtTime: Date,
                expirationTime: Date,
                email: String? = nil,
                emailVerified: Bool? = nil,
                firebase: Firebase = Firebase(identities: [:], signInProvider: "")) {
        self.id = id
        self.authTime = authTime
        self.issuedAtTime = issuedAtTime
        self.expirationTime = expirationTime
        self.email = email
        self.emailVerified = emailVerified
        self.firebase = firebase
    }

    public init(jwt: JWT) {
        self.init(id: jwt.userId!,
                  authTime: jwt.authTime!,
                  issuedAtTime: jwt.issuedAtTime!,
                  expirationTime: jwt.expirationTime!,
                  email: jwt.email,
                  emailVerified: jwt.emailVerified,
                  firebase: Firebase(json: jwt.payload["firebase"]!))
    }
}


//
//  FuelGaugeTabTests.swift
//  GaugesDemo
//
//  Created by Ron Lisle on 4/5/15.
//  Copyright (c) 2015 Ron Lisle. All rights reserved.
//

import UIKit
import XCTest

class FuelGaugeTabTests: XCTestCase {

    var vc: FirstViewController!

    override func setUp() {
        super.setUp()

        let storyboard = UIStoryboard(name: "Main", bundle: NSBundle(forClass: self.dynamicType))
        vc = storyboard.instantiateViewControllerWithIdentifier("FuelVC") as! FirstViewController

        let dummy = vc.view // force loading subviews and setting outlets

        vc.viewDidLoad()
    }

    func testFirstViewControllerLoaded() {
        XCTAssertNotNil(vc, "FirstViewController not found")
    }

}

Add test that fuel slider is connected.

//
//  FuelGaugeTabTests.swift
//  GaugesDemo
//
//  Created by Ron Lisle on 4/5/15.
//  Copyright (c) 2015 Ron Lisle. All rights reserved.
//

import UIKit
import XCTest

class FuelGaugeTabTests: XCTestCase {

    var vc: FirstViewController!

    override func setUp() {
        super.setUp()

        let storyboard = UIStoryboard(name: "Main", bundle: NSBundle(forClass: self.dynamicType))
        vc = storyboard.instantiateViewControllerWithIdentifier("FuelVC") as! FirstViewController

        let dummy = vc.view // force loading subviews and setting outlets

        vc.viewDidLoad()
    }

    func testFirstViewControllerLoaded() {
        XCTAssertNotNil(vc, "FirstViewController not found")
    }

    func testSliderCreated() {
        let slider = vc.slider
        XCTAssertNotNil(slider, "Slider not created or connected")
    }

}


//
//  ModelGenerator.swift
//  model-generator
//
//  Created by Dominik Hádl on 19/01/16.
//  Copyright © 2016 Nodes. All rights reserved.
//

import Foundation

public struct ModelGeneratorSettings {
    public var moduleName: String?
    public var noConvertCamelCase: Bool = false
    public var useNativeDictionaries: Bool = false

    public init() {}
}

public protocol ModelGeneratorErrorType: ErrorType {
    func description() -> String
}

public struct ModelGenerator {
    public static func modelCodeFromSourceCode(sourceCode: String, withSettings settings: ModelGeneratorSettings) throws -> String {
        // Parse the model and its properties first
        var model        = try ModelParser.modelFromSourceCode(sourceCode)
        model.properties = try PropertyParser.propertiesFromSourceCode(sourceCode, noConvertCamelCaseKeys: settings.noConvertCamelCase)

        // Genereate encodable and decodable code blocks
        let decodableCode = DecodableCodeGenerator.decodableCodeWithModel(model, useNativeDictionaries: settings.useNativeDictionaries)
        let encodableCode = EncodableCodeGenerator.encodableCodeWithModel(model, useNativeDictionaries: settings.useNativeDictionaries)

        // Combine both blocks in an extension block and return it
        return ExtensionCodeGenerator.extensionCodeWithModel(model, moduleName: nil, andContent: decodableCode + encodableCode)
    }
}

Fix module name not being passed to generator

//
//  ModelGenerator.swift
//  model-generator
//
//  Created by Dominik Hádl on 19/01/16.
//  Copyright © 2016 Nodes. All rights reserved.
//

import Foundation

public struct ModelGeneratorSettings {
    public var moduleName: String?
    public var noConvertCamelCase: Bool = false
    public var useNativeDictionaries: Bool = false

    public init() {}
}

public protocol ModelGeneratorErrorType: ErrorType {
    func description() -> String
}

public struct ModelGenerator {
    public static func modelCodeFromSourceCode(sourceCode: String, withSettings settings: ModelGeneratorSettings) throws -> String {
        // Parse the model and its properties first
        var model        = try ModelParser.modelFromSourceCode(sourceCode)
        model.properties = try PropertyParser.propertiesFromSourceCode(sourceCode, noConvertCamelCaseKeys: settings.noConvertCamelCase)

        // Genereate encodable and decodable code blocks
        let decodableCode = DecodableCodeGenerator.decodableCodeWithModel(model, useNativeDictionaries: settings.useNativeDictionaries)
        let encodableCode = EncodableCodeGenerator.encodableCodeWithModel(model, useNativeDictionaries: settings.useNativeDictionaries)

        // Combine both blocks in an extension block and return it
        return ExtensionCodeGenerator.extensionCodeWithModel(model, moduleName: settings.moduleName, andContent: decodableCode + encodableCode)
    }
}


//
//  EachFilterTests.swift
//  GRMustache
//
//  Created by Gwendal Roué on 29/11/2014.
//  Copyright (c) 2014 Gwendal Roué. All rights reserved.
//

import XCTest
import GRMustache

class EachFilterTests: XCTestCase {

    func testEachFilterTriggersRenderableItemsInArray() {
        let renderable = { (info: RenderingInfo, error: NSErrorPointer) -> Rendering in
            let rendering = info.tag.render(info.context)!
            return Rendering("<\(rendering.string)>", rendering.contentType)
        }
        let value = Value(["array": Value([Value(renderable)])])
        let template = Template(string: "{{#each(array)}}{{@index}}{{/}}")!
        let rendering = template.render(value)!
        XCTAssertEqual(rendering, "<0>")
    }

    func testEachFilterTriggersRenderableItemsInDictionary() {
        let renderable = { (info: RenderingInfo, error: NSErrorPointer) -> Rendering in
            let rendering = info.tag.render(info.context)!
            return Rendering("<\(rendering.string)>", rendering.contentType)
        }
        let value = Value(["dictionary": Value(["a": Value(renderable)])])
        let template = Template(string: "{{#each(dictionary)}}{{@key}}{{/}}")!
        let rendering = template.render(value)!
        XCTAssertEqual(rendering, "<a>")
    }

}

Work around a weird kind of Swift bug

//
//  EachFilterTests.swift
//  GRMustache
//
//  Created by Gwendal Roué on 29/11/2014.
//  Copyright (c) 2014 Gwendal Roué. All rights reserved.
//

import XCTest
import GRMustache

class EachFilterTests: XCTestCase {

    func testEachFilterTriggersRenderableItemsInArray() {
        let renderable = { (info: RenderingInfo, error: NSErrorPointer) -> Rendering? in
            let rendering = info.tag.render(info.context)!
            return Rendering("<\(rendering.string)>", rendering.contentType)
        }
        let value = Value(["array": Value([Value(renderable)])])
        let template = Template(string: "{{#each(array)}}{{@index}}{{/}}")!
        let rendering = template.render(value)!
        XCTAssertEqual(rendering, "<0>")
    }

    func testEachFilterTriggersRenderableItemsInDictionary() {
        let renderable = { (info: RenderingInfo, error: NSErrorPointer) -> Rendering? in
            let rendering = info.tag.render(info.context)!
            return Rendering("<\(rendering.string)>", rendering.contentType)
        }
        let value = Value(["dictionary": Value(["a": Value(renderable)])])
        let template = Template(string: "{{#each(dictionary)}}{{@key}}{{/}}")!
        let rendering = template.render(value)!
        XCTAssertEqual(rendering, "<a>")
    }

}


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

import Traversal
import XCTest

class ReducibleOfTests: XCTestCase {
	func testConstructionFromSequenceType() {
		let sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9]
		XCTAssertEqual(Traversal.reduce(ReducibleOf(sequence: sequence), 0, +), 45)
	}
}

Test ReducibleOf construction from ReducibleType.

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

import Traversal
import XCTest

class ReducibleOfTests: XCTestCase {
	func testConstructionFromSequenceType() {
		let sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9]
		XCTAssertEqual(Traversal.reduce(ReducibleOf(sequence: sequence), 0, +), 45)
	}

	func testConstructionFromReducibleType() {
		let sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9]
		let reducible = ReducibleOf(sequence: sequence)
		let outer = ReducibleOf(reducible)
		XCTAssertEqual(Traversal.reduce(outer, 0, +), 45)
	}
}


public enum DependencyResolverError : ErrorType, Equatable, CustomStringConvertible {
  case NoSuchDependency(Dependency)
  case CircularDependency(DependencyGraph)
  case Conflict(String, requiredBy: [Dependency])

  public var description: String {
    switch self {
    case .NoSuchDependency(let dependency):
      return "Dependency '\(dependency)' not found."
    case .Conflict(let dependencyName, let requirements):
      return "Dependency '\(dependencyName)' requires conflicting versions from requirements: \(requirements)."
    case .CircularDependency(let graph):
      return "Dependency '\(graph.root.name)' resolved to a cycle using requirements: \(graph.flatten())"
    }
  }
}

/// Returns if to dependency resolver errors are identical
/// note: Circular dependencies do not correctly check the inner specifications
public func == (lhs: DependencyResolverError, rhs: DependencyResolverError) -> Bool {
  switch (lhs, rhs) {
  case let (.NoSuchDependency(lhsDependency), .NoSuchDependency(rhsDependency)):
    return lhsDependency == rhsDependency
  case let (.Conflict(lhsName, lhsRequirements), .Conflict(rhsName, rhsRequirements)):
    return lhsName == rhsName && lhsRequirements == rhsRequirements
  case let (.CircularDependency(lhsGraph), .CircularDependency(rhsGraph)):
    return lhsGraph ~= rhsGraph
  default:
    return false
  }
}

Order dependency error types alphabetically

public enum DependencyResolverError : ErrorType, Equatable, CustomStringConvertible {
  case CircularDependency(DependencyGraph)
  case Conflict(String, requiredBy: [Dependency])
  case NoSuchDependency(Dependency)

  public var description: String {
    switch self {
    case .CircularDependency(let graph):
      return "Dependency '\(graph.root.name)' resolved to a cycle using requirements: \(graph.flatten())"
    case .Conflict(let dependencyName, let requirements):
      return "Dependency '\(dependencyName)' requires conflicting versions from requirements: \(requirements)."
    case .NoSuchDependency(let dependency):
      return "Dependency '\(dependency)' not found."
    }
  }
}

/// Returns if to dependency resolver errors are identical
/// note: Circular dependencies do not correctly check the inner specifications
public func == (lhs: DependencyResolverError, rhs: DependencyResolverError) -> Bool {
  switch (lhs, rhs) {
  case let (.NoSuchDependency(lhsDependency), .NoSuchDependency(rhsDependency)):
    return lhsDependency == rhsDependency
  case let (.Conflict(lhsName, lhsRequirements), .Conflict(rhsName, rhsRequirements)):
    return lhsName == rhsName && lhsRequirements == rhsRequirements
  case let (.CircularDependency(lhsGraph), .CircularDependency(rhsGraph)):
    return lhsGraph ~= rhsGraph
  default:
    return false
  }
}


//
//  ConstraintUtil.swift
//  Pods
//
//  Created by Gregory Sholl e Santos on 21/07/17.
//
//

import UIKit

// MARK: - Multiplier

public class ConstraintUtil {

    static public func changeMultiplier(of constraint: NSLayoutConstraint, to value: CGFloat, in view: UIView?) -> NSLayoutConstraint {
        let newConstraint = NSLayoutConstraint(item: constraint.firstItem, attribute: constraint.firstAttribute, relatedBy: constraint.relation, toItem: constraint.secondItem, attribute: constraint.secondAttribute, multiplier: value, constant: constraint.constant)

        newConstraint.priority = constraint.priority

        if #available(iOS 9.0, *) {
            view?.removeConstraint(constraint)
            view?.addConstraint(newConstraint)
        } else {
            NSLayoutConstraint.deactivate([constraint])
            NSLayoutConstraint.activate([newConstraint])
        }

        return newConstraint
    }
}

Fix constraint related issue of new Swift 4 init

//
//  ConstraintUtil.swift
//  Pods
//
//  Created by Gregory Sholl e Santos on 21/07/17.
//
//

import UIKit

// MARK: - Multiplier

public class ConstraintUtil {

    static public func changeMultiplier(of constraint: NSLayoutConstraint, to value: CGFloat, in view: UIView?) -> NSLayoutConstraint {

        let newConstraint = NSLayoutConstraint(item: constraint.firstItem as Any,
                                               attribute: constraint.firstAttribute,
                                               relatedBy: constraint.relation,
                                               toItem: constraint.secondItem,
                                               attribute: constraint.secondAttribute,
                                               multiplier: value,
                                               constant: constraint.constant)

        newConstraint.priority = constraint.priority

        if #available(iOS 9.0, *) {
            view?.removeConstraint(constraint)
            view?.addConstraint(newConstraint)
        } else {
            NSLayoutConstraint.deactivate([constraint])
            NSLayoutConstraint.activate([newConstraint])
        }

        return newConstraint
    }
}


//
//  ComponentContext.swift
//  Theodolite
//
//  Created by Oliver Rickard on 10/29/17.
//  Copyright © 2017 Oliver Rickard. All rights reserved.
//

import Foundation

internal func GetContext(_ component: Component) -> ComponentContext? {
  return (component as? UnTypedComponent)?.context
}

public protocol MountInfoProtocol {
  var mountContext: MountContext? {get set}
  var mountedLayout: Layout? {get set}
}

public struct MountInfo: MountInfoProtocol {
  public var currentView: UIView? = nil
  public var mountContext: MountContext? = nil
  public var mountedLayout: Layout? = nil
}

public struct LayoutInfo {
  /** We can't store a ref to the Layout directly because that would form a retain cycle. */
  let constraint: SizeRange
  let size: CGSize
  let children: [LayoutChild]
  let extra: Any?
}

/** The bag of information needed by the framework to do its work. This is an implementation detail of the framework */
public class ComponentContext {
  public var props: Any? = nil
  public var key: AnyHashable? = nil
  public var scopeHandle: ScopeHandle? = nil

  public var mountInfo: MountInfo = MountInfo()
  public var layoutInfo: Atomic<LayoutInfo?> = Atomic(nil)

  public init() {}
}

Mark the private stuff internal to the framework

//
//  ComponentContext.swift
//  Theodolite
//
//  Created by Oliver Rickard on 10/29/17.
//  Copyright © 2017 Oliver Rickard. All rights reserved.
//

import Foundation

internal func GetContext(_ component: Component) -> ComponentContext? {
  return (component as? UnTypedComponent)?.context
}

public protocol MountInfoProtocol {
  var mountContext: MountContext? {get set}
  var mountedLayout: Layout? {get set}
}

public struct MountInfo: MountInfoProtocol {
  public var currentView: UIView? = nil
  public var mountContext: MountContext? = nil
  public var mountedLayout: Layout? = nil
}

public struct LayoutInfo {
  /** We can't store a ref to the Layout directly because that would form a retain cycle. */
  let constraint: SizeRange
  let size: CGSize
  let children: [LayoutChild]
  let extra: Any?
}

/** The bag of information needed by the framework to do its work. This is an implementation detail of the framework. */
public class ComponentContext {
  internal var props: Any? = nil
  internal var key: AnyHashable? = nil
  internal var scopeHandle: ScopeHandle? = nil

  public var mountInfo: MountInfo = MountInfo()
  public var layoutInfo: Atomic<LayoutInfo?> = Atomic(nil)

  public init() {}
}


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

Check that declared types are types.

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


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

public struct Identifier: Comparable, Hashable, Printable {
	public init(graph: Graph<Node>) {
		value = graph.nodes.isEmpty ? 0 : maxElement(graph.nodes.keys).value + 1
	}

	public init() {
		self.value = Identifier.cursor++
	}

	// MARK: Endpoint constructors

	public func input(index: Int) -> Edge.Destination {
		return (identifier: self, inputIndex: index)
	}

	public func output(index: Int) -> Edge.Source {
		return (identifier: self, outputIndex: index)
	}

	// MARK: Hashable

	public var hashValue: Int {
		return value.hashValue
	}

	// MARK: Printable

	public var description: String {
		return value.description
	}

	// MARK: Private

	private let value: Int

	private static var cursor = 0
}

public func == (left: Identifier, right: Identifier) -> Bool {
	return left.value == right.value
}

public func < (left: Identifier, right: Identifier) -> Bool {
	return left.value < right.value
}

// MARK: - Imports

import Prelude

Add a private constructor taking an Int.

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

public struct Identifier: Comparable, Hashable, Printable {
	public init(graph: Graph<Node>) {
		value = graph.nodes.isEmpty ? 0 : maxElement(graph.nodes.keys).value + 1
	}

	public init() {
		self.value = Identifier.cursor++
	}

	// MARK: Endpoint constructors

	public func input(index: Int) -> Edge.Destination {
		return (identifier: self, inputIndex: index)
	}

	public func output(index: Int) -> Edge.Source {
		return (identifier: self, outputIndex: index)
	}

	// MARK: Hashable

	public var hashValue: Int {
		return value.hashValue
	}

	// MARK: Printable

	public var description: String {
		return value.description
	}

	// MARK: Private

	private init(_ value: Int) {
		self.value = value
	}

	private let value: Int

	private static var cursor = 0
}

public func == (left: Identifier, right: Identifier) -> Bool {
	return left.value == right.value
}

public func < (left: Identifier, right: Identifier) -> Bool {
	return left.value < right.value
}

// MARK: - Imports

import Prelude


//
//  WagnerFischerTests.swift
//  WagnerFischerTests
//
//  Created by Sam Soffes on 2/22/16.
//  Copyright © 2016 Caleb Davenport. All rights reserved.
//

import XCTest
import WagnerFischer

class WagnerFischer_OSXTests: XCTestCase {
    func testStringEditSteps() {
        let source = "Caleb Davenport"
        let destination = "Sam Soffes"

        let steps = editSteps(source, destination)
        XCTAssertEqual(applyEditSteps(source, editSteps: steps)!, destination)
    }

    func testInvalidEditSteps() {
        let source = "Caleb Davenport"
        let destination = "Sam Soffes"

        let steps = editSteps(source, destination)
        XCTAssertNil(applyEditSteps("", editSteps: steps))

        XCTAssertNil(applyEditSteps("", editSteps: [.Delete(location: 0)]))
        XCTAssertNil(applyEditSteps("", editSteps: [.Delete(location: 1)]))
    }

    func testApplyToEmptySource() {
        XCTAssertEqual(applyEditSteps("", editSteps: [.Insert(location: 0, value: "S".characters.first!)]), "S")
    }
}

Test for applying to empty destination

//
//  WagnerFischerTests.swift
//  WagnerFischerTests
//
//  Created by Sam Soffes on 2/22/16.
//  Copyright © 2016 Caleb Davenport. All rights reserved.
//

import XCTest
import WagnerFischer

class WagnerFischer_OSXTests: XCTestCase {
    func testStringEditSteps() {
        let source = "Caleb Davenport"
        let destination = "Sam Soffes"

        let steps = editSteps(source, destination)
        XCTAssertEqual(applyEditSteps(source, editSteps: steps)!, destination)
    }

    func testInvalidEditSteps() {
        let source = "Caleb Davenport"
        let destination = "Sam Soffes"

        let steps = editSteps(source, destination)
        XCTAssertNil(applyEditSteps("", editSteps: steps))

        XCTAssertNil(applyEditSteps("", editSteps: [.Delete(location: 0)]))
        XCTAssertNil(applyEditSteps("", editSteps: [.Delete(location: 1)]))
    }

    func testApplyToEmptySource() {
        XCTAssertEqual(applyEditSteps("", editSteps: [.Insert(location: 0, value: "S".characters.first!)]), "S")
    }

    func testApplyToEmptyDestination() {
        XCTAssertEqual(applyEditSteps("S", editSteps: [.Delete(location: 0)]), "")
    }
}