//
//  SGLocationManager.swift
//  Pods
//
//  Created by Adrian Schoenig on 14/7/17.
//
//

import Foundation

// SGPermissionManager overrides

extension SGLocationManager {

  open override func featureIsAvailable() -> Bool {
    return true
  }

  open override func authorizationRestrictionsApply() -> Bool {
    return true
  }

  open override func authorizationStatus() -> SGAuthorizationStatus {
    guard CLLocationManager.locationServicesEnabled() else {
      return .denied
    }

    guard !authorizationRestrictionsApply() else {
      return .authorized
    }

    switch CLLocationManager.authorizationStatus() {
    case .authorizedAlways, .authorizedWhenInUse: return .authorized
    case .denied: return .denied
    case .restricted: return .restricted
    case .notDetermined: return .notDetermined
    }
  }

  open override func authorizationAlertText() -> String! {
    return NSLocalizedString("Location services are required to use this feature. Please go to the Settings app > Privacy > Location Services, make sure they are turned on and authorise this app.", tableName: "Shared", bundle: SGStyleManager.bundle(), comment: "Location iOS authorisation needed text")
  }

}

Fix for bad guard statement

//
//  SGLocationManager.swift
//  Pods
//
//  Created by Adrian Schoenig on 14/7/17.
//
//

import Foundation

// SGPermissionManager overrides

extension SGLocationManager {

  open override func featureIsAvailable() -> Bool {
    return true
  }

  open override func authorizationRestrictionsApply() -> Bool {
    return true
  }

  open override func authorizationStatus() -> SGAuthorizationStatus {
    guard CLLocationManager.locationServicesEnabled() else {
      return .denied
    }

    guard authorizationRestrictionsApply() else {
      return .authorized
    }

    switch CLLocationManager.authorizationStatus() {
    case .authorizedAlways, .authorizedWhenInUse: return .authorized
    case .denied: return .denied
    case .restricted: return .restricted
    case .notDetermined: return .notDetermined
    }
  }

  open override func authorizationAlertText() -> String! {
    return NSLocalizedString("Location services are required to use this feature. Please go to the Settings app > Privacy > Location Services, make sure they are turned on and authorise this app.", tableName: "Shared", bundle: SGStyleManager.bundle(), comment: "Location iOS authorisation needed text")
  }

}


//
//  TimelineView.swift
//  NetNewsWire
//
//  Created by Maurice Parker on 6/30/20.
//  Copyright © 2020 Ranchero Software. All rights reserved.
//

import SwiftUI

struct TimelineView: View {

	@EnvironmentObject private var timelineModel: TimelineModel
	@State var navigate = false

	@ViewBuilder var body: some View {
		#if os(macOS)
		ZStack {
			NavigationLink(destination: ArticleContainerView(articles: timelineModel.selectedArticles), isActive: $navigate) {
				EmptyView()
			}.hidden()
			List(timelineModel.timelineItems, selection: $timelineModel.selectedArticleIDs) { timelineItem in
				buildTimelineItemNavigation(timelineItem)
			}
		}
		.onChange(of: timelineModel.selectedArticleIDs) { value in
			navigate = !timelineModel.selectedArticleIDs.isEmpty
		}
		#else
		List(timelineModel.timelineItems) { timelineItem in
			buildTimelineItemNavigation(timelineItem)
		}
		#endif
    }

	func buildTimelineItemNavigation(_ timelineItem: TimelineItem) -> some View {
		#if os(macOS)
		return TimelineItemView(timelineItem: timelineItem)
		#else
		return ZStack {
			TimelineItemView(timelineItem: timelineItem)
			NavigationLink(destination: ArticleContainerView(articles: timelineModel.selectedArticles),
						   tag: timelineItem.article.articleID,
						   selection: $timelineModel.selectedArticleID) {
				EmptyView()
			}.buttonStyle(PlainButtonStyle())
		}
		#endif
	}

}

Refactor timeline code to be more clear

//
//  TimelineView.swift
//  NetNewsWire
//
//  Created by Maurice Parker on 6/30/20.
//  Copyright © 2020 Ranchero Software. All rights reserved.
//

import SwiftUI

struct TimelineView: View {

	@EnvironmentObject private var timelineModel: TimelineModel
	@State var navigate = false

	@ViewBuilder var body: some View {
		#if os(macOS)
		ZStack {
			NavigationLink(destination: ArticleContainerView(articles: timelineModel.selectedArticles), isActive: $navigate) {
				EmptyView()
			}.hidden()
			List(timelineModel.timelineItems, selection: $timelineModel.selectedArticleIDs) { timelineItem in
				TimelineItemView(timelineItem: timelineItem)
			}
		}
		.onChange(of: timelineModel.selectedArticleIDs) { value in
			navigate = !timelineModel.selectedArticleIDs.isEmpty
		}
		#else
		List(timelineModel.timelineItems) { timelineItem in
			ZStack {
				TimelineItemView(timelineItem: timelineItem)
				NavigationLink(destination: ArticleContainerView(articles: timelineModel.selectedArticles),
							   tag: timelineItem.article.articleID,
							   selection: $timelineModel.selectedArticleID) {
					EmptyView()
				}.buttonStyle(PlainButtonStyle())
			}
		}
		#endif
    }

}


//
//  Created by Pierluigi Cifani on 01/08/2018.
//

import UIKit

@objc(BSWGradientView)
open class GradientView: UIImageView {
    override open func layoutSubviews() {
        super.layoutSubviews()
        image = GradientFactory.transparentGradient(size: self.frame.size)
    }
}

public enum GradientFactory {
    public static func transparentGradient(size: CGSize) -> UIImage {
        let colorTop = UIColor(white: 0.1, alpha: 0.5)
        let colorBottom = UIColor(white: 0.1, alpha: 0.0)
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        gradientLayer.colors = [colorTop, colorBottom].map {$0.cgColor}
        gradientLayer.locations = [0.0, 1.0]
        return UIImage.image(fromGradientLayer: gradientLayer)
    }
}

Add a better API for creating gradients

//
//  Created by Pierluigi Cifani on 01/08/2018.
//

import UIKit

@objc(BSWGradientView)
open class GradientView: UIImageView {

    public enum Kind {
        case transparent
        case colors([UIColor])
    }

    public let kind: Kind

    public init(kind: Kind) {
        self.kind = kind
        super.init(frame: .zero)
    }

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

    override open func layoutSubviews() {
        super.layoutSubviews()
        switch kind {
        case .colors(let colors):
            image = GradientFactory.gradientFromColors(colors: colors, size: self.frame.size)
        case .transparent:
            image = GradientFactory.transparentGradient(size: self.frame.size)
        }
    }
}

public enum GradientFactory {

    public static func transparentGradient(size: CGSize) -> UIImage {
        let colorTop = UIColor(white: 0.1, alpha: 0.5)
        let colorBottom = UIColor(white: 0.1, alpha: 0.0)
        return gradientFromColors(colors: [colorTop, colorBottom], size: size)
    }

    public static func gradientFromColors(colors: [UIColor], size: CGSize) -> UIImage {
        let gradientLayer = gradientLayerFromColors(colors: colors, size: size)
        return UIImage.image(fromGradientLayer: gradientLayer)
    }

    public static func gradientLayerFromColors(colors: [UIColor], size: CGSize) -> CAGradientLayer {
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        gradientLayer.colors = colors.map {$0.cgColor}
        gradientLayer.locations = [0.0, 1.0]
        gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
        return gradientLayer
    }
}


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

import Prelude
import Tesseract
import XCTest

final class ValueTests: XCTestCase {
	func testConstantValueDestructuresToSomeOfSameType() {
		assertEqual(Value(constant: 1).constant(), 1)
	}

	func testConstantValueDestructuresToNoneOfDifferentType() {
		assertNil(Value(constant: 1).constant() as ()?)
	}

	func testFunctionValueDestructuresAsConstantToNone() {
		assertNil(Value(function: id as Any -> Any).constant() as Any?)
	}

	func testFunctionValueDestructuresToSomeOfSameType() {
		assertNotNil(Value(function: id as Any -> Any).function() as (Any -> Any)?)
	}

	func testFunctionValueDestructuresToNoneOfDifferentType() {
		assertNil(Value(function: id as Any -> Any).function() as (Int -> Int)?)
	}
}

Test constant destructuring as function.

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

import Prelude
import Tesseract
import XCTest

final class ValueTests: XCTestCase {
	func testConstantValueDestructuresToSomeOfSameType() {
		assertEqual(Value(constant: 1).constant(), 1)
	}

	func testConstantValueDestructuresToNoneOfDifferentType() {
		assertNil(Value(constant: 1).constant() as ()?)
	}

	func testFunctionValueDestructuresAsConstantToNone() {
		assertNil(Value(function: id as Any -> Any).constant() as Any?)
	}

	func testFunctionValueDestructuresToSomeOfSameType() {
		assertNotNil(Value(function: id as Any -> Any).function() as (Any -> Any)?)
	}

	func testFunctionValueDestructuresToNoneOfDifferentType() {
		assertNil(Value(function: id as Any -> Any).function() as (Int -> Int)?)
	}

	func testConstantValueDestructuresAsFunctionToNone() {
		assertNil(Value(constant: ()).function() as (Any -> Any)?)
	}
}


//
//  LayoutViewPosition.swift
//  NotAutoLayout
//
//  Created by 史翔新 on 2017/02/09.
//  Copyright © 2017年 史翔新. All rights reserved.
//

import Foundation

extension LayoutView {

	public enum Position {

		public enum CustomValue {
			case absolute(CGFloat)
			case relative(CGFloat)
		}

		case absolute(CGRect)
		case relative(CGRect)
		case custom(x: CustomValue, y: CustomValue, width: CustomValue, height: CustomValue)

	}

}

extension LayoutView.Position.CustomValue {

	func absoluteValue(in length: CGFloat) -> CGFloat {

		switch self {
		case .absolute(let value):
			return value

		case .relative(let value):
			return value * length
		}

	}

}

extension LayoutView.Position {

	func absoluteRect(in size: CGSize) -> CGRect {

		switch self {
		case .absolute(let rect):
			return rect

		case .relative(let rect):
			return rect.absoluteRectApplied(to: size)

		case .custom(x: let x, y: let y, width: let width, height: let height):
			let x = x.absoluteValue(in: size.width)
			let y = y.absoluteValue(in: size.height)
			let width = width.absoluteValue(in: size.width)
			let height = height.absoluteValue(in: size.height)
			return CGRect(x: x, y: y, width: width, height: height)
		}

	}

}

Remove old LayoutView.Position.CustomValue enum, and use LayoutView.Position.custom((CGSize) -> CGRect) instead, which is much more powerful and customizable

//
//  LayoutViewPosition.swift
//  NotAutoLayout
//
//  Created by 史翔新 on 2017/02/09.
//  Copyright © 2017年 史翔新. All rights reserved.
//

import Foundation

extension LayoutView {

	public enum Position {

		case absolute(CGRect)
		case relative(CGRect)
		case custom((CGSize) -> CGRect)

	}

}

extension LayoutView.Position {

	func absoluteRect(in size: CGSize) -> CGRect {

		switch self {
		case .absolute(let rect):
			return rect

		case .relative(let rect):
			return rect.absoluteRectApplied(to: size)

		case .custom(let rectClosure):
			return rectClosure(size)
		}

	}

}


//
//  Luminous+Audio.swift
//  Luminous
//
//  Created by Andrea Mario Lufino on 10/11/2019.
//

import AVFoundation
import Foundation

extension Luminous {

    // MARK: Audio

    public struct Audio {

        /// A value in the range `0.0` to `1.0`, with `0.0` representing the minimum volume and `1.0` representing the maximum volume.
        public static var currentAudioOutputVolume: Double? {

            let audioSession = AVAudioSession.sharedInstance()
            do {
                try audioSession.setActive(true)
                let volume = audioSession.outputVolume
                try audioSession.setActive(false)
                return Double(volume)
            } catch {
                print("Luminous - Failed to activate audio session.")
                return nil
            }
        }

        /// The value is true when another application with a non-mixable audio session is playing audio.
        public static var secondaryAudioShouldBeSilencedHint: Bool {

            return AVAudioSession.sharedInstance().secondaryAudioShouldBeSilencedHint
        }
    }
}

Fix for playback pausing when getting volume

//
//  Luminous+Audio.swift
//  Luminous
//
//  Created by Andrea Mario Lufino on 10/11/2019.
//

import AVFoundation
import Foundation

extension Luminous {

    // MARK: Audio

    public struct Audio {

        /// A value in the range `0.0` to `1.0`, with `0.0` representing the minimum volume and `1.0` representing the maximum volume.
        public static var currentAudioOutputVolume: Double? {

            let audioSession = AVAudioSession.sharedInstance()
            do {
                try audioSession.setActive(true)
                let volume = audioSession.outputVolume
                return Double(volume)
            } catch {
                print("Luminous - Failed to activate audio session.")
                return nil
            }
        }

        /// The value is true when another application with a non-mixable audio session is playing audio.
        public static var secondaryAudioShouldBeSilencedHint: Bool {

            return AVAudioSession.sharedInstance().secondaryAudioShouldBeSilencedHint
        }
    }
}


//
//  TableViewCell.swift
//  AddressBook
//
//  Created by Alexey Belkevich on 7/31/14.
//  Copyright (c) 2014 alterplay. All rights reserved.
//

import Foundation

class TableViewCell: DTTableViewCell {

    override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
        super.init(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier)
    }

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

    override func updateWithModel(model: AnyObject!) {
        let contact = model as APContact
        self.imageView.image = contact.thumbnail
        self.textLabel.text = self.contactName(contact)
        self.detailTextLabel?.text = self.contactPhones(contact)
    }

    func contactName(contact :APContact) -> String {
        if contact.firstName != nil && contact.lastName != nil {
            return "\(contact.firstName) \(contact.lastName)"
        }
        else if contact.firstName != nil || contact.lastName != nil {
            return (contact.firstName != nil) ? "\(contact.firstName)" : "\(contact.lastName)"
        }
        else {
            return "Unnamed contact"
        }
    }

    func contactPhones(contact :APContact) -> String {
        if let phones = contact.phones {
            let array = phones as NSArray
            return array.componentsJoinedByString(" ")
        }
        return "No phone"
    }
}

Fix build error in Swift example project

//
//  TableViewCell.swift
//  AddressBook
//
//  Created by Alexey Belkevich on 7/31/14.
//  Copyright (c) 2014 alterplay. All rights reserved.
//

import Foundation

class TableViewCell: DTTableViewCell {

    override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
        super.init(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier)
    }

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

    override func updateWithModel(model: AnyObject!) {
        let contact = model as APContact
        self.imageView?.image = contact.thumbnail
        self.textLabel?.text = self.contactName(contact)
        self.detailTextLabel?.text = self.contactPhones(contact)
    }

    func contactName(contact :APContact) -> String {
        if contact.firstName != nil && contact.lastName != nil {
            return "\(contact.firstName) \(contact.lastName)"
        }
        else if contact.firstName != nil || contact.lastName != nil {
            return (contact.firstName != nil) ? "\(contact.firstName)" : "\(contact.lastName)"
        }
        else {
            return "Unnamed contact"
        }
    }

    func contactPhones(contact :APContact) -> String {
        if let phones = contact.phones {
            let array = phones as NSArray
            return array.componentsJoinedByString(" ")
        }
        return "No phone"
    }
}


import Aztec
import Foundation

public extension Element {
    static let gutenpack = Element("gutenpack")
}

public class GutenpackConverter: ElementConverter {

    // MARK: - ElementConverter

    public func convert(
        _ element: ElementNode,
        inheriting attributes: [NSAttributedStringKey: Any],
        childrenSerializer serializeChildren: ChildrenSerializer) -> NSAttributedString {

        precondition(element.type == .gutenpack)

        let attachment = HTMLAttachment()
        let decoder = GutenbergAttributeDecoder()
        if let content = decoder.decodedAttribute(named: GutenbergAttributeNames.selfCloser, from: element) {
            attachment.rawHTML = String(content.prefix(upTo: content.index(before:content.endIndex)))
            attachment.rootTagName = String(content.trimmingCharacters(in: .whitespacesAndNewlines).prefix(while: { (char) -> Bool in
                char != " "
            }))
        } else {
            let serializer = HTMLSerializer()
            attachment.rootTagName = element.name
            attachment.rawHTML = serializer.serialize(element)
        }

            return NSAttributedString(attachment: attachment, attributes: attributes)
    }

}

Use subscript on string instead of method.

import Aztec
import Foundation

public extension Element {
    static let gutenpack = Element("gutenpack")
}

public class GutenpackConverter: ElementConverter {

    // MARK: - ElementConverter

    public func convert(
        _ element: ElementNode,
        inheriting attributes: [NSAttributedStringKey: Any],
        childrenSerializer serializeChildren: ChildrenSerializer) -> NSAttributedString {

        precondition(element.type == .gutenpack)

        let attachment = HTMLAttachment()
        let decoder = GutenbergAttributeDecoder()
        if let content = decoder.decodedAttribute(named: GutenbergAttributeNames.selfCloser, from: element) {
            attachment.rawHTML = String(content[content.startIndex ..< content.index(before: content.endIndex)])
            attachment.rootTagName = String(content.trimmingCharacters(in: .whitespacesAndNewlines).prefix(while: { (char) -> Bool in
                char != " "
            }))
        } else {
            let serializer = HTMLSerializer()
            attachment.rootTagName = element.name
            attachment.rawHTML = serializer.serialize(element)
        }

            return NSAttributedString(attachment: attachment, attributes: attributes)
    }

}


//
//  AppTheme.swift
//  LobstersReader
//
//  Created by Colin Drake on 5/28/17.
//  Copyright © 2017 Colin Drake. All rights reserved.
//

import UIKit

/// Define app-specific colors.
extension UIColor {
    static let lobstersRed = UIColor.red
}

/// Application themer.
final class AppTheme {
    static func apply() {
        UITabBar.appearance().tintColor = .lobstersRed
        UIBarButtonItem.appearance().tintColor = .lobstersRed
    }
}

Use red color for navigation bars

//
//  AppTheme.swift
//  LobstersReader
//
//  Created by Colin Drake on 5/28/17.
//  Copyright © 2017 Colin Drake. All rights reserved.
//

import UIKit

/// Define app-specific colors.
extension UIColor {
    static let lobstersRed = UIColor.red
}

/// Application themer.
final class AppTheme {
    static func apply() {
        UITabBar.appearance().tintColor = .lobstersRed
        UIBarButtonItem.appearance().tintColor = .lobstersRed
        UINavigationBar.appearance().tintColor = .lobstersRed
    }
}


//
//  ExampleFolioReaderContainer
//  StoryboardExample
//
//  Created by Panajotis Maroungas on 18/08/16.
//  Copyright © 2016 FolioReader. All rights reserved.
//

import UIKit
import FolioReaderKit

class ExampleFolioReaderContainer: FolioReaderContainer {

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

        let config = FolioReaderConfig()
        config.scrollDirection = .horizontalWithVerticalContent
		config.shouldHideNavigationOnTap = false

		// Print the chapter ID if one was clicked
		// A chapter in "The Silver Chair" looks like this "<section class="chapter" title="Chapter I" epub:type="chapter" id="id70364673704880">"
		// To knwo if a user tapped on a chapter we can listen to events on the class "chapter" and receive the id value
		let listener = ClassBasedOnClickListener(schemeName: "chapterTapped", className: "chapter", parameterName: "id", onClickAction: { (parameterContent: String?) in
			print("chapter with id: " + (parameterContent ?? "-") + " clicked")
		})
		config.classBasedOnClickListeners.append(listener)

        guard let bookPath = NSBundle.mainBundle().pathForResource("The Silver Chair", ofType: "epub") else { return }
        setupConfig(config, epubPath: bookPath)
	}
}

Use valid URL scheme name

//
//  ExampleFolioReaderContainer
//  StoryboardExample
//
//  Created by Panajotis Maroungas on 18/08/16.
//  Copyright © 2016 FolioReader. All rights reserved.
//

import UIKit
import FolioReaderKit

class ExampleFolioReaderContainer: FolioReaderContainer {

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

        let config = FolioReaderConfig()
        config.scrollDirection = .horizontalWithVerticalContent
		config.shouldHideNavigationOnTap = false

		// Print the chapter ID if one was clicked
		// A chapter in "The Silver Chair" looks like this "<section class="chapter" title="Chapter I" epub:type="chapter" id="id70364673704880">"
		// To knwo if a user tapped on a chapter we can listen to events on the class "chapter" and receive the id value
		let listener = ClassBasedOnClickListener(schemeName: "chaptertapped", className: "chapter", parameterName: "id", onClickAction: { (parameterContent: String?) in
			print("chapter with id: " + (parameterContent ?? "-") + " clicked")
		})
		config.classBasedOnClickListeners.append(listener)

        guard let bookPath = NSBundle.mainBundle().pathForResource("The Silver Chair", ofType: "epub") else { return }
        setupConfig(config, epubPath: bookPath)
	}
}


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

}

Add thumbnailForAttachment in 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
    config.wall.thumbnailForAttachment = {
      (attachment: Attachment, size: CGSize) -> URLStringConvertible? in
      var string: URLStringConvertible?

      if let thumbnail = attachment.thumbnail {
        string = String(format: thumbnail.string, Int(size.width), Int(size.height))
      }

      return string
    }

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

}


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

func rdar26564101(a: [Double], m: Double) -> Double {
  return Double(Array(0...a.count - 1).reduce(0) { $0 + $1 - m })
  // expected-error@-1 {{cannot convert value of type}}
}

Disable a test on Linux at swift_test_mode_optimize_none.

// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1
// REQUIRES: tools-release,no_asan
// UNSUPPORTED: swift_test_mode_optimize_none && OS=linux-gnu

func rdar26564101(a: [Double], m: Double) -> Double {
  return Double(Array(0...a.count - 1).reduce(0) { $0 + $1 - m })
  // expected-error@-1 {{cannot convert value of type}}
}


//
//  KeyboardButtonRowComponent.swift
//  KeyboardKit
//
//  Created by Daniel Saidi on 2019-04-28.
//  Copyright © 2019 Daniel Saidi. All rights reserved.
//

/*

 A keyboard button row component is a view that can be added
 to a keyboard button row's horizontal stack view.

 The `KeyboardButtonRow`'s stack view uses `.fillEqually` by
 default, but you can change it's behavior at any time. When
 you do, you may have to set a hard width for each component.

 */

import UIKit

public protocol KeyboardButtonRowComponent: UIView {

    var widthConstraint: NSLayoutConstraint? { get set }
}

public extension KeyboardButtonRowComponent {

    var width: CGFloat {
        get { return widthConstraint?.constant ?? intrinsicContentSize.width }
        set { setWidthConstraint(to: newValue) }
    }
}

private extension KeyboardButtonRowComponent {

    func setWidthConstraint(to width: CGFloat) {
        if let widthConstraint = widthConstraint {
            widthConstraint.constant = width
        } else {
            widthConstraint = widthAnchor.constraint(equalToConstant: width)
        }
        widthConstraint?.isActive = true
    }
}

Clean up width constraint logic

//
//  KeyboardButtonRowComponent.swift
//  KeyboardKit
//
//  Created by Daniel Saidi on 2019-04-28.
//  Copyright © 2019 Daniel Saidi. All rights reserved.
//

/*

 A keyboard button row component is a view that can be added
 to a keyboard button row's horizontal stack view.

 The `KeyboardButtonRow`'s stack view uses `.fillEqually` by
 default, but you can change it's behavior at any time. When
 you do, you may have to set a hard width for each component.

 */

import UIKit

public protocol KeyboardButtonRowComponent: UIView {

    var widthConstraint: NSLayoutConstraint? { get set }
}

public extension KeyboardButtonRowComponent {

    var width: CGFloat {
        get { return widthConstraint?.constant ?? intrinsicContentSize.width }
        set { setWidth(to: newValue) }
    }
}

private extension KeyboardButtonRowComponent {

    func setWidth(to width: CGFloat) {
        widthConstraint = widthConstraint ?? widthAnchor.constraint(equalToConstant: width)
        widthConstraint?.constant = width
        widthConstraint?.isActive = true
    }
}


import Foundation

class MHomeStrategyWaitingLocation:MHomeStrategy
{
    private var delegate:MHomeStrategyWaitingLocationDelegate?

    deinit
    {
        delegate?.locationManager.stopUpdatingLocation()
        delegate?.locationManager.delegate = nil
    }

    override func nextStep()
    {
        super.nextStep()

        guard

            let controller:CHome = self.controller

        else
        {
            return
        }

        delegate = MHomeStrategyWaitingLocationDelegate(
            controller:controller)
    }
}

Call delegate on main thread

import Foundation

class MHomeStrategyWaitingLocation:MHomeStrategy
{
    private var delegate:MHomeStrategyWaitingLocationDelegate?

    deinit
    {
        delegate?.locationManager.stopUpdatingLocation()
        delegate?.locationManager.delegate = nil
    }

    override func nextStep()
    {
        super.nextStep()

        DispatchQueue.main.async
        { [weak self] in

            self?.factoryDelegate()
        }
    }

    //MARK: private

    private func factoryDelegate()
    {
        guard

            let controller:CHome = self.controller

        else
        {
            return
        }

        delegate = MHomeStrategyWaitingLocationDelegate(
            controller:controller)
    }
}


//
//  UIViewPropertyAnimatorTests+Rx.swift
//  RxSwiftExt
//
//  Created by Thibault Wittemberg on 3/4/18.
//  Copyright © 2017 RxSwift Community. All rights reserved.
//

import XCTest
import RxSwift
import RxCocoa
import RxSwiftExt
import UIKit

class UIViewPropertyAnimatorTests: XCTestCase {
    let disposeBag = DisposeBag()

    @available(iOS 10.0, *)
    func testAnimationCompleted() {
        let expectations = expectation(description: "Animation completed")

        let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        let animator = UIViewPropertyAnimator(duration: 0.5, curve: .linear) {
            view.transform = CGAffineTransform(translationX: 100, y: 100)
        }

        animator
            .rx.animate()
            .subscribe(onCompleted: {
                XCTAssertEqual(100, view.frame.origin.x)
                XCTAssertEqual(100, view.frame.origin.y)
                expectations.fulfill()
            })
            .disposed(by: self.disposeBag)

        waitForExpectations(timeout: 1)
    }
}

Add UIViewPropertyAnimator fractionComplete binder tests

//
//  UIViewPropertyAnimatorTests+Rx.swift
//  RxSwiftExt
//
//  Created by Thibault Wittemberg on 3/4/18.
//  Copyright © 2017 RxSwift Community. All rights reserved.
//

import XCTest
import RxSwift
import RxCocoa
import RxSwiftExt
import RxTest
import UIKit

class UIViewPropertyAnimatorTests: XCTestCase {

    var disposeBag: DisposeBag!

    override func setUp() {
        disposeBag = DisposeBag()
    }

    @available(iOS 10.0, *)
    func testAnimationCompleted() {
        let expectations = expectation(description: "Animation completed")

        let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        let animator = UIViewPropertyAnimator(duration: 0.5, curve: .linear) {
            view.transform = CGAffineTransform(translationX: 100, y: 100)
        }

        animator
            .rx.animate()
            .subscribe(onCompleted: {
                XCTAssertEqual(100, view.frame.origin.x)
                XCTAssertEqual(100, view.frame.origin.y)
                expectations.fulfill()
            })
            .disposed(by: disposeBag)

        waitForExpectations(timeout: 1)
    }

    @available(iOS 10.0, *)
    func testBindToFractionCompleted() {
        let animator = UIViewPropertyAnimator(
            duration: 0, curve: .linear, animations: { }
        )

        let subject = PublishSubject<CGFloat>()

        subject
            .bind(to: animator.rx.fractionComplete)
            .disposed(by: disposeBag)

        subject.onNext(0.3)
        XCTAssertEqual(animator.fractionComplete, 0.3)

        subject.onNext(0.5)
        XCTAssertEqual(animator.fractionComplete, 0.5)
    }
}


//
//  UserDefaults.swift
//  P3Foundation
//
//  Created by Oscar Swanros on 6/15/16.
//  Copyright © 2016 Pacific3. All rights reserved.
//

private let userDefaults = UserDefaults.standard()

extension UserDefaults {
    // MARK: - Get Values
    static func p3_getString(key: String) -> String {
        let s = userDefaults.object(forKey: key) as? String
        if let s = s {
            return s
        }

        return ""
    }

    static func p3_getBool(key: String) -> Bool {
        return userDefaults.bool(forKey: key)
    }

    static func p3_getInt(key: String) -> Int {
        return userDefaults.integer(forKey: key)
    }

    // MARK: - Set Values
    static func p3_setString(key: String, value: String) -> Bool {
        userDefaults.set(value, forKey: key)
        return userDefaults.synchronize()
    }

    static func p3_setBool(key: String, value: Bool) -> Bool {
        userDefaults.set(value, forKey: key)
        return userDefaults.synchronize()
    }

    static func p3_setInt(key: String, value: Int) -> Bool {
        userDefaults.set(value, forKey: key)
        return userDefaults.synchronize()
    }
}

Add discardableResult attributes to setters for user defaults

//
//  UserDefaults.swift
//  P3Foundation
//
//  Created by Oscar Swanros on 6/15/16.
//  Copyright © 2016 Pacific3. All rights reserved.
//

private let userDefaults = UserDefaults.standard()

extension UserDefaults {
    // MARK: - Get Values
    static func p3_getString(key: String) -> String {
        let s = userDefaults.object(forKey: key) as? String
        if let s = s {
            return s
        }

        return ""
    }

    static func p3_getBool(key: String) -> Bool {
        return userDefaults.bool(forKey: key)
    }

    static func p3_getInt(key: String) -> Int {
        return userDefaults.integer(forKey: key)
    }

    // MARK: - Set Values
    @discardableResult
    static func p3_setString(key: String, value: String) -> Bool {
        userDefaults.set(value, forKey: key)
        return userDefaults.synchronize()
    }

    @discardableResult
    static func p3_setBool(key: String, value: Bool) -> Bool {
        userDefaults.set(value, forKey: key)
        return userDefaults.synchronize()
    }

    @discardableResult
    static func p3_setInt(key: String, value: Int) -> Bool {
        userDefaults.set(value, forKey: key)
        return userDefaults.synchronize()
    }
}


extension String: Error {
  public func print(terminator: String = "") {
    Swift.print(self, terminator: terminator)
  }
}

Add Array transform: mutating versions of map

extension String: Error {
  public func print(terminator: String = "") {
    Swift.print(self, terminator: terminator)
  }
}

extension Array {
  public mutating func transform(by transforming: (Element) throws -> Element) rethrows {
    for index in 0..<count {
      self[index] = try transforming(self[index])
    }
  }

  public mutating func transform<S: Sequence>(at indices: S, by transforming: (Element) throws -> Element) rethrows
  where Index == S.Iterator.Element {
    for index in indices {
      self[index] = try transforming(self[index])
    }
  }
}


//
//  SWCraftMu-KataBowling-160527-strikes.swift
//  SWCraftMu-KataBowling-160527
//
//  Created by Jose on 29/5/16.
//  Copyright © 2016 ByBDesigns. All rights reserved.
//

import XCTest
@testable import SWCraftMu_KataBowling_160527

class SWCraftMu_KataBowling_160527_strikes: XCTestCase {

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

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

//    func testExample() {
//        // This is an example of a functional test case.
//        // Use XCTAssert and related functions to verify your tests produce the correct results.
//    }
//
//    func testPerformanceExample() {
//        // This is an example of a performance test case.
//        self.measureBlock {
//            // Put the code you want to measure the time of here.
//        }
//    }

	func testAllStrikes() {
		let counter = BowlingCounter("XXXXXXXXXXXX")

		XCTAssert(counter.score == 30*10)
	}
}

Test fallo: solo primer strike, resto fallos

//
//  SWCraftMu-KataBowling-160527-strikes.swift
//  SWCraftMu-KataBowling-160527
//
//  Created by Jose on 29/5/16.
//  Copyright © 2016 ByBDesigns. All rights reserved.
//

import XCTest
@testable import SWCraftMu_KataBowling_160527

class SWCraftMu_KataBowling_160527_strikes: XCTestCase {

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

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

//    func testExample() {
//        // This is an example of a functional test case.
//        // Use XCTAssert and related functions to verify your tests produce the correct results.
//    }
//
//    func testPerformanceExample() {
//        // This is an example of a performance test case.
//        self.measureBlock {
//            // Put the code you want to measure the time of here.
//        }
//    }

	func testAllStrikes() {
		let counter = BowlingCounter("XXXXXXXXXXXX")

		XCTAssert(counter.score == 30*10)
	}

	func testOnlyFirstStrike() {
		let counter = BowlingCounter("X------------------")

		XCTAssert(counter.score == 10)
	}
}


import Foundation

///
/// Using class so it can be shared even if
/// it appears to be a field in a class.
///
class Mutex {

    ///
    /// The mutex instance.
    ///
    private var mutex = pthread_mutex_t()

    ///
    /// Initialization
    ///
    init() {
        pthread_mutex_init(&mutex, nil)
    }

    ///
    /// Running the supplied closure synchronously.
    ///
    /// - Parameter closure: the closure to run
    /// - Returns: the value returned by the closure
    /// - Throws: the exception populated by the closure run
    ///
    @discardableResult
    func synchronized<R>(closure: () throws -> R) rethrows -> R {
        pthread_mutex_lock(&mutex)
        defer {
            pthread_mutex_unlock(&mutex)
        }
        return try closure()
    }

    deinit {
        // free the mutex resource
        pthread_mutex_destroy(&mutex)
    }
}

Use crossplatform semaphore instead of unsafe raw pthread_mutex_t

import Foundation

///
/// Using class so it can be shared even if
/// it appears to be a field in a class.
///
class Mutex {
    ///
    /// The mutex instance.
    ///
    private let semaphore = DispatchSemaphore(value: 1)

    ///
    /// Running the supplied closure synchronously.
    ///
    /// - Parameter closure: the closure to run
    /// - Returns: the value returned by the closure
    /// - Throws: the exception populated by the closure run
    ///
    @discardableResult
    func synchronized<R>(closure: () throws -> R) rethrows -> R {
        semaphore.wait()
        defer {
            semaphore.signal()
        }
        return try closure()
    }
}


#!/usr/bin/env swiftshell

import SwiftShell

let filepath =  main.tempdirectory + "newfile.txt"

// File doesn't exist. Create it.
let file1 = try! open(forWriting: filepath)
file1.writeln("line 1")
file1.close()

// File does exist. Append it.
let file2 =  try! open(forWriting: filepath)
file2.writeln("line 2")
file2.close()

// Test file.
let file3 = try! open(filepath)
if file3.read() != "line 1\nline 2\n" {
	exit(errormessage: "newfile.txt should contain 'line 1\\n line 2\\n'." )
}

// File exists. Overwrite it.
let file4 = try! open(forWriting: filepath, overwrite: true)
file4.write("file now contains only this")
file4.close()

// Test file.
let file5 = try! open(filepath)
if file5.read() != "file now contains only this" {
	exit(errormessage: "newfile.txt should contain 'file now contains only this'." )
}

Remove a couple of double spaces.


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

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

// FIXME: Should be DW_TAG_interface_type
// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "IGiveOutInts"
// CHECK-SAME:             identifier: [[PT:"[^"]+"]]
protocol IGiveOutInts {
  func callMe() -> Int64
}

class SomeImplementor : IGiveOutInts {
  init() {}
  func callMe() -> Int64 { return 1 }
}

func printSomeNumbers(gen: IGiveOutInts) {
  var gen = gen
  // CHECK: !DILocalVariable(name: "gen", scope{{.*}} line: [[@LINE-1]]
  // CHECK: !DILocalVariable(name: "gen", arg: 1{{.*}} line: [[@LINE-3]]
  // CHECK-SAME:             type: ![[PT]]
  markUsed(gen.callMe())
}

var i1 : IGiveOutInts = SomeImplementor()

printSomeNumbers(i1)

Simplify this testcase while making it stricter.

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

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

public protocol IGiveOutInts {
  func callMe() -> Int64
}

// CHECK: define {{.*}}@_TF11protocolarg16printSomeNumbersFPS_12IGiveOutInts_T_
// CHECK: @llvm.dbg.declare(metadata %P11protocolarg12IGiveOutInts_* %
// CHECK-SAME:              metadata ![[VAR:.*]], metadata ![[EMPTY:.*]])
// CHECK: @llvm.dbg.declare(metadata %P11protocolarg12IGiveOutInts_** %
// CHECK-SAME:              metadata ![[ARG:.*]], metadata ![[DEREF:.*]])

// FIXME: Should be DW_TAG_interface_type
// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "IGiveOutInts"
// CHECK-SAME:             identifier: [[PT:"[^"]+"]]

public func printSomeNumbers(gen: IGiveOutInts) {
  var gen = gen
  // CHECK: ![[EMPTY]] = !DIExpression()
  // CHECK: ![[VAR]] = !DILocalVariable(name: "gen", {{.*}} line: [[@LINE-2]]
  // CHECK: ![[ARG]] = !DILocalVariable(name: "gen", arg: 1,
  // CHECK-SAME:                        line: [[@LINE-5]], type: ![[PT]]
  // CHECK: ![[DEREF]] = !DIExpression(DW_OP_deref)
  markUsed(gen.callMe())
}


//
//  NSNotificationCenterExtensions.swift
//  ReactiveCocoa
//
//  Created by Justin Spahr-Summers on 2014-07-03.
//  Copyright (c) 2014 GitHub, Inc. All rights reserved.
//

import Foundation

extension NSNotificationCenter {
	/// Returns a Signal of the latest posted notification that matches the
	/// given criteria.
	func rac_notifications(name: String? = nil, object: AnyObject? = nil) -> Signal<NSNotification?> {
		return Signal(initialValue: nil) { sink in
			// TODO: Figure out how to deregister from this.
			self.addObserverForName(name, object: object, queue: nil) { notification in
				sink.put(notification)
			}

			return ()
		}
	}
}

Stop observing notifications when Signal deallocs

//
//  NSNotificationCenterExtensions.swift
//  ReactiveCocoa
//
//  Created by Justin Spahr-Summers on 2014-07-03.
//  Copyright (c) 2014 GitHub, Inc. All rights reserved.
//

import Foundation

extension NSNotificationCenter {
	/// Returns a Signal of the latest posted notification that matches the
	/// given criteria.
	func rac_notifications(name: String? = nil, object: AnyObject? = nil) -> Signal<NSNotification?> {
		let disposable = ScopedDisposable(SerialDisposable())

		return Signal(initialValue: nil) { sink in
			let observer = self.addObserverForName(name, object: object, queue: nil) { notification in
				sink.put(notification)
			}

			disposable.innerDisposable.innerDisposable = ActionDisposable {
				self.removeObserver(observer)
			}

			return ()
		}
	}
}


//
//  Nodes.swift
//  Nodes
//
//  Created by Kasper Welner on 18/03/16.
//  Copyright © 2016 Nodes. All rights reserved.
//

import Foundation
import Blobfish

public struct BlobfishConfiguration {
    static func errorCodeMapping() -> [Int : Blobfish.AlamofireConfig.ErrorCategory] {
        return [
            441 : .token,
            442 : .token,
            443 : .token,
        ]
    }
}

Make Blobfish error configuration public

//
//  Nodes.swift
//  Nodes
//
//  Created by Kasper Welner on 18/03/16.
//  Copyright © 2016 Nodes. All rights reserved.
//

import Foundation
import Blobfish

public struct BlobfishConfiguration {
    public static func errorCodeMapping() -> [Int : Blobfish.AlamofireConfig.ErrorCategory] {
        return [
            441 : .token,
            442 : .token,
            443 : .token,
        ]
    }
}


// Shirley
// Written in 2015 by Nate Stedman <nate@natestedman.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and
// related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with
// this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.

@testable import Shirley
import ReactiveCocoa
import XCTest

class TransformSessionTests: XCTestCase
{
    func testTransformedValues()
    {
        let session = TransformSession(session: SquareSession(), flattenStrategy: .Concat, transform: { result in
            SignalProducer(value: result * 2)
        })

        XCTAssertEqual(session.producerForRequest(2).first()?.value, 8)
    }

    func testTransformedErrors()
    {
        let session = TransformSession(session: ErrorSession(), transform: { error in
            SignalProducer(error: TestError(value: error.value + 1))
        })

        XCTAssertEqual(session.producerForRequest(2).first()?.error?.value, 3)
    }
}

Fix test compilation re: transformError

// Shirley
// Written in 2015 by Nate Stedman <nate@natestedman.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and
// related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with
// this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.

@testable import Shirley
import ReactiveCocoa
import XCTest

class TransformSessionTests: XCTestCase
{
    func testTransformedValues()
    {
        let session = TransformSession(session: SquareSession(), flattenStrategy: .Concat, transform: { result in
            SignalProducer(value: result * 2)
        })

        XCTAssertEqual(session.producerForRequest(2).first()?.value, 8)
    }

    func testTransformedErrors()
    {
        let session = TransformSession(session: ErrorSession(), transformError: { error in
            SignalProducer(error: TestError(value: error.value + 1))
        })

        XCTAssertEqual(session.producerForRequest(2).first()?.error?.value, 3)
    }
}


//
//  Invitation.swift
//  GithubClient
//
//  Created by Eduardo Arenas on 2/18/18.
//  Copyright © 2018 GameChanger. All rights reserved.
//

import Foundation

public struct Invitation: Decodable {
  public let id: Int
  public let repository: Repository
  public let invetee: User
  public let inviter: User
  public let permissions: InvitationPermissions
  public let createdAt: Date
  public let url: String
  public let htmlUrl: String
}

Correct coding keys for invitation

//
//  Invitation.swift
//  GithubClient
//
//  Created by Eduardo Arenas on 2/18/18.
//  Copyright © 2018 GameChanger. All rights reserved.
//

import Foundation

public struct Invitation: Decodable {
  public let id: Int
  public let repository: Repository
  public let invetee: User
  public let inviter: User
  public let permissions: InvitationPermissions
  public let createdAt: Date
  public let url: String
  public let htmlUrl: String
}

extension Invitation {
  enum CodingKeys: String, CodingKey {
    case id
    case repository
    case invetee
    case inviter
    case permissions
    case createdAt = "created_at"
    case url
    case htmlUrl = "html_url"
  }
}


import UIKit

//HAX: work-around for iOS 9 infinite recursion loop bug with UIAlertController
// http://stackoverflow.com/a/36476346/135557 . Noticed while attempting 3d touch
// on link in reference panel.
extension UIAlertController {
    public override func shouldAutorotate() -> Bool {
        return true
    }
    public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.All
    }
}

public class WMFRotationRespectingTabBarController: UITabBarController {

    public override func shouldAutorotate() -> Bool {
        if let vc = self.presentedViewController {
            return vc.shouldAutorotate()
        } else if let vc = self.selectedViewController {
            return vc.shouldAutorotate()
        }else{
            return super.shouldAutorotate()
        }
    }

    public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        if let vc = self.presentedViewController {
            return vc.supportedInterfaceOrientations()
        } else if let vc = self.selectedViewController {
            return vc.supportedInterfaceOrientations()
        }else{
            return super.supportedInterfaceOrientations()
        }
    }

    public override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
        if let vc = self.presentedViewController {
            return vc.preferredInterfaceOrientationForPresentation()
        } else if let vc = self.selectedViewController {
            return vc.preferredInterfaceOrientationForPresentation()
        }else{
            return super.preferredInterfaceOrientationForPresentation()
        }
    }
}

Revert "Workaround for iOS 9 bug which can cause infinite recursion crash."

import UIKit

public class WMFRotationRespectingTabBarController: UITabBarController {

    public override func shouldAutorotate() -> Bool {
        if let vc = self.presentedViewController {
            return vc.shouldAutorotate()
        } else if let vc = self.selectedViewController {
            return vc.shouldAutorotate()
        }else{
            return super.shouldAutorotate()
        }
    }

    public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        if let vc = self.presentedViewController {
            return vc.supportedInterfaceOrientations()
        } else if let vc = self.selectedViewController {
            return vc.supportedInterfaceOrientations()
        }else{
            return super.supportedInterfaceOrientations()
        }
    }

    public override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
        if let vc = self.presentedViewController {
            return vc.preferredInterfaceOrientationForPresentation()
        } else if let vc = self.selectedViewController {
            return vc.preferredInterfaceOrientationForPresentation()
        }else{
            return super.preferredInterfaceOrientationForPresentation()
        }
    }
}


public struct GitHubLibraryConfigFile: Equatable {
    let type: GitHubLibraryConfigFileType
    let content: String?
}

extension GitHubLibraryConfigFile {
    static func carthage(content: String?) -> GitHubLibraryConfigFile { .init(type: .carthage, content: content) }
    static func mint(content: String?) -> GitHubLibraryConfigFile { .init(type: .mint, content: content) }
    static func licensePlist(content: String?) -> GitHubLibraryConfigFile { .init(type: .licensePlist, content: content) }
}

public enum GitHubLibraryConfigFileType: Int, CaseIterable {
    case carthage
    case mint
    case licensePlist
}

extension GitHubLibraryConfigFileType {
    func regexString(version: Bool) -> String {
        let pattern = "[\\w\\.\\-]+"
        switch self {
        case .carthage:
            let quotes = "\""
            return "github \(quotes)(\(pattern))/(\(pattern))\(quotes)" + (version ? " \(quotes)(\(pattern))\(quotes)" : "")
        case .mint:
            return "(\(pattern))/(\(pattern))" + (version ? "@(\(pattern))" : "")
        case .licensePlist:
            return "(\(pattern))/(\(pattern))" + (version ? " (\(pattern))" : "")
        }
    }
}

Fix build error for Xcode 10.1

public struct GitHubLibraryConfigFile: Equatable {
    let type: GitHubLibraryConfigFileType
    let content: String?
}

extension GitHubLibraryConfigFile {
    static func carthage(content: String?) -> GitHubLibraryConfigFile { return .init(type: .carthage, content: content) }
    static func mint(content: String?) -> GitHubLibraryConfigFile { return .init(type: .mint, content: content) }
    static func licensePlist(content: String?) -> GitHubLibraryConfigFile { return .init(type: .licensePlist, content: content) }
}

public enum GitHubLibraryConfigFileType: Int, CaseIterable {
    case carthage
    case mint
    case licensePlist
}

extension GitHubLibraryConfigFileType {
    func regexString(version: Bool) -> String {
        let pattern = "[\\w\\.\\-]+"
        switch self {
        case .carthage:
            let quotes = "\""
            return "github \(quotes)(\(pattern))/(\(pattern))\(quotes)" + (version ? " \(quotes)(\(pattern))\(quotes)" : "")
        case .mint:
            return "(\(pattern))/(\(pattern))" + (version ? "@(\(pattern))" : "")
        case .licensePlist:
            return "(\(pattern))/(\(pattern))" + (version ? " (\(pattern))" : "")
        }
    }
}


import XCTest

class TMHomeStrategyFactory:XCTestCase
{
}

Add test for status new

import XCTest
@testable import gattaca

class TMHomeStrategyFactory:XCTestCase
{
    private var controller:CHome?
    private var session:MSession?

    override func setUp()
    {
        super.setUp()

        let session:MSession = MSession()
        self.session = session

        controller = CHome(session:session)
    }

    //MARK: internal

    func testInit()
    {
        XCTAssertNotNil(
            session,
            "failed to create session")

        XCTAssertNotNil(
            controller,
            "failed to create controller")
    }

    func testFactoryStrategyNew()
    {
        guard

            let controller:CHome = self.controller

        else
        {
            return
        }

        session?.status = MSession.Status.new

        let strategy:MHomeStrategy? = MHomeStrategy.factoryStrategy(
            controller:controller)
        let strategyNew:MHomeStrategyNew? = strategy as? MHomeStrategyNew

        XCTAssertNotNil(
            strategyNew,
            "failed loading strategy for status new")
    }
}


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

import Foundation

public enum EurofurenceDataStoreState {
    case absent
    case stale
    case available
}

public protocol EurofurenceApplicationProtocol: ApplicationNotificationHandling,
                                         RefreshService,
                                         AnnouncementsService,
                                         AuthenticationService,
                                         EventsService,
                                         DealersService,
                                         KnowledgeService,
                                         LinkLookupService,
                                         ConventionCountdownService,
                                         CollectThemAllService,
                                         MapsService {

    func performFullStoreRefresh(completionHandler: @escaping (Error?) -> Void) -> Progress

    func setExternalContentHandler(_ externalContentHandler: ExternalContentHandler)

    var localPrivateMessages: [Message] { get }

    func storeRemoteNotificationsToken(_ deviceToken: Data)
    func resolveDataStoreState(completionHandler: @escaping (EurofurenceDataStoreState) -> Void)
    func retrieveCurrentUser(completionHandler: @escaping (User?) -> Void)

    func add(_ observer: PrivateMessagesObserver)
    func fetchPrivateMessages(completionHandler: @escaping (PrivateMessageResult) -> Void)
    func markMessageAsRead(_ message: Message)

    func login(_ arguments: LoginArguments, completionHandler: @escaping (LoginResult) -> Void)
    func logout(completionHandler: @escaping (LogoutResult) -> Void)

}

Remove duplicated protocol requirements + formatting

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

import Foundation

public enum EurofurenceDataStoreState {
    case absent
    case stale
    case available
}

public protocol EurofurenceApplicationProtocol: ApplicationNotificationHandling,
                                                RefreshService,
                                                AnnouncementsService,
                                                AuthenticationService,
                                                EventsService,
                                                DealersService,
                                                KnowledgeService,
                                                LinkLookupService,
                                                ConventionCountdownService,
                                                CollectThemAllService,
                                                MapsService {

    func performFullStoreRefresh(completionHandler: @escaping (Error?) -> Void) -> Progress

    func setExternalContentHandler(_ externalContentHandler: ExternalContentHandler)

    var localPrivateMessages: [Message] { get }

    func storeRemoteNotificationsToken(_ deviceToken: Data)
    func resolveDataStoreState(completionHandler: @escaping (EurofurenceDataStoreState) -> Void)
    func retrieveCurrentUser(completionHandler: @escaping (User?) -> Void)

    func add(_ observer: PrivateMessagesObserver)
    func fetchPrivateMessages(completionHandler: @escaping (PrivateMessageResult) -> Void)
    func markMessageAsRead(_ message: Message)

}


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

func main() {
  var nsarr: NSArray = NSArray(array: [Int(123456),Int32(234567),UInt16(45678),Double(1.25),Float(2.5)])
  var swarr = unsafeBitCast(unsafeBitCast(nsarr, to: Int.self), to: NSArray.self) as! [AnyObject]
  print("break here")
}

main()

Add a comment to this test case to make it obvious why we are using explicit type annotations

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

func main() {
  // explicit type annotations here are by design - we want to make sure we bridge to types other than Int
  var nsarr: NSArray = NSArray(array: [Int(123456),Int32(234567),UInt16(45678),Double(1.25),Float(2.5)])
  var swarr = unsafeBitCast(unsafeBitCast(nsarr, to: Int.self), to: NSArray.self) as! [AnyObject]
  print("break here")
}

main()


import Leaf

public extension LeafTagConfig {
    public mutating func use(_ list: [String: TagRenderer]) {
        for item in list {
            self.use(item.value, as: item.key)
        }
    }
}

Update for proposed leaf change

import Leaf

public extension LeafTagConfig {
    public func use(_ list: [String: TagRenderer]) {
        for item in list {
            self.use(item.value, as: item.key)
        }
    }
}


//
//  LoginViewControllerV2Factory.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 04/12/2017.
//  Copyright © 2017 Eurofurence. All rights reserved.
//

import UIKit.UIStoryboard
import UIKit.UIViewController

struct LoginViewControllerV2Factory {

    private let storyboard = UIStoryboard(name: "Login", bundle: .main)

    func makeLoginScene() -> UIViewController & LoginScene {
        return storyboard.instantiateViewController(withIdentifier: "LoginViewControllerV2") as! LoginViewControllerV2
    }

}

Make login view controller factory conform to scene factory

//
//  LoginViewControllerV2Factory.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 04/12/2017.
//  Copyright © 2017 Eurofurence. All rights reserved.
//

import UIKit.UIStoryboard
import UIKit.UIViewController

struct LoginViewControllerV2Factory: LoginSceneFactory {

    private let storyboard = UIStoryboard(name: "Login", bundle: .main)

    func makeLoginScene() -> UIViewController & LoginScene {
        return storyboard.instantiateViewController(withIdentifier: "LoginViewControllerV2") as! LoginViewControllerV2
    }

}


import Foundation
import ReactiveSwift

extension Reactive where Base: NSObject {
	/// Creates a binding target which uses the lifetime of the object, and weakly
	/// references the object so that the supplied `action` is triggered only if
	/// the object has not deinitialized.
	///
	/// - important: The binding target is bound to the main queue.
	///
	/// - parameters:
	///   - action: The action to consume values from the bindings.
	///
	/// - returns:
	///   A binding target that holds no strong references to the object.
	internal func makeBindingTarget<U>(action: @escaping (Base, U) -> Void) -> BindingTarget<U> {
		let scheduler = associatedValue { _ in UIScheduler() }

		return BindingTarget(on: scheduler, lifetime: lifetime) { [weak base = self.base] value in
			if let base = base {
				action(base, value)
			}
		}
	}
}

Create one `UIScheduler` for each instance of binding target.

import Foundation
import ReactiveSwift

extension Reactive where Base: NSObject {
	/// Creates a binding target which uses the lifetime of the object, and weakly
	/// references the object so that the supplied `action` is triggered only if
	/// the object has not deinitialized.
	///
	/// - important: The binding target is bound to the main queue.
	///
	/// - parameters:
	///   - action: The action to consume values from the bindings.
	///
	/// - returns:
	///   A binding target that holds no strong references to the object.
	internal func makeBindingTarget<U>(_ key: StaticString = #function, action: @escaping (Base, U) -> Void) -> BindingTarget<U> {
		return BindingTarget(on: UIScheduler(), lifetime: lifetime) { [weak base = self.base] value in
			if let base = base {
				action(base, value)
			}
		}
	}
}


//
//  RepositoryInvitationsClient.swift
//  GithubClient
//
//  Created by Eduardo Arenas on 2/18/18.
//  Copyright © 2018 GameChanger. All rights reserved.
//

import RxSwift

@available(OSX 10.12, *)
public final class RepositoryInvitationsClient: ApiClient {

  public func listAll(owner: String, repo: String, limit: Int?) -> Observable<[Invitation]> {
    return getObjects(apiUrl: .invitations(owner: owner, repo: repo), limit: limit)
  }

  public func listAllPaginated(owner: String, repo: String) -> Observable<PageResult<Invitation>> {
    return getPaginatedObjects(apiUrl: .invitations(owner: owner, repo: repo))
  }

  public func delete(owner: String, repo: String, id: Int) -> Completable {
    return delete(apiUrl: .invitation(owner: owner, repo: repo, id: id))
  }

}

Add default argument for limit

//
//  RepositoryInvitationsClient.swift
//  GithubClient
//
//  Created by Eduardo Arenas on 2/18/18.
//  Copyright © 2018 GameChanger. All rights reserved.
//

import RxSwift

@available(OSX 10.12, *)
public final class RepositoryInvitationsClient: ApiClient {

  public func listAll(owner: String, repo: String, limit: Int? = nil) -> Observable<[Invitation]> {
    return getObjects(apiUrl: .invitations(owner: owner, repo: repo), limit: limit)
  }

  public func listAllPaginated(owner: String, repo: String) -> Observable<PageResult<Invitation>> {
    return getPaginatedObjects(apiUrl: .invitations(owner: owner, repo: repo))
  }

  public func delete(owner: String, repo: String, id: Int) -> Completable {
    return delete(apiUrl: .invitation(owner: owner, repo: repo, id: id))
  }

}


//
//  UINib+Extension.swift
//  SwiftUtilities
//
//  Created by Rodrigo Ruiz on 6/29/17.
//  Copyright © 2017 Rodrigo Ruiz. All rights reserved.
//

extension UINib {

    public static func instantiateView<T: UIView>() -> T {
        let nib = UINib(nibName: String(describing: T.self), bundle: nil)
        guard let view = nib.instantiate(withOwner: nil, options: nil)[0] as? T else {
            fatalError()
        }
        return view
    }

}

Add instantiateView method to UINib.

//
//  UINib+Extension.swift
//  SwiftUtilities
//
//  Created by Rodrigo Ruiz on 6/29/17.
//  Copyright © 2017 Rodrigo Ruiz. All rights reserved.
//

extension UINib {

    public static func instantiateView<T: UIView>() -> T {
        let nib = UINib(nibName: String(describing: T.self), bundle: nil)
        guard let view = nib.instantiate(withOwner: nil, options: nil)[0] as? T else {
            fatalError()
        }
        return view
    }

    public static func instantiateView(_ nibName: String) -> UIView {
        let nib = UINib(nibName: nibName, bundle: nil)
        guard let view = nib.instantiate(withOwner: nil, options: nil)[0] as? UIView else {
            fatalError()
        }
        return view
    }

}


//
//  ConfigViewController.swift
//  Patriot
//
//  Created by Ron Lisle on 5/29/17.
//  Copyright © 2017 Ron Lisle. All rights reserved.
//

import UIKit

class ConfigViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func closeMenu(sender: AnyObject) {
        dismiss(animated: true, completion: nil)
    }
}

Add blank row at top

//
//  ConfigViewController.swift
//  Patriot
//
//  Created by Ron Lisle on 5/29/17.
//  Copyright © 2017 Ron Lisle. All rights reserved.
//

import UIKit

class ConfigViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func closeMenu(sender: AnyObject) {
        dismiss(animated: true, completion: nil)
    }

    override func viewDidLayoutSubviews() {
        if let rect = self.navigationController?.navigationBar.frame {
            let y = rect.size.height + rect.origin.y
            self.tableView.contentInset = UIEdgeInsetsMake( y, 0, 0, 0)
        }
    }
}


//
//  Middleware.swift
//  ReSwift
//
//  Created by Benji Encz on 12/24/15.
//  Copyright © 2015 Benjamin Encz. All rights reserved.
//

import Foundation

public typealias DispatchFunction =  (Action) -> Any
public typealias GetState = () -> StateType
public typealias Middleware = (DispatchFunction, GetState) -> DispatchFunction -> DispatchFunction

Set return type of `GetState` to be an `Optional<StateType>`

//
//  Middleware.swift
//  ReSwift
//
//  Created by Benji Encz on 12/24/15.
//  Copyright © 2015 Benjamin Encz. All rights reserved.
//

import Foundation

public typealias DispatchFunction =  (Action) -> Any
public typealias GetState = () -> StateType?
public typealias Middleware = (DispatchFunction, GetState) -> DispatchFunction -> DispatchFunction


import Crypto

public extension String {
    public static func randomAlphaNumericString(_ length: Int = 64) -> String {
        func makeRandom(min: Int, max: Int) -> Int {
            let top = max - min + 1
            #if os(Linux)
                // will always be initialized
                guard randomInitialized else { fatalError() }
                return Int(COperatingSystem.random() % top) + min
            #else
                return Int(arc4random_uniform(UInt32(top))) + min
            #endif
        }

        let letters: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        let len = letters.count

        var randomString = ""
        for _ in 0 ..< length {
            let rand = makeRandom(min: 0, max: Int(len - 1))
            let char = letters[letters.index(letters.startIndex, offsetBy: rand)]
            randomString += String(char)
        }

        return randomString
    }
}

Make it build on Linux

import Crypto

public extension String {
    public static func randomAlphaNumericString(_ length: Int = 64) -> String {
        func makeRandom(min: Int, max: Int) -> Int {
            let top = max - min + 1
            #if os(Linux)
                // will always be initialized
                guard randomInitialized else { fatalError() }
                return Int(COperatingSystem.random() % top) + min
            #else
                return Int(arc4random_uniform(UInt32(top))) + min
            #endif
        }

        let letters: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        let len = letters.count

        var randomString = ""
        for _ in 0 ..< length {
            let rand = makeRandom(min: 0, max: Int(len - 1))
            let char = letters[letters.index(letters.startIndex, offsetBy: rand)]
            randomString += String(char)
        }

        return randomString
    }
}

#if os(Linux)
    /// Generates a random number between (and inclusive of)
    /// the given minimum and maximum.
    private let randomInitialized: Bool = {
        /// This stylized initializer is used to work around dispatch_once
        /// not existing and still guarantee thread safety
        let current = Date().timeIntervalSinceReferenceDate
        let salt = current.truncatingRemainder(dividingBy: 1) * 100000000
        COperatingSystem.srand(UInt32(current + salt))
        return true
    }()
#endif


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

import SwiftyJSON

class PermissionsRequest: APIRequest {
    typealias APIResourceType = PermissionsResource

    let requiredVersion: Version = Version(0, 61, 0)
    let path = "/api/v1/permissions"
}

class PermissionsResource: APIResource {
    var permissions: [Permission] {
        return raw?.arrayValue.map {
            let permission = Permission()
            permission.map($0, realm: nil)
            return permission
        } ?? []
    }
}

Update API endpoint of Permissions list

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

import SwiftyJSON

class PermissionsRequest: APIRequest {
    typealias APIResourceType = PermissionsResource

    let requiredVersion: Version = Version(0, 61, 0)
    let path = "/api/v1/permissions.list"
}

class PermissionsResource: APIResource {
    var permissions: [Permission] {
        return raw?.arrayValue.map {
            let permission = Permission()
            permission.map($0, realm: nil)
            return permission
        } ?? []
    }
}


//
//  GitHubSearchViewReactor.swift
//  GitHubSearch
//
//  Created by Suyeol Jeon on 13/05/2017.
//  Copyright © 2017 Suyeol Jeon. All rights reserved.
//

import ReactorKit

final class GitHubSearchViewReactor: Reactor {
  enum Action {
  }

  enum Mutation {
  }

  struct State {
  }

  let initialState = State()
}

Implement reactor with dummy data

//
//  GitHubSearchViewReactor.swift
//  GitHubSearch
//
//  Created by Suyeol Jeon on 13/05/2017.
//  Copyright © 2017 Suyeol Jeon. All rights reserved.
//

import ReactorKit
import RxSwift

final class GitHubSearchViewReactor: Reactor {
  enum Action {
    case updateQuery(String?)
  }

  enum Mutation {
    case setRepos([String])
  }

  struct State {
    var repos: [String] = []
  }

  let initialState = State()

  func mutate(action: Action) -> Observable<Mutation> {
    switch action {
    case let .updateQuery(query):
      if let query = query {
        let dummyRepos = ["\(query)1", "\(query)2", "\(query)3"]
        return Observable.just(Mutation.setRepos(dummyRepos))
      } else {
        return Observable.just(Mutation.setRepos([]))
      }
    }
  }

  func reduce(state: State, mutation: Mutation) -> State {
    switch mutation {
    case let .setRepos(repos):
      var newState = state
      newState.repos = repos
      return newState
    }
  }
}


import struct Models.Activity
import protocol Library.ViewModelType
import struct ReactiveCocoa.SignalProducer
import enum Result.NoError
import struct Library.Environment
import struct Library.AppEnvironment
import ReactiveExtensions

internal protocol ActivitiesViewModelOutputs {
  var activities: SignalProducer<[Activity], NoError> { get }
}

internal protocol ActivitiesViewModelType {
  var outputs: ActivitiesViewModelOutputs { get }
}

internal struct ActivitiesViewModel: ViewModelType, ActivitiesViewModelType, ActivitiesViewModelOutputs {
  typealias Model = Activity

  internal let activities: SignalProducer<[Activity], NoError>

  internal var outputs: ActivitiesViewModelOutputs { return self }

  init(env: Environment = AppEnvironment.current) {
    let service = env.apiService

    self.activities = service.fetchActivities()
      .demoteErrors()
      .map { env in env.activities }
      .replayLazily(1)
  }
}

Use class, not struct for view model.

import struct Models.Activity
import protocol Library.ViewModelType
import struct ReactiveCocoa.SignalProducer
import enum Result.NoError
import struct Library.Environment
import struct Library.AppEnvironment
import ReactiveExtensions

internal protocol ActivitiesViewModelOutputs {
  var activities: SignalProducer<[Activity], NoError> { get }
}

internal protocol ActivitiesViewModelType {
  var outputs: ActivitiesViewModelOutputs { get }
}

internal final class ActivitiesViewModel: ViewModelType, ActivitiesViewModelType, ActivitiesViewModelOutputs {
  typealias Model = Activity

  internal let activities: SignalProducer<[Activity], NoError>

  internal var outputs: ActivitiesViewModelOutputs { return self }

  init(env: Environment = AppEnvironment.current) {
    let service = env.apiService

    self.activities = service.fetchActivities()
      .demoteErrors()
      .map { env in env.activities }
      .replayLazily(1)
  }
}


//
//  UIWindow+RootViewController.swift
//  Swiftilities
//
//  Created by Nicholas Bonatsakis on 2/5/16.
//  Copyright © 2016 Raizlabs. All rights reserved.
//

import UIKit

/**
 *  UIWindow extension for setting the rootViewController on a UIWindow instance in a safe and animatable way.
 */
public extension UIWindow {

    /**
     Set the rootViewController on this UIWindow instance.

     - parameter viewController: The view controller to set
     - parameter animated:       Whether or not to animate the transition, animation is a cross-fade
     - parameter completion:     Completion block to be invoked after the transition finishes
     */
    @nonobjc
    func setRootViewController(_ viewController: UIViewController, animated: Bool, duration: TimeInterval = 0.3, completion: ((Bool) -> Void)? = nil) {
        if animated {
            UIView.transition(with: self, duration: duration, options: .transitionCrossDissolve, animations: { () -> Void in
                let oldState = UIView.areAnimationsEnabled
                UIView.setAnimationsEnabled(false)

                self.rootViewController = viewController

                UIView.setAnimationsEnabled(oldState)
            }, completion: completion)
        } else {
            self.rootViewController = viewController
        }
    }
}

Remove unnecessary type annotation from animations

//
//  UIWindow+RootViewController.swift
//  Swiftilities
//
//  Created by Nicholas Bonatsakis on 2/5/16.
//  Copyright © 2016 Raizlabs. All rights reserved.
//

import UIKit

/**
 *  UIWindow extension for setting the rootViewController on a UIWindow instance in a safe and animatable way.
 */
public extension UIWindow {

    /**
     Set the rootViewController on this UIWindow instance.

     - parameter viewController: The view controller to set
     - parameter animated:       Whether or not to animate the transition, animation is a cross-fade
     - parameter completion:     Completion block to be invoked after the transition finishes
     */
    @nonobjc
    func setRootViewController(_ viewController: UIViewController, animated: Bool, duration: TimeInterval = 0.3, completion: ((Bool) -> Void)? = nil) {
        if animated {
            UIView.transition(with: self, duration: duration, options: .transitionCrossDissolve, animations: {
                let oldState = UIView.areAnimationsEnabled
                UIView.setAnimationsEnabled(false)

                self.rootViewController = viewController

                UIView.setAnimationsEnabled(oldState)
            }, completion: completion)
        } else {
            self.rootViewController = viewController
        }
    }
}


//
//  ViewController.swift
//  CoreMotionDemo
//
//  Created by BJ Miller on 8/6/14.
//  Copyright (c) 2014 Six Five Software, LLC. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var stepCountLabel: UILabel!
    @IBOutlet weak var distanceLabel: UILabel!
    @IBOutlet weak var rateLabel: UILabel!
    @IBOutlet weak var lastUpdatedLabel: UILabel!

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

}

Complete demo with workable pedometer.

//
//  ViewController.swift
//  CoreMotionDemo
//
//  Created by BJ Miller on 8/6/14.
//  Copyright (c) 2014 Six Five Software, LLC. All rights reserved.
//

import UIKit
import CoreMotion

class ViewController: UIViewController {

    let pedometer = CMPedometer()
    var lastDistance = 0.0
    var lastUpdatedDate = NSDate()
    let dateFormatter = NSDateFormatter()

    @IBOutlet weak var stepCountLabel: UILabel!
    @IBOutlet weak var distanceLabel: UILabel!
    @IBOutlet weak var rateLabel: UILabel!
    @IBOutlet weak var lastUpdatedLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
        dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle
    }

    override func viewWillAppear(animated: Bool) {
        setupPedometer()
        super.viewWillAppear(animated)
    }

    override func viewWillDisappear(animated: Bool) {
        pedometer.stopPedometerUpdates()
        super.viewWillDisappear(animated)
    }

    func setupPedometer() {
        if CMPedometer.isStepCountingAvailable() {
            self.pedometer.startPedometerUpdatesFromDate(midnight) { pedometerData, pedError in
                if pedError != nil {
                    // failed, handle error
                } else {
                    let meters = pedometerData.distance.doubleValue
                    let distanceFormatter = NSLengthFormatter()

                    let timeDelta = pedometerData.endDate.timeIntervalSinceDate(self.lastUpdatedDate)
                    let distanceDelta = meters - self.lastDistance
                    let rate = distanceDelta / timeDelta

                    self.lastUpdatedDate = NSDate()
                    self.lastDistance = meters

                    dispatch_async(dispatch_get_main_queue()) {
                        self.stepCountLabel.text = "\(pedometerData.numberOfSteps.integerValue) steps"
                        self.distanceLabel.text = "\(distanceFormatter.stringFromMeters(meters))"
                        self.rateLabel.text = "\(distanceFormatter.stringFromMeters(rate)) / s"
                        self.lastUpdatedLabel.text = "Last updated: \(self.dateFormatter.stringFromDate(pedometerData.endDate))"
                    }
                }
            }
        }
    }

    var midnight: NSDate {
        let cal = NSCalendar.autoupdatingCurrentCalendar()
        return cal.startOfDayForDate(NSDate())
    }

}


//
//  UIScrollView.swift
//  DarkSwift
//
//  Created by Dark Dong on 2017/7/29.
//  Copyright © 2017年 Dark Dong. All rights reserved.
//

import UIKit

public extension UIScrollView {
    func scrollToEnd(animated: Bool, scrollDirection: UICollectionViewScrollDirection = .vertical) {
        switch scrollDirection {
        case .vertical:
            let diff = contentSize.height + contentInset.bottom - frame.height
            if (diff > 0) {
                setContentOffset(CGPoint(x: contentOffset.x, y: diff), animated: animated)
            }
        case .horizontal:
            let diff = contentSize.width + contentInset.right - frame.width
            if (diff > 0) {
                setContentOffset(CGPoint(x: diff, y: contentOffset.y), animated: animated)
            }
        }
    }
}

Add UITableView and UICollectionView ext

//
//  UIScrollView.swift
//  DarkSwift
//
//  Created by Dark Dong on 2017/7/29.
//  Copyright © 2017年 Dark Dong. All rights reserved.
//

import UIKit

public extension UIScrollView {
    func scrollToEnd(animated: Bool, scrollDirection: UICollectionViewScrollDirection = .vertical) {
        switch scrollDirection {
        case .vertical:
            let diff = contentSize.height + contentInset.bottom - frame.height
            if (diff > 0) {
                setContentOffset(CGPoint(x: contentOffset.x, y: diff), animated: animated)
            }
        case .horizontal:
            let diff = contentSize.width + contentInset.right - frame.width
            if (diff > 0) {
                setContentOffset(CGPoint(x: diff, y: contentOffset.y), animated: animated)
            }
        }
    }
}

public extension UITableView {
    func clearsSelection(animated: Bool) {
        if let indexPaths = indexPathsForSelectedRows {
            for indexPath in indexPaths {
                deselectRow(at: indexPath, animated: animated)
            }
        }
    }
}

public extension UICollectionView {
    func clearsSelection(animated: Bool) {
        if let indexPaths = indexPathsForSelectedItems {
            for indexPath in indexPaths {
                deselectItem(at: indexPath, animated: animated)
            }
        }
    }
}


import UIKit

func ==(lhs: NSLayoutConstraint, rhs: NSLayoutConstraint) -> Bool {
    guard let lhsFirstItem = lhs.firstItem as? UIView,
        let rhsFirstItem = rhs.firstItem as? UIView,
        let lhsSecondItem = lhs.secondItem as? UIView,
        let rhsSecondItem = rhs.secondItem as? UIView else
    {
        return false
    }

    return lhsFirstItem == rhsFirstItem
        && lhs.firstAttribute == rhs.firstAttribute
        && lhsSecondItem == rhsSecondItem
        && lhs.secondAttribute == rhs.secondAttribute
        && lhs.relation == rhs.relation
}

Fix custom equatable for NSLayoutConstraint

import UIKit

func ==(lhs: NSLayoutConstraint, rhs: NSLayoutConstraint) -> Bool {
    guard let lhsFirstItem = lhs.firstItem as? UIView,
        let rhsFirstItem = rhs.firstItem as? UIView,
        let lhsSecondItem = lhs.secondItem as? UIView,
        let rhsSecondItem = rhs.secondItem as? UIView else
    {
        return false
    }

    return lhsFirstItem == rhsFirstItem
        && lhs.firstAttribute == rhs.firstAttribute
        && lhsSecondItem == rhsSecondItem
        && lhs.secondAttribute == rhs.secondAttribute
        && lhs.relation == rhs.relation
        && lhs.multiplier == rhs.multiplier
}


//
//  MessagesViewControllerSearching.swift
//  Rocket.Chat
//
//  Created by Matheus Cardoso on 11/12/18.
//  Copyright © 2018 Rocket.Chat. All rights reserved.
//

extension MessagesViewController {
    func updateSearchMessagesButton() {
        if subscription != nil {
            navigationItem.rightBarButtonItem = UIBarButtonItem(
                barButtonSystemItem: .search,
                target: self,
                action: #selector(showSearchMessages)
            )
        } else {
            navigationItem.rightBarButtonItem = nil
        }
    }

    @objc func showSearchMessages() {
        guard
            let controller = storyboard?.instantiateViewController(withIdentifier: "MessagesList"),
            let messageList = controller as? MessagesListViewController
            else {
                return
        }

        messageList.data.subscription = subscription
        messageList.data.isSearchingMessages = true
        let searchMessagesNav = BaseNavigationController(rootViewController: messageList)

        present(searchMessagesNav, animated: true, completion: nil)

    }
}

Use new search icon on the screen

//
//  MessagesViewControllerSearching.swift
//  Rocket.Chat
//
//  Created by Matheus Cardoso on 11/12/18.
//  Copyright © 2018 Rocket.Chat. All rights reserved.
//

extension MessagesViewController {
    func updateSearchMessagesButton() {
        if subscription != nil {
            navigationItem.rightBarButtonItem = UIBarButtonItem(
                image: UIImage(named: "Search"),
                style: .done,
                target: self,
                action: #selector(showSearchMessages)
            )
        } else {
            navigationItem.rightBarButtonItem = nil
        }
    }

    @objc func showSearchMessages() {
        guard
            let controller = storyboard?.instantiateViewController(withIdentifier: "MessagesList"),
            let messageList = controller as? MessagesListViewController
            else {
                return
        }

        messageList.data.subscription = subscription
        messageList.data.isSearchingMessages = true
        let searchMessagesNav = BaseNavigationController(rootViewController: messageList)

        present(searchMessagesNav, animated: true, completion: nil)

    }
}


import UIKit

class VProfileEditListHeader:UICollectionReusableView
{
    private weak var labelTitle:UILabel!
    private let kTitleHeight:CGFloat = 30
    private let kTitleMarginLeft:CGFloat = 10
    private let kTitleWidth:CGFloat = 200

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

        let labelTitle:UILabel = UILabel()
        labelTitle.translatesAutoresizingMaskIntoConstraints = false
        labelTitle.backgroundColor = UIColor.clear
        labelTitle.isUserInteractionEnabled = false
        labelTitle.font = UIFont.medium(size:15)
        labelTitle.textColor = UIColor.colourBackgroundDark
        self.labelTitle = labelTitle

        NSLayoutConstraint.bottomToTop(
            view:labelTitle,
            toView:self)
        NSLayoutConstraint.height(
            view:labelTitle,
            constant:kTitleHeight)
        NSLayoutConstraint.leftToLeft(
            view:labelTitle,
            toView:self)
        NSLayoutConstraint.width(
            view:labelTitle,
            constant:kTitleWidth)
    }

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

    //MARK: internal

    func config(model:MProfileEditItemProtocol)
    {
        labelTitle.text = model.headerTitle
    }
}

Add label to view hierarchy

import UIKit

class VProfileEditListHeader:UICollectionReusableView
{
    private weak var labelTitle:UILabel!
    private let kTitleHeight:CGFloat = 30
    private let kTitleMarginLeft:CGFloat = 10
    private let kTitleWidth:CGFloat = 200

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

        let labelTitle:UILabel = UILabel()
        labelTitle.translatesAutoresizingMaskIntoConstraints = false
        labelTitle.backgroundColor = UIColor.clear
        labelTitle.isUserInteractionEnabled = false
        labelTitle.font = UIFont.medium(size:15)
        labelTitle.textColor = UIColor.colourBackgroundDark
        self.labelTitle = labelTitle

        addSubview(labelTitle)

        NSLayoutConstraint.bottomToTop(
            view:labelTitle,
            toView:self)
        NSLayoutConstraint.height(
            view:labelTitle,
            constant:kTitleHeight)
        NSLayoutConstraint.leftToLeft(
            view:labelTitle,
            toView:self)
        NSLayoutConstraint.width(
            view:labelTitle,
            constant:kTitleWidth)
    }

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

    //MARK: internal

    func config(model:MProfileEditItemProtocol)
    {
        labelTitle.text = model.headerTitle
    }
}


//
//  ViewController.swift
//  OpenSourceController
//
//  Created by terflogag on 01/30/2017.
//  Copyright (c) 2017 terflogag. All rights reserved.
//

import UIKit
import OpenSourceController

class ViewController: UIViewController {

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

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

    @IBAction func showOpenSource(_ sender: Any) {
        // Create controller
        let openSourceVC = OpenSourceController()

        // Init with LicenceFile object
        openSourceVC.licences = [LicenceFile(title: "FacebookImagePicker",
                                             url: "https://raw.githubusercontent.com/terflogag/FacebookImagePicker/master/LICENSE"),
                                 LicenceFile(title: "JSQMessagesViewController",
                                             url: "https://raw.githubusercontent.com/jessesquires/JSQMessagesViewController/develop/LICENSE")]

        // Present controller
        openSourceVC.presentOpenSourceController(from: self)
    }
}

Add licence file for demo

//
//  ViewController.swift
//  OpenSourceController
//
//  Created by terflogag on 01/30/2017.
//  Copyright (c) 2017 terflogag. All rights reserved.
//

import UIKit
import OpenSourceController

class ViewController: UIViewController {

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

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

    @IBAction func showOpenSource(_ sender: Any) {
        // Create controller
        let openSourceVC = OpenSourceController()

        // Init with LicenceFile object
        openSourceVC.licences = [LicenceFile(title: "FacebookImagePicker",
                                             url: "https://raw.githubusercontent.com/terflogag/FacebookImagePicker/master/LICENSE"),
                                 LicenceFile(title: "JSQMessagesViewController",
                                             url: "https://raw.githubusercontent.com/jessesquires/JSQMessagesViewController/develop/LICENSE"),
                                 LicenceFile(title: "OpenSourceController",
                                             url: "https://raw.githubusercontent.com/terflogag/OpenSourceController/master/LICENSE")]

        // Present controller
        openSourceVC.presentOpenSourceController(from: self)
    }
}


//
//  CombinedChangeable.swift
//  SwiftRebound
//
//  Created by Andrew Hunter on 12/07/2016.
//
//

import Foundation

///
/// Changeable implementation that works by combined many changeable objects into one
///
internal class CombinedChangeable : Changeable {
    /// The chageables that are combined in this one
    private let _combined: [Changeable];

    init(changeables: [Changeable]) {
        var flatChangeables = [Changeable]();

        // Flatten out the list so that we don't create nested combined changeables
        for changeable in changeables {
            let alsoCombined = changeable as? CombinedChangeable;
            if let alsoCombined = alsoCombined {
                flatChangeables.appendContentsOf(alsoCombined._combined);
            }
        }

        _combined = flatChangeables;
    }

    ///
    /// Calls a function any time this value is marked as changed
    ///
    func whenChanged(target: Notifiable) -> Lifetime {
        var lifetimes = [Lifetime]();

        // Combine the changeables and generate a lifetime for each one
        for changeable in _combined {
            let lifetime = changeable.whenChanged(target);
            lifetimes.append(lifetime);
        }

        // Result is a combined lifetime
        return CombinedLifetime(lifetimes: lifetimes);
    }
}

Make the combined changeable mutable so we can use it with the binding context

//
//  CombinedChangeable.swift
//  SwiftRebound
//
//  Created by Andrew Hunter on 12/07/2016.
//
//

import Foundation

///
/// Changeable implementation that works by combined many changeable objects into one
///
internal class CombinedChangeable : Changeable {
    /// The chageables that are combined in this one
    private var _combined: [Changeable];

    init(changeables: [Changeable]) {
        var flatChangeables = [Changeable]();

        // Flatten out the list so that we don't create nested combined changeables
        for changeable in changeables {
            let alsoCombined = changeable as? CombinedChangeable;
            if let alsoCombined = alsoCombined {
                flatChangeables.appendContentsOf(alsoCombined._combined);
            }
        }

        _combined = flatChangeables;
    }

    ///
    /// Calls a function any time this value is marked as changed
    ///
    func whenChanged(target: Notifiable) -> Lifetime {
        var lifetimes = [Lifetime]();

        // Combine the changeables and generate a lifetime for each one
        for changeable in _combined {
            let lifetime = changeable.whenChanged(target);
            lifetimes.append(lifetime);
        }

        // Result is a combined lifetime
        return CombinedLifetime(lifetimes: lifetimes);
    }

    ///
    /// Adds a new changeable to the changeable items being managed by this object
    ///
    func addChangeable(newChangeable: Changeable) {
        _combined.append(newChangeable);
    }
}


import Foundation

extension MConnecting
{
    //MARK: internal

    func statusLoading()
    {
        status = MConnectingStatusLoading()
    }

    func statusPin()
    {
        status = MConnectingStatusPin()
    }
}

Create method for status timeout

import Foundation

extension MConnecting
{
    //MARK: internal

    func statusLoading()
    {
        status = MConnectingStatusLoading()
    }

    func statusPin()
    {
        status = MConnectingStatusPin()
    }

    func statusTimeout()
    {
        status = MConnectingStatusTimeout()
    }
}


//
// Stream_Tests.swift
// SwiftShell
//
// Created by Kåre Morstøl on 21/08/14.
// Copyright (c) 2014 NotTooBad Software. All rights reserved.
//

import SwiftShell
import XCTest

class Stream_Tests: XCTestCase {

	func testStreams () {
		let (writer,reader) = streams()

		writer.write("one")
		XCTAssertEqual(reader.readSome(), "one")

		writer.writeln()
		writer.writeln("two")
		XCTAssertEqual(reader.readSome(), "\ntwo\n")

		writer.write("three")
		writer.close()
		XCTAssertEqual(reader.read(), "three")
	}

	func testReadableStreamRun () {
		let (writer,reader) = streams()

		writer.write("one")
		writer.close()

		XCTAssertEqual(reader.run("cat"), "one")
	}

	func testReadableStreamRunAsync () {
		let (writer,reader) = streams()

		writer.write("one")
		writer.close()

		XCTAssertEqual(reader.runAsync("cat").stdout.read(), "one")
	}
}

Test using streams with ‘print’.

//
// Stream_Tests.swift
// SwiftShell
//
// Created by Kåre Morstøl on 21/08/14.
// Copyright (c) 2014 NotTooBad Software. All rights reserved.
//

import SwiftShell
import XCTest

class Stream_Tests: XCTestCase {

	func testStreams () {
		let (writer,reader) = streams()

		writer.write("one")
		XCTAssertEqual(reader.readSome(), "one")

		writer.writeln()
		writer.writeln("two")
		XCTAssertEqual(reader.readSome(), "\ntwo\n")

		writer.write("three")
		writer.close()
		XCTAssertEqual(reader.read(), "three")
	}

	func testReadableStreamRun () {
		let (writer,reader) = streams()

		writer.write("one")
		writer.close()

		XCTAssertEqual(reader.run("cat"), "one")
	}

	func testReadableStreamRunAsync () {
		let (writer,reader) = streams()

		writer.write("one")
		writer.close()

		XCTAssertEqual(reader.runAsync("cat").stdout.read(), "one")
	}

	func testPrintStream () {
		let (writer,reader) = streams()
		writer.write("one")
		writer.close()

		var string = ""
		print(reader, toStream: &string)

		XCTAssertEqual(string, "one\n")
	}

	func testPrintToStream () {
		var (writer,reader) = streams()

		print("one", toStream: &writer)

		XCTAssertEqual(reader.readSome(), "one\n")
	}
}


//  Copyright © 2017 Stefan van den Oord. All rights reserved.

import UIKit

class ViewController: UIViewController {

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

}

Add call to NetUtils to make sure it compiles correctly

//  Copyright © 2017 Stefan van den Oord. All rights reserved.

import UIKit
import NetUtils

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        print("\(Interface.allInterfaces())")
    }

}


// The MIT License (MIT)
//
// Copyright (c) 2015-2021 Alexander Grebenyuk (github.com/kean).

import Foundation
import CommonCrypto

extension String {
    /// Calculates SHA1 from the given string and returns its hex representation.
    ///
    /// ```swift
    /// print("http://test.com".sha1)
    /// // prints "50334ee0b51600df6397ce93ceed4728c37fee4e"
    /// ```
    var sha1: String? {
        guard let input = self.data(using: .utf8) else {
            return nil
        }

        let hash = input.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in
            var hash = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
            CC_SHA1(bytes.baseAddress, CC_LONG(input.count), &hash)
            return hash
        }

        return hash.map({ String(format: "%02x", $0) }).joined()
    }
}

extension NSLock {
    func sync<T>(_ closure: () -> T) -> T {
        lock()
        defer { unlock() }
        return closure()
    }
}

extension URL {
    var isCacheable: Bool {
        let scheme = self.scheme
        return scheme != "file" && scheme != "data"
    }
}

Make sure sha1 returns nil for empty input

// The MIT License (MIT)
//
// Copyright (c) 2015-2021 Alexander Grebenyuk (github.com/kean).

import Foundation
import CommonCrypto

extension String {
    /// Calculates SHA1 from the given string and returns its hex representation.
    ///
    /// ```swift
    /// print("http://test.com".sha1)
    /// // prints "50334ee0b51600df6397ce93ceed4728c37fee4e"
    /// ```
    var sha1: String? {
        guard !isEmpty, let input = self.data(using: .utf8) else {
            return nil
        }

        let hash = input.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in
            var hash = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
            CC_SHA1(bytes.baseAddress, CC_LONG(input.count), &hash)
            return hash
        }

        return hash.map({ String(format: "%02x", $0) }).joined()
    }
}

extension NSLock {
    func sync<T>(_ closure: () -> T) -> T {
        lock()
        defer { unlock() }
        return closure()
    }
}

extension URL {
    var isCacheable: Bool {
        let scheme = self.scheme
        return scheme != "file" && scheme != "data"
    }
}