//
//  AppDelegate.swift
//  Currency
//
//  Created by Nuno Coelho Santos on 11/02/2016.
//  Copyright © 2016 Nuno Coelho Santos. All rights reserved.
//

import UIKit
import RealmSwift

func bundlePath(path: String) -> String? {
    let resourcePath = NSBundle.mainBundle().resourcePath as NSString?
    return resourcePath?.stringByAppendingPathComponent(path)
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        let defaultPath = Realm.Configuration.defaultConfiguration.path!
        if let initialDatabasePath = bundlePath("initial.realm") {
            do {
                try NSFileManager.defaultManager().removeItemAtPath(defaultPath)
                try NSFileManager.defaultManager().copyItemAtPath(initialDatabasePath, toPath: defaultPath)
            } catch {}
        }

        return true
    }

}

Check number of currencies prior to database copy.

//
//  AppDelegate.swift
//  Currency
//
//  Created by Nuno Coelho Santos on 11/02/2016.
//  Copyright © 2016 Nuno Coelho Santos. All rights reserved.
//

import UIKit
import RealmSwift
import Realm

func bundlePath(path: String) -> String? {
    let resourcePath = NSBundle.mainBundle().resourcePath as NSString?
    return resourcePath?.stringByAppendingPathComponent(path)
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        if Currency.allObjects().count == 0 {
            let defaultPath = Realm.Configuration.defaultConfiguration.path!
            if let initialDatabasePath = bundlePath("initial.realm") {
                do {
                    try NSFileManager.defaultManager().removeItemAtPath(defaultPath)
                    try NSFileManager.defaultManager().copyItemAtPath(initialDatabasePath, toPath: defaultPath)
                } catch {}
            }
        }

        return true
    }

}


// RUN: %target-build-swift %S/Inputs/ObjcSuperClass.swift %s -module-name a -emit-ir 2>&1 | FileCheck %s

// REQUIRES: objc_interop

// CHECK: @_TWvdvC1a12ObjCSubclass5fieldSi = global i64 16
// CHECK: @_TWvdvC1a12ObjCSubclass5fieldSi = external global i64

func test(o: ObjCSubclass) {
  o.field = 10
}

Fix test case for 32 bit

// RUN: %target-build-swift %S/Inputs/ObjcSuperClass.swift %s -module-name a -emit-ir 2>&1 | FileCheck %s

// REQUIRES: objc_interop

// CHECK: @_TWvdvC1a12ObjCSubclass5fieldSi = global i{{[0-9]+}}
// CHECK: @_TWvdvC1a12ObjCSubclass5fieldSi = external global i{{[0-9]+}}

func test(o: ObjCSubclass) {
  o.field = 10
}


//
//  Channel.swift
//  Harekaze
//
//  Created by Yuki MIZUNO on 2016/07/10.
//  Copyright © 2016年 Yuki MIZUNO. All rights reserved.
//

import RealmSwift
import ObjectMapper

class Channel: Object, Mappable {

	// MARK: - Managed instance fileds
	dynamic var channel: Int = 0
	dynamic var id: String = ""
	dynamic var name: String = ""
	dynamic var number: Int = 0
	dynamic var sid: Int = 0
	dynamic var type: String = ""

	// MARK: - Primary key definition
	override static func primaryKey() -> String? {
		return "id"
	}

	// MARK: - Class initialization
	required convenience init?(_ map: Map) {
		self.init()
		mapping(map)
	}

	// MARK: - JSON value mapping
	func mapping(map: Map) {
		channel <- map["channel"]
		id <- map["id"]
		name <- map["name"]
		number <- map["n"]
		sid <- (map["sid"], TransformOf<Int, String>(fromJSON: { Int($0!) }, toJSON: { $0.map { String($0) } }))
		type <- map["type"]
	}
}

Fix channel json object parsing

//
//  Channel.swift
//  Harekaze
//
//  Created by Yuki MIZUNO on 2016/07/10.
//  Copyright © 2016年 Yuki MIZUNO. All rights reserved.
//

import RealmSwift
import ObjectMapper

class Channel: Object, Mappable {

	// MARK: - Managed instance fileds
	dynamic var channel: Int = 0
	dynamic var id: String = ""
	dynamic var name: String = ""
	dynamic var number: Int = 0
	dynamic var sid: Int = 0
	dynamic var type: String = ""

	// MARK: - Primary key definition
	override static func primaryKey() -> String? {
		return "id"
	}

	// MARK: - Class initialization
	required convenience init?(_ map: Map) {
		self.init()
		mapping(map)
	}

	// MARK: - JSON value mapping
	func mapping(map: Map) {
		channel <- (map["channel"], TransformOf<Int, String>(fromJSON: { Int($0!) }, toJSON: { $0.map { String($0) } }))
		id <- map["id"]
		name <- map["name"]
		number <- map["n"]
		sid <- (map["sid"], TransformOf<Int, String>(fromJSON: { Int($0!) }, toJSON: { $0.map { String($0) } }))
		type <- map["type"]
	}
}


//
//  This source file is part of the carousell/pickle open source project
//
//  Copyright © 2019 Carousell and the project authors
//  Licensed under Apache License v2.0
//
//  See https://github.com/carousell/pickle/blob/master/LICENSE for license information
//  See https://github.com/carousell/pickle/graphs/contributors for the list of project authors
//

import AVFoundation
import UIKit

final class LiveView: UIView {

    override class var layerClass: AnyClass {
        return AVCaptureVideoPreviewLayer.self
    }

    var videoPreviewLayer: AVCaptureVideoPreviewLayer {
        guard let layer = self.layer as? AVCaptureVideoPreviewLayer else {
            fatalError("Expected `AVCaptureVideoPreviewLayer` type for layer. Check PreviewView.layerClass implementation.")
        }
        layer.videoGravity = .resizeAspectFill
        return layer
    }

    var session: AVCaptureSession? {
        get {
            return videoPreviewLayer.session
        }
        set {
            videoPreviewLayer.session = newValue
        }
    }
}

Make property private and fix typo

//
//  This source file is part of the carousell/pickle open source project
//
//  Copyright © 2019 Carousell and the project authors
//  Licensed under Apache License v2.0
//
//  See https://github.com/carousell/pickle/blob/master/LICENSE for license information
//  See https://github.com/carousell/pickle/graphs/contributors for the list of project authors
//

import AVFoundation
import UIKit

final class LiveView: UIView {

    override class var layerClass: AnyClass {
        return AVCaptureVideoPreviewLayer.self
    }

    private var videoPreviewLayer: AVCaptureVideoPreviewLayer {
        guard let layer = self.layer as? AVCaptureVideoPreviewLayer else {
            fatalError("Expected `AVCaptureVideoPreviewLayer` type for layer. Check LiveView.layerClass implementation.")
        }
        layer.videoGravity = .resizeAspectFill
        return layer
    }

    var session: AVCaptureSession? {
        get {
            return videoPreviewLayer.session
        }
        set {
            videoPreviewLayer.session = newValue
        }
    }
}


import Foundation

final class MVitaItemInDirectory:MVitaItemIn
{
    let category:MVitaItemCategory
    var rawElements:[UInt32]
    var elements:[MVitaItemInElement]

    init(itemTreat:MVitaItemTreat)
    {
        category = itemTreat.category
        rawElements = []
        elements = []

        super.init(
            format:MVitaItemFormat.directory,
            treatId:itemTreat.treatId)
    }

    override func requestContent(
        strategy:MVitaLinkStrategyRequestItemTreat)
    {
        strategy.requestItemElements(
            treatId:treatId)
    }
}

Add directory type to item

import Foundation

final class MVitaItemInDirectory:MVitaItemIn
{
    let category:MVitaItemCategory
    let directoryType:UInt32
    var rawElements:[UInt32]
    var elements:[MVitaItemInElement]

    init(itemTreat:MVitaItemTreat)
    {
        category = itemTreat.category
        directoryType = itemTreat.directoryType
        rawElements = []
        elements = []

        super.init(
            format:MVitaItemFormat.directory,
            treatId:itemTreat.treatId)
    }

    override func requestContent(
        strategy:MVitaLinkStrategyRequestItemTreat)
    {
        strategy.requestItemElements(
            treatId:treatId)
    }
}


//
//  ChartAxisValueDate.swift
//  swift_charts
//
//  Created by ischuetz on 01/03/15.
//  Copyright (c) 2015 ivanschuetz. All rights reserved.
//

import UIKit

public class ChartAxisValueDate: ChartAxisValue {

    private let formatter: NSDateFormatter

    public var date: NSDate {
        return ChartAxisValueDate.dateFromScalar(self.scalar)
    }

    public init(date: NSDate, formatter: NSDateFormatter, labelSettings: ChartLabelSettings = ChartLabelSettings()) {
        self.formatter = formatter
        super.init(scalar: ChartAxisValueDate.scalarFromDate(date), labelSettings: labelSettings)
    }

    public class func dateFromScalar(scalar: Double) -> NSDate {
        return NSDate(timeIntervalSince1970: NSTimeInterval(scalar))
    }

    public class func scalarFromDate(date: NSDate) -> Double {
        return Double(date.timeIntervalSince1970)
    }

    // MARK: CustomStringConvertible

    override public var description: String {
        return self.formatter.stringFromDate(self.date)
    }
}

Use a simple closure to map dates instead of requiring a date formatter

//
//  ChartAxisValueDate.swift
//  swift_charts
//
//  Created by ischuetz on 01/03/15.
//  Copyright (c) 2015 ivanschuetz. All rights reserved.
//

import UIKit

public class ChartAxisValueDate: ChartAxisValue {

    private let formatter: (NSDate) -> String

    public var date: NSDate {
        return ChartAxisValueDate.dateFromScalar(self.scalar)
    }

    public init(date: NSDate, formatter: (NSDate) -> String, labelSettings: ChartLabelSettings = ChartLabelSettings()) {
        self.formatter = formatter
        super.init(scalar: ChartAxisValueDate.scalarFromDate(date), labelSettings: labelSettings)
    }

    convenience public init(date: NSDate, formatter: NSDateFormatter, labelSettings: ChartLabelSettings = ChartLabelSettings()) {
        self.init(date: date, formatter: { formatter.stringFromDate($0) }, labelSettings: labelSettings)
    }

    public class func dateFromScalar(scalar: Double) -> NSDate {
        return NSDate(timeIntervalSince1970: NSTimeInterval(scalar))
    }

    public class func scalarFromDate(date: NSDate) -> Double {
        return Double(date.timeIntervalSince1970)
    }

    // MARK: CustomStringConvertible

    override public var description: String {
        return self.formatter(self.date)
    }
}


//
//  SKBFLoginViewController.swift
//  SKBFLoginViewControllerDemo
//
//  Created by 孙恺 on 16/3/26.
//  http://www.talisk.cn/
//  Copyright © 2016年 sunkai. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

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

    @IBAction func presentVC(sender: AnyObject) {

        let loginVC = SKBFLoginViewController.sharedInstance // Singleton
        loginVC.blurEffectStyle = .Light // Default style is light
        loginVC.backgroundArray = [UIImage(named: "img1.jpg"),UIImage(named:"img2.jpg"), UIImage(named: "img3.jpg"), UIImage(named: "img4.jpg"), UIImage(named: "img5.jpg")]

        presentViewController(SKBFLoginViewController.sharedInstance, animated: true, completion: nil)

    }

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

}

Optimize performance of images memory.

//
//  SKBFLoginViewController.swift
//  SKBFLoginViewControllerDemo
//
//  Created by 孙恺 on 16/3/26.
//  http://www.talisk.cn/
//  Copyright © 2016年 sunkai. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

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

    @IBAction func presentVC(sender: AnyObject) {

//        let loginVC = SKBFLoginViewController.sharedInstance // Singleton
//        loginVC.blurEffectStyle = .Light // Default style is light
//        loginVC.backgroundArray = [UIImage(named: "img1.jpg"),UIImage(named:"img2.jpg"), UIImage(named: "img3.jpg"), UIImage(named: "img4.jpg"), UIImage(named: "img5.jpg")]
//
        presentViewController(SKBFLoginViewController.sharedInstance, animated: true, completion: nil)

    }

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

}


//
//  Contact.swift
//  GeneratedResults
//
//  Created by Marcin Krzyzanowski on 22/06/15.
//  Copyright (c) 2015 Marcin Krzyżanowski. All rights reserved.
//

import Foundation

struct Contact: Hashable {
    let firstName: String
    let lastName: String

    var hashValue: Int {
        return firstName.hashValue ^ lastName.hashValue
    }

    static func load() -> [Contact]? {
        if let path = NSBundle.mainBundle().pathForResource("Contacts", ofType: "csv"),
           let data = NSData(contentsOfFile: path),
           let text = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
        {
            var contacts = [Contact]()
            let lines = split(text.characters) {$0 == "\n"}.map { String($0) }
            for line in lines {
                let name = split(line.characters) { $0 == "|" }.map { String($0) }
                contacts.append(Contact(firstName: name[0], lastName: name[1]))
            }
            return contacts.count > 0 ? contacts : nil
        }
        return nil
    }
}

func ==(lhs: Contact, rhs: Contact) -> Bool {
    return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName
}

Migrate split function to new split method

//
//  Contact.swift
//  GeneratedResults
//
//  Created by Marcin Krzyzanowski on 22/06/15.
//  Copyright (c) 2015 Marcin Krzyżanowski. All rights reserved.
//

import Foundation

struct Contact: Hashable {
    let firstName: String
    let lastName: String

    var hashValue: Int {
        return firstName.hashValue ^ lastName.hashValue
    }

    static func load() -> [Contact]? {
        if let path = NSBundle.mainBundle().pathForResource("Contacts", ofType: "csv"),
           let data = NSData(contentsOfFile: path),
           let text = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
        {
            var contacts = [Contact]()
            let lines = text.characters.split() {$0 == "\n"}.map { String($0) }
            for line in lines {
                let name = line.characters.split() { $0 == "|" }.map { String($0) }
                contacts.append(Contact(firstName: name[0], lastName: name[1]))
            }
            return contacts.count > 0 ? contacts : nil
        }
        return nil
    }
}

func ==(lhs: Contact, rhs: Contact) -> Bool {
    return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName
}


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

// RUN: %target-swift-frontend -typecheck -F %S/Inputs/frameworks -DOLD -verify %s
// RUN: %target-swift-frontend -typecheck -F %S/Inputs/frameworks -DNEW -verify %s

import PrivateAsSubmodule.Private

#if OLD
import PrivateAsParallel.Private
#elseif NEW
import PrivateAsParallel_Private
#else
#error("OLD or NEW must be defined")
#endif

let _: Bool = PSGlobal // expected-error {{cannot convert value of type 'Int32'}}
let _: Bool = PSPrivateGlobal // expected-error {{cannot convert value of type 'Int32'}}
let _: Bool = PPGlobal // expected-error {{cannot convert value of type 'Int32'}}
let _: Bool = PPPrivateGlobal // expected-error {{cannot convert value of type 'Int32'}}

Add -Xcc -Wno-private-module to a test about private modules

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

// RUN: %target-swift-frontend -typecheck -F %S/Inputs/frameworks -DOLD -verify %s -Xcc -Wno-private-module
// RUN: %target-swift-frontend -typecheck -F %S/Inputs/frameworks -DNEW -verify %s -Xcc -Wno-private-module

import PrivateAsSubmodule.Private

#if OLD
import PrivateAsParallel.Private
#elseif NEW
import PrivateAsParallel_Private
#else
#error("OLD or NEW must be defined")
#endif

let _: Bool = PSGlobal // expected-error {{cannot convert value of type 'Int32'}}
let _: Bool = PSPrivateGlobal // expected-error {{cannot convert value of type 'Int32'}}
let _: Bool = PPGlobal // expected-error {{cannot convert value of type 'Int32'}}
let _: Bool = PPPrivateGlobal // expected-error {{cannot convert value of type 'Int32'}}


open class Stroke {

    open let fill: Fill
    open let width: Double
    open let cap: LineCap
    open let join: LineJoin
    open let miterLimit: Double
    open let dashes: [Double]
    open let offset: Double

    public init(fill: Fill = Color.black, width: Double = 1, cap: LineCap = .butt, join: LineJoin = .miter, miterLimit: Double = 4, dashes: [Double] = [], offset: Double = 0.0) {
        self.fill = fill
        self.width = width
        self.cap = cap
        self.join = join
        self.miterLimit = miterLimit
        self.dashes = dashes
        self.offset = offset
    }
}

Change default miter limit value

open class Stroke {

    open let fill: Fill
    open let width: Double
    open let cap: LineCap
    open let join: LineJoin
    open let miterLimit: Double
    open let dashes: [Double]
    open let offset: Double

    public init(fill: Fill = Color.black, width: Double = 1, cap: LineCap = .butt, join: LineJoin = .miter, miterLimit: Double = 10, dashes: [Double] = [], offset: Double = 0.0) {
        self.fill = fill
        self.width = width
        self.cap = cap
        self.join = join
        self.miterLimit = miterLimit
        self.dashes = dashes
        self.offset = offset
    }
}


import Foundation

enum InputStreamError: Error {
    case invalidDataCapacity(Int)
    case unreadableStream(InputStream)
}

extension Data {
    init(inputStream: InputStream, capacity: Int = Int(UInt16.max)) throws {
        var data = Data(capacity: capacity)

        let bufferSize = Swift.min(Int(UInt16.max), capacity)
        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)

        var readSize: Int

        repeat {
            readSize = inputStream.read(buffer, maxLength: bufferSize)

            switch readSize {
            case let x where x > 0:
                data.append(buffer, count: readSize)

            case let x where x < 0:
                throw InputStreamError.unreadableStream(inputStream)

            default:
                break
            }
        } while readSize > 0

        buffer.deallocate(capacity: bufferSize)

        self.init(data)
    }
}

Use buffer.deallocate() instead of buffer.deallocate(capacity:)

import Foundation

enum InputStreamError: Error {
    case invalidDataCapacity(Int)
    case unreadableStream(InputStream)
}

extension Data {
    init(inputStream: InputStream, capacity: Int = Int(UInt16.max)) throws {
        var data = Data(capacity: capacity)

        let bufferSize = Swift.min(Int(UInt16.max), capacity)
        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)

        var readSize: Int

        repeat {
            readSize = inputStream.read(buffer, maxLength: bufferSize)

            switch readSize {
            case let x where x > 0:
                data.append(buffer, count: readSize)

            case let x where x < 0:
                throw InputStreamError.unreadableStream(inputStream)

            default:
                break
            }
        } while readSize > 0

        buffer.deallocate()

        self.init(data)
    }
}


// MARK: - Delete

public extension <%= model.name %> {
    var delete: Bool {
        get {
            let deleteSQL = "DELETE FROM \(<%= model.name %>.tableName) \(itself)"
            executeSQL(deleteSQL)
            return true
        }
    }
    static var deleteAll: Bool { get { return <%= model.relation_name %>().deleteAll } }
}

public extension <%= model.relation_name %> {
    var delete: Bool { get { return deleteAll } }

    var deleteAll: Bool {
        get {
            self.result.forEach { $0.delete }
            return true
        }
    }
}

Change delete and deleteAll type to Void

// MARK: - Delete

public extension <%= model.name %> {
    var delete: Void {
        get {
            let deleteSQL = "DELETE FROM \(<%= model.name %>.tableName) \(itself)"
            executeSQL(deleteSQL)
        }
    }
    static var deleteAll: Void { get { return <%= model.relation_name %>().deleteAll } }
}

public extension <%= model.relation_name %> {
    var delete: Void { get { return deleteAll } }

    var deleteAll: Void {
        get {
            self.result.forEach { $0.delete }
        }
    }
}


//
//  Result.swift
//  Result
//
//  Created by John Gallagher on 9/12/14.
//  Copyright (c) 2014 Big Nerd Ranch. All rights reserved.
//

import Foundation

public enum Result<T> {
    case Failure(ErrorType)

    // TODO: Get rid of @autoclosure hack at some point after 6.1b1
    case Success(@autoclosure () -> T)

    public var isSuccess: Bool {
        switch self {
        case .Success: return true
        case .Failure: return false
        }
    }

    public var isFailure: Bool {
        switch self {
        case .Success: return false
        case .Failure: return true
        }
    }

    public func map<U>(f: T -> U) -> Result<U> {
        switch self {
        case let .Failure(error): return .Failure(error)
        case let .Success(value): return .Success(f(value()))
        }
    }

    public func bind<U>(f: T -> Result<U>) -> Result<U> {
        switch self {
        case let .Failure(error): return .Failure(error)
        case let .Success(value): return f(value())
        }
    }
}

extension Result: Printable {
    public var description: String {
        switch self {
        case let .Failure(error): return "Result.Failure(\(error))"
        case let .Success(value): return "Result.Success(\(value()))"
        }
    }
}

Add getters for success/failure values

//
//  Result.swift
//  Result
//
//  Created by John Gallagher on 9/12/14.
//  Copyright (c) 2014 Big Nerd Ranch. All rights reserved.
//

import Foundation

public enum Result<T> {
    case Failure(ErrorType)

    // TODO: Get rid of @autoclosure hack at some point after 6.1b1
    case Success(@autoclosure () -> T)

    public var successValue: T? {
        switch self {
        case let .Success(success): return success()
        case .Failure: return nil
        }
    }

    public var failureValue: ErrorType? {
        switch self {
        case .Success: return nil
        case let .Failure(error): return error
        }
    }

    public var isSuccess: Bool {
        switch self {
        case .Success: return true
        case .Failure: return false
        }
    }

    public var isFailure: Bool {
        switch self {
        case .Success: return false
        case .Failure: return true
        }
    }

    public func map<U>(f: T -> U) -> Result<U> {
        switch self {
        case let .Failure(error): return .Failure(error)
        case let .Success(value): return .Success(f(value()))
        }
    }

    public func bind<U>(f: T -> Result<U>) -> Result<U> {
        switch self {
        case let .Failure(error): return .Failure(error)
        case let .Success(value): return f(value())
        }
    }
}

extension Result: Printable {
    public var description: String {
        switch self {
        case let .Failure(error): return "Result.Failure(\(error))"
        case let .Success(value): return "Result.Success(\(value()))"
        }
    }
}


import Foundation
import CocoaLumberjackSwift

/// This adapter connects to remote directly.
class DirectAdapter: AdapterSocket {
    /// If this is set to `false`, then the IP address will be resolved by system.
    var resolveHost = false

    /**
     Connect to remote according to the `ConnectRequest`.

     - parameter request: The connect request.
     */
    override func openSocketWithRequest(request: ConnectRequest) {
        super.openSocketWithRequest(request)
        let host: String
        if resolveHost {
            host = request.ipAddress
            if host == "" {
                DDLogError("DNS look up failed for direct connect to \(request.host), disconnect now.")
                delegate?.didDisconnect(self)
            }
        } else {
            host = request.host
        }
        do {
            try socket.connectTo(host, port: Int(request.port), enableTLS: false, tlsSettings: nil)
        } catch {}
    }

    /**
     The socket did connect to remote.

     - parameter socket: The connected socket.
     */
    override func didConnect(socket: RawTCPSocketProtocol) {
        super.didConnect(socket)
        delegate?.readyToForward(self)
    }
}

Fix that delegate is not called

import Foundation
import CocoaLumberjackSwift

/// This adapter connects to remote directly.
class DirectAdapter: AdapterSocket {
    /// If this is set to `false`, then the IP address will be resolved by system.
    var resolveHost = false

    /**
     Connect to remote according to the `ConnectRequest`.

     - parameter request: The connect request.
     */
    override func openSocketWithRequest(request: ConnectRequest) {
        super.openSocketWithRequest(request)

        let host: String
        if resolveHost {
            host = request.ipAddress
            if host == "" {
                DDLogError("DNS look up failed for direct connect to \(request.host), disconnect now.")
                delegate?.didDisconnect(self)
            }
        } else {
            host = request.host
        }
        do {
            try socket.connectTo(host, port: Int(request.port), enableTLS: false, tlsSettings: nil)
        } catch {}
    }

    /**
     The socket did connect to remote.

     - parameter socket: The connected socket.
     */
    override func didConnect(socket: RawTCPSocketProtocol) {
        super.didConnect(socket)
        delegate?.readyToForward(self)
    }

    override func didReadData(data: NSData, withTag tag: Int, from rawSocket: RawTCPSocketProtocol) {
        super.didReadData(data, withTag: tag, from: rawSocket)
        delegate?.didReadData(data, withTag: tag, from: self)
    }

    override func didWriteData(data: NSData?, withTag tag: Int, from rawSocket: RawTCPSocketProtocol) {
        super.didWriteData(data, withTag: tag, from: rawSocket)
        delegate?.didWriteData(data, withTag: tag, from: self)
    }
}


import UIKit

public class TiltShiftOperation : NSOperation {
  public var inputImage: UIImage?
  public var outputImage: UIImage?

  override public func main() {
    guard let inputImage = inputImage else { return }
    let mask = topAndBottomGradient(inputImage.size)
    outputImage = inputImage.applyBlurWithRadius(4, maskImage: mask)
  }
}

Update the TiltShift operation to accept parameters

/*
* Copyright (c) 2015 Razeware LLC
*
* 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 UIKit

public class TiltShiftOperation : NSOperation {

  public init(image: UIImage, completion: ((UIImage?) -> ())) {
    inputImage = image
    self.completion = completion
    super.init()
  }

  private var inputImage: UIImage
  private var completion: ((UIImage?) -> ())

  override public func main() {
    let mask = topAndBottomGradient(inputImage.size)
    let outputImage = inputImage.applyBlurWithRadius(4, maskImage: mask)
    completion(outputImage)
  }
}


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

final class ErrorTests: XCTestCase {
	func testError() {
		["xy": "expected rest of sequence, or term"]
		parse(term, "x")
	}
}

// MARK: - Fixtures

private enum Tree {
	case Leaf
	case Branch([Tree])
}

private let group: Parser<String, Tree>.Function = ignore("(") ++ sequence ++ ignore(")")
private let sequence: Parser<String, Tree>.Function = (term ++ (ignore(",") ++ term)+) --> { Tree.Branch([$0] + $1) }
private let term: Parser<String, Tree>.Function = delay { (%"x" --> { _, _, _ in Tree.Leaf }) | group }

// MARK: - Imports

import Madness
import Prelude
import XCTest

Add a function to lift current parsers into error-reporting parsers.

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

final class ErrorTests: XCTestCase {
	func testError() {
		["xy": "expected rest of sequence, or term"]
		parse(term, "x")
	}
}

private func lift<C: CollectionType, Tree>(parser: Parser<C, Tree>.Function) -> (C, C.Index) -> Either<Error<C.Index>, (Tree, C.Index)> {
	return { input, index in
		parser(input, index).map { tree, rest in Either.right(tree, rest) }
			??	Either.left(Error.leaf("", index))
	}
}

// MARK: - Fixtures

private enum Tree {
	case Leaf
	case Branch([Tree])
}

private let group: Parser<String, Tree>.Function = ignore("(") ++ sequence ++ ignore(")")
private let sequence: Parser<String, Tree>.Function = (term ++ (ignore(",") ++ term)+) --> { Tree.Branch([$0] + $1) }
private let term: Parser<String, Tree>.Function = delay { (%"x" --> { _, _, _ in Tree.Leaf }) | group }

// MARK: - Imports

import Either
import Madness
import Prelude
import XCTest


import Foundation

final class MVitaPtpMessageInConfirm:MVitaPtpMessageIn
{
    let code:UInt16
    let transactionId:UInt32

    override init?(
        header:MVitaPtpMessageInHeader,
        data:Data)
    {
        let codeSize:Int = MemoryLayout<UInt16>.size
        let transactionSize:Int = MemoryLayout<UInt32>.size
        let expectedSize:Int = codeSize + transactionSize

        guard

            data.count == expectedSize

        else
        {
            return nil
        }

        let rangeTransaction:Range<Data.Index> = Range<Data.Index>(
            codeSize ..< data.count)
        let subdataTransaction:Data = data.subdata(in:rangeTransaction)

        guard

            let code:UInt16 = data.valueFromBytes(),
            let transactionId:UInt32 = subdataTransaction.valueFromBytes()

        else
        {
            return nil
        }

        self.code = code
        self.transactionId = transactionId

        super.init(
            header:header,
            data:data)
    }
}

Allow confirm data to be greater

import Foundation

final class MVitaPtpMessageInConfirm:MVitaPtpMessageIn
{
    let code:UInt16
    let transactionId:UInt32

    override init?(
        header:MVitaPtpMessageInHeader,
        data:Data)
    {
        let codeSize:Int = MemoryLayout<UInt16>.size
        let transactionSize:Int = MemoryLayout<UInt32>.size
        let expectedSize:Int = codeSize + transactionSize

        guard

            data.count >= expectedSize

        else
        {
            return nil
        }

        let rangeTransaction:Range<Data.Index> = Range<Data.Index>(
            codeSize ..< data.count)
        let subdataTransaction:Data = data.subdata(in:rangeTransaction)

        guard

            let code:UInt16 = data.valueFromBytes(),
            let transactionId:UInt32 = subdataTransaction.valueFromBytes()

        else
        {
            return nil
        }

        self.code = code
        self.transactionId = transactionId

        super.init(
            header:header,
            data:data)
    }
}


//
//  VersionCommand.swift
//  SwiftCov
//
//  Created by JP Simard on 2015-05-20.
//  Copyright (c) 2015 Realm. All rights reserved.
//

import Commandant
import Result
import SwiftCovFramework

struct VersionCommand: CommandType {
    typealias ClientError = SwiftCovError
    let verb = "version"
    let function = "Display the current version of SwiftCov"

    func run(mode: CommandMode) -> Result<(), CommandantError<SwiftCovError>> {
        switch mode {
        case let .Arguments:
            let version = NSBundle(identifier: SwiftCovFrameworkBundleIdentifier)?.objectForInfoDictionaryKey("CFBundleShortVersionString") as? String
            println(version!)

        default:
            break
        }
        return .success(())
    }
}

Remove unnecessary let for switch-case

//
//  VersionCommand.swift
//  SwiftCov
//
//  Created by JP Simard on 2015-05-20.
//  Copyright (c) 2015 Realm. All rights reserved.
//

import Commandant
import Result
import SwiftCovFramework

struct VersionCommand: CommandType {
    typealias ClientError = SwiftCovError
    let verb = "version"
    let function = "Display the current version of SwiftCov"

    func run(mode: CommandMode) -> Result<(), CommandantError<SwiftCovError>> {
        switch mode {
        case .Arguments:
            let version = NSBundle(identifier: SwiftCovFrameworkBundleIdentifier)?.objectForInfoDictionaryKey("CFBundleShortVersionString") as? String
            println(version!)

        default:
            break
        }
        return .success(())
    }
}


import Leaf
import Vapor

public final class SidebarLink: BasicTag {
    public enum Error: Swift.Error {
        case invalidSyntax(String)
    }

    public init() {}
    public let name = "sidebar:link"

    public func run(arguments: ArgumentList) throws -> Node? {
        guard arguments.count >= 2 else {
            throw Error.invalidSyntax("sidebar:link parse error: expected #sidebar:link(title, path, <icon>, ...<activePaths>)")
        }

        guard let title = arguments[0]?.string else {
            throw Error.invalidSyntax("sidebar:link parse error: expected a valid title")
        }

        guard let path = arguments[1]?.string else {
            throw Error.invalidSyntax("sidebar:link parse error: expected a valid path")
        }

        let currentPath = arguments.extractPath()

        // drop `title` and `path`
        let isActive = Request.isActive(currentPath, path, arguments.list.dropFirst(3), arguments.stem, arguments.context)

        var link = "
"

        if let icon = arguments[2]?.string {
            link.append(" ")
        }

        link.append("\(title)
")

        return .bytes(link.makeBytes())
    }
}

Fix issue with links in compact mode


//
//  Environment.swift
//  pxctest
//
//  Created by Johannes Plunien on 28/11/16.
//  Copyright © 2016 Johannes Plunien. All rights reserved.
//

import Foundation

final class Environment {

    private static let prefix = "PXCTEST_CHILD_"
    private static let insertLibrariesKey = "DYLD_INSERT_LIBRARIES"

    static func injectPrefixedVariables(from source: [String: String], into destination: [String: String]?, workingDirectoryURL: URL) -> [String: String] {
        var result = destination ?? [:]
        for (key, value) in source {
            if !key.hasPrefix(prefix) {
                continue
            }
            result[key.replacingOccurrences(of: prefix, with: "")] = value
        }
        ["IMAGE_DIFF_DIR", "KIF_SCREENSHOTS"].forEach { result[$0] = workingDirectoryURL.path }
        return result
    }

    static func injectLibrary(atPath libraryPath: String, into environment: [String: String]?) -> [String: String] {
        var result = environment ?? [:]
        var insertLibraries = (result[insertLibrariesKey] ?? "").components(separatedBy: ":").filter { $0.characters.count > 0 }
        insertLibraries.append(libraryPath)
        result[insertLibrariesKey] = insertLibraries.joined(separator: ":")
        return result
    }

}

Set environment variables to generate (raw) test coverage data

//
//  Environment.swift
//  pxctest
//
//  Created by Johannes Plunien on 28/11/16.
//  Copyright © 2016 Johannes Plunien. All rights reserved.
//

import Foundation

final class Environment {

    private static let prefix = "PXCTEST_CHILD_"
    private static let insertLibrariesKey = "DYLD_INSERT_LIBRARIES"

    static func injectPrefixedVariables(from source: [String: String], into destination: [String: String]?, workingDirectoryURL: URL) -> [String: String] {
        var result = destination ?? [:]
        for (key, value) in source {
            if !key.hasPrefix(prefix) {
                continue
            }
            result[key.replacingOccurrences(of: prefix, with: "")] = value
        }
        ["IMAGE_DIFF_DIR", "KIF_SCREENSHOTS"].forEach { result[$0] = workingDirectoryURL.path }
        result["LLVM_PROFILE_FILE"] = workingDirectoryURL.appendingPathComponent("test-coverage.%p.profraw").path
        result["__XPC_LLVM_PROFILE_FILE"] = workingDirectoryURL.appendingPathComponent("test-coverage.%p.profraw").path
        return result
    }

    static func injectLibrary(atPath libraryPath: String, into environment: [String: String]?) -> [String: String] {
        var result = environment ?? [:]
        var insertLibraries = (result[insertLibrariesKey] ?? "").components(separatedBy: ":").filter { $0.characters.count > 0 }
        insertLibraries.append(libraryPath)
        result[insertLibrariesKey] = insertLibraries.joined(separator: ":")
        return result
    }

}


//
//  StartViewController.swift
//  PDFReader
//
//  Created by Ricardo Nunez on 7/8/16.
//  Copyright © 2016 AK. All rights reserved.
//

import UIKit
import PDFReader

internal final class StartViewController: UIViewController {
    @IBAction private func showSmallPDFDocument() {
        let smallPDFDocumentName = "apple"
        showDocument(document(smallPDFDocumentName))
    }

    @IBAction private func showLargePDFDocument() {
        let smallPDFDocumentName = "mongodb"
        showDocument(document(smallPDFDocumentName))
    }

    private func document(name: String) -> PDFDocument {
        guard let documentURL = NSBundle.mainBundle().URLForResource(name, withExtension: "pdf") else {
            fatalError("File could not be found")
        }
        return PDFDocument(tempURL: documentURL)
    }

    private func showDocument(document: PDFDocument) {
        let storyboard = UIStoryboard(name: "PDFReader", bundle: NSBundle(forClass: PDFViewController.self))
        let controller = storyboard.instantiateInitialViewController() as! PDFViewController
        controller.document = document
        controller.title = document.fileName
        navigationController?.pushViewController(controller, animated: true)
    }

}

Fix parameter name on example

//
//  StartViewController.swift
//  PDFReader
//
//  Created by Ricardo Nunez on 7/8/16.
//  Copyright © 2016 AK. All rights reserved.
//

import UIKit
import PDFReader

internal final class StartViewController: UIViewController {
    @IBAction private func showSmallPDFDocument() {
        let smallPDFDocumentName = "apple"
        showDocument(document(smallPDFDocumentName))
    }

    @IBAction private func showLargePDFDocument() {
        let smallPDFDocumentName = "mongodb"
        showDocument(document(smallPDFDocumentName))
    }

    private func document(name: String) -> PDFDocument {
        guard let documentURL = NSBundle.mainBundle().URLForResource(name, withExtension: "pdf") else {
            fatalError("File could not be found")
        }
        return PDFDocument(fileURL: documentURL)
    }

    private func showDocument(document: PDFDocument) {
        let storyboard = UIStoryboard(name: "PDFReader", bundle: NSBundle(forClass: PDFViewController.self))
        let controller = storyboard.instantiateInitialViewController() as! PDFViewController
        controller.document = document
        controller.title = document.fileName
        navigationController?.pushViewController(controller, animated: true)
    }

}


import UIKit

class StingCell: UICollectionViewCell {

    @IBOutlet weak var playbackIndicator: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var footerLabel: UILabel!

    var color = Color.default {
        didSet {
            backgroundColor = color.value
            layer.borderColor = color.value.cgColor
        }
    }

    var isPlaying = false {
        didSet {
            updatePlaybackIndicator()
        }
    }

    var isCued = false {
        didSet {
            updatePlaybackIndicator()
        }
    }

    var isMissing = false {
        didSet {
            updatePlaybackIndicator()
        }
    }

    func updatePlaybackIndicator() {
        if isMissing {
            playbackIndicator.image = UIImage(systemName: "exclamationmark.octagon")
            playbackIndicator.tintColor = .white
        } else if isPlaying {
            playbackIndicator.image = UIImage(systemName: "play.circle.fill")
            playbackIndicator.tintColor = .white
        } else if isCued{
            playbackIndicator.image = UIImage(systemName: "pause.circle")
            playbackIndicator.tintColor = .white
        } else {
            playbackIndicator.image = UIImage(systemName: "circle")
            playbackIndicator.tintColor = .backgroundColor
        }
    }

}

Make missing sting indicator more obvious.

import UIKit

class StingCell: UICollectionViewCell {

    @IBOutlet weak var playbackIndicator: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var footerLabel: UILabel!

    var color = Color.default {
        didSet {
            backgroundColor = color.value
            layer.borderColor = color.value.cgColor
        }
    }

    var isPlaying = false {
        didSet {
            updatePlaybackIndicator()
        }
    }

    var isCued = false {
        didSet {
            updatePlaybackIndicator()
        }
    }

    var isMissing = false {
        didSet {
            updatePlaybackIndicator()
        }
    }

    func updatePlaybackIndicator() {
        if isMissing {
            playbackIndicator.image = UIImage(systemName: "exclamationmark.octagon.fill")
            playbackIndicator.tintColor = UIColor.white.withAlphaComponent(0.8)
        } else if isPlaying {
            playbackIndicator.image = UIImage(systemName: "play.circle.fill")
            playbackIndicator.tintColor = .white
        } else if isCued{
            playbackIndicator.image = UIImage(systemName: "pause.circle")
            playbackIndicator.tintColor = .white
        } else {
            playbackIndicator.image = UIImage(systemName: "circle")
            playbackIndicator.tintColor = .backgroundColor
        }
    }

}


// RUN: %target-run-simple-swift(-parse-as-library -Xfrontend -disable-availability-checking) | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: concurrency_runtime

// UNSUPPORTED: back_deployment_runtime

class C {}

@_silgen_name("exit")
func exit(_ code : UInt32) -> Never

@main
enum Main {
  static func main() async {
    weak var weakRef: C?
    do {
      let c = C()
      let t = Task.detached { return c }
      weakRef = c
    }
    Task.detached {
      try await Task.sleep(nanoseconds: 10_000_000_000)
      print("Fail!")
      exit(1)
    }

    while weakRef != nil {
      await Task.yield()
    }
    // CHECK: Success
    print("Success!")
  }
}

Stop calling exit with wrong calling convention

// RUN: %target-run-simple-swift(-parse-as-library -Xfrontend -disable-availability-checking) | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: concurrency_runtime

// UNSUPPORTED: back_deployment_runtime

class C {}

@main
enum Main {
  static func main() async {
    weak var weakRef: C?
    do {
      let c = C()
      let t = Task.detached { return c }
      weakRef = c
    }
    Task.detached {
      try await Task.sleep(nanoseconds: 10_000_000_000)
      fatalError("Fail!")
    }

    while weakRef != nil {
      await Task.yield()
    }
    // CHECK: Success
    print("Success!")
  }
}


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

public typealias Type = Value

public typealias Context = [Name: Type]

public func lookup<A: Hashable, B>(dictionary: [A: B], key: A) -> B? {
	return dictionary[key]
}

public func lookup<A: Equatable, B, S: SequenceType where S.Generator.Element == (A, B)>(sequence: S, key: A) -> B? {
	for (k, v) in sequence {
		if k == key { return v }
	}
	return nil
}

Remove the old lookup function.


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

// RUN: not --crash %target-swift-frontend %s -emit-ir
{{}
return.h.h == Int

Disable a compiler-crasher that is crashing inconsistently.

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

// RUN: not --crash %target-swift-frontend %s -emit-ir
// REQUIRES: non_escaping_type_variables
{{}
return.h.h == Int


// RUN: %sourcekitd-test -req=doc-info -module Foo -- -F %S/../Inputs/libIDE-mock-sdk \
// RUN:         %mcp_opt %clang-importer-sdk | %sed_clean > %t.response
// RUN: diff -u %s.response %t.response

Disable failing test for now

// XFAIL: *
// RUN: %sourcekitd-test -req=doc-info -module Foo -- -F %S/../Inputs/libIDE-mock-sdk \
// RUN:         %mcp_opt %clang-importer-sdk | %sed_clean > %t.response
// RUN: diff -u %s.response %t.response


import XCTest
@testable import gattaca

class TMGifLoader:XCTestCase
{
    private let kWaitExpectation:TimeInterval = 3

    //MARK: internal

    func testLoad()
    {
        let bundle:Bundle = Bundle(for:TMGifLoader.self)

        guard

            let coreData:Database = Database(bundle:bundle)

        else
        {
            return
        }

        let loadExpectation:XCTestExpectation = expectation(
            description:"load gifs")

        let gif:MGif = MGif()
        gif.load(coreData:coreData)
        {
            loadExpectation.fulfill()
        }

        waitForExpectations(timeout:kWaitExpectation)
        { (error:Error?) in
        }
    }
}

Test load complete and map

import XCTest
@testable import gattaca

class TMGifLoader:XCTestCase
{
    private var coreData:Database?
    private let kIdentifier:String = "lorem ipsum"
    private let kWaitExpectation:TimeInterval = 3

    override func setUp()
    {
        super.setUp()

        let bundle:Bundle = Bundle(for:TMGifLoader.self)
        coreData = Database(bundle:bundle)
    }

    //MARK: private

    private func createGif(completion:@escaping((DGif) -> ()))
    {
        guard

            let coreData:Database = self.coreData

        else
        {
            return
        }

        let identifier:String = kIdentifier

        coreData.create
        { (gif:DGif) in

            gif.initialValues(identifier:identifier)
            completion(gif)
        }
    }

    //MARK: internal

    func testLoad()
    {
        guard

            let coreData:Database = self.coreData

        else
        {
            return
        }

        let loadExpectation:XCTestExpectation = expectation(
            description:"load gifs")

        let gif:MGif = MGif()
        gif.load(coreData:coreData)
        {
            loadExpectation.fulfill()
        }

        waitForExpectations(timeout:kWaitExpectation)
        { (error:Error?) in
        }
    }

    func testLoadCompleteAndMap()
    {
        let identifier:String = kIdentifier
        let gif:MGif = MGif()
        let loadExpectation:XCTestExpectation = expectation(
            description:"load gifs")

        createGif
        { (item:DGif) in

            let items:[DGif] = [item]
            gif.loadComplete(gifs:items)
            {
                loadExpectation.fulfill()
            }
        }

        waitForExpectations(timeout:kWaitExpectation)
        { (error:Error?) in

            XCTAssertNotNil(
                gif.map[identifier],
                "failed mapping item")
        }
    }
}


import UIKit
import GifHero

class VHomeDisplay:View<VHome, MHome, CHome>
{
    private weak var viewGif:GifView?

    required init(controller:CHome)
    {
        super.init(controller:controller)
        isUserInteractionEnabled = false
        backgroundColor = UIColor.black
    }

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

    //MARK: private

    private func factoryGif()
    {
        guard

            let item:MHomeItem = controller.model.items.first

        else
        {
            return
        }

        let url:URL = item.url

        let viewGif:GifView = GifView()
        viewGif.url = url
        viewGif.animating = true
        self.viewGif = viewGif

        addSubview(viewGif)

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

    //MARK: public

    func refresh()
    {
        viewGif?.removeFromSuperview()
        factoryGif()
    }
}

Change gif content to aspect fit

import UIKit
import GifHero

class VHomeDisplay:View<VHome, MHome, CHome>
{
    private weak var viewGif:GifView?

    required init(controller:CHome)
    {
        super.init(controller:controller)
        isUserInteractionEnabled = false
        backgroundColor = UIColor.black
    }

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

    //MARK: private

    private func factoryGif()
    {
        guard

            let item:MHomeItem = controller.model.items.first

        else
        {
            return
        }

        let url:URL = item.url

        let viewGif:GifView = GifView()
        viewGif.contentMode = UIViewContentMode.scaleAspectFit
        viewGif.url = url
        viewGif.animating = true
        self.viewGif = viewGif

        addSubview(viewGif)

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

    //MARK: public

    func refresh()
    {
        viewGif?.removeFromSuperview()
        factoryGif()
    }
}


//
//  PlacementResponseOperation.swift
//  AdButler
//
//  Created by Ryuichi Saito on 11/11/16.
//  Copyright © 2016 AdButler. All rights reserved.
//

import Foundation

class PlacementResponseOperation: AsynchronousOperation {
    let _responseCollector: ResponseCollector

    init(responseCollector: ResponseCollector) {
        _responseCollector = responseCollector
    }

    override func main() {
        let responses = _responseCollector.responses
        var placements = [Placement]()
        for response in responses {
            switch response {
            case .success(let status, let eachPlacements):
                placements.append(contentsOf: eachPlacements)
            default:
                ()
            }
        }
        let status: ResponseStatus = placements.isEmpty ? .noAds : .success
        _responseCollector.complete(.success(status, placements))
        finish()
    }
}

Handle unsuccesful requests for multiple placements

//
//  PlacementResponseOperation.swift
//  AdButler
//
//  Created by Ryuichi Saito on 11/11/16.
//  Copyright © 2016 AdButler. All rights reserved.
//

import Foundation

class PlacementResponseOperation: AsynchronousOperation {
    let _responseCollector: ResponseCollector

    init(responseCollector: ResponseCollector) {
        _responseCollector = responseCollector
    }

    override func main() {
        defer {
            finish()
        }

        let responses = _responseCollector.responses
        var placements = [Placement]()
        for response in responses {
            if case let .success(status, eachPlacements) = response {
                // we aggregate all successful responses
                placements.append(contentsOf: eachPlacements)
            } else {
                // for unsuccessful requests, we just return the first failure
                _responseCollector.complete(response)
                return
            }
        }
        let status: ResponseStatus = placements.isEmpty ? .noAds : .success
        _responseCollector.complete(.success(status, placements))
    }
}


import UIKit
import Timepiece

class TimelineCollectionViewController: UICollectionViewController {

    var timeArray = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        for (var date = NSDate().beginningOfDay; date < NSDate().endOfDay; date = date + 30.minutes) {
            timeArray.append(date.stringFromFormat("HH:mm"))
        }
    }

    // MARK: UICollectionViewDataSource

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return timeArray.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let reuseIdentifier = CollectionViewCellreuseIdentifier.TimeCell.rawValue
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! TimeCollectionViewCell
        cell.timeLabel.text = timeArray[indexPath.row]
        return cell
    }
}

Move position to current time

import UIKit
import Timepiece

class TimelineCollectionViewController: UICollectionViewController {

    var timeArray = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        for (var date = NSDate().beginningOfDay; date < NSDate().endOfDay; date = date + 30.minutes) {
            timeArray.append(date.stringFromFormat("HH:mm"))
        }
    }

    override func viewDidAppear(animated: Bool) {
        let date = NSDate()
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
        let hour = components.hour
        let minute = components.minute

        let newIndex = NSIndexPath(forItem: (hour * 60 + minute) / 30, inSection: 0)
        self.collectionView?.scrollToItemAtIndexPath(newIndex, atScrollPosition: UICollectionViewScrollPosition.CenteredVertically, animated: true)
    }

    // MARK: UICollectionViewDataSource

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return timeArray.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let reuseIdentifier = CollectionViewCellreuseIdentifier.TimeCell.rawValue
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! TimeCollectionViewCell
        cell.timeLabel.text = timeArray[indexPath.row]
        return cell
    }
}


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

import Foundation

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

    public init(){}

    private enum StorageKeys{

        static let emailKey = "SendToMeEmail"
    }

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

        return !getEmail().isEmpty
    }

    /**
     Returns the email value saved

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

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

    /**
     Save an email value in the local storage

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

        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setValue(email, forKey: StorageKeys.emailKey)

        defaults.synchronize()
    }

    /**
     Clear the value of the email in the storage
     */
    public func clearEmail()
    {
        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.removeObjectForKey(StorageKeys.emailKey)
    }

}

Change class to struct since is more appropiate

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

import Foundation

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

    public init(){}

    private enum StorageKeys{

        static let emailKey = "SendToMeEmail"
    }

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

        return !getEmail().isEmpty
    }

    /**
     Returns the email value saved

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

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

    /**
     Save an email value in the local storage

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

        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setValue(email, forKey: StorageKeys.emailKey)

        defaults.synchronize()

        log.debug("Email \(email) saved")
    }

    /**
     Clear the value of the email in the storage
     */
    public func clearEmail()
    {
        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.removeObjectForKey(StorageKeys.emailKey)

        log.debug("Email cleared")
    }

}


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

import Foundation
import SwiftyJSON

public protocol JSONInitializable {
    init(json: JSON) throws
}

public protocol JSONRepresentable {
    var jsonValue: JSON { get }
}

extension String: JSONInitializable, JSONRepresentable {
    public init(json: JSON) throws { self = try json.value() }
    public var jsonValue: JSON { return JSON(self) }
}

extension Bool: JSONInitializable, JSONRepresentable {
    public init(json: JSON) throws { self = try json.value() }
    public var jsonValue: JSON { return JSON(self) }
}

extension Int: JSONInitializable, JSONRepresentable {
    public init(json: JSON) throws { self = try json.value() }
    public var jsonValue: JSON { return JSON(self) }
}

extension Double: JSONInitializable, JSONRepresentable {
    public init(json: JSON) throws { self = try json.value() }
    public var jsonValue: JSON { return JSON(self) }
}

Use protocol inits in extensions to basic types

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

import Foundation
import SwiftyJSON

public protocol JSONInitializable {
    init(json: JSON) throws
}

public protocol JSONRepresentable {
    var jsonValue: JSON { get }
}

extension String: JSONInitializable, JSONRepresentable {
    public init(json: JSON) throws { self = try json.value() }
    public var jsonValue: JSON { return JSON(string: self) }
}

extension Bool: JSONInitializable, JSONRepresentable {
    public init(json: JSON) throws { self = try json.value() }
    public var jsonValue: JSON { return JSON(bool: self) }
}

extension Int: JSONInitializable, JSONRepresentable {
    public init(json: JSON) throws { self = try json.value() }
    public var jsonValue: JSON { return JSON(int: self) }
}

extension Double: JSONInitializable, JSONRepresentable {
    public init(json: JSON) throws { self = try json.value() }
    public var jsonValue: JSON { return JSON(double: self) }
}


import Foundation

struct MCreateSaveRenderRect
{
    let x:Int
    let y:Int
    let width:Int
    let height:Int
}

Change rect to double values

import Foundation

struct MCreateSaveRenderRect
{
    let x:Double
    let y:Double
    let width:Double
    let height:Double
}


//
//  NotificationRouter.swift
//  Eurofurence
//
//  Copyright © 2017 Eurofurence. All rights reserved.
//

import Foundation
import UserNotificationsUI

protocol NotificationRouter {
	func showLocalNotificationTarget(for notification: UILocalNotification, doWaitForDataStore: Bool)
	func showLocalNotification(for notification: UILocalNotification)

	func showRemoteNotificationTarget(for userInfo: [AnyHashable : Any], doWaitForDataStore: Bool)
	func showRemoteNotification(for userInfo: [AnyHashable : Any])
}

enum NotificationUserInfoKey: String {
	/// See NotificationContentType for expected values
	case ContentType = "event"
	/// Id of event related to local notification
	case EventId = "event_id"
	case EventLastChangeDateTimeUtc = "event_lastchangedatetimeutc"
	/// Id of announcement related to remote notification
	case AnnouncementId = "announcement_id"
}

enum NotificationContentType: String {
	/// New announcement has been posted
	case Announcement = "announcement"
	/// Generic notification (currently only used for messages)
	case Notification = "notification"
	/// Backend data changed; should trigger silent background sync
	case Sync = "sync"
}

Add notification sound options enum

//
//  NotificationRouter.swift
//  Eurofurence
//
//  Copyright © 2017 Eurofurence. All rights reserved.
//

import Foundation
import UserNotificationsUI

protocol NotificationRouter {
	func showLocalNotificationTarget(for notification: UILocalNotification, doWaitForDataStore: Bool)
	func showLocalNotification(for notification: UILocalNotification)

	func showRemoteNotificationTarget(for userInfo: [AnyHashable : Any], doWaitForDataStore: Bool)
	func showRemoteNotification(for userInfo: [AnyHashable : Any])
}

enum NotificationUserInfoKey: String {
	/// See NotificationContentType for expected values
	case ContentType = "event"
	/// Id of event related to local notification
	case EventId = "event_id"
	case EventLastChangeDateTimeUtc = "event_lastchangedatetimeutc"
	/// Id of announcement related to remote notification
	case AnnouncementId = "announcement_id"
}

enum NotificationContentType: String {
	/// New announcement has been posted
	case Announcement = "announcement"
	/// Generic notification (currently only used for messages)
	case Notification = "notification"
	/// Backend data changed; should trigger silent background sync
	case Sync = "sync"
}

enum NotificationSound: Int {
	case None = 0
	case Classic = 1
	case Themed = 2
}


//
//  DataSettable.swift
//  FountainKit
//
//  Created by Cesar Tardaguila on 5/3/2016.
//

/**
    This protocol should be implemented by table view and collection view cells.
*/
public protocol DataSettable {
    associatedtype DataType
    var data: DataType? {get set}
}

/**
    Cells implementing the DataSettable protocol would also implement cellReuseIdentifier
*/
extension DataSettable {
    /**
        Returns the cell name as string, so the cell can be registered with table or collection views.
    */
    public static func cellReuseIdentifier() -> String {
        return String(self)
    }
}

Update to latest Xcode beta

//
//  DataSettable.swift
//  FountainKit
//
//  Created by Cesar Tardaguila on 5/3/2016.
//

/**
    This protocol should be implemented by table view and collection view cells.
*/
public protocol DataSettable {
    associatedtype DataType
    var data: DataType? {get set}
}

/**
    Cells implementing the DataSettable protocol would also implement cellReuseIdentifier
*/
extension DataSettable {
    /**
        Returns the cell name as string, so the cell can be registered with table or collection views.
    */
    public static func cellReuseIdentifier() -> String {
        return String(describing:self)
    }
}


//
//  UIKit+TMBarItem.swift
//  Tabman
//
//  Created by Merrick Sapsford on 19/10/2018.
//  Copyright © 2018 UI At Six. All rights reserved.
//

import UIKit

/// :nodoc:
extension UINavigationItem: TMBarItemable {

    public var image: UIImage? {
        return nil
    }
}

/// :nodoc:
extension UITabBarItem: TMBarItemable {
}

/// :nodoc:
extension UIViewController: TMBarItemable {

    public var image: UIImage? {
        return tabBarItem.image
    }
}

Remove UIViewController support from TMBarItemable


//
//  Storyboard.swift
//  BothamUI
//
//  Created by Davide Mendolia on 03/12/15.
//  Copyright © 2015 GoKarumi S.L. All rights reserved.
//

import Foundation

public struct BothamStoryboard {
    private let name: String

    public init(name: String) {
        self.name = name
    }

    private func storyboard(name: String) -> UIStoryboard {
        return UIStoryboard(name: name, bundle: NSBundle.mainBundle())
    }

    public func initialViewController<T>() -> T {
        let uiStoryboard = storyboard(name)
        return uiStoryboard.instantiateInitialViewController() as! T
    }

    public func instantiateViewController<T>(viewControllerIdentifier: String) -> T {
        let uiStoryboard = storyboard(name)
        return uiStoryboard.instantiateViewControllerWithIdentifier(viewControllerIdentifier) as! T
    }

    public func instantiateViewController<T>() -> T {
        return instantiateViewController(String(T.self))
    }
}

Add support to indicate the bundle in which the Storyboard should be located

//
//  Storyboard.swift
//  BothamUI
//
//  Created by Davide Mendolia on 03/12/15.
//  Copyright © 2015 GoKarumi S.L. All rights reserved.
//

import Foundation

public struct BothamStoryboard {
    private let name: String
    private let bundle: NSBundle

    public init(name: String, bundle: NSBundle = NSBundle.mainBundle()) {
        self.name = name
        self.bundle = bundle
    }

    private func storyboard(name: String, bundle: NSBundle) -> UIStoryboard {
        return UIStoryboard(name: name, bundle: bundle)
    }

    public func initialViewController<T>() -> T {
        let uiStoryboard = storyboard(name, bundle: bundle)
        return uiStoryboard.instantiateInitialViewController() as! T
    }

    public func instantiateViewController<T>(viewControllerIdentifier: String) -> T {
        let uiStoryboard = storyboard(name, bundle: bundle)
        return uiStoryboard.instantiateViewControllerWithIdentifier(viewControllerIdentifier) as! T
    }

    public func instantiateViewController<T>() -> T {
        return instantiateViewController(String(T.self))
    }
}


//
//  DispatchTimeIntervalExtension.swift
//  HandySwift
//
//  Created by Cihat Gündüz on 28.01.17.
//  Copyright © 2017 Flinesoft. All rights reserved.
//

import Foundation

public typealias Timespan = DispatchTimeInterval

extension Timespan {
    /// - Returns: The time in seconds using the`TimeInterval` type.
    var timeInterval: TimeInterval {
        switch self {
        case .seconds(let seconds):
            return Double(seconds)
        case .milliseconds(let milliseconds):
            return Double(milliseconds) / 1_000
        case .microseconds(let microseconds):
            return Double(microseconds) / 1_000_000
        case .nanoseconds(let nanoseconds):
            return Double(nanoseconds) / 1_000_000_000
        }
    }
}

Make DispatchTimeInterval extension timeInterval method public

//
//  DispatchTimeIntervalExtension.swift
//  HandySwift
//
//  Created by Cihat Gündüz on 28.01.17.
//  Copyright © 2017 Flinesoft. All rights reserved.
//

import Foundation

public typealias Timespan = DispatchTimeInterval

extension Timespan {
    /// - Returns: The time in seconds using the`TimeInterval` type.
    public var timeInterval: TimeInterval {
        switch self {
        case .seconds(let seconds):
            return Double(seconds)
        case .milliseconds(let milliseconds):
            return Double(milliseconds) / 1_000
        case .microseconds(let microseconds):
            return Double(microseconds) / 1_000_000
        case .nanoseconds(let nanoseconds):
            return Double(nanoseconds) / 1_000_000_000
        }
    }
}


//
//  UIButton.swift
//  ZamzamUI
//
//  Created by Basem Emara on 2019-05-22.
//  Copyright © 2019 Zamzam Inc. All rights reserved.
//

#if os(iOS)
import UIKit

public extension UIButton {

    /// The color of the title font with UIAppearance support.
    @objc dynamic var titleFont: UIFont? {
        // UIAppearance: https://stackoverflow.com/a/42410383
        get { return titleLabel?.font }
        set { titleLabel?.font = newValue }
    }
}
#endif

Fix App Store confusion of private API error

//
//  UIButton.swift
//  ZamzamUI
//
//  Created by Basem Emara on 2019-05-22.
//  Copyright © 2019 Zamzam Inc. All rights reserved.
//

#if os(iOS)
import UIKit

public extension UIButton {

    /// The color of the title font with UIAppearance support.
    @objc dynamic var titleLabelFont: UIFont? {
        // UIAppearance: https://stackoverflow.com/a/42410383
        get { return titleLabel?.font }
        set { titleLabel?.font = newValue }
    }
}
#endif


//
//  DrawController.swift
//  Draw
//
//  Created by Julian Grosshauser on 18/01/16.
//  Copyright © 2016 Julian Grosshauser. All rights reserved.
//

import UIKit

class DrawController: UIViewController {

    //MARK: Properties

    private var previousTouchLocation: CGPoint?

    //MARK: UIViewController

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        previousTouchLocation = touches.first?.locationInView(view)
    }
}

Add fullscreen image view as subview

//
//  DrawController.swift
//  Draw
//
//  Created by Julian Grosshauser on 18/01/16.
//  Copyright © 2016 Julian Grosshauser. All rights reserved.
//

import UIKit

class DrawController: UIViewController {

    //MARK: Properties

    private var previousTouchLocation: CGPoint?
    private let imageView = UIImageView()

    //MARK: UIViewController

    override func viewDidLoad() {
        super.viewDidLoad()
        imageView.frame = view.frame
        view.addSubview(imageView)
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        previousTouchLocation = touches.first?.locationInView(view)
    }
}


//
//  ApplicationManager.swift
//  ledger-wallet-ios
//
//  Created by Nicolas Bigot on 13/02/2015.
//  Copyright (c) 2015 Ledger. All rights reserved.
//

import Foundation

final class ApplicationManager: BaseManager {

    var UUID: String {
        if let uuid = preferences.stringForKey("uuid") {
            return uuid
        }
        let uuid = NSUUID().UUIDString
        preferences.setObject(uuid, forKey: "uuid")
        return uuid
    }

    var isInDebug: Bool {
        #if DEBUG
            return true
            #else
            return false
        #endif
    }

    var isInProduction: Bool {
        return !isInDebug
    }

    var bundleIdentifier: String {
        return NSBundle.mainBundle().bundleIdentifier ?? ""
    }

    var disablesIdleTimer: Bool {
        get {
            return UIApplication.sharedApplication().idleTimerDisabled
        }
        set {
            UIApplication.sharedApplication().idleTimerDisabled = newValue
        }
    }

    func handleFirstLaunch() {
        // if app hasn't been launched before
        if !preferences.boolForKey("already_launched") {
            preferences.setBool(true, forKey: "already_launched")

            // delete all pairing keychain items
            PairingKeychainItem.destroyAll()
        }
    }

}

Add library path management in Application Manager

//
//  ApplicationManager.swift
//  ledger-wallet-ios
//
//  Created by Nicolas Bigot on 13/02/2015.
//  Copyright (c) 2015 Ledger. All rights reserved.
//

import Foundation

final class ApplicationManager: BaseManager {

    //lazy private var logger = { return Logger.sharedInstance("ApplicationManager") }()

    var UUID: String {
        if let uuid = preferences.stringForKey("uuid") {
            return uuid
        }
        let uuid = NSUUID().UUIDString
        preferences.setObject(uuid, forKey: "uuid")
        return uuid
    }

    var isInDebug: Bool {
        #if DEBUG
            return true
            #else
            return false
        #endif
    }

    var isInProduction: Bool {
        return !isInDebug
    }

    var bundleIdentifier: String {
        return NSBundle.mainBundle().bundleIdentifier ?? ""
    }

    var disablesIdleTimer: Bool {
        get {
            return UIApplication.sharedApplication().idleTimerDisabled
        }
        set {
            UIApplication.sharedApplication().idleTimerDisabled = newValue
        }
    }

    var libraryDirectoryPath: String {
        return NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0] as! String
    }

    // MARK: Utilities

    func handleFirstLaunch() {
        // if app hasn't been launched before
        if !preferences.boolForKey("already_launched") {
            preferences.setBool(true, forKey: "already_launched")

            // delete all pairing keychain items
            PairingKeychainItem.destroyAll()
        }
    }

    func printLibraryPathIfNeeded() {
        if self.isInDebug {
            Logger.sharedInstance(self.className()).info(libraryDirectoryPath)
        }
    }

}


//
//  Copyright (c) 2018 Google Inc.
//
//  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 UIKit
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Initialize Firebase service.
    FirebaseApp.configure()
    return true
  }
}

Update CrashlyticsExample to Swift 4.2

//
//  Copyright (c) 2018 Google Inc.
//
//  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 UIKit
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Initialize Firebase service.
    FirebaseApp.configure()
    return true
  }
}


//
//  ViewController.swift
//  DPI
//
//  Created by Bas Broek on 5/26/16.
//  Copyright © 2016 Bas Broek. All rights reserved.
//

import UIKit

public var allUsers: [User] = []
private let printer = Printer()

class ViewController: UIViewController {

  @IBOutlet weak var notificationPicker: UIPickerView!
  @IBOutlet weak var notificationMessage: UITextField!

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

extension ViewController {

  @IBAction func send(sender: AnyObject) {
    guard let message = notificationMessage.text else { return }
    let topic = Topic.cases[notificationPicker.selectedRowInComponent(0)]

    printer.send(notification: Notification(topic: topic, message: message))
    notificationMessage.text = ""
  }
}

extension ViewController: UIPickerViewDataSource {

  func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
  }

  func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return Topic.cases.count
  }
}

extension ViewController: UIPickerViewDelegate {

  func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return Topic.cases[row].rawValue
  }
}

Set picker standard to third item

//
//  ViewController.swift
//  DPI
//
//  Created by Bas Broek on 5/26/16.
//  Copyright © 2016 Bas Broek. All rights reserved.
//

import UIKit

public var allUsers: [User] = []
private let printer = Printer()

class ViewController: UIViewController {

  @IBOutlet weak var notificationPicker: UIPickerView! {
    didSet {
      notificationPicker.selectRow(2, inComponent: 0, animated: true)
    }
  }
  @IBOutlet weak var notificationMessage: UITextField!

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

extension ViewController {

  @IBAction func send(sender: AnyObject) {
    guard let message = notificationMessage.text else { return }
    let topic = Topic.cases[notificationPicker.selectedRowInComponent(0)]

    printer.send(notification: Notification(topic: topic, message: message))
    notificationMessage.text = ""
  }
}

extension ViewController: UIPickerViewDataSource {

  func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
  }

  func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return Topic.cases.count
  }
}

extension ViewController: UIPickerViewDelegate {

  func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return Topic.cases[row].rawValue
  }
}


//
//  ApiUrls.swift
//  GithubClient
//
//  Created by Eduardo Arenas on 8/5/17.
//  Copyright © 2017 GameChanger. All rights reserved.
//

import Foundation

enum ApiUrl {
  private static let baseURL = "https://api.github.com/"

  case user(String)
  case users

  var fullPath: String {
    switch self {
    case .user(let username): return ApiUrl.fullPath(from: ["users", username])
    case .users: return ApiUrl.fullPath(from: ["users"])
    }
  }

  static func fullPath(from components: [CustomStringConvertible]) -> String {
    let endpointPath = components.map({ $0.description }).joined(separator: "/")
    return baseURL.appending(endpointPath)
  }
}

Add label to username associated value

//
//  ApiUrls.swift
//  GithubClient
//
//  Created by Eduardo Arenas on 8/5/17.
//  Copyright © 2017 GameChanger. All rights reserved.
//

import Foundation

enum ApiUrl {
  private static let baseURL = "https://api.github.com/"

  // Users
  case user(username: String)
  case users

  var fullPath: String {
    switch self {
    case .user(let username): return ApiUrl.fullPath(from: ["users", username])
    case .users: return ApiUrl.fullPath(from: ["users"])
    }
  }

  static func fullPath(from components: [CustomStringConvertible]) -> String {
    let endpointPath = components.map({ $0.description }).joined(separator: "/")
    return baseURL.appending(endpointPath)
  }
}


// RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test

// REQUIRES: objc_interop
// REQUIRES: OS=macosx

// rdar://20990451 is tracking the fix for compiling this test optimized.
// XFAIL: swift_test_mode_optimize
// XFAIL: swift_test_mode_optimize_unchecked

import Foundation

protocol Fooable {
  func foo()
}

func fooify<T>(_ x: T) {
  if let foo = x as? Fooable {
    foo.foo()
  } else {
    print("not fooable")
  }
}

extension NSRect: Fooable {
  func foo() { print("NSRect") }
}

extension CFSet: Fooable {
  func foo() { print("CFSet") }
}

extension NSString: Fooable {
  func foo() { print("NSString") }
}

fooify(NSRect()) // CHECK: NSRect
fooify(NSPoint()) // CHECK-NEXT: not fooable
// FIXME: CF types get their ObjC class dynamically looked up during dynamic
// casting.
fooify(CFSetCreate(kCFAllocatorDefault, nil, 0, nil)!) // TODO-NEXT: CFSet CHECK-NEXT: not fooable
fooify(CFArrayCreate(kCFAllocatorDefault, nil, 0, nil)!) // CHECK-NEXT: not fooable
fooify(NSString()) // CHECK-NEXT: NSString
fooify(NSMutableString()) // CHECK-NEXT: NSString
fooify(NSSet()) // CHECK-NEXT: not fooable

Disable test case under Os

// RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test

// REQUIRES: objc_interop
// REQUIRES: OS=macosx

// rdar://20990451 is tracking the fix for compiling this test optimized.
// XFAIL: swift_test_mode_optimize
// XFAIL: swift_test_mode_optimize_size
// XFAIL: swift_test_mode_optimize_unchecked

import Foundation

protocol Fooable {
  func foo()
}

func fooify<T>(_ x: T) {
  if let foo = x as? Fooable {
    foo.foo()
  } else {
    print("not fooable")
  }
}

extension NSRect: Fooable {
  func foo() { print("NSRect") }
}

extension CFSet: Fooable {
  func foo() { print("CFSet") }
}

extension NSString: Fooable {
  func foo() { print("NSString") }
}

fooify(NSRect()) // CHECK: NSRect
fooify(NSPoint()) // CHECK-NEXT: not fooable
// FIXME: CF types get their ObjC class dynamically looked up during dynamic
// casting.
fooify(CFSetCreate(kCFAllocatorDefault, nil, 0, nil)!) // TODO-NEXT: CFSet CHECK-NEXT: not fooable
fooify(CFArrayCreate(kCFAllocatorDefault, nil, 0, nil)!) // CHECK-NEXT: not fooable
fooify(NSString()) // CHECK-NEXT: NSString
fooify(NSMutableString()) // CHECK-NEXT: NSString
fooify(NSSet()) // CHECK-NEXT: not fooable


//
//  SwipeExtensions.swift
//  sample
//
//  Created by satoshi on 10/15/15.
//  Copyright © 2015 Satoshi Nakajima. All rights reserved.
//

import UIKit

extension String {
    var localized:String {
        return NSLocalizedString(self, comment:"")
    }
}

extension URL {
    static func url(_ urlString:String, baseURL:URL?) -> URL? {
        let url = URL(string: urlString, relativeTo: baseURL!)
        if let scheme = url?.scheme, scheme.characters.count > 0 {
            return url
        }

        var components = urlString.components(separatedBy: "/")
        if components.count == 1 {
            return Bundle.main.url(forResource: urlString, withExtension: nil)
        }
        let filename = components.last
        components.removeLast()
        let dir = components.joined(separator: "/")
        return Bundle.main.url(forResource: filename, withExtension: nil, subdirectory: dir)
    }
}

Remove a wrongly added force unwrap during migration to Swift 3.

//
//  SwipeExtensions.swift
//  sample
//
//  Created by satoshi on 10/15/15.
//  Copyright © 2015 Satoshi Nakajima. All rights reserved.
//

import UIKit

extension String {
    var localized:String {
        return NSLocalizedString(self, comment:"")
    }
}

extension URL {
    static func url(_ urlString:String, baseURL:URL?) -> URL? {
        let url = URL(string: urlString, relativeTo: baseURL)
        if let scheme = url?.scheme, scheme.characters.count > 0 {
            return url
        }

        var components = urlString.components(separatedBy: "/")
        if components.count == 1 {
            return Bundle.main.url(forResource: urlString, withExtension: nil)
        }
        let filename = components.last
        components.removeLast()
        let dir = components.joined(separator: "/")
        return Bundle.main.url(forResource: filename, withExtension: nil, subdirectory: dir)
    }
}


//
//  SidebarToolbarModel.swift
//  NetNewsWire
//
//  Created by Stuart Breckenridge on 4/7/20.
//  Copyright © 2020 Ranchero Software. All rights reserved.
//

import Foundation

enum SidebarSheets {
	case none, web, twitter, reddit, folder, settings, fixCredentials
}

class SidebarToolbarModel: ObservableObject {

	@Published var showSheet: Bool = false
	@Published var sheetToShow: SidebarSheets = .none {
		didSet {
			sheetToShow != .none ? (showSheet = true) : (showSheet = false)
		}
	}
	@Published var showActionSheet: Bool = false
	@Published var showAddSheet: Bool = false

}

Remove action sheet var on sidebar toolbar model

//
//  SidebarToolbarModel.swift
//  NetNewsWire
//
//  Created by Stuart Breckenridge on 4/7/20.
//  Copyright © 2020 Ranchero Software. All rights reserved.
//

import Foundation

enum SidebarSheets {
	case none, web, twitter, reddit, folder, settings, fixCredentials
}

class SidebarToolbarModel: ObservableObject {

	@Published var showSheet: Bool = false
	@Published var sheetToShow: SidebarSheets = .none {
		didSet {
			sheetToShow != .none ? (showSheet = true) : (showSheet = false)
		}
	}
	@Published var showAddSheet: Bool = false

}


//
//  PaymentTest.swift
//  MercadoPagoSDK
//
//  Created by Maria cristina rodriguez on 1/3/16.
//  Copyright © 2016 MercadoPago. All rights reserved.
//

import XCTest

class PaymentTest: BaseTest {

    func testFromJSON(){
        let json : NSDictionary = MockManager.getMockFor("Payment")!
        let paymentFromJSON = Payment.fromJSON(json)
        XCTAssertEqual(paymentFromJSON._id, 123123124235)
        XCTAssertEqual(paymentFromJSON.currencyId, "currency_id")
        XCTAssertEqual(paymentFromJSON.card.idCard, 123456)
        XCTAssertEqual(paymentFromJSON.card.lastFourDigits, "4444")
        XCTAssertEqual(paymentFromJSON.card.customerId, "customer_id")
        XCTAssertEqual(paymentFromJSON.card.firstSixDigits, "451234")
        XCTAssertEqual(paymentFromJSON.paymentMethodId, "payment_method_id")
        XCTAssertEqual(paymentFromJSON.paymentTypeId, "payment_type_id")
        XCTAssertEqual(paymentFromJSON.payer.email, "email")
        XCTAssertEqual(paymentFromJSON.status, "status")
        XCTAssertEqual(paymentFromJSON.statusDetail, "status_detail")
    }

}

Correct compilation error in tests

//
//  PaymentTest.swift
//  MercadoPagoSDK
//
//  Created by Maria cristina rodriguez on 1/3/16.
//  Copyright © 2016 MercadoPago. All rights reserved.
//

import XCTest

class PaymentTest: BaseTest {

    func testFromJSON(){
        let json : NSDictionary = MockManager.getMockFor("Payment")!
        let paymentFromJSON = Payment.fromJSON(json)
        XCTAssertEqual(paymentFromJSON._id, "123123124235")
        XCTAssertEqual(paymentFromJSON.currencyId, "currency_id")
        XCTAssertEqual(paymentFromJSON.card.idCard, 123456)
        XCTAssertEqual(paymentFromJSON.card.lastFourDigits, "4444")
        XCTAssertEqual(paymentFromJSON.card.customerId, "customer_id")
        XCTAssertEqual(paymentFromJSON.card.firstSixDigits, "451234")
        XCTAssertEqual(paymentFromJSON.paymentMethodId, "payment_method_id")
        XCTAssertEqual(paymentFromJSON.paymentTypeId, "payment_type_id")
        XCTAssertEqual(paymentFromJSON.payer.email, "email")
        XCTAssertEqual(paymentFromJSON.status, "status")
        XCTAssertEqual(paymentFromJSON.statusDetail, "status_detail")
    }

}


//
//  BrewServices.swift
//  Barmaid
//
//  Created by Zen Kyprianou on 14/07/2014.
//  Copyright (c) 2014 Zen Kyprianou. All rights reserved.
//

import Cocoa

class BrewServices {

    var task: NSTask
    var pipe: NSPipe
    var file: NSFileHandle

    init() {
        self.task = NSTask()
        self.task.launchPath = "/bin/bash"
        self.pipe = NSPipe()
        self.file = NSFileHandle()
    }

    func getServices() {
        var arguments = ["-c", "/usr/bin/find -L /usr/local/opt -type f -name 'homebrew*.plist'"]
        self.task.arguments = arguments

        self.task.standardOutput = self.pipe

        self.file = self.pipe.fileHandleForReading

        self.task.launch()
        self.task.waitUntilExit()

        var data = NSData()
        data = self.file.readDataToEndOfFile()

        var stringResult = NSString(data: data, encoding: NSUTF8StringEncoding)

        println("results are: \(stringResult)")
    }
}

Improve brew services to return a dictionary of all available services

//
//  BrewServices.swift
//  Barmaid
//
//  Created by Zen Kyprianou on 14/07/2014.
//  Copyright (c) 2014 Zen Kyprianou. All rights reserved.
//

import Cocoa

class BrewServices {

    var task: NSTask
    var pipe: NSPipe
    var file: NSFileHandle
    var services: Dictionary<String, String>

    init() {
        self.task = NSTask()
        self.task.launchPath = "/bin/bash"
        self.pipe = NSPipe()
        self.file = NSFileHandle()
        self.services = Dictionary<String, String>()
        self.task.arguments = ["-c", "/usr/bin/find -L /usr/local/opt -type f -name 'homebrew*.plist'"]

        self.findServices()

    }

    func findServices() {
        self.task.standardOutput = self.pipe
        self.file = self.pipe.fileHandleForReading
        self.task.launch()
        self.task.waitUntilExit()

        var data = NSData()
        data = self.file.readDataToEndOfFile()

        var stringResult = NSString(data: data, encoding: NSUTF8StringEncoding) as String
        var allPaths = stringResult.componentsSeparatedByString("\n")

        for service in allPaths {
            if (service != "") {
                var key = service.componentsSeparatedByString("/")[4].capitalizedString
                services[key] = service
            }
        }

    }
}


//
//  AppImages.swift
//  NetNewsWire
//
//  Created by Brent Simmons on 2/17/18.
//  Copyright © 2018 Ranchero Software. All rights reserved.
//

import AppKit

extension NSImage.Name {
	static let star = NSImage.Name("star")
	static let unstar = NSImage.Name("unstar")
	static let timelineStar = NSImage.Name("timelineStar")
}

struct AppImages {

	static var genericFeedImage: NSImage? = {
		let path = "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/BookmarkIcon.icns"
		let image = NSImage(contentsOfFile: path)
		return image
	}()

	static var timelineStar: NSImage! = {
		return NSImage(named: .timelineStar)
	}()
}

Remove reference to unused unstar image.

//
//  AppImages.swift
//  NetNewsWire
//
//  Created by Brent Simmons on 2/17/18.
//  Copyright © 2018 Ranchero Software. All rights reserved.
//

import AppKit

extension NSImage.Name {
	static let star = NSImage.Name("star")
	static let timelineStar = NSImage.Name("timelineStar")
}

struct AppImages {

	static var genericFeedImage: NSImage? = {
		let path = "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/BookmarkIcon.icns"
		let image = NSImage(contentsOfFile: path)
		return image
	}()

	static var timelineStar: NSImage! = {
		return NSImage(named: .timelineStar)
	}()
}


//
//  XCTestCase+SnapshotTests.swift
//  CriticalMapsSnapshotTests
//
//  Created by MAXIM TSVETKOV on 05.10.19.
//  Copyright © 2019 Pokus Labs. All rights reserved.
//

@testable import CriticalMaps
import SnapshotTesting
import XCTest

extension XCTestCase {
    func assertViewSnapshot(for themes: [Theme] = [.light, .dark],
                            matching value: UIView,
                            with size: CGSize? = nil,
                            file: StaticString = #file,
                            testName: String = #function,
                            line: UInt = #line) {
        themes.forEach { theme in
            MockThemeController.shared.changeTheme(to: theme)
            MockThemeController.shared.applyTheme()
            assertSnapshot(matching: value,
                           as: .image(size: size),
                           named: theme.displayName,
                           file: file,
                           testName: testName,
                           line: line)
        }
    }
}

private extension Theme {
    var displayName: String {
        switch self {
        case .light:
            return "Light"
        case .dark:
            return "Dark"
        }
    }
}

Test if Snapshots succeed on CI with 99% Precision

//
//  XCTestCase+SnapshotTests.swift
//  CriticalMapsSnapshotTests
//
//  Created by MAXIM TSVETKOV on 05.10.19.
//  Copyright © 2019 Pokus Labs. All rights reserved.
//

@testable import CriticalMaps
import SnapshotTesting
import XCTest

extension XCTestCase {
    func assertViewSnapshot(for themes: [Theme] = [.light, .dark],
                            matching value: UIView,
                            with size: CGSize? = nil,
                            file: StaticString = #file,
                            testName: String = #function,
                            line: UInt = #line) {
        themes.forEach { theme in
            MockThemeController.shared.changeTheme(to: theme)
            MockThemeController.shared.applyTheme()
            assertSnapshot(matching: value,
                           as: .image(precision: 0.99, size: size),
                           named: theme.displayName,
                           file: file,
                           testName: testName,
                           line: line)
        }
    }
}

private extension Theme {
    var displayName: String {
        switch self {
        case .light:
            return "Light"
        case .dark:
            return "Dark"
        }
    }
}


import Foundation

public protocol MODownloadManagerDelegate {

    func downloadRequestDidUpdateProgress(downloadModel: MODownloadModel, index: Int)

    func downloadRequestStarted(downloadOperation: DownloadOperation, index: Int)

    func downloadRequestPaused(downloadModel: MODownloadModel, index: Int)

    func downloadRequestedResumed(downloadModel: MODownloadModel, index: Int)

    func downloadRequesteDeleted(downloadModel: MODownloadModel, index: Int)

    func downloadRequestCancelled(downloadModel: MODownloadModel, index: Int)

    func downloadRequestFinished(downloadModel: MODownloadModel, errorOptional: NSError?)

    func downloadRequestFailed(downloadModel: MODownloadModel, errorOptional: NSError?)

}

public protocol DownloadManager {

    var delegate: MODownloadManagerDelegate? { get set }

    func startDownload(asset: Asset)

    func pauseDownload(asset: Asset)

    func cancelDownload(asset: Asset)

    func deleteDownload(asset: Asset)

    func resumeDownload(asset: Asset)

}

public protocol Asset {

    var id: String { get }

    var fileName: String { get }

    var fileURL: String { get }

}

Update to protocol so all downloadManagers will need to implement a download queue

import Foundation

public protocol MODownloadManagerDelegate {

    func downloadRequestDidUpdateProgress(downloadModel: MODownloadModel, index: Int)

    func downloadRequestStarted(downloadOperation: DownloadOperation, index: Int)

    func downloadRequestPaused(downloadModel: MODownloadModel, index: Int)

    func downloadRequestedResumed(downloadModel: MODownloadModel, index: Int)

    func downloadRequesteDeleted(downloadModel: MODownloadModel, index: Int)

    func downloadRequestCancelled(downloadModel: MODownloadModel, index: Int)

    func downloadRequestFinished(downloadModel: MODownloadModel, errorOptional: NSError?)

    func downloadRequestFailed(downloadModel: MODownloadModel, errorOptional: NSError?)

}

public protocol DownloadManager {

    var delegate: MODownloadManagerDelegate? { get set }

    var downloadQueue: [DownloadOperation] { get }

    func startDownload(asset: Asset)

    func pauseDownload(asset: Asset)

    func cancelDownload(asset: Asset)

    func deleteDownload(asset: Asset)

    func resumeDownload(asset: Asset)

}

public protocol Asset {

    var id: String { get }

    var fileName: String { get }

    var fileURL: String { get }

}


//
//  ExampleAppUITests.swift
//  ExampleAppUITests
//
//  Created by Andrey Fidrya on 04/07/15.
//  Copyright © 2015 Zabiyaka. All rights reserved.
//

import Foundation
import XCTest

class ExampleAppUITests: XCTestCase {

    override func setUp() {
        super.setUp()

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

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

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

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

}

Implement wait() function in example project

//
//  ExampleAppUITests.swift
//  ExampleAppUITests
//
//  Created by Andrey Fidrya on 04/07/15.
//  Copyright © 2015 Zabiyaka. All rights reserved.
//

import Foundation
import XCTest

class ExampleAppUITests: XCTestCase {

    override func setUp() {
        super.setUp()

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

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

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

    func testExample() {
        // Use recording to get started writing UI tests.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
        let app = XCUIApplication()
        let tabBar = app.tabBars
        tabBar.buttons["Second"].tap()
        wait(5)
        tabBar.buttons["First"].tap()
        wait(5)

    }

    // - MARK: wait()

    var waitExpectation: XCTestExpectation?

    func wait(duration: NSTimeInterval) {
        waitExpectation = expectationWithDescription("wait")
        NSTimer.scheduledTimerWithTimeInterval(duration, target: self,
            selector: Selector("onTimer"), userInfo: nil, repeats: false)
        waitForExpectationsWithTimeout(duration + 3, handler: nil)
    }

    func onTimer() {
        waitExpectation?.fulfill()
    }
}