//
//  UIColor+HexColors.swift
//  Palettes
//
//  Created by Andrew Shepard on 12/11/14.
//  Copyright (c) 2014 Andrew Shepard. All rights reserved.
//

import UIKit

extension UIColor {

    // http://stackoverflow.com/a/27203691

    class func hexColor(_ string: String) -> UIColor {
        let set = CharacterSet.whitespacesAndNewlines
        var colorString = string.trimmingCharacters(in: set).uppercased()

        if (colorString.hasPrefix("#")) {
            colorString = colorString.substring(from: colorString.index(colorString.startIndex, offsetBy: 1))
        }

        if (colorString.characters.count != 6) {
            return UIColor.gray
        }

        var rgbValue: UInt32 = 0
        Scanner(string: colorString).scanHexInt32(&rgbValue)

        return UIColor(
            red:   CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue:  CGFloat(rgbValue & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }
}

Use substring with partial range

//
//  UIColor+HexColors.swift
//  Palettes
//
//  Created by Andrew Shepard on 12/11/14.
//  Copyright (c) 2014 Andrew Shepard. All rights reserved.
//

import UIKit

extension UIColor {

    // http://stackoverflow.com/a/27203691

    class func hexColor(_ string: String) -> UIColor {
        let set = CharacterSet.whitespacesAndNewlines
        var colorString = string.trimmingCharacters(in: set).uppercased()

        if let index = colorString.index(of: "#") {
            colorString = String(colorString[index...])
        }

        if (colorString.characters.count != 6) {
            return UIColor.gray
        }

        var rgbValue: UInt32 = 0
        Scanner(string: colorString).scanHexInt32(&rgbValue)

        return UIColor(
            red:   CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue:  CGFloat(rgbValue & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }
}


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

final class BinaryTreeTests: XCTestCase {
	func testEmptyTreesAreEmpty() {
		XCTAssert(BinaryTree<Int>().isEmpty)
	}

	func testEmptyTreesAreNotLeaves() {
		XCTAssertFalse(BinaryTree<Int>().isLeaf)
	}

	func testEmptyTreesAreNotBranches() {
		XCTAssertFalse(BinaryTree<Int>().isBranch)
	}

	func testLeavesAreLeaves() {
		XCTAssert(BinaryTree(0).isLeaf)
	}

	func testLeavesAreNonEmpty() {
		XCTAssertFalse(BinaryTree(0).isEmpty)
	}

	func testLeavesAreNotBranches() {
		XCTAssertFalse(BinaryTree(0).isBranch)
	}

	func testLeftBranchesAreBranches() {
		XCTAssert(BinaryTree(BinaryTree(0), 0, nil).isBranch)
	}

	func testRightBranchesAreBranches() {
		XCTAssert(BinaryTree(nil, 0, BinaryTree(0)).isBranch)
	}
}

import BinaryTree
import XCTest

Test that branches are branches.

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

final class BinaryTreeTests: XCTestCase {
	func testEmptyTreesAreEmpty() {
		XCTAssert(BinaryTree<Int>().isEmpty)
	}

	func testEmptyTreesAreNotLeaves() {
		XCTAssertFalse(BinaryTree<Int>().isLeaf)
	}

	func testEmptyTreesAreNotBranches() {
		XCTAssertFalse(BinaryTree<Int>().isBranch)
	}

	func testLeavesAreLeaves() {
		XCTAssert(BinaryTree(0).isLeaf)
	}

	func testLeavesAreNonEmpty() {
		XCTAssertFalse(BinaryTree(0).isEmpty)
	}

	func testLeavesAreNotBranches() {
		XCTAssertFalse(BinaryTree(0).isBranch)
	}

	func testLeftBranchesAreBranches() {
		XCTAssert(BinaryTree(BinaryTree(0), 0, nil).isBranch)
	}

	func testRightBranchesAreBranches() {
		XCTAssert(BinaryTree(nil, 0, BinaryTree(0)).isBranch)
	}

	func testBranchesAreBranches() {
		XCTAssert(BinaryTree<Int>(BinaryTree(0), 0, BinaryTree(0)).isBranch)
	}
}

import BinaryTree
import XCTest


//
//  AppDelegate.swift
//  Checklists
//
//  Created by iosdevlog on 15/12/28.
//  Copyright © 2015年 iosdevlog. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    var dataModel = DataModel()

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        let navigationController = window?.rootViewController as! UINavigationController
        let controller = navigationController.viewControllers[0] as! AllListsViewController

        controller.dataModel = dataModel

        // local notification test
        let notifacationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Sound, .Badge], categories: nil)
        UIApplication.sharedApplication().registerUserNotificationSettings(notifacationSettings)

        let date = NSDate(timeIntervalSinceNow: 10)
        let localNotification = UILocalNotification()
        localNotification.fireDate = date
        localNotification.timeZone = NSTimeZone.defaultTimeZone()
        localNotification.applicationIconBadgeNumber = 100
        localNotification.alertBody = "I am a local notification"
        localNotification.soundName = UILocalNotificationDefaultSoundName
        UIApplication.sharedApplication().scheduleLocalNotification(localNotification)

        return true
    }

    func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
        print("didReceiveLocalNotification \(notification)")
    }

    func applicationDidEnterBackground(application: UIApplication) {
        saveData()
    }

    func applicationWillTerminate(application: UIApplication) {
        saveData()
    }

    // MARK: - helper
    func saveData() {
        dataModel.saveChecklists()
    }
}

Remove Notification test from app delegate

//
//  AppDelegate.swift
//  Checklists
//
//  Created by iosdevlog on 15/12/28.
//  Copyright © 2015年 iosdevlog. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    var dataModel = DataModel()

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        let navigationController = window?.rootViewController as! UINavigationController
        let controller = navigationController.viewControllers[0] as! AllListsViewController

        controller.dataModel = dataModel

        return true
    }

    func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
    }

    func applicationDidEnterBackground(application: UIApplication) {
        saveData()
    }

    func applicationWillTerminate(application: UIApplication) {
        saveData()
    }

    // MARK: - helper
    func saveData() {
        dataModel.saveChecklists()
    }
}


//
//  HTTPMethod.swift
//  Linchi
//

/// Enum describing an HTTPMethod
public enum HTTPMethod: String {
    case GET = "GET"
    case POST = "POST"
    case HEAD = "HEAD"
    case DELETE = "DELETE"
    case OPTIONS = "OPTIONS"
    case PUT = "PUT"
    case CONNECT = "CONNECT"
    case PATCH = "PATCH"
    case TRACE = "TRACE"
}

Use the default String values, no need to retype

//
//  HTTPMethod.swift
//  Linchi
//

/// Enum describing an HTTPMethod
public enum HTTPMethod: String {
    case GET
    case POST
    case HEAD
    case DELETE
    case OPTIONS
    case PUT
    case CONNECT
    case PATCH
    case TRACE
}


//
//  ViewController.swift
//  CHCarouselView
//
//  Created by Calvin on 8/5/16.
//  Copyright © 2016 CapsLock. All rights reserved.
//

import UIKit
import Kingfisher

class ViewController: UIViewController {
    @IBOutlet weak var carouselView: CarouselView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let imageUrls = [
            "https://dl.dropboxusercontent.com/u/108987767/Meme/01_Cupido.jpg",
            "https://dl.dropboxusercontent.com/u/108987767/Meme/bugs_everywhere.png",
            "https://dl.dropboxusercontent.com/u/108987767/Meme/p56an6SZj5_d.gif",
            "https://dl.dropboxusercontent.com/u/108987767/Meme/1557643_489616404482423_780202608_n.jpg",
        ]

        carouselView.views = imageUrls
                                .map { url -> UIImageView in
                                    let imageView = UIImageView()
                                    imageView.kf_setImageWithURL(NSURL(string: url)!)
                                    imageView.contentMode = .ScaleAspectFill
                                    imageView.clipsToBounds = true

                                    return imageView
                                }
    }
}

Add example code for selected demo.

//
//  ViewController.swift
//  CHCarouselView
//
//  Created by Calvin on 8/5/16.
//  Copyright © 2016 CapsLock. All rights reserved.
//

import UIKit
import Kingfisher

class ViewController: UIViewController {
    @IBOutlet weak var carouselView: CarouselView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let imageUrls = [
            "https://dl.dropboxusercontent.com/u/108987767/Meme/01_Cupido.jpg",
            "https://dl.dropboxusercontent.com/u/108987767/Meme/bugs_everywhere.png",
            "https://dl.dropboxusercontent.com/u/108987767/Meme/p56an6SZj5_d.gif",
            "https://dl.dropboxusercontent.com/u/108987767/Meme/1557643_489616404482423_780202608_n.jpg",
        ]

        carouselView.selectedCallback = { [unowned self] (currentPage: Int) in
            let alertController = UIAlertController(title: nil, message: "You selected page: \(currentPage) in carousel.", preferredStyle: .Alert)

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

        carouselView.views = imageUrls
                                .map { url -> UIImageView in
                                    let imageView = UIImageView()
                                    imageView.kf_setImageWithURL(NSURL(string: url)!)
                                    imageView.contentMode = .ScaleAspectFill
                                    imageView.clipsToBounds = true

                                    return imageView
                                }
    }
}


//
//  AppURLOpener.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 20/03/2018.
//  Copyright © 2018 Eurofurence. All rights reserved.
//

import Foundation.NSURL
import UIKit.UIApplication

struct AppURLOpener: URLOpener {

    func open(_ url: URL) {
        UIApplication.shared.openURL(url)
    }

}

Remove warning for opening URLs using deprecated API

//
//  AppURLOpener.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 20/03/2018.
//  Copyright © 2018 Eurofurence. All rights reserved.
//

import Foundation.NSURL
import UIKit.UIApplication

struct AppURLOpener: URLOpener {

    func open(_ url: URL) {
        UIApplication.shared.open(url)
    }

}


//
//  AppDelegate.swift
//  React
//
//  Created by Sacha Durand Saint Omer on 29/03/2017.
//  Copyright © 2017 Freshos. All rights reserved.
//

import UIKit
import Komponents

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        let navVC = UINavigationController(rootViewController: NavigationVC())
        navVC.navigationBar.isTranslucent = false
        window?.rootViewController = navVC
        window?.makeKeyAndVisible()
        Komponents.logsEnabled = true
        return true
    }
}

Add injection for Xcode snippet

//
//  AppDelegate.swift
//  React
//
//  Created by Sacha Durand Saint Omer on 29/03/2017.
//  Copyright © 2017 Freshos. All rights reserved.
//

import UIKit
import Komponents

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        Bundle(path: "/Applications/InjectionIII.app/Contents/Resources/iOSInjection10.bundle")?.load()

        window = UIWindow(frame: UIScreen.main.bounds)
        let navVC = UINavigationController(rootViewController: NavigationVC())
        navVC.navigationBar.isTranslucent = false
        window?.rootViewController = navVC
        window?.makeKeyAndVisible()
        Komponents.logsEnabled = true
        return true
    }
}


//
//  Observable.swift
//  Sleipnir
//
//  Created by Artur Termenji on 6/24/14.
//  Copyright (c) 2014 railsware. All rights reserved.
//

import Foundation

class Observable<T> {

    typealias DidSet = (newValue: T) -> ()
    typealias Observer = (post: DidSet)

    var observers = Dictionary<String, Observer>()

    var observableProperty: T {
    didSet {
        notify()
    }
    }

    init(value: T) {
        self.observableProperty = value
    }

    func get() -> T {
        return observableProperty
    }

    func update(value: T) {
        observableProperty = value
    }

    func addObserver(identifier: String, observer: Observer) {
        observers[identifier] = observer
    }

    func removeObserver(identifer: String) {
        observers.removeValueForKey(identifer)
    }

    // Private

    func notify() {
        for (identifier, observer) in observers {
            observer.post(newValue: observableProperty)
        }
    }
}

Fix compiler error with Observer class

//
//  Observable.swift
//  Sleipnir
//
//  Created by Artur Termenji on 6/24/14.
//  Copyright (c) 2014 railsware. All rights reserved.
//

import Foundation

class Observable<T> {

    typealias Observer = (newValue: T) -> ()

    var observers = Dictionary<String, Observer>()

    var observableProperty: T {
    didSet {
        notify()
    }
    }

    init(value: T) {
        self.observableProperty = value
    }

    func get() -> T {
        return observableProperty
    }

    func update(value: T) {
        observableProperty = value
    }

    func addObserver(identifier: String, observer: Observer) {
        observers[identifier] = observer
    }

    func removeObserver(identifer: String) {
        observers.removeValueForKey(identifer)
    }

    // Private

    func notify() {
        for (identifier, observer) in observers {
            observer(newValue: observableProperty)
        }
    }
}


import Vapor

public extension Environment {
    public static func get(_ key: String, _ fallback: String) -> String {
        return ProcessInfo.processInfo.environment[key] ?? fallback
    }
}

public func env(_ key: String, _ fallback: String) -> String {
    return Environment.get(key, fallback)
}

Add more convenience for getting env variables

import Vapor

public extension Environment {
    enum EnvironmentError: Error {
        case keyNotFound(key: String)
    }

    public static func get(_ key: String, _ fallback: String) -> String {
        return ProcessInfo.processInfo.environment[key] ?? fallback
    }

    public static func get(_ key: String) -> String? {
        return ProcessInfo.processInfo.environment[key]
    }
}

public func env(_ key: String, _ fallback: String) -> String {
    return Environment.get(key, fallback)
}

public func env(_ key: String) -> String? {
    return Environment.get(key)
}

public func assertEnv(_ key: String) throws -> String {
    guard let value = Environment.get(key) else {
        throw Environment.EnvironmentError.keyNotFound(key: key)
    }
    return value
}


//
//  AppDelegate.swift
//  QiitaFeed
//
//  Created by Jiro Nagashima on 2/26/15.
//  Copyright (c) 2015 Jiro Nagashima. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
}

Add a flag for stub responses

//
//  AppDelegate.swift
//  QiitaFeed
//
//  Created by Jiro Nagashima on 2/26/15.
//  Copyright (c) 2015 Jiro Nagashima. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        let stubbing = false
        // let stubbing = true

        if stubbing {
            QiitaProvider.sharedProvider = QiitaProvider.StubbingProvider()
        }

        return true
    }
}


// Run test ASTSection.swift, with separate compile and link steps.

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

// RUN: %target-swift-frontend -c -sdk /fake/sdk/path -Xcc -DA -Xcc -DB -emit-module -o %t %S/ASTSection.swift -swift-version 4
// RUN: %swift-ide-test -test-CompilerInvocation-from-module -source-filename=%t/ASTSection.swiftmodule

// Test the inline section mechanism.
// RUN: %target-ld %t/ASTSection.o -sectcreate __DWARF __swift_ast %t/ASTSection.swiftmodule -o %t/ASTSection.dylib -dylib -lSystem -lobjc
// RUN: %lldb-moduleimport-test -verbose %t/ASTSection.dylib | %FileCheck %s

// Test the symbol table entry.
// RUN: %target-ld %t/ASTSection.o -add_ast_path %t/ASTSection.swiftmodule -o %t/ASTSection.dylib -dylib -lSystem -lobjc
// RUN: %lldb-moduleimport-test -verbose %t/ASTSection.dylib | %FileCheck %s

// REQUIRES: OS=macosx

// CHECK: - Swift Version: {{.+}}.{{.+}}
// CHECK: - Compatibility Version: 4
// CHECK: - Target: {{.+}}-{{.+}}-{{.+}}
// CHECK: - SDK path: /fake/sdk/path{{$}}
// CHECK: - -Xcc options: -working-directory {{.+}} -DA -DB
// CHECK: Importing ASTSection... ok!

Update test to link against the Darwin SDK

// Run test ASTSection.swift, with separate compile and link steps.

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

// RUN: %target-swift-frontend -c -Xcc -DA -Xcc -DB -emit-module -o %t %S/ASTSection.swift -swift-version 4
// RUN: %swift-ide-test -test-CompilerInvocation-from-module -source-filename=%t/ASTSection.swiftmodule

// Test the inline section mechanism.
// RUN: %target-ld %t/ASTSection.o -sectcreate __DWARF __swift_ast %t/ASTSection.swiftmodule -o %t/ASTSection.dylib -dylib -L%sdk/usr/lib -lSystem -lobjc
// RUN: %lldb-moduleimport-test -verbose %t/ASTSection.dylib | %FileCheck %s

// Test the symbol table entry.
// RUN: %target-ld %t/ASTSection.o -add_ast_path %t/ASTSection.swiftmodule -o %t/ASTSection.dylib -dylib -L%sdk/usr/lib -lSystem -lobjc
// RUN: %lldb-moduleimport-test -verbose %t/ASTSection.dylib | %FileCheck %s

// REQUIRES: OS=macosx

// CHECK: - Swift Version: {{.+}}.{{.+}}
// CHECK: - Compatibility Version: 4
// CHECK: - Target: {{.+}}-{{.+}}-{{.+}}
// CHECK: - SDK path: {{.*}}MacOS{{.*}}.sdk
// CHECK: - -Xcc options: -working-directory {{.+}} -DA -DB
// CHECK: Importing ASTSection... ok!


// RUN: %target-swiftc_driver %s -g -sanitize=thread %import-libdispatch -o %t_tsan-binary
// RUN: %target-codesign %t_tsan-binary
// RUN: not env %env-TSAN_OPTIONS=abort_on_error=0 %target-run %t_tsan-binary 2>&1 | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: tsan_runtime
// UNSUPPORTED: OS=tvos

// FIXME: This should be covered by "tsan_runtime"; older versions of Apple OSs
// don't support TSan.
// UNSUPPORTED: remote_run

// Test ThreadSanitizer execution end-to-end with libdispatch.

import Dispatch

let sync1 = DispatchSemaphore(value: 0)
let sync2 = DispatchSemaphore(value: 0)
let finish = DispatchSemaphore(value: 0)

let q = DispatchQueue(label: "q", attributes: .concurrent)

var racy = 1

q.async {
  sync1.wait()
  sync2.signal()
  racy = 2
  finish.signal()
}
q.async {
  sync1.signal()
  sync2.wait()
  racy = 3
  finish.signal()
}

finish.wait()
finish.wait()

print("Done!")

// CHECK: ThreadSanitizer: data race
// CHECK: Done!

Disable flaky test to unblock CI

// RUN: %target-swiftc_driver %s -g -sanitize=thread %import-libdispatch -o %t_tsan-binary
// RUN: %target-codesign %t_tsan-binary
// RUN: not env %env-TSAN_OPTIONS=abort_on_error=0 %target-run %t_tsan-binary 2>&1 | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: tsan_runtime
// UNSUPPORTED: OS=tvos

// FIXME: This should be covered by "tsan_runtime"; older versions of Apple OSs
// don't support TSan.
// UNSUPPORTED: remote_run

// rdar://51730684
// REQUIRES: disable

// Test ThreadSanitizer execution end-to-end with libdispatch.

import Dispatch

let sync1 = DispatchSemaphore(value: 0)
let sync2 = DispatchSemaphore(value: 0)
let finish = DispatchSemaphore(value: 0)

let q = DispatchQueue(label: "q", attributes: .concurrent)

var racy = 1

q.async {
  sync1.wait()
  sync2.signal()
  racy = 2
  finish.signal()
}
q.async {
  sync1.signal()
  sync2.wait()
  racy = 3
  finish.signal()
}

finish.wait()
finish.wait()

print("Done!")

// CHECK: ThreadSanitizer: data race
// CHECK: Done!


/*
* Released under the MIT License (MIT), http://opensource.org/licenses/MIT
*
* Copyright (c) 2014 Kåre Morstøl, NotTooBad Software (nottoobadsoftware.com)
*
* Contributors:
*	Kåre Morstøl, https://github.com/kareman - initial API and implementation.
*/

import Foundation

/**
The tempdirectory is unique each time a script is run and is created the first time it is used.
It lies in the user's temporary directory and will be automatically deleted at some point.
*/
public var tempdirectory: NSURL = {
	var error: NSError?
	let tempdirectory = NSURL(fileURLWithPath: NSTemporaryDirectory().stringByAppendingPathComponent("SwiftShell-" + NSProcessInfo.processInfo().globallyUniqueString), isDirectory: true)!
	NSFileManager.defaultManager()
		.createDirectoryAtURL(tempdirectory, withIntermediateDirectories:true, attributes: nil, error: &error)
	if let error = error {
		printErrorAndExit("could not create new temporary directory '\(tempdirectory)':\n\(error.localizedDescription)")
	}

	return tempdirectory
}()

Make URL to "tempdirectory" read only.

/*
* Released under the MIT License (MIT), http://opensource.org/licenses/MIT
*
* Copyright (c) 2014 Kåre Morstøl, NotTooBad Software (nottoobadsoftware.com)
*
* Contributors:
*	Kåre Morstøl, https://github.com/kareman - initial API and implementation.
*/

import Foundation

/**
The tempdirectory is unique each time a script is run and is created the first time it is used.
It lies in the user's temporary directory and will be automatically deleted at some point.
*/
public let tempdirectory: NSURL = {
	var error: NSError?
	let tempdirectory = NSURL(fileURLWithPath: NSTemporaryDirectory().stringByAppendingPathComponent("SwiftShell-" + NSProcessInfo.processInfo().globallyUniqueString), isDirectory: true)!
	NSFileManager.defaultManager()
		.createDirectoryAtURL(tempdirectory, withIntermediateDirectories:true, attributes: nil, error: &error)
	if let error = error {
		printErrorAndExit("could not create new temporary directory '\(tempdirectory)':\n\(error.localizedDescription)")
	}

	return tempdirectory
}()


/*
 Courtesy of the Swift Algorithm Club: https://github.com/raywenderlich/swift-algorithm-club/blob/master/Hash%20Set/HashSet.swift
 Slightly modified to fit my needs. Whether a hashset should allow you to get an element from it that is equal to another element is an academic debate I don't feel like having.
 Sure, I could just pass around a Dictionary<Hashable: Hashable>, but whatever, wanna fight about it?
 */
struct HashSet<T: Hashable> {
    private var dictionary = Dictionary<T, T>()

    init() { }

    init(_ elements: [T]) {
        elements.forEach() { dictionary[$0] = $0 }
    }

    mutating func insert(_ element: T) {
        dictionary[element] = element
    }

    mutating func insert(_ elements: [T]) {
        elements.forEach() { insert($0) }
    }

    mutating func remove(_ element: T) {
        dictionary[element] = nil
    }

    func contains(_ element: T) -> Bool {
        return dictionary[element] != nil
    }

    func get(_ element: T) -> T? {
        return dictionary[element]
    }

    func allElements() -> [T] {
        return Array(dictionary.keys)
    }

    var count: Int {
        return dictionary.count
    }

    var isEmpty: Bool {
        return dictionary.isEmpty
    }
}

Update way to merge sequence into dictionary to use standard library methods

/*
 Courtesy of the Swift Algorithm Club: https://github.com/raywenderlich/swift-algorithm-club/blob/master/Hash%20Set/HashSet.swift
 Slightly modified to fit my needs. Whether a hashset should allow you to get an element from it that is equal to another element is an academic debate I don't feel like having.
 Sure, I could just pass around a Dictionary<Hashable: Hashable>, but whatever, wanna fight about it?
 */
struct HashSet<T: Hashable> {
    private var dictionary = Dictionary<T, T>()

    init() { }

    init(_ elements: [T]) {
        dictionary.merge(zip(elements, elements)) { (_, new) in new }
    }

    mutating func insert(_ element: T) {
        dictionary[element] = element
    }

    mutating func insert(_ elements: [T]) {
        elements.forEach() { insert($0) }
    }

    mutating func remove(_ element: T) {
        dictionary[element] = nil
    }

    func contains(_ element: T) -> Bool {
        return dictionary[element] != nil
    }

    func get(_ element: T) -> T? {
        return dictionary[element]
    }

    func allElements() -> [T] {
        return Array(dictionary.keys)
    }

    var count: Int {
        return dictionary.count
    }

    var isEmpty: Bool {
        return dictionary.isEmpty
    }
}


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

import Foundation

struct Device {

}

Add a function to extract the device model number from the OS itself.

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

import Foundation

struct Device {

	static var identifier: String {
		var systemInfo = utsname()
		uname(&systemInfo)
		let machineMirror = Mirror(reflecting: systemInfo.machine)
		let identifier = machineMirror.children.reduce("") { identifier, element in
			guard let value = element.value as? Int8,
				  value != 0 else {
				return identifier
			}
			return identifier + String(UnicodeScalar(UInt8(value)))
		}

		return identifier
	}

}


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

import UIKit

public class ElloEditableTextView: UITextView {
    required override public init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        sharedSetup()
    }

    required public init(coder: NSCoder) {
        super.init(coder: coder)
        sharedSetup()
    }

    func sharedSetup() {
        backgroundColor = UIColor.greyE5()
        font = UIFont.typewriterFont(12.0)
        textColor = UIColor.blackColor()

        setNeedsDisplay()
    }

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

        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("textViewDidBeginEditing:"), name: UITextViewTextDidBeginEditingNotification, object: .None)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("textViewDidEndEditing:"), name: UITextViewTextDidEndEditingNotification, object: .None)
    }

    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    func textViewDidBeginEditing(notification: NSNotification) {
        if let textView = notification.object as? UITextView {
            if textView == self {
                UIView.animateWithDuration(0.2) {
                    self.backgroundColor = UIColor.whiteColor()
                }
            }
        }
    }

    func textViewDidEndEditing(notification: NSNotification) {
        if let textView = notification.object as? UITextView {
            if textView == self {
                UIView.animateWithDuration(0.2) {
                    self.backgroundColor = UIColor.greyE5()
                }
            }
        }
    }
}

Update insets on the bio view in settings.

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

import UIKit

public class ElloEditableTextView: UITextView {
    required override public init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        sharedSetup()
    }

    required public init(coder: NSCoder) {
        super.init(coder: coder)
        sharedSetup()
    }

    func sharedSetup() {
        backgroundColor = UIColor.greyE5()
        font = UIFont.typewriterFont(12.0)
        textColor = UIColor.blackColor()
        contentInset = UIEdgeInsets(top: 8.0, left: 8.0, bottom: 8.0, right: 15.0)
        setNeedsDisplay()
    }
}


import SwiftUI

// MARK: - ViewControlAttributesTests

@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView {

    func labelsHidden() throws -> Bool {
        _  = try modifierAttribute(modifierLookup: { modifier -> Bool in
            modifier.modifierType.hasPrefix("_LabeledViewStyleModifier<HiddenLabel")
        }, path: "modifier|style", type: Any.self, call: "labelsHidden")
        return true
    }

    func horizontalRadioGroupLayout() throws -> Bool {
        _ = try modifierAttribute(
            modifierName: "RadioGroupLayoutModifier<_HStackLayout>",
            path: "modifier|style",
            type: Any.self, call: "horizontalRadioGroupLayout")
        return true
    }

    func controlSize() throws -> ControlSize {
        let reference = EmptyView().controlSize(.regular)
        let keyPath = try Inspector.environmentKeyPath(ControlSize.self, reference)
        return try environmentModifier(keyPath: keyPath, call: "controlSize")
    }
}

Make controlSize modifier available for macOS only

import SwiftUI

// MARK: - ViewControlAttributesTests

@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView {

    func labelsHidden() throws -> Bool {
        _  = try modifierAttribute(modifierLookup: { modifier -> Bool in
            modifier.modifierType.hasPrefix("_LabeledViewStyleModifier<HiddenLabel")
        }, path: "modifier|style", type: Any.self, call: "labelsHidden")
        return true
    }

    func horizontalRadioGroupLayout() throws -> Bool {
        _ = try modifierAttribute(
            modifierName: "RadioGroupLayoutModifier<_HStackLayout>",
            path: "modifier|style",
            type: Any.self, call: "horizontalRadioGroupLayout")
        return true
    }

    #if os(macOS)
    func controlSize() throws -> ControlSize {
        let reference = EmptyView().controlSize(.regular)
        let keyPath = try Inspector.environmentKeyPath(ControlSize.self, reference)
        return try environmentModifier(keyPath: keyPath, call: "controlSize")
    }
    #endif
}


import XCTest
import SQLite

class FoundationTests: XCTestCase {
    func testDataFromBlob() {
        let data = Data([1, 2, 3])
        let blob = data.datatypeValue
        XCTAssertEqual([1, 2, 3], blob.bytes)
    }

    func testBlobToData() {
        let blob = Blob(bytes: [1, 2, 3])
        let data = Data.fromDatatypeValue(blob)
        XCTAssertEqual(Data([1, 2, 3]), data)
    }

    func testStringFromUUID() {
        let uuid = UUID(uuidString: "4ABE10C9-FF12-4CD4-90C1-4B429001BAD3")!
        let string = uuid.datatypeValue
        XCTAssertEqual("4ABE10C9-FF12-4CD4-90C1-4B429001BAD3", string)
    }

    func testUUIDFromString() {
        let string = "4ABE10C9-FF12-4CD4-90C1-4B429001BAD3"
        let uuid = UUID.fromDatatypeValue(string)
        XCTAssertEqual(UUID(uuidString: "4ABE10C9-FF12-4CD4-90C1-4B429001BAD3"), uuid)
    }

}

Add tests for NSURL conformance

import XCTest
import SQLite

class FoundationTests: XCTestCase {
    func testDataFromBlob() {
        let data = Data([1, 2, 3])
        let blob = data.datatypeValue
        XCTAssertEqual([1, 2, 3], blob.bytes)
    }

    func testBlobToData() {
        let blob = Blob(bytes: [1, 2, 3])
        let data = Data.fromDatatypeValue(blob)
        XCTAssertEqual(Data([1, 2, 3]), data)
    }

    func testStringFromUUID() {
        let uuid = UUID(uuidString: "4ABE10C9-FF12-4CD4-90C1-4B429001BAD3")!
        let string = uuid.datatypeValue
        XCTAssertEqual("4ABE10C9-FF12-4CD4-90C1-4B429001BAD3", string)
    }

    func testUUIDFromString() {
        let string = "4ABE10C9-FF12-4CD4-90C1-4B429001BAD3"
        let uuid = UUID.fromDatatypeValue(string)
        XCTAssertEqual(UUID(uuidString: "4ABE10C9-FF12-4CD4-90C1-4B429001BAD3"), uuid)
    }

    func testURLFromString() {
        let string = "http://foo.com"
        let url = URL.fromDatatypeValue(string)
        XCTAssertEqual(URL(string: string), url)
    }

    func testStringFromURL() {
        let url = URL(string: "http://foo.com")!
        let string = url.datatypeValue
        XCTAssertEqual("http://foo.com", string)
    }
}


//
//  HabitsTests.swift
//  HabitsTests
//
//  Created by Julian Grosshauser on 26/09/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import Quick
import Nimble
@testable import Habits

class HabitsTests: XCTestCase {
    override func setUp() {
        super.setUp()
    }

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

Remove `setUp()` and `tearDown()` methods

//
//  HabitsTests.swift
//  HabitsTests
//
//  Created by Julian Grosshauser on 26/09/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import Quick
import Nimble
@testable import Habits

class HabitsTests: XCTestCase {}


//
//  ParserTests.swift
//  Mustachio
//
//  Created by Montemayor Elosua, Juan Carlos on 8/31/14.
//  Copyright (c) 2014 jmont. All rights reserved.
//

import UIKit
import XCTest
import Mustachio

class ParserTests: XCTestCase {

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

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

    func testVariableParser() {
        var result = Parser.parse("{{name}}")
        XCTAssertEqual(result, [Tag.Variable("name")])
    }
}

Add parser tests for string

//
//  ParserTests.swift
//  Mustachio
//
//  Created by Montemayor Elosua, Juan Carlos on 8/31/14.
//  Copyright (c) 2014 jmont. All rights reserved.
//

import UIKit
import XCTest
import Mustachio

class ParserTests: XCTestCase {

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

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

    func testVariableParser() {
        var result = Parser.parse("{{name}}")
        XCTAssertEqual(result, [Tag.Variable("name")])
    }

    func testStringParser() {
        var result = Parser.parse("Hello")
        XCTAssertEqual(result, [Tag.Str("Hello")])
    }

    func testMultiplesParser() {
        var result = Parser.parse("Hello {{name}}")
        XCTAssertEqual(result, [Tag.Str("Hello"), Tag.Variable("name")])
    }
}


//
//  Created by Mateusz Karwat on 12/03/2017.
//  Copyright © 2017 Mateusz Karwat. All rights reserved.
//

import Cocoa
import Foundation

final class StatusBarItemController {

    private let statusItem = NSStatusBar.system().statusItem(withLength: -2)

    // MARK: - Lifecycle

    init() {
        setupStatusItem()
    }

    // MARK: - Public Functions

    /// Shows status item.
    func showStatusItem() {
        statusItem.isVisible = true
    }

    /// Hides status item.
    func hideStatusItem() {
        statusItem.isVisible = false
    }

    // MARK: - Private Functions

    private func setupStatusItem() {
        statusItem.isVisible = false
        statusItem.image = #imageLiteral(resourceName: "StatusBarButtonImage")
        statusItem.target = self
        statusItem.action = #selector(statusItemClicked(_:))
    }

    @objc private func statusItemClicked(_ sender: AnyObject) {
        let delegate = NSApp.delegate as! AppDelegate
        _ = delegate.applicationShouldHandleReopen(NSApp, hasVisibleWindows: false)
    }
}

Replace function to show/hide status bar item with one property

//
//  Created by Mateusz Karwat on 12/03/2017.
//  Copyright © 2017 Mateusz Karwat. All rights reserved.
//

import Cocoa
import Foundation

final class StatusBarItemController {

    private let statusItem = NSStatusBar.system().statusItem(withLength: -2)

    var isStatusItemVisible = false {
        didSet {
            statusItem.isVisible = isStatusItemVisible
        }
    }

    // MARK: - Lifecycle

    init() {
        setupStatusItem()
    }

    // MARK: - Private Functions

    private func setupStatusItem() {
        statusItem.isVisible = false
        statusItem.image = #imageLiteral(resourceName: "StatusBarButtonImage")
        statusItem.target = self
        statusItem.action = #selector(statusItemClicked(_:))
    }

    @objc private func statusItemClicked(_ sender: AnyObject) {
        let delegate = NSApp.delegate as! AppDelegate
        _ = delegate.applicationShouldHandleReopen(NSApp, hasVisibleWindows: false)
    }
}


//
//  162_FindAPeakElement.swift
//  LeetcodeSwift
//
//  Created by yansong li on 2016-09-03.
//  Copyright © 2016 YANSONG LI. All rights reserved.
//

import Foundation

/**
	Title:162 Find Peak Element
	URL: https://leetcode.com/problems/find-peak-element/
	Space: O(n)
	Time: O(n)
 */

class FindPeakElement_Solution {
  // My solution loop through.
  func findPeakElement(nums: [Int]) -> Int {
    guard nums.count > 1 else {
      return nums.count == 1 ? 0 : -1
    }
    if nums[0] > nums[1]{
      return 0
    }
    if nums[nums.count - 1] > nums[nums.count - 2] {
      return nums.count - 1
    }
    for i in 1..<nums.count - 1 {
      if nums[i] > nums[i - 1] && nums[i] > nums[i + 1] {
        return i
      }
    }
    return -1
  }
}

Add binary search for find peak element.

//
//  162_FindAPeakElement.swift
//  LeetcodeSwift
//
//  Created by yansong li on 2016-09-03.
//  Copyright © 2016 YANSONG LI. All rights reserved.
//

import Foundation

/**
	Title:162 Find Peak Element
	URL: https://leetcode.com/problems/find-peak-element/
	Space: O(1)
	Time: O(lgn)
 */

class FindPeakElement_Solution {
  // My solution loop through.
  func MyfindPeakElement(nums: [Int]) -> Int {
    guard nums.count > 1 else {
      return nums.count == 1 ? 0 : -1
    }
    if nums[0] > nums[1]{
      return 0
    }
    if nums[nums.count - 1] > nums[nums.count - 2] {
      return nums.count - 1
    }
    for i in 1..<nums.count - 1 {
      if nums[i] > nums[i - 1] && nums[i] > nums[i + 1] {
        return i
      }
    }
    return -1
  }

  func findPeakElement(nums: [Int]) -> Int {
    guard nums.count > 1 else {
      return nums.count == 1 ? 0 : -1
    }
    var left = 0
    var right = nums.count - 1
    while left + 1 < right {
      let mid = left + (right - left) / 2
      if nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1] {
        return mid
      }
      if nums[mid] > nums[mid + 1] {
        right = mid
      } else {
        left = mid
      }
    }
    if nums[left] > nums[right] {
      return left
    } else {
      return right
    }
  }
}


//
//  Sound.swift
//  Micronaut
//
//  Created by Christopher Williams on 4/7/16.
//  Copyright © 2016 Christopher Williams. All rights reserved.
//
//  Handles playing and stopping soundtracks.

import SpriteKit

class Sound {
    static private var scene:SKScene?

    class func initialize(scene: SKScene) {
        self.scene = scene

        play("Monster-Street-Fighters.mp3", loop: true)
    }

    class func play(filename: String, loop: Bool) {
        if loop {
            scene!.runAction(SKAction.repeatActionForever(SKAction.playSoundFileNamed(filename, waitForCompletion: true)))
        } else {
            scene!.runAction(SKAction.playSoundFileNamed(filename, waitForCompletion: true))
        }
    }
}

Revert "reenabled sound and incremented build number"

//
//  Sound.swift
//  Micronaut
//
//  Created by Christopher Williams on 4/7/16.
//  Copyright © 2016 Christopher Williams. All rights reserved.
//
//  Handles playing and stopping soundtracks.

import SpriteKit

class Sound {
    static private var scene:SKScene?

    class func initialize(scene: SKScene) {
        self.scene = scene

        play("Monster-Street-Fighters.mp3", loop: true)
    }

    class func play(filename: String, loop: Bool) {
//        if loop {
//            scene!.runAction(SKAction.repeatActionForever(SKAction.playSoundFileNamed(filename, waitForCompletion: true)))
//        } else {
//            scene!.runAction(SKAction.playSoundFileNamed(filename, waitForCompletion: true))
//        }
    }
}


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

import Foundation

@objcMembers
public class MXStoreRoomListDataManager: NSObject, MXRoomListDataManager {
    public weak var session: MXSession?

    public func configure(withSession session: MXSession) {
        assert(self.session == nil, "Cannot configure the session again")
        self.session = session
    }

    public func fetcher(withOptions options: MXRoomListDataFetchOptions) -> MXRoomListDataFetcher {
        guard let store = session?.store else {
            fatalError("Session has no store")
        }
        return MXStoreRoomListDataFetcher(fetchOptions: options, store: store)
    }
}

Return suggested rooms fetcher if onlySuggested

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

import Foundation

@objcMembers
public class MXStoreRoomListDataManager: NSObject, MXRoomListDataManager {
    public weak var session: MXSession?

    public func configure(withSession session: MXSession) {
        assert(self.session == nil, "Cannot configure the session again")
        self.session = session
    }

    public func fetcher(withOptions options: MXRoomListDataFetchOptions) -> MXRoomListDataFetcher {
        if options.filterOptions.onlySuggested {
            guard let spaceService = session?.spaceService else {
                fatalError("Session has no spaceService")
            }
            return MXSuggestedRoomListDataFetcher(fetchOptions: options,
                                                  spaceService: spaceService)
        }
        guard let store = session?.store else {
            fatalError("Session has no store")
        }
        return MXStoreRoomListDataFetcher(fetchOptions: options,
                                          store: store)
    }
}


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

import Foundation

class ConversationsManager {

    class func checkForConversations(userId: Int) {
        DriftAPIManager.getEnrichedConversations(userId) { (result) in
            switch result {
            case .success(let conversations):
                let conversationsToShow = conversations.filter({$0.unreadMessages > 0})
                PresentationManager.sharedInstance.didRecieveNewMessages(conversationsToShow)
            case .failure(let error):
                LoggerManager.didRecieveError(error)
            }
        }
    }

    class func markMessageAsRead(_ messageId: Int) {
        DriftAPIManager.markMessageAsRead(messageId: messageId) { (result) in
            switch result {
            case .success:
                LoggerManager.log("Successfully marked Message Read: \(messageId)")
            case .failure(let error):
                LoggerManager.didRecieveError(error)
            }
        }
    }

}

Mark conversations as read rather than a single message at a time

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

import Foundation

class ConversationsManager {

    class func checkForConversations(userId: Int) {
        DriftAPIManager.getEnrichedConversations(userId) { (result) in
            switch result {
            case .success(let conversations):
                let conversationsToShow = conversations.filter({$0.unreadMessages > 0})
                PresentationManager.sharedInstance.didRecieveNewMessages(conversationsToShow)
            case .failure(let error):
                LoggerManager.didRecieveError(error)
            }
        }
    }

    class func markMessageAsRead(_ messageId: Int) {
        DriftAPIManager.markConversationAsRead(messageId: messageId) { (result) in
            switch result {
            case .success:
                LoggerManager.log("Successfully marked Message Read: \(messageId)")
            case .failure(let error):
                LoggerManager.didRecieveError(error)
            }
        }
    }

}


//
//  NoteCell.swift
//  Babies
//
//  Created by phi on 19/10/16.
//  Copyright © 2016 Stanhope Road. All rights reserved.
//

import UIKit

class NoteCell: UITableViewCell, UITextViewDelegate {
    @IBOutlet var textView: UITextView!
    var baby: Baby?

    func textViewDidChange(_ textView: UITextView) {
        baby?.notes = self.textView.text
    }

    func updateInterface() {
        if let text = self.baby?.notes {
            self.textView.text = text
        } else {
            self.textView.text = "default"
        }
    }
}

Add a text prompt key when there are no notes and erase it when editing starts

//
//  NoteCell.swift
//  Babies
//
//  Created by phi on 19/10/16.
//  Copyright © 2016 Stanhope Road. All rights reserved.
//

import UIKit

class NoteCell: UITableViewCell, UITextViewDelegate {
    @IBOutlet var textView: UITextView!
    var baby: Baby?

    func textViewDidBeginEditing(_ textView: UITextView) {
        if self.baby?.notes == nil {
            self.textView.text = ""
        }
    }

    func textViewDidChange(_ textView: UITextView) {
        baby?.notes = self.textView.text
    }

    func updateInterface() {
        if let text = self.baby?.notes {
            self.textView.text = text
        } else {
            self.textView.text = "EMPTY_NOTE_TEXTVIEW_PROMPT"
        }
    }
}


//
//  decode.swift
//  Himotoki
//
//  Created by Syo Ikeda on 5/19/15.
//  Copyright (c) 2015 Syo Ikeda. All rights reserved.
//

public func decode<T: Decodable where T.DecodedType == T>(object: AnyObject) -> T? {
    let extractor = Extractor(object)
    return T.decode(extractor)
}

public func decode<T: Decodable where T.DecodedType == T>(object: AnyObject) -> [T]? {
    if let array = object as? [AnyObject] {
        return array.reduce([]) { (var accum: [T], value) in
            decode(value).map { accum.append($0) }
            return accum
        }
    } else {
        return nil
    }
}

public func decode<T: Decodable where T.DecodedType == T>(object: AnyObject) -> [String: T]? {
    if let dictionary = object as? [String: AnyObject] {
        return dictionary.reduce([:]) { (var accum: [String: T], element) in
            let (key, value) = element
            accum[key] = decode(value)
            return accum
        }
    } else {
        return nil
    }
}

Use `SequenceType.flatMap<T>(transform: (Self.Generator.Element) -> T?) -> [T]`

//
//  decode.swift
//  Himotoki
//
//  Created by Syo Ikeda on 5/19/15.
//  Copyright (c) 2015 Syo Ikeda. All rights reserved.
//

public func decode<T: Decodable where T.DecodedType == T>(object: AnyObject) -> T? {
    let extractor = Extractor(object)
    return T.decode(extractor)
}

public func decode<T: Decodable where T.DecodedType == T>(object: AnyObject) -> [T]? {
    if let array = object as? [AnyObject] {
        return array.flatMap(decode)
    } else {
        return nil
    }
}

public func decode<T: Decodable where T.DecodedType == T>(object: AnyObject) -> [String: T]? {
    if let dictionary = object as? [String: AnyObject] {
        return dictionary.reduce([:]) { (var accum: [String: T], element) in
            let (key, value) = element
            accum[key] = decode(value)
            return accum
        }
    } else {
        return nil
    }
}


//
//  OctoPrintAPI.swift
//  OctoPhone
//
//  Created by Josef Dolezal on 27/02/2017.
//  Copyright © 2017 Josef Dolezal. All rights reserved.
//

import Foundation
import Moya

typealias Parameters = [String: Any]
typealias OctoPrintProvider = DynamicProvider<OctoPrintAPI>

/// Targets definition
///
/// - version: OctoPrint API version
enum OctoPrintAPI {
    case version
}

// MARK: - TargetPart implementation
// Implements Moya protocol for creating Endpoints from Targets
extension OctoPrintAPI: TargetPart {
    var path: String { return requestData.path }

    var method: Moya.Method { return requestData.method }

    var parameters: Parameters? { return requestData.parameters }

    var parameterEncoding: ParameterEncoding { return Moya.JSONEncoding.default }

    var sampleData: Data { return Data() }

    var task: Task { return requestData.task }

    var validate: Bool { return false }

    /// Target to endpoint data maping
    var requestData: (path: String, method: Moya.Method, task: Task, parameters: Parameters?) {
        switch self {
        case .version: return ("api/version", .get, .request, nil)
        }
    }
}

Implement files endpoint to moya

//
//  OctoPrintAPI.swift
//  OctoPhone
//
//  Created by Josef Dolezal on 27/02/2017.
//  Copyright © 2017 Josef Dolezal. All rights reserved.
//

import Foundation
import Moya

typealias Parameters = [String: Any]
typealias OctoPrintProvider = DynamicProvider<OctoPrintAPI>

/// Targets definition
///
/// - version: OctoPrint API version
enum OctoPrintAPI {
    case version
    case files
}

// MARK: - TargetPart implementation
// Implements Moya protocol for creating Endpoints from Targets
extension OctoPrintAPI: TargetPart {
    var path: String { return requestData.path }

    var method: Moya.Method { return requestData.method }

    var parameters: Parameters? { return requestData.parameters }

    var parameterEncoding: ParameterEncoding { return Moya.JSONEncoding.default }

    var sampleData: Data { return Data() }

    var task: Task { return requestData.task }

    var validate: Bool { return false }

    /// Target to endpoint data maping
    var requestData: (path: String, method: Moya.Method, task: Task, parameters: Parameters?) {
        switch self {
        case .version: return ("api/version", .get, .request, nil)
        case .files: return ("api/files", .get, .request, nil)
        }
    }
}


/*
  RECUR 1 SWIFT

  Simply run with: 'swift-t recur-1.swift | nl'
*/

app (void v) dummy(string parent, int stage, int id, void block)
{
  "echo" ("parent='%3s'"%parent) ("stage="+stage) ("id="+id) ;
}

N = 4;

void A[string];

(void v) runstage(int N, string parent, int stage, int id, void block)
{
  string this = parent+int2string(id);
  v = dummy(parent, stage, id, block);
  if (stage < 3)
  {
    foreach id_child in [0:N-1]
    {
      runstage(N, this, stage+1, id_child, v);
    }
  }
}

int stage = 1;
foreach id in [0:N-1]
{
  runstage(N, "", stage, id, propagate());
}

Clean up, make S a variable

/*
  RECUR 1 SWIFT

  Simply run with: 'swift-t recur-1.swift | nl'
*/

app (void v) dummy(string parent, int stage, int id, void block)
{
  "echo" ("parent='%3s'"%parent) ("stage="+stage) ("id="+id) ;
}

N = 4; // Data split factor
S = 3; // Maximum stage number (tested up to S=7, 21,844 dummy tasks)

(void v) runstage(int N, int S, string parent, int stage, int id, void block)
{
  string this = parent+int2string(id);
  v = dummy(parent, stage, id, block);
  if (stage < S)
  {
    foreach id_child in [0:N-1]
    {
      runstage(N, S, this, stage+1, id_child, v);
    }
  }
}

int stage = 1;
foreach id in [0:N-1]
{
  runstage(N, S, "", stage, id, propagate());
}


import Foundation

struct MVitaPtpCommand
{
    static let openSession:UInt16 = 4098
    static let success:UInt16 = 8193
    static let requestVitaInfo:UInt16 = 38161
}

Add send local info code

import Foundation

struct MVitaPtpCommand
{
    static let openSession:UInt16 = 4098
    static let success:UInt16 = 8193
    static let requestVitaInfo:UInt16 = 38161
    static let sendLocalInfo:UInt16 = 38172
}


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

import Foundation

public final class ComponentViewController: UIViewController {
  private let factory: () -> Component

  public init(factory: @escaping () -> Component) {
    self.factory = factory
    super.init(nibName: nil, bundle: nil)
  }

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

  override public func loadView() {
    let hostingView = ComponentHostingView(factory: factory)
    hostingView.backgroundColor = .white

    self.view = hostingView
  }

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

Add delegate to component VC

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

import Foundation

public final class ComponentViewController: UIViewController, ComponentHostingViewDelegate {
  private let factory: () -> Component

  public init(factory: @escaping () -> Component) {
    self.factory = factory
    super.init(nibName: nil, bundle: nil)
  }

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

  override public func loadView() {
    let hostingView = ComponentHostingView(factory: factory)
    hostingView.backgroundColor = .white
    hostingView.delegate = self

    self.view = hostingView
  }

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

  }

  public func hostingViewDidUpdate(hostingView: ComponentHostingView) {
    if let entryPointComponent = hostingView.root as? EntryPointComponent {
      self.title = entryPointComponent.title
    }
  }
}


public enum Method: String {

	case CONNECT
	case DELETE
	case GET
	case HEAD
	case OPTIONS
	case PATCH
	case POST
	case PUT
	case TRACE

}

public struct Request {

	public let method: Method
	public let path: Path
	public let headers: [(String, String)]
	public let body: String? // FIXME: Data instead?

	init(method: Method, path: Path, headers: [(String, String)] = [], body: String? = nil) {
		self.method = method
		self.path = path
		self.headers = headers
		self.body = body
	}

}

public struct MatchedRequest {

	public let request: Request
	public let route: Route

    internal func paramAtIndex<T: PathType>(index: Int) -> T {
        let wildcardKey = route.wildcardPath.wildcards[index]
        return param(wildcardKey: wildcardKey)
    }

    private func param<T: PathType>(wildcardKey wildcardKey: String) -> T {
        guard let wildcardIndex = route.wildcardPath.indexOfWildcard(wildcardKey) else {
            preconditionFailure("No wildcard with key \(wildcardKey)")
        }

		let value = request.path.components[wildcardIndex]
		return T.fromString(value)!
    }

}

Return nil instead of triggering a precondition failure.

public enum Method: String {

	case CONNECT
	case DELETE
	case GET
	case HEAD
	case OPTIONS
	case PATCH
	case POST
	case PUT
	case TRACE

}

public struct Request {

	public let method: Method
	public let path: Path
	public let headers: [(String, String)]
	public let body: String? // FIXME: Data instead?

	init(method: Method, path: Path, headers: [(String, String)] = [], body: String? = nil) {
		self.method = method
		self.path = path
		self.headers = headers
		self.body = body
	}

}

public struct MatchedRequest {

	public let request: Request
	public let route: Route

    internal func paramAtIndex<T: PathType>(index: Int) -> T? {
        let wildcardKey = route.wildcardPath.wildcards[index]
        return param(wildcardKey: wildcardKey)
    }

    private func param<T: PathType>(wildcardKey wildcardKey: String) -> T? {
        guard let wildcardIndex = route.wildcardPath.indexOfWildcard(wildcardKey) else {
            return nil
        }

		let value = request.path.components[wildcardIndex]
		return T.fromString(value)
    }

}


public enum RequestResult<T> {

    case success(T)
    case error(Error)

    var value: T? {
        switch self {
        case .success(let value):
            return value
        default:
            return nil
        }
    }

    var error: Error? {
        switch self {
        case .error(let error):
            return error
        default:
            return nil
        }
    }
}

Fix result property access level

public enum RequestResult<T> {

    case success(T)
    case error(Error)

    public var value: T? {
        switch self {
        case .success(let value):
            return value
        default:
            return nil
        }
    }

    public var error: Error? {
        switch self {
        case .error(let error):
            return error
        default:
            return nil
        }
    }
}


//
//  JSONExtension.swift
//  SwiftyJSONModel
//
//  Created by Oleksii on 17/09/16.
//  Copyright © 2016 Oleksii Dykan. All rights reserved.
//

import Foundation
import SwiftyJSON

public extension JSON {
    public func boolValue() throws -> Bool {
        guard let boolValue = bool else {
            throw JSONModelError.elementAbsent
        }
        return boolValue
    }

    public func intValue() throws -> Int {
        guard let intValue = int else {
            throw JSONModelError.elementAbsent
        }
        return intValue
    }

    public func doubleValue() throws -> Double {
        guard let doubleValue = double else {
            throw JSONModelError.elementAbsent
        }
        return doubleValue
    }

    public func stringValue() throws -> String {
        guard let stringValue = string else {
            throw JSONModelError.elementAbsent
        }
        return stringValue
    }

    public func arrayValue() throws -> [JSON] {
        guard let arrayValue = array else {
            throw JSONModelError.elementAbsent
        }
        return arrayValue
    }

    public func uuidStringValue() throws -> String {
        guard let stringValue = string else {
            throw JSONModelError.elementAbsent
        }
        guard let uuidStrigValue = NSUUID(uuidString: stringValue) else {
            throw JSONModelError.invalidUUIDString
        }

        return uuidStrigValue.uuidString
    }
}

Change the error in from element absent to invalid element

//
//  JSONExtension.swift
//  SwiftyJSONModel
//
//  Created by Oleksii on 17/09/16.
//  Copyright © 2016 Oleksii Dykan. All rights reserved.
//

import Foundation
import SwiftyJSON

public extension JSON {
    public func boolValue() throws -> Bool {
        guard let boolValue = bool else { throw JSONModelError.invalidElement }
        return boolValue
    }

    public func intValue() throws -> Int {
        guard let intValue = int else { throw JSONModelError.invalidElement }
        return intValue
    }

    public func doubleValue() throws -> Double {
        guard let doubleValue = double else { throw JSONModelError.invalidElement }
        return doubleValue
    }

    public func stringValue() throws -> String {
        guard let stringValue = string else { throw JSONModelError.invalidElement }
        return stringValue
    }

    public func arrayValue() throws -> [JSON] {
        guard let arrayValue = array else { throw JSONModelError.invalidElement }
        return arrayValue
    }

    public func uuidStringValue() throws -> String {
        guard let stringValue = string else { throw JSONModelError.invalidElement }
        guard let uuidStrigValue = NSUUID(uuidString: stringValue) else {
            throw JSONModelError.invalidUUIDString
        }

        return uuidStrigValue.uuidString
    }
}


//
//  OAuthSwiftURLHandlerType.swift
//  OAuthSwift
//
//  Created by phimage on 11/05/15.
//  Copyright (c) 2015 Dongri Jin. All rights reserved.
//

import AppKit

@objc public protocol OAuthSwiftURLHandlerType {
    func handle(url: NSURL)
}

public class OAuthSwiftOpenURLExternally: OAuthSwiftURLHandlerType {
    class var sharedInstance : OAuthSwiftOpenURLExternally {
        struct Static {
            static var onceToken : dispatch_once_t = 0
            static var instance : OAuthSwiftOpenURLExternally? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = OAuthSwiftOpenURLExternally()
        }
        return Static.instance!
    }

    @objc public func handle(url: NSURL) {
        #if os(iOS)
            UIApplication.sharedApplication().openURL(url)
        #elseif os(OSX)
            NSWorkspace.sharedWorkspace().openURL(url)
        #endif
    }
}

Fix compatible iOS / OSX

//
//  OAuthSwiftURLHandlerType.swift
//  OAuthSwift
//
//  Created by phimage on 11/05/15.
//  Copyright (c) 2015 Dongri Jin. All rights reserved.
//

import Foundation

#if os(iOS)
    import UIKit
#elseif os(OSX)
    import AppKit
#endif

@objc public protocol OAuthSwiftURLHandlerType {
    func handle(url: NSURL)
}

public class OAuthSwiftOpenURLExternally: OAuthSwiftURLHandlerType {
    class var sharedInstance : OAuthSwiftOpenURLExternally {
        struct Static {
            static var onceToken : dispatch_once_t = 0
            static var instance : OAuthSwiftOpenURLExternally? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = OAuthSwiftOpenURLExternally()
        }
        return Static.instance!
    }

    @objc public func handle(url: NSURL) {
        #if os(iOS)
            UIApplication.sharedApplication().openURL(url)
        #elseif os(OSX)
            NSWorkspace.sharedWorkspace().openURL(url)
        #endif
    }
}


import Glibc

public class Tick {

  // Alias for millis.
  public static var millisecondsSinceEpoch: Int {
    return millis
  }

  public static var millis: Int {
    var ts = timespec()
    clock_gettime(CLOCK_REALTIME, &ts)
    return (ts.tv_sec * 1000) + Int(ts.tv_nsec / 1000000)
  }

}

public class Stopwatch: CustomStringConvertible {

  var startTime: Int = 0

  var sliceTime: Int = 0

  var stopped = true

  // Make the constructor public.
  public init() { }

  public func start() {
    startTime = Tick.millis
    sliceTime = startTime
    stopped = false
  }

  public func stop() {
    doSlice()
    stopped = true
  }

  func doSlice() {
    sliceTime = Tick.millis
  }

  // Alias for millis.
  public var elapsedMilliseconds: Int {
    return millis
  }

  public var millis: Int {
    if (!stopped) {
      doSlice()
    }
    return sliceTime - startTime
  }

  public var description: String {
    return "Stopwatch(startTime: \(startTime), sliceTime: \(sliceTime), " +
        "stopped: \(stopped))"
  }

}

Change Tick.millis to MONOTONIC time.

import Glibc

public class Tick {

  // Alias for millis.
  public static var millisecondsSinceEpoch: Int {
    return millis
  }

  public static var millis: Int {
    var ts = timespec()
    clock_gettime(CLOCK_MONOTONIC, &ts)
    return (ts.tv_sec * 1000) + Int(ts.tv_nsec / 1000000)
  }

}

public class Stopwatch: CustomStringConvertible {

  var startTime: Int = 0

  var sliceTime: Int = 0

  var stopped = true

  // Make the constructor public.
  public init() { }

  public func start() {
    startTime = Tick.millis
    sliceTime = startTime
    stopped = false
  }

  public func stop() {
    doSlice()
    stopped = true
  }

  func doSlice() {
    sliceTime = Tick.millis
  }

  // Alias for millis.
  public var elapsedMilliseconds: Int {
    return millis
  }

  public var millis: Int {
    if (!stopped) {
      doSlice()
    }
    return sliceTime - startTime
  }

  public var description: String {
    return "Stopwatch(startTime: \(startTime), sliceTime: \(sliceTime), " +
        "stopped: \(stopped))"
  }

}


//
//  ArticlePasteboardWriter.swift
//  Evergreen
//
//  Created by Brent Simmons on 11/6/17.
//  Copyright © 2017 Ranchero Software. All rights reserved.
//

import Cocoa
import Data

@objc final class ArticlePasteboardWriter: NSObject, NSPasteboardWriting {

	private let article: Article

	init(article: Article) {

		self.article = article
	}

	// MARK: - NSPasteboardWriting

	func writableTypes(for pasteboard: NSPasteboard) -> [NSPasteboard.PasteboardType] {

		return [NSPasteboard.PasteboardType]() // TODO: add types
	}

	func pasteboardPropertyList(forType type: NSPasteboard.PasteboardType) -> Any? {

		return nil // TODO: write data
	}
}

Write the string plist for the article.

//
//  ArticlePasteboardWriter.swift
//  Evergreen
//
//  Created by Brent Simmons on 11/6/17.
//  Copyright © 2017 Ranchero Software. All rights reserved.
//

import Cocoa
import Data

@objc final class ArticlePasteboardWriter: NSObject, NSPasteboardWriting {

	private let article: Article

	init(article: Article) {

		self.article = article
	}

	// MARK: - NSPasteboardWriting

	func writableTypes(for pasteboard: NSPasteboard) -> [NSPasteboard.PasteboardType] {

		// TODO: add more types

		var types = [NSPasteboard.PasteboardType]()

		if let _ = article.title {
			types += [.string]
		}

		return types // TODO: add types
	}

	func pasteboardPropertyList(forType type: NSPasteboard.PasteboardType) -> Any? {

		// TODO: write data for all types declared in writableTypes.

		let plist: Any?

		switch type {
		case .string:
			plist = article.title ?? ""
		default:
			plist = nil
		}

		return plist
	}
}


//
//  GalleryTableViewCell.swift
//  TOZ_iOS
//
//  Created by Kobsonauta on 27.03.2017.
//  Copyright © 2017 intive. All rights reserved.
//

import UIKit

class GalleryTableViewCell: UITableViewCell {
    @IBOutlet weak var animalImage: UIImageView!
    @IBOutlet weak var animalName: UILabel!
    @IBOutlet weak var animalType: UILabel!

    private var animalID: String?

    func configure(for animal: AnimalItem) {
        animalID = animal.animalID
        self.animalName.text = animal.name
        self.animalType.text = animal.type
        let imageUrl: URL? = URL(string: "https://placehold.it/350x350")
        animalImage.image = nil
        if let imageUrl = imageUrl {
            PhotoManager.shared.getPhoto(from: imageUrl, completion: {(image) -> (Void) in
                if self.animalID == animal.animalID {
                    self.animalImage.image = image
                }
            })
        }
    }
}

Replace hardcoded url with model url

//
//  GalleryTableViewCell.swift
//  TOZ_iOS
//
//  Created by Kobsonauta on 27.03.2017.
//  Copyright © 2017 intive. All rights reserved.
//

import UIKit

class GalleryTableViewCell: UITableViewCell {
    @IBOutlet weak var animalImage: UIImageView!
    @IBOutlet weak var animalName: UILabel!
    @IBOutlet weak var animalType: UILabel!

    private var animalID: String?

    func configure(for animal: AnimalItem) {
        animalID = animal.animalID
        self.animalName.text = animal.name
        self.animalType.text = animal.type
        let imageUrl: URL? = animal.imageUrl
        animalImage.image = nil
        if let imageUrl = imageUrl {
            PhotoManager.shared.getPhoto(from: imageUrl, completion: {(image) -> (Void) in
                if self.animalID == animal.animalID {
                    self.animalImage.image = image
                }
            })
        }
    }
}


//
//  UIGradePercentageView.swift
//  GradePoint
//
//  Created by Luis Padron on 5/4/18.
//  Copyright © 2018 Luis Padron. All rights reserved.
//

import UIKit

@IBDesignable
class UIGradePercentageView: UIView {

    // MARK: Members

    @IBInspectable public var gradeLetter: String = "A+" {
        didSet { self.label.text = self.gradeLetter }
    }

    // MARK: Init

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.initialize()
    }

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

    private func initialize() {
        self.backgroundColor = .clear
        self.addSubview(self.label)
    }

    // MARK: Layout

    override func layoutSubviews() {
        super.layoutSubviews()

        self.label.sizeToFit()
        self.label.frame = CGRect(x: 16, y: self.center.y / 2, width: self.label.frame.width, height: self.label.frame.height)
    }

    // MARK: Api

    // MARK: Subviews

    private lazy var label: UILabel = {
        let label = UILabel()
        label.textColor = ApplicationTheme.shared.mainTextColor()
        label.font = UIFont.systemFont(ofSize: 20)
        return label
    }()

}

Set default letter when creating label

//
//  UIGradePercentageView.swift
//  GradePoint
//
//  Created by Luis Padron on 5/4/18.
//  Copyright © 2018 Luis Padron. All rights reserved.
//

import UIKit

@IBDesignable
class UIGradePercentageView: UIView {

    // MARK: Members

    @IBInspectable public var gradeLetter: String = "A+" {
        didSet { self.label.text = self.gradeLetter }
    }

    // MARK: Init

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.initialize()
    }

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

    private func initialize() {
        self.backgroundColor = .clear
        self.addSubview(self.label)
    }

    // MARK: Layout

    override func layoutSubviews() {
        super.layoutSubviews()

        self.label.sizeToFit()
        self.label.frame = CGRect(x: 16, y: self.center.y / 2, width: self.label.frame.width, height: self.label.frame.height)
    }

    // MARK: Api

    // MARK: Subviews

    private lazy var label: UILabel = {
        let label = UILabel()
        label.text = self.gradeLetter
        label.textColor = ApplicationTheme.shared.mainTextColor()
        label.font = UIFont.systemFont(ofSize: 20)
        return label
    }()

}


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

import Foundation

struct TextClipping: Decodable {

    let string: String

    enum CodingKeys: String, CodingKey {

        case string = "public.utf8-plain-text"
    }

    init(url: URL) throws {

        let data = try Data(contentsOf: url)
        let plist = try PropertyListDecoder().decode([String: TextClipping].self, from: data)

        guard let textClipping = plist["UTI-Data"] else { throw CocoaError(.coderReadCorrupt) }

        self = textClipping
    }

}

Add url info to CocoaError

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

import Foundation

struct TextClipping: Decodable {

    let string: String

    enum CodingKeys: String, CodingKey {

        case string = "public.utf8-plain-text"
    }

    init(url: URL) throws {

        let data = try Data(contentsOf: url)
        let plist = try PropertyListDecoder().decode([String: TextClipping].self, from: data)

        guard let textClipping = plist["UTI-Data"] else { throw CocoaError.error(.coderReadCorrupt, url: url) }

        self = textClipping
    }

}


//
//  ColorPaletteItemResource.swift
//  R.swift.Library
//
//  Created by Tom Lokhorst on 2016-03-13.
//  From: https://github.com/mac-cain13/R.swift.Library
//  License: MIT License
//

import Foundation

public protocol ColorPaletteItemResourceType {

  /// Name of the color
  var name: String { get }

  /// Red componenent of color
  var red: CGFloat { get }

  /// Green componenent of color
  var green: CGFloat { get }

  /// Blue componenent of color
  var blue: CGFloat { get }

  /// Alpha componenent of color
  var alpha: CGFloat { get }
}

@available(*, deprecated: 11, message: "Use color assets instead")
public struct ColorPaletteItemResource: ColorPaletteItemResourceType {

  /// Name of the color
  public let name: String

  /// Red componenent of color
  public let red: CGFloat

  /// Green componenent of color
  public let green: CGFloat

  /// Blue componenent of color
  public let blue: CGFloat

  /// Alpha componenent of color
  public let alpha: CGFloat

  public init(name: String, red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
    self.name = name
    self.red = red
    self.green = green
    self.blue = blue
    self.alpha = alpha
  }
}

Fix compilation for static linking

//
//  ColorPaletteItemResource.swift
//  R.swift.Library
//
//  Created by Tom Lokhorst on 2016-03-13.
//  From: https://github.com/mac-cain13/R.swift.Library
//  License: MIT License
//

import CoreGraphics

public protocol ColorPaletteItemResourceType {

  /// Name of the color
  var name: String { get }

  /// Red componenent of color
  var red: CGFloat { get }

  /// Green componenent of color
  var green: CGFloat { get }

  /// Blue componenent of color
  var blue: CGFloat { get }

  /// Alpha componenent of color
  var alpha: CGFloat { get }
}

@available(*, deprecated: 11, message: "Use color assets instead")
public struct ColorPaletteItemResource: ColorPaletteItemResourceType {

  /// Name of the color
  public let name: String

  /// Red componenent of color
  public let red: CGFloat

  /// Green componenent of color
  public let green: CGFloat

  /// Blue componenent of color
  public let blue: CGFloat

  /// Alpha componenent of color
  public let alpha: CGFloat

  public init(name: String, red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
    self.name = name
    self.red = red
    self.green = green
    self.blue = blue
    self.alpha = alpha
  }
}


//
//  KeyPathTests.swift
//  Collections
//
//  Created by James Bean on 12/23/16.
//
//

import XCTest
import Collections

class KeyPathTests: XCTestCase {

    func testInitArray() {
        let keyPath = KeyPath(["1", "2", "ok"])
        XCTAssertEqual(keyPath.count, 3)
    }

    func testInitArrayLiteral() {
        let keyPath: KeyPath = ["1", "2", "ok"]
        XCTAssertEqual(keyPath.count, 3)
    }

    func testInitStringLiteral() {
        let keyPath: KeyPath = "a.b.2.ok.g"
        XCTAssertEqual(keyPath.count, 5)
    }

    func testInitHeterogeneousType() {
        let keyPath = KeyPath(["a", 1])
        XCTAssertEqual(keyPath[0] as! String, "a")
        XCTAssertEqual(keyPath[1] as! Int, 1)
    }
}

Use Collections.KeyPath explicitly in tests

//
//  KeyPathTests.swift
//  Collections
//
//  Created by James Bean on 12/23/16.
//
//

import XCTest
import Collections

class KeyPathTests: XCTestCase {

    func testInitArray() {
        let keyPath = Collections.KeyPath(["1", "2", "ok"])
        XCTAssertEqual(keyPath.count, 3)
    }

    func testInitArrayLiteral() {
        let keyPath: Collections.KeyPath = ["1", "2", "ok"]
        XCTAssertEqual(keyPath.count, 3)
    }

    func testInitStringLiteral() {
        let keyPath: Collections.KeyPath = "a.b.2.ok.g"
        XCTAssertEqual(keyPath.count, 5)
    }

    func testInitHeterogeneousType() {
        let keyPath = KeyPath(["a", 1])
        XCTAssertEqual(keyPath[0] as! String, "a")
        XCTAssertEqual(keyPath[1] as! Int, 1)
    }
}


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

extension TermContainerType {
	// MARK: Variables

	public var maxBoundVariable: Int {
		return cata {
			switch $0 {
			case .Type, .Variable:
				return -1
			case let .Application(a, b):
				return max(a, b)
			case let .Lambda(i, .Some(a), b):
				return i < 0 ? max(a, b) : max(i, a)
			case let .Lambda(i, .None, b):
				return i < 0 ? b : i
			}
		}
	}

	public var freeVariables: Set<Int> {
		return cata {
			switch $0 {
			case .Type, .Variable(.Global):
				return []
			case let .Variable(.Local(i)):
				return [ i ]
			case let .Application(a, b):
				return a.union(b)
			case let .Lambda(i, a, b):
				return b.subtract([ i ]).union(a ?? [])
			}
		}
	}
}

import Prelude

Implement generalization of terms w.r.t. their free variables.

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

extension TermContainerType {
	// MARK: Variables

	public var maxBoundVariable: Int {
		return cata {
			switch $0 {
			case .Type, .Variable:
				return -1
			case let .Application(a, b):
				return max(a, b)
			case let .Lambda(i, .Some(a), b):
				return i < 0 ? max(a, b) : max(i, a)
			case let .Lambda(i, .None, b):
				return i < 0 ? b : i
			}
		}
	}

	public var freeVariables: Set<Int> {
		return cata {
			switch $0 {
			case .Type, .Variable(.Global):
				return []
			case let .Variable(.Local(i)):
				return [ i ]
			case let .Application(a, b):
				return a.union(b)
			case let .Lambda(i, a, b):
				return b.subtract([ i ]).union(a ?? [])
			}
		}
	}
}

extension Term {
	public func generalize() -> Term {
		return freeVariables.sort().reduce(self) {
			.Lambda($1, nil, $0)
		}
	}
}

import Prelude


import SpriteKit

class PlayScene: SKScene{
    // Sprite node for the bar
    let runningBar = SKSpriteNode(imageNamed: "bar")
    // Original X position for the running bar
    let originRunningBarPositionX = CGFloat(0)

    override func didMoveToView(view: SKView!) {
        self.backgroundColor = UIColor(hex: 0x809DFF)

        // Set the anchor point of the running bar at (0, 0.5)
        self.runningBar.anchorPoint = CGPointMake(0, 0.5)
        // Set the bar at the bottom of the screen
        self.runningBar.position = CGPointMake(
            CGRectGetMinX(self.frame),
            CGRectGetMinY(self.frame) * (self.runningBar.size.height / 2))

        // Set the original running bar X-position
        self.originRunningBarPositionX = self.runningBar.position.x

        // Present the running bar in the screen
        self.addChild(self.runningBar)

    }

    /// Update the scene: It will run every single frame
    override func update(currentTime: NSTimeInterval) {

    }
}

Set the MaxBarX which is the available amount of the running bar that is not visivisible in the screen

import SpriteKit

class PlayScene: SKScene{
    // Sprite node for the bar
    let runningBar = SKSpriteNode(imageNamed: "bar")
    // Original X position for the running bar
    let originRunningBarPositionX = CGFloat(0)
    // Amount of the hidden running bar that is available (The bar width is longer than the screen size)
    let maxBarX = CGFloat(0)

    override func didMoveToView(view: SKView!) {
        self.backgroundColor = UIColor(hex: 0x809DFF)

        // Set the anchor point of the running bar at (0, 0.5)
        self.runningBar.anchorPoint = CGPointMake(0, 0.5)
        // Set the bar at the bottom of the screen
        self.runningBar.position = CGPointMake(
            CGRectGetMinX(self.frame),
            CGRectGetMinY(self.frame) * (self.runningBar.size.height / 2))

        // Set the original running bar X-position
        self.originRunningBarPositionX = self.runningBar.position.x

        // Set the MaxBarX ( RunningBar's widht - Screen's width)=> Available Running Bar
        self.maxBarX = self.runningBar.size.width - self.frame.width
        self.maxBarX *= -1 // Make a negative number

        // Present the running bar in the screen
        self.addChild(self.runningBar)

    }

    /// Update the scene: It will run every single frame
    override func update(currentTime: NSTimeInterval) {

    }
}


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

final class BinaryTreeTests: XCTestCase {
	func testEmptyTreesAreEmpty() {
		XCTAssert(BinaryTree<Int>().isEmpty)
	}

	func testEmptyTreesAreNotLeaves() {
		XCTAssertFalse(BinaryTree<Int>().isLeaf)
	}

	func testLeavesAreLeaves() {
		XCTAssert(BinaryTree(0).isLeaf)
	}

	func testLeavesAreNonEmpty() {
		XCTAssertFalse(BinaryTree(0).isEmpty)
	}

	func testLeavesAreNotBranches() {
		XCTAssertFalse(BinaryTree(0).isBranch)
	}
}

import BinaryTree
import XCTest

Test that empty trees are not branches.

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

final class BinaryTreeTests: XCTestCase {
	func testEmptyTreesAreEmpty() {
		XCTAssert(BinaryTree<Int>().isEmpty)
	}

	func testEmptyTreesAreNotLeaves() {
		XCTAssertFalse(BinaryTree<Int>().isLeaf)
	}

	func testEmptyTreesAreNotBranches() {
		XCTAssertFalse(BinaryTree<Int>().isBranch)
	}

	func testLeavesAreLeaves() {
		XCTAssert(BinaryTree(0).isLeaf)
	}

	func testLeavesAreNonEmpty() {
		XCTAssertFalse(BinaryTree(0).isEmpty)
	}

	func testLeavesAreNotBranches() {
		XCTAssertFalse(BinaryTree(0).isBranch)
	}
}

import BinaryTree
import XCTest


//
//  StartStop.swift
//  Pingit
//
//  Created by Vaughn, Jack on 10/9/15.
//  Copyright © 2015 Rutherford County Schools. All rights reserved.
//

import Foundation
import Cocoa

extension AppDelegate {

    func startChecking() {
        actionItem.title = "Stop checking....."

        Storage.timerKiller = false

        Storage.clipboardContent = Pasteboard().getContent()
        computerNameItem.title = "Checking \(Storage.clipboardContent)....."

        let timerQueue = dispatch_queue_create("org.rcsnc.startChecking", dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_BACKGROUND, 0))
        _ = DispatchTimer.scheduledTimerWithTimeInterval(milliseconds: 3000, queue: timerQueue, repeats: true) { (timer:DispatchTimer) in
            if (Storage.timerKiller) {
                timer.invalidate()
                self.setIcon(name: "normal")
            } else {
                if (self.ping(Storage.clipboardContent) == "invalid") {
                    timer.invalidate()
                }
            }
        }
    }

    func stopChecking() {
        actionItem.title = "Check computer in clipboard....."
        computerNameItem.title = "No computer to check"

        Storage.timerKiller = true

        Storage.onlineNotificationCount = 0
        Storage.offlineNotification = true

        setIcon(name: "normal")
    }
}

Put initial ping behind a separate quicker timer (1ms) so it doesn't take 3 seconds to start like the normal interval.

//
//  StartStop.swift
//  Pingit
//
//  Created by Vaughn, Jack on 10/9/15.
//  Copyright © 2015 Rutherford County Schools. All rights reserved.
//

import Foundation
import Cocoa

extension AppDelegate {

    func startChecking() {
        actionItem.title = "Stop checking....."

        Storage.timerKiller = false

        Storage.clipboardContent = Pasteboard().getContent()
        computerNameItem.title = "Checking \(Storage.clipboardContent)....."

        pingOnTimer(id: "org.rcnsc.quick_check", milliseconds: 1, repeats: false)
        pingOnTimer(id: "org.rcsnc.check_on_interval", milliseconds: 3000, repeats: true)
    }

    func stopChecking() {
        actionItem.title = "Check computer in clipboard....."
        computerNameItem.title = "No computer to check"

        Storage.timerKiller = true

        Storage.onlineNotificationCount = 0
        Storage.offlineNotification = true

        setIcon(name: "normal")
    }

    func pingOnTimer(id id: String, milliseconds: UInt, repeats: Bool) {
        let timerQueue = dispatch_queue_create(id, dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_BACKGROUND, 0))
        _ = DispatchTimer.scheduledTimerWithTimeInterval(milliseconds: milliseconds, queue: timerQueue, repeats: repeats) { (timer:DispatchTimer) in
            if (Storage.timerKiller) {
                timer.invalidate()
                self.setIcon(name: "normal")
            } else {
                if (self.ping(Storage.clipboardContent) == "invalid") {
                    timer.invalidate()
                }
            }
        }

    }
}


import UIKit
import RxSwift

class ScrollViewController: UIViewController {

    init(keyboardListener: KeyboardFrameChangeListening,
         scrollViewKeyboardAvoider: ScrollViewKeyboardAvoiding) {
        self.keyboardListener = keyboardListener
        self.scrollViewKeyboardAvoider = scrollViewKeyboardAvoider
        super.init(nibName: nil, bundle: nil)
    }

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

    // MARK: View

    var contentView: UIView? {
        get { return scrollView.contentView }
        set { scrollView.contentView = newValue }
    }

    override func loadView() {
        view = ScrollView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupBindings()
    }

    private var scrollView: ScrollView! {
        return self.view as? ScrollView
    }

    // MARK: Private

    private let keyboardListener: KeyboardFrameChangeListening
    private let scrollViewKeyboardAvoider: ScrollViewKeyboardAvoiding
    private let disposeBag = DisposeBag()

    private func setupBindings() {
        keyboardListener.keyboardWillChangeFrame
            .bind(to: scrollViewKeyboardAvoider.observeKeyboardFrameChanges(for: scrollView.scrollView))
            .disposed(by: disposeBag)
    }

}

Update visible content layout guide when adjusted content insets changes

import UIKit
import RxSwift

class ScrollViewController: UIViewController, UIScrollViewDelegate {

    init(keyboardListener: KeyboardFrameChangeListening,
         scrollViewKeyboardAvoider: ScrollViewKeyboardAvoiding) {
        self.keyboardListener = keyboardListener
        self.scrollViewKeyboardAvoider = scrollViewKeyboardAvoider
        super.init(nibName: nil, bundle: nil)
    }

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

    // MARK: View

    var contentView: UIView? {
        get { return scrollView.contentView }
        set { scrollView.contentView = newValue }
    }

    override func loadView() {
        view = ScrollView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        scrollView.scrollView.delegate = self
        setupBindings()
    }

    private var scrollView: ScrollView! {
        return self.view as? ScrollView
    }

    // MARK: UIScrollViewDelegate

    func scrollViewDidChangeAdjustedContentInset(_ scrollView: UIScrollView) {
        self.scrollView.updateVisibleContentLayoutGuide(insets: scrollView.adjustedContentInset)
    }

    // MARK: Private

    private let keyboardListener: KeyboardFrameChangeListening
    private let scrollViewKeyboardAvoider: ScrollViewKeyboardAvoiding
    private let disposeBag = DisposeBag()

    private func setupBindings() {
        keyboardListener.keyboardWillChangeFrame
            .bind(to: scrollViewKeyboardAvoider.observeKeyboardFrameChanges(for: scrollView.scrollView))
            .disposed(by: disposeBag)
    }

}


import UIKit

final class NotificationsCenterView: SetupView {

    // MARK: - Properties

    lazy var collectionView: UICollectionView = {
        return UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    }()

    // MARK: - Setup

    override func setup() {
        backgroundColor = .white
        wmf_addSubviewWithConstraintsToEdges(collectionView)
    }

}

extension NotificationsCenterView: Themeable {

    func apply(theme: Theme) {
        backgroundColor = theme.colors.paperBackground
        collectionView.backgroundColor = theme.colors.paperBackground
    }

}

Update Notifications Center collection view layout.

import UIKit

final class NotificationsCenterView: SetupView {

    // MARK: - Properties

	lazy var collectionView: UICollectionView = {
		let collectionView = UICollectionView(frame: .zero, collectionViewLayout: tableStyleLayout)
		collectionView.register(NotificationsCenterCell.self, forCellWithReuseIdentifier: NotificationsCenterCell.reuseIdentifier)
		collectionView.alwaysBounceVertical = true
		collectionView.translatesAutoresizingMaskIntoConstraints = false
		// collectionView.allowsMultipleSelection = true
		return collectionView
	}()

	private lazy var tableStyleLayout: UICollectionViewLayout = {
		if #available(iOS 13.0, *) {
			let estimatedHeightDimension = NSCollectionLayoutDimension.estimated(130)
			let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),heightDimension: estimatedHeightDimension)
			let item = NSCollectionLayoutItem(layoutSize: itemSize)
			let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),heightDimension: estimatedHeightDimension)
			let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize,subitems: [item])
			let section = NSCollectionLayoutSection(group: group)
			let layout = UICollectionViewCompositionalLayout(section: section)
			return layout
		} else {
			fatalError()
		}
	}()

    // MARK: - Setup

    override func setup() {
        backgroundColor = .white
        wmf_addSubviewWithConstraintsToEdges(collectionView)
    }

}

extension NotificationsCenterView: Themeable {

    func apply(theme: Theme) {
        backgroundColor = theme.colors.paperBackground
        collectionView.backgroundColor = theme.colors.paperBackground
    }

}


//
//  SearchBar.swift
//  Yomu
//
//  Created by Sendy Halim on 9/3/17.
//  Copyright © 2017 Sendy Halim. All rights reserved.
//

import Foundation
import UIKit

class SearchBar: UISearchBar {

  override func willMove(toSuperview newSuperview: UIView?) {
    super.willMove(toSuperview: newSuperview)

    setImage(#imageLiteral(resourceName: "search"), for: .search, state: .normal)
  }
}

Customize search bar style and colors

//
//  SearchBar.swift
//  Yomu
//
//  Created by Sendy Halim on 9/3/17.
//  Copyright © 2017 Sendy Halim. All rights reserved.
//

import Foundation
import UIKit

class SearchBar: UISearchBar {

  override func willMove(toSuperview newSuperview: UIView?) {
    super.willMove(toSuperview: newSuperview)

    setImage(#imageLiteral(resourceName: "search"), for: .search, state: .normal)
    searchBarStyle = .minimal

    let textField = value(forKey: "_searchField") as! UITextField

    textField.borderStyle = .none
    textField.backgroundColor = UIColor(hex: "#F7F7F7")
    textField.clipsToBounds = true
    textField.layer.cornerRadius = 6.0
    textField.layer.borderWidth = 1.0
    textField.layer.borderColor = textField.backgroundColor!.cgColor
    textField.textColor = UIColor(hex: "#555555")
  }
}


//
//  KataStringCalculatorSwiftUnitTests.swift
//  KataStringCalculatorSwiftUnitTests
//
//  Created by Pedro Vicente on 14/10/15.
//  Copyright © 2015 Pedro Vicente Gómez Sánchez. All rights reserved.
//

import XCTest

class KataStringCalculatorSwiftUnitTests: XCTestCase {

    func testShouldReturnZeroIfTheStringIsEmpty() {
        let stringCalculator = givenAStringCalculator()

        let sum = stringCalculator.add("")

        XCTAssertEqual(0, sum)
    }

    func testShouldReturnTheContentOfTheStringIfTheInputContainsJustOneNumber() {
        let stringCalculator = givenAStringCalculator()

        let sum = stringCalculator.add("1")

        XCTAssertEqual(1, sum)
    }

    private func givenAStringCalculator() -> StringCalculator {
        return StringCalculator()
    }

}

Add another test case related with the just one number scenario but with more than one digit

//
//  KataStringCalculatorSwiftUnitTests.swift
//  KataStringCalculatorSwiftUnitTests
//
//  Created by Pedro Vicente on 14/10/15.
//  Copyright © 2015 Pedro Vicente Gómez Sánchez. All rights reserved.
//

import XCTest

class KataStringCalculatorSwiftUnitTests: XCTestCase {

    func testShouldReturnZeroIfTheStringIsEmpty() {
        let stringCalculator = givenAStringCalculator()

        let sum = stringCalculator.add("")

        XCTAssertEqual(0, sum)
    }

    func testShouldReturnTheContentOfTheStringIfTheInputContainsJustOneNumber() {
        let stringCalculator = givenAStringCalculator()

        let sum = stringCalculator.add("1")

        XCTAssertEqual(1, sum)
    }

    func testShouldReturnTheContentOfTheStringIfTheInputContainsJustOneNumberWithMoreThanOneDigit() {
        let stringCalculator = givenAStringCalculator()

        let sum = stringCalculator.add("11")

        XCTAssertEqual(11, sum)
    }

    private func givenAStringCalculator() -> StringCalculator {
        return StringCalculator()
    }

}