/**
 * Question Link: https://leetcode.com/problems/longest-substring-without-repeating-characters/
 * Primary idea: Use a set to hold characters and then iterate the string,
 *               update maxLen, set, startIdx encountering duplicates
 *
 * Note: Swift does not have a way to access a character in a string with O(1),
 *       thus we have to first transfer the string to a character array
 * Time Complexity: O(n), Space Complexity: O(n)
 *
 */

class LongestSubstringWithoutRepeatingCharacters {
    func lengthOfLongestSubstring(s: String) -> Int {
        var left = 0, right = 0, substring = Set<Character>(), longest = 0
        let sChars = Array(s)

        while right < sChars.count {
            let currentChar = sChars[right]

            if substring.contains(currentChar) {
                longest = max(longest, right - left)
                substring.remove(sChars[left])
                left += 1
            } else {
                substring.insert(currentChar)
                right += 1

                if right == sChars.count {
                    longest = max(longest, right - left)
                }
            }
        }

        return longest
    }
}

Update solution to Longest Substring Without Repeating Characters

/**
 * Question Link: https://leetcode.com/problems/longest-substring-without-repeating-characters/
 * Primary idea: Use a set to hold characters and then iterate the string,
 *               update maxLen, set, startIdx encountering duplicates
 *
 * Note: Swift does not have a way to access a character in a string with O(1),
 *       thus we have to first transfer the string to a character array
 * Time Complexity: O(n), Space Complexity: O(n)
 *
 */

class LongestSubstringWithoutRepeatingCharacters {
    func lengthOfLongestSubstring(_ s: String) -> Int {
        var longest = 0, left = 0, set = Set<Character>()
        let sChars = Array(s)

        for (i, char) in sChars.enumerated() {
            if set.contains(char) {

                longest = max(longest, i - left)

                while sChars[left] != char {
                    set.remove(sChars[left])
                    left += 1
                }
                left += 1

            } else {
                set.insert(char)
            }
        }

        return max(longest, sChars.count - left)
    }
}


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

@dispatch=WORKER
(string output) javascript(string code) "turbine" "0.1.0"
    [ "set <<output>> [ turbine::javascript <<code>> ]" ];

Put all JVM stuff here

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

@dispatch=WORKER
(string output) javascript(string code, string expr) "turbine" "0.1.0"
    [ "set <<output>> [ javascript::eval <<code>> ]" ];

@dispatch=WORKER
  (string output) groovy(string code, string expr)
    "turbine" "0.1.0"
    [ "set <<output>> [ groovy::eval <<code>> <<expr>> ]" ];


// Ensure that the LLVMIR hash of the 2nd compilation in batch mode
// is consistent no matter if the first one generates code or not.

// RUN: %empty-directory(%t)
// RUN: echo 'public enum E: Error {}' >%t/main.swift
// RUN: echo >%t/other.swift
// RUN: touch -t 201901010101 %t/*.swift

// RUN: cd %t; %target-swift-frontend -c -g -enable-batch-mode -module-name main -primary-file ./main.swift -primary-file other.swift

// RUN: cp %t/main{,-old}.o
// RUN: cp %t/other{,-old}.o
// RUN: %{python} %S/Inputs/make-old.py %t/*.swift

// RUN: cd %t; %target-swift-frontend -c -g -enable-batch-mode -module-name main -primary-file ./main.swift -primary-file other.swift

// Ensure that code generation was not performed for other.swift

// RUN: ls -t %t | %FileCheck %s

// CHECK: other.swift
// CHECK: other.o

Fix the path to make-old.py

// Ensure that the LLVMIR hash of the 2nd compilation in batch mode
// is consistent no matter if the first one generates code or not.

// RUN: %empty-directory(%t)
// RUN: echo 'public enum E: Error {}' >%t/main.swift
// RUN: echo >%t/other.swift
// RUN: touch -t 201901010101 %t/*.swift

// RUN: cd %t; %target-swift-frontend -c -g -enable-batch-mode -module-name main -primary-file ./main.swift -primary-file other.swift

// RUN: cp %t/main{,-old}.o
// RUN: cp %t/other{,-old}.o
// RUN: %{python} %S/../Inputs/make-old.py %t/*.swift

// RUN: cd %t; %target-swift-frontend -c -g -enable-batch-mode -module-name main -primary-file ./main.swift -primary-file other.swift

// Ensure that code generation was not performed for other.swift

// RUN: ls -t %t | %FileCheck %s

// CHECK: other.swift
// CHECK: other.o


// RUN: %target-run-simple-swift(-I %S/Inputs -Xfrontend -enable-cxx-interop -Xcc -fno-exceptions)
//
// REQUIRES: executable_test
//
// Enable this everywhere once we have a solution for modularizing libstdc++: rdar://87654514
// REQUIRES: OS=macosx

import DefineReferencedInline
import StdlibUnittest

var TemplatesTestSuite = TestSuite("TemplatesTestSuite")

TemplatesTestSuite.test("tests") {
  let a = CtorCallsInlineFn<CInt>(0)
  let b = HasInlineDtor<CInt>()
  let c = ParentWithChildWithInlineCtorDtor<CInt>()
  let d = HolderWithChildWithInlineCtorDtor<CInt>()
  let e = DtorCallsInlineMethod<CInt>()
}

runAllTests()

Enable a test on Linux

// RUN: %target-run-simple-swift(-I %S/Inputs -Xfrontend -enable-cxx-interop -Xcc -fno-exceptions)
//
// REQUIRES: executable_test

import DefineReferencedInline
import StdlibUnittest

var TemplatesTestSuite = TestSuite("TemplatesTestSuite")

TemplatesTestSuite.test("tests") {
  let a = CtorCallsInlineFn<CInt>(0)
  let b = HasInlineDtor<CInt>()
  let c = ParentWithChildWithInlineCtorDtor<CInt>()
  let d = HolderWithChildWithInlineCtorDtor<CInt>()
  let e = DtorCallsInlineMethod<CInt>()
}

runAllTests()


//
//  PostCollectionViewCell.swift
//  FlingChallenge
//
//  Created by Alexander Kolov on 9/5/16.
//  Copyright © 2016 Alexander Kolov. All rights reserved.
//

import UIKit

class PostCollectionViewCell: UICollectionViewCell {

  @IBOutlet weak var imageView: RemoteImageView!

  @IBOutlet weak var titleLabel: UILabel! {
    didSet {
      titleLabel.layer.shadowOffset = CGSize(width: 1, height: 1)
      titleLabel.layer.shadowColor = UIColor.blackColor().CGColor
      titleLabel.layer.shadowOpacity = 0.6
      titleLabel.layer.shadowRadius = 1
    }
  }

  @IBOutlet weak var authorLabel: UILabel!

  @IBOutlet weak var bottomSeparatorHeightConstraint: NSLayoutConstraint! {
    didSet {
      bottomSeparatorHeightConstraint.constant = 0.5
    }
  }

  override func awakeFromNib() {
    super.awakeFromNib()
    contentView.layoutMargins = UIEdgeInsetsZero
  }

  override func prepareForReuse() {
    super.prepareForReuse()
    imageView.cancelImageLoadingOperation()
  }

}

Apply rounded corners when showing more than one column

//
//  PostCollectionViewCell.swift
//  FlingChallenge
//
//  Created by Alexander Kolov on 9/5/16.
//  Copyright © 2016 Alexander Kolov. All rights reserved.
//

import UIKit

class PostCollectionViewCell: UICollectionViewCell {

  @IBOutlet weak var imageView: RemoteImageView!

  @IBOutlet weak var titleLabel: UILabel! {
    didSet {
      titleLabel.layer.shadowOffset = CGSize(width: 1, height: 1)
      titleLabel.layer.shadowColor = UIColor.blackColor().CGColor
      titleLabel.layer.shadowOpacity = 0.6
      titleLabel.layer.shadowRadius = 1
    }
  }

  @IBOutlet weak var authorLabel: UILabel!

  @IBOutlet weak var bottomSeparatorHeightConstraint: NSLayoutConstraint! {
    didSet {
      bottomSeparatorHeightConstraint.constant = 0.5
    }
  }

  override func awakeFromNib() {
    super.awakeFromNib()
    contentView.layoutMargins = UIEdgeInsetsZero
  }

  override func prepareForReuse() {
    super.prepareForReuse()
    imageView.cancelImageLoadingOperation()
  }

  override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
    switch (traitCollection.horizontalSizeClass, traitCollection.verticalSizeClass) {
    case (.Compact, .Regular):
      imageView.layer.cornerRadius = 0
      imageView.layer.masksToBounds = false
    default:
      imageView.layer.cornerRadius = 3
      imageView.layer.masksToBounds = true
    }
  }

}


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

final class ValueTests: XCTestCase {
	func testQuotation() {
		assert(Value.pi(.Type, id).quote, ==, Value.pi(.Type, id).quote)
	}

	func testNestedQuotation() {
		assert(Value.pi(.Type) { Value.pi(.Type, const($0)) }.quote, ==, Term(.Pi(0, Box(.type), Box(Term(.Pi(1, Box(.type), Box(Term(.Bound(0)))))))))
	}

	func testQuotationMapsQuotedVariablesToBoundVariables() {
		assert(Value.Free(.Quote(1)).quote, ==, Term(.Bound(1)))
	}

	func testQuotationMapsNestedBoundVariablesToBoundVariables() {
		assert(Value.Pi(Box(.Type)) { _ in Either.right(Value.Pi(Box(.Type), Either.right)) }.quote, ==, Term(.Pi(0, Box(.type), Box(Term(.Pi(1, Box(.type), Box(Term(.Bound(1)))))))))
	}
}

import Assertions
import Box
import Either
import Manifold
import Prelude
import XCTest

Use parameters in the tests.

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

final class ValueTests: XCTestCase {
	func testQuotation() {
		assert(Value.pi(.Type, id).quote, ==, Value.pi(.Type, id).quote)
	}

	func testNestedQuotation() {
		assert(Value.pi(.Type) { Value.pi(.Type, const($0)) }.quote, ==, Term(.Pi(0, Box(.type), Box(Term(.Pi(1, Box(.type), Box(Term(.Bound(0)))))))))
	}

	func testQuotationMapsQuotedVariablesToBoundVariables() {
		assert(Value.parameter(.Quote(1)).quote, ==, Term(.Bound(1)))
	}

	func testQuotationMapsNestedBoundVariablesToBoundVariables() {
		assert(Value.Pi(Box(.Type)) { _ in Either.right(Value.Pi(Box(.Type), Either.right)) }.quote, ==, Term(.Pi(0, Box(.type), Box(Term(.Pi(1, Box(.type), Box(Term(.Bound(1)))))))))
	}
}

import Assertions
import Box
import Either
import Manifold
import Prelude
import XCTest


import UIKit
import DateTools

public class DayViewController: UIViewController {

  lazy var dayView: DayView = DayView()

  override public func viewDidLoad() {
    super.viewDidLoad()
    self.edgesForExtendedLayout = UIRectEdge.None
    view.addSubview(dayView)
    view.tintColor = UIColor.redColor()

    dayView.dataSource = self
  }

  public override func viewDidLayoutSubviews() {
    dayView.fillSuperview()
  }
}

extension DayViewController: DayViewDataSource {
  func eventViewsForDate(date: NSDate) -> [EventView] {

    let datePeriod = DTTimePeriod(size: .Hour, startingAt: date)
    let eventView = EventView()
    eventView.datePeriod = datePeriod

    return [eventView]
  }
}

Implement mock events in controller

import UIKit
import DateTools

public class DayViewController: UIViewController {

  lazy var dayView: DayView = DayView()

  override public func viewDidLoad() {
    super.viewDidLoad()
    self.edgesForExtendedLayout = UIRectEdge.None
    view.addSubview(dayView)
    view.tintColor = UIColor.redColor()

    dayView.dataSource = self
  }

  public override func viewDidLayoutSubviews() {
    dayView.fillSuperview()
  }
}

extension DayViewController: DayViewDataSource {
  func eventViewsForDate(date: NSDate) -> [EventView] {

    return generateMockEventsForDate(date)
  }

  func generateMockEventsForDate(var date: NSDate) -> [EventView] {
    var events = [EventView]()
    let step = 2

    date = date.dateByAddingMinutes(24)

    for _ in 0...5 {
      let event = EventView()
      let datePeriod = DTTimePeriod(size: .Hour, startingAt: date)
      event.datePeriod = datePeriod
      date = date.dateByAddingHours(step)
      events.append(event)
    }
    return events
  }
}


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

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

private let module = Module<Term>.either

@testable import Manifold
import XCTest

Test that the Either module has equivalent definitions to the ChurchEither module.

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

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

	func testAutomaticallyEncodedDefinitionsAreEquivalentToHandEncodedDefinitions() {
		let churchModule = Module<Term>.churchEither
		module.definitions.forEach { symbol, type, value in
			assert(churchModule.context[symbol], ==, type)
			assert(churchModule.environment[symbol], ==, value)
		}
	}
}

private let module = Module<Term>.either

import Assertions
@testable import Manifold
import XCTest


//
//  ContentListHeaderView.swift
//  JumuNordost
//
//  Created by Martin Richter on 02/03/16.
//  Copyright © 2016 Martin Richter. All rights reserved.
//

import Cartography

class ContestListHeaderView: UIView {

    private let textLabel = Label(fontWeight: .Regular, fontStyle: .Italic, fontSize: .Large)

    // MARK: - Lifecycle

    convenience init(text: String) {
        self.init()

        self.layoutMargins = UIEdgeInsets(top: 24, left: 16, bottom: 8, right: 16)

        textLabel.numberOfLines = 0
        textLabel.textAlignment = .Center
        textLabel.textColor = Color.secondaryTextColor
        textLabel.text = text

        addSubview(textLabel)
        makeConstraints()
    }

    // MARK: - Layout

    private func makeConstraints() {
        constrain(textLabel, self) { textLabel, superview in
            textLabel.edges == superview.edgesWithinMargins
        }
    }
}

Make text in contest list's header smaller

//
//  ContentListHeaderView.swift
//  JumuNordost
//
//  Created by Martin Richter on 02/03/16.
//  Copyright © 2016 Martin Richter. All rights reserved.
//

import Cartography

class ContestListHeaderView: UIView {

    private let textLabel = Label(fontWeight: .Regular, fontStyle: .Italic, fontSize: .Medium)

    // MARK: - Lifecycle

    convenience init(text: String) {
        self.init()

        self.layoutMargins = UIEdgeInsets(top: 24, left: 16, bottom: 8, right: 16)

        textLabel.numberOfLines = 0
        textLabel.textAlignment = .Center
        textLabel.textColor = Color.secondaryTextColor
        textLabel.text = text

        addSubview(textLabel)
        makeConstraints()
    }

    // MARK: - Layout

    private func makeConstraints() {
        constrain(textLabel, self) { textLabel, superview in
            textLabel.edges == superview.edgesWithinMargins
        }
    }
}


//
//  NutritionManager.swift
//  WeeklyFoodPlan
//
//  Created by vulgur on 2016/12/29.
//  Copyright © 2016年 MAD. All rights reserved.
//

import Foundation
import ObjectMapper

struct NutritionManager {
    static func nutritionList() -> [Nutrition] {
        if let path = Bundle.main.path(forResource: "nutritions", ofType: "json") {
            print(path)
            if let jsonData = NSData(contentsOfFile: path) {
                if let jsonString = String.init(data: jsonData as Data, encoding: .utf8) {
                    let list = Mapper<Nutrition>().mapArray(JSONString: jsonString)
                    return list!
                }
            }
        }

        return []
    }
}

Add if-let to return value

//
//  NutritionManager.swift
//  WeeklyFoodPlan
//
//  Created by vulgur on 2016/12/29.
//  Copyright © 2016年 MAD. All rights reserved.
//

import Foundation
import ObjectMapper

struct NutritionManager {
    static func nutritionList() -> [Nutrition] {
        if let path = Bundle.main.path(forResource: "nutritions", ofType: "json") {
            print(path)
            if let jsonData = NSData(contentsOfFile: path) {
                if let jsonString = String.init(data: jsonData as Data, encoding: .utf8) {
                    if let list = Mapper<Nutrition>().mapArray(JSONString: jsonString) {
                        return list
                    }
                }
            }
        }

        return []
    }
}


//
//  Outdated.swift
//  mas-cli
//
//  Created by Andrew Naylor on 21/08/2015.
//  Copyright (c) 2015 Andrew Naylor. All rights reserved.
//

struct OutdatedCommand: CommandType {
    let verb = "outdated"
    let function = "Lists pending updates from the Mac App Store"

    func run(mode: CommandMode) -> Result<(), CommandantError<MASError>> {
        switch mode {
        case .Arguments:
            let updateController = CKUpdateController.sharedUpdateController()
            let updates = updateController.availableUpdates() as! [CKUpdate]
            for update in updates {
                print("\(update.itemIdentifier) \(update.title)")
            }
        default:
            break
        }
        return .Success(())
    }
}

Include the new version number in outdated

//
//  Outdated.swift
//  mas-cli
//
//  Created by Andrew Naylor on 21/08/2015.
//  Copyright (c) 2015 Andrew Naylor. All rights reserved.
//

struct OutdatedCommand: CommandType {
    let verb = "outdated"
    let function = "Lists pending updates from the Mac App Store"

    func run(mode: CommandMode) -> Result<(), CommandantError<MASError>> {
        switch mode {
        case .Arguments:
            let updateController = CKUpdateController.sharedUpdateController()
            let updates = updateController.availableUpdates() as! [CKUpdate]
            for update in updates {
                print("\(update.itemIdentifier) \(update.title) (\(update.bundleVersion))")
            }
        default:
            break
        }
        return .Success(())
    }
}


// RUN: %target-typecheck-verify-swift

// SR-7884
func f<T>(_ x: T) -> T {
  return x
}

func f<T>(_ x: T?) -> T? {
  return x
}

let r = f(1) // calls optional variant
let _ = r! // expected-error {{cannot force unwrap value of non-optional type 'Int'}}

// SR-7899
let optSeq: LazySequence<[Int]>? = nil
let lazySequence = optSeq?.lazy
let value = lazySequence?.compactMap({ $0 as? Int }).first // expected-warning {{conditional cast from 'Int' to 'Int' always succeeds}}
let _: Int = value!

Remove incorrect comment in test file.

// RUN: %target-typecheck-verify-swift

// SR-7884
func f<T>(_ x: T) -> T {
  return x
}

func f<T>(_ x: T?) -> T? {
  return x
}

let r = f(1)
let _ = r! // expected-error {{cannot force unwrap value of non-optional type 'Int'}}

// SR-7899
let optSeq: LazySequence<[Int]>? = nil
let lazySequence = optSeq?.lazy
let value = lazySequence?.compactMap({ $0 as? Int }).first // expected-warning {{conditional cast from 'Int' to 'Int' always succeeds}}
let _: Int = value!


//
//  BetterSegmentedControl+PredefinedStyles.swift
//  BetterSegmentedControl
//
//  Created by George Marmaridis on 18.10.20.
//

import UIKit

public extension BetterSegmentedControl {
     class func appleStyled(frame: CGRect, titles: [String]) -> BetterSegmentedControl {
        let control = BetterSegmentedControl(
            frame: frame,
            segments: LabelSegment.segments(withTitles: titles,
                                            normalFont: .systemFont(ofSize: 13.0),
                                            normalTextColor: .appleSegmentedControlDefaultSegmentText,
                                            selectedFont: .systemFont(ofSize: 13.0, weight: .medium),
                                            selectedTextColor: .appleSegmentedControlDefaultSegmentText),
            index: 0,
            options: [.backgroundColor(.appleSegmentedControlDefaultControlBackground),
                      .indicatorViewBackgroundColor(.appleSegmentedControlDefaultIndicatorBackground),
                      .cornerRadius(8),
                      .indicatorViewInset(2)])
        control.indicatorView.layer.shadowColor = UIColor.black.cgColor
        control.indicatorView.layer.shadowOpacity = 0.1
        control.indicatorView.layer.shadowOffset = CGSize(width: 1, height: 1)
        control.indicatorView.layer.shadowRadius = 2

        return control
    }
}

Simplify implementation of `appleStyled` extension

//
//  BetterSegmentedControl+PredefinedStyles.swift
//  BetterSegmentedControl
//
//  Created by George Marmaridis on 18.10.20.
//

import UIKit

public extension BetterSegmentedControl {
     class func appleStyled(frame: CGRect, titles: [String]) -> BetterSegmentedControl {
        let control = BetterSegmentedControl(
            frame: frame,
            segments: LabelSegment.segments(withTitles: titles),
            options: [.cornerRadius(8)])
        control.indicatorView.layer.shadowColor = UIColor.black.cgColor
        control.indicatorView.layer.shadowOpacity = 0.1
        control.indicatorView.layer.shadowOffset = CGSize(width: 1, height: 1)
        control.indicatorView.layer.shadowRadius = 2

        return control
    }
}


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

// RUN: not --crash %target-swift-frontend %s -emit-ir
protocol A:A&CLong

Disable a test that seems to infinitely recurse on a diagnostic sometimes.

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

// RUN: not --crash %target-swift-frontend %s -emit-ir
// REQUIRES: rdar38932729
protocol A:A&CLong


import Foundation
import QuartzCore

extension UINavigationBar {

    func wmf_applyGalleryTopGradientBackground() {
        if (!CGRectIsNull(bounds)){
            if (CGRectGetWidth(bounds) > 0 && CGRectGetHeight(bounds) > 0){
                setBackgroundImage(wmf_galleryTopGradientBackgroundImage(), forBarMetrics: .Default)
            }
        }
    }

    func wmf_galleryTopGradientBackgroundImage() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)

        let context = UIGraphicsGetCurrentContext()

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let locations:[CGFloat] = [0.0, 0.78, 1.0]
        let top = UIColor.blackColor().CGColor
        let middle = UIColor.blackColor().CGColor
        let bottom = UIColor.clearColor().CGColor

        let gradient = CGGradientCreateWithColors(colorSpace, [top, middle, bottom], locations)

        let start = CGPoint(x: 0, y: 0)
        let end = CGPoint(x: 0, y: CGRectGetHeight(bounds))

        CGContextDrawLinearGradient(context!, gradient!, start, end, [])

        let finalImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return finalImage!
    }
}

Revert "Adjust top gradient stops to better match mock."

import Foundation
import QuartzCore

extension UINavigationBar {

    func wmf_applyGalleryTopGradientBackground() {
        if (!CGRectIsNull(bounds)){
            if (CGRectGetWidth(bounds) > 0 && CGRectGetHeight(bounds) > 0){
                setBackgroundImage(wmf_galleryTopGradientBackgroundImage(), forBarMetrics: .Default)
            }
        }
    }

    func wmf_galleryTopGradientBackgroundImage() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)

        let context = UIGraphicsGetCurrentContext()

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let locations:[CGFloat] = [0.0, 1.0]
        let bottom = UIColor.clearColor().CGColor
        let top = UIColor.blackColor().CGColor

        let gradient = CGGradientCreateWithColors(colorSpace, [top, bottom], locations)

        let start = CGPoint(x: 0, y: 0)
        let end = CGPoint(x: 0, y: CGRectGetHeight(bounds))

        CGContextDrawLinearGradient(context!, gradient!, start, end, [])

        let finalImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return finalImage!
    }
}


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

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

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

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

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


// Sources/SwiftProtobufPluginLibrary/ProvidesLocationPath.swift - Proto Field numbers
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------

import Foundation

public protocol ProvidesLocationPath {
  func getLocationPath(path: inout [Int32])
  weak var file: FileDescriptor! { get }
}

Drop `weak` from the protocol as it has no meaning.

// Sources/SwiftProtobufPluginLibrary/ProvidesLocationPath.swift - Proto Field numbers
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------

import Foundation

public protocol ProvidesLocationPath {
  func getLocationPath(path: inout [Int32])
  var file: FileDescriptor! { get }
}


import UIKit

class DayView: UIView {

  var headerHeight: CGFloat = 88

  let dayHeaderView = DayHeaderView()
  let timelinePager = PagingScrollView()

  override init(frame: CGRect) {
    super.init(frame: frame)
    configure()
  }

  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    configure()
    addSubview(dayHeaderView)
  }

  func configure() {
    configureTimelinePager()
  }

  func configureTimelinePager() {
    for _ in 0...2 {
      print("asd")
      let timeline = TimelineView(frame: bounds)
      timeline.frame.size.height = timeline.fullHeight

      let verticalScrollView = UIScrollView(frame: bounds)
      verticalScrollView.addSubview(timeline)
      verticalScrollView.contentSize = timeline.frame.size

      timelinePager.addSubview(verticalScrollView)
      timelinePager.reusableViews.append(verticalScrollView)
    }

    let contentWidth = CGFloat(timelinePager.reusableViews.count) * bounds.width
    let contentHeight = timelinePager.reusableViews.first!.bounds.height
    let size = CGSize(width: contentWidth, height: contentHeight)
    timelinePager.contentSize = size

    addSubview(timelinePager)
  }

  override func layoutSubviews() {
var rect = bounds
    rect.size.height = headerHeight

    dayHeaderView.frame = rect

//    timelinePager.frame = bounds
  }
}

Add subview in proper place

import UIKit

class DayView: UIView {

  var headerHeight: CGFloat = 88

  let dayHeaderView = DayHeaderView()
  let timelinePager = PagingScrollView()

  override init(frame: CGRect) {
    super.init(frame: frame)
    configure()
  }

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

  func configure() {
    configureTimelinePager()
    addSubview(dayHeaderView)
  }

  func configureTimelinePager() {
    for _ in 0...2 {
      let timeline = TimelineView(frame: bounds)
      timeline.frame.size.height = timeline.fullHeight

      let verticalScrollView = UIScrollView(frame: bounds)
      verticalScrollView.addSubview(timeline)
      verticalScrollView.contentSize = timeline.frame.size

      timelinePager.addSubview(verticalScrollView)
      timelinePager.reusableViews.append(verticalScrollView)
    }

    let contentWidth = CGFloat(timelinePager.reusableViews.count) * bounds.width
    let contentHeight = timelinePager.reusableViews.first!.bounds.height
    let size = CGSize(width: contentWidth, height: contentHeight)
    timelinePager.contentSize = size

    addSubview(timelinePager)
  }

  override func layoutSubviews() {
var rect = bounds
    rect.size.height = headerHeight

    dayHeaderView.frame = rect

//    timelinePager.frame = bounds
  }
}


//
//  Request.swift
//  Pods
//
//  Created by Kilian Költzsch on 16/11/2016.
//
//

import Foundation

public protocol Request {}

Add servicerequest and requestpayload wrappers

//
//  Request.swift
//  Triassic
//
//  Created by Kilian Költzsch on 16/11/2016.
//  Copyright © 2016 Triassic Park. All rights reserved.
//

import Foundation

public struct ServiceRequest {
    public let payload: RequestPayload
}

public struct RequestPayload {
    public let request: Request
}

public protocol Request {}


//
//  ImageKeyboard.swift
//  KeyboardKit
//
//  Created by Daniel Saidi on 2020-09-13.
//  Copyright © 2021 Daniel Saidi. All rights reserved.
//

import KeyboardKit
import KeyboardKitSwiftUI
import SwiftUI

/**
 This keyboard is a custom view that is implemented for this
 project alone. It implements the shared `DemoImageKeyboard`
 and lists its images in a grid, where the number of columns
 depend on if the grid is presented in portrait or landscape.
 */
struct ImageKeyboard: View, DemoImageKeyboard {

    @EnvironmentObject var context: ObservableKeyboardContext

    var body: some View {
        KeyboardGrid(
            actions: actions,
            columns: isLandscape ? 8 : 6,
            spacing: 20,
            buttonBuilder: button)
    }
}

private extension ImageKeyboard {

    var isLandscape: Bool { context.controller.deviceOrientation.isLandscape }

    func button(for action: KeyboardAction) -> some View {
        KeyboardImageButton(action: action)
            .keyboardAction(action, context: context)
    }
}

Add globe button to image keyboard

//
//  ImageKeyboard.swift
//  KeyboardKit
//
//  Created by Daniel Saidi on 2020-09-13.
//  Copyright © 2021 Daniel Saidi. All rights reserved.
//

import KeyboardKit
import KeyboardKitSwiftUI
import SwiftUI

/**
 This keyboard is a custom view that is implemented for this
 project alone. It implements the shared `DemoImageKeyboard`
 and lists its images in a grid, where the number of columns
 depend on if the grid is presented in portrait or landscape.
 */
struct ImageKeyboard: View, DemoImageKeyboard {

    @EnvironmentObject var context: ObservableKeyboardContext

    var body: some View {
        VStack(spacing: 30) {
            KeyboardGrid(
                actions: actions,
                columns: columns,
                spacing: 20,
                buttonBuilder: imageButton)
            bottomRow.frame(height: 40)
        }.frame(height: 300)
    }
}

private extension ImageKeyboard {

    var columns: Int { isLandscape ? 8 : 6 }

    var isLandscape: Bool { context.controller.deviceOrientation.isLandscape }

    var bottomRow: some View {
        button(for: .nextKeyboard)
    }

    func button(for action: KeyboardAction) -> some View {
        SystemKeyboardButton(action: action)
    }

    func imageButton(for action: KeyboardAction) -> some View {
        KeyboardImageButton(action: action)
            .keyboardAction(action, context: context)
    }
}


//
//  HttpMethod.swift
//  HMRequestFramework
//
//  Created by Hai Pham on 5/7/17.
//  Copyright © 2017 Holmusk. All rights reserved.
//

import SwiftUtilities

public enum HttpOperation: EnumerableType {
    case get
    case post
    case head
    case put
    case upload

    public static func allValues() -> [HttpOperation] {
        return [.get, .post, .head, .put, .upload]
    }

    public func method() -> String {
        switch self {
        case .get:
            return "GET"

        case .post, .upload:
            return "POST"

        case .head:
            return "HEAD"

        case .put:
            return "PUT"
        }
    }

    /// Check if the current method requires a HTTP body.
    ///
    /// - Returns: A Bool value.
    public func requiresBody() -> Bool {
        switch self {
        case .post, .put, .upload:
            return true;

        default:
            return false
        }
    }
}

Add patch to http operation

//
//  HttpMethod.swift
//  HMRequestFramework
//
//  Created by Hai Pham on 5/7/17.
//  Copyright © 2017 Holmusk. All rights reserved.
//

import SwiftUtilities

public enum HttpOperation: EnumerableType {
    case get
    case post
    case patch
    case head
    case put
    case upload

    public static func allValues() -> [HttpOperation] {
        return [.get, .post, .patch, .head, .put, .upload]
    }

    public func method() -> String {
        switch self {
        case .get:
            return "GET"

        case .post, .upload:
            return "POST"

        case .patch:
            return "PATCH"

        case .head:
            return "HEAD"

        case .put:
            return "PUT"

        }
    }

    /// Check if the current method requires a HTTP body.
    ///
    /// - Returns: A Bool value.
    public func requiresBody() -> Bool {
        switch self {
        case .post, .put, .upload, .patch:
            return true;

        default:
            return false
        }
    }
}


//
//  Data+Extensions.swift
//  PunyCocoa Swift
//
//  Created by Nate Weaver on 2020-04-12.
//

import Foundation
import zlib

extension Data {

	/// Compute the CRC-32 of the data.
	///
	/// Does not handle data with a `count` larger than `UInt32.max` on macOS
	/// < 10.13 or on iOS < 11.0.
	var crc32: UInt32 {
		return self.withUnsafeBytes {
			let buffer = $0.bindMemory(to: UInt8.self)

			if #available(macOS 10.13, iOS 11.0, tvOS 9999.0, watchOS 9999.0, *) {
				let initial = zlib.crc32_z(0, nil, 0)
				return UInt32(zlib.crc32_z(initial, buffer.baseAddress, buffer.count))
			} else {
				let initial = zlib.crc32(0, nil, 0)
				return UInt32(zlib.crc32(initial, buffer.baseAddress, UInt32(buffer.count)))
			}
		}
	}

}

Use correct tvOS and watchOS versions

//
//  Data+Extensions.swift
//  PunyCocoa Swift
//
//  Created by Nate Weaver on 2020-04-12.
//

import Foundation
import zlib

extension Data {

	/// Compute the CRC-32 of the data.
	///
	/// Does not handle data with a `count` larger than `UInt32.max` on macOS
	/// < 10.13 or on iOS < 11.0.
	var crc32: UInt32 {
		return self.withUnsafeBytes {
			let buffer = $0.bindMemory(to: UInt8.self)

			if #available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) {
				let initial = zlib.crc32_z(0, nil, 0)
				return UInt32(zlib.crc32_z(initial, buffer.baseAddress, buffer.count))
			} else {
				let initial = zlib.crc32(0, nil, 0)
				return UInt32(zlib.crc32(initial, buffer.baseAddress, UInt32(buffer.count)))
			}
		}
	}

}


//  Copyright © 2017 Peekazoo. All rights reserved.
//

import Foundation

struct WeasylHomepageFeed: HomepageFeed {

    struct WeasylHomepageItem: HomepageItem {

        var contentIdentifier: String
        var title: String

    }

    let homepageURL = URL(string: "https://www.weasyl.com/api/submissions/frontpage")!

    func loadFeed(networkAdapter: NetworkAdapter, delegate: HomepageFeedDelegate) {
        networkAdapter.get(homepageURL) { data, _ in
            if let data = data {
                self.parseHomepageItems(from: data, delegate: delegate)
            } else {
                delegate.feedDidFailToLoad()
            }
        }
    }

    private func parseHomepageItems(from data: Data, delegate: HomepageFeedDelegate) {
        if let jsonObject = self.jsonObject(from: data) {
            delegate.feedDidFinishLoading(items: parse(jsonObject))
        } else {
            delegate.feedDidFailToLoad()
        }
    }

    private func jsonObject(from data: Data) -> [[String : Any]]? {
        return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)) as? [[String : Any]]
    }

    private func parse(_ jsonObject: [[String : Any]]) -> [HomepageItem] {
        var homepageItems = [HomepageItem]()
        for object in jsonObject {
            guard let title = object["title"] as? String,
                  let contentIdentifier = object["submitid"] as? Int else { continue }

            let item = WeasylHomepageItem(contentIdentifier: String(contentIdentifier), title: title)
            homepageItems.append(item)
        }

        return homepageItems
    }

}

Move item initialization into structure

//  Copyright © 2017 Peekazoo. All rights reserved.
//

import Foundation

struct WeasylHomepageFeed: HomepageFeed {

    struct WeasylHomepageItem: HomepageItem {

        var contentIdentifier: String
        var title: String

        fileprivate init?(jsonObject: [String : Any]) {
            guard let title = jsonObject["title"] as? String,
                  let contentIdentifier = jsonObject["submitid"] as? Int else { return nil }

            self.title = title
            self.contentIdentifier = String(contentIdentifier)
        }

    }

    let homepageURL = URL(string: "https://www.weasyl.com/api/submissions/frontpage")!

    func loadFeed(networkAdapter: NetworkAdapter, delegate: HomepageFeedDelegate) {
        networkAdapter.get(homepageURL) { data, _ in
            if let data = data {
                self.parseHomepageItems(from: data, delegate: delegate)
            } else {
                delegate.feedDidFailToLoad()
            }
        }
    }

    private func parseHomepageItems(from data: Data, delegate: HomepageFeedDelegate) {
        if let jsonObject = self.jsonObject(from: data) {
            delegate.feedDidFinishLoading(items: parse(jsonObject))
        } else {
            delegate.feedDidFailToLoad()
        }
    }

    private func jsonObject(from data: Data) -> [[String : Any]]? {
        return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)) as? [[String : Any]]
    }

    private func parse(_ jsonObject: [[String : Any]]) -> [HomepageItem] {
        return jsonObject.flatMap(WeasylHomepageItem.init)
    }

}


import FirebaseMessaging
import MobileCoreServices
import UIKit

class DebugTableViewController: UITableViewController {

    // MARK: Properties

    @IBOutlet private weak var fcmTokenLabel: UILabel!
    private lazy var actions: [IndexPath : () -> Void] = [
        IndexPath(item: 0, section: 0): self.copyFCMToPasteBoard
    ]

    // MARK: Overrides

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let value = Messaging.messaging().fcmToken else { return }
        fcmTokenLabel.text = value
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        actions[indexPath]?()
    }

    // MARK: Functions

    @IBAction private func doneButtonTapped(_ sender: Any) {
        dismiss(animated: true)
    }

    private func copyFCMToPasteBoard() {
        guard let value = Messaging.messaging().fcmToken else { return }
        UIPasteboard.general.setValue(value, forPasteboardType: kUTTypeRTF as String)

        let alert = UIAlertController(title: "FCM Copied", message: nil, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .cancel))
        present(alert, animated: true)
    }

}

Use plain text type identifier for FCM copying

import FirebaseMessaging
import MobileCoreServices
import UIKit

class DebugTableViewController: UITableViewController {

    // MARK: Properties

    @IBOutlet private weak var fcmTokenLabel: UILabel!
    private lazy var actions: [IndexPath : () -> Void] = [
        IndexPath(item: 0, section: 0): self.copyFCMToPasteBoard
    ]

    // MARK: Overrides

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let value = Messaging.messaging().fcmToken else { return }
        fcmTokenLabel.text = value
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        actions[indexPath]?()
    }

    // MARK: Functions

    @IBAction private func doneButtonTapped(_ sender: Any) {
        dismiss(animated: true)
    }

    private func copyFCMToPasteBoard() {
        guard let value = Messaging.messaging().fcmToken else { return }
        UIPasteboard.general.setValue(value, forPasteboardType: kUTTypePlainText as String)

        let alert = UIAlertController(title: "FCM Copied", message: nil, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .cancel))
        present(alert, animated: true)
    }

}


//
//  StreamImageCellPresenter.swift
//  Ello
//
//  Created by Sean on 2/18/15.
//  Copyright (c) 2015 Ello. All rights reserved.
//

import Foundation

public struct StreamImageCellPresenter {

    static func configure(
        cell:UICollectionViewCell,
        streamCellItem:StreamCellItem,
        streamKind: StreamKind,
        indexPath: NSIndexPath,
        currentUser: User?)
    {
        if let cell = cell as? StreamImageCell {
            if let photoData = streamCellItem.data as! ImageRegion? {

                var photoToLoad: NSURL?
                if photoData.asset != nil && photoData.asset!.isGif {
                    photoToLoad = photoData.asset?.optimized?.url
                }
                else if streamKind.isGridLayout {
                    photoToLoad = photoData.asset?.ldpi?.url
                }
                else {
                    photoToLoad = photoData.asset?.mdpi?.url
                }

                if let photoURL = photoToLoad {
                    cell.serverProvidedAspectRatio = StreamCellItemParser.aspectRatioForImageBlock(photoData)
                    cell.setImageURL(photoURL)
                }
                else if let photoURL = photoData.url {
                    cell.setImageURL(photoURL)
                }
            }
        }
    }

}

Load higher resultion images in streams.

//
//  StreamImageCellPresenter.swift
//  Ello
//
//  Created by Sean on 2/18/15.
//  Copyright (c) 2015 Ello. All rights reserved.
//

import Foundation

public struct StreamImageCellPresenter {

    static func configure(
        cell:UICollectionViewCell,
        streamCellItem:StreamCellItem,
        streamKind: StreamKind,
        indexPath: NSIndexPath,
        currentUser: User?)
    {
        if let cell = cell as? StreamImageCell {
            if let photoData = streamCellItem.data as! ImageRegion? {

                var photoToLoad: NSURL?
                if photoData.asset != nil && photoData.asset!.isGif {
                    photoToLoad = photoData.asset?.optimized?.url
                }
                else if streamKind.isGridLayout {
                    photoToLoad = photoData.asset?.mdpi?.url
                }
                else {
                    photoToLoad = photoData.asset?.hdpi?.url
                }

                if let photoURL = photoToLoad {
                    cell.serverProvidedAspectRatio = StreamCellItemParser.aspectRatioForImageBlock(photoData)
                    cell.setImageURL(photoURL)
                }
                else if let photoURL = photoData.url {
                    cell.setImageURL(photoURL)
                }
            }
        }
    }

}


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

import Foundation

extension UIAlertController {

}

Implement first version of show extension.

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

import Foundation
import ObjectiveC

private var alertWindowAssociationKey: UInt8 = 0

public extension UIAlertController {

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

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

    override public func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)

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


import Euler

Add example code to playground

import Foundation
import Euler

// Constants

𝑒

// Logic

¬true

// Arithmetic

3 × 4

// Sets

let prime: Set<Int> = [2, 3, 5, 7, 11]
let fibonacci: Set<Int> = [1, 1, 2, 3, 5, 8, 13]
prime ∩ fibonacci

// Sequences

∑[1, 2, 3, 4, 5]

// Vectors

[1, 2] ⋅ [3, 4]

// Comparison

7 ≠ 9

// Calculus

let f: (Double) -> Double = sin
let fPrime = f′

f(π)
fPrime(π)

// Functions

let g: (Double) -> Double = cos

(f ∘ g)(π)


//
//  FeedViewModel.swift
//  EmonCMSiOS
//
//  Created by Matt Galloway on 12/09/2016.
//  Copyright © 2016 Matt Galloway. All rights reserved.
//

import Foundation

import RxSwift
import RxCocoa
import Realm

class FeedViewModel {

  private let account: Account
  private let api: EmonCMSAPI
  private let feed: Feed

  private let disposeBag = DisposeBag()

  let name = Variable<String>("")
  let value = Variable<String>("")

  init(account: Account, api: EmonCMSAPI, feed: Feed) {
    self.account = account
    self.api = api
    self.feed = feed

    self.feed.rx.observe(String.self, "name")
      .map { $0 ?? "" }
      .bindTo(self.name)
      .addDisposableTo(self.disposeBag)

    self.feed.rx.observe(Double.self, "value")
      .map { $0 ?? 0 }
      .map { $0.prettyFormat() }
      .bindTo(self.value)
      .addDisposableTo(self.disposeBag)
  }

  func fetchData(at startTime: Date, until endTime: Date, interval: Int) -> Observable<[DataPoint]> {
    return self.api.feedData(account, id: self.feed.id, at: startTime, until: endTime, interval: interval)
  }

}

Add update method on feed view model

//
//  FeedViewModel.swift
//  EmonCMSiOS
//
//  Created by Matt Galloway on 12/09/2016.
//  Copyright © 2016 Matt Galloway. All rights reserved.
//

import Foundation

import RxSwift
import RxCocoa
import Realm

class FeedViewModel {

  private let account: Account
  private let api: EmonCMSAPI
  private let feed: Feed

  private let disposeBag = DisposeBag()

  let name = Variable<String>("")
  let value = Variable<String>("")

  init(account: Account, api: EmonCMSAPI, feed: Feed) {
    self.account = account
    self.api = api
    self.feed = feed

    self.feed.rx.observe(String.self, "name")
      .map { $0 ?? "" }
      .bindTo(self.name)
      .addDisposableTo(self.disposeBag)

    self.feed.rx.observe(Double.self, "value")
      .map { $0 ?? 0 }
      .map { $0.prettyFormat() }
      .bindTo(self.value)
      .addDisposableTo(self.disposeBag)
  }

  func fetchData(at startTime: Date, until endTime: Date, interval: Int) -> Observable<[DataPoint]> {
    return self.api.feedData(account, id: self.feed.id, at: startTime, until: endTime, interval: interval)
  }

  func update() -> Observable<()> {
    return self.api.feedFields(self.account, id: self.feed.id)
      .becomeVoidAndIgnoreElements()
  }

}


class Cache<T> {
    var cache: [String: T] = [:]

    init() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didRecieveMemoryWarning"), name: UIApplicationDidReceiveMemoryWarningNotification, object: .None)
    }

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

    func didRecieveMemoryWarning() {
        cache.removeAll(keepCapacity: false)
    }

    func itemForKey(key: String) -> T? {
        return cache[key]
    }

    func setItem(item: T, forKey key: String) {
        cache[key] = item
    }
}

Make cache an NSObject for notifications

class Cache<T>: NSObject {
    var cache: [String: T] = [:]

    override init() {
        super.init()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didRecieveMemoryWarning"), name: UIApplicationDidReceiveMemoryWarningNotification, object: .None)
    }

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

    func didRecieveMemoryWarning() {
        cache.removeAll(keepCapacity: false)
    }

    func itemForKey(key: String) -> T? {
        return cache[key]
    }

    func setItem(item: T, forKey key: String) {
        cache[key] = item
    }
}


//
//  ViewController.swift
//  GobanSampleProject
//
//  Created by Bobo on 3/19/16.
//  Copyright © 2016 Boris Emorine. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var gobanView: GobanView! {
        didSet {
            gobanManager = GobanManager(gobanView: gobanView)
            gobanView.gobanTouchDelegate = gobanManager
        }
    }

    var gobanManager: GobanManager?

    override func viewDidLoad() {
        super.viewDidLoad()
        gobanView.gobanSize = GobanSize(width: 9, height: 9)
    }

    @IBAction func didTapClearGobanButton(sender: AnyObject) {
        gobanManager?.removeAllStones()
    }

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

Change goban size to 13x13.

//
//  ViewController.swift
//  GobanSampleProject
//
//  Created by Bobo on 3/19/16.
//  Copyright © 2016 Boris Emorine. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var gobanView: GobanView! {
        didSet {
            gobanManager = GobanManager(gobanView: gobanView)
            gobanView.gobanTouchDelegate = gobanManager
        }
    }

    var gobanManager: GobanManager?

    override func viewDidLoad() {
        super.viewDidLoad()
        gobanView.gobanSize = GobanSize(width: 13, height: 13)
    }

    @IBAction func didTapClearGobanButton(sender: AnyObject) {
        gobanManager?.removeAllStones()
    }

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


//
//  FirebaseModel+Extension.swift
//  FirebaseCommunity
//
//  Created by Victor Alisson on 15/08/17.
//

import Foundation
import FirebaseCommunity

public extension FirebaseModel {
    typealias JSON = [String: Any]

    internal static var classPath: DatabaseReference {
        return reference.child(Self.className)
    }
    static var reference: DatabaseReference {
        return Database.database().reference()
    }
    internal static var className: String {
        return String(describing: self)
    }
    internal static var autoId: String {
        return Self.reference.childByAutoId().key
    }
    func toJSONObject() -> JSON? {
        return toJSON()
    }
}

Add conversion with functional operators for deserialization

//
//  FirebaseModel+Extension.swift
//  FirebaseCommunity
//
//  Created by Victor Alisson on 15/08/17.
//

import Foundation
import FirebaseCommunity

public extension FirebaseModel {
    typealias JSON = [String: Any]

    internal static var classPath: DatabaseReference {
        return reference.child(Self.className)
    }
    static var reference: DatabaseReference {
        return Database.database().reference()
    }
    internal static var className: String {
        return String(describing: self)
    }
    internal static var autoId: String {
        return Self.reference.childByAutoId().key
    }
    func toJSONObject() -> JSON? {
        return toJSON()
    }
    internal static func getFirebaseModels(_ snapshot: DataSnapshot) -> [Self]? {
        let dataSnapshot = snapshot.children.allObjects as? [DataSnapshot]
        let keys = dataSnapshot?.map({$0.key})
        let arraySelf = dataSnapshot?.flatMap({Self.deserialize(from: $0.value as? NSDictionary)})
        if let firebaseModels = arraySelf {
            for firebaseModel in firebaseModels {keys?.forEach({firebaseModel.key = $0})}
        }
        return arraySelf
    }
}


/*
 The MIT License (MIT)

 Copyright (c) 2015 Shun Takebayashi

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
*/

#if os(OSX)
    import Darwin
#elseif os(Linux)
    import Glibc
#endif

enum WriterError: ErrorType {
    case GenericError(error: Int32)
}

public class HTTPResponseWriter {

    let socket: Int32

    init(socket: Int32) {
        self.socket = socket
    }

    public func write(bytes: UnsafePointer<Int8>) throws {
        if send(socket, bytes, Int(strlen(bytes)), 0) < 0 {
            throw WriterError.GenericError(error: errno)
        }
    }

}

Fix problems that HTTP response is broken

/*
 The MIT License (MIT)

 Copyright (c) 2015 Shun Takebayashi

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
*/

#if os(OSX)
    import Darwin
#elseif os(Linux)
    import Glibc
#endif

enum WriterError: ErrorType {
    case GenericError(error: Int32)
}

public class HTTPResponseWriter {

    let socket: Int32

    init(socket: Int32) {
        self.socket = socket
    }

    public func write(bytes: UnsafePointer<Int8>) throws {
        if send(socket, bytes, Int(strlen(bytes)) + 1, 0) < 0 {
            throw WriterError.GenericError(error: errno)
        }
    }

}


// RUN: %target-typecheck-verify-swift

// With a bit of effort, we could make this work -- but for now, let's just
// not crash.

protocol P {
  var x: Int { get set } // expected-note {{protocol requires property 'x' with type 'Int'; do you want to add a stub?}}
}

struct S : P { // expected-error {{type 'S' does not conform to protocol 'P'}}
  static var x = 0 // expected-note {{candidate operates on a type, not an instance as required}}
  var x = S.x // expected-note {{candidate references itself}}
}

Add a test for circular protocol inheritance through a typealias

// RUN: %target-typecheck-verify-swift

// With a bit of effort, we could make this work -- but for now, let's just
// not crash.

protocol P {
  var x: Int { get set } // expected-note {{protocol requires property 'x' with type 'Int'; do you want to add a stub?}}
}

struct S : P { // expected-error {{type 'S' does not conform to protocol 'P'}}
  static var x = 0 // expected-note {{candidate operates on a type, not an instance as required}}
  var x = S.x // expected-note {{candidate references itself}}
}

// FIXME: Lousy diagnostics on this case.
protocol SR9224_Foo: SR9224_Foobar {} // expected-error 2 {{protocol 'SR9224_Foo' refines itself}}
protocol SR9224_Bar: SR9224_Foobar {} // expected-error {{protocol 'SR9224_Bar' refines itself}} expected-note {{protocol 'SR9224_Bar' declared here}}
typealias SR9224_Foobar = SR9224_Foo & SR9224_Bar


//
//  DefaultClosureHandler.swift
//  InstantMock
//
//  Created by Patrick on 08/05/2017.
//  Copyright © 2017 pirishd. All rights reserved.
//

/** Helper that provides a simple way to create closure arguments with any argument and return value types */
class DefaultClosureHandler {

    /** Provide a default closure with provided signature */
    public static func it<ARGS, RET>() -> (ARGS) -> RET {
        let closure: (ARGS) -> RET = { args in return Void() as! RET }
        return closure
    }

}

Add default closures up to 5 args (due to SE-0110)

//
//  DefaultClosureHandler.swift
//  InstantMock
//
//  Created by Patrick on 08/05/2017.
//  Copyright © 2017 pirishd. All rights reserved.
//

/** Helper that provides a simple way to create closure arguments with any argument and return value types */
class DefaultClosureHandler {

    /** Provide a default closure with provided signature (no args) */
    public static func it<Ret>() -> () -> Ret {
        let closure: () -> Ret = { return Void() as! Ret }
        return closure
    }

    /** Provide a default closure with provided signature (one arg) */
    public static func it<Arg1, Ret>() -> (Arg1) -> Ret {
        let closure: (Arg1) -> Ret = { _ in return Void() as! Ret }
        return closure
    }

    /** Provide a default closure with provided signature (2 args) */
    public static func it<Arg1, Arg2, Ret>() -> (Arg1, Arg2) -> Ret {
        let closure: (Arg1, Arg2) -> Ret = { _, _ in return Void() as! Ret }
        return closure
    }

    /** Provide a default closure with provided signature (3 args) */
    public static func it<Arg1, Arg2, Arg3, Ret>() -> (Arg1, Arg2, Arg3) -> Ret {
        let closure: (Arg1, Arg2, Arg3) -> Ret = { _, _, _ in return Void() as! Ret }
        return closure
    }

    /** Provide a default closure with provided signature (4 args) */
    public static func it<Arg1, Arg2, Arg3, Arg4, Ret>() -> (Arg1, Arg2, Arg3, Arg4) -> Ret {
        let closure: (Arg1, Arg2, Arg3, Arg4) -> Ret = { _, _, _, _ in return Void() as! Ret }
        return closure
    }

}


import UIKit

struct FormSheetLoginModuleProviding: LoginModuleProviding {

    var loginModuleProviding: LoginModuleProviding

    func makeLoginModule(_ delegate: LoginModuleDelegate) -> UIViewController {
        let contentController = loginModuleProviding.makeLoginModule(delegate)
        let navigationController = UINavigationController(rootViewController: contentController)
        navigationController.modalPresentationStyle = .formSheet

        if #available(iOS 13.0, *) {
            navigationController.isModalInPresentation = true
        }

        return navigationController
    }

}

Remove requirement for sheet to be modal

import UIKit

struct FormSheetLoginModuleProviding: LoginModuleProviding {

    var loginModuleProviding: LoginModuleProviding

    func makeLoginModule(_ delegate: LoginModuleDelegate) -> UIViewController {
        let contentController = loginModuleProviding.makeLoginModule(delegate)
        let navigationController = UINavigationController(rootViewController: contentController)
        navigationController.modalPresentationStyle = .formSheet

        return navigationController
    }

}


//
//  UIViewController+Helpers.swift
//  SwiftPlusPlus
//
//  Created by Andrew J Wagner on 4/2/16.
//  Copyright © 2016 Drewag LLC. All rights reserved.
//

import Foundation

extension UIViewController {
    public func presentPopoverViewController(viewController: UIViewController, fromSourceView sourceView: UIView) {
        viewController.modalPresentationStyle = .Popover

        self.presentViewController(viewController, animated: true, completion: nil)

        viewController.popoverPresentationController!.permittedArrowDirections = .Any
        viewController.popoverPresentationController!.sourceView = sourceView
    }

    public func presentOverlayViewController(viewController: UIViewController) {
        viewController.modalPresentationStyle = .OverCurrentContext
        viewController.modalTransitionStyle = .CrossDissolve

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

Allow specifying source rect and arrow direction for popovers

//
//  UIViewController+Helpers.swift
//  SwiftPlusPlus
//
//  Created by Andrew J Wagner on 4/2/16.
//  Copyright © 2016 Drewag LLC. All rights reserved.
//

import Foundation

extension UIViewController {
    public func present(popoverViewController viewController: UIViewController, fromSourceView sourceView: UIView, sourceRect: CGRect? = nil, permittedArrowDirections: UIPopoverArrowDirection = .Any) {
        viewController.modalPresentationStyle = .Popover

        self.presentViewController(viewController, animated: true, completion: nil)

        viewController.popoverPresentationController!.permittedArrowDirections = permittedArrowDirections
        viewController.popoverPresentationController!.sourceView = sourceView
        if let sourceRect = sourceRect {
            viewController.popoverPresentationController!.sourceRect = sourceRect
        }
    }

    public func present(overlayViewController viewController: UIViewController) {
        viewController.modalPresentationStyle = .OverCurrentContext
        viewController.modalTransitionStyle = .CrossDissolve

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


class FilledView: NSView {

	var backgroundColor: NSColor? {
		didSet {
			self.setNeedsDisplayInRect(self.bounds)
		}
	}

	var cornerRadius: CGFloat? {
		didSet {
			self.setNeedsDisplayInRect(self.bounds)
		}
	}

	var borderColor: NSColor? {
		didSet {
			self.setNeedsDisplayInRect(self.bounds)
		}
	}

    override func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)

		if let b = backgroundColor {
			b.set()
			if let c = cornerRadius {
				let path = NSBezierPath(roundedRect: dirtyRect, xRadius: c, yRadius: c)
				path.addClip()
			}
			NSRectFill(dirtyRect)
		} else if let b = borderColor {
			b.set()
			let path = NSBezierPath(rect: dirtyRect)
			path.lineWidth = 0.5
			path.stroke()
		}
    }

}

Fix for vibrancy mode unread-count badge on some systems

class FilledView: NSView {

	var backgroundColor: NSColor? {
		didSet {
			self.setNeedsDisplayInRect(self.bounds)
		}
	}

	var cornerRadius: CGFloat? {
		didSet {
			self.setNeedsDisplayInRect(self.bounds)
		}
	}

	var borderColor: NSColor? {
		didSet {
			self.setNeedsDisplayInRect(self.bounds)
		}
	}

    override func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)

		if let b = backgroundColor {
			b.set()
			if let c = cornerRadius {
				let path = NSBezierPath(roundedRect: dirtyRect, xRadius: c, yRadius: c)
				path.addClip()
			}
			NSRectFill(dirtyRect)
		} else if let b = borderColor {
			b.set()
			let path = NSBezierPath(rect: dirtyRect)
			path.lineWidth = 0.5
			path.stroke()
		}
    }

	func allowsVibrancy() -> Bool {
		return true
	}
}


/*
 |  _   ____   ____   _
 | | |‾|  ⚈ |-| ⚈  |‾| |
 | | |  ‾‾‾‾| |‾‾‾‾  | |
 |  ‾        ‾        ‾
 */

import Foundation
import Reactor
import CloudKit

public struct FetchRecordZone<U: State>: Command {

    public var zoneID: CKRecordZoneID
    public var completion: ((Bool) -> Void)?

    public init(with zoneID: CKRecordZoneID, completion: ((Bool) -> Void)? = nil) {
        self.zoneID = zoneID
        self.completion = completion
    }

    public func execute(state: U, core: Core<U>) {
        let operation = CKFetchRecordZonesOperation(recordZoneIDs: [zoneID])
        operation.fetchRecordZonesCompletionBlock = { zonesDictionary, error in
            if let error = error {
                core.fire(event: CloudKitOperationUpdated(status: .errored(error), type: .fetch))
            } else {
                let found = zonesDictionary?[self.zoneID] != nil
                core.fire(event: CloudKitOperationUpdated(status: .completed, type: .fetch))
                self.completion?(found)
            }
        }
        operation.qualityOfService = .userInitiated
        CKContainer.default().privateCloudDatabase.add(operation)
    }

}

Call completion when zone not found

/*
 |  _   ____   ____   _
 | | |‾|  ⚈ |-| ⚈  |‾| |
 | | |  ‾‾‾‾| |‾‾‾‾  | |
 |  ‾        ‾        ‾
 */

import Foundation
import Reactor
import CloudKit

public struct FetchRecordZone<U: State>: Command {

    public var zoneID: CKRecordZoneID
    public var completion: ((Bool) -> Void)?

    public init(with zoneID: CKRecordZoneID, completion: ((Bool) -> Void)? = nil) {
        self.zoneID = zoneID
        self.completion = completion
    }

    public func execute(state: U, core: Core<U>) {
        let operation = CKFetchRecordZonesOperation(recordZoneIDs: [zoneID])
        operation.fetchRecordZonesCompletionBlock = { zonesDictionary, error in
            if let error = error {
                core.fire(event: CloudKitOperationUpdated(status: .errored(error), type: .fetch))
                self.completion?(false)
            } else {
                let found = zonesDictionary?[self.zoneID] != nil
                core.fire(event: CloudKitOperationUpdated(status: .completed, type: .fetch))
                self.completion?(found)
            }
        }
        operation.qualityOfService = .userInitiated
        CKContainer.default().privateCloudDatabase.add(operation)
    }

}


import XCTest
import APIKit
import XCTest

class ProtobufDataParserTests: XCTestCase {
    func testContentType() {
        let parser = ProtobufDataParser()
        XCTAssertEqual(parser.contentType, "application/protobuf")
    }

    func testJSONSuccess() {
        let dictionary = [
            "foo": 1,
            "bar": 2,
            "baz": 3
        ]
        let data = NSKeyedArchiver.archivedData(withRootObject: dictionary)
        let parser = ProtobufDataParser()

        do {
            let object = try parser.parse(data: data) as! Data
            let parsedDictionary = NSKeyedUnarchiver.unarchiveObject(with: object) as! [String: Int]
            XCTAssertEqual(parsedDictionary["foo"], dictionary["foo"])
            XCTAssertEqual(parsedDictionary["bar"], dictionary["bar"])
            XCTAssertEqual(parsedDictionary["baz"], dictionary["baz"])
        } catch {
            XCTFail()
        }
    }
}

Fix test case for protobuf data parser

import XCTest
import APIKit
import XCTest

class ProtobufDataParserTests: XCTestCase {
    func testContentType() {
        let parser = ProtobufDataParser()
        XCTAssertEqual(parser.contentType, "application/protobuf")
    }

    func testProtobufSuccess() {
        let data = NSKeyedArchiver.archivedData(withRootObject: ["foo": 1, "bar": 2, "baz": 3])
        let parser = ProtobufDataParser()

        do {
            let object = try parser.parse(data: data) as! Data
            let dictionary = NSKeyedUnarchiver.unarchiveObject(with: object) as? [String: Int]
            XCTAssertEqual(dictionary?["foo"], 1)
            XCTAssertEqual(dictionary?["bar"], 2)
            XCTAssertEqual(dictionary?["baz"], 3)
        } catch {
            XCTFail()
        }
    }
}


import SpriteKit

class GameScene: SKScene {
    // Play button node
    let playButton = SKSpriteNode(imageNamed: "play")

    override func didMoveToView(view: SKView) {
        // Position the play button in the middle of the screen
        // It position the button in the middle of the frame.
        self.playButton.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}

Add the button to the screen

import SpriteKit

class GameScene: SKScene {
    // Play button node
    let playButton = SKSpriteNode(imageNamed: "play")

    override func didMoveToView(view: SKView) {
        // Position the play button in the middle of the screen
        // It position the button in the middle of the frame.
        self.playButton.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))

        // Add the button to the screen
        self.addChild(self.playButton)
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}


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

import XCTest

class FutureDebugTests: 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.measure {
            // Put the code you want to measure the time of here.
        }
    }

}

Cover String lastPathComponent with unit tests

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

import XCTest
@testable import BrightFutures

class FutureDebugTests: XCTestCase {

    func testStringLastPathComponent() {
        XCTAssertEqual("/tmp/scratch.tiff".lastPathComponent, "scratch.tiff")
        XCTAssertEqual("/tmp/scratch".lastPathComponent, "scratch")
        XCTAssertEqual("/tmp/".lastPathComponent, "tmp")
        XCTAssertEqual("scratch///".lastPathComponent, "scratch")
        XCTAssertEqual("/".lastPathComponent, "/")
    }

}


//
//  PostsDataViewModels.swift
//  Basem Emara
//
//  Created by Basem Emara on 2018-06-21.
//  Copyright © 2018 Zamzam Inc. All rights reserved.
//

public struct PostsDataViewModel {
    public let id: Int
    public let title: String
    public let summary: String
    public let content: String
    public let link: String
    public let date: String
    public let imageURL: String?
    public let favorite: Bool?
}

public extension PostsDataViewModel {

    init(from object: PostType, media: MediaType?, favorite: Bool? = nil, dateFormatter: DateFormatter) {
        self.id = object.id
        self.title = object.title
        self.summary = !object.excerpt.isEmpty ? object.excerpt
            : object.content.htmlStripped.htmlDecoded.prefix(150).string
        self.content = object.content
        self.link = object.link
        self.date = dateFormatter.string(from: object.createdAt)
        self.imageURL = media?.link
        self.favorite = favorite
    }
}

public protocol PostsDataViewCell {
    func bind(_ model: PostsDataViewModel)
    func bind(_ model: PostsDataViewModel, delegate: PostsDataViewDelegate?)
}

public extension PostsDataViewCell {

    func bind(_ model: PostsDataViewModel, delegate: PostsDataViewDelegate?) {
        bind(model)
    }
}

Allow remote media URL to be configurable so caller can decide target size

//
//  PostsDataViewModels.swift
//  Basem Emara
//
//  Created by Basem Emara on 2018-06-21.
//  Copyright © 2018 Zamzam Inc. All rights reserved.
//

public struct PostsDataViewModel {
    public let id: Int
    public let title: String
    public let summary: String
    public let content: String
    public let link: String
    public let date: String
    public let imageURL: String?
    public let favorite: Bool?
}

public extension PostsDataViewModel {

    init(from object: PostType, mediaURL: String?, favorite: Bool? = nil, dateFormatter: DateFormatter) {
        self.id = object.id
        self.title = object.title
        self.summary = !object.excerpt.isEmpty ? object.excerpt
            : object.content.htmlStripped.htmlDecoded.prefix(150).string
        self.content = object.content
        self.link = object.link
        self.date = dateFormatter.string(from: object.createdAt)
        self.imageURL = mediaURL
        self.favorite = favorite
    }
}

public protocol PostsDataViewCell {
    func bind(_ model: PostsDataViewModel)
    func bind(_ model: PostsDataViewModel, delegate: PostsDataViewDelegate?)
}

public extension PostsDataViewCell {

    func bind(_ model: PostsDataViewModel, delegate: PostsDataViewDelegate?) {
        bind(model)
    }
}


//
//  NewsTableViewCell.swift
//  TOZ_iOS
//
//  Copyright © 2017 intive. All rights reserved.
//

import UIKit

class NewsTableViewCell: UITableViewCell {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var datePublishedLabel: UILabel!
    @IBOutlet weak var photoView: ProfilePhotoView!
    @IBOutlet weak var contentTextView: UITextView!
    override func awakeFromNib() {
        super.awakeFromNib()
        contentTextView.isUserInteractionEnabled = false
        self.backgroundColor = Color.Cell.Background.primary
    }

    func configure(with news: NewsItem) {

        titleLabel.text = news.title
        contentTextView.text = news.contents
        let dateToString = DateFormatter()
        dateToString.dateFormat = "yyyy-MM-dd"
        let downloadedDate = Date(timeIntervalSince1970: TimeInterval(news.published))
        datePublishedLabel.text = dateToString.string(from: downloadedDate)
    }

}

Add downloading images from server “feature”

//
//  NewsTableViewCell.swift
//  TOZ_iOS
//
//  Copyright © 2017 intive. All rights reserved.
//

import UIKit

class NewsTableViewCell: UITableViewCell {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var datePublishedLabel: UILabel!
    @IBOutlet weak var photoView: ProfilePhotoView!
    @IBOutlet weak var contentTextView: UITextView!
    override func awakeFromNib() {
        super.awakeFromNib()
        contentTextView.isUserInteractionEnabled = false
        self.backgroundColor = Color.Cell.Background.primary
    }

    func configure(with news: NewsItem) {

        titleLabel.text = news.title
        contentTextView.text = news.contents
        let dateToString = DateFormatter()
        dateToString.dateFormat = "yyyy-MM-dd"
        let downloadedDate = Date(timeIntervalSince1970: TimeInterval(news.published))
        datePublishedLabel.text = dateToString.string(from: downloadedDate)

        PhotoManager.shared.getPhoto(from: news.photoUrl, completion: {(image) -> (Void) in
            if let image = image {
                self.photoView.photo = image
            }
        })
    }

}


// RUN: %swift -target x86_64-apple-macosx10.9 %s -emit-ir -g -o - | FileCheck %s
var puzzleInput = "great minds think alike"
var puzzleOutput = ""
// CHECK: [ DW_TAG_auto_variable ] [$generator] [line [[@LINE+2]]]
// CHECK: [ DW_TAG_auto_variable ] [letter] [line [[@LINE+1]]]
for letter in puzzleInput {
    switch letter {
        case "a", "e", "i", "o", "u", " ":
            continue
        default:
            puzzleOutput += letter
    }
}
println(puzzleOutput)

func count() {
  // CHECK: [ DW_TAG_auto_variable ] [$generator] [line [[@LINE+2]]]
  // CHECK: [ DW_TAG_auto_variable ] [i] [line [[@LINE+1]]]
  for i in 0...100 {
    println(i)
  }
}
count()

Debug info: Add an end-to-end test to catch LLVM backend regressions.

// RUN: %swift -target x86_64-apple-macosx10.9 %s -emit-ir -g -o %t.ll
// RUN cat %t.ll | FileCheck %s
var puzzleInput = "great minds think alike"
var puzzleOutput = ""
// CHECK: [ DW_TAG_auto_variable ] [$generator] [line [[@LINE+2]]]
// CHECK: [ DW_TAG_auto_variable ] [letter] [line [[@LINE+1]]]
for letter in puzzleInput {
    switch letter {
        case "a", "e", "i", "o", "u", " ":
            continue
        default:
            puzzleOutput += letter
    }
}
println(puzzleOutput)

func count() {
  // CHECK: [ DW_TAG_auto_variable ] [$generator] [line [[@LINE+2]]]
  // CHECK: [ DW_TAG_auto_variable ] [i] [line [[@LINE+1]]]
  for i in 0...100 {
    println(i)
  }
}
count()

// End-to-end test:
// RUN: llc %t.ll -filetype=obj -o - | llvm-dwarfdump - | FileCheck %s --check-prefix DWARF-CHECK
// DWARF-CHECK:  DW_TAG_variable
// DWARF-CHECK:  DW_AT_name {{.*}} "letter"
//
// DWARF-CHECK:  DW_TAG_variable
// DWARF-CHECK:  DW_AT_name {{.*}} "i"


final public class Network {
    public init() {}

    // MARK: - Processes
    private var processes: [Int:Component] = [:]

    public func addNode<T: Component>(name: String, _ component: T.Type) -> T {
        let process = component.init(self)
        processes[process.id] = process
        return process
    }

    // MARK: - Connections
    private var connections: [Int:Port] = [:]

    public func addConnection<T>(fromPort: OutPort<T>, _ toPort: InPort<T>) {
        connections[fromPort.id] = toPort
    }

    // MARK - Sending
    public func send<T>(outPort: OutPort<T>, _ packet: T) {
        if let inPort = connections[outPort.id] as? InPort<T> {
            inPort.receive(packet)
        }
        else {
            print("Unconnected out port on \"\(outPort.process)\" tried to send a packet.")
        }
    }
}

Update addNode to receive an instance of a component, not a type.

final public class Network {
    public init() {}

    // MARK: - Processes
    private var processes: [Int:Component] = [:]

    public func addNode<T: Component>(name: String, _ process: T) -> T {
        processes[process.id] = process
        return process
    }

    // MARK: - Connections
    private var connections: [Int:Port] = [:]

    public func addConnection<T>(fromPort: OutPort<T>, _ toPort: InPort<T>) {
        connections[fromPort.id] = toPort
    }

    // MARK - Sending
    public func send<T>(outPort: OutPort<T>, _ packet: T) {
        if let inPort = connections[outPort.id] as? InPort<T> {
            inPort.receive(packet)
        }
        else {
            print("Unconnected out port on \"\(outPort.process)\" tried to send a packet.")
        }
    }
}


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

import UIKit
import XCTest

class FuelGaugeKitTests: XCTestCase {

    var fuelGauge: FuelGaugeView!

    override func setUp() {
        super.setUp()
        fuelGauge = FuelGaugeView()
    }

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

    func testFuelGaugeInstantiated() {
        XCTAssertNotNil(self.fuelGauge, "FuelGaugeView not instantiated")
    }

    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measureBlock() {
            // Put the code you want to measure the time of here.
        }
    }

}

Create failing test the background image loaded.

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

import UIKit
import XCTest

class FuelGaugeKitTests: XCTestCase {

    var fuelGauge: FuelGaugeView!

    override func setUp() {
        super.setUp()
        fuelGauge = FuelGaugeView()
    }

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

    func testFuelGaugeInstantiated() {
        XCTAssertNotNil(self.fuelGauge, "FuelGaugeView not instantiated")
    }

    func testBackgroundImageLoaded() {
        XCTAssertNotNil(fuelGauge.backgroundImage, "Background image not loaded.")
    }

    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measureBlock() {
            // Put the code you want to measure the time of here.
        }
    }

}


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

extension Module {
	public static var finiteSet: Module {
		let Natural: Recur = "Natural"
		let FiniteSet: Recur = "FiniteSet"
		let finiteSet = Declaration("FiniteSet",
			type: Natural --> .Type,
			value: (Natural, .Type) => { n, A in n[.Type, A --> A, Natural => { (n: Recur) in (FiniteSet[n] --> A) --> A }] })

		let successor: Recur = "successor"
		let zeroth = Declaration("zeroth",
			type: Natural => { (n: Recur) in FiniteSet[successor[n]] },
			value: .Type => { A in A => id })

		let nextth = Declaration("nextth",
			type: Natural => { (n: Recur) in FiniteSet[n] --> FiniteSet[successor[n]] },
			value: (Natural, .Type) => { (n: Recur, A) in FiniteSet[n] => { (a: Recur) in (FiniteSet[n] --> A) => { $0[a] } } })

		return Module("FiniteSet", [ natural ], [ finiteSet, zeroth, nextth ])
	}
}

import Prelude

Correct the definition of `nextth`.

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

extension Module {
	public static var finiteSet: Module {
		let Natural: Recur = "Natural"
		let FiniteSet: Recur = "FiniteSet"
		let finiteSet = Declaration("FiniteSet",
			type: Natural --> .Type,
			value: (Natural, .Type) => { n, A in n[.Type, A --> A, Natural => { (n: Recur) in (FiniteSet[n] --> A) --> A }] })

		let successor: Recur = "successor"
		let zeroth = Declaration("zeroth",
			type: Natural => { (n: Recur) in FiniteSet[successor[n]] },
			value: .Type => { A in A => id })

		let nextth = Declaration("nextth",
			type: Natural => { (n: Recur) in FiniteSet[n] --> FiniteSet[successor[n]] },
			value: Natural => { (n: Recur) in (FiniteSet[n], .Type) => { (prev: Recur, A) in (FiniteSet[n] --> A) => { $0[prev] } } })

		return Module("FiniteSet", [ natural ], [ finiteSet, zeroth, nextth ])
	}
}

import Prelude


import Foundation
import UIKit

public class CardCVVTextField: OmiseTextField, UITextFieldDelegate {
    private let maxLength = 3

    public override var isValid: Bool {
        return text?.characters.count >= maxLength
    }

    override public init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

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

    override public init() {
        super.init(frame: CGRectZero)
        setup()
    }

    func setup() {
        keyboardType = .NumberPad
        placeholder = "123"
        secureTextEntry = true
        delegate = self // TODO: 👈 remove, replace with mask instead
    }

    public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        if string.characters.count == 0 && range.length == 1 {
            if range.location == maxLength {
                deleteBackward()
            }
        }

        if(range.length + range.location > maxLength) {
            return false
        }

        return true
    }
}

Remove UITextFieldDelegate reference in CVV field.

import Foundation
import UIKit

public class CardCVVTextField: OmiseTextField {
    private let maxLength = 3

    public override var isValid: Bool {
        return text?.characters.count >= maxLength
    }

    override public init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

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

    override public init() {
        super.init(frame: CGRectZero)
        setup()
    }

    func setup() {
        keyboardType = .NumberPad
        placeholder = "123"
        secureTextEntry = true
    }
}


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

Test function destructuring with the same type.

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


//
//  CharacterSet+LinuxHack.swift
//  SwiftLint
//
//  Created by Marcelo Fabri on 12/25/16.
//  Copyright © 2016 Realm. All rights reserved.
//

import Foundation

extension CharacterSet {
    func isSuperset(ofCharactersIn string: String) -> Bool {
        #if os(Linux)
            // workaround for https://bugs.swift.org/browse/SR-3485
            let chars = Set(string.characters)
            for char in chars where !contains(char.unicodeScalar) {
                return false
            }

            return true
        #else
            let otherSet = CharacterSet(charactersIn: string)
            return isSuperset(of: otherSet)
        #endif
    }
}

private extension Character {
    var unicodeScalar: UnicodeScalar {
        let characterString = String(self)
        let scalars = characterString.unicodeScalars

        return scalars[scalars.startIndex]
    }
}

Remove hack for SR-3485 when building with Swift 4

//
//  CharacterSet+LinuxHack.swift
//  SwiftLint
//
//  Created by Marcelo Fabri on 12/25/16.
//  Copyright © 2016 Realm. All rights reserved.
//

import Foundation

extension CharacterSet {
    func isSuperset(ofCharactersIn string: String) -> Bool {
        #if swift(>=4.0) || os(macOS)
            let otherSet = CharacterSet(charactersIn: string)
            return isSuperset(of: otherSet)
        #else
            // workaround for https://bugs.swift.org/browse/SR-3485
            let chars = Set(string.characters)
            for char in chars where !contains(char.unicodeScalar) {
                return false
            }

            return true
        #endif
    }
}

private extension Character {
    var unicodeScalar: UnicodeScalar {
        let characterString = String(self)
        let scalars = characterString.unicodeScalars

        return scalars[scalars.startIndex]
    }
}


import Authentication
import Flash
import HTTP
import Routing
import Vapor

/// Defines basic reset password routes.
public struct FrontendResetPasswordRoutes: RouteCollection {
    public typealias Wrapped = Responder

    private let controller: FrontendResetPasswordControllerType

    /// Initializes the user route collection.
    ///
    /// - Parameters:
    ///   - resetPasswordController: controller for handling user reset password
    ///     routes.
    public init(
        resetPasswordController: FrontendResetPasswordControllerType
    ) {
        self.controller = resetPasswordController
    }

    public func build(
        _ builder: RouteBuilder
    ) throws {

        // Get the base path group
        let path = builder.grouped("users", "reset-password")

        path.group(FlashMiddleware()) { routes in
            routes.get(
                "form",
                String.parameter,
                handler: controller.resetPasswordForm
            )
            routes.post(
                "change",
                String.parameter,
                handler: controller.resetPasswordChange
            )
        }
    }
}

Add FieldSetMiddleware to form route

import Authentication
import Flash
import Forms
import HTTP
import Routing
import Vapor

/// Defines basic reset password routes.
public struct FrontendResetPasswordRoutes: RouteCollection {
    public typealias Wrapped = Responder

    private let controller: FrontendResetPasswordControllerType

    /// Initializes the user route collection.
    ///
    /// - Parameters:
    ///   - resetPasswordController: controller for handling user reset password
    ///     routes.
    public init(
        resetPasswordController: FrontendResetPasswordControllerType
    ) {
        self.controller = resetPasswordController
    }

    public func build(
        _ builder: RouteBuilder
    ) throws {

        // Get the base path group
        let path = builder.grouped("users", "reset-password")

        path.group(FlashMiddleware(), FieldSetMiddleware()) { routes in
            routes.get(
                "form",
                String.parameter,
                handler: controller.resetPasswordForm
            )
            routes.post(
                "change",
                String.parameter,
                handler: controller.resetPasswordChange
            )
        }
    }
}


// RUN: %target-swift-frontend -emit-syntax %s | %FileCheck %s

// CHECK: "kind":"kw_struct"
// CHECK: "kind":"identifier",
// CHECK: "text":"Foo"
// CHECK: "kind":"l_brace"
struct Foo {
  // CHECK: "kind":"kw_let"
  // CHECK: "kind":"colon"
  // CHECK: "kind":"identifier"
  // CHECK: "text":"Int"
  let x: Int
// CHECK: "kind":"r_brace"
}

// CHECK: "leadingTrivia":[
// CHECK: "kind":"LineComment",
// CHECK: "value":"\/\/ Comment at the end of the file"

// Comment at the end of the file

Add successfully test pattern for missing parse ellipsis of function

// RUN: %target-swift-frontend -emit-syntax %s | %FileCheck %s

// CHECK: "kind":"kw_struct"
// CHECK: "kind":"identifier",
// CHECK: "text":"Foo"
// CHECK: "kind":"l_brace"
struct Foo {
  // CHECK: "kind":"kw_let"
  // CHECK: "kind":"colon"
  // CHECK: "kind":"identifier"
  // CHECK: "text":"Int"
  let x: Int
// CHECK: "kind":"r_brace"
}

// CHECK: "kind":"kw_func"
// CHECK: "kind":"identifier"
// CHECK: "text":"Bar"
// CHECK: "kind":"l_paren"
// CHECK: "kind":"FunctionParameterList"
// CHECK: "kind":"FunctionParameter"
// CHECK: "kind":"identifier"
// CHECK: "text":"arg1"
// CHECK: "kind":"colon"
// CHECK: "kind":"identifier"
// CHECK: "text":"String"
// CHECK: "kind":"comma"
// CHECK: "null"
// CHECK: "kind":"identifier"
// CHECK: "text":"arg2"
// CHECK-NEXT: "null"
// CHECK: "kind":"colon"
// CHECK: "kind":"identifier"
// CHECK: "text":"Int"
// CHECK: "kind":"r_paren"
// CHECK: "kind":"l_brace"
func Bar(arg1: String, arg2: Int) {
// CHECK: "kind":"r_brace"
}

// CHECK: "leadingTrivia":[
// CHECK: "kind":"LineComment",
// CHECK: "value":"\/\/ Comment at the end of the file"

// Comment at the end of the file


// SKIP-THIS-TEST
// Check wrapping and recursive wait for struct with nested arrays and structs
type person {
  string name;
  int age;
}

type megastruct {
  person people[];
  person person;
}

type uberstruct {
  person person;
  megastruct mega;
}

(string o) fmt(megastruct s) "turbine" "0" [
  "set <<o>> <<s>>"
];

(string o) fmt2(uberstruct s) "turbine" "0" [
  "set <<o>> <<s>>"
];

import assert;

main {
  megastruct s;
  s.person.name = "Bob";
  s.person.age = 100;

  person t;
  t.name = "X";
  t.age = 1;
  s.people[0] = t;
  s.people[1] = s.person;
  s.people[2] = t;

  trace("test1",fmt(s));

  uberstruct s2;
  s2.mega.person = s.person;
  s2.mega.people = s.people;
  s2.person.name = "Jane";
  s2.person.age = 101;

  trace("test2",fmt2(s2));
}

Test for recursive store of struct

// SKIP-THIS-TEST
// Check returning structs with nested arrays
type person {
  string name;
  int age;
}

type megastruct {
  person people[];
  person person;
}

type uberstruct {
  person person;
  megastruct mega;
}

(megastruct o) fmt(person person, person ppl[]) "turbine" "0" [
  "set <<o>> [ dict create person <<person>> people <<ppl>>]"
];

(uberstruct o) fmt2(person person, person ppl[]) "turbine" "0" [
  "set <<o>> [ dict create mega [ dict create person <<person>> people <<ppl>> ] person <<person>> ]"
];

import assert;

main {
  person p1, p2;
  p1.name = "Bob";
  p1.age = 100;
  p2.name = "Jane";
  p2.age = 101;

  person ppl[] = [p1, p2, p1];

  assertEqual(fmt(p1, ppl).person.name, "Bob", "a");
  assertEqual(fmt(p1, ppl).person.age, 100, "b");
  assertEqual(fmt(p1, ppl).people[0].name, "Bob", "c");
  assertEqual(fmt(p1, ppl).people[1].name, "Jane", "d");

  assertEqual(fmt2(p1, ppl).person.name, "Bob", "e");
  assertEqual(fmt2(p1, ppl).person.age, 100, "f");

  assertEqual(fmt2(p1, ppl).mega.people[0], "Bob", "g");
  assertEqual(fmt2(p1, ppl).mega.people[1], "Jane", "h");

}


//
//  YellrConstants.swift
//  Yellr
//
//  Created by Debjit Saha on 6/1/15.
//  Copyright (c) 2015 wxxi. All rights reserved.
//

import Foundation

Add a global constants file for Yellr

//
//  YellrConstants.swift
//  Yellr
//
//  Created by Debjit Saha on 6/1/15.
//  Copyright (c) 2015 wxxi. All rights reserved.
//

import Foundation

struct YellrConstants {
    struct LocalPosts {
        static let Title = "local_post_title"
    }

    struct Assignments {
        static let Title = "assignments_title"
    }

    struct Stories {
        static let Title = "stories_title"
    }

    struct Profile {
        static let Title = "profile_title"
    }

    struct NewPost {
        static let Title = "new_post_title"
    }
}


#!/usr/bin/swift

import Foundation

let userInfo = ["com.apple.MCX.changedDomains": ["com.github.ygini.Hello-IT"]]

NSDistributedNotificationCenter.defaultCenter().postNotificationName("com.apple.MCX._managementStatusChangedForDomains", object: "com.apple.MCX", userInfo: userInfo)

exit(0)

Fix test tool to support new swift syntax

#!/usr/bin/swift

import Foundation

let userInfo = ["com.apple.MCX.changedDomains": ["com.github.ygini.Hello-IT"]]

DistributedNotificationCenter.default().post(name: Notification.Name("com.apple.MCX._managementStatusChangedForDomains"), object: "com.apple.MCX", userInfo: userInfo)

exit(0)


//
//  TrailingNewlineRule.swift
//  SwiftLint
//
//  Created by JP Simard on 2015-05-16.
//  Copyright (c) 2015 Realm. All rights reserved.
//

import SourceKittenFramework

public struct TrailingNewlineRule: Rule {
    public init() {}

    public let identifier = "trailing_newline"

    public func validateFile(file: File) -> [StyleViolation] {
        let string = file.contents
        let start = string.endIndex.advancedBy(-2, limit: string.startIndex)
        let range = Range(start: start, end: string.endIndex)
        let substring = string[range].utf16
        let newLineSet = NSCharacterSet.newlineCharacterSet()
        let slices = substring.split(allowEmptySlices: true) { !newLineSet.characterIsMember($0) }

        if let slice = slices.last where slice.count != 1 {
            return [StyleViolation(type: .TrailingNewline,
                location: Location(file: file.path, line: file.lines.count + 1),
                severity: .Warning,
                reason: "File should have a single trailing newline")]
        }

        return []
    }

    public let example = RuleExample(
        ruleName: "Trailing newline rule",
        ruleDescription: "Files should have a single trailing newline.",
        nonTriggeringExamples: [],
        triggeringExamples: [],
        showExamples: false
    )
}

Change TrailingNewLine violation line to have an index within the file

//
//  TrailingNewlineRule.swift
//  SwiftLint
//
//  Created by JP Simard on 2015-05-16.
//  Copyright (c) 2015 Realm. All rights reserved.
//

import SourceKittenFramework

public struct TrailingNewlineRule: Rule {
    public init() {}

    public let identifier = "trailing_newline"

    public func validateFile(file: File) -> [StyleViolation] {
        let string = file.contents
        let start = string.endIndex.advancedBy(-2, limit: string.startIndex)
        let range = Range(start: start, end: string.endIndex)
        let substring = string[range].utf16
        let newLineSet = NSCharacterSet.newlineCharacterSet()
        let slices = substring.split(allowEmptySlices: true) { !newLineSet.characterIsMember($0) }

        if let slice = slices.last where slice.count != 1 {
            return [StyleViolation(type: .TrailingNewline,
                location: Location(file: file.path, line: file.lines.count),
                severity: .Warning,
                reason: "File should have a single trailing newline")]
        }

        return []
    }

    public let example = RuleExample(
        ruleName: "Trailing newline rule",
        ruleDescription: "Files should have a single trailing newline.",
        nonTriggeringExamples: [],
        triggeringExamples: [],
        showExamples: false
    )
}