//
//  BundleResourceLoader.swift
//  AlliCrab
//
//  Copyright © 2016 Chris Laverty. All rights reserved.
//

import Foundation

protocol BundleResourceLoader {
    func loadBundleResource(name: String, withExtension: String, javascriptEncode: Bool) -> String
}

extension BundleResourceLoader {
    func loadBundleResource(name: String, withExtension: String, javascriptEncode: Bool) -> String {
        guard let scriptURL = Bundle.main.url(forResource: name, withExtension: withExtension) else {
            fatalError("Count not find resource \(name).\(withExtension) in main bundle")
        }

        let contents = try! String(contentsOf: scriptURL)
        return javascriptEncode ? encodeForJavascript(contents) : contents
    }

    private func encodeForJavascript(_ string: String) -> String {
        return string.unicodeScalars.map { $0.escaped(asASCII: false) }.joined(separator: "")
    }
}

Use lazy when encoding unicodeScalars

//
//  BundleResourceLoader.swift
//  AlliCrab
//
//  Copyright © 2016 Chris Laverty. All rights reserved.
//

import Foundation

protocol BundleResourceLoader {
    func loadBundleResource(name: String, withExtension: String, javascriptEncode: Bool) -> String
}

extension BundleResourceLoader {
    func loadBundleResource(name: String, withExtension: String, javascriptEncode: Bool) -> String {
        guard let scriptURL = Bundle.main.url(forResource: name, withExtension: withExtension) else {
            fatalError("Count not find resource \(name).\(withExtension) in main bundle")
        }

        let contents = try! String(contentsOf: scriptURL)
        return javascriptEncode ? encodeForJavascript(contents) : contents
    }

    private func encodeForJavascript(_ string: String) -> String {
        return string.unicodeScalars.lazy.map { $0.escaped(asASCII: false) }.joined(separator: "")
    }
}


//
//  ChatViewControllerBanner.swift
//  Rocket.Chat
//
//  Created by Matheus Cardoso on 7/5/18.
//  Copyright © 2018 Rocket.Chat. All rights reserved.
//

import UIKit

extension ChatViewController {
    func showBanner(_ model: ChatBannerViewModel) {
        bannerView?.model = model
        bannerView?.isHidden = false
    }

    func hideBanner() {
        bannerView?.isHidden = true
    }

    func setupBanner() -> ChatBannerView? {
        guard let bannerView = ChatBannerView.instantiateFromNib() else {
            return nil
        }

        view.addSubview(bannerView)

        view.addConstraints(
            NSLayoutConstraint.constraints(
                withVisualFormat: "|-0-[bannerView]-0-|",
                options: .alignAllLeft,
                metrics: nil,
                views: ["bannerView": bannerView]
            )
        )

        view.addConstraints(
            NSLayoutConstraint.constraints(
                withVisualFormat: "V:|-0-[bannerView]",
                options: .alignAllLeft,
                metrics: nil,
                views: ["bannerView": bannerView]
            )
        )

        return bannerView
    }
}

Fix banner disappearing on rotation

//
//  ChatViewControllerBanner.swift
//  Rocket.Chat
//
//  Created by Matheus Cardoso on 7/5/18.
//  Copyright © 2018 Rocket.Chat. All rights reserved.
//

import UIKit

extension ChatViewController {
    func showBanner(_ model: ChatBannerViewModel) {
        bannerView?.model = model
        bannerView?.isHidden = false
    }

    func hideBanner() {
        bannerView?.isHidden = true
    }

    func setupBanner() -> ChatBannerView? {
        guard let bannerView = ChatBannerView.instantiateFromNib() else {
            return nil
        }

        bannerView.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(bannerView)

        view.addConstraints(
            NSLayoutConstraint.constraints(
                withVisualFormat: "|-0-[bannerView]-0-|",
                options: .alignAllLeft,
                metrics: nil,
                views: ["bannerView": bannerView]
            )
        )

        view.addConstraints(
            NSLayoutConstraint.constraints(
                withVisualFormat: "V:|-0-[bannerView(54)]",
                options: .alignAllLeft,
                metrics: nil,
                views: ["bannerView": bannerView]
            )
        )

        return bannerView
    }
}


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

import Foundation

extension String {
  public func lines() -> [String] {
    var xs: [String] = []
    var line: String = ""
    // loop school
    for x in self {
      if x == "\n" {
        xs.append(line)
        line = ""
      } else {
        line += x
      }
    }
    if line != "" {
      xs.append(line)
    }
    return xs
  }

  public static func unlines(xs: [String]) -> String {
    return xs.reduce("", combine: { "\($0)\($1)\n" } )
  }

  public static func lines() -> Iso<String, String, [String], [String]> {
    return Iso(get: { $0.lines() }, inject: unlines)
  }
}

Use `append` to append characters to a String

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

import Foundation

extension String {
  public func lines() -> [String] {
    var xs: [String] = []
    var line: String = ""
    // loop school
    for x in self {
      if x == "\n" {
        xs.append(line)
        line = ""
      } else {
        line.append(x)
      }
    }
    if line != "" {
      xs.append(line)
    }
    return xs
  }

  public static func unlines(xs: [String]) -> String {
    return xs.reduce("", combine: { "\($0)\($1)\n" } )
  }

  public static func lines() -> Iso<String, String, [String], [String]> {
    return Iso(get: { $0.lines() }, inject: unlines)
  }
}


//
//  AppDelegate.swift
//  PinpointKitExample
//
//  Created by Paul Rehkugler on 2/7/16.
//  Copyright © 2016 Lickability. All rights reserved.
//

import UIKit
import PinpointKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    lazy var window: UIWindow? = {
        return ShakeDetectingWindow(frame: UIScreen.mainScreen().bounds)
    }()

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        NSLog("Initial test log for the system logger.")
        return true
    }
}

Use the Shorter Form Lazy Syntax in Example Project

//
//  AppDelegate.swift
//  PinpointKitExample
//
//  Created by Paul Rehkugler on 2/7/16.
//  Copyright © 2016 Lickability. All rights reserved.
//

import UIKit
import PinpointKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    lazy var window: UIWindow? = ShakeDetectingWindow(frame: UIScreen.mainScreen().bounds)

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        NSLog("Initial test log for the system logger.")
        return true
    }
}


// RUN: %target-swift-frontend %s -emit-ir -gdwarf-types -o - | %FileCheck %s

func markUsed<T>(_ t: T) {}

// Int1 uses 1 bit, but is aligned at 8 bits.
// CHECK: !DIBasicType(name: "_T0Bi1_D", size: 1, encoding: DW_ATE_unsigned)
func main() {
  var t = true
  var f = false
  markUsed("hello")
}

main()

Add a testcase for the debug infor generated for 'Bool'.

// RUN: %target-swift-frontend %s -emit-ir -gdwarf-types -o - | %FileCheck %s
// RUN: %target-swift-frontend %s -emit-ir -g -o - \
// RUN:   | %FileCheck %s --check-prefix=CHECK_G

func markUsed<T>(_ t: T) {}

// Int1 uses 1 bit, but is aligned at 8 bits.
// CHECK: !DIBasicType(name: "_T0Bi1_D", size: 1, encoding: DW_ATE_unsigned)
// Bool has a fixed layout with a storage size of 1 byte and 7 "spare" bits.
// CHECK_G: !DICompositeType(tag: DW_TAG_structure_type, name: "Bool",
// CHECK_G-SAME:             size: 8
func main() {
  var t = true
  var f = false
  markUsed("hello")
}

main()


//  DoshaHistory.swift

import Foundation

class DoshaHistory: CustomStringConvertible {

    var log = [Date: Answers]() // Mapping from creation date -> answer instance

    init() {
        load()
        }

    // Load previously saved dosha quiz answers.
    func load() {
        if let data = UserDefaults.standard.object(forKey: "History") as? Data {
            log = NSKeyedUnarchiver.unarchiveObject(with: data) as! [Date: Answers]
            }
        }

    // Save dosha quiz answers.
    func save() {
        let data = NSKeyedArchiver.archivedData(withRootObject: log)
        UserDefaults.standard.set(data, forKey: "History")
        }

    // Fetch latest answers object, or nil if none exists.
    func latest() -> Answers? {
        if log.count < 1 {
            return nil
            }
        let dates = log.keys.sorted()
        let key = dates.last!
        return log[key]
        }

    // Create a new Answers instance and add it to the log; also saves it. Returns the newly created instance.
    func add() -> Answers {
        let new = Answers()
        log[new.created] = new
        save()
        return new
        }

    // Erase entire history.
    func erase() {
        log.removeAll()
        save()
        }

    // String representation of entire object.
    var description: String {
        return "<DoshaHistory: \(log)>"
        }
    }

Copy prakruti from previously completed test

//  DoshaHistory.swift

import Foundation

class DoshaHistory: CustomStringConvertible {

    var log = [Date: Answers]() // Mapping from creation date -> answer instance

    init() {
        load()
        }

    // Load previously saved dosha quiz answers.
    func load() {
        if let data = UserDefaults.standard.object(forKey: "History") as? Data {
            log = NSKeyedUnarchiver.unarchiveObject(with: data) as! [Date: Answers]
            }
        }

    // Save dosha quiz answers.
    func save() {
        let data = NSKeyedArchiver.archivedData(withRootObject: log)
        UserDefaults.standard.set(data, forKey: "History")
        }

    // Fetch latest answers object, or nil if none exists.
    func latest() -> Answers? {
        if log.count < 1 {
            return nil
            }
        let dates = log.keys.sorted()
        let key = dates.last!
        return log[key]
        }

    // Create a new Answers instance and add it to the log; also saves it. Returns the newly created instance.
    // If previous Answers exist in the log, copy over the pakruti scores from the latest.
    func add() -> Answers {
        var new: Answers
        if let lat = latest() {
            new = Answers(lat)
            }
        else {
            new = Answers()
            }
        log[new.created] = new
        save()
        return new
        }

    // Erase entire history.
    func erase() {
        log.removeAll()
        save()
        }

    // String representation of entire object.
    var description: String {
        return "<DoshaHistory: \(log)>"
        }
    }


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

public struct Environment: DictionaryLiteralConvertible, Printable {
	private let bindings: [Symbol: Value]

	public subscript (key: String) -> (Symbol, Value)? {
		let index = find(bindings) { symbol, _ in symbol.name == key }
		return index.map { self.bindings[$0] }?
	}

	public subscript (key: Symbol) -> Value? {
		return bindings[key]
	}

	// MARK: DictionaryLiteralConvertible

	public init(dictionaryLiteral elements: (Symbol, Value)...) {
		bindings = Dictionary(elements)
	}

	// MARK: Printable

	public var description: String {
		return "[\n" + join("", lazy(bindings).map { "\t\(toString($0)): \(toString($1)),\n" }) + "]"
	}
}

public let Prelude: Environment = [
	Symbol("unit", .Unit): Value(constant: ()),
	Symbol("true", .Boolean): Value(constant: true),
	Symbol("false", .Boolean): Value(constant: false),
	Symbol("identity", 0 --> 0): Value(function: id as Any -> Any),
	Symbol("const", 0 --> 1 --> 0): Value(function: const as Any -> Any -> Any),
]

// MARK: - Imports

import Prelude

Rename const function to constant.

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

public struct Environment: DictionaryLiteralConvertible, Printable {
	private let bindings: [Symbol: Value]

	public subscript (key: String) -> (Symbol, Value)? {
		let index = find(bindings) { symbol, _ in symbol.name == key }
		return index.map { self.bindings[$0] }?
	}

	public subscript (key: Symbol) -> Value? {
		return bindings[key]
	}

	// MARK: DictionaryLiteralConvertible

	public init(dictionaryLiteral elements: (Symbol, Value)...) {
		bindings = Dictionary(elements)
	}

	// MARK: Printable

	public var description: String {
		return "[\n" + join("", lazy(bindings).map { "\t\(toString($0)): \(toString($1)),\n" }) + "]"
	}
}

public let Prelude: Environment = [
	Symbol("unit", .Unit): Value(constant: ()),
	Symbol("true", .Boolean): Value(constant: true),
	Symbol("false", .Boolean): Value(constant: false),
	Symbol("identity", 0 --> 0): Value(function: id as Any -> Any),
	Symbol("constant", 0 --> 1 --> 0): Value(function: const as Any -> Any -> Any),
]

// MARK: - Imports

import Prelude


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

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

import Assertions
@testable import Manifold
import XCTest

Test that top-level nodes have no parents or siblings.

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

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

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

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

import Assertions
@testable import Manifold
import XCTest


import Foundation

public class Promise<Value> {
    private let lock = NSRecursiveLock()

    private var value: Value?
    private var handlers: [(Value) -> ()] = []

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

    public init(_ executor: (_ fulfill: @escaping (Value) -> ()) -> ()) {
        executor(fulfill)
    }

    private func fulfill(_ value: Value) {
        lock.lock()
        defer { lock.unlock() }

        precondition(self.value == nil, "`fulfill` cannot be called multiple times.")

        self.value = value
        handlers.forEach { $0(value) }
        handlers.removeAll(keepingCapacity: false)
    }

    public func get(_ handler: @escaping (Value) -> ()) {
        lock.lock()
        defer { lock.unlock() }

        if let value = self.value {
            handler(value)
        } else {
            handlers.append(handler)
        }
    }

    public func map<T>(_ transform: @escaping (Value) -> T) -> Promise<T> {
        return Promise<T> { fulfill in get { fulfill(transform($0)) } }
    }

    public func flatMap<T>(_ transform: @escaping (Value) -> Promise<T>) -> Promise<T> {
        return Promise<T> { fulfill in get { transform($0).get { fulfill($0) } } }
    }
}

extension Promise : CustomStringConvertible {
    public var description: String {
        if let value = self.value {
            return "Promise(\(value))"
        } else {
            return "Promise(\(Value.self))"
        }
    }
}

Change `fulfill` to a closure expression

import Foundation

public class Promise<Value> {
    private let lock = NSRecursiveLock()

    private var value: Value?
    private var handlers: [(Value) -> ()] = []

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

    public init(_ executor: (_ fulfill: @escaping (Value) -> ()) -> ()) {
        executor { value in
            self.lock.lock()
            defer { self.lock.unlock() }

            precondition(self.value == nil, "`fulfill` cannot be called multiple times.")

            self.value = value
            self.handlers.forEach { $0(value) }
            self.handlers.removeAll(keepingCapacity: false)
        }
    }

    public func get(_ handler: @escaping (Value) -> ()) {
        lock.lock()
        defer { lock.unlock() }

        if let value = self.value {
            handler(value)
        } else {
            handlers.append(handler)
        }
    }

    public func map<T>(_ transform: @escaping (Value) -> T) -> Promise<T> {
        return Promise<T> { fulfill in get { fulfill(transform($0)) } }
    }

    public func flatMap<T>(_ transform: @escaping (Value) -> Promise<T>) -> Promise<T> {
        return Promise<T> { fulfill in get { transform($0).get { fulfill($0) } } }
    }
}

extension Promise : CustomStringConvertible {
    public var description: String {
        if let value = self.value {
            return "Promise(\(value))"
        } else {
            return "Promise(\(Value.self))"
        }
    }
}


//
//  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
        }()

        var familyName = self.familyName

        var pointSize = self.pointSize

        if familyName.starts(with: ".SF") {
            familyName = "Hiragino Sans"
            pointSize = pointSize - 1
        }

        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 - 1)
    }
}

Fix Hiragino Sans weight corrupted

//
//  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
                case "CTFontDemiUsage":
                    weight = .bold
                default:
                    break
            }

            return weight
        }()

        var familyName = self.familyName

        var pointSize = self.pointSize

        if familyName.starts(with: ".SF") {
            familyName = "Hiragino Sans"
            pointSize = pointSize - 1
        }

        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 - 1)
    }
}


//
//  UIViewController+ManualLayout.swift
//  ManualLayout
//
//  Created by Baris Sencan on 25/02/15.
//  Copyright (c) 2015 Baris Sencan. All rights reserved.
//

import UIKit

public extension UIViewController {

  // MARK: - Center

  public var center: CGPoint {
    return view.center
  }

  public var centerX: CGFloat {
    return view.centerX
  }

  public var centerY: CGFloat {
    return view.centerY
  }

  // MARK: - Size

  public var size: CGSize {
    return view.size
  }

  public var width: CGFloat {
    return view.width
  }

  public var height: CGFloat {
    return view.height
  }

  // MARK: - Edges

  public var top: CGFloat {
    return topLayoutGuide.length
  }

  public var right: CGFloat {
    return view.width
  }

  public var bottom: CGFloat {
    return view.height - bottomLayoutGuide.length
  }

  public var left: CGFloat {
    return 0
  }
}

Add bounds property to view controllers

//
//  UIViewController+ManualLayout.swift
//  ManualLayout
//
//  Created by Baris Sencan on 25/02/15.
//  Copyright (c) 2015 Baris Sencan. All rights reserved.
//

import UIKit

public extension UIViewController {

  public var bounds: CGRect {
    return view.bounds
  }

  // MARK: - Center

  public var center: CGPoint {
    return view.center
  }

  public var centerX: CGFloat {
    return view.centerX
  }

  public var centerY: CGFloat {
    return view.centerY
  }

  // MARK: - Size

  public var size: CGSize {
    return view.size
  }

  public var width: CGFloat {
    return view.width
  }

  public var height: CGFloat {
    return view.height
  }

  // MARK: - Edges

  public var top: CGFloat {
    return topLayoutGuide.length
  }

  public var right: CGFloat {
    return view.width
  }

  public var bottom: CGFloat {
    return view.height - bottomLayoutGuide.length
  }

  public var left: CGFloat {
    return 0
  }
}


//
//  DetailViewController.swift
//  Commands
//
//  Created by Liu Liang on 5/1/16.
//  Copyright © 2016 Liu Liang. All rights reserved.
//

import UIKit

class DetailViewController: UIViewController {

    @IBOutlet var detailTextView: UITextView!

    var detailItem: AnyObject? {
        didSet {
            // Update the view.
            self.configureView()
        }
    }

    func configureView() {
        // Update the user interface for the detail item.
        if let detail = self.detailItem {
            if let textView = self.detailTextView {
                textView.textAlignment = .Left
                let result = Utils.executeCmd(detail as? String ?? "uname -a")
                switch result {
                case .Success:
                    textView.text = result.value
                case .Failure:
                    textView.text = result.error?.localizedDescription
                }
            }
        }
    }

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

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

}

Set textView.editable to false for detail view.

//
//  DetailViewController.swift
//  Commands
//
//  Created by Liu Liang on 5/1/16.
//  Copyright © 2016 Liu Liang. All rights reserved.
//

import UIKit

class DetailViewController: UIViewController {

    @IBOutlet var detailTextView: UITextView!

    var detailItem: AnyObject? {
        didSet {
            // Update the view.
            self.configureView()
        }
    }

    func configureView() {
        // Update the user interface for the detail item.
        if let detail = self.detailItem {
            if let textView = self.detailTextView {
                textView.textAlignment = .Left
                textView.editable = false
                let result = Utils.executeCmd(detail as? String ?? "uname -a")
                switch result {
                case .Success:
                    textView.text = result.value
                case .Failure:
                    textView.text = result.error?.localizedDescription
                }
            }
        }
    }

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

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

}


enum Foo : Int {
  case A = 0
}

enum Bar : UInt {
  case A = 0
  case B = 22
}

enum Baz : UInt {
  case A = 0
}

enum Garply : String {
    case A = "A"
}

Modify the lowerCamelCase the Case of Enum.

enum Foo : Int {
  case a = 0
}

enum Bar : UInt {
  case a = 0
  case b = 22
}

enum Baz : UInt {
  case a = 0
}

enum Garply : String {
    case a = "A"
}


//
//  TableViewControllerTests.swift
//  InlinePicker
//
//  Created by Jeffrey Kereakoglow on 4/21/16.
//  Copyright © 2016 Alexis Digital. All rights reserved.
//

import XCTest
@testable import InlinePicker

final class TableViewControllerTests: XCTestCase {
  private var tableVC: TableViewController!

  override func setUp() {
    tableVC = TableViewController(style: .Plain, dataSource: TableViewDataSource.dataSource)
  }

  override func tearDown() {
    tableVC = nil
  }

  func testDataSource() {
    XCTAssertNotNil(TableViewDataSource.dataSource)
  }
}

Add table view controller tests

//
//  TableViewControllerTests.swift
//  InlinePicker
//
//  Created by Jeffrey Kereakoglow on 4/21/16.
//  Copyright © 2016 Alexis Digital. All rights reserved.
//

import XCTest
@testable import InlinePicker

final class TableViewControllerTests: XCTestCase {
  private var viewController: TableViewController!

  override func setUp() {
    viewController = TableViewController(style: .Plain, dataSource: TableViewDataSource.dataSource)
  }

  override func tearDown() {
    viewController = nil
  }

  func testNumberOfSections() {
    XCTAssertEqual(viewController.numberOfSectionsInTableView(viewController.tableView), 1)
  }

  func testNumberOfRowsInSection() {
    XCTAssertEqual(
      viewController.tableView(viewController.tableView, numberOfRowsInSection: 0),
      TableViewDataSource.dataSource.count
    )
  }
}


//
//  TopicComposeView.swift
//  Stage1st
//
//  Created by Zheng Li on 2019/6/10.
//  Copyright © 2019 Renaissance. All rights reserved.
//

import SwiftUI

@available(iOS 13.0, *)
struct TopicComposeView: UIViewControllerRepresentable {

    let title: String
    let content: String

    init(title: String = "", content: String = "") {
        self.title = title
        self.content = content
    }

    func makeUIViewController(context: UIViewControllerRepresentableContext<TopicComposeView>) -> UINavigationController {
        return UINavigationController(rootViewController: TopicComposeViewController(forumID: 6))
    }

    func updateUIViewController(_ uiViewController: UINavigationController, context: UIViewControllerRepresentableContext<TopicComposeView>) {
        let composeViewController = uiViewController.viewControllers.first! as! TopicComposeViewController
        composeViewController.textField.text = title
        composeViewController.textView.text = content
    }

}

#if DEBUG
@available(iOS 13.0, *)
struct TopicComposeView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            TopicComposeView()
            TopicComposeView(title: "Hello World")
            TopicComposeView(title: "Hello World", content: "WWWWWWWWWWWWWWWWWWWWWWWWWWWW")
        }
    }
}
#endif

Remove code related to SwiftUI since it can not be ignored by Xcode 10

//
//  TopicComposeView.swift
//  Stage1st
//
//  Created by Zheng Li on 2019/6/10.
//  Copyright © 2019 Renaissance. All rights reserved.
//

//import SwiftUI
//
//@available(iOS 13.0, *)
//struct TopicComposeView: UIViewControllerRepresentable {
//
//    let title: String
//    let content: String
//
//    init(title: String = "", content: String = "") {
//        self.title = title
//        self.content = content
//    }
//
//    func makeUIViewController(context: UIViewControllerRepresentableContext<TopicComposeView>) -> UINavigationController {
//        return UINavigationController(rootViewController: TopicComposeViewController(forumID: 6))
//    }
//
//    func updateUIViewController(_ uiViewController: UINavigationController, context: UIViewControllerRepresentableContext<TopicComposeView>) {
//        let composeViewController = uiViewController.viewControllers.first! as! TopicComposeViewController
//        composeViewController.textField.text = title
//        composeViewController.textView.text = content
//    }
//
//}
//
//#if DEBUG
//@available(iOS 13.0, *)
//struct TopicComposeView_Previews: PreviewProvider {
//    static var previews: some View {
//        Group {
//            TopicComposeView()
//            TopicComposeView(title: "Hello World")
//            TopicComposeView(title: "Hello World", content: "WWWWWWWWWWWWWWWWWWWWWWWWWWWW")
//        }
//    }
//}
//#endif


//
// Copyright (c) Badoo Trading Limited, 2010-present. All rights reserved.
//

import Foundation

public struct DelegateStore<Delegate> {
    fileprivate var delegatesTable = NSHashTable<AnyObject>.weakObjects()

    public init() {}

    public func add(_ delegate: Delegate) {
        self.delegatesTable.add(delegate as AnyObject)
    }

    public func remove(_ delegate: Delegate) {
        self.delegatesTable.remove(delegate as AnyObject)
    }

    public func contains(_ delegate: Delegate) -> Bool {
        return self.delegatesTable.contains(delegate as AnyObject)
    }

    public func notifyAll(_ block: (Delegate) -> Void) {
        self.delegatesTable.allObjects.compactMap { $0 as? Delegate }.forEach(block)
    }
}

extension DelegateStore: CustomStringConvertible {

    public var description: String {
        var string = "DelegateStore ["
        string += self.delegatesTable.allObjects.map({ return "<\(type(of: $0))>"}).joined(separator: ", ")
        return string + "]"
    }

}

Change DelegateStore.delegatesTable from fileprivate to private

//
// Copyright (c) Badoo Trading Limited, 2010-present. All rights reserved.
//

import Foundation

public struct DelegateStore<Delegate> {
    private var delegatesTable = NSHashTable<AnyObject>.weakObjects()

    public init() {}

    public func add(_ delegate: Delegate) {
        self.delegatesTable.add(delegate as AnyObject)
    }

    public func remove(_ delegate: Delegate) {
        self.delegatesTable.remove(delegate as AnyObject)
    }

    public func contains(_ delegate: Delegate) -> Bool {
        return self.delegatesTable.contains(delegate as AnyObject)
    }

    public func notifyAll(_ block: (Delegate) -> Void) {
        self.delegatesTable.allObjects.compactMap { $0 as? Delegate }.forEach(block)
    }
}

extension DelegateStore: CustomStringConvertible {

    public var description: String {
        var string = "DelegateStore ["
        string += self.delegatesTable.allObjects.map({ return "<\(type(of: $0))>"}).joined(separator: ", ")
        return string + "]"
    }

}


// RUN: rm -rf %t  &&  mkdir %t
// RUN: %target-build-swift -module-name FactoryTest %s -o %t/a.out
// RUN: %target-run %t/a.out | FileCheck %s
// REQUIRES: OS=macosx

import AppKit

let service = NSSharingService(named: NSSharingServiceNamePostOnTwitter)
// CHECK: Twitter
println(service.title)

Adjust test to not depend on the current user account's configuration.

// RUN: rm -rf %t  &&  mkdir %t
// RUN: %target-build-swift -module-name FactoryTest %s -o %t/a.out
// RUN: %target-run %t/a.out | FileCheck %s
// REQUIRES: OS=macosx

import AppKit

let image = NSImage(named: NSImageNameTrashEmpty)
// CHECK: TrashEmpty
println(image.name())


import Foundation

class JSONFileReader {
  class func JSON(fromFile file: String) -> AnyObject? {
    let path = NSBundle(forClass: self).pathForResource(file, ofType: "json")

    if path != nil {
      let data = NSData(contentsOfFile: path!)
      return NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(0), error: nil)
    }

    return .None
  }
}

Use if-let for data unwrapping

import Foundation

class JSONFileReader {
  class func JSON(fromFile file: String) -> AnyObject? {
    let path = NSBundle(forClass: self).pathForResource(file, ofType: "json")

    if path != nil {
      if let data = NSData(contentsOfFile: path!) {
        return NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil)
      }
    }

    return .None
  }
}


extension Node {
    public final class BooleanOperation: Vector {
        let operation: Operation
        enum Operation: String, Decodable {
            case union = "UNION"
            case intersect = "INTERSECT"
            case subtract = "SUBTRACT"
            case exclude = "EXCLUDE"
        }

        private enum CodingKeys: String, CodingKey {
            case operation
        }

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

            self.operation = try keyedDecoder.decode(Operation.self, forKey: .operation)

            try super.init(from: decoder)
        }

        public override func encode(to encoder: Encoder) throws {
            fatalError("Not yet implemented")
        }

        override var contentDescription: String {
            return """
                - operation: \(operation)
                """
        }
    }
}

Fix typo in boolean operation property.

extension Node {
    public final class BooleanOperation: Vector {
        let booleanOperation: Operation
        enum Operation: String, Decodable {
            case union = "UNION"
            case intersect = "INTERSECT"
            case subtract = "SUBTRACT"
            case exclude = "EXCLUDE"
        }

        private enum CodingKeys: String, CodingKey {
            case booleanOperation
        }

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

            self.booleanOperation = try keyedDecoder.decode(Operation.self, forKey: .booleanOperation)

            try super.init(from: decoder)
        }

        public override func encode(to encoder: Encoder) throws {
            fatalError("Not yet implemented")
        }

        override var contentDescription: String {
            return """
                - booleanOperation: \(booleanOperation)
                """
        }
    }
}


import Foundation
import Yaml

/// Represents a workshop
// TODO: Rename this struct to `Workshop` when it's ready for use
public struct NewWorkshop {
  let title: String

  /// People that have directly contributed content to this workshop
  let contributors: [String]

  /// Non-contributors we would like to thank for helping to inspire, develop or facilitate this workshop
  let thanks: [String]

  /// Links that attendees may which to read after the workhsop
  let furtherReadingLinks: [(String, URL)]

  /// A link to a video recording of this workshop
  let recordingLink: URL?

  /// A link to any slides for this workshop
  let slidesLink: URL?

  /// A set of keywords associated with the workshop
  let tags: [String]

  /// A string of a https://spdx.org/licenses/ license identifier
  // TODO: Make a type safe version of this
  let license: String

  /// The prose content that accompanies the workshop (and slides)
  let notes: Markdown

  /// A URL of a promotional image for the workshop, to be displayed on top of `promoImageBackground`
  let promoImageForeground: URL

  /// The background for `promoImageForeground`
  let promoImageBackground: Background

  /// Prose describing the nature of the workshop
  let description: Markdown

  /// Prose describing who the workshop is aimed at
  let whoItsFor: Markdown

  /// Prose describing what attendees should already know
  let prerequisites: Markdown

  /// Prose describing how attendees should prepare for the workshop
  let setupInstructions: Markdown

  /// The URL to the workshop repository
  let repositoryURL: URL
}

Remove whoItsFor, Fix Typos, adopt IDs

import Foundation
import Yaml

/// Represents a workshop
// TODO: Rename this struct to `Workshop` when it's ready for use
public struct NewWorkshop {
  let title: String

  /// People that have directly contributed content to this workshop
  let contributors: [String]

  /// Non-contributors we would like to thank for helping to inspire, develop or facilitate this workshop
  let thanks: [String]

  /// Links that attendees may wish to read after the workhsop
  let furtherReadingLinks: [Link]

  /// A link to a video recording of this workshop
  let recordingLink: URL?

  /// A link to any slides for this workshop
  let slidesLink: URL?

  /// A set of keywords associated with the workshop
  let tags: [String]

  /// A string of a https://spdx.org/licenses/ license identifier
  // TODO: Make a type safe version of this
  let license: String

  /// The prose content that accompanies the workshop (and slides)
  let notes: Markdown

  /// A URL of a promotional image for the workshop, to be displayed on top of `promoImageBackground`
  let promoImageForeground: URL

  /// The background for `promoImageForeground`
  let promoImageBackground: Background

  /// Prose describing the nature of the workshop
  let description: Markdown

  /// Prose describing what attendees should already know
  let prerequisites: Markdown

  /// Prose describing how attendees should prepare for the workshop
  let setupInstructions: Markdown

  /// The ID of the workshop as determined by its workshop repository URL
  let workshopId: String
}


//
//  FileLogHandler.swift
//  Embassy
//
//  Created by Fang-Pen Lin on 6/2/16.
//  Copyright © 2016 Fang-Pen Lin. All rights reserved.
//

import Foundation

/// A log handler which writes log records to given file handle
public struct FileLogHandler: LogHandlerType {
    let fileHandle: NSFileHandle
    public var formatter: LogFormatterType?

    public init(fileHandle: NSFileHandle, formatter: LogFormatterType? = DefaultLogFormatter()) {
        self.fileHandle = fileHandle
        self.formatter = formatter
    }

    public func emit(record: LogRecord) {
        if let formatter = formatter {
            let msg = formatter.format(record) + "\n"
            fileHandle.writeData(msg.dataUsingEncoding(NSUTF8StringEncoding)!)
            fileHandle.synchronizeFile()
        }
    }

    public static func stderrHandler() -> FileLogHandler {
        return FileLogHandler(fileHandle: NSFileHandle.fileHandleWithStandardError())
    }
}

Allow file log handler to receive log records concurrently

//
//  FileLogHandler.swift
//  Embassy
//
//  Created by Fang-Pen Lin on 6/2/16.
//  Copyright © 2016 Fang-Pen Lin. All rights reserved.
//

import Foundation

/// A log handler which writes log records to given file handle
public struct FileLogHandler: LogHandlerType {
    let fileHandle: NSFileHandle
    public var formatter: LogFormatterType?

    private let queue = dispatch_queue_create(
        "com.envoy.Embassy.logging.FileLogHandler.queue",
        DISPATCH_QUEUE_SERIAL
    )

    public init(fileHandle: NSFileHandle, formatter: LogFormatterType? = DefaultLogFormatter()) {
        self.fileHandle = fileHandle
        self.formatter = formatter
    }

    public func emit(record: LogRecord) {
        dispatch_async(queue) {
            if let formatter = self.formatter {
                let msg = formatter.format(record) + "\n"
                self.fileHandle.writeData(msg.dataUsingEncoding(NSUTF8StringEncoding)!)
                self.fileHandle.synchronizeFile()
            }
        }
    }

    public static func stderrHandler() -> FileLogHandler {
        return FileLogHandler(fileHandle: NSFileHandle.fileHandleWithStandardError())
    }
}


//
//  EmployeeSearch.swift
//  Colleagues
//
//  Created by Nguyen Vinh on 10/13/15.
//  Copyright © 2015 Razeware LLC. All rights reserved.
//

import CoreSpotlight

extension Employee {
  public static let domainIdentifier = "com.raywenderlich.colleagues.employee"
  public var userActivityUserInfo: [NSObject: AnyObject] {
    return ["id": objectId]
  }
  public var userActivity: NSUserActivity {
    let activity = NSUserActivity(activityType: Employee.domainIdentifier)

    activity.title = name
    activity.userInfo = userActivityUserInfo
    activity.keywords = [email, department]

    return activity
  }
}

Add information in search result

//
//  EmployeeSearch.swift
//  Colleagues
//
//  Created by Nguyen Vinh on 10/13/15.
//  Copyright © 2015 Razeware LLC. All rights reserved.
//

import CoreSpotlight
import MobileCoreServices

extension Employee {
  public static let domainIdentifier = "com.raywenderlich.colleagues.employee"
  public var userActivityUserInfo: [NSObject: AnyObject] {
    return ["id": objectId]
  }
  public var userActivity: NSUserActivity {
    let activity = NSUserActivity(activityType: Employee.domainIdentifier)

    activity.title = name
    activity.userInfo = userActivityUserInfo
    activity.keywords = [email, department]
    activity.contentAttributeSet = attributeSet

    return activity
  }
  public var attributeSet: CSSearchableItemAttributeSet {
    let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeContact as String)

    attributeSet.title = name
    attributeSet.contentDescription = "\(department), \(title)\n\(phone)"
    attributeSet.thumbnailData = UIImageJPEGRepresentation(loadPicture(), 0.9)
    attributeSet.supportsPhoneCall = true
    attributeSet.phoneNumbers = [phone]
    attributeSet.emailAddresses = [email]
    attributeSet.keywords = skills

    return attributeSet
  }
}


//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 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
//
//===----------------------------------------------------------------------===//

import SwiftSyntax

extension VariableDecl {
  public init(
    leadingTrivia: Trivia = [],
    _ letOrVarKeyword: TokenSyntax,
    name: ExpressibleAsIdentifierPattern,
    type: ExpressibleAsTypeAnnotation? = nil,
    initializer: ExpressibleAsInitializerClause? = nil
  ) {
    self.init(leadingTrivia: leadingTrivia, letOrVarKeyword: letOrVarKeyword) {
      PatternBinding(
        pattern: name,
        typeAnnotation: type,
        initializer: initializer
      )
    }
  }
}

Add modifiers parameter to VariableDecl convenience init

//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 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
//
//===----------------------------------------------------------------------===//

import SwiftSyntax

extension VariableDecl {
  public init(
    leadingTrivia: Trivia = [],
    modifiers: ModifierList? = nil,
    _ letOrVarKeyword: TokenSyntax,
    name: ExpressibleAsIdentifierPattern,
    type: ExpressibleAsTypeAnnotation? = nil,
    initializer: ExpressibleAsInitializerClause? = nil
  ) {
    self.init(leadingTrivia: leadingTrivia, modifiers: modifiers, letOrVarKeyword: letOrVarKeyword) {
      PatternBinding(
        pattern: name,
        typeAnnotation: type,
        initializer: initializer
      )
    }
  }
}


//
//  PresetAppearanceConfigs.swift
//  Tabman-Example
//
//  Created by Merrick Sapsford on 10/03/2017.
//  Copyright © 2017 Merrick Sapsford. All rights reserved.
//

import Foundation
import Tabman

class PresetAppearanceConfigs: Any {

    static func forStyle(_ style: TabmanBar.Style, currentAppearance: TabmanBar.Appearance?) -> TabmanBar.Appearance? {
        let appearance = currentAppearance ?? TabmanBar.Appearance.defaultAppearance

        var view: UIView? = UIView()
        let defaultTintColor = view!.tintColor
        view = nil

        switch style {

        case .buttonBar, .bar:
            appearance.state.color = UIColor.white.withAlphaComponent(0.6)
            appearance.state.selectedColor = UIColor.white
            appearance.style.background = .blur(style: .light)
            appearance.indicator.color = UIColor.white
            appearance.layout.itemVerticalPadding = 16.0

        case .blockTabBar:
            appearance.state.color = UIColor.white.withAlphaComponent(0.6)
            appearance.state.selectedColor = defaultTintColor
            appearance.style.background = .solid(color: UIColor.white.withAlphaComponent(0.3))
            appearance.indicator.color = UIColor.white.withAlphaComponent(0.8)

        default:()
        }

        return appearance
    }
}

Add example appearance config for .bar

//
//  PresetAppearanceConfigs.swift
//  Tabman-Example
//
//  Created by Merrick Sapsford on 10/03/2017.
//  Copyright © 2017 Merrick Sapsford. All rights reserved.
//

import Foundation
import Tabman

class PresetAppearanceConfigs: Any {

    static func forStyle(_ style: TabmanBar.Style, currentAppearance: TabmanBar.Appearance?) -> TabmanBar.Appearance? {
        let appearance = currentAppearance ?? TabmanBar.Appearance.defaultAppearance

        var view: UIView? = UIView()
        let defaultTintColor = view!.tintColor
        view = nil

        switch style {

        case .bar:
            appearance.style.background = .solid(color: .black)
            appearance.indicator.color = .white
            appearance.indicator.lineWeight = .thick

        case .buttonBar:
            appearance.state.color = UIColor.white.withAlphaComponent(0.6)
            appearance.state.selectedColor = UIColor.white
            appearance.style.background = .blur(style: .light)
            appearance.indicator.color = UIColor.white
            appearance.layout.itemVerticalPadding = 16.0

        case .blockTabBar:
            appearance.state.color = UIColor.white.withAlphaComponent(0.6)
            appearance.state.selectedColor = defaultTintColor
            appearance.style.background = .solid(color: UIColor.white.withAlphaComponent(0.3))
            appearance.indicator.color = UIColor.white.withAlphaComponent(0.8)

        default:()
        }

        return appearance
    }
}


// RUN: %target-typecheck-verify-swift -enable-experimental-concurrency

// REQUIRES: concurrency

async let x = 1 // okay

struct X {
  async let x = 1 // expected-error{{'async let' can only be used on local declarations}}
  // FIXME: expected-error@-1{{'async' call cannot occur in a property initializer}}
}

func testAsyncFunc() async {
  async let (z1, z2) = (2, 3)
  async let (_, _) = (2, 3)
  async let x2 = 1

  async var x = 17 // expected-error{{'async' can only be used with 'let' declarations}}{{9-12=let}}
  async let (_, _) = (1, 2), y2 = 7 // expected-error{{'async let' requires at least one named variable}}
  async let y: Int // expected-error{{'async let' binding requires an initializer expression}}
  _ = await x
  _ = y
  _ = await z1
  _ = await z2
  _ = await x2
  await x = 1
  _ = y2
}

Add an async let example with multiple initializer clauses

// RUN: %target-typecheck-verify-swift -enable-experimental-concurrency

// REQUIRES: concurrency

async let x = 1 // okay

struct X {
  async let x = 1 // expected-error{{'async let' can only be used on local declarations}}
  // FIXME: expected-error@-1{{'async' call cannot occur in a property initializer}}
}

func testAsyncFunc() async {
  async let (z1, z2) = (2, 3)
  async let (_, _) = (2, 3)
  async let x2 = 1

  async var x = 17 // expected-error{{'async' can only be used with 'let' declarations}}{{9-12=let}}
  async let (_, _) = (1, 2), y2 = 7 // expected-error{{'async let' requires at least one named variable}}
  async let y: Int // expected-error{{'async let' binding requires an initializer expression}}
  _ = await x
  _ = y
  _ = await z1
  _ = await z2
  _ = await x2
  await x = 1
  _ = y2
}

// Cooking example
func chopVegetables() async throws -> [String] { [] }
func marinateMeat() async -> String { "MEAT" }

func cook() async throws {
  async let veggies = await try chopVegetables(), meat = await marinateMeat()
  _ = await try veggies
  _ = await meat
}


//
//  Container+SwinjectStoryboardSpec.swift
//  Swinject
//
//  Created by Yoichi Tagaya on 2/27/16.
//  Copyright © 2016 Swinject Contributors. All rights reserved.
//

import Quick
import Nimble
@testable import Swinject

#if os(iOS) || os(OSX) || os(tvOS)
class Container_SwinjectStoryboardSpec: QuickSpec {
    override func spec() {
        var container: Container!
        beforeEach {
            container = Container()
        }

        describe("CustomStringConvertible") {
            it("describes a registration with storyboard option.") {
                let controllerType = String(Container.Controller.self) // "UIViewController" for iOS/tvOS, "AnyObject" for OSX.
                container.registerForStoryboard(AnimalViewController.self) { r, c in }

                expect(container.description) ==
                    "[\n"
                    + "    { Service: \(controllerType), Storyboard: SwinjectTests.AnimalViewController, "
                    + "Factory: (ResolverType, \(controllerType)) -> \(controllerType), ObjectScope: Graph, InitCompleted: Specified }\n"
                    + "]"
            }
        }
    }
}
#endif

Fix CustomStringConvertible test for SwinjectStoryboard to match the current name space.

//
//  Container+SwinjectStoryboardSpec.swift
//  Swinject
//
//  Created by Yoichi Tagaya on 2/27/16.
//  Copyright © 2016 Swinject Contributors. All rights reserved.
//

import Quick
import Nimble
@testable import Swinject

#if os(iOS) || os(OSX) || os(tvOS)
class Container_SwinjectStoryboardSpec: QuickSpec {
    override func spec() {
        var container: Container!
        beforeEach {
            container = Container()
        }

        describe("CustomStringConvertible") {
            it("describes a registration with storyboard option.") {
                let controllerType = String(Container.Controller.self) // "UIViewController" for iOS/tvOS, "AnyObject" for OSX.
                container.registerForStoryboard(AnimalViewController.self) { r, c in }

                expect(container.description) ==
                    "[\n"
                    + "    { Service: \(controllerType), Storyboard: SwinjectStoryboardTests.AnimalViewController, "
                    + "Factory: (ResolverType, \(controllerType)) -> \(controllerType), ObjectScope: Graph, InitCompleted: Specified }\n"
                    + "]"
            }
        }
    }
}
#endif


//
//  NSManagedObjectContext+Extensions.swift
//  CoreDataSMS
//
//  Created by Robert Edwards on 2/23/15.
//  Copyright (c) 2015 Big Nerd Ranch. All rights reserved.
//

import CoreData

public extension NSManagedObjectContext {
    public func saveContextAndWait() -> Bool {
        var success = true

        let sharedSaveFlow: () -> Bool = {
            var saveError: NSError?
            if self.hasChanges && !self.save(&saveError) {
                success = false
                println("Failed to save managed object context")
                if let error = saveError {
                    println("Error: \(saveError)")
                }
            }
            return success
        }

        switch concurrencyType {
        case .ConfinementConcurrencyType:
            success = sharedSaveFlow()
        case .MainQueueConcurrencyType:
            fallthrough
        case .PrivateQueueConcurrencyType:
            self.performBlockAndWait { [unowned self] in
                success = sharedSaveFlow()
            }
        }

        return success
    }

    public func saveContext() {
        let sharedSaveFlow: () -> () = {
            var saveError: NSError?
            if self.hasChanges && !self.save(&saveError) {
                println("Failed to save managed object context")
                if let error = saveError {
                    println("Error: \(saveError)")
                }
            }
        }

        switch concurrencyType {
        case .ConfinementConcurrencyType:
            sharedSaveFlow()
        case .MainQueueConcurrencyType:
            fallthrough
        case .PrivateQueueConcurrencyType:
            self.performBlock { [unowned self] in
                sharedSaveFlow()
            }
        }
    }
}

Refactor save errors to not throw away the error.

//
//  NSManagedObjectContext+Extensions.swift
//  CoreDataSMS
//
//  Created by Robert Edwards on 2/23/15.
//  Copyright (c) 2015 Big Nerd Ranch. All rights reserved.
//

import CoreData

public typealias CoreDataSaveCompletion = (Bool, NSError?) -> Void

public extension NSManagedObjectContext {
    public func saveContextAndWait(error: NSErrorPointer) -> Bool {
        var success = true
        switch concurrencyType {
        case .ConfinementConcurrencyType:
            success = sharedSaveFlow(error)
        case .MainQueueConcurrencyType:
            fallthrough
        case .PrivateQueueConcurrencyType:
            self.performBlockAndWait { [unowned self] in
                success = self.sharedSaveFlow(error)
            }
        }

        return success
    }

    public func saveContext(completion: CoreDataSaveCompletion? = nil) {
        var error: NSError?
        var success: Bool = true
        switch concurrencyType {
        case .ConfinementConcurrencyType:
            success = sharedSaveFlow(&error)
            completion?(success, error)
        case .MainQueueConcurrencyType:
            fallthrough
        case .PrivateQueueConcurrencyType:
            self.performBlock { [unowned self] in
                success = self.sharedSaveFlow(&error)
                completion?(success, error)
            }
        }
    }

    private func sharedSaveFlow(error: NSErrorPointer) -> Bool {
        var success = true
        if self.hasChanges && !self.save(error) {
            success = false
            println("Failed to save managed object context")
            if let error = error.memory {
                println("Error: \(error)")
            }
        }
        return success
    }
}


// RUN: %empty-directory(%t)

// RUN: %empty-directory(%t/linker)
// RUN: %target-build-swift -emit-module -c %S/Inputs/library.swift -o %t/linker/library.o
// RUN: %target-build-swift -emit-library -c %S/Inputs/library.swift -o %t/linker/library.o
// RUN: %target-build-swift %S/main.swift %t/linker/library.o -I %t/linker/ -L %t/linker/ -o %t/linker/main

// RUN: %target-build-swift -g -emit-module -c %S/Inputs/library.swift -o %t/linker/library.o
// RUN: %target-build-swift -g -emit-library -c %S/Inputs/library.swift -o %t/linker/library.o
// RUN: %target-build-swift -g %S/main.swift %t/linker/library.o -I %t/linker/ -L %t/linker/ -o %t/linker/main

import library

func testFunction<T>(withCompletion completion: (Result<T, Error>) -> Void) { }
testFunction { (result: GenericResult<Int>) in }

Add qualified import of Result in the test

// RUN: %empty-directory(%t)

// RUN: %empty-directory(%t/linker)
// RUN: %target-build-swift -emit-module -c %S/Inputs/library.swift -o %t/linker/library.o
// RUN: %target-build-swift -emit-library -c %S/Inputs/library.swift -o %t/linker/library.o
// RUN: %target-build-swift %S/main.swift %t/linker/library.o -I %t/linker/ -L %t/linker/ -o %t/linker/main

// RUN: %target-build-swift -g -emit-module -c %S/Inputs/library.swift -o %t/linker/library.o
// RUN: %target-build-swift -g -emit-library -c %S/Inputs/library.swift -o %t/linker/library.o
// RUN: %target-build-swift -g %S/main.swift %t/linker/library.o -I %t/linker/ -L %t/linker/ -o %t/linker/main

import library
import enum library.Result

func testFunction<T>(withCompletion completion: (Result<T, Error>) -> Void) { }
testFunction { (result: GenericResult<Int>) in }


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

final class TermTests: XCTestCase {
	func testPiTypeDescription() {
		assert(identity.typecheck().right?.description, ==, "Π : Type . Π : a . a")
	}

	func testSigmaTypeDescription() {
		assert(Term.sigma(.unit, .unit).typecheck().right?.description, ==, "Σ Unit . Unit")
	}

	func testGlobalsPrintTheirNames() {
		assert(Term.free("Global").description, ==, "Global")
	}

	func testNullarySumsAreUnitType() {
		assert(Term.sum([]), ==, .unitType)
	}
}

private let identity = Term.pi(.type, .pi(0, 0))
private let constant = Term.pi(.type, .pi(.type, .pi(1, .pi(1, 1))))

import Assertions
import Manifold
import XCTest

Test that the sum is the identity constructor for unary arguments.

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

final class TermTests: XCTestCase {
	func testPiTypeDescription() {
		assert(identity.typecheck().right?.description, ==, "Π : Type . Π : a . a")
	}

	func testSigmaTypeDescription() {
		assert(Term.sigma(.unit, .unit).typecheck().right?.description, ==, "Σ Unit . Unit")
	}

	func testGlobalsPrintTheirNames() {
		assert(Term.free("Global").description, ==, "Global")
	}

	func testNullarySumsAreUnitType() {
		assert(Term.sum([]), ==, .unitType)
	}

	func testUnarySumsAreTheIdentityConstructor() {
		assert(Term.sum([ .booleanType ]), ==, .booleanType)
	}
}

private let identity = Term.pi(.type, .pi(0, 0))
private let constant = Term.pi(.type, .pi(.type, .pi(1, .pi(1, 1))))

import Assertions
import Manifold
import XCTest


//
//  InfoRequest.swift
//  Rocket.Chat
//
//  Created by Matheus Cardoso on 9/18/17.
//  Copyright © 2017 Rocket.Chat. All rights reserved.
//
//  DOCS: https://rocket.chat/docs/developer-guides/rest-api/miscellaneous/info

import SwiftyJSON

final class InfoRequest: APIRequest {
    typealias APIResourceType = InfoResource

    let path = "/api/v1/info"
}

final class InfoResource: APIResource {
    var version: String? {
        return raw?["info"]["version"].string
    }
}

Update info request to use the /api/info endpoint

//
//  InfoRequest.swift
//  Rocket.Chat
//
//  Created by Matheus Cardoso on 9/18/17.
//  Copyright © 2017 Rocket.Chat. All rights reserved.
//
//  DOCS: https://rocket.chat/docs/developer-guides/rest-api/miscellaneous/info

import SwiftyJSON

final class InfoRequest: APIRequest {
    typealias APIResourceType = InfoResource

    let path = "/api/info"
}

final class InfoResource: APIResource {
    var version: String? {
        return raw?["version"].string
    }
}


//
//  SpreadsheetView+UIScrollView.swift
//  SpreadsheetView
//
//  Created by Kishikawa Katsumi on 5/1/17.
//  Copyright © 2017 Kishikawa Katsumi. All rights reserved.
//

import UIKit

extension SpreadsheetView {
    public override func isKind(of aClass: AnyClass) -> Bool {
        return rootView.isKind(of: aClass)
    }

    public var contentOffset: CGPoint {
        get {
            return tableView.contentOffset
        }
        set {
            tableView.contentOffset = newValue
        }
    }

    public var scrollIndicatorInsets: UIEdgeInsets {
        get {
            return overlayView.scrollIndicatorInsets
        }
        set {
            overlayView.scrollIndicatorInsets = newValue
        }
    }

    public var contentSize: CGSize {
        get {
            return overlayView.contentSize
        }
    }

    public var contentInset: UIEdgeInsets {
        get {
            return rootView.contentInset
        }
        set {
            rootView.contentInset = newValue
        }
    }

    var _isAutomaticContentOffsetAdjustmentEnabled: Bool {
        get {
            return isAutomaticContentOffsetAdjustmentEnabled
        }
    }

    var _canScrollX: Bool {
        return tableView.isScrollEnabled && tableView.contentSize.width > tableView.frame.width
    }

    var _canScrollY: Bool {
        return tableView.isScrollEnabled && tableView.contentSize.height > tableView.frame.height
    }

    var _panGestureRecognizer: UIPanGestureRecognizer? {
        get {
            return rootView.panGestureRecognizer
        }
    }

    func _setAutomaticContentOffsetAdjustmentEnabled(_ enabled: Bool) {
        isAutomaticContentOffsetAdjustmentEnabled = enabled
    }

    func _adjustContentOffsetIfNecessary() {}

    func _notifyDidScroll() {
        adjustScrollViewSizes()
        adjustOverlayViewContentSize()
    }
}

Use `forwardingTarget(for:)` to redirect UIScrollView's methods instead of overriding undocumented methods.

//
//  SpreadsheetView+UIScrollView.swift
//  SpreadsheetView
//
//  Created by Kishikawa Katsumi on 5/1/17.
//  Copyright © 2017 Kishikawa Katsumi. All rights reserved.
//

import UIKit

extension SpreadsheetView {
    public override func isKind(of aClass: AnyClass) -> Bool {
        return rootView.isKind(of: aClass)
    }

    public var contentOffset: CGPoint {
        get {
            return tableView.contentOffset
        }
        set {
            tableView.contentOffset = newValue
        }
    }

    public var scrollIndicatorInsets: UIEdgeInsets {
        get {
            return overlayView.scrollIndicatorInsets
        }
        set {
            overlayView.scrollIndicatorInsets = newValue
        }
    }

    public var contentSize: CGSize {
        get {
            return overlayView.contentSize
        }
    }

    public var contentInset: UIEdgeInsets {
        get {
            return rootView.contentInset
        }
        set {
            rootView.contentInset = newValue
        }
    }

    func _notifyDidScroll() {
        adjustScrollViewSizes()
        adjustOverlayViewContentSize()
    }

    public override func forwardingTarget(for aSelector: Selector!) -> Any? {
        if overlayView.responds(to: aSelector) {
            return overlayView
        } else {
            return super.forwardingTarget(for: aSelector)
        }
    }
}


import Foundation
import UIKit

class Blockquote {
    static let attributeName = "AZBlockquote"
}

struct BlockquoteFormatter: ParagraphAttributeFormatter {
    let attributes: [String: AnyObject] = {
        let style = NSMutableParagraphStyle()
        style.headIndent = Metrics.defaultIndentation
        style.firstLineHeadIndent = style.headIndent
        style.tailIndent = -Metrics.defaultIndentation
        style.paragraphSpacing = Metrics.defaultIndentation
        style.paragraphSpacingBefore = Metrics.defaultIndentation

        return [
            NSParagraphStyleAttributeName: style,
            Blockquote.attributeName: Blockquote()
        ]
    }()

    func present(inAttributes attributes: [String : AnyObject]) -> Bool {
        return attributes[Blockquote.attributeName] is Blockquote
    }
}

Make blockquote attribute comply to NSCoding in order to be serialised properly on copy paste.

import Foundation
import UIKit

class Blockquote: NSObject, NSCoding {
    static let attributeName = "AZBlockquote"

    public func encode(with aCoder: NSCoder) {

    }

    override public init() {

    }

    required public init?(coder aDecoder: NSCoder){

    }
}

struct BlockquoteFormatter: ParagraphAttributeFormatter {
    let attributes: [String: AnyObject] = {
        let style = NSMutableParagraphStyle()
        style.headIndent = Metrics.defaultIndentation
        style.firstLineHeadIndent = style.headIndent
        style.tailIndent = -Metrics.defaultIndentation
        style.paragraphSpacing = Metrics.defaultIndentation
        style.paragraphSpacingBefore = Metrics.defaultIndentation

        return [
            NSParagraphStyleAttributeName: style,
            Blockquote.attributeName: Blockquote()
        ]
    }()

    func present(inAttributes attributes: [String : AnyObject]) -> Bool {
        return attributes[Blockquote.attributeName] is Blockquote
    }
}


//: Playground - noun: a place where people can play

import Foundation

struct myStruct {
}

func switchOnAny(any: Any) -> String {
    println("Dynamic Type == \(any.dynamicType)")
    switch any {
    case let array as [Any]:
        return "Array"
    case let array as NSArray:
        return "NSArray"
    default:
        return "Default"
    }
}

let emptyStringArray : [String] = []
let stringArray : [String] = ["Bob", "Roger"]
let intArray = [1, 2, 3]
let customStructArray : [myStruct] = []

println("\t\touput : \(switchOnAny([]))")
println("\t\touput : \(switchOnAny(emptyStringArray))")
println("\t\touput : \(switchOnAny(stringArray))")
println("\t\touput : \(switchOnAny(intArray))")
println("\t\touput : \(switchOnAny(customStructArray))")

Add more experimentation in playground

//: Playground - noun: a place where people can play

import Foundation

//protocol ArrayType {}
//extension Array : ArrayType {}
//extension NSArray : ArrayType {}

struct myStruct {
}

func switchOnAny(any: Any) -> String {
    println("Dynamic Type == \(any.dynamicType)")
    switch any {
//    case let array as ArrayType:
//        return "Stack"
    case let array as [Any]:
        return "Array"
    case let array as NSArray:
        return "NSArray"
    default:
        return "Default"
    }
}

let emptyStringArray : [String] = []
let stringArray : [String] = ["Bob", "Roger"]
let intArray = [1, 2, 3]
let customStructArray : [myStruct] = []

println("\t\touput : \(switchOnAny([]))")
println("\t\touput : \(switchOnAny(emptyStringArray))")
println("\t\touput : \(switchOnAny(stringArray))")
println("\t\touput : \(switchOnAny(intArray))")
println("\t\touput : \(switchOnAny(customStructArray))")


//
//  UIImageView.swift
//  SwiftyPress
//
//  Created by Basem Emara on 4/1/16.
//
//

import UIKit
import Kingfisher

public extension UIImageView {

    /**
     Set an image with a URL and placeholder using caching.

     - parameter URL:         The URL of the image.
     - parameter placeholder: The palceholder image when retrieving the image at the URL.
     */
    public func setURL(_ url: String, placeholder: String? = "placeholder") {
        self.kf.setImage(with: URL(string: url)!,
            placeholder: placeholder != nil ? UIImage(named: placeholder!) : nil)
    }

}

Fix image extension when loading blank URL’s based on Swift 3 migration changes.

//
//  UIImageView.swift
//  SwiftyPress
//
//  Created by Basem Emara on 4/1/16.
//
//

import UIKit
import Kingfisher

public extension UIImageView {

    /**
     Set an image with a URL and placeholder using caching.

     - parameter URL:         The URL of the image.
     - parameter placeholder: The palceholder image when retrieving the image at the URL.
     */
    public func setURL(_ url: String, placeholder: String? = "placeholder") {
        guard let url = URL(string: url) else {
            self.image = UIImage(named: placeholder!)
            return
        }

        self.kf.setImage(with: url, placeholder:
            placeholder != nil ? UIImage(named: placeholder!) : nil)
    }

}


//
//  UIAlertController+Show.swift
//  UIAlertController+Show
//
//  Created by Erik Ackermann on 1/20/16.
//
//

import Foundation
import UIKit
import ObjectiveC

private var alertWindowAssociationKey: UInt8 = 0

extension UIAlertController {

    var alertWindow: UIWindow? {
        get {
            return objc_getAssociatedObject(self, &alertWindowAssociationKey) as? UIWindow
        }
        set(newValue) {
            objc_setAssociatedObject(self, &alertWindowAssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    @objc public func show() {
        show(animated: true)
    }

    @objc public func show(animated: Bool) {
        self.alertWindow = UIWindow(frame: UIScreen.main.bounds)
        self.alertWindow?.rootViewController = UIViewController()
        self.alertWindow?.windowLevel = UIWindowLevelAlert + 1
        self.alertWindow?.makeKeyAndVisible()
        self.alertWindow?.rootViewController?.present(self, animated: animated, completion: nil)
    }

    override open func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)

        self.alertWindow?.isHidden = true
        self.alertWindow = nil
    }
}

Fix missing Swift 3.0 syntax changes.

//
//  UIAlertController+Show.swift
//  UIAlertController+Show
//
//  Created by Erik Ackermann on 1/20/16.
//
//

import Foundation
import UIKit
import ObjectiveC

private var alertWindowAssociationKey: UInt8 = 0

extension UIAlertController {

    var alertWindow: UIWindow? {
        get {
            return objc_getAssociatedObject(self, &alertWindowAssociationKey) as? UIWindow
        }
        set(newValue) {
            objc_setAssociatedObject(self, &alertWindowAssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    @objc public func show() {
        show(true)
    }

    @objc public func show(_ animated: Bool) {
        self.alertWindow = UIWindow(frame: UIScreen.main.bounds)
        self.alertWindow?.rootViewController = UIViewController()
        self.alertWindow?.windowLevel = UIWindowLevelAlert + 1
        self.alertWindow?.makeKeyAndVisible()
        self.alertWindow?.rootViewController?.present(self, animated: animated, completion: nil)
    }

    override open func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)

        self.alertWindow?.isHidden = true
        self.alertWindow = nil
    }
}


//
//  BaseViewController.swift
//  Rocket.Chat
//
//  Created by Rafael K. Streit on 7/6/16.
//  Copyright © 2016 Rocket.Chat. All rights reserved.
//

import UIKit

class BaseViewController: UIViewController {
    var isNavigationBarTransparent: Bool {
        return false
    }

    func updateNavigationBarTransparency() {
        if isNavigationBarTransparent {
            navigationController?.navigationBar.setTransparent()
        } else {
            navigationController?.navigationBar.setNonTransparent()
        }

        navigationController?.redrawNavigationBar()
    }

    func willBePushed(animated: Bool) {
        updateNavigationBarTransparency()
    }

    func willBePopped(animated: Bool) {
        let controller = navigationController?.topViewController as? BaseViewController
        controller?.updateNavigationBarTransparency()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        ThemeManager.addObserver(self)

        navigationItem.backBarButtonItem = UIBarButtonItem(
            title: "",
            style: .plain,
            target: nil,
            action: nil
        )
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        let screenName = String(describing: type(of: self))
        AnalyticsManager.log(event: .screenView(screenName: screenName))
    }

    override func applyTheme() {
        super.applyTheme()
        updateNavigationBarTransparency()
    }
}

Fix navigation bar transparent after pop

//
//  BaseViewController.swift
//  Rocket.Chat
//
//  Created by Rafael K. Streit on 7/6/16.
//  Copyright © 2016 Rocket.Chat. All rights reserved.
//

import UIKit

class BaseViewController: UIViewController {
    var isNavigationBarTransparent: Bool {
        return false
    }

    func updateNavigationBarTransparency() {
        if isNavigationBarTransparent {
            navigationController?.navigationBar.setTransparent()
        } else {
            navigationController?.navigationBar.setNonTransparent()
        }

        navigationController?.redrawNavigationBar()
    }

    func willBePushed(animated: Bool) {
        updateNavigationBarTransparency()
    }

    func willBePopped(animated: Bool) {
        if let controller = navigationController?.topViewController as? BaseViewController {
            controller.updateNavigationBarTransparency()
        } else {
            navigationController?.navigationBar.setNonTransparent()
            navigationController?.redrawNavigationBar()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        ThemeManager.addObserver(self)

        navigationItem.backBarButtonItem = UIBarButtonItem(
            title: "",
            style: .plain,
            target: nil,
            action: nil
        )
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        let screenName = String(describing: type(of: self))
        AnalyticsManager.log(event: .screenView(screenName: screenName))
    }

    override func applyTheme() {
        super.applyTheme()
        updateNavigationBarTransparency()
    }
}


/**
    If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these
    multiples is 23.

    Find the sum of all the multiples of 3 or 5 below 1000.
*/

let MAX = 1000                              // Upperbound
let factors:Array<Int> = [3,5]              // Factors to check for multiples

/*
    Iterates through the given Natural numbers collection.
    If an element of the Natural numbers collections is a multiple
    of the given factors, add it to the current sum.
*/

func findSum() {
    var sumOfMultiples:Int = 0              // Initialize and set sum to 0

    for i in factors.minElement()!..<MAX {  // Iterate from lowerbound to upperbound.
        for j in factors {                  // Iterate over given factors.
            if i % j == 0 {                 // If current element of the collection N is a multiple of current factor element,
                sumOfMultiples += i         // add the current element to the current sum.
                break
            }
        }
    }

    print(sumOfMultiples)                   // Return summated result of found factor multiples.
}

Revert removing returning value, actually call execute and print result

/**
    If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these
    multiples is 23.

    Find the sum of all the multiples of 3 or 5 below 1000.
*/

let MAX = 1000                              // Upperbound
let factors:Array<Int> = [3,5]              // Factors to check for multiples

/*
    Iterates through the given Natural numbers collection.
    If an element of the Natural numbers collections is a multiple
    of the given factors, add it to the current sum.
*/

func findSum()-> Int {
    var sumOfMultiples:Int = 0              // Initialize and set sum to 0

    for i in factors.minElement()!..<MAX {  // Iterate from lowerbound to upperbound.
        for j in factors {                  // Iterate over given factors.
            if i % j == 0 {                 // If current element of the collection N is a multiple of current factor element,
                sumOfMultiples += i         // add the current element to the current sum.
                break
            }
        }
    }

    return sumOfMultiples                   // Return summated result of found factor multiples.
}

print(findSum())                            // Execute functie, print result.


//
//  80_RemoveDuplicatesFromSortedArrayII.swift
//  LeetcodeSwift
//
//  Created by yansong li on 2016-11-05.
//  Copyright © 2016 YANSONG LI. All rights reserved.
//

import Foundation

/**
	Title:80 Remove Duplicates from sorted array II
	URL: https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
	Space: O(N)
	Time: O(N)
 */

class RemoveDuplicatesFromSortedArrayII_Solution {
  func removeDuplicates(_ nums: inout [Int]) -> Int {
    let totalCount = nums.count
    guard totalCount > 2 else {
      return totalCount
    }

    // This time we need to treat the first item differently.
    var currentRepeatTolerance = 0
    var lastFoundValidElementIndex = -1
    var lastValidElement = nums[0]

    for num in nums {
      if num != lastValidElement {
        lastFoundValidElementIndex += 1
        nums[lastFoundValidElementIndex] = num
        currentRepeatTolerance = 1
        lastValidElement = num
      } else if currentRepeatTolerance < 2 {
        lastFoundValidElementIndex += 1
        nums[lastFoundValidElementIndex] = num
        currentRepeatTolerance += 1
      }
    }
    return lastFoundValidElementIndex + 1
  }
}

Add Brilliant solution for Remove Duplicates From Sorted Array II.

//
//  80_RemoveDuplicatesFromSortedArrayII.swift
//  LeetcodeSwift
//
//  Created by yansong li on 2016-11-05.
//  Copyright © 2016 YANSONG LI. All rights reserved.
//

import Foundation

/**
	Title:80 Remove Duplicates from sorted array II
	URL: https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
	Space: O(N)
	Time: O(N)
 */

class RemoveDuplicatesFromSortedArrayII_Solution {
  func removeDuplicates(_ nums: inout [Int]) -> Int {
    let totalCount = nums.count
    guard totalCount > 2 else {
      return totalCount
    }

    // This time we need to treat the first item differently.
    var currentRepeatTolerance = 0
    var lastFoundValidElementIndex = -1
    var lastValidElement = nums[0]

    for num in nums {
      if num != lastValidElement {
        lastFoundValidElementIndex += 1
        nums[lastFoundValidElementIndex] = num
        currentRepeatTolerance = 1
        lastValidElement = num
      } else if currentRepeatTolerance < 2 {
        lastFoundValidElementIndex += 1
        nums[lastFoundValidElementIndex] = num
        currentRepeatTolerance += 1
      }
    }
    return lastFoundValidElementIndex + 1
  }

  func brilliantSolution(_ nums: inout [Int]) -> Int {
    var lastValidIndex = 0
    for num in nums {
      if lastValidIndex < 2 || num > nums[lastValidIndex - 2] {
        nums[lastValidIndex] = num
        lastValidIndex += 1
      }
    }
    return lastValidIndex
  }
}


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

// RUN: %target-swift-frontend %s -parse -verify
protocol c : b { // expected-error {{use of undeclared type 'b'}} expected-note {{to match this opening '{'}}
	func b // expected-error {{expected '(' in argument list of function declaration}}
// expected-error@+1 {{expected '}' in protocol}}

Update an crasher test not to use -verify

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

// RUN: not %target-swift-frontend %s -parse
protocol c : b {
	func b


//
//  String+Range.swift
//  Pods
//
//  Created by Jelle Vandebeeck on 05/06/2017.
//
//

import Foundation

extension String {

    // swiftlint:disable identifier_name
    subscript (r: Range<Int>) -> String? {
        guard
            let start = index(startIndex, offsetBy: r.lowerBound, limitedBy: endIndex),
            // swiftlint:disable identifier_name
            let end = index(startIndex, offsetBy: r.upperBound - r.lowerBound, limitedBy: endIndex) else {
            return nil
        }

        return String(self[Range(start ..< end)])
    }

}

Fix the compile warning in Xcode 10.

//
//  String+Range.swift
//  Pods
//
//  Created by Jelle Vandebeeck on 05/06/2017.
//
//

import Foundation

extension String {

    // swiftlint:disable identifier_name
    subscript (r: Range<Int>) -> String? {
        guard
            let start = index(startIndex, offsetBy: r.lowerBound, limitedBy: endIndex),
            // swiftlint:disable identifier_name
            let end = index(startIndex, offsetBy: r.upperBound - r.lowerBound, limitedBy: endIndex) else {
            return nil
        }

        let range = start..<end
        return String(self[range])
    }

}


import UIKit

class VideoFormatter: StandardAttributeFormatter {
    static let htmlRepresentationKey = "Video.htmlRepresentation"

    init() {
        super.init(attributeKey: NSAttachmentAttributeName,
                   attributeValue: VideoAttachment(identifier: NSUUID().uuidString),
                   htmlRepresentationKey: VideoFormatter.htmlRepresentationKey)
    }

    override func apply(to attributes: [String : Any], andStore representation: HTMLRepresentation?) -> [String: Any] {
        let elementRepresentation = representation as? HTMLElementRepresentation

        guard representation == nil || elementRepresentation != nil else {
            fatalError("This should not be possible.  Review the logic")
        }

        return apply(to: attributes, andStore: elementRepresentation)
    }

    func apply(to attributes: [String : Any], andStore representation: HTMLElementRepresentation?) -> [String: Any] {

        if let representation = representation {

            let srcURL: URL?

            if let urlString = representation.valueForAttribute(named: "src") {
                srcURL = URL(string: urlString)
            } else {
                srcURL = nil
            }

            let posterURL: URL?

            if let urlString = representation.valueForAttribute(named: "poster") {
                posterURL = URL(string: urlString)
            } else {
                posterURL = nil
            }

            let attachment = VideoAttachment(identifier: UUID().uuidString, srcURL: srcURL, posterURL: posterURL)

            attributeValue = attachment
        }

        return super.apply(to: attributes, andStore: representation)
    }
}

Read extra attributes on videos.

import UIKit

class VideoFormatter: StandardAttributeFormatter {
    static let htmlRepresentationKey = "Video.htmlRepresentation"

    init() {
        super.init(attributeKey: NSAttachmentAttributeName,
                   attributeValue: VideoAttachment(identifier: NSUUID().uuidString),
                   htmlRepresentationKey: VideoFormatter.htmlRepresentationKey)
    }

    override func apply(to attributes: [String : Any], andStore representation: HTMLRepresentation?) -> [String: Any] {
        let elementRepresentation = representation as? HTMLElementRepresentation

        guard representation == nil || elementRepresentation != nil else {
            fatalError("This should not be possible.  Review the logic")
        }

        return apply(to: attributes, andStore: elementRepresentation)
    }

    func apply(to attributes: [String : Any], andStore representation: HTMLElementRepresentation?) -> [String: Any] {

        if let representation = representation {

            var namedAttributes = [String:String]()
            for attributeRepresentation in representation.attributes {
                if let value = attributeRepresentation.value {
                    namedAttributes[attributeRepresentation.name] = value
                }
            }

            let srcURL: URL?

            if let urlString = representation.valueForAttribute(named: "src") {
                srcURL = URL(string: urlString)
                namedAttributes.removeValue(forKey: "src")
            } else {
                srcURL = nil
            }

            let posterURL: URL?

            if let urlString = representation.valueForAttribute(named: "poster") {
                posterURL = URL(string: urlString)
                namedAttributes.removeValue(forKey: "poster")
            } else {
                posterURL = nil
            }

            let attachment = VideoAttachment(identifier: UUID().uuidString, srcURL: srcURL, posterURL: posterURL)

            attachment.namedAttributes = namedAttributes

            attributeValue = attachment
        }

        return super.apply(to: attributes, andStore: representation)
    }
}


//
//  String+PercentEncoder.swift
//  PercentEncoder
//
//  Created by Kazunobu Tasaka on 8/4/15.
//  Copyright (c) 2015 Kazunobu Tasaka. All rights reserved.
//

import Foundation

public extension String {
    func encodeURI() -> String {
        return PercentEncoding.EncodeURI.evaluate(string: self)
    }

    func encodeURIComponent() -> String {
        return PercentEncoding.EncodeURIComponent.evaluate(string: self)
    }

    func decodeURI() -> String {
        return PercentEncoding.DecodeURI.evaluate(string: self)
    }

    func decodeURIComponent() -> String {
        return PercentEncoding.DecodeURIComponent.evaluate(string: self)
    }
}

Append prefix string "ped" to String extension methods

//
//  String+PercentEncoder.swift
//  PercentEncoder
//
//  Created by Kazunobu Tasaka on 8/4/15.
//  Copyright (c) 2015 Kazunobu Tasaka. All rights reserved.
//

import Foundation

public extension String {
    func ped_encodeURI() -> String {
        return PercentEncoding.EncodeURI.evaluate(string: self)
    }

    func ped_encodeURIComponent() -> String {
        return PercentEncoding.EncodeURIComponent.evaluate(string: self)
    }

    func ped_decodeURI() -> String {
        return PercentEncoding.DecodeURI.evaluate(string: self)
    }

    func ped_decodeURIComponent() -> String {
        return PercentEncoding.DecodeURIComponent.evaluate(string: self)
    }
}


//
//  ViewController.swift
//  CarteDemo
//
//  Created by 전수열 on 8/4/15.
//  Copyright (c) 2015 Suyeol Jeon. All rights reserved.
//

import Carte
import UIKit

public class ViewController: UIViewController {

    public override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Carte Demo"
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(
            title: "\u{2699}",
            style: .Plain,
            target: self,
            action: "settingsDidTap"
        )
    }

    public func settingsDidTap() {
        let item = CarteItem()
        item.name = "Carte"
        item.version = "1.0.0"
        item.licenseName = "MIT"
        item.licenseText = "Hello, World!"

        let carteViewController = CarteViewController()
        carteViewController.items.append(item)

        let navigationController = UINavigationController(rootViewController: carteViewController)
        self.presentViewController(navigationController, animated: true, completion: nil)
    }

}

Remove hard coded Carte item.

//
//  ViewController.swift
//  CarteDemo
//
//  Created by 전수열 on 8/4/15.
//  Copyright (c) 2015 Suyeol Jeon. All rights reserved.
//

import Carte
import UIKit

public class ViewController: UIViewController {

    public override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Carte Demo"
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(
            title: "\u{2699}",
            style: .Plain,
            target: self,
            action: "settingsDidTap"
        )
    }

    public func settingsDidTap() {
        let carteViewController = CarteViewController()
        let navigationController = UINavigationController(rootViewController: carteViewController)
        self.presentViewController(navigationController, animated: true, completion: nil)
    }

}


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

final class InferenceTests: XCTestCase {
	func testVariablesAreAssignedAFreshTypeVariable() {
		let expression = Expression(variable: 0)
		assertEqual(assertRight(typeOf(expression))?.0, Type(Variable()))
	}
}

import Manifold
import Prelude
import XCTest

Test that applications are typed with a fresh type variable.

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

final class InferenceTests: XCTestCase {
	func testVariablesAreAssignedAFreshTypeVariable() {
		let expression = Expression(variable: 0)
		assertEqual(assertRight(typeOf(expression))?.0, Type(Variable()))
	}

	func testApplicationsAreAssignedAFreshTypeVariable() {
		let function = Expression(variable: 0) // fixme: this should be an abstraction
		let variable = Expression(variable: 1)
		let application = Expression(apply: function, to: variable)
		assertEqual(assertRight(typeOf(application))?.0, Type(Variable()))
	}
}

import Manifold
import Prelude
import XCTest


//
//  SpringBoardLaunchedAppViewController.swift
//  UIPlayground
//
//  Created by Kip Nicol on 9/27/16.
//  Copyright © 2016 Kip Nicol. All rights reserved.
//

import UIKit

class SpringBoardLaunchedAppViewController: UIViewController {

    let exitButton = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white

        view.addSubview(exitButton)
        exitButton.translatesAutoresizingMaskIntoConstraints = false
        exitButton.anchorConstraintsToCenterInSuperview()
        exitButton.contentEdgeInsets = UIEdgeInsets(top: 7, left: 20, bottom: 7, right: 20)
        exitButton.setTitle("Exit", for: .normal)
        exitButton.setTitleColor(.white, for: .normal)
        exitButton.setTitleColor(.red, for: .highlighted)
        exitButton.titleLabel?.font = .systemFont(ofSize: 26)
        exitButton.addTarget(self, action: #selector(exitPressed), for: .touchUpInside)
        exitButton.backgroundColor = .black
        exitButton.clipsToBounds = true
        exitButton.layer.cornerRadius = 8
    }

    // MARK: - Actions

    func exitPressed(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
    }
}

Use red for launched app for now.

//
//  SpringBoardLaunchedAppViewController.swift
//  UIPlayground
//
//  Created by Kip Nicol on 9/27/16.
//  Copyright © 2016 Kip Nicol. All rights reserved.
//

import UIKit

class SpringBoardLaunchedAppViewController: UIViewController {

    let exitButton = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .red

        view.addSubview(exitButton)
        exitButton.translatesAutoresizingMaskIntoConstraints = false
        exitButton.anchorConstraintsToCenterInSuperview()
        exitButton.contentEdgeInsets = UIEdgeInsets(top: 7, left: 20, bottom: 7, right: 20)
        exitButton.setTitle("Exit", for: .normal)
        exitButton.setTitleColor(.white, for: .normal)
        exitButton.setTitleColor(.red, for: .highlighted)
        exitButton.titleLabel?.font = .systemFont(ofSize: 26)
        exitButton.addTarget(self, action: #selector(exitPressed), for: .touchUpInside)
        exitButton.backgroundColor = .black
        exitButton.clipsToBounds = true
        exitButton.layer.cornerRadius = 8
    }

    // MARK: - Actions

    func exitPressed(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
    }
}


class SemverIncrementer {
    func usage() {
        print("usage: origin-version $incrementBy")
        print("e.g. semver-incrementer 0.6.6 9")
    }

    func run(args: [String]) {
        guard args.count > 2 else {
            useGit()
            return
        }
        useInput(args)
        exit(0)
    }

    func useInput(args: [String]) {
        describe(args[1], incrementBy: args[2])
    }

    func describe(originVersion: String, incrementBy: String) {
        guard let version = Semver.fromString(originVersion.trim()) else {
            print("error:\(originVersion):not a valid version")
            return
        }

        guard let by = Int(incrementBy) else {
            print("error:\(incrementBy) is not a valid increment value")
            return
        }
        print(version.increment(by).short)
    }

    func useGit() {
        guard let git = Git(path:"/usr/bin/git") else {
            usage()
            return
        }
        guard let version = git.lastTag as? String else {
            print("error: no version")
            return
        }
        describe(version, incrementBy: "1")
    }
}

Revert "add exit call when done running"

class SemverIncrementer {
    func usage() {
        print("usage: origin-version $incrementBy")
        print("e.g. semver-incrementer 0.6.6 9")
    }

    func run(args: [String]) {
        guard args.count > 2 else {
            useGit()
            return
        }
        useInput(args)
    }

    func useInput(args: [String]) {
        describe(args[1], incrementBy: args[2])
    }

    func describe(originVersion: String, incrementBy: String) {
        guard let version = Semver.fromString(originVersion.trim()) else {
            print("error:\(originVersion):not a valid version")
            return
        }

        guard let by = Int(incrementBy) else {
            print("error:\(incrementBy) is not a valid increment value")
            return
        }
        print(version.increment(by).short)
    }

    func useGit() {
        guard let git = Git(path:"/usr/bin/git") else {
            usage()
            return
        }
        guard let version = git.lastTag as? String else {
            print("error: no version")
            return
        }
        describe(version, incrementBy: "1")
    }
}


//
//  ASAnnotationView.swift
//  AugmentedSzczecin
//
//  Created by Sebastian Jędruszkiewicz on 30/04/15.
//  Copyright (c) 2015 BLStream. All rights reserved.
//

import UIKit

class ASAnnotationView : BLSAugmentedAnnotationView {

    @IBOutlet weak var addressLabel: UILabel!
    @IBOutlet weak var distanceLabel: UILabel!

    class func nibName() -> String {
        return "ASAnnotationView"
    }

    class func view() -> ASAnnotationView? {
        let bundle = NSBundle(forClass: ASAnnotationView.classForCoder())
        return UIView.loadFromNibNamed(ASAnnotationView.nibName(), bundle: bundle) as? ASAnnotationView
    }
}

Add method to setup view from POI

//
//  ASAnnotationView.swift
//  AugmentedSzczecin
//
//  Created by Sebastian Jędruszkiewicz on 30/04/15.
//  Copyright (c) 2015 BLStream. All rights reserved.
//

import UIKit

class ASAnnotationView : BLSAugmentedAnnotationView {

    @IBOutlet weak var addressLabel: UILabel!
    @IBOutlet weak var distanceLabel: UILabel!

    class func nibName() -> String {
        return "ASAnnotationView"
    }

    class func view() -> ASAnnotationView? {
        let bundle = NSBundle(forClass: ASAnnotationView.classForCoder())
        return UIView.loadFromNibNamed(ASAnnotationView.nibName(), bundle: bundle) as? ASAnnotationView
    }

    class func view(withPOI: ASPOI, location: CLLocation) ->ASAnnotationView? {
        let view = UIView.loadFromNibNamed(ASAnnotationView.nibName(), bundle: NSBundle(forClass: ASAnnotationView.classForCoder())) as? ASAnnotationView

        var destinationLat = withPOI.latitude as! CLLocationDegrees
        var destinationLon = withPOI.longitude as! CLLocationDegrees
        var destinationLoc = CLLocation(latitude: destinationLat, longitude: destinationLon)

        view?.distanceLabel.text = String(stringInterpolationSegment: destinationLoc.distanceFromLocation(location))

        withPOI.getAddress(CLGeocoder(), completionHandler: { (address) -> Void in
            view?.addressLabel.text = address!.name
        })

        return view
    }
}


//
//  EditProfileViewController.swift
//  Pods
//
//  Created by John Rikard Nilsen on 23/2/16.
//
//

import UIKit
import Tapglue

class EditProfileViewController: UIViewController {
    @IBOutlet weak var userNameTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        userNameTextField.text = TGUser.currentUser().username

        let save = UIBarButtonItem(barButtonSystemItem: .Save, target: self, action: "saveTapped")
        navigationItem.rightBarButtonItem = save
    }

    func saveTapped() {
        navigationItem.rightBarButtonItem?.enabled = false
        let user = TGUser.currentUser()
        user.username = userNameTextField.text
        user.saveWithCompletionBlock { (success: Bool, error: NSError!) -> Void in
            dispatch_async(dispatch_get_main_queue()) { () -> Void in
                self.navigationItem.rightBarButtonItem?.enabled = true
                if success {
                    self.navigationController?.popViewControllerAnimated(true)
                } else {
                    AlertFactory.defaultAlert(self)
                }
            }

        }
    }
}

Add background color to edit profile screen

//
//  EditProfileViewController.swift
//  Pods
//
//  Created by John Rikard Nilsen on 23/2/16.
//
//

import UIKit
import Tapglue

class EditProfileViewController: UIViewController {
    @IBOutlet weak var userNameTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        userNameTextField.text = TGUser.currentUser().username

        let save = UIBarButtonItem(barButtonSystemItem: .Save, target: self, action: "saveTapped")
        navigationItem.rightBarButtonItem = save
        view.backgroundColor = UIColor.clearColor()
        applyConfiguration(TapglueUI.config)
    }

    func saveTapped() {
        navigationItem.rightBarButtonItem?.enabled = false
        let user = TGUser.currentUser()
        user.username = userNameTextField.text
        user.saveWithCompletionBlock { (success: Bool, error: NSError!) -> Void in
            dispatch_async(dispatch_get_main_queue()) { () -> Void in
                self.navigationItem.rightBarButtonItem?.enabled = true
                if success {
                    self.navigationController?.popViewControllerAnimated(true)
                } else {
                    AlertFactory.defaultAlert(self)
                }
            }

        }
    }
}