Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Comment failing test(template test code)
// https://github.com/Quick/Quick import Quick import Nimble import RGInnerBadgeButton class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
// https://github.com/Quick/Quick import Quick import Nimble import RGInnerBadgeButton class TableOfContentsSpec: QuickSpec { override func spec() { // describe("these will fail") { // // it("can do maths") { // expect(1) == 2 // } // // it("can read") { // expect("number") == "string" // } // // it("will eventually fail") { // expect("time").toEventually( equal("done") ) // } // context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } // } } }
Add json and protobuf api for swift
import Kitura import HeliumLogger import SwiftProtobuf HeliumLogger.use() let router = Router() func getLibrary() -> MyLibrary { let map = ["route": "66"] var bookInfo = BookInfo() bookInfo.id = 10 bookInfo.title = "Welcome to Swift" bookInfo.author = "Apple Inc." var library = MyLibrary() library.id = 20 library.name = "Swift" library.books = [bookInfo] library.keys = map return library } router.get("/") { request, response, next in let library = getLibrary() let accept = request.headers["Accept"] if accept == "application/protobuf" { response.headers["Content-Type"] = "application/protobuf" response.send(data: try library.serializeProtobuf()) } else { response.headers["Content-Type"] = "application/json; charset=UTF-8" response.send(try library.serializeJSON()) } next() } Kitura.addHTTPServer(onPort: 8090, with: router) Kitura.run()
import Kitura import HeliumLogger import SwiftProtobuf HeliumLogger.use() let router = Router() func getLibrary() -> MyLibrary { let map = ["route": "66"] var bookInfo = BookInfo() bookInfo.id = 10 bookInfo.title = "Welcome to Swift" bookInfo.author = "Apple Inc." var library = MyLibrary() library.id = 20 library.name = "Swift" library.books = [bookInfo] library.keys = map return library } router.get("/json") { request, response, next in let library = getLibrary() response.headers["Content-Type"] = "application/json; charset=UTF-8" response.send(try library.serializeJSON()) next() } router.get("/protobuf") { request, response, next in let library = getLibrary() response.headers["Content-Type"] = "application/protobuf" response.send(data: try library.serializeProtobuf()) next() } router.get("/") { request, response, next in let library = getLibrary() let accept = request.headers["Accept"] if accept == "application/protobuf" { response.headers["Content-Type"] = "application/protobuf" response.send(data: try library.serializeProtobuf()) } else { response.headers["Content-Type"] = "application/json; charset=UTF-8" response.send(try library.serializeJSON()) } next() } Kitura.addHTTPServer(onPort: 8090, with: router) Kitura.run()
Update ConfigExample to Swift 4.2
// // Copyright (c) 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // [START configure_firebase] FirebaseApp.configure() // [END configure_firebase] return true } }
// // Copyright (c) 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // [START configure_firebase] FirebaseApp.configure() // [END configure_firebase] return true } }
Add sendJSON funcs to canvas model
// // Canvas.swift // place // // Created by Valtteri Koskivuori on 18/06/2017. // // import Vapor class Canvas { //Connection is a key-val pair; userID:WebSocket //Consider making User hashable somehow? And have User:WebSocket keyval pairs var connections: [String: WebSocket] func updateTileToClients() { //We've received a tile change, it's been approved, send that update to ALL connected clients } //Init canvas, load it from the DB here init() { connections = [:] } }
// // Canvas.swift // place // // Created by Valtteri Koskivuori on 18/06/2017. // // import Vapor class Canvas { //Connection is a key-val pair; userID:WebSocket //Consider making User hashable somehow? And have User:WebSocket keyval pairs var connections: [String: WebSocket] func updateTileToClients() { //We've received a tile change, it's been approved, send that update to ALL connected clients } //Send to a specific user func sendJSON(to: User, json: JSON) { for (uuid, socket) in connections { guard uuid != to.uuid else{ continue } try? socket.send(json.string!) } } //Send to all users func sendJSON(json: JSON) { for (_, socket) in connections { try? socket.send(json.string!) } } //Init canvas, load it from the DB here init() { connections = [:] } }
Add newline at end of file.
// // FakeProfileHeaderCellSizeCalculator.swift // Ello // // Created by Ryan Boyajian on 3/24/15. // Copyright (c) 2015 Ello. All rights reserved. // import Foundation class FakeProfileHeaderCellSizeCalculator: ProfileHeaderCellSizeCalculator { override func processCells(cellItems:[StreamCellItem], completion:ElloEmptyCompletion) { self.completion = completion self.cellItems = cellItems completion() } }
// // FakeProfileHeaderCellSizeCalculator.swift // Ello // // Created by Ryan Boyajian on 3/24/15. // Copyright (c) 2015 Ello. All rights reserved. // import Foundation class FakeProfileHeaderCellSizeCalculator: ProfileHeaderCellSizeCalculator { override func processCells(cellItems:[StreamCellItem], completion:ElloEmptyCompletion) { self.completion = completion self.cellItems = cellItems completion() } }
Optimize deck shuffling in Swift
public struct Card: CustomStringConvertible { public enum Suit: Int { case Spade = 0 case Club case Heart case Diamond } public enum FaceValue: Int { case Ace = 1 case Two = 2 case Three = 3 case Four = 4 case Five = 5 case Six = 6 case Seven = 7 case Eight = 8 case Nine = 9 case Ten = 10 case Jack = 11 case Queen = 12 case King = 13 } private(set) public var suit: Suit private(set) public var value: FaceValue public var description: String { return "\(value) of \(suit)" } } public struct Deck: CustomStringConvertible { private var deck: [Card] public init() { deck = [Card]() for s in 0..<4 { for v in 1...13 { deck.append(Card(suit: Card.Suit(rawValue: s)!, value: Card.FaceValue(rawValue: v)!)) } } } public mutating func shuffle() { deck = deck.sorted { (_, _) -> Bool in return arc4random() % 2 == 0 } } public var description: String { var deckString = "" for (i, card) in deck.enumerated() { deckString.append(card.description) if (i % 4 == 3) { deckString.append("\n") } else { deckString.append("\t") } } return deckString } }
import Foundation public struct Card: CustomStringConvertible { public enum Suit: Int { case Spade = 0 case Club case Heart case Diamond } public enum FaceValue: Int { case Ace = 1 case Two = 2 case Three = 3 case Four = 4 case Five = 5 case Six = 6 case Seven = 7 case Eight = 8 case Nine = 9 case Ten = 10 case Jack = 11 case Queen = 12 case King = 13 } private(set) public var suit: Suit private(set) public var value: FaceValue public var description: String { return "\(value) of \(suit)" } } public struct Deck: CustomStringConvertible { private var deck: [Card] public init() { deck = [Card]() for s in 0..<4 { for v in 1...13 { deck.append(Card(suit: Card.Suit(rawValue: s)!, value: Card.FaceValue(rawValue: v)!)) } } } public mutating func shuffle() { deck.sort { (_, _) -> Bool in return arc4random() % 2 == 0 } } public var description: String { var deckString = "" for (i, card) in deck.enumerated() { deckString.append(card.description) if (i % 4 == 3) { deckString.append("\n") } else { deckString.append("\t") } } return deckString } }
Use setup in test to init models
import XCTest import CoreLocation @testable import columbus final class UTMCreateLocationDelegate:XCTestCase { private let kAccuracy:CLLocationAccuracy = kCLLocationAccuracyBestForNavigation //MARK: tests func testAskAuthorization() { let model:MCreateLocationDelegate = MCreateLocationDelegate() model.askAuthorization() XCTAssertNotNil( model.locationManager, "failed creating location manager") XCTAssertNotNil( model.locationManager?.delegate, "failed assigning delegate to location manager") XCTAssertEqual( model.locationManager?.desiredAccuracy, kAccuracy, "failed assigning maximum accuracy for location manager") } func testClean() { let model:MCreateLocationDelegate = MCreateLocationDelegate() model.askAuthorization() model.clean() XCTAssertNil( model.locationManager?.delegate, "failed removing delegate from location manager") } }
import XCTest import CoreLocation @testable import columbus final class UTMCreateLocationDelegate:XCTestCase { private var modelLocation:MCreateLocationDelegate? private var modelCreate:MCreate? private let kAccuracy:CLLocationAccuracy = kCLLocationAccuracyBestForNavigation override func setUp() { super.setUp() modelLocation = MCreateLocationDelegate() modelCreate = MCreate() modelLocation?.model = modelCreate modelLocation?.askAuthorization() } //MARK: tests func testAskAuthorization() { XCTAssertNotNil( modelLocation?.locationManager, "failed creating location manager") XCTAssertNotNil( modelLocation?.locationManager?.delegate, "failed assigning delegate to location manager") XCTAssertEqual( modelLocation?.locationManager?.desiredAccuracy, kAccuracy, "failed assigning maximum accuracy for location manager") } func testClean() { modelLocation?.clean() XCTAssertNil( modelLocation?.locationManager?.delegate, "failed removing delegate from location manager") } }
Update the test for modernization of QuartzCore APIs
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: OS=macosx // FIXME: iOS doesn't have CIVector? import QuartzCore // Do NOT add anything that publicly imports Foundation here! var v = CIVector(x:7); // CHECK: x = 7 println("x = \(v.X())");
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: OS=macosx // FIXME: iOS doesn't have CIVector? import QuartzCore // Do NOT add anything that publicly imports Foundation here! var v = CIVector(x:7); // CHECK: x = 7 println("x = \(v.X)")
Fix temporarily a test case
// // BasicStringTest.swift // MochaUtilities // // Created by Gregory Sholl e Santos on 09/06/17. // Copyright © 2017 CocoaPods. All rights reserved. // import XCTest @testable import MochaUtilities class BasicStringTest: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testLengthWithEmpty() { let empty = "" XCTAssertEqual(0, empty.length) } func testLengthWithCharactersCount() { let someString = "testingString" XCTAssertEqual(someString.characters.count, someString.length) } func testEmpty() { let emptyString = "" XCTAssertFalse(emptyString.isNotEmpty) } func testNotEmpty() { let nonEmptyString = "string" XCTAssertTrue(nonEmptyString.isNotEmpty) } func testInsetiveString() { let portugueseWord = "coração" let weirdlyCasePortugueseWord = "CoRaÇãO" XCTAssertTrue(portugueseWord.equalsIgnoreCase(weirdlyCasePortugueseWord)) } }
// // BasicStringTest.swift // MochaUtilities // // Created by Gregory Sholl e Santos on 09/06/17. // Copyright © 2017 CocoaPods. All rights reserved. // import XCTest @testable import MochaUtilities class BasicStringTest: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testLengthWithEmpty() { let empty = "" XCTAssertEqual(0, empty.length) } func testLengthWithCharactersCount() { let someString = "testingString" XCTAssertEqual(someString.count, someString.length) } func testEmpty() { let emptyString = "" XCTAssertFalse(emptyString.isNotEmpty) } func testNotEmpty() { let nonEmptyString = "string" XCTAssertTrue(nonEmptyString.isNotEmpty) } func testInsetiveString() { let portugueseWord = "coração" let weirdlyCasePortugueseWord = "CoRaÇãO" XCTAssertTrue(portugueseWord.equalsIgnoreCase(weirdlyCasePortugueseWord)) } }
Use faker in detail view
import Foundation import Wall class DetailViewController: WallController { override func viewDidLoad() { super.viewDidLoad() title = post!.text let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { self.posts = self.generatePosts(1, to: 20) } } func generatePosts(from: Int, to: Int) -> [Post] { var posts = [Post]() var startFrom = self.posts.count for i in from...to { posts.append(Post(text: "Comment -> \(i+startFrom)", date: NSDate())) } return posts } }
import Foundation import Wall import Faker class DetailViewController: WallController { let faker = Faker() override func viewDidLoad() { super.viewDidLoad() title = post!.text let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { self.posts = self.generatePosts(1, to: 3) } } func generatePosts(from: Int, to: Int) -> [Post] { var posts = [Post]() var startFrom = self.posts.count for i in from...to { let sencenceCount = Int(arc4random_uniform(8) + 1) posts.append(Post(text: faker.lorem.sentences(amount: sencenceCount), date: NSDate())) } return posts } }
Add NSDate -> String transformation
// // ServerDateFormatter.swift // Ello // // Created by Sean Dougherty on 12/3/14. // Copyright (c) 2014 Ello. All rights reserved. // import Foundation let ServerDateFormatter = NSDateFormatter() public extension NSString { func toNSDate() -> NSDate? { ServerDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" ServerDateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") return ServerDateFormatter.dateFromString(self as String) } }
// // ServerDateFormatter.swift // Ello // // Created by Sean Dougherty on 12/3/14. // Copyright (c) 2014 Ello. All rights reserved. // import Foundation let ServerDateFormatter: NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" formatter.timeZone = NSTimeZone(abbreviation: "UTC") return formatter }() public extension NSString { func toNSDate() -> NSDate? { return ServerDateFormatter.dateFromString(self as String) } } public extension NSDate { func toNSString() -> NSString { return ServerDateFormatter.stringFromDate(self) } }
Remove padding from 'Load more comments' cells
// // MoreCommentCellView.swift // Breadit // // Created by William Hester on 4/30/16. // Copyright © 2016 William Hester. All rights reserved. // import UIKit class MoreCommentCellView: CommentCellView { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.uiLabel { v in v.text = "Load more comments..." v.fontSize = 12 v.textColor = Colors.secondaryTextColor }.constrain { v in self.paddingConstraint = v.leftAnchor.constraintEqualToAnchor(self.contentView.leftAnchor) self.paddingConstraint.active = true v.rightAnchor.constraintEqualToAnchor(self.contentView.rightAnchor).active = true self.contentView.heightAnchor.constraintEqualToAnchor(v.heightAnchor, constant: 16).active = true } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // MoreCommentCellView.swift // Breadit // // Created by William Hester on 4/30/16. // Copyright © 2016 William Hester. All rights reserved. // import UIKit class MoreCommentCellView: CommentCellView { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.uiLabel { v in v.text = "Load more comments..." v.fontSize = 12 v.textColor = Colors.secondaryTextColor }.constrain { v in self.paddingConstraint = v.leftAnchor.constraintEqualToAnchor(self.contentView.leftAnchor) self.paddingConstraint.active = true v.rightAnchor.constraintEqualToAnchor(self.contentView.rightAnchor).active = true self.contentView.heightAnchor.constraintEqualToAnchor(v.heightAnchor).active = true self.heightAnchor.constraintEqualToAnchor(self.contentView.heightAnchor).active = true self.contentView.translatesAutoresizingMaskIntoConstraints = false } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
Make `SECCommonGraphicStyle` conform to `SECEnumable` an `SECMappable`
// // SECGraphicStyle.swift // SwiftyEcharts // // Created by Pluto Y on 11/02/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // public protocol SECGraphicStyle : SECShadowable { var fill: SECColor? { get set } var stroke: SECColor? { get set } var lineWidth: Float? { get set } } public struct SECCommonGraphicStyle : SECGraphicStyle { public var fill: SECColor? public var stroke: SECColor? public var lineWidth: Float? public var shadowBlur: Float? public var shadowOffsetX: Float? public var shadowOffsetY: Float? public var shadowColor: SECColor? }
// // SECGraphicStyle.swift // SwiftyEcharts // // Created by Pluto Y on 11/02/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // public protocol SECGraphicStyle : SECShadowable { var fill: SECColor? { get set } var stroke: SECColor? { get set } var lineWidth: Float? { get set } } public struct SECCommonGraphicStyle : SECGraphicStyle { public var fill: SECColor? public var stroke: SECColor? public var lineWidth: Float? public var shadowBlur: Float? public var shadowOffsetX: Float? public var shadowOffsetY: Float? public var shadowColor: SECColor? public init() {} } extension SECCommonGraphicStyle : SECEnumable { public enum Enums { case fill(SECColor), stroke(SECColor), lineWidth(Float), shadowBlur(Float), shadowOffsetX(Float), shadowOffsetY(Float), shadowColor(SECColor) } public typealias ContentEnum = Enums public init(_ elements: Enums...) { for ele in elements { switch ele { case let .fill(fill): self.fill = fill case let .stroke(stroke): self.stroke = stroke case let .lineWidth(lineWidth): self.lineWidth = lineWidth case let .shadowBlur(shadowBlur): self.shadowBlur = shadowBlur case let .shadowOffsetX(shadowOffsetX): self.shadowOffsetX = shadowOffsetX case let .shadowOffsetY(shadowOffsetY): self.shadowOffsetY = shadowOffsetY case let .shadowColor(shadowColor): self.shadowColor = shadowColor } } } } extension SECCommonGraphicStyle : SECMappable { public func mapping(map: SECMap) { map["fill"] = fill map["stroke"] = stroke map["lineWidth"] = lineWidth map["shadowBlur"] = shadowBlur map["shadowOffsetX"] = shadowOffsetX map["shadowOffsetY"] = shadowOffsetY map["shadowColor"] = shadowColor } }
Add a Church-encoded `true` value.
// Copyright © 2015 Rob Rix. All rights reserved. extension Module { public static var churchBoolean: Module { let Boolean = Declaration("Boolean", type: .Type, value: Recur.lambda(.Type) { Recur.lambda($0, $0, const($0)) }) return Module([ Boolean ]) } } import Prelude
// Copyright © 2015 Rob Rix. All rights reserved. extension Module { public static var churchBoolean: Module { let Boolean = Declaration("Boolean", type: .Type, value: Recur.lambda(.Type) { Recur.lambda($0, $0, const($0)) }) let `true` = Declaration("true", type: Boolean.ref, value: Recur.lambda(.Type) { A in Recur.lambda(A, A, { a, _ in a }) }) return Module([ Boolean, `true` ]) } } import Prelude
Use config instead of loading everything out of the config dictionary
// // Dependencies.swift // Whitelabel // // Created by Martin Eberl on 27.02.17. // Copyright © 2017 Martin Eberl. All rights reserved. // import Foundation class Dependencies { static let shared = Dependencies() let loader: ContentLoader? let locationProvider: LocationProvider? let timeStore: TimeStore private init() { if let urlString = Bundle.main.infoDictionary?["LOAD_PATH"] as? String, let url = URL(string: urlString) { loader = ContentLoader(url: url) } else { loader = nil } locationProvider = LocationProvider() timeStore = TimeStore() } }
// // Dependencies.swift // Whitelabel // // Created by Martin Eberl on 27.02.17. // Copyright © 2017 Martin Eberl. All rights reserved. // import Foundation class Dependencies { static let shared = Dependencies() let loader: ContentLoader? let locationProvider: LocationProvider? let timeStore: TimeStore private init() { if let urlString = Config.apiBasePath, let url = URL(string: urlString) { loader = ContentLoader(url: url) } else { loader = nil } locationProvider = LocationProvider() timeStore = TimeStore() } }
Fix whitespace in a test
// RUN: %target-swift-frontend %s -emit-ir -o - func f() { enum NotAnError: Swift.Error { case nope(length: Int) } }
// RUN: %target-swift-frontend %s -emit-ir -o - func f() { enum NotAnError: Swift.Error { case nope(length: Int) } }
Stop checking for quit players' ready states
// // WKRReadyStates.swift // WKRKit // // Created by Andrew Finke on 8/31/17. // Copyright © 2017 Andrew Finke. All rights reserved. // import Foundation public struct WKRReadyStates: Codable { let players: [WKRPlayer] init(players: [WKRPlayer]) { self.players = players } public func isPlayerReady(_ player: WKRPlayer) -> Bool { guard let index = players.firstIndex(of: player) else { return false } return players[index].state == .readyForNextRound } var isReadyForNextRound: Bool { for player in players where player.state != .readyForNextRound { return false } return true } func areAllRacePlayersReady(racePlayers: [WKRPlayer]) -> Bool { let relevantPlayers = players.filter({ racePlayers.contains($0) }) for player in relevantPlayers where player.state != .readyForNextRound { return false } return true } }
// // WKRReadyStates.swift // WKRKit // // Created by Andrew Finke on 8/31/17. // Copyright © 2017 Andrew Finke. All rights reserved. // import Foundation public struct WKRReadyStates: Codable { let players: [WKRPlayer] init(players: [WKRPlayer]) { self.players = players } public func isPlayerReady(_ player: WKRPlayer) -> Bool { guard let index = players.firstIndex(of: player) else { return false } return players[index].state == .readyForNextRound } func areAllRacePlayersReady(racePlayers: [WKRPlayer]) -> Bool { let relevantPlayers = players.filter({ racePlayers.contains($0) && $0.state != .quit }) for player in relevantPlayers where player.state != .readyForNextRound { return false } return true } }
Simplify type-erasure by making it just a function
// // Property.swift // R.swift // // Created by Mathijs Kadijk on 05-01-16. // Copyright © 2016 Mathijs Kadijk. All rights reserved. // import Foundation protocol Property: UsedTypesProvider, CustomStringConvertible { var name: String { get } } extension Property { var callName: String { return sanitizedSwiftName(name, lowercaseFirstCharacter: true) } }
// // Property.swift // R.swift // // Created by Mathijs Kadijk on 05-01-16. // Copyright © 2016 Mathijs Kadijk. All rights reserved. // import Foundation protocol Property: UsedTypesProvider, CustomStringConvertible { var name: String { get } } extension Property { var callName: String { return sanitizedSwiftName(name, lowercaseFirstCharacter: true) } } /// Type-erasure function func anyProperty(property: Property) -> Property { return property }
Add a random number to more filter awesomeness
// // FilterHelper.swift // CETAVFilter // // Created by Chris Jimenez on 2/14/16. // Copyright © 2016 Chris Jimenez. All rights reserved. // import Foundation import UIKit /// A helper class to apply filters to an image public class FilterHelper { //The context that will help us creating the image let context = CIContext(options: nil) /** Applys the filter to an image and returns it - parameter imageToFilter: Image to apply the filter to - returns: image with the filter apply */ public func applyFilter(imageToFilter: UIImage) -> UIImage { //Creates the CI image let inputImage = CIImage(image: imageToFilter) //Adds the filter to the image let filteredImage = inputImage!.imageByApplyingFilter("CIHueAdjust", withInputParameters: [kCIInputAngleKey:200]) //Renders the image let renderedImage = context.createCGImage(filteredImage, fromRect: filteredImage.extent) //Returns the image return UIImage(CGImage: renderedImage) } }
// // FilterHelper.swift // CETAVFilter // // Created by Chris Jimenez on 2/14/16. // Copyright © 2016 Chris Jimenez. All rights reserved. // import Foundation import UIKit /// A helper class to apply filters to an image public class FilterHelper { //The context that will help us creating the image let context = CIContext(options: nil) /** Applys the filter to an image and returns it - parameter imageToFilter: Image to apply the filter to - returns: image with the filter apply */ public func applyFilter(imageToFilter: UIImage) -> UIImage { //Creates the CI image let inputImage = CIImage(image: imageToFilter) //Generates a random number let randomNumber = Double(arc4random_uniform(300)+1) //Adds the filter to the image let filteredImage = inputImage!.imageByApplyingFilter("CIHueAdjust", withInputParameters: [kCIInputAngleKey:randomNumber]) //Renders the image let renderedImage = context.createCGImage(filteredImage, fromRect: filteredImage.extent) //Returns the image return UIImage(CGImage: renderedImage) } }
Check if dragged file has movie ext
// // MovieDraggable.swift // Subtle // // Created by Miguel Molina on 03/02/16. // Copyright © 2016 Miguel Molina. All rights reserved. // import Cocoa protocol FileQueueDelegate { func queueFile(path: String) } class MovieDraggable: NSView { var delegate: FileQueueDelegate? required init(coder: NSCoder) { super.init(coder: coder)! registerForDraggedTypes([NSFilenamesPboardType]) } override init(frame: NSRect) { super.init(frame: frame) registerForDraggedTypes([NSFilenamesPboardType]) } override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) } override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation { return NSDragOperation.Copy } override func performDragOperation(sender: NSDraggingInfo) -> Bool { let board = sender.draggingPasteboard() if let files = board.propertyListForType(NSFilenamesPboardType) as? NSArray { for file in files { if let path = file as? String { if isMovie(path) { delegate?.queueFile(path) } } } return true } return false } func isMovie(path: String) -> Bool { return true } }
// // MovieDraggable.swift // Subtle // // Created by Miguel Molina on 03/02/16. // Copyright © 2016 Miguel Molina. All rights reserved. // import Cocoa protocol FileQueueDelegate { func queueFile(path: String) } let movieExtensions = ["mov", "avi", "mkv", "mp4"] private func isMovie(path: String) -> Bool { if let idx = path.characters.reverse().indexOf(".") { let ext = path.substringFromIndex(idx.base) return movieExtensions.contains(ext) } return false } class MovieDraggable: NSView { var delegate: FileQueueDelegate? required init(coder: NSCoder) { super.init(coder: coder)! registerForDraggedTypes([NSFilenamesPboardType]) } override init(frame: NSRect) { super.init(frame: frame) registerForDraggedTypes([NSFilenamesPboardType]) } override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) } override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation { return NSDragOperation.Copy } override func performDragOperation(sender: NSDraggingInfo) -> Bool { let board = sender.draggingPasteboard() if let files = board.propertyListForType(NSFilenamesPboardType) as? NSArray { for file in files { if let path = file as? String { if isMovie(path) { delegate?.queueFile(path) } } } return true } return false } }
Fix a unit test for CustomStringConvertible conformance for string representation of Container in Swift 3.
// // Container+SwinjectStoryboardSpec.swift // Swinject // // Created by Yoichi Tagaya on 2/27/16. // Copyright © 2016 Swinject Contributors. All rights reserved. // import Quick import Nimble import Swinject #if os(iOS) || os(OSX) || os(tvOS) class Container_SwinjectStoryboardSpec: QuickSpec { override func spec() { var container: Container! beforeEach { container = Container() } describe("CustomStringConvertible") { it("describes a registration with storyboard option.") { let controllerType = String(Container.Controller.self) // "UIViewController" for iOS/tvOS, "AnyObject" for OSX. container.registerForStoryboard(AnimalViewController.self) { r, c in } expect(container.description) == "[\n" + " { Service: \(controllerType), Storyboard: SwinjectStoryboardTests.AnimalViewController, " + "Factory: (ResolverType, \(controllerType)) -> \(controllerType), ObjectScope: Graph, InitCompleted: Specified }\n" + "]" } } } } #endif
// // Container+SwinjectStoryboardSpec.swift // Swinject // // Created by Yoichi Tagaya on 2/27/16. // Copyright © 2016 Swinject Contributors. All rights reserved. // import Quick import Nimble import Swinject #if os(iOS) || os(OSX) || os(tvOS) class Container_SwinjectStoryboardSpec: QuickSpec { override func spec() { var container: Container! beforeEach { container = Container() } describe("CustomStringConvertible") { it("describes a registration with storyboard option.") { let controllerType = String(Container.Controller.self) // "UIViewController" for iOS/tvOS, "AnyObject" for OSX. container.registerForStoryboard(AnimalViewController.self) { r, c in } expect(container.description) == "[\n" + " { Service: \(controllerType), Storyboard: SwinjectStoryboardTests.AnimalViewController, " + "Factory: ((ResolverType, \(controllerType))) -> \(controllerType), ObjectScope: graph, InitCompleted: Specified }\n" + "]" } } } } #endif
Add equatable conformance to Environment
enum Environment { case Production, Development, custom(String) var string: String { switch self { case .Production: return "Production" case .Development: return "Development" case .custom(let string): return string } } } // looks like this will be automatic in a later version of Swift func ==(lhs: Environment, rhs: Environment) -> Bool { return lhs.string == rhs.string } // FlyConfig protocol FlyConfig { var environment: Environment { get } var showDebugRoutes: Bool { get } } extension FlyConfig { var environment: Environment { return .Production } var showDebugRoutes: Bool { return environment == Environment.Development } }
enum Environment { case Production, Development, custom(String) var string: String { switch self { case .Production: return "Production" case .Development: return "Development" case .custom(let string): return string } } } extension Environment: Equatable {} // looks like this will be automatic in a later version of Swift func ==(lhs: Environment, rhs: Environment) -> Bool { return lhs.string == rhs.string } // FlyConfig protocol FlyConfig { var environment: Environment { get } var showDebugRoutes: Bool { get } } extension FlyConfig { var environment: Environment { return .Production } var showDebugRoutes: Bool { return environment == Environment.Development } }
Add struct for dealing with broker connection
// // Broker.swift // SwiftKafka // // Created by Athanasios Theodoridis on 26/08/2017. // // /// An enum representing the protocol used for a broker connection public enum BrokerProtocol: String { case plaintext = "PLAINTEXT://" case ssl = "SSL://" case sasl = "SASL://" case sasl_plaintext = "SASL_PLAINTEXT://" } /// Represents a Kafka broker that we can connect to public struct Broker { // MARK: - Private Properties /// The used protocol for this broker connection fileprivate let `protocol`: BrokerProtocol /// The port of this broker connection fileprivate let port: Int /// The host of this broker connection fileprivate let host: String // MARK: - Initialiser init(withProtocol protocol: BrokerProtocol = .plaintext, host: String, port: Int) { self.`protocol` = `protocol` self.host = host self.port = port } }
// // Broker.swift // SwiftKafka // // Created by Athanasios Theodoridis on 26/08/2017. // // /// An enum representing the protocol used for a broker connection public enum BrokerProtocol: String { case plaintext = "PLAINTEXT://" case ssl = "SSL://" case sasl = "SASL://" case sasl_plaintext = "SASL_PLAINTEXT://" } /// Represents a Kafka broker for connecting to public struct Broker { // MARK: - Private Properties /// The used protocol for this broker connection fileprivate let `protocol`: BrokerProtocol /// The port of this broker connection fileprivate let port: Int /// The host of this broker connection fileprivate let host: String // MARK: - Initialiser init(withProtocol protocol: BrokerProtocol = .plaintext, host: String, port: Int? = 9092) { self.`protocol` = `protocol` self.host = host self.port = port } } extension Broker: CustomStringConvertible { public var description: String { return "\(`protocol`.rawValue)\(host):\(port)" } }
Fix Doc for CGFloat Central
// // CEMKit+CGFloat.swift // // // Created by Cem Olcay on 12/08/15. // // import UIKit extension CGFloat { /// EZSwiftExtensions public var center: CGFloat { return (self / 2) } } /// EZSE: Converts angle degrees to radians public func degreesToRadians (angle: CGFloat) -> CGFloat { return (CGFloat (M_PI) * angle) / 180.0 }
// // CEMKit+CGFloat.swift // // // Created by Cem Olcay on 12/08/15. // // import UIKit extension CGFloat { /// EZSE: Return the central value of CGFloat. public var center: CGFloat { return (self / 2) } } /// EZSE: Converts angle degrees to radians. public func degreesToRadians (angle: CGFloat) -> CGFloat { return (CGFloat (M_PI) * angle) / 180.0 }
Add moveToPath(_:) method to File
// // FileKit.swift // FileKit // // Created by Nikolai Vazquez on 9/1/15. // Copyright © 2015 Nikolai Vazquez. All rights reserved. // import Foundation public class File: StringLiteralConvertible { // MARK: - File public var path: Path public init(path: Path) { self.path = path } // MARK: - StringLiteralConvertible public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType public typealias UnicodeScalarLiteralType = StringLiteralType public required init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { path = Path(value) } public required init(stringLiteral value: StringLiteralType) { path = Path(value) } public required init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { path = Path(value) } }
// // FileKit.swift // FileKit // // Created by Nikolai Vazquez on 9/1/15. // Copyright © 2015 Nikolai Vazquez. All rights reserved. // import Foundation public class File: StringLiteralConvertible { // MARK: - File public var path: Path public init(path: Path) { self.path = path } func moveToPath(path: Path) throws { try NSFileManager.defaultManager().moveItemAtPath(path._path, toPath: path._path) self.path = path } // MARK: - StringLiteralConvertible public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType public typealias UnicodeScalarLiteralType = StringLiteralType public required init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { path = Path(value) } public required init(stringLiteral value: StringLiteralType) { path = Path(value) } public required init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { path = Path(value) } }
Add search bar to navigation bar
import UIKit class ControllerList:UIViewController { init() { super.init(nibName:nil, bundle:nil) } required init?(coder:NSCoder) { return nil } override func loadView() { let view:ViewList = ViewList(controller:self) self.view = view } }
import UIKit class ControllerList:UIViewController { init() { super.init(nibName:nil, bundle:nil) navigationItem.titleView = ViewListBar() } required init?(coder:NSCoder) { return nil } override func loadView() { let view:ViewList = ViewList(controller:self) self.view = view } }
Use data phase as enum
import Foundation struct MVitaPtpDataPhase { static let none:UInt32 = 0 static let send:UInt32 = 1 static let receive:UInt32 = 2 }
import Foundation enum MVitaPtpDataPhase:UInt32 { case none = 0 case send = 1 case receive = 2 }
Mark another StdlibUnittest as "XFAIL: interpret".
// RUN: %target-run-simple-swift import Foundation import StdlibUnittest var FoundationPrinting = TestSuite("FoundationPrinting") FoundationPrinting.test("OverlayTypesHaveDescription") { func hasDescription(_: Printable) {} var a: ObjCBool = true hasDescription(a) } FoundationPrinting.test("ObjCBoolPrinting") { var true_: ObjCBool = true var false_: ObjCBool = false expectPrinted("true", true_) expectPrinted("false", false_) } FoundationPrinting.test("SelectorPrinting") { expectPrinted("", Selector("")) expectPrinted(":", Selector(":")) expectPrinted("a", Selector("a")) expectPrinted("abc", Selector("abc")) expectPrinted("abc:", Selector("abc:")) expectPrinted("abc:def:", Selector("abc:def:")) } runAllTests()
// RUN: %target-run-simple-swift // XFAIL: interpret import Foundation import StdlibUnittest var FoundationPrinting = TestSuite("FoundationPrinting") FoundationPrinting.test("OverlayTypesHaveDescription") { func hasDescription(_: Printable) {} var a: ObjCBool = true hasDescription(a) } FoundationPrinting.test("ObjCBoolPrinting") { var true_: ObjCBool = true var false_: ObjCBool = false expectPrinted("true", true_) expectPrinted("false", false_) } FoundationPrinting.test("SelectorPrinting") { expectPrinted("", Selector("")) expectPrinted(":", Selector(":")) expectPrinted("a", Selector("a")) expectPrinted("abc", Selector("abc")) expectPrinted("abc:", Selector("abc:")) expectPrinted("abc:def:", Selector("abc:def:")) } runAllTests()
Correct typo and add clockwise direction
// // GTProgressBarDirection.swift // GTProgressBar // // Created by greg on 15/11/2017. // import Foundation public enum GTProgressBarDirection: Int { case anticlocwise }
// // GTProgressBarDirection.swift // GTProgressBar // // Created by greg on 15/11/2017. // import Foundation public enum GTProgressBarDirection: Int { case clockwise case anticlockwise }
Use swift tools version 5
// swift-tools-version:4.2 import PackageDescription let package = Package( name: "Clang", products: [ .library( name: "Clang", targets: ["Clang"]) ], dependencies: [ ], targets: [ .systemLibrary( name: "cclang", pkgConfig: "cclang", providers: [ .brew(["llvm"]), ]), .target( name: "Clang", dependencies: ["cclang"]), .testTarget( name: "ClangTests", dependencies: ["Clang"]) ] )
// swift-tools-version:5.0 import PackageDescription let package = Package( name: "Clang", products: [ .library( name: "Clang", targets: ["Clang"]) ], dependencies: [ ], targets: [ .systemLibrary( name: "cclang", pkgConfig: "cclang", providers: [ .brew(["llvm"]), ]), .target( name: "Clang", dependencies: ["cclang"]), .testTarget( name: "ClangTests", dependencies: ["Clang"]) ] )
Change getting started to bullet points.
import Prelude /*: # Prelude A collection of tools that are used in the Kickstarter apps. --- ## Getting started To execute these playground files you must first open `Prelude.xcworkspace` instead of the playground file directly, and hit `cmd+B` in order to build the framework. To render the markdown go to Editor > Show Rendered Markup. ## Table of contents * [Array.swift](Array.swift) * [Function.swift](Function.swift) */
import Prelude /*: # Prelude A collection of tools that are used in the Kickstarter apps. --- ## Getting started * Open `Prelude.xcworkspace` instead of the playground file directly. * Build the `Prelude` framework (`cmd+B`). * Render the markdown by going to Editor > Show Rendered Markup. ## Table of contents * [Array.swift](Array.swift) * [Function.swift](Function.swift) */
Test the iteration of effectful streams.
// Copyright (c) 2014 Rob Rix. All rights reserved. import Traversal import XCTest class StreamTests: XCTestCase { func testStreams() { let sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9] let reducible = ReducibleOf(sequence: sequence) let stream = Stream(reducible) XCTAssertEqual(first(stream)!, 1) XCTAssertEqual(first(stream)!, 1) XCTAssertEqual(first(dropFirst(stream))!, 2) XCTAssertEqual(first(dropFirst(stream))!, 2) XCTAssertEqual(first(dropFirst(dropFirst(dropFirst(stream))))!, 4) var n = 0 for (a, b) in Zip2(stream, sequence) { XCTAssertEqual(a, b) n++ } XCTAssertEqual(Array(stream), sequence) XCTAssertEqual(n, sequence.count) } }
// Copyright (c) 2014 Rob Rix. All rights reserved. import Traversal import XCTest class StreamTests: XCTestCase { func testStreams() { let sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9] let reducible = ReducibleOf(sequence: sequence) let stream = Stream(reducible) XCTAssertEqual(first(stream)!, 1) XCTAssertEqual(first(stream)!, 1) XCTAssertEqual(first(dropFirst(stream))!, 2) XCTAssertEqual(first(dropFirst(stream))!, 2) XCTAssertEqual(first(dropFirst(dropFirst(dropFirst(stream))))!, 4) var n = 0 for (a, b) in Zip2(stream, sequence) { XCTAssertEqual(a, b) n++ } XCTAssertEqual(Array(stream), sequence) XCTAssertEqual(n, sequence.count) } func testEffectfulStreams() { var effects = 0 let sequence = SequenceOf<Int> { GeneratorOf { if effects < 5 { effects++ return effects } return nil } } XCTAssertEqual(effects, 0) let stream = Stream(ReducibleOf(sequence: sequence)) XCTAssertEqual(effects, 1) first(stream) XCTAssertEqual(effects, 1) first(dropFirst(stream)) XCTAssertEqual(effects, 2) for each in stream {} XCTAssertEqual(effects, 5) XCTAssertEqual(first(stream)!, 1) XCTAssertEqual(first(dropFirst(dropFirst(dropFirst(dropFirst(stream)))))!, 5) XCTAssertNil(first(dropFirst(dropFirst(dropFirst(dropFirst(dropFirst(stream))))))) } }
Revert "Make subscribe handler argument anonymous"
import Foundation public struct SubscriptionOptions: OptionSetType { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let New = SubscriptionOptions(rawValue: 1) public static let Initial = SubscriptionOptions(rawValue: 2) } public struct Observable<T> { // MARK: - Types public typealias SubscriptionType = Subscription<T> // MARK: - Properties private let eventQueue = dispatch_get_global_queue(QOS_CLASS_UTILITY, 0) public var value: T { didSet { dispatch_sync(eventQueue) { self.subscribers.send(self.value) } } } // MARK: - Initialization public init(initial value: T) { self.value = value } // MARK: - Subscribers private var subscribers = Subscriptions<T>() public mutating func subscribe(options: SubscriptionOptions = [.New], _ handler: SubscriptionType.EventHandler) -> SubscriptionType { let subscription = Subscription(handler: handler) if options.contains(.Initial) { subscription.handler(value) } subscribers.add(subscription) return subscription } public mutating func unsubscribe(subscriber: SubscriptionType) { subscribers.remove(subscriber) } }
import Foundation public struct SubscriptionOptions: OptionSetType { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let New = SubscriptionOptions(rawValue: 1) public static let Initial = SubscriptionOptions(rawValue: 2) } public struct Observable<T> { // MARK: - Types public typealias SubscriptionType = Subscription<T> // MARK: - Properties private let eventQueue = dispatch_get_global_queue(QOS_CLASS_UTILITY, 0) public var value: T { didSet { dispatch_sync(eventQueue) { self.subscribers.send(self.value) } } } // MARK: - Initialization public init(initial value: T) { self.value = value } // MARK: - Subscribers private var subscribers = Subscriptions<T>() public mutating func subscribe(options: SubscriptionOptions = [.New], handler: SubscriptionType.EventHandler) -> SubscriptionType { let subscription = Subscription(handler: handler) if options.contains(.Initial) { subscription.handler(value) } subscribers.add(subscription) return subscription } public mutating func unsubscribe(subscriber: SubscriptionType) { subscribers.remove(subscriber) } }
Add some tests for malformed availability attributes.
// RUN: %swift %s -parse -verify @availability(*, unavailable) func unavailable_func() {} @availability(*, unavailable, message="message") func unavailable_func_with_message() {} @availability(iOS, unavailable) @availability(OSX, unavailable) func unavailable_multiple_platforms() {} @availability(badPlatform, unavailable) // expected-error {{unknown platform 'badPlatform' for attribute 'availability'}} func unavailable_bad_platform() {} // Handle unknown platform. @availability(HAL9000, unavailable) // expected-error {{unknown platform 'HAL9000'}} func availabilityUnknownPlatform() {} // <rdar://problem/17669805> Availability can't appear on a typealias @availability(*, unavailable, message="oh no you dont") typealias int = Int var x : int // expected-error {{'int' is unavailable: oh no you dont}}
// RUN: %swift %s -parse -verify @availability(*, unavailable) func unavailable_func() {} @availability(*, unavailable, message="message") func unavailable_func_with_message() {} @availability(iOS, unavailable) @availability(OSX, unavailable) func unavailable_multiple_platforms() {} @availability // expected-error {{expected '(' in 'availability' attribute}} func noArgs() {} @availability(*) // expected-error {{expected ',' in 'availability' attribute}} expected-error {{expected declaration}} func noKind() {} @availability(badPlatform, unavailable) // expected-error {{unknown platform 'badPlatform' for attribute 'availability'}} func unavailable_bad_platform() {} // Handle unknown platform. @availability(HAL9000, unavailable) // expected-error {{unknown platform 'HAL9000'}} func availabilityUnknownPlatform() {} // <rdar://problem/17669805> Availability can't appear on a typealias @availability(*, unavailable, message="oh no you dont") typealias int = Int var x : int // expected-error {{'int' is unavailable: oh no you dont}}
Add wildcard parameter case to VariableType test
func x(_ param: Int) -> Int { param } let y: (String) -> Void = { param in } let z = { (param: String) in param.count } // RUN: %sourcekitd-test -req=collect-var-type %s -- %s | %FileCheck %s // CHECK: (1:10, 1:15): Int (explicit type: 1) // CHECK: (5:5, 5:6): (String) -> Void (explicit type: 1) // CHECK: (5:29, 5:34): String (explicit type: 0) // CHECK: (7:5, 7:6): (String) -> Int (explicit type: 0) // CHECK: (7:12, 7:17): String (explicit type: 1)
func x(_ param: Int) -> Int { param } let y: (String) -> Void = { param in } let z = { (param: String) in param.count } let w: (String, Int) -> Void = { (_, x) in } // RUN: %sourcekitd-test -req=collect-var-type %s -- %s | %FileCheck %s // CHECK: (1:10, 1:15): Int (explicit type: 1) // CHECK: (5:5, 5:6): (String) -> Void (explicit type: 1) // CHECK: (5:29, 5:34): String (explicit type: 0) // CHECK: (7:5, 7:6): (String) -> Int (explicit type: 0) // CHECK: (7:12, 7:17): String (explicit type: 1) // CHECK: (11:35, 11:36): String (explicit type: 0) // CHECK: (11:38, 11:39): Int (explicit type: 0)
Add static shorthands for left, right, up and down 2D vectors
import Darwin struct Vector2D { let x: Double let y: Double init(_ x: Double, _ y: Double) { self.x = x self.y = y } var magnitude: Double { return sqrt(x * x + y * y) } }
import Darwin struct Vector2D { let x: Double let y: Double init(_ x: Double, _ y: Double) { self.x = x self.y = y } var magnitude: Double { return sqrt(x * x + y * y) } static let left = Vector2D(-1, 0) static let right = Vector2D(1, 0) static let up = Vector2D(0, 1) static let down = Vector2D(0, -1) }
Remove empty UI test to save build time
// // Rocket_ChatUITests.swift // Rocket.ChatUITests // // Created by Rafael K. Streit on 7/5/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import XCTest class RocketChatUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
// // Rocket_ChatUITests.swift // Rocket.ChatUITests // // Created by Rafael K. Streit on 7/5/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import XCTest class RocketChatUITests: XCTestCase { }
Add test cases for `GraphSerie.Circular`
// // GraphSerieSpec.swift // SwiftyEcharts // // Created by Pluto Y on 26/10/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // import Quick import Nimble @testable import SwiftyEcharts class GraphSerieSpec: QuickSpec { override func spec() { describe("For GraphSerie.Layout") { let noneString = "none" let circularString = "circular" let forceString = "force" let noneLayout = GraphSerie.Layout.none let circularLayout = GraphSerie.Layout.circular let forceLayout = GraphSerie.Layout.force it("needs to check the jsonString") { expect(noneLayout.jsonString).to(equal(noneString.jsonString)) expect(circularLayout.jsonString).to(equal(circularString.jsonString)) expect(forceLayout.jsonString).to(equal(forceString.jsonString)) } } } }
// // GraphSerieSpec.swift // SwiftyEcharts // // Created by Pluto Y on 26/10/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // import Quick import Nimble @testable import SwiftyEcharts class GraphSerieSpec: QuickSpec { override func spec() { describe("For GraphSerie.Layout") { let noneString = "none" let circularString = "circular" let forceString = "force" let noneLayout = GraphSerie.Layout.none let circularLayout = GraphSerie.Layout.circular let forceLayout = GraphSerie.Layout.force it("needs to check the jsonString") { expect(noneLayout.jsonString).to(equal(noneString.jsonString)) expect(circularLayout.jsonString).to(equal(circularString.jsonString)) expect(forceLayout.jsonString).to(equal(forceString.jsonString)) } } let rotateLabelCircularValue = false let circular = GraphSerie.Circular() circular.rotateLabel = rotateLabelCircularValue describe("For GraphSerie.Circular") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "rotateLabel": rotateLabelCircularValue ] expect(circular.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let circularByEnums = GraphSerie.Circular( .rotateLabel(rotateLabelCircularValue) ) expect(circularByEnums.jsonString).to(equal(circular.jsonString)) } } } }
Test factory url and request
import XCTest class TMGiphyRandom:XCTestCase { }
import XCTest @testable import gattaca class TMGiphyRandom:XCTestCase { //MARK: internal func testFactoryUrl() { let url:URL? = MGiphy.factoryRandomUrl() XCTAssertNotNil( url, "failed factorying url") } func testFactoryRequest() { let request:URLRequest? = MGiphy.factoryRandomRequest() XCTAssertNotNil( request, "failed factorying request") } }
Fix releasing the object too fast
import Foundation import XCTest // NOTE: This file is not intended to be included in the Xcode project or CocoaPods. // It is picked up by the Swift Package Manager during its build process. #if SWIFT_PACKAGE open class QuickConfiguration: NSObject { open class func configure(_ configuration: Configuration) {} } #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) internal func qck_enumerateSubclasses<T: AnyObject>(_ klass: T.Type, block: (T.Type) -> Void) { var classesCount = objc_getClassList(nil, 0) guard classesCount > 0 else { return } let classes = UnsafeMutablePointer<AnyClass?>.allocate(capacity: Int(classesCount)) classesCount = objc_getClassList(AutoreleasingUnsafeMutablePointer(classes), classesCount) var subclass: AnyClass! for i in 0..<classesCount { subclass = classes[Int(i)] if let superclass = class_getSuperclass(subclass), superclass === klass { block(subclass as! T.Type) // swiftlint:disable:this force_cast } } free(classes) } #endif #endif
import Foundation import XCTest // NOTE: This file is not intended to be included in the Xcode project or CocoaPods. // It is picked up by the Swift Package Manager during its build process. #if SWIFT_PACKAGE open class QuickConfiguration: NSObject { open class func configure(_ configuration: Configuration) {} } #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) internal func qck_enumerateSubclasses<T: AnyObject>(_ klass: T.Type, block: (T.Type) -> Void) { var classesCount = objc_getClassList(nil, 0) guard classesCount > 0 else { return } let classes = UnsafeMutablePointer<AnyClass?>.allocate(capacity: Int(classesCount)) classesCount = objc_getClassList(AutoreleasingUnsafeMutablePointer(classes), classesCount) var subclass: AnyClass! for i in 0..<classesCount { subclass = classes[Int(i)] guard let superclass = class_getSuperclass(subclass), superclass == klass else { continue } block(subclass as! T.Type) // swiftlint:disable:this force_cast } free(classes) } #endif #endif
Use NS_BLOCK_ASSERTIONS for SwiftPM release builds
// swift-tools-version:5.1 import PackageDescription let package = Package( name: "TrustKit", platforms: [ .iOS(.v12), .macOS(.v10_13), .tvOS(.v12), .watchOS(.v4) ], products: [ .library( name: "TrustKit", targets: ["TrustKit"] ), .library( name: "TrustKitDynamic", type: .dynamic, targets: ["TrustKit"] ), .library( name: "TrustKitStatic", type: .static, targets: ["TrustKit"] ), ], dependencies: [ ], targets: [ .target( name: "TrustKit", dependencies: [], path: "TrustKit", publicHeadersPath: "public" ), ] )
// swift-tools-version:5.1 import PackageDescription let package = Package( name: "TrustKit", platforms: [ .iOS(.v12), .macOS(.v10_13), .tvOS(.v12), .watchOS(.v4) ], products: [ .library( name: "TrustKit", targets: ["TrustKit"] ), .library( name: "TrustKitDynamic", type: .dynamic, targets: ["TrustKit"] ), .library( name: "TrustKitStatic", type: .static, targets: ["TrustKit"] ), ], dependencies: [ ], targets: [ .target( name: "TrustKit", dependencies: [], path: "TrustKit", publicHeadersPath: "public", cSettings: [.define("NS_BLOCK_ASSERTIONS", to: "1", .when(configuration: .release))] ), ] )
Stop using internal/external name as property name overrides it and prevents the code from working. Make components a var so that it can be modified (isn't it a reference type?).
// // NSURL+HTTP.swift // ModestProposal // // Copyright (c) 2014 Justin Kolb - http://franticapparatus.net // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public extension NSURL { public func buildURL(path pathOrNil: String?, parameters: [String:String]? = nil) -> NSURL? { if let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: true) { components.path = String.pathWithComponents([components.path ?? "", path ?? ""]) components.parameters = parameters return components.URL } else { return nil } } }
// // NSURL+HTTP.swift // ModestProposal // // Copyright (c) 2014 Justin Kolb - http://franticapparatus.net // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public extension NSURL { public func buildURL(# path: String?, parameters: [String:String]? = nil) -> NSURL? { if var components = NSURLComponents(URL: self, resolvingAgainstBaseURL: true) { components.path = String.pathWithComponents([components.path ?? "", path ?? ""]) components.parameters = parameters return components.URL } else { return nil } } }
Send editingChanged when using UITextField setClearButton
// // Created by Tom Baranes on 18/01/2017. // Copyright © 2017 Tom Baranes. All rights reserved. // import UIKit public extension UITextField { public func setClearButton(with image: UIImage) { let clearButton = UIButton(type: .custom) clearButton.setImage(image, for: .normal) clearButton.frame = CGRect(origin: .zero, size: image.size) clearButton.contentMode = .left clearButton.addTarget(self, action: #selector(clear), for: .touchUpInside) clearButtonMode = .never rightView = clearButton rightViewMode = .whileEditing } func clear() { self.text = "" } }
// // Created by Tom Baranes on 18/01/2017. // Copyright © 2017 Tom Baranes. All rights reserved. // import UIKit public extension UITextField { public func setClearButton(with image: UIImage) { let clearButton = UIButton(type: .custom) clearButton.setImage(image, for: .normal) clearButton.frame = CGRect(origin: .zero, size: image.size) clearButton.contentMode = .left clearButton.addTarget(self, action: #selector(clear), for: .touchUpInside) clearButtonMode = .never rightView = clearButton rightViewMode = .whileEditing } func clear() { self.text = "" self.sendActions(for: .editingChanged) } }
Disable cache for DELETE request
// // S3+Delete.swift // S3 // // Created by Ondrej Rafaj on 11/05/2018. // import Foundation import Vapor // Helper S3 extension for deleting files by their URL/path public extension S3 { // MARK: Delete /// Delete file from S3 public func delete(file: LocationConvertible, headers: [String: String], on container: Container) throws -> Future<Void> { let builder = urlBuilder(for: container) let url = try builder.url(file: file) let headers = try signer.headers(for: .DELETE, urlString: url.absoluteString, headers: headers, payload: .none) return try make(request: url, method: .DELETE, headers: headers, data: emptyData(), on: container).map(to: Void.self) { response in try self.check(response) return Void() } } /// Delete file from S3 public func delete(file: LocationConvertible, on container: Container) throws -> Future<Void> { return try delete(file: file, headers: [:], on: container) } }
// // S3+Delete.swift // S3 // // Created by Ondrej Rafaj on 11/05/2018. // import Foundation import Vapor // Helper S3 extension for deleting files by their URL/path public extension S3 { // MARK: Delete /// Delete file from S3 public func delete(file: LocationConvertible, headers: [String: String], on container: Container) throws -> Future<Void> { let builder = urlBuilder(for: container) let url = try builder.url(file: file) let headers = try signer.headers(for: .DELETE, urlString: url.absoluteString, headers: headers, payload: .none) return try make(request: url, method: .DELETE, headers: headers, data: emptyData(), cachePolicy: .reloadIgnoringLocalCacheData, on: container).map(to: Void.self) { response in try self.check(response) return Void() } } /// Delete file from S3 public func delete(file: LocationConvertible, on container: Container) throws -> Future<Void> { return try delete(file: file, headers: [:], on: container) } }
Support both versions of Swift
import Foundation import AutobahnDescription // let autobahn = Autobahn() // autoban.defaultTask = "release" beforeAll { highway in print("Driving highway: \(highway)") } highway("build") { print("Building...") try sh("swift", "build") } highway("test") { try sh("swift", "test") } highway("deploy") { print("Deploying...") } highway("release", dependsOn: ["build", "deploy"]) { print("Releasing...") } afterAll { highway in print("Successfully ran task: \(highway)") } onError { highway, error in print("Error driving highway: \(highway)") print("Error: \(error.localizedDescription)") }
import Foundation import AutobahnDescription // let autobahn = Autobahn() // autoban.defaultTask = "release" beforeAll { highway in print("Driving highway: \(highway)") } highway("build") { print("Building...") try sh("swift", "build") } highway("test") { try sh("swift", "test") } highway("deploy") { print("Deploying...") } highway("release", dependsOn: ["build", "deploy"]) { print("Releasing...") } afterAll { highway in print("Successfully drove highway: \(highway)") } onError { highway, error in print("Error driving highway: \(highway)") print("Error: \(error.localizedDescription)") }
Update UIApplicationLaunchOptionsKey to UIApplication.LaunchOptionsKey for xcode10
/* * Copyright 2015-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ import UIKit @UIApplicationMain final class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let vc = UIViewController() vc.view.backgroundColor = UIColor.red let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = vc self.window = window window.makeKeyAndVisible() return true } }
/* * Copyright 2015-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ import UIKit @UIApplicationMain final class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let vc = UIViewController() vc.view.backgroundColor = UIColor.red let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = vc self.window = window window.makeKeyAndVisible() return true } }
Add public initializer to error middleware
// // JsonApiErrorMiddleware.swift // VaporJsonApi // // Created by Koray Koska on 01/05/2017. // // import Vapor import HTTP public final class JsonApiErrorMiddleware: Middleware { public func respond(to request: Request, chainingTo next: Responder) throws -> Response { do { return try next.respond(to: request) } catch let e as JsonApiError { let error = JsonApiErrorObject(status: String(e.status.statusCode), code: e.code, title: e.title, detail: e.detail) let document = JsonApiDocument(errors: [error]) let response = JsonApiResponse(status: e.status, document: document) return try response.makeResponse() } } }
// // JsonApiErrorMiddleware.swift // VaporJsonApi // // Created by Koray Koska on 01/05/2017. // // import Vapor import HTTP public final class JsonApiErrorMiddleware: Middleware { public init() {} public func respond(to request: Request, chainingTo next: Responder) throws -> Response { do { return try next.respond(to: request) } catch let e as JsonApiError { let error = JsonApiErrorObject(status: String(e.status.statusCode), code: e.code, title: e.title, detail: e.detail) let document = JsonApiDocument(errors: [error]) let response = JsonApiResponse(status: e.status, document: document) return try response.makeResponse() } } }
Update to match the new array syntax
// Playground - noun: a place where people can play import Cocoa class Person { var name: String var age: Int? var consideredDangerous = false init(name: String, age: Int?) { self.name = name self.age = age } convenience init(name: String) { self.init(name: name, age: nil) } } enum Weapon { case Katana, Tsuba, Shuriken, Kusarigama, Fukiya } class Ninja: Person { var weapons: Weapon[]? init(name: String, age: Int?, weapons: Weapon[]?) { self.weapons = weapons super.init(name: name, age: age) self.consideredDangerous = true } convenience init(name: String) { self.init(name: name, age: nil, weapons: nil) } } let tony = Person(name: "tony") tony.consideredDangerous tony.age tony.age = 43 tony let tara = Person(name: "tara", age: 27) tara.consideredDangerous tara.age let trevor = Ninja(name: "trevor") trevor.age trevor.consideredDangerous let tina = Ninja(name: "tina", age: 23, weapons: [.Fukiya, .Tsuba]) tina.consideredDangerous tina.weapons tina.age
// Playground - noun: a place where people can play import Cocoa class Person { var name: String var age: Int? var consideredDangerous = false init(name: String, age: Int?) { self.name = name self.age = age } convenience init(name: String) { self.init(name: name, age: nil) } } enum Weapon { case Katana, Tsuba, Shuriken, Kusarigama, Fukiya } class Ninja: Person { var weapons: [Weapon]? init(name: String, age: Int?, weapons: [Weapon]?) { self.weapons = weapons super.init(name: name, age: age) self.consideredDangerous = true } convenience init(name: String) { self.init(name: name, age: nil, weapons: nil) } } let tony = Person(name: "tony") tony.consideredDangerous tony.age tony.age = 43 tony let tara = Person(name: "tara", age: 27) tara.consideredDangerous tara.age let trevor = Ninja(name: "trevor") trevor.age trevor.consideredDangerous let tina = Ninja(name: "tina", age: 23, weapons: [.Fukiya, .Tsuba]) tina.consideredDangerous tina.weapons tina.age
Change parameter type of updateProfile: [String:String] to
// // ProfileAPI.swift // FeedlyKit // // Created by Hiroki Kumamoto on 1/20/15. // Copyright (c) 2015 Hiroki Kumamoto. All rights reserved. // import Alamofire import SwiftyJSON extension CloudAPIClient { /** Get the profile of the user GET /v3/profile */ public func fetchProfile(completionHandler: (Response<Profile, NSError>) -> Void) -> Request { return manager.request(Router.FetchProfile(target)).validate().responseObject(completionHandler) } /** Update the profile of the user POST /v3/profile */ public func updateProfile(params: [String:String], completionHandler: (Response<Profile, NSError>) -> Void) -> Request { return manager.request(Router.UpdateProfile(target, params)).validate().responseObject(completionHandler) } }
// // ProfileAPI.swift // FeedlyKit // // Created by Hiroki Kumamoto on 1/20/15. // Copyright (c) 2015 Hiroki Kumamoto. All rights reserved. // import Alamofire import SwiftyJSON extension CloudAPIClient { /** Get the profile of the user GET /v3/profile */ public func fetchProfile(completionHandler: (Response<Profile, NSError>) -> Void) -> Request { return manager.request(Router.FetchProfile(target)).validate().responseObject(completionHandler) } /** Update the profile of the user POST /v3/profile */ public func updateProfile(params: [String:AnyObject], completionHandler: (Response<Profile, NSError>) -> Void) -> Request { return manager.request(Router.UpdateProfile(target, params)).validate().responseObject(completionHandler) } }
Change struct with static funcs to enum
// // StatusBar.swift // Freetime // // Created by Ryan Nystrom on 5/17/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import JDStatusBarNotification struct StatusBar { private static func provideHapticFeedback() { UINotificationFeedbackGenerator().notificationOccurred(.error) } static func showRevokeError() { JDStatusBarNotification.show( withStatus: NSLocalizedString("Your access token was revoked.", comment: ""), dismissAfter: 3, styleName: JDStatusBarStyleError ) provideHapticFeedback() } static func showNetworkError() { JDStatusBarNotification.show( withStatus: NSLocalizedString("Network connection lost.", comment: ""), dismissAfter: 3, styleName: JDStatusBarStyleError ) provideHapticFeedback() } static func showGenericError() { JDStatusBarNotification.show( withStatus: NSLocalizedString("Something went wrong.", comment: ""), dismissAfter: 3, styleName: JDStatusBarStyleError ) provideHapticFeedback() } }
// // StatusBar.swift // Freetime // // Created by Ryan Nystrom on 5/17/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import JDStatusBarNotification enum StatusBar { private static func provideHapticFeedback() { UINotificationFeedbackGenerator().notificationOccurred(.error) } static func showRevokeError() { JDStatusBarNotification.show( withStatus: NSLocalizedString("Your access token was revoked.", comment: ""), dismissAfter: 3, styleName: JDStatusBarStyleError ) provideHapticFeedback() } static func showNetworkError() { JDStatusBarNotification.show( withStatus: NSLocalizedString("Network connection lost.", comment: ""), dismissAfter: 3, styleName: JDStatusBarStyleError ) provideHapticFeedback() } static func showGenericError() { JDStatusBarNotification.show( withStatus: NSLocalizedString("Something went wrong.", comment: ""), dismissAfter: 3, styleName: JDStatusBarStyleError ) provideHapticFeedback() } }
Use default (empty) edge sets.
// Copyright (c) 2015 Rob Rix. All rights reserved. final class InferenceTests: XCTestCase { func testGraphsWithoutReturnsHaveUnitType() { assert(type(Graph()), ==, .Unit) } func testGraphsWithOneReturnHaveVariableType() { assert(type(Graph(nodes: [Identifier(): .Return((0, .Unit))])), ==, 0) } func testGraphsWithOneParameterAndNoReturnsHaveFunctionTypeReturningUnit() { assert(type(Graph(nodes: [Identifier(): .Parameter((0, .Unit))], edges: [])), ==, .function(0, .Unit)) } func testGraphsWithOneParameterAndOneReturnHaveFunctionTypeFromVariableToDifferentVariable() { assert(type(Graph(nodes: [Identifier(): .Parameter((0, .Unit)), Identifier(): .Return((0, .Unit))], edges: [])), ==, .function(1, 0)) } } private func type(graph: Graph<Node>) -> Term { return simplify(constraints(graph).0) } private func simplify(type: Term) -> Term { return Substitution(lazy(enumerate(type.freeVariables |> (flip(sorted) <| { $0.value < $1.value }))).map { ($1, Term(integerLiteral: $0)) }).apply(type) } import Assertions import Manifold import Prelude import TesseractCore import XCTest
// Copyright (c) 2015 Rob Rix. All rights reserved. final class InferenceTests: XCTestCase { func testGraphsWithoutReturnsHaveUnitType() { assert(type(Graph()), ==, .Unit) } func testGraphsWithOneReturnHaveVariableType() { assert(type(Graph(nodes: [Identifier(): .Return((0, .Unit))])), ==, 0) } func testGraphsWithOneParameterAndNoReturnsHaveFunctionTypeReturningUnit() { assert(type(Graph(nodes: [Identifier(): .Parameter((0, .Unit))])), ==, .function(0, .Unit)) } func testGraphsWithOneParameterAndOneReturnHaveFunctionTypeFromVariableToDifferentVariable() { assert(type(Graph(nodes: [Identifier(): .Parameter((0, .Unit)), Identifier(): .Return((0, .Unit))])), ==, .function(1, 0)) } } private func type(graph: Graph<Node>) -> Term { return simplify(constraints(graph).0) } private func simplify(type: Term) -> Term { return Substitution(lazy(enumerate(type.freeVariables |> (flip(sorted) <| { $0.value < $1.value }))).map { ($1, Term(integerLiteral: $0)) }).apply(type) } import Assertions import Manifold import Prelude import TesseractCore import XCTest
Revert "[Identity] Require non blur image even if we find a barcode"
// // DocumentScannerOutput.swift // StripeIdentity // // Created by Mel Ludowise on 3/1/22. // import Foundation @_spi(STP) import StripeCameraCore /** Consolidated output from all ML models / detectors that make up document scanning. The combination of this output will determine if the image captured is high enough quality to accept. */ struct DocumentScannerOutput: Equatable { let idDetectorOutput: IDDetectorOutput let barcode: BarcodeDetectorOutput? let motionBlur: MotionBlurDetector.Output let cameraProperties: CameraSession.DeviceProperties? /** Determines if the document is high quality and matches the desired document type and side. - Parameters: - type: Type of the desired document - side: Side of the desired document. */ func isHighQuality( matchingDocumentType type: DocumentType, side: DocumentSide ) -> Bool { // Even if barcode is clear enough to decode, still wait for a non blur image let hasNoBlur: Bool if let barcode = barcode { let hasGoodBarcode = barcode.hasBarcode && !barcode.isTimedOut hasNoBlur = !motionBlur.hasMotionBlur && hasGoodBarcode } else { hasNoBlur = !motionBlur.hasMotionBlur } return idDetectorOutput.classification.matchesDocument(type: type, side: side) && cameraProperties?.isAdjustingFocus != true && hasNoBlur } }
// // DocumentScannerOutput.swift // StripeIdentity // // Created by Mel Ludowise on 3/1/22. // import Foundation @_spi(STP) import StripeCameraCore /** Consolidated output from all ML models / detectors that make up document scanning. The combination of this output will determine if the image captured is high enough quality to accept. */ struct DocumentScannerOutput: Equatable { let idDetectorOutput: IDDetectorOutput let barcode: BarcodeDetectorOutput? let motionBlur: MotionBlurDetector.Output let cameraProperties: CameraSession.DeviceProperties? /** Determines if the document is high quality and matches the desired document type and side. - Parameters: - type: Type of the desired document - side: Side of the desired document. */ func isHighQuality( matchingDocumentType type: DocumentType, side: DocumentSide ) -> Bool { // If the barcode is clear enough to decode, then that's good enough and // it doesn't matter if the MotionBlurDetector believes there's motion blur let hasNoBlur = barcode?.hasBarcode == true || (!motionBlur.hasMotionBlur && barcode == nil || barcode?.isTimedOut == true) return idDetectorOutput.classification.matchesDocument(type: type, side: side) && cameraProperties?.isAdjustingFocus != true && hasNoBlur } }
Add additional Roostfile parsing test
import Speedy import Nimble class RoostfileSpec: Spec { var definition: String { get { return "\n".join([ "name: Test", "version: 0.1.2", "target_type: executable", ]) } } func spec() { describe("when parsing") { it("should parse basic properties") { let r = Roostfile() r.parseFromString(self.definition) expect(r.name).to(equal("Test")) expect(r.targetType).to(equal(TargetType.Executable)) } } } }
import Speedy import Nimble class RoostfileSpec: Spec { var definition: String { get { return "\n".join([ "name: Test", "version: 0.1.2", "target_type: executable", "sources:", " - TestFile.swift", " - TestDirectory/", ]) } } func spec() { describe("when parsing") { var r: Roostfile! beforeEach { r = Roostfile() r.parseFromString(self.definition) } it("should parse basic properties") { expect(r.name).to(equal("Test")) expect(r.targetType).to(equal(TargetType.Executable)) } it("should parse sources") { expect(r.sources.count).to(equal(2)) expect(r.sources[0]).to(equal("TestFile.swift")) expect(r.sources[1]).to(equal("TestDirectory/")) } } } }
Interpolate with a temporary variable.
// Copyright (c) 2015 Rob Rix. All rights reserved. public func export<T>(graph: Graph<T>) -> String { return "digraph tesseract {\n" + join("", lazy(graph.edges).map { "\t" + $0.source.identifier.description + " -> " + $0.destination.identifier.description + ";\n" }) + "}" } // MARK: - Imports import Prelude
// Copyright (c) 2015 Rob Rix. All rights reserved. public func export<T>(graph: Graph<T>) -> String { let edges = join("\n", lazy(graph.edges).map { "\t" + $0.source.identifier.description + " -> " + $0.destination.identifier.description + ";" }) return "digraph tesseract {\n\(edges)\n}" } // MARK: - Imports import Prelude
Switch to my own branch of Promise library fix a fix
// swift-tools-version:4.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "RequestBuilder", products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "RequestBuilder", targets: ["RequestBuilder"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. .package(url: "https://github.com/khanlou/Promise.git", .revision("2a4157075c390f447f412f52c8a18e298357d05f")), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "RequestBuilder", dependencies: ["Promise"]), .testTarget( name: "RequestBuilderTests", dependencies: ["RequestBuilder"]), ] )
// swift-tools-version:4.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "RequestBuilder", products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "RequestBuilder", targets: ["RequestBuilder"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. .package(url: "https://github.com/Soryu/Promise.git", .branch("master")), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "RequestBuilder", dependencies: ["Promise"]), .testTarget( name: "RequestBuilderTests", dependencies: ["RequestBuilder"]), ] )
Update 285 for combined engine/server
// Regression test for optimizations that might incorrectly execute function // on wrong process @dispatch=WORKER (int o) worker_task (int i) "turbine" "0.0.1" [ "set <<o>> <<i>>; if { $turbine::mode != \"WORKER\" } { error $turbine::mode }" ]; @dispatch=CONTROL (int o) control_task (int i) "turbine" "0.0.1" [ "set <<o>> <<i>>; if { $turbine::mode != \"ENGINE\" } { error $turbine::mode }" ]; import assert; main { // Check that optimizer doesn't pull up worker task into control context int x = worker_task(1); // Check that optimizer doesn't pull up control task into worker context int y = control_task(x); assertEqual(y, 1, "y in main"); // Check that same holds after inlining f(2); } f (int i) { int x = worker_task(i); int y = control_task(x); assertEqual(y, 2, "y in f"); }
// Regression test for optimizations that might incorrectly execute function // on wrong process. // This test updated for merged engine/server // Check that worker task doesn't run twice in same context @dispatch=WORKER (int o) worker_task (int i) "turbine" "0.0.1" [ "set <<o>> <<i>>; if { $turbine::mode != \"WORKER\" } { error $turbine::mode }; if [ info exists __ranhere ] { error \"Already ran here \" } ; set __ranhere 1" ]; @dispatch=CONTROL (int o) control_task (int i) "turbine" "0.0.1" [ "set <<o>> <<i>>; if { $turbine::mode != \"WORKER\" } { error $turbine::mode }" ]; import assert; main { // Check that optimizer doesn't pull up worker task into control context int x = worker_task(1); // Check that optimizer doesn't pull up control task into worker context int y = control_task(x); assertEqual(y, 1, "y in main"); // Check that same holds after inlining f(2); } f (int i) { int x = worker_task(i); int y = control_task(x); assertEqual(y, 2, "y in f"); }
Add moves(to:) method to Sequence
// // Sequence+Fischer.swift // Fischer // // Copyright 2016 Nikolai Vazquez // // 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. // #if swift(>=3) extension Sequence where Iterator.Element == Square { /// Returns moves from `square` to the squares in `self`. public func moves(from square: Square) -> [Move] { return self.map({ square >>> $0 }) } } #else extension SequenceType where Generator.Element == Square { /// Returns moves from `square` to the squares in `self`. @warn_unused_result public func moves(from square: Square) -> [Move] { return self.map({ square >>> $0 }) } } #endif
// // Sequence+Fischer.swift // Fischer // // Copyright 2016 Nikolai Vazquez // // 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. // #if swift(>=3) extension Sequence where Iterator.Element == Square { /// Returns moves from `square` to the squares in `self`. public func moves(from square: Square) -> [Move] { return self.map({ square >>> $0 }) } /// Returns moves from the squares in `self` to `square`. @warn_unused_result public func moves(to square: Square) -> [Move] { return self.map({ $0 >>> square }) } } #else extension SequenceType where Generator.Element == Square { /// Returns moves from `square` to the squares in `self`. @warn_unused_result public func moves(from square: Square) -> [Move] { return self.map({ square >>> $0 }) } /// Returns moves from the squares in `self` to `square`. @warn_unused_result public func moves(to square: Square) -> [Move] { return self.map({ $0 >>> square }) } } #endif
Split example tests in two tests: how to run a single or multiple native feature files.
// // ExampleNativeFeatureTest.swift // XCTest-Gherkin // // Created by Marcin Raburski on 30/06/2016. // Copyright © 2016 CocoaPods. All rights reserved. // import XCTest import XCTest_Gherkin class ExampleNativeFeatureTest: NativeTestCase { override func setUp() { super.setUp() let bundle = NSBundle(forClass: self.dynamicType) // In case you want to use only one feature file instead of the whole folder // Just provide the URL to the file self.path = bundle.resourceURL?.URLByAppendingPathComponent("NativeFeatures/native_example.feature") XCTAssertNotNil(self.path) } }
// // ExampleNativeFeatureTest.swift // XCTest-Gherkin // // Created by Marcin Raburski on 30/06/2016. // Copyright © 2016 CocoaPods. All rights reserved. // import XCTest import XCTest_Gherkin class RunSingleFeatureFileTest: NativeTestCase { override func setUp() { super.setUp() let bundle = NSBundle(forClass: self.dynamicType) // In case you want to use only one feature file instead of the whole folder // Just provide the URL to the file self.path = bundle.resourceURL?.URLByAppendingPathComponent("NativeFeatures/native_example.feature") } } class RunMultipleFeatureFilesTest: NativeTestCase { override func setUp() { super.setUp() let bundle = NSBundle(forClass: self.dynamicType) self.path = bundle.resourceURL?.URLByAppendingPathComponent("NativeFeatures/") } }
Use AnyObject instead of class in protocol requirements
// // SignalBroadcasting.swift // Beacon // // Created by Zhu Shengqi on 14/06/2017. // Copyright © 2017 zetasq. All rights reserved. // import Foundation public protocol BroadcastIdentifiable: RawRepresentable { var rawValue: String { get } } public protocol SignalBroadcasting: class { associatedtype BroadcastIdentifier: BroadcastIdentifiable associatedtype BroadcastPayload } extension SignalBroadcasting { public func broadcast(identifier: BroadcastIdentifier, payload: BroadcastPayload, within beacon: Beacon = .default) { beacon.enqueueBroadcastRequest(broadcaster: self, identifier: identifier, payload: payload) } public static func uniqueBroadcastID(for broadcastIdentifier: BroadcastIdentifier) -> String { let qualifiedName = String(reflecting: self) return "\(qualifiedName).\(broadcastIdentifier.rawValue)" } }
// // SignalBroadcasting.swift // Beacon // // Created by Zhu Shengqi on 14/06/2017. // Copyright © 2017 zetasq. All rights reserved. // import Foundation public protocol BroadcastIdentifiable: RawRepresentable { var rawValue: String { get } } public protocol SignalBroadcasting: AnyObject { associatedtype BroadcastIdentifier: BroadcastIdentifiable associatedtype BroadcastPayload } extension SignalBroadcasting { public func broadcast(identifier: BroadcastIdentifier, payload: BroadcastPayload, within beacon: Beacon = .default) { beacon.enqueueBroadcastRequest(broadcaster: self, identifier: identifier, payload: payload) } public static func uniqueBroadcastID(for broadcastIdentifier: BroadcastIdentifier) -> String { let qualifiedName = String(reflecting: self) return "\(qualifiedName).\(broadcastIdentifier.rawValue)" } }
Order defaults to method GET
import Quick import Nimble import Faro @testable import Faro_Example class OrderSpec: QuickSpec { override func spec() { describe("Order") { context("initialisation") { it("should have a path"){ let expected = "path" let order = Order(path: expected) expect(order.path).to(equal(expected)) } } } } }
import Quick import Nimble import Faro @testable import Faro_Example class OrderSpec: QuickSpec { override func spec() { describe("Order") { let expected = "path" let order = Order(path: expected) context("initialisation") { it("should have a path"){ expect(order.path).to(equal(expected)) } it("should default to .GET") { expect(order.method.rawValue).to(equal("GET")) } } } } }
Test the equivalence of Pair encodings.
// Copyright © 2015 Rob Rix. All rights reserved. final class PairTests: XCTestCase { func testModuleTypechecks() { module.typecheck().forEach { XCTFail($0) } } } private let module = Module<Term>.pair import Manifold import XCTest
// Copyright © 2015 Rob Rix. All rights reserved. final class PairTests: XCTestCase { func testModuleTypechecks() { module.typecheck().forEach { XCTFail($0) } } func testAutomaticallyEncodedDefinitionsAreEquivalentToHandEncodedDefinitions() { expected.definitions.forEach { symbol, type, value in assert(module.context[symbol], ==, type, message: "\(symbol)") assert(module.environment[symbol], ==, value, message: "\(symbol)") } } } private let module = Module<Term>.pair private let expected: Module<Term> = { let Pair = Declaration("Pair", type: Term.FunctionType(.Type, .Type, .Type), value: Term.lambda(.Type, .Type, .Type) { A, B, Result in .lambda(.FunctionType(A, B, Result), const(Result)) }) let pair = Declaration("pair", type: Term.lambda(.Type, .Type) { A, B in .FunctionType(A, B, Pair.ref[A, B]) }, value: Term.lambda(.Type, .Type) { A, B in Term.lambda(A, B, .Type) { a, b, Result in Term.lambda(.FunctionType(A, B, Result)) { f in f[a, b] } } }) return Module("ChurchPair", [ Pair, pair, ]) }() import Assertions import Manifold import Prelude import XCTest
Add convenience funcs for activating constraints
// Copyright (c) 2015 Steve Brambilla. All rights reserved. import UIKit /// Evaluates a distinct layout expression into a single constraint. /// /// Returns an evaluated NSLayoutConstraint public func evaluateLayoutExpression(_ expression: DistinctExpressionType) -> NSLayoutConstraint { return expression.evaluateDistinct() } /// Evaluates a layout expression into constraints. /// /// Returns an array of layout constraints. public func evaluateLayoutExpression(_ expression: ExpressionProtocol) -> [NSLayoutConstraint] { return expression.evaluateAll() } /// Evaluates multiple layout expressions into constraints. /// /// Returns an array of layout constraints. public func evaluateLayoutExpressions(_ expressions: [ExpressionProtocol]) -> [NSLayoutConstraint] { return expressions.reduce([]) { acc, expression in return acc + expression.evaluateAll() } }
// Copyright (c) 2015 Steve Brambilla. All rights reserved. import UIKit /// Evaluates a distinct layout expression into a single constraint. /// /// Returns an evaluated NSLayoutConstraint public func evaluateLayoutExpression(_ expression: DistinctExpressionType) -> NSLayoutConstraint { return expression.evaluateDistinct() } /// Evaluates a layout expression into constraints. /// /// Returns an array of layout constraints. public func evaluateLayoutExpression(_ expression: ExpressionProtocol) -> [NSLayoutConstraint] { return expression.evaluateAll() } /// Evaluates multiple layout expressions into constraints. /// /// Returns an array of layout constraints. public func evaluateLayoutExpressions(_ expressions: [ExpressionProtocol]) -> [NSLayoutConstraint] { return expressions.reduce([]) { acc, expression in return acc + expression.evaluateAll() } } /// Evaluates a distinct layout expression and activates the constraint. /// /// The effect of this function is the same as setting the `isActive` property of the constraint to /// `true`. public func activateLayoutExpression(_ expression: DistinctExpressionType) { evaluateLayoutExpression(expression).isActive = true } /// Evaluates a layout expression and activates its constraints. /// /// The effect of this function is the same as setting the `isActive` property of the constraints to /// `true`. public func activateLayoutExpression(_ expression: ExpressionProtocol) { evaluateLayoutExpression(expression).activateConstraints() } /// Evaluates multiple layout expressions and activates their constraints. /// /// The effect of this function is the same as setting the `isActive` property of each constraint /// to `true`. public func activateLayoutExpressions(_ expressions: [ExpressionProtocol]) { evaluateLayoutExpressions(expressions).activateConstraints() }
Add present initial view controller method on app coordinators
// // AppCoordinator // Cruciverber // // Created by Cihat Gündüz on 12.03.16. // Copyright © 2016 Flinesoft. All rights reserved. // import UIKit /// This class is a coordinator for screen flows starting on app start / using windows. open class AppCoordinator: Coordinator { // MARK: - Stored Instance Properties public let window = UIWindow(frame: UIScreen.main.bounds) // MARK: - Initializers /// Initializes a new AppCoordinator object and creates a window. public init() { let pseudoViewController = UIViewController() super.init(presentingViewController: pseudoViewController) } override init(presentingViewController: UIViewController) { preconditionFailure("illegal init call – use init() instead") } }
// // AppCoordinator // Cruciverber // // Created by Cihat Gündüz on 12.03.16. // Copyright © 2016 Flinesoft. All rights reserved. // import UIKit /// This class is a coordinator for screen flows starting on app start / using windows. open class AppCoordinator: Coordinator { // MARK: - Stored Instance Properties public let window = UIWindow(frame: UIScreen.main.bounds) // MARK: - Initializers /// Initializes a new AppCoordinator object and creates a window. public init() { let pseudoViewController = UIViewController() super.init(presentingViewController: pseudoViewController) } override init(presentingViewController: UIViewController) { preconditionFailure("illegal init call – use init() instead") } // MARK: - Instance Methods /// Presents the initial view controllers as the windows root view. /// /// - Parameters: /// - viewController: The view controller to be presented. public func presentInitialViewController(_ viewController: UIViewController) { window.rootViewController = viewController window.makeKeyAndVisible() } }
Add date parameter to trace
// // NSObject.swift // DarkSwift // // Created by Dark Dong on 2017/5/26. // Copyright © 2017年 Dark Dong. All rights reserved. // import Foundation private var associatedObjectKey = 0 public extension NSObject { func trace(funcname: String = #function, _ items: Any...) { print(type(of: self), funcname, items) } func clone() -> AnyObject { return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as AnyObject } var associatedObject: Any? { get { return objc_getAssociatedObject(self, &associatedObjectKey) } set { objc_setAssociatedObject(self, &associatedObjectKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } }
// // NSObject.swift // DarkSwift // // Created by Dark Dong on 2017/5/26. // Copyright © 2017年 Dark Dong. All rights reserved. // import Foundation private var associatedObjectKey = 0 public extension NSObject { func trace(timestamp: Bool = false, funcname: String = #function, _ items: Any...) { if timestamp { print(Date(), type(of: self), funcname, items) } else { print(type(of: self), funcname, items) } } func clone() -> AnyObject { return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as AnyObject } var associatedObject: Any? { get { return objc_getAssociatedObject(self, &associatedObjectKey) } set { objc_setAssociatedObject(self, &associatedObjectKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } }
Work around for the date formatter issue where being within an hour of a component transition will display more components than desired.
// // NSDateComponentsFormatter+Postfix.swift // PartyUP // // Created by Fritz Vander Heide on 2016-03-25. // Copyright © 2016 Sandcastle Application Development. All rights reserved. // import Foundation extension NSDateComponentsFormatter { func stringFromDate(startDate: NSDate, toDate endDate: NSDate, classicThreshold classic: NSTimeInterval?, postfix: Bool = false, substituteZero zero: String? = nil) -> String? { var capped = false var interval = endDate.timeIntervalSinceDate(startDate) if let classic = classic where interval > classic { interval = classic capped = true if unitsStyle != .Abbreviated { return NSLocalizedString("Classic", comment: "Stale time display") } } var formatted = stringFromTimeInterval(interval) ?? "?" if capped { formatted += "+" } if let zero = zero where formatted.hasPrefix("0") { formatted = zero } else if postfix { formatted += NSLocalizedString(" ago", comment:"Samples more than a minute old") } return formatted } }
// // NSDateComponentsFormatter+Postfix.swift // PartyUP // // Created by Fritz Vander Heide on 2016-03-25. // Copyright © 2016 Sandcastle Application Development. All rights reserved. // import Foundation extension NSDateComponentsFormatter { func stringFromDate(startDate: NSDate, toDate endDate: NSDate, classicThreshold classic: NSTimeInterval?, postfix: Bool = false, substituteZero zero: String? = nil) -> String? { var capped = false var interval = endDate.timeIntervalSinceDate(startDate) if let classic = classic where interval > classic { interval = classic capped = true if unitsStyle != .Abbreviated { return NSLocalizedString("Classic", comment: "Stale time display") } } var formatted = stringFromTimeInterval(interval) ?? "?" formatted = formatted.characters.split(",").prefixUpTo(self.maximumUnitCount).map { String($0) }.joinWithSeparator(",") if capped { formatted += "+" } if let zero = zero where formatted.hasPrefix("0") { formatted = zero } else if postfix { formatted += NSLocalizedString(" ago", comment:"Samples more than a minute old") } return formatted } }
Move Dropbox key appo separate variable and add warning for missing value
// // AppDelegate.swift // Vandelay // // Created by Daniel Saidi on 06/07/2016. // Copyright © 2016 Daniel Saidi. All rights reserved. // import UIKit import SwiftyDropbox @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { DropboxClientsManager.setupWithAppKey("4j6q36uumkro49k") return true } func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { if let authResult = DropboxClientsManager.handleRedirectURL(url) { switch authResult { case .success: print("Success! User is logged into Dropbox.") case .cancel: print("Authorization flow was manually canceled by user!") case .error(_, let description): print("Error: \(description)") } } return true } }
// // AppDelegate.swift // Vandelay // // Created by Daniel Saidi on 06/07/2016. // Copyright © 2016 Daniel Saidi. All rights reserved. // import UIKit import SwiftyDropbox @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var dropboxAppKey = "" func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { if (dropboxAppKey.isEmpty) { print("*** IMPORTANT ***") print("In order to try Dropbox import/export, you must set the dropboxAppKey value in AppDelegate\n") } DropboxClientsManager.setupWithAppKey(dropboxAppKey) return true } func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { if let authResult = DropboxClientsManager.handleRedirectURL(url) { switch authResult { case .success: print("Success! User is logged into Dropbox.") case .cancel: print("Authorization flow was manually canceled by user!") case .error(_, let description): print("Error: \(description)") } } return true } }
Update Swift tools version to Swift 5.2
// swift-tools-version:5.1 import PackageDescription let package = Package( name: "Differ", products: [ .library(name: "Differ", targets: ["Differ"]), ], targets: [ .target(name: "Differ"), .testTarget(name: "DifferTests", dependencies: ["Differ"]), ] )
// swift-tools-version:5.2 import PackageDescription let package = Package( name: "Differ", products: [ .library(name: "Differ", targets: ["Differ"]), ], targets: [ .target(name: "Differ"), .testTarget(name: "DifferTests", dependencies: [ .target(name: "Differ") ]), ] )
Add Task and UserDefaults to Service Provider
// // ServiceProvider.swift // Zero // // Created by Jairo Eli de Leon on 5/8/17. // Copyright © 2017 Jairo Eli de León. All rights reserved. // protocol ServiceProviderType: class {} final class ServiceProvider: ServiceProviderType {}
// // ServiceProvider.swift // Zero // // Created by Jairo Eli de Leon on 5/8/17. // Copyright © 2017 Jairo Eli de León. All rights reserved. // protocol ServiceProviderType: class { var userDefaultsService: UserDefaultsServiceType { get } var taskService: TaskServiceType { get } } final class ServiceProvider: ServiceProviderType { lazy var userDefaultsService: UserDefaultsServiceType = UserDefaultsService(provider: self) lazy var taskService: TaskServiceType = TaskService(provider: self) }
Make the DispatchQoS extension internal when building from Xcode
// // dispatchqos.swift // deferred // // Created by Guillaume Lessard on 31/08/2016. // Copyright © 2016 Guillaume Lessard. All rights reserved. // import Dispatch extension DispatchQoS { public static func current(fallback: DispatchQoS.QoSClass = .utility) -> DispatchQoS { let qos = DispatchQoS.QoSClass(rawValue: qos_class_self()) ?? fallback return DispatchQoS(qosClass: qos, relativePriority: 0) } }
// // dispatchqos.swift // deferred // // Created by Guillaume Lessard on 31/08/2016. // Copyright © 2016 Guillaume Lessard. All rights reserved. // import Dispatch extension DispatchQoS { #if SWIFT_PACKAGE public static func current(fallback: DispatchQoS.QoSClass = .utility) -> DispatchQoS { let qos = DispatchQoS.QoSClass(rawValue: qos_class_self()) ?? fallback return DispatchQoS(qosClass: qos, relativePriority: 0) } #else static func current(fallback: DispatchQoS.QoSClass = .utility) -> DispatchQoS { let qos = DispatchQoS.QoSClass(rawValue: qos_class_self()) ?? fallback return DispatchQoS(qosClass: qos, relativePriority: 0) } #endif }
Add example code for selected demo.
// // ViewController.swift // CHCarouselView // // Created by Calvin on 8/5/16. // Copyright © 2016 CapsLock. All rights reserved. // import UIKit import Kingfisher class ViewController: UIViewController { @IBOutlet weak var carouselView: CarouselView! override func viewDidLoad() { super.viewDidLoad() let imageUrls = [ "https://dl.dropboxusercontent.com/u/108987767/Meme/01_Cupido.jpg", "https://dl.dropboxusercontent.com/u/108987767/Meme/bugs_everywhere.png", "https://dl.dropboxusercontent.com/u/108987767/Meme/p56an6SZj5_d.gif", "https://dl.dropboxusercontent.com/u/108987767/Meme/1557643_489616404482423_780202608_n.jpg", ] carouselView.views = imageUrls .map { url -> UIImageView in let imageView = UIImageView() imageView.kf_setImageWithURL(NSURL(string: url)!) imageView.contentMode = .ScaleAspectFill imageView.clipsToBounds = true return imageView } } }
// // ViewController.swift // CHCarouselView // // Created by Calvin on 8/5/16. // Copyright © 2016 CapsLock. All rights reserved. // import UIKit import Kingfisher class ViewController: UIViewController { @IBOutlet weak var carouselView: CarouselView! override func viewDidLoad() { super.viewDidLoad() let imageUrls = [ "https://dl.dropboxusercontent.com/u/108987767/Meme/01_Cupido.jpg", "https://dl.dropboxusercontent.com/u/108987767/Meme/bugs_everywhere.png", "https://dl.dropboxusercontent.com/u/108987767/Meme/p56an6SZj5_d.gif", "https://dl.dropboxusercontent.com/u/108987767/Meme/1557643_489616404482423_780202608_n.jpg", ] carouselView.selectedCallback = { [unowned self] (currentPage: Int) in let alertController = UIAlertController(title: nil, message: "You selected page: \(currentPage) in carousel.", preferredStyle: .Alert) self.presentViewController(alertController, animated: true, completion: nil) } carouselView.views = imageUrls .map { url -> UIImageView in let imageView = UIImageView() imageView.kf_setImageWithURL(NSURL(string: url)!) imageView.contentMode = .ScaleAspectFill imageView.clipsToBounds = true return imageView } } }
Add injection for Xcode snippet
// // AppDelegate.swift // React // // Created by Sacha Durand Saint Omer on 29/03/2017. // Copyright © 2017 Freshos. All rights reserved. // import UIKit import Komponents @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) let navVC = UINavigationController(rootViewController: NavigationVC()) navVC.navigationBar.isTranslucent = false window?.rootViewController = navVC window?.makeKeyAndVisible() Komponents.logsEnabled = true return true } }
// // AppDelegate.swift // React // // Created by Sacha Durand Saint Omer on 29/03/2017. // Copyright © 2017 Freshos. All rights reserved. // import UIKit import Komponents @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { Bundle(path: "/Applications/InjectionIII.app/Contents/Resources/iOSInjection10.bundle")?.load() window = UIWindow(frame: UIScreen.main.bounds) let navVC = UINavigationController(rootViewController: NavigationVC()) navVC.navigationBar.isTranslucent = false window?.rootViewController = navVC window?.makeKeyAndVisible() Komponents.logsEnabled = true return true } }
Clean up, make S a variable
/* RECUR 1 SWIFT Simply run with: 'swift-t recur-1.swift | nl' */ app (void v) dummy(string parent, int stage, int id, void block) { "echo" ("parent='%3s'"%parent) ("stage="+stage) ("id="+id) ; } N = 4; void A[string]; (void v) runstage(int N, string parent, int stage, int id, void block) { string this = parent+int2string(id); v = dummy(parent, stage, id, block); if (stage < 3) { foreach id_child in [0:N-1] { runstage(N, this, stage+1, id_child, v); } } } int stage = 1; foreach id in [0:N-1] { runstage(N, "", stage, id, propagate()); }
/* RECUR 1 SWIFT Simply run with: 'swift-t recur-1.swift | nl' */ app (void v) dummy(string parent, int stage, int id, void block) { "echo" ("parent='%3s'"%parent) ("stage="+stage) ("id="+id) ; } N = 4; // Data split factor S = 3; // Maximum stage number (tested up to S=7, 21,844 dummy tasks) (void v) runstage(int N, int S, string parent, int stage, int id, void block) { string this = parent+int2string(id); v = dummy(parent, stage, id, block); if (stage < S) { foreach id_child in [0:N-1] { runstage(N, S, this, stage+1, id_child, v); } } } int stage = 1; foreach id in [0:N-1] { runstage(N, S, "", stage, id, propagate()); }
Fix compatible iOS / OSX
// // OAuthSwiftURLHandlerType.swift // OAuthSwift // // Created by phimage on 11/05/15. // Copyright (c) 2015 Dongri Jin. All rights reserved. // import AppKit @objc public protocol OAuthSwiftURLHandlerType { func handle(url: NSURL) } public class OAuthSwiftOpenURLExternally: OAuthSwiftURLHandlerType { class var sharedInstance : OAuthSwiftOpenURLExternally { struct Static { static var onceToken : dispatch_once_t = 0 static var instance : OAuthSwiftOpenURLExternally? = nil } dispatch_once(&Static.onceToken) { Static.instance = OAuthSwiftOpenURLExternally() } return Static.instance! } @objc public func handle(url: NSURL) { #if os(iOS) UIApplication.sharedApplication().openURL(url) #elseif os(OSX) NSWorkspace.sharedWorkspace().openURL(url) #endif } }
// // OAuthSwiftURLHandlerType.swift // OAuthSwift // // Created by phimage on 11/05/15. // Copyright (c) 2015 Dongri Jin. All rights reserved. // import Foundation #if os(iOS) import UIKit #elseif os(OSX) import AppKit #endif @objc public protocol OAuthSwiftURLHandlerType { func handle(url: NSURL) } public class OAuthSwiftOpenURLExternally: OAuthSwiftURLHandlerType { class var sharedInstance : OAuthSwiftOpenURLExternally { struct Static { static var onceToken : dispatch_once_t = 0 static var instance : OAuthSwiftOpenURLExternally? = nil } dispatch_once(&Static.onceToken) { Static.instance = OAuthSwiftOpenURLExternally() } return Static.instance! } @objc public func handle(url: NSURL) { #if os(iOS) UIApplication.sharedApplication().openURL(url) #elseif os(OSX) NSWorkspace.sharedWorkspace().openURL(url) #endif } }
Write the string plist for the article.
// // ArticlePasteboardWriter.swift // Evergreen // // Created by Brent Simmons on 11/6/17. // Copyright © 2017 Ranchero Software. All rights reserved. // import Cocoa import Data @objc final class ArticlePasteboardWriter: NSObject, NSPasteboardWriting { private let article: Article init(article: Article) { self.article = article } // MARK: - NSPasteboardWriting func writableTypes(for pasteboard: NSPasteboard) -> [NSPasteboard.PasteboardType] { return [NSPasteboard.PasteboardType]() // TODO: add types } func pasteboardPropertyList(forType type: NSPasteboard.PasteboardType) -> Any? { return nil // TODO: write data } }
// // ArticlePasteboardWriter.swift // Evergreen // // Created by Brent Simmons on 11/6/17. // Copyright © 2017 Ranchero Software. All rights reserved. // import Cocoa import Data @objc final class ArticlePasteboardWriter: NSObject, NSPasteboardWriting { private let article: Article init(article: Article) { self.article = article } // MARK: - NSPasteboardWriting func writableTypes(for pasteboard: NSPasteboard) -> [NSPasteboard.PasteboardType] { // TODO: add more types var types = [NSPasteboard.PasteboardType]() if let _ = article.title { types += [.string] } return types // TODO: add types } func pasteboardPropertyList(forType type: NSPasteboard.PasteboardType) -> Any? { // TODO: write data for all types declared in writableTypes. let plist: Any? switch type { case .string: plist = article.title ?? "" default: plist = nil } return plist } }
Update Notifications Center collection view layout.
import UIKit final class NotificationsCenterView: SetupView { // MARK: - Properties lazy var collectionView: UICollectionView = { return UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) }() // MARK: - Setup override func setup() { backgroundColor = .white wmf_addSubviewWithConstraintsToEdges(collectionView) } } extension NotificationsCenterView: Themeable { func apply(theme: Theme) { backgroundColor = theme.colors.paperBackground collectionView.backgroundColor = theme.colors.paperBackground } }
import UIKit final class NotificationsCenterView: SetupView { // MARK: - Properties lazy var collectionView: UICollectionView = { let collectionView = UICollectionView(frame: .zero, collectionViewLayout: tableStyleLayout) collectionView.register(NotificationsCenterCell.self, forCellWithReuseIdentifier: NotificationsCenterCell.reuseIdentifier) collectionView.alwaysBounceVertical = true collectionView.translatesAutoresizingMaskIntoConstraints = false // collectionView.allowsMultipleSelection = true return collectionView }() private lazy var tableStyleLayout: UICollectionViewLayout = { if #available(iOS 13.0, *) { let estimatedHeightDimension = NSCollectionLayoutDimension.estimated(130) let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),heightDimension: estimatedHeightDimension) let item = NSCollectionLayoutItem(layoutSize: itemSize) let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),heightDimension: estimatedHeightDimension) let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize,subitems: [item]) let section = NSCollectionLayoutSection(group: group) let layout = UICollectionViewCompositionalLayout(section: section) return layout } else { fatalError() } }() // MARK: - Setup override func setup() { backgroundColor = .white wmf_addSubviewWithConstraintsToEdges(collectionView) } } extension NotificationsCenterView: Themeable { func apply(theme: Theme) { backgroundColor = theme.colors.paperBackground collectionView.backgroundColor = theme.colors.paperBackground } }
Update response mapping for transit
// // TransitRoutes.swift // Pods // // Created by John Neyer on 8/24/17. // // import Foundation import ObjectMapper public class TransitRoutes : RestResponse { var results: Int? var route: Int? var buses: [TransitRoute]? public override func mapping(map: Map) { super.mapping(map: map) if (map["buses"].isKeyPresent) { success = true; } results <- map["results"] route <- map["route"] buses <- map["buses"] } }
// // TransitRoutes.swift // Pods // // Created by John Neyer on 8/24/17. // // import Foundation import ObjectMapper public class TransitRoutes : RestResponse { var results: Int? var route: Int? var transit: [TransitRoute]? public override func mapping(map: Map) { super.mapping(map: map) if (map["buses"].isKeyPresent) { success = true; } results <- map["results"] route <- map["route"] transit <- map["transit"] } }
Correct Min MacOS version for CoreBluetooth Framework
// swift-tools-version:5.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "RxBluetoothKit", platforms: [ .macOS(.v10_10), .iOS(.v8), .tvOS(.v11), .watchOS(.v4) ], products: [ .library(name: "RxBluetoothKit", targets: ["RxBluetoothKit"]) ], dependencies: [ .package(url: "https://github.com/ReactiveX/RxSwift.git", .upToNextMajor(from: "5.1.1")) ], targets: [ .target( name: "RxBluetoothKit", dependencies: [ "RxSwift" ], path: ".", exclude: [ "Example", "Tests", "Source/Info.plist", "Source/RxBluetoothKit.h" ], sources: [ "Source" ] ) ] )
// swift-tools-version:5.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "RxBluetoothKit", platforms: [ .macOS(.v10_13), .iOS(.v8), .tvOS(.v11), .watchOS(.v4) ], products: [ .library(name: "RxBluetoothKit", targets: ["RxBluetoothKit"]) ], dependencies: [ .package(url: "https://github.com/ReactiveX/RxSwift.git", .upToNextMajor(from: "5.1.1")) ], targets: [ .target( name: "RxBluetoothKit", dependencies: [ "RxSwift" ], path: ".", exclude: [ "Example", "Tests", "Source/Info.plist", "Source/RxBluetoothKit.h" ], sources: [ "Source" ] ) ] )
Add Swift version to conditions
// // shim.swift // Yams // // Created by Norio Nomura 1/27/18. // Copyright (c) 2018 Yams. All rights reserved. // #if !swift(>=4.1) extension Sequence { func compactMap<ElementOfResult>( _ transform: (Self.Element ) throws -> ElementOfResult?) rethrows -> [ElementOfResult] { return try flatMap(transform) } } #endif #if os(Linux) extension Substring { func hasPrefix(_ prefix: String) -> Bool { return String(self).hasPrefix(prefix) } } #endif
// // shim.swift // Yams // // Created by Norio Nomura 1/27/18. // Copyright (c) 2018 Yams. All rights reserved. // #if !swift(>=4.1) extension Sequence { func compactMap<ElementOfResult>( _ transform: (Self.Element ) throws -> ElementOfResult?) rethrows -> [ElementOfResult] { return try flatMap(transform) } } #endif #if os(Linux) && !swift(>=4.2) extension Substring { func hasPrefix(_ prefix: String) -> Bool { return String(self).hasPrefix(prefix) } } #endif
Remove completion block from update operation
// // UpdateDataOperation.swift // CriticalMaps // // Created by Илья Глущук on 13/10/2019. // Copyright © 2019 Pokus Labs. All rights reserved. // import Foundation final class UpdateDataOperation: AsyncOperation { private struct SendLocationPostBody: Encodable { let device: String let location: Location } private let locationProvider: LocationProvider private let idProvider: IDProvider private let networkLayer: NetworkLayer var onCompletion: ((Result<ApiResponse, NetworkError>) -> Void)? init(locationProvider: LocationProvider, idProvider: IDProvider, networkLayer: NetworkLayer) { self.locationProvider = locationProvider self.idProvider = idProvider self.networkLayer = networkLayer super.init() } override func main() { guard let currentLocation = locationProvider.currentLocation else { let request = GetLocationsAndChatMessagesRequest() networkLayer.get(request: request) { [weak self] result in guard let self = self else { return } self.onCompletion?(result) self.completeOperation() } return } let body = SendLocationPostBody(device: idProvider.id, location: currentLocation) guard let bodyData = try? body.encoded() else { completeOperation() return } let request = PostLocationRequest() networkLayer.post(request: request, bodyData: bodyData) { [weak self] result in guard let self = self else { return } self.onCompletion?(result) self.completeOperation() } } }
// // UpdateDataOperation.swift // CriticalMaps // // Created by Илья Глущук on 13/10/2019. // Copyright © 2019 Pokus Labs. All rights reserved. // import Foundation final class UpdateDataOperation: AsyncOperation { private struct SendLocationPostBody: Encodable { let device: String let location: Location } private let locationProvider: LocationProvider private let idProvider: IDProvider private let networkLayer: NetworkLayer var result: (Result<ApiResponse, NetworkError>)? init(locationProvider: LocationProvider, idProvider: IDProvider, networkLayer: NetworkLayer) { self.locationProvider = locationProvider self.idProvider = idProvider self.networkLayer = networkLayer super.init() } override func main() { guard let currentLocation = locationProvider.currentLocation else { let request = GetLocationsAndChatMessagesRequest() networkLayer.get(request: request) { [weak self] result in guard let self = self else { return } self.result = result self.completeOperation() } return } let body = SendLocationPostBody(device: idProvider.id, location: currentLocation) guard let bodyData = try? body.encoded() else { completeOperation() return } let request = PostLocationRequest() networkLayer.post(request: request, bodyData: bodyData) { [weak self] result in guard let self = self else { return } self.result = result self.completeOperation() } } }
Fix users detail title presentation at navigation bar
// // UserDetailPresenter.swift // RandomUser // // Created by Toni on 02/07/2017. // Copyright © 2017 Random User Inc. All rights reserved. // import Foundation import BothamUI class UserDetailPresenter: BothamPresenter { fileprivate let username: String fileprivate let getUserDetail: GetUserDetail fileprivate weak var ui: UserUI? init(username: String, ui: UserUI, getUserDetail: GetUserDetail) { self.username = username self.ui = ui self.getUserDetail = getUserDetail } func viewDidLoad() { ui?.showLoader() getUserDetail.execute(username: username) { (result) in DispatchQueue.main.async { self.ui?.hideLoader() if let error = result.error { self.ui?.showError(error.errorDescription) return } guard let user = result.value else { return } self.ui?.title = user.username self.ui?.show(user: user) } } } }
// // UserDetailPresenter.swift // RandomUser // // Created by Toni on 02/07/2017. // Copyright © 2017 Random User Inc. All rights reserved. // import Foundation import BothamUI class UserDetailPresenter: BothamPresenter { fileprivate let username: String fileprivate let getUserDetail: GetUserDetail fileprivate weak var ui: UserUI? init(username: String, ui: UserUI, getUserDetail: GetUserDetail) { self.username = username self.ui = ui self.getUserDetail = getUserDetail } func viewDidLoad() { ui?.title = username ui?.showLoader() getUserDetail.execute(username: username) { (result) in DispatchQueue.main.async { self.ui?.hideLoader() if let error = result.error { self.ui?.showError(error.errorDescription) return } guard let user = result.value else { return } self.ui?.show(user: user) } } } }
Add a method to be able to transform BothamError into Todo api client errors
// // TODOAPIClientError.swift // KataTODOAPIClient // // Created by Pedro Vicente Gomez on 12/02/16. // Copyright © 2016 Karumi. All rights reserved. // import Foundation public enum TODOAPIClientError: ErrorType { case NetworkError case ItemNotFound case UnknownError }
// // TODOAPIClientError.swift // KataTODOAPIClient // // Created by Pedro Vicente Gomez on 12/02/16. // Copyright © 2016 Karumi. All rights reserved. // import Foundation import Result import BothamNetworking public enum TODOAPIClientError: ErrorType { case NetworkError case ItemNotFound case UnknownError(code: Int) } extension ResultType where Error == BothamAPIClientError { func mapErrorToTODOAPIClientError() -> Result<Value, TODOAPIClientError> { return mapError { error in switch error { case BothamAPIClientError.HTTPResponseError(404, _): return TODOAPIClientError.ItemNotFound case BothamAPIClientError.HTTPResponseError(let statusCode, _): return TODOAPIClientError.UnknownError(code: statusCode) default: return TODOAPIClientError.NetworkError } } } }
Update test expectations. Not sure why this number changed from a few minutes ago.
// // FileUtilsTests.swift // WebKittyTests // // Created by Steve Baker on 3/19/15. // Copyright (c) 2015 Beepscore LLC. All rights reserved. // import XCTest class FileUtilsTests: XCTestCase { var fileUtils: FileUtils? override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. fileUtils = FileUtils() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testFileNamesAtBundleResourcePath() { let expected = 107 let webViewResourcesSubdirectory = "webViewResources" XCTAssertEqual(expected, fileUtils!.fileNamesAtBundleResourcePath().count) } func testFileNamesAtURL() { let expected = 107 let webViewResourcesSubdirectory = "webViewResources" XCTAssertEqual(expected, fileUtils!.fileNamesAtBundleResourcePath().count) } func testFileNamesWithExtensionHtml() { let expected = ["index.html"] let webViewResourcesSubdirectory = "webViewResources" XCTAssertEqual(expected, fileUtils!.fileNamesWithExtensionHtml()) } }
// // FileUtilsTests.swift // WebKittyTests // // Created by Steve Baker on 3/19/15. // Copyright (c) 2015 Beepscore LLC. All rights reserved. // import XCTest class FileUtilsTests: XCTestCase { var fileUtils: FileUtils? override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. fileUtils = FileUtils() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testFileNamesAtBundleResourcePath() { let expected = 110 let webViewResourcesSubdirectory = "webViewResources" XCTAssertEqual(expected, fileUtils!.fileNamesAtBundleResourcePath().count) } func testFileNamesAtURL() { let expected = 110 let webViewResourcesSubdirectory = "webViewResources" XCTAssertEqual(expected, fileUtils!.fileNamesAtBundleResourcePath().count) } func testFileNamesWithExtensionHtml() { let expected = ["index.html"] let webViewResourcesSubdirectory = "webViewResources" XCTAssertEqual(expected, fileUtils!.fileNamesWithExtensionHtml()) } }
Improve 'announce' logic when VoiceOver is not active.
// // AccessibilityInstructions.swift // Access // // Created by David Sweetman on 11/29/15. // Copyright © 2016. All rights reserved. // import UIKit public class VO { private init() {} public enum AccessibilityEventType { case Layout case ScreenChange func value() -> UIAccessibilityNotifications { switch (self) { case .Layout: return UIAccessibilityLayoutChangedNotification case .ScreenChange: return UIAccessibilityScreenChangedNotification } } } static public func announce(message: String, delay: UInt64 = 0, completion: ListenerCompletion? = nil) { guard UIAccessibilityIsVoiceOverRunning() else { dispatch_async(dispatch_get_main_queue()) { completion?(success: true) } return } dispatch_after(delay, dispatch_get_main_queue()) { UIAccessibilityPostNotification( UIAccessibilityAnnouncementNotification, message ); if let c = completion { AnnouncementListener.listenForFinishWithCompletion(message, completion: c) } } } static public func focusElement(element: UIView, event: AccessibilityEventType = .Layout, delay: UInt64 = 0) { dispatch_after(delay, dispatch_get_main_queue()) { UIAccessibilityPostNotification(event.value(), element) } } }
// // AccessibilityInstructions.swift // Access // // Created by David Sweetman on 11/29/15. // Copyright © 2016. All rights reserved. // import UIKit public class VO { private init() {} public enum AccessibilityEventType { case Layout case ScreenChange func value() -> UIAccessibilityNotifications { switch (self) { case .Layout: return UIAccessibilityLayoutChangedNotification case .ScreenChange: return UIAccessibilityScreenChangedNotification } } } static func handleVoiceoverDisabled(completion: ListenerCompletion?) { guard let completion = completion else { return } dispatch_async(dispatch_get_main_queue()) { completion(success: true) } } static public func announce(message: String, delay: UInt64 = 0, completion: ListenerCompletion? = nil) { guard UIAccessibilityIsVoiceOverRunning() else { handleVoiceoverDisabled(completion) return } dispatch_after(delay, dispatch_get_main_queue()) { UIAccessibilityPostNotification( UIAccessibilityAnnouncementNotification, message ); if let c = completion { AnnouncementListener.listenForFinishWithCompletion(message, completion: c) } } } static public func focusElement(element: UIView, event: AccessibilityEventType = .Layout, delay: UInt64 = 0) { dispatch_after(delay, dispatch_get_main_queue()) { UIAccessibilityPostNotification(event.value(), element) } } }
Change return value type UIResponder to Event.Responder
// // Stimulator.swift // Pods // // Created by Yuki Takahashi on 2015/07/29. // // import Foundation public protocol Event { typealias Responder func stimulate(responder: Responder) } public extension UIResponder { public func stimulate<E: Event>(event: E) -> UIResponder? { var responder : UIResponder? = self while (responder != nil) { if let r = responder as? E.Responder { event.stimulate(r) return responder } responder = responder?.nextResponder() } return nil } }
// // Stimulator.swift // Pods // // Created by Yuki Takahashi on 2015/07/29. // // import Foundation public protocol Event { typealias Responder func stimulate(responder: Responder) } public extension UIResponder { public func stimulate<E: Event>(event: E) -> E.Responder? { var responder : UIResponder? = self while (responder != nil) { if let responder = responder as? E.Responder { event.stimulate(responder) return responder } responder = responder?.nextResponder() } return nil } }
Mark removed method as unavailable for easier migration
// Copyright © 2020 Flinesoft. All rights reserved. /// Simple protocol to make modifying objects with multiple properties more pleasant (functional, chainable, point-free). public protocol Withable { /* no requirements */ } extension Withable { /// Create a copy (if a struct) or use same object (if class), improving chainability e.g. after init method. @inlinable public func with(_ config: (inout Self) -> Void) -> Self { var copy = self config(&copy) return copy } }
// Copyright © 2020 Flinesoft. All rights reserved. /// Simple protocol to make modifying objects with multiple properties more pleasant (functional, chainable, point-free). public protocol Withable { /* no requirements */ } extension Withable { @available(*, unavailable, message: "Add `().with` after the type name, e.g. `Foo().with { $0.bar = 5 }` instead of `Foo { $0.bar = 5 }`.") @inlinable public init(with config: (inout Self) -> Void) { // swiftlint:disable:this missing_docs fatalError("Function no longer available. Xcode should actually show an unavailable error with message and not compile.") } /// Create a copy (if a struct) or use same object (if class), improving chainability e.g. after init method. @inlinable public func with(_ config: (inout Self) -> Void) -> Self { var copy = self config(&copy) return copy } }
Add Reusable protocol declaration to scrollview
import UIKit class PagingScrollView: UIScrollView { var reusableViews = [UIView]() override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configure() } func configure() { pagingEnabled = true directionalLockEnabled = true } override func layoutSubviews() { super.layoutSubviews() recenterIfNecessary() } func recenterIfNecessary() { if reusableViews.isEmpty { return } let contentWidth = contentSize.width let centerOffsetX = (contentWidth - bounds.size.width) / 2 let distanceFromCenter = contentOffset.x - centerOffsetX if fabs(distanceFromCenter) > (contentWidth / 3) { contentOffset = CGPoint(x: centerOffsetX, y: contentOffset.y) if distanceFromCenter > 0 { reusableViews.shiftRight() } else { reusableViews.shiftLeft() } for (index, subview) in reusableViews.enumerate() { subview.frame.origin.x = bounds.width * CGFloat(index) subview.frame.size = bounds.size } } } } extension Array { mutating func shiftLeft() { insert(removeFirst(), atIndex: 0) } mutating func shiftRight() { append(removeFirst()) } }
import UIKit protocol Reusable: class { func prepareForReuse() } class PagingScrollView: UIScrollView { var reusableViews = [UIView]() override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configure() } func configure() { pagingEnabled = true directionalLockEnabled = true } override func layoutSubviews() { super.layoutSubviews() recenterIfNecessary() } func recenterIfNecessary() { if reusableViews.isEmpty { return } let contentWidth = contentSize.width let centerOffsetX = (contentWidth - bounds.size.width) / 2 let distanceFromCenter = contentOffset.x - centerOffsetX if fabs(distanceFromCenter) > (contentWidth / 3) { contentOffset = CGPoint(x: centerOffsetX, y: contentOffset.y) if distanceFromCenter > 0 { reusableViews.shiftRight() } else { reusableViews.shiftLeft() } for (index, subview) in reusableViews.enumerate() { subview.frame.origin.x = bounds.width * CGFloat(index) subview.frame.size = bounds.size } } } } extension Array { mutating func shiftLeft() { insert(removeFirst(), atIndex: 0) } mutating func shiftRight() { append(removeFirst()) } }
Revert to IBM-Swift/SwiftyJSON for Linux support
import PackageDescription let package = Package( name: "zosconnectforswift", targets: [], dependencies: [ .Package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", versions: Version(1,0,0)..<Version(3, .max, .max)), .Package(url: "https://github.com/IBM-Swift/Kitura-net", majorVersion: 1, minor: 3), ] )
import PackageDescription let package = Package( name: "zosconnectforswift", targets: [], dependencies: [ .Package(url: "https://github.com/IBM-Swift/SwiftyJSON", versions: Version(1,0,0)..<Version(15, .max, .max)), .Package(url: "https://github.com/IBM-Swift/Kitura-net", majorVersion: 1, minor: 3), ] )
Implement pinch to zoom in media viewer
// // MediaViewerController.swift // AtMe // // Created by Joel Rorseth on 2018-04-28. // Copyright © 2018 Joel Rorseth. All rights reserved. // import UIKit class MediaViewerController: UIViewController { var contentImageView: UIImageView! var image: UIImage? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.black contentImageView = UIImageView(frame: self.view.frame) contentImageView.contentMode = UIViewContentMode.scaleAspectFit view.addSubview(contentImageView) // contentImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true // contentImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true // contentImageView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true // contentImageView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true if let image = image { contentImageView.image = image } else { print("Error: No image provided to MediaViewerController") } let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(MediaViewerController.viewTapped)) view.addGestureRecognizer(tapRecognizer) } @objc func viewTapped() { dismiss(animated: true, completion: nil) } }
// // MediaViewerController.swift // AtMe // // Created by Joel Rorseth on 2018-04-28. // Copyright © 2018 Joel Rorseth. All rights reserved. // import UIKit class MediaViewerController: UIViewController { var scrollView: UIScrollView! var contentImageView: UIImageView! var image: UIImage? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.black scrollView = UIScrollView(frame: view.frame) scrollView.minimumZoomScale = 1.0 scrollView.maximumZoomScale = 5.0 scrollView.delegate = self contentImageView = UIImageView(frame: self.view.frame) contentImageView.contentMode = UIViewContentMode.scaleAspectFit // Form view hierarchy -- UIView -> UIScrollView -> UIImageView view.addSubview(scrollView) scrollView.addSubview(contentImageView) // Provide the UIImage to the UIImageView if let image = image { contentImageView.image = image } else { print("Error: No image provided to MediaViewerController") } let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(MediaViewerController.viewTapped)) view.addGestureRecognizer(tapRecognizer) } // Handler for tap gesture on the view @objc func viewTapped() { dismiss(animated: true, completion: nil) } } // MARK: UIScrollViewDelegate extension MediaViewerController: UIScrollViewDelegate { // Provide the view to be scaled when zooming in the UIScrollView func viewForZooming(in scrollView: UIScrollView) -> UIView? { return contentImageView } }
Add ReactiveKit as test dependency
// swift-tools-version:4.2 import PackageDescription let package = Package( name: "Bond", products: [ .library(name: "Bond", targets: ["Bond"]) ], dependencies: [ .package(url: "https://github.com/DeclarativeHub/ReactiveKit.git", .upToNextMajor(from: "3.10.0")), .package(url: "https://github.com/tonyarnold/Differ.git", .upToNextMajor(from: "1.4.1")) ], targets: [ .target(name: "BNDProtocolProxyBase"), .target(name: "Bond", dependencies: ["BNDProtocolProxyBase", "ReactiveKit", "Differ"]), .testTarget(name: "BondTests", dependencies: ["Bond"]) ] )
// swift-tools-version:4.2 import PackageDescription let package = Package( name: "Bond", products: [ .library(name: "Bond", targets: ["Bond"]) ], dependencies: [ .package(url: "https://github.com/DeclarativeHub/ReactiveKit.git", .upToNextMajor(from: "3.10.0")), .package(url: "https://github.com/tonyarnold/Differ.git", .upToNextMajor(from: "1.4.1")) ], targets: [ .target(name: "BNDProtocolProxyBase"), .target(name: "Bond", dependencies: ["BNDProtocolProxyBase", "ReactiveKit", "Differ"]), .testTarget(name: "BondTests", dependencies: ["Bond", "ReactiveKit"]) ] )
Add new yellow and red colors
// // Created by Alexander Maslennikov on 27.01.16. // Copyright (c) 2016 Heads and Hands. All rights reserved. // import UIKit import ChameleonFramework extension UIColor { static func hhkl_mainColor() -> UIColor { return UIColor.flatBlackColorDark() } static func hhkl_secondaryColor() -> UIColor { return UIColor.flatWhiteColor() } static func hhkl_tertiaryColor() -> UIColor { return UIColor.flatWhiteColorDark() } static func hhkl_yellowFlatColor() -> UIColor { return UIColor.flatYellowColor() } static func hhkl_redFlatColor() -> UIColor { return UIColor.flatRedColor() } static func hhkl_textColor() -> UIColor { return UIColor(contrastingBlackOrWhiteColorOn:UIColor.hhkl_mainColor(), isFlat: true) } }
// // Created by Alexander Maslennikov on 27.01.16. // Copyright (c) 2016 Heads and Hands. All rights reserved. // import UIKit import ChameleonFramework extension UIColor { static func hhkl_mainColor() -> UIColor { return UIColor.flatBlackColorDark() } static func hhkl_secondaryColor() -> UIColor { return UIColor.flatWhiteColor() } static func hhkl_tertiaryColor() -> UIColor { return UIColor.flatWhiteColorDark() } static func hhkl_yellowFlatColor() -> UIColor { return UIColor(red: 252/255, green: 186/255, blue: 4/255, alpha: 1.0) } static func hhkl_redFlatColor() -> UIColor { return UIColor(red: 186/255, green: 45/255, blue: 11/255, alpha: 1.0) } static func hhkl_textColor() -> UIColor { return UIColor(contrastingBlackOrWhiteColorOn:UIColor.hhkl_mainColor(), isFlat: true) } }
Remove check for auto play
import UIKit extension UIViewController { // MARK: - Method Swizzling public override class func initialize() { struct Static { static var token: dispatch_once_t = 0 } if self !== UIViewController.self { return } dispatch_once(&Static.token) { MethodSwizzler.swizzleMethod("viewWillAppear:", cls: self) MethodSwizzler.swizzleMethod("viewWillDisappear:", cls: self) } } func jukebox_viewWillAppear(animated: Bool) { jukebox_viewWillAppear(animated) guard animated else { return } var sound: Sound? if isMovingToParentViewController() { sound = .Push } else if isBeingPresented() { sound = .Present } guard let autoSound = sound else { return } Jukebox.autoPlay(autoSound) } func jukebox_viewWillDisappear(animated: Bool) { jukebox_viewWillDisappear(animated) guard animated && Jukebox.autoPlay else { return } var sound: Sound? if isMovingFromParentViewController() { sound = .Pop } else if isBeingDismissed() { sound = .Dismiss } guard let autoSound = sound else { return } Jukebox.autoPlay(autoSound) } }
import UIKit extension UIViewController { // MARK: - Method Swizzling public override class func initialize() { struct Static { static var token: dispatch_once_t = 0 } if self !== UIViewController.self { return } dispatch_once(&Static.token) { MethodSwizzler.swizzleMethod("viewWillAppear:", cls: self) MethodSwizzler.swizzleMethod("viewWillDisappear:", cls: self) } } func jukebox_viewWillAppear(animated: Bool) { jukebox_viewWillAppear(animated) guard animated else { return } var sound: Sound? if isMovingToParentViewController() { sound = .Push } else if isBeingPresented() { sound = .Present } guard let autoSound = sound else { return } Jukebox.autoPlay(autoSound) } func jukebox_viewWillDisappear(animated: Bool) { jukebox_viewWillDisappear(animated) guard animated else { return } var sound: Sound? if isMovingFromParentViewController() { sound = .Pop } else if isBeingDismissed() { sound = .Dismiss } guard let autoSound = sound else { return } Jukebox.autoPlay(autoSound) } }
Add string helper for nil or empty
/* | _ ____ ____ _ | | |‾| ⚈ |-| ⚈ |‾| | | | | ‾‾‾‾| |‾‾‾‾ | | | ‾ ‾ ‾ */ import UIKit public extension String { func height(with width: CGFloat, font: UIFont = UIFont.preferredFont(forTextStyle: .body)) -> CGFloat { let nsString = self as NSString let rect = nsString.boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) return ceil(rect.height) } }
/* | _ ____ ____ _ | | |‾| ⚈ |-| ⚈ |‾| | | | | ‾‾‾‾| |‾‾‾‾ | | | ‾ ‾ ‾ */ import UIKit public extension String { func height(with width: CGFloat, font: UIFont = UIFont.preferredFont(forTextStyle: .body)) -> CGFloat { let nsString = self as NSString let rect = nsString.boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) return ceil(rect.height) } } public extension Optional where Wrapped == String { var isBlank: Bool { return (self ?? "").isEmpty } }
Add test for RequestBuilder init
// // RequestBuilderTests.swift // BreweryDB // // Created by Jake Welton on 1/30/16. // Copyright © 2016 Jake Welton. All rights reserved. // import XCTest class RequestBuilderTests: 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() } }
// // RequestBuilderTests.swift // BreweryDB // // Created by Jake Welton on 1/30/16. // Copyright © 2016 Jake Welton. All rights reserved. // import XCTest @testable import BreweryDB class RequestBuilderTests: 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 testRequestBuilderInitsWithRequestEndPoint() { let requestBuilder = RequestBuilder(endPoint: .Beer) XCTAssertNotNil(requestBuilder) } }
Add a missing REQUIRES and availability macro.
// RUN: %target-swift-frontend -emit-sil %s -Onone -Xllvm \ // RUN: -sil-print-after=mandatory-inlining \ // RUN: -enable-ownership-stripping-after-serialization \ // RUN: -Xllvm -sil-print-debuginfo -o /dev/null 2>&1 | %FileCheck %s // CHECK: begin_borrow {{.*}} : $OSLog, loc {{.*}}, scope 3 // CHECK: tuple (), loc {{.*}}, scope 3 // CHECK: end_borrow %3 : $OSLog, loc {{.*}}, scope 3 import os func bar() { foo(OSLog.default) } @_transparent func foo(_ logObject: OSLog) { }
// REQUIRES: objc_interop // RUN: %target-swift-frontend -emit-sil %s -Onone -Xllvm \ // RUN: -sil-print-after=mandatory-inlining \ // RUN: -enable-ownership-stripping-after-serialization \ // RUN: -Xllvm -sil-print-debuginfo -o /dev/null 2>&1 | %FileCheck %s // CHECK: begin_borrow {{.*}} : $OSLog, loc {{.*}}, scope 5 // CHECK: tuple (), loc {{.*}}, scope 5 // CHECK: end_borrow %9 : $OSLog, loc {{.*}}, scope 5 import os func bar() { if #available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) { foo(OSLog.default) } } @_transparent func foo(_ logObject: OSLog) { }
Update way to deserialize only with functional operations
// // 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} guard let firebaseModels = (dataSnapshot?.flatMap {Self.deserialize(from: $0.value as? NSDictionary)}) else { return nil } for (index, firebaseModel) in firebaseModels.enumerated() { firebaseModel.key = keys?[index] } return firebaseModels } }
// // 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 firebaseModels = (dataSnapshot? .flatMap{ Self.deserialize(from: $0.value as? NSDictionary) })? .enumerated() .flatMap { offset, element -> Self in element.key = keys?[offset]; return element } return firebaseModels } }
Increase version number in swcomp
// Copyright (c) 2017 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation import SWCompression import SwiftCLI let cli = CLI(name: "swcomp", version: "4.0.0-test.1", description: """ swcomp - small command-line client for SWCompression framework. Serves as an example of SWCompression usage. """) cli.commands = [XZCommand(), LZMACommand(), BZip2Command(), GZipCommand(), ZipCommand(), TarCommand(), SevenZipCommand()] cli.goAndExit()
// Copyright (c) 2017 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation import SWCompression import SwiftCLI let cli = CLI(name: "swcomp", version: "4.0.0-test.2", description: """ swcomp - small command-line client for SWCompression framework. Serves as an example of SWCompression usage. """) cli.commands = [XZCommand(), LZMACommand(), BZip2Command(), GZipCommand(), ZipCommand(), TarCommand(), SevenZipCommand()] cli.goAndExit()
Check based on equality, not identity
// // ExpressionRewriter.swift // DDMathParser // // Created by Dave DeLong on 8/25/15. // // import Foundation public struct ExpressionRewriter { private var rules: Array<RewriteRule> public init(rules: Array<RewriteRule> = RewriteRule.defaultRules) { self.rules = rules } public mutating func addRule(rule: RewriteRule) { rules.append(rule) } public func rewriteExpression(expression: Expression, evaluator: Evaluator) -> Expression { var tmp = expression var iterationCount = 0 repeat { var changed = false for rule in rules { let rewritten = rewrite(tmp, usingRule: rule, evaluator: evaluator) if rewritten != tmp { changed = true tmp = rewritten } } if changed == false { break } iterationCount++ } while iterationCount < 256 if iterationCount >= 256 { NSLog("replacement limit reached") } return tmp } private func rewrite(expression: Expression, usingRule rule: RewriteRule, evaluator: Evaluator) -> Expression { let rewritten = rule.rewrite(expression, evaluator: evaluator) if rewritten !== expression { return rewritten } guard case let .Function(f, args) = rewritten.kind else { return rewritten } let newArgs = args.map { rewrite($0, usingRule: rule, evaluator: evaluator) } // if nothing changed, reture guard args != newArgs else { return rewritten } return Expression(kind: .Function(f, args), range: rewritten.range) } }
// // ExpressionRewriter.swift // DDMathParser // // Created by Dave DeLong on 8/25/15. // // import Foundation public struct ExpressionRewriter { private var rules: Array<RewriteRule> public init(rules: Array<RewriteRule> = RewriteRule.defaultRules) { self.rules = rules } public mutating func addRule(rule: RewriteRule) { rules.append(rule) } public func rewriteExpression(expression: Expression, evaluator: Evaluator) -> Expression { var tmp = expression var iterationCount = 0 repeat { var changed = false for rule in rules { let rewritten = rewrite(tmp, usingRule: rule, evaluator: evaluator) if rewritten != tmp { changed = true tmp = rewritten } } if changed == false { break } iterationCount++ } while iterationCount < 256 if iterationCount >= 256 { NSLog("replacement limit reached") } return tmp } private func rewrite(expression: Expression, usingRule rule: RewriteRule, evaluator: Evaluator) -> Expression { let rewritten = rule.rewrite(expression, evaluator: evaluator) if rewritten != expression { return rewritten } guard case let .Function(f, args) = rewritten.kind else { return rewritten } let newArgs = args.map { rewrite($0, usingRule: rule, evaluator: evaluator) } // if nothing changed, reture guard args != newArgs else { return rewritten } return Expression(kind: .Function(f, args), range: rewritten.range) } }
Read only *.json data files
// // main.swift // awesome-creator // // Created by Caesar Wirth on 4/13/15. // Copyright (c) 2015 Caesar Wirth. All rights reserved. // import Foundation func dataFilePaths() -> [String] { var paths: [String] = [] let fileManager = NSFileManager.defaultManager() if let datas = fileManager.contentsOfDirectoryAtPath("data", error: nil) { for data in datas { if let file = data as? String { if file == "Template.json" { continue } paths.append("./data/" + file) } } } return paths } func readDataFile(path: String) -> Page { let page = Page() var error: NSError? if let data = NSData(contentsOfFile: path), json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: &error) as? [String: AnyObject] { page.update(json) page.filename = path.pathComponents.last?.stringByReplacingOccurrencesOfString("json", withString: "md") ?? "" } if let error = error { println(error) } return page } let paths = dataFilePaths() let pages = paths.map(readDataFile) write(pages)
// // main.swift // awesome-creator // // Created by Caesar Wirth on 4/13/15. // Copyright (c) 2015 Caesar Wirth. All rights reserved. // import Foundation func dataFilePaths() -> [String] { var paths: [String] = [] let fileManager = NSFileManager.defaultManager() if let datas = fileManager.contentsOfDirectoryAtPath("data", error: nil) { for data in datas { if let file = data as? String { if !file.hasSuffix(".json") { continue } if file == "Template.json" { continue } paths.append("./data/" + file) } } } return paths } func readDataFile(path: String) -> Page { let page = Page() var error: NSError? if let data = NSData(contentsOfFile: path), json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: &error) as? [String: AnyObject] { page.update(json) page.filename = path.pathComponents.last?.stringByReplacingOccurrencesOfString("json", withString: "md") ?? "" } if let error = error { println(error) } return page } let paths = dataFilePaths() let pages = paths.map(readDataFile) write(pages)
Add a test of MIMEType for linux.
/* ************************************************************************************************* MIMETypeTests.swift © 2018 YOCKOW. Licensed under MIT License. See "LICENSE.txt" for more information. ************************************************************************************************ */ import XCTest @testable import HTTP final class MIMETypeTests: XCTestCase { func test_parser() { let xhtml_type_utf8_string = "application/xhtml+xml; charset=UTF-8; myparameter=myvalue" let xhtml_type = MIMEType(xhtml_type_utf8_string) XCTAssertNotNil(xhtml_type) XCTAssertEqual(xhtml_type?.type, .application) XCTAssertEqual(xhtml_type?.tree, nil) XCTAssertEqual(xhtml_type?.subtype, "xhtml") XCTAssertEqual(xhtml_type?.suffix, .xml) XCTAssertEqual(xhtml_type?.parameters?["charset"], "UTF-8") XCTAssertEqual(xhtml_type?.parameters?["myparameter"], "myvalue") } func test_pathExtensions() { let txt_ext: MIMEType.PathExtension = .txt let text_mime_type = MIMEType(pathExtension:txt_ext) XCTAssertEqual(text_mime_type, MIMEType(type:.text, subtype:"plain")) XCTAssertEqual(text_mime_type?.possiblePathExtensions?.contains(txt_ext), true) } static var allTests = [ ("test_parser", test_parser) ] }
/* ************************************************************************************************* MIMETypeTests.swift © 2018 YOCKOW. Licensed under MIT License. See "LICENSE.txt" for more information. ************************************************************************************************ */ import XCTest @testable import HTTP final class MIMETypeTests: XCTestCase { func test_parser() { let xhtml_type_utf8_string = "application/xhtml+xml; charset=UTF-8; myparameter=myvalue" let xhtml_type = MIMEType(xhtml_type_utf8_string) XCTAssertNotNil(xhtml_type) XCTAssertEqual(xhtml_type?.type, .application) XCTAssertEqual(xhtml_type?.tree, nil) XCTAssertEqual(xhtml_type?.subtype, "xhtml") XCTAssertEqual(xhtml_type?.suffix, .xml) XCTAssertEqual(xhtml_type?.parameters?["charset"], "UTF-8") XCTAssertEqual(xhtml_type?.parameters?["myparameter"], "myvalue") } func test_pathExtensions() { let txt_ext: MIMEType.PathExtension = .txt let text_mime_type = MIMEType(pathExtension:txt_ext) XCTAssertEqual(text_mime_type, MIMEType(type:.text, subtype:"plain")) XCTAssertEqual(text_mime_type?.possiblePathExtensions?.contains(txt_ext), true) } static var allTests = [ ("test_parser", test_parser), ("test_pathExtensions", test_pathExtensions), ] }
Use 5.0.0 version of cli framework
// swift-tools-version:4.0 import PackageDescription let package = Package( name: "SWCompression", products: [ .library( name: "SWCompression", targets: ["SWCompression"]), ], dependencies: [ // SWCOMP: Uncomment the line below to build swcomp example program. // .package(url: "https://github.com/jakeheis/SwiftCLI", // from: "4.2.0"), .package(url: "https://github.com/tsolomko/BitByteData", from: "1.2.0-test"), ], targets: [ // SWCOMP: Uncomment the lines below to build swcomp example program. // .target( // name: "swcomp", // dependencies: ["SWCompression", "SwiftCLI"], // path: "Sources", // sources: ["swcomp"]), .target( name: "SWCompression", dependencies: ["BitByteData"], path: "Sources", sources: ["Common", "7-Zip", "BZip2", "Deflate", "GZip", "LZMA", "LZMA2", "TAR", "XZ", "ZIP", "Zlib"]), ], swiftLanguageVersions: [4] )
// swift-tools-version:4.0 import PackageDescription let package = Package( name: "SWCompression", products: [ .library( name: "SWCompression", targets: ["SWCompression"]), ], dependencies: [ // SWCOMP: Uncomment the line below to build swcomp example program. // .package(url: "https://github.com/jakeheis/SwiftCLI", // from: "5.0.0"), .package(url: "https://github.com/tsolomko/BitByteData", from: "1.2.0-test"), ], targets: [ // SWCOMP: Uncomment the lines below to build swcomp example program. // .target( // name: "swcomp", // dependencies: ["SWCompression", "SwiftCLI"], // path: "Sources", // sources: ["swcomp"]), .target( name: "SWCompression", dependencies: ["BitByteData"], path: "Sources", sources: ["Common", "7-Zip", "BZip2", "Deflate", "GZip", "LZMA", "LZMA2", "TAR", "XZ", "ZIP", "Zlib"]), ], swiftLanguageVersions: [4] )