Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add function to apply accessibility identifiers | /*
| _ ____ ____ _
| | |βΎ| β |-| β |βΎ| |
| | | βΎβΎβΎβΎ| |βΎβΎβΎβΎ | |
| βΎ βΎ βΎ
*/
import Foundation
public protocol Nameable { }
public extension Nameable {
public static var name: String {
return String(describing: Self.self)
}
}
| /*
| _ ____ ____ _
| | |βΎ| β |-| β |βΎ| |
| | | βΎβΎβΎβΎ| |βΎβΎβΎβΎ | |
| βΎ βΎ βΎ
*/
import Foundation
public protocol Nameable { }
public extension Nameable {
public static var name: String {
return String(describing: Self.self)
}
public func addAccessibilityIdentifiers() {
for (label, object) in Mirror(reflecting: self).children {
guard let label = label else { continue }
let accessibleObject: UIAccessibilityIdentification
if let view = object as? UIView {
accessibleObject = view
} else if let barItem = object as? UIBarItem {
accessibleObject = barItem
} else {
continue
}
accessibleObject.accessibilityIdentifier = Self.name + "." + label
}
}
}
|
Add a check for the implicit import line to this testcase. | // RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-build-swift -module-cache-path %t/clang-module-cache -emit-ir -g %s -o - | FileCheck %s
// CHECK: i32 {{.*}}, metadata !{{[0-9]+}}, metadata ![[ObjectiveC:[0-9]+]], {{.*}}metadata !"_TtCSo8Protocol"} ; [ DW_TAG_structure_type ] [Protocol]
// CHECK: ![[ObjectiveC]] = metadata !{{.*}} ; [ DW_TAG_module ] [ObjectiveC]
import Foundation
func f() {
var protocolObject = NSProtocolFromString("HelperTool")!
}
| // RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-build-swift -module-cache-path %t/clang-module-cache -emit-ir -g %s -o - | FileCheck %s
// CHECK: i32 {{.*}}, metadata !{{[0-9]+}}, metadata ![[ObjectiveC:[0-9]+]], {{.*}}metadata !"_TtCSo8Protocol"} ; [ DW_TAG_structure_type ] [Protocol]
// CHECK: ![[ObjectiveC]] = metadata !{{.*}} ; [ DW_TAG_module ] [ObjectiveC] [line 1]
import Foundation
func f() {
var protocolObject = NSProtocolFromString("HelperTool")!
var bounds = NSPoint(x: 1, y: 1)
}
|
Simplify output of clock face emojis | //
// Time.swift
// EmojiTimeFormatter
//
// Created by Thomas Paul Mann on 21/08/16.
// Copyright Β© 2016 Thomas Paul Mann. All rights reserved.
//
public enum ClockFaceEmoji: String {
// Whole
case one = "π"
case two = "π"
case three = "π"
case four = "π"
case five = "π"
case six = "π"
case seven = "π"
case eight = "π"
case nine = "π"
case ten = "π"
case eleven = "π"
case twelve = "π"
// Half
case oneThirty = "π"
case twoThirty = "π"
case threeThirty = "π"
case fourThirty = "π"
case fiveThirty = "π "
case sixThirty = "π‘"
case sevenThirty = "π’"
case eightThirty = "π£"
case nineThirty = "π€"
case tenThirty = "π₯"
case elevenThirty = "π¦"
case twelveThirty = "π§"
}
| //
// Time.swift
// EmojiTimeFormatter
//
// Created by Thomas Paul Mann on 21/08/16.
// Copyright Β© 2016 Thomas Paul Mann. All rights reserved.
//
public enum ClockFaceEmoji: String {
// Whole
case one = "π"
case two = "π"
case three = "π"
case four = "π"
case five = "π"
case six = "π"
case seven = "π"
case eight = "π"
case nine = "π"
case ten = "π"
case eleven = "π"
case twelve = "π"
// Half
case oneThirty = "π"
case twoThirty = "π"
case threeThirty = "π"
case fourThirty = "π"
case fiveThirty = "π "
case sixThirty = "π‘"
case sevenThirty = "π’"
case eightThirty = "π£"
case nineThirty = "π€"
case tenThirty = "π₯"
case elevenThirty = "π¦"
case twelveThirty = "π§"
}
// MARK: - Custom String Convertible
extension ClockFaceEmoji: CustomStringConvertible {
public var description: String {
return self.rawValue
}
}
|
Add missing arg in ContactLog initializer in test | //
// ContactLogsTests.swift
// FiveCalls
//
// Created by Ben Scheirman on 2/5/17.
// Copyright Β© 2017 5calls. All rights reserved.
//
import XCTest
import Pantry
@testable import FiveCalls
class ContactLogsTests: XCTestCase {
override func setUp() {
super.setUp()
Pantry.removeAllCache()
}
override func tearDown() {
super.tearDown()
}
func testLoadsEmptyContactLogs() {
let logs = ContactLogs.load()
let expected: [ContactLog] = []
XCTAssertEqual(logs.all, expected)
}
func testSavingLog() {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: "1984-01-24")!
let log = ContactLog(issueId: "issue1", contactId: "contact1", phone: "111-222-3333", outcome: "Left Voicemail", date: date)
Pantry.pack([log], key: "log")
if let loadedLogs: [ContactLog] = Pantry.unpack("log") {
XCTAssertEqual([log], loadedLogs)
} else {
XCTFail()
}
var logs = ContactLogs()
logs.add(log: log)
let loadedLogs = ContactLogs.load()
XCTAssertEqual(loadedLogs.all, [log])
}
}
| //
// ContactLogsTests.swift
// FiveCalls
//
// Created by Ben Scheirman on 2/5/17.
// Copyright Β© 2017 5calls. All rights reserved.
//
import XCTest
import Pantry
@testable import FiveCalls
class ContactLogsTests: XCTestCase {
override func setUp() {
super.setUp()
Pantry.removeAllCache()
}
override func tearDown() {
super.tearDown()
}
func testLoadsEmptyContactLogs() {
let logs = ContactLogs.load()
let expected: [ContactLog] = []
XCTAssertEqual(logs.all, expected)
}
func testSavingLog() {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: "1984-01-24")!
let log = ContactLog(issueId: "issue1", contactId: "contact1", phone: "111-222-3333", outcome: "Left Voicemail", date: date, reported: true)
Pantry.pack([log], key: "log")
if let loadedLogs: [ContactLog] = Pantry.unpack("log") {
XCTAssertEqual([log], loadedLogs)
} else {
XCTFail()
}
var logs = ContactLogs()
logs.add(log: log)
let loadedLogs = ContactLogs.load()
XCTAssertEqual(loadedLogs.all, [log])
}
}
|
Update iOS example to use connection state change delegate | //
// ViewController.swift
// iOS Example
//
// Created by Hamilton Chapman on 24/02/2015.
// Copyright (c) 2015 Pusher. All rights reserved.
//
import UIKit
import PusherSwift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let pusher = Pusher(key: "87572504efd5d4f1b353", options: ["secret": "ab53d405ac3c245972ee"])
pusher.connect()
let chan = pusher.subscribe("test-channel")
chan.bind("test-event", callback: { (data: AnyObject?) -> Void in
print(data)
if let data = data as? Dictionary<String, AnyObject> {
if let testVal = data["test"] as? String {
print(testVal)
}
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| //
// ViewController.swift
// iOS Example
//
// Created by Hamilton Chapman on 24/02/2015.
// Copyright (c) 2015 Pusher. All rights reserved.
//
import UIKit
import PusherSwift
class ViewController: UIViewController, ConnectionStateChangeDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let pusher = Pusher(key: "87572504efd5d4f1b353", options: ["secret": "ab53d405ac3c245972ee"])
pusher.connection.stateChangeDelegate = self
pusher.connect()
let chan = pusher.subscribe("test-channel")
chan.bind("test-event", callback: { (data: AnyObject?) -> Void in
print(data)
if let data = data as? Dictionary<String, AnyObject> {
if let testVal = data["test"] as? String {
print(testVal)
}
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func connectionChange(old: ConnectionState, new: ConnectionState) {
print("old: \(old) -> new: \(new)")
}
}
|
Define gradient stop colours for various temperature tiers | // Copyright Β© 2016 Gavan Chan. All rights reserved.
import UIKit
final class PlaceholderWeatherViewController: UIViewController {
@IBOutlet private weak var locationLabel: UILabel!
@IBOutlet private weak var weatherInformationLabel: UILabel!
}
final class PlaceholderWeatherView: UIView {
override static var layerClass: AnyClass { return CAGradientLayer.self }
}
struct PlaceholderWeatherViewModel {
}
| // Copyright Β© 2016 Gavan Chan. All rights reserved.
import UIKit
final class PlaceholderWeatherViewController: UIViewController {
@IBOutlet private weak var locationLabel: UILabel!
@IBOutlet private weak var weatherInformationLabel: UILabel!
}
final class PlaceholderWeatherView: UIView {
enum Theme {
case blistering
case hot
case neutral
case cold
var gradientColors: (light: UIColor, dark: UIColor) {
switch self {
case .blistering:
return (.init(rgb: (254, 229, 207)), .init(rgb: (253, 191, 132)))
case .hot:
return (.init(rgb: (254, 212, 171)), .init(rgb: (255, 240, 233)))
case .neutral:
return (.init(rgb: (226, 232, 254)), .init(rgb: (255, 249, 255)))
case .cold:
return (.init(rgb: (253, 194, 164)), .init(rgb: (226, 232, 254)))
}
}
}
override static var layerClass: AnyClass { return CAGradientLayer.self }
}
struct PlaceholderWeatherViewModel {
}
fileprivate extension UIColor {
convenience init(rgb: (Int, Int, Int), alpha: CGFloat = 1.0) {
let red: CGFloat = CGFloat(rgb.0) / 255.0
let green: CGFloat = CGFloat(rgb.1) / 255.0
let blue: CGFloat = CGFloat(rgb.2) / 255.0
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
|
Update for Xcode 8 beta 4 | //
// _RecursiveLock.swift
// SwiftTask
//
// Created by Yasuhiro Inami on 2015/05/18.
// Copyright (c) 2015εΉ΄ Yasuhiro Inami. All rights reserved.
//
import Darwin
internal final class _RecursiveLock
{
private let mutex: UnsafeMutablePointer<pthread_mutex_t>
private let attribute: UnsafeMutablePointer<pthread_mutexattr_t>
internal init()
{
self.mutex = UnsafeMutablePointer<pthread_mutex_t>(allocatingCapacity: 1)
self.attribute = UnsafeMutablePointer<pthread_mutexattr_t>(allocatingCapacity: 1)
pthread_mutexattr_init(self.attribute)
pthread_mutexattr_settype(self.attribute, PTHREAD_MUTEX_RECURSIVE)
pthread_mutex_init(self.mutex, self.attribute)
}
deinit
{
pthread_mutexattr_destroy(self.attribute)
pthread_mutex_destroy(self.mutex)
self.attribute.deallocateCapacity(1)
self.mutex.deallocateCapacity(1)
}
internal func lock()
{
pthread_mutex_lock(self.mutex)
}
internal func unlock()
{
pthread_mutex_unlock(self.mutex)
}
}
| //
// _RecursiveLock.swift
// SwiftTask
//
// Created by Yasuhiro Inami on 2015/05/18.
// Copyright (c) 2015εΉ΄ Yasuhiro Inami. All rights reserved.
//
import Darwin
internal final class _RecursiveLock
{
private let mutex: UnsafeMutablePointer<pthread_mutex_t>
private let attribute: UnsafeMutablePointer<pthread_mutexattr_t>
internal init()
{
self.mutex = UnsafeMutablePointer<pthread_mutex_t>.allocate(capacity: 1)
self.attribute = UnsafeMutablePointer<pthread_mutexattr_t>.allocate(capacity: 1)
pthread_mutexattr_init(self.attribute)
pthread_mutexattr_settype(self.attribute, PTHREAD_MUTEX_RECURSIVE)
pthread_mutex_init(self.mutex, self.attribute)
}
deinit
{
pthread_mutexattr_destroy(self.attribute)
pthread_mutex_destroy(self.mutex)
self.attribute.deallocate(capacity: 1)
self.mutex.deallocate(capacity: 1)
}
internal func lock()
{
pthread_mutex_lock(self.mutex)
}
internal func unlock()
{
pthread_mutex_unlock(self.mutex)
}
}
|
Split lines by a pipe symbol | //
// main.swift
// ParseCSV
//
// Created by Alexander Farber on 27.06.21.
//
import Foundation
func process(string: String) throws {
print("your code here")
}
func processFile(at url: URL) throws {
let s = try String(contentsOf: url)
try process(string: s)
}
func main() {
guard CommandLine.arguments.count > 1 else {
print("usage: \(CommandLine.arguments[0]) file...")
return
}
for path in CommandLine.arguments[1...] {
do {
let u = URL(fileURLWithPath: path)
try processFile(at: u)
} catch {
print("error processing: \(path): \(error)")
}
}
}
main()
exit(EXIT_SUCCESS)
| //
// main.swift
// ParseCSV
//
// Created by Alexander Farber on 27.06.21.
//
import Foundation
func process(string: String) throws {
let lines = string.split(separator: "\n")
for line in lines {
let columns = line.split(separator: "|", omittingEmptySubsequences: true)
for column in columns {
print("column: \(column)")
}
}
}
func processFile(at url: URL) throws {
let s = try String(contentsOf: url)
try process(string: s)
}
func main() {
guard CommandLine.arguments.count > 1 else {
print("usage: \(CommandLine.arguments[0]) file...")
return
}
for path in CommandLine.arguments[1...] {
do {
let u = URL(fileURLWithPath: path)
try processFile(at: u)
} catch {
print("error processing: \(path): \(error)")
}
}
}
main()
exit(EXIT_SUCCESS)
|
Add importing Glibc for Linux platforms | /*
The MIT License (MIT)
Copyright (c) 2015 Shun Takebayashi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import swiftra
get("/abc") { req in
return Response("/abc was requested with GET")
}
post("/abc") { req in
return "/abc was requested with POST, body = \(req.body)"
}
get("/def") { req in
return "/def was was requested with GET"
}
serve(8080)
| /*
The MIT License (MIT)
Copyright (c) 2015 Shun Takebayashi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import swiftra
#if os(Linux)
import Glibc
#endif
get("/abc") { req in
return Response("/abc was requested with GET")
}
post("/abc") { req in
return "/abc was requested with POST, body = \(req.body)"
}
get("/def") { req in
return "/def was was requested with GET"
}
serve(8080)
|
Add CEvent and ConfigFile imports | import PackageDescription
let package = Package(
name: "Smud"
)
| import PackageDescription
let package = Package(
name: "Smud",
dependencies: [
.Package(url: "https://github.com/smud/CEvent.git", majorVersion: 0),
.Package(url: "https://github.com/smud/ConfigFile.git", majorVersion: 0),
]
)
|
Update the iOSSwiftTest to work with Swift 2.0 | //
// Formatter.swift
// Lumberjack
//
// Created by C.W. Betts on 10/3/14.
//
//
import Foundation
import CocoaLumberjack.DDDispatchQueueLogFormatter
class Formatter: DDDispatchQueueLogFormatter, DDLogFormatter {
let threadUnsafeDateFormatter: NSDateFormatter
override init() {
threadUnsafeDateFormatter = NSDateFormatter()
threadUnsafeDateFormatter.formatterBehavior = .Behavior10_4
threadUnsafeDateFormatter.dateFormat = "HH:mm:ss.SSS"
super.init()
}
override func formatLogMessage(logMessage: DDLogMessage!) -> String {
let dateAndTime = threadUnsafeDateFormatter.stringFromDate(logMessage.timestamp)
var logLevel: String
let logFlag = logMessage.flag
if logFlag & .Error == .Error {
logLevel = "E"
} else if logFlag & .Warning == .Warning {
logLevel = "W"
} else if logFlag & .Info == .Info {
logLevel = "I"
} else if logFlag & .Debug == .Debug {
logLevel = "D"
} else if logFlag & .Verbose == .Verbose {
logLevel = "V"
} else {
logLevel = "?"
}
let formattedLog = "\(dateAndTime) |\(logLevel)| [\(logMessage.fileName) \(logMessage.function)] #\(logMessage.line): \(logMessage.message)"
return formattedLog;
}
}
| //
// Formatter.swift
// Lumberjack
//
// Created by C.W. Betts on 10/3/14.
//
//
import Foundation
import CocoaLumberjack.DDDispatchQueueLogFormatter
class Formatter: DDDispatchQueueLogFormatter {
let threadUnsafeDateFormatter: NSDateFormatter
override init() {
threadUnsafeDateFormatter = NSDateFormatter()
threadUnsafeDateFormatter.formatterBehavior = .Behavior10_4
threadUnsafeDateFormatter.dateFormat = "HH:mm:ss.SSS"
super.init()
}
override func formatLogMessage(logMessage: DDLogMessage!) -> String {
let dateAndTime = threadUnsafeDateFormatter.stringFromDate(logMessage.timestamp)
var logLevel: String
let logFlag = logMessage.flag
if logFlag.contains(.Error) {
logLevel = "E"
} else if logFlag.contains(.Warning){
logLevel = "W"
} else if logFlag.contains(.Info) {
logLevel = "I"
} else if logFlag.contains(.Debug) {
logLevel = "D"
} else if logFlag.contains(.Verbose) {
logLevel = "V"
} else {
logLevel = "?"
}
let formattedLog = "\(dateAndTime) |\(logLevel)| [\(logMessage.fileName) \(logMessage.function)] #\(logMessage.line): \(logMessage.message)"
return formattedLog;
}
}
|
Update generated test index names | //
// OnlineTestCase.swift
//
//
// Created by Vladislav Fitc on 05/03/2020.
//
import Foundation
import XCTest
@testable import AlgoliaSearchClientSwift
class OnlineTestCase: XCTestCase {
var client: Client!
var index: Index!
let expectationTimeout: TimeInterval = 100
/// Abstract base class for online test cases.
///
override func setUpWithError() throws {
try super.setUpWithError()
guard let credentials = TestCredentials.environment else {
throw Error.missingCredentials
}
client = Client(appID: credentials.applicationID, apiKey: credentials.apiKey)
// NOTE: We use a different index name for each test function.
let className = String(reflecting: type(of: self)).components(separatedBy: ".").last!
let functionName = invocation!.selector.description
let indexName = IndexName(stringLiteral: "\(className).\(functionName)")
index = client.index(withName: indexName)
try index.delete()
}
override func tearDownWithError() throws {
try super.tearDownWithError()
try index.delete()
}
}
extension OnlineTestCase {
enum Error: Swift.Error {
case missingCredentials
}
}
| //
// OnlineTestCase.swift
//
//
// Created by Vladislav Fitc on 05/03/2020.
//
import Foundation
import XCTest
@testable import AlgoliaSearchClientSwift
class OnlineTestCase: XCTestCase {
var client: Client!
var index: Index!
let expectationTimeout: TimeInterval = 100
/// Abstract base class for online test cases.
///
override func setUpWithError() throws {
try super.setUpWithError()
guard let credentials = TestCredentials.environment else {
throw Error.missingCredentials
}
client = Client(appID: credentials.applicationID, apiKey: credentials.apiKey)
// NOTE: We use a different index name for each test function.
let className = String(reflecting: type(of: self)).components(separatedBy: ".").last!
let functionName = invocation!.selector.description
let testID = "\(className).\(functionName)"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-DD_HH:mm:ss"
let dateString = dateFormatter.string(from: .init())
let indexName = IndexName(stringLiteral: "swift_\(dateString)_\(NSUserName().description)_\(testID)")
index = client.index(withName: indexName)
try index.delete()
}
override func tearDownWithError() throws {
try super.tearDownWithError()
try index.delete()
}
}
extension OnlineTestCase {
enum Error: Swift.Error {
case missingCredentials
}
}
|
Add a tableView with constraints to the AllChatsVC | //
// AllChatsViewController.swift
// V
//
// Created by Dulio Denis on 5/17/16.
// Copyright Β© 2016 Dulio Denis. All rights reserved.
//
import UIKit
import CoreData
class AllChatsViewController: UIViewController {
var context: NSManagedObjectContext?
private var fetchedResultsController: NSFetchedResultsController?
private let tableView = UITableView(frame: CGRectZero, style: .Plain)
private let cellIdentifier = "MessageCell"
}
| //
// AllChatsViewController.swift
// V
//
// Created by Dulio Denis on 5/17/16.
// Copyright Β© 2016 Dulio Denis. All rights reserved.
//
import UIKit
import CoreData
class AllChatsViewController: UIViewController {
var context: NSManagedObjectContext?
private var fetchedResultsController: NSFetchedResultsController?
private let tableView = UITableView(frame: CGRectZero, style: .Plain)
private let cellIdentifier = "MessageCell"
override func viewDidLoad() {
super.viewDidLoad()
// Set navbar title and new chat bar button item
title = "Chats"
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "new_chat"), style: .Plain, target: self, action: "newChat")
// ensure the tableview isn't distorted due to the navbar
automaticallyAdjustsScrollViewInsets = false
// tableView setup: register class, initialize tableview footer, allow our use of auto-layout
tableView.registerClass(ChatCell.self, forCellReuseIdentifier: cellIdentifier)
tableView.tableFooterView = UIView(frame: CGRectZero)
tableView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(tableView)
// add constraints to the tableview
let tableViewConstraints: [NSLayoutConstraint] = [
tableView.topAnchor.constraintEqualToAnchor(topLayoutGuide.bottomAnchor),
tableView.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor),
tableView.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor),
tableView.bottomAnchor.constraintEqualToAnchor(bottomLayoutGuide.topAnchor)
]
// activate the constraints
NSLayoutConstraint.activateConstraints(tableViewConstraints)
}
func newChat() {
}
}
|
Add missing test for divider | import XCTest
import SwiftUI
@testable import ViewInspector
final class DividerTests: XCTestCase {
func testExtractionFromSingleViewContainer() throws {
let view = AnyView(Divider())
XCTAssertNoThrow(try view.inspect().divider())
}
func testExtractionFromMultipleViewContainer() throws {
let view = HStack {
Text("")
Divider()
Text("")
Divider()
}
XCTAssertNoThrow(try view.inspect().divider(1))
XCTAssertNoThrow(try view.inspect().divider(3))
}
static var allTests = [
("testExtractionFromSingleViewContainer", testExtractionFromSingleViewContainer),
("testExtractionFromMultipleViewContainer", testExtractionFromMultipleViewContainer),
]
}
| import XCTest
import SwiftUI
@testable import ViewInspector
final class DividerTests: XCTestCase {
func testInspect() throws {
XCTAssertNoThrow(try Divider().inspect())
}
func testExtractionFromSingleViewContainer() throws {
let view = AnyView(Divider())
XCTAssertNoThrow(try view.inspect().divider())
}
func testExtractionFromMultipleViewContainer() throws {
let view = HStack {
Text("")
Divider()
Text("")
Divider()
}
XCTAssertNoThrow(try view.inspect().divider(1))
XCTAssertNoThrow(try view.inspect().divider(3))
}
static var allTests = [
("testInspect", testInspect),
("testExtractionFromSingleViewContainer", testExtractionFromSingleViewContainer),
("testExtractionFromMultipleViewContainer", testExtractionFromMultipleViewContainer),
]
}
|
Add another tests for HalfToneDyadSpeller | //
// HalfToneDyadSpellerTests.swift
// PitchSpellingTools
//
// Created by James Bean on 5/12/16.
//
//
import XCTest
import Pitch
@testable import PitchSpellingTools
class HalfToneDyadSpellerTests: XCTestCase {
func testCG() {
let dyad = Dyad(Pitch(noteNumber: 60.0), Pitch(noteNumber: 67.0))
let speller = DyadSpeller.makeSpeller(forDyad: dyad)
guard let options = speller?.options else { XCTFail(); return }
switch options {
case .single(let pitchSpellingDyad):
let expected = PitchSpellingDyad(PitchSpelling(.c), PitchSpelling(.g))
XCTAssertEqual(pitchSpellingDyad, expected)
default: XCTFail()
}
}
}
| //
// HalfToneDyadSpellerTests.swift
// PitchSpellingTools
//
// Created by James Bean on 5/12/16.
//
//
import XCTest
import Pitch
@testable import PitchSpellingTools
class HalfToneDyadSpellerTests: XCTestCase {
func testCG() {
let dyad = Dyad(Pitch(noteNumber: 60.0), Pitch(noteNumber: 67.0))
let speller = DyadSpeller.makeSpeller(forDyad: dyad)
guard let options = speller?.options else { XCTFail(); return }
switch options {
case .single(let pitchSpellingDyad):
let expected = PitchSpellingDyad(PitchSpelling(.c), PitchSpelling(.g))
XCTAssertEqual(pitchSpellingDyad, expected)
default: XCTFail()
}
}
func test61_68() {
let dyad = Dyad(Pitch(noteNumber: 61.0), Pitch(noteNumber: 68.0))
let speller = DyadSpeller.makeSpeller(forDyad: dyad)
guard let options = speller?.options else { XCTFail(); return }
switch options {
case .multiple(let pitchSpellingDyads):
let expected = [
PitchSpellingDyad(PitchSpelling(.c, .sharp), PitchSpelling(.g, .sharp)),
PitchSpellingDyad(PitchSpelling(.d, .flat), PitchSpelling(.a, .flat))
]
XCTAssertEqual(pitchSpellingDyads, expected)
default: XCTFail()
}
}
}
|
Fix test by providing more invalid params | import Quick
import Nimble
@testable import Elephant
class DatabaseSpec: QuickSpec {
override func spec() {
describe("connect") {
context("with valid connection parameters") {
it("returns a connection") {
expect {
try Database.connect()
return nil
}.toNot(throwError())
}
}
context("with invalid connection parameters") {
it("throws a connection failed error") {
expect {
let parameters = ConnectionParameters(host: "")
try Database.connect(parameters: parameters)
return nil
}.to(throwError(errorType: ConnectionError.self))
}
}
}
}
}
| import Quick
import Nimble
@testable import Elephant
class DatabaseSpec: QuickSpec {
override func spec() {
describe("connect") {
context("with valid connection parameters") {
it("returns a connection") {
expect {
try Database.connect()
return nil
}.toNot(throwError())
}
}
context("with invalid connection parameters") {
it("throws a connection failed error") {
expect {
let parameters = ConnectionParameters(host: "sillyhost", port: "666", databaseName: "forgetit", user: "nouser", password: "forgetit")
try Database.connect(parameters: parameters)
return nil
}.to(throwError(errorType: ConnectionError.self))
}
}
}
}
}
|
Use shared instead of sharedInstance | import Cocoa
class PreferencesWindowController: NSWindowController {
static let sharedInstance: PreferencesWindowController = PreferencesWindowController(windowNibName: "Preferences")
}
| import Cocoa
class PreferencesWindowController: NSWindowController {
static let shared = PreferencesWindowController(windowNibName: "Preferences")
}
|
Add documentation about the motivation of the FileString typealias. | import Foundation
#if _runtime(_ObjC)
public typealias FileString = String
#else
public typealias FileString = StaticString
#endif
public final class SourceLocation : NSObject {
public let file: FileString
public let line: UInt
override init() {
file = "Unknown File"
line = 0
}
init(file: FileString, line: UInt) {
self.file = file
self.line = line
}
override public var description: String {
return "\(file):\(line)"
}
}
| import Foundation
// Ideally we would always use `StaticString` as the type for tracking the file name
// that expectations originate from, for consistency with `assert` etc. from the
// stdlib, and because recent versions of the XCTest overlay require `StaticString`
// when calling `XCTFail`. Under the Objective-C runtime (i.e. building on Mac), we
// have to use `String` instead because StaticString can't be generated from Objective-C
#if _runtime(_ObjC)
public typealias FileString = String
#else
public typealias FileString = StaticString
#endif
public final class SourceLocation : NSObject {
public let file: FileString
public let line: UInt
override init() {
file = "Unknown File"
line = 0
}
init(file: FileString, line: UInt) {
self.file = file
self.line = line
}
override public var description: String {
return "\(file):\(line)"
}
}
|
Update test to match llvm.dbg.value change | // RUN: %target-swift-frontend %s -g -emit-ir -o - | %FileCheck %s
// REQUIRES: objc_interop, CPU=x86_64
import simd
func use<T>(_ x: T) {}
func getInt32() -> Int32 { return -1 }
public func rangeExtension(x: Int32, y: Int32) {
let p = int2(x, y)
// CHECK: define {{.*}}rangeExtension
// CHECK: llvm.dbg.value(metadata <2 x i32> %[[P:.*]], metadata
use(p)
// CHECK: asm sideeffect "", "r"{{.*}}[[P]]
}
| // RUN: %target-swift-frontend %s -g -emit-ir -o - | %FileCheck %s
// REQUIRES: objc_interop, CPU=x86_64
import simd
func use<T>(_ x: T) {}
func getInt32() -> Int32 { return -1 }
public func rangeExtension(x: Int32, y: Int32) {
let p = int2(x, y)
// CHECK: define {{.*}}rangeExtension
// CHECK: llvm.dbg.value(metadata <2 x i32> %[[P:.*]], metadata {{.*}}, metadata
use(p)
// CHECK: asm sideeffect "", "r"{{.*}}[[P]]
}
|
Set JSON as default content type | import Foundation
import When
public class Networking {
enum SessionTaskKind {
case Data, Upload, Download
}
let sessionConfiguration: SessionConfiguration
lazy var session: NSURLSession = {
return NSURLSession(configuration: self.sessionConfiguration.value)
}()
public init(sessionConfiguration: SessionConfiguration = .Default) {
self.sessionConfiguration = sessionConfiguration
}
func request(method: Method, URL: NSURL, contentType: ContentType, parameters: [String: AnyObject]?) throws -> Response<NSData> {
let promise = Response<NSData>()
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = method.rawValue
request.addValue(contentType.value, forHTTPHeaderField: "Content-Type")
promise.request = request
if let encoder = parameterEncoders[contentType], let parameters = parameters {
request.HTTPBody = try encoder.encode(parameters)
}
session.dataTaskWithRequest(request, completionHandler: { data, response, error in
guard let response = response as? NSHTTPURLResponse else {
promise.reject(Error.NoResponseReceived)
return
}
promise.response = response
if let error = error {
promise.reject(error)
return
}
guard let data = data else {
promise.reject(Error.NoDataInResponse)
return
}
promise.resolve(data)
}).resume()
return promise
}
}
| import Foundation
import When
public class Networking {
enum SessionTaskKind {
case Data, Upload, Download
}
let sessionConfiguration: SessionConfiguration
lazy var session: NSURLSession = {
return NSURLSession(configuration: self.sessionConfiguration.value)
}()
public init(sessionConfiguration: SessionConfiguration = .Default) {
self.sessionConfiguration = sessionConfiguration
}
func request(method: Method, URL: NSURL, contentType: ContentType = .JSON, parameters: [String: AnyObject]?) throws -> Response<NSData> {
let promise = Response<NSData>()
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = method.rawValue
request.addValue(contentType.value, forHTTPHeaderField: "Content-Type")
promise.request = request
if let encoder = parameterEncoders[contentType], let parameters = parameters {
request.HTTPBody = try encoder.encode(parameters)
}
session.dataTaskWithRequest(request, completionHandler: { data, response, error in
guard let response = response as? NSHTTPURLResponse else {
promise.reject(Error.NoResponseReceived)
return
}
promise.response = response
if let error = error {
promise.reject(error)
return
}
guard let data = data else {
promise.reject(Error.NoDataInResponse)
return
}
promise.resolve(data)
}).resume()
return promise
}
}
|
Test that empty trees are empty. | // Copyright (c) 2015 Rob Rix. All rights reserved.
final class BinaryTreeTests: XCTestCase {
func testEmptyTreesAreNotLeaves() {
XCTAssertFalse(BinaryTree<Int>().isLeaf)
}
func testLeavesAreLeaves() {
XCTAssert(BinaryTree(0).isLeaf)
}
func testLeavesAreNonEmpty() {
XCTAssertFalse(BinaryTree(0).isEmpty)
}
func testLeavesAreNotBranches() {
XCTAssertFalse(BinaryTree(0).isBranch)
}
}
import BinaryTree
import XCTest
| // Copyright (c) 2015 Rob Rix. All rights reserved.
final class BinaryTreeTests: XCTestCase {
func testEmptyTreesAreEmpty() {
XCTAssert(BinaryTree<Int>().isEmpty)
}
func testEmptyTreesAreNotLeaves() {
XCTAssertFalse(BinaryTree<Int>().isLeaf)
}
func testLeavesAreLeaves() {
XCTAssert(BinaryTree(0).isLeaf)
}
func testLeavesAreNonEmpty() {
XCTAssertFalse(BinaryTree(0).isEmpty)
}
func testLeavesAreNotBranches() {
XCTAssertFalse(BinaryTree(0).isBranch)
}
}
import BinaryTree
import XCTest
|
Add bolusVolume to NS enacted struct | //
// LoopEnacted.swift
// RileyLink
//
// Created by Pete Schwamb on 7/28/16.
// Copyright Β© 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public struct LoopEnacted {
typealias RawValue = [String: Any]
let rate: Double
let duration: TimeInterval
let timestamp: Date
let received: Bool
public init(rate: Double, duration: TimeInterval, timestamp: Date, received: Bool) {
self.rate = rate
self.duration = duration
self.timestamp = timestamp
self.received = received
}
public var dictionaryRepresentation: [String: Any] {
var rval = [String: Any]()
rval["rate"] = rate
rval["duration"] = duration / 60.0
rval["timestamp"] = TimeFormat.timestampStrFromDate(timestamp)
rval["received"] = received
return rval
}
init?(rawValue: RawValue) {
guard
let rate = rawValue["rate"] as? Double,
let durationMinutes = rawValue["duration"] as? Double,
let timestampStr = rawValue["timestamp"] as? String,
let timestamp = TimeFormat.dateFromTimestamp(timestampStr),
let received = rawValue["received"] as? Bool
else {
return nil
}
self.rate = rate
self.duration = TimeInterval(minutes: durationMinutes)
self.timestamp = timestamp
self.received = received
}
}
| //
// LoopEnacted.swift
// RileyLink
//
// Created by Pete Schwamb on 7/28/16.
// Copyright Β© 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public struct LoopEnacted {
typealias RawValue = [String: Any]
let rate: Double
let duration: TimeInterval
let timestamp: Date
let received: Bool
let bolusVolume: Double
public init(rate: Double, duration: TimeInterval, timestamp: Date, received: Bool, bolusVolume: Double = 0) {
self.rate = rate
self.duration = duration
self.timestamp = timestamp
self.received = received
self.bolusVolume = bolusVolume
}
public var dictionaryRepresentation: [String: Any] {
var rval = [String: Any]()
rval["rate"] = rate
rval["duration"] = duration / 60.0
rval["timestamp"] = TimeFormat.timestampStrFromDate(timestamp)
rval["received"] = received
rval["bolusVolume"] = bolusVolume
return rval
}
init?(rawValue: RawValue) {
guard
let rate = rawValue["rate"] as? Double,
let durationMinutes = rawValue["duration"] as? Double,
let timestampStr = rawValue["timestamp"] as? String,
let timestamp = TimeFormat.dateFromTimestamp(timestampStr),
let received = rawValue["received"] as? Bool
else {
return nil
}
self.rate = rate
self.duration = TimeInterval(minutes: durationMinutes)
self.timestamp = timestamp
self.received = received
self.bolusVolume = rawValue["bolusVolume"] as? Double ?? 0
}
}
|
Update package manifest to Swift 4 format. | import Foundation
import PackageDescription
let package = Package(
name: "iCalendar",
dependencies: [
.Package(url: "https://github.com/antitypical/Result.git", versions: Version(3, 2, 3)..<Version(3, .max, .max)),
.Package(url: "https://github.com/Quick/Quick.git", majorVersion: 1, minor: 1),
.Package(url: "https://github.com/Quick/Nimble.git", majorVersion: 7)
],
swiftLanguageVersions: [3, 4]
)
| // swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "iCalendar",
products: [
.library(
name: "iCalendar",
targets: ["iCalendar"]),
],
dependencies: [
.package(url: "https://github.com/antitypical/Result.git", from: "3.0.0"),
.package(url: "https://github.com/Quick/Quick.git", .upToNextMinor(from: "1.1.0")),
.package(url: "https://github.com/Quick/Nimble.git", from: "7.0.0"),
],
targets: [
.target(
name: "iCalendar",
dependencies: ["Result"],
path: "Sources"),
.testTarget(
name: "iCalendarTests",
dependencies: ["iCalendar", "Quick", "Nimble"]),
],
swiftLanguageVersions: [3, 4]
)
|
Optimize code style for Decode Ways | /**
* Question Link: https://leetcode.com/problems/decode-ways/
* Primary idea: Dynamic Programming, dp[i] = dp[i - 1] + dp[i - 2],
* determine if current one or two characters are number at first
* Time Complexity: O(n), Space Complexity: O(n)
*
*/
class DecodeWays {
func numDecodings(_ s: String) -> Int {
let chars = Array(s.characters), len = chars.count
guard len > 0 else {
return 0
}
var dp = Array(repeating: 0, count: len + 1)
dp[0] = 1
dp[1] = isValid(String(chars[0 ..< 1])) ? 1 : 0
guard len >= 2 else {
return dp[len]
}
for i in 2 ... len {
if isValid(String(chars[i - 1 ..< i])) {
dp[i] += dp[i - 1]
}
if isValid(String(chars[i - 2 ..< i])) {
dp[i] += dp[i - 2]
}
}
return dp[len]
}
private func isValid(_ str: String) -> Bool {
let chars = Array(str.characters)
if chars[0] == "0" {
return false
}
let num = Int(str)!
return num > 0 && num <= 26
}
} | /**
* Question Link: https://leetcode.com/problems/decode-ways/
* Primary idea: Dynamic Programming, dp[i] = dp[i - 1] + dp[i - 2],
* determine if current one or two characters are number at first
* Time Complexity: O(n), Space Complexity: O(n)
*
*/
class DecodeWays {
func numDecodings(_ s: String) -> Int {
let sChars = Array(s.characters), len = sChars.count
var dp = Array(repeating: 0, count: len + 1)
dp[0] = 1
guard len >= 1 else {
return 0
}
for i in 1 ... len {
if isValid(String(sChars[i - 1 ..< i])) {
dp[i] += dp[i - 1]
}
if i >= 2 && isValid(String(sChars[i - 2 ..< i])) {
dp[i] += dp[i - 2]
}
}
return dp[len]
}
private func isValid(_ numStr: String) -> Bool {
if Array(numStr.characters).first == "0" {
return false
}
guard let num = Int(numStr) else {
return false
}
return num >= 1 && num <= 26
}
} |
Make the test case from r31995 exercise the failure path too. | // RUN: rm -rf %t && mkdir %t
// RUN: %target-swift-frontend -emit-module -o %t %s -module-name Import
// RUN: %target-swift-frontend -parse -I %t %s -module-name main -DMAIN
// Note: This file is compiled both as a library and as a client of that library.
import Import
public func test() {
Import.test()
}
| // RUN: rm -rf %t && mkdir %t
// RUN: %target-swift-frontend -emit-module -o %t %s -module-name Import
// RUN: %target-swift-frontend -parse -I %t %s -module-name main -DMAIN -verify
// Note: This file is compiled both as a library and as a client of that library. The -verify checks only apply to the client.
import Import
public func test() {
Import.test()
Import.hidden() // expected-error {{module 'Import' has no member named 'hidden'}}
}
internal func hidden() {}
|
Add a constructor for a fresh identifier in a graph. | // Copyright (c) 2014 Rob Rix. All rights reserved.
public struct Identifier: Comparable, Hashable, Printable {
public init() {
self.value = Identifier.cursor++
}
// MARK: Endpoint constructors
public func input(index: Int) -> Edge.Destination {
return (identifier: self, inputIndex: index)
}
public func output(index: Int) -> Edge.Source {
return (identifier: self, outputIndex: index)
}
// MARK: Hashable
public var hashValue: Int {
return value.hashValue
}
// MARK: Printable
public var description: String {
return value.description
}
// MARK: Private
private let value: Int
private static var cursor = 0
}
public func == (left: Identifier, right: Identifier) -> Bool {
return left.value == right.value
}
public func < (left: Identifier, right: Identifier) -> Bool {
return left.value < right.value
}
// MARK: - Imports
import Prelude
| // Copyright (c) 2014 Rob Rix. All rights reserved.
public struct Identifier: Comparable, Hashable, Printable {
public init(graph: Graph<Node>) {
value = graph.nodes.isEmpty ? 0 : maxElement(graph.nodes.keys).value + 1
}
public init() {
self.value = Identifier.cursor++
}
// MARK: Endpoint constructors
public func input(index: Int) -> Edge.Destination {
return (identifier: self, inputIndex: index)
}
public func output(index: Int) -> Edge.Source {
return (identifier: self, outputIndex: index)
}
// MARK: Hashable
public var hashValue: Int {
return value.hashValue
}
// MARK: Printable
public var description: String {
return value.description
}
// MARK: Private
private let value: Int
private static var cursor = 0
}
public func == (left: Identifier, right: Identifier) -> Bool {
return left.value == right.value
}
public func < (left: Identifier, right: Identifier) -> Bool {
return left.value < right.value
}
// MARK: - Imports
import Prelude
|
Add dependency to the main target. `objc_retainAutoreleasedReturnValue` will be required even if compiled with release-mode. note: "libdispatch" has an implementation of `objc_retainAutoreleasedReturnValue`. This modification would be unnecessary when linking libdispatch. | // swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
#if os(Linux)
let linux = true
#else
let linux = false
#endif
var targets: [Target] = [
// 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:"CGIResponder", dependencies:[]),
]
if linux {
targets.append(.target(name:"SR_5986", dependencies:[], path:"Tests/SR-5986"))
}
targets.append(.testTarget(name:"CGIResponderTests", dependencies:linux ? ["CGIResponder", "SR_5986"] : ["CGIResponder"]))
let package = Package(
name:"CGIResponder",
products:[
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(name:"SwiftCGIResponder", type:.dynamic, targets:["CGIResponder"]),
],
dependencies:[
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets:targets,
swiftLanguageVersions:[4]
)
| // swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
#if os(Linux)
let linux = true
#else
let linux = false
#endif
var targets: [Target] = [
// 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:"CGIResponder", dependencies:linux ? ["SR_5986"] : []),
]
if linux {
targets.append(.target(name:"SR_5986", dependencies:[], path:"Tests/SR-5986"))
}
targets.append(.testTarget(name:"CGIResponderTests", dependencies:linux ? ["CGIResponder", "SR_5986"] : ["CGIResponder"]))
let package = Package(
name:"CGIResponder",
products:[
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(name:"SwiftCGIResponder", type:.dynamic, targets:["CGIResponder"]),
],
dependencies:[
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets:targets,
swiftLanguageVersions:[4]
)
|
Improve the product line check and add support for the iPhone lines. | //
// Device
// Thingy
//
// Created by Bojan Dimovski on 19/01/2020.
// Copyright Β© 2020 Bojan Dimovski. All rights reserved.
//
import Foundation
public extension Device {
/// Product line of the model, currently supported only for the iPad.
var productLine: ProductLine? {
switch self {
case .iPad2,
.iPad3,
.iPad4,
.iPad5,
.iPad6,
.iPad7:
return Lines.iPad.regular
case .iPadAir,
.iPadAir2,
.iPadAir3:
return Lines.iPad.air
case .iPadPro12Inch,
.iPadPro12Inch2G,
.iPadPro12Inch3G,
.iPadPro9Inch,
.iPadPro10Inch,
.iPadPro11Inch:
return Lines.iPad.pro
case .iPadMini,
.iPadMini2,
.iPadMini3,
.iPadMini4,
.iPadMini5:
return Lines.iPad.mini
default:
return nil
}
}
}
| //
// Device
// Thingy
//
// Created by Bojan Dimovski on 19/01/2020.
// Copyright Β© 2020 Bojan Dimovski. All rights reserved.
//
import Foundation
public extension Device {
/// Product line of the model, currently supported only for the iPad.
var productLine: ProductLine? {
switch family {
case .pad:
switch self {
case .iPadAir,
.iPadAir2,
.iPadAir3:
return Lines.iPad.air
case .iPadPro12Inch,
.iPadPro12Inch2G,
.iPadPro12Inch3G,
.iPadPro9Inch,
.iPadPro10Inch,
.iPadPro11Inch:
return Lines.iPad.pro
case .iPadMini,
.iPadMini2,
.iPadMini3,
.iPadMini4,
.iPadMini5:
return Lines.iPad.mini
default:
return Lines.iPad.standard
}
case .phone:
switch self {
case .iPhoneSE,
.iPhoneSE2G:
return Lines.iPhone.se
case .iPhoneX,
.iPhoneXS,
.iPhoneXSMax,
.iPhone11Pro,
.iPhone11ProMax:
return Lines.iPhone.pro
default:
return Lines.iPhone.standard
}
default:
return nil
}
}
}
|
Move transactions with 0 timestamp to top of list | //
// Wallet+ViewModels.swift
// breadwallet
//
// Created by Adrian Corscadden on 2017-01-12.
// Copyright Β© 2017 breadwallet LLC. All rights reserved.
//
import Foundation
import BRCore
extension BRWallet {
func makeTransactionViewModels(blockHeight: UInt32) -> [Transaction] {
return transactions.flatMap{ $0 }.sorted{ $0.pointee.timestamp > $1.pointee.timestamp }.map {
return Transaction($0, wallet: self, blockHeight: blockHeight)
}
}
}
| //
// Wallet+ViewModels.swift
// breadwallet
//
// Created by Adrian Corscadden on 2017-01-12.
// Copyright Β© 2017 breadwallet LLC. All rights reserved.
//
import Foundation
import BRCore
extension BRWallet {
func makeTransactionViewModels(blockHeight: UInt32) -> [Transaction] {
return transactions.flatMap{ $0 }.sorted {
if $0.pointee.timestamp == 0 {
return true
} else {
return $0.pointee.timestamp > $1.pointee.timestamp
}
}.map {
return Transaction($0, wallet: self, blockHeight: blockHeight)
}
}
}
|
Use Collection return value in ChordExtension | // Copyright (c) 2015 Ben Guo. All rights reserved.
import Foundation
extension Chord {
/// Creates a new `Harmonizer` using the (1-indexed) indices of the given harmonizer
public static func create(_ harmonizer: Harmonizer, indices: [UInt]) -> Harmonizer {
if indices.count < 2 || indices.contains(0) {
return Harmony.IdentityHarmonizer
}
// sort and convert to zero-indexed indices
let sortedIndices = (indices.map { $0 - 1 }).sorted()
let maxIndex = Int(sortedIndices.last!)
let scalePitches = harmonizer(Chroma.c*0)
// extend scale until it covers the max index
while (scalePitches.count < maxIndex + 1) {
_ = scalePitches.extend(1)
}
let chosenPitches = PitchSet(sortedIndices.map { scalePitches[Int($0)] })
return Harmony.create(MKUtil.intervals(chosenPitches.semitoneIndices()))
}
}
| // Copyright (c) 2015 Ben Guo. All rights reserved.
import Foundation
extension Chord {
/// Creates a new `Harmonizer` using the (1-indexed) indices of the given harmonizer
public static func create(_ harmonizer: Harmonizer, indices: [UInt]) -> Harmonizer {
if indices.count < 2 || indices.contains(0) {
return Harmony.IdentityHarmonizer
}
// sort and convert to zero-indexed indices
let sortedIndices = (indices.map { $0 - 1 }).sorted()
let maxIndex = Int(sortedIndices.last!)
var scalePitches = harmonizer(Chroma.c*0)
// extend scale until it covers the max index
while (scalePitches.count < maxIndex + 1) {
scalePitches = scalePitches.extend(1)
}
let chosenPitches = PitchSet(sortedIndices.map { scalePitches[Int($0)] })
return Harmony.create(MKUtil.intervals(chosenPitches.semitoneIndices()))
}
}
|
Extend CellIdentifier to extract from table view cell | //
// CellIdentifiable.swift
// ZamzamKit
//
// Created by Basem Emara on 4/28/17.
// Copyright Β© 2017 Zamzam. All rights reserved.
//
import UIKit
public protocol CellIdentifiable {
associatedtype CellIdentifier: RawRepresentable
}
public extension CellIdentifiable where Self: UITableViewController, CellIdentifier.RawValue == String {
/**
Gets the visible cell with the specified identifier name.
- parameter identifier: Enum value of the cell identifier.
- returns: Returns the table view cell.
*/
func tableViewCell(at identifier: CellIdentifier) -> UITableViewCell? {
return tableView.visibleCells.first { $0.reuseIdentifier == identifier.rawValue }
}
}
| //
// CellIdentifiable.swift
// ZamzamKit
//
// Created by Basem Emara on 4/28/17.
// Copyright Β© 2017 Zamzam. All rights reserved.
//
import UIKit
public protocol CellIdentifiable {
associatedtype CellIdentifier: RawRepresentable
}
public extension CellIdentifiable where Self: UITableViewController, CellIdentifier.RawValue == String {
/**
Gets the visible cell with the specified identifier name.
- parameter identifier: Enum value of the cell identifier.
- returns: Returns the table view cell.
*/
func tableViewCell(at identifier: CellIdentifier) -> UITableViewCell? {
return tableView.visibleCells.first { $0.reuseIdentifier == identifier.rawValue }
}
}
public extension RawRepresentable where Self.RawValue == String {
init?(from cell: UITableViewCell) {
guard let identifier = cell.reuseIdentifier else { return nil }
self.init(rawValue: identifier)
}
}
|
Update solution to Decode Ways | /**
* Question Link: https://leetcode.com/problems/decode-ways/
* Primary idea: Dynamic Programming, dp[i] = dp[i - 1] + dp[i - 2],
* determine if current one or two characters are number at first
* Time Complexity: O(n), Space Complexity: O(n)
*
*/
class DecodeWays {
func numDecodings(_ s: String) -> Int {
let sChars = Array(s.characters), len = sChars.count
var dp = Array(repeating: 0, count: len + 1)
dp[0] = 1
guard len >= 1 else {
return 0
}
for i in 1...len {
if isValid(String(sChars[i - 1..<i])) {
dp[i] += dp[i - 1]
}
if i >= 2 && isValid(String(sChars[i - 2..<i])) {
dp[i] += dp[i - 2]
}
}
return dp[len]
}
private func isValid(_ numStr: String) -> Bool {
if Array(numStr.characters).first == "0" {
return false
}
guard let num = Int(numStr) else {
return false
}
return num >= 1 && num <= 26
}
} | /**
* Question Link: https://leetcode.com/problems/decode-ways/
* Primary idea: Dynamic Programming, dp[i] = dp[i - 1] + dp[i - 2],
* determine if current one or two characters are number at first
* Time Complexity: O(n), Space Complexity: O(n)
*
*/
class DecodeWays {
func numDecodings(_ s: String) -> Int {
let sChars = Array(s)
var dp = Array(repeating: 0, count: s.count + 1)
dp[0] = 1
guard s.count >= 1 else {
return 0
}
for i in 1...s.count {
if String(sChars[i - 1..<i]).isValid {
dp[i] += dp[i - 1]
}
if i >= 2 && String(sChars[i - 2..<i]).isValid {
dp[i] += dp[i - 2]
}
}
return dp[s.count]
}
}
extension String {
var isValid: Bool {
if let first = first, first == "0" {
return false
}
guard let num = Int(self) else {
return false
}
return 0 < num && 26 >= num
}
} |
Add qualified import of Result in the test | // RUN: %empty-directory(%t)
// RUN: %empty-directory(%t/linker)
// RUN: %target-build-swift -emit-module -c %S/Inputs/library.swift -o %t/linker/library.o
// RUN: %target-build-swift -emit-library -c %S/Inputs/library.swift -o %t/linker/library.o
// RUN: %target-build-swift %S/main.swift %t/linker/library.o -I %t/linker/ -L %t/linker/ -o %t/linker/main
// RUN: %target-build-swift -g -emit-module -c %S/Inputs/library.swift -o %t/linker/library.o
// RUN: %target-build-swift -g -emit-library -c %S/Inputs/library.swift -o %t/linker/library.o
// RUN: %target-build-swift -g %S/main.swift %t/linker/library.o -I %t/linker/ -L %t/linker/ -o %t/linker/main
import library
func testFunction<T>(withCompletion completion: (Result<T, Error>) -> Void) { }
testFunction { (result: GenericResult<Int>) in }
| // RUN: %empty-directory(%t)
// RUN: %empty-directory(%t/linker)
// RUN: %target-build-swift -emit-module -c %S/Inputs/library.swift -o %t/linker/library.o
// RUN: %target-build-swift -emit-library -c %S/Inputs/library.swift -o %t/linker/library.o
// RUN: %target-build-swift %S/main.swift %t/linker/library.o -I %t/linker/ -L %t/linker/ -o %t/linker/main
// RUN: %target-build-swift -g -emit-module -c %S/Inputs/library.swift -o %t/linker/library.o
// RUN: %target-build-swift -g -emit-library -c %S/Inputs/library.swift -o %t/linker/library.o
// RUN: %target-build-swift -g %S/main.swift %t/linker/library.o -I %t/linker/ -L %t/linker/ -o %t/linker/main
import library
import enum library.Result
func testFunction<T>(withCompletion completion: (Result<T, Error>) -> Void) { }
testFunction { (result: GenericResult<Int>) in }
|
Revert "add exit call when done running" | class SemverIncrementer {
func usage() {
print("usage: origin-version $incrementBy")
print("e.g. semver-incrementer 0.6.6 9")
}
func run(args: [String]) {
guard args.count > 2 else {
useGit()
return
}
useInput(args)
exit(0)
}
func useInput(args: [String]) {
describe(args[1], incrementBy: args[2])
}
func describe(originVersion: String, incrementBy: String) {
guard let version = Semver.fromString(originVersion.trim()) else {
print("error:\(originVersion):not a valid version")
return
}
guard let by = Int(incrementBy) else {
print("error:\(incrementBy) is not a valid increment value")
return
}
print(version.increment(by).short)
}
func useGit() {
guard let git = Git(path:"/usr/bin/git") else {
usage()
return
}
guard let version = git.lastTag as? String else {
print("error: no version")
return
}
describe(version, incrementBy: "1")
}
}
| class SemverIncrementer {
func usage() {
print("usage: origin-version $incrementBy")
print("e.g. semver-incrementer 0.6.6 9")
}
func run(args: [String]) {
guard args.count > 2 else {
useGit()
return
}
useInput(args)
}
func useInput(args: [String]) {
describe(args[1], incrementBy: args[2])
}
func describe(originVersion: String, incrementBy: String) {
guard let version = Semver.fromString(originVersion.trim()) else {
print("error:\(originVersion):not a valid version")
return
}
guard let by = Int(incrementBy) else {
print("error:\(incrementBy) is not a valid increment value")
return
}
print(version.increment(by).short)
}
func useGit() {
guard let git = Git(path:"/usr/bin/git") else {
usage()
return
}
guard let version = git.lastTag as? String else {
print("error: no version")
return
}
describe(version, incrementBy: "1")
}
}
|
Add discardableResult attributes to setters for user defaults | //
// UserDefaults.swift
// P3Foundation
//
// Created by Oscar Swanros on 6/15/16.
// Copyright Β© 2016 Pacific3. All rights reserved.
//
private let userDefaults = UserDefaults.standard()
extension UserDefaults {
// MARK: - Get Values
static func p3_getString(key: String) -> String {
let s = userDefaults.object(forKey: key) as? String
if let s = s {
return s
}
return ""
}
static func p3_getBool(key: String) -> Bool {
return userDefaults.bool(forKey: key)
}
static func p3_getInt(key: String) -> Int {
return userDefaults.integer(forKey: key)
}
// MARK: - Set Values
static func p3_setString(key: String, value: String) -> Bool {
userDefaults.set(value, forKey: key)
return userDefaults.synchronize()
}
static func p3_setBool(key: String, value: Bool) -> Bool {
userDefaults.set(value, forKey: key)
return userDefaults.synchronize()
}
static func p3_setInt(key: String, value: Int) -> Bool {
userDefaults.set(value, forKey: key)
return userDefaults.synchronize()
}
}
| //
// UserDefaults.swift
// P3Foundation
//
// Created by Oscar Swanros on 6/15/16.
// Copyright Β© 2016 Pacific3. All rights reserved.
//
private let userDefaults = UserDefaults.standard()
extension UserDefaults {
// MARK: - Get Values
static func p3_getString(key: String) -> String {
let s = userDefaults.object(forKey: key) as? String
if let s = s {
return s
}
return ""
}
static func p3_getBool(key: String) -> Bool {
return userDefaults.bool(forKey: key)
}
static func p3_getInt(key: String) -> Int {
return userDefaults.integer(forKey: key)
}
// MARK: - Set Values
@discardableResult
static func p3_setString(key: String, value: String) -> Bool {
userDefaults.set(value, forKey: key)
return userDefaults.synchronize()
}
@discardableResult
static func p3_setBool(key: String, value: Bool) -> Bool {
userDefaults.set(value, forKey: key)
return userDefaults.synchronize()
}
@discardableResult
static func p3_setInt(key: String, value: Int) -> Bool {
userDefaults.set(value, forKey: key)
return userDefaults.synchronize()
}
}
|
Make Blobfish error configuration public | //
// Nodes.swift
// Nodes
//
// Created by Kasper Welner on 18/03/16.
// Copyright Β© 2016 Nodes. All rights reserved.
//
import Foundation
import Blobfish
public struct BlobfishConfiguration {
static func errorCodeMapping() -> [Int : Blobfish.AlamofireConfig.ErrorCategory] {
return [
441 : .token,
442 : .token,
443 : .token,
]
}
}
| //
// Nodes.swift
// Nodes
//
// Created by Kasper Welner on 18/03/16.
// Copyright Β© 2016 Nodes. All rights reserved.
//
import Foundation
import Blobfish
public struct BlobfishConfiguration {
public static func errorCodeMapping() -> [Int : Blobfish.AlamofireConfig.ErrorCategory] {
return [
441 : .token,
442 : .token,
443 : .token,
]
}
}
|
Fix test compilation re: transformError | // Shirley
// Written in 2015 by Nate Stedman <nate@natestedman.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and
// related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with
// this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
@testable import Shirley
import ReactiveCocoa
import XCTest
class TransformSessionTests: XCTestCase
{
func testTransformedValues()
{
let session = TransformSession(session: SquareSession(), flattenStrategy: .Concat, transform: { result in
SignalProducer(value: result * 2)
})
XCTAssertEqual(session.producerForRequest(2).first()?.value, 8)
}
func testTransformedErrors()
{
let session = TransformSession(session: ErrorSession(), transform: { error in
SignalProducer(error: TestError(value: error.value + 1))
})
XCTAssertEqual(session.producerForRequest(2).first()?.error?.value, 3)
}
}
| // Shirley
// Written in 2015 by Nate Stedman <nate@natestedman.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and
// related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with
// this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
@testable import Shirley
import ReactiveCocoa
import XCTest
class TransformSessionTests: XCTestCase
{
func testTransformedValues()
{
let session = TransformSession(session: SquareSession(), flattenStrategy: .Concat, transform: { result in
SignalProducer(value: result * 2)
})
XCTAssertEqual(session.producerForRequest(2).first()?.value, 8)
}
func testTransformedErrors()
{
let session = TransformSession(session: ErrorSession(), transformError: { error in
SignalProducer(error: TestError(value: error.value + 1))
})
XCTAssertEqual(session.producerForRequest(2).first()?.error?.value, 3)
}
}
|
Add test for status new | import XCTest
class TMHomeStrategyFactory:XCTestCase
{
}
| import XCTest
@testable import gattaca
class TMHomeStrategyFactory:XCTestCase
{
private var controller:CHome?
private var session:MSession?
override func setUp()
{
super.setUp()
let session:MSession = MSession()
self.session = session
controller = CHome(session:session)
}
//MARK: internal
func testInit()
{
XCTAssertNotNil(
session,
"failed to create session")
XCTAssertNotNil(
controller,
"failed to create controller")
}
func testFactoryStrategyNew()
{
guard
let controller:CHome = self.controller
else
{
return
}
session?.status = MSession.Status.new
let strategy:MHomeStrategy? = MHomeStrategy.factoryStrategy(
controller:controller)
let strategyNew:MHomeStrategyNew? = strategy as? MHomeStrategyNew
XCTAssertNotNil(
strategyNew,
"failed loading strategy for status new")
}
}
|
Add blank row at top | //
// ConfigViewController.swift
// Patriot
//
// Created by Ron Lisle on 5/29/17.
// Copyright Β© 2017 Ron Lisle. All rights reserved.
//
import UIKit
class ConfigViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func closeMenu(sender: AnyObject) {
dismiss(animated: true, completion: nil)
}
}
| //
// ConfigViewController.swift
// Patriot
//
// Created by Ron Lisle on 5/29/17.
// Copyright Β© 2017 Ron Lisle. All rights reserved.
//
import UIKit
class ConfigViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func closeMenu(sender: AnyObject) {
dismiss(animated: true, completion: nil)
}
override func viewDidLayoutSubviews() {
if let rect = self.navigationController?.navigationBar.frame {
let y = rect.size.height + rect.origin.y
self.tableView.contentInset = UIEdgeInsetsMake( y, 0, 0, 0)
}
}
}
|
Complete demo with workable pedometer. | //
// ViewController.swift
// CoreMotionDemo
//
// Created by BJ Miller on 8/6/14.
// Copyright (c) 2014 Six Five Software, LLC. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var stepCountLabel: UILabel!
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var rateLabel: UILabel!
@IBOutlet weak var lastUpdatedLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
}
| //
// ViewController.swift
// CoreMotionDemo
//
// Created by BJ Miller on 8/6/14.
// Copyright (c) 2014 Six Five Software, LLC. All rights reserved.
//
import UIKit
import CoreMotion
class ViewController: UIViewController {
let pedometer = CMPedometer()
var lastDistance = 0.0
var lastUpdatedDate = NSDate()
let dateFormatter = NSDateFormatter()
@IBOutlet weak var stepCountLabel: UILabel!
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var rateLabel: UILabel!
@IBOutlet weak var lastUpdatedLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle
}
override func viewWillAppear(animated: Bool) {
setupPedometer()
super.viewWillAppear(animated)
}
override func viewWillDisappear(animated: Bool) {
pedometer.stopPedometerUpdates()
super.viewWillDisappear(animated)
}
func setupPedometer() {
if CMPedometer.isStepCountingAvailable() {
self.pedometer.startPedometerUpdatesFromDate(midnight) { pedometerData, pedError in
if pedError != nil {
// failed, handle error
} else {
let meters = pedometerData.distance.doubleValue
let distanceFormatter = NSLengthFormatter()
let timeDelta = pedometerData.endDate.timeIntervalSinceDate(self.lastUpdatedDate)
let distanceDelta = meters - self.lastDistance
let rate = distanceDelta / timeDelta
self.lastUpdatedDate = NSDate()
self.lastDistance = meters
dispatch_async(dispatch_get_main_queue()) {
self.stepCountLabel.text = "\(pedometerData.numberOfSteps.integerValue) steps"
self.distanceLabel.text = "\(distanceFormatter.stringFromMeters(meters))"
self.rateLabel.text = "\(distanceFormatter.stringFromMeters(rate)) / s"
self.lastUpdatedLabel.text = "Last updated: \(self.dateFormatter.stringFromDate(pedometerData.endDate))"
}
}
}
}
}
var midnight: NSDate {
let cal = NSCalendar.autoupdatingCurrentCalendar()
return cal.startOfDayForDate(NSDate())
}
}
|
Make the combined changeable mutable so we can use it with the binding context | //
// CombinedChangeable.swift
// SwiftRebound
//
// Created by Andrew Hunter on 12/07/2016.
//
//
import Foundation
///
/// Changeable implementation that works by combined many changeable objects into one
///
internal class CombinedChangeable : Changeable {
/// The chageables that are combined in this one
private let _combined: [Changeable];
init(changeables: [Changeable]) {
var flatChangeables = [Changeable]();
// Flatten out the list so that we don't create nested combined changeables
for changeable in changeables {
let alsoCombined = changeable as? CombinedChangeable;
if let alsoCombined = alsoCombined {
flatChangeables.appendContentsOf(alsoCombined._combined);
}
}
_combined = flatChangeables;
}
///
/// Calls a function any time this value is marked as changed
///
func whenChanged(target: Notifiable) -> Lifetime {
var lifetimes = [Lifetime]();
// Combine the changeables and generate a lifetime for each one
for changeable in _combined {
let lifetime = changeable.whenChanged(target);
lifetimes.append(lifetime);
}
// Result is a combined lifetime
return CombinedLifetime(lifetimes: lifetimes);
}
}
| //
// CombinedChangeable.swift
// SwiftRebound
//
// Created by Andrew Hunter on 12/07/2016.
//
//
import Foundation
///
/// Changeable implementation that works by combined many changeable objects into one
///
internal class CombinedChangeable : Changeable {
/// The chageables that are combined in this one
private var _combined: [Changeable];
init(changeables: [Changeable]) {
var flatChangeables = [Changeable]();
// Flatten out the list so that we don't create nested combined changeables
for changeable in changeables {
let alsoCombined = changeable as? CombinedChangeable;
if let alsoCombined = alsoCombined {
flatChangeables.appendContentsOf(alsoCombined._combined);
}
}
_combined = flatChangeables;
}
///
/// Calls a function any time this value is marked as changed
///
func whenChanged(target: Notifiable) -> Lifetime {
var lifetimes = [Lifetime]();
// Combine the changeables and generate a lifetime for each one
for changeable in _combined {
let lifetime = changeable.whenChanged(target);
lifetimes.append(lifetime);
}
// Result is a combined lifetime
return CombinedLifetime(lifetimes: lifetimes);
}
///
/// Adds a new changeable to the changeable items being managed by this object
///
func addChangeable(newChangeable: Changeable) {
_combined.append(newChangeable);
}
}
|
Add @noescape attribute to `each` function's closure | //
// ArrayUtils.swift
// QuickJump
//
// Created by Victor Shamanov on 5/29/15.
// Copyright (c) 2015 Victor Shamanov. All rights reserved.
//
import Foundation
extension Array {
var decomposed: (T, [T])? {
return isEmpty ? nil : (first!, Array(dropFirst(self)))
}
func each(f: T -> Void) {
for x in self {
f(x)
}
}
func findFirst(p: T -> Bool) -> T? {
for x in self {
if p(x) {
return x
}
}
return nil
}
}
| //
// ArrayUtils.swift
// QuickJump
//
// Created by Victor Shamanov on 5/29/15.
// Copyright (c) 2015 Victor Shamanov. All rights reserved.
//
import Foundation
extension Array {
var decomposed: (T, [T])? {
return isEmpty ? nil : (first!, Array(dropFirst(self)))
}
func each(@noescape f: T -> Void) {
for x in self {
f(x)
}
}
func findFirst(p: T -> Bool) -> T? {
for x in self {
if p(x) {
return x
}
}
return nil
}
}
|
Add binarySearch extension to Array | import Foundation
// http://stackoverflow.com/questions/31904396/swift-binary-search-for-standard-array
extension Array {
/// Finds such index N that predicate is true for all elements up to
/// but not including the index N, and is false for all elements
/// starting with index N.
/// Behavior is undefined if there is no such N.
public func binarySearch(predicate: (Iterator.Element) -> Bool) -> Index {
var low = startIndex
var high = endIndex
while low != high {
let mid = index(low, offsetBy: distance(from: low, to: high)/2)
if predicate(self[mid]) {
low = index(after: mid)
} else {
high = mid
}
}
return low
}
}
| |
Add minimal test case for rdar://problem/54580427. | // FIXME: This should be linear instead of exponential.
// RUN: %scale-test --begin 1 --end 10 --step 1 --select NumLeafScopes --invert-result %s
// REQUIRES: OS=macosx
// REQUIRES: asserts
enum Val {
case d([String: Val])
case f(Double)
}
struct X {
var x : Float
}
extension X {
func val() -> Val {
return Val.d([
%for i in range(0, N):
"x": .f(Double(x)),
%end
])
}
}
| |
Add basic SwiftPM manifest file for iOS | // swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "RxGesture",
products: [
.library(name: "RxGesture", targets: ["RxGesture"])
],
targets: [
.target(
name: "RxGesture",
path: "Pod",
exclude: ["Pod/Classes/OSX"]
)
]
)
| |
Add test case for crash triggered in swift::constraints::ConstraintSystem::assignFixedType(swift::TypeVariableType*, swift::Type, bool) | // RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{println(""""?struct{
| |
Split the initialization test cases into their own file. | // RUN: rm -rf %t/clang-module-cache
// RUN: %swift %clang-importer-sdk -emit-sil -module-cache-path %t/clang-module-cache -I %S/Inputs/custom-modules -target x86_64-apple-darwin13 %s -verify
// RUN: ls -lR %t/clang-module-cache | grep ObjectiveC.pcm
import AppKit
import objc_ext
import TestProtocols
import ObjCParseExtras
// Subclassing and designated initializers
func testNSInterestingDesignated() {
NSInterestingDesignated()
NSInterestingDesignated(withString:"hello")
NSInterestingDesignatedSub()
NSInterestingDesignatedSub(withString:"hello")
}
class MyDocument1 : NSDocument {
init() {
super.init()
}
}
func createMyDocument1() {
var md = MyDocument1()
md = MyDocument1(withURL: "http://llvm.org")
}
class MyDocument2 : NSDocument {
init withURL(url: String) {
return super.init(withURL: url) // expected-error{{must call a designated initializer of the superclass 'NSDocument'}}
}
}
class MyDocument3 : NSAwesomeDocument {
init() {
super.init()
}
}
func createMyDocument3() {
var md = MyDocument3()
md = MyDocument3(withURL: "http://llvm.org")
}
class MyInterestingDesignated : NSInterestingDesignatedSub {
init withString(str: String) {
super.init(withString: str)
}
init withInt(i: Int) {
super.init() // expected-error{{must call a designated initializer of the superclass 'NSInterestingDesignatedSub'}}
}
}
func createMyInterestingDesignated() {
var md = MyInterestingDesignated(withURL: "http://llvm.org")
}
func testNoReturn(a : NSAwesomeDocument) -> Int {
a.noReturnMethod(42)
return 17 // TODO: In principle, we should produce an unreachable code diagnostic here.
}
| |
Add a solution to Flatten Binary Tree to Linked List | /**
* Question Link: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
* Primary idea: Reset left to nil and change current node to left child every time
* Time Complexity: O(n), Space Complexity: O(1)
*
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class FlattenBinaryTreeLinkedList {
func flatten(_ root: TreeNode?) {
helper(root)
}
private func helper(_ node: TreeNode?) -> TreeNode? {
var node = node
if node == nil {
return node
}
if node!.left == nil && node!.right == nil {
return node
}
let left = node!.left, right = node!.right
node!.left = nil
if let left = left {
node!.right = left
node = helper(left)
}
if let right = right {
node!.right = right
node = helper(right)
}
return node
}
} | |
Add a simple ClassBasedOnClickListener example to the StoryboardExample project | //
// ExampleFolioReaderContainer
// StoryboardExample
//
// Created by Panajotis Maroungas on 18/08/16.
// Copyright Β© 2016 FolioReader. All rights reserved.
//
import UIKit
import FolioReaderKit
class ExampleFolioReaderContainer: FolioReaderContainer {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let config = FolioReaderConfig()
config.scrollDirection = .horizontalWithVerticalContent
guard let bookPath = NSBundle.mainBundle().pathForResource("The Silver Chair", ofType: "epub") else { return }
setupConfig(config, epubPath: bookPath)
}
} | //
// ExampleFolioReaderContainer
// StoryboardExample
//
// Created by Panajotis Maroungas on 18/08/16.
// Copyright Β© 2016 FolioReader. All rights reserved.
//
import UIKit
import FolioReaderKit
class ExampleFolioReaderContainer: FolioReaderContainer {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let config = FolioReaderConfig()
config.scrollDirection = .horizontalWithVerticalContent
config.shouldHideNavigationOnTap = false
// Print the chapter ID if one was clicked
// A chapter in "The Silver Chair" looks like this "<section class="chapter" title="Chapter I" epub:type="chapter" id="id70364673704880">"
// To knwo if a user tapped on a chapter we can listen to events on the class "chapter" and receive the id value
let listener = ClassBasedOnClickListener(schemeName: "chapterTapped", className: "chapter", parameterName: "id", onClickAction: { (parameterContent: String?) in
print("chapter with id: " + (parameterContent ?? "-") + " clicked")
})
config.classBasedOnClickListeners.append(listener)
guard let bookPath = NSBundle.mainBundle().pathForResource("The Silver Chair", ofType: "epub") else { return }
setupConfig(config, epubPath: bookPath)
}
} |
Move IEEE754 support into its own file | enum IEEEFloatingPointClass {
case SignalingNaN
case QuietNaN
case NegativeInfinity
case NegativeNormal
case NegativeSubnormal
case NegativeZero
case PositiveZero
case PositiveSubnormal
case PositiveNormal
case PositiveInfinity
}
extension IEEEFloatingPointClass : Equatable {}
func ==(lhs: IEEEFloatingPointClass, rhs: IEEEFloatingPointClass) -> Bool {
switch (lhs, rhs) {
case (.SignalingNaN, .SignalingNaN):
case (.QuietNaN, .QuietNaN):
case (.NegativeInfinity, .NegativeInfinity):
case (.NegativeNormal, .NegativeNormal):
case (.NegativeSubnormal, .NegativeSubnormal):
case (.NegativeZero, .NegativeZero):
case (.PositiveZero, .PositiveZero):
case (.PositiveSubnormal, .PositiveSubnormal):
case (.PositiveNormal, .PositiveNormal):
case (.PositiveInfinity, .PositiveInfinity):
return true
default:
return false
}
}
protocol IEEEFloatingPointNumber {
typealias _BitsType
static func _fromBitPattern(bits: _BitsType) -> Self
func _toBitPattern() -> _BitsType
// FIXME: make these readonly static properties.
/// Returns positive infinity.
static func inf() -> Self
/// Returns a quiet NaN.
static func NaN() -> Self
static func quietNaN() -> Self
static func signalingNaN() -> Self
/// @{
/// IEEE 754-2008 Non-computational operations.
// IEEE 754 calls this 'class', but this name is a keyword, and is too
// general.
// FIXME: make readonly.
var floatingPointClass: IEEEFloatingPointClass
/// Returns true if this number has a negative sign.
func isSignMinus() -> Bool
/// Returns true if this number is normal (not zero, subnormal, infinite, or
/// NaN).
func isNormal() -> Bool
/// Returns true if this number is zero, subnormal, or normal (not infinite
/// or NaN).
func isFinite() -> Bool
/// Returns true if this number is +0.0 or -0.0.
func isZero() -> Bool
/// Returns true if this number is subnormal.
func isSubnormal() -> Bool
/// Returns true if this number is infinite.
func isInfinite() -> Bool
/// Returns true if this number is NaN.
func isNaN() -> Bool
/// Returns true if this number is a signaling NaN.
func isSignaling() -> Bool
// Not implemented, because it only makes sense for decimal floating point.
// Binary floating point numbers are always canonical.
// func isCanonical() -> Bool
/// @}
}
| |
Extend `Data` with `func readData(toByte byte:UInt8, maximumLength:Int = Int.max) -> Data`. | /***************************************************************************************************
FileHandle+ReadDataToByte.swift
Β© 2017 YOCKOW.
Licensed under MIT License.
See "LICENSE.txt" for more information.
**************************************************************************************************/
import Foundation
extension FileHandle {
/// Read data until `byte` appears.
public func readData(toByte byte:UInt8, maximumLength:Int = Int.max) -> Data {
var result = Data()
for _ in 0..<maximumLength {
let byteData = self.readData(ofLength:1)
if byteData.isEmpty { break }
result.append(byteData)
if byteData[0] == byte { return result }
}
return result
}
}
| |
Add test case for crash triggered in swift::Expr::propagateLValueAccessKind(swift::AccessKind, bool) | // RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class g{deinit{{&.T
| |
Add two way binding operator | //
// TextfieldBinding.swift
// Pods
//
// Created by Jakub OlejnΓk on 28/06/2017.
//
//
import ReactiveSwift
infix operator <~> : BindingPrecedence
public func <~> (property: MutableProperty<String?>, textField: UITextField) {
textField.reactive.text <~ property
property <~ textField.reactive.continuousTextValues
}
public func <~> (textField: UITextField, property: MutableProperty<String?>) {
textField.reactive.text <~ property
property <~ textField.reactive.continuousTextValues
}
public func <~> (property: MutableProperty<String>, textField: UITextField) {
textField.reactive.text <~ property
property <~ textField.reactive.continuousTextValues.map { $0 ?? "" }
}
public func <~> (textField: UITextField, property: MutableProperty<String>) {
textField.reactive.text <~ property
property <~ textField.reactive.continuousTextValues.map { $0 ?? "" }
}
public func <~> (property: MutableProperty<String?>, textField: UITextView) {
textField.reactive.text <~ property
property <~ textField.reactive.continuousTextValues
}
public func <~> (textField: UITextView, property: MutableProperty<String?>) {
textField.reactive.text <~ property
property <~ textField.reactive.continuousTextValues
}
public func <~> (textField: UITextView, property: MutableProperty<String>) {
textField.reactive.text <~ property
property <~ textField.reactive.continuousTextValues.map { $0 ?? "" }
}
| |
Test the ObserveTest's runBeforeEachChild method | //
// WhenRunningBeforeAndAfterChildrenBlockFromATestObject.swift
// Observe
//
// Created by Sam Meech-Ward on 2016-12-09.
//
//
@testable import Observe
import XCTest
class WhenRunningBeforeAndAfterChildrenBlockFromATestObject: XCTestCase {
var observeTest: ObserveTest!
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
observeTest = ObserveTest()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func test_runBeforeEachChild() {
}
func test_runBeforeEachChild_runsTheClosure() {
var run = false
observeTest.beforeEachChild = {
run = true
}
observeTest.runBeforeEachChild()
XCTAssertTrue(run)
}
}
func test_popNextChild() {
}
| |
Add π₯ case (π’ β 51, π β 5090) triggered in swift::createDesignatedInitOverride(β¦) | // 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
// RUN: not --crash %target-swift-frontend %s -parse
let:{{class a{enum S<U:a{class B:a{init}}class a
| |
Add test case for leak fixed by my SILGenPattern work. | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
// Make sure that in the following code we do not leak the case of the enum.
protocol MyProtocol {}
// An enum that wraps LeakingClass
enum LeakingEnum1: MyProtocol {
case eNone1
case eLeakingClass1(LifetimeTracked)
}
// An enum that wraps LeakingClass
enum LeakingEnum2 : MyProtocol {
case eNone2
case eLeakingClass2(LifetimeTracked)
}
var Tests = TestSuite("patternmatch_on_enum_protocol_leak")
Tests.test("dontLeak") {
do {
let leakingClass = LifetimeTracked(0)
let leakEnum = LeakingEnum1.eLeakingClass1(leakingClass)
let control: MyProtocol = leakEnum
// This switch case order, interleaving LeakingEnum1 and LeakingEnum2 cases triggers the leak.
switch control
{
case LeakingEnum1.eNone1: break
case LeakingEnum2.eNone2: break
case LeakingEnum1.eLeakingClass1: break
case LeakingEnum2.eLeakingClass2: break
default: break
}
}
expectEqual(0, LifetimeTracked.instances)
}
runAllTests()
| |
Add Service/Characteristic Identifiers for easier use | //
// CarSmartsService.swift
// SmartCar
//
// Created by Robert Smith on 4/30/17.
// Copyright Β© 2017 Robert Smith. All rights reserved.
//
import Foundation
import RxBluetoothKit
import CoreBluetooth
enum CarSmartsService: String, ServiceIdentifier {
case smartLock = "A1A4C256-3370-4D9A-99AA-70BFA81B906B"
var uuid: CBUUID {
return CBUUID(string: self.rawValue)
}
}
enum SmartLockCharacteristic: String, CharacteristicIdentifier {
case lock = "6121294F-5171-4F3D-BD46-43ADAADDA75C"
case window = "79EFB0FA-484F-4202-8C5F-A90EC8FD6605"
var uuid: CBUUID {
return CBUUID(string: self.rawValue)
}
var service: ServiceIdentifier {
return CarSmartsService.smartLock
}
}
| |
Add test case for crash triggered in swift::constraints::ConstraintGraph::addConstraint(swift::constraints::Constraint*) | // RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a{
var f=[[
map class d
{
protocol A:A
{
typealias d
class A:A
func a
class A:d
| |
Create area item ground prot | //
// MOptionTamalesOaxaquenosAreaItemGroundProtocol.swift
// miniMancera
//
// Created by zero on 7/14/17.
// Copyright Β© 2017 iturbide. All rights reserved.
//
import Foundation
| |
Add a test for serialization under optimizations. | // RUN: rm -rf %t && mkdir -p %t
// RUN: %swift -O -emit-module -o %t %s
// At one point this triggered deserialization of enough of the stdlib to cause
// an assertion failure in serialization.
class Rdar17567391 {
let data: [Int] = []
}
| |
Add test case for crash triggered in swift::TypeChecker::typeCheckDecl(swift::Decl*, bool) | // RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class B<h{var d={struct d{typealias e:B
let t:e,A
| |
Add test that converts a .swiftinterface to .swiftmodule and uses it. | // RUN: %empty-directory(%t)
// RUN: %empty-directory(%t/modulecache)
// RUN: %target-swift-frontend -enable-resilience -emit-parseable-module-interface-path %t/TestModule.swiftinterface -module-name TestModule %S/Inputs/other.swift -emit-module -o /dev/null
// RUN: test -f %t/TestModule.swiftinterface
// RUN: %target-swift-frontend -typecheck -enable-parseable-module-interface -module-cache-path %t/modulecache -I %t %s
// RUN: llvm-bcanalyzer -dump %t/modulecache/TestModule-*.swiftmodule | %FileCheck %s -check-prefix=CHECK-SWIFTMODULE
// CHECK-SWIFTMODULE: {{MODULE_NAME.*blob data = 'TestModule'}}
// CHECK-SWIFTMODULE: FUNC_DECL
// CHECK-SWIFTMODULE: RESILIENCE_STRATEGY
import TestModule
func foo() {
otherFileFunction()
}
| |
Add a new extension that tint UIImage | //
// UIImageExtension.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 8/16/16.
// Copyright Β© 2016 Rocket.Chat. All rights reserved.
//
import UIKit
extension UIImage {
func imageWithTint(color: UIColor, alpha: CGFloat = 1.0) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.mainScreen().scale)
let context = UIGraphicsGetCurrentContext()
color.setFill()
CGContextTranslateCTM(context, 0, self.size.height)
CGContextScaleCTM(context, 1.0, -1.0)
CGContextSetBlendMode(context, CGBlendMode.ColorBurn)
let rect = CGRectMake(0.0, 0.0, self.size.width, self.size.height)
CGContextDrawImage(context, rect, self.CGImage)
CGContextSetBlendMode(context, CGBlendMode.SourceIn)
CGContextAddRect(context, rect)
CGContextDrawPath(context, CGPathDrawingMode.Fill)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
| |
Add basic SwiftPM manifest file | // swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "MBProgressHUD",
products: [
.library(name: "MBProgressHUD", targets: ["MBProgressHUD"])
],
targets: [
.target(
name: "MBProgressHUD",
path: ".",
exclude: ["Demo"],
sources: ["MBProgressHUD.h", "MBProgressHUD.m"]
)
]
)
| |
Add tests for URLProtectionSpace.description property | // 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
//
class TestURLProtectionSpace : XCTestCase {
static var allTests: [(String, (TestURLProtectionSpace) -> () throws -> Void)] {
return [
("test_description", test_description),
]
}
func test_description() {
var space = URLProtectionSpace(
host: "apple.com",
port: 80,
protocol: "http",
realm: nil,
authenticationMethod: "basic"
)
XCTAssert(space.description.hasPrefix("<URLProtectionSpace "))
XCTAssert(space.description.hasSuffix(": Host:apple.com, Server:http, Auth-Scheme:NSURLAuthenticationMethodDefault, Realm:(null), Port:80, Proxy:NO, Proxy-Type:(null)"))
space = URLProtectionSpace(
host: "apple.com",
port: 80,
protocol: "http",
realm: nil,
authenticationMethod: "NSURLAuthenticationMethodHTMLForm"
)
XCTAssert(space.description.hasPrefix("<URLProtectionSpace "))
XCTAssert(space.description.hasSuffix(": Host:apple.com, Server:http, Auth-Scheme:NSURLAuthenticationMethodHTMLForm, Realm:(null), Port:80, Proxy:NO, Proxy-Type:(null)"))
}
}
| |
Add logic for getting files lines. | import Foundation
let path = FileManager.default.currentDirectoryPath
let file = "\(path)/Sources/game_configurations.txt"
do {
let gameConfigurations: String = try String(
contentsOfFile: file,
encoding: String.Encoding.utf8
)
var lines = gameConfigurations.components(separatedBy: "\n")
// remove unnecessary lines like commented and empty one
lines = lines.filter { $0.isEmpty == false }
lines = lines.filter { $0[$0.startIndex] != "#" }
print(lines)
} catch let error {
print(error)
}
| |
Add solution for 137. Single Number II. | /**
* Question Link: https://leetcode.com/problems/single-number-ii/
* Primary idea: Every number has 64 bits, for the i-th bit of each number.
* In total, we should have (nums.count) 0s and 1s.
* If the i-th bit of the single number is 1, then we should have (3n + 1) 1s, and (3n) 0s.
* Otherwise, the i-th bit is 0.
* In this way, we can calculate each bit of the single number.
*
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class Solution {
func singleNumber(nums: [Int]) -> Int {
var ans = 0
var sum = 0
for i in 0 ..< 64 {
sum = 0
let tmp = (1 << i)
for j in 0 ..< nums.count {
if tmp & nums[j] != 0 {
sum = sum + 1
}
}
if sum % 3 == 1 {
ans = ans ^ tmp
}
}
return ans
}
}
| |
Add test case for crash triggered in swift::IterativeTypeChecker::processInheritedProtocols(swift::ProtocolDecl*, llvm::function_ref<bool (swift::TypeCheckRequest)>) | // RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
// REQUIRES: asserts
protocol e:A.a
class A{
protocol c:e
func a<H:A.c func a#^A^# | |
Add test case for crash triggered in swift::ValueDecl::setType(swift::Type) | // RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
// REQUIRES: asserts
protocol P{struct X{let a={class d:a{class B<b:a{#^A^# | |
Add test case for crash triggered in swift::BoundGenericType::getSubstitutions(swift::ModuleDecl*, swift::LazyResolver*, swift::DeclContext*) | // RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
class A<h{#^A^#class B<a{let:AnyObject.Type=B | |
Add a SwiftPM 4 version of the manifest. | // swift-tools-version:4.0
// Package.swift
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
import PackageDescription
let package = Package(
name: "SwiftProtobuf",
products: [
.executable(name: "protoc-gen-swift", targets: ["protoc-gen-swift"]),
.library(name: "SwiftProtobuf", type: .static, targets: ["SwiftProtobuf"]),
],
targets: [
.target(name: "SwiftProtobuf"),
.target(name: "PluginLibrary",
dependencies: ["SwiftProtobuf"]),
.target(name: "protoc-gen-swift",
dependencies: ["PluginLibrary", "SwiftProtobuf"]),
.target(name: "Conformance",
dependencies: ["SwiftProtobuf"]),
.testTarget(name: "SwiftProtobufTests",
dependencies: ["SwiftProtobuf"]),
.testTarget(name: "PluginLibraryTests",
dependencies: ["PluginLibrary"]),
],
swiftLanguageVersions: [3, 4]
)
| |
Add cache manager by Swiftful Thinking | //
// CacheManager.swift
// FetchJsonEscapable
//
// Created by Alexander Farber on 05.05.21.
//
class CacheManager {
static let instance = CacheManager()
private init()
var imageCache: NSCache<NSString, UIImage> = {
let cache = NSCache<NSString, UIImage>()
cache.countLimit = 100
cache.totalCostLimit = 100 * 1024 * 1024
return cache
}()
func add(image: UIImage, name: String) {
imageCache.setObject(image, forKey: name as NSString)
}
func remove(name: String) {
imageCache.removeObject(image, forKey: name as NSString)
}
func get(name: String) -> UIImage? {
return imageCache.object(forKey: name as NSString)
}
}
| |
Add test case for crash triggered in swift::Expr::propagateLValueAccessKind(swift::AccessKind, bool) | // RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let e=[[[]_
| |
Add App Store page presenting for SwiftUI | //
// StoreSheet.swift
// ZamzamUI
//
// Created by Basem Emara on 2021-08-07.
// Copyright Β© 2021 Zamzam Inc. All rights reserved.
//
#if os(iOS) && canImport(StoreKit)
import StoreKit
import SwiftUI
public extension View {
/// Presents iTunes Store product information using the given App Store parameters.
///
/// - Parameters:
/// - itunesID: The iTunes identifier for the item you want the store to display when the view controller is presented.
/// - affiliateToken: The affiliate identifier you wish to use for any purchase made through the view controller.
/// - campaignToken: An App Analytics campaign.
/// - application: The application to present the store page from.
/// - completion: The block to execute after the presentation finishes.
func open(
itunesID: String,
affiliateToken: String? = nil,
campaignToken: String? = nil,
application: UIApplication,
completion: (() -> Void)? = nil
) {
// Temporary solution until supported by SwiftUI:
// https://stackoverflow.com/q/64503955
let viewController = SKStoreProductViewController()
var parameters = [SKStoreProductParameterITunesItemIdentifier: itunesID]
if let affiliateToken = affiliateToken {
parameters[SKStoreProductParameterAffiliateToken] = affiliateToken
}
if let campaignToken = campaignToken {
parameters[SKStoreProductParameterCampaignToken] = campaignToken
}
viewController.loadProduct(withParameters: parameters) { loaded, _ in
guard let rootViewController = application.connectedScenes
.filter({ $0.activationState == .foregroundActive })
.compactMap({ $0 as? UIWindowScene })
.first?
.windows
.filter(\.isKeyWindow)
.first?
.rootViewController,
loaded
else {
completion?()
return
}
rootViewController.present(viewController, animated: true, completion: completion)
}
}
}
#endif
| |
Add test case for crash triggered in swift::constraints::ConstraintSystem::diagnoseFailureForExpr(swift::Expr*) | // This source file is part of the Swift.org open source project
// See http://swift.org/LICENSE.txt for license information
// RUN: not --crash %target-swift-frontend %s -parse
!(0^_{
| |
Add a test for a crasher that was reported. | // RUN: not --crash %target-typecheck-verify-swift
extension Dictionary {
func doSomething<T>() -> [T : Value] {
let pairs: [(T, Value)] = []
return Dictionary(uniqueKeysWithValues: pairs)
}
}
| |
Add accessors for rows and columns | //
// MatrixRowsAndColumns.swift
// SwiftNum
//
// Created by Donald Pinckney on 1/4/17.
//
//
public extension Matrix {
// Returns an array of row vectors
var rows: [Matrix] {
return (0..<height).map { self[$0, 0..<width] }
}
// Return an array of column vectors
var columns: [Matrix] {
return (0..<width).map { self[0..<height, $0] }
}
}
| |
Add tests for DeepL integration | @testable import BartyCrouchTranslator
import Foundation
import Microya
import XCTest
class DeeplTranslatorApiTests: XCTestCase {
func testTranslate() {
let apiKey = "" // TODO: load from environment variable
guard !apiKey.isEmpty else { return }
let endpoint = DeeplApi.translate(
texts: ["How old are you?", "Love"],
from: .english,
to: .german,
apiKey: apiKey
)
let apiProvider = ApiProvider<DeeplApi>()
switch apiProvider.performRequestAndWait(on: endpoint, decodeBodyTo: DeeplTranslateResponse.self) {
case let .success(translateResponses):
XCTAssertEqual(translateResponses.translations[0].text, "Wie alt sind Sie?")
case let .failure(failure):
XCTFail(failure.localizedDescription)
}
}
}
| |
Move parameter extraction to userdefaults extension in separate file | //
// UserDefaults+LaunchParameters.swift
// Callisto
//
// Created by Patrick Kladek on 02.08.19.
// Copyright Β© 2019 IdeasOnCanvas. All rights reserved.
//
import Foundation
extension UserDefaults {
enum Action: String, CaseIterable {
case summarize
case upload
case unknown
}
var action: Action {
switch self.string(forKey: "action") {
case "summarize":
return .summarize
case "upload":
return .upload
default:
LogError("No action specified. Possible values are: \(Action.allCases.filter { $0 != .unknown }.map { $0.rawValue })")
exit(ExitCodes.invalidAction.rawValue)
}
}
var fastlaneOutputURL: URL {
return self.url(forKey: "fastlane") ?? { quit(.invalidFile) }()
}
var branch: String {
return self.string(forKey: "branch") ?? { quit(.invalidBranch) }()
}
var githubAccount: GithubAccount {
let username = self.string(forKey: "githubUsername") ?? { quit(.invalidGithubUsername) }()
let token = self.string(forKey: "githubToken") ?? { quit(.invalidGithubCredentials) }()
return GithubAccount(username: username, token: token)
}
var githubRepository: GithubRepository {
let organisation = self.string(forKey: "githubOrganisation") ?? { quit(.invalidGithubOrganisation) }()
let repository = self.string(forKey: "githubRepository") ?? { quit(.invalidGithubRepository) }()
return GithubRepository(organisation: organisation, repository: repository)
}
var slackURL: URL {
let slackPath = self.string(forKey: "slack") ?? { quit(.invalidSlackWebhook) }()
return URL(string: slackPath) ?? { quit(.invalidSlackWebhook) }()
}
var ignoredKeywords: [String] {
return self.string(forKey: "ignore")?.components(separatedBy: ", ") ?? []
}
}
| |
Add regression test for substituting type var into template | // THIS-TEST-SHOULD-NOT-COMPILE
// Regression test for compiler internal error where we substitute invalid
// type into typevar
// NOTE: if we allow passing structs into TCL code directly, will need
// to modify test
type test {
int a;
int b;
}
<T> puts (T t) "turbine" "0.0.0" [
"puts <<t>>"
];
main () {
test t;
t.a = 1;
t.b = 2;
puts(t);
}
| |
Create a new PlayScene object with the same size of the current scene | import SpriteKit
class GameScene: SKScene {
// Play button node
let playButton = SKSpriteNode(imageNamed: "play")
override func didMoveToView(view: SKView) {
// Position the play button in the middle of the screen
// It position the button in the middle of the frame.
self.playButton.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
// Add the button to the screen
self.addChild(self.playButton)
// Set the background color
self.backgroundColor = UIColor(hex: 0x809DFF)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch:AnyObject in touches{
// Grab the touch location
let location = touch.locationInNode(self)
// Retrieve the sprite in that location
// If the sprite at that location is matching play button, the do something!
if( self.nodeAtPoint(location) == self.playButton){
println("Start playing")
}
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
| import SpriteKit
class GameScene: SKScene {
// Play button node
let playButton = SKSpriteNode(imageNamed: "play")
override func didMoveToView(view: SKView) {
// Position the play button in the middle of the screen
// It position the button in the middle of the frame.
self.playButton.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
// Add the button to the screen
self.addChild(self.playButton)
// Set the background color
self.backgroundColor = UIColor(hex: 0x809DFF)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch:AnyObject in touches{
// Grab the touch location
let location = touch.locationInNode(self)
// Retrieve the sprite in that location
// If the sprite at that location is matching play button, the do something!
if( self.nodeAtPoint(location) == self.playButton){
let playScene = PlayScene(size:self.size)
}
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
|
Add an executable test for checking the correctness of let properties optimizations. | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-build-swift -O %s -o %t/a.out
// RUN: %target-run %t/a.out | FileCheck %s -check-prefix=CHECK-OUTPUT
// REQUIRES: executable_test
// Check that in optimized builds the compiler generates correct code for
// initializations of let properties, which is assigned multipe times inside
// initializers.
public class Foo1 {
internal let Prop1: Int32
internal let Prop2: Int32
// Initialize Prop3 as part of declaration.
internal let Prop3: Int32 = 20
internal let Prop4: Int32
@inline(never)
init(_ count: Int32) {
// Intialize Prop4 unconditionally and only once.
Prop4 = 300
// There are two different assignments to Prop1 and Prop2
// on different branchs of the if-statement.
if count < 2 {
// Initialize Prop1 and Prop2 conditionally.
// Use other properties in the definition of Prop1 and Prop2.
Prop1 = 5
Prop2 = 10 - Prop1 + Prop4 - Prop3
} else {
// Initialize Prop1 and Prop2 conditionally.
// Use other properties in the definition of Prop1 and Prop2.
Prop1 = 100
Prop2 = 200 + Prop1 - Prop4 - Prop3
}
}
}
public func testClassLet(f: Foo1) -> Int32 {
return f.Prop1 + f.Prop2 + f.Prop3 + f.Prop4
}
// Prop1 = 5, Prop2 = (10-5+300-20) = 285, Prop3 = 20, Prop4 = 300
// Hence Prop1 + Prop2 + Prop3 + Prop4 = 610
// CHECK-OUTPUT: 610
print(testClassLet(Foo1(1)))
// Prop1 = 100, Prop2 = (200+100-300-20) = -20, Prop3 = 20, Prop4 = 300
// Hence Prop1 + Prop2 + Prop3 + Prop4 = 610
// CHECK-OUTPUT: 400
print(testClassLet(Foo1(10)))
| |
Add compiler crasher from SR-5825 | // RUN: not --crash %target-swift-frontend %s -emit-ir
struct DefaultAssociatedType {
}
protocol Protocol {
associatedtype AssociatedType = DefaultAssociatedType
init(object: AssociatedType)
}
final class Conformance: Protocol {
private let object: AssociatedType
init(object: AssociatedType) {
self.object = object
}
}
| |
Add fixed crasher for rdar://problem/30154791. | // RUN: not %target-swift-frontend %s -typecheck
struct X<T> {}
struct Y<T> {}
protocol P {
associatedtype T = X<U>
associatedtype U
func foo() -> T
}
protocol Q: P {
func bar() -> T
func bas() -> U
}
extension P {
func foo() -> X<U> { fatalError() }
}
extension Q {
func foo() -> Y<U> { fatalError() }
func bar() -> Y<U> { fatalError() }
}
struct S {}
extension S {
func bas() -> Int {}
}
extension S: Q {}
let x: Y = S().foo()
| |
Add test case for crash triggered in swift::constraints::ConstraintSystem::simplify(bool) | // RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{struct b{let a{struct D{let a=b([print{}}}}struct b
| |
Add test case for crash triggered in swift::TypeChecker::applyUnboundGenericArguments(swift::UnboundGenericType*, swift::SourceLoc, swift::DeclContext*, llvm::MutableArrayRef<swift::TypeLoc>, bool, swift::GenericTypeResolver*) | // RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class B<T{func a{{func g:A}protocol A{typealias e=c<T>struct c<a]typealias d:e
| |
Put ProfilePageView in an UIViewController | //
// ProfileViewController.swift
// Markit
//
// Created by rrao on 10/13/16.
// Copyright Β© 2016 Victor Frolov. All rights reserved.
//
import Foundation
| |
Add an execution test for extensions to CF types. | // RUN: %target-run-simple-swift | FileCheck %s
import Foundation
#if os(OSX)
import AppKit
#endif
#if os(iOS)
import UIKit
#endif
extension CGColorSpace {
class func deviceRGB() -> CGColorSpace {
return CGColorSpaceCreateDeviceRGB()
}
}
extension CGColor {
class func create(#colorSpace: CGColorSpace, #components: [CGFloat])
-> CGColor {
return CGColorCreate(colorSpace, components)
}
var r: CGFloat { return CGColorGetComponents(self)[0] }
var g: CGFloat { return CGColorGetComponents(self)[1] }
var b: CGFloat { return CGColorGetComponents(self)[2] }
}
let pink = CGColor.create(colorSpace: .deviceRGB(),
components: [1.0, 0.5, 0.25, 1.0])
// CHECK: 1.0
println(pink.r)
// CHECK-NEXT: 0.5
println(pink.g)
// CHECK-NEXT: 0.25
println(pink.b)
| |
Add temporary comment depth indicator. | import UIKit
import WMF
// TODO
final class TalkPageCellCommentDepthIndicator: SetupView {
let depth: Int
let label = UILabel()
required init(depth: Int) {
self.depth = depth
super.init(frame: .zero)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
override func setup() {
label.translatesAutoresizingMaskIntoConstraints = false
label.setContentCompressionResistancePriority(.required, for: .horizontal)
label.setContentHuggingPriority(.required, for: .horizontal)
label.font = UIFont.wmf_font(.body)
label.adjustsFontForContentSizeCategory = true
label.text = " \(depth) "
addSubview(label)
NSLayoutConstraint.activate([
label.leadingAnchor.constraint(equalTo: leadingAnchor),
label.trailingAnchor.constraint(equalTo: trailingAnchor),
label.topAnchor.constraint(equalTo: topAnchor),
label.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
}
extension TalkPageCellCommentDepthIndicator: Themeable {
func apply(theme: Theme) {
label.textColor = theme.colors.paperBackground
label.backgroundColor = theme.colors.link
}
}
| |
Add test file for fast completion | class Foo {
var x: Int
var y: Int
func fooMethod() {}
}
struct Bar {
var a: Int
var b: Int
func barMethod() {}
}
func foo(arg: Foo) {
_ = arg.
}
func bar(arg: Bar) {
_ = arg.
}
// NOTE: Tests for 'key.codecomplete.reuseastcontex' option.
// RUN: %sourcekitd-test \
// RUN: -req=track-compiles == \
// RUN: -req=complete -pos=12:11 %s -- %s == \
// RUN: -req=complete -pos=15:11 %s -- %s > %t.response
// RUN: %FileCheck --check-prefix=RESULT %s < %t.response
// RUN: %FileCheck --check-prefix=TRACE_NORMAL %s < %t.response
// RUN: %sourcekitd-test \
// RUN: -req=track-compiles == \
// RUN: -req=complete -req-opts=reuseastcontext=1 -pos=12:11 %s -- %s == \
// RUN: -req=complete -req-opts=reuseastcontext=1 -pos=15:11 %s -- %s > %t.response.reuseastcontext
// RUN: %FileCheck --check-prefix=RESULT %s < %t.response.reuseastcontext
// RUN: %FileCheck --check-prefix=TRACE_REUSEAST %s < %t.response.reuseastcontext
// RESULT-LABEL: key.results: [
// RESULT-DAG: key.name: "fooMethod()"
// RESULT-DAG: key.name: "self"
// RESULT-DAG: key.name: "x"
// RESULT-DAG: key.name: "y"
// RESULT: ]
// RESULT-LABEL: key.results: [
// RESULT-DAG: key.name: "barMethod()"
// RESULT-DAG: key.name: "self"
// RESULT-DAG: key.name: "a"
// RESULT-DAG: key.name: "b"
// RESULT: ]
// TRACE_NORMAL-LABEL: key.notification: source.notification.compile-did-finish,
// TRACE_NORMAL-NOT: key.description: "completion reusing previous ASTContext (benign diagnostic)"
// TRACE_NORMAL-LABEL: key.notification: source.notification.compile-did-finish,
// TRACE_NORMAL-NOT: key.description: "completion reusing previous ASTContext (benign diagnostic)"
// TRACE_REUSEAST-LABEL: key.notification: source.notification.compile-did-finish,
// TRACE_REUSEAST-NOT: key.description: "completion reusing previous ASTContext (benign diagnostic)"
// TRACE_REUSEAST-LABEL: key.notification: source.notification.compile-did-finish,
// TRACE_REUSEAST: key.description: "completion reusing previous ASTContext (benign diagnostic)"
| |
Add UIGestureRecognizer property for isEnabled. | /*
Copyright 2016-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
/** Retrieve a scoped property builder for the given UIGestureRecognizer. */
public func propertyOf(_ view: UIGestureRecognizer) -> UIGestureRecognizerReactivePropertyBuilder {
return UIGestureRecognizerReactivePropertyBuilder(view)
}
/** A scoped property builder for UIGestureRecognizer instances. */
public class UIGestureRecognizerReactivePropertyBuilder {
/** A property representing the view's .isEnabled value. */
public var isEnabled: ReactiveProperty<Bool> {
let gestureRecognizer = self.gestureRecognizer
return ReactiveProperty(read: { gestureRecognizer.isEnabled },
write: { gestureRecognizer.isEnabled = $0 })
}
private let gestureRecognizer: UIGestureRecognizer
fileprivate init(_ gestureRecognizer: UIGestureRecognizer) {
self.gestureRecognizer = gestureRecognizer
}
}
| |
Add basic SwifPM manifest file | // swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "Motion",
// platforms: [.iOS("8.0")],
products: [
.library(name: "Motion", targets: ["Motion"])
],
targets: [
.target(
name: "Motion",
path: "Sources"
)
]
)
| |
Add new Swift compiler crash with extension of generic type with type alias | import Foundation;
public protocol HasReflect {
typealias T : HasReflect
static func reflect() -> Type<T>
}
public protocol JsonSerializable : HasReflect, StringSerializable {
}
public protocol StringSerializable {
typealias T
static func fromString(string:String) -> T?
}
public class TypeAccessor {}
public class Type<T : HasReflect> : TypeAccessor {
}
public class QueryResponse<T : JsonSerializable> {}
extension QueryResponse : JsonSerializable
{
public static func reflect() -> Type<QueryResponse<T>> {
return Type<QueryResponse<T>>()
}
public static func fromString(string:String) -> QueryResponse<T>? {
return nil
}
}
| |
Set the location for the m map using CLLocationCoordinate2D | import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Add the longitude and latitude
var longitude:CLLocationDegrees = 98.3
var latitude:CLLocationDegrees = 21.44
// Latitude delta: The map will look more zoom-in
var latDelta:CLLocationDegrees = 0.01
// Longitude delta
var longDelta:CLLocationDegrees = 0.01
// It defines the latitude and longitude directions to show on a map.
var spanCoordinate: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Add the longitude and latitude
var longitude:CLLocationDegrees = 98.3
var latitude:CLLocationDegrees = 21.44
// Latitude delta: The map will look more zoom-in
var latDelta:CLLocationDegrees = 0.01
// Longitude delta
var longDelta:CLLocationDegrees = 0.01
// It defines the latitude and longitude directions to show on a map.
var spanCoordinate: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
// Set the location
var myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
Add regression test for rdar://59496033 | // RUN: %target-swift-emit-silgen %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import CoreGraphics
let _: (CFURL) -> CGDataProvider? = CGDataProvider.init
// CHECK-LABEL: sil private [ossa] @$s15cf_curried_initSo17CGDataProviderRefaSgSo8CFURLRefacfu_ : $@convention(thin) (@guaranteed CFURL) -> @owned Optional<CGDataProvider>
// CHECK-LABEL: sil [available 10.0] [clang CGDataProvider.init] @CGDataProviderCreateWithURL : $@convention(c) (CFURL) -> @owned Optional<CGDataProvider> | |
Drop _ObjectiveCBridgeable since swift-corelibs-foundation transacts upon non-objc clases | // 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
//
/// Decorates types which are backed by a Foundation reference type.
///
/// All `ReferenceConvertible` types are hashable, equatable, and provide description functions.
public protocol ReferenceConvertible : _ObjectiveCBridgeable, CustomStringConvertible, CustomDebugStringConvertible, Hashable, Equatable {
associatedtype ReferenceType : NSObject, NSCopying
}
| // 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
//
/// Decorates types which are backed by a Foundation reference type.
///
/// All `ReferenceConvertible` types are hashable, equatable, and provide description functions.
public protocol ReferenceConvertible : CustomStringConvertible, CustomDebugStringConvertible, Hashable, Equatable {
associatedtype ReferenceType : NSObject, NSCopying
}
|
Add test case for crash triggered in swift::TypeChecker::checkInheritanceClause(swift::Decl*, swift::GenericTypeResolver*) | // RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
// REQUIRES: asserts
struct S<e{let e={func d<T{{enum a:e)#^A^# | |
Add trivial test for IR generation of the getter/setter for a property. | // RUN: %swift -triple x86_64-apple-darwin10 -I %S/.. %s -emit-llvm | FileCheck %s
import swift
var _x : Int = 0;
var x : Int {
// CHECK: define i64 @_T10properties__get1xFT_NSs5Int64
get { return -_x; }
// CHECK: define void @_T10properties__set1xFT5valueNSs5Int64_T_
set { _x = value + 1; }
}
func f() ->Int {
x = 17
return x
}
| |
Add enum representing Results that may fail with an ErrorType | //
// ResultType.swift
// WolframAlpha
//
// Created by Roman Roibu on 8/29/15.
// Copyright Β© 2015 Roman Roibu. All rights reserved.
//
import Foundation
public enum Result<SuccessType> {
case Success(SuccessType)
case Failure(ErrorType)
public var value: SuccessType? {
switch self {
case Success(let value): return value
case Failure(_): return nil
}
}
public var error: ErrorType? {
switch self {
case Failure(let error): return error
case Success(_): return nil
}
}
}
| |
Update delegate flow without [weak self] | //
// DelegateHelper.swift
// Mockingjay
//
// Created by Tien Nhat Vu on 5/17/18.
//
import Foundation
/// Use this object to remove the needs of [unowned self] or [weak self] in closure delegate callback
public struct DelegateHelper<I, O> {
private(set) var handler: ((I) -> O?)?
public init() {
}
/// Execute delegate callback
///
/// - Parameter input: input
/// - Returns: output
public func call(_ input: I) -> O? {
return handler?(input)
}
/// Remove delegate
public mutating func removeDelegate() {
handler = nil
}
/// Register T to be a weak delegate
///
/// - Parameters:
/// - target: delegate
/// - handler: the callback
mutating public func delegate<T: AnyObject>(to target: T, handler: @escaping ((T, I) -> O)) {
self.handler = { [weak target] input in
guard let target = target else {
return nil
}
return handler(target, input)
}
}
/// Register T to be strong delegate
///
/// - Parameters:
/// - target: delegate
/// - handler: the callback
mutating public func strongDelegate<T: AnyObject>(to target: T, handler: @escaping ((T, I) -> O)) {
self.handler = { input in
return handler(target, input)
}
}
}
public extension DelegateHelper where I == Void {
mutating public func delegate<T: AnyObject>(to target: T, handler: @escaping ((T) -> O)) {
self.handler = { [weak target] input in
guard let target = target else {
return nil
}
return handler(target)
}
}
mutating public func strongDelegate<T: AnyObject>(to target: T, handler: @escaping ((T) -> O)) {
self.handler = { input in
return handler(target)
}
}
public func call() -> O? {
return self.call(())
}
}
public extension DelegateHelper where O == Void {
public func call(_ input: I) {
handler?(input)
}
}
public extension DelegateHelper where I == Void, O == Void {
public func call() {
self.call(())
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.