//
//  UIApplication+OAuthSwift.swift
//  OAuthSwift
//
//  Created by phimage on 11/12/15.
//  Copyright © 2015 Dongri Jin. All rights reserved.
//

#if os(iOS) || os(tvOS)
    import UIKit

    extension UIApplication {
        static var topViewController: UIViewController? {
            #if !OAUTH_APP_EXTENSIONS
                return UIApplication.shared.topViewController
            #else
                return nil
            #endif
        }

        var topViewController: UIViewController? {
            guard let rootController = self.keyWindow?.rootViewController else {
                return nil
            }
            return UIViewController.topViewController(rootController)
        }
    }

    extension UIViewController {

        static func topViewController(_ viewController: UIViewController) -> UIViewController {
            guard let presentedViewController = viewController.presentedViewController else {
                return viewController
            }
            #if !topVCCastDisabled
            if let navigationController = presentedViewController as? UINavigationController {
                if let visibleViewController = navigationController.visibleViewController {
                    return topViewController(visibleViewController)
                }
            } else if let tabBarController = presentedViewController as? UITabBarController {
                if let selectedViewController = tabBarController.selectedViewController {
                    return topViewController(selectedViewController)
                }
            }
            #endif
            return topViewController(presentedViewController)
        }
    }

#endif

Add @nonobjc to topViewController in UIApplication extension to fix ld warning

//
//  UIApplication+OAuthSwift.swift
//  OAuthSwift
//
//  Created by phimage on 11/12/15.
//  Copyright © 2015 Dongri Jin. All rights reserved.
//

#if os(iOS) || os(tvOS)
    import UIKit

    extension UIApplication {
        @nonobjc static var topViewController: UIViewController? {
            #if !OAUTH_APP_EXTENSIONS
                return UIApplication.shared.topViewController
            #else
                return nil
            #endif
        }

        var topViewController: UIViewController? {
            guard let rootController = self.keyWindow?.rootViewController else {
                return nil
            }
            return UIViewController.topViewController(rootController)
        }
    }

    extension UIViewController {

        static func topViewController(_ viewController: UIViewController) -> UIViewController {
            guard let presentedViewController = viewController.presentedViewController else {
                return viewController
            }
            #if !topVCCastDisabled
            if let navigationController = presentedViewController as? UINavigationController {
                if let visibleViewController = navigationController.visibleViewController {
                    return topViewController(visibleViewController)
                }
            } else if let tabBarController = presentedViewController as? UITabBarController {
                if let selectedViewController = tabBarController.selectedViewController {
                    return topViewController(selectedViewController)
                }
            }
            #endif
            return topViewController(presentedViewController)
        }
    }

#endif


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

import Ello
import Quick
import Nimble

class DynamicSettingsSpec: QuickSpec {
    override func spec() {
        it("coverts from JSON") {
            let parsedDynamicSettings = stubbedJSONDataArray("profile_available_user_profile_toggles", "categories")
            let dynamicSettings = parsedDynamicSettings.map { DynamicSettingCategory.fromJSON($0) as DynamicSettingCategory }

            expect(dynamicSettings.count) == 4
            expect(dynamicSettings.first?.label) == "Preferences"
            expect(dynamicSettings.first?.settings.count) == 6
            expect(dynamicSettings.first?.settings.first?.label) == "Public Profile"
        }
    }
}

Update dynamic setting spec assertion

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

import Ello
import Quick
import Nimble

class DynamicSettingsSpec: QuickSpec {
    override func spec() {
        it("coverts from JSON") {
            let parsedDynamicSettings = stubbedJSONDataArray("profile_available_user_profile_toggles", "categories")
            let dynamicSettings = parsedDynamicSettings.map { DynamicSettingCategory.fromJSON($0) as DynamicSettingCategory }

            expect(dynamicSettings.count) == 4
            expect(dynamicSettings.first?.label) == "Preferences"
            expect(dynamicSettings.first?.settings.count) == 8
            expect(dynamicSettings.first?.settings.first?.label) == "Public Profile"
        }
    }
}


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

enum Term {
	case Parameter(String, Type)
	case Return(String, Type)
}

Add constant terms of a given value.

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

enum Term {
	case Parameter(String, Type)
	case Return(String, Type)

	case Constant(Value)
}

enum Value {
	case Boolean(Swift.Bool)
	case Integer(Swift.Int)
	case String(Swift.String)
}


import Foundation
import Foundation
import XCTest
@testable import Bourne

class ArrayTests: XCTestCase {
    func testArrayDecoding() {
        let json = JSON([1])

        XCTAssertEqual(json.array?.first?.int, 1)
        XCTAssertEqual(json.array?.count, 1)
    }

    static var allTests = [
        ("testArrayDecoding", testArrayDecoding),
    ]
}

Add cases for invalid arrays

import Foundation
import Foundation
import XCTest
@testable import Bourne

class ArrayTests: XCTestCase {
    func testArrayDecoding() {
        let json = JSON([1])

        XCTAssertEqual(json.array?.first?.int, 1)
        XCTAssertEqual(json.array?.count, 1)
    }

    func testInvalidArrayDecoding() {
        let notAnArray = JSON(nil)

        XCTAssertNil(notAnArray.array)
        XCTAssertEqual(notAnArray.arrayValue, [])
    }

    static var allTests = [
        ("testArrayDecoding", testArrayDecoding),
        ("testInvalidArrayDecoding", testInvalidArrayDecoding),
    ]
}


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

public func constraints(graph: Graph<Node>) -> (Term, assumptions: AssumptionSet, constraints: ConstraintSet) {
	let parameters = Node.parameters(graph)
	let returns = Node.returns(graph)
	let returnType: Term = reduce(returns, nil) { $0.0.map { .product(Term(), $0) } ?? Term() } ?? .Unit
	return (reduce(parameters, returnType) {
		.function(Term(), $0.0)
	}, [:], [])
}

import Manifold

Remove the assumption set return.

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

public func constraints(graph: Graph<Node>) -> (Term, constraints: ConstraintSet) {
	let parameters = Node.parameters(graph)
	let returns = Node.returns(graph)
	let returnType: Term = reduce(returns, nil) { $0.0.map { .product(Term(), $0) } ?? Term() } ?? .Unit
	return (reduce(parameters, returnType) {
		.function(Term(), $0.0)
	}, [])
}

import Manifold


// swift-tools-version:5.0

import PackageDescription

let package = Package(
    name: "URLQueryItemEncoder",
    products: [
        .library(
            name: "URLQueryItemEncoder",
            targets: ["URLQueryItemEncoder"]),
    ],
    dependencies: [
    ],
    targets: [
        .target(
            name: "URLQueryItemEncoder",
            dependencies: [],
            path: "URLQueryItemEncoder"),
        .testTarget(
            name: "URLQueryItemEncoderTests",
            dependencies: ["URLQueryItemEncoder"]
      )
    ],
    swiftLanguageVersions: [5]
)

Update the Swift Language Version

// swift-tools-version:5.0

import PackageDescription

let package = Package(
    name: "URLQueryItemEncoder",
    products: [
        .library(
            name: "URLQueryItemEncoder",
            targets: ["URLQueryItemEncoder"]),
    ],
    dependencies: [
    ],
    targets: [
        .target(
            name: "URLQueryItemEncoder",
            dependencies: [],
            path: "URLQueryItemEncoder"),
        .testTarget(
            name: "URLQueryItemEncoderTests",
            dependencies: ["URLQueryItemEncoder"]
      )
    ],
    swiftLanguageVersions: [.v5]
)


// swift-tools-version:5.0

import PackageDescription

let package = Package(
    name: "Swinject",
    products: [
        .library(name: "Swinject",
                 targets: ["Swinject"]),
    ],
    targets: [
        .target(name: "Swinject",
                path: "Sources"),
    ]
)

Add dynamic version of Swinject in SPM

// swift-tools-version:5.0

import PackageDescription

let package = Package(
    name: "Swinject",
    products: [
        .library(name: "Swinject",
                 targets: ["Swinject"]),
        .library(name: "Swinject-Dynamic",
                 type: .dynamic,
                 targets: ["Swinject"]),
    ],
    targets: [
        .target(name: "Swinject",
                path: "Sources"),
    ]
)


import PackageDescription

let package = Package(
	name: "IBMPushNotifications",
    dependencies: [
        .Package(url: "https://github.com/ibm-bluemix-mobile-services/bluemix-simple-http-client-swift.git", majorVersion: 0, minor: 8),
        .Package(url: "https://github.com/IBM-Swift/SwiftyJSON.git", majorVersion: 17)
    ]
)

Update HTTP Client to 0.9.X

import PackageDescription

let package = Package(
	name: "IBMPushNotifications",
    dependencies: [
        .Package(url: "https://github.com/ibm-bluemix-mobile-services/bluemix-simple-http-client-swift.git", majorVersion: 0, minor: 9),
        .Package(url: "https://github.com/IBM-Swift/SwiftyJSON.git", majorVersion: 17)
    ]
)


//
//  IDFYListOperationDataManager.swift
//  iDecide4U
//
//  Created by Dominic Frei on 01/05/2015.
//  Copyright (c) 2015 dominicfrei.com. All rights reserved.
//

import Foundation
import CoreData

class IDFYListOperationDataManager {

  private let managedObjectContext = IDFYCoreDataStack.sharedCoreDataStack().managedObjectContext!
  private let optionListEntityName = IDFYCoreDataStack.sharedCoreDataStack().optionListEntityName

  func getListOfLists() -> [IDFYOptionList] {
    return IDFYCommonDataManager.fetchEntity(optionListEntityName, fromManagedObjectContext: managedObjectContext, withPredicate: nil) as! [IDFYOptionList]
  }

}

Transform the IDFYManagedObjectList objects to IDFYOptionList objects before returning them.

//
//  IDFYListOperationDataManager.swift
//  iDecide4U
//
//  Created by Dominic Frei on 01/05/2015.
//  Copyright (c) 2015 dominicfrei.com. All rights reserved.
//

import Foundation
import CoreData

class IDFYListOperationDataManager {

  private let managedObjectContext = IDFYCoreDataStack.sharedCoreDataStack().managedObjectContext!

  func getListOfLists() -> [IDFYOptionList] {
    let optionListEntityName = NSStringFromClass(IDFYManagedOptionList).componentsSeparatedByString(".").last! as String
    let managedOptionLists = IDFYCommonDataManager.fetchEntity(optionListEntityName, fromManagedObjectContext: managedObjectContext, withPredicate: nil) as! [IDFYManagedOptionList]
    var listOfTransformedLists = [IDFYOptionList]()
    for managedOptionList : IDFYManagedOptionList in managedOptionLists {
      listOfTransformedLists.append(IDFYOptionList(name: managedOptionList.name, options: managedOptionList.options))
    }
    return listOfTransformedLists
  }

}


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

extension ObservableType where E: Collection {

  func mapArgumentsTo<First>(_ first: First.Type) -> Observable<First> {
    return map {
      let value: First! = $0.first as? First
      return value
    }
  }

  func mapArgumentsTo<First, Second>(_ first: First.Type, _ second: Second.Type) -> Observable<(First, Second)> {
    return map {
      var iterator: E.Iterator = $0.makeIterator()
      let first: First! = iterator.next() as? First
      let second: Second! = iterator.next() as? Second
      return (first, second)
    }
  }

}

extension ObservableType where E: OptionalProtocol {

  func ignoringNil() -> Observable<E.Wrapped> {
    return filter { $0.optional != nil }
      .map {
        guard let value = $0.optional else { fatalError() }
        return value
    }
  }

}

import RxSwift

Implement `then` and `combinePrevious` equivalents for Rx

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

extension ObservableType {

  func then<U>(observable replacement: Observable<U>) -> Observable<U> {
    return Observable<U>.create { observer in
      let disposable: CompositeDisposable = CompositeDisposable()

      let outerDisposable = self.subscribe { event in
        switch event {
        case .next:
          break
        case let .error(error):
          observer.onError(error)
        case .completed:
          let innerDisposable: Disposable = replacement.subscribe(observer)
          _ = disposable.insert(innerDisposable)
        }
      }

      _ = disposable.insert(outerDisposable)
      return disposable
    }
  }

  func combiningPrevious(startingWith initialValue: E) -> Observable<(E, E)> {
    return scan((initialValue, initialValue)) { previousPair, newValue in (previousPair.1, newValue) }
  }

}

extension ObservableType where E: Collection {

  func mapArgumentsTo<First>(_ first: First.Type) -> Observable<First> {
    return map {
      let value: First! = $0.first as? First
      return value
    }
  }

  func mapArgumentsTo<First, Second>(_ first: First.Type, _ second: Second.Type) -> Observable<(First, Second)> {
    return map {
      var iterator: E.Iterator = $0.makeIterator()
      let first: First! = iterator.next() as? First
      let second: Second! = iterator.next() as? Second
      return (first, second)
    }
  }

}

extension ObservableType where E: OptionalProtocol {

  func ignoringNil() -> Observable<E.Wrapped> {
    return filter { $0.optional != nil }
      .map {
        guard let value = $0.optional else { fatalError() }
        return value
    }
  }

}

import RxSwift


//
// Command.swift
// SwiftShell
//
// Created by Kåre Morstøl on 15/08/14.
// Copyright (c) 2014 NotTooBad Software. All rights reserved.
//

import Foundation

private func newtask (shellcommand: String) -> NSTask {
	let task = NSTask()
	task.arguments = ["-c",shellcommand]
	task.launchPath = "/bin/bash"
	task.standardInput = NSPipe ()// to avoid implicit reading of the script's standardInput

	return task
}

public func run (shellcommand: String) -> ReadableStreamType {
	let task = newtask(shellcommand)
	let output = NSPipe ()
	task.standardOutput = output
	task.launch()
	return output.fileHandleForReading
}

public func run (shellcommand: String)(input: ReadableStreamType) -> ReadableStreamType {
	let task = newtask(shellcommand)
	task.standardInput = input as File
	let output = NSPipe ()
	task.standardOutput = output
	task.launch()
	return output.fileHandleForReading
}

Make sure a command is finished before the next begins.

//
// Command.swift
// SwiftShell
//
// Created by Kåre Morstøl on 15/08/14.
// Copyright (c) 2014 NotTooBad Software. All rights reserved.
//

import Foundation

private func newtask (shellcommand: String) -> NSTask {
	let task = NSTask()
	task.arguments = ["-c",shellcommand]
	task.launchPath = "/bin/bash"

	// avoids implicit reading of the main script's standardInput
	task.standardInput = NSPipe ()

	return task
}

public func run (shellcommand: String) -> ReadableStreamType {
	let task = newtask(shellcommand)

	let output = NSPipe ()
	task.standardOutput = output
	task.launch()
	task.waitUntilExit()
	return output.fileHandleForReading
}

public func run (shellcommand: String)(input: ReadableStreamType) -> ReadableStreamType {
	let task = newtask(shellcommand)
	task.standardInput = input as File

	let output = NSPipe ()
	task.standardOutput = output
	task.launch()
	task.waitUntilExit()
	return output.fileHandleForReading
}


// swift-tools-version:4.0
import PackageDescription

let package = Package(
    name: "HandySwift",
    products: [
        .library(
            name: "HandySwift",
            targets: ["HandySwift"]
        )
    ],
    targets: [
        .target(
            name: "HandySwift",
            path: "Framework/Sources",
            exclude: [
                "Sources/SupportingFiles"
            ]
        ),
        .testTarget(
            name: "HandySwiftTests",
            dependencies: ["HandySwift"],
            path: "Tests"
        )
    ],
    swiftLanguageVersions: [4]
)

Exclude supporting files from tests

// swift-tools-version:4.0
import PackageDescription

let package = Package(
    name: "HandySwift",
    products: [
        .library(
            name: "HandySwift",
            targets: ["HandySwift"]
        )
    ],
    targets: [
        .target(
            name: "HandySwift",
            path: "Framework/Sources",
            exclude: [
                "Sources/SupportingFiles"
            ]
        ),
        .testTarget(
            name: "HandySwiftTests",
            dependencies: ["HandySwift"],
            path: "Tests",
            exclude: [
                "Tests/SupportingFiles"
            ]
        )
    ],
    swiftLanguageVersions: [4]
)


import PackageDescription

let package = Package(
    name: "Moya",
    targets: [
        Target(
            name: "Moya"
        ),
        Target(
            name: "ReactiveMoya",
            dependencies: ["Moya"]
        ),
        Target(
            name: "RxMoya",
            dependencies: ["Moya"]
        )
    ],
    dependencies: [
        .Package(url: "https://github.com/Alamofire/Alamofire", majorVersion: 4),
        .Package(url: "https://github.com/ReactiveCocoa/ReactiveSwift", majorVersion: 1),
        .Package(url: "https://github.com/ReactiveX/RxSwift", majorVersion: 3)
    ],
    exclude: [
        "Tests"
    ]
)

Add Result as an explicit dependency in SwiftPM

import PackageDescription

let package = Package(
    name: "Moya",
    targets: [
        Target(
            name: "Moya"
        ),
        Target(
            name: "ReactiveMoya",
            dependencies: ["Moya"]
        ),
        Target(
            name: "RxMoya",
            dependencies: ["Moya"]
        )
    ],
    dependencies: [
        .Package(url: "https://github.com/Alamofire/Alamofire", majorVersion: 4),
        .Package(url: "https://github.com/ReactiveCocoa/ReactiveSwift", majorVersion: 1),
        .Package(url: "https://github.com/ReactiveX/RxSwift", majorVersion: 3),
        .Package(url: "https://github.com/antitypical/Result", majorVersion: 3)
    ],
    exclude: [
        "Tests"
    ]
)


import PackageDescription

let package = Package(
    name: "pikter",
    targets: [
        Target(name: "pikter", dependencies: ["Docopt"]),
    ],
    dependencies: [
    ]
)

Update dependencies to outside Docopt

import PackageDescription

let package = Package(
    name: "pikter",
    dependencies: [
        .Package(url: "https://github.com/docopt/docopt.swift.git", Version(0,6,4)),
    ]
)


//
//  main.swift
//  quicktype
//
//  Created by Mark Probst on 8/24/17.
//  Copyright © 2017 quicktype. All rights reserved.
//

import Foundation

let filename = CommandLine.arguments[1]
guard
    let data = FileHandle(forReadingAtPath: filename)?.readDataToEndOfFile(),
    let obj = topLevel(fromJSONData: data),
    let newData = jsonData(fromTopLevel: obj),
    let jsonString = String(data: newData, encoding: String.Encoding.utf8)
else {
    exit(1)
}

print(jsonString)

Print error messages in the swift test driver

//
//  main.swift
//  quicktype
//
//  Created by Mark Probst on 8/24/17.
//  Copyright © 2017 quicktype. All rights reserved.
//

import Foundation

let filename = CommandLine.arguments[1]
guard let data = FileHandle(forReadingAtPath: filename)?.readDataToEndOfFile()
else {
    print("Error: Could not read input file")
    exit(1)
}

guard let obj = topLevel(fromJSONData: data)
else {
    print("Error: Could not deserialize")
    exit(1)
}

guard let newData = jsonData(fromTopLevel: obj)
else {
    print("Error: Could not deserialize")
    exit(1)
}

guard let jsonString = String(data: newData, encoding: String.Encoding.utf8)
else {
    print("Error: Could not stringify")
    exit(1)
}

print(jsonString)


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

import Assertions
import XCTest

final class AssertionsTests: XCTestCase {
	func testAssertingWithOptionalArrays() {
		let array: [Int]? = [1, 2, 3]
		assert(array, ==, [1, 2, 3])
//		XCTAssertEqual(array, [1, 2, 3]) // => error: value of optional type '[Int]?' not unwrapped; did you mean to use '!' or '?'?
	}

	func testAssertingWithOptionalStrings() {
		let string: String? = "hello"
		assert(string, ==, "hello")
//		XCTAssertEqual(string, "hello") // => error: cannot find an overload for 'XCTAssertEqual' that accepts an argument list of type '(String?, String)'
	}

	func testAssertingWithMethods() {
		let set: Set<Int>? = Set([1, 2, 3])
		assert(set, Set.contains, 3)
	}

	func testAssertingPropertyWithPredicate() {
		let string: String? = ""
		assert(string, { $0.isEmpty })
	}

	func testAssertingNilOfEquatableType() {
		let x: Int? = nil
		assert(x, ==, nil)
	}
}

Test asserting that an Equatable != nil.

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

import Assertions
import XCTest

final class AssertionsTests: XCTestCase {
	func testAssertingWithOptionalArrays() {
		let array: [Int]? = [1, 2, 3]
		assert(array, ==, [1, 2, 3])
//		XCTAssertEqual(array, [1, 2, 3]) // => error: value of optional type '[Int]?' not unwrapped; did you mean to use '!' or '?'?
	}

	func testAssertingWithOptionalStrings() {
		let string: String? = "hello"
		assert(string, ==, "hello")
//		XCTAssertEqual(string, "hello") // => error: cannot find an overload for 'XCTAssertEqual' that accepts an argument list of type '(String?, String)'
	}

	func testAssertingWithMethods() {
		let set: Set<Int>? = Set([1, 2, 3])
		assert(set, Set.contains, 3)
	}

	func testAssertingPropertyWithPredicate() {
		let string: String? = ""
		assert(string, { $0.isEmpty })
	}

	func testAssertingNilOfEquatableType() {
		let x: Int? = nil
		assert(x, ==, nil)
	}

	func testAssertingNonNilOfEquatableType() {
		let x: Int? = 1
		assert(x, !=, nil)
	}
}


//
//  HTTPBinConfigurable.swift
//  Restofire
//
//  Created by Rahul Katariya on 15/04/16.
//  Copyright © 2016 AarKay. All rights reserved.
//

import Foundation
@testable import Restofire

protocol HTTPBinConfigurable: Configurable { }

extension HTTPBinConfigurable {

    var configuration: Configuration {
        var config = Configuration()
        config.scheme = "https://"
        config.baseURL = "httpbin.org/"
        return config
    }

}

Remove Trailing Slash from base url

//
//  HTTPBinConfigurable.swift
//  Restofire
//
//  Created by Rahul Katariya on 15/04/16.
//  Copyright © 2016 AarKay. All rights reserved.
//

import Foundation
@testable import Restofire

protocol HTTPBinConfigurable: Configurable { }

extension HTTPBinConfigurable {

    var configuration: Configuration {
        var config = Configuration()
        config.scheme = "https://"
        config.baseURL = "httpbin.org"
        return config
    }

}


//
//  EventListViewController.swift
//  UIKonf
//
//  Copyright © 2016 Raised by Wolves. All rights reserved.
//

import UIKit
import IBAnimatable
import Reusable

final class EventListViewController: TableViewController<Event, BasicTableViewCell> {

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

        items = Event.allEvents
        configureCell = { cell, event in
            cell.configure(withTitle: event.name, detail: event.description, image: event.image)
        }
        willDisplayCell = { cell in
            cell.animate(.none)
        }
        didSelect = { [unowned self] event in
            self.perform(segue: StoryboardSegue.Main.showEventRegistration, prepare: { segue in
                guard let detail = segue.destination as? EventRegistrationViewController
                    else { fatalError("Wrong view controller type.") }
                detail.event = event
            })
        }
    }
}

Add missing disclosure indicator for event list cell.

//
//  EventListViewController.swift
//  UIKonf
//
//  Copyright © 2016 Raised by Wolves. All rights reserved.
//

import UIKit
import IBAnimatable
import Reusable

final class EventListViewController: TableViewController<Event, BasicTableViewCell> {

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

        items = Event.allEvents
        configureCell = { cell, event in
            cell.accessoryType = .disclosureIndicator
            cell.configure(withTitle: event.name, detail: event.description, image: event.image)
        }
        willDisplayCell = { cell in
            cell.animate(.none)
        }
        didSelect = { [unowned self] event in
            self.perform(segue: StoryboardSegue.Main.showEventRegistration, prepare: { segue in
                guard let detail = segue.destination as? EventRegistrationViewController
                    else { fatalError("Wrong view controller type.") }
                detail.event = event
            })
        }
    }
}


//
//  ItemsViewController.swift
//  Homepwner
//
//  Created by Omer Wazir on 9/3/14.
//  Copyright (c) 2014 Omer Wazir. All rights reserved.
//

import UIKit

class ItemsViewController: UITableViewController {

    override init(){
        super.init(style: UITableViewStyle.Plain)
    }

    override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    override convenience init(style: UITableViewStyle) {
        self.init()
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("NSCoding not supported")
    }

}

Create items and add to table view

//
//  ItemsViewController.swift
//  Homepwner
//
//  Created by Omer Wazir on 9/3/14.
//  Copyright (c) 2014 Omer Wazir. All rights reserved.
//

import UIKit

class ItemsViewController: UITableViewController {

    override init(){
        super.init(style: UITableViewStyle.Plain)

        for _ in 1...5 {
            ItemStore.sharedStore.createItem()
        }
    }

    override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    override convenience init(style: UITableViewStyle) {
        self.init()
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("NSCoding not supported")
    }

    override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return ItemStore.sharedStore.allItems.count
    }

    override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {

        // create an instance of UITableViewCell with the default appearance
        let cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "UITableViewCell")

        //Set the text of the cell with the description of the item
        //that is at the nth index of ItemStore.sharedStore.allitems

        let items = ItemStore.sharedStore.allItems
        let item:Item = items[indexPath.row]

        cell.textLabel.text = item.description

        return cell
    }
}


//
//  Box.swift
//  TemplateKit
//
//  Created by Matias Cudich on 9/3/16.
//  Copyright © 2016 Matias Cudich. All rights reserved.
//

import Foundation

public class Box: UIView, NativeView {
  public var eventTarget: AnyObject?

  public var properties = [String : Any]() {
    didSet {
      applyCommonProperties(properties: properties)
    }
  }

  public var children: [NativeView]? {
    didSet {
      // TODO(mcudich): Be smarter about adding/removing/moving here.
      for view in subviews {
        view.removeFromSuperview()
      }

      for child in (children ?? []) {
        if let subview = child as? UIView {
          addSubview(subview)
        }
      }
    }
  }

  public required init() {
    super.init(frame: CGRect.zero)
  }

  required public init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

Clean up child view insertion

//
//  Box.swift
//  TemplateKit
//
//  Created by Matias Cudich on 9/3/16.
//  Copyright © 2016 Matias Cudich. All rights reserved.
//

import Foundation

public class Box: UIView, NativeView {
  public var eventTarget: AnyObject?

  public var properties = [String : Any]() {
    didSet {
      applyCommonProperties(properties: properties)
    }
  }

  public var children: [NativeView]? {
    didSet {
      var pendingViews = Set(subviews)

      for (index, child) in (children ?? []).enumerated() {
        guard let childView = child as? UIView else {
          fatalError()
        }

        insertSubview(childView, at: index)
        pendingViews.remove(childView)
      }

      pendingViews.forEach { $0.removeFromSuperview() }
    }
  }

  public required init() {
    super.init(frame: CGRect.zero)
  }

  required public init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}


//
//  IntegerTypeExtensionTests.swift
//  HandySwift
//
//  Created by Cihat Gündüz on 18.12.15.
//  Copyright © 2015 Flinesoft. All rights reserved.
//

import XCTest

@testable import HandySwift

class IntExtensionTests: XCTestCase {

    func testTimesMethod() {
        var testString = ""

        0.times{ testString += "." }

        XCTAssertEqual(testString, "")

        3.times() {
            testString += "."
        }

        XCTAssertEqual(testString, "...")
    }

}

Use fixed syntax in Tests, too

//
//  IntegerTypeExtensionTests.swift
//  HandySwift
//
//  Created by Cihat Gündüz on 18.12.15.
//  Copyright © 2015 Flinesoft. All rights reserved.
//

import XCTest

@testable import HandySwift

class IntExtensionTests: XCTestCase {

    func testTimesMethod() {
        var testString = ""

        0.times{ testString += "." }

        XCTAssertEqual(testString, "")

        3.times {
            testString += "."
        }

        XCTAssertEqual(testString, "...")
    }

}


import XCTest
#if GRDBCUSTOMSQLITE
    import GRDBCustomSQLite
#else
    import GRDB
#endif

class DatabaseConfigurationTests: GRDBTestCase {
    func testPrepareDatabase() throws {
        // prepareDatabase is called when connection opens
        var connectionCount = 0
        var configuration = Configuration()
        configuration.prepareDatabase = { db in
            connectionCount += 1
        }

        _ = DatabaseQueue(configuration: configuration)
        XCTAssertEqual(connectionCount, 1)

        _ = try makeDatabaseQueue(configuration: configuration)
        XCTAssertEqual(connectionCount, 2)

        let pool = try makeDatabasePool(configuration: configuration)
        XCTAssertEqual(connectionCount, 3)

        try pool.read { _ in }
        XCTAssertEqual(connectionCount, 4)

        try pool.makeSnapshot().read { _ in }
        XCTAssertEqual(connectionCount, 5)
    }
}

Test that prepareDatabase errors are rethrown

import XCTest
#if GRDBCUSTOMSQLITE
    import GRDBCustomSQLite
#else
    import GRDB
#endif

class DatabaseConfigurationTests: GRDBTestCase {
    func testPrepareDatabase() throws {
        // prepareDatabase is called when connection opens
        var connectionCount = 0
        var configuration = Configuration()
        configuration.prepareDatabase = { db in
            connectionCount += 1
        }

        _ = DatabaseQueue(configuration: configuration)
        XCTAssertEqual(connectionCount, 1)

        _ = try makeDatabaseQueue(configuration: configuration)
        XCTAssertEqual(connectionCount, 2)

        let pool = try makeDatabasePool(configuration: configuration)
        XCTAssertEqual(connectionCount, 3)

        try pool.read { _ in }
        XCTAssertEqual(connectionCount, 4)

        try pool.makeSnapshot().read { _ in }
        XCTAssertEqual(connectionCount, 5)
    }

    func testPrepareDatabaseError() throws {
        struct TestError: Error { }
        var error: TestError?

        var configuration = Configuration()
        configuration.prepareDatabase = { db in
            if let error = error {
                throw error
            }
        }

        // TODO: what about in-memory DatabaseQueue???

        do {
            error = TestError()
            _ = try makeDatabaseQueue(configuration: configuration)
            XCTFail("Expected TestError")
        } catch is TestError { }

        do {
            error = TestError()
            _ = try makeDatabasePool(configuration: configuration)
            XCTFail("Expected TestError")
        } catch is TestError { }

        do {
            error = nil
            let pool = try makeDatabasePool(configuration: configuration)

            do {
                error = TestError()
                try pool.read { _ in }
                XCTFail("Expected TestError")
            } catch is TestError { }

            do {
                error = TestError()
                _ = try pool.makeSnapshot()
                XCTFail("Expected TestError")
            } catch is TestError { }
        }
    }
}


//
//  AppDelegate.swift
//  kawa
//
//  Created by noraesae on 27/07/2015.
//  Copyright (c) 2015 noraesae. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(aNotification: NSNotification) {
        InputSourceManager.initialize()
    }

    func applicationWillTerminate(aNotification: NSNotification) {
    }
}

Set the application policy to Accessory.

//
//  AppDelegate.swift
//  kawa
//
//  Created by noraesae on 27/07/2015.
//  Copyright (c) 2015 noraesae. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(aNotification: NSNotification) {
        NSApp.setActivationPolicy(NSApplicationActivationPolicy.Accessory)
        InputSourceManager.initialize()
    }

    func applicationWillTerminate(aNotification: NSNotification) {
    }
}


//
//  UIView+Mixed.swift
//  Pods
//
//  Created by Draveness on 6/30/16.
//
//

import Foundation
import ObjectiveC

public extension UIView {
    public var mixedBackgroundColor: MixedColor? {
        get { return getMixedColor(&Keys.backgroundColor) }
        set {
            backgroundColor = newValue?.unfold()
            setMixedColor(&Keys.backgroundColor, value: newValue)
        }
    }
    public var mixedTintColor: MixedColor? {
        get { return getMixedColor(&Keys.tintColor) }
        set {
            tintColor = newValue?.unfold()
            setMixedColor(&Keys.tintColor, value: newValue)
        }
    }

    override func updateCurrentColor() {
        super.updateCurrentColor()

        if let mixedBackgroundColor = mixedBackgroundColor {
            backgroundColor = mixedBackgroundColor.unfold()
        }

        if let mixedTintColor = mixedTintColor {
            tintColor = mixedTintColor.unfold()
        }

    }
}

Add white line before var declare


import Vapor

extension Droplet {

    func setupRoutes() throws {
        get("hello") { req in
            var json = JSON()
            try json.set("hello", "world")
            return json
        }

        get("plaintext") { req in
            return "Hello, world!"
        }

        // response to requests to /info domain
        // with a description of the request
        get("info") { req in
            return req.description
        }

        get("description") { req in return req.description }
    }
}

Update routes to expose /api/v1 and /api/v1/market linked to MarketController

import Vapor

extension Droplet {

    func setupRoutes() throws {

        let api = grouped("api", "v1")

        api.get("hello") { request in

            var json = JSON()
            try json.set("hello", "world")

            return json
        }

        let marketController = MarketController()

        api.get("market") { request in

            return try marketController.market(request)
        }
    }
}


//
//  NotificationBanner.swift
//  Ello
//
//  Created by Gordon Fontenot on 5/21/15.
//  Copyright (c) 2015 Ello. All rights reserved.
//

import CRToast

public struct NotificationBanner {
    public static func displayAlertForPayload(payload: PushPayload) {
        configureDefaultsWithPayload(payload)
        CRToastManager.showNotificationWithMessage(payload.message) { }
    }
}

private extension NotificationBanner {
    static func configureDefaultsWithPayload(payload: PushPayload) {
        let interactionResponder = CRToastInteractionResponder(interactionType: CRToastInteractionType.TapOnce, automaticallyDismiss: true) { _ in
            postNotification(PushNotificationNotifications.interactedWithPushNotification, payload)
        }

        CRToastManager.setDefaultOptions(
            [
                kCRToastInteractionRespondersKey: [interactionResponder],

                kCRToastNotificationTypeKey: CRToastType.NavigationBar.rawValue,
                kCRToastNotificationPresentationTypeKey: CRToastPresentationType.Cover.rawValue,

                kCRToastTextColorKey: UIColor.whiteColor(),
                kCRToastBackgroundColorKey: UIColor.blackColor(),

                kCRToastAnimationOutDirectionKey: CRToastAnimationDirection.Top.rawValue,

                kCRToastAnimationInTimeIntervalKey: DefaultAnimationDuration,
                kCRToastAnimationOutTimeIntervalKey: DefaultAnimationDuration,

                kCRToastFontKey: UIFont.typewriterFont(12.0),
                kCRToastTextAlignmentKey: NSTextAlignment.Left.rawValue,
            ]
        )
    }
}

Set max number of lines to 2

//
//  NotificationBanner.swift
//  Ello
//
//  Created by Gordon Fontenot on 5/21/15.
//  Copyright (c) 2015 Ello. All rights reserved.
//

import CRToast

public struct NotificationBanner {
    public static func displayAlertForPayload(payload: PushPayload) {
        configureDefaultsWithPayload(payload)
        CRToastManager.showNotificationWithMessage(payload.message) { }
    }
}

private extension NotificationBanner {
    static func configureDefaultsWithPayload(payload: PushPayload) {
        let interactionResponder = CRToastInteractionResponder(interactionType: CRToastInteractionType.TapOnce, automaticallyDismiss: true) { _ in
            postNotification(PushNotificationNotifications.interactedWithPushNotification, payload)
        }

        CRToastManager.setDefaultOptions(
            [
                kCRToastInteractionRespondersKey: [interactionResponder],

                kCRToastNotificationTypeKey: CRToastType.NavigationBar.rawValue,
                kCRToastNotificationPresentationTypeKey: CRToastPresentationType.Cover.rawValue,

                kCRToastTextColorKey: UIColor.whiteColor(),
                kCRToastBackgroundColorKey: UIColor.blackColor(),

                kCRToastAnimationOutDirectionKey: CRToastAnimationDirection.Top.rawValue,

                kCRToastAnimationInTimeIntervalKey: DefaultAnimationDuration,
                kCRToastAnimationOutTimeIntervalKey: DefaultAnimationDuration,

                kCRToastFontKey: UIFont.typewriterFont(12.0),
                kCRToastTextAlignmentKey: NSTextAlignment.Left.rawValue,
                kCRToastTextMaxNumberOfLinesKey: 2,
            ]
        )
    }
}


//
//  Distance.swift
//  Compass
//
//  Created by Fabian Canas on 5/20/15.
//  Copyright (c) 2015 Fabian Canas. All rights reserved.
//

import Foundation

public struct Distance :NumericType {
    public var value :Double
    public init(_ value: Double) {
        self.value = value
    }
}

extension Distance :IntegerLiteralConvertible {
    public init(integerLiteral: IntegerLiteralType) {
        self.init(Double(integerLiteral))
    }
}

extension Distance :FloatLiteralConvertible {
    public init(floatLiteral: FloatLiteralType) {
        self.init(Double(floatLiteral))
    }
}

public struct Area :NumericType {
    public var value :Double
    public init(_ value: Double) {
        self.value = value
    }
}

extension Area :IntegerLiteralConvertible {
    public init(integerLiteral: IntegerLiteralType) {
        self.init(Double(integerLiteral))
    }
}

extension Area :FloatLiteralConvertible {
    public init(floatLiteral: FloatLiteralType) {
        self.init(Double(floatLiteral))
    }
}

extension Distance :MultiplicativeType {
    typealias ProductType = Area
}

Remove unneeded Double constructor call

//
//  Distance.swift
//  Compass
//
//  Created by Fabian Canas on 5/20/15.
//  Copyright (c) 2015 Fabian Canas. All rights reserved.
//

import Foundation

public struct Distance :NumericType {
    public var value :Double
    public init(_ value: Double) {
        self.value = value
    }
}

extension Distance :IntegerLiteralConvertible {
    public init(integerLiteral: IntegerLiteralType) {
        self.init(Double(integerLiteral))
    }
}

extension Distance :FloatLiteralConvertible {
    public init(floatLiteral: FloatLiteralType) {
        self.init(floatLiteral)
    }
}

public struct Area :NumericType {
    public var value :Double
    public init(_ value: Double) {
        self.value = value
    }
}

extension Area :IntegerLiteralConvertible {
    public init(integerLiteral: IntegerLiteralType) {
        self.init(Double(integerLiteral))
    }
}

extension Area :FloatLiteralConvertible {
    public init(floatLiteral: FloatLiteralType) {
        self.init(floatLiteral)
    }
}

extension Distance :MultiplicativeType {
    typealias ProductType = Area
}


public protocol Stream {
    func read(maxBytes: Int) throws -> [UInt8]
    func write(bytes: [UInt8]) throws -> Int
    func close() throws
}

Add 8-bit int read/write functions

public protocol Stream {
    func read(maxBytes: Int) throws -> [UInt8]
    func write(bytes: [UInt8]) throws -> Int
    func close() throws
}

extension Stream {
    func readUInt8() throws -> UInt8 {
        return try read(1)[0]
    }

    func readInt8() throws -> Int8 {
        return try read(1)[0]
    }

    func writeInt8(int8: Int8) throws {
        try write([int8])
    }

    func write(uint8: UInt8) throws {
        try write([uint8])
    }
}


//
//  Fixtures.swift
//  DeferredTests
//
//  Created by Zachary Waldowski on 6/10/15.
//  Copyright © 2014-2016 Big Nerd Ranch. Licensed under MIT.
//

import XCTest
@testable import Deferred
#if SWIFT_PACKAGE
import Result
#endif

let TestTimeout: NSTimeInterval = 15

enum Error: ErrorType {
    case First
    case Second
    case Third
}

extension ResultType {
    var value: Value? {
        return withValues(ifSuccess: { $0 }, ifFailure: { _ in nil })
    }

    var error: ErrorType? {
        return withValues(ifSuccess: { _ in nil }, ifFailure: { $0 })
    }
}

Add a Task convenience for unit tests

//
//  Fixtures.swift
//  DeferredTests
//
//  Created by Zachary Waldowski on 6/10/15.
//  Copyright © 2014-2016 Big Nerd Ranch. Licensed under MIT.
//

import XCTest
@testable import Deferred
#if SWIFT_PACKAGE
import Result
#endif

let TestTimeout: NSTimeInterval = 15

enum Error: ErrorType {
    case First
    case Second
    case Third
}

extension XCTestCase {
    func waitForTaskToComplete<T>(task: Task<T>) -> TaskResult<T>! {
        let expectation = expectationWithDescription("task completed")
        var result: TaskResult<T>?
        task.uponMainQueue { [weak expectation] in
            result = $0
            expectation?.fulfill()
        }
        waitForExpectationsWithTimeout(TestTimeout, handler: nil)

        return result
    }
}

extension ResultType {
    var value: Value? {
        return withValues(ifSuccess: { $0 }, ifFailure: { _ in nil })
    }

    var error: ErrorType? {
        return withValues(ifSuccess: { _ in nil }, ifFailure: { $0 })
    }
}


//
//  Quadratic.swift
//  PathTools
//
//  Created by James Bean on 11/24/16.
//
//

import QuartzCore

// TODO: Move to `ArithmeticType`.

/// - returns: Two possible answers, if `descriminant > 0`. Returns an empty set if the
///     discriminant is empty, and the solution would therefore be complex.
public func quadratic(_ a: CGFloat, _ b: CGFloat, _ c: CGFloat) -> Set<CGFloat> {

    let discriminant = pow(b,2) - 4 * a * c

    guard discriminant > 0 else {
        return Set()
    }

    return Set(
        [1, -1].map { sign in (-b + sign * sqrt(discriminant)) / (2 * a) }
    )
}

Fix typo in doc comment

//
//  Quadratic.swift
//  PathTools
//
//  Created by James Bean on 11/24/16.
//
//

import QuartzCore

// TODO: Move to `ArithmeticType`.

/// - returns: Two possible answers, if `discriminant > 0`. Returns an empty set if the
///     discriminant is empty, and the solution would therefore be complex.
public func quadratic(_ a: CGFloat, _ b: CGFloat, _ c: CGFloat) -> Set<CGFloat> {

    let discriminant = pow(b,2) - 4 * a * c

    guard discriminant > 0 else {
        return Set()
    }

    return Set(
        [1, -1].map { sign in (-b + sign * sqrt(discriminant)) / (2 * a) }
    )
}


//
//  WhosNextVC.swift
//  Perspective
//
//  Created by Apprentice on 2/17/15.
//  Copyright (c) 2015 Dev Bootcamp. All rights reserved.
//

import UIKit

class WhosNextVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

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

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

Add whos next view and controller.

//
//  WhosNextVC.swift
//  Perspective
//
//  Created by Apprentice on 2/17/15.
//  Copyright (c) 2015 Dev Bootcamp. All rights reserved.
//

import UIKit

class WhosNextVC: UIViewController {

    var url: String!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

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

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}


//
//  NSBundle+Cocoapods.swift
//  Pods
//
//  Created by Jelle Vandebeeck on 08/06/16.
//
//

import Foundation

class BaseBundle {}

extension Bundle {

    static func deliriumBundle() -> Bundle {
        let bundlePath = Bundle(for: BaseBundle.self).path(forResource: "Delirium", ofType: "bundle")!
        return Bundle(path: bundlePath)!
    }

    fileprivate static func localeBundle() -> Bundle {
        // Fetch your current language.
        let components = Locale.components(fromIdentifier: Locale.current.identifier)
        let language = components[Locale.current.languageCode!]

        // When we can't find the bundle we prepare the English bunde.
        var path = deliriumBundle().path(forResource: language, ofType: "lproj")
        if path == nil { path = deliriumBundle().path(forResource: "en", ofType: "lproj") }
        return Bundle(path: path!)!
    }

}

extension String {

    var localizedString: String {
        return NSLocalizedString(self, bundle: Bundle.localeBundle(), comment: "")
    }

}

Use the correct localizable file from the pod.

//
//  NSBundle+Cocoapods.swift
//  Pods
//
//  Created by Jelle Vandebeeck on 08/06/16.
//
//

import Foundation

class BaseBundle {}

extension Bundle {

    static func deliriumBundle() -> Bundle {
        let bundlePath = Bundle(for: BaseBundle.self).path(forResource: "Delirium", ofType: "bundle")!
        return Bundle(path: bundlePath)!
    }

    fileprivate static func localeBundle() -> Bundle {
        // Fetch your current language.
        let components = Locale.components(fromIdentifier: Locale.current.identifier)
        let language = components[Locale.current.languageCode!]

        // When we can't find the bundle we prepare the English bunde.
        var path = deliriumBundle().path(forResource: language, ofType: "lproj")
        if path == nil { path = deliriumBundle().path(forResource: "en", ofType: "lproj") }
        return Bundle(path: path!)!
    }

}

extension String {

    var localizedString: String {
        return NSLocalizedString(self, tableName: "DeliriumLocalizable", bundle: Bundle.localeBundle(), comment: "")
    }

}


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

/// Wrapper for a contiguous array of T.  UnsafeArray is both a
/// Collection—which is multi-pass if you use indices or call
/// generate() on it—and a Generator, which can only be assumed to be
/// single-pass.  It's not clear how well this combination will work
/// out, or whether all Collections should also be Streams; consider
/// this an experiment.
struct UnsafeArray<T> : Collection, Generator {

  var startIndex: Int {
    return 0
  }

  var endIndex: Int {
    return _end - _position
  }

  subscript(i: Int) -> T {
    assert(i >= 0)
    assert(i < endIndex)
    return (_position + i).get()
  }

  init(start: UnsafePointer<T>, length: Int) {
    _position = start
    _end = start + length
  }

  mutating func next() -> T? {
    if _position == _end {
      return .None
    }
    return .Some((_position++).get())
  }

  func generate() -> UnsafeArray {
    return self
  }

  var _position, _end: UnsafePointer<T>
}

Remove non-ascii dash character from a comment.

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

/// Wrapper for a contiguous array of T.  UnsafeArray is both a
/// Collection-which is multi-pass if you use indices or call
/// generate() on it-and a Generator, which can only be assumed to be
/// single-pass.  It's not clear how well this combination will work
/// out, or whether all Collections should also be Streams; consider
/// this an experiment.
struct UnsafeArray<T> : Collection, Generator {

  var startIndex: Int {
    return 0
  }

  var endIndex: Int {
    return _end - _position
  }

  subscript(i: Int) -> T {
    assert(i >= 0)
    assert(i < endIndex)
    return (_position + i).get()
  }

  init(start: UnsafePointer<T>, length: Int) {
    _position = start
    _end = start + length
  }

  mutating func next() -> T? {
    if _position == _end {
      return .None
    }
    return .Some((_position++).get())
  }

  func generate() -> UnsafeArray {
    return self
  }

  var _position, _end: UnsafePointer<T>
}


//
//  ViewController.swift
//  GearAnimation
//
//  Created by Andrea Mazzini on 18/03/15.
//  Copyright (c) 2015 Fancy Pixel. All rights reserved.
//

import UIKit

class ViewController: UITableViewController {

    var gearRefreshControl: GearRefreshControl!

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        return tableView.dequeueReusableCellWithIdentifier("Cell")! as UITableViewCell
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        gearRefreshControl = GearRefreshControl(frame: self.view.bounds)
        gearRefreshControl.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
        self.refreshControl = gearRefreshControl
    }

    func refresh(){
        var popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(3.0 * Double(NSEC_PER_SEC)));
        dispatch_after(popTime, dispatch_get_main_queue()) { () -> Void in
            self.gearRefreshControl.endRefreshing()
        }
    }

    override func scrollViewDidScroll(scrollView: UIScrollView) {
        gearRefreshControl.scrollViewDidScroll(scrollView)
    }
}

Update swift syntax to 1.2

//
//  ViewController.swift
//  GearAnimation
//
//  Created by Andrea Mazzini on 18/03/15.
//  Copyright (c) 2015 Fancy Pixel. All rights reserved.
//

import UIKit

class ViewController: UITableViewController {

    var gearRefreshControl: GearRefreshControl!

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        return tableView.dequeueReusableCellWithIdentifier("Cell")! as! UITableViewCell
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        gearRefreshControl = GearRefreshControl(frame: self.view.bounds)
        gearRefreshControl.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
        self.refreshControl = gearRefreshControl
    }

    func refresh(){
        var popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(3.0 * Double(NSEC_PER_SEC)));
        dispatch_after(popTime, dispatch_get_main_queue()) { () -> Void in
            self.gearRefreshControl.endRefreshing()
        }
    }

    override func scrollViewDidScroll(scrollView: UIScrollView) {
        gearRefreshControl.scrollViewDidScroll(scrollView)
    }
}


//
//  Store.swift
//  HomeControl
//
//  Created by Julian Grosshauser on 30/11/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import ReactiveCocoa
import SWXMLHash

enum StoreError: ErrorType {
    case NetworkError(ErrorType?)
    case ReadError(ErrorType)
}

class Store {

    func parseStructureFile(path: String) -> SignalProducer<[Room], StoreError> {
        let structureFileContent: String

        do {
            structureFileContent = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
        } catch {
            return SignalProducer(error: .ReadError(error))
        }

        let structureFile = SWXMLHash.parse(structureFileContent)
        var roomDictionary = [UInt: String]()

        for room in structureFile["LoxLIVE"]["Rooms"]["Room"] {
            if let idString = room.element?.attributes["n"], id = UInt(idString), name = room.element?.attributes["name"] {
                roomDictionary[id] = name
            }
        }

        let rooms = [Room]()
        return SignalProducer(value: rooms)
    }
}

Use mutable Room array to collect parsed rooms

//
//  Store.swift
//  HomeControl
//
//  Created by Julian Grosshauser on 30/11/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import ReactiveCocoa
import SWXMLHash

enum StoreError: ErrorType {
    case NetworkError(ErrorType?)
    case ReadError(ErrorType)
}

class Store {

    func parseStructureFile(path: String) -> SignalProducer<[Room], StoreError> {
        let structureFileContent: String

        do {
            structureFileContent = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
        } catch {
            return SignalProducer(error: .ReadError(error))
        }

        let structureFile = SWXMLHash.parse(structureFileContent)
        var rooms = [Room]()

        for room in structureFile["LoxLIVE"]["Rooms"]["Room"] {
            if let idString = room.element?.attributes["n"], id = UInt(idString), name = room.element?.attributes["name"] {
                rooms.append(Room(id: id, name: name))
            }
        }

        return SignalProducer(value: rooms)
    }
}


//
//  MainViewController.swift
//  Pargi
//
//  Main view controller, contains both the map as well as the
//  detail VCs and controls the information the two display
//
//  Created by Henri Normak on 27/04/2017.
//  Copyright © 2017 Henri Normak. All rights reserved.
//

import Foundation
import UIKit
import Pulley

class MainViewController: PulleyViewController, MapViewControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Grab all zones and force them down to the map/detail views
        let zones = ApplicationData.currentDatabase.zones

        if let mapView = self.primaryContentViewController as? MapViewController {
            mapView.zones = zones
            mapView.delegate = self
        }
    }

    // MARK: MapViewControllerDelegate

    func mapViewController(_ controller: MapViewController, didUpdateVisibleZones zones: [Zone]) {
        let top = zones[0..<min(zones.count, 5)]
        print("Closest zones \(top.count) => \(top.map({ $0.code }))")
    }
}

Handle zone selection in the main VC

//
//  MainViewController.swift
//  Pargi
//
//  Main view controller, contains both the map as well as the
//  detail VCs and controls the information the two display
//
//  Created by Henri Normak on 27/04/2017.
//  Copyright © 2017 Henri Normak. All rights reserved.
//

import Foundation
import UIKit
import Pulley

class MainViewController: PulleyViewController, MapViewControllerDelegate, DetailViewControllerDelegate {

    fileprivate var mapViewController: MapViewController? {
        get {
            return self.primaryContentViewController as? MapViewController
        }
    }

    fileprivate var detailViewController: DetailViewController? {
        get {
            return self.drawerContentViewController as? DetailViewController
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Grab all zones and force them down to the map/detail views
        let zones = ApplicationData.currentDatabase.zones

        if let mapView = self.mapViewController {
            mapView.zones = zones
            mapView.delegate = self
        }

        if let detailView = self.detailViewController {
            detailView.delegate = self
        }
    }

    // MARK: MapViewControllerDelegate

    func mapViewController(_ controller: MapViewController, didUpdateVisibleZones zones: [Zone]) {
        let bestMatches = Array(zones[0..<min(zones.count, 3)])

        if let detailView = self.drawerContentViewController as? DetailViewController {
            detailView.zones = bestMatches
        }
    }

    // MARK: DetailViewControllerDelegate

    func detailViewController(_ controller: DetailViewController, didSelectZone zone: Zone?) {
        print("Selected zone \(zone)")
    }
}


//
//  LTSplitViewController.swift
//  VPNOn
//
//  Created by Lex on 1/18/15.
//  Copyright (c) 2015 LexTang.com. All rights reserved.
//

import UIKit

class LTSplitViewController: UISplitViewController
{

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.blackColor()
    }

}

Change color of status bar.

//
//  LTSplitViewController.swift
//  VPNOn
//
//  Created by Lex on 1/18/15.
//  Copyright (c) 2015 LexTang.com. All rights reserved.
//

import UIKit

class LTSplitViewController: UISplitViewController
{

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.blackColor()
    }

    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return UIStatusBarStyle.LightContent
    }

}


// Package.swift - description
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//

import PackageDescription

let package = Package(
  name: "SwiftProtobuf",
  targets: [
    Target(name: "PluginLibrary",
           dependencies: ["SwiftProtobuf"]),
    Target(name: "protoc-gen-swift",
           dependencies: ["PluginLibrary", "SwiftProtobuf"]),
    Target(name: "Conformance",
           dependencies: ["SwiftProtobuf"]),
  ]
)

Allow SwiftPM to use Swift 3 or 4

// swift-tools-version:3.1
// Package.swift - description
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//

import PackageDescription

#if swift(>=3.1)
let package = Package(
  name: "SwiftProtobuf",
  targets: [
    Target(name: "PluginLibrary",
           dependencies: ["SwiftProtobuf"]),
    Target(name: "protoc-gen-swift",
           dependencies: ["PluginLibrary", "SwiftProtobuf"]),
    Target(name: "Conformance",
           dependencies: ["SwiftProtobuf"]),
  ],
  swiftLanguageVersions: [3, 4]
)
#else
let package = Package(
  name: "SwiftProtobuf",
  targets: [
    Target(name: "PluginLibrary",
           dependencies: ["SwiftProtobuf"]),
    Target(name: "protoc-gen-swift",
           dependencies: ["PluginLibrary", "SwiftProtobuf"]),
    Target(name: "Conformance",
           dependencies: ["SwiftProtobuf"]),
  ]
)
#endif


import Cocoa
import SafariServices

class ViewController: NSViewController {
    @IBOutlet weak var enabledLabel: NSTextField!
    @IBOutlet weak var disabledLabel: NSTextField!
    @IBOutlet weak var enabledImage: NSImageView!
    @IBOutlet weak var disabledImage: NSImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        SFContentBlockerManager.getStateOfContentBlocker(withIdentifier: "com.kablock.macos.Ka-Block-Content-Blocker") {
            (state, error) in

            if let state = state {
                DispatchQueue.main.async {
                    let isEnabled = state.isEnabled
                    self.enabledLabel.isHidden = !isEnabled
                    self.disabledLabel.isHidden = isEnabled
                    self.enabledImage.isHidden = !isEnabled
                    self.disabledImage.isHidden = isEnabled
                }
            }
        }
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }
}

Check content blocker state every 10s

import Cocoa
import SafariServices

class ViewController: NSViewController {
    @IBOutlet weak var enabledLabel: NSTextField!
    @IBOutlet weak var disabledLabel: NSTextField!
    @IBOutlet weak var enabledImage: NSImageView!
    @IBOutlet weak var disabledImage: NSImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        updateContentBlockerState()
        Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(ViewController.updateContentBlockerState), userInfo: nil, repeats: true)
    }

    override var representedObject: Any? {
        didSet {
            // Update the view, if already loaded.
        }
    }

    @objc func updateContentBlockerState() {
        SFContentBlockerManager.getStateOfContentBlocker(withIdentifier: "com.kablock.macos.Ka-Block-Content-Blocker") {
            (state, error) in

            if let state = state {
                DispatchQueue.main.async {
                    let isEnabled = state.isEnabled
                    self.enabledLabel.isHidden = !isEnabled
                    self.disabledLabel.isHidden = isEnabled
                    self.enabledImage.isHidden = !isEnabled
                    self.disabledImage.isHidden = isEnabled
                }
            }
        }
    }
}


import Foundation
import AsyncDisplayKit
import Kingfisher

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

      let manager = KingfisherManager.sharedManager

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

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

Fix warning in image cache

import Foundation
import AsyncDisplayKit
import Kingfisher

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

      let manager = KingfisherManager.sharedManager

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

      return task
  }

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


//
//  ViewController.swift
//  FireRecord
//
//  Created by victoralissont5@gmail.com on 08/09/2017.
//  Copyright (c) 2017 victoralissont5@gmail.com. All rights reserved.
//

import UIKit
import FireRecord

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let user = User()
        user.name = "Correia"

        user.save { error in
            print(error ?? "=)")
        }

        User.findFirst { user in
            print(user.name ?? "Does not contain name")
            user.name = "Alisson"
            user.update(completion: { error in
                print(error ?? "=)")
            })
        }

        User.all { users in
            let names = users.flatMap({$0.name})
            names.forEach({print($0)})
        }
    }
}
class User: FireRecord {
    public var name: String?
    init(name: String) { self.name = name }
    required public init() {}
}

Add removal of firebaseModel in example

//
//  ViewController.swift
//  FireRecord
//
//  Created by victoralissont5@gmail.com on 08/09/2017.
//  Copyright (c) 2017 victoralissont5@gmail.com. All rights reserved.
//

import UIKit
import FireRecord

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let user = User()
        user.name = "Correia"

        user.save { error in
            print(error ?? "=)")
        }
        user.destroy { error in
            print(error ?? "=)")
        }

        User.findFirst { user in
            print(user.name ?? "Does not contain name")
            user.name = "Alisson"
            user.update(completion: { error in
                print(error ?? "=)")
            })
        }

        User.all { users in
            let names = users.flatMap({$0.name})
            names.forEach({print($0)})
        }
    }
}
class User: FireRecord {
    public var name: String?
    init(name: String) { self.name = name }
    required public init() {}
}


import Foundation

extension Date {

    /// Return a randomized `Date` in the next midnight hour. Will return nil if a `Date` can't be constructed given the calendar
    /// and component constraints, though in practice will likely always return some value.
    func randomDateShortlyAfterMidnight(calendar: Calendar = .current) -> Date? {
        let components = DateComponents(day: 1, minute: .random(in: 0..<60), second: .random(in: 0..<60))
        let startOfDay = calendar.startOfDay(for: self)
        return calendar.date(byAdding: components, to: startOfDay)
    }

}

Update date randomization interval to within 30 minutes.

import Foundation

extension Date {

    /// Return a randomized `Date` in the next midnight hour. Will return nil if a `Date` can't be constructed given the calendar
    /// and component constraints, though in practice will likely always return some value.
    func randomDateShortlyAfterMidnight(calendar: Calendar = .current) -> Date? {
        let components = DateComponents(day: 1, minute: .random(in: 0..<30), second: .random(in: 0..<60))
        let startOfDay = calendar.startOfDay(for: self)
        return calendar.date(byAdding: components, to: startOfDay)
    }

}


// swift-tools-version:5.0
import PackageDescription

_ = Package(name: "GATT",
            products: [
                .library(
                    name: "GATT",
                    type: .dynamic,
                    targets: ["GATT"]
                ),
                .library(
                    name: "DarwinGATT",
                    type: .dynamic,
                    targets: ["DarwinGATT"]
                )
            ],
            dependencies: [
                .package(
                    url: "https://github.com/PureSwift/Bluetooth.git",
                    .branch("master")
                )
            ],
            targets: [
                .target(name: "GATT", dependencies: ["Bluetooth"]),
                .target(name: "DarwinGATT", dependencies: ["GATT"]),
                .testTarget(name: "GATTTests", dependencies: ["GATT"])
            ],
            swiftLanguageVersions: [.v5])

Build dynamic framework on Linux

// swift-tools-version:5.0
import PackageDescription

#if os(Linux)
let libraryType: PackageDescription.Product.Library.LibraryType = .dynamic
#else
let libraryType: PackageDescription.Product.Library.LibraryType = .static
#endif

_ = Package(name: "GATT",
            products: [
                .library(
                    name: "GATT",
                    type: libraryType,
                    targets: ["GATT"]
                ),
                .library(
                    name: "DarwinGATT",
                    type: libraryType,
                    targets: ["DarwinGATT"]
                )
            ],
            dependencies: [
                .package(
                    url: "https://github.com/PureSwift/Bluetooth.git",
                    .branch("master")
                )
            ],
            targets: [
                .target(name: "GATT", dependencies: ["Bluetooth"]),
                .target(name: "DarwinGATT", dependencies: ["GATT"]),
                .testTarget(name: "GATTTests", dependencies: ["GATT"])
            ],
            swiftLanguageVersions: [.v5])


// GLOB.SWIFT

#ifndef GLOB_SWIFT
#define GLOB_SWIFT

@pure
(string t[]) glob(string s)
"turbine" "0.0.2" "glob";

@pure
(string t) readFile(string s)
"turbine" "0.0.2" "readFile";

#endif

Fix macro name to match convention

// FILES.SWIFT

#ifndef FILES_SWIFT
#define FILES_SWIFT

@pure
(string t[]) glob(string s)
"turbine" "0.0.2" "glob";

@pure
(string t) readFile(string s)
"turbine" "0.0.2" "readFile";

#endif // FILES_SWIFT


import XCTest
@testable import AlchemyDataNewsV1Tests
@testable import ConversationV1Tests
@testable import DiscoveryV1Tests
@testable import DocumentConversionV1Tests
@testable import LanguageTranslatorV2Tests
@testable import NaturalLanguageClassifierV1Tests
@testable import PersonalityInsightsV3Tests
@testable import RelationshipExtractionV1BetaTests
@testable import RetrieveAndRankV1Tests
@testable import ToneAnalyzerV3Tests
@testable import TradeoffAnalyticsV1Tests
@testable import VisualRecognitionV3Tests

XCTMain([
    testCase(AlchemyDataNewsTests.allTests),
    testCase(ConversationTests.allTests),
    testCase(DiscoveryTests.allTests),
    testCase(DocumentConversionTests.allTests),
    testCase(LanguageTranslatorTests.allTests),
    testCase(NaturalLanguageClassifierTests.allTests),
    testCase(PersonalityInsightsTests.allTests),
    testCase(RelationshipExtractionTests.allTests),
    testCase(RetrieveAndRankTests.allTests),
    testCase(ToneAnalyzerTests.allTests),
    testCase(TradeoffAnalyticsTests.allTests),
    testCase(VisualRecognitionTests.allTests),
])

Add comments for disabled tests

import XCTest

@testable import AlchemyDataNewsV1Tests
@testable import ConversationV1Tests
@testable import DiscoveryV1Tests
@testable import DocumentConversionV1Tests
@testable import LanguageTranslatorV2Tests
@testable import NaturalLanguageClassifierV1Tests
@testable import PersonalityInsightsV3Tests
@testable import RelationshipExtractionV1BetaTests
@testable import RetrieveAndRankV1Tests
@testable import ToneAnalyzerV3Tests
@testable import TradeoffAnalyticsV1Tests
@testable import VisualRecognitionV3Tests

// the following tests are currently disabled becuase
// their dependencies do not build with Swift Package Manager
// @testable import TextToSpeechV1Tests
// @testable import SpeechToTextV1Tests

// the following tests are currently disabled because
// the services are deprecated and will be removed soon
// @testable import AlchemyLanguageV1Tests
// @testable import AlchemyVisionV1Tests
// @testable import DialogV1Tests
// @testable import PersonalityInsightsV2Tests

XCTMain([
    testCase(AlchemyDataNewsTests.allTests),
    testCase(ConversationTests.allTests),
    testCase(DiscoveryTests.allTests),
    testCase(DocumentConversionTests.allTests),
    testCase(LanguageTranslatorTests.allTests),
    testCase(NaturalLanguageClassifierTests.allTests),
    testCase(PersonalityInsightsTests.allTests),
    testCase(RelationshipExtractionTests.allTests),
    testCase(RetrieveAndRankTests.allTests),
    testCase(ToneAnalyzerTests.allTests),
    testCase(TradeoffAnalyticsTests.allTests),
    testCase(VisualRecognitionTests.allTests),

    // the following tests are currently disabled because their
    // dependencies do not build with Swift Package Manager
    // testCase(TextToSpeechTests.allTests)
    // testCase(SpeechToTextTests.allTests)

    // the following tests are currently disabled because
    // the services are deprecated and will be removed soon
    // testCase(AlchemyLanguageTests.allTests),
    // testCase(AlchemyVisionTests.allTests),
    // testCase(DialogV1Tests.allTests),
    // testCase(PersonalityInsightsTests.allTests)
])


// Checks that SourceKit does not crash for enum patterns in generics.
// RUN: %sourcekitd-test -req cursor -pos 17:15 %s -- %s | FileCheck %s
// CHECK: source.lang.swift.ref.enumelement (11:10-11:17)

public protocol MyErrorType {
}

enum MyErrorEnum: MyErrorType {
}

public enum ResultTest<Value, Error: MyErrorType> {
    case Success(Value)
    case Failure(Error)

    /// Returns `true` if the result is a success, `false` otherwise.
    public var isSuccess: Bool {
        switch self {
        case .Success:
            return true
        case .Failure:
            return false
        }
    }
}

Add of comment affected line offsets of test

// Checks that SourceKit does not crash for enum patterns in generics.
// RUN: %sourcekitd-test -req cursor -pos 18:15 %s -- %s | FileCheck %s
// CHECK: source.lang.swift.ref.enumelement (12:10-12:17)

public protocol MyErrorType {
}

enum MyErrorEnum: MyErrorType {
}

public enum ResultTest<Value, Error: MyErrorType> {
    case Success(Value)
    case Failure(Error)

    /// Returns `true` if the result is a success, `false` otherwise.
    public var isSuccess: Bool {
        switch self {
        case .Success:
            return true
        case .Failure:
            return false
        }
    }
}


// swift-tools-version:5.1
import PackageDescription

let package = Package(
    name: "XCDYouTubeKit",
    platforms: [
        .iOS(.v8),
        .tvOS(.v9),
        .macOS(.v10_10)
    ],
    products: [
        .library(name: "XCDYouTubeKit" , targets: ["XCDYouTubeKit"])
    ],
    targets: [
        .target(
            name: "XCDYouTubeKit",
            path: ".",
            sources: ["XCDYouTubeKit"],
            publicHeadersPath: "XCDYouTubeKit"
        )
    ]
)

Exclude plist files from SPM

// swift-tools-version:5.1
import PackageDescription

let package = Package(
    name: "XCDYouTubeKit",
    platforms: [
        .iOS(.v8),
        .tvOS(.v9),
        .macOS(.v10_10)
    ],
    products: [
        .library(name: "XCDYouTubeKit" , targets: ["XCDYouTubeKit"])
    ],
    targets: [
        .target(
            name: "XCDYouTubeKit",
            path: ".",
            exclude: [
                "XCDYouTubeKit/Info.plist",
                "XCDYouTubeKit/Configuration.plist",
                "XCDYouTubeKit/AppledocSettings.plist"
            ],
            sources: ["XCDYouTubeKit"],
            publicHeadersPath: "XCDYouTubeKit"
        )
    ]
)


//
//  main.swift
//  SDSRunner
//
//  Created by Tim Ekl on 6/2/14.
//  Copyright (c) 2014 Tim Ekl. All rights reserved.
//

import Foundation

var od = OrderedDictionary<String,Int>()
od["Tim"] = 23
od[0] = 24
println(od.description)

Add a second value to the OrderedDictionary

//
//  main.swift
//  SDSRunner
//
//  Created by Tim Ekl on 6/2/14.
//  Copyright (c) 2014 Tim Ekl. All rights reserved.
//

import Foundation

var od = OrderedDictionary<String,Int>()
od["Tim"] = 23
od[0] = 24
od["Catherine"] = 23
println(od.description)


public protocol Stream {
    func read(maxBytes: Int) throws -> [UInt8]
    func write(bytes: [UInt8]) throws -> Int
    func close() throws
}

public extension Stream {
    func readInt8() throws -> Int8 {
        return Int8(try read(1)[0])
    }

    func write(int8: Int8) throws {
        try write([UInt8(int8)])
    }

    func readUInt8() throws -> UInt8 {
        return try read(1)[0]
    }

    func write(uint8: UInt8) throws {
        try write([uint8])
    }

    func readString() throws -> String {
        var str = ""

        while true {
            let byte = try read(1)[0]

            if byte == 0x0 {
                return str
            } else {
                str.appendContentsOf(String(UnicodeScalar(byte)))
            }
        }
    }

    func writeString(string: String) throws {
        try write([UInt8](string.utf8))
    }
}

Change write parameter name and change writeString to write

public enum StreamError: ErrorType {
    case ReadFailed(Int)
    case WriteFailed(Int)
    case CloseFailed(Int)
    case Closed
}

public protocol Stream {
    func read(count: Int) throws -> [UInt8]
    func write(bytes: [UInt8]) throws -> Int
    func close() throws
}

public extension Stream {
    func readInt8() throws -> Int8 {
        return Int8(try read(1)[0])
    }

    func write(int8: Int8) throws {
        try write([UInt8(int8)])
    }

    func readUInt8() throws -> UInt8 {
        return try read(1)[0]
    }

    func write(uint8: UInt8) throws {
        try write([uint8])
    }

    func readString() throws -> String {
        var str = ""

        while true {
            let byte = try read(1)[0]

            if byte == 0x0 {
                return str
            } else {
                str.appendContentsOf(String(UnicodeScalar(byte)))
            }
        }
    }

    func write(string: String) throws {
        try write([UInt8](string.utf8))
    }
}


// RUN: %target-swift-frontend -parse -primary-file %S/../Inputs/empty.swift %s -verify

struct A: Collection {
  struct Index: BidirectionalIndex {}
}

extension A.Index {
  // Force validate "A".
}

Update test to refer to Comparable rather than BidirectionalIndex.

// RUN: %target-swift-frontend -parse -primary-file %S/../Inputs/empty.swift %s -verify

struct A: Collection {
  struct Index: Comparable {}
}

extension A.Index {
  // Force validate "A".
}


//
//  Analytics.swift
//  Paste
//
//  Created by Dasmer Singh on 12/21/15.
//  Copyright © 2015 Dastronics Inc. All rights reserved.
//

import Foundation
import Mixpanel

struct Analytics {
   static let sharedInstance = Analytics()

    func start() {
        Mixpanel.sharedInstanceWithToken("547e5d6894da24ac5876599ffa3ebb12")
    }

    func track(eventName: String, properties: [String: String]) {
        Mixpanel.sharedInstance().track(eventName, properties: properties)
        #if DEBUG
            print("✒ Event Tracked == Name:\(eventName) Properties:\(properties))")
        #endif
    }
}

Update analytics print for DEBUG

//
//  Analytics.swift
//  Paste
//
//  Created by Dasmer Singh on 12/21/15.
//  Copyright © 2015 Dastronics Inc. All rights reserved.
//

import Foundation
import Mixpanel

struct Analytics {
   static let sharedInstance = Analytics()

    func start() {
        Mixpanel.sharedInstanceWithToken("547e5d6894da24ac5876599ffa3ebb12")
    }

    func track(eventName: String, properties: [String: String]) {
        Mixpanel.sharedInstance().track(eventName, properties: properties)
        #if DEBUG
            print("Analytics Event Tracked ✒\nName: \(eventName)\nProperties: \(properties))\n")
        #endif
    }
}


struct CommandLine {

    var text = "Hello, World!"
}

Add implementation of command line

import Foundation

#if !os(macOS)
public typealias Process = Task
#endif

public typealias Command = String

public enum CommandLineResult {

    case output(String)
    case error(String)

}

/// Ref.: https://github.com/spotify/HubFramework/blob/master/live/sources/CommandLine.swift
public struct CommandLine {

    public func execute(_ command: Command, with arguments: [String] = []) -> CommandLineResult {
        let process = Process()
        process.launchPath = command
        process.arguments = arguments

        let outputPipe = Pipe()
        let errorPipe = Pipe()
        process.standardOutput = outputPipe
        process.standardError = errorPipe
        process.launch()

        if let errorOutput = output(from: errorPipe), errorOutput.characters.count > 0 {
            return .error(errorOutput)
        } else {
            return .output(output(from: outputPipe) ?? "")
        }
    }

    private func output(from pipe: Pipe) -> String? {
        let outputData = pipe.fileHandleForReading.readDataToEndOfFile()
        return String(data: outputData, encoding: .utf8)
    }

}


//
//  main.swift
//  partial-md5s
//
//  Created by Jeff Kelley on 5/19/17.
//  Copyright © 2017 Jeff Kelley. All rights reserved.
//

import Foundation
import os

guard let arguments = CommandLine.parseArguments() else {
    Arguments.printUsage()
    exit(EXIT_FAILURE)
}

let inputURL = URL(fileURLWithPath: arguments.inputPath)

if #available(OSX 10.12, *) {
    os_log("Opening file at path %@",
           log: .default,
           type: .info,
           arguments.inputPath)
}

do {
    let data = try Data.init(contentsOf: inputURL, options: .alwaysMapped)

    if #available(OSX 10.12, *) {
        os_log("Using chunk size of %{bytes}d",
               log: .default,
               type: .info,
               arguments.chunkSize)
    }

    data.withChunks(ofSize: arguments.chunkSize) { subdata in
        print(subdata.md5)
    }
}
catch {
    if #available(OSX 10.12, *) {
        os_log("Error opening file at %@: %@",
               log: .default,
               type: .error,
               arguments.inputPath, error.localizedDescription)
    }

    exit(EXIT_FAILURE)
}

Use “macOS” instead of “OSX.”

//
//  main.swift
//  partial-md5s
//
//  Created by Jeff Kelley on 5/19/17.
//  Copyright © 2017 Jeff Kelley. All rights reserved.
//

import Foundation
import os

guard let arguments = CommandLine.parseArguments() else {
    Arguments.printUsage()
    exit(EXIT_FAILURE)
}

let inputURL = URL(fileURLWithPath: arguments.inputPath)

if #available(macOS 10.12, *) {
    os_log("Opening file at path %@",
           log: .default,
           type: .info,
           arguments.inputPath)
}

do {
    let data = try Data.init(contentsOf: inputURL, options: .alwaysMapped)

    if #available(macOS 10.12, *) {
        os_log("Using chunk size of %{bytes}d",
               log: .default,
               type: .info,
               arguments.chunkSize)
    }

    data.withChunks(ofSize: arguments.chunkSize) { subdata in
        print(subdata.md5)
    }
}
catch {
    if #available(macOS 10.12, *) {
        os_log("Error opening file at %@: %@",
               log: .default,
               type: .error,
               arguments.inputPath, error.localizedDescription)
    }

    exit(EXIT_FAILURE)
}


internal class QuickSelectedTestSuiteBuilder: QuickTestSuiteBuilder {

    let testCaseClass: AnyClass!

    var namespacedClassName: String {
        return NSStringFromClass(testCaseClass)
    }

    init?(forTestCaseWithName name: String) {
        guard let testCaseClass = testCaseClassForTestCaseWithName(name) else {
            self.testCaseClass = nil
            return nil
        }

        self.testCaseClass = testCaseClass
    }

    func buildTestSuite() -> QuickTestSuite {
        return QuickTestSuite(forTestCaseClass: testCaseClass)
    }

}

private func testCaseClassForTestCaseWithName(name: String) -> AnyClass? {
    func extractClassName(name: String) -> String? {
        return name.characters.split("/").first.map(String.init)
    }

    guard let className = extractClassName(name) else { return nil }
    guard let bundle = NSBundle.currentTestBundle else { return nil }

    if let testCaseClass = bundle.classNamed(className) {
        return testCaseClass
    }

    guard let moduleName = bundle.bundlePath.fileName else { return nil }

    return NSClassFromString("\(moduleName).\(className)")
}

Put any early returns on a single line to for balance & scannability


import MapKit

final class VHomeReadyMapTiler:MKTileOverlay
{
    init(plan:MHomePlan)
    {
        debugPrint("---- template \(plan.tileTemplate)")

        super.init(urlTemplate:plan.tileTemplate)
        canReplaceMapContent = true
    }

    override func loadTile(
        at path:MKTileOverlayPath,
        result:@escaping (Data?, Error?) -> Void)
    {
        debugPrint("path: \(path)")

        super.loadTile(at:path, result:result)
    }
}

Use min and max ranges

import MapKit

final class VHomeReadyMapTiler:MKTileOverlay
{
    init(plan:MHomePlan)
    {
        debugPrint("---- template \(plan.tileTemplate)")

        super.init(urlTemplate:plan.tileTemplate)
        canReplaceMapContent = true
        minimumZ = 16
        maximumZ = 16
    }

    override func loadTile(
        at path:MKTileOverlayPath,
        result:@escaping (Data?, Error?) -> Void)
    {
        debugPrint("path: \(path)")

        let newPath:MKTileOverlayPath = MKTileOverlayPath(
            x:path.x,
            y:path.y,
            z:16,
            contentScaleFactor:path.contentScaleFactor)
        super.loadTile(at:newPath, result:result)
    }
}


//
//  UIWindow+RootViewController.swift
//  Swiftilities
//
//  Created by Nicholas Bonatsakis on 2/5/16.
//  Copyright © 2016 Raizlabs. All rights reserved.
//

import UIKit

/**
 *  UIWindow extension for setting the rootViewController on a UIWindow instance in a safe and animatable way.
 */
public extension UIWindow {

    /**
     Set the rootViewController on this UIWindow instance.

     - parameter viewController: The view controller to set
     - parameter animated:       Whether or not to animate the transition, animation is a cross-fade
     - parameter completion:     Completion block to be invoked after the transition finishes
     */
    @nonobjc
    func setRootViewController(_ viewController: UIViewController, animated: Bool, duration: TimeInterval = 0.3, options: UIView.AnimationOptions = [.transitionCrossDissolve], completion: ((Bool) -> Void)? = nil) {
        if animated {
            UIView.transition(with: self, duration: duration, options: options, animations: {
                self.rootViewController = viewController
            }, completion: completion)
        } else {
            self.rootViewController = viewController
        }
    }
}

Drop brackets since AnimationOptions is OptionSet

//
//  UIWindow+RootViewController.swift
//  Swiftilities
//
//  Created by Nicholas Bonatsakis on 2/5/16.
//  Copyright © 2016 Raizlabs. All rights reserved.
//

import UIKit

/**
 *  UIWindow extension for setting the rootViewController on a UIWindow instance in a safe and animatable way.
 */
public extension UIWindow {

    /**
     Set the rootViewController on this UIWindow instance.

     - parameter viewController: The view controller to set
     - parameter animated:       Whether or not to animate the transition, animation is a cross-fade
     - parameter completion:     Completion block to be invoked after the transition finishes
     */
    @nonobjc
    func setRootViewController(_ viewController: UIViewController, animated: Bool, duration: TimeInterval = 0.3, options: UIView.AnimationOptions = .transitionCrossDissolve, completion: ((Bool) -> Void)? = nil) {
        if animated {
            UIView.transition(with: self, duration: duration, options: options, animations: {
                self.rootViewController = viewController
            }, completion: completion)
        } else {
            self.rootViewController = viewController
        }
    }
}


import XCTest
import WebKit
import Neeman

/**
 This is used to provide a default implimentation so that the unit tests are less verbose.
 */
open class TestNeemanNavigationDelegate: NSObject, NeemanNavigationDelegate {
    var expectation: XCTestExpectation?

    override init() {
        super.init()
    }

    init(expectation: XCTestExpectation) {
        self.expectation = expectation
    }

    open func webView(_ webView: WKWebView, didReceiveServerRedirectToURL: URL?) {}
    open func webView(_ webView: WKWebView, didFinishNavigationWithURL: URL?) {}
    open func webView(_ webView: WKWebView, didFinishLoadingWithError error: NSError) {}
    open func shouldPreventNavigationAction(_ navigationAction: WKNavigationAction) -> Bool {
        return false
    }
    open func shouldForcePushOfNavigationAction(_ navigationAction: WKNavigationAction) -> Bool {
        return false
    }
    open func shouldPreventPushOfNavigationAction(_ navigationAction: WKNavigationAction) -> Bool {
        return false
    }
    open func pushNewWebViewControllerWithURL(_ url: URL) {}
}

Add the new delegate method to the test delegate.

import XCTest
import WebKit
import Neeman

/**
 This is used to provide a default implimentation so that the unit tests are less verbose.
 */
open class TestNeemanNavigationDelegate: NSObject, NeemanNavigationDelegate {
    var expectation: XCTestExpectation?

    override init() {
        super.init()
    }

    init(expectation: XCTestExpectation) {
        self.expectation = expectation
    }

    open func webView(_ webView: WKWebView, didReceiveServerRedirectToURL: URL?) {}
    open func webView(_ webView: WKWebView, didFinishNavigationWithURL: URL?) {}
    open func webView(_ webView: WKWebView, didFinishLoadingWithError error: NSError) {}
    open func webView(_ webView: WKWebView, didBeginLoadingURL URL: URL?) {}
    open func shouldPreventNavigationAction(_ navigationAction: WKNavigationAction) -> Bool {
        return false
    }
    open func shouldForcePushOfNavigationAction(_ navigationAction: WKNavigationAction) -> Bool {
        return false
    }
    open func shouldPreventPushOfNavigationAction(_ navigationAction: WKNavigationAction) -> Bool {
        return false
    }
    open func pushNewWebViewControllerWithURL(_ url: URL) {}
}


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

extension Constructor: Relatable {
	public typealias To = T

	public func toFunctor<U>() -> Functor<Constructor, Constructor<U>> {
		return Functor(self, Constructor.map)
	}
}

public struct Term: FixpointType {
	public init(_ out: Constructor<Term>) {
		self.out = out
	}

	public static func out(term: Term) -> Constructor<Term> {
		return term.out
	}

	public let out: Constructor<Term>
}

public struct Functor<F: Relatable, G: Relatable>: Relatable {
	public init(_ out: F, _ map: F -> (F.To -> G.To) -> G) {
		self.out = out
		self.map = map
	}

	public func map(transform: F.To -> G.To) -> G {
		return map(out)(transform)
	}

	private let out: F
	private let map: F -> (F.To -> G.To) -> G

	// MARK: Relatable

	public typealias To = F.To
}

public protocol Relatable {
	typealias To
}

public protocol FixpointType {
	typealias F
	init(F)
	static func out(Self) -> F
}

public func cata<T, Fix: FixpointType, F: Relatable, G: Relatable where Fix.F == Functor<F, G>, F.To == Fix, G.To == T>(f: G -> T)(_ term: Fix) -> T {
	return f(Fix.out(term).map(cata(f)))
}

public func cata<T, Fix: FixpointType where Fix.F == Constructor<Fix>>(f: Constructor<T> -> T)(_ term: Fix) -> T {
	return term |> (Fix.out >>> (flip(uncurry(Constructor.map)) <| cata(f)) >>> f)
}

// MARK: - Imports

import Prelude

Revert "Attempt to implement Functor and an abstract catamorphism."

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

public struct Term: FixpointType {
	public init(_ out: Constructor<Term>) {
		self.out = out
	}

	public static func out(term: Term) -> Constructor<Term> {
		return term.out
	}

	public let out: Constructor<Term>
}

public protocol FixpointType {
	typealias F
	init(F)
	static func out(Self) -> F
}

public func cata<T, Fix: FixpointType where Fix.F == Constructor<Fix>>(f: Constructor<T> -> T)(_ term: Fix) -> T {
	return term |> (Fix.out >>> (flip(uncurry(Constructor.map)) <| cata(f)) >>> f)
}

// MARK: - Imports

import Prelude


// Statically link a "hello world" program
// REQUIRES: OS=linux-gnu
// REQUIRES: static_stdlib
print("hello world!")
// RUN: %empty-directory(%t)
// RUN: %target-swiftc_driver -driver-print-jobs -static-stdlib -o %t/static-stdlib %s -Xlinker --no-allow-multiple-definition 2>&1| %FileCheck %s
// CHECK: {{.*}}/swift-autolink-extract{{.*}}
// CHECK: {{.*}}swiftrt.o /{{.*}}/linker-args-order-linux-{{[a-z0-9]+}}.o @/{{.*}}/linker-args-order-linux-{{[a-z0-9]+}}.autolink {{.*}} @{{.*}}/static-stdlib-args.lnk {{.*}} -Xlinker --no-allow-multiple-definition

Add back frontend command check

// Statically link a "hello world" program
// REQUIRES: OS=linux-gnu
// REQUIRES: static_stdlib
print("hello world!")
// RUN: %empty-directory(%t)
// RUN: %target-swiftc_driver -driver-print-jobs -static-stdlib -o %t/static-stdlib %s -Xlinker --no-allow-multiple-definition 2>&1| %FileCheck %s
// CHECK: {{.*}}/swift -frontend -c -primary-file {{.*}}/linker-args-order-linux.swift
// CHECK: {{.*}}/swift-autolink-extract{{.*}}
// CHECK: {{.*}}swiftrt.o /{{.*}}/linker-args-order-linux-{{[a-z0-9]+}}.o @/{{.*}}/linker-args-order-linux-{{[a-z0-9]+}}.autolink {{.*}} @{{.*}}/static-stdlib-args.lnk {{.*}} -Xlinker --no-allow-multiple-definition


//
//  CandidateLabelsInteractor.swift
//  QuickJump
//
//  Created by Victor Shamanov on 30.05.16.
//  Copyright © 2016 Victor Shamanov. All rights reserved.
//

struct CandidateLabelsInteractor {

    private let candidateFactory: CandidateFactory

    var candidateInfos: [CandidateInfo] = []

    init(alphabet: [Character]) {
        candidateFactory = .init(alphabet: alphabet)
    }

    mutating func initialize(locations: [CandidateInfo.Location]) {
        let candidates = candidateFactory.candidates(locations.count)
        candidateInfos = zip(candidates, locations).map { .init(candidate: $0, location: $1) }
    }

    mutating func next(char: Character) -> CandidateInfo? {
        var matched = candidateInfos.filter { $0.candidate.char == char }

        for i in matched.indices {
            if let next = matched[i].candidate.next() {
                matched[i].candidate = next
            } else {
                return matched[i]
            }
        }

        // User input char which is not equal to any of candidates
        guard !matched.isEmpty else { return nil }

        candidateInfos = matched

        return nil
    }

    mutating func cancel() {
        candidateInfos = []
    }
}

Disable changing candidateInfos from the outside

//
//  CandidateLabelsInteractor.swift
//  QuickJump
//
//  Created by Victor Shamanov on 30.05.16.
//  Copyright © 2016 Victor Shamanov. All rights reserved.
//

struct CandidateLabelsInteractor {

    private let candidateFactory: CandidateFactory

    private(set) var candidateInfos: [CandidateInfo] = []

    init(alphabet: [Character]) {
        candidateFactory = .init(alphabet: alphabet)
    }

    mutating func initialize(locations: [CandidateInfo.Location]) {
        let candidates = candidateFactory.candidates(locations.count)
        candidateInfos = zip(candidates, locations).map { .init(candidate: $0, location: $1) }
    }

    mutating func next(char: Character) -> CandidateInfo? {
        var matched = candidateInfos.filter { $0.candidate.char == char }

        for i in matched.indices {
            if let next = matched[i].candidate.next() {
                matched[i].candidate = next
            } else {
                return matched[i]
            }
        }

        // User input char which is not equal to any of candidates
        guard !matched.isEmpty else { return nil }

        candidateInfos = matched

        return nil
    }

    mutating func cancel() {
        candidateInfos = []
    }
}