Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix Xcode version check to detect versions higher than 6.3 | import Foundation
let RequiredXcodeVersion = "Xcode 6.3"
func isRequiredXcodeIsInstalled() -> Bool {
return currentXcodeVersion() == RequiredXcodeVersion
}
func currentXcodeVersion() -> String? {
return run("xcodebuild -version").first
}
| import Foundation
let RequiredXcodeVersion = "Xcode 6.3"
func isRequiredXcodeIsInstalled() -> Bool {
if let comparationResult = currentXcodeVersion()?.localizedCaseInsensitiveCompare(RequiredXcodeVersion) {
switch comparationResult {
case .OrderedDescending, .OrderedSame: return true
default: ()
}
}
return false
}
func currentXcodeVersion() -> String? {
return run("xcodebuild -version").first
}
|
Revert "Using VC main view disposer as VC Disposer" | // Copyright © 2016 Compass. All rights reserved.
#if os(iOS) || os(tvOS)
import UIKit
#else
import Foundation
#endif
extension UIViewController {
public var disposer: Disposer {
return view.disposer
}
}
| // Copyright © 2016 Compass. All rights reserved.
#if os(iOS) || os(tvOS)
import UIKit
#else
import Foundation
#endif
extension UIViewController {
private static var disposerKey = "com.compass.Snail.UIViewController.disposer"
public var disposer: Disposer {
if let disposer = objc_getAssociatedObject(self, &UIViewController.disposerKey) as? Disposer {
return disposer
}
let disposer = Disposer()
objc_setAssociatedObject(self, &UIViewController.disposerKey, disposer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return disposer
}
}
|
Remove ana (because nothing uses it). | // Copyright © 2015 Rob Rix. All rights reserved.
public protocol TermContainerType: Equatable, CustomDebugStringConvertible, CustomStringConvertible {
var out: Expression<Self> { get }
}
extension TermContainerType {
public static func out(container: Self) -> Expression<Self> {
return container.out
}
public func cata<Result>(transform: Expression<Result> -> Result) -> Result {
return (Self.out >>> { $0.map { $0.cata(transform) } } >>> transform)(self)
}
public func para<Result>(transform: Expression<(Self, Result)> -> Result) -> Result {
return (Self.out >>> { $0.map { ($0, $0.para(transform)) } } >>> transform)(self)
}
}
public func == <Term: TermContainerType> (left: Term, right: Term) -> Bool {
return left.out == right.out
}
public protocol TermType: IntegerLiteralConvertible, StringLiteralConvertible, TermContainerType {
init(_: () -> Expression<Self>)
}
extension TermType {
public init(_ expression: Expression<Self>) {
self.init { expression }
}
public static func ana<A>(transform: A -> Expression<A>)(_ seed: A) -> Self {
return (Self.init <<< { $0.map(ana(transform)) } <<< transform)(seed)
}
}
import Either
import Prelude
| // Copyright © 2015 Rob Rix. All rights reserved.
public protocol TermContainerType: Equatable, CustomDebugStringConvertible, CustomStringConvertible {
var out: Expression<Self> { get }
}
extension TermContainerType {
public static func out(container: Self) -> Expression<Self> {
return container.out
}
public func cata<Result>(transform: Expression<Result> -> Result) -> Result {
return (Self.out >>> { $0.map { $0.cata(transform) } } >>> transform)(self)
}
public func para<Result>(transform: Expression<(Self, Result)> -> Result) -> Result {
return (Self.out >>> { $0.map { ($0, $0.para(transform)) } } >>> transform)(self)
}
}
public func == <Term: TermContainerType> (left: Term, right: Term) -> Bool {
return left.out == right.out
}
public protocol TermType: IntegerLiteralConvertible, StringLiteralConvertible, TermContainerType {
init(_: () -> Expression<Self>)
}
extension TermType {
public init(_ expression: Expression<Self>) {
self.init { expression }
}
}
import Either
import Prelude
|
Use flat string in double bytes | public enum Tone: String {
case A
case Bb
case B
case C
case Db
case D
case Eb
case E
case F
case Gb
case G
case Ab
}
public extension Tone {
// Even though each tone is represented in String, we still need order of each tone.
public var order: Int {
switch self {
case .A: return 0
case .Bb: return 1
case .B: return 2
case .C: return 3
case .Db: return 4
case .D: return 5
case .Eb: return 6
case .E: return 7
case .F: return 8
case .Gb: return 9
case .G: return 10
case .Ab: return 11
}
}
}
extension Tone: Comparable {
public static func < (lhs: Tone, rhs: Tone) -> Bool {
return lhs.order < rhs.order
}
}
| public enum Tone: String {
case A
case Bb = "B♭"
case B
case C
case Db = "D♭"
case D
case Eb = "E♭"
case E
case F
case Gb = "G♭"
case G
case Ab = "A♭"
}
public extension Tone {
// Even though each tone is represented in String, we still need order of each tone.
public var order: Int {
switch self {
case .A: return 0
case .Bb: return 1
case .B: return 2
case .C: return 3
case .Db: return 4
case .D: return 5
case .Eb: return 6
case .E: return 7
case .F: return 8
case .Gb: return 9
case .G: return 10
case .Ab: return 11
}
}
}
extension Tone: Comparable {
public static func < (lhs: Tone, rhs: Tone) -> Bool {
return lhs.order < rhs.order
}
}
|
Add values to the disjoint set. | // Copyright (c) 2015 Rob Rix. All rights reserved.
public struct DisjointSet {
public mutating func union(a: Int, b: Int) {
let (r1, r2) = (find(a), find(b))
let (n1, n2) = (sets[r1], sets[r2])
if r1 != r2 {
if n1.rank < n2.rank {
sets[r1].parent = r2
} else {
sets[r2].parent = r1
if n1.rank == n2.rank {
++sets[r1].rank
}
}
}
}
public mutating func find(a: Int) -> Int {
let n = sets[a]
if n.parent == a {
return a
} else {
let parent = find(n.parent)
sets[a].parent = parent
return parent
}
}
// MARK: Private
private var sets: [(parent: Int, rank: Int)]
}
| // Copyright (c) 2015 Rob Rix. All rights reserved.
public struct DisjointSet<T> {
public mutating func union(a: Int, b: Int) {
let (r1, r2) = (find(a), find(b))
let (n1, n2) = (sets[r1], sets[r2])
if r1 != r2 {
if n1.rank < n2.rank {
sets[r1].parent = r2
} else {
sets[r2].parent = r1
if n1.rank == n2.rank {
++sets[r1].rank
}
}
}
}
public mutating func find(a: Int) -> Int {
let n = sets[a]
if n.parent == a {
return a
} else {
let parent = find(n.parent)
sets[a].parent = parent
return parent
}
}
// MARK: Private
private var sets: [(parent: Int, rank: Int, value: T)]
}
|
Use string for layout key | import UIKit
public protocol LayoutKey {
var layoutKey: String { get }
}
extension String: LayoutKey {
public var layoutKey: String { return self }
}
public class Layout {
private var constraints = [NSLayoutConstraint]()
private var sublayouts = [String : Layout]()
private var allConstraints: [NSLayoutConstraint] {
return constraints + sublayouts.values.flatMap({ $0.allConstraints })
}
public init() {
}
public static func +=(layout: Layout, constraints: [NSLayoutConstraint]) {
layout.constraints += constraints
}
public static func +=(layout: Layout, constraint: NSLayoutConstraint) {
layout.constraints += [constraint]
}
public subscript(key: LayoutKey) -> Layout {
if let subLayout = sublayouts[key.layoutKey] {
return subLayout
} else {
let sublayout = Layout()
sublayouts[key.layoutKey] = sublayout
return sublayout
}
}
public func activate() {
allConstraints.forEach { $0.isActive = true }
}
public func deactivate() {
allConstraints.forEach { $0.isActive = false }
}
public func activate(keys: LayoutKey...) {
sublayouts(keys).forEach { $0.activate() }
}
public func deactivate(keys: LayoutKey...) {
sublayouts(keys).forEach { $0.deactivate() }
}
private func sublayouts(_ keys: [LayoutKey]) -> [Layout] {
let layoutKeys = keys.map { $0.layoutKey }
return sublayouts.filter { layoutKeys.contains($0.key) } .map { $0.value }
}
}
| import UIKit
public typealias LayoutKey = String
public class Layout {
private var constraints = [NSLayoutConstraint]()
private var sublayouts = [String : Layout]()
private var allConstraints: [NSLayoutConstraint] {
return constraints + sublayouts.values.flatMap({ $0.allConstraints })
}
public init() {
}
public static func +=(layout: Layout, constraints: [NSLayoutConstraint]) {
layout.constraints += constraints
}
public static func +=(layout: Layout, constraint: NSLayoutConstraint) {
layout.constraints += [constraint]
}
public subscript(key: LayoutKey) -> Layout {
if let subLayout = sublayouts[key] {
return subLayout
} else {
let sublayout = Layout()
sublayouts[key] = sublayout
return sublayout
}
}
public func activate() {
allConstraints.forEach { $0.isActive = true }
}
public func deactivate() {
allConstraints.forEach { $0.isActive = false }
}
public func activate(keys: LayoutKey...) {
sublayouts(keys).forEach { $0.activate() }
}
public func deactivate(keys: LayoutKey...) {
sublayouts(keys).forEach { $0.deactivate() }
}
private func sublayouts(_ keys: [LayoutKey]) -> [Layout] {
return sublayouts.filter { keys.contains($0.key) } .map { $0.value }
}
}
|
Update test scheme to use test server | //
// ApplicationController.swift
// TrolleyTracker
//
// Created by Austin on 3/22/17.
// Copyright © 2017 Code For Greenville. All rights reserved.
//
import Foundation
class ApplicationController {
let trolleyRouteService: TrolleyRouteService
let trolleyLocationService: TrolleyLocationService
let trolleyScheduleService: TrolleyScheduleService
init() {
trolleyScheduleService = TrolleyScheduleService()
switch EnvironmentVariables.currentBuildConfiguration() {
case .Release:
trolleyLocationService = TrolleyLocationServiceLive.sharedService
trolleyRouteService = TrolleyRouteServiceLive()
case .Test:
trolleyLocationService = TrolleyLocationServiceFake()
trolleyRouteService = TrolleyRouteServiceFake()
}
}
}
| //
// ApplicationController.swift
// TrolleyTracker
//
// Created by Austin on 3/22/17.
// Copyright © 2017 Code For Greenville. All rights reserved.
//
import Foundation
class ApplicationController {
let trolleyRouteService: TrolleyRouteService
let trolleyLocationService: TrolleyLocationService
let trolleyScheduleService: TrolleyScheduleService
init() {
trolleyScheduleService = TrolleyScheduleService()
trolleyLocationService = TrolleyLocationServiceLive.sharedService
trolleyRouteService = TrolleyRouteServiceLive()
// switch EnvironmentVariables.currentBuildConfiguration() {
// case .Release:
// trolleyLocationService = TrolleyLocationServiceLive.sharedService
// trolleyRouteService = TrolleyRouteServiceLive()
// case .Test:
// trolleyLocationService = TrolleyLocationServiceFake()
// trolleyRouteService = TrolleyRouteServiceFake()
// }
}
}
|
Add support for building package with Xcode 11 and SPM. | import PackageDescription
let package = Package(
name: "LoadableView"
)
| // swift-tools-version:5.0
//
// Package.swift
//
// Copyright © 2019 MLSDev Inc(https://mlsdev.com).
//
// 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 PackageDescription
let package = Package(
name: "LoadableViews",
platforms: [
.iOS(.v8),
.tvOS(.v9)
],
products: [
.library(
name: "LoadableViews",
targets: ["LoadableViews"])
],
targets: [
.target(
name: "LoadableViews",
path: "Source")
],
swiftLanguageVersions: [.v5]
)
|
Revert "Fixed missing animated GIF" | // swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "DTFoundation",
platforms: [
.iOS(.v9), //.v8 - .v13
.macOS(.v10_10), //.v10_10 - .v10_15
.tvOS(.v9), //.v9 - .v13
],
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "DTFoundation",
targets: ["DTFoundation"]),
],
targets: [
.target(
name: "DTFoundation",
dependencies: [],
path: "Core",
cSettings: [
.headerSearchPath("include/DTFoundation"),
.headerSearchPath("Source/Externals/minizip"),
.define("TARGET_OS_IPHONE=1", .when(platforms: [.iOS, .tvOS])),
.define("TARGET_OS_OSX=1", .when(platforms: [.macOS])),
]
),
.testTarget(
name: "DTFoundationTests",
dependencies: ["DTFoundation"]),
]
)
| // swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "DTCoreText",
platforms: [
.iOS(.v9), //.v8 - .v13
.macOS(.v10_10), //.v10_10 - .v10_15
.tvOS(.v9), //.v9 - .v13
],
products: [
.library(
name: "DTCoreText",
targets: ["DTCoreText"]),
],
dependencies: [
.package(url: "https://github.com/Cocoanetics/DTFoundation.git", from: "1.7.15"),
],
targets: [
.target(
name: "DTCoreText",
dependencies: [
.product(name: "DTFoundation", package: "DTFoundation"),
],
path: "Core"),
.testTarget(
name: "DTCoreTextTests",
dependencies: ["DTCoreText"]),
]
)
|
Revert "add switch statement to handle mapping of wiki language to ISO language code" | // Created by Monte Hurd on 10/4/15.
// Copyright (c) 2015 Wikimedia Foundation. Provided under MIT-style license; please copy and modify!
import Foundation
extension NSLocale {
class func wmf_isCurrentLocaleEnglish() -> Bool {
guard let langCode = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode) as? String else {
return false
}
return (langCode == "en" || langCode.hasPrefix("en-")) ? true : false;
}
func wmf_localizedLanguageNameForCode(code: String) -> String? {
var ISOLanguageCode:String
switch code {
case "als": //wiki language codes don't map 1:1 to ISOLanguageCodes
ISOLanguageCode = "gsw"
default:
ISOLanguageCode = code
}
return self.displayNameForKey(NSLocaleLanguageCode, value: ISOLanguageCode)
}
}
| // Created by Monte Hurd on 10/4/15.
// Copyright (c) 2015 Wikimedia Foundation. Provided under MIT-style license; please copy and modify!
import Foundation
extension NSLocale {
class func wmf_isCurrentLocaleEnglish() -> Bool {
guard let langCode = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode) as? String else {
return false
}
return (langCode == "en" || langCode.hasPrefix("en-")) ? true : false;
}
func wmf_localizedLanguageNameForCode(code: String) -> String? {
return self.displayNameForKey(NSLocaleLanguageCode, value: code)
}
}
|
Upgrade dependencies, switch back to upstream BigInt package | // swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "SRP",
products: [
.library(name: "SRP", targets: ["SRP"]),
],
dependencies: [
.package(url: "https://github.com/IBM-Swift/BlueCryptor.git", from: "1.0.14"),
.package(url: "https://github.com/Boilertalk/BigInt.swift.git", from: "1.0.0"),
],
targets: [
.target(name: "SRP", dependencies: ["Cryptor", "BigInt"], path: "Sources"),
.testTarget(name: "SRPTests", dependencies: ["Cryptor", "SRP"]),
],
swiftLanguageVersions: [4]
)
| // swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "SRP",
products: [
.library(name: "SRP", targets: ["SRP"]),
],
dependencies: [
.package(url: "https://github.com/IBM-Swift/BlueCryptor.git", from: "1.0.31"),
.package(url: "https://github.com/attaswift/BigInt.git", from: "5.0.0"),
],
targets: [
.target(name: "SRP", dependencies: ["Cryptor", "BigInt"], path: "Sources"),
.testTarget(name: "SRPTests", dependencies: ["Cryptor", "SRP"]),
],
swiftLanguageVersions: [4]
)
|
Fix account header image alignment and foreground color | //
// AccountHeaderImageView.swift
// Multiplatform iOS
//
// Created by Rizwan on 08/07/20.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
import SwiftUI
import RSCore
struct AccountHeaderImageView: View {
var image: RSImage
var body: some View {
HStack(alignment: .center) {
Image(rsImage: image)
.resizable()
.scaledToFit()
.frame(height: 48, alignment: .center)
.padding()
}
}
}
struct AccountHeaderImageView_Previews: PreviewProvider {
static var previews: some View {
Group {
AccountHeaderImageView(image: AppAssets.image(for: .onMyMac)!)
AccountHeaderImageView(image: AppAssets.image(for: .feedbin)!)
AccountHeaderImageView(image: AppAssets.accountLocalPadImage)
}
}
}
| //
// AccountHeaderImageView.swift
// Multiplatform iOS
//
// Created by Rizwan on 08/07/20.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
import SwiftUI
import RSCore
struct AccountHeaderImageView: View {
var image: RSImage
var body: some View {
HStack(alignment: .center) {
Spacer()
Image(rsImage: image)
.resizable()
.scaledToFit()
.frame(height: 48, alignment: .center)
.foregroundColor(Color.primary)
Spacer()
}
.padding(16)
}
}
struct AccountHeaderImageView_Previews: PreviewProvider {
static var previews: some View {
Group {
AccountHeaderImageView(image: AppAssets.image(for: .onMyMac)!)
AccountHeaderImageView(image: AppAssets.image(for: .feedbin)!)
AccountHeaderImageView(image: AppAssets.accountLocalPadImage)
}
}
}
|
Add small test for auth | //
// BiometricsAuthorizationServiceTests.swift
// iExtra
//
// Created by Saidi Daniel (BookBeat) on 2017-03-04.
// Copyright © 2017 Daniel Saidi. All rights reserved.
//
import Quick
import Nimble
import iExtra
class BiometricsAuthorizationServiceTests: QuickSpec {
override func spec() {
var service: AuthorizationService!
beforeEach {
service = BiometricsAuthorizationService()
}
context("when checking if authorized") {
it("returns false if no previous authorization is cached") {
expect(service.isAuthorized(forAction: "foo")).to(equal(false))
}
}
}
}
| //
// BiometricsAuthorizationServiceTests.swift
// iExtra
//
// Created by Saidi Daniel (BookBeat) on 2017-03-04.
// Copyright © 2017 Daniel Saidi. All rights reserved.
//
import Quick
import Nimble
import iExtra
class BiometricsAuthorizationServiceTests: QuickSpec {
override func spec() {
var service: AuthorizationService!
beforeEach {
service = BiometricsAuthorizationService()
}
context("when checking if user is authorized") {
it("says no if no previous authorization is cached") {
expect(service.isAuthorized(forAction: "foo")).to(equal(false))
}
}
context("when resetting authorization") {
it("considers user to not be previously authorized") {
service.resetAuthorization(forAction: "foo")
expect(service.isAuthorized(forAction: "foo")).to(equal(false))
}
}
}
}
|
Change definition (var -> let) | //
// Context.swift
// Cmg
//
// Created by xxxAIRINxxx on 2016/02/20.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import Foundation
import UIKit
import CoreImage
public final class Context {
public static var shared = Context()
public static var egleContext : EAGLContext { return Context.shared.egleContext ?? Context.shared.defaultEgleContext }
public static var ciContext : CIContext { return Context.shared.ciContext ?? Context.shared.defaultCIContext }
public let defaultEgleContext : EAGLContext
public let defaultCIContext : CIContext
public var egleContext : EAGLContext?
public var ciContext : CIContext?
private init() {
self.defaultEgleContext = EAGLContext(API: .OpenGLES2)
#if (arch(i386) || arch(x86_64)) && os(iOS)
self.defaultCIContext = CIContext(options: [
kCIContextPriorityRequestLow: true,
kCIContextOutputColorSpace: NSNull()
])
#else
self.defaultCIContext = CIContext(EAGLContext: self.defaultEgleContext, options: [kCIContextUseSoftwareRenderer: false])
#endif
}
}
| //
// Context.swift
// Cmg
//
// Created by xxxAIRINxxx on 2016/02/20.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import Foundation
import UIKit
import CoreImage
public final class Context {
public static let shared = Context()
public static var egleContext : EAGLContext { return Context.shared.egleContext ?? Context.shared.defaultEgleContext }
public static var ciContext : CIContext { return Context.shared.ciContext ?? Context.shared.defaultCIContext }
public let defaultEgleContext : EAGLContext
public let defaultCIContext : CIContext
public var egleContext : EAGLContext?
public var ciContext : CIContext?
private init() {
self.defaultEgleContext = EAGLContext(API: .OpenGLES2)
#if (arch(i386) || arch(x86_64)) && os(iOS)
self.defaultCIContext = CIContext(options: [
kCIContextPriorityRequestLow: true,
kCIContextOutputColorSpace: NSNull()
])
#else
self.defaultCIContext = CIContext(EAGLContext: self.defaultEgleContext, options: [kCIContextUseSoftwareRenderer: false])
#endif
}
}
|
Use `NSDate` instead of `Date` | //
// VIMLive.swift
// Pods
//
// Created by Nguyen, Van on 8/29/17.
//
//
import Foundation
public enum LiveStreamingStatus: String
{
case unavailable = "unavailable"
case pending = "pending"
case ready = "ready"
case streamingPreview = "streaming_preview"
case streaming = "streaming"
case streamingError = "streaming_error"
case done = "done"
}
public class VIMLive: VIMModelObject
{
public var link: String?
public var key: String?
public var activeTime: Date?
public var endedTime: Date?
public var archivedTime: Date?
public var status: LiveStreamingStatus?
}
| //
// VIMLive.swift
// Pods
//
// Created by Nguyen, Van on 8/29/17.
//
//
import Foundation
public enum LiveStreamingStatus: String
{
case unavailable = "unavailable"
case pending = "pending"
case ready = "ready"
case streamingPreview = "streaming_preview"
case streaming = "streaming"
case streamingError = "streaming_error"
case done = "done"
}
public class VIMLive: VIMModelObject
{
public var link: String?
public var key: String?
public var activeTime: NSDate?
public var endedTime: NSDate?
public var archivedTime: NSDate?
public var status: LiveStreamingStatus?
}
|
Include first name and last name in credit card validation | //
// CreditCard.swift
// Spreedly
//
// Created by David Santoso on 10/8/15.
// Copyright © 2015 Spreedly Inc. All rights reserved.
//
import Foundation
public class CreditCard {
public var firstName, lastName, number, verificationValue, month, year: String?
public var address1, address2, city, state, zip, country, phoneNumber: String?
public init() {}
public func isValid() -> Bool {
if (number != nil &&
verificationValue != nil &&
month != nil &&
year != nil) {
return(true)
} else {
return(false)
}
}
public static func extractMonth(expiration: String) -> String {
return(self.splitExpirationString(expiration).first!)
}
public static func extractYear(expiration: String) -> String {
return("20" + self.splitExpirationString(expiration).last!)
}
static func splitExpirationString(expiration: String) -> [String] {
let expirationArray = expiration.componentsSeparatedByString("/")
return expirationArray
}
} | //
// CreditCard.swift
// Spreedly
//
// Created by David Santoso on 10/8/15.
// Copyright © 2015 Spreedly Inc. All rights reserved.
//
import Foundation
public class CreditCard {
public var firstName, lastName, number, verificationValue, month, year: String?
public var address1, address2, city, state, zip, country, phoneNumber: String?
public init() {}
public func isValid() -> Bool {
if (firstName != nil &&
lastName != nil &&
number != nil &&
verificationValue != nil &&
month != nil &&
year != nil) {
return(true)
} else {
return(false)
}
}
public static func extractMonth(expiration: String) -> String {
return(self.splitExpirationString(expiration).first!)
}
public static func extractYear(expiration: String) -> String {
return("20" + self.splitExpirationString(expiration).last!)
}
static func splitExpirationString(expiration: String) -> [String] {
let expirationArray = expiration.componentsSeparatedByString("/")
return expirationArray
}
} |
Cover JSONModelType with unit tests | //
// SwiftyJSONModelTests.swift
// SwiftyJSONModelTests
//
// Created by Oleksii on 17/09/16.
// Copyright © 2016 Oleksii Dykan. All rights reserved.
//
import XCTest
@testable import SwiftyJSONModel
class SwiftyJSONModelTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| //
// SwiftyJSONModelTests.swift
// SwiftyJSONModelTests
//
// Created by Oleksii on 17/09/16.
// Copyright © 2016 Oleksii Dykan. All rights reserved.
//
import XCTest
import SwiftyJSON
@testable import SwiftyJSONModel
struct FullName {
let firstName: String
let lastName: String
}
extension FullName: JSONModelType {
enum PropertyKey: String {
case firstName, lastName
}
init(properties: [PropertyKey : JSON]) throws {
firstName = try properties.value(for: .firstName).stringValue()
lastName = try properties.value(for: .lastName).stringValue()
}
var dictValue: [PropertyKey : JSON] {
return [.firstName: JSON(firstName), .lastName: JSON(lastName)]
}
}
extension FullName: Equatable {}
func == (left: FullName, right: FullName) -> Bool {
return left.firstName == right.firstName && left.lastName == right.lastName
}
class SwiftyJSONModelTests: XCTestCase {
func testJSONModelProtocols() {
let name = FullName(firstName: "John", lastName: "Doe")
XCTAssertEqual(try? FullName(json: name.jsonValue), name)
}
}
|
Move protocol conformance to extensions | //
// AuthenticationData.swift
// HomeControl
//
// Created by Julian Grosshauser on 01/12/15.
// Copyright © 2015 Julian Grosshauser. All rights reserved.
//
import Locksmith
/// Contains all data necessary to authenticate a user at the server.
struct AuthenticationData: ReadableSecureStorable, CreateableSecureStorable, DeleteableSecureStorable, GenericPasswordSecureStorable {
//MARK: Properties
/// Address of server.
let serverAddress: String
/// Name that identifies user.
let username: String
/// Password of user.
let password: String
//MARK: GenericPasswordSecureStorable
/// The service that the authentication data is saved under in the keychain.
let service = "HomeControl"
/// The account that identifies the authentication data in the keychain.
var account: String { return username }
//MARK: CreateableSecureStorable
/// Data that's saved in the keychain.
var data: [String: AnyObject] {
return ["password": password, "serverAddress": serverAddress]
}
//MARK: Initialization
/// Construct `AuthenticationData` containing server address, username and password.
/// The result is `nil` iff any parameter contains no characters.
init?(serverAddress: String, username: String, password: String) {
if [serverAddress, username, password].containsEmptyElement {
return nil
}
self.serverAddress = serverAddress
self.username = username
self.password = password
}
}
| //
// AuthenticationData.swift
// HomeControl
//
// Created by Julian Grosshauser on 01/12/15.
// Copyright © 2015 Julian Grosshauser. All rights reserved.
//
import Locksmith
/// Contains all data necessary to authenticate a user at the server.
struct AuthenticationData {
//MARK: Properties
/// Address of server.
let serverAddress: String
/// Name that identifies user.
let username: String
/// Password of user.
let password: String
//MARK: Initialization
/// Construct `AuthenticationData` containing server address, username and password.
/// The result is `nil` iff any parameter contains no characters.
init?(serverAddress: String, username: String, password: String) {
if [serverAddress, username, password].containsEmptyElement {
return nil
}
self.serverAddress = serverAddress
self.username = username
self.password = password
}
}
//MARK: GenericPasswordSecureStorable
extension AuthenticationData: GenericPasswordSecureStorable {
/// The service that the authentication data is saved under in the keychain.
var service: String {
return "HomeControl"
}
/// The account that identifies the authentication data in the keychain.
var account: String {
return username
}
}
//MARK: CreateableSecureStorable
extension AuthenticationData: CreateableSecureStorable {
/// Data that's saved in the keychain.
var data: [String: AnyObject] {
return ["password": password, "serverAddress": serverAddress]
}
}
//MARK: ReadableSecureStorable
extension AuthenticationData: ReadableSecureStorable {}
//MARK: DeleteableSecureStorable
extension AuthenticationData: DeleteableSecureStorable {}
|
Update tests to run map() inside a closure. | func main() -> Int {
let names = ["foo", "patatino"]
var reversedNames = names.sorted(by: {
$0 > $1 } //%self.expect('p $0', substrs=['patatino'])
//%self.expect('p $1', substrs=['foo'])
//%self.expect('frame var $0', substrs=['patatino'])
//%self.expect('frame var $1', substrs=['foo'])
)
var tinky = [1,2].map({$0 * 2})
return 0 //%self.expect('expr tinky.map({$0 * 2})', substrs=['[0] = 2', '[1] = 4'])
//%self.expect('expr [2,4].map({$0 * 2})', substrs=['[0] = 4', '[1] = 8'])
//%self.expect('expr $0', substrs=['unresolved identifier \'$0\''], error=True)
}
_ = main()
| func main() -> Int {
let names = ["foo", "patatino"]
var reversedNames = names.sorted(by: {
$0 > $1 } //%self.expect('p $0', substrs=['patatino'])
//%self.expect('p $1', substrs=['foo'])
//%self.expect('frame var $0', substrs=['patatino'])
//%self.expect('frame var $1', substrs=['foo'])
)
var tinky = [1,2].map({
$0 * 2 //%self.expect('expr [12, 14].map({$0 + 2})', substrs=['[0] = 14', '[1] = 16'])
})
return 0 //%self.expect('expr tinky.map({$0 * 2})', substrs=['[0] = 4', '[1] = 8'])
//%self.expect('expr [2,4].map({$0 * 2})', substrs=['[0] = 4', '[1] = 8'])
//%self.expect('expr $0', substrs=['unresolved identifier \'$0\''], error=True)
}
_ = main()
|
Hide bottom bar if only one item activated. | //
// YPBottomPagerView.swift
// YPImagePicker
//
// Created by Sacha DSO on 24/01/2018.
// Copyright © 2016 Yummypets. All rights reserved.
//
import UIKit
import Stevia
final class YPBottomPagerView: UIView {
var header = YPPagerMenu()
var scrollView = UIScrollView()
convenience init() {
self.init(frame: .zero)
backgroundColor = .offWhiteOrBlack
sv(
scrollView,
header
)
layout(
0,
|scrollView|,
0,
|header| ~ 44
)
if #available(iOS 11.0, *) {
header.Bottom == safeAreaLayoutGuide.Bottom
} else {
header.bottom(0)
}
header.heightConstraint?.constant = YPConfig.hidesBottomBar ? 0 : 44
clipsToBounds = false
setupScrollView()
}
private func setupScrollView() {
scrollView.clipsToBounds = false
scrollView.isPagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
}
}
| //
// YPBottomPagerView.swift
// YPImagePicker
//
// Created by Sacha DSO on 24/01/2018.
// Copyright © 2016 Yummypets. All rights reserved.
//
import UIKit
import Stevia
final class YPBottomPagerView: UIView {
var header = YPPagerMenu()
var scrollView = UIScrollView()
convenience init() {
self.init(frame: .zero)
backgroundColor = .offWhiteOrBlack
sv(
scrollView,
header
)
layout(
0,
|scrollView|,
0,
|header| ~ 44
)
if #available(iOS 11.0, *) {
header.Bottom == safeAreaLayoutGuide.Bottom
} else {
header.bottom(0)
}
header.heightConstraint?.constant = (YPConfig.hidesBottomBar || (YPConfig.screens.count == 1)) ? 0 : 44
clipsToBounds = false
setupScrollView()
}
private func setupScrollView() {
scrollView.clipsToBounds = false
scrollView.isPagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
}
}
|
Clear database if migration is required | //
// AppDelegate.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/5/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import UIKit
import Fabric
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Fabric.with([Crashlytics.self])
return true
}
}
| //
// AppDelegate.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/5/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import UIKit
import Fabric
import Crashlytics
import RealmSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Fabric.with([Crashlytics.self])
Realm.Configuration.defaultConfiguration = Realm.Configuration(
deleteRealmIfMigrationNeeded: true
)
return true
}
}
|
Create a formatter for each call. | import Foundation
public final class Configuration {
public static var headersWithBoldTrait = false
static var defaultBoldFormatter: AttributeFormatter = {
if headersWithBoldTrait {
return BoldWithShadowForHeadingFormatter()
} else {
return BoldFormatter()
}
} ()
}
| import Foundation
public final class Configuration {
public static var headersWithBoldTrait = false
static var defaultBoldFormatter: AttributeFormatter {
get {
if headersWithBoldTrait {
return BoldWithShadowForHeadingFormatter()
} else {
return BoldFormatter()
}
}
}
}
|
Add associated types to protocol | import UIKit
protocol MMenuItemProtocol
{
var icon:UIImage { get }
var order:MMenu.Order { get }
init(order:MMenu.Order)
func controller(session:MSession) -> UIViewController
}
| import UIKit
protocol MMenuItemProtocol
{
associatedtype V:ViewMain
associatedtype M:Model<Self.V>
associatedtype C:Controller<Self.V, Self.M>
var icon:UIImage { get }
var order:MMenu.Order { get }
var controller:C.Type { get }
init(order:MMenu.Order)
}
|
Fix a typo in comment. | //
// Notification.swift
// ESOcean
//
// Created by Tomohiro Kumagai on H27/04/23.
//
//
import Foundation
// MARK: - Protocol
/// All native notifications need to confirm to the protocol.
public protocol Notification : NotificationProtocol, Postable {
}
/// All notifications (without NSNotification) need to confirm to the protocol.
public protocol NotificationProtocol : AnyObject {
}
| //
// Notification.swift
// ESOcean
//
// Created by Tomohiro Kumagai on H27/04/23.
//
//
import Foundation
// MARK: - Protocol
/// All native notifications need to confirm to the protocol.
public protocol Notification : NotificationProtocol, Postable {
}
/// All notifications (without NSNotification) need to conforms to the protocol.
public protocol NotificationProtocol : AnyObject {
}
|
Update Socket test to wait for socket shutdown | //
// UDPSocketTests.swift
// WIFIAV
//
// Created by Max Odnovolyk on 3/13/17.
// Copyright © 2017 Max Odnovolyk. All rights reserved.
//
import XCTest
@testable import WIFIAV
class UDPSocketTests: XCTestCase {
override func setUp() {
super.setUp()
continueAfterFailure = false
}
func testNotListeningSocketGetsDeallocatedImmediately() {
var socket: UDPSocket? = try! UDPSocket(port: 55000)
weak var weakSocket = socket
XCTAssertNotNil(weakSocket)
socket = nil
XCTAssertNil(weakSocket)
}
func testListeningSocketGetsDeallocatedAfterShutdown() {
weak var weakSocket: Socket?
autoreleasepool {
var socket: UDPSocket? = try! UDPSocket(port: 55001)
weakSocket = socket
socket?.listen()
socket = nil
XCTAssertNotNil(weakSocket)
weakSocket?.shutdown()
}
XCTAssertNil(weakSocket)
}
}
| //
// UDPSocketTests.swift
// WIFIAV
//
// Created by Max Odnovolyk on 3/13/17.
// Copyright © 2017 Max Odnovolyk. All rights reserved.
//
import XCTest
@testable import WIFIAV
class UDPSocketTests: XCTestCase {
override func setUp() {
super.setUp()
continueAfterFailure = false
}
func testNotListeningSocketGetsDeallocatedImmediately() {
var socket: UDPSocket? = try! UDPSocket(port: 55000)
weak var weakSocket = socket
XCTAssertNotNil(weakSocket)
socket = nil
XCTAssertNil(weakSocket)
}
func testListeningSocketGetsDeallocatedAfterShutdown() {
weak var weakSocket: Socket?
var socket: UDPSocket? = try! UDPSocket(port: 55001)
weakSocket = socket
socket?.listen()
socket = nil
XCTAssertNotNil(weakSocket)
weakSocket?.shutdown()
let nullifyExpectation = expectation(description: "Wait for socket shutdown")
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
XCTAssertNil(weakSocket)
nullifyExpectation.fulfill()
}
waitForExpectations(timeout: 2)
}
}
|
Use let instead of var | struct Card {
var rank: Rank
var suit: Suit
}
extension Card: Equatable { }
func == (lhs: Card, rhs: Card) -> Bool {
return lhs.rank == rhs.rank && lhs.suit == rhs.suit
}
| struct Card {
let rank: Rank
let suit: Suit
}
extension Card: Equatable { }
func == (lhs: Card, rhs: Card) -> Bool {
return lhs.rank == rhs.rank && lhs.suit == rhs.suit
}
|
Test Unique handles Equatable Arrays. | // Copyright © 2017 Compass. All rights reserved.
import Foundation
import XCTest
@testable import Snail
class UniqueTests: XCTestCase {
func testVariableChanges() {
var events: [String?] = []
let subject = Unique<String?>(nil)
subject.asObservable().subscribe(
onNext: { string in events.append(string) }
)
subject.value = nil
subject.value = "1"
subject.value = "2"
subject.value = "2"
subject.value = "2"
XCTAssert(events[0] == "1")
XCTAssert(events[1] == "2")
XCTAssert(subject.value == "2")
XCTAssert(events.count == 2)
}
func testVariableNotifiesOnSubscribe() {
let subject = Unique("initial")
subject.value = "new"
var result: String?
subject.asObservable().subscribe(onNext: { string in
result = string
})
XCTAssertEqual("new", result)
}
func testVariableNotifiesInitialOnSubscribe() {
let subject = Unique<String?>(nil)
var result: String?
subject.asObservable().subscribe(onNext: { string in
result = string
})
XCTAssertEqual(nil, result)
}
}
| // Copyright © 2017 Compass. All rights reserved.
import Foundation
import XCTest
@testable import Snail
class UniqueTests: XCTestCase {
func testVariableChanges() {
var events: [String?] = []
let subject = Unique<String?>(nil)
subject.asObservable().subscribe(
onNext: { string in events.append(string) }
)
subject.value = nil
subject.value = "1"
subject.value = "2"
subject.value = "2"
subject.value = "2"
XCTAssert(events[0] == "1")
XCTAssert(events[1] == "2")
XCTAssert(subject.value == "2")
XCTAssert(events.count == 2)
}
func testVariableNotifiesOnSubscribe() {
let subject = Unique("initial")
subject.value = "new"
var result: String?
subject.asObservable().subscribe(onNext: { string in
result = string
})
XCTAssertEqual("new", result)
}
func testVariableNotifiesInitialOnSubscribe() {
let subject = Unique<String?>(nil)
var result: String?
subject.asObservable().subscribe(onNext: { string in
result = string
})
XCTAssertEqual(nil, result)
}
func testVariableHandlesEquatableArrays() {
var events: [[String]] = []
let subject = Unique<[String]>(["1", "2"])
subject.asObservable().subscribe(
onNext: { array in events.append(array) }
)
subject.value = ["1", "2"]
subject.value = ["2", "1"]
subject.value = ["2", "1"]
subject.value = ["1", "2"]
XCTAssert(events[0] == ["2", "1"])
XCTAssert(events[1] == ["1", "2"])
}
}
|
Use flatMap to avoid mutability | import Foundation
struct Cassette {
let name: String
let interactions: [Interaction]
init(name: String, interactions: [Interaction]) {
self.name = name
self.interactions = interactions
}
func interactionForRequest(request: NSURLRequest) -> Interaction? {
for interaction in interactions {
let r = interaction.request
// Note: We don't check headers right now
if r.HTTPMethod == request.HTTPMethod && r.URL == request.URL && r.HTTPBody == request.HTTPBody {
return interaction
}
}
return nil
}
}
extension Cassette {
var dictionary: [String: AnyObject] {
return [
"name": name,
"interactions": interactions.map { $0.dictionary }
]
}
init?(dictionary: [String: AnyObject]) {
guard let name = dictionary["name"] as? String else { return nil }
self.name = name
var interactions = [Interaction]()
if let array = dictionary["interactions"] as? [[String: AnyObject]] {
for dictionary in array {
if let interaction = Interaction(dictionary: dictionary) {
interactions.append(interaction)
}
}
}
self.interactions = interactions
}
}
| import Foundation
struct Cassette {
let name: String
let interactions: [Interaction]
init(name: String, interactions: [Interaction]) {
self.name = name
self.interactions = interactions
}
func interactionForRequest(request: NSURLRequest) -> Interaction? {
for interaction in interactions {
let r = interaction.request
// Note: We don't check headers right now
if r.HTTPMethod == request.HTTPMethod && r.URL == request.URL && r.HTTPBody == request.HTTPBody {
return interaction
}
}
return nil
}
}
extension Cassette {
var dictionary: [String: AnyObject] {
return [
"name": name,
"interactions": interactions.map { $0.dictionary }
]
}
init?(dictionary: [String: AnyObject]) {
guard let name = dictionary["name"] as? String else { return nil }
self.name = name
if let array = dictionary["interactions"] as? [[String: AnyObject]] {
interactions = array.flatMap { Interaction(dictionary: $0) }
} else {
interactions = []
}
}
}
|
Update test to use correct mode name | // 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");
}
| // 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 != \"WORK\" } { 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 != \"WORK\" } { 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");
}
|
Update default values for Menu Item | //
// Created by zen on 31/01/15.
// Copyright (c) 2015 Yalantis. All rights reserved.
//
import Foundation
import UIKit.UIImage
public struct MenuItem {
public var name: String?
public var image: UIImage
public var highlightedImage: UIImage?
public var backgroundColor = UIColor.blackColor()
public var highlightedBackgroundColor = UIColor.redColor()
}
| //
// Created by zen on 31/01/15.
// Copyright (c) 2015 Yalantis. All rights reserved.
//
import Foundation
import UIKit.UIImage
public struct MenuItem {
public var name: String?
public var image: UIImage
public var highlightedImage: UIImage?
public var backgroundColor = UIColor(red: 50.0 / 255.0, green: 49.0 / 255.0, blue: 73.0 / 255.0, alpha: 1.0)
public var highlightedBackgroundColor = UIColor(red: 1.0, green: 61.0 / 255.0, blue: 130.0 / 255.0, alpha: 1.0)
public var shadowColor = UIColor(red: 41.0 / 255.0, green: 44.0 / 255.0, blue: 69.0 / 255.0, alpha: 1.0)
}
|
Initialize `HabitsController` with view model | //
// AppDelegate.swift
// Habits
//
// Created by Julian Grosshauser on 26/09/15.
// Copyright © 2015 Julian Grosshauser. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow? = {
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
window.backgroundColor = .whiteColor()
return window
}()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let navigationController = UINavigationController(rootViewController: HabitsController())
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
return true
}
}
| //
// AppDelegate.swift
// Habits
//
// Created by Julian Grosshauser on 26/09/15.
// Copyright © 2015 Julian Grosshauser. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow? = {
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
window.backgroundColor = .whiteColor()
return window
}()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let navigationController = UINavigationController(rootViewController: HabitsController(viewModel: HabitsViewModel()))
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
return true
}
}
|
Revert "Rename news jsonNode photoUrl to imageUrl" | //
// NewsMapper.swift
// TOZ_iOS
//
// Copyright © 2017 intive. All rights reserved.
//
import Foundation
final class NewsResponseMapper: ArrayResponseMapper<NewsItem>, ResponseMapperProtocol {
static func process(_ obj: AnyObject?) throws -> [NewsItem] {
return try process(obj, mapper: { jsonNode in
guard let publishDate = jsonNode["published"] as? Int? else { return nil }
guard let title = jsonNode["title"] as? String else { return nil }
guard let contents = jsonNode["contents"] as? String else { return nil }
guard let photoUrl = jsonNode["imageUrl"] as? String? else { return nil }
var published: Date? = nil
if let publishDate = publishDate {
published = Date(timeIntervalSince1970: TimeInterval(publishDate/1000))
}
var photoURL: URL? = nil
if let photoUrl = photoUrl {
photoURL = BackendConfiguration.shared.photosURL.appendingPathComponent(photoUrl)
}
return NewsItem(title: title, contents: contents, photoUrl: photoURL, published: published)
})
}
}
| //
// NewsMapper.swift
// TOZ_iOS
//
// Copyright © 2017 intive. All rights reserved.
//
import Foundation
final class NewsResponseMapper: ArrayResponseMapper<NewsItem>, ResponseMapperProtocol {
static func process(_ obj: AnyObject?) throws -> [NewsItem] {
return try process(obj, mapper: { jsonNode in
guard let publishDate = jsonNode["published"] as? Int? else { return nil }
guard let title = jsonNode["title"] as? String else { return nil }
guard let contents = jsonNode["contents"] as? String else { return nil }
guard let photoUrl = jsonNode["photoUrl"] as? String? else { return nil }
var published: Date? = nil
if let publishDate = publishDate {
published = Date(timeIntervalSince1970: TimeInterval(publishDate/1000))
}
var photoURL: URL? = nil
if let photoUrl = photoUrl {
photoURL = BackendConfiguration.shared.photosURL.appendingPathComponent(photoUrl)
}
return NewsItem(title: title, contents: contents, photoUrl: photoURL, published: published)
})
}
}
|
Change glob to return files |
#include <builtins.swift>
#include <io.swift>
#include <files.swift>
#include <sys.swift>
//usage: stc 563-glob.swift -S=/home/zzhang/*.swift
main
{
string s[];
s = glob(argv("S"));
foreach f in s
{
printf("file: %s", f);
}
}
|
#include <builtins.swift>
#include <io.swift>
#include <files.swift>
#include <sys.swift>
//usage: stc 563-glob.swift -S=/home/zzhang/*.swift
main
{
file s[];
s = glob(argv("S"));
foreach f in s
{
printf("file: %s", filename(f));
}
}
|
Add a MARK to an extension of UINavigationBar | //
// UINavigationBar+Colors.swift
// RGUIExtension
//
// Created by RAIN on 15/11/30.
// Copyright © 2015年 Smartech. All rights reserved.
//
import UIKit
extension UINavigationBar {
/**
修改 Navigation Bar 的背景颜色
- parameter color: 提供给 Navigation Bar 的背景的 tint color
*/
static func barTintColor(color: UIColor) {
UINavigationBar.appearance().barTintColor = color
}
/**
修改 Navigation item 和 bar button item 的 tint color
- parameter color: 提供给 Navigation item 和 bar button item 的 tint color
*/
static func tintColor(color: UIColor) {
UINavigationBar.appearance().tintColor = color
}
/**
修改 Navigation Bar 的文字颜色
- parameter color: 提供给 Navigation Bar 上文字的颜色
*/
static func titleTextColor(color: UIColor) {
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: color]
}
}
| //
// UINavigationBar+Colors.swift
// RGUIExtension
//
// Created by RAIN on 15/11/30.
// Copyright © 2015年 Smartech. All rights reserved.
//
import UIKit
// MARK: Colors
extension UINavigationBar {
/**
修改 Navigation Bar 的背景颜色
- parameter color: 提供给 Navigation Bar 的背景的 tint color
*/
static func barTintColor(color: UIColor) {
UINavigationBar.appearance().barTintColor = color
}
/**
修改 Navigation item 和 bar button item 的 tint color
- parameter color: 提供给 Navigation item 和 bar button item 的 tint color
*/
static func tintColor(color: UIColor) {
UINavigationBar.appearance().tintColor = color
}
/**
修改 Navigation Bar 的文字颜色
- parameter color: 提供给 Navigation Bar 上文字的颜色
*/
static func titleTextColor(color: UIColor) {
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: color]
}
}
|
Break the Maybe declaration out into a temporary. | // Copyright © 2015 Rob Rix. All rights reserved.
extension Module {
public static var maybe: Module {
return Module("Maybe", [
Declaration.Datatype("Maybe", .Argument(.Type, {
[
"just": .Argument($0, const(.End)),
"nothing": .End
]
}))
])
}
}
import Prelude
| // Copyright © 2015 Rob Rix. All rights reserved.
extension Module {
public static var maybe: Module {
let Maybe = Declaration.Datatype("Maybe", .Argument(.Type, {
[
"just": .Argument($0, const(.End)),
"nothing": .End
]
}))
return Module("Maybe", [ Maybe ])
}
}
import Prelude
|
Add extra variadic generic test | // RUN: %target-typecheck-verify-swift -enable-experimental-variadic-generics
protocol P {}
protocol P1 {
associatedtype A... // expected-error {{associated types cannot be variadic}}
associatedtype B<U>...
// expected-error@-1 {{associated types cannot be variadic}}
// expected-error@-2 {{associated types must not have a generic parameter list}}
}
typealias Alias<T...> = (T...)
struct S1<T...> {}
struct S2<T, U...> {}
struct S3<T..., U> {}
struct S4<T...:P, U> {}
struct S5<T... :P, U> {}
struct S6<T...: P> {}
struct S7<T... : P> {}
func foo<T...>(_ x: T...) {}
func bar<T...:P>(_ x: T...) {}
func baz<T... :P>(_ x: T...) {}
func qux<T... : P>(_ x: T...) {}
func quux<T...: P>(_ x: T...) {}
func foobar<T, U, V...>(x: T, y: U, z: V...) { }
func foobaz<T, U..., V>(x: T, y: U..., z: V) { }
func fooqux<T..., U..., V...>(x: T..., y: U..., z: V...) { }
| // RUN: %target-typecheck-verify-swift -enable-experimental-variadic-generics
protocol P {}
protocol P1 {
associatedtype A... // expected-error {{associated types cannot be variadic}}
associatedtype B<U>...
// expected-error@-1 {{associated types cannot be variadic}}
// expected-error@-2 {{associated types must not have a generic parameter list}}
}
typealias Alias<T...> = (T...)
struct S1<T...> {}
struct S2<T, U...> {}
struct S3<T..., U> {}
struct S4<T...:P, U> {}
struct S5<T... :P, U> {}
struct S6<T...: P> {}
struct S7<T... : P> {}
func foo<T...>(_ x: T...) {}
func bar<T...:P>(_ x: T...) {}
func baz<T... :P>(_ x: T...) {}
func qux<T... : P>(_ x: T...) {}
func quux<T...: P>(_ x: T...) {}
func foobar<T, U, V...>(x: T, y: U, z: V...) { }
func foobaz<T, U..., V>(x: T, y: U..., z: V) { }
func fooqux<T..., U..., V...>(x: T..., y: U..., z: V...) { }
// We allow whitespace between the generic parameter and the '...', this is
// consistent with regular variadic parameters.
func withWhitespace<T ...>(_ x: T ...) -> (T ...) {}
|
Remove modifiedTime property. Add migrated property. | //
// SubscriptionCollection.swift
// Pods
//
// Created by Lim, Jennifer on 1/20/17.
//
//
/// Represents all the subscriptions with extra informations
public class SubscriptionCollection: VIMModelObject
{
// MARK: - Properties
/// Represents the uri
public var uri: String?
/// Represents the modified time
public var modifiedTime: Date?
/// Represents the subscription
public var subscription: Subscription?
// MARK: - VIMMappable
public override func getObjectMapping() -> Any
{
return ["modified_time": "modifiedTime",
"subscriptions": "subscription"]
}
public override func getClassForObjectKey(_ key: String!) -> AnyClass!
{
if key == "subscriptions"
{
return Subscription.self
}
return nil
}
}
| //
// SubscriptionCollection.swift
// Pods
//
// Created by Lim, Jennifer on 1/20/17.
//
//
/// Represents all the subscriptions with extra informations
public class SubscriptionCollection: VIMModelObject
{
// MARK: - Properties
/// Represents the uri
public var uri: String?
/// Represents the subscription
public var subscription: Subscription?
/// Represents the migration that indicates whether the user has migrated from the old system `VIMTrigger` to new new system `Localytics`.
public var migrated: NSNumber?
// MARK: - VIMMappable
public override func getObjectMapping() -> Any
{
return ["subscriptions": "subscription"]
}
public override func getClassForObjectKey(_ key: String!) -> AnyClass!
{
if key == "subscriptions"
{
return Subscription.self
}
return nil
}
}
|
Augment Test for Confusing ExpressibleByNilLiteral Case | // RUN: %target-typecheck-verify-swift
enum Hey {
case listen
}
func test() {
switch Hey.listen {
case nil: // expected-warning {{type 'Hey' is not optional, value can never be nil}}
break
default:
break
}
}
| // RUN: %target-typecheck-verify-swift
enum Hey {
case listen
}
func test() {
switch Hey.listen {
case nil: // expected-warning {{type 'Hey' is not optional, value can never be nil}}
break
default:
break
}
}
struct Nilable: ExpressibleByNilLiteral {
init(nilLiteral: ()) {}
}
func testNil() {
// N.B. A deeply confusing case as no conversion is performed on the `nil`
// literal. Instead, the match subject is converted to `Nilable?` and compared
// using ~=.
switch Nilable(nilLiteral: ()) {
case nil: // expected-warning {{type 'Nilable' is not optional, value can never be nil}}
break
default:
break
}
}
|
Fix mahjong face image in keyboard. | //
// MahjongFaceCell.swift
// Stage1st
//
// Created by Zheng Li on 2018/10/1.
// Copyright © 2018 Renaissance. All rights reserved.
//
import Alamofire
import Kingfisher
final class MahjongFaceCell: UICollectionViewCell {
let imageView = UIImageView(frame: .zero)
static let placeholderImage = UIImage(named: "MahjongFacePlaceholder")
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(imageView)
imageView.snp.makeConstraints { (make) in
make.center.equalTo(self.contentView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
self.imageView.kf.cancelDownloadTask()
}
func configure(with item: MahjongFaceInputView.Category.Item) {
imageView.kf.setImage(with: item.url, placeholder: MahjongFaceCell.placeholderImage)
imageView.snp.remakeConstraints { (make) in
make.center.equalTo(contentView)
make.width.equalTo(item.width)
make.height.equalTo(item.height)
}
}
}
| //
// MahjongFaceCell.swift
// Stage1st
//
// Created by Zheng Li on 2018/10/1.
// Copyright © 2018 Renaissance. All rights reserved.
//
import Alamofire
import Kingfisher
final class MahjongFaceCell: UICollectionViewCell {
let imageView = UIImageView(frame: .zero)
static let placeholderImage = UIImage(named: "MahjongFacePlaceholder")
override init(frame: CGRect) {
super.init(frame: frame)
imageView.contentMode = .scaleAspectFit
contentView.addSubview(imageView)
imageView.snp.makeConstraints { (make) in
make.center.equalTo(self.contentView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
self.imageView.kf.cancelDownloadTask()
}
func configure(with item: MahjongFaceInputView.Category.Item) {
imageView.kf.setImage(with: .provider(LocalFileImageDataProvider(fileURL: item.url)), placeholder: MahjongFaceCell.placeholderImage)
imageView.snp.remakeConstraints { (make) in
make.center.equalTo(contentView)
make.width.equalTo(item.width)
make.height.equalTo(item.height)
}
}
}
|
Configure the job list to take in views | //
// JobList.swift
// JenkinsiOS
//
// Created by Robert on 23.09.16.
// Copyright © 2016 MobiLab Solutions. All rights reserved.
//
import Foundation
class JobList: CustomStringConvertible{
var jobs: [Job] = []
init(data: Any) throws{
guard let json = data as? [String: AnyObject]
else { throw ParsingError.DataNotCorrectFormatError }
guard let jsonJobs = json["jobs"] as? [[String: AnyObject]]
else{ throw ParsingError.KeyMissingError(key: "jobs") }
for jsonJob in jsonJobs{
if let job = Job(json: jsonJob, minimalVersion: true){
jobs.append(job)
}
}
}
var description: String{
return "{\n" + jobs.reduce("", { (result, job) -> String in
return "\(result) Name: \(job.name), Description: \(job.description) \n"
}) + "}"
}
}
| //
// JobList.swift
// JenkinsiOS
//
// Created by Robert on 23.09.16.
// Copyright © 2016 MobiLab Solutions. All rights reserved.
//
import Foundation
class JobList: CustomStringConvertible{
var jobs: [Job] = []
var views: [View]?
//FIXME: Init with different tree
init(data: Any) throws{
guard let json = data as? [String: AnyObject]
else { throw ParsingError.DataNotCorrectFormatError }
guard let jsonJobs = json["jobs"] as? [[String: AnyObject]]
else{ throw ParsingError.KeyMissingError(key: "jobs") }
for jsonJob in jsonJobs{
if let job = Job(json: jsonJob, minimalVersion: true){
jobs.append(job)
}
}
if let jsonViews = json["views"] as? [[String: AnyObject]]{
views = []
for jsonView in jsonViews{
if let view = View(json: jsonView){
views?.append(view)
}
}
}
}
var description: String{
return "{\n" + jobs.reduce("", { (result, job) -> String in
return "\(result) Name: \(job.name), Description: \(job.description) \n"
}) + (views?.reduce("Views: ", { (result, view) -> String in
return "\(result)\(view)\n"
}) ?? "No views") + "}"
}
}
|
Add explicit target to package manifest | // swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "StringScanner"
)
| // swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "StringScanner",
targets: [
.target(
name: "StringScanner",
path: "Sources")
]
)
|
Correct the set of free variables in annotated terms. | // Copyright © 2015 Rob Rix. All rights reserved.
public enum AnnotatedTerm<Annotation>: TermContainerType {
indirect case Unroll(Annotation, Scoping<AnnotatedTerm>)
public var annotation: Annotation {
get {
return destructure.0
}
set {
self = .Unroll(newValue, out)
}
}
public var destructure: (Annotation, Scoping<AnnotatedTerm>) {
switch self {
case let .Unroll(all):
return all
}
}
// MARK: TermContainerType
public var out: Scoping<AnnotatedTerm> {
return destructure.1
}
public var freeVariables: Set<Name> {
return []
}
}
public func == <Annotation: Equatable> (left: AnnotatedTerm<Annotation>, right: AnnotatedTerm<Annotation>) -> Bool {
return left.annotation == right.annotation && Scoping.equal(==)(left.out, right.out)
}
| // Copyright © 2015 Rob Rix. All rights reserved.
public enum AnnotatedTerm<Annotation>: TermContainerType {
indirect case Unroll(Annotation, Scoping<AnnotatedTerm>)
public var annotation: Annotation {
get {
return destructure.0
}
set {
self = .Unroll(newValue, out)
}
}
public var destructure: (Annotation, Scoping<AnnotatedTerm>) {
switch self {
case let .Unroll(all):
return all
}
}
// MARK: TermContainerType
public var out: Scoping<AnnotatedTerm> {
return destructure.1
}
public var freeVariables: Set<Name> {
switch out {
case let .Identity(expression):
return expression.foldMap { $0.freeVariables }
case let .Variable(name):
return [ name ]
case let .Abstraction(name, scope):
return scope.freeVariables.subtract([ name ])
}
}
}
public func == <Annotation: Equatable> (left: AnnotatedTerm<Annotation>, right: AnnotatedTerm<Annotation>) -> Bool {
return left.annotation == right.annotation && Scoping.equal(==)(left.out, right.out)
}
|
Use NSURLSession instead of NSURLConnection | import UIKit
import DATAStack
import Sync
class Networking {
let AppNetURL = "https://api.app.net/posts/stream/global"
let dataStack: DATAStack
required init(dataStack: DATAStack) {
self.dataStack = dataStack
}
func fetchItems(completion: (NSError?) -> Void) {
if let urlAppNet = NSURL(string: AppNetURL) {
let request = NSURLRequest(URL: urlAppNet)
let operationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: operationQueue) { [unowned self] _, data, error in
if let data = data, json = (try? NSJSONSerialization.JSONObjectWithData(data,
options: NSJSONReadingOptions.MutableContainers)) as? Dictionary<String, AnyObject> {
Sync.changes(json["data"] as! Array,
inEntityNamed: "Data",
dataStack: self.dataStack,
completion: { error in
completion(error)
})
} else {
completion(error)
}
}
}
}
}
| import UIKit
import DATAStack
import Sync
class Networking {
let AppNetURL = "https://api.app.net/posts/stream/global"
let dataStack: DATAStack
required init(dataStack: DATAStack) {
self.dataStack = dataStack
}
func fetchItems(completion: (NSError?) -> Void) {
let session = NSURLSession.sharedSession()
let request = NSURLRequest(URL: NSURL(string: AppNetURL)!)
session.dataTaskWithRequest(request, completionHandler: { data, response, error in
if let data = data, json = (try? NSJSONSerialization.JSONObjectWithData(data, options: [])) as? [String: AnyObject] {
Sync.changes(json["data"] as! Array,
inEntityNamed: "Data",
dataStack: self.dataStack,
completion: { error in
completion(error)
})
} else {
completion(error)
}
}).resume()
}
}
|
Build a type constructor directly. | // Copyright © 2015 Rob Rix. All rights reserved.
extension Expression where Recur: TermType {
public static var list: Module<Recur> {
return Module([
Declaration.Data("List", .Type, {
[
"nil": .End,
"cons": .Argument($0, const(.Recursive(.End)))
]
})
])
}
}
import Prelude
| // Copyright © 2015 Rob Rix. All rights reserved.
extension Expression where Recur: TermType {
public static var list: Module<Recur> {
return Module([
Declaration.Datatype("List", .Argument(.Type, {
.End([
"nil": .End,
"cons": .Argument($0, const(.Recursive(.End)))
])
}))
])
}
}
import Prelude
|
Switch from rxwei/Parsey to kyouko-taiga/Parsey. | // swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "LogicKit",
products: [
.library(name: "LogicKit", type: .static, targets: ["LogicKit"]),
.executable(name: "lki", targets: ["lki"]),
],
dependencies: [
.package(url: "https://github.com/rxwei/Parsey", from: "2.0.0"),
],
targets: [
.target(name: "LogicKit"),
.target(name: "LogicKitParser", dependencies: ["LogicKit", "Parsey"]),
.target(name: "lki", dependencies: ["LogicKit", "LogicKitParser", "linenoise"]),
.target(name: "linenoise"),
.testTarget(name: "LogicKitTests", dependencies: ["LogicKit"]),
.testTarget(name: "LogicKitParserTests", dependencies: ["LogicKit", "LogicKitParser"]),
]
)
| // swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "LogicKit",
products: [
.library(name: "LogicKit", type: .static, targets: ["LogicKit"]),
.executable(name: "lki", targets: ["lki"]),
],
dependencies: [
.package(url: "https://github.com/kyouko-taiga/Parsey", .branch("master")),
],
targets: [
.target(name: "LogicKit"),
.target(name: "LogicKitParser", dependencies: ["LogicKit", "Parsey"]),
.target(name: "lki", dependencies: ["LogicKit", "LogicKitParser", "linenoise"]),
.target(name: "linenoise"),
.testTarget(name: "LogicKitTests", dependencies: ["LogicKit"]),
.testTarget(name: "LogicKitParserTests", dependencies: ["LogicKit", "LogicKitParser"]),
]
)
|
Add utility class for test calendars | //
// TimeUnitTestsUtilities.swift
// Tunits
//
// Created by Tom on 12/27/15.
// Copyright © 2015 CocoaPods. All rights reserved.
//
import Foundation
| //
// TimeUnitTestsUtilities.swift
// Tunits
//
// Created by Tom on 12/27/15.
// Copyright © 2015 CocoaPods. All rights reserved.
//
import Foundation
import Tunits
public class TimeUnitTestsUtilities : NSObject {
public enum Weekday : Int {
case Sunday = 1
case Monday = 2
case Tuesday = 3
case Wednesday = 4
case Thursday = 5
case Friday = 6
case Saturday = 7
}
public func timeUnitWithCalendarWithMondayAsFirstWeekday() -> TimeUnit {
return self.timeUnitWithCalendarWithFirstWeekday(Weekday.Monday);
}
public func timeUnitWithCalendarWithSundayAsFirstWeekday() -> TimeUnit {
return self.timeUnitWithCalendarWithFirstWeekday(Weekday.Sunday);
}
public func timeUnitWithCalendarWithFirstWeekday(weekday : Weekday) -> TimeUnit {
let tunit = TimeUnit()
tunit.calendar = self.calendarWithFirstWeekday(weekday)
return tunit
}
public func calendarWithSundayAsFirstWeekday() -> NSCalendar {
return self.calendarWithFirstWeekday(Weekday.Sunday)
}
public func calendarWithMondayAsFirstWeekday() -> NSCalendar {
return self.calendarWithFirstWeekday(Weekday.Monday)
}
public func calendarWithFirstWeekday(weekday: Weekday) -> NSCalendar {
let calendar = NSCalendar.currentCalendar()
calendar.firstWeekday = weekday.rawValue
return calendar
}
} |
Add a little animation on large button press | import UIKit
@IBDesignable
class RoundedCornerButton: UIButton {
@IBInspectable
var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.noIntrinsicMetric, height: 45)
}
}
| import UIKit
@IBDesignable
class RoundedCornerButton: UIButton {
@IBInspectable
var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.noIntrinsicMetric, height: 45)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
transitionToPressedState()
super.touchesBegan(touches, with: event)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
transitionToUnpressedState()
super.touchesEnded(touches, with: event)
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
transitionToUnpressedState()
super.touchesCancelled(touches, with: event)
}
private func transitionToPressedState() {
let scaleFactor: CGFloat = 0.95
let scaleTransform = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor)
swapTransform(to: scaleTransform)
}
private func transitionToUnpressedState() {
swapTransform(to: .identity)
}
private func swapTransform(to transform: CGAffineTransform) {
UIView.animate(withDuration: 0.15,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: 0,
options: .beginFromCurrentState,
animations: {
self.layer.setAffineTransform(transform)
})
}
}
|
Remove deprecated use of Range(start:end:) | //
// StringExtensions.swift
// BlueCap
//
// Created by Troy Stribling on 6/29/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import Foundation
public extension String {
public var floatValue : Float {
return (self as NSString).floatValue
}
public func dataFromHexString() -> NSData {
var bytes = [UInt8]()
for i in 0..<(self.characters.count/2) {
let stringBytes = self.substringWithRange(Range(start:self.startIndex.advancedBy(2*i), end:self.startIndex.advancedBy(2*i+2)))
let byte = strtol((stringBytes as NSString).UTF8String, nil, 16)
bytes.append(UInt8(byte))
}
return NSData(bytes:bytes, length:bytes.count)
}
} | //
// StringExtensions.swift
// BlueCap
//
// Created by Troy Stribling on 6/29/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import Foundation
public extension String {
public var floatValue : Float {
return (self as NSString).floatValue
}
public func dataFromHexString() -> NSData {
var bytes = [UInt8]()
for i in 0..<(self.characters.count/2) {
let range = self.startIndex.advancedBy(2*i)..<self.startIndex.advancedBy(2*i+2)
let stringBytes = self.substringWithRange(range)
let byte = strtol((stringBytes as NSString).UTF8String, nil, 16)
bytes.append(UInt8(byte))
}
return NSData(bytes:bytes, length:bytes.count)
}
} |
Revert "[test] Remove copy-pasted XFAIL line" | // RUN: %target-swift-ide-test -syntax-coloring -source-filename %s | %FileCheck %s
// RUN: %target-swift-ide-test -syntax-coloring -typecheck -source-filename %s | %FileCheck %s
// CHECK: <kw>let</kw> x = <str>"""
// CHECK-NEXT: This is an unterminated
// CHECK-NEXT: \( "multiline" )
// CHECK-NEXT: string followed by code
// CHECK-NEXT: ""
// CHECK-NEXT: func foo() {}
// CHECK-NEXT: </str>
let x = """
This is an unterminated
\( "multiline" )
string followed by code
""
func foo() {}
| // RUN: %target-swift-ide-test -syntax-coloring -source-filename %s | %FileCheck %s
// RUN: %target-swift-ide-test -syntax-coloring -typecheck -source-filename %s | %FileCheck %s
// XFAIL: broken_std_regex
// CHECK: <kw>let</kw> x = <str>"""
// CHECK-NEXT: This is an unterminated
// CHECK-NEXT: \( "multiline" )
// CHECK-NEXT: string followed by code
// CHECK-NEXT: ""
// CHECK-NEXT: func foo() {}
// CHECK-NEXT: </str>
let x = """
This is an unterminated
\( "multiline" )
string followed by code
""
func foo() {}
|
Remove implicit animation on selecting row | import SwiftUI
struct SelectableRow<ID, Label>: View where ID: Identifiable, Label: View {
var tag: ID?
@Binding var selection: ID?
var content: () -> Label
var body: some View {
Button {
withAnimation {
selection = tag
}
} label: {
HStack {
content()
Spacer()
if selection?.id == tag?.id {
Image(systemName: "checkmark")
.font(.caption.bold())
.foregroundColor(.blue)
}
}
.contentShape(Rectangle())
}
.buttonStyle(.plain)
}
}
| import SwiftUI
struct SelectableRow<ID, Label>: View where ID: Identifiable, Label: View {
var tag: ID?
@Binding var selection: ID?
var content: () -> Label
var body: some View {
Button {
selection = tag
} label: {
HStack {
content()
Spacer()
if selection?.id == tag?.id {
Image(systemName: "checkmark")
.font(.caption.bold())
.foregroundColor(.blue)
}
}
.contentShape(Rectangle())
}
.buttonStyle(.plain)
}
}
|
Make sure a test that has never run on any platform continues to never run on any platforms. | // RUN: rm -rf %t
// RUN: mkdir %t
// RUN: %swift -target x86_64-unknown-linux-gnu -emit-module -parse-stdlib -o %t -module-name Empty -module-link-name swiftEmpty %S/../Inputs/empty.swift
// RUN: %swift -target x86_64-unknown-linux-gnu %s -I %t -parse-stdlib -disable-objc-interop -module-name main -emit-ir -o - | FileCheck %s
// REQUIRES: X86
import Empty
// Check that on ELF targets autolinking information is emitted and marked
// as used.
// CHECK-DAG: @_swift1_autolink_entries = private constant [13 x i8] c"-lswiftEmpty\00", section ".swift1_autolink_entries", align 8
// CHECK-DAG: @llvm.used = appending global [1 x i8*] [i8* getelementptr inbounds ([13 x i8], [13 x i8]* @_swift1_autolink_entries, i32 0, i32 0)], section "llvm.metadata", align 8
| // RUN: rm -rf %t
// RUN: mkdir %t
// RUN: %swift -target x86_64-unknown-linux-gnu -emit-module -parse-stdlib -o %t -module-name Empty -module-link-name swiftEmpty %S/../Inputs/empty.swift
// RUN: %swift -target x86_64-unknown-linux-gnu %s -I %t -parse-stdlib -disable-objc-interop -module-name main -emit-ir -o - | FileCheck %s
// REQUIRES: SR2116
// REQUIRES: X86
import Empty
// Check that on ELF targets autolinking information is emitted and marked
// as used.
// CHECK-DAG: @_swift1_autolink_entries = private constant [13 x i8] c"-lswiftEmpty\00", section ".swift1_autolink_entries", align 8
// CHECK-DAG: @llvm.used = appending global [1 x i8*] [i8* getelementptr inbounds ([13 x i8], [13 x i8]* @_swift1_autolink_entries, i32 0, i32 0)], section "llvm.metadata", align 8
|
Make 'satisfy' parser, have 'any' and 'token' use it. | //
// Parser.swift
// FootlessParser
//
// Released under the MIT License (MIT), http://opensource.org/licenses/MIT
//
// Copyright (c) 2015 NotTooBad Software. All rights reserved.
//
import Result
import Runes
// TODO: Implement ParserError
public typealias ParserError = String
public struct Parser <Token, Output> {
public let parse: ParserInput<Token> -> Result<(output: Output, nextinput: ParserInput<Token>), ParserError>
}
/** Match a single token. */
public func token <T: Equatable> (token: T) -> Parser<T, T> {
return Parser { input in
return input.read(expect: toString(token)) >>- { next in
if next.head == token {
return .success(output:token, nextinput:next.tail)
} else {
return .failure("expected '\(token)', got '\(next.head)'.")
}
}
}
}
/** Return whatever the next token is. */
public func any <T> () -> Parser<T, T> {
return Parser { input in
return input.read(expect: "anything") >>- { .success(output:$0.head, nextinput:$0.tail) }
}
}
| //
// Parser.swift
// FootlessParser
//
// Released under the MIT License (MIT), http://opensource.org/licenses/MIT
//
// Copyright (c) 2015 NotTooBad Software. All rights reserved.
//
import Result
import Runes
// TODO: Implement ParserError
public typealias ParserError = String
public struct Parser <Token, Output> {
public let parse: ParserInput<Token> -> Result<(output: Output, nextinput: ParserInput<Token>), ParserError>
}
/** Succeeds iff 'condition' is true. Returns the token it read. */
public func satisfy <T> (# expect: String, condition: T -> Bool) -> Parser<T, T> {
return Parser { input in
return input.read(expect: expect) >>- { next in
if condition(next.head) {
return .success(output:next.head, nextinput:next.tail)
} else {
return .failure("expected '\(expect)', got '\(next.head)'.")
}
}
}
}
/** Match a single token. */
public func token <T: Equatable> (token: T) -> Parser<T, T> {
return satisfy(expect: toString(token)) { $0 == token }
}
/** Return whatever the next token is. */
public func any <T> () -> Parser<T, T> {
return satisfy(expect: "anything") { T in true }
}
|
Add some logging so we can see when requests are made | //
// FetchIssuesOperation.swift
// FiveCalls
//
// Created by Ben Scheirman on 1/31/17.
// Copyright © 2017 5calls. All rights reserved.
//
import Foundation
class FetchIssuesOperation : BaseOperation {
let zipCode: String?
var httpResponse: HTTPURLResponse?
var error: Error?
var issuesList: IssuesList?
init(zipCode: String?) {
self.zipCode = zipCode
}
lazy var sessionConfiguration = URLSessionConfiguration.default
lazy var session: URLSession = { return URLSession(configuration: self.sessionConfiguration) }()
override func execute() {
let url = URL(string: "https://5calls.org/issues/")!
let task = session.dataTask(with: url) { (data, response, error) in
if let e = error {
print("Error fetching issues: \(e.localizedDescription)")
} else {
let http = response as! HTTPURLResponse
self.httpResponse = http
if http.statusCode == 200 {
do {
try self.parseIssues(data: data!)
} catch let e {
print("Error parsing issues: \(e.localizedDescription)")
}
} else {
print("Received HTTP \(http.statusCode)")
}
}
self.finish()
}
task.resume()
}
private func parseIssues(data: Data) throws {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! JSONDictionary
issuesList = IssuesList(dictionary: json)
}
}
| //
// FetchIssuesOperation.swift
// FiveCalls
//
// Created by Ben Scheirman on 1/31/17.
// Copyright © 2017 5calls. All rights reserved.
//
import Foundation
class FetchIssuesOperation : BaseOperation {
let zipCode: String?
var httpResponse: HTTPURLResponse?
var error: Error?
var issuesList: IssuesList?
init(zipCode: String?) {
self.zipCode = zipCode
}
lazy var sessionConfiguration = URLSessionConfiguration.default
lazy var session: URLSession = { return URLSession(configuration: self.sessionConfiguration) }()
override func execute() {
let url = URL(string: "https://5calls.org/issues/")!
let task = session.dataTask(with: url) { (data, response, error) in
if let e = error {
print("Error fetching issues: \(e.localizedDescription)")
} else {
let http = response as! HTTPURLResponse
print("HTTP \(http.statusCode)")
self.httpResponse = http
if http.statusCode == 200 {
do {
try self.parseIssues(data: data!)
} catch let e {
print("Error parsing issues: \(e.localizedDescription)")
}
} else {
print("Received HTTP \(http.statusCode)")
}
}
self.finish()
}
print("Fetching issues (zip: \(zipCode ?? ""))...")
task.resume()
}
private func parseIssues(data: Data) throws {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! JSONDictionary
issuesList = IssuesList(dictionary: json)
}
}
|
Add a definitions-only module constructor. | // Copyright © 2015 Rob Rix. All rights reserved.
public struct Module<Recur> {
public typealias Environment = Expression<Recur>.Environment
public typealias Context = Expression<Recur>.Context
public init<D: SequenceType, S: SequenceType where D.Generator.Element == Module, S.Generator.Element == Binding<Recur>>(_ dependencies: D, _ definitions: S) {
self.dependencies = Array(dependencies)
self.definitions = Array(definitions)
}
public let dependencies: [Module]
public let definitions: [Binding<Recur>]
public var environment: Environment {
let dependencies = lazy(self.dependencies).map { $0.environment }
let definitions = lazy(self.definitions).map { [$0.symbol: $0.value] }
return dependencies
.concat(definitions)
.reduce(Environment(), combine: +)
}
public var context: Context {
let dependencies = lazy(self.dependencies).map { $0.context }
let definitions = lazy(self.definitions).map { [$0.symbol: $0.type] }
return dependencies
.concat(definitions)
.reduce(Context(), combine: +)
}
}
| // Copyright © 2015 Rob Rix. All rights reserved.
public struct Module<Recur> {
public typealias Environment = Expression<Recur>.Environment
public typealias Context = Expression<Recur>.Context
public init<D: SequenceType, S: SequenceType where D.Generator.Element == Module, S.Generator.Element == Binding<Recur>>(_ dependencies: D, _ definitions: S) {
self.dependencies = Array(dependencies)
self.definitions = Array(definitions)
}
public init<S: SequenceType where S.Generator.Element == Binding<Recur>>(_ definitions: S) {
self.init([], definitions)
}
public let dependencies: [Module]
public let definitions: [Binding<Recur>]
public var environment: Environment {
let dependencies = lazy(self.dependencies).map { $0.environment }
let definitions = lazy(self.definitions).map { [$0.symbol: $0.value] }
return dependencies
.concat(definitions)
.reduce(Environment(), combine: +)
}
public var context: Context {
let dependencies = lazy(self.dependencies).map { $0.context }
let definitions = lazy(self.definitions).map { [$0.symbol: $0.type] }
return dependencies
.concat(definitions)
.reduce(Context(), combine: +)
}
}
|
Fix issue with scroll inset for hidden nav bar | //
// DezignableHiddenNavigationBar.swift
// Pods
//
// Created by Daniel van Hoesel on 02-03-16.
//
//
import UIKit
public protocol DezignableHiddenNavigationBar {
var navigationBarHidden: Bool { get set }
}
public extension DezignableHiddenNavigationBar where Self: UIViewController {
public func setupHiddenNavigationBar() {
self.navigationController?.navigationBarHidden = self.navigationBarHidden
self.automaticallyAdjustsScrollViewInsets = false
}
public func resetHiddenNavigationBar() {
self.navigationController?.navigationBarHidden = false
self.automaticallyAdjustsScrollViewInsets = true
}
} | //
// DezignableHiddenNavigationBar.swift
// Pods
//
// Created by Daniel van Hoesel on 02-03-16.
//
//
import UIKit
public protocol DezignableHiddenNavigationBar {
var navigationBarHidden: Bool { get set }
}
public extension DezignableHiddenNavigationBar where Self: UIViewController {
public func setupHiddenNavigationBar() {
self.navigationController?.navigationBarHidden = self.navigationBarHidden
self.automaticallyAdjustsScrollViewInsets = !self.navigationBarHidden
}
public func resetHiddenNavigationBar() {
self.navigationController?.navigationBarHidden = false
self.automaticallyAdjustsScrollViewInsets = true
}
} |
Use a function for one of the fixtures. | // Copyright (c) 2015 Rob Rix. All rights reserved.
final class SubstitutionTests: XCTestCase {
let (a, b) = (Variable(), Variable())
let (c, d) = (Variable(), Variable())
var t1: Type { return Type(c) }
var t2: Type { return Type(d) }
func testCompositionIsIdempotentIfOperandsAreIdempotent() {
let s1 = Substitution(elements: [ a: t1 ])
let s2 = Substitution(elements: [ b: t2 ])
assertEqual(s1.compose(s2).occurringVariables, Set())
assertEqual(s2.compose(s1).occurringVariables, Set())
}
func testCompositionIsNotIdempotentIfLeftOperandIsNotIdempotent() {
let s1 = Substitution(elements: [ a: Type(a) ])
let s2 = Substitution(elements: [ b: t2 ])
assertEqual(s1.compose(s2).occurringVariables, Set(a))
}
func testCompositionIsNotIdempotentIfRightOperandIsNotIdempotent() {
let s1 = Substitution(elements: [ a: t1 ])
let s2 = Substitution(elements: [ b: Type(b) ])
assertEqual(s1.compose(s2).occurringVariables, Set(b))
}
}
// MARK: - Imports
import Manifold
import Set
import XCTest
| // Copyright (c) 2015 Rob Rix. All rights reserved.
final class SubstitutionTests: XCTestCase {
let (a, b) = (Variable(), Variable())
let (c, d) = (Variable(), Variable())
var t1: Type { return Type(c) }
var t2: Type { return Type(function: Type(d), Type(d)) }
func testCompositionIsIdempotentIfOperandsAreIdempotent() {
let s1 = Substitution(elements: [ a: t1 ])
let s2 = Substitution(elements: [ b: t2 ])
assertEqual(s1.compose(s2).occurringVariables, Set())
assertEqual(s2.compose(s1).occurringVariables, Set())
}
func testCompositionIsNotIdempotentIfLeftOperandIsNotIdempotent() {
let s1 = Substitution(elements: [ a: Type(a) ])
let s2 = Substitution(elements: [ b: t2 ])
assertEqual(s1.compose(s2).occurringVariables, Set(a))
}
func testCompositionIsNotIdempotentIfRightOperandIsNotIdempotent() {
let s1 = Substitution(elements: [ a: t1 ])
let s2 = Substitution(elements: [ b: Type(b) ])
assertEqual(s1.compose(s2).occurringVariables, Set(b))
}
}
// MARK: - Imports
import Manifold
import Set
import XCTest
|
Allow TortoiseCharmer to use default value on initialization to prevent run-time crash | import CoreGraphics
public class GraphicsCanvas: Canvas {
private var tortoiseCharmer = TortoiseCharmer(tortoiseCount: 0)
private let graphicsContext: GraphicsContext
public init(size: CGSize, context: CGContext) {
#if os(iOS)
let isUIViewContext = true
#else
let isUIViewContext = false
#endif
self.graphicsContext = GraphicsContext(size: size,
cgContext: context,
backgroundColor: color?.cgColor,
isUIViewContext: isUIViewContext)
}
// MARK: - Canvas Protocol
public func drawing(drawingBlock: @escaping (Tortoise) -> Void) {
tortoiseCharmer.initialize(tortoiseCount: 1)
drawingBlock(tortoiseCharmer.tortoises[0])
tortoiseCharmer.charm(with: graphicsContext, toFrame: nil)
}
public func drawingWithTortoises(count: Int, drawingBlock: @escaping ([Tortoise]) -> Void) {
tortoiseCharmer.initialize(tortoiseCount: count)
drawingBlock(tortoiseCharmer.tortoises)
tortoiseCharmer.charm(with: graphicsContext, toFrame: nil)
}
public var color: Color?
}
| import CoreGraphics
public class GraphicsCanvas: Canvas {
private var tortoiseCharmer = TortoiseCharmer()
private let graphicsContext: GraphicsContext
public init(size: CGSize, context: CGContext) {
#if os(iOS)
let isUIViewContext = true
#else
let isUIViewContext = false
#endif
self.graphicsContext = GraphicsContext(size: size,
cgContext: context,
backgroundColor: color?.cgColor,
isUIViewContext: isUIViewContext)
}
// MARK: - Canvas Protocol
public func drawing(drawingBlock: @escaping (Tortoise) -> Void) {
tortoiseCharmer.initialize(tortoiseCount: 1)
drawingBlock(tortoiseCharmer.tortoises[0])
tortoiseCharmer.charm(with: graphicsContext, toFrame: nil)
}
public func drawingWithTortoises(count: Int, drawingBlock: @escaping ([Tortoise]) -> Void) {
tortoiseCharmer.initialize(tortoiseCount: count)
drawingBlock(tortoiseCharmer.tortoises)
tortoiseCharmer.charm(with: graphicsContext, toFrame: nil)
}
public var color: Color?
}
|
Fix typo in NSBundle path | import Foundation
extension Bundle {
@objc public class var aztecBundle: Bundle {
let defaultBundle = Bundle(for: EditorView.self)
// If installed with CocoaPods, resources will be in WordPress-Aztec-iOS.bundle
if let bundleURL = defaultBundle.resourceURL,
let resourceBundle = Bundle(url: bundleURL.appendingPathComponent("WordPress-Aztec-iOS")) {
return resourceBundle
}
// Otherwise, the default bundle is used for resources
return defaultBundle
}
}
| import Foundation
extension Bundle {
@objc public class var aztecBundle: Bundle {
let defaultBundle = Bundle(for: EditorView.self)
// If installed with CocoaPods, resources will be in WordPress-Aztec-iOS.bundle
if let bundleURL = defaultBundle.resourceURL,
let resourceBundle = Bundle(url: bundleURL.appendingPathComponent("WordPress-Aztec-iOS.bundle")) {
return resourceBundle
}
// Otherwise, the default bundle is used for resources
return defaultBundle
}
}
|
Fix license in Swift+Path file | //
// String+Path.swift
// MobileLocalizationConverter
//
// Created by Sébastien Duperron on 23/05/2016.
// Copyright © 2016 Sébastien Duperron. All rights reserved.
//
import Foundation
extension String {
func appending(pathComponent component: String) -> String {
return (self as NSString).stringByAppendingPathComponent(component)
}
}
| //
// String+Path.swift
//
// Created by Sébastien Duperron on 23/05/2016.
// Copyright © 2016 Sébastien Duperron
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import Foundation
extension String {
func appending(pathComponent component: String) -> String {
return (self as NSString).stringByAppendingPathComponent(component)
}
}
|
Correct the order of System Font Weights. | import Foundation
public enum SystemFontWeight: String {
public static let allValues: [SystemFontWeight] = [
.ultralight, .thin, .light, .regular, .medium, .semibold, .bold, .heavy, .black
]
case ultralight
case thin
case light
case regular
case medium
case semibold
case bold
case heavy
case black
public var name: String {
switch self {
case .ultralight:
return "UIFontWeightUltraLight"
case .thin:
return "UIFontWeightThin"
case .light:
return "UIFontWeightLight"
case .regular:
return "UIFontWeightRegular"
case .medium:
return "UIFontWeightMedium"
case .semibold:
return "UIFontWeightSemibold"
case .bold:
return "UIFontWeightBold"
case .heavy:
return "UIFontWeightHeavy"
case .black:
return "UIFontWeightBlack"
}
}
#if ReactantRuntime
public var value: CGFloat {
switch self {
case .ultralight:
return UIFontWeightUltraLight
case .thin:
return UIFontWeightThin
case .light:
return UIFontWeightLight
case .regular:
return UIFontWeightRegular
case .medium:
return UIFontWeightMedium
case .semibold:
return UIFontWeightSemibold
case .bold:
return UIFontWeightBold
case .heavy:
return UIFontWeightHeavy
case .black:
return UIFontWeightBlack
}
}
#endif
}
| import Foundation
public enum SystemFontWeight: String {
public static let allValues: [SystemFontWeight] = [
.thin, .ultralight, .light, .regular, .medium, .semibold, .bold, .heavy, .black
]
case ultralight
case thin
case light
case regular
case medium
case semibold
case bold
case heavy
case black
public var name: String {
switch self {
case .thin:
return "UIFontWeightThin"
case .ultralight:
return "UIFontWeightUltraLight"
case .light:
return "UIFontWeightLight"
case .regular:
return "UIFontWeightRegular"
case .medium:
return "UIFontWeightMedium"
case .semibold:
return "UIFontWeightSemibold"
case .bold:
return "UIFontWeightBold"
case .heavy:
return "UIFontWeightHeavy"
case .black:
return "UIFontWeightBlack"
}
}
#if ReactantRuntime
public var value: CGFloat {
switch self {
case .thin:
return UIFontWeightThin
case .ultralight:
return UIFontWeightUltraLight
case .light:
return UIFontWeightLight
case .regular:
return UIFontWeightRegular
case .medium:
return UIFontWeightMedium
case .semibold:
return UIFontWeightSemibold
case .bold:
return UIFontWeightBold
case .heavy:
return UIFontWeightHeavy
case .black:
return UIFontWeightBlack
}
}
#endif
}
|
Add enum special case for ';' test | import Foundation;
println("Hello, World!")
// Class examples
class lowerCamelCase {
var x: String = "hello";
let b = 2;
func demo()
{
for var x = 0; ; {
print(x);
};
if temperatureInFahrenheit <= 32 {
println("It's very cold. Consider wearing a scarf.");
} else if temperatureInFahrenheit >= 86 {
println("It's really warm. Don't forget to wear sunscreen.");
} else {
println("It's not that cold. Wear a t-shirt.");
}
};
};
| import Foundation;
println("Hello, World!")
enum CompassPoint {
case North;
case South;
case East;
case West;
};
// Class examples
class lowerCamelCase {
var x: String = "hello";
let b = 2;
func demo()
{
for var x = 0; ; {
print(x);
};
if temperatureInFahrenheit <= 32 {
println("It's very cold. Consider wearing a scarf.");
} else if temperatureInFahrenheit >= 86 {
println("It's really warm. Don't forget to wear sunscreen.");
} else {
println("It's not that cold. Wear a t-shirt.");
}
};
};
|
Expand the Branches/Type test out a little. | // Copyright © 2015 Rob Rix. All rights reserved.
final class TagTests: XCTestCase {
func testTagTypechecksAsFunction() {
let expected = Expression.FunctionType([ Enumeration, Term(.Type(0)) ])
let actual = Tag.out.checkType(expected, context: context)
assert(actual.left, ==, nil)
assert(actual.right, ==, expected)
}
func testBranchesProducesAType() {
assert(Branches[Empty, Term(.lambda(Tag[Empty], const(Term(.UnitType))))].out.checkType(.Type(0), context: context).right, ==, .Type(0))
}
func testBranchesOfEmptyEnumerationIsUnitType() {
assert(Branches[Empty, Term(.lambda(Tag[Empty], const(Term(.BooleanType))))].out.evaluate(environment), ==, .UnitType)
}
}
private let Enumeration = Term("Enumeration")
private let Branches = Term("Branches")
private let `nil` = Term("[]")
private let Tag = Term("Tag")
private let Empty = `nil`[Term("String")]
private let module = Expression<Term>.tag
private let context = module.context
private let environment = module.environment
import Assertions
@testable import Manifold
import Prelude
import XCTest
| // Copyright © 2015 Rob Rix. All rights reserved.
final class TagTests: XCTestCase {
func testTagTypechecksAsFunction() {
let expected = Expression.FunctionType([ Enumeration, Term(.Type(0)) ])
let actual = Tag.out.checkType(expected, context: context)
assert(actual.left, ==, nil)
assert(actual.right, ==, expected)
}
func testBranchesProducesAType() {
let branches = Branches[Empty, Term(.lambda(Tag[Empty], const(Term(.UnitType))))].out.checkType(.Type(0), context: context)
assert(branches.left, ==, nil)
assert(branches.right, ==, .Type(0))
}
func testBranchesOfEmptyEnumerationIsUnitType() {
assert(Branches[Empty, Term(.lambda(Tag[Empty], const(Term(.BooleanType))))].out.evaluate(environment), ==, .UnitType)
}
}
private let Enumeration = Term("Enumeration")
private let Branches = Term("Branches")
private let `nil` = Term("[]")
private let Tag = Term("Tag")
private let Empty = `nil`[Term("String")]
private let module = Expression<Term>.tag
private let context = module.context
private let environment = module.environment
import Assertions
@testable import Manifold
import Prelude
import XCTest
|
Hide Next / Previous button by default | //
// SwiftRadio-Settings.swift
// Swift Radio
//
// Created by Matthew Fecher on 7/2/15.
// Copyright (c) 2015 MatthewFecher.com. All rights reserved.
//
import Foundation
//**************************************
// GENERAL SETTINGS
//**************************************
// Display Comments
let kDebugLog = true
//**************************************
// STATION JSON
//**************************************
// If this is set to "true", it will use the JSON file in the app
// Set it to "false" to use the JSON file at the stationDataURL
let useLocalStations = true
let stationDataURL = "http://yoururl.com/json/stations.json"
//**************************************
// SEARCH BAR
//**************************************
// Set this to "true" to enable the search bar
let searchable = false
//**************************************
// NEXT / PREVIOUS BUTTONS
//**************************************
let hideNextPreviousButtons = false
| //
// SwiftRadio-Settings.swift
// Swift Radio
//
// Created by Matthew Fecher on 7/2/15.
// Copyright (c) 2015 MatthewFecher.com. All rights reserved.
//
import Foundation
//**************************************
// GENERAL SETTINGS
//**************************************
// Display Comments
let kDebugLog = true
//**************************************
// STATION JSON
//**************************************
// If this is set to "true", it will use the JSON file in the app
// Set it to "false" to use the JSON file at the stationDataURL
let useLocalStations = true
let stationDataURL = "http://yoururl.com/json/stations.json"
//**************************************
// SEARCH BAR
//**************************************
// Set this to "true" to enable the search bar
let searchable = false
//**************************************
// NEXT / PREVIOUS BUTTONS
//**************************************
let hideNextPreviousButtons = true
|
Disable throttle in debug mode | #if os(iOS)
import UIKit
#endif
public class NetworkActivityIndicator {
/**
The shared instance.
*/
public static let sharedIndicator = NetworkActivityIndicator()
/**
The number of activities in progress.
*/
internal var activitiesCount = 0
/**
A Boolean value that turns an indicator of network activity on or off.
Specify true if the app should show network activity and false if it should not. The default value is false. A spinning indicator in the status bar shows network activity. Multiple calls to visible cause an internal counter to take care of persisting the number of times this method has being called.
*/
public var visible: Bool = false {
didSet {
if visible {
self.activitiesCount++
} else {
self.activitiesCount--
}
if self.activitiesCount < 0 {
self.activitiesCount = 0
}
#if os(iOS)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
UIApplication.sharedApplication().networkActivityIndicatorVisible = (self.activitiesCount > 0)
})
#endif
}
}
}
| #if os(iOS)
import UIKit
#endif
public class NetworkActivityIndicator {
/**
The shared instance.
*/
public static let sharedIndicator = NetworkActivityIndicator()
/**
The number of activities in progress.
*/
internal var activitiesCount = 0
/**
A Boolean value that turns an indicator of network activity on or off.
Specify true if the app should show network activity and false if it should not. The default value is false. A spinning indicator in the status bar shows network activity. Multiple calls to visible cause an internal counter to take care of persisting the number of times this method has being called.
*/
public var visible: Bool = false {
didSet {
if visible {
self.activitiesCount++
} else {
self.activitiesCount--
}
if self.activitiesCount < 0 {
self.activitiesCount = 0
}
#if os(iOS)
#if DEBUG
dispatch_async(dispatch_get_main_queue()) {
self.update()
}
#else
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
self.update()
})
#endif
#endif
}
}
private func update() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = (self.activitiesCount > 0)
}
}
|
Revert "Updated for Swift 4" | // 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: "LittleCMS",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "LittleCMS",
targets: ["LittleCMS"]),
],
dependencies: [
.package(url: "https://github.com/PureSwift/CLCMS.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: "LittleCMS",
dependencies: ["CLCMS"]),
.testTarget(
name: "LittleCMSTests",
dependencies: ["LittleCMS"]),
]
)
| // 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: "LittleCMS",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "LittleCMS",
targets: ["LittleCMS"]),
],
dependencies: [
.package(url: "https://github.com/PureSwift/CLCMS.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: "LittleCMS",
dependencies: []),
.testTarget(
name: "LittleCMSTests",
dependencies: ["LittleCMS"]),
]
)
|
Remove the default implementation of _ObjectiveCBridgeable._unconditionallyBridgeFromObjectiveC. | //===--- NSValue.swift - Bridging things in NSValue -----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension NSRange : _ObjectiveCBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public func _bridgeToObjectiveC() -> NSValue {
return NSValue(range: self)
}
public static func _forceBridgeFromObjectiveC(
x: NSValue,
result: inout NSRange?
) {
result = x.rangeValue
}
public static func _conditionallyBridgeFromObjectiveC(
x: NSValue,
result: inout NSRange?
) -> Bool {
self._forceBridgeFromObjectiveC(x, result: &result)
return true
}
}
| //===--- NSValue.swift - Bridging things in NSValue -----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension NSRange : _ObjectiveCBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public func _bridgeToObjectiveC() -> NSValue {
return NSValue(range: self)
}
public static func _forceBridgeFromObjectiveC(
x: NSValue,
result: inout NSRange?
) {
result = x.rangeValue
}
public static func _conditionallyBridgeFromObjectiveC(
x: NSValue,
result: inout NSRange?
) -> Bool {
self._forceBridgeFromObjectiveC(x, result: &result)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(source: NSValue?)
-> NSRange {
var result: NSRange?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
|
Add a PathContaining protocol for expanding paths to the source file's directory | import Foundation
import JSONUtilities
import PathKit
import Yams
extension Project {
public init(path: Path) throws {
let basePath = path.parent()
let template = try Spec(filename: path.lastComponent, basePath: basePath)
try self.init(spec: template, basePath: basePath)
}
}
| import Foundation
import JSONUtilities
import PathKit
import Yams
extension Project {
public init(path: Path) throws {
let basePath = path.parent()
let template = try Spec(filename: path.lastComponent, basePath: basePath)
try self.init(spec: template, basePath: basePath)
}
}
protocol PathContaining {
associatedtype JSONSourceType
static func expandPaths(for source: JSONSourceType, relativeTo path: Path) -> JSONSourceType
}
extension PathContaining {
static func expandStringPaths(from source: JSONDictionary, forKey key: String, relativeTo path: Path) -> JSONDictionary {
var result = source
if let source = result[key] as? String {
result[key] = (path + source).string
} else if let source = result[key] as? [String] {
result[key] = source.map { (path + $0).string }
} else if let source = result[key] as? [String: String] {
result[key] = source.mapValues { (path + $0).string }
}
return result
}
static func expandChildPaths<T: PathContaining>(from source: JSONDictionary, forKey key: String, relativeTo path: Path, type: T.Type) -> JSONDictionary {
var result = source
if let source = result[key] as? T.JSONSourceType {
result[key] = T.expandPaths(for: source, relativeTo: path)
} else if let source = result[key] as? [T.JSONSourceType] {
result[key] = source.map { T.expandPaths(for: $0, relativeTo: path) }
} else if let source = result[key] as? [String: T.JSONSourceType] {
result[key] = source.mapValues { T.expandPaths(for: $0, relativeTo: path) }
}
return result
}
static func expandChildPaths<T: PathContaining>(from source: JSONDictionary, forPotentialKeys keys: [String], relativeTo path: Path, type: T.Type) -> JSONDictionary {
var result = source
for key in keys {
result = expandChildPaths(from: result, forKey: key, relativeTo: path, type: type)
}
return result
}
}
|
Define standard implementation of the Orderable protocol | //
// Ordinable+FirebaseModel.swift
// FireRecord
//
// Created by Victor Alisson on 25/09/17.
//
import FirebaseCommunity
extension Orderable where Self: FirebaseModel {
public static func order(byProperty property: String) -> Self.Type {
Self.fireRecordReference = Self.classPath.queryOrdered(byChild: property) as? DatabaseReference
return self
}
}
| //
// Ordinable+FirebaseModel.swift
// FireRecord
//
// Created by Victor Alisson on 25/09/17.
//
import FirebaseCommunity
extension Orderable where Self: FirebaseModel {
public static func order(byProperty property: String) -> Self.Type {
Self.fireRecordQuery = Self.classPath.queryOrdered(byChild: property) as? DatabaseQuery
return self
}
}
|
Fix warning about discarding result | //
// ViewController.swift
// ELReachabilityExample
//
// Created by Sam Grover on 8/13/15.
// Copyright © 2015 WalmartLabs. All rights reserved.
//
import UIKit
import ELReachability
class ViewController: UIViewController {
let theInternets: NetworkStatus?
required init?(coder aDecoder: NSCoder) {
theInternets = NetworkStatus.networkStatusForInternetConnection()
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Set up a callback
theInternets?.startNetworkStatusMonitoring { status in
guard let connection = status.connection else {
print("Internet is not reachable")
return
}
switch connection {
case .cellular:
print("Internet is reachable via cellular conneciton")
case .wifi:
print("Internet is reachable via WiFi conneciton")
}
}
}
@IBAction func checkNetworkStatus() {
guard let theInternets = theInternets else {
return
}
guard let connection = theInternets.connection else {
print("[Synchronous] Internet is not reachable")
return
}
switch connection {
case .cellular:
print("[Synchronous] Internet is reachable via cellular conneciton")
case .wifi:
print("[Synchronous] Internet is reachable via WiFi conneciton")
}
}
}
| //
// ViewController.swift
// ELReachabilityExample
//
// Created by Sam Grover on 8/13/15.
// Copyright © 2015 WalmartLabs. All rights reserved.
//
import UIKit
import ELReachability
class ViewController: UIViewController {
let theInternets: NetworkStatus?
required init?(coder aDecoder: NSCoder) {
theInternets = NetworkStatus.networkStatusForInternetConnection()
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Set up a callback
_ = theInternets?.startNetworkStatusMonitoring { status in
guard let connection = status.connection else {
print("Internet is not reachable")
return
}
switch connection {
case .cellular:
print("Internet is reachable via cellular conneciton")
case .wifi:
print("Internet is reachable via WiFi conneciton")
}
}
}
@IBAction func checkNetworkStatus() {
guard let theInternets = theInternets else {
return
}
guard let connection = theInternets.connection else {
print("[Synchronous] Internet is not reachable")
return
}
switch connection {
case .cellular:
print("[Synchronous] Internet is reachable via cellular conneciton")
case .wifi:
print("[Synchronous] Internet is reachable via WiFi conneciton")
}
}
}
|
Implement `type` in terms of `destructure`. | // Copyright © 2015 Rob Rix. All rights reserved.
public enum Elaborated<Term: TermType>: TermContainerType {
indirect case Unroll(Term, Expression<Elaborated>)
/// Construct an elaborated term by coiteration.
public static func coiterate(elaborate: Term throws -> Expression<Term>)(_ seed: Term) rethrows -> Elaborated {
return try .Unroll(seed, elaborate(seed).map { try coiterate(elaborate)($0) })
}
public var type: Term {
switch self {
case let .Unroll(type, _):
return type
}
}
public var term: Term {
return Term(term: self)
}
public var destructure: (Term, Expression<Elaborated>) {
switch self {
case let .Unroll(all):
return all
}
}
// MARK: TermContainerType
public var out: Expression<Elaborated> {
switch self {
case let .Unroll(_, term):
return term
}
}
}
| // Copyright © 2015 Rob Rix. All rights reserved.
public enum Elaborated<Term: TermType>: TermContainerType {
indirect case Unroll(Term, Expression<Elaborated>)
/// Construct an elaborated term by coiteration.
public static func coiterate(elaborate: Term throws -> Expression<Term>)(_ seed: Term) rethrows -> Elaborated {
return try .Unroll(seed, elaborate(seed).map { try coiterate(elaborate)($0) })
}
public var type: Term {
return destructure.0
}
public var term: Term {
return Term(term: self)
}
public var destructure: (Term, Expression<Elaborated>) {
switch self {
case let .Unroll(all):
return all
}
}
// MARK: TermContainerType
public var out: Expression<Elaborated> {
switch self {
case let .Unroll(_, term):
return term
}
}
}
|
Add equality and hash value capability. | //
// Atom.swift
// IMVS
//
// Created by Allistair Crossley on 06/07/2014.
// Copyright (c) 2014 Allistair Crossley. All rights reserved.
//
import Foundation
class Atom {
var id: String = ""
var name: String = ""
var residue: String = ""
var chain: String = ""
var element: String = ""
var position = Point3D()
var valence: Float = 0.0
var remoteness: String = "" // A, B, G, D, E, Z, H
init(id: String, name: String, residue: String, chain: String, element: String, x: Float, y: Float, z: Float, remoteness: String) {
self.id = id
self.name = name
self.residue = residue
self.chain = chain
self.element = element
position.x = x
position.y = y
position.z = z
self.remoteness = remoteness
}
} | //
// Atom.swift
// IMVS
//
// Created by Allistair Crossley on 06/07/2014.
// Copyright (c) 2014 Allistair Crossley. All rights reserved.
//
import Foundation
class Atom : Hashable {
var id: String = ""
var name: String = ""
var residue: String = ""
var chain: String = ""
var element: String = ""
var position = Point3D()
var valence: Float = 0.0
var remoteness: String = "" // A, B, G, D, E, Z, H
var hashValue : Int {
get {
return "\(self.position.x)\(self.position.y)\(self.position.z)".hashValue
}
}
init(id: String, name: String, residue: String, chain: String, element: String, x: Float, y: Float, z: Float, remoteness: String) {
self.id = id
self.name = name
self.residue = residue
self.chain = chain
self.element = element
position.x = x
position.y = y
position.z = z
self.remoteness = remoteness
}
}
func ==(lhs: Atom, rhs: Atom) -> Bool {
return lhs.hashValue == rhs.hashValue
} |
Test >>- over right values. | // Copyright (c) 2014 Rob Rix. All rights reserved.
import Either
import Prelude
import XCTest
final class EitherTests: XCTestCase {
let left = Either<Int, String>.left(4)
let right = Either<Int, String>.right("four")
func isFull<T>(string: String) -> Either<T, Bool> {
return .right(!string.isEmpty)
}
// MARK: - either
func testEitherExtractsFromLeft() {
let value = left.either(id, countElements)
XCTAssertEqual(value, 4)
}
func testEitherExtractsFromRight() {
let value = right.either(toString, id)
XCTAssertEqual(value, "four")
}
// MARK: - map
func testMapIgnoresLeftValues() {
let result = left.map(const(5)).either(id, id)
XCTAssertEqual(result, 4)
}
func testMapAppliesToRightValues() {
let result = right.map(const(5)).either(id, id)
XCTAssertEqual(result, 5)
}
// MARK: - >>-
func testFlatMapRetypesLeftValues() {
let result = (left >>- isFull).either(id, const(0))
XCTAssertEqual(result, 4)
}
}
| // Copyright (c) 2014 Rob Rix. All rights reserved.
import Either
import Prelude
import XCTest
final class EitherTests: XCTestCase {
let left = Either<Int, String>.left(4)
let right = Either<Int, String>.right("four")
func isFull<T>(string: String) -> Either<T, Bool> {
return .right(!string.isEmpty)
}
// MARK: - either
func testEitherExtractsFromLeft() {
let value = left.either(id, countElements)
XCTAssertEqual(value, 4)
}
func testEitherExtractsFromRight() {
let value = right.either(toString, id)
XCTAssertEqual(value, "four")
}
// MARK: - map
func testMapIgnoresLeftValues() {
let result = left.map(const(5)).either(id, id)
XCTAssertEqual(result, 4)
}
func testMapAppliesToRightValues() {
let result = right.map(const(5)).either(id, id)
XCTAssertEqual(result, 5)
}
// MARK: - >>-
func testFlatMapRetypesLeftValues() {
let result = (left >>- isFull).either(id, const(0))
XCTAssertEqual(result, 4)
}
func testFlatMapAppliesItsRightOperandToRightValues() {
let result = (right >>- isFull).either(const(false), id)
XCTAssert(result)
}
}
|
Disable selecting and editing of about attributed string views. | //
// SettingsAttributedStringView.swift
// NetNewsWire-iOS
//
// Created by Maurice Parker on 9/16/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import SwiftUI
struct SettingsAttributedStringView: UIViewRepresentable {
let string: NSAttributedString
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.attributedText = string
textView.adjustsFontForContentSizeCategory = true
textView.translatesAutoresizingMaskIntoConstraints = false
textView.font = .preferredFont(forTextStyle: .body)
textView.textColor = UIColor.label
textView.backgroundColor = UIColor.secondarySystemGroupedBackground
return textView
}
func updateUIView(_ textView: UITextView, context: Context) {
}
}
| //
// SettingsAttributedStringView.swift
// NetNewsWire-iOS
//
// Created by Maurice Parker on 9/16/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import SwiftUI
struct SettingsAttributedStringView: UIViewRepresentable {
let string: NSAttributedString
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.attributedText = string
textView.translatesAutoresizingMaskIntoConstraints = false
textView.adjustsFontForContentSizeCategory = true
textView.font = .preferredFont(forTextStyle: .body)
textView.textColor = UIColor.label
textView.backgroundColor = UIColor.secondarySystemGroupedBackground
textView.isEditable = false
textView.isSelectable = false
return textView
}
func updateUIView(_ textView: UITextView, context: Context) {
}
}
|
Use GH flavoured MD extensions for web view | //
// MDWebViewController.swift
// Markdown
//
// Created by Boris Bügling on 01/12/15.
// Copyright © 2015 Contentful GmbH. All rights reserved.
//
import MMMarkdown
import WebKit
class MDWebViewController: UIViewController {
convenience init() {
self.init(nibName: nil, bundle: nil)
self.tabBarItem = UITabBarItem(title: "WebView", image: UIImage(named: "webView"), tag: 0)
}
override func viewDidLoad() {
super.viewDidLoad()
let webView = WKWebView(frame: view.bounds)
view.addSubview(webView)
client.fetchEntry("4bJdF7zhwkwcWq202gmkuM").1.next { (entry) in
if let markdown = entry.fields["body"] as? String {
do {
let html = try MMMarkdown.HTMLStringWithMarkdown(markdown)
webView.loadHTMLString(html, baseURL: nil)
} catch let error {
showError(error, self)
}
}
}.error { (error) in
showError(error, self)
}
}
}
| //
// MDWebViewController.swift
// Markdown
//
// Created by Boris Bügling on 01/12/15.
// Copyright © 2015 Contentful GmbH. All rights reserved.
//
import MMMarkdown
import WebKit
class MDWebViewController: UIViewController {
convenience init() {
self.init(nibName: nil, bundle: nil)
self.tabBarItem = UITabBarItem(title: "WebView", image: UIImage(named: "webView"), tag: 0)
}
override func viewDidLoad() {
super.viewDidLoad()
let webView = WKWebView(frame: view.bounds)
view.addSubview(webView)
webView.scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: tabBarController?.tabBar.frame.size.height ?? 0, right: 0)
webView.scrollView.scrollIndicatorInsets = webView.scrollView.contentInset
client.fetchEntry("4bJdF7zhwkwcWq202gmkuM").1.next { (entry) in
if let markdown = entry.fields["body"] as? String {
do {
let html = try MMMarkdown.HTMLStringWithMarkdown(markdown, extensions: MMMarkdownExtensions.GitHubFlavored)
webView.loadHTMLString(html, baseURL: nil)
} catch let error {
showError(error, self)
}
}
}.error { (error) in
showError(error, self)
}
}
}
|
Remove unnecessary activity response types | //
// ActivityResponse.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** The model that defines the actions that can be taken for a given Activity entry */
public class ActivityResponse: JSONEncodable {
public enum ActivityResponseType: String {
case ConnectionRequestAccept = "connection_request_accept"
case ConnectionRequestDecline = "connection_request_decline"
case ConnectionAcceptedView = "connection_accepted_view"
case MatchSuggestedAccept = "match_suggested_accept"
case MatchSuggestedDecline = "match_suggested_decline"
case MatchAcceptedView = "match_accepted_view"
case DateSuggestedAccept = "date_suggested_accept"
case DateSuggestedSuggest = "date_suggested_suggest"
case DateAcceptedView = "date_accepted_view"
case MessageReceivedView = "message_received_view"
}
/** The text to show when presenting the response */
public var text: String?
/** The different types of responses to activities */
public var activityResponseType: ActivityResponseType?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["text"] = self.text
nillableDictionary["activity_response_type"] = self.activityResponseType?.rawValue
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
| //
// ActivityResponse.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** The model that defines the actions that can be taken for a given Activity entry */
public class ActivityResponse: JSONEncodable {
public enum ActivityResponseType: String {
case ConnectionRequestAccept = "connection_request_accept"
case ConnectionRequestDecline = "connection_request_decline"
case MatchSuggestedAccept = "match_suggested_accept"
case MatchSuggestedDecline = "match_suggested_decline"
case DateSuggestedAccept = "date_suggested_accept"
case DateSuggestedSuggest = "date_suggested_suggest"
case MessageReceivedView = "message_received_view"
}
/** The text to show when presenting the response */
public var text: String?
/** The different types of responses to activities */
public var activityResponseType: ActivityResponseType?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["text"] = self.text
nillableDictionary["activity_response_type"] = self.activityResponseType?.rawValue
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
|
Convert hit point to viewForClearTouches coordinate system | //
// ClearContainerView.swift
// SlideOutable
//
// Created by Domas Nutautas on 20/05/16.
// Copyright © 2016 Domas Nutautas. All rights reserved.
//
import UIKit
// MARK: - ContainterView
///
/// Passes touches if background is clear and point is not inside one of its subviews
///
open class ClearContainerView: UIView {
open weak var viewForClearTouches: UIView?
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let superHit = super.hitTest(point, with: event)
guard backgroundColor == nil || backgroundColor == .clear else { return superHit }
return self == superHit ? viewForClearTouches?.hitTest(point, with: event) : superHit
}
}
| //
// ClearContainerView.swift
// SlideOutable
//
// Created by Domas Nutautas on 20/05/16.
// Copyright © 2016 Domas Nutautas. All rights reserved.
//
import UIKit
// MARK: - ContainterView
///
/// Passes touches if background is clear and point is not inside one of its subviews
///
open class ClearContainerView: UIView {
open weak var viewForClearTouches: UIView?
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let superHit = super.hitTest(point, with: event)
guard
backgroundColor == nil || backgroundColor == .clear,
self == superHit
else { return superHit }
return viewForClearTouches?.hitTest(convert(point, to: viewForClearTouches), with: event)
}
}
|
Make error message more user friendly | //
// Created by Christopher Trott on 10/22/15.
// Copyright © 2015 twocentstudios. All rights reserved.
//
import Foundation
public enum EventError : ErrorType {
case UnderlyingError(error: NSError)
case InvalidResponse
case ImageURLMissing
case StreamURLMissing
case UnknownError
func localizedDescription() -> String {
switch self {
case .InvalidResponse:
return "The server returned an invalid response.".l10()
case .StreamURLMissing:
return "The stream's URL could not be found.".l10()
case .ImageURLMissing:
return "The stream's image URL could not be found.".l10()
case .UnderlyingError(let e):
return e.localizedDescription
default:
return "An unknown error occurred. Please try again.".l10()
}
}
} | //
// Created by Christopher Trott on 10/22/15.
// Copyright © 2015 twocentstudios. All rights reserved.
//
import Foundation
public enum EventError : ErrorType {
case UnderlyingError(error: NSError)
case InvalidResponse
case ImageURLMissing
case StreamURLMissing
case UnknownError
func localizedDescription() -> String {
switch self {
case .InvalidResponse:
return "The server returned an invalid response.".l10()
case .StreamURLMissing:
return "This stream is currently offline. Please try again later.".l10()
case .ImageURLMissing:
return "The stream's image URL could not be found.".l10()
case .UnderlyingError(let e):
return e.localizedDescription
default:
return "An unknown error occurred. Please try again.".l10()
}
}
} |
Refactor to loadImageNamed. 8 tests still passing. | //
// FuelGaugeView.swift
// FuelGaugeKit
//
// Created by Ron Lisle on 3/19/15.
// Copyright (c) 2015 Ron Lisle. All rights reserved.
//
import UIKit
class FuelGaugeView: UIView {
var backgroundImage:UIImageView!
var needleImage:UIImageView!
override func layoutSubviews() {
super.layoutSubviews()
if backgroundImage == nil {
backgroundImage = createSubviewWithImageNamed("FuelGaugeBG")
}
if needleImage == nil {
needleImage = createSubviewWithImageNamed("FuelGaugeNeedle")
}
}
func createSubviewWithImageNamed(name: String) -> UIImageView {
let newImageView = createImageViewWithImageNamed(name)
addSubview(newImageView)
return newImageView
}
func createImageViewWithImageNamed(name: String) -> UIImageView {
let newImageView = UIImageView()
newImageView.frame = self.bounds
newImageView.image = UIImage(named: name, inBundle: NSBundle(forClass: FuelGaugeView.self), compatibleWithTraitCollection: nil)
return newImageView
}
}
| //
// FuelGaugeView.swift
// FuelGaugeKit
//
// Created by Ron Lisle on 3/19/15.
// Copyright (c) 2015 Ron Lisle. All rights reserved.
//
import UIKit
class FuelGaugeView: UIView {
var backgroundImage:UIImageView!
var needleImage:UIImageView!
override func layoutSubviews() {
super.layoutSubviews()
if backgroundImage == nil {
backgroundImage = createSubviewWithImageNamed("FuelGaugeBG")
}
if needleImage == nil {
needleImage = createSubviewWithImageNamed("FuelGaugeNeedle")
}
}
func createSubviewWithImageNamed(name: String) -> UIImageView {
let newImageView = createImageViewWithImageNamed(name)
addSubview(newImageView)
return newImageView
}
func createImageViewWithImageNamed(name: String) -> UIImageView {
let newImageView = UIImageView()
newImageView.frame = self.bounds
newImageView.image = loadImageNamed(name)
return newImageView
}
func loadImageNamed(name: String) -> UIImage? {
let newImage = UIImage(named: name, inBundle: NSBundle(forClass: FuelGaugeView.self), compatibleWithTraitCollection: nil)
return newImage
}
}
|
Remove unnecessary @testable import of Swinject. | //
// Container+SwinjectStoryboardSpec.swift
// Swinject
//
// Created by Yoichi Tagaya on 2/27/16.
// Copyright © 2016 Swinject Contributors. All rights reserved.
//
import Quick
import Nimble
@testable import Swinject
#if os(iOS) || os(OSX) || os(tvOS)
class Container_SwinjectStoryboardSpec: QuickSpec {
override func spec() {
var container: Container!
beforeEach {
container = Container()
}
describe("CustomStringConvertible") {
it("describes a registration with storyboard option.") {
let controllerType = String(Container.Controller.self) // "UIViewController" for iOS/tvOS, "AnyObject" for OSX.
container.registerForStoryboard(AnimalViewController.self) { r, c in }
expect(container.description) ==
"[\n"
+ " { Service: \(controllerType), Storyboard: SwinjectStoryboardTests.AnimalViewController, "
+ "Factory: (ResolverType, \(controllerType)) -> \(controllerType), ObjectScope: Graph, InitCompleted: Specified }\n"
+ "]"
}
}
}
}
#endif
| //
// 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 missing newline to the end. | #!/usr/bin/env swiftshell
import SwiftShell
for line in open("../shorttext.txt").lines() {
// Do something with each line
println(line)
} | #!/usr/bin/env swiftshell
import SwiftShell
for line in open("../shorttext.txt").lines() {
// Do something with each line
println(line)
}
|
Fix to create view snapshot | //
// UIView+SnapshotImage.swift
// View2ViewTransitionExample
//
// Created by naru on 2016/08/29.
// Copyright © 2016年 naru. All rights reserved.
//
import UIKit
public extension UIView {
public func snapshotImage() -> UIImage? {
let size: CGSize = CGSize(width: floor(self.frame.size.width), height: floor(self.frame.size.height))
UIGraphicsBeginImageContextWithOptions(size, true, 0.0)
if let context: CGContext = UIGraphicsGetCurrentContext() {
self.layer.render(in: context)
}
let snapshot: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return snapshot
}
}
| //
// UIView+SnapshotImage.swift
// View2ViewTransitionExample
//
// Created by naru on 2016/08/29.
// Copyright © 2016年 naru. All rights reserved.
//
import UIKit
public extension UIView {
public func snapshotImage() -> UIImage? {
let size: CGSize = CGSize(width: floor(self.frame.size.width), height: floor(self.frame.size.height))
UIGraphicsBeginImageContextWithOptions(size, true, 0.0)
self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
let snapshot: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return snapshot
}
}
|
Update public database query property | import FirebaseCommunity
import HandyJSON
open class FireRecord: FirebaseModel {
public var key: String?
public static var fireRecordReference: DatabaseReference?
static var fireRecordQuery: DatabaseQuery?
required public init() {}
public func mapping(mapper: HelpingMapper) {
mapper >>> key
mapper >>> FireRecord.fireRecordReference
mapper >>> FireRecord.fireRecordQuery
}
}
| import FirebaseCommunity
import HandyJSON
open class FireRecord: FirebaseModel {
public var key: String?
public static var fireRecordReference: DatabaseReference?
public static var fireRecordQuery: DatabaseQuery?
required public init() {}
public func mapping(mapper: HelpingMapper) {
mapper >>> key
mapper >>> FireRecord.fireRecordReference
mapper >>> FireRecord.fireRecordQuery
}
}
|
Use latest levels of SwiftyJSON and Kitura-Net | import PackageDescription
#if os(Linux)
let swiftyJsonUrl = "https://github.com/IBM-Swift/SwiftyJSON.git"
let swiftyJsonVersion = 3
#else
let swiftyJsonUrl = "https://github.com/SwiftyJSON/SwiftyJSON.git"
let swiftyJsonVersion = 2
#endif
let package = Package(
name: "zosconnectforswift",
targets: [],
dependencies: [
.Package(url: swiftyJsonUrl, majorVersion: swiftyJsonVersion),
.Package(url: "https://github.com/IBM-Swift/Kitura-net",
majorVersion: 0, minor: 5),
]
)
| import PackageDescription
#if os(Linux)
let swiftyJsonUrl = "https://github.com/IBM-Swift/SwiftyJSON.git"
let swiftyJsonVersion = 3
#else
let swiftyJsonUrl = "https://github.com/SwiftyJSON/SwiftyJSON.git"
let swiftyJsonVersion = 2
#endif
let package = Package(
name: "zosconnectforswift",
targets: [],
dependencies: [
.Package(url: "https://github.com/IBM-Swift/SwiftyJSON.git", majorVersion: 7),
.Package(url: "https://github.com/IBM-Swift/Kitura-net",
majorVersion: 0, minor: 13),
]
)
|
Upgrade package manifest to Swift 4 | //
// Package.swift
// CoreTensor
//
// Copyright 2016-2017 Richard Wei.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import PackageDescription
let package = Package(
name: "CoreTensor",
targets: [
Target(name: "CoreTensor"),
Target(name: "RankedTensor", dependencies: ["CoreTensor"]),
],
dependencies: [
]
)
| // swift-tools-version:4.0
//
// Package.swift
// CoreTensor
//
// Copyright 2016-2017 Richard Wei.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import PackageDescription
let package = Package(
name: "CoreTensor",
targets: [
.target(name: "CoreTensor"),
.target(name: "RankedTensor", dependencies: ["CoreTensor"]),
],
swiftLanguageVersions: [ 4 ]
)
|
Add test for jukebox observing | //
// EveryoneGetsToDJTests.swift
// EveryoneGetsToDJTests
//
// Created by Patrick O'Leary on 6/7/17.
// Copyright © 2017 Patrick O'Leary. All rights reserved.
//
import XCTest
@testable import EveryoneGetsToDJ
class EveryoneGetsToDJTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| //
// EveryoneGetsToDJTests.swift
// EveryoneGetsToDJTests
//
// Created by Patrick O'Leary on 6/7/17.
// Copyright © 2017 Patrick O'Leary. All rights reserved.
//
import XCTest
@testable import EveryoneGetsToDJ
import PromiseKit
class EveryoneGetsToDJTests: 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 testObserveTracks() {
let firExpectation = expectation(description: "expect return from observe function")
let firManager = FirebaseManager.sharedInstance
firManager.observe(jukebox: "-KnZjudS6PoKyQFaQU5M").then { jukebox -> String in
XCTAssertTrue(jukebox.tracks.count == 1, "Should observe one track within test jukebox")
firExpectation.fulfill()
return "Done"
}.catch { error in
}
waitForExpectations(timeout: 20) { (error) in
if let error = error {
print("Error: \(error.localizedDescription)")
}
}
}
}
|
Add test searching with empty string | import XCTest
@testable import worldcities
class TestModelListSearch:XCTestCase
{
private let kWaitExpectation:TimeInterval = 90
func testSearchItems()
{
let itemsExpectation:XCTestExpectation = expectation(
description:"items loaded")
let modelList:ModelList = ModelList()
modelList.loadItems
{
itemsExpectation.fulfill()
}
waitForExpectations(timeout:kWaitExpectation)
{ [weak self] (error:Error?) in
}
}
}
| import XCTest
@testable import worldcities
class TestModelListSearch:XCTestCase
{
private let kStringEmpty:String = ""
private let kWaitExpectation:TimeInterval = 90
func testSearchItems()
{
let itemsExpectation:XCTestExpectation = expectation(
description:"items loaded")
let modelList:ModelList = ModelList()
modelList.loadItems
{
itemsExpectation.fulfill()
}
waitForExpectations(timeout:kWaitExpectation)
{ [weak self] (error:Error?) in
self?.inputEmpty(modelList:modelList)
}
}
//MARK: private
private func inputEmpty(modelList:ModelList)
{
let foundItems:[ModelListItem] = modelList.searchItems(
forInput:kStringEmpty)
let foundCount:Int = foundItems.count
let totalCount:Int = modelList.items.count
XCTAssertEqual(
foundCount,
totalCount,
"failed searching with empty string")
}
}
|
Make the content of a captured stream public | //
// OutputByteStream.swift
// SwiftCLI
//
// Created by Jake Heiser on 9/11/17.
//
import Foundation
public protocol OutputByteStream {
func output(_ content: String)
}
public class StdoutStream: OutputByteStream {
public init() {}
public func output(_ content: String) {
print(content)
}
}
public class StderrStream: OutputByteStream {
public init() {}
public func output(_ content: String) {
printError(content)
}
}
public class NullStream: OutputByteStream {
public init() {}
public func output(_ content: String) {}
}
public class FileStream: OutputByteStream {
let handle: FileHandle
public init?(path: String) {
guard let handle = FileHandle(forWritingAtPath: path) else {
return nil
}
handle.seekToEndOfFile()
self.handle = handle
}
public func output(_ content: String) {
guard let data = (content + "\n").data(using: .utf8) else {
fatalError("Couldn't output content: \(content)")
}
handle.write(data)
}
deinit {
handle.closeFile()
}
}
public class CaptureStream: OutputByteStream {
private(set) var content: String = ""
public init() {}
public func output(_ content: String) {
self.content += content + "\n"
}
}
public func <<(stream: OutputByteStream, text: String) {
stream.output(text)
}
| //
// OutputByteStream.swift
// SwiftCLI
//
// Created by Jake Heiser on 9/11/17.
//
import Foundation
public protocol OutputByteStream {
func output(_ content: String)
}
public class StdoutStream: OutputByteStream {
public init() {}
public func output(_ content: String) {
print(content)
}
}
public class StderrStream: OutputByteStream {
public init() {}
public func output(_ content: String) {
printError(content)
}
}
public class NullStream: OutputByteStream {
public init() {}
public func output(_ content: String) {}
}
public class FileStream: OutputByteStream {
let handle: FileHandle
public init?(path: String) {
guard let handle = FileHandle(forWritingAtPath: path) else {
return nil
}
handle.seekToEndOfFile()
self.handle = handle
}
public func output(_ content: String) {
guard let data = (content + "\n").data(using: .utf8) else {
fatalError("Couldn't output content: \(content)")
}
handle.write(data)
}
deinit {
handle.closeFile()
}
}
public class CaptureStream: OutputByteStream {
public private(set) var content: String = ""
public init() {}
public func output(_ content: String) {
self.content += content + "\n"
}
}
public func <<(stream: OutputByteStream, text: String) {
stream.output(text)
}
|
Update participant role mapping with new role identifiers | //
// Appearance.swift
// JumuNordost
//
// Created by Martin Richter on 21/02/16.
// Copyright © 2016 Martin Richter. All rights reserved.
//
import Argo
import Curry
enum ParticipantRole: String {
case Soloist = "S"
case Ensemblist = "E"
case Accompanist = "B"
}
struct Appearance {
let participantName: String
let participantRole: ParticipantRole
let instrument: String
}
// MARK: - Decodable
extension ParticipantRole: Decodable {}
extension Appearance: Decodable {
static func decode(json: JSON) -> Decoded<Appearance> {
return curry(self.init)
<^> json <| "participant_name"
<*> json <| "participant_role"
<*> json <| "instrument_name"
}
}
| //
// Appearance.swift
// JumuNordost
//
// Created by Martin Richter on 21/02/16.
// Copyright © 2016 Martin Richter. All rights reserved.
//
import Argo
import Curry
enum ParticipantRole: String {
case Soloist = "soloist"
case Ensemblist = "ensemblist"
case Accompanist = "accompanist"
}
struct Appearance {
let participantName: String
let participantRole: ParticipantRole
let instrument: String
}
// MARK: - Decodable
extension ParticipantRole: Decodable {}
extension Appearance: Decodable {
static func decode(json: JSON) -> Decoded<Appearance> {
return curry(self.init)
<^> json <| "participant_name"
<*> json <| "participant_role"
<*> json <| "instrument_name"
}
}
|
Remove option from test that did not do anything. | // RUN: %target-build-swift -target arm64-apple-ios8.0 -target-cpu cyclone \
// RUN: -O -S %s -parse-as-library | \
// RUN: FileCheck --check-prefix=TBI %s
// RUN: %target-build-swift -target arm64-apple-ios8.0 -target-cpu cyclone \
// RUN: -Xcc -Xclang -Xcc -target-feature -Xcc -Xclang -Xcc -tbi \
// RUN: -O -S %s -parse-as-library | \
// RUN: FileCheck --check-prefix=NO_TBI %s
// REQUIRES: executable_test
// REQUIRES: CPU=arm64, OS=ios
// Verify that TBI is on by default in Swift.
func f(i: Int) -> Int8 {
let j = i & 0xff_ffff_ffff_ffff
// TBI-NOT: and
// NO_TBI: and
let p = UnsafeMutablePointer<Int8>(bitPattern: j)
return p[0]
}
| // RUN: %target-build-swift -target arm64-apple-ios8.0 -target-cpu cyclone \
// RUN: -O -S %s -parse-as-library | \
// RUN: FileCheck --check-prefix=TBI %s
// RUN: %target-build-swift -target arm64-apple-ios8.0 -target-cpu cyclone \
// RUN: -O -S %s -parse-as-library | \
// RUN: FileCheck --check-prefix=NO_TBI %s
// REQUIRES: executable_test
// REQUIRES: CPU=arm64, OS=ios
// Verify that TBI is on by default in Swift.
func f(i: Int) -> Int8 {
let j = i & 0xff_ffff_ffff_ffff
// TBI-NOT: and
// NO_TBI: and
let p = UnsafeMutablePointer<Int8>(bitPattern: j)
return p[0]
}
|
Fix the dependency versions to use semantic version numbers | // swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "Bond",
platforms: [
.macOS(.v10_11), .iOS(.v8), .tvOS(.v9)
],
products: [
.library(name: "Bond", targets: ["Bond"])
],
dependencies: [
.package(url: "https://github.com/DeclarativeHub/ReactiveKit.git", .upToNextMajor(from: "3.14")),
.package(url: "https://github.com/tonyarnold/Differ.git", .upToNextMajor(from: "1.4"))
],
targets: [
.target(name: "BNDProtocolProxyBase"),
.target(name: "Bond", dependencies: ["BNDProtocolProxyBase", "ReactiveKit", "Differ"]),
.testTarget(name: "BondTests", dependencies: ["Bond", "ReactiveKit"])
]
)
| // swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "Bond",
platforms: [
.macOS(.v10_11), .iOS(.v8), .tvOS(.v9)
],
products: [
.library(name: "Bond", targets: ["Bond"])
],
dependencies: [
.package(url: "https://github.com/DeclarativeHub/ReactiveKit.git", .upToNextMajor(from: "3.14.2")),
.package(url: "https://github.com/tonyarnold/Differ.git", .upToNextMajor(from: "1.4.3"))
],
targets: [
.target(name: "BNDProtocolProxyBase"),
.target(name: "Bond", dependencies: ["BNDProtocolProxyBase", "ReactiveKit", "Differ"]),
.testTarget(name: "BondTests", dependencies: ["Bond", "ReactiveKit"])
]
)
|
Remove constraints to generic arguments | //
// RACHelpers.swift
// TodaysReactiveMenu
//
// Created by Steffen Damtoft Sommer on 25/05/15.
// Copyright (c) 2015 steffendsommer. All rights reserved.
//
import Foundation
import ReactiveCocoa
public func ignoreNil<T: AnyObject, E: Any>(signalProducer: SignalProducer<T?, E>) -> SignalProducer<T?, E> {
return signalProducer
|> filter { value in
value != nil
}
}
public func ignoreError<T: Any, E: ErrorType>(signalProducer: SignalProducer<T, E>) -> SignalProducer<T, NoError> {
return signalProducer
|> catch { _ in
SignalProducer<T, NoError>.empty
}
}
public func merge<T, E: ErrorType>(signals: [SignalProducer<T, E>]) -> SignalProducer<T, E> {
return SignalProducer<SignalProducer<T, E>, E>(values: signals)
|> flatten(FlattenStrategy.Merge)
} | //
// RACHelpers.swift
// TodaysReactiveMenu
//
// Created by Steffen Damtoft Sommer on 25/05/15.
// Copyright (c) 2015 steffendsommer. All rights reserved.
//
import ReactiveCocoa
public func ignoreNil<T: AnyObject, E: Any>(signalProducer: SignalProducer<T?, E>) -> SignalProducer<T?, E> {
return signalProducer
|> filter { value in
value != nil
}
}
public func ignoreError<T: Any, E: ErrorType>(signalProducer: SignalProducer<T, E>) -> SignalProducer<T, NoError> {
public func ignoreError<T, E>(signalProducer: SignalProducer<T, E>) -> SignalProducer<T, NoError> {
return signalProducer
|> catch { _ in
SignalProducer<T, NoError>.empty
}
}
public func merge<T, E>(signals: [SignalProducer<T, E>]) -> SignalProducer<T, E> {
return SignalProducer<SignalProducer<T, E>, E>(values: signals)
|> flatten(.Merge)
} |
Add the AEXML dependency to the package. | import PackageDescription
let package = Package(
name: "GPXKit"
)
| import PackageDescription
let package = Package(
name: "GPXKit",
dependencies: [
.Package(url: "https://github.com/fousa/AEXML.git", majorVersion: 2, minor: 1)
]
)
|
Make sure test case does not collide with private discriminators. | // RUN: %target-swift-frontend -O -emit-sil %s | FileCheck %s
protocol DrawingElementDispatchType {}
extension DrawingElementDispatchType {
final var boundingBox: Int32 {
return 0
}
}
protocol DrawingElementType : DrawingElementDispatchType {
var boundingBox: Int32 {get}
}
struct D : DrawingElementType {
var boundingBox: Int32 = 42
}
// Check that that boundingBox is devirtualized and inlined.
// CHECK: sil @{{.*}}test1111
// bb0:
// CHECK-NOT: class_method
// CHECK-NOT: witness_method
// CHECK: integer_literal $Builtin.Int32, 42
// CHECK-NOT: class_method
// CHECK-NOT: witness_method
// CHECK-NOT: bb1
// return
public func test1111() -> Int32 {
return (D() as DrawingElementType).boundingBox
}
| // RUN: %target-swift-frontend -O -emit-sil %s | FileCheck %s
protocol DrawingElementDispatchType {}
extension DrawingElementDispatchType {
final var boundingBox: Int32 {
return 0
}
}
protocol DrawingElementType : DrawingElementDispatchType {
var boundingBox: Int32 {get}
}
struct D : DrawingElementType {
var boundingBox: Int32 = 42
}
// Check that that boundingBox is devirtualized and inlined.
// CHECK: sil @{{.*}}test1111
// bb0:
// CHECK-NOT: class_method
// CHECK-NOT: witness_method
// CHECK: integer_literal $Builtin.Int32, 42
// CHECK-NOT: class_method
// CHECK-NOT: witness_method
// CHECK-NOT: bb1:
// return
public func test1111() -> Int32 {
return (D() as DrawingElementType).boundingBox
}
|
Make about field in error object optional since it is not always present. | //
// AppleMusicAPIError.swift
// Cider
//
// Created by Scott Hoyt on 8/9/17.
// Copyright © 2017 Scott Hoyt. All rights reserved.
//
import Foundation
struct AppleMusicAPIError: Error, Codable {
let id: String
let about: String
let status: String
let code: String
let title: String
let detail: String
// let source: Source
// let meta: Meta
}
| //
// AppleMusicAPIError.swift
// Cider
//
// Created by Scott Hoyt on 8/9/17.
// Copyright © 2017 Scott Hoyt. All rights reserved.
//
import Foundation
struct AppleMusicAPIError: Error, Codable {
let id: String
let about: String?
let status: String
let code: String
let title: String
let detail: String
// let source: Source
// let meta: Meta
}
|
Remove the "AshtonDynamic" library product | // swift-tools-version:5.1
import PackageDescription
let package = Package(
name: "Ashton",
platforms: [.iOS("13.4"), .macOS(.v10_15)],
products: [
.library(name: "Ashton", targets: ["Ashton"]),
.library(name: "AshtonDynamic", type: .dynamic, targets: ["Ashton"]),
],
targets: [
.target(
name: "Ashton",
dependencies: [],
path: "Sources"),
.testTarget(
name: "AshtonTests",
dependencies: ["Ashton"],
path: "Tests",
exclude: ["TestFiles", "AshtonBenchmark", "Bridging.h", "AshtonBenchmarkTests.swift"]),
]
)
| // swift-tools-version:5.1
import PackageDescription
let package = Package(
name: "Ashton",
platforms: [.iOS("13.4"), .macOS(.v10_15)],
products: [.library(name: "Ashton", targets: ["Ashton"])],
targets: [
.target(
name: "Ashton",
dependencies: [],
path: "Sources"),
.testTarget(
name: "AshtonTests",
dependencies: ["Ashton"],
path: "Tests",
exclude: ["TestFiles", "AshtonBenchmark", "Bridging.h", "AshtonBenchmarkTests.swift"]),
]
)
|
Upgrade to Swift 3 syntax | //
// main.swift
// swcat
//
// Created by Caius Durling on 03/06/2014.
// Copyright (c) 2014 Caius Durling. All rights reserved.
//
// cat(1) (not a full) clone written in swift
//
// Given no arguments, prints stdin to stdout. Given arguments reads them as files, printing content to stdout. Errors on stderr if files not found.
//
import Foundation
// Outputs
let stderr = NSFileHandle.fileHandleWithStandardError()
let stdin = NSFileHandle.fileHandleWithStandardInput()
let stdout = NSFileHandle.fileHandleWithStandardOutput()
// Grab ARGV by getting process arguments and losing $0 from it
var argv = Array(NSProcessInfo.processInfo().arguments.map { $0 as String })
argv.removeAtIndex(0)
if argv.count > 0 {
// Each argument is a potential filename, output contents if we can, or output error if not
let fileManager = NSFileManager.defaultManager()
for filename in argv {
if !fileManager.isReadableFileAtPath(filename) {
let errorMessage = "swcat: \(filename): No such file or directory\n"
stderr.writeData(errorMessage.dataUsingEncoding(NSUTF8StringEncoding))
continue
}
stdout.writeData(fileManager.contentsAtPath(filename))
}
} else {
// Read from stdin
stdout.writeData(stdin.readDataToEndOfFile())
}
| //
// main.swift
// swcat
//
// Created by Caius Durling on 03/06/2014.
// Copyright (c) 2014 Caius Durling. All rights reserved.
//
// cat(1) (not a full) clone written in swift
//
// Given no arguments, prints stdin to stdout. Given arguments reads them as files, printing content to stdout. Errors on stderr if files not found.
//
import Foundation
// Outputs
let stderr = FileHandle.withStandardError
let stdin = FileHandle.withStandardInput
let stdout = FileHandle.withStandardOutput
// Grab ARGV by getting process arguments and losing $0 from it
var argv = Array(ProcessInfo.processInfo.arguments.map { $0 as String })
argv.remove(at: 0)
if argv.count > 0 {
// Each argument is a potential filename, output contents if we can, or output error if not
let fileManager = FileManager.default
for filename in argv {
if !fileManager.isReadableFile(atPath: filename) {
let errorMessage = "swcat: \(filename): No such file or directory\n"
stderr.write(errorMessage.data(using: String.Encoding.utf8)!)
continue
}
stdout.write(fileManager.contents(atPath: filename)!)
}
} else {
// Read from stdin
stdout.write(stdin.readDataToEndOfFile())
}
|
Test cases should pass now | //
// ZapicTests.swift
// ZapicTests
//
// Created by Daniel Sarfati on 6/30/17.
// Copyright © 2017 Zapic. All rights reserved.
//
import XCTest
@testable import Zapic
class ZapicTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
XCTAssert(1 == 2)
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| //
// ZapicTests.swift
// ZapicTests
//
// Created by Daniel Sarfati on 6/30/17.
// Copyright © 2017 Zapic. All rights reserved.
//
import XCTest
@testable import Zapic
class ZapicTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
|
Use Task.runDetached instead of custom runAsync | //
// AsyncExtensions.swift
// Promissum
//
// Created by Tom Lokhorst on 2021-03-06.
//
import Foundation
import _Concurrency
extension Promise {
public func get() async throws -> Value {
try await withUnsafeThrowingContinuation { continuation in
self.finallyResult { result in
continuation.resume(with: result)
}
}
}
public func getResult() async -> Result<Value, Error> {
await withUnsafeContinuation { continuation in
self.finallyResult { result in
continuation.resume(returning: result)
}
}
}
}
extension Promise where Error == Swift.Error {
public convenience init(block: @escaping () async throws -> Value) {
let source = PromiseSource<Value, Error>()
self.init(source: source)
runAsync {
do {
let value = try await block()
source.resolve(value)
} catch {
source.reject(error)
}
}
}
}
extension Promise where Error == Never {
public func get() async -> Value {
await withUnsafeContinuation { continuation in
self.finallyResult { result in
continuation.resume(with: result)
}
}
}
public convenience init(block: @escaping () async -> Value) {
let source = PromiseSource<Value, Never>()
self.init(source: source)
runAsync {
let value = await block()
source.resolve(value)
}
}
}
@asyncHandler private func runAsync(operation: @escaping () async -> Void) {
await operation()
}
| //
// AsyncExtensions.swift
// Promissum
//
// Created by Tom Lokhorst on 2021-03-06.
//
import Foundation
import _Concurrency
extension Promise {
public func get() async throws -> Value {
try await withUnsafeThrowingContinuation { continuation in
self.finallyResult { result in
continuation.resume(with: result)
}
}
}
public func getResult() async -> Result<Value, Error> {
await withUnsafeContinuation { continuation in
self.finallyResult { result in
continuation.resume(returning: result)
}
}
}
}
extension Promise where Error == Swift.Error {
public convenience init(block: @escaping () async throws -> Value) {
let source = PromiseSource<Value, Error>()
self.init(source: source)
Task.runDetached {
do {
let value = try await block()
source.resolve(value)
} catch {
source.reject(error)
}
}
}
}
extension Promise where Error == Never {
public func get() async -> Value {
await withUnsafeContinuation { continuation in
self.finallyResult { result in
continuation.resume(with: result)
}
}
}
public convenience init(block: @escaping () async -> Value) {
let source = PromiseSource<Value, Never>()
self.init(source: source)
Task.runDetached {
let value = await block()
source.resolve(value)
}
}
}
//@asyncHandler private func runAsync(operation: @escaping () async -> Void) {
// await operation()
//}
|
Add new common enum type named 'EmptyEnum' | //
// Enumable.swift
// SwiftyEcharts
//
// Created by Pluto Y on 15/01/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
public protocol Enumable {
associatedtype ContentEnum
init(_ elements: Self.ContentEnum...)
}
extension Enumable {
public init(_ element: Self.ContentEnum) {
/// 兼容只有一个参数的情况
self.init(element, element)
}
}
| //
// Enumable.swift
// SwiftyEcharts
//
// Created by Pluto Y on 15/01/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
/// 针对那种只有只读属性或者没有属性的类型
public enum EmptyEnum { }
public protocol Enumable {
associatedtype ContentEnum
init(_ elements: Self.ContentEnum...)
}
extension Enumable {
public init(_ element: Self.ContentEnum) {
/// 兼容只有一个参数的情况
self.init(element, element)
}
}
|
Fix reference for the Schedule table | import Foundation
import SwiftUI
import MapKit
import Combine
public class FeedViewModel: ObservableObject {
@ObservedObject var store = NSBrazilStore()
private var cancellable: AnyCancellable? = nil
public init() {
fetchInfo()
}
func fetchInfo() {
isLoading = true
cancellable = store.fetchInfo()
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: { received in
switch received {
case .finished:
print("sim")
case .failure(_):
print("nao")
self.isEmpty = true
}
}, receiveValue: { value in
self.isLoading = false
self.homeFeed = value.feed.feedItems
self.scheduleFeed = value.feed.feedItems
})
}
@Published var homeFeed: [FeedItem] = []
@Published var scheduleFeed: [FeedItem] = []
@Published var isEmpty: Bool = false
@Published var isLoading: Bool = false
}
| import Foundation
import SwiftUI
import MapKit
import Combine
public class FeedViewModel: ObservableObject {
@ObservedObject var store = NSBrazilStore()
private var cancellable: AnyCancellable? = nil
public init() {
fetchInfo()
}
func fetchInfo() {
isLoading = true
cancellable = store.fetchInfo()
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: { received in
switch received {
case .finished:
print("sim")
case .failure(_):
print("nao")
self.isEmpty = true
}
}, receiveValue: { value in
self.isLoading = false
self.homeFeed = value.feed.feedItems
self.scheduleFeed = value.schedule.feedItems
})
}
@Published var homeFeed: [FeedItem] = []
@Published var scheduleFeed: [FeedItem] = []
@Published var isEmpty: Bool = false
@Published var isLoading: Bool = false
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.