//
//  View.swift
//  Cartography
//
//  Created by Robert Böhnke on 26/06/14.
//  Copyright (c) 2014 Robert Böhnke. All rights reserved.
//

import Foundation

#if os(iOS)
    import UIKit
    public typealias View = UIView

    extension View {
        func car_updateLayout() {
            layoutIfNeeded()
        }

        func car_setTranslatesAutoresizingMaskIntoConstraints(flag: Bool) {
            setTranslatesAutoresizingMaskIntoConstraints(flag)
        }
    }
#else
    import AppKit
    public typealias View = NSView

    extension View {
        func car_updateLayout() {
            superview?.layoutSubtreeIfNeeded()
        }

        func car_setTranslatesAutoresizingMaskIntoConstraints(flag: Bool) {
            translatesAutoresizingMaskIntoConstraints = flag
        }
    }
#endif

private var key: UInt8 = 0

extension View {
    var car_installedLayoutConstraints: [Constraint]? {
        get {
            return objc_getAssociatedObject(self, &key) as? [Constraint]
        }
        set {
            objc_setAssociatedObject(self, &key, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_COPY_NONATOMIC))
        }
    }
}

Use StaticString as associated object key type

//
//  View.swift
//  Cartography
//
//  Created by Robert Böhnke on 26/06/14.
//  Copyright (c) 2014 Robert Böhnke. All rights reserved.
//

import Foundation

#if os(iOS)
    import UIKit
    public typealias View = UIView

    extension View {
        func car_updateLayout() {
            layoutIfNeeded()
        }

        func car_setTranslatesAutoresizingMaskIntoConstraints(flag: Bool) {
            setTranslatesAutoresizingMaskIntoConstraints(flag)
        }
    }
#else
    import AppKit
    public typealias View = NSView

    extension View {
        func car_updateLayout() {
            superview?.layoutSubtreeIfNeeded()
        }

        func car_setTranslatesAutoresizingMaskIntoConstraints(flag: Bool) {
            translatesAutoresizingMaskIntoConstraints = flag
        }
    }
#endif

private var InstalledLayoutConstraintsKey: StaticString = "InstalledLayoutConstraintsKey"

extension View {
    var car_installedLayoutConstraints: [Constraint]? {
        get {
            return objc_getAssociatedObject(self, &InstalledLayoutConstraintsKey) as? [Constraint]
        }
        set {
            objc_setAssociatedObject(self, &InstalledLayoutConstraintsKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_COPY_NONATOMIC))
        }
    }
}


import Foundation

public extension Int {
    public var minsInSecs: Int {
        return self * 60
    }

    public var hoursInSecs: Int {
        return self.minsInSecs * 60
    }

    public var daysInSecs: Int {
        return self.hoursInSecs * 24
    }

    public var weeksInSecs: Int {
        return self.daysInSecs * 7
    }
}

public extension TimeInterval {
    public var minsInSecs: TimeInterval {
        return self * 60
    }

    public var hoursInSecs: TimeInterval {
        return self.minsInSecs * 60
    }

    public var daysInSecs: TimeInterval {
        return self.hoursInSecs * 24
    }

    public var weeksInSecs: TimeInterval {
        return self.daysInSecs * 7
    }
}

Use Numeric over Int and TimeInterval

public extension Numeric {
    public var minsInSecs: Self {
        return self * 60
    }

    public var hoursInSecs: Self {
        return self.minsInSecs * 60
    }

    public var daysInSecs: Self {
        return self.hoursInSecs * 24
    }

    public var weeksInSecs: Self {
        return self.daysInSecs * 7
    }
}


import Foundation
import Wall
import Faker

class DetailViewController: WallController {

  let faker = Faker()

  override func viewDidLoad() {
    super.viewDidLoad()

    title = post!.text

    if let comments = post?.comments {
      let delayTime = dispatch_time(DISPATCH_TIME_NOW,
        Int64(0.1 * Double(NSEC_PER_SEC)))
      dispatch_after(delayTime, dispatch_get_main_queue()) {
        var posts = [Post]()
        posts.append(self.post!)
        comments.map { posts.append($0) }
        self.posts = posts
      }
    }
  }

}

Set collection view background color for detail view

import Foundation
import Wall
import Faker

class DetailViewController: WallController {

  let faker = Faker()

  override func viewDidLoad() {
    super.viewDidLoad()

    title = post!.text
    collectionView.backgroundColor = Config.Wall.Comment.backgroundColor

    if let comments = post?.comments {
      let delayTime = dispatch_time(DISPATCH_TIME_NOW,
        Int64(0.1 * Double(NSEC_PER_SEC)))
      dispatch_after(delayTime, dispatch_get_main_queue()) {
        var posts = [Post]()
        posts.append(self.post!)
        comments.map { posts.append($0) }
        self.posts = posts
      }
    }
  }

}


//
//  NSBundle.swift
//  Core
//
//  Created by Guido Marucci Blas on 5/7/16.
//  Copyright © 2016 Wolox. All rights reserved.
//

import Foundation

public extension NSBundle {

    /**
     Loads a nib from the bundle.

     - parameter nibName: Contains a StringRepresentable nib.
     - returns: The loaded NibType or .None if it don't exists.
     - seealso: loadNib(nibName: String)
     */
    public func loadNib<NibType, T: RawRepresentable where T.RawValue == String>(nibName: T) -> NibType? {
        return loadNib(nibName.rawValue)
    }

    /**
     Returns the value associated with the specified key in the receiver's information property list.

     The value associated with key in the receiver's property list (Info.plist).
     The localized value of a key is returned when one is available.

     - parameter key: A key in the receiver's property list.
     - returns: The value associated with key in the receiver's property list (Info.plist) or .None if it don't exists.
     - seealso: objectForInfoDictionaryKey()
    */
    public subscript(key: String) -> String? {
        guard let value = objectForInfoDictionaryKey(key) as? String where !value.isEmpty else {
            return .None
        }
        return value
    }

}

extension String: RawRepresentable {
    public init?(rawValue: String) {
        self = rawValue
    }

    public var rawValue: String {
        return self
    }
}

Fix loadNib() which crashed (infinite loop)

//
//  NSBundle.swift
//  Core
//
//  Created by Guido Marucci Blas on 5/7/16.
//  Copyright © 2016 Wolox. All rights reserved.
//

import Foundation

public extension NSBundle {

    /**
     Loads a nib from the bundle.

     - parameter nibName: Contains a StringRepresentable nib.
     - returns: The loaded NibType or .None if it don't exists.
     - seealso: loadNib(nibName: String)
     */
    public func loadNib<NibType, T: RawRepresentable where T.RawValue == String>(nibName: T) -> NibType? {
        return loadNibNamed(nibName.rawValue, owner: self, options: nil)[0] as? NibType
    }

    /**
     Returns the value associated with the specified key in the receiver's information property list.

     The value associated with key in the receiver's property list (Info.plist).
     The localized value of a key is returned when one is available.

     - parameter key: A key in the receiver's property list.
     - returns: The value associated with key in the receiver's property list (Info.plist) or .None if it don't exists.
     - seealso: objectForInfoDictionaryKey()
    */
    public subscript(key: String) -> String? {
        guard let value = objectForInfoDictionaryKey(key) as? String where !value.isEmpty else {
            return .None
        }
        return value
    }

}

extension String: RawRepresentable {
    public init?(rawValue: String) {
        self = rawValue
    }

    public var rawValue: String {
        return self
    }
}


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

import ReactiveCocoa

class HabitsViewModel {

    //MARK: Properties

    private let store: Store

    var habits: Habits {
        return store.habits
    }

    //MARK: Initialization

    init(store: Store) {
        self.store = store
    }

    //MARK: Manage Habits

    private func addHabit(name: String) -> SignalProducer<NSIndexPath, NoError> {
        return SignalProducer(value: store.addHabit(name))
    }

    private func deleteHabit(primaryKey: PrimaryKey) -> SignalProducer<NSIndexPath, StoreError> {
        return SignalProducer(result: store.deleteHabit(primaryKey))
    }
}

Add action properties and their mutable properties

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

import ReactiveCocoa

class HabitsViewModel {

    //MARK: Properties

    private let store: Store

    var habits: Habits {
        return store.habits
    }

    let addHabitEnabled = MutableProperty(true)
    let deleteHabitEnabled = MutableProperty(true)

    private(set) var addHabit: Action<String, NSIndexPath, NoError>!
    private(set) var deleteHabit: Action<PrimaryKey, NSIndexPath, StoreError>!

    //MARK: Initialization

    init(store: Store) {
        self.store = store
    }

    //MARK: Manage Habits

    private func addHabit(name: String) -> SignalProducer<NSIndexPath, NoError> {
        return SignalProducer(value: store.addHabit(name))
    }

    private func deleteHabit(primaryKey: PrimaryKey) -> SignalProducer<NSIndexPath, StoreError> {
        return SignalProducer(result: store.deleteHabit(primaryKey))
    }
}


//
//  TraktUser.swift
//  TraktKit
//
//  Created by Maximilian Litteral on 4/13/16.
//  Copyright © 2016 Maximilian Litteral. All rights reserved.
//

import Foundation

public struct User: Codable {

    // Min
    public let username: String?
    public let isPrivate: Bool
    public let name: String?
    public let isVIP: Bool?
    public let isVIPEP: Bool?

    // Full
    public let joinedAt: Date?
    public let location: String?
    public let about: String?
    public let gender: String?
    public let age: Int?

    // VIP
    public let vipOG: Bool?
    public let vipYears: Int?

    enum CodingKeys: String, CodingKey {
        case username
        case isPrivate = "private"
        case name
        case isVIP = "vip"
        case isVIPEP = "vip_ep"
        case joinedAt = "joined_at"
        case location
        case about
        case gender
        case age
        case vipOG = "vip_og"
        case vipYears = "vip_years"
    }
}

Add slug and avatar to user

//
//  TraktUser.swift
//  TraktKit
//
//  Created by Maximilian Litteral on 4/13/16.
//  Copyright © 2016 Maximilian Litteral. All rights reserved.
//

import Foundation

public struct User: Codable {

    // Min
    public let username: String?
    public let isPrivate: Bool
    public let name: String?
    public let isVIP: Bool?
    public let isVIPEP: Bool?
    public let ids: IDs

    // Full
    public let joinedAt: Date?
    public let location: String?
    public let about: String?
    public let gender: String?
    public let age: Int?
    public let images: Images?

    // VIP
    public let vipOG: Bool?
    public let vipYears: Int?

    enum CodingKeys: String, CodingKey {
        case username
        case isPrivate = "private"
        case name
        case isVIP = "vip"
        case isVIPEP = "vip_ep"
        case ids
        case joinedAt = "joined_at"
        case location
        case about
        case gender
        case age
        case images
        case vipOG = "vip_og"
        case vipYears = "vip_years"
    }

    public struct IDs: Codable {
        public let slug: String
    }

    public struct Images: Codable {
        public let avatar: Image
    }

    public struct Image: Codable {
        public let full: String
    }
}


// RUN: echo '#include "header.h"' > %t.m
// RUN: %target-swift-ide-test -source-filename %s -print-header -header-to-print %S/Inputs/header.h --cc-args -target %target-triple -fsyntax-only %t.m -I %S/Inputs > %t.txt
// RUN: FileCheck -input-file=%t.txt %s

// CHECK: func doSomethingInHead(arg: Int32)
// CHECK: class BaseInHead {
// CHECK:   class func doIt(arg: Int32)
// CHECK:   func doIt(arg: Int32)
// CHECK: }

// CHECK: /// Awesome name.
// CHECK: class SameName {
// CHECK: }
// CHECK: protocol SameNameProtocol {
// CHECK: }

Revert "[test] Use '-target' for cc args as well."

// RUN: echo '#include "header.h"' > %t.m
// RUN: %target-swift-ide-test -source-filename %s -print-header -header-to-print %S/Inputs/header.h --cc-args -Xclang -triple -Xclang %target-triple -fsyntax-only %t.m -I %S/Inputs > %t.txt
// RUN: FileCheck -input-file=%t.txt %s

// CHECK: func doSomethingInHead(arg: Int32)
// CHECK: class BaseInHead {
// CHECK:   class func doIt(arg: Int32)
// CHECK:   func doIt(arg: Int32)
// CHECK: }

// CHECK: /// Awesome name.
// CHECK: class SameName {
// CHECK: }
// CHECK: protocol SameNameProtocol {
// CHECK: }


// THIS- TEST-SHOULD-NOT-RUN // Flex Jenkins error handling
// check that asserts fail as expected

import assert;

main {
    assert(false, "false"); // should fail
}

Undo failure injection - Jenkins is stable

// THIS-TEST-SHOULD-NOT-RUN
// check that asserts fail as expected

import assert;

main {
    assert(false, "false"); // should fail
}


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

extension Module {
	public static var sigma: Module {
		let Sigma = Declaration("Sigma", Datatype(.Type, { A in
			Datatype.Argument(A --> .Type) { B in
				[ "sigma": Telescope.Argument(A) { a in .Argument(B[a], const(.End)) } ]
			}
		}))

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

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

		return Module("Sigma", [ Sigma, first, second ])
	}
}

import Prelude

Use `nil` instead of `()`.

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

extension Module {
	public static var sigma: Module {
		let Sigma = Declaration("Sigma", Datatype(.Type, { A in
			Datatype.Argument(A --> .Type) { B in
				[ "sigma": Telescope.Argument(A) { a in .Argument(B[a], const(.End)) } ]
			}
		}))

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

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

		return Module("Sigma", [ Sigma, first, second ])
	}
}

import Prelude


/*
 To achieve a borderless, transparent, colored, rounded window **with** shadow:

 - Alpha is set on the window
 - Window's background color is clear
 - Window is opaque and borderless
 - The actual color and corner radius are drawn in the content view

 The window will then automatically apply a shadow

 See also Apple's `RoundTransparentWindow` example where they do just that:
   https://developer.apple.com/library/content/samplecode/RoundTransparentWindow

 Alternatives (e.g. using the content view's layer properties or colors with alpha
 baked in) don't seem to work as reliably or are more complex (drawing the shadow
 manually).
 */

import Cocoa

/// Intented to be used with `RulerView` as content view.
final class RulerWindow: NSWindow {

    var rulerView: RulerView {
        return contentView as! RulerView
    }

    override var canBecomeKey: Bool {
        return false
    }

    override var canBecomeMain: Bool {
        return false
    }

    override init(contentRect: NSRect,
                  styleMask style: NSWindowStyleMask,
                  backing bufferingType: NSBackingStoreType,
                  defer flag: Bool) {

        super.init(contentRect: contentRect,
                   styleMask: .borderless,  // borderless
                   backing: bufferingType,
                   defer: flag)

        backgroundColor = .clear
        isOpaque = false
    }
}

Make ruler a non-activating panel.

/*
 To achieve a borderless, transparent, colored, rounded window **with** shadow:

 - Alpha is set on the window
 - Window's background color is clear
 - Window is opaque and borderless
 - The actual color and corner radius are drawn in the content view

 The window will then automatically apply a shadow

 See also Apple's `RoundTransparentWindow` example where they do just that:
   https://developer.apple.com/library/content/samplecode/RoundTransparentWindow

 Alternatives (e.g. using the content view's layer properties or colors with alpha
 baked in) don't seem to work as reliably or are more complex (drawing the shadow
 manually).
 */

import Cocoa

/// Intented to be used with `RulerView` as content view.
final class RulerWindow: NSPanel {

    var rulerView: RulerView {
        return contentView as! RulerView
    }

    override var canBecomeKey: Bool {
        return false
    }

    override var canBecomeMain: Bool {
        return false
    }

    override init(contentRect: NSRect,
                  styleMask style: NSWindowStyleMask,
                  backing bufferingType: NSBackingStoreType,
                  defer flag: Bool) {

        super.init(contentRect: contentRect,
                   styleMask: [.borderless, .nonactivatingPanel],
                   backing: bufferingType,
                   defer: flag)

        backgroundColor = .clear
        isOpaque = false
    }
}


import UIKit
import MapKit

class ViewController: UIViewController, MKMapViewDelegate {

    @IBOutlet var theMap: MKMapView

    override func viewDidLoad() {
        super.viewDidLoad()

        // Add the longitude and latitude
        var longitude:CLLocationDegrees = 98.3
        var latitude:CLLocationDegrees = 21.44

        // Latitude delta: The map will look more zoom-in
        var latDelta:CLLocationDegrees = 0.01
        // Longitude delta
        var longDelta:CLLocationDegrees = 0.01

        // It defines the latitude and longitude directions to show on a map.
        var spanCoordinate: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)

        // Set the location
        var myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)

        // Create a region: it defines which portion of the map to display
        var theRegion:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, spanCoordinate)

        // Set the region in the mapview
        self.theMap.setRegion(theRegion, animated: true)

        // Add an annotation on the center of the map (PIN)
        var myLocationAnnotation = MKPointAnnotation()
        // Coordinate of the pin
        myLocationAnnotation.coordinate = myLocation
        // Title of the pin
        myLocationAnnotation.title = "The PIN title"
        // Subtitle of the pin
        myLocationAnnotation.subtitle = "The PIN subtitle"

    }

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

}

Add the annotation(PIN) to the mapview

import UIKit
import MapKit

class ViewController: UIViewController, MKMapViewDelegate {

    @IBOutlet var theMap: MKMapView

    override func viewDidLoad() {
        super.viewDidLoad()

        // Add the longitude and latitude
        var longitude:CLLocationDegrees = 98.3
        var latitude:CLLocationDegrees = 21.44

        // Latitude delta: The map will look more zoom-in
        var latDelta:CLLocationDegrees = 0.01
        // Longitude delta
        var longDelta:CLLocationDegrees = 0.01

        // It defines the latitude and longitude directions to show on a map.
        var spanCoordinate: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)

        // Set the location
        var myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)

        // Create a region: it defines which portion of the map to display
        var theRegion:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, spanCoordinate)

        // Set the region in the mapview
        self.theMap.setRegion(theRegion, animated: true)

        // Add an annotation on the center of the map (PIN)
        var myLocationAnnotation = MKPointAnnotation()
        // Coordinate of the pin
        myLocationAnnotation.coordinate = myLocation
        // Title of the pin
        myLocationAnnotation.title = "The PIN title"
        // Subtitle of the pin
        myLocationAnnotation.subtitle = "The PIN subtitle"

        // Add the annotation to the mapview
        self.theMap.addAnnotation(myLocationAnnotation)

    }

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

}


//
//  Extensions.swift
//  JenkinsiOS
//
//  Created by Robert on 25.09.16.
//  Copyright © 2016 MobiLab Solutions. All rights reserved.
//

import Foundation
import UIKit

extension URL{
    /// Get the current url, replacing its scheme with a given scheme and its port with a given port
    ///
    /// - parameter scheme: The url scheme that should be used (i.e. https)
    /// - parameter port:   The port that should be used (i.e. 443)
    ///
    /// - returns: The given url, with port and scheme replaced
    func using(scheme: String, at port: Int? = nil) -> URL?{
        var components = URLComponents(url: self, resolvingAgainstBaseURL: true)
        components?.port = port
        components?.scheme = "https"
        return components?.url
    }
}

extension UIColor{
    /// Get the corresponding UIColor from a given JenkinsColor
    ///
    /// - parameter jenkinsColor: The Jenkins Color whose UIColor should be determined
    ///
    /// - returns: The UIColor that corresponds to the given JenkinsColor
    static func from(jenkinsColor color: JenkinsColor) -> UIColor{
        return Constants.Colors.jenkinsColors[color] ?? UIColor.clear
    }
}

Add an extension to textify optionals

//
//  Extensions.swift
//  JenkinsiOS
//
//  Created by Robert on 25.09.16.
//  Copyright © 2016 MobiLab Solutions. All rights reserved.
//

import Foundation
import UIKit

extension URL{
    /// Get the current url, replacing its scheme with a given scheme and its port with a given port
    ///
    /// - parameter scheme: The url scheme that should be used (i.e. https)
    /// - parameter port:   The port that should be used (i.e. 443)
    ///
    /// - returns: The given url, with port and scheme replaced
    func using(scheme: String, at port: Int? = nil) -> URL?{
        var components = URLComponents(url: self, resolvingAgainstBaseURL: true)
        components?.port = port
        components?.scheme = "https"
        return components?.url
    }
}

extension UIColor{
    /// Get the corresponding UIColor from a given JenkinsColor
    ///
    /// - parameter jenkinsColor: The Jenkins Color whose UIColor should be determined
    ///
    /// - returns: The UIColor that corresponds to the given JenkinsColor
    static func from(jenkinsColor color: JenkinsColor) -> UIColor{
        return Constants.Colors.jenkinsColors[color] ?? UIColor.clear
    }
}

extension Optional{
    /// Return a nicer version of an optional value string
    ///
    /// - returns: A string describing the optional: either "nil" or its actual value
    func textify() -> String{
        switch self{
            case .none:
                return "nil"
            default:
                return "\(self!)"
        }
    }
}


import Foundation

class FDatabaseCountriesItem:FDatabaseProtocol
{
    var identifier:String?
    var parent:FDatabaseProtocol?
    let users:[String]

    init(
        countries:FDatabaseCountries,
        identifier:String)
    {
        self.identifier = identifier
        parent = countries
        users = []
    }

    required init?(json:Any)
    {
        guard

            let users:[String] = json as? [String]

        else
        {
            return nil
        }

        self.users = users
    }
}

Use users in country as model, nor string

import Foundation

class FDatabaseCountriesItem:FDatabaseProtocol
{
    var identifier:String?
    var parent:FDatabaseProtocol?
    let users:[FDatabaseCountriesItemUser]

    init(
        countries:FDatabaseCountries,
        identifier:String)
    {
        self.identifier = identifier
        parent = countries
        users = []
    }

    required init?(json:Any)
    {
        guard

        let rawUsers:[String:Any] = json as? [String:AnyObject]

        else
        {
            return nil
        }

        var users:[FDatabaseCountriesItemUser] = []
        let usersIds:[String] = Array(rawUsers.keys)

        for userId:String in usersIds
        {
            guard

                let rawUser:Any = rawUsers[userId],
                let user:FDatabaseCountriesItemUser = FDatabaseCountriesItemUser(
                    json:rawUser)

            else
            {
                continue
            }

            users.append(user)
        }

        self.users = users
    }
}


import UIKit
import AsyncDisplayKit

public class WallDataSource: NSObject, ASCollectionViewDataSource {

  var delegate: AnyObject?

  struct Constants {
    static let cellIdentifier = "PostCell"
  }

  lazy public var data = { return [Post]() }()

  func textTapped(sender: AnyObject) {
    if let delegate = delegate as? WallTapDelegate,
      delegateMethod = delegate.wallPostTextWasTapped {
        delegateMethod(sender)
    }
  }
}

extension WallDataSource: ASCollectionViewDataSource {

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

  public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1
  }

  public func collectionView(collectionView: ASCollectionView!, nodeForItemAtIndexPath indexPath: NSIndexPath!) -> ASCellNode! {
    let cellNode = PostCellNode(post: data[indexPath.row],
        width: collectionView.frame.width, self)

    return cellNode
  }
}

Use delegate instead of self

import UIKit
import AsyncDisplayKit

public class WallDataSource: NSObject, ASCollectionViewDataSource {

  var delegate: AnyObject?

  struct Constants {
    static let cellIdentifier = "PostCell"
  }

  lazy public var data = { return [Post]() }()

  func textTapped(sender: AnyObject) {
    if let delegate = delegate as? WallTapDelegate,
      delegateMethod = delegate.wallPostTextWasTapped {
        delegateMethod(sender)
    }
  }
}

extension WallDataSource: ASCollectionViewDataSource {

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

  public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1
  }

  public func collectionView(collectionView: ASCollectionView!, nodeForItemAtIndexPath indexPath: NSIndexPath!) -> ASCellNode! {
    let cellNode = PostCellNode(post: data[indexPath.row],
        width: collectionView.frame.width, delegate)

    return cellNode
  }
}


import ObjectiveC.runtime

public protocol Dynamic {
  var OBJC_CLASS: NSObjectProtocol { get }
  var obj: NSObject { get }

  var `class`: AnyClass { get }
}

public extension Dynamic {
  public var `class`: AnyClass {
    return (OBJC_CLASS as? AnyClass) ?? undefined()
  }
}

public protocol Named: Dynamic {
  var name: String { get }
}

public extension Named {
  public var name: String {
    return (obj.valueForKey("name") as? String) ?? undefined()
  }
}

Make calling ObjC things a little easier

import ObjectiveC.runtime

func call(object: NSObjectProtocol, _ methodName: String, _ argument: NSObject? = nil) -> NSObject {
  let result: Unmanaged<AnyObject>!

  if let argument = argument {
    result = object.performSelector(Selector(methodName), withObject: argument)
  } else {
    result = object.performSelector(Selector(methodName))
  }

  return (result.takeRetainedValue() as? NSObject) ?? undefined()
}

func getObjCClass(name: String) -> NSObjectProtocol {
  return (objc_getClass(name) as? NSObjectProtocol) ?? undefined("No such class: \(name)")
}

public protocol Dynamic {
  var OBJC_CLASS: NSObjectProtocol { get }
  var obj: NSObject { get }

  var `class`: AnyClass { get }
}

public extension Dynamic {
  public var `class`: AnyClass {
    return (OBJC_CLASS as? AnyClass) ?? undefined()
  }
}

public protocol Named: Dynamic {
  var name: String { get }
}

public extension Named {
  public var name: String {
    return (obj.valueForKey("name") as? String) ?? undefined()
  }
}


Add silgen test to check triviality of foreign reference types.

// RUN: %target-swift-emit-silgen %s -I %S/Inputs -enable-experimental-cxx-interop | %FileCheck %s
//
// XFAIL: OS=linux-android, OS=linux-androideabi

import POD
import ReferenceCounted

// CHECK-LABEL: sil [ossa] @$s4main11testTrivialyyF : $@convention(thin) () -> ()
// CHECK-NOT: retain
// CHECK-NOT: release
// CHECK-NOT: copy_value
// CHECK-NOT: destroy_value
// CHECK-NOT: begin_borrow
// CHECK-NOT: end_borrow
// CHECK: return
// CHECK-LABEL: end sil function '$s4main11testTrivialyyF'
public func testTrivial() {
    let x = Empty.create()
    let t = (x, x, x)
}

// CHECK-LABEL: sil [ossa] @$s4main14testNonTrivialyyF : $@convention(thin) () -> ()
// CHECK:  copy_value %{{[0-9]+}} : $LocalCount
// CHECK:  copy_value %{{[0-9]+}} : $LocalCount
// CHECK:  copy_value %{{[0-9]+}} : $LocalCount
// CHECK: return
// CHECK-LABEL: end sil function '$s4main14testNonTrivialyyF'
public func testNonTrivial() {
    let x = LocalCount.create()
    let t = (x, x, x)
}


//
//  Manager.swift
//  WindowKit
//
//  Created by 林達也 on 2015/12/12.
//  Copyright © 2015年 jp.sora0077. All rights reserved.
//

import Foundation
import UIKit.UIWindow
import UIKit.UIScreen
import UIKit.UIView

public protocol WindowLevel: Hashable {

    var rawValue: UInt { get }
}

public final class Manager<Level: WindowLevel> {

    private weak var _keyWindow: UIWindow?
    private var _windows: [Level: UIWindow] = [:]

    public init(keyWindow: UIWindow) {
        _keyWindow = keyWindow
    }

    public subscript (level: Level) -> UIWindow {

        if let window = _windows[level] {
            return window
        }

        let window = Window(frame: UIScreen.mainScreen().bounds)
        window.windowLevel = UIWindowLevelNormal + UIWindowLevel(level.rawValue)
        window.hidden = false
        _windows[level] = window

        return window
    }

}

Modify WindowLevel protocol rawValue type to Int

//
//  Manager.swift
//  WindowKit
//
//  Created by 林達也 on 2015/12/12.
//  Copyright © 2015年 jp.sora0077. All rights reserved.
//

import Foundation
import UIKit.UIWindow
import UIKit.UIScreen
import UIKit.UIView

public protocol WindowLevel: Hashable {

    var rawValue: Int { get }
}

public final class Manager<Level: WindowLevel> {

    private weak var _keyWindow: UIWindow?
    private var _windows: [Level: UIWindow] = [:]

    public init(keyWindow: UIWindow) {
        _keyWindow = keyWindow
    }

    public subscript (level: Level) -> UIWindow {

        assert(level.rawValue > 0)

        if let window = _windows[level] {
            return window
        }

        let window = Window(frame: UIScreen.mainScreen().bounds)
        window.windowLevel = UIWindowLevelNormal + UIWindowLevel(level.rawValue)
        window.hidden = false
        _windows[level] = window

        return window
    }

}


//
//  FuelGaugeView.swift
//  FuelGaugeKit
//
//  Created by Ron Lisle on 3/19/15.
//  Copyright (c) 2015 Ron Lisle. All rights reserved.
//

import UIKit

class FuelGaugeView: UIView {

    var backgroundImage:UIImageView!
    var needleImage:UIImageView!

    override func layoutSubviews() {
        super.layoutSubviews()

        if backgroundImage == nil {
            backgroundImage = createSubviewWithImageNamed("FuelGaugeBG")
        }
        if needleImage == nil {
            needleImage = createSubviewWithImageNamed("FuelGaugeNeedle")
        }
    }

    func createSubviewWithImageNamed(name: String) -> UIImageView {
        let newImageView = createImageViewWithImageNamed(name)
        addSubview(newImageView)
        return newImageView
    }

    func createImageViewWithImageNamed(name: String) -> UIImageView {
        let newImageView = UIImageView()
        newImageView.frame = self.bounds
        newImageView.image = UIImage(named: name, inBundle: NSBundle(forClass: FuelGaugeView.self), compatibleWithTraitCollection: nil)
        return newImageView
    }
}

Refactor to loadImageNamed. 8 tests still passing.

//
//  FuelGaugeView.swift
//  FuelGaugeKit
//
//  Created by Ron Lisle on 3/19/15.
//  Copyright (c) 2015 Ron Lisle. All rights reserved.
//

import UIKit

class FuelGaugeView: UIView {

    var backgroundImage:UIImageView!
    var needleImage:UIImageView!

    override func layoutSubviews() {
        super.layoutSubviews()

        if backgroundImage == nil {
            backgroundImage = createSubviewWithImageNamed("FuelGaugeBG")
        }
        if needleImage == nil {
            needleImage = createSubviewWithImageNamed("FuelGaugeNeedle")
        }
    }

    func createSubviewWithImageNamed(name: String) -> UIImageView {
        let newImageView = createImageViewWithImageNamed(name)
        addSubview(newImageView)
        return newImageView
    }

    func createImageViewWithImageNamed(name: String) -> UIImageView {
        let newImageView = UIImageView()
        newImageView.frame = self.bounds
        newImageView.image = loadImageNamed(name)
        return newImageView
    }

    func loadImageNamed(name: String) -> UIImage? {
        let newImage = UIImage(named: name, inBundle: NSBundle(forClass: FuelGaugeView.self), compatibleWithTraitCollection: nil)
        return newImage
    }
}


import Argo
import Foundation
import Result

extension Result {
  @available(*, unavailable, renamed: "Result.init(_:)")
  public static func fromDecoded(_: Decoded<T>) -> Result<T, SwishError> {
    fatalError("unavailable")
  }
}

Add fix-its for renamed methods

import Argo
import Foundation
import Result

extension Client {
  @available(*, unavailable, renamed: "perform(_:completionHandler:)")
  func performRequest<T: Request>(_: T, completionHandler _: @escaping (Result<T.ResponseObject, SwishError>) -> ()) -> URLSessionDataTask {
    fatalError("unavailable")
  }
}

extension RequestPerformer {
  @available(*, unavailable, renamed: "perform(_:completionHandler:)")
  public func performRequest(_: URLRequest, completionHandler _: @escaping (Result<HTTPResponse, SwishError>) -> Void) -> URLSessionDataTask {
    fatalError("unavailable")
  }
}

extension Result {
  @available(*, unavailable, renamed: "Result.init(_:)")
  public static func fromDecoded(_: Decoded<T>) -> Result<T, SwishError> {
    fatalError("unavailable")
  }
}


//
//  AppDelegate.swift
//  UitzendingGemist
//
//  Created by Jeff Kreeftmeijer on 06/11/15.
//  Copyright © 2015 Jeff Kreeftmeijer. All rights reserved.
//

import UIKit
import TVMLKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, TVApplicationControllerDelegate {

  var window: UIWindow?

  var appController: TVApplicationController?

  static let TVBaseURL = "http://localhost:9001/"

  static let TVBootURL = "\(AppDelegate.TVBaseURL)js/application.js"

  func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    let appControllerContext = TVApplicationControllerContext()

    if let javaScriptURL = NSURL(string: AppDelegate.TVBootURL) {
      appControllerContext.javaScriptApplicationURL = javaScriptURL
    }

    appControllerContext.launchOptions["BASEURL"] = AppDelegate.TVBaseURL

    if let launchOptions = launchOptions as? [String: AnyObject] {
      for (kind, value) in launchOptions {
        appControllerContext.launchOptions[kind] = value
      }
    }

    appController = TVApplicationController(context: appControllerContext, window: window, delegate: self)

    return true
  }
}

Use S3 instead of localhost:9001

//
//  AppDelegate.swift
//  UitzendingGemist
//
//  Created by Jeff Kreeftmeijer on 06/11/15.
//  Copyright © 2015 Jeff Kreeftmeijer. All rights reserved.
//

import UIKit
import TVMLKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, TVApplicationControllerDelegate {

  var window: UIWindow?

  var appController: TVApplicationController?
  static let TVBaseURL = "http://atvnpo.s3-website-us-east-1.amazonaws.com/"

  static let TVBootURL = "\(AppDelegate.TVBaseURL)js/application.js"

  func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    let appControllerContext = TVApplicationControllerContext()

    if let javaScriptURL = NSURL(string: AppDelegate.TVBootURL) {
      appControllerContext.javaScriptApplicationURL = javaScriptURL
    }

    appControllerContext.launchOptions["BASEURL"] = AppDelegate.TVBaseURL

    if let launchOptions = launchOptions as? [String: AnyObject] {
      for (kind, value) in launchOptions {
        appControllerContext.launchOptions[kind] = value
      }
    }

    appController = TVApplicationController(context: appControllerContext, window: window, delegate: self)

    return true
  }
}


//
//  DemoView.swift
//  SwiftRebound
//
//  Created by Andrew Hunter on 15/07/2016.
//
//

import Foundation

///
/// Click/drag to move the circle
///
class DemoView : ReactiveView {
    override func drawReactive() {
        if leftMouseDown.value {
            // Draw an oval centered on the current position
            let clickPos    = mousePosition.value;
            let ovalRect    = NSInsetRect(NSRect(origin: clickPos, size: NSSize(width: 0, height: 0)), -64, -64);

            NSColor.blueColor().set();
            NSBezierPath.init(ovalInRect: ovalRect).fill();
        } else if mouseOver.value {
            // Draw an square centered on the current position
            let clickPos    = mousePosition.value;
            let square      = NSInsetRect(NSRect(origin: clickPos, size: NSSize(width: 0, height: 0)), -16, -16);

            NSColor.greenColor().set();
            NSRectFill(square);
        }
    }
}

Make comments explain the demo a bit better

//
//  DemoView.swift
//  SwiftRebound
//
//  Created by Andrew Hunter on 15/07/2016.
//
//

import Foundation

///
/// Click/drag to draw a circle. A green box will follow the mouse when the button is not down.
///
class DemoView : ReactiveView {
    override func drawReactive() {
        if leftMouseDown.value {
            // Draw an oval centered on the current position
            let clickPos    = mousePosition.value;
            let ovalRect    = NSInsetRect(NSRect(origin: clickPos, size: NSSize(width: 0, height: 0)), -64, -64);

            NSColor.blueColor().set();
            NSBezierPath.init(ovalInRect: ovalRect).fill();
        } else if mouseOver.value {
            // Draw an square centered on the current position
            let clickPos    = mousePosition.value;
            let square      = NSInsetRect(NSRect(origin: clickPos, size: NSSize(width: 0, height: 0)), -16, -16);

            NSColor.greenColor().set();
            NSRectFill(square);
        }
    }
}


import Authentication
import Crypto
import Fluent
import JWT
import Sugar
import Vapor

public protocol JWTKeychainUser: JWTCustomPayloadKeychainUser where
    JWTPayload == Payload
{}

extension JWTKeychainUser {
    public func makePayload(
        expirationTime: Date,
        on container: Container
    ) throws -> Future<Payload> {
        return Future.map(on: container) {
            try Payload(
                exp: ExpirationClaim(value: expirationTime),
                sub: SubjectClaim(value: self.requireID().description)
            )
        }
    }
}

// MARK: - JWTCustomPayloadKeychainUser

public protocol JWTCustomPayloadKeychainUser:
    Content,
    HasPassword,
    JWTAuthenticatable,
    Model,
    PasswordAuthenticatable,
    PublicRepresentable,
    UserType
where
    Self.Database: QuerySupporting,
    Self.ID: LosslessStringConvertible
{}

extension JWTCustomPayloadKeychainUser {
    public static func authenticate(
        using payload: JWTPayload,
        on connection: DatabaseConnectable
    ) throws -> Future<Self?> {
        guard let id = ID(payload.sub.value) else {
            throw JWTKeychainError.malformedPayload
        }

        return try find(id, on: connection)
    }
}

Move default authenticate implementation to Sugar


//
//  ArrayExtensions.swift
//  Collections
//
//  Created by James Bean on 2/13/17.
//
//

extension Array {

    /// - returns: Left-hand-side value appening the right-hand-side value, if it exists.
    /// Otherwise, the left-hand-side value.
    public static func + (lhs: Array, rhs: Element?) -> Array {

        if let element = rhs {
            return lhs + element
        }

        return lhs
    }
}

Add Array.removing(at:) for good measure

//
//  ArrayExtensions.swift
//  Collections
//
//  Created by James Bean on 2/13/17.
//
//

extension Array {

    /// - Returns: Left-hand-side value appening the right-hand-side value, if it exists.
    /// Otherwise, the left-hand-side value.
    public static func + (lhs: Array, rhs: Element?) -> Array {

        if let element = rhs {
            return lhs + element
        }

        return lhs
    }

    /// - Returns: Array with the element at the given `index` removed.
    public func removing(at index: Int) -> [Element] {
        var copy = self
        copy.remove(at: index)
        return copy
    }
}


public class Faker {

  public var locale: String {
    didSet {
      if locale != oldValue {
        parser.locale = locale
      }
    }
  }

  public let address: Address
  public let app: App
  public let business: Business
  public let commerce: Commerce
  public let internet: Internet
  public let lorem: Lorem
  public let name: Name
  public let phoneNumber: PhoneNumber
  public let team: Team

  let parser: Parser

  public init(locale: String = Config.defaultLocale) {
    self.locale = locale
    parser = Parser(locale: self.locale)

    address = Address(parser: parser)
    app = App(parser: parser)
    business = Business(parser: parser)
    commerce = Commerce(parser: parser)
    internet = Internet(parser: parser)
    lorem = Lorem(parser: parser)
    name = Name(parser: parser)
    phoneNumber = PhoneNumber(parser: parser)
    team = Team(parser: parser)
  }
}

Add the company generator as a property, as mentioned in the Readme.

public class Faker {

  public var locale: String {
    didSet {
      if locale != oldValue {
        parser.locale = locale
      }
    }
  }

  public let address: Address
  public let app: App
  public let business: Business
  public let company: Company
  public let commerce: Commerce
  public let internet: Internet
  public let lorem: Lorem
  public let name: Name
  public let phoneNumber: PhoneNumber
  public let team: Team

  let parser: Parser

  public init(locale: String = Config.defaultLocale) {
    self.locale = locale
    parser = Parser(locale: self.locale)

    address = Address(parser: parser)
    app = App(parser: parser)
    business = Business(parser: parser)
    company = Company(parser: parser)
    commerce = Commerce(parser: parser)
    internet = Internet(parser: parser)
    lorem = Lorem(parser: parser)
    name = Name(parser: parser)
    phoneNumber = PhoneNumber(parser: parser)
    team = Team(parser: parser)
  }
}


public enum Tone: String {
    case A
    case Bb
    case B
    case C
    case Db
    case D
    case Eb
    case E
    case F
    case Gb
    case G
    case Ab
}

extension Tone: Comparable {
    public static func < (lhs: Tone, rhs: Tone) -> Bool {
        return lhs.rawValue < rhs.rawValue
    }
}

Change tone so that it gets compared based on order

public enum Tone: String {
    case A
    case Bb
    case B
    case C
    case Db
    case D
    case Eb
    case E
    case F
    case Gb
    case G
    case Ab
}

public extension Tone {
    // Even though each tone is represented in String, we still need order of each tone.
    public var order: Int {
        switch self {
        case .A:  return 0
        case .Bb: return 1
        case .B:  return 2
        case .C:  return 3
        case .Db: return 4
        case .D:  return 5
        case .Eb: return 6
        case .E:  return 7
        case .F:  return 8
        case .Gb: return 9
        case .G:  return 10
        case .Ab: return 11
        }
    }
}

extension Tone: Comparable {
    public static func < (lhs: Tone, rhs: Tone) -> Bool {
        return lhs.order < rhs.order
    }
}


import UIKit

class DefaultColorViewController: UITableViewController {

    lazy var dataSource = makeDataSource()

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = dataSource
        #warning("UITableView was told to layout its visible cells and other contents without being in the view hierarchy")
        applySnapshot()
    }

    func makeDataSource() -> UITableViewDiffableDataSource<Int, Color> {
        UITableViewDiffableDataSource<Int, Color>(tableView: tableView) { tableView, indexPath, color -> UITableViewCell? in
            let cell = tableView.dequeueReusableCell(withIdentifier: "ColorCell") ?? UITableViewCell()

            cell.textLabel?.text = "\(color)".capitalized
            cell.imageView?.tintColor = color.value
            cell.accessoryType = color == Color.default ? .checkmark : .none

            return cell
        }
    }

    func applySnapshot() {
        var snapshot = NSDiffableDataSourceSnapshot<Int, Color>()
        snapshot.appendSections([0])
        snapshot.appendItems(Color.allCases)
        dataSource.apply(snapshot, animatingDifferences: false)
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        defer { tableView.deselectRow(at: indexPath, animated: true) }
        let oldColor = Color.default
        guard let color = dataSource.itemIdentifier(for: indexPath), oldColor != color else { return }

        Color.default = color

        var snapshot = dataSource.snapshot()
        snapshot.reloadItems([color, oldColor])

        dataSource.apply(snapshot)
    }

}

Remove warning that's no longer applicable.

import UIKit

class DefaultColorViewController: UITableViewController {

    lazy var dataSource = makeDataSource()

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = dataSource
        applySnapshot()
    }

    func makeDataSource() -> UITableViewDiffableDataSource<Int, Color> {
        UITableViewDiffableDataSource<Int, Color>(tableView: tableView) { tableView, indexPath, color -> UITableViewCell? in
            let cell = tableView.dequeueReusableCell(withIdentifier: "ColorCell") ?? UITableViewCell()

            cell.textLabel?.text = "\(color)".capitalized
            cell.imageView?.tintColor = color.value
            cell.accessoryType = color == Color.default ? .checkmark : .none

            return cell
        }
    }

    func applySnapshot() {
        var snapshot = NSDiffableDataSourceSnapshot<Int, Color>()
        snapshot.appendSections([0])
        snapshot.appendItems(Color.allCases)
        dataSource.apply(snapshot, animatingDifferences: false)
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        defer { tableView.deselectRow(at: indexPath, animated: true) }
        let oldColor = Color.default
        guard let color = dataSource.itemIdentifier(for: indexPath), oldColor != color else { return }

        Color.default = color

        var snapshot = dataSource.snapshot()
        snapshot.reloadItems([color, oldColor])

        dataSource.apply(snapshot)
    }

}


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

import Quick
import Nimble
import EasyZoom

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

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

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

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

            context("these will pass") {

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

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

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

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

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

                        done()
                    }
                }
            }
        }
    }
}

Test file commented in for now

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

import Quick
import Nimble
import EasyZoom

class TableOfContentsSpec: QuickSpec {
    override func spec() {
//        describe("these will fail") {
//
//            it("can do maths") {
//                expect(1) == 2
//            }
//
//            it("can read") {
//                expect("number") == "string"
//            }
//
//            it("will eventually fail") {
//                expect("time").toEventually( equal("done") )
//            }
//
//            context("these will pass") {
//
//                it("can do maths") {
//                    expect(23) == 23
//                }
//
//                it("can read") {
//                    expect("🐮") == "🐮"
//                }
//
//                it("will eventually pass") {
//                    var time = "passing"
//
//                    dispatch_async(dispatch_get_main_queue()) {
//                        time = "done"
//                    }
//
//                    waitUntil { done in
//                        NSThread.sleepForTimeInterval(0.5)
//                        expect(time) == "done"
//
//                        done()
//                    }
//                }
//            }
//        }
    }
}


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

import Quick
import Nimble
@testable import Swinject

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

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

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

Remove unnecessary @testable import of Swinject.

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

import Quick
import Nimble
import Swinject

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

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

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


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

import UIKit

class HabitsController: UITableViewController {
    //MARK: Properties

    let viewModel: HabitsViewModel

    //MARK: Initialization

    init(viewModel: HabitsViewModel) {
        self.viewModel = viewModel
        super.init(style: .Plain)
    }

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

    //MARK: UIViewController

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.registerClass(HabitsCell.self, forCellReuseIdentifier: String(HabitsCell))
    }
}

Set table view's data source during initialization

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

import UIKit

class HabitsController: UITableViewController {
    //MARK: Properties

    let viewModel: HabitsViewModel

    //MARK: Initialization

    init(viewModel: HabitsViewModel, dataSource: HabitsDataSource) {
        self.viewModel = viewModel
        super.init(style: .Plain)
        tableView.dataSource = dataSource
    }

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

    //MARK: UIViewController

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.registerClass(HabitsCell.self, forCellReuseIdentifier: String(HabitsCell))
    }
}


//
//  AppDelegate.swift
//  Example
//
//  Created by David Cordero on 15.02.17.
//  Copyright © 2017 David Cordero. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

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

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

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

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

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

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

}

Remove useless code from the Example project

//
//  AppDelegate.swift
//  Example
//
//  Created by David Cordero on 15.02.17.
//  Copyright © 2017 David Cordero. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

}


import Foundation

public enum PusherHost {
    case host(String)
    case cluster(String)

    public var stringValue: String {
        switch self {
            case .host(let host): return host
        case .cluster(let cluster): return "ws-\(cluster).\(Constants.API.pusherDomain)"
        }
    }
}

public enum AuthMethod {
    case endpoint(authEndpoint: String)
    case authRequestBuilder(authRequestBuilder: AuthRequestBuilderProtocol)
    case authorizer(authorizer: Authorizer)
    case inline(secret: String)
    case noMethod
}

@objcMembers
@objc public class PusherClientOptions: NSObject {
    public var authMethod: AuthMethod
    public let attemptToReturnJSONObject: Bool
    public let autoReconnect: Bool
    public let host: String
    public let port: Int
    public let useTLS: Bool
    public let activityTimeout: TimeInterval?

    @nonobjc public init(
        authMethod: AuthMethod = .noMethod,
        attemptToReturnJSONObject: Bool = true,
        autoReconnect: Bool = true,
        host: PusherHost = .host(Constants.API.defaultHost),
        port: Int? = nil,
        useTLS: Bool = true,
        activityTimeout: TimeInterval? = nil
    ) {
        self.authMethod = authMethod
        self.attemptToReturnJSONObject = attemptToReturnJSONObject
        self.autoReconnect = autoReconnect
        self.host = host.stringValue
        self.port = port ?? (useTLS ? 443 : 80)
        self.useTLS = useTLS
        self.activityTimeout = activityTimeout
    }
}

Resolve switch statement indentation issue.


//
//  Playlist.swift
//  Cider
//
//  Created by Scott Hoyt on 8/25/17.
//  Copyright © 2017 Scott Hoyt. All rights reserved.
//

import Foundation

public typealias Playlist = Resource<PlaylistAttributes, PlaylistRelationships>

public enum PlaylistType: String, Codable {
    case userShared = "user-shared"
    case editorial
    case external
    case personalMix = "personal-mix"
}

public struct PlaylistAttributes: Codable {
    public let artwork: Artwork?
    public let curatorName: String?
    public let description: EditorialNotes?
    public let lastModifiedDate: String
    public let name: String
    public let playlistType: PlaylistType
    public let playParams: PlayParameters?
    public let url: URL
}

public struct PlaylistRelationships: Codable {
    public let curator: Relationship<Curator>
    public let tracks: Relationship<Track>
}

Add docs for playlist type.

//
//  Playlist.swift
//  Cider
//
//  Created by Scott Hoyt on 8/25/17.
//  Copyright © 2017 Scott Hoyt. All rights reserved.
//

import Foundation

public typealias Playlist = Resource<PlaylistAttributes, PlaylistRelationships>

/// A type describing the kind of playlist
public enum PlaylistType: String, Codable {
    /// A playlist created and shared by an Apple Music user
    case userShared = "user-shared"

    /// A playlist created by an Apple Music curator
    case editorial

    /// A playlist created by an non-Apple curator or brand
    case external

    /// A personalized playlist for an Apple Music user
    case personalMix = "personal-mix"
}

public struct PlaylistAttributes: Codable {
    public let artwork: Artwork?
    public let curatorName: String?
    public let description: EditorialNotes?
    public let lastModifiedDate: String
    public let name: String
    public let playlistType: PlaylistType
    public let playParams: PlayParameters?
    public let url: URL
}

public struct PlaylistRelationships: Codable {
    public let curator: Relationship<Curator>
    public let tracks: Relationship<Track>
}


//
//  LoggerHelper.swift
//  alamofire_activity_logger
//
//  Created by Manuel García-Estañ on 19/10/16.
//  Copyright © 2016 manuege. All rights reserved.
//

import Foundation
import Alamofire
import AlamofireActivityLogger

private struct URLConstants {
    static let successURL = "http://www.mocky.io/v2/574c43dc100000760eed69ca"
    static let failURL = "http://www.mocky.io/v2/574c440d100000860eed69cb"
}

struct Constants {
    static let levelsAndNames: [(LogLevel, String)] = [
        (.none, "None"),
        (.all, "All"),
        (.info, "Info"),
        (.error, "Error")
    ]
}

struct Helper {

    static func performRequest(success: Bool, level: LogLevel, options: [LogOption], completion: @escaping () -> Void) {

        let url = success ? URLConstants.successURL : URLConstants.failURL;

        request(url, method: .get)
            .validate()
            .log(level: level, options: options)
            .responseData { (response) in
                completion()
        }
    }
}

Add custom printer to sample app

//
//  LoggerHelper.swift
//  alamofire_activity_logger
//
//  Created by Manuel García-Estañ on 19/10/16.
//  Copyright © 2016 manuege. All rights reserved.
//

import Foundation
import Alamofire
import AlamofireActivityLogger

private struct URLConstants {
    static let successURL = "http://www.mocky.io/v2/574c43dc100000760eed69ca"
    static let failURL = "http://www.mocky.io/v2/574c440d100000860eed69cb"
}

struct Constants {
    static let levelsAndNames: [(LogLevel, String)] = [
        (.none, "None"),
        (.all, "All"),
        (.info, "Info"),
        (.error, "Error")
    ]
}

struct Helper {

    static func performRequest(success: Bool, level: LogLevel, options: [LogOption], completion: @escaping () -> Void) {

        let url = success ? URLConstants.successURL : URLConstants.failURL;

        request(url, method: .get)
            .validate()
            .log(level: level, options: options, printer: NativePrinter())
            .responseData { (response) in
                completion()
        }
    }
}

struct MyPrinter: Printer {
    func print(_ string: String, phase: Phase) {
        if phase.isError {
            Swift.print("🍎\n\(string)")
        }
        else {
            Swift.print("🍏\n\(string)")
        }
    }
}


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

final class TypeDifferentialTests: XCTestCase {

}

import Assertions
import Manifold
import TesseractCore
import XCTest

Test that patching with the empty diff is idempotent.

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

final class TypeDifferentialTests: XCTestCase {

	// MARK: Patching

	func testEmptyDiffIsIdempotent() {
		assert(TypeDifferential.Empty.apply(Term.Bool), ==, Term.Bool)
	}
}

import Assertions
import Manifold
import TesseractCore
import XCTest


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

final class ChurchListTests: XCTestCase {}

import Manifold
import XCTest

Test that the module typechecks.

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

final class ChurchListTests: XCTestCase {
	func testModuleTypechecks() {
		module.typecheck().forEach { XCTFail($0.description) }
	}
}

private let module = Module<Term>.churchList

import Manifold
import XCTest


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

/// Describes a sequence as a set.
internal func describe<S: SequenceType>(sequence: S) -> String {
	return wrapDescription(join(", ", lazy(sequence).map(toString)))
}

/// Debug-describes a sequence as a set.
internal func debugDescribe<S: SequenceType>(sequence: S) -> String {
	return wrapDescription(join(", ", lazy(sequence).map(toDebugString)))
}

/// Wraps a string appropriately for formatting as a set.
private func wrapDescription(description: String) -> String {
	return description.isEmpty ?
		"{}"
	:	"{ \(description) }"
}

Remove the padding from the non-empty set descriptions.

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

/// Describes a sequence as a set.
internal func describe<S: SequenceType>(sequence: S) -> String {
	return wrapDescription(join(", ", lazy(sequence).map(toString)))
}

/// Debug-describes a sequence as a set.
internal func debugDescribe<S: SequenceType>(sequence: S) -> String {
	return wrapDescription(join(", ", lazy(sequence).map(toDebugString)))
}

/// Wraps a string appropriately for formatting as a set.
private func wrapDescription(description: String) -> String {
	return description.isEmpty ?
		"{}"
	:	"{\(description)}"
}


//
//  ViewController.swift
//  TwicketSegmentedControlDemo
//
//  Created by Pol Quintana on 17/09/16.
//  Copyright © 2016 Pol Quintana. All rights reserved.
//

import UIKit
import TwicketSegmentedControl

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let titles = ["First", "Second", "Third"]
        let frame = CGRect(x: 5, y: view.frame.height / 2 - 20, width: view.frame.width - 10, height: 40)

        let segmentedControl = TwicketSegmentedControl(frame: frame)
        segmentedControl.setSegmentItems(titles)

        view.addSubview(segmentedControl)
    }

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

Update example project with delegate implementation

//
//  ViewController.swift
//  TwicketSegmentedControlDemo
//
//  Created by Pol Quintana on 17/09/16.
//  Copyright © 2016 Pol Quintana. All rights reserved.
//

import UIKit
import TwicketSegmentedControl

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let titles = ["First", "Second", "Third"]
        let frame = CGRect(x: 5, y: view.frame.height / 2 - 20, width: view.frame.width - 10, height: 40)

        let segmentedControl = TwicketSegmentedControl(frame: frame)
        segmentedControl.setSegmentItems(titles)
        segmentedControl.delegate = self

        view.addSubview(segmentedControl)
    }
}

extension ViewController: TwicketSegmentedControlDelegate {
    func didSelect(_ segmentIndex: Int) {
        print("Selected idex: \(segmentIndex)")
    }
}


// RUN: not --crash %target-swift-frontend %s -c -o /dev/null
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/codafi (Robert Widmann)

struct X<T> {
	let s : X<X>
}

Use canonical "-emit-silgen" to trigger crash case.

// RUN: not --crash %target-swift-frontend %s -emit-silgen
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/codafi (Robert Widmann)

struct X<T> {
	let s : X<X>
}


//
//  AsyncType+Debug.swift
//  BrightFutures
//
//  Created by Oleksii on 23/09/2016.
//  Copyright © 2016 Thomas Visser. All rights reserved.
//

import Result

public protocol LoggerType {
    func log(message: String)
}

struct Logger: LoggerType {
    func log(message: String) {
        print(message)
    }
}

Add public debug func on async type

//
//  AsyncType+Debug.swift
//  BrightFutures
//
//  Created by Oleksii on 23/09/2016.
//  Copyright © 2016 Thomas Visser. All rights reserved.
//

import Result

public protocol LoggerType {
    func log(message: String)
}

struct Logger: LoggerType {
    func log(message: String) {
        print(message)
    }
}

public extension AsyncType where Value: ResultProtocol {
    public func debug(logger: LoggerType = Logger(), context c: @escaping ExecutionContext = DefaultThreadingModel(), messageBlock: @escaping (Self.Value) -> String) -> Self {
        return andThen(context: c, callback: { result in
            logger.log(message: messageBlock(result))
        })
    }
}


//
//  UIImageExtension.swift
//  Haneke
//
//  Created by Oriol Blanc Gimeno on 01/08/14.
//  Copyright (c) 2014 Haneke. All rights reserved.
//

import UIKit

extension UIImage {

    func isEqualPixelByPixel(theOtherImage: UIImage!) -> Bool {
        let imageData = UIImagePNGRepresentation(self);
        let theOtherImageData = UIImagePNGRepresentation(theOtherImage);

        return imageData.isEqualToData(theOtherImageData);
    }

    class func imageWithColor(color: UIColor, _ size: CGSize, _ opaque: Bool) -> UIImage{
        UIGraphicsBeginImageContextWithOptions(size, opaque, 0);
        let context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, color.CGColor);
        CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height));
        let image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image;
    }
}

Add default values for convenience

//
//  UIImageExtension.swift
//  Haneke
//
//  Created by Oriol Blanc Gimeno on 01/08/14.
//  Copyright (c) 2014 Haneke. All rights reserved.
//

import UIKit

extension UIImage {

    func isEqualPixelByPixel(theOtherImage: UIImage!) -> Bool {
        let imageData = UIImagePNGRepresentation(self);
        let theOtherImageData = UIImagePNGRepresentation(theOtherImage);

        return imageData.isEqualToData(theOtherImageData);
    }

    class func imageWithColor(color: UIColor, _ size: CGSize = CGSize(width: 1, height: 1), _ opaque: Bool = true) -> UIImage{
        UIGraphicsBeginImageContextWithOptions(size, opaque, 0);
        let context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, color.CGColor);
        CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height));
        let image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image;
    }
}


//
//  ViewController.swift
//  Katanga
//
//  Created by Víctor Galán on 9/10/16.
//  Copyright © 2016 Software Craftsmanship Toledo. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa

class InitialViewController: UIViewController {

    var disposeBag = DisposeBag()

    var spinner: UIActivityIndicatorView?

    @IBOutlet weak var searchLocationButton: UIButton! {
        didSet {
            searchLocationButton.backgroundColor = .katangaYellow
            searchLocationButton.layer.cornerRadius = 30

            spinner = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
            spinner!.color = .black
            spinner!.center = CGPoint(x: 30, y: 30)

            searchLocationButton.addSubview(spinner!)
        }
    }

    @IBOutlet weak var metersSlider: UISlider!
    @IBOutlet weak var metersLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        setUpRx()
    }

    private func setUpRx() {
        metersSlider.rx.value
            .startWith(500)
            .map {"\(Int($0))"}
            .bindTo(metersLabel.rx.text)
            .addDisposableTo(disposeBag)

        searchLocationButton.rx.tap
            .bindNext {
                self.spinner?.startAnimating()
            }
            .addDisposableTo(disposeBag)
    }
}

Move to near bus stops view controller on click

//
//  ViewController.swift
//  Katanga
//
//  Created by Víctor Galán on 9/10/16.
//  Copyright © 2016 Software Craftsmanship Toledo. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa

class InitialViewController: UIViewController {

    var disposeBag = DisposeBag()

    var spinner: UIActivityIndicatorView?

    @IBOutlet weak var searchLocationButton: UIButton! {
        didSet {
            searchLocationButton.backgroundColor = .katangaYellow
            searchLocationButton.layer.cornerRadius = 30

            spinner = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
            spinner!.color = .black
            spinner!.center = CGPoint(x: 30, y: 30)

            searchLocationButton.addSubview(spinner!)
        }
    }

    @IBOutlet weak var metersSlider: UISlider!
    @IBOutlet weak var metersLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        setUpRx()
    }

    private func setUpRx() {
        metersSlider.rx.value
            .startWith(500)
            .map {"\(Int($0))"}
            .bindTo(metersLabel.rx.text)
            .addDisposableTo(disposeBag)

        searchLocationButton.rx.tap
            .bindNext {
                self.spinner?.startAnimating()
                self.performSegue(withIdentifier: "shownearstops", sender: nil)
            }
            .addDisposableTo(disposeBag)
    }
}


//
//  AppDelegate.swift
//  BabyMoment
//
//  Created by Xueliang Zhu on 8/24/16.
//  Copyright © 2016 kotlinchina. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        IQKeyboardManager.sharedManager().enable = true
        return true
    }
}

Add sleep 1 for launch screen

//
//  AppDelegate.swift
//  BabyMoment
//
//  Created by Xueliang Zhu on 8/24/16.
//  Copyright © 2016 kotlinchina. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        sleep(1)
        IQKeyboardManager.sharedManager().enable = true
        return true
    }
}


//
//  CloudRecordType.swift
//  GROCloudStore
//
//  Created by Andrew Shepard on 2/9/16.
//  Copyright © 2016 Andrew Shepard. All rights reserved.
//

import Foundation
import CoreData

protocol CloudRecordType {
    var recordType: String { get }
}

// FIXME: do you need this anymore?

//extension NSFetchRequest where Self == NS {
//    override var recordType: String {
//        return self.entityName ?? ""
//    }
//}

extension NSPersistentStoreRequest: CloudRecordType {
    var recordType: String {
        return ""
    }
}

Add note about failure with protocol

//
//  CloudRecordType.swift
//  GROCloudStore
//
//  Created by Andrew Shepard on 2/9/16.
//  Copyright © 2016 Andrew Shepard. All rights reserved.
//

import Foundation
import CoreData

// FIXME: this isn't working right now, fix it

//protocol CloudRecordType {
//    var recordType: String { get }
//}

//extension CloudRecordType {
//    var recordType: String {
//        return ""
//    }
//}

//extension NSFetchRequest {
//    var recordType: String {
//        return self.entityName ?? ""
//    }
//}


#!/usr/bin/env swiftshell

import SwiftShell

for line in open("../shorttext.txt").lines() {
	// Do something with each line
	println(line)
}

Add missing newline to the end.


import UIKit

class CHome:Controller<VHome, MHome>
{
    override func modelRefresh()
    {
        DispatchQueue.main.async
        { [weak self] in

            self?.dispatchRefresh()
        }
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()

        model.requestRandomGif()
    }

    //MARK: private

    private func dispatchRefresh()
    {
        guard

            let view:VHome = self.view as? VHome

        else
        {
            return
        }

        view.refresh()
    }
}

Use status bar light in home

import UIKit

class CHome:Controller<VHome, MHome>
{
    override var preferredStatusBarStyle:UIStatusBarStyle
    {
        get
        {
            return UIStatusBarStyle.lightContent
        }
    }

    override func modelRefresh()
    {
        DispatchQueue.main.async
        { [weak self] in

            self?.dispatchRefresh()
        }
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()

        model.requestRandomGif()
    }

    //MARK: private

    private func dispatchRefresh()
    {
        guard

            let view:VHome = self.view as? VHome

        else
        {
            return
        }

        view.refresh()
    }
}


import UIKit

final class VCreateStatusReadyMapMenuCell:
    UICollectionViewCell
{
    private weak var icon:UIImageView!
    private let kAlphaSelected:CGFloat = 0.6
    private let kAlphaNotSelected:CGFloat = 1

    override init(frame:CGRect)
    {
        super.init(frame:frame)
        clipsToBounds = true
        backgroundColor = UIColor.clear

        let icon:UIImageView = UIImageView()
        icon.isUserInteractionEnabled = false
        icon.translatesAutoresizingMaskIntoConstraints = false
        icon.contentMode = UIViewContentMode.center
        icon.clipsToBounds = true
        self.icon = icon

        addSubview(icon)

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

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

    override var isSelected:Bool
    {
        didSet
        {
            hover()
        }
    }

    override var isHighlighted:Bool
    {
        didSet
        {
            hover()
        }
    }

    //MARK: private

    private func hover()
    {
        if isSelected || isHighlighted
        {
            icon.alpha = kAlphaSelected
        }
        else
        {
            icon.alpha = kAlphaNotSelected
        }
    }

    //MARK: internal

    func config(model:MCreateMapMenuProtocol)
    {
        icon.image = model.icon
        hover()
    }
}

Update map menu cell hover

import UIKit

final class VCreateStatusReadyMapMenuCell:
    UICollectionViewCell
{
    private weak var icon:UIImageView!
    private weak var image:UIImage?
    private weak var imageSelected:UIImage?

    override init(frame:CGRect)
    {
        super.init(frame:frame)
        clipsToBounds = true
        backgroundColor = UIColor.clear

        let icon:UIImageView = UIImageView()
        icon.isUserInteractionEnabled = false
        icon.translatesAutoresizingMaskIntoConstraints = false
        icon.contentMode = UIViewContentMode.center
        icon.clipsToBounds = true
        self.icon = icon

        addSubview(icon)

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

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

    override var isSelected:Bool
    {
        didSet
        {
            hover()
        }
    }

    override var isHighlighted:Bool
    {
        didSet
        {
            hover()
        }
    }

    //MARK: private

    private func hover()
    {
        if isSelected || isHighlighted
        {
            icon.image = imageSelected
        }
        else
        {
            icon.image = image
        }
    }

    //MARK: internal

    func config(model:MCreateMapMenuProtocol)
    {
        image = model.icon
        imageSelected = model.iconSelected
        hover()
    }
}


// RUN: %target-swift-emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -enable-experimental-concurrency > %t.out
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-%target-ptrsize %s < %t.out
// RUN: %FileCheck -check-prefix=NEGATIVE %s < %t.out

// REQUIRES: objc_interop
// REQUIRES: concurrency

import gizmo

func hashEm<H: Hashable>(_ x: H) {}

public class A {
  @asyncHandler
  public func f() {
    hashEm(NSRuncingOptions.mince)
  }
}

// CHECK: sil_witness_table shared [serialized] NSRuncingOptions: Hashable module gizmo

Fix a stray FileCheck in new test

// RUN: %target-swift-emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -enable-experimental-concurrency > %t.out
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-%target-ptrsize %s < %t.out

// REQUIRES: objc_interop
// REQUIRES: concurrency

import gizmo

func hashEm<H: Hashable>(_ x: H) {}

public class A {
  @asyncHandler
  public func f() {
    hashEm(NSRuncingOptions.mince)
  }
}

// CHECK: sil_witness_table shared [serialized] NSRuncingOptions: Hashable module gizmo


//
// PlayerRecord.swift
//
// This source file is part of the SMUD open source project
//
// Copyright (c) 2016 SMUD project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SMUD project authors
//

import Foundation
import GRDB

class PlayerRecord: Record, ModifiablePersistable {
    var entity: Player

    override class var databaseTableName: String { return "players" }

    required init(row: Row) {
        entity = Player()

        super.init(row: row)

        entity.playerId = row.value(named: "player_id")
        let accountId: Int64 = row.value(named: "account_id")
        entity.account = Account.with(id: accountId)

        entity.name = row.value(named: "name")
    }

    required init(entity: Player) {
        self.entity = entity
        super.init()
    }

    override var persistentDictionary: [String: DatabaseValueConvertible?] {
        return ["player_id": entity.playerId,
                "account_id": entity.account?.accountId,
                "name": entity.name.lowercased()]
    }

    override func didInsert(with rowID: Int64, for column: String?) {
        Player.removeFromIndexes(player: entity)
        entity.playerId = rowID
        Player.addToIndexes(player: entity)
    }
}

Fix player name capitalization on load

//
// PlayerRecord.swift
//
// This source file is part of the SMUD open source project
//
// Copyright (c) 2016 SMUD project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SMUD project authors
//

import Foundation
import GRDB

class PlayerRecord: Record, ModifiablePersistable {
    var entity: Player

    override class var databaseTableName: String { return "players" }

    required init(row: Row) {
        entity = Player()

        super.init(row: row)

        entity.playerId = row.value(named: "player_id")
        let accountId: Int64 = row.value(named: "account_id")
        entity.account = Account.with(id: accountId)

        let lowercasedName: String = row.value(named: "name")
        entity.name = lowercasedName.capitalized
    }

    required init(entity: Player) {
        self.entity = entity
        super.init()
    }

    override var persistentDictionary: [String: DatabaseValueConvertible?] {
        return ["player_id": entity.playerId,
                "account_id": entity.account?.accountId,
                "name": entity.name.lowercased()]
    }

    override func didInsert(with rowID: Int64, for column: String?) {
        Player.removeFromIndexes(player: entity)
        entity.playerId = rowID
        Player.addToIndexes(player: entity)
    }
}


//
//  UIView+SnapshotImage.swift
//  View2ViewTransitionExample
//
//  Created by naru on 2016/08/29.
//  Copyright © 2016年 naru. All rights reserved.
//

import UIKit

public extension UIView {

    public func snapshotImage() -> UIImage? {

        let size: CGSize = CGSize(width: floor(self.frame.size.width), height: floor(self.frame.size.height))
        UIGraphicsBeginImageContextWithOptions(size, true, 0.0)

        if let context: CGContext = UIGraphicsGetCurrentContext() {
            self.layer.render(in: context)
        }
        let snapshot: UIImage? = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        return snapshot
    }
}

Fix to create view snapshot

//
//  UIView+SnapshotImage.swift
//  View2ViewTransitionExample
//
//  Created by naru on 2016/08/29.
//  Copyright © 2016年 naru. All rights reserved.
//

import UIKit

public extension UIView {

    public func snapshotImage() -> UIImage? {

        let size: CGSize = CGSize(width: floor(self.frame.size.width), height: floor(self.frame.size.height))
        UIGraphicsBeginImageContextWithOptions(size, true, 0.0)

        self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
        let snapshot: UIImage? = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        return snapshot
    }
}


//
//  RelaxViewController.swift
//  Relax
//
//  Created by Ryan Arana on 2/7/15.
//  Copyright (c) 2015 PDX-iOS. All rights reserved.
//

import UIKit

class RelaxViewController: UIViewController {

    @IBOutlet weak var activityTitleLabel: UILabel!

    var allActivities = [Activity]()
    var currentActivityIndex: Int = 0 {
        didSet {
            if self.currentActivityIndex >= allActivities.count {
                self.currentActivityIndex = 0
                return
            }
            if activityTitleLabel != nil {
                activityTitleLabel.text = allActivities[self.currentActivityIndex].title
            }
        }
    }

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

        allActivities = DataStore.loadActivities()
        nextActivity()
    }

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

    @IBAction func nextActivity() {
        self.currentActivityIndex = Int(arc4random_uniform(UInt32(allActivities.count)))
    }

    @IBAction func beginActivity() {
    }
}

Add another log message and TODO:

//
//  RelaxViewController.swift
//  Relax
//
//  Created by Ryan Arana on 2/7/15.
//  Copyright (c) 2015 PDX-iOS. All rights reserved.
//

import UIKit

class RelaxViewController: UIViewController {

    @IBOutlet weak var activityTitleLabel: UILabel!

    var allActivities = [Activity]()
    var currentActivityIndex: Int = 0 {
        didSet {
            if self.currentActivityIndex >= allActivities.count {
                self.currentActivityIndex = 0
                return
            }
            if activityTitleLabel != nil {
                activityTitleLabel.text = allActivities[self.currentActivityIndex].title
            }
        }
    }

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

        allActivities = DataStore.loadActivities()
        nextActivity()
    }

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

    @IBAction func nextActivity() {
        self.currentActivityIndex = Int(arc4random_uniform(UInt32(allActivities.count)))
    }

    @IBAction func beginActivity() {
        DataStore.setCurrentActivity(allActivities[currentActivityIndex])

        // TODO: Implement me!
        println( "beginActivity called... but it's not implemented yet!")
    }
}


import FirebaseCommunity
import HandyJSON

open class FireRecord: FirebaseModel {
    public var key: String?
    public static var fireRecordReference: DatabaseReference?
    static var fireRecordQuery: DatabaseQuery?

    required public init() {}

    public func mapping(mapper: HelpingMapper) {
        mapper >>> key
        mapper >>> FireRecord.fireRecordReference
        mapper >>> FireRecord.fireRecordQuery
    }
}

Update public database query property

import FirebaseCommunity
import HandyJSON

open class FireRecord: FirebaseModel {
    public var key: String?
    public static var fireRecordReference: DatabaseReference?
    public static var fireRecordQuery: DatabaseQuery?

    required public init() {}

    public func mapping(mapper: HelpingMapper) {
        mapper >>> key
        mapper >>> FireRecord.fireRecordReference
        mapper >>> FireRecord.fireRecordQuery
    }
}


// swift-tools-version:5.1
import PackageDescription

let package = Package(
    name: "SwiftMessages",
    platforms: [.iOS("9.0")],
    products: [
        .library(name: "SwiftMessages", targets: ["SwiftMessages"])
    ],
    targets: [
        .target(
            name: "SwiftMessages",
            path: "SwiftMessages"
        )
    ]
)

Update swift tools version to support resources

// swift-tools-version:5.3
import PackageDescription

let package = Package(
    name: "SwiftMessages",
    platforms: [
        .iOS("9.0")
    ],
    products: [
        .library(name: "SwiftMessages", targets: ["SwiftMessages"])
    ],
    targets: [
        .target(
            name: "SwiftMessages",
            path: "SwiftMessages"
        )
    ]
)


//
//  OTPToken.swift
//  OneTimePassword
//
//  Created by Matt Rubin on 6/10/14.
//  Copyright (c) 2014 Matt Rubin. All rights reserved.
//

class OTPToken: NSObject {
    var name: String?
    var issuer: String?
    var type: TokenType?
    var secret: NSData?
    var algorithm: Algorithm?
    var digits: Integer?

    enum TokenType {
        case Counter, Timer
    }

    enum Algorithm {
        case SHA1, SHA256, SHA512
    }
}

Use Int instead of Integer

//
//  OTPToken.swift
//  OneTimePassword
//
//  Created by Matt Rubin on 6/10/14.
//  Copyright (c) 2014 Matt Rubin. All rights reserved.
//

class OTPToken: NSObject {
    var name: String?
    var issuer: String?
    var type: TokenType?
    var secret: NSData?
    var algorithm: Algorithm?
    var digits: Int?

    enum TokenType {
        case Counter, Timer
    }

    enum Algorithm {
        case SHA1, SHA256, SHA512
    }
}


import PackageDescription

#if os(Linux)
   let swiftyJsonUrl = "https://github.com/IBM-Swift/SwiftyJSON.git"
   let swiftyJsonVersion = 3
#else
   let swiftyJsonUrl = "https://github.com/SwiftyJSON/SwiftyJSON.git"
   let swiftyJsonVersion = 2
#endif

let package = Package(
    name: "zosconnectforswift",
    targets: [],
    dependencies: [
      .Package(url: swiftyJsonUrl, majorVersion: swiftyJsonVersion),
      .Package(url: "https://github.com/IBM-Swift/Kitura-net",
          majorVersion: 0, minor: 5),
    ]
)

Use latest levels of SwiftyJSON and Kitura-Net

import PackageDescription

#if os(Linux)
   let swiftyJsonUrl = "https://github.com/IBM-Swift/SwiftyJSON.git"
   let swiftyJsonVersion = 3
#else
   let swiftyJsonUrl = "https://github.com/SwiftyJSON/SwiftyJSON.git"
   let swiftyJsonVersion = 2
#endif

let package = Package(
    name: "zosconnectforswift",
    targets: [],
    dependencies: [
      .Package(url: "https://github.com/IBM-Swift/SwiftyJSON.git", majorVersion: 7),
      .Package(url: "https://github.com/IBM-Swift/Kitura-net",
          majorVersion: 0, minor: 13),
    ]
)


//
//  Package.swift
//  CoreTensor
//
//  Copyright 2016-2017 Richard Wei.
//
//  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 PackageDescription

let package = Package(
    name: "CoreTensor",
    targets: [
        Target(name: "CoreTensor"),
        Target(name: "RankedTensor", dependencies: ["CoreTensor"]),
    ],
    dependencies: [
    ]
)

Upgrade package manifest to Swift 4

// swift-tools-version:4.0
//
//  Package.swift
//  CoreTensor
//
//  Copyright 2016-2017 Richard Wei.
//
//  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 PackageDescription

let package = Package(
    name: "CoreTensor",
    targets: [
        .target(name: "CoreTensor"),
        .target(name: "RankedTensor", dependencies: ["CoreTensor"]),
    ],
    swiftLanguageVersions: [ 4 ]
)


//
//  CustomTableRowView.swift
//  FocusPlan
//
//  Created by Vojtech Rinik on 5/11/17.
//  Copyright © 2017 Median. All rights reserved.
//

import Foundation
import AppKit

open class EditableTableRowView: NSTableRowView {
    open var isEditing = false
}

open class CustomTableRowView: EditableTableRowView {
    override open var isSelected: Bool {
        didSet {
            needsDisplay = true
        }
    }

    override open var isEditing: Bool {
        didSet {
            needsDisplay = true
        }
    }

    override open func drawBackground(in dirtyRect: NSRect) {
        let rect = bounds.insetBy(dx: 4, dy: 4)
        let path = NSBezierPath(roundedRect: rect, cornerRadius: 3)
        let blue = NSColor(hexString: "A6CAFD")!.withAlphaComponent(0.3)

        if isEditing {
            NSColor.white.set()
            NSRectFill(bounds)

            blue.setStroke()
            path.stroke()
        } else if isSelected {
            NSColor.white.set()
            NSRectFill(bounds)

            blue.setFill()
            path.fill()
        } else {
//            NSColor.white.set()
//            NSRectFill(bounds)
        }
    }
}

Revert "Not drawing white background for every row view"

//
//  CustomTableRowView.swift
//  FocusPlan
//
//  Created by Vojtech Rinik on 5/11/17.
//  Copyright © 2017 Median. All rights reserved.
//

import Foundation
import AppKit

open class EditableTableRowView: NSTableRowView {
    open var isEditing = false
}

open class CustomTableRowView: EditableTableRowView {
    override open var isSelected: Bool {
        didSet {
            needsDisplay = true
        }
    }

    override open var isEditing: Bool {
        didSet {
            needsDisplay = true
        }
    }

    override open func drawBackground(in dirtyRect: NSRect) {
        let rect = bounds.insetBy(dx: 4, dy: 4)
        let path = NSBezierPath(roundedRect: rect, cornerRadius: 3)
        let blue = NSColor(hexString: "A6CAFD")!.withAlphaComponent(0.3)

        if isEditing {
            NSColor.white.set()
            NSRectFill(bounds)

            blue.setStroke()
            path.stroke()
        } else if isSelected {
            NSColor.white.set()
            NSRectFill(bounds)

            blue.setFill()
            path.fill()
        } else {
            NSColor.white.set()
            NSRectFill(bounds)
        }
    }
}


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

public enum Description<Index> {
	public static func end(index: Index) -> Description {
		return .End(Box(index))
	}

	var end: Index? {
		switch self {
		case let .End(index):
			return index.value
		default:
			return nil
		}
	}

	// MARK: Analyses

	public func analysis<T>(@noescape #ifEnd: Index -> T) -> T {
		switch self {
		case let .End(index):
			return ifEnd(index.value)
		}
	}

	// MARK: Cases

	case End(Box<Index>)
}

import Box

Reimplement the destructor in terms of analysis.

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

public enum Description<Index> {
	public static func end(index: Index) -> Description {
		return .End(Box(index))
	}

	var end: Index? {
		return analysis(ifEnd: unit)
	}

	// MARK: Analyses

	public func analysis<T>(@noescape #ifEnd: Index -> T) -> T {
		switch self {
		case let .End(index):
			return ifEnd(index.value)
		}
	}

	// MARK: Cases

	case End(Box<Index>)
}

import Box


//
//  JumpController.swift
//  XJump
//
//  Created by Victor Shamanov on 5/26/15.
//  Copyright (c) 2015 Victor Shamanov. All rights reserved.
//

import AppKit

final class JumpController {

    // MARK:- Type declarations

    private enum State {
        case Inactive
        case InputChar
        case ShowResults
    }

    // MARK:- Private properties

    private var currentEditorView: DVTSourceTextView? {
        let windowController = NSApplication.sharedApplication().keyWindow?.windowController() as? IDEWorkspaceWindowController
        let editor = windowController?.editorArea?.lastActiveEditorContext?.editor
        return editor?.mainScrollView?.contentView.documentView as? DVTSourceTextView
    }

    private lazy var inputTextField = NSTextField()

    private var state = State.Inactive

    // MARK:- Internal methods

    func toggle() {

    }

    // MARK:- Private methods

    private func showTextField() {

        if let editorView = currentEditorView {

            let textFieldSize = NSSize(width: 20, height: 20)
            let textFieldRect = NSRect(origin: editorView.cursorPosition, size: textFieldSize)

            inputTextField.frame = textFieldRect

            editorView.addSubview(inputTextField)

            let success = inputTextField.becomeFirstResponder()
        }
    }

    private func hideTextField() {
        inputTextField.removeFromSuperview()
    }

}

Implement single char text field delegate

//
//  JumpController.swift
//  XJump
//
//  Created by Victor Shamanov on 5/26/15.
//  Copyright (c) 2015 Victor Shamanov. All rights reserved.
//

import AppKit

final class JumpController: SingleCharTextFieldDelegate {

    // MARK:- Type declarations

    private enum State {
        case Inactive
        case InputChar
        case ShowResults
    }

    // MARK:- Private properties

    private var currentEditorView: DVTSourceTextView? {
        let windowController = NSApplication.sharedApplication().keyWindow?.windowController() as? IDEWorkspaceWindowController
        let editor = windowController?.editorArea?.lastActiveEditorContext?.editor
        return editor?.mainScrollView?.contentView.documentView as? DVTSourceTextView
    }

    private let inputTextField = SingleCharTextField()
    private var state = State.Inactive

    // MARK:- Instantiation

    init() {
        inputTextField.charInputDelegate = self
    }

    // MARK:- Internal methods

    func toggle() {

    }

    // MARK:- Private methods

    private func showTextField() {

        if let editorView = currentEditorView {

            let textFieldSize = NSSize(width: 20, height: 20)
            let textFieldRect = NSRect(origin: editorView.cursorPosition, size: textFieldSize)

            inputTextField.frame = textFieldRect

            editorView.addSubview(inputTextField)

            if inputTextField.becomeFirstResponder() {
                state = .InputChar
            } else {
                state = .Inactive
                hideTextField()
            }
        }
    }

    private func hideTextField() {
        inputTextField.removeFromSuperview()
    }

    private func showResults(char: Character) {
        state = .ShowResults

    }

    // MARK:- SingleCharTextFieldDelegate

    func didRecieveChar(textField: SingleCharTextField, char: Character) {
        hideTextField()
        showResults(char)
    }

}