//
//  UIButton+BlockTarget.swift
//  SwiftPlusPlus
//
//  Created by Andrew J Wagner on 10/19/16.
//  Copyright © 2016 Drewag LLC. All rights reserved.
//

#if os(iOS)
import UIKit
import ObjectiveC

private var ActionBlockKey: UInt8 = 0

private class ActionBlockWrapper: NSObject {
    let block: () -> ()

    init(block: @escaping () -> ()) {
        self.block = block
    }
}

extension UIButton {
    public func addBlock(forControlEvents events: UIControlEvents = .touchUpInside, block: @escaping () -> ()) {
        objc_setAssociatedObject(self, &ActionBlockKey, ActionBlockWrapper(block: block), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        self.addTarget(self, action: #selector(handleBlockCall), for: events)
    }

    public func handleBlockCall() {
        let wrapper =  objc_getAssociatedObject(self, &ActionBlockKey) as! ActionBlockWrapper
        wrapper.block()
    }
}
#endif

Fix language around setting block target on button

//
//  UIButton+BlockTarget.swift
//  SwiftPlusPlus
//
//  Created by Andrew J Wagner on 10/19/16.
//  Copyright © 2016 Drewag LLC. All rights reserved.
//

#if os(iOS)
import UIKit
import ObjectiveC

private var ActionBlockKey: UInt8 = 0

private class ActionBlockWrapper: NSObject {
    let block: () -> ()

    init(block: @escaping () -> ()) {
        self.block = block
    }
}

extension UIButton {
    public func setBlock(forControlEvents events: UIControlEvents = .touchUpInside, block: @escaping () -> ()) {
        objc_setAssociatedObject(self, &ActionBlockKey, ActionBlockWrapper(block: block), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        self.addTarget(self, action: #selector(handleBlockCall), for: events)
    }

    public func removeBlock(forControlEvents events: UIControlEvents = .touchUpInside) {
        if let target = objc_getAssociatedObject(self, &ActionBlockKey) as? ActionBlockWrapper {
            self.removeTarget(target, action: nil, for: events)
        }
        objc_setAssociatedObject(self, &ActionBlockKey, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }

    public func handleBlockCall() {
        let wrapper =  objc_getAssociatedObject(self, &ActionBlockKey) as! ActionBlockWrapper
        wrapper.block()
    }
}
#endif


import CoreGraphics

extension CGAffineTransform {
    public func nearlyEqual(to transform: CGAffineTransform, epsilon: CGFloat) -> Bool {
        return fabs(a - transform.a) < epsilon && fabs(b - transform.b) < epsilon && fabs(c - transform.c) < epsilon && fabs(d - transform.d) < epsilon && fabs(tx - transform.tx) < epsilon && fabs(ty - transform.ty) < epsilon
    }

    public var inverse: CGAffineTransform {
        return self.inverted()
    }

    public func isIdentity() -> Bool {
        return self.isIdentity
    }
}

extension CGAffineTransform: CustomStringConvertible {
    public var description: String {
        return "(\(a), \(b), \(c), \(d), \(tx), \(ty))"
    }
}

public func * (left: CGAffineTransform, right: CGAffineTransform) -> CGAffineTransform {
    return left.concatenating(right)
}

public func * (left: CGAffineTransform, right: CGPoint) -> CGPoint {
    return right.applying(left)
}

public func * (left: CGPoint, right: CGAffineTransform) -> CGPoint {
    return left.applying(right)
}

public func *= (left: inout CGAffineTransform, right: CGAffineTransform) {
    left = left * right
}

Remove unnecessary extension method `isIdentity`

import CoreGraphics

extension CGAffineTransform {
    public func nearlyEqual(to transform: CGAffineTransform, epsilon: CGFloat) -> Bool {
        return fabs(a - transform.a) < epsilon && fabs(b - transform.b) < epsilon && fabs(c - transform.c) < epsilon && fabs(d - transform.d) < epsilon && fabs(tx - transform.tx) < epsilon && fabs(ty - transform.ty) < epsilon
    }

    public var inverse: CGAffineTransform {
        return self.inverted()
    }
}

extension CGAffineTransform: CustomStringConvertible {
    public var description: String {
        return "(\(a), \(b), \(c), \(d), \(tx), \(ty))"
    }
}

public func * (left: CGAffineTransform, right: CGAffineTransform) -> CGAffineTransform {
    return left.concatenating(right)
}

public func * (left: CGAffineTransform, right: CGPoint) -> CGPoint {
    return right.applying(left)
}

public func * (left: CGPoint, right: CGAffineTransform) -> CGPoint {
    return left.applying(right)
}

public func *= (left: inout CGAffineTransform, right: CGAffineTransform) {
    left = left * right
}


type soa {
    int A[];
    int B[];
}

(int r) q () {
    r = 0;
}

() f (soa a) {
    trace(a.A[0], a.B[0]);
}

() g (int A[], int B[]) {
    trace(A[0], B[0]);
}

main {
    soa a;
    a.A[0] = 1;
    a.B[0] = 2;

    // check that array closing works ok with conditionals
    if (q()) {
        a.A[1] = 2;
    }  else {
        a.B[1] = 2;
    }

    f(a);
    g(a.A, a.B);
}

Mark test 383 with known problem

// SKIP-O0-TEST
// We fail to correctly refcount a.B and a.B
// See issue #685

type soa {
    int A[];
    int B[];
}

(int r) q () {
    r = 0;
}

() f (soa a) {
    trace(a.A[0], a.B[0]);
}

() g (int A[], int B[]) {
    trace(A[0], B[0]);
}

main {
    soa a;
    a.A[0] = 1;
    a.B[0] = 2;

    // check that array closing works ok with conditionals
    if (q()) {
        a.A[1] = 2;
    }  else {
        a.B[1] = 2;
    }

    f(a);
    g(a.A, a.B);
}


// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module-path %t/Globals.swiftmodule %S/Globals.swift
// RUN: %swiftc_driver -g -debug-prefix-map %/S=/var/empty -debug-prefix-map %t=/var/empty %/s -I %t -emit-ir -o - | %FileCheck %s

import Globals

func square(_ n: Int) -> Int {
  return n * n
}

// CHECK: !DIFile(filename: "/var/empty/debug_prefix_map.swift"
// CHECK: !DIModule(scope: null, name: "Globals", includePath: "/var/empty/Globals.swiftmodule"

Swap to use %target-swiftc_driver for test

// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module-path %t/Globals.swiftmodule %S/Globals.swift
// RUN: %target-swiftc_driver -g -debug-prefix-map %/S=/var/empty -debug-prefix-map %t=/var/empty %/s -I %t -emit-ir -o - | %FileCheck %s

import Globals

func square(_ n: Int) -> Int {
  return n * n
}

// CHECK: !DIFile(filename: "/var/empty/debug_prefix_map.swift"
// CHECK: !DIModule(scope: null, name: "Globals", includePath: "/var/empty/Globals.swiftmodule"


//
//  ZipCodeRule.swift
//  Validator
//
//  Created by Jeff Potter on 3/6/15.
//  Copyright (c) 2015 jpotts18. All rights reserved.
//

import Foundation

/**
 `ZipCodeRule` is a subclass of `RegexRule` that represents how zip codes are to be validated.
 */
public class ZipCodeRule: RegexRule {
    /**
     Initializes a `ZipCodeRule` object.

     - parameter message: String that holds error message.
     - returns: An initialized object, or nil if an object could not be created for some reason that would not result in an exception.
     */
    public convenience init(message : String = "Enter a valid 5 digit zipcode"){
        self.init(regex: "\\d{5}", message : message)
    }
}

Add support for 9 digit zip codes

//
//  ZipCodeRule.swift
//  Validator
//
//  Created by Jeff Potter on 3/6/15.
//  Copyright (c) 2015 jpotts18. All rights reserved.
//

import Foundation

/**
 `ZipCodeRule` is a subclass of `RegexRule` that represents how zip codes are to be validated.
 */
public class ZipCodeRule: RegexRule {
    /**
     Initializes a `ZipCodeRule` object.

     - parameter message: String that holds error message.
     - returns: An initialized object, or nil if an object could not be created for some reason that would not result in an exception.
     */
    public convenience init(message : String = "Enter a valid 5 or 9 digit zipcode"){
        self.init(regex: "\\d{5}(-\\d{4})?", message : message)
    }
}


precedencegroup A {higherThan: AdditionPrecedence lowerThan: MultiplicationPrecedence associativity: left }
infix operator ~|*|~ : A
postfix operator ^^

func ~|*|~ (x: Int, y: Int) -> Int {
    return 2 * x + y
}

postfix func ^^ (x: Int) -> Int {
    return x - 2
}

assert(8^^ ~|*|~ 3 == 15)

Tidy up some Swift code

precedencegroup A {
  higherThan: AdditionPrecedence
  lowerThan: MultiplicationPrecedence
  associativity: left
}

infix operator ~|*|~ : A
postfix operator ^^

func ~|*|~ (x: Int, y: Int) -> Int {
    return 2 * x + y
}

postfix func ^^ (x: Int) -> Int {
    return x - 2
}

assert(8^^ ~|*|~ 3 == 15)


// RUN: %target-swift-frontend -typecheck -primary-file %/s -access-notes-path %/S/Inputs/missing.accessnotes 2>&1 | %FileCheck --check-prefix=CHECK-MISSING %s
// CHECK-MISSING: <unknown>:0: warning: ignored access notes file at 'SOURCE_DIR/test/Sema/Inputs/missing.accessnotes' because it cannot be read: No such file or directory{{$}}

// RUN: %target-typecheck-verify-swift -access-notes-path %S/Inputs/bad.accessnotes -verify-additional-file %S/Inputs/bad.accessnotes

// RUN: %target-typecheck-verify-swift -access-notes-path %S/Inputs/extra.accessnotes -verify-additional-file %S/Inputs/extra.accessnotes

// FIXME: Should diagnose multiple access notes for the same decl

// FIXME: Should diagnose access notes that don't match a decl in the source code

Handle Windows error spelling difference

// RUN: %target-swift-frontend -typecheck -primary-file %/s -access-notes-path %/S/Inputs/missing.accessnotes 2>&1 | %FileCheck --check-prefix=CHECK-MISSING %s
// CHECK-MISSING: <unknown>:0: warning: ignored access notes file at 'SOURCE_DIR/test/Sema/Inputs/missing.accessnotes' because it cannot be read: {{[Nn]}}o such file or directory{{$}}

// RUN: %target-typecheck-verify-swift -access-notes-path %S/Inputs/bad.accessnotes -verify-additional-file %S/Inputs/bad.accessnotes

// RUN: %target-typecheck-verify-swift -access-notes-path %S/Inputs/extra.accessnotes -verify-additional-file %S/Inputs/extra.accessnotes

// FIXME: Should diagnose multiple access notes for the same decl

// FIXME: Should diagnose access notes that don't match a decl in the source code


// RUN: rm -rf %t/clang-module-cache
// RUN: %swift %clang-importer-sdk -parse -module-cache-path %t/clang-module-cache %s -verify

import CoreFoundation
import Foundation

func testCFToObjC(let cfStr: CFString, cfMutableStr: CFMutableString) {
  var nsStr: NSString = cfStr
  nsStr = cfMutableStr

  var nsMutableStr: NSMutableString = cfMutableStr
  nsMutableStr = cfStr // expected-error{{'NSString' is not a subtype of 'NSMutableString'}}

  // sanity check
  nsStr = nsMutableStr
}

func testObjCToCF(let nsStr: NSString, nsMutableStr: NSMutableString) {
  var cfStr: CFString = nsStr
  cfStr = nsMutableStr

  var cfMutableStr: CFMutableString = nsMutableStr
  cfMutableStr = cfStr // expected-error{{'CFString' is not convertible to 'CFMutableString'}}

  // sanity check
  cfStr = cfMutableStr
}

Test CFString <-> String implicit conversions.

// RUN: rm -rf %t/clang-module-cache
// RUN: %swift %clang-importer-sdk -parse -module-cache-path %t/clang-module-cache %s -verify

import CoreFoundation
import Foundation

func testCFToObjC(let cfStr: CFString, cfMutableStr: CFMutableString) {
  var nsStr: NSString = cfStr
  nsStr = cfMutableStr

  var nsMutableStr: NSMutableString = cfMutableStr
  nsMutableStr = cfStr // expected-error{{'NSString' is not a subtype of 'NSMutableString'}}

  // sanity check
  nsStr = nsMutableStr
}

func testObjCToCF(let nsStr: NSString, nsMutableStr: NSMutableString) {
  var cfStr: CFString = nsStr
  cfStr = nsMutableStr

  var cfMutableStr: CFMutableString = nsMutableStr
  cfMutableStr = cfStr // expected-error{{'CFString' is not convertible to 'CFMutableString'}}

  // sanity check
  cfStr = cfMutableStr
}

func testCFToNative(cfStr: CFString, cfMutableStr: CFMutableString) {
  var str: String = cfStr
  str = cfMutableStr
}

func testNativeToCF(str: String) {
  var cfStr: CFString = str
  var cfMutableStr: CFMutableString = str // expected-error{{'NSString' is not a subtype of 'NSMutableString'}}
}


import Foundation
import CommonCrypto

extension HMACAlgorithm: SignAlgorithm, VerifyAlgorithm {
  public func sign(_ message: Data) -> Data {
    let context = UnsafeMutablePointer<CCHmacContext>.allocate(capacity: 1)
    defer { context.deallocate(capacity: 1) }

    key.withUnsafeBytes() { (buffer: UnsafePointer<UInt8>) in
      CCHmacInit(context, hash.commonCryptoAlgorithm, buffer, size_t(key.count))
    }

    message.withUnsafeBytes { (buffer: UnsafePointer<UInt8>) in
      CCHmacUpdate(context, buffer, size_t(message.count))
    }

    var hmac = Array<UInt8>(repeating: 0, count: Int(hash.commonCryptoDigestLength))
    CCHmacFinal(context, &hmac)

    return Data(hmac)
  }
}

extension HMACAlgorithm.Hash {
  var commonCryptoAlgorithm: CCHmacAlgorithm {
    switch self {
    case .sha256:
      return CCHmacAlgorithm(kCCHmacAlgSHA256)
    case .sha384:
      return CCHmacAlgorithm(kCCHmacAlgSHA384)
    case .sha512:
      return CCHmacAlgorithm(kCCHmacAlgSHA512)
    }
  }

  var commonCryptoDigestLength: Int32 {
    switch self {
    case .sha256:
      return CC_SHA256_DIGEST_LENGTH
    case .sha384:
      return CC_SHA384_DIGEST_LENGTH
    case .sha512:
      return CC_SHA512_DIGEST_LENGTH
    }
  }
}

Fix warning about deallocate(capacity:) deprecation

import Foundation
import CommonCrypto

extension HMACAlgorithm: SignAlgorithm, VerifyAlgorithm {
  public func sign(_ message: Data) -> Data {
    let context = UnsafeMutablePointer<CCHmacContext>.allocate(capacity: 1)
    defer { context.deallocate() }

    key.withUnsafeBytes() { (buffer: UnsafePointer<UInt8>) in
      CCHmacInit(context, hash.commonCryptoAlgorithm, buffer, size_t(key.count))
    }

    message.withUnsafeBytes { (buffer: UnsafePointer<UInt8>) in
      CCHmacUpdate(context, buffer, size_t(message.count))
    }

    var hmac = Array<UInt8>(repeating: 0, count: Int(hash.commonCryptoDigestLength))
    CCHmacFinal(context, &hmac)

    return Data(hmac)
  }
}

extension HMACAlgorithm.Hash {
  var commonCryptoAlgorithm: CCHmacAlgorithm {
    switch self {
    case .sha256:
      return CCHmacAlgorithm(kCCHmacAlgSHA256)
    case .sha384:
      return CCHmacAlgorithm(kCCHmacAlgSHA384)
    case .sha512:
      return CCHmacAlgorithm(kCCHmacAlgSHA512)
    }
  }

  var commonCryptoDigestLength: Int32 {
    switch self {
    case .sha256:
      return CC_SHA256_DIGEST_LENGTH
    case .sha384:
      return CC_SHA384_DIGEST_LENGTH
    case .sha512:
      return CC_SHA512_DIGEST_LENGTH
    }
  }
}


//
//  FunJCamUITests.swift
//  FunJCamUITests
//
//  Created by boxjeon on 2017. 1. 12..
//  Copyright © 2017년 the42apps. All rights reserved.
//

import XCTest

class FunJCamUITests: XCTestCase {

    override func setUp() {
        super.setUp()

        // Put setup code here. This method is called before the invocation of each test method in the class.

        // In UI tests it is usually best to stop immediately when a failure occurs.
        continueAfterFailure = false
        // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
        XCUIApplication().launch()

        // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
    }

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

    func testExample() {
        // Use recording to get started writing UI tests.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }

}

Add UITest for CI test.

//
//  FunJCamUITests.swift
//  FunJCamUITests
//
//  Created by boxjeon on 2017. 1. 12..
//  Copyright © 2017년 the42apps. All rights reserved.
//

import XCTest

class FunJCamUITests: XCTestCase {

    override func setUp() {
        super.setUp()

        // Put setup code here. This method is called before the invocation of each test method in the class.

        // In UI tests it is usually best to stop immediately when a failure occurs.
        continueAfterFailure = false
        // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
        XCUIApplication().launch()

        // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
    }

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

    func testSearch() {
        let app = XCUIApplication()
        let textField = app.textFields["김연아"]
        textField.tap()
        let collectionViewsQuery = app.collectionViews
        collectionViewsQuery/*@START_MENU_TOKEN@*/.buttons["GIF"]/*[[".cells.buttons[\"GIF\"]",".buttons[\"GIF\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()
        textField.tap()
        textField.tap()
        collectionViewsQuery.children(matching: .cell).element(boundBy: 3).children(matching: .other).element/*@START_MENU_TOKEN@*/.swipeRight()/*[[".swipeUp()",".swipeRight()"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/
    }
}


//
//  SECBarOptions.swift
//  SwiftyEcharts
//
//  Created by Pluto-Y on 16/01/2017.
//  Copyright © 2017 com.pluto-y. All rights reserved.
//

import SwiftyEcharts

public struct SECBarOptions {

}

Add new demo for `bar-animation-delay`

//
//  SECBarOptions.swift
//  SwiftyEcharts
//
//  Created by Pluto-Y on 16/01/2017.
//  Copyright © 2017 com.pluto-y. All rights reserved.
//

import SwiftyEcharts

public struct SECBarOptions {

    // MARK: 柱状图动画延迟
    // FIXME: (未成功)
    /// 地址: http://echarts.baidu.com/demo.html#bar-animation-delay
    static func barAnimationDelayOption() -> SECOption {
        func calculateData(index: Float, function: (Double) -> Double) -> Float {
            var tmp: Float = Float(function(Double(index) / 5.0))
            tmp *= (index / 5.0 - 1.0)
            tmp += index / 6.0
            tmp *= 5.0
            return tmp
        }
        var xAxisData: [SECJsonable] = []
        var data1: [SECJsonable] = []
        var data2: [SECJsonable] = []
        for i in 0..<100 {
            xAxisData.append("类目\(i)")
            data1.append(calculateData(Float(i), function: sin))
            data2.append(calculateData(Float(i), function: cos))
        }
        return SECOption(
            .title(SECTitle(
                .text("柱状图动画延迟")
                )),
            .legend(SECLegend(
                .data(["bar", "bar2"]),
                .align(.left)
                )),
            .toolbox(SECToolbox(
                .feature(SECTFeature(
                    .magicType(SECTFMagicType(
                        .type([.stack, .tiled])
                        )),
                    .dataView(SECTFDataView(
                        )),
                    .saveAsImage(SECTFSaveAsImage(
                        .pixelRatio(2)
                        ))
                    ))
                )),
            .tooltip(SECTooltip()),
            .xAxis([
                SECAxis(
                    .data(xAxisData),
                    .silent(false),
                    .splitLine(SECSplitLine(
                        .show(false)
                        ))
                )
                ]),
            .yAxis([
                SECAxis()
                ]),
            .series([
                SECBarSerie(
                    .name("bar"),
                    .data(data1),
                    .animationDelay(.function("function seriesDelay(idx){ return idx * 10; }"))
                ),
                SECBarSerie(
                    .name("bar2"),
                    .data(data2),
                    .animationDelay(.function("function seriesDelay2(idx){ return idx * 10 + 100; }"))
                )
                ]),
            .animationEasing(.elasticOut),
            .animationDelayUpdate(.function("function optionDelayUpdate(idx){ return idx * 5; }"))
        )
    }

}


// RUN: %target-swift-frontend %s -parse
// XFAIL: no_asserts

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/fluidsonic (Marc Knaup)

import Foundation
extension NSSet {
    convenience init<T>(array: Array<T>) {
    }
}

Annotate a crash test that does not crash now

// RUN: %target-swift-frontend %s -parse

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/fluidsonic (Marc Knaup)

import Foundation
extension NSSet {
    convenience init<T>(array: Array<T>) {
    }
}


import Darwin
import Foundation
import Yaml
import Rapier

private func main() throws -> Int32 {
    let rapier = Rapier(ymlFile: "/Users/cipi1965/Downloads/tests/telegram.yml")

    try rapier.parseYml()

    let generator = TelegramBotSDKGenerator(directory: "/Users/cipi1965/Downloads/tests/")
    try rapier.generate(generator: generator)

    return 0
}

do {
    exit(try main())
} catch {
    print(error.localizedDescription)
    exit(1)
}

Add arguments to rapier cli

import Darwin
import Foundation
import Yaml
import Rapier

private func main() throws -> Int32 {
    guard CommandLine.arguments.count == 3 else {
        print("Usage: rapier <yaml path> <output path>")
        return 1
    }
    let rapier = Rapier(ymlFile: CommandLine.arguments[1])

    try rapier.parseYml()

    let generator = TelegramBotSDKGenerator(directory: CommandLine.arguments[2])
    try rapier.generate(generator: generator)

    return 0
}

do {
    exit(try main())
} catch {
    print(error.localizedDescription)
    exit(1)
}


//
//  ViewController.swift
//  GymTimer
//
//  Created by Hisma Mulya S on 11/10/16.
//  Copyright © 2016 mamaz. All rights reserved.
//

import UIKit

class GTSetupViewController: UIViewController {

    // the compiler for swift 2.3 / 3
    // require this
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }

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

    convenience init(flowController: AnyObject, viewModel: AnyObject) {
        self.init()
        // overridden construct here
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white
        self.title = "Setup View"

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

}

Add label and stepper to setup view

//
//  ViewController.swift
//  GymTimer
//
//  Created by Hisma Mulya S on 11/10/16.
//  Copyright © 2016 mamaz. All rights reserved.
//

import UIKit
import SnapKit

class GTSetupViewController: UIViewController {

    private lazy var stepper = UIStepper()
    private lazy var startButton = UIButton()

    // the compiler for swift 2.3 / 3
    // require this
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }

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

    convenience init(flowController: AnyObject, viewModel: AnyObject) {
        self.init()
        // overridden construct here
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white
        self.title = "Setup View"
        self.setUpStepper()
        self.setUpStartButton()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

    // Views
    private func setUpStepper() {
        self.view.addSubview(stepper);
        self.stepper.snp.makeConstraints { make in
            make.width.equalTo(100)
            make.height.equalTo(30)
            make.centerY.equalTo(self.view).offset(50)
            make.centerX.equalTo(self.view)
        }
    }

    private func setUpStartButton() {
        let startText = "Start Training"
        self.startButton.setTitle(startText, for: .normal)
        self.startButton.setTitle(startText, for: .highlighted)
        self.startButton.setTitleColor(UIColor.black, for: .normal)
        self.startButton.setTitleColor(UIColor.black, for: .highlighted)
        self.view.addSubview(self.startButton);

        self.startButton.snp.makeConstraints { make in
            make.width.equalTo(150)
            make.height.equalTo(30)
            make.top.equalTo(self.stepper.snp.bottom).offset(20.0)
            make.centerX.equalTo(self.stepper)
        }
    }

}


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

import Foundation

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

    public init() {}

    public var count: Int = 0

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

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

    public mutating func removeAll() {
        self.valueStore.removeAll()
        self.lookup.removeAll()
        self.count = 0
    }
}

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

Allow creating ordered dictionary with initial values

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

import Foundation

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

    public init() {}
    public init(values: [(Key,Value)]) {
        for (key, value) in values {
            self[key] = value
        }
    }

    public var count: Int = 0

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

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

    public mutating func removeAll() {
        self.valueStore.removeAll()
        self.lookup.removeAll()
        self.count = 0
    }
}

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


//
//  SettingsTests.swift
//
//
//  Created by Vladislav Fitc on 12.03.2020.
//

import Foundation
import XCTest
@testable import AlgoliaSearchClient

class SettingsTests: XCTestCase {

  func testHome() {
    var settings = Settings()
    settings.attributesForFaceting = [.default("attr1"), .filterOnly("attr2"), .searchable("attr3")]
    settings.sortFacetsBy = .count
    settings.attributesToHighlight = ["attr2", "attr3"]
    print(settings)
  }

  func testDecoding() throws {
    let data = try Data(filename: "Settings.json")
    let decoder = JSONDecoder()
    _ = try decoder.decode(Settings.self, from: data)
  }
}

Add attributeCriteriaComputedByMinProximity check to Settings unit test

//
//  SettingsTests.swift
//
//
//  Created by Vladislav Fitc on 12.03.2020.
//

import Foundation
import XCTest
@testable import AlgoliaSearchClient

class SettingsTests: XCTestCase {

  func testHome() {
    var settings = Settings()
    settings.attributesForFaceting = [.default("attr1"), .filterOnly("attr2"), .searchable("attr3")]
    settings.sortFacetsBy = .count
    settings.attributesToHighlight = ["attr2", "attr3"]
    settings.attributeCriteriaComputedByMinProximity = false
  }

  func testDecoding() throws {
    let data = try Data(filename: "Settings.json")
    let decoder = JSONDecoder()
    let settings = try decoder.decode(Settings.self, from: data)
    XCTAssertEqual(settings.attributeCriteriaComputedByMinProximity, false)
  }
}


//
//  AppCoordinator.swift
//  Artikolo
//
//  Created by Grant Butler on 4/30/17.
//  Copyright © 2017 Grant Butler. All rights reserved.
//

import UIKit
import Dip

class AppCoordinator: Coordinator {

    override func start() {
        container.register(.singleton) { DataManager(backend: CoreDataDataManagerBackend(containerName: "Artikolo")) }

        setupForRunning()

        let articleListCoordinator = ArticleListCoordinator(navigationController: navigationController, container: container)
        addChild(articleListCoordinator)
    }

    func setupForRunning() {
        if CommandLine.arguments.contains("-ResetDatabase") {
            let dataManager = try! container.resolve() as DataManager
            try! dataManager.reset()
        }
    }

}

Rework debug command argument system to be more robust.

//
//  AppCoordinator.swift
//  Artikolo
//
//  Created by Grant Butler on 4/30/17.
//  Copyright © 2017 Grant Butler. All rights reserved.
//

import UIKit
import Dip

private enum Command {

    case basic(() -> Void)
    case input((String) -> Void)

}

class AppCoordinator: Coordinator {

    override func start() {
        container.register(.singleton) { DataManager(backend: CoreDataDataManagerBackend(containerName: "Artikolo")) }

        setupForRunning()

        let articleListCoordinator = ArticleListCoordinator(navigationController: navigationController, container: container)
        addChild(articleListCoordinator)
    }

    private var commands: [String: Command]{
        return [
            "ResetDatabase": Command.basic(self.resetDatabase),
        ]
    }

    func setupForRunning() {
        let regularExpression = try! NSRegularExpression(pattern: "-([A-Za-z]+)(=(.*))?", options: [])
        CommandLine.arguments.forEach { (argument) in
            guard let match = regularExpression.firstMatch(in: argument, options: [], range: NSMakeRange(0, argument.utf16.count)) else { return }

            let commandRange = match.rangeAt(0)
            let commandName = (argument as NSString).substring(with: commandRange)
            guard let command = commands[commandName] else { return }

            let hasInput = match.numberOfRanges > 1

            switch (command, hasInput) {
            case (let .basic(action), _): action()
            case (let .input(action), true):
                let metadataRange = match.rangeAt(2)
                let metadata = (argument as NSString).substring(with: metadataRange)
                action(metadata)

            case (.input, false): fatalError("Command wants input, but no input provided.")
            }
        }
    }

    private func resetDatabase() {
        let dataManager = try! container.resolve() as DataManager
        try! dataManager.reset()
    }

}


// swift-tools-version:5.6

import PackageDescription

let package = Package(
    name: "SwiftRandom",
    platforms: [
        .macOS(.v10_15), .iOS(.v8), .tvOS(.v13)
    ],
    products: [
        .library(
            name: "SwiftRandom",
            targets: ["SwiftRandom"]
        )
    ],
    targets: [
        .target(name: "SwiftRandom"),
        .testTarget(
            name: "SwiftRandomTests",
            dependencies: ["SwiftRandom"])
    ]
)

Raise iOS Deployment Target to iOS 10

// swift-tools-version:5.6

import PackageDescription

let package = Package(
    name: "SwiftRandom",
    platforms: [
        .macOS(.v10_15), .iOS(.v10), .tvOS(.v13)
    ],
    products: [
        .library(
            name: "SwiftRandom",
            targets: ["SwiftRandom"]
        )
    ],
    targets: [
        .target(name: "SwiftRandom"),
        .testTarget(
            name: "SwiftRandomTests",
            dependencies: ["SwiftRandom"])
    ]
)


/*
The challenge here is to implement the longestRun function so that the
longest run of the same continuous character will be selected from a String.
This excercise lends itself to TDD and we have provided a few basic tests below.
*/

import Cocoa

func longestRun(whole: String) -> [String] {
    return [whole]
}

// identity test
var zzzz = "zzzz"
assert([zzzz] == longestRun(zzzz), "\(zzzz) should be the longest run of chars")

// book
// var book = "book"
// assert("oo" == longestRun(book), "longest run in \(book) is 'oo'")

Add tests for two equally long longest runs and emojis

/*
The challenge here is to implement the longestRun function so that the
longest run of the same continuous character will be selected from a String.
This excercise lends itself to TDD and we have provided a few basic tests below.
*/

import Cocoa

func longestRun(whole: String) -> [String] {
    return [whole]
}

// identity test
var zzzz = "zzzz"
assert([zzzz] == longestRun(zzzz), "\(zzzz) should be the longest run of chars")

// book
// var book = "book"
// assert("oo" == longestRun(book), "longest run in \(book) is 'oo'")

// two equally long longest runs test
//var zzzzyyyy = "zzzzyyyy"
//assert(["zzzz", "yyyy"] == longestRun(zzzzyyyy), "\(zzzzyyyy) should be the longest run of chars")

// unicode test
//var emojis = "😝😎😎😎😛"
//assert(["😎😎😎"] == longestRun(emojis), "😎😎😎 should be the longest run of chars")


import HaCTML
import Foundation

extension LandingFeatures {
  static var gitWorkshop: LandingFeature {
    return EventFeature(
      startDate: Date.from(year: 2017, month: 10, day: 1, hour: 19, minute: 00),
      endDate: Date.from(year: 2017, month: 11, day: 1, hour: 20, minute: 30),
      eventLink: "https://www.facebook.com/events/1906244696304681",
      liveLink: nil, // TODO
      hero: ImageHero(
        background: .color("#F1283B"),
        imagePath: "/static/images/git-foreground.svg",
        alternateText: "HaC Tools for Programmers: Bash on 25 October"
      ),
      textShade: .light
    )
  }
}

Fix date of Git workshop

import HaCTML
import Foundation

extension LandingFeatures {
  static var gitWorkshop: LandingFeature {
    return EventFeature(
      startDate: Date.from(year: 2017, month: 11, day: 1, hour: 19, minute: 00),
      endDate: Date.from(year: 2017, month: 11, day: 1, hour: 20, minute: 30),
      eventLink: "https://www.facebook.com/events/1906244696304681",
      liveLink: nil, // TODO
      hero: ImageHero(
        background: .color("#F1283B"),
        imagePath: "/static/images/git-foreground.svg",
        alternateText: "HaC Tools for Programmers: Bash on 25 October"
      ),
      textShade: .light
    )
  }
}


//
//  UIViewControllerExtensionInitialization.swift
//  Visuality
//
//  Created by Igor Matyushkin on 23.10.15.
//  Copyright © 2015 Igor Matyushkin. All rights reserved.
//

import Foundation
import UIKit

public extension UIViewController {

    // MARK: Public class methods

    /**
     Creates new instance of view controller.

     - Parameters:
         - nib: Nib query.
         - bundle: Bundle query.

     - returns: View controller from specified location.
     */
    public class func from(nib: NibQuery, inBundle bundle: BundleQuery) -> Self {
        let initializer = ViewControllerInitializer(viewControllerClass: self)
        return initializer.viewController(fromNib: nib, locatedInBundle: bundle)
    }

    // MARK: Private class methods

    // MARK: Public object methods

    // MARK: Private object methods

}

Load view immediately when instantiating new view controller

//
//  UIViewControllerExtensionInitialization.swift
//  Visuality
//
//  Created by Igor Matyushkin on 23.10.15.
//  Copyright © 2015 Igor Matyushkin. All rights reserved.
//

import Foundation
import UIKit

public extension UIViewController {

    // MARK: Public class methods

    /**
     Creates new instance of view controller.

     - Parameters:
         - nib: Nib query.
         - bundle: Bundle query.
         - loadView: Defines whether view controller's view should be loaded immediately. By default, it's `false`.

     - returns: View controller from specified location.
     */
    public class func from(nib: NibQuery, inBundle bundle: BundleQuery, loadView: Bool = false) -> Self {
        let initializer = ViewControllerInitializer(viewControllerClass: self)
        return initializer.viewController(fromNib: nib, locatedInBundle: bundle, loadView: loadView)
    }

    // MARK: Private class methods

    // MARK: Public object methods

    // MARK: Private object methods

}


import Foundation;

println("Hello, World!")

// Class examples

class lowerCamelCase {
    var x: String = "hello"

    func demo()
    {
        for var x = 0; ; {
            print(x);
        };
    }
};

Test for more ';' cases

import Foundation;

println("Hello, World!")

// Class examples

class lowerCamelCase {
    var x: String = "hello";
    let b = 2;

    func demo()
    {
        for var x = 0; ; {
            print(x);
        };

        if temperatureInFahrenheit <= 32 {
            println("It's very cold. Consider wearing a scarf.");
        } else if temperatureInFahrenheit >= 86 {
            println("It's really warm. Don't forget to wear sunscreen.");
        } else {
            println("It's not that cold. Wear a t-shirt.");
        }
    };
};


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

 Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
 Licensed under Apache License v2.0 with Runtime Library Exception

 See http://swift.org/LICENSE.txt for license information
 See http://swift.org/CONTRIBUTORS.txt for Swift project authors
 */

extension Collection {
    /// Returns the only element of the collection or nil.
    public var only: Element? {
        return count == 1 ? self[startIndex] : nil
    }
}

Add dump method to Collections for debugging

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

 Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
 Licensed under Apache License v2.0 with Runtime Library Exception

 See http://swift.org/LICENSE.txt for license information
 See http://swift.org/CONTRIBUTORS.txt for Swift project authors
 */

extension Collection {
    /// Returns the only element of the collection or nil.
    public var only: Element? {
        return count == 1 ? self[startIndex] : nil
    }

    /// Prints the element of array to standard output stream.
    ///
    /// This method should be used for debugging only.
    public func dump() {
        for element in self {
            print(element)
        }
    }
}


//
//  TeamMember.swift
//  Drift
//
//  Created by Brian McDonald on 31/08/2017.
//  Copyright © 2017 Drift. All rights reserved.
//

import Foundation

class TeamMember: Mappable {
    var id: Int = 0
    var avatarURL: String!
    var bot: Bool!

    required init?(map: Map) {
        if map.JSON["avatarUrl"] as? String == "" || map.JSON["avatarUrl"] as? String == nil{
            return nil
        }

        mapping(map: map)
    }

    func mapping(map: Map) {
        id          <- map["id"]
        avatarURL   <- map["avatarUrl"]
        bot         <- map["bot"]
    }
}

Add missing import for object mapper to team members

//
//  TeamMember.swift
//  Drift
//
//  Created by Brian McDonald on 31/08/2017.
//  Copyright © 2017 Drift. All rights reserved.
//

import ObjectMapper

class TeamMember: Mappable {
    var id: Int = 0
    var avatarURL: String!
    var bot: Bool!

    required init?(map: Map) {
        if map.JSON["avatarUrl"] as? String == "" || map.JSON["avatarUrl"] as? String == nil{
            return nil
        }

        mapping(map: map)
    }

    func mapping(map: Map) {
        id          <- map["id"]
        avatarURL   <- map["avatarUrl"]
        bot         <- map["bot"]
    }
}


//
//  NSRect+PointHelpers.swift
//  LinkedIdeas
//
//  Created by Felipe Espinoza Castillo on 04/12/15.
//  Copyright © 2015 Felipe Espinoza Dev. All rights reserved.
//

import Cocoa

extension NSRect {
  init(p1: NSPoint, p2: NSPoint) {
    origin = NSMakePoint(min(p1.x, p2.x), min(p1.y, p2.y))
    size = NSSize(width:  abs(p2.x - p1.x), height: abs(p2.y - p1.y))
  }

  var bottomLeftPoint: NSPoint { return origin }
  var bottomRightPoint: NSPoint { return NSMakePoint(origin.x + size.width, origin.y) }
  var topRightPoint: NSPoint { return NSMakePoint(origin.x + size.width, origin.y + size.height) }
  var topLeftPoint: NSPoint { return NSMakePoint(origin.x, origin.y + size.height) }
  var center: NSPoint { return NSMakePoint(origin.x + size.width / 2, origin.y + size.height / 2) }

  var maxX: CGFloat { return origin.x + size.width }
  var maxY: CGFloat { return origin.x + size.width }
}

Add initializer to NSRect by center point and size

//
//  NSRect+PointHelpers.swift
//  LinkedIdeas
//
//  Created by Felipe Espinoza Castillo on 04/12/15.
//  Copyright © 2015 Felipe Espinoza Dev. All rights reserved.
//

import Cocoa

extension NSRect {
  init(p1: NSPoint, p2: NSPoint) {
    origin = NSMakePoint(min(p1.x, p2.x), min(p1.y, p2.y))
    size = NSSize(width:  abs(p2.x - p1.x), height: abs(p2.y - p1.y))
  }

  init(center: NSPoint, size: NSSize) {
    origin = NSMakePoint(center.x - size.width / 2, center.y - size.height / 2)
    self.size = size
  }

  var bottomLeftPoint: NSPoint { return origin }
  var bottomRightPoint: NSPoint { return NSMakePoint(origin.x + size.width, origin.y) }
  var topRightPoint: NSPoint { return NSMakePoint(origin.x + size.width, origin.y + size.height) }
  var topLeftPoint: NSPoint { return NSMakePoint(origin.x, origin.y + size.height) }
  var center: NSPoint { return NSMakePoint(origin.x + size.width / 2, origin.y + size.height / 2) }

  var maxX: CGFloat { return origin.x + size.width }
  var maxY: CGFloat { return origin.x + size.width }
}


//
//  Kernel.swift
//  Warp
//
//  Created by Richard Wei on 11/2/16.
//
//

import CUDADriver

/// Kernel operators

public extension KernelArgument {

    public static func array<T>(_ array: inout DeviceArray<T>) -> KernelArgument {
        return array.withUnsafeMutableDevicePointer { ptr in
            KernelArgument(unsafeAddress: ptr.deviceAddress)
        }
    }

    public static func reference<T>(_ value: inout DeviceValue<T>) -> KernelArgument {
        return value.withUnsafeMutableDevicePointer { ptr in
            KernelArgument(unsafeAddress: ptr.deviceAddress)
        }
    }

}

Remove argument label ignored by the buggy compiler

//
//  Kernel.swift
//  Warp
//
//  Created by Richard Wei on 11/2/16.
//
//

import CUDADriver

/// Kernel operators

public extension KernelArgument {

    public static func array<T>(_ array: inout DeviceArray<T>) -> KernelArgument {
        return array.withUnsafeMutableDevicePointer { ptr in
            self.init(ptr.deviceAddress)
        }
    }

    public static func reference<T>(_ value: inout DeviceValue<T>) -> KernelArgument {
        return value.withUnsafeMutableDevicePointer { ptr in
            self.init(ptr.deviceAddress)
        }
    }

}


//
//  Metadata.swift
//  Mixpanel
//
//  Created by Yarden Eitan on 10/24/17.
//  Copyright © 2017 Mixpanel. All rights reserved.
//

import Foundation

class SessionMetadata {
    var eventsCounter: UInt64 = 0
    var peopleCounter: UInt64 = 0
    var sessionID: UInt64 = 0
    var sessionStartEpoch: UInt64 = 0
    var trackingQueue: DispatchQueue

    init(trackingQueue: DispatchQueue) {
        self.trackingQueue = trackingQueue
    }
    func applicationDidBecomeActive() {
        trackingQueue.async {
            self.eventsCounter = 0
            self.peopleCounter = 0
            self.sessionID = UInt64.random
            self.sessionStartEpoch = UInt64(Date().timeIntervalSince1970)
        }
    }

    func toDict(isEvent: Bool = true) -> InternalProperties {
        let dict = ["$mp_event_id": UInt64.random,
                    "$mp_session_id": sessionID,
                    "$mp_session_seq_id": (isEvent ? eventsCounter : peopleCounter),
                    "$mp_session_start_sec": sessionStartEpoch]
        isEvent ? (eventsCounter += 1) : (peopleCounter += 1)
        return dict
    }
}

extension UInt64 {
    static var random: UInt64 {
        let hex = UUID().uuidString
            .components(separatedBy: "-")
            .suffix(2)
            .joined()
        return UInt64(hex, radix: 0x10)!
    }
}

Change ids in session metadata to 16 hex chars

//
//  Metadata.swift
//  Mixpanel
//
//  Created by Yarden Eitan on 10/24/17.
//  Copyright © 2017 Mixpanel. All rights reserved.
//

import Foundation

class SessionMetadata {
    var eventsCounter: UInt64 = 0
    var peopleCounter: UInt64 = 0
    var sessionID: String = ""
    var sessionStartEpoch: UInt64 = 0
    var trackingQueue: DispatchQueue

    init(trackingQueue: DispatchQueue) {
        self.trackingQueue = trackingQueue
    }

    func applicationDidBecomeActive() {
        trackingQueue.async {
            self.eventsCounter = 0
            self.peopleCounter = 0
            self.sessionID = String.randomId()
            self.sessionStartEpoch = UInt64(Date().timeIntervalSince1970)
        }
    }

    func toDict(isEvent: Bool = true) -> InternalProperties {
        let dict : [String: Any] = ["$mp_event_id":  String.randomId(),
                    "$mp_session_id": sessionID,
                    "$mp_session_seq_id": (isEvent ? eventsCounter : peopleCounter),
                    "$mp_session_start_sec": sessionStartEpoch]
        isEvent ? (eventsCounter += 1) : (peopleCounter += 1)
        return dict
    }
}

private extension String {
    static func randomId() -> String {
        return String(format: "%08x%08x", arc4random(), arc4random())
    }
}


//
//  ArgumentsArray.swift
//  Commandant
//
//  Created by Anton Domashnev on 27/11/2016.
//  Copyright © 2016 Carthage. All rights reserved.
//

import Foundation

/// Represents an array of arguments that are converted from the given string
/// Using comma as a separator
/// E.g. "banana, apple, peach" -> ["banana", "apple", "peach"]
struct ArgumentsArray: ArgumentProtocol {
	/// Array of arguments that were passed by a comma separated string
	public let arguments: Array<String>

	/// Separator to be used to split string into values
	private static let separator = ","

	public static let name = "array"

	public static func from(string: String) -> ArgumentsArray? {
		let trimmedComponents = string.components(separatedBy: separator).map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
		if trimmedComponents.count > 1 {
			return ArgumentsArray(arguments: trimmedComponents)
		}
		return string.rangeOfCharacter(from: .whitespaces) == nil ? ArgumentsArray(arguments: [string]) : nil
	}
}

extension ArgumentsArray: Equatable {
	public static func ==(lhs: ArgumentsArray, rhs: ArgumentsArray) -> Bool {
		return lhs.arguments == rhs.arguments
	}
}

Update for code style guide;


//
//  Updatable+Extension.swift
//  FirebaseCommunity
//
//  Created by Victor Alisson on 16/08/17.
//

import Foundation

public extension Updatable where Self: FirebaseModel {
    func update(completion: @escaping (_ error: Error?) -> Void) {
        Self.path.updateChildValues(self.toJSON()) { (error, reference) in
            completion(error)
        }
    }
}

Change how to update the FirebaseModel

//
//  Updatable+Extension.swift
//  FirebaseCommunity
//
//  Created by Victor Alisson on 16/08/17.
//

import Foundation

public extension Updatable where Self: FirebaseModel {
    func update(completion: @escaping (_ error: Error?) -> Void) {
        guard let key = self.key else {
            return
        }
        Self.classPath.child(key).updateChildValues(toJSON()) { (error, reference) in
            completion(error)
        }
    }
}


//
//  Global.swift
//  Buy
//
//  Created by Dima Bart on 2017-02-24.
//  Copyright © 2017 Shopify Inc. All rights reserved.
//

import Foundation

private final class BundleCoordinator: NSObject {

    static func frameworkBundle() -> Bundle {
        return Bundle(for: self.classForCoder())
    }
}

struct Global {

    // ----------------------------------
    //  MARK: - User Agent -
    //
    static var userAgent: String {
        return "Mobile Buy SDK iOS/\(self.frameworkVersion)/\(self.applicationIdentifier)"
    }

    // ----------------------------------
    //  MARK: - Versions -
    //
    static var frameworkVersion: String {
        return self.frameworkBundle.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String ?? "x.x"
    }

    static var applicationIdentifier: String {
        return self.applicationBundle.object(forInfoDictionaryKey: kCFBundleIdentifierKey as String) as? String ?? "com.unknown.bundle"
    }

    // ----------------------------------
    //  MARK: - Bundles -
    //
    private static var frameworkBundle: Bundle {
        return BundleCoordinator.frameworkBundle()
    }

    private static var applicationBundle: Bundle {
        return Bundle.main
    }
}

Simplify getting the framework bundle.

//
//  Global.swift
//  Buy
//
//  Created by Dima Bart on 2017-02-24.
//  Copyright © 2017 Shopify Inc. All rights reserved.
//

import Foundation

class Global {

    // ----------------------------------
    //  MARK: - User Agent -
    //
    static var userAgent: String {
        return "Mobile Buy SDK iOS/\(self.frameworkVersion)/\(self.applicationIdentifier)"
    }

    // ----------------------------------
    //  MARK: - Versions -
    //
    static var frameworkVersion: String {
        return self.frameworkBundle.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String ?? "x.x"
    }

    static var applicationIdentifier: String {
        return self.applicationBundle.object(forInfoDictionaryKey: kCFBundleIdentifierKey as String) as? String ?? "com.unknown.bundle"
    }

    // ----------------------------------
    //  MARK: - Bundles -
    //
    private static var frameworkBundle: Bundle {
        return Bundle(for: self)
    }

    private static var applicationBundle: Bundle {
        return Bundle.main
    }
}


// RUN: not %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
// REQUIRES: asserts
extension String->[Void{#^A^#

Remove 'not' because code completion prints result.

// RUN: %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
// REQUIRES: asserts
extension String->[Void{#^A^#


// RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s
class C {
  func foo() {
    func bar() {
      self.foo()
    }
    // Yes, there are really two arguments calles self in this example!
    // CHECK: (name: "self", arg: 1, scope: ![[SCOPE:[0-9]+]], {{.*}}line: 10,
    // CHECK: (name: "self", arg: 2, scope: ![[SCOPE]], {{.*}}line: 3,
    {[weak self] in _ = self!; bar() }()
  }
}

Fix recently introduced typo: "calles" → "called"

// RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s
class C {
  func foo() {
    func bar() {
      self.foo()
    }
    // Yes, there are really two arguments called self in this example!
    // CHECK: (name: "self", arg: 1, scope: ![[SCOPE:[0-9]+]], {{.*}}line: 10,
    // CHECK: (name: "self", arg: 2, scope: ![[SCOPE]], {{.*}}line: 3,
    {[weak self] in _ = self!; bar() }()
  }
}


//
//  NSCursor+Dark.swift
//
//  CotEditor
//  https://coteditor.com
//
//  Created by 1024jp on 2018-09-26.
//
//  ---------------------------------------------------------------------------
//
//  © 2018-2019 1024jp
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  https://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

import AppKit.NSCursor

extension NSCursor {

    /// i-beam for dark background
    static var lightIBeam = NSCursor(image: #imageLiteral(resourceName: "LightIBeam"), hotSpot: NSCursor.iBeam.hotSpot)

    /// i-beam for vertical text orientation and dark background
    static var lightIBeamCursorForVerticalLayout = NSCursor(image: #imageLiteral(resourceName: "LightIBeamCursorForVerticalLayout"), hotSpot: NSCursor.iBeamCursorForVerticalLayout.hotSpot)
}

Change NSCursor’s static var to let

//
//  NSCursor+Dark.swift
//
//  CotEditor
//  https://coteditor.com
//
//  Created by 1024jp on 2018-09-26.
//
//  ---------------------------------------------------------------------------
//
//  © 2018-2020 1024jp
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  https://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

import AppKit.NSCursor

extension NSCursor {

    /// I-beam for dark background.
    static let lightIBeam = NSCursor(image: #imageLiteral(resourceName: "LightIBeam"), hotSpot: NSCursor.iBeam.hotSpot)

    /// I-beam for vertical text orientation and dark background.
    static let lightIBeamCursorForVerticalLayout = NSCursor(image: #imageLiteral(resourceName: "LightIBeamCursorForVerticalLayout"), hotSpot: NSCursor.iBeamCursorForVerticalLayout.hotSpot)
}


//
//  CreditCard.swift
//  Spreedly
//
//  Created by David Santoso on 10/8/15.
//  Copyright © 2015 Spreedly Inc. All rights reserved.
//

import Foundation

public class CreditCard {
    public var firstName, lastName, number, verificationValue, month, year: String?
    public var address1, address2, city, state, zip, country, phoneNumber: String?

    public init() {}
}

Include string formatters for expiration dates

//
//  CreditCard.swift
//  Spreedly
//
//  Created by David Santoso on 10/8/15.
//  Copyright © 2015 Spreedly Inc. All rights reserved.
//

import Foundation

public class CreditCard {
    public var firstName, lastName, number, verificationValue, month, year: String?
    public var address1, address2, city, state, zip, country, phoneNumber: String?

    public init() {}

    public static func extractMonth(expiration: String) -> String {
        return(self.splitExpirationString(expiration).first)!
    }

    public static func extractYear(expiration: String) -> String {
        return(self.splitExpirationString(expiration).last)!
    }

    static func splitExpirationString(expiration: String) -> [String] {
        let expirationArray = expiration.componentsSeparatedByString("/")
        return expirationArray
    }
}


//
//  Extensions.swift
//  RingSig
//
//  Created by Fabio Tacke on 14.06.17.
//
//

import Foundation
import BigInt

extension BigUInt {

  public static func randomPrime(length: Int) -> BigUInt {
    var random = BigUInt.randomInteger(withMaximumWidth: length)

    while !random.isPrime() {
      random = BigUInt.randomInteger(withMaximumWidth: length)
    }

    return random
  }

  public func bytesWithPadding(to bytesCount: Int) -> Array<UInt8> {
    let bytes = self.serialize().bytes
    let paddingBytes = bytesCount - bytes.count
    var padding = Array<UInt8>()
    for _ in 0..<paddingBytes {
      padding += [0]
    }
    return padding + bytes
  }

}

Refactor by using an initializer for arrays repeating an element

//
//  Extensions.swift
//  RingSig
//
//  Created by Fabio Tacke on 14.06.17.
//
//

import Foundation
import BigInt

extension BigUInt {

  public static func randomPrime(length: Int) -> BigUInt {
    var random = BigUInt.randomInteger(withMaximumWidth: length)

    while !random.isPrime() {
      random = BigUInt.randomInteger(withMaximumWidth: length)
    }

    return random
  }

  public func bytesWithPadding(to bytesCount: Int) -> Array<UInt8> {
    let bytes = self.serialize().bytes
    let paddingBytes = bytesCount - bytes.count
    let padding = Array<UInt8>(repeating: 0, count: paddingBytes)
    return padding + bytes
  }

}


//
//  StackViewController.swift
//  Beeline
//
//  Created by Karl Bowden on 5/01/2016.
//  Copyright © 2016 Featherweight Labs. All rights reserved.
//

import UIKit

public class StackViewController: UINavigationController {

    public enum TransitionAction {
        case Pop(Segment)
        case Push(Segment)
        case Change(Segment)
    }

    public var currentStack: [Segment] = []

    public func setStack(newStack: [Segment]) {

        let transitionStack = ZippedStack(currentStack, newStack)
        let stackActions = transitionActions(transitionStack)
        performActions(stackActions)
        currentStack = newStack
    }

    public func transitionActions(stack: ZippedStack<Segment>) -> [TransitionAction] {

        let fromActions: [TransitionAction] = stack.from.reverse().map { .Pop($0) }
        let toActions: [TransitionAction] = stack.to.map { .Push($0) }
        return fromActions + toActions
    }

    public func performActions(actionStack: [TransitionAction]) {
        for action in actionStack {
            switch action {

            case .Push(let segment):
                pushViewController(segment.create(), animated: true)

            case .Pop:
                popViewControllerAnimated(true)

            case .Change:
                fatalError("No change event yet")
            }
        }
    }

}

Remove unused change action in StackRoute for now

//
//  StackViewController.swift
//  Beeline
//
//  Created by Karl Bowden on 5/01/2016.
//  Copyright © 2016 Featherweight Labs. All rights reserved.
//

import UIKit

public class StackViewController: UINavigationController {

    public enum TransitionAction {
        case Pop(Segment)
        case Push(Segment)
    }

    public var currentStack: [Segment] = []

    public func setStack(newStack: [Segment]) {

        let transitionStack = ZippedStack(currentStack, newStack)
        let stackActions = transitionActions(transitionStack)
        performActions(stackActions)
        currentStack = newStack
    }

    public func transitionActions(stack: ZippedStack<Segment>) -> [TransitionAction] {

        let fromActions: [TransitionAction] = stack.from.reverse().map { .Pop($0) }
        let toActions: [TransitionAction] = stack.to.map { .Push($0) }
        return fromActions + toActions
    }

    public func performActions(actionStack: [TransitionAction]) {
        for action in actionStack {
            switch action {

            case .Push(let segment):
                pushViewController(segment.create(), animated: true)

            case .Pop:
                popViewControllerAnimated(true)
            }
        }
    }

}


class PageUserScript: WKUserScript {
    override init(source: String, injectionTime: WKUserScriptInjectionTime, forMainFrameOnly: Bool) {
        if #available(iOS 14.0, *) {
            super.init(source: source, injectionTime: .atDocumentStart, forMainFrameOnly: true, in: WKContentWorld.page)
        } else {
            super.init(source: source, injectionTime: .atDocumentStart, forMainFrameOnly: true)
        }
    }
}

Fix WKUserScript bug caused by not passing injection time to super.init

/// PageUserScript uses the platform-appropriate WKUserScript initializer to create a user script in WKContentWorld.page
class PageUserScript: WKUserScript {
    override init(source: String, injectionTime: WKUserScriptInjectionTime, forMainFrameOnly: Bool) {
        if #available(iOS 14.0, *) {
            super.init(source: source, injectionTime: injectionTime, forMainFrameOnly: true, in: WKContentWorld.page)
        } else {
            super.init(source: source, injectionTime: injectionTime, forMainFrameOnly: true)
        }
    }
}


//
//  EmptyResultView.swift
//  RandomUser
//
//  Created by Toni on 01/07/2017.
//  Copyright © 2017 Random User Inc. All rights reserved.
//

import Foundation
import BothamUI
import UIKit

@IBDesignable
public class EmptyResultView: BothamCustomView {
  @IBOutlet public weak var emptyLabel: UILabel! {
    didSet {
      emptyLabel.text = "No results found...\nSorry but this aren't the droids you're looking for."
    }
  }

  @IBInspectable public var color: UIColor? = nil {
    didSet {
      emptyLabel.textColor = color
    }
  }
}

Prepare empty view for acceptance tests

//
//  EmptyResultView.swift
//  RandomUser
//
//  Created by Toni on 01/07/2017.
//  Copyright © 2017 Random User Inc. All rights reserved.
//

import Foundation
import BothamUI
import UIKit

@IBDesignable
public class EmptyResultView: BothamCustomView {
  @IBOutlet public weak var emptyLabel: UILabel! {
    didSet {
      emptyLabel.text = "No results found...\nSorry but this aren't the droids you're looking for."
      emptyLabel.accessibilityLabel = "No results found"
    }
  }

  @IBInspectable public var color: UIColor? = nil {
    didSet {
      emptyLabel.textColor = color
    }
  }
}


// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import Foundation
#if os(OSX)
  import Cocoa
#endif

internal func openURL(_ url: URL) {
  #if os(OSX)
    if !NSWorkspace.shared().open(url) {
      print("default browser could not be opened")
    }
  #else
    printf("openURL(\(String(describing:url))) is not implemented on this platform.")
  #endif
}

Replace printf() call with print().

// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import Foundation
#if os(OSX)
  import Cocoa
#endif

internal func openURL(_ url: URL) {
  #if os(OSX)
    if !NSWorkspace.shared().open(url) {
      print("default browser could not be opened")
    }
  #else
    print("openURL(\(String(describing:url))) is not implemented on this platform.")
  #endif
}


//
//  CommentTableRowView.swift
//  Diurna
//
//  Created by Nicolas Gaulard-Querol on 28/02/2016.
//  Copyright © 2016 Nicolas Gaulard-Querol. All rights reserved.
//

import Cocoa

class CommentTableRowView: NSTableRowView {

    override func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)

        guard let cellView = viewAtColumn(0) else {
            return
        }

        let cellXOrigin = cellView.frame.origin.x
        var pos: CGFloat = 10
        var alpha: CGFloat = 0.5

        while pos < cellXOrigin {
            let line = NSBezierPath()
            line.lineWidth = 1.0
            NSColor.gridColor().colorWithAlphaComponent(alpha).setStroke()

            line.moveToPoint(NSPoint(x: pos, y: NSMaxY(self.bounds)))
            line.lineToPoint(NSPoint(x: pos, y: NSMinY(self.bounds)))
            line.stroke()

            pos += 20
            alpha -= 0.05
        }
    }
}

Change comments indent guides color

//
//  CommentTableRowView.swift
//  Diurna
//
//  Created by Nicolas Gaulard-Querol on 28/02/2016.
//  Copyright © 2016 Nicolas Gaulard-Querol. All rights reserved.
//

import Cocoa

class CommentTableRowView: NSTableRowView {

    let indentGuideColor = NSColor(calibratedHue: 1.0, saturation: 0.0, brightness: 0.85, alpha: 1.0)

    override func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)

        guard let cellView = viewAtColumn(0) else {
            return
        }

        let cellXOrigin = cellView.frame.origin.x

        var pos: CGFloat = 10
        var alpha: CGFloat = 1.0

        while pos < cellXOrigin {
            let line = NSBezierPath()
            line.lineWidth = 1.0
            indentGuideColor.colorWithAlphaComponent(alpha).setStroke()

            line.moveToPoint(NSPoint(x: pos, y: NSMaxY(self.bounds)))
            line.lineToPoint(NSPoint(x: pos, y: NSMinY(self.bounds)))
            line.stroke()

            pos += 20
            alpha -= 0.1
        }
    }
}


prefix operator <- {}
infix operator <- {}
infix operator <+ {}

public prefix func <-<T>(rhs: T?) throws -> T {
  guard let rhs = rhs else {
    throw MappableError.TypeError(message: "Unable to unrwap value")
  }
  return rhs
}

public func <- <T>(inout left: T, right: T) {
  left = right
}

public func <- <T>(inout left: T, right: T?) {
  guard let right = right else { return }

  left = right
}

public func <+ <T>(inout left: [T], right: [T]?) {
  guard let right = right else { return }
  left.appendContentsOf(right)
}

public func <+ <T>(inout left: [T], right: T?) {
  guard let right = right else { return }
  left.append(right)
}

Add operator to use throwable functions

prefix operator <- {}
infix operator <- {}
infix operator <+ {}

public prefix func <-<T>(rhs: T?) throws -> T {
  guard let rhs = rhs else {
    throw MappableError.TypeError(message: "Unable to unrwap value")
  }
  return rhs
}

public prefix func <-<T>(rhs: T) throws -> T {
  return rhs
}

public func <- <T>(inout left: T, right: T) {
  left = right
}

public func <- <T>(inout left: T, right: T?) {
  guard let right = right else { return }

  left = right
}

public func <+ <T>(inout left: [T], right: [T]?) {
  guard let right = right else { return }
  left.appendContentsOf(right)
}

public func <+ <T>(inout left: [T], right: T?) {
  guard let right = right else { return }
  left.append(right)
}


//
//  AdianTests.swift
//  AdianTests
//
//  Created by Jeremy on 2015-12-02.
//  Copyright © 2015 Jeremy W. Sherman. All rights reserved.
//

import XCTest
@testable import Adian

class ComposePostViewControllerTests: XCTestCase {

    var composePostViewController: ComposePostViewController!

    override func setUp() {
        super.setUp()
        composePostViewController = ComposePostViewController.instantiate()
    }

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

    func testKnowsItsStoryboardID() {
        // passes if we don't explode when as!'ing the ComposePostViewController in setUp()
    }

    func testHasASendButton() {
        havingLoadedItsView()
        XCTAssertNotNil(composePostViewController.sendButton, "nil sendButton")
    }

    func havingLoadedItsView() {
        _ = composePostViewController.view
    }

}

Make sendPost button the default

//
//  AdianTests.swift
//  AdianTests
//
//  Created by Jeremy on 2015-12-02.
//  Copyright © 2015 Jeremy W. Sherman. All rights reserved.
//

import XCTest
@testable import Adian

class ComposePostViewControllerTests: XCTestCase {

    var composePostViewController: ComposePostViewController!

    override func setUp() {
        super.setUp()
        composePostViewController = ComposePostViewController.instantiate()
    }

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

    func testKnowsItsStoryboardID() {
        // passes if we don't explode when as!'ing the ComposePostViewController in setUp()
    }

    func testHasASendButton() {
        havingLoadedItsView()
        XCTAssertNotNil(composePostViewController.sendButton, "nil sendButton")
    }

    func testSendButtonIsDefaultButton() {
        havingLoadedItsView()
        XCTAssertEqual(composePostViewController.sendButton.keyEquivalent, "\r")
    }

    func havingLoadedItsView() {
        _ = composePostViewController.view
    }

}


public struct AnswerSet: IteratorProtocol, Sequence {

  init(realizer: RealizerBase, variables: Set<String>) {
    self.realizer = realizer
    self.variables = variables
  }

  private var realizer: RealizerBase
  private var variables: Set<String>

  public func next() -> BindingMap? {
    return realizer.next()?.reified.filter { variables.contains($0.key) }
  }

}

Implement a `.all` property on knowledge bases

public struct AnswerSet: IteratorProtocol, Sequence {

  init(realizer: RealizerBase, variables: Set<String>) {
    self.realizer = realizer
    self.variables = variables
  }

  private var realizer: RealizerBase
  private var variables: Set<String>

  public func next() -> BindingMap? {
    return realizer.next()?.reified.filter { variables.contains($0.key) }
  }

  public var all: [BindingMap] { Array(self) }

}


//
//  ChainableCommand.swift
//  SwiftCLI
//
//  Created by Jake Heiser on 7/25/14.
//  Copyright (c) 2014 jakeheis. All rights reserved.
//

/// A chainable interface to a CommandType; all functions return the object itself for easy chaining.
/// Should only be used for simple commands.
public class ChainableCommand: LightweightCommand {

    public func withSignature(_ signature: String) -> ChainableCommand {
        self.signature = signature
        return self
    }

    public func withShortDescription(_ shortDescription: String) -> ChainableCommand {
        self.shortDescription = shortDescription
        return self
    }

    public func withOptionsSetup(_ optionsSetup: @escaping OptionsSetupBlock) -> ChainableCommand {
        optionsSetupBlock = optionsSetup
        return self
    }

    public func withUnrecognizedOptionsPrintingBehavior(_ behavior: UnrecognizedOptionsPrintingBehavior) -> ChainableCommand {
        unrecognizedOptionsPrintingBehavior = behavior
        return self
    }

    public func withFailOnUnrecognizedOptions(_ shouldFail: Bool) -> ChainableCommand {
        failOnUnrecognizedOptions = shouldFail
        return self
    }

    public func withExecutionBlock(_ execution: @escaping ExecutionBlock) -> ChainableCommand {
        executionBlock = execution
        return self
    }

}

Make all chainable withs discardable

//
//  ChainableCommand.swift
//  SwiftCLI
//
//  Created by Jake Heiser on 7/25/14.
//  Copyright (c) 2014 jakeheis. All rights reserved.
//

/// A chainable interface to a CommandType; all functions return the object itself for easy chaining.
/// Should only be used for simple commands.
public class ChainableCommand: LightweightCommand {

    @discardableResult
    public func withSignature(_ signature: String) -> ChainableCommand {
        self.signature = signature
        return self
    }

    @discardableResult
    public func withShortDescription(_ shortDescription: String) -> ChainableCommand {
        self.shortDescription = shortDescription
        return self
    }

    @discardableResult
    public func withOptionsSetup(_ optionsSetup: @escaping OptionsSetupBlock) -> ChainableCommand {
        optionsSetupBlock = optionsSetup
        return self
    }

    @discardableResult
    public func withUnrecognizedOptionsPrintingBehavior(_ behavior: UnrecognizedOptionsPrintingBehavior) -> ChainableCommand {
        unrecognizedOptionsPrintingBehavior = behavior
        return self
    }

    @discardableResult
    public func withFailOnUnrecognizedOptions(_ shouldFail: Bool) -> ChainableCommand {
        failOnUnrecognizedOptions = shouldFail
        return self
    }

    @discardableResult
    public func withExecutionBlock(_ execution: @escaping ExecutionBlock) -> ChainableCommand {
        executionBlock = execution
        return self
    }

}


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

import Foundation

extension DataWithPointer {

    func getZipStringField(_ length: Int, _ useUtf8: Bool) -> String? {
        guard length > 0
            else { return "" }
        let bytes = self.bytes(count: length)
        let bytesAreUtf8 = ZipString.needsUtf8(bytes)
        if !useUtf8 && ZipString.cp437Available && !bytesAreUtf8 {
            return String(data: Data(bytes: bytes), encoding: String.Encoding(rawValue:
                CFStringConvertEncodingToNSStringEncoding(ZipString.cp437Encoding)))
        } else {
            return String(data: Data(bytes: bytes), encoding: .utf8)
        }
    }

}

Fix build problem on linux

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

import Foundation

#if os(Linux)
    import CoreFoundation
#endif

extension DataWithPointer {

    func getZipStringField(_ length: Int, _ useUtf8: Bool) -> String? {
        guard length > 0
            else { return "" }
        let bytes = self.bytes(count: length)
        let bytesAreUtf8 = ZipString.needsUtf8(bytes)
        if !useUtf8 && ZipString.cp437Available && !bytesAreUtf8 {
            return String(data: Data(bytes: bytes), encoding: String.Encoding(rawValue:
                CFStringConvertEncodingToNSStringEncoding(ZipString.cp437Encoding)))
        } else {
            return String(data: Data(bytes: bytes), encoding: .utf8)
        }
    }

}


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

import Prelude
import Tesseract
import XCTest

final class ValueTests: XCTestCase {
	func testConstantValueDestructuresToSomeOfSameType() {
		assertEqual(Value(constant: 1).constant(), 1)
	}

	func testConstantValueDestructuresToNoneOfDifferentType() {
		assertNil(Value(constant: 1).constant() as ()?)
	}

	func testFunctionValueDestructuresAsConstantToNone() {
		assertNil(Value(function: id as Any -> Any).constant() as Any?)
	}

	func testFunctionValueDestructuresToSomeOfSameType() {
		assertNotNil(Value(function: id as Any -> Any).function() as (Any -> Any)?)
	}
}

Test function destructuring with different type.

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

import Prelude
import Tesseract
import XCTest

final class ValueTests: XCTestCase {
	func testConstantValueDestructuresToSomeOfSameType() {
		assertEqual(Value(constant: 1).constant(), 1)
	}

	func testConstantValueDestructuresToNoneOfDifferentType() {
		assertNil(Value(constant: 1).constant() as ()?)
	}

	func testFunctionValueDestructuresAsConstantToNone() {
		assertNil(Value(function: id as Any -> Any).constant() as Any?)
	}

	func testFunctionValueDestructuresToSomeOfSameType() {
		assertNotNil(Value(function: id as Any -> Any).function() as (Any -> Any)?)
	}

	func testFunctionValueDestructuresToNoneOfDifferentType() {
		assertNil(Value(function: id as Any -> Any).function() as (Int -> Int)?)
	}
}


import PackageDescription

let package = Package(
    name: "GzipSwift",
    dependencies: [.Package(url: "https://github.com/michael-yuji/zlib.git", versions: Version(0,0,0)..<Version(1,0,0))]
)

Change repository URL of zlib package

import PackageDescription

let package = Package(
    name: "GzipSwift",
    dependencies: [.Package(url: "https://github.com/1024jp/zlib.git", versions: Version(0,0,0)..<Version(1,0,0))]
)


// RUN: %empty-directory(%t)
// Clang-import a module.
import ClangModule

// Note: This test is highly dependent on the clang module cache
// format, but it is testing specifics of the module cache.

// 1. Test that swift-ide-test creates a thin module without debug info.

// RUN: %swift-ide-test_plain -print-usrs -target %target-triple -module-cache-path %t  -I %S/Inputs -source-filename %s
// RUN: %target-swift-frontend %s -c -g -o %t.o -module-cache-path %t -I %S/Inputs
// RUN: file %t/*/ClangModule-*.pcm | grep data

// 2. Test that swift is creating clang modules with debug info.

// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -c -g -o %t.o -module-cache-path %t -I %S/Inputs
// RUN: file %t/*/ClangModule-*.pcm | egrep '(Mach-O|ELF)'

// 3. Test that swift-ide-check will not share swiftc's module cache.

// RUN: %swift-ide-test_plain -print-usrs -target %target-triple -module-cache-path %t  -I %S/Inputs -source-filename %s

Make test more robust. file(1) may not always recognize CPCH as data.

// RUN: %empty-directory(%t)
// Clang-import a module.
import ClangModule

// Note: This test is highly dependent on the clang module cache
// format, but it is testing specifics of the module cache.

// 1. Test that swift-ide-test creates a thin module without debug info.

// RUN: %empty-directory(%t)
// RUN: %swift-ide-test_plain -print-usrs -target %target-triple -module-cache-path %t  -I %S/Inputs -source-filename %s
// RUN: head -c 4 %t/*/ClangModule-*.pcm | grep -q CPCH

// 2. Test that swift is creating clang modules with debug info.

// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -c -g -o %t.o -module-cache-path %t -I %S/Inputs
// RUN: file %t/*/ClangModule-*.pcm | egrep -q '(Mach-O|ELF)'

// 3. Test that swift-ide-check will not share swiftc's module cache.

// RUN: %swift-ide-test_plain -print-usrs -target %target-triple -module-cache-path %t  -I %S/Inputs -source-filename %s


//
//  EmailDataStorage.swift
//  SendToMe
//
//  Created by Chris Jimenez on 1/26/16.
//  Copyright © 2016 Chris Jimenez. All rights reserved.
//

import Foundation

/// Simple data storage using NSUserDefault to store the email value set
public struct EmailDataStorage {

    let defaults = NSUserDefaults.init(suiteName: "group.com.greenpixels.sendtomeapp")

    public init(){}

    private enum StorageKeys{

        static let emailKey = "SendToMeEmail"
    }

    /// Has saved an email address/
    public var hasEmailSaved :Bool{

        return !getEmail().isEmpty
    }

    /**
     Returns the email value saved

     - returns: <#return value description#>
     */
    public func getEmail() -> String{

        var emailValue = ""
        if let email = defaults?.stringForKey(StorageKeys.emailKey) {
            emailValue = email
        }
        return emailValue
    }

    /**
     Save an email value in the local storage

     - parameter email: email value
     */
    public func saveEmail(email:String){

        defaults?.setValue(email, forKey: StorageKeys.emailKey)

        defaults?.synchronize()

        print("Email \(email) saved")
    }

    /**
     Clear the value of the email in the storage
     */
    public func clearEmail()
    {

        defaults?.removeObjectForKey(StorageKeys.emailKey)

        print("Email cleared")
    }

}

Update data storage bundle identifier

//
//  EmailDataStorage.swift
//  SendToMe
//
//  Created by Chris Jimenez on 1/26/16.
//  Copyright © 2016 Chris Jimenez. All rights reserved.
//

import Foundation

/// Simple data storage using NSUserDefault to store the email value set
public struct EmailDataStorage {

    let defaults = NSUserDefaults.init(suiteName: "group.com.greenpixels.sendtome")

    public init(){}

    private enum StorageKeys{

        static let emailKey = "SendToMeEmail"
    }

    /// Has saved an email address/
    public var hasEmailSaved :Bool{

        return !getEmail().isEmpty
    }

    /**
     Returns the email value saved

     - returns: <#return value description#>
     */
    public func getEmail() -> String{

        var emailValue = ""
        if let email = defaults?.stringForKey(StorageKeys.emailKey) {
            emailValue = email
        }
        return emailValue
    }

    /**
     Save an email value in the local storage

     - parameter email: email value
     */
    public func saveEmail(email:String){

        defaults?.setValue(email, forKey: StorageKeys.emailKey)

        defaults?.synchronize()

        print("Email \(email) saved")
    }

    /**
     Clear the value of the email in the storage
     */
    public func clearEmail()
    {

        defaults?.removeObjectForKey(StorageKeys.emailKey)

        print("Email cleared")
    }

}


#!/usr/bin/env swift

import Foundation

var num_steps: Int = 1000000000

if CommandLine.arguments.count == 2 {
    num_steps = Int(CommandLine.arguments[1])!;
}

print("Calculating PI with:")
print("  " + String(num_steps) + " slices")
print("  1 process")

var total_sim: Double = 0.0
var step: Double = 1.0/Double(num_steps)

// Get time.
let start = Date()

for i in 1...num_steps {
    var x: Double = (Double(i) - 0.5) * step
    total_sim += 4.0/(1.0+(x*x))
}

var pi: Double = total_sim * step

// Get time again.
let stop = Date()
let interval = stop.timeIntervalSince(start)

print("Obtained value of PI: " + String(pi))
print("Time taken: " + String(interval) + " seconds")

Use preprocessor directives to support Swift 2.x

#!/usr/bin/env swift

import Foundation

var num_steps: Int = 1000000000

#if swift(>=3)
if CommandLine.arguments.count == 2 {
    num_steps = Int(CommandLine.arguments[1])!;
}
#else
if Process.arguments.count == 2 {
    num_steps = Int(Process.arguments[1])!;
}
#endif

print("Calculating PI with:")
print("  " + String(num_steps) + " slices")
print("  1 process")

var total_sim: Double = 0.0
var step: Double = 1.0/Double(num_steps)

// Get time.
let start = Date()

for i in 1...num_steps {
    var x: Double = (Double(i) - 0.5) * step
    total_sim += 4.0/(1.0+(x*x))
}

var pi: Double = total_sim * step

// Get time again.
let stop = Date()
let interval = stop.timeIntervalSince(start)

print("Obtained value of PI: " + String(pi))
print("Time taken: " + String(interval) + " seconds")


import Quick
import Nimble
@testable import Fakery

class BankSpec: QuickSpec {

    override func spec() {
        describe("Bank") {
            var bank: Bank!

            beforeEach {
                let parser = Parser(locale: "en-TEST")
                bank = Bank(parser: parser)
            }

            describe("#name") {
                it("returns the correct text") {
                    let name = bank.name()
                    expect(name).to(equal("ABN AMRO CORPORATE FINANCE LIMITED"))
                }
            }

            describe("#swiftBic") {
                it("returns a valid BIC") {
                    let swiftBic = bank.swiftBic()
                    expect(swiftBic).to(equal("AAFMGB21"))
                }
            }

            describe("#iban") {
                it("returns a valid IBAN") {
                    let iban = bank.iban()
                    expect(iban).to(match("[A-Z]{2}\\d{2}[A-Z]{4}\\d{10}"))
                }
            }
        }
    }
}

Add capability to generate Dutch BBAN numbers

import Quick
import Nimble
@testable import Fakery

class BankSpec: QuickSpec {

    override func spec() {
        describe("Bank") {
            var bank: Bank!

            beforeEach {
                let parser = Parser(locale: "en-TEST")
                bank = Bank(parser: parser)
            }

            describe("#name") {
                it("returns the correct text") {
                    let name = bank.name()
                    expect(name).to(equal("ABN AMRO CORPORATE FINANCE LIMITED"))
                }
            }

            describe("#swiftBic") {
                it("returns a valid BIC") {
                    let swiftBic = bank.swiftBic()
                    expect(swiftBic).to(equal("AAFMGB21"))
                }
            }

            describe("#iban") {
                it("returns a valid IBAN") {
                    let iban = bank.iban()
                    expect(iban).to(match("[A-Z]{2}\\d{2}[A-Z]{4}\\d{10}"))
                }
            }

            describe("#bban") {
                it("returns a valid BBAN") {
                    let bban = bank.bban()
                    expect(bban).to(match("[A-Z]{4}\\d{10}"))
                }
            }
        }
    }
}


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

extension Module {
	public static var churchSigma: Module {
		let Sigma = Declaration("Sigma",
			type: Recur.lambda(.Type) { A in .FunctionType(.FunctionType(A, .Type), .Type) },
			value: Recur.lambda(.Type) { A in Recur.lambda(.FunctionType(A, .Type), .Type) { B, C in Recur.FunctionType(Recur.lambda(A) { x in .FunctionType(B[x], C) }, C) } })

		let sigma = Declaration("sigma",
			type: Recur.lambda(.Type) { A in Recur.lambda(.FunctionType(A, .Type), A) { B, x in .FunctionType(B[x], Sigma.ref[A, Recur.lambda(A) { B[$0] }]) } },
			value: Recur.lambda(.Type) { A in Recur.lambda(.FunctionType(A, .Type), A) { B, x in Recur.lambda(B[x], .Type) { y, C in Recur.lambda(Recur.lambda(A) { xʹ in .FunctionType(B[xʹ], C) }) { f in f[x, y] } } } })

		return Module("ChurchSigma", [ Sigma, sigma ])
	}
}

Add the `first` eliminator for sigmas.

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

extension Module {
	public static var churchSigma: Module {
		let Sigma = Declaration("Sigma",
			type: Recur.lambda(.Type) { A in .FunctionType(.FunctionType(A, .Type), .Type) },
			value: Recur.lambda(.Type) { A in Recur.lambda(.FunctionType(A, .Type), .Type) { B, C in Recur.FunctionType(Recur.lambda(A) { x in .FunctionType(B[x], C) }, C) } })

		let sigma = Declaration("sigma",
			type: Recur.lambda(.Type) { A in Recur.lambda(.FunctionType(A, .Type), A) { B, x in .FunctionType(B[x], Sigma.ref[A, Recur.lambda(A) { B[$0] }]) } },
			value: Recur.lambda(.Type) { A in Recur.lambda(.FunctionType(A, .Type), A) { B, x in Recur.lambda(B[x], .Type) { y, C in Recur.lambda(Recur.lambda(A) { xʹ in .FunctionType(B[xʹ], C) }) { f in f[x, y] } } } })

		let first = Declaration("first",
			type: Recur.lambda(.Type) { A in Recur.lambda(A --> .Type) { B in Sigma.ref[A, Recur.lambda(A) { x in B[x] }] --> A } },
			value: .Type => { A in (A --> .Type) => { B in Sigma.ref[A, A => { x in B[x] }] => { v in v[A, A => { x in B[x] => const(x) }] } } })

		return Module("ChurchSigma", [ Sigma, sigma, first ])
	}
}

import Prelude


import Foundation
import XCTest
import HTTP
@testable import AppLogic
@testable import Vapor

class RouteTests: XCTestCase, DropletTests {
    /// This is a requirement for XCTest on Linux
    /// to function properly.
    /// See ./Tests/LinuxMain.swift for examples
    static let allTests = [
        ("testV1Collections", testV1Collections),
        ("testCORSMiddlewareConnection", testCORSMiddlewareConnection)
    ]

    var drop: Droplet!

    override func setUp() {
         super.setUp()

        drop = type(of: self).createDroplet()
    }

    func testV1Collections() {
        XCTAssertNotNil(V1AdminCollection())
        XCTAssertNotNil(V1ManageCollection())
        XCTAssertNotNil(V1PublicCollection())
    }

    func testCORSMiddlewareConnection() throws {
        try AppLogic.setup(drop)
        try drop.runCommands()

        var found = false
        for item in drop.middleware where item is CORSMiddleware { found = true }

        XCTAssertTrue(found)
    }
}

Fix tests fail without db connection

import Foundation
import XCTest
import HTTP
@testable import AppLogic
@testable import Vapor

class RouteTests: XCTestCase, DropletTests {
    /// This is a requirement for XCTest on Linux
    /// to function properly.
    /// See ./Tests/LinuxMain.swift for examples
    static let allTests = [
        ("testV1Collections", testV1Collections),
        ("testCORSMiddlewareConnection", testCORSMiddlewareConnection)
    ]

    var drop: Droplet!

    override func setUp() {
         super.setUp()

        drop = type(of: self).createDroplet()
    }

    func testV1Collections() {
        XCTAssertNotNil(V1AdminCollection())
        XCTAssertNotNil(V1ManageCollection())
        XCTAssertNotNil(V1PublicCollection())
    }

    func testCORSMiddlewareConnection() throws {
        try? AppLogic.setup(drop)

        var found = false
        for item in drop.middleware where item is CORSMiddleware { found = true }

        XCTAssertTrue(found)

    }
}


//
//  SKMesurement.swift
//  SKPhotoBrowser
//
//  Created by 鈴木 啓司 on 2016/08/09.
//  Copyright © 2016年 suzuki_keishi. All rights reserved.
//

import Foundation
import UIKit

struct SKMesurement {
    static let isPhone: Bool = UIDevice.current.userInterfaceIdiom == .phone
    static let isPad: Bool = UIDevice.current.userInterfaceIdiom == .pad
    static var statusBarH: CGFloat {
        return UIApplication.shared.statusBarFrame.height
    }
    static var screenHeight: CGFloat {
        return UIApplication.shared.preferredApplicationWindow?.bounds.height ?? UIScreen.main.bounds.height
    }
    static var screenWidth: CGFloat {
        return UIApplication.shared.preferredApplicationWindow?.bounds.width ?? UIScreen.main.bounds.width
    }
    static var screenScale: CGFloat {
        return UIScreen.main.scale
    }
    static var screenRatio: CGFloat {
        return screenWidth / screenHeight
    }
    static var isPhoneX: Bool {
        if isPhone && UIScreen.main.nativeBounds.height == 2436 {
           return true
        }
        return false
    }
}

Support for iPhoneXS, XSMax and XR

//
//  SKMesurement.swift
//  SKPhotoBrowser
//
//  Created by 鈴木 啓司 on 2016/08/09.
//  Copyright © 2016年 suzuki_keishi. All rights reserved.
//

import Foundation
import UIKit

struct SKMesurement {
    static let isPhone: Bool = UIDevice.current.userInterfaceIdiom == .phone
    static let isPad: Bool = UIDevice.current.userInterfaceIdiom == .pad
    static var statusBarH: CGFloat {
        return UIApplication.shared.statusBarFrame.height
    }
    static var screenHeight: CGFloat {
        return UIApplication.shared.preferredApplicationWindow?.bounds.height ?? UIScreen.main.bounds.height
    }
    static var screenWidth: CGFloat {
        return UIApplication.shared.preferredApplicationWindow?.bounds.width ?? UIScreen.main.bounds.width
    }
    static var screenScale: CGFloat {
        return UIScreen.main.scale
    }
    static var screenRatio: CGFloat {
        return screenWidth / screenHeight
    }
    static var isPhoneX: Bool {
        let iPhoneXHeights: [CGFloat] = [2436, 2688, 1792]
        if isPhone, iPhoneXHeights.contains(UIScreen.main.nativeBounds.height) {
           return true
        }
        return false
    }
}


//
//  Premier+UserDefaults.swift
//  PremierKit
//
//  Created by Ricardo Pereira on 01/10/2019.
//  Copyright © 2019 Ricardo Pereira. All rights reserved.
//

import Foundation

@propertyWrapper
public struct UserDefault<T> {
    let key: String
    let defaultValue: T

    public init(_ key: String, defaultValue: T) {
        self.key = key
        self.defaultValue = defaultValue
    }

    public var wrappedValue: T {
        get {
            return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue
        }
        set {
            UserDefaults.standard.set(newValue, forKey: key)
        }
    }
}

Add OptionalUserDefault and accept a suite name for shared UserDefaults using AppGroups

//
//  Premier+UserDefaults.swift
//  PremierKit
//
//  Created by Ricardo Pereira on 01/10/2019.
//  Copyright © 2019 Ricardo Pereira. All rights reserved.
//

import Foundation

@propertyWrapper
public struct UserDefault<T> {
    let key: String
    let defaultValue: T
    let suiteName: String?

    public init(_ key: String, defaultValue: T, suiteName: String? = nil) {
        self.key = key
        self.defaultValue = defaultValue
        self.suiteName = suiteName
    }

    private func userDefaults() -> UserDefaults {
        var userDefaults = UserDefaults.standard
        if let suiteName = suiteName, let suiteUserDefaults = UserDefaults(suiteName: suiteName) {
            userDefaults = suiteUserDefaults
        }
        return userDefaults
    }

    public var wrappedValue: T {
        get {
            return userDefaults().object(forKey: key) as? T ?? defaultValue
        }
        set {
            userDefaults().set(newValue, forKey: key)
        }
    }
}

@propertyWrapper
public struct OptionalUserDefault<T> {
    let key: String
    let defaultValue: T?
    let suiteName: String?

    public init(_ key: String, defaultValue: T? = nil, suiteName: String? = nil) {
        self.key = key
        self.defaultValue = defaultValue
        self.suiteName = suiteName
    }

    private func userDefaults() -> UserDefaults {
        var userDefaults = UserDefaults.standard
        if let suiteName = suiteName, let suiteUserDefaults = UserDefaults(suiteName: suiteName) {
            userDefaults = suiteUserDefaults
        }
        return userDefaults
    }

    public var wrappedValue: T? {
        get {
            return userDefaults().object(forKey: key) as? T ?? defaultValue
        }
        set {
            userDefaults().set(newValue, forKey: key)
        }
    }
}

private struct TestUserDefault {

    @UserDefault(#function, defaultValue: "")
    static var a: String

    @UserDefault(#function, defaultValue: "", suiteName: "PremierKitGroup")
    static var b: String

    @OptionalUserDefault(#function)
    static var c: String?

    @OptionalUserDefault(#function, suiteName: "PremierKitGroup")
    static var d: String?

}


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

/// The app from which an item, like a video, was originally uploaded, i.e.: iMovie, Vimeo for macOS, Cameo, etc.
@objcMembers
public class APIClientApp: VIMModelObject {

    /// The name of the app.
    public var name: String?

    /// A URI which may serve as a unique identifier for the app.
    public var uri: String?
}

Fix name in header documentation

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

/// The app from which an item, like a video, was originally uploaded, i.e.: iMovie, Vimeo for macOS, Cameo, etc.
@objcMembers
public class APIClientApp: VIMModelObject {

    /// The name of the app.
    public var name: String?

    /// A URI which may serve as a unique identifier for the app.
    public var uri: String?
}


//
//  PropertySpec.swift
//  SwiftCheck
//
//  Created by Robert Widmann on 6/5/15.
//  Copyright (c) 2015 Robert Widmann. All rights reserved.
//

import XCTest
import SwiftCheck

class PropertySpec : XCTestCase {
	func testAll() {
		property["Once really only tests a property once"] = forAll { (n : Int) in
			var bomb : Optional<Int> = .Some(n)
			return once(forAll { (_ : Int) in
				let b = bomb! // Will explode if we test more than once
				bomb = nil
				return b == n
			})
		}
	}
}

Convert new test to 0.3.0

//
//  PropertySpec.swift
//  SwiftCheck
//
//  Created by Robert Widmann on 6/5/15.
//  Copyright (c) 2015 Robert Widmann. All rights reserved.
//

import XCTest
import SwiftCheck

class PropertySpec : XCTestCase {
	func testAll() {
		property("Once really only tests a property once") <- forAll { (n : Int) in
			var bomb : Optional<Int> = .Some(n)
			return once(forAll { (_ : Int) in
				let b = bomb! // Will explode if we test more than once
				bomb = nil
				return b == n
			})
		}
	}
}


//
//  JSONArray.swift
//  SwiftyJSONModel
//
//  Created by Oleksii on 21/09/2016.
//  Copyright © 2016 Oleksii Dykan. All rights reserved.
//

import Foundation
import SwiftyJSON

public struct JSONArray<T> where T: JSONInitializable & JSONRepresentable {
    public let array: [T]

    public init(_ array: [T]) {
        self.array = array
    }
}

extension JSONArray: JSONInitializable {
    public init(json: JSON) throws {
        guard json.type == .array else {
            throw JSONModelError.invalidJSON
        }
        array = try json.arrayValue().map({ try T(json: $0) })
    }
}

extension JSONArray: JSONRepresentable {
    public var jsonValue: JSON {
        return JSON(array.map({ $0.jsonValue }))
    }
}

extension Array where Element: JSONInitializable & JSONRepresentable {
    var jsonArray: JSONArray<Element> {
        return JSONArray<Element>(self)
    }
}

Make sure to make json array private

//
//  JSONArray.swift
//  SwiftyJSONModel
//
//  Created by Oleksii on 21/09/2016.
//  Copyright © 2016 Oleksii Dykan. All rights reserved.
//

import Foundation
import SwiftyJSON

struct JSONArray<T: JSONRepresentable>: JSONRepresentable {
    let array: [T]

    init(_ array: [T]) {
        self.array = array
    }

    var jsonValue: JSON {
        return JSON(array.map({ $0.jsonValue }))
    }
}

public extension Array where Element: JSONRepresentable {
    public var jsonRepresantable: JSONRepresentable {
        return JSONArray<Element>(self)
    }
}