// RUN: %swift %s -parse -verify

@availability(*, unavailable)
func unavailable_func() {}

@availability(*, unavailable, message="message")
func unavailable_func_with_message() {}

@availability(iOS, unavailable)
@availability(OSX, unavailable)
func unavailable_multiple_platforms() {}

@availability(badPlatform, unavailable) // expected-error {{unknown platform 'badPlatform' for attribute 'availability'}}
func unavailable_bad_platform() {}

// Handle unknown platform.
@availability(HAL9000, unavailable) // expected-error {{unknown platform 'HAL9000'}}
func availabilityUnknownPlatform() {}

// <rdar://problem/17669805> Availability can't appear on a typealias
@availability(*, unavailable, message="oh no you dont")
typealias int = Int

var x : int // expected-error {{'int' is unavailable: oh no you dont}}

Add some tests for malformed availability attributes.

// RUN: %swift %s -parse -verify

@availability(*, unavailable)
func unavailable_func() {}

@availability(*, unavailable, message="message")
func unavailable_func_with_message() {}

@availability(iOS, unavailable)
@availability(OSX, unavailable)
func unavailable_multiple_platforms() {}

@availability // expected-error {{expected '(' in 'availability' attribute}}
func noArgs() {}
@availability(*) // expected-error {{expected ',' in 'availability' attribute}} expected-error {{expected declaration}}
func noKind() {}

@availability(badPlatform, unavailable) // expected-error {{unknown platform 'badPlatform' for attribute 'availability'}}
func unavailable_bad_platform() {}

// Handle unknown platform.
@availability(HAL9000, unavailable) // expected-error {{unknown platform 'HAL9000'}}
func availabilityUnknownPlatform() {}

// <rdar://problem/17669805> Availability can't appear on a typealias
@availability(*, unavailable, message="oh no you dont")
typealias int = Int

var x : int // expected-error {{'int' is unavailable: oh no you dont}}


//
//  WelcomePromptStringFactory.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 25/08/2017.
//  Copyright © 2017 Eurofurence. All rights reserved.
//

import Foundation

protocol WelcomePromptStringFactory {

    func makeString(for user: User) -> String
    func makeStringForAnonymousUser() -> String

}

Add unlocalised adapter for welcome prompt factory

//
//  WelcomePromptStringFactory.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 25/08/2017.
//  Copyright © 2017 Eurofurence. All rights reserved.
//

import Foundation

protocol WelcomePromptStringFactory {

    func makeString(for user: User) -> String
    func makeStringForAnonymousUser() -> String

}

struct UnlocalizedWelcomePromptStringFactory: WelcomePromptStringFactory {

    func makeString(for user: User) -> String {
        return "Welcome, \(user.username) (\(user.registrationNumber))"
    }

    func makeStringForAnonymousUser() -> String {
        return "You are currently not logged in"
    }

}


//
//  TabsViewController.swift
//  DStackExample
//
//  Created by Andrei Erusaev on 8/21/17.
//

import DStack
import UIKit

@objcMembers
class TabsViewController: DSTabsViewController<HeaderView> {

    // MARK: Properties

    private
    let ctrl2 = DSTemplateViewController<WelcomelView>()

    private
    let ctrl3 = Example3ViewController()

    private
    let ctrl4 = CollectionViewController()

    // MARK: Initialization

    init() {
        super.init(
            viewControllers: []
        )
        title = "Tabs"
    }

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

    // MARK: Overrided Methods

    override
    func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white
        viewControllers = [ctrl4, ctrl2]
        navigationItem.rightBarButtonItems = [
            UIBarButtonItem(
                title: "2 tabs",
                style: .done,
                target: self,
                action: #selector(on2Tapped)
            ),
            UIBarButtonItem(
                title: "3 tabs",
                style: .done,
                target: self,
                action: #selector(on3Tapped)
            )
        ]
    }

    // MARK: Actions

    @objc private
    func on2Tapped() {
        viewControllers = [
            ctrl4,
            ctrl2
        ]
    }

    @objc private
    func on3Tapped() {
        viewControllers = [
            ctrl2,
            ctrl3,
            ctrl4
        ]
    }

}

Add title on Welcome View

//
//  TabsViewController.swift
//  DStackExample
//
//  Created by Andrei Erusaev on 8/21/17.
//

import DStack
import UIKit

@objcMembers
class TabsViewController: DSTabsViewController<HeaderView> {

    // MARK: Properties

    private
    let ctrl2: DSTemplateViewController<WelcomelView> = {
        let ctrl = DSTemplateViewController<WelcomelView>()
        ctrl.title = "Welcome View"
        return ctrl
    }()

    private
    let ctrl3 = Example3ViewController()

    private
    let ctrl4 = CollectionViewController()

    // MARK: Initialization

    init() {
        super.init(
            viewControllers: []
        )
        title = "Tabs"
    }

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

    // MARK: Overrided Methods

    override
    func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white
        viewControllers = [ctrl4, ctrl2]
        navigationItem.rightBarButtonItems = [
            UIBarButtonItem(
                title: "2 tabs",
                style: .done,
                target: self,
                action: #selector(on2Tapped)
            ),
            UIBarButtonItem(
                title: "3 tabs",
                style: .done,
                target: self,
                action: #selector(on3Tapped)
            )
        ]
    }

    // MARK: Actions

    @objc private
    func on2Tapped() {
        viewControllers = [
            ctrl4,
            ctrl2
        ]
    }

    @objc private
    func on3Tapped() {
        viewControllers = [
            ctrl2,
            ctrl3,
            ctrl4
        ]
    }

}


import XCTest
import SwiftUI
@testable import ViewInspector

@available(iOS 13.0, macOS 10.15, *)
@available(tvOS, unavailable)
final class TreeViewTests: XCTestCase {

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

    @available(watchOS, deprecated: 7.0)
    func testRetainsModifiers() throws {
        let view = Text("Test")
            .padding()
            .contextMenu(ContextMenu(menuItems: { Text("Menu") }))
            .padding().padding()
        let sut = try view.inspect().text()
        XCTAssertEqual(sut.content.medium.viewModifiers.count, 3)
    }
}

// MARK: - View Modifiers

@available(iOS 13.0, macOS 10.15, *)
@available(tvOS, unavailable)
final class GlobalModifiersForTreeView: XCTestCase {

    @available(watchOS, deprecated: 7.0)
    func testContextMenu() throws {
        let sut = EmptyView().contextMenu(ContextMenu(menuItems: { Text("") }))
        XCTAssertNoThrow(try sut.inspect().emptyView())
    }
}

Fix a failing test in iOS 15.5

import XCTest
import SwiftUI
@testable import ViewInspector

@available(iOS 13.0, macOS 10.15, *)
@available(tvOS, unavailable)
final class TreeViewTests: XCTestCase {

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

    @available(watchOS, deprecated: 7.0)
    func testRetainsModifiers() throws {
        let view = Text("Test")
            .padding()
            .contextMenu(ContextMenu(menuItems: { Text("Menu") }))
            .padding().padding()
        let sut = try view.inspect().text()
        let count: Int
        if #available(iOS 15.3, macOS 12.3, *) {
            count = 4
        } else {
            count = 3
        }
        XCTAssertEqual(sut.content.medium.viewModifiers.count, count)
    }
}

// MARK: - View Modifiers

@available(iOS 13.0, macOS 10.15, *)
@available(tvOS, unavailable)
final class GlobalModifiersForTreeView: XCTestCase {

    @available(watchOS, deprecated: 7.0)
    func testContextMenu() throws {
        let sut = EmptyView().contextMenu(ContextMenu(menuItems: { Text("") }))
        XCTAssertNoThrow(try sut.inspect().emptyView())
    }
}


func x(_ param: Int) -> Int {
  param
}

let y: (String) -> Void = { param in }

let z = { (param: String) in
  param.count
}

// RUN: %sourcekitd-test -req=collect-var-type %s -- %s | %FileCheck %s
// CHECK: (1:10, 1:15): Int (explicit type: 1)
// CHECK: (5:5, 5:6): (String) -> Void (explicit type: 1)
// CHECK: (5:29, 5:34): String (explicit type: 0)
// CHECK: (7:5, 7:6): (String) -> Int (explicit type: 0)
// CHECK: (7:12, 7:17): String (explicit type: 1)

Add wildcard parameter case to VariableType test

func x(_ param: Int) -> Int {
  param
}

let y: (String) -> Void = { param in }

let z = { (param: String) in
  param.count
}

let w: (String, Int) -> Void = { (_, x) in }

// RUN: %sourcekitd-test -req=collect-var-type %s -- %s | %FileCheck %s
// CHECK: (1:10, 1:15): Int (explicit type: 1)
// CHECK: (5:5, 5:6): (String) -> Void (explicit type: 1)
// CHECK: (5:29, 5:34): String (explicit type: 0)
// CHECK: (7:5, 7:6): (String) -> Int (explicit type: 0)
// CHECK: (7:12, 7:17): String (explicit type: 1)
// CHECK: (11:35, 11:36): String (explicit type: 0)
// CHECK: (11:38, 11:39): Int (explicit type: 0)


// 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// RUN: not --crash %target-swift-frontend %s -emit-ir
Int)func b(UInt=1 + 1 + 1 + 1 as?Int){{{{{{{{{{{{{a{

Mark a crasher as non-deterministically failing.

// 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// RUN: not --crash %target-swift-frontend %s -emit-ir

// REQUIRES: deterministic-behavior
Int)func b(UInt=1 + 1 + 1 + 1 as?Int){{{{{{{{{{{{{a{


//
//  [UINavigationController][T][Appearance].swift
//  T
//
//  Created by Virpik on 11/04/2018.
//

import Foundation

Add support method to UINavigationController

//
//  [UINavigationController][T][Appearance].swift
//  T
//
//  Created by Virpik on 11/04/2018.
//

import Foundation

public extension UINavigationController {

    /// Удаляет линию под navigation bar
    /// [ВАЖНО] isTranslucent = false
    public func clearBottomLine() {

        self.navigationBar.isTranslucent = false
        self.navigationBar.setBackgroundImage(UIImage(), for: .default)
        self.navigationBar.shadowImage = UIImage()
    }

    /// Сбрасывает линию под navigation bar
    public func resetBottomLine() {
        self.navigationBar.setBackgroundImage(nil, for: .default)
        self.navigationBar.shadowImage = nil
    }
}


import Foundation
import Result
import LoggerAPI

public class ResultOperation<T, E: Error>: Operation {
    typealias ResultType = Result<T, E>
    var result: ResultType?
    let closure: ((ResultOperation) -> ResultType)
    init(_ closure: @escaping ((ResultOperation) -> ResultType)) {
        self.closure = closure
    }
    public override func main() {
        if isCancelled {
            Log.debug("canncelled")
            return
        }
        result = closure(self)
    }
    func resultSync() -> ResultType {
        if !isFinished {
            OperationQueue().addOperations([self], waitUntilFinished: true)
        }
        return result!
    }
}

Fix typo in the debugging log

import Foundation
import Result
import LoggerAPI

public class ResultOperation<T, E: Error>: Operation {
    typealias ResultType = Result<T, E>
    var result: ResultType?
    let closure: ((ResultOperation) -> ResultType)
    init(_ closure: @escaping ((ResultOperation) -> ResultType)) {
        self.closure = closure
    }
    public override func main() {
        if isCancelled {
            Log.debug("cancelled")
            return
        }
        result = closure(self)
    }
    func resultSync() -> ResultType {
        if !isFinished {
            OperationQueue().addOperations([self], waitUntilFinished: true)
        }
        return result!
    }
}


//
//  TrackKit
//
//  Created by Jelle Vandebeeck on 21/03/16.
//

extension String {

    func isoDate() -> Date? {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
        formatter.timeZone = TimeZone(abbreviation: "UTC")
        return formatter.date(from: self)
    }

    func isoDateWithMilliseconds() -> Date? {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        formatter.timeZone = TimeZone(abbreviation: "UTC")
        return formatter.date(from: self)
    }

}

Optimize the use of the date formatters.

//
//  TrackKit
//
//  Created by Jelle Vandebeeck on 21/03/16.
//

extension String {

    func isoDate() -> Date? {
        return DateFormatter.isoDateFormatter.date(from: self)
    }

    func isoDateWithMilliseconds() -> Date? {
        return DateFormatter.isoDateFormatterWithMilliseconds.date(from: self)
    }

}

extension DateFormatter {

    fileprivate static let isoDateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
        formatter.timeZone = TimeZone(abbreviation: "UTC")
        return formatter
    }()

    fileprivate static let isoDateFormatterWithMilliseconds: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        formatter.timeZone = TimeZone(abbreviation: "UTC")
        return formatter
    }()

}


import Foundation
import UIKit

struct DeviceIdentifier {
    private var device = UIDevice.currentDevice()

    func deviceColor() {
        var selector:Selector = "deviceInfoForKey:"
        if (!device.respondsToSelector(selector)) {
            selector = "_deviceInfoForKey:"
        }

        if (!device.respondsToSelector(selector)) {
            return
        }

        print(device.modelName)

        // See https://docs.google.com/spreadsheets/d/1yFjZvtNaV7cYOB_hRDjgPiNgQDZtMzaLAUhfxv449ZA/edit#gid=0
        print(device.performSelector("_deviceInfoForKey:", withObject: "DeviceColor"))
        print(device.performSelector("_deviceInfoForKey:", withObject: "DeviceEnclosureColor"))
    }
}

Clean up logging in deviceIdentifier

import Foundation
import UIKit

struct DeviceIdentifier {
    private var device = UIDevice.currentDevice()

    func deviceColor() {
        var selector:Selector = "deviceInfoForKey:"
        if (!device.respondsToSelector(selector)) {
            selector = "_deviceInfoForKey:"
        }

        if (!device.respondsToSelector(selector)) {
            return
        }

        print("Model name: \(device.modelName)")

        // See https://docs.google.com/spreadsheets/d/1yFjZvtNaV7cYOB_hRDjgPiNgQDZtMzaLAUhfxv449ZA/edit#gid=0
        print("Color:", device.performSelector("_deviceInfoForKey:", withObject: "DeviceColor"))
        print("Enclosure color:", device.performSelector("_deviceInfoForKey:", withObject: "DeviceEnclosureColor"))
    }
}


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

import Foundation

import FeedlyKit
import Quick
import Nimble

class CloudAPISpec: QuickSpec {
    internal let client: CloudAPIClient = CloudAPIClient(target: SpecHelper.target)
    var profile: Profile?

    func fetchProfile(callback: () -> ()) {
        self.client.fetchProfile {
            guard let _ = $0.response?.statusCode,
                  let profile = $0.result.value else { return }
            self.profile = profile
            callback()
        }
    }

    func fetchLatestEntries(callback: ([Entry]) -> ()) {
        fetchProfile() {
            guard let p = self.profile else { return }
            let params = PaginationParams()
            params.count = SpecHelper.perPage
            self.client.fetchContents(p.allCategory.id, paginationParams: params) {
                callback($0.result.value!.items)
            }
        }
    }
}

Improve SpecHelper. Cache profile data, if profile is already fetched. use it

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

import Foundation

import FeedlyKit
import Quick
import Nimble

class CloudAPISpec: QuickSpec {
    internal let client: CloudAPIClient = CloudAPIClient(target: SpecHelper.target)
    var profile: Profile?

    func fetchProfile(callback: () -> ()) {
        if let _ = profile {
            callback()
            return
        }
        self.client.fetchProfile {
            guard let _ = $0.response?.statusCode,
                  let profile = $0.result.value else { return }
            self.profile = profile
            callback()
        }
    }

    func fetchLatestEntries(callback: ([Entry]) -> ()) {
        fetchProfile() {
            guard let p = self.profile else { return }
            let params = PaginationParams()
            params.count = SpecHelper.perPage
            self.client.fetchContents(p.allCategory.id, paginationParams: params) {
                callback($0.result.value!.items)
            }
        }
    }
}


// RUN: %target-run-simple-swift

// REQUIRES: executable_test

import StdlibUnittest

class Klass {}

var suite = TestSuite("LifetimeManagement")

suite.test("copy") {
  let k = Klass()
  expectTrue(k === _copy(k))
}

suite.test("move") {
  let k = Klass()
  let k2 = k
  expectTrue(k2 === _move(k))
}

runAllTests()

Fix bots by adding optimized_stdlib flag to a test.

// RUN: %target-run-simple-swift

// REQUIRES: executable_test
// REQUIRES: optimized_stdlib

import StdlibUnittest

class Klass {}

var suite = TestSuite("LifetimeManagement")

suite.test("copy") {
  let k = Klass()
  expectTrue(k === _copy(k))
}

suite.test("move") {
  let k = Klass()
  let k2 = k
  expectTrue(k2 === _move(k))
}

runAllTests()


//
// SwiftGenKit
// Copyright © 2019 SwiftGen
// MIT Licence
//

import Foundation
import PathKit

extension Strings {
  final class StringsDictFileParser: StringsFileTypeParser {
    private let options: ParserOptionValues

    init(options: ParserOptionValues) {
      self.options = options
    }

    static let extensions = ["stringsdict"]
    static let allOptions: ParserOptionList = [Option.separator]
    static let propertyListDecoder = PropertyListDecoder()

    func parseFile(at path: Path) throws -> [Strings.Entry] {
      guard let data = try? path.read() else {
        throw ParserError.failureOnLoading(path: path.string)
      }

      let plurals = try Strings.StringsDictFileParser.propertyListDecoder.decode([String: StringsDict].self, from: data)
        .compactMapValues { stringsDict -> StringsDict.PluralEntry? in
          guard case let .pluralEntry(pluralEntry) = stringsDict else { return nil }
          return pluralEntry
        }

      return try plurals.map { keyValuePair -> Entry in
        let (key, pluralEntry) = keyValuePair
        // swiftlint:disable:next todo
        // TODO: this only considers the first format value type. If the formatKey of a plural contains
        // different variables, it won't be able to create a fitting Entry
        let formatValueType = "%\(pluralEntry.variables.first?.value.valueTypeKey ?? "")"
        let placeholderTypes = try PlaceholderType.placeholders(fromFormat: formatValueType)
        return Entry(
          key: key,
          translation: pluralEntry.translation ?? "",
          types: placeholderTypes,
          keyStructureSeparator: options[Option.separator]
        )
      }
    }
  }
}

Handle multiple variables in one formatkey

//
// SwiftGenKit
// Copyright © 2019 SwiftGen
// MIT Licence
//

import Foundation
import PathKit

extension Strings {
  final class StringsDictFileParser: StringsFileTypeParser {
    private let options: ParserOptionValues

    init(options: ParserOptionValues) {
      self.options = options
    }

    static let extensions = ["stringsdict"]
    static let allOptions: ParserOptionList = [Option.separator]
    static let propertyListDecoder = PropertyListDecoder()

    func parseFile(at path: Path) throws -> [Strings.Entry] {
      guard let data = try? path.read() else {
        throw ParserError.failureOnLoading(path: path.string)
      }

      let plurals = try Strings.StringsDictFileParser.propertyListDecoder
        .decode([String: StringsDict].self, from: data)
        .compactMapValues { stringsDict -> StringsDict.PluralEntry? in
          guard case let .pluralEntry(pluralEntry) = stringsDict else { return nil }
          return pluralEntry
        }

      return try plurals.map { keyValuePair -> Entry in
        let (key, pluralEntry) = keyValuePair
        let valueTypes = pluralEntry.variables.reduce(into: [String]()) { valueTypes, keyValuePair in
          valueTypes.append("%\(keyValuePair.value.valueTypeKey)")
        }

        return Entry(
          key: key,
          translation: pluralEntry.translation ?? "",
          types: try PlaceholderType.placeholders(fromFormat: valueTypes.joined(separator: " ")),
          keyStructureSeparator: options[Option.separator]
        )
      }
    }
  }
}


import XCTest
import SwiftyJSON

@testable import SwiftRestModel

class SwiftRestModelTests: XCTestCase {

    let model = SwiftRestModel()

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

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

    func testModelNotNil() {
        XCTAssertNotNil(model, "model is nil")
    }

    func testParse() {
        let data: JSON = model.data
        model.parse()
        XCTAssertEqual(data.rawString(), model.data.rawString(), "parse method modified data")
    }

    func testIsNew() {
        XCTAssertTrue(model.isNew(), "model should be new")
        model.data["id"] = "1"
        XCTAssertFalse(model.isNew(), "model should not be new")
    }

}

Add tests for fetch method

import XCTest
import SwiftyJSON

@testable import SwiftRestModel

class SwiftRestModelTests: XCTestCase {

    let model = SwiftRestModel()

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

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

    func testModelNotNil() {
        XCTAssertNotNil(model, "model is nil")
    }

    func testParse() {
        let data: JSON = model.data
        model.parse()
        XCTAssertEqual(data.rawString(), model.data.rawString(), "parse method modified data")
    }

    func testFetchNewModel() {
        let expectation = self.expectationWithDescription("fetch posts")

        model.rootUrl = "http://jsonplaceholder.typicode.com/posts"
        model.fetch(
            success: {
                response in
                XCTAssertNotNil(self.model.data, "response is empty")
                XCTAssertNotEqual(self.model.data.arrayValue.count, 0, "collection is empty")
                expectation.fulfill()
        })

        self.waitForExpectationsWithTimeout(5.0, handler: nil)
    }

    func testFetchExistingModel() {
        let expectation = self.expectationWithDescription("fetch posts")

        model.rootUrl = "http://jsonplaceholder.typicode.com/posts"
        model.data["id"] = "1"
        model.fetch(
            success: {
                response in
                XCTAssertNotNil(self.model.data, "response is empty")
                XCTAssertEqual(self.model.data.arrayValue.count, 0, "collection is not empty")
                expectation.fulfill()
        })

        self.waitForExpectationsWithTimeout(5.0, handler: nil)
    }

    func testIsNew() {
        XCTAssertTrue(model.isNew(), "model should be new")
        model.data["id"] = "id1"
        XCTAssertFalse(model.isNew(), "model should not be new")
    }

}


var p: UnsafeMutablePointer<Int>
// p is not allocated yet, using it here would be an error
p = UnsafeMutablePointer<Int>(allocatingCapacity: 1)
// allocated but not initialized, p.memory is an arbitarary integer
p.pointee = 8
// now p is initialized
assert(p.pointee == 8)
p.deinitialize()
// at this point, the memory p points to is "garbage"
p.deallocateCapacity(1)
// now the memory is all freed up

Use the count-form of UnsafeMutablePointer.deinitialize

var p: UnsafeMutablePointer<Int>
// p is not allocated yet, using it here would be an error
p = UnsafeMutablePointer<Int>(allocatingCapacity: 1)
// allocated but not initialized, p.memory is an arbitarary integer
p.pointee = 8
// now p is initialized
assert(p.pointee == 8)
p.deinitialize(count: 1)
// at this point, the memory p points to is "garbage"
p.deallocateCapacity(1)
// now the memory is all freed up


//
//  ProjectSpec.swift
//  Carthage
//
//  Created by Robert Böhnke on 27/12/14.
//  Copyright (c) 2014 Carthage. All rights reserved.
//

import CarthageKit
import Foundation
import Nimble
import Quick

class ProjectSpec: QuickSpec {
	override func spec() {
		let directoryURL = NSBundle(forClass: self.dynamicType).URLForResource("CartfilePrivateOnly", withExtension: nil)!

		it("should load a combined Cartfile when only a Cartfile.private is present") {
			let result = Project.loadCombinedCartfile(directoryURL).single()

			expect(result.isSuccess()).to(beTrue())

			let dependencies = result.value()!.dependencies

			expect(countElements(dependencies)).to(equal(1))
			expect(dependencies[0].project.name).to(equal("Carthage"))
		}
	}
}

Use the beTruthy matcher instead

//
//  ProjectSpec.swift
//  Carthage
//
//  Created by Robert Böhnke on 27/12/14.
//  Copyright (c) 2014 Carthage. All rights reserved.
//

import CarthageKit
import Foundation
import Nimble
import Quick

class ProjectSpec: QuickSpec {
	override func spec() {
		let directoryURL = NSBundle(forClass: self.dynamicType).URLForResource("CartfilePrivateOnly", withExtension: nil)!

		it("should load a combined Cartfile when only a Cartfile.private is present") {
			let result = Project.loadCombinedCartfile(directoryURL).single()

			expect(result.isSuccess()).to(beTruthy())

			let dependencies = result.value()!.dependencies

			expect(countElements(dependencies)).to(equal(1))
			expect(dependencies[0].project.name).to(equal("Carthage"))
		}
	}
}


//
//  TableViewKitTests.swift
//  TableViewKitTests
//
//  Created by Alfredo Delli Bovi on 28/08/16.
//  Copyright © 2016 odigeo. All rights reserved.
//

import XCTest
import TableViewKit
import Nimble

@testable import TableViewKit

class TableViewKitTests: XCTestCase {

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

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

    func testAddSection() {
        let tableViewManager = TableViewManager(tableView: UITableView())

        let section = HeaderFooterTitleSection()
        tableViewManager.sections.append(section)

        expect(tableViewManager.sections.count).to(equal(1))
    }

    func testAddItem() {

        let tableViewManager = TableViewManager(tableView: UITableView())

        let item: Item = TestItem()

        let section = HeaderFooterTitleSection()
        section.items.append(item)

        tableViewManager.sections.append(section)

        expect(section.items.count).to(equal(1))
        expect(item.section(inManager: tableViewManager)).notTo(beNil())

        section.items.remove(at: 0)
        section.items.append(item)

        section.items.replace(with: [TestItem(), item])
    }

    func testConvenienceInit() {
        let tableViewManager = TableViewManager(tableView: UITableView(), sections: [HeaderFooterTitleSection()])

        expect(tableViewManager.sections.count).to(equal(1))
    }

}

Fix bug for Swift 2.3

//
//  TableViewKitTests.swift
//  TableViewKitTests
//
//  Created by Alfredo Delli Bovi on 28/08/16.
//  Copyright © 2016 odigeo. All rights reserved.
//

import XCTest
import TableViewKit
import Nimble

@testable import TableViewKit

class TableViewKitTests: XCTestCase {

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

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

    func testAddSection() {
        let tableViewManager = TableViewManager(tableView: UITableView())

        let section = HeaderFooterTitleSection()
        tableViewManager.sections.append(section)

        expect(tableViewManager.sections.count).to(equal(1))
    }

    func testAddItem() {

        let tableViewManager = TableViewManager(tableView: UITableView())

        let item: Item = TestItem()

        let section = HeaderFooterTitleSection()
        section.items.append(item)

        tableViewManager.sections.append(section)

        expect(section.items.count).to(equal(1))
        expect(item.section(inManager: tableViewManager)).notTo(beNil())

        section.items.removeAtIndex(0)
        section.items.append(item)

        section.items.replace(with: [TestItem(), item])
    }

    func testConvenienceInit() {
        let tableViewManager = TableViewManager(tableView: UITableView(), sections: [HeaderFooterTitleSection()])

        expect(tableViewManager.sections.count).to(equal(1))
    }

}


import Darwin

struct Vector2D {
    let x: Double
    let y: Double

    init(_ x: Double, _ y: Double) {
        self.x = x
        self.y = y
    }

    var magnitude: Double {
        return sqrt(x * x + y * y)
    }
}

Add static shorthands for left, right, up and down 2D vectors

import Darwin

struct Vector2D {
    let x: Double
    let y: Double

    init(_ x: Double, _ y: Double) {
        self.x = x
        self.y = y
    }

    var magnitude: Double {
        return sqrt(x * x + y * y)
    }

    static let left = Vector2D(-1, 0)
    static let right = Vector2D(1, 0)
    static let up = Vector2D(0, 1)
    static let down = Vector2D(0, -1)
}


import Foundation

protocol VKURLSessionTask: ObservableObject {
    func resume()
    func cancel()

    var countOfBytesReceived: Int64 { get }
    var countOfBytesSent: Int64 { get }
    var countOfBytesExpectedToSend: Int64 { get }
    var countOfBytesExpectedToReceive: Int64 { get }
}

extension URLSessionTask: VKURLSessionTask {}

Fix vars and methods sequencing

import Foundation

protocol VKURLSessionTask: ObservableObject {
    var countOfBytesReceived: Int64 { get }
    var countOfBytesSent: Int64 { get }
    var countOfBytesExpectedToSend: Int64 { get }
    var countOfBytesExpectedToReceive: Int64 { get }

    func resume()
    func cancel()
}

extension URLSessionTask: VKURLSessionTask {}


import UIKit

class VConnectingPinListCell:UICollectionViewCell
{
    override init(frame:CGRect)
    {
        super.init(frame:frame)
    }

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

Add background view to cell

import UIKit

class VConnectingPinListCell:UICollectionViewCell
{
    private let kCornerRadius:CGFloat = 6

    override init(frame:CGRect)
    {
        super.init(frame:frame)
        isUserInteractionEnabled = false

        let background:UIView = UIView()
        background.isUserInteractionEnabled = false
        background.backgroundColor = UIColor(white:1, alpha:0.6)
        background.translatesAutoresizingMaskIntoConstraints = false
        background.layer.cornerRadius = kCornerRadius

        addSubview(background)

        NSLayoutConstraint.equals(
            view:background,
            toView:self)
    }

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


//
//  SingleCharTextField.swift
//  QuickJump
//
//  Created by Victor Shamanov on 5/28/15.
//  Copyright (c) 2015 Victor Shamanov. All rights reserved.
//

import AppKit

protocol SingleCharTextFieldDelegate: class {
    func didRecieveChar(textField: SingleCharTextField, char: Character)
    func didLoseFocus(textField: SingleCharTextField)
}

final class SingleCharTextField: NSTextField, NSTextFieldDelegate {

    // MARK:- Public properties

    weak var charInputDelegate: SingleCharTextFieldDelegate?

    // MARK:- Instantiation

    convenience init() {
        self.init(frame: .zeroRect)
    }

    override init(frame: NSRect) {
        super.init(frame: frame)
        delegate = self
    }

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

    // MARK:- Overriden methods

    override func controlTextDidEndEditing(obj: NSNotification) {
        charInputDelegate?.didLoseFocus(self)
        stringValue = ""
    }

    override func textDidChange(_: NSNotification) {
        if let char = last(stringValue) {
            charInputDelegate?.didRecieveChar(self, char: char)
            stringValue = ""
        }
    }

}

Exit on ESC key press

//
//  SingleCharTextField.swift
//  QuickJump
//
//  Created by Victor Shamanov on 5/28/15.
//  Copyright (c) 2015 Victor Shamanov. All rights reserved.
//

import AppKit

protocol SingleCharTextFieldDelegate: class {
    func didRecieveChar(textField: SingleCharTextField, char: Character)
    func didLoseFocus(textField: SingleCharTextField)
}

final class SingleCharTextField: NSTextField, NSTextFieldDelegate {

    // MARK:- Public properties

    weak var charInputDelegate: SingleCharTextFieldDelegate?

    // MARK:- Instantiation

    convenience init() {
        self.init(frame: .zeroRect)
    }

    override init(frame: NSRect) {
        super.init(frame: frame)
        delegate = self
    }

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

    // MARK:- NSTextFieldDelegate

    func control(control: NSControl, textView: NSTextView, doCommandBySelector commandSelector: Selector) -> Bool {
        switch commandSelector {
        case "complete:":
            charInputDelegate?.didLoseFocus(self)
            return true
        default:
            return false
        }
    }

    // MARK:- Overriden methods

    override func controlTextDidEndEditing(obj: NSNotification) {
        charInputDelegate?.didLoseFocus(self)
        stringValue = ""
    }

    override func textDidChange(_: NSNotification) {
        if let char = last(stringValue) {
            charInputDelegate?.didRecieveChar(self, char: char)
            stringValue = ""
        }
    }

}


import XCTest

extension XCTestCase {
    func waitForElementToAppear(element: XCUIElement, timeout: NSTimeInterval = 10,  file: String = __FILE__, line: UInt = __LINE__) {
        let existsPredicate = NSPredicate(format: "exists == true")

        expectationForPredicate(existsPredicate,
            evaluatedWithObject: element, handler: nil)

        waitForExpectationsWithTimeout(timeout) { (error) -> Void in
            if (error != nil) {
                let message = "Failed to find \(element) after \(timeout) seconds."
                self.recordFailureWithDescription(message, inFile: file, atLine: line, expected: true)
            }
        }
    }
}

extension XCUIElement {
    func forceTapElement() {
        if self.hittable {
            self.tap()
        } else {
            let coordinate: XCUICoordinate = self.coordinateWithNormalizedOffset(CGVectorMake(0.0, 0.0))
            coordinate.tap()
        }
    }
}

Remove deprecated Swift syntax from UI test

import XCTest

extension XCTestCase {
    func waitForElementToAppear(element: XCUIElement, timeout: NSTimeInterval = 10,  file: String = #file, line: UInt = #line) {
        let existsPredicate = NSPredicate(format: "exists == true")

        expectationForPredicate(existsPredicate,
            evaluatedWithObject: element, handler: nil)

        waitForExpectationsWithTimeout(timeout) { (error) -> Void in
            if (error != nil) {
                let message = "Failed to find \(element) after \(timeout) seconds."
                self.recordFailureWithDescription(message, inFile: file, atLine: line, expected: true)
            }
        }
    }
}

extension XCUIElement {
    func forceTapElement() {
        if self.hittable {
            self.tap()
        } else {
            let coordinate: XCUICoordinate = self.coordinateWithNormalizedOffset(CGVectorMake(0.0, 0.0))
            coordinate.tap()
        }
    }
}


//
//  Shuffle.swift
//  Attabench
//
//  Created by Károly Lőrentey on 2017-01-18.
//  Copyright © 2017 Károly Lőrentey.
//

import Foundation

extension Array {
    public mutating func shuffle() {
        for i in 0 ..< count {
            let j = Int(arc4random_uniform(UInt32(count)))
            if i != j {
                self.swapAt(i, j)
            }
        }
    }
}

extension Sequence {
    public func shuffled() -> [Iterator.Element] {
        var array = Array(self)
        array.shuffle()
        return array
    }
}

Use Fisher-Yates shuffle. Add support for >4G elements.

//
//  Shuffle.swift
//  Attabench
//
//  Created by Károly Lőrentey on 2017-01-18.
//  Copyright © 2017 Károly Lőrentey.
//

import Foundation

extension FixedWidthInteger {
    /// Return a random nonnegative value that is less than `limit`, which must be positive.
    /// Uses the `arc4` family of functions to generate random bits.
    public static func random(below limit: Self) -> Self {
        precondition(limit > 0)
        if Self.bitWidth <= UInt32.bitWidth || limit <= UInt32.max {
            return Self(arc4random_uniform(UInt32(limit)))
        }
        var random: Self = 0
        repeat {
            withUnsafeMutableBytes(of: &random) { buffer in
                arc4random_buf(buffer.baseAddress, buffer.count)
            }
            random >>= limit.leadingZeroBitCount
        } while random >= limit
        return random
    }
}

extension Array {
    public mutating func shuffle() {
        for i in 0 ..< count {
            let j = i + Int.random(below: self.count - i)
            if i != j {
                self.swapAt(i, j)
            }
        }
    }
}

extension Sequence {
    public func shuffled() -> [Iterator.Element] {
        var array = Array(self)
        array.shuffle()
        return array
    }
}


//
//  TypeEquality.swift
//  swiftz
//
//  Created by Maxwell Swadling on 19/06/2014.
//  Copyright (c) 2014 Maxwell Swadling. All rights reserved.
//

import Foundation

// For more info, see:
// http://hackage.haskell.org/package/type-equality-0.1.2/docs/Data-Type-Equality.html
protocol TypeEquality {
	typealias From
	typealias To

	func apply(a: From) -> To
}

@final class Refl<X> : TypeEquality {
	typealias From = X
	typealias To = X

	func apply(a: From) -> To {
		return a
	}
}

Make Refl into a struct

//
//  TypeEquality.swift
//  swiftz
//
//  Created by Maxwell Swadling on 19/06/2014.
//  Copyright (c) 2014 Maxwell Swadling. All rights reserved.
//

import Foundation

// For more info, see:
// http://hackage.haskell.org/package/type-equality-0.1.2/docs/Data-Type-Equality.html
protocol TypeEquality {
	typealias From
	typealias To

	func apply(a: From) -> To
}

struct Refl<X>: TypeEquality {
	typealias From = X
	typealias To = X

	func apply(a: From) -> To {
		return a
	}
}


//
//  TodayViewController.swift
//  CountdownToday
//
//  Created by Julian Grosshauser on 04/11/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import UIKit
import NotificationCenter

@objc(TodayViewController)
class TodayViewController: UIViewController, NCWidgetProviding {

    //MARK: UIViewController

    override func viewDidLoad() {
        super.viewDidLoad()
        preferredContentSize = CGSize(width: 0, height: 50)
    }

    func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
        completionHandler(.NoData)
    }
}

Move `NCWidgetProviding` method to an extension

//
//  TodayViewController.swift
//  CountdownToday
//
//  Created by Julian Grosshauser on 04/11/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import UIKit
import NotificationCenter

@objc(TodayViewController)
class TodayViewController: UIViewController {

    //MARK: UIViewController

    override func viewDidLoad() {
        super.viewDidLoad()
        preferredContentSize = CGSize(width: 0, height: 50)
    }
}

//MARK: NCWidgetProviding

extension TodayViewController: NCWidgetProviding {

    func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
        completionHandler(.NoData)
    }
}


//
//  TMBarIndicatorContainer.swift
//  Tabman
//
//  Created by Merrick Sapsford on 02/09/2018.
//  Copyright © 2018 UI At Six. All rights reserved.
//

import Foundation

/// Container view that embeds a `TMBarIndicator`.
///
/// Used for providing AutoLayout properties to `TMBarIndicatorLayoutHandler`.
internal final class TMBarIndicatorContainer<Indicator: TMBarIndicator>: UIView {

    // MARK: Properties

    private(set) var layoutHandler: TMBarIndicatorLayoutHandler!

    // MARK: Init

    init(for indicator: Indicator) {
        super.init(frame: .zero)
        isUserInteractionEnabled = false
        layout(indicator: indicator)
    }

    @available(*, unavailable)
    required init?(coder aDecoder: NSCoder) {
        fatalError()
    }

    // MARK: Layout

    private func layout(indicator: Indicator) {
        guard indicator.superview == nil else {
            fatalError("Indicator already has a superview.")
        }

        addSubview(indicator)
        indicator.translatesAutoresizingMaskIntoConstraints = false

        let leading = indicator.leadingAnchor.constraint(equalTo: leadingAnchor)
        let top = indicator.topAnchor.constraint(equalTo: topAnchor)
        let bottom = indicator.bottomAnchor.constraint(equalTo: bottomAnchor)
        let width = indicator.widthAnchor.constraint(equalToConstant: 0.0)

        NSLayoutConstraint.activate([leading, top, bottom, width])
        self.layoutHandler = TMBarIndicatorLayoutHandler(leading: leading,
                                                       width: width)
    }
}

Fix leading constraint for indicator

//
//  TMBarIndicatorContainer.swift
//  Tabman
//
//  Created by Merrick Sapsford on 02/09/2018.
//  Copyright © 2018 UI At Six. All rights reserved.
//

import Foundation

/// Container view that embeds a `TMBarIndicator`.
///
/// Used for providing AutoLayout properties to `TMBarIndicatorLayoutHandler`.
internal final class TMBarIndicatorContainer<Indicator: TMBarIndicator>: UIView {

    // MARK: Properties

    private(set) var layoutHandler: TMBarIndicatorLayoutHandler!

    // MARK: Init

    init(for indicator: Indicator) {
        super.init(frame: .zero)
        isUserInteractionEnabled = false
        layout(indicator: indicator)
    }

    @available(*, unavailable)
    required init?(coder aDecoder: NSCoder) {
        fatalError()
    }

    // MARK: Layout

    private func layout(indicator: Indicator) {
        guard indicator.superview == nil else {
            fatalError("Indicator already has a superview.")
        }

        addSubview(indicator)
        indicator.translatesAutoresizingMaskIntoConstraints = false

        let leading = indicator.leftAnchor.constraint(equalTo: leftAnchor)
        let top = indicator.topAnchor.constraint(equalTo: topAnchor)
        let bottom = indicator.bottomAnchor.constraint(equalTo: bottomAnchor)
        let width = indicator.widthAnchor.constraint(equalToConstant: 0.0)

        NSLayoutConstraint.activate([leading, top, bottom, width])
        self.layoutHandler = TMBarIndicatorLayoutHandler(leading: leading,
                                                       width: width)
    }
}


//
//  Rocket_ChatUITests.swift
//  Rocket.ChatUITests
//
//  Created by Rafael K. Streit on 7/5/16.
//  Copyright © 2016 Rocket.Chat. All rights reserved.
//

import XCTest

class RocketChatUITests: 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.
    }

}

Remove empty UI test to save build time

//
//  Rocket_ChatUITests.swift
//  Rocket.ChatUITests
//
//  Created by Rafael K. Streit on 7/5/16.
//  Copyright © 2016 Rocket.Chat. All rights reserved.
//

import XCTest

class RocketChatUITests: XCTestCase {

}


//
//  RecordingTag.swift
//  sway
//
//  Created by Christopher McMahon on 10/23/15.
//  Copyright © 2015 VCH. All rights reserved.
//

import Foundation
import CoreData

let recordingTagEntityName = "RecordingTag"

let defaultPartTags = [
    "melody", "harmony", "rhythm", "beat", "lead", "ambience", "accompaniment", "effects"
]

let defaultInstrumentTags = [
    "vocals", "guitar", "keyboard", "bass", "percussion", "strings"
]

let defaultFeelTags = [
    "slow", "fast", "medium", "quiet", "loud", "upbeat", "melancholy"
]

let needsTagPrefix = "needs_"

class RecordingTag: NSManagedObject {

    var isNeedsTag: Bool = false

    lazy var baseTag: String? = {
        [unowned self] in
        if let tag = self.tag {
            let asRange = tag.rangeOfString(needsTagPrefix)
            if let asRange = asRange where asRange.startIndex == tag.startIndex {
                self.isNeedsTag = true
                return tag.substringFromIndex(tag.startIndex.advancedBy(needsTagPrefix.characters.count + 1))
            } else {
                return tag
            }
        } else {
            return nil
        }
    }()

}

Fix tag parse bug after removing extra underscore

//
//  RecordingTag.swift
//  sway
//
//  Created by Christopher McMahon on 10/23/15.
//  Copyright © 2015 VCH. All rights reserved.
//

import Foundation
import CoreData

let recordingTagEntityName = "RecordingTag"

let defaultPartTags = [
    "melody", "harmony", "rhythm", "beat", "lead", "ambience", "accompaniment", "effects"
]

let defaultInstrumentTags = [
    "vocals", "guitar", "keyboard", "bass", "percussion", "strings"
]

let defaultFeelTags = [
    "slow", "fast", "medium", "quiet", "loud", "upbeat", "melancholy"
]

let needsTagPrefix = "needs_"

class RecordingTag: NSManagedObject {

    var isNeedsTag: Bool = false

    lazy var baseTag: String? = {
        [unowned self] in
        if let tag = self.tag {
            let asRange = tag.rangeOfString(needsTagPrefix)
            if let asRange = asRange where asRange.startIndex == tag.startIndex {
                self.isNeedsTag = true
                return tag.substringFromIndex(tag.startIndex.advancedBy(needsTagPrefix.characters.count))
            } else {
                return tag
            }
        } else {
            return nil
        }
    }()

}


//
//  GraphSerieSpec.swift
//  SwiftyEcharts
//
//  Created by Pluto Y on 26/10/2017.
//  Copyright © 2017 com.pluto-y. All rights reserved.
//

import Quick
import Nimble
@testable import SwiftyEcharts

class GraphSerieSpec: QuickSpec {
    override func spec() {
        describe("For GraphSerie.Layout") {
            let noneString = "none"
            let circularString = "circular"
            let forceString = "force"

            let noneLayout = GraphSerie.Layout.none
            let circularLayout = GraphSerie.Layout.circular
            let forceLayout = GraphSerie.Layout.force

            it("needs to check the jsonString") {
                expect(noneLayout.jsonString).to(equal(noneString.jsonString))
                expect(circularLayout.jsonString).to(equal(circularString.jsonString))
                expect(forceLayout.jsonString).to(equal(forceString.jsonString))
            }
        }
    }
}

Add test cases for `GraphSerie.Circular`

//
//  GraphSerieSpec.swift
//  SwiftyEcharts
//
//  Created by Pluto Y on 26/10/2017.
//  Copyright © 2017 com.pluto-y. All rights reserved.
//

import Quick
import Nimble
@testable import SwiftyEcharts

class GraphSerieSpec: QuickSpec {
    override func spec() {
        describe("For GraphSerie.Layout") {
            let noneString = "none"
            let circularString = "circular"
            let forceString = "force"

            let noneLayout = GraphSerie.Layout.none
            let circularLayout = GraphSerie.Layout.circular
            let forceLayout = GraphSerie.Layout.force

            it("needs to check the jsonString") {
                expect(noneLayout.jsonString).to(equal(noneString.jsonString))
                expect(circularLayout.jsonString).to(equal(circularString.jsonString))
                expect(forceLayout.jsonString).to(equal(forceString.jsonString))
            }
        }

        let rotateLabelCircularValue = false

        let circular = GraphSerie.Circular()
        circular.rotateLabel = rotateLabelCircularValue

        describe("For GraphSerie.Circular") {
            it("needs to check the jsonString") {
                let resultDic: [String: Jsonable] = [
                    "rotateLabel": rotateLabelCircularValue
                ]

                expect(circular.jsonString).to(equal(resultDic.jsonString))
            }

            it("needs to check the Enumable") {
                let circularByEnums = GraphSerie.Circular(
                    .rotateLabel(rotateLabelCircularValue)
                )

                expect(circularByEnums.jsonString).to(equal(circular.jsonString))
            }
        }
    }
}


//
//  UIViewController+Helpers.swift
//  SwiftPlusPlus
//
//  Created by Andrew J Wagner on 4/2/16.
//  Copyright © 2016 Drewag LLC. All rights reserved.
//

import Foundation

extension UIViewController {
    public func present(popoverViewController viewController: UIViewController, fromSourceView sourceView: UIView, sourceRect: CGRect? = nil, permittedArrowDirections: UIPopoverArrowDirection = .Any) {
        viewController.modalPresentationStyle = .Popover

        self.presentViewController(viewController, animated: true, completion: nil)

        viewController.popoverPresentationController!.permittedArrowDirections = permittedArrowDirections
        viewController.popoverPresentationController!.sourceView = sourceView
        if let sourceRect = sourceRect {
            viewController.popoverPresentationController!.sourceRect = sourceRect
        }
    }

    public func present(overlayViewController viewController: UIViewController) {
        viewController.modalPresentationStyle = .OverCurrentContext
        viewController.modalTransitionStyle = .CrossDissolve

        self.presentViewController(viewController, animated: true, completion: nil)
    }
}

Allow specifying easy popover source positions

//
//  UIViewController+Helpers.swift
//  SwiftPlusPlus
//
//  Created by Andrew J Wagner on 4/2/16.
//  Copyright © 2016 Drewag LLC. All rights reserved.
//

import Foundation

public enum PopoverPosition {
    case Default
    case TopMiddle
    case Custom(sourceRect: CGRect)
}

extension UIViewController {
    public func present(popoverViewController viewController: UIViewController, fromSourceView sourceView: UIView, permittedArrowDirections: UIPopoverArrowDirection = .Any, position: PopoverPosition = .Default) {
        viewController.modalPresentationStyle = .Popover

        self.presentViewController(viewController, animated: true, completion: nil)

        viewController.popoverPresentationController!.permittedArrowDirections = permittedArrowDirections
        viewController.popoverPresentationController!.sourceView = sourceView

        switch position {
        case .Default:
            break
        case .TopMiddle:
            let rect = CGRect(origin: CGPoint(x: sourceView.bounds.midX, y: sourceView.bounds.minY), size: CGSize(width: 1, height: 1))
            viewController.popoverPresentationController!.sourceRect = rect
        case .Custom(sourceRect: let rect):
            viewController.popoverPresentationController!.sourceRect = rect
        }
    }

    public func present(overlayViewController viewController: UIViewController) {
        viewController.modalPresentationStyle = .OverCurrentContext
        viewController.modalTransitionStyle = .CrossDissolve

        self.presentViewController(viewController, animated: true, completion: nil)
    }
}


import Foundation

let count = CommandLine.arguments.count
guard count > 1 else {
    abort()
}

let path = CommandLine.arguments[1]

if CommandLine.arguments.contains("export") {
    Process.launchedProcess(launchPath: "\(path)/scripts/localization_extract", arguments: [path]).waitUntilExit()
    exportLocalizationsFromSourceCode(path)
}

if CommandLine.arguments.contains("import") {
    importLocalizationsFromTWN(path)
}

Revert "run localization_extract along with the export"

import Foundation

let count = CommandLine.arguments.count
guard count > 1 else {
    abort()
}

let path = CommandLine.arguments[1]

//Process.launchedProcess(launchPath: "\(path)/scripts/localization_extract", arguments: [path]).waitUntilExit()

if CommandLine.arguments.contains("export") {
    exportLocalizationsFromSourceCode(path)
}

if CommandLine.arguments.contains("import") {
    importLocalizationsFromTWN(path)
}


// RUN: rm -rf %t
// RUN: mkdir %t
// RUN: %target-build-swift -c -force-single-frontend-invocation -parse-as-library -parse-stdlib -module-name Swift -emit-module -emit-module-path %t/Swift.swiftmodule -o %t/Swift.o %S/Inputs/Swift.swift
// RUN: ls %t/Swift.swiftmodule
// RUN: ls %t/Swift.swiftdoc
// RUN: ls %t/Swift.o
// RUN: %target-clang -x c -c %S/Inputs/RuntimeStubs.c -o %t/RuntimeStubs.o
// RUN: %target-build-swift -I %t -module-name main -o %t/hello %S/Inputs/main.swift %t/Swift.o %t/RuntimeStubs.o
// RUN: %target-run %t/hello | FileCheck %s
// REQUIRES: executable_test
// CHECK: Hello

Disable test to unbreak the builds.

// RUN: rm -rf %t
// RUN: mkdir %t
// RUN: %target-build-swift -c -force-single-frontend-invocation -parse-as-library -parse-stdlib -module-name Swift -emit-module -emit-module-path %t/Swift.swiftmodule -o %t/Swift.o %S/Inputs/Swift.swift
// RUN: ls %t/Swift.swiftmodule
// RUN: ls %t/Swift.swiftdoc
// RUN: ls %t/Swift.o
// RUN: %target-clang -x c -c %S/Inputs/RuntimeStubs.c -o %t/RuntimeStubs.o
// RUN: %target-build-swift -I %t -module-name main -o %t/hello %S/Inputs/main.swift %t/Swift.o %t/RuntimeStubs.o
// RUN: %target-run %t/hello | FileCheck %s
// REQUIRES: executable_test
// CHECK: Hello
// REQUIRES: rdar27558848


//
//  UIFont+Extensions.swift
//  Kerner
//
//  Created by Taishi Ikai on 2017/09/02.
//  Copyright © 2017年 Ikai. All rights reserved.
//

import UIKit
import CoreText

public extension UIFont {

    public var altHalf: UIFont {

        let featureSettings: [[UIFontDescriptor.FeatureKey: Int]] = [
            [
                .featureIdentifier: kTextSpacingType,
                .typeIdentifier: kAltHalfWidthTextSelector
            ]
        ]

        var attributes = self.fontDescriptor.fontAttributes

        attributes[.family] = self.familyName.starts(with: ".SF") ? "Hiragino Sans" : self.familyName
        attributes[.featureSettings] = featureSettings

        return UIFont(descriptor: UIFontDescriptor(fontAttributes: attributes),
                      size: self.pointSize)
    }
}

Modify to respect original font weight

//
//  UIFont+Extensions.swift
//  Kerner
//
//  Created by Taishi Ikai on 2017/09/02.
//  Copyright © 2017年 Ikai. All rights reserved.
//

import UIKit
import CoreText

public extension UIFont {

    public var altHalf: UIFont {

        let weight: UIFont.Weight = {

            var weight = UIFont.Weight.regular

            let usageAttribute = self.fontDescriptor.fontAttributes[
                .init(rawValue: "NSCTFontUIUsageAttribute")] as? String ?? ""

            switch usageAttribute {
                case "CTFontEmphasizedUsage", "CTFontBoldUsage":
                    weight = .bold
                default:
                    break
            }

            return weight
        }()

        let familyName = self.familyName.starts(with: ".SF") ? "Hiragino Sans" : self.familyName

        let featureSettings: [[UIFontDescriptor.FeatureKey: Int]] = [
            [
                .featureIdentifier: kTextSpacingType,
                .typeIdentifier: kAltHalfWidthTextSelector
            ]
        ]

        let traits: [UIFontDescriptor.TraitKey: CGFloat] = [
            .weight: weight.rawValue
        ]

        let fontDescriptor = UIFontDescriptor(fontAttributes: [
            .family: familyName,
            .traits: traits,
            .featureSettings: featureSettings,
        ])

        return UIFont(descriptor: fontDescriptor, size: self.pointSize)
    }
}


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

// Random access for String.UTF16View, only when Foundation is
// imported.  Making this API dependent on Foundation decouples the
// Swift core from a UTF16 representation.
extension String.UTF16View.Index : Strideable {
    /// Construct from an integer offset.
    public init(_ offset: Int) {
        _precondition(offset >= 0, "Negative UTF16 index offset not allowed")
        self.init(encodedOffset: offset)
    }

    public func distance(to other: String.UTF16View.Index) -> Int {
        return encodedOffset.distance(to: other.encodedOffset)
    }

    public func advanced(by n: Int) -> String.UTF16View.Index {
        return String.UTF16View.Index(encodedOffset.advanced(by: n))
    }
}

extension String.UTF16View : RandomAccessCollection {}
extension String.UTF16View.Indices : RandomAccessCollection {}

Drop RandomAccessCollection conformance for String.UTF16View


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

public typealias ConstraintSet = Multiset<Constraint>

public func typeOf(expression: Expression) -> Either<Error, (Type, AssumptionSet, ConstraintSet)> {
	return expression.analysis(
		ifVariable: { v in
			let type = Type(Variable())
			return .right(type, [ v: [ Scheme([], type) ] ], [])
		},
		ifAbstraction: const(.left("unimplemented")),
		ifApplication: { e1, e2 in (typeOf(e1) && typeOf(e2)) >>- { e1, e2 in
			let type = Type(Variable())
			let c = Constraint(equality: e1.0, e2.0 --> type)
			return .right(type, e1.1 + e2.1, e1.2 + e2.2 + [ c ]) }
		})
}

// MARK: - Imports

import Either
import Prelude
import Set

Use === to construct constraints.

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

public typealias ConstraintSet = Multiset<Constraint>

public func typeOf(expression: Expression) -> Either<Error, (Type, AssumptionSet, ConstraintSet)> {
	return expression.analysis(
		ifVariable: { v in
			let type = Type(Variable())
			return .right(type, [ v: [ Scheme([], type) ] ], [])
		},
		ifAbstraction: const(.left("unimplemented")),
		ifApplication: { e1, e2 in (typeOf(e1) && typeOf(e2)) >>- { e1, e2 in
			let type = Type(Variable())
			let c = e1.0 === (e2.0 --> type)
			return .right(type, e1.1 + e2.1, e1.2 + e2.2 + [ c ]) }
		})
}

// MARK: - Imports

import Either
import Prelude
import Set


import XCTest

class TCHome:XCTestCase
{

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

Add test for loading session

import XCTest
@testable import gattaca

class TCHome:XCTestCase
{
    private var session:MSession?
    private var controller:CHome?
    private let kWaitSession:UInt32 = 3

    override func setUp()
    {
        super.setUp()

        let session:MSession = MSession()
        self.session = session
        controller = CHome(session:session)
    }

    func testSessionLoads()
    {
        sleep(kWaitSession)

        guard

            let status:MSession.Status = session?.status

        else
        {
            return
        }

        XCTAssertEqual(
            status,
            MSession.Status.loaded,
            "session is not being loaded")
    }
}


//
//  ChapterViewModel.swift
//  Yomu
//
//  Created by Sendy Halim on 7/6/16.
//  Copyright © 2016 Sendy Halim. All rights reserved.
//

import RxCocoa
import RxMoya
import RxSwift

struct ChapterViewModel {
  private let _chapter: Variable<Chapter>
  private let _previewUrl = Variable(ImageUrl(endpoint: ""))

  var previewUrl: Driver<NSURL> {
    return _previewUrl
      .asDriver()
      .filter { $0.endpoint.characters.count != 0 }
      .map { $0.url }
  }

  var title: Driver<String> {
    return _chapter.asDriver().map { $0.title }
  }

  var chapter: Chapter {
    return _chapter.value
  }

  init(chapter: Chapter) {
    _chapter = Variable(chapter)
  }

  func fetchPreview() -> Disposable {
    let id = _chapter.value.id

    return MangaEden
      .request(MangaEdenAPI.ChapterPages(id))
      .mapArray(ChapterPage.self, withRootKey: "images")
      .subscribeNext {
        let sortedPages = $0.sort {
          let (x, y) = $0

          return x.number < y.number
        }

        self._previewUrl.value = sortedPages.first!.image
    }
  }
}

Add method to check if chapter title contains the given string

//
//  ChapterViewModel.swift
//  Yomu
//
//  Created by Sendy Halim on 7/6/16.
//  Copyright © 2016 Sendy Halim. All rights reserved.
//

import RxCocoa
import RxMoya
import RxSwift

struct ChapterViewModel {
  private let _chapter: Variable<Chapter>
  private let _previewUrl = Variable(ImageUrl(endpoint: ""))

  var previewUrl: Driver<NSURL> {
    return _previewUrl
      .asDriver()
      .filter { $0.endpoint.characters.count != 0 }
      .map { $0.url }
  }

  var title: Driver<String> {
    return _chapter.asDriver().map { $0.title }
  }

  var chapter: Chapter {
    return _chapter.value
  }

  init(chapter: Chapter) {
    _chapter = Variable(chapter)
  }

  func titleContains(pattern: String) -> Bool {
    return _chapter.value.title.lowercaseString.containsString(pattern)
  }

  func fetchPreview() -> Disposable {
    let id = _chapter.value.id

    return MangaEden
      .request(MangaEdenAPI.ChapterPages(id))
      .mapArray(ChapterPage.self, withRootKey: "images")
      .subscribeNext {
        let sortedPages = $0.sort {
          let (x, y) = $0

          return x.number < y.number
        }

        self._previewUrl.value = sortedPages.first!.image
    }
  }
}


//
//  HTTPMethod.swift
//  Swiftlier
//
//  Created by Andrew J Wagner on 10/10/17.
//

public enum HTTPMethod: String {
    case any

    case get
    case post
    case put
    case delete
    case options
    case patch
}

extension HTTPMethod {
    public func matches(_ other: HTTPMethod) -> Bool {
        switch self {
        case .any:
            return true
        case .get:
            switch other {
            case .get, .any:
                return true
            default:
                return false
            }
        case .post:
            switch other {
            case .post, .any:
                return true
            default:
                return false
            }
        case .put:
            switch other {
            case .put, .any:
                return true
            default:
                return false
            }
        case .delete:
            switch other {
            case .delete, .any:
                return true
            default:
                return false
            }
        case .options:
            switch other {
            case .options, .any:
                return true
            default:
                return false
            }
        case .patch:
            switch other {
            case .patch, .any:
                return true
            default:
                return false
            }
        }
    }
}

Make HTTP methods upper case

//
//  HTTPMethod.swift
//  Swiftlier
//
//  Created by Andrew J Wagner on 10/10/17.
//

public enum HTTPMethod: String {
    case any = "ANY"

    case get = "GET"
    case post = "POST"
    case put = "PUT"
    case delete = "DELETE"
    case options = "OPTIONS"
    case patch = "PATCH"
}

extension HTTPMethod {
    public func matches(_ other: HTTPMethod) -> Bool {
        switch self {
        case .any:
            return true
        case .get:
            switch other {
            case .get, .any:
                return true
            default:
                return false
            }
        case .post:
            switch other {
            case .post, .any:
                return true
            default:
                return false
            }
        case .put:
            switch other {
            case .put, .any:
                return true
            default:
                return false
            }
        case .delete:
            switch other {
            case .delete, .any:
                return true
            default:
                return false
            }
        case .options:
            switch other {
            case .options, .any:
                return true
            default:
                return false
            }
        case .patch:
            switch other {
            case .patch, .any:
                return true
            default:
                return false
            }
        }
    }
}


//
//  SwitchStyle.swift
//  Nori
//
//  Created by yukiasai on 11/22/16.
//  Copyright © 2016 yukiasai. All rights reserved.
//

public class SwitchStyle: ViewStyle {
    var onTintColor: UIColor?
}

Access control of properties to public, and make initializer

//
//  SwitchStyle.swift
//  Nori
//
//  Created by yukiasai on 11/22/16.
//  Copyright © 2016 yukiasai. All rights reserved.
//

public class SwitchStyle: ViewStyle {
    public var onTintColor: UIColor?

    public convenience init(closure: (SwitchStyle) -> Void) {
        self.init()
        closure(self)
    }
}


// swift-tools-version:4.2
import PackageDescription

let package = Package(
    name: "KeychainSwift",
    products: [
        .library(name: "KeychainSwift", targets: ["KeychainSwift"]),
    ],
    dependencies: [
    ],
    targets: [
        .target(name: "KeychainSwift", dependencies: [], path: "Sources"),
        .testTarget(name: "KeychainSwiftTests", dependencies: ["KeychainSwift"])
    ]
)

Exclude ClearTests from SPM test target

// swift-tools-version:4.2
import PackageDescription

let package = Package(
    name: "KeychainSwift",
    products: [
        .library(name: "KeychainSwift", targets: ["KeychainSwift"]),
    ],
    dependencies: [
    ],
    targets: [
        .target(name: "KeychainSwift", dependencies: [], path: "Sources"),
        .testTarget(
            name: "KeychainSwiftTests",
            dependencies: ["KeychainSwift"],
            exclude: ["ClearTests.swift"]
        )
    ]
)


// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 -swift-version 4
// REQUIRES: tools-release,no_asserts

let _ = 1 | UInt32(0) << 0 | UInt32(1) << 1 | UInt32(2) << 2
// expected-error@-1 {{reasonable time}}

Make test-case for rdar://problem/33688063 more complicated

// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 -swift-version 4
// REQUIRES: tools-release,no_asserts

let _ = 1 | UInt32(0) << 0 | UInt32(1) << 1 | UInt32(2) << 2 | UInt32(3) << 3 | UInt32(4) << 4
// expected-error@-1 {{reasonable time}}


//
//  AccountHeaderImageView.swift
//  Multiplatform iOS
//
//  Created by Rizwan on 08/07/20.
//  Copyright © 2020 Ranchero Software. All rights reserved.
//

import SwiftUI
import RSCore

struct AccountHeaderImageView: View {
	var image: RSImage

    var body: some View {
		HStack {
			Spacer()
			Image(rsImage: image)
				.resizable()
				.aspectRatio(1, contentMode: .fit)
				.frame(height: 48, alignment: .center)
				.padding()
			Spacer()
		}
    }
}

struct AccountHeaderImageView_Previews: PreviewProvider {
    static var previews: some View {
		AccountHeaderImageView(image: AppAssets.image(for: .onMyMac)!)
    }
}

Add simplified Account Header image view without stacks

//
//  AccountHeaderImageView.swift
//  Multiplatform iOS
//
//  Created by Rizwan on 08/07/20.
//  Copyright © 2020 Ranchero Software. All rights reserved.
//

import SwiftUI
import RSCore

struct AccountHeaderImageView: View {
	var image: RSImage

	var body: some View {
		Image(rsImage: image)
			.resizable()
			.aspectRatio(1, contentMode: .fit)
			.frame(height: 48, alignment: .center)
			.padding()

	}
}

struct AccountHeaderImageView_Previews: PreviewProvider {
	static var previews: some View {
		AccountHeaderImageView(image: AppAssets.image(for: .onMyMac)!)
	}
}


import UIKit

extension VCreateTravelBackground
{
    struct Constants
    {
        static let alpha:CGFloat = 0.98
    }
}

Fix blur in travel view

import UIKit

extension VCreateTravelBackground
{
    struct Constants
    {
        static let alpha:CGFloat = 0.999
    }
}


//
//  Constants.swift
//  ParkenDD
//
//  Created by Kilian Költzsch on 08/03/15.
//  Copyright (c) 2015 Kilian Koeltzsch. All rights reserved.
//

/**
*  Stores global constants like the API Server URL
*/
struct Constants {
	static var parkinglotURL = "http://jkliemann.de/offenesdresden.de/json.php"
}

Add URL for optional notifications

//
//  Constants.swift
//  ParkenDD
//
//  Created by Kilian Költzsch on 08/03/15.
//  Copyright (c) 2015 Kilian Koeltzsch. All rights reserved.
//

/**
*  Stores global constants like the API Server URL
*/
struct Constants {
	static var parkinglotURL = "http://jkliemann.de/offenesdresden.de/json.php"
	static var notificationURL = "http://parkendd.kilian.io/notification.json"
}


//
//  SocketError.swift
//  Rocket.Chat
//
//  Created by Matheus Cardoso on 10/16/17.
//  Copyright © 2017 Rocket.Chat. All rights reserved.
//

import SwiftyJSON

extension SocketError {
    enum Error {
        case invalidSession
        case other(String)

        init(rawValue: String) {
            switch rawValue {
            case "403":
                self = .invalidSession
            default:
                self = .other(rawValue)
            }
        }
    }
}

extension SocketError {
    struct Details {
        let method: String
        init(json: JSON) {
            method = json["method"].stringValue
        }
    }
}

struct SocketError {
    let details: SocketError.Details
    let error: SocketError.Error
    let reason: String
    let message: String
    let type: String
    let isClientSafe: Bool

    init(json: JSON) {
        details = SocketError.Details(json: json["details"])
        error = SocketError.Error(rawValue: json["error"].stringValue)
        reason = json["reason"].stringValue
        message = json["message"].stringValue
        type = json["errorType"].stringValue
        isClientSafe = json["isClientSafe"].boolValue
    }
}

Add 401 as an invalid session error on mapping

//
//  SocketError.swift
//  Rocket.Chat
//
//  Created by Matheus Cardoso on 10/16/17.
//  Copyright © 2017 Rocket.Chat. All rights reserved.
//

import SwiftyJSON

extension SocketError {
    enum Error {
        case invalidSession
        case other(String)

        init(rawValue: String) {
            switch rawValue {
            case "403", "401":
                self = .invalidSession
            default:
                self = .other(rawValue)
            }
        }
    }
}

extension SocketError {
    struct Details {
        let method: String
        init(json: JSON) {
            method = json["method"].stringValue
        }
    }
}

struct SocketError {
    let details: SocketError.Details
    let error: SocketError.Error
    let reason: String
    let message: String
    let type: String
    let isClientSafe: Bool

    init(json: JSON) {
        details = SocketError.Details(json: json["details"])
        error = SocketError.Error(rawValue: json["error"].stringValue)
        reason = json["reason"].stringValue
        message = json["message"].stringValue
        type = json["errorType"].stringValue
        isClientSafe = json["isClientSafe"].boolValue
    }
}


//
//  PasteboardServiceTests.swift
//  PasteFlow
//
//  Created by Agnes Vasarhelyi on 06/12/15.
//  Copyright © 2015 Agnes Vasarhelyi. All rights reserved.
//

import XCTest
import VinceRP
@testable import PasteFlow

class PasteboardServiceTests: XCTestCase {

    let pasteboardService = PasteboardService()

    override func setUp() {
        super.setUp()
        pasteboardService.pasteboardItems <- [.Text("paste")]
    }

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

    func testpollPasteboardItems() {
        pasteboardService.addItemToPasteboard(.Text("flow"))
        pasteboardService.pollPasteboardItems()

        XCTAssertTrue(pasteboardService.pasteboardItems.value()[0] == .Text("flow"), "it should poll new items")
    }
}

Test for adding items to pasteboard

//
//  PasteboardServiceTests.swift
//  PasteFlow
//
//  Created by Agnes Vasarhelyi on 06/12/15.
//  Copyright © 2015 Agnes Vasarhelyi. All rights reserved.
//

import XCTest
import VinceRP
@testable import PasteFlow

class PasteboardServiceTests: XCTestCase {

    let pasteboardService = PasteboardService()

    override func setUp() {
        super.setUp()
        pasteboardService.pasteboard.clearContents()
        pasteboardService.pasteboardItems <- [.Text("paste")]
    }

    func addItemToPasteboard() {
        pasteboardService.addItemToPasteboard(.Text("flow"))
        XCTAssertTrue(pasteboardService.pasteboardItems.value()[0] == .Text("flow"), "it should add new items")
    }

    func testpollPasteboardItems() {
        pasteboardService.pasteboard.writeObjects(["flow" as NSPasteboardWriting])
        pasteboardService.pollPasteboardItems()

        XCTAssertTrue(pasteboardService.pasteboardItems.value()[0] == .Text("flow"), "it should poll new items")
    }
}


import XCTest

class TMGiphyRandom:XCTestCase
{
}

Test factory url and request

import XCTest
@testable import gattaca

class TMGiphyRandom:XCTestCase
{
    //MARK: internal

    func testFactoryUrl()
    {
        let url:URL? = MGiphy.factoryRandomUrl()

        XCTAssertNotNil(
            url,
            "failed factorying url")
    }

    func testFactoryRequest()
    {
        let request:URLRequest? = MGiphy.factoryRandomRequest()

        XCTAssertNotNil(
            request,
            "failed factorying request")
    }
}


//
//  POSIXError.swift
//  SwiftySockets
//
//  Created by Michael Ferenduros on 08/08/2016.
//  Copyright © 2016 Mike Ferenduros. All rights reserved.
//

import Foundation

#if os(Linux)
protocol LocalizedError : Error { }
#endif

public struct POSIXError : LocalizedError, Equatable, CustomDebugStringConvertible {

    public let code: Int32

    public var errorDescription: String? {
        return String(cString: strerror(code))
    }

    public var debugDescription: String {
        return "POSIXError(\(code)): \(errorDescription!)"
    }

    public init(_ code: Int32) {
        self.code = code
    }

    public static func ==(lhs: POSIXError, rhs: POSIXError) -> Bool {
        return lhs.code == rhs.code
    }

    public static func ~=(lhs: POSIXError, rhs: Error) -> Bool {
        return lhs == (rhs as? POSIXError)
    }
}

Remove hack for missing Linux API

//
//  POSIXError.swift
//  SwiftySockets
//
//  Created by Michael Ferenduros on 08/08/2016.
//  Copyright © 2016 Mike Ferenduros. All rights reserved.
//

import Foundation

public struct POSIXError : LocalizedError, Equatable, CustomDebugStringConvertible {

    public let code: Int32

    public var errorDescription: String? {
        return String(cString: strerror(code))
    }

    public var debugDescription: String {
        return "POSIXError(\(code)): \(errorDescription!)"
    }

    public init(_ code: Int32) {
        self.code = code
    }

    public static func ==(lhs: POSIXError, rhs: POSIXError) -> Bool {
        return lhs.code == rhs.code
    }

    public static func ~=(lhs: POSIXError, rhs: Error) -> Bool {
        return lhs == (rhs as? POSIXError)
    }
}


extension SurveyResponse {
  internal static let template = SurveyResponse(
    answeredAt: nil,
    id: 1,
    project: .template,
    urls: SurveyResponse.UrlsEnvelope(
      web: SurveyResponse.UrlsEnvelope.WebEnvelope(
        survey: "http://www.surveys.com"
      )
    )
  )
}

Use more realistic survey link

extension SurveyResponse {
  internal static let template = SurveyResponse(
    answeredAt: nil,
    id: 1,
    project: .template,
    urls: SurveyResponse.UrlsEnvelope(
      web: SurveyResponse.UrlsEnvelope.WebEnvelope(
        survey: "https://www.kickstarter.com/projects/creator/project/surveys/1"
      )
    )
  )
}


import Foundation
import XCTest

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

#if SWIFT_PACKAGE

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

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

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

    guard classesCount > 0 else {
        return
    }

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

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

        if let superclass = class_getSuperclass(subclass), superclass === klass {
            block(subclass as! T.Type) // swiftlint:disable:this force_cast
        }
    }

    free(classes)
}

#endif

#endif

Fix releasing the object too fast

import Foundation
import XCTest

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

#if SWIFT_PACKAGE

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

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

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

    guard classesCount > 0 else {
        return
    }

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

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

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

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

    free(classes)
}

#endif

#endif


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

import Foundation
import SWCompression
import SwiftCLI

/* TODO: Switch to usage of Bundle.allBundles() function of Foundation framework when it becomes implemented.*/
// Version constants:
let SWCompressionVersion = "3.4.0"
let swcompRevision = "88"

CLI.setup(name: "swcomp",
          version: "\(swcompRevision), SWCompression version: \(SWCompressionVersion)",
          description: "swcomp - small command-line client for SWCompression framework.")
SwiftCLI.GlobalOptions.source(GlobalOptions.self)
CLI.register(commands: [XZCommand(),
                        LZMACommand(),
                        BZip2Command(),
                        CompressBZip2Command(),
                        GZipCommand(),
                        CompressGZipCommand(),
                        ZipCommand(),
                        TarCommand(),
                        SevenZipCommand()])
_ = CLI.go()

Remove swcomp revision and update swcomp's description

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

import Foundation
import SWCompression
import SwiftCLI

CLI.setup(name: "swcomp",
          version: "3.4.0",
          description: """
                       swcomp - small command-line client for SWCompression framework.
                       Serves as an example of SWCompression usage.
                       """)
SwiftCLI.GlobalOptions.source(GlobalOptions.self)
CLI.register(commands: [XZCommand(),
                        LZMACommand(),
                        BZip2Command(),
                        CompressBZip2Command(),
                        GZipCommand(),
                        CompressGZipCommand(),
                        ZipCommand(),
                        TarCommand(),
                        SevenZipCommand()])
_ = CLI.go()


//
//  Network.swift
//  Engine
//
//  Created by Paul Young on 15/11/2014.
//  Copyright (c) 2014 CocoaFlow. All rights reserved.
//

import Foundation

final public class Network {
    public init() {}

    // MARK: - Processes
    private var processes: [Int:Component] = [:]

    public func addNode<T: Component>(name: String, _ component: T.Type) -> T {
        let process = component(self)
        let id: Int = ObjectIdentifier(process).hashValue
        processes[id] = process
        return process
    }

    // MARK: - Connections
    private var connections: [Int:Port] = [:]

    public func addEdge<T>(fromPort: OutPort<T>, _ toPort: InPort<T>) {
        connections[fromPort.id] = toPort
    }

    // MARK - Sending
    public func send<T>(outPort: OutPort<T>, _ packet: T) {
        if let inPort = connections[outPort.id] as? InPort<T> {
            inPort.receive(packet)
        }
        else {
            println("Unconnected out port on \"\(outPort.process)\" tried to send a packet.")
        }
    }
}

Add newline to end of file.


import Foundation

public struct Transcoder<Input, Output> {
  let encoder: (Input) throws -> Output
  let decoder: (Output) throws -> (Input)

  public func encode(_ input: Input) throws -> Output {
    return try encoder(input)
  }

  public func decode(_ output: Output) throws -> Input{
    return try decoder(output)
  }
}

public func + <A,B,C>(lhs: Transcoder<A,B>, rhs: Transcoder<B,C>) -> Transcoder<A,C> {
  return .init(encoder: { (a: A) -> C in try rhs.encode(lhs.encode(a)) },
               decoder: { (c: C) -> A in try lhs.decode(rhs.decode(c)) })
}

Add builders for common transcoder types.

import Foundation
import Yams

public struct Transcoder<Input, Output> {
  let encoder: (Input) throws -> Output
  let decoder: (Output) throws -> (Input)

  public func encode(_ input: Input) throws -> Output {
    return try encoder(input)
  }

  public func decode(_ output: Output) throws -> Input{
    return try decoder(output)
  }
}

public func + <A,B,C>(lhs: Transcoder<A,B>, rhs: Transcoder<B,C>) -> Transcoder<A,C> {
  return .init(encoder: { (a: A) -> C in try rhs.encode(lhs.encode(a)) },
               decoder: { (c: C) -> A in try lhs.decode(rhs.decode(c)) })
}

extension Transcoder {
  public static var taskToYaml: Transcoder<[Task], String> {
    return taskToNodes + nodeListToNode + nodeToString
  }

  public static var stringToData: Transcoder<String, Data> {
    return .init(encoder: { $0.data(using: .utf8) ?? Data() },
                 decoder: { String(data: $0, encoding: .utf8) ?? "" })
  }
}

// Implementation for coding between Tasks and Yaml Strings.
extension Transcoder {
  static var taskToNodes: Transcoder<[Task], [Node]> {
    return .init(encoder: { try $0.map { task in try task.represented() } },
                 decoder: { $0.flatMap(Task.init(from:)) })
  }

  static var nodeListToNode: Transcoder<[Node], Node> {
    return .init(encoder: { try $0.represented() },
                 decoder: { node in
                   switch node {
                   case .sequence(let list, _, _):
                     return list
                   case .scalar("null", _, _):
                     return []
                   default:
                     return [node]
                   }
                 })
  }

  static var nodeToString: Transcoder<Node, String> {
    return .init(encoder: { try Yams.dump(object: $0) },
                 decoder: { try Yams.load(yaml: $0).represented() })
  }
}


import UIKit

class SCGameRoomViewCell: UICollectionViewCell {
    @IBOutlet weak var wordLabel: SCLabel!

    override func awakeFromNib() {
        self.wordLabel.font = SCFonts.smallSizeFont(.medium)
        self.contentView.layer.borderWidth = 1.0
        self.contentView.layer.borderColor = UIColor.spycodesGrayColor().cgColor
        self.contentView.layer.cornerRadius = 5.0
        self.contentView.layer.masksToBounds = true

        self.layer.masksToBounds = false
    }
}

Update look of game view cell

import UIKit

class SCGameRoomViewCell: UICollectionViewCell {
    @IBOutlet weak var wordLabel: SCLabel!

    override func awakeFromNib() {
        self.wordLabel.font = SCFonts.smallSizeFont(.bold)
        self.contentView.layer.borderWidth = 2.0
        self.contentView.layer.borderColor = UIColor.spycodesBorderColor().cgColor
        self.contentView.layer.cornerRadius = 5.0
        self.contentView.layer.masksToBounds = true

        self.layer.masksToBounds = false
    }
}


import Foundation
import APIKit
import Himotoki

public protocol GarageRequestParameterContainer {
    var method: HTTPMethod { get }
    var path: String { get }
    var decodeRootKeyPath: KeyPath? { get }
    var queryParameters: [String: Any]? { get }
    var bodyParameters: BodyParameters? { get }
    var headerFields: [String: String] { get }

    func intercept(urlRequest: NSMutableURLRequest) throws -> NSMutableURLRequest
}

public extension GarageRequestParameterContainer {

    public var rootKeyPath: [String]? {
        return nil
    }

    public var queryParameters: [String: Any]? {
        return nil
    }

    public var bodyParameters: BodyParameters? {
        return nil
    }

    public var headerFields: [String: String] {
        return [:]
    }

    public func intercept(urlRequest: NSMutableURLRequest) throws -> NSMutableURLRequest {
        return urlRequest
    }
}

public protocol GarageRequest: GarageRequestParameterContainer {
    associatedtype Resource
}

Fix decode root key path default value.

import Foundation
import APIKit
import Himotoki

public protocol GarageRequestParameterContainer {
    var method: HTTPMethod { get }
    var path: String { get }
    var decodeRootKeyPath: KeyPath? { get }
    var queryParameters: [String: Any]? { get }
    var bodyParameters: BodyParameters? { get }
    var headerFields: [String: String] { get }

    func intercept(urlRequest: NSMutableURLRequest) throws -> NSMutableURLRequest
}

public extension GarageRequestParameterContainer {

    public var decodeRootKeyPath: KeyPath? {
        return nil
    }

    public var queryParameters: [String: Any]? {
        return nil
    }

    public var bodyParameters: BodyParameters? {
        return nil
    }

    public var headerFields: [String: String] {
        return [:]
    }

    public func intercept(urlRequest: NSMutableURLRequest) throws -> NSMutableURLRequest {
        return urlRequest
    }
}

public protocol GarageRequest: GarageRequestParameterContainer {
    associatedtype Resource
}


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

import Quick
import Nimble
import PROJECT

class TableOfContentsSpec: QuickSpec {
    override func spec() {
        describe("these will fail") {

            it("can do maths") {
                expect(1) == 2
            }

            it("can read") {
                expect("number") == "string"
            }

            it("will eventually fail") {
                expect("time").toEventually( equal("done") )
            }
        }

        context("these will pass") {

            it("can do maths") {
                expect(23) == 23
            }

            it("can read") {
                expect("🐮") == "🐮"
            }

            it("will eventually pass") {
                var time = "passing"

                dispatch_async(dispatch_get_main_queue()) {
                    time = "done"
                }

                waitUntil { done in
                    NSThread.sleepForTimeInterval(0.5)
                    expect(time) == "done"

                    done()
                }
            }
        }
    }
}

Move context within describe, so tests will be run.

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

import Quick
import Nimble
import PROJECT

class TableOfContentsSpec: QuickSpec {
    override func spec() {
        describe("these will fail") {

            it("can do maths") {
                expect(1) == 2
            }

            it("can read") {
                expect("number") == "string"
            }

            it("will eventually fail") {
                expect("time").toEventually( equal("done") )
            }

            context("these will pass") {

                it("can do maths") {
                    expect(23) == 23
                }

                it("can read") {
                    expect("🐮") == "🐮"
                }

                it("will eventually pass") {
                    var time = "passing"

                    dispatch_async(dispatch_get_main_queue()) {
                        time = "done"
                    }

                    waitUntil { done in
                        NSThread.sleepForTimeInterval(0.5)
                        expect(time) == "done"

                        done()
                    }
                }
            }
        }
    }
}


import Quick
import Nimble
import Foundation

class ValidatorsFactorySpec: QuickSpec {

    override func spec() {
        var factory: ValidatorsFactory!

        beforeEach {
            factory = ValidatorsFactory.sharedInstance
        }

        describe("sharedInstance") {
            it("returns the same instance every time") {
                let factory1 = ValidatorsFactory.sharedInstance
                let factory2 = ValidatorsFactory.sharedInstance
                expect(factory1).to(beIdenticalTo(factory2))
            }
        }

        describe("registrationValidator") {
            var registrationValidator: RegistrationValidator!

            beforeEach {
                registrationValidator = factory.registrationValidator()
            }

            it("is not nil") {
                expect(registrationValidator).toNot(beNil())
            }
        }

        describe("settingsValidator") {
            var settingsValidator: SettingsValidator!

            beforeEach {
                settingsValidator = factory.settingsValidator()
            }

            it("is not nil") {
                expect(settingsValidator).toNot(beNil())
            }
        }

        describe("phoneNumberValidator") {
            var phoneNumberValidator: CompositeValidator!

            beforeEach {
                phoneNumberValidator = factory.phoneNumberValidator()
            }

            it("is not nil") {
                expect(phoneNumberValidator).toNot(beNil())
            }
        }

        describe("emailValidator") {
            var emailValidator: CompositeValidator!

            beforeEach {
                emailValidator = factory.emailValidator()
            }

            it("is not nil") {
                expect(emailValidator).toNot(beNil())
            }
        }
    }
}

Clean up tests for the validators factory

import Quick
import Nimble

class ValidatorsFactorySpec: QuickSpec {

    override func spec() {
        var factory: ValidatorsFactory!

        beforeEach {
            factory = ValidatorsFactory.sharedInstance
        }

        describe("sharedInstance") {
            it("returns the same instance every time") {
                let factory1 = ValidatorsFactory.sharedInstance
                let factory2 = ValidatorsFactory.sharedInstance
                expect(factory1).to(beIdenticalTo(factory2))
            }
        }

        describe("registrationValidator") {
            it("is not nil") {
                let registrationValidator = factory.registrationValidator()
                expect(registrationValidator).toNot(beNil())
            }
        }

        describe("settingsValidator") {
            it("is not nil") {
                let settingsValidator = factory.settingsValidator()
                expect(settingsValidator).toNot(beNil())
            }
        }

        describe("phoneNumberValidator") {
            it("is not nil") {
                let phoneNumberValidator = factory.phoneNumberValidator()
                expect(phoneNumberValidator).toNot(beNil())
            }
        }

        describe("emailValidator") {
            it("is not nil") {
                let emailValidator = factory.emailValidator()
                expect(emailValidator).toNot(beNil())
            }
        }
    }
}


//
//  Router.swift
//  HackTX
//
//  Created by Drew Romanyk on 9/6/15.
//  Copyright (c) 2015 HackTX. All rights reserved.
//

import Foundation
import Alamofire

enum Router: URLRequestConvertible {
    static let baseURLString = "https://my.hacktx.com/api"

    case Schedule(String)
    case Announcements()
    case Partners()
    case Feedback([String: Int])

    var method: Alamofire.Method {
        switch self {
        case .Schedule:
            return .GET
        case .Announcements:
            return .GET
        case .Partners:
            return .GET
        case .Feedback:
            return .POST
        }
    }

    var path: String {
        switch self {
        case .Schedule(let dayId):
            return "/schedule/\(dayId)"
        case .Announcements():
            return "/announcements"
        case .Partners():
            return "/sponsors"
        case .Feedback:
            return "/feedback"
        }
    }

    // MARK: URLRequestConvertible

    var URLRequest: NSURLRequest {
        let URL = NSURL(string: Router.baseURLString)!
        let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
        mutableURLRequest.HTTPMethod = method.rawValue

        switch self {
        case .Feedback(let parameters):
            return ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0
        default:
            return mutableURLRequest
        }
    }
}

Change url request to be mutable

//
//  Router.swift
//  HackTX
//
//  Created by Drew Romanyk on 9/6/15.
//  Copyright (c) 2015 HackTX. All rights reserved.
//

import Foundation
import Alamofire

enum Router: URLRequestConvertible {
    static let baseURLString = "https://my.hacktx.com/api"

    case Schedule(String)
    case Announcements()
    case Partners()
    case Feedback([String: Int])

    var method: Alamofire.Method {
        switch self {
        case .Schedule:
            return .GET
        case .Announcements:
            return .GET
        case .Partners:
            return .GET
        case .Feedback:
            return .POST
        }
    }

    var path: String {
        switch self {
        case .Schedule(let dayId):
            return "/schedule/\(dayId)"
        case .Announcements():
            return "/announcements"
        case .Partners():
            return "/sponsors"
        case .Feedback:
            return "/feedback"
        }
    }

    // MARK: URLRequestConvertible

    var URLRequest: NSMutableURLRequest {
        let URL = NSURL(string: Router.baseURLString)!
        let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
        mutableURLRequest.HTTPMethod = method.rawValue

        switch self {
        case .Feedback(let parameters):
            return ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0
        default:
            return mutableURLRequest
        }
    }
}


import XCTest
@testable import SwiftConfigurationTests

XCTMain([
    testCase(ConfigurationNodeTest.allTests),
    testCase(ConfigurationManagerTest.allTests),
])

Fix unit test on Linux

import XCTest
@testable import ConfigurationTests

XCTMain([
    testCase(ConfigurationNodeTest.allTests),
    testCase(ConfigurationManagerTest.allTests),
])