repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
noxytrux/ButtonsGoodPracticeTutorial
FlatButtons/UIImage+Extension.swift
1
832
// // UIImage+Extension.swift // FlatButtons // // Created by Marcin Pędzimąż on 24.09.2014. // Copyright (c) 2014 Marcin Pedzimaz. All rights reserved. // import UIKit extension UIImage { class func imageWithColor(color:UIColor?) -> UIImage! { let rect = CGRectMake(0.0, 0.0, 1.0, 1.0); UIGraphicsBeginImageContextWithOptions(rect.size, false, 0) let context = UIGraphicsGetCurrentContext(); if let color = color { color.setFill() } else { UIColor.whiteColor().setFill() } CGContextFillRect(context, rect); let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } }
mit
jholsapple/TIY-Assignments
30 -- HighVoltage -- John Holsapple/30 -- HighVoltage -- John Holsapple/ConversionsTableViewController.swift
2
6625
// // ConversionsTableViewController.swift // 30 -- HighVoltage -- John Holsapple // // Created by John Holsapple on 7/24/15. // Copyright (c) 2015 John Holsapple -- The Iron Yard. All rights reserved. // import UIKit protocol PopoverVCDelegate { func valueTypeWasChosen(chosenValueType: String) } protocol ElectricityModelDelegate { func valuesWereCalculated() } class ConversionsTableViewController: UITableViewController, UIPopoverPresentationControllerDelegate, PopoverVCDelegate, UITextFieldDelegate, ElectricityModelDelegate { var tableData = [String]() let valueTypes = ["Watts": "WattsCell", "Volts": "VoltsCell", "Amps": "AmpsCell", "Ohms": "OhmsCell"] var ampsTextField: UITextField? var wattsTextField: UITextField? var voltsTextField: UITextField? var ohmsTextField: UITextField? var electricityConverter = ElectricityModel() func valuesWereCalculated() { if voltsTextField == nil { let cellIdentifier = valueTypes["Volts"] tableData.append(cellIdentifier!) } if ampsTextField == nil { let cellIdentifier = valueTypes["Amps"] tableData.append(cellIdentifier!) } if wattsTextField == nil { let cellIdentifier = valueTypes["Watts"] tableData.append(cellIdentifier!) } if ohmsTextField == nil { let cellIdentifier = valueTypes["Ohms"] tableData.append(cellIdentifier!) } tableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() electricityConverter.delegate = self // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. self.navigationItem.leftBarButtonItem = self.editButtonItem() } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { switch editingStyle { case .Delete: self.tableData.removeAtIndex(indexPath.row) self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) default: return } } override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { let row = self.tableData.removeAtIndex(sourceIndexPath.row) self.tableData.insert(row, atIndex: destinationIndexPath.row) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return tableData.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = tableData[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) let textField = cell.viewWithTag(1) as! UITextField switch identifier { case "WattsCell": wattsTextField = textField if electricityConverter.wattsString != "" { textField.text = electricityConverter.wattsString } case "AmpsCell": ampsTextField = textField if electricityConverter.ampsString != "" { textField.text = electricityConverter.ampsString } case "VoltsCell": voltsTextField = textField if electricityConverter.voltsString != "" { textField.text = electricityConverter.voltsString } case "OhmsCell": ohmsTextField = textField if electricityConverter.ohmsString != "" { textField.text = electricityConverter.ohmsString } default: print("") } return cell } func valueTypeWasChosen(chosenValueType: String) { navigationController?.dismissViewControllerAnimated(true, completion: nil) let identifier = valueTypes[chosenValueType] tableData.append(identifier!) tableView.reloadData() } func textFieldShouldReturn(textField: UITextField) -> Bool { var textFieldReturn = false if textField.text != "" { textFieldReturn = true if textField == ampsTextField { electricityConverter.ampsString = textField.text! } if textField == wattsTextField { electricityConverter.wattsString = textField.text! } if textField == voltsTextField { electricityConverter.voltsString = textField.text! } if textField == ohmsTextField { electricityConverter.ohmsString = textField.text! } } if textFieldReturn { textField.resignFirstResponder() } electricityConverter.findOtherValuesIfPossible() return textFieldReturn } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "PopoverSegue" { if let controller = segue.destinationViewController as? PopoverTableViewController { controller.popoverPresentationController!.delegate = self controller.delegate = self controller.preferredContentSize = CGSize(width: 100, height: 44 * valueTypes.count) controller.dataTypes = valueTypes.keys.values print("Roadhouse!") } } } func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return UIModalPresentationStyle.None } }
cc0-1.0
jverkoey/FigmaKit
Sources/FigmaKit/Node/StarNode.swift
1
68
extension Node { public final class StarNode: VectorNode { } }
apache-2.0
halo/LinkLiar
LinkTools/Log.swift
1
2979
/* * Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar * * 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 os.log import Foundation public struct Log { private static let log = OSLog(subsystem: Identifiers.gui.rawValue, category: "logger") public static func debug(_ message: String, callerPath: String = #file) { write(message, level: .debug, callerPath: callerPath) } public static func info(_ message: String, callerPath: String = #file) { write(message, level: .info, callerPath: callerPath) } public static func error(_ message: String, callerPath: String = #file) { write(message, level: .error, callerPath: callerPath) } private static func write(_ message: String, level: OSLogType, callerPath: String) { guard let filename = callerPath.components(separatedBy: "/").last else { return write(message, level: level) } guard let classname = filename.components(separatedBy: ".").first else { return write(message, level: level) } write("\(classname) - \(message)", level: level) } private static func write(_ message: String, level: OSLogType) { os_log("%{public}@", log: log, type: level, message) appendToLogfile(message, level: level) } private static func appendToLogfile(_ message: String, level: OSLogType) { var prefix = "UNKNOWN" switch level { case OSLogType.debug: prefix = "DEBUG" case OSLogType.info: prefix = "INFO" case OSLogType.error: prefix = "ERROR" default: prefix = "DEFAULT" } let data = "\(prefix) \(message)\n".data(using: .utf8)! if let fileHandle = FileHandle(forWritingAtPath: Paths.debugLogFile) { defer { fileHandle.closeFile() } fileHandle.seekToEndOfFile() fileHandle.write(data) } else { // There is no logfile, which means the end-user does not want file logging // You may also end up here if you turned on app sandboxing. } } }
mit
kstaring/swift
validation-test/compiler_crashers_fixed/27591-swift-modulefile-gettype.swift
11
454
// 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 %target-swift-frontend %s -parse class a<T where g:a{class a<w{var:{class A{let f:a{}class b:a
apache-2.0
apple/swift-async-algorithms
Sources/AsyncAlgorithms/Merge/MergeStateMachine.swift
1
24933
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Async Algorithms open source project // // Copyright (c) 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// @_implementationOnly import DequeModule /// The state machine for any of the `merge` operator. /// /// Right now this state machine supports 3 upstream `AsyncSequences`; however, this can easily be extended. /// Once variadic generic land we should migrate this to use them instead. struct MergeStateMachine< Base1: AsyncSequence, Base2: AsyncSequence, Base3: AsyncSequence > where Base1.Element == Base2.Element, Base1.Element == Base3.Element, Base1: Sendable, Base2: Sendable, Base3: Sendable, Base1.Element: Sendable { typealias Element = Base1.Element private enum State { /// The initial state before a call to `makeAsyncIterator` happened. case initial( base1: Base1, base2: Base2, base3: Base3? ) /// The state after `makeAsyncIterator` was called and we created our `Task` to consume the upstream. case merging( task: Task<Void, Never>, buffer: Deque<Element>, upstreamContinuations: [UnsafeContinuation<Void, Error>], upstreamsFinished: Int, downstreamContinuation: UnsafeContinuation<Element?, Error>? ) /// The state once any of the upstream sequences threw an `Error`. case upstreamFailure( buffer: Deque<Element>, error: Error ) /// The state once all upstream sequences finished or the downstream consumer stopped, i.e. by dropping all references /// or by getting their `Task` cancelled. case finished /// Internal state to avoid CoW. case modifying } /// The state machine's current state. private var state: State private let numberOfUpstreamSequences: Int /// Initializes a new `StateMachine`. init( base1: Base1, base2: Base2, base3: Base3? ) { state = .initial( base1: base1, base2: base2, base3: base3 ) if base3 == nil { self.numberOfUpstreamSequences = 2 } else { self.numberOfUpstreamSequences = 3 } } /// Actions returned by `iteratorDeinitialized()`. enum IteratorDeinitializedAction { /// Indicates that the `Task` needs to be cancelled and /// all upstream continuations need to be resumed with a `CancellationError`. case cancelTaskAndUpstreamContinuations( task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) /// Indicates that nothing should be done. case none } mutating func iteratorDeinitialized() -> IteratorDeinitializedAction { switch state { case .initial: // Nothing to do here. No demand was signalled until now return .none case .merging(_, _, _, _, .some): // An iterator was deinitialized while we have a suspended continuation. preconditionFailure("Internal inconsistency current state \(self.state) and received iteratorDeinitialized()") case let .merging(task, _, upstreamContinuations, _, .none): // The iterator was dropped which signals that the consumer is finished. // We can transition to finished now and need to clean everything up. state = .finished return .cancelTaskAndUpstreamContinuations( task: task, upstreamContinuations: upstreamContinuations ) case .upstreamFailure: // The iterator was dropped which signals that the consumer is finished. // We can transition to finished now. The cleanup already happened when we // transitioned to `upstreamFailure`. state = .finished return .none case .finished: // We are already finished so there is nothing left to clean up. // This is just the references dropping afterwards. return .none case .modifying: preconditionFailure("Invalid state") } } mutating func taskStarted(_ task: Task<Void, Never>) { switch state { case .initial: // The user called `makeAsyncIterator` and we are starting the `Task` // to consume the upstream sequences state = .merging( task: task, buffer: .init(), upstreamContinuations: [], // This should reserve capacity in the variadic generics case upstreamsFinished: 0, downstreamContinuation: nil ) case .merging, .upstreamFailure, .finished: // We only a single iterator to be created so this must never happen. preconditionFailure("Internal inconsistency current state \(self.state) and received taskStarted()") case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `childTaskSuspended()`. enum ChildTaskSuspendedAction { /// Indicates that the continuation should be resumed which will lead to calling `next` on the upstream. case resumeContinuation( upstreamContinuation: UnsafeContinuation<Void, Error> ) /// Indicates that the continuation should be resumed with an Error because another upstream sequence threw. case resumeContinuationWithError( upstreamContinuation: UnsafeContinuation<Void, Error>, error: Error ) /// Indicates that nothing should be done. case none } mutating func childTaskSuspended(_ continuation: UnsafeContinuation<Void, Error>) -> ChildTaskSuspendedAction { switch state { case .initial: // Child tasks are only created after we transitioned to `merging` preconditionFailure("Internal inconsistency current state \(self.state) and received childTaskSuspended()") case .merging(_, _, _, _, .some): // We have outstanding demand so request the next element return .resumeContinuation(upstreamContinuation: continuation) case .merging(let task, let buffer, var upstreamContinuations, let upstreamsFinished, .none): // There is no outstanding demand from the downstream // so we are storing the continuation and resume it once there is demand. state = .modifying upstreamContinuations.append(continuation) state = .merging( task: task, buffer: buffer, upstreamContinuations: upstreamContinuations, upstreamsFinished: upstreamsFinished, downstreamContinuation: nil ) return .none case .upstreamFailure: // Another upstream already threw so we just need to throw from this continuation // which will end the consumption of the upstream. return .resumeContinuationWithError( upstreamContinuation: continuation, error: CancellationError() ) case .finished: // Since cancellation is cooperative it might be that child tasks are still getting // suspended even though we already cancelled them. We must tolerate this and just resume // the continuation with an error. return .resumeContinuationWithError( upstreamContinuation: continuation, error: CancellationError() ) case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `elementProduced()`. enum ElementProducedAction { /// Indicates that the downstream continuation should be resumed with the element. case resumeContinuation( downstreamContinuation: UnsafeContinuation<Element?, Error>, element: Element ) /// Indicates that nothing should be done. case none } mutating func elementProduced(_ element: Element) -> ElementProducedAction { switch state { case .initial: // Child tasks that are producing elements are only created after we transitioned to `merging` preconditionFailure("Internal inconsistency current state \(self.state) and received elementProduced()") case let .merging(task, buffer, upstreamContinuations, upstreamsFinished, .some(downstreamContinuation)): // We produced an element and have an outstanding downstream continuation // this means we can go right ahead and resume the continuation with that element precondition(buffer.isEmpty, "We are holding a continuation so the buffer must be empty") state = .merging( task: task, buffer: buffer, upstreamContinuations: upstreamContinuations, upstreamsFinished: upstreamsFinished, downstreamContinuation: nil ) return .resumeContinuation( downstreamContinuation: downstreamContinuation, element: element ) case .merging(let task, var buffer, let upstreamContinuations, let upstreamsFinished, .none): // There is not outstanding downstream continuation so we must buffer the element // This happens if we race our upstream sequences to produce elements // and the _losers_ are signalling their produced element state = .modifying buffer.append(element) state = .merging( task: task, buffer: buffer, upstreamContinuations: upstreamContinuations, upstreamsFinished: upstreamsFinished, downstreamContinuation: nil ) return .none case .upstreamFailure: // Another upstream already produced an error so we just drop the new element return .none case .finished: // Since cancellation is cooperative it might be that child tasks // are still producing elements after we finished. // We are just going to drop them since there is nothing we can do return .none case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `upstreamFinished()`. enum UpstreamFinishedAction { /// Indicates that the task and the upstream continuations should be cancelled. case cancelTaskAndUpstreamContinuations( task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) /// Indicates that the downstream continuation should be resumed with `nil` and /// the task and the upstream continuations should be cancelled. case resumeContinuationWithNilAndCancelTaskAndUpstreamContinuations( downstreamContinuation: UnsafeContinuation<Element?, Error>, task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) /// Indicates that nothing should be done. case none } mutating func upstreamFinished() -> UpstreamFinishedAction { switch state { case .initial: preconditionFailure("Internal inconsistency current state \(self.state) and received upstreamFinished()") case .merging(let task, let buffer, let upstreamContinuations, var upstreamsFinished, let .some(downstreamContinuation)): // One of the upstreams finished precondition(buffer.isEmpty, "We are holding a continuation so the buffer must be empty") // First we increment our counter of finished upstreams upstreamsFinished += 1 if upstreamsFinished == self.numberOfUpstreamSequences { // All of our upstreams have finished and we can transition to finished now // We also need to cancel the tasks and any outstanding continuations state = .finished return .resumeContinuationWithNilAndCancelTaskAndUpstreamContinuations( downstreamContinuation: downstreamContinuation, task: task, upstreamContinuations: upstreamContinuations ) } else { // There are still upstreams that haven't finished so we are just storing our new // counter of finished upstreams state = .merging( task: task, buffer: buffer, upstreamContinuations: upstreamContinuations, upstreamsFinished: upstreamsFinished, downstreamContinuation: downstreamContinuation ) return .none } case .merging(let task, let buffer, let upstreamContinuations, var upstreamsFinished, .none): // First we increment our counter of finished upstreams upstreamsFinished += 1 state = .merging( task: task, buffer: buffer, upstreamContinuations: upstreamContinuations, upstreamsFinished: upstreamsFinished, downstreamContinuation: nil ) if upstreamsFinished == self.numberOfUpstreamSequences { // All of our upstreams have finished; however, we are only transitioning to // finished once our downstream calls `next` again. return .cancelTaskAndUpstreamContinuations( task: task, upstreamContinuations: upstreamContinuations ) } else { // There are still upstreams that haven't finished. return .none } case .upstreamFailure: // Another upstream threw already so we can just ignore this finish return .none case .finished: // This is just everything finishing up, nothing to do here return .none case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `upstreamThrew()`. enum UpstreamThrewAction { /// Indicates that the task and the upstream continuations should be cancelled. case cancelTaskAndUpstreamContinuations( task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) /// Indicates that the downstream continuation should be resumed with the `error` and /// the task and the upstream continuations should be cancelled. case resumeContinuationWithErrorAndCancelTaskAndUpstreamContinuations( downstreamContinuation: UnsafeContinuation<Element?, Error>, error: Error, task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) /// Indicates that nothing should be done. case none } mutating func upstreamThrew(_ error: Error) -> UpstreamThrewAction { switch state { case .initial: preconditionFailure("Internal inconsistency current state \(self.state) and received upstreamThrew()") case let .merging(task, buffer, upstreamContinuations, _, .some(downstreamContinuation)): // An upstream threw an error and we have a downstream continuation. // We just need to resume the downstream continuation with the error and cancel everything precondition(buffer.isEmpty, "We are holding a continuation so the buffer must be empty") // We can transition to finished right away because we are returning the error state = .finished return .resumeContinuationWithErrorAndCancelTaskAndUpstreamContinuations( downstreamContinuation: downstreamContinuation, error: error, task: task, upstreamContinuations: upstreamContinuations ) case let .merging(task, buffer, upstreamContinuations, _, .none): // An upstream threw an error and we don't have a downstream continuation. // We need to store the error and wait for the downstream to consume the // rest of the buffer and the error. However, we can already cancel the task // and the other upstream continuations since we won't need any more elements. state = .upstreamFailure( buffer: buffer, error: error ) return .cancelTaskAndUpstreamContinuations( task: task, upstreamContinuations: upstreamContinuations ) case .upstreamFailure: // Another upstream threw already so we can just ignore this error return .none case .finished: // This is just everything finishing up, nothing to do here return .none case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `cancelled()`. enum CancelledAction { /// Indicates that the downstream continuation needs to be resumed and /// task and the upstream continuations should be cancelled. case resumeDownstreamContinuationWithNilAndCancelTaskAndUpstreamContinuations( downstreamContinuation: UnsafeContinuation<Element?, Error>, task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) /// Indicates that the task and the upstream continuations should be cancelled. case cancelTaskAndUpstreamContinuations( task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) /// Indicates that nothing should be done. case none } mutating func cancelled() -> CancelledAction { switch state { case .initial: // Since we are transitioning to `merging` before we return from `makeAsyncIterator` // this can never happen preconditionFailure("Internal inconsistency current state \(self.state) and received cancelled()") case let .merging(task, _, upstreamContinuations, _, .some(downstreamContinuation)): // The downstream Task got cancelled so we need to cancel our upstream Task // and resume all continuations. We can also transition to finished. state = .finished return .resumeDownstreamContinuationWithNilAndCancelTaskAndUpstreamContinuations( downstreamContinuation: downstreamContinuation, task: task, upstreamContinuations: upstreamContinuations ) case let .merging(task, _, upstreamContinuations, _, .none): // The downstream Task got cancelled so we need to cancel our upstream Task // and resume all continuations. We can also transition to finished. state = .finished return .cancelTaskAndUpstreamContinuations( task: task, upstreamContinuations: upstreamContinuations ) case .upstreamFailure: // An upstream already threw and we cancelled everything already. // We can just transition to finished now state = .finished return .none case .finished: // We are already finished so nothing to do here: state = .finished return .none case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `next()`. enum NextAction { /// Indicates that a new `Task` should be created that consumes the sequence and the downstream must be supsended case startTaskAndSuspendDownstreamTask(Base1, Base2, Base3?) /// Indicates that the `element` should be returned. case returnElement(Result<Element, Error>) /// Indicates that `nil` should be returned. case returnNil /// Indicates that the `error` should be thrown. case throwError(Error) /// Indicates that the downstream task should be suspended. case suspendDownstreamTask } mutating func next() -> NextAction { switch state { case .initial(let base1, let base2, let base3): // This is the first time we got demand signalled. We need to start the task now // We are transitioning to merging in the taskStarted method. return .startTaskAndSuspendDownstreamTask(base1, base2, base3) case .merging(_, _, _, _, .some): // We have multiple AsyncIterators iterating the sequence preconditionFailure("Internal inconsistency current state \(self.state) and received next()") case .merging(let task, var buffer, let upstreamContinuations, let upstreamsFinished, .none): state = .modifying if let element = buffer.popFirst() { // We have an element buffered already so we can just return that. state = .merging( task: task, buffer: buffer, upstreamContinuations: upstreamContinuations, upstreamsFinished: upstreamsFinished, downstreamContinuation: nil ) return .returnElement(.success(element)) } else { // There was nothing in the buffer so we have to suspend the downstream task state = .merging( task: task, buffer: buffer, upstreamContinuations: upstreamContinuations, upstreamsFinished: upstreamsFinished, downstreamContinuation: nil ) return .suspendDownstreamTask } case .upstreamFailure(var buffer, let error): state = .modifying if let element = buffer.popFirst() { // There was still a left over element that we need to return state = .upstreamFailure( buffer: buffer, error: error ) return .returnElement(.success(element)) } else { // The buffer is empty and we can now throw the error // that an upstream produced state = .finished return .throwError(error) } case .finished: // We are already finished so we are just returning `nil` return .returnNil case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `next(for)`. enum NextForAction { /// Indicates that the upstream continuations should be resumed to demand new elements. case resumeUpstreamContinuations( upstreamContinuations: [UnsafeContinuation<Void, Error>] ) } mutating func next(for continuation: UnsafeContinuation<Element?, Error>) -> NextForAction { switch state { case .initial, .merging(_, _, _, _, .some), .upstreamFailure, .finished: // All other states are handled by `next` already so we should never get in here with // any of those preconditionFailure("Internal inconsistency current state \(self.state) and received next(for:)") case let .merging(task, buffer, upstreamContinuations, upstreamsFinished, .none): // We suspended the task and need signal the upstreams state = .merging( task: task, buffer: buffer, upstreamContinuations: [], // TODO: don't alloc new array here upstreamsFinished: upstreamsFinished, downstreamContinuation: continuation ) return .resumeUpstreamContinuations( upstreamContinuations: upstreamContinuations ) case .modifying: preconditionFailure("Invalid state") } } }
apache-2.0
AssafYehudai/MarkDownKit
MarkDownKit/Classes/OSColorEx.swift
1
266
// // OSColorEx.swift // Pods // // Created by assaf yehudai on 9/26/17. // // import Foundation extension OSColor { class var codeForeground: OSColor { return OSColor(red: 206 / 255.0 , green: 26 / 255.0 , blue: 83 / 255.0 , alpha: 1) } }
mit
easyui/Alamofire
Source/Request.swift
1
78663
// // Request.swift // // Copyright (c) 2014-2020 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback /// handling. public class Request { /// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or /// `cancel()` on the `Request`. public enum State { /// Initial state of the `Request`. case initialized /// `State` set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on /// them in this state. case resumed /// `State` set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on /// them in this state. case suspended /// `State` set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on /// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer transition /// to any other state. case cancelled /// `State` set when all response serialization completion closures have been cleared on the `Request` and /// enqueued on their respective queues. case finished /// Determines whether `self` can be transitioned to the provided `State`. func canTransitionTo(_ state: State) -> Bool { switch (self, state) { case (.initialized, _): return true case (_, .initialized), (.cancelled, _), (.finished, _): return false case (.resumed, .cancelled), (.suspended, .cancelled), (.resumed, .suspended), (.suspended, .resumed): return true case (.suspended, .suspended), (.resumed, .resumed): return false case (_, .finished): return true } } } // MARK: - Initial State /// `UUID` providing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances. public let id: UUID /// The serial queue for all internal async actions. public let underlyingQueue: DispatchQueue /// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`. public let serializationQueue: DispatchQueue /// `EventMonitor` used for event callbacks. public let eventMonitor: EventMonitor? /// The `Request`'s interceptor. public let interceptor: RequestInterceptor? /// The `Request`'s delegate. public private(set) weak var delegate: RequestDelegate? // MARK: - Mutable State /// Type encapsulating all mutable state that may need to be accessed from anything other than the `underlyingQueue`. struct MutableState { /// State of the `Request`. var state: State = .initialized /// `ProgressHandler` and `DispatchQueue` provided for upload progress callbacks. var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? /// `ProgressHandler` and `DispatchQueue` provided for download progress callbacks. var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? /// `RedirectHandler` provided for to handle request redirection. var redirectHandler: RedirectHandler? /// `CachedResponseHandler` provided to handle response caching. var cachedResponseHandler: CachedResponseHandler? /// Queue and closure called when the `Request` is able to create a cURL description of itself. var cURLHandler: (queue: DispatchQueue, handler: (String) -> Void)? /// Queue and closure called when the `Request` creates a `URLRequest`. var urlRequestHandler: (queue: DispatchQueue, handler: (URLRequest) -> Void)? /// Queue and closure called when the `Request` creates a `URLSessionTask`. var urlSessionTaskHandler: (queue: DispatchQueue, handler: (URLSessionTask) -> Void)? /// Response serialization closures that handle response parsing. var responseSerializers: [() -> Void] = [] /// Response serialization completion closures executed once all response serializers are complete. var responseSerializerCompletions: [() -> Void] = [] /// Whether response serializer processing is finished. var responseSerializerProcessingFinished = false /// `URLCredential` used for authentication challenges. var credential: URLCredential? /// All `URLRequest`s created by Alamofire on behalf of the `Request`. var requests: [URLRequest] = [] /// All `URLSessionTask`s created by Alamofire on behalf of the `Request`. var tasks: [URLSessionTask] = [] /// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond /// exactly the the `tasks` created. var metrics: [URLSessionTaskMetrics] = [] /// Number of times any retriers provided retried the `Request`. var retryCount = 0 /// Final `AFError` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`. var error: AFError? /// Whether the instance has had `finish()` called and is running the serializers. Should be replaced with a /// representation in the state machine in the future. var isFinishing = false } /// Protected `MutableState` value that provides thread-safe access to state values. @Protected fileprivate var mutableState = MutableState() /// `State` of the `Request`. public var state: State { mutableState.state } /// Returns whether `state` is `.initialized`. public var isInitialized: Bool { state == .initialized } /// Returns whether `state is `.resumed`. public var isResumed: Bool { state == .resumed } /// Returns whether `state` is `.suspended`. public var isSuspended: Bool { state == .suspended } /// Returns whether `state` is `.cancelled`. public var isCancelled: Bool { state == .cancelled } /// Returns whether `state` is `.finished`. public var isFinished: Bool { state == .finished } // MARK: Progress /// Closure type executed when monitoring the upload or download progress of a request. public typealias ProgressHandler = (Progress) -> Void /// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried. public let uploadProgress = Progress(totalUnitCount: 0) /// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried. public let downloadProgress = Progress(totalUnitCount: 0) /// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`. private var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { get { mutableState.uploadProgressHandler } set { mutableState.uploadProgressHandler = newValue } } /// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`. fileprivate var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { get { mutableState.downloadProgressHandler } set { mutableState.downloadProgressHandler = newValue } } // MARK: Redirect Handling /// `RedirectHandler` set on the instance. public private(set) var redirectHandler: RedirectHandler? { get { mutableState.redirectHandler } set { mutableState.redirectHandler = newValue } } // MARK: Cached Response Handling /// `CachedResponseHandler` set on the instance. public private(set) var cachedResponseHandler: CachedResponseHandler? { get { mutableState.cachedResponseHandler } set { mutableState.cachedResponseHandler = newValue } } // MARK: URLCredential /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods. public private(set) var credential: URLCredential? { get { mutableState.credential } set { mutableState.credential = newValue } } // MARK: Validators /// `Validator` callback closures that store the validation calls enqueued. @Protected fileprivate var validators: [() -> Void] = [] // MARK: URLRequests /// All `URLRequests` created on behalf of the `Request`, including original and adapted requests. public var requests: [URLRequest] { mutableState.requests } /// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed. public var firstRequest: URLRequest? { requests.first } /// Last `URLRequest` created on behalf of the `Request`. public var lastRequest: URLRequest? { requests.last } /// Current `URLRequest` created on behalf of the `Request`. public var request: URLRequest? { lastRequest } /// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`. May be different from /// `requests` due to `URLSession` manipulation. public var performedRequests: [URLRequest] { $mutableState.read { $0.tasks.compactMap { $0.currentRequest } } } // MARK: HTTPURLResponse /// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the /// last `URLSessionTask`. public var response: HTTPURLResponse? { lastTask?.response as? HTTPURLResponse } // MARK: Tasks /// All `URLSessionTask`s created on behalf of the `Request`. public var tasks: [URLSessionTask] { mutableState.tasks } /// First `URLSessionTask` created on behalf of the `Request`. public var firstTask: URLSessionTask? { tasks.first } /// Last `URLSessionTask` crated on behalf of the `Request`. public var lastTask: URLSessionTask? { tasks.last } /// Current `URLSessionTask` created on behalf of the `Request`. public var task: URLSessionTask? { lastTask } // MARK: Metrics /// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created. public var allMetrics: [URLSessionTaskMetrics] { mutableState.metrics } /// First `URLSessionTaskMetrics` gathered on behalf of the `Request`. public var firstMetrics: URLSessionTaskMetrics? { allMetrics.first } /// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`. public var lastMetrics: URLSessionTaskMetrics? { allMetrics.last } /// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`. public var metrics: URLSessionTaskMetrics? { lastMetrics } // MARK: Retry Count /// Number of times the `Request` has been retried. public var retryCount: Int { mutableState.retryCount } // MARK: Error /// `Error` returned from Alamofire internally, from the network request directly, or any validators executed. public fileprivate(set) var error: AFError? { get { mutableState.error } set { mutableState.error = newValue } } /// Default initializer for the `Request` superclass. /// /// - Parameters: /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets /// `underlyingQueue`, but can be passed another queue from a `Session`. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. init(id: UUID = UUID(), underlyingQueue: DispatchQueue, serializationQueue: DispatchQueue, eventMonitor: EventMonitor?, interceptor: RequestInterceptor?, delegate: RequestDelegate) { self.id = id self.underlyingQueue = underlyingQueue self.serializationQueue = serializationQueue self.eventMonitor = eventMonitor self.interceptor = interceptor self.delegate = delegate } // MARK: - Internal Event API // All API must be called from underlyingQueue. /// Called when an initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active, /// the `URLRequest` will be adapted before being issued. /// /// - Parameter request: The `URLRequest` created. func didCreateInitialURLRequest(_ request: URLRequest) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) $mutableState.write { $0.requests.append(request) } eventMonitor?.request(self, didCreateInitialURLRequest: request) } /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`. /// /// - Note: Triggers retry. /// /// - Parameter error: `AFError` thrown from the failed creation. func didFailToCreateURLRequest(with error: AFError) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) self.error = error eventMonitor?.request(self, didFailToCreateURLRequestWithError: error) callCURLHandlerIfNecessary() retryOrFinish(error: error) } /// Called when a `RequestAdapter` has successfully adapted a `URLRequest`. /// /// - Parameters: /// - initialRequest: The `URLRequest` that was adapted. /// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`. func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) $mutableState.write { $0.requests.append(adaptedRequest) } eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest) } /// Called when a `RequestAdapter` fails to adapt a `URLRequest`. /// /// - Note: Triggers retry. /// /// - Parameters: /// - request: The `URLRequest` the adapter was called with. /// - error: The `AFError` returned by the `RequestAdapter`. func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) self.error = error eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error) callCURLHandlerIfNecessary() retryOrFinish(error: error) } /// Final `URLRequest` has been created for the instance. /// /// - Parameter request: The `URLRequest` created. func didCreateURLRequest(_ request: URLRequest) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) $mutableState.read { state in state.urlRequestHandler?.queue.async { state.urlRequestHandler?.handler(request) } } eventMonitor?.request(self, didCreateURLRequest: request) callCURLHandlerIfNecessary() } /// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`. private func callCURLHandlerIfNecessary() { $mutableState.write { mutableState in guard let cURLHandler = mutableState.cURLHandler else { return } cURLHandler.queue.async { cURLHandler.handler(self.cURLDescription()) } mutableState.cURLHandler = nil } } /// Called when a `URLSessionTask` is created on behalf of the instance. /// /// - Parameter task: The `URLSessionTask` created. func didCreateTask(_ task: URLSessionTask) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) $mutableState.write { state in state.tasks.append(task) guard let urlSessionTaskHandler = state.urlSessionTaskHandler else { return } urlSessionTaskHandler.queue.async { urlSessionTaskHandler.handler(task) } } eventMonitor?.request(self, didCreateTask: task) } /// Called when resumption is completed. func didResume() { dispatchPrecondition(condition: .onQueue(underlyingQueue)) eventMonitor?.requestDidResume(self) } /// Called when a `URLSessionTask` is resumed on behalf of the instance. /// /// - Parameter task: The `URLSessionTask` resumed. func didResumeTask(_ task: URLSessionTask) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) eventMonitor?.request(self, didResumeTask: task) } /// Called when suspension is completed. func didSuspend() { dispatchPrecondition(condition: .onQueue(underlyingQueue)) eventMonitor?.requestDidSuspend(self) } /// Called when a `URLSessionTask` is suspended on behalf of the instance. /// /// - Parameter task: The `URLSessionTask` suspended. func didSuspendTask(_ task: URLSessionTask) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) eventMonitor?.request(self, didSuspendTask: task) } /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`. func didCancel() { dispatchPrecondition(condition: .onQueue(underlyingQueue)) error = error ?? AFError.explicitlyCancelled eventMonitor?.requestDidCancel(self) } /// Called when a `URLSessionTask` is cancelled on behalf of the instance. /// /// - Parameter task: The `URLSessionTask` cancelled. func didCancelTask(_ task: URLSessionTask) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) eventMonitor?.request(self, didCancelTask: task) } /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the instance. /// /// - Parameter metrics: The `URLSessionTaskMetrics` gathered. func didGatherMetrics(_ metrics: URLSessionTaskMetrics) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) $mutableState.write { $0.metrics.append(metrics) } eventMonitor?.request(self, didGatherMetrics: metrics) } /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning. /// /// - Parameters: /// - task: The `URLSessionTask` which failed. /// - error: The early failure `AFError`. func didFailTask(_ task: URLSessionTask, earlyWithError error: AFError) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) self.error = error // Task will still complete, so didCompleteTask(_:with:) will handle retry. eventMonitor?.request(self, didFailTask: task, earlyWithError: error) } /// Called when a `URLSessionTask` completes. All tasks will eventually call this method. /// /// - Note: Response validation is synchronously triggered in this step. /// /// - Parameters: /// - task: The `URLSessionTask` which completed. /// - error: The `AFError` `task` may have completed with. If `error` has already been set on the instance, this /// value is ignored. func didCompleteTask(_ task: URLSessionTask, with error: AFError?) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) self.error = self.error ?? error validators.forEach { $0() } eventMonitor?.request(self, didCompleteTask: task, with: error) retryOrFinish(error: self.error) } /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`. func prepareForRetry() { dispatchPrecondition(condition: .onQueue(underlyingQueue)) $mutableState.write { $0.retryCount += 1 } reset() eventMonitor?.requestIsRetrying(self) } /// Called to determine whether retry will be triggered for the particular error, or whether the instance should /// call `finish()`. /// /// - Parameter error: The possible `AFError` which may trigger retry. func retryOrFinish(error: AFError?) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) guard let error = error, let delegate = delegate else { finish(); return } delegate.retryResult(for: self, dueTo: error) { retryResult in switch retryResult { case .doNotRetry: self.finish() case let .doNotRetryWithError(retryError): self.finish(error: retryError.asAFError(orFailWith: "Received retryError was not already AFError")) case .retry, .retryWithDelay: delegate.retryRequest(self, withDelay: retryResult.delay) } } } /// Finishes this `Request` and starts the response serializers. /// /// - Parameter error: The possible `Error` with which the instance will finish. func finish(error: AFError? = nil) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) guard !mutableState.isFinishing else { return } mutableState.isFinishing = true if let error = error { self.error = error } // Start response handlers processNextResponseSerializer() eventMonitor?.requestDidFinish(self) } /// Appends the response serialization closure to the instance. /// /// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`. /// /// - Parameter closure: The closure containing the response serialization call. func appendResponseSerializer(_ closure: @escaping () -> Void) { $mutableState.write { mutableState in mutableState.responseSerializers.append(closure) if mutableState.state == .finished { mutableState.state = .resumed } if mutableState.responseSerializerProcessingFinished { underlyingQueue.async { self.processNextResponseSerializer() } } if mutableState.state.canTransitionTo(.resumed) { underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } } } } } /// Returns the next response serializer closure to execute if there's one left. /// /// - Returns: The next response serialization closure, if there is one. func nextResponseSerializer() -> (() -> Void)? { var responseSerializer: (() -> Void)? $mutableState.write { mutableState in let responseSerializerIndex = mutableState.responseSerializerCompletions.count if responseSerializerIndex < mutableState.responseSerializers.count { responseSerializer = mutableState.responseSerializers[responseSerializerIndex] } } return responseSerializer } /// Processes the next response serializer and calls all completions if response serialization is complete. func processNextResponseSerializer() { guard let responseSerializer = nextResponseSerializer() else { // Execute all response serializer completions and clear them var completions: [() -> Void] = [] $mutableState.write { mutableState in completions = mutableState.responseSerializerCompletions // Clear out all response serializers and response serializer completions in mutable state since the // request is complete. It's important to do this prior to calling the completion closures in case // the completions call back into the request triggering a re-processing of the response serializers. // An example of how this can happen is by calling cancel inside a response completion closure. mutableState.responseSerializers.removeAll() mutableState.responseSerializerCompletions.removeAll() if mutableState.state.canTransitionTo(.finished) { mutableState.state = .finished } mutableState.responseSerializerProcessingFinished = true mutableState.isFinishing = false } completions.forEach { $0() } // Cleanup the request cleanup() return } serializationQueue.async { responseSerializer() } } /// Notifies the `Request` that the response serializer is complete. /// /// - Parameter completion: The completion handler provided with the response serializer, called when all serializers /// are complete. func responseSerializerDidComplete(completion: @escaping () -> Void) { $mutableState.write { $0.responseSerializerCompletions.append(completion) } processNextResponseSerializer() } /// Resets all task and response serializer related state for retry. func reset() { error = nil uploadProgress.totalUnitCount = 0 uploadProgress.completedUnitCount = 0 downloadProgress.totalUnitCount = 0 downloadProgress.completedUnitCount = 0 $mutableState.write { state in state.isFinishing = false state.responseSerializerCompletions = [] } } /// Called when updating the upload progress. /// /// - Parameters: /// - totalBytesSent: Total bytes sent so far. /// - totalBytesExpectedToSend: Total bytes expected to send. func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { uploadProgress.totalUnitCount = totalBytesExpectedToSend uploadProgress.completedUnitCount = totalBytesSent uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) } } /// Perform a closure on the current `state` while locked. /// /// - Parameter perform: The closure to perform. func withState(perform: (State) -> Void) { $mutableState.withState(perform: perform) } // MARK: Task Creation /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override. /// /// - Parameters: /// - request: `URLRequest` to use to create the `URLSessionTask`. /// - session: `URLSession` which creates the `URLSessionTask`. /// /// - Returns: The `URLSessionTask` created. func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { fatalError("Subclasses must override.") } // MARK: - Public API // These APIs are callable from any queue. // MARK: State /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended. /// /// - Returns: The instance. @discardableResult public func cancel() -> Self { $mutableState.write { mutableState in guard mutableState.state.canTransitionTo(.cancelled) else { return } mutableState.state = .cancelled underlyingQueue.async { self.didCancel() } guard let task = mutableState.tasks.last, task.state != .completed else { underlyingQueue.async { self.finish() } return } // Resume to ensure metrics are gathered. task.resume() task.cancel() underlyingQueue.async { self.didCancelTask(task) } } return self } /// Suspends the instance. /// /// - Returns: The instance. @discardableResult public func suspend() -> Self { $mutableState.write { mutableState in guard mutableState.state.canTransitionTo(.suspended) else { return } mutableState.state = .suspended underlyingQueue.async { self.didSuspend() } guard let task = mutableState.tasks.last, task.state != .completed else { return } task.suspend() underlyingQueue.async { self.didSuspendTask(task) } } return self } /// Resumes the instance. /// /// - Returns: The instance. @discardableResult public func resume() -> Self { $mutableState.write { mutableState in guard mutableState.state.canTransitionTo(.resumed) else { return } mutableState.state = .resumed underlyingQueue.async { self.didResume() } guard let task = mutableState.tasks.last, task.state != .completed else { return } task.resume() underlyingQueue.async { self.didResumeTask(task) } } return self } // MARK: - Closure API /// Associates a credential using the provided values with the instance. /// /// - Parameters: /// - username: The username. /// - password: The password. /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default. /// /// - Returns: The instance. @discardableResult public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self { let credential = URLCredential(user: username, password: password, persistence: persistence) return authenticate(with: credential) } /// Associates the provided credential with the instance. /// /// - Parameter credential: The `URLCredential`. /// /// - Returns: The instance. @discardableResult public func authenticate(with credential: URLCredential) -> Self { mutableState.credential = credential return self } /// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server. /// /// - Note: Only the last closure provided is used. /// /// - Parameters: /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default. /// - closure: The closure to be executed periodically as data is read from the server. /// /// - Returns: The instance. @discardableResult public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self { mutableState.downloadProgressHandler = (handler: closure, queue: queue) return self } /// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server. /// /// - Note: Only the last closure provided is used. /// /// - Parameters: /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default. /// - closure: The closure to be executed periodically as data is sent to the server. /// /// - Returns: The instance. @discardableResult public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self { mutableState.uploadProgressHandler = (handler: closure, queue: queue) return self } // MARK: Redirects /// Sets the redirect handler for the instance which will be used if a redirect response is encountered. /// /// - Note: Attempting to set the redirect handler more than once is a logic error and will crash. /// /// - Parameter handler: The `RedirectHandler`. /// /// - Returns: The instance. @discardableResult public func redirect(using handler: RedirectHandler) -> Self { $mutableState.write { mutableState in precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.") mutableState.redirectHandler = handler } return self } // MARK: Cached Responses /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response. /// /// - Note: Attempting to set the cache handler more than once is a logic error and will crash. /// /// - Parameter handler: The `CachedResponseHandler`. /// /// - Returns: The instance. @discardableResult public func cacheResponse(using handler: CachedResponseHandler) -> Self { $mutableState.write { mutableState in precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.") mutableState.cachedResponseHandler = handler } return self } // MARK: - Lifetime APIs /// Sets a handler to be called when the cURL description of the request is available. /// /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called. /// /// - Parameters: /// - queue: `DispatchQueue` on which `handler` will be called. /// - handler: Closure to be called when the cURL description is available. /// /// - Returns: The instance. @discardableResult public func cURLDescription(on queue: DispatchQueue, calling handler: @escaping (String) -> Void) -> Self { $mutableState.write { mutableState in if mutableState.requests.last != nil { queue.async { handler(self.cURLDescription()) } } else { mutableState.cURLHandler = (queue, handler) } } return self } /// Sets a handler to be called when the cURL description of the request is available. /// /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called. /// /// - Parameter handler: Closure to be called when the cURL description is available. Called on the instance's /// `underlyingQueue` by default. /// /// - Returns: The instance. @discardableResult public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { $mutableState.write { mutableState in if mutableState.requests.last != nil { underlyingQueue.async { handler(self.cURLDescription()) } } else { mutableState.cURLHandler = (underlyingQueue, handler) } } return self } /// Sets a closure to called whenever Alamofire creates a `URLRequest` for this instance. /// /// - Note: This closure will be called multiple times if the instance adapts incoming `URLRequest`s or is retried. /// /// - Parameters: /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default. /// - handler: Closure to be called when a `URLRequest` is available. /// /// - Returns: The instance. @discardableResult public func onURLRequestCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLRequest) -> Void) -> Self { $mutableState.write { state in if let request = state.requests.last { queue.async { handler(request) } } state.urlRequestHandler = (queue, handler) } return self } /// Sets a closure to be called whenever the instance creates a `URLSessionTask`. /// /// - Note: This API should only be used to provide `URLSessionTask`s to existing API, like `NSFileProvider`. It /// **SHOULD NOT** be used to interact with tasks directly, as that may be break Alamofire features. /// Additionally, this closure may be called multiple times if the instance is retried. /// /// - Parameters: /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default. /// - handler: Closure to be called when the `URLSessionTask` is available. /// /// - Returns: The instance. @discardableResult public func onURLSessionTaskCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLSessionTask) -> Void) -> Self { $mutableState.write { state in if let task = state.tasks.last { queue.async { handler(task) } } state.urlSessionTaskHandler = (queue, handler) } return self } // MARK: Cleanup /// Final cleanup step executed when the instance finishes response serialization. func cleanup() { delegate?.cleanup(after: self) // No-op: override in subclass } } // MARK: - Protocol Conformances extension Request: Equatable { public static func ==(lhs: Request, rhs: Request) -> Bool { lhs.id == rhs.id } } extension Request: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(id) } } extension Request: CustomStringConvertible { /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been /// created, as well as the response status code, if a response has been received. public var description: String { guard let request = performedRequests.last ?? lastRequest, let url = request.url, let method = request.httpMethod else { return "No request created yet." } let requestDescription = "\(method) \(url.absoluteString)" return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription } } extension Request { /// cURL representation of the instance. /// /// - Returns: The cURL equivalent of the instance. public func cURLDescription() -> String { guard let request = lastRequest, let url = request.url, let host = url.host, let method = request.httpMethod else { return "$ curl command could not be created" } var components = ["$ curl -v"] components.append("-X \(method)") if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage { let protectionSpace = URLProtectionSpace(host: host, port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic) if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { for credential in credentials { guard let user = credential.user, let password = credential.password else { continue } components.append("-u \(user):\(password)") } } else { if let credential = credential, let user = credential.user, let password = credential.password { components.append("-u \(user):\(password)") } } } if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies { if let cookieStorage = configuration.httpCookieStorage, let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";") components.append("-b \"\(allCookies)\"") } } var headers = HTTPHeaders() if let sessionHeaders = delegate?.sessionConfiguration.headers { for header in sessionHeaders where header.name != "Cookie" { headers[header.name] = header.value } } for header in request.headers where header.name != "Cookie" { headers[header.name] = header.value } for header in headers { let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"") components.append("-H \"\(header.name): \(escapedValue)\"") } if let httpBodyData = request.httpBody { let httpBody = String(decoding: httpBodyData, as: UTF8.self) var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") components.append("-d \"\(escapedBody)\"") } components.append("\"\(url.absoluteString)\"") return components.joined(separator: " \\\n\t") } } /// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`. public protocol RequestDelegate: AnyObject { /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s. var sessionConfiguration: URLSessionConfiguration { get } /// Determines whether the `Request` should automatically call `resume()` when adding the first response handler. var startImmediately: Bool { get } /// Notifies the delegate the `Request` has reached a point where it needs cleanup. /// /// - Parameter request: The `Request` to cleanup after. func cleanup(after request: Request) /// Asynchronously ask the delegate whether a `Request` will be retried. /// /// - Parameters: /// - request: `Request` which failed. /// - error: `Error` which produced the failure. /// - completion: Closure taking the `RetryResult` for evaluation. func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void) /// Asynchronously retry the `Request`. /// /// - Parameters: /// - request: `Request` which will be retried. /// - timeDelay: `TimeInterval` after which the retry will be triggered. func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) } // MARK: - Subclasses // MARK: - DataRequest /// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`. public class DataRequest: Request { /// `URLRequestConvertible` value used to create `URLRequest`s for this instance. public let convertible: URLRequestConvertible /// `Data` read from the server so far. public var data: Data? { mutableData } /// Protected storage for the `Data` read by the instance. @Protected private var mutableData: Data? = nil /// Creates a `DataRequest` using the provided parameters. /// /// - Parameters: /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets /// `underlyingQueue`, but can be passed another queue from a `Session`. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. init(id: UUID = UUID(), convertible: URLRequestConvertible, underlyingQueue: DispatchQueue, serializationQueue: DispatchQueue, eventMonitor: EventMonitor?, interceptor: RequestInterceptor?, delegate: RequestDelegate) { self.convertible = convertible super.init(id: id, underlyingQueue: underlyingQueue, serializationQueue: serializationQueue, eventMonitor: eventMonitor, interceptor: interceptor, delegate: delegate) } override func reset() { super.reset() mutableData = nil } /// Called when `Data` is received by this instance. /// /// - Note: Also calls `updateDownloadProgress`. /// /// - Parameter data: The `Data` received. func didReceive(data: Data) { if self.data == nil { mutableData = data } else { $mutableData.write { $0?.append(data) } } updateDownloadProgress() } override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { let copiedRequest = request return session.dataTask(with: copiedRequest) } /// Called to updated the `downloadProgress` of the instance. func updateDownloadProgress() { let totalBytesReceived = Int64(data?.count ?? 0) let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown downloadProgress.totalUnitCount = totalBytesExpected downloadProgress.completedUnitCount = totalBytesReceived downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) } } /// Validates the request, using the specified closure. /// /// - Note: If validation fails, subsequent calls to response handlers will have an associated error. /// /// - Parameter validation: `Validation` closure used to validate the response. /// /// - Returns: The instance. @discardableResult public func validate(_ validation: @escaping Validation) -> Self { let validator: () -> Void = { [unowned self] in guard self.error == nil, let response = self.response else { return } let result = validation(self.request, response, self.data) if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) } self.eventMonitor?.request(self, didValidateRequest: self.request, response: response, data: self.data, withResult: result) } $validators.write { $0.append(validator) } return self } } // MARK: - DataStreamRequest /// `Request` subclass which streams HTTP response `Data` through a `Handler` closure. public final class DataStreamRequest: Request { /// Closure type handling `DataStreamRequest.Stream` values. public typealias Handler<Success, Failure: Error> = (Stream<Success, Failure>) throws -> Void /// Type encapsulating an `Event` as it flows through the stream, as well as a `CancellationToken` which can be used /// to stop the stream at any time. public struct Stream<Success, Failure: Error> { /// Latest `Event` from the stream. public let event: Event<Success, Failure> /// Token used to cancel the stream. public let token: CancellationToken /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`. public func cancel() { token.cancel() } } /// Type representing an event flowing through the stream. Contains either the `Result` of processing streamed /// `Data` or the completion of the stream. public enum Event<Success, Failure: Error> { /// Output produced every time the instance receives additional `Data`. The associated value contains the /// `Result` of processing the incoming `Data`. case stream(Result<Success, Failure>) /// Output produced when the instance has completed, whether due to stream end, cancellation, or an error. /// Associated `Completion` value contains the final state. case complete(Completion) } /// Value containing the state of a `DataStreamRequest` when the stream was completed. public struct Completion { /// Last `URLRequest` issued by the instance. public let request: URLRequest? /// Last `HTTPURLResponse` received by the instance. public let response: HTTPURLResponse? /// Last `URLSessionTaskMetrics` produced for the instance. public let metrics: URLSessionTaskMetrics? /// `AFError` produced for the instance, if any. public let error: AFError? } /// Type used to cancel an ongoing stream. public struct CancellationToken { weak var request: DataStreamRequest? init(_ request: DataStreamRequest) { self.request = request } /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`. public func cancel() { request?.cancel() } } /// `URLRequestConvertible` value used to create `URLRequest`s for this instance. public let convertible: URLRequestConvertible /// Whether or not the instance will be cancelled if stream parsing encounters an error. public let automaticallyCancelOnStreamError: Bool /// Internal mutable state specific to this type. struct StreamMutableState { /// `OutputStream` bound to the `InputStream` produced by `asInputStream`, if it has been called. var outputStream: OutputStream? /// Stream closures called as `Data` is received. var streams: [(_ data: Data) -> Void] = [] /// Number of currently executing streams. Used to ensure completions are only fired after all streams are /// enqueued. var numberOfExecutingStreams = 0 /// Completion calls enqueued while streams are still executing. var enqueuedCompletionEvents: [() -> Void] = [] } @Protected var streamMutableState = StreamMutableState() /// Creates a `DataStreamRequest` using the provided parameters. /// /// - Parameters: /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` /// by default. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this /// instance. /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance will be cancelled when an `Error` /// is thrown while serializing stream `Data`. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default /// targets /// `underlyingQueue`, but can be passed another queue from a `Session`. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by /// the `Request`. init(id: UUID = UUID(), convertible: URLRequestConvertible, automaticallyCancelOnStreamError: Bool, underlyingQueue: DispatchQueue, serializationQueue: DispatchQueue, eventMonitor: EventMonitor?, interceptor: RequestInterceptor?, delegate: RequestDelegate) { self.convertible = convertible self.automaticallyCancelOnStreamError = automaticallyCancelOnStreamError super.init(id: id, underlyingQueue: underlyingQueue, serializationQueue: serializationQueue, eventMonitor: eventMonitor, interceptor: interceptor, delegate: delegate) } override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { let copiedRequest = request return session.dataTask(with: copiedRequest) } override func finish(error: AFError? = nil) { $streamMutableState.write { state in state.outputStream?.close() } super.finish(error: error) } func didReceive(data: Data) { $streamMutableState.write { state in #if !(os(Linux) || os(Windows)) if let stream = state.outputStream { underlyingQueue.async { var bytes = Array(data) stream.write(&bytes, maxLength: bytes.count) } } #endif state.numberOfExecutingStreams += state.streams.count let localState = state underlyingQueue.async { localState.streams.forEach { $0(data) } } } } /// Validates the `URLRequest` and `HTTPURLResponse` received for the instance using the provided `Validation` closure. /// /// - Parameter validation: `Validation` closure used to validate the request and response. /// /// - Returns: The `DataStreamRequest`. @discardableResult public func validate(_ validation: @escaping Validation) -> Self { let validator: () -> Void = { [unowned self] in guard self.error == nil, let response = self.response else { return } let result = validation(self.request, response) if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) } self.eventMonitor?.request(self, didValidateRequest: self.request, response: response, withResult: result) } $validators.write { $0.append(validator) } return self } #if !(os(Linux) || os(Windows)) /// Produces an `InputStream` that receives the `Data` received by the instance. /// /// - Note: The `InputStream` produced by this method must have `open()` called before being able to read `Data`. /// Additionally, this method will automatically call `resume()` on the instance, regardless of whether or /// not the creating session has `startRequestsImmediately` set to `true`. /// /// - Parameter bufferSize: Size, in bytes, of the buffer between the `OutputStream` and `InputStream`. /// /// - Returns: The `InputStream` bound to the internal `OutboundStream`. public func asInputStream(bufferSize: Int = 1024) -> InputStream? { defer { resume() } var inputStream: InputStream? $streamMutableState.write { state in Foundation.Stream.getBoundStreams(withBufferSize: bufferSize, inputStream: &inputStream, outputStream: &state.outputStream) state.outputStream?.open() } return inputStream } #endif func capturingError(from closure: () throws -> Void) { do { try closure() } catch { self.error = error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) cancel() } } func appendStreamCompletion<Success, Failure>(on queue: DispatchQueue, stream: @escaping Handler<Success, Failure>) { appendResponseSerializer { self.underlyingQueue.async { self.responseSerializerDidComplete { self.$streamMutableState.write { state in guard state.numberOfExecutingStreams == 0 else { state.enqueuedCompletionEvents.append { self.enqueueCompletion(on: queue, stream: stream) } return } self.enqueueCompletion(on: queue, stream: stream) } } } } } func enqueueCompletion<Success, Failure>(on queue: DispatchQueue, stream: @escaping Handler<Success, Failure>) { queue.async { do { let completion = Completion(request: self.request, response: self.response, metrics: self.metrics, error: self.error) try stream(.init(event: .complete(completion), token: .init(self))) } catch { // Ignore error, as errors on Completion can't be handled anyway. } } } } extension DataStreamRequest.Stream { /// Incoming `Result` values from `Event.stream`. public var result: Result<Success, Failure>? { guard case let .stream(result) = event else { return nil } return result } /// `Success` value of the instance, if any. public var value: Success? { guard case let .success(value) = result else { return nil } return value } /// `Failure` value of the instance, if any. public var error: Failure? { guard case let .failure(error) = result else { return nil } return error } /// `Completion` value of the instance, if any. public var completion: DataStreamRequest.Completion? { guard case let .complete(completion) = event else { return nil } return completion } } // MARK: - DownloadRequest /// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`. public class DownloadRequest: Request { /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination /// `URL`. public struct Options: OptionSet { /// Specifies that intermediate directories for the destination URL should be created. public static let createIntermediateDirectories = Options(rawValue: 1 << 0) /// Specifies that any previous file at the destination `URL` should be removed. public static let removePreviousFile = Options(rawValue: 1 << 1) public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } } // MARK: Destination /// A closure executed once a `DownloadRequest` has successfully completed in order to determine where to move the /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL /// and the `HTTPURLResponse`, and returns two values: the file URL where the temporary file should be moved and /// the options defining how the file should be moved. /// /// - Note: Downloads from a local `file://` `URL`s do not use the `Destination` closure, as those downloads do not /// return an `HTTPURLResponse`. Instead the file is merely moved within the temporary directory. public typealias Destination = (_ temporaryURL: URL, _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options) /// Creates a download file destination closure which uses the default file manager to move the temporary file to a /// file URL in the first available directory with the specified search path directory and search path domain mask. /// /// - Parameters: /// - directory: The search path directory. `.documentDirectory` by default. /// - domain: The search path domain mask. `.userDomainMask` by default. /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by /// default. /// - Returns: The `Destination` closure. public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory, in domain: FileManager.SearchPathDomainMask = .userDomainMask, options: Options = []) -> Destination { { temporaryURL, response in let directoryURLs = FileManager.default.urls(for: directory, in: domain) let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL return (url, options) } } /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files /// with this destination must be additionally moved if they should survive the system reclamation of temporary /// space. static let defaultDestination: Destination = { url, _ in (defaultDestinationURL(url), []) } /// Default `URL` creation closure. Creates a `URL` in the temporary directory with `Alamofire_` prepended to the /// provided file name. static let defaultDestinationURL: (URL) -> URL = { url in let filename = "Alamofire_\(url.lastPathComponent)" let destination = url.deletingLastPathComponent().appendingPathComponent(filename) return destination } // MARK: Downloadable /// Type describing the source used to create the underlying `URLSessionDownloadTask`. public enum Downloadable { /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value. case request(URLRequestConvertible) /// Download should be started from the associated resume `Data` value. case resumeData(Data) } // MARK: Mutable State /// Type containing all mutable state for `DownloadRequest` instances. private struct DownloadRequestMutableState { /// Possible resume `Data` produced when cancelling the instance. var resumeData: Data? /// `URL` to which `Data` is being downloaded. var fileURL: URL? } /// Protected mutable state specific to `DownloadRequest`. @Protected private var mutableDownloadState = DownloadRequestMutableState() /// If the download is resumable and is eventually cancelled or fails, this value may be used to resume the download /// using the `download(resumingWith data:)` API. /// /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel). public var resumeData: Data? { #if !(os(Linux) || os(Windows)) return mutableDownloadState.resumeData ?? error?.downloadResumeData #else return mutableDownloadState.resumeData #endif } /// If the download is successful, the `URL` where the file was downloaded. public var fileURL: URL? { mutableDownloadState.fileURL } // MARK: Initial State /// `Downloadable` value used for this instance. public let downloadable: Downloadable /// The `Destination` to which the downloaded file is moved. let destination: Destination /// Creates a `DownloadRequest` using the provided parameters. /// /// - Parameters: /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets /// `underlyingQueue`, but can be passed another queue from a `Session`. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request` /// - destination: `Destination` closure used to move the downloaded file to its final location. init(id: UUID = UUID(), downloadable: Downloadable, underlyingQueue: DispatchQueue, serializationQueue: DispatchQueue, eventMonitor: EventMonitor?, interceptor: RequestInterceptor?, delegate: RequestDelegate, destination: @escaping Destination) { self.downloadable = downloadable self.destination = destination super.init(id: id, underlyingQueue: underlyingQueue, serializationQueue: serializationQueue, eventMonitor: eventMonitor, interceptor: interceptor, delegate: delegate) } override func reset() { super.reset() $mutableDownloadState.write { $0.resumeData = nil $0.fileURL = nil } } /// Called when a download has finished. /// /// - Parameters: /// - task: `URLSessionTask` that finished the download. /// - result: `Result` of the automatic move to `destination`. func didFinishDownloading(using task: URLSessionTask, with result: Result<URL, AFError>) { eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result) switch result { case let .success(url): mutableDownloadState.fileURL = url case let .failure(error): self.error = error } } /// Updates the `downloadProgress` using the provided values. /// /// - Parameters: /// - bytesWritten: Total bytes written so far. /// - totalBytesExpectedToWrite: Total bytes expected to write. func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) { downloadProgress.totalUnitCount = totalBytesExpectedToWrite downloadProgress.completedUnitCount += bytesWritten downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) } } override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { session.downloadTask(with: request) } /// Creates a `URLSessionTask` from the provided resume data. /// /// - Parameters: /// - data: `Data` used to resume the download. /// - session: `URLSession` used to create the `URLSessionTask`. /// /// - Returns: The `URLSessionTask` created. public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask { session.downloadTask(withResumeData: data) } /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended. /// /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`. /// /// - Returns: The instance. @discardableResult override public func cancel() -> Self { cancel(producingResumeData: false) } /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be /// resumed or suspended. /// /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if /// available. /// /// - Returns: The instance. @discardableResult public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self { cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil) } /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed /// or suspended. /// /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData` /// property. /// /// - Parameter completionHandler: The completion handler that is called when the download has been successfully /// cancelled. It is not guaranteed to be called on a particular queue, so you may /// want use an appropriate queue to perform your work. /// /// - Returns: The instance. @discardableResult public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self { cancel(optionallyProducingResumeData: completionHandler) } /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed, /// cancellation is performed without producing resume data. /// /// - Parameter completionHandler: Optional resume data handler. /// /// - Returns: The instance. private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self { $mutableState.write { mutableState in guard mutableState.state.canTransitionTo(.cancelled) else { return } mutableState.state = .cancelled underlyingQueue.async { self.didCancel() } guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else { underlyingQueue.async { self.finish() } return } if let completionHandler = completionHandler { // Resume to ensure metrics are gathered. task.resume() task.cancel { resumeData in self.mutableDownloadState.resumeData = resumeData self.underlyingQueue.async { self.didCancelTask(task) } completionHandler(resumeData) } } else { // Resume to ensure metrics are gathered. task.resume() task.cancel(byProducingResumeData: { _ in }) self.underlyingQueue.async { self.didCancelTask(task) } } } return self } /// Validates the request, using the specified closure. /// /// - Note: If validation fails, subsequent calls to response handlers will have an associated error. /// /// - Parameter validation: `Validation` closure to validate the response. /// /// - Returns: The instance. @discardableResult public func validate(_ validation: @escaping Validation) -> Self { let validator: () -> Void = { [unowned self] in guard self.error == nil, let response = self.response else { return } let result = validation(self.request, response, self.fileURL) if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) } self.eventMonitor?.request(self, didValidateRequest: self.request, response: response, fileURL: self.fileURL, withResult: result) } $validators.write { $0.append(validator) } return self } } // MARK: - UploadRequest /// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`. public class UploadRequest: DataRequest { /// Type describing the origin of the upload, whether `Data`, file, or stream. public enum Uploadable { /// Upload from the provided `Data` value. case data(Data) /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be /// automatically removed once uploaded. case file(URL, shouldRemove: Bool) /// Upload from the provided `InputStream`. case stream(InputStream) } // MARK: Initial State /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance. public let upload: UploadableConvertible /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written /// to disk. public let fileManager: FileManager // MARK: Mutable State /// `Uploadable` value used by the instance. public var uploadable: Uploadable? /// Creates an `UploadRequest` using the provided parameters. /// /// - Parameters: /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets /// `underlyingQueue`, but can be passed another queue from a `Session`. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. init(id: UUID = UUID(), convertible: UploadConvertible, underlyingQueue: DispatchQueue, serializationQueue: DispatchQueue, eventMonitor: EventMonitor?, interceptor: RequestInterceptor?, fileManager: FileManager, delegate: RequestDelegate) { upload = convertible self.fileManager = fileManager super.init(id: id, convertible: convertible, underlyingQueue: underlyingQueue, serializationQueue: serializationQueue, eventMonitor: eventMonitor, interceptor: interceptor, delegate: delegate) } /// Called when the `Uploadable` value has been created from the `UploadConvertible`. /// /// - Parameter uploadable: The `Uploadable` that was created. func didCreateUploadable(_ uploadable: Uploadable) { self.uploadable = uploadable eventMonitor?.request(self, didCreateUploadable: uploadable) } /// Called when the `Uploadable` value could not be created. /// /// - Parameter error: `AFError` produced by the failure. func didFailToCreateUploadable(with error: AFError) { self.error = error eventMonitor?.request(self, didFailToCreateUploadableWithError: error) retryOrFinish(error: error) } override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { guard let uploadable = uploadable else { fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.") } switch uploadable { case let .data(data): return session.uploadTask(with: request, from: data) case let .file(url, _): return session.uploadTask(with: request, fromFile: url) case .stream: return session.uploadTask(withStreamedRequest: request) } } override func reset() { // Uploadable must be recreated on every retry. uploadable = nil super.reset() } /// Produces the `InputStream` from `uploadable`, if it can. /// /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash. /// /// - Returns: The `InputStream`. func inputStream() -> InputStream { guard let uploadable = uploadable else { fatalError("Attempting to access the input stream but the uploadable doesn't exist.") } guard case let .stream(stream) = uploadable else { fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.") } eventMonitor?.request(self, didProvideInputStream: stream) return stream } override public func cleanup() { defer { super.cleanup() } guard let uploadable = self.uploadable, case let .file(url, shouldRemove) = uploadable, shouldRemove else { return } try? fileManager.removeItem(at: url) } } /// A type that can produce an `UploadRequest.Uploadable` value. public protocol UploadableConvertible { /// Produces an `UploadRequest.Uploadable` value from the instance. /// /// - Returns: The `UploadRequest.Uploadable`. /// - Throws: Any `Error` produced during creation. func createUploadable() throws -> UploadRequest.Uploadable } extension UploadRequest.Uploadable: UploadableConvertible { public func createUploadable() throws -> UploadRequest.Uploadable { self } } /// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`. public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {}
mit
portah/dangerous-room
dangerous-room/Meteor/CoreDataExtensions.swift
1
1491
// Copyright (c) 2015 Peter Siegesmund <peter.siegesmund@icloud.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import CoreData public extension NSManagedObject { /** Returns a dictionary of the properties of an NSManagedObject */ public var dictionary:NSDictionary { let keys = Array(self.entity.attributesByName.keys) return self.dictionaryWithValues(forKeys: keys) as NSDictionary } }
apache-2.0
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/InfiniteScrollViewController.swift
1
4696
// // InfiniteScrollViewController.swift // UIScrollViewDemo // // Created by 伯驹 黄 on 2016/11/29. // Copyright © 2016年 伯驹 黄. All rights reserved. // import UIKit class InfiniteScrollViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white let scrollView = InfiniteScrollView(frame: view.bounds.insetBy(dx: 0, dy: 200)) scrollView.contentInsetAdjustmentBehavior = .never scrollView.backgroundColor = UIColor.blue view.addSubview(scrollView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } class InfiniteScrollView: UIScrollView, UIScrollViewDelegate { var visibleLabels: [UILabel] = [] let labelContainerView = UIView() override init(frame: CGRect) { super.init(frame: frame) contentSize = CGSize(width: 5000, height: frame.height) labelContainerView.frame = CGRect(x: 0, y: 0, width: contentSize.width, height: contentSize.height / 2) addSubview(labelContainerView) labelContainerView.isUserInteractionEnabled = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func recenterIfNecessary() { let currentOffset = contentOffset let contentWidth = contentSize.width let centerOffsetX = (contentWidth - bounds.width) / 2.0 let distanceFromCenter = abs(currentOffset.x - centerOffsetX) if distanceFromCenter > (contentWidth / 4.0) { contentOffset = CGPoint(x: centerOffsetX, y: currentOffset.y) // move content by the same amount so it appears to stay still for label in visibleLabels { var center = labelContainerView.convert(label.center, to: self) center.x += (centerOffsetX - currentOffset.x) label.center = convert(center, to: labelContainerView) } } } override func layoutSubviews() { super.layoutSubviews() recenterIfNecessary() let visibleBounds = convert(bounds, to: labelContainerView) tileLabels(from: visibleBounds.minX, to: visibleBounds.maxX) } func insertLabel() -> UILabel { let label = UILabel(frame: CGRect(x: 0, y: 0, width: bounds.width, height: 80)) label.backgroundColor = UIColor.white label.numberOfLines = 3 label.text = "1024 Block Street\nShaffer, CA\n95014" labelContainerView.addSubview(label) return label } // 向左滑 @discardableResult func placeNewLabelOnRight(_ rightEdge: CGFloat) -> CGFloat { let label = insertLabel() visibleLabels.append(label) // add rightmost label at the end of the array var frame = label.frame frame.origin.x = rightEdge frame.origin.y = labelContainerView.bounds.height - frame.height label.frame = frame return frame.maxX } // 向右滑 func placeNewLabel(on leftEdge: CGFloat) -> CGFloat { let label = insertLabel() visibleLabels.insert(label, at: 0) // add leftmost label at the beginning of the array var frame = label.frame frame.origin.x = leftEdge - frame.width frame.origin.y = labelContainerView.bounds.height - frame.height label.frame = frame return frame.minX } func tileLabels(from minimumVisibleX: CGFloat, to maximumVisibleX: CGFloat) { if visibleLabels.isEmpty { placeNewLabelOnRight(minimumVisibleX) } var lastLabel = visibleLabels.last var rightEdge = lastLabel!.frame.maxX while rightEdge < maximumVisibleX { rightEdge = placeNewLabelOnRight(rightEdge) } var firstLabel = visibleLabels[0] var leftEdge = firstLabel.frame.minX while leftEdge > minimumVisibleX { leftEdge = placeNewLabel(on: leftEdge) } // remove labels that have fallen off right edge lastLabel = visibleLabels.last while lastLabel!.frame.minX > maximumVisibleX { lastLabel!.removeFromSuperview() visibleLabels.removeLast() lastLabel = visibleLabels.last } // remove labels that have fallen off left edge firstLabel = visibleLabels[0] while firstLabel.frame.maxX < minimumVisibleX { firstLabel.removeFromSuperview() visibleLabels.removeFirst() firstLabel = visibleLabels[0] } } }
mit
luksfarris/SwiftRandomForest
SwiftRandomForestTests/RandomForestPerformanceTest.swift
1
1201
// // RandomForestPerformanceTest.swift // SwiftRandomForest // // Created by Lucas Farris on 02/06/2017. // Copyright © 2017 Lucas Farris. All rights reserved. // import XCTest class RandomForestPerformanceTest: XCTestCase { func testPerformance() { measure { let reader = CSVReader<Int>.init(encoding: String.Encoding.utf8, hasHeader: true) let matrix = reader.parseFileWith(name: "mock") let dataset = MatrixReference<Int>.init(matrix: matrix!) dataset.fill(100) let rf = RandomForest.init(maxDepth: 100, minSize:20,sampleSize:0.2, treesCount:12, seed:"Magic", weighs:[1,2], outputClasses: [0,1]) let train = rf.subsample(dataset: dataset, sampleRatio: 0.8) let test = rf.subsample(dataset: dataset, sampleRatio: 0.2) let expect = self.expectation(description: "Expect it to finish running") rf.runClassifier(trainDataset: train, testDataset: test) { (outputs:Array<Int>) in // Classifier finished running expect.fulfill() } self.wait(for: [expect], timeout: 1000) } } }
mit
mightydeveloper/swift
validation-test/compiler_crashers_fixed/1796-swift-modulefile-getdecl.swift
13
332
// RUN: not %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 func b(b: Hashable> A { A<T : [1](") class a { deinit { func f: A { } init(T: Any, let a { } protocol e : a { func a
apache-2.0
steelwheels/KiwiScript
KiwiShell/Test/Shell/main.swift
1
1193
/** * @file main.swift * @brief Main function of shell test * @par Copyright * Copyright (C) 2018 Steel Wheels Project */ import KiwiShell import KiwiEngine import KiwiLibrary import CoconutData import CoconutShell import JavaScriptCore import Foundation public func main() { let inhdl = FileHandle.standardInput let outhdl = FileHandle.standardOutput let errhdl = FileHandle.standardError let console = CNFileConsole(input: inhdl, output: outhdl, error: errhdl) let env = CNEnvironment() let manager = KLBuiltinScripts.shared manager.setup(subdirectory: "Documents/Script", forClass: KHShellThread.self) console.print(string: "***** UTShellCommand\n") let res0 = UTShellCommand(console: console) console.print(string: "***** UTParser\n") let res3 = UTParser(environment: env, console: console) console.print(string: "***** UTScriptManager\n") let res2 = UTScriptManager(console: console) console.print(string: "***** UTScript\n") let res4 = UTScript(input: inhdl, output: outhdl, error: errhdl, console: console) if res0 && res2 && res3 && res4 { console.print(string: "Summary: OK\n") } else { console.print(string: "Summary: NG\n") } } main()
lgpl-2.1
WhatsTaste/WTImagePickerController
Vendor/Views/WTEditingControlsView.swift
1
5165
// // WTEditingControlsView.swift // WTImagePickerController // // Created by Jayce on 2017/2/10. // Copyright © 2017年 WhatsTaste. All rights reserved. // import UIKit protocol WTEditingControlsViewDelegate: class { func editingControlsViewDidCancel(_ view: WTEditingControlsView) func editingControlsViewDidFinish(_ view: WTEditingControlsView) func editingControlsViewDidReset(_ view: WTEditingControlsView) } private let horizontalMargin: CGFloat = 15 private let verticalMargin: CGFloat = 10 private let spacing: CGFloat = 15 class WTEditingControlsView: UIView { override init(frame: CGRect) { super.init(frame: frame) // Initialization code addSubview(cancelButton) addSubview(doneButton) addSubview(resetButton) self.addConstraint(NSLayoutConstraint.init(item: cancelButton, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: horizontalMargin)) self.addConstraint(NSLayoutConstraint.init(item: cancelButton, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: verticalMargin)) self.addConstraint(NSLayoutConstraint.init(item: self, attribute: .bottom, relatedBy: .equal, toItem: cancelButton, attribute: .bottom, multiplier: 1, constant: verticalMargin)) self.addConstraint(NSLayoutConstraint.init(item: resetButton, attribute: .left, relatedBy: .equal, toItem: cancelButton, attribute: .right, multiplier: 1, constant: spacing)) self.addConstraint(NSLayoutConstraint.init(item: resetButton, attribute: .top, relatedBy: .equal, toItem: cancelButton, attribute: .top, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint.init(item: resetButton, attribute: .bottom, relatedBy: .equal, toItem: cancelButton, attribute: .bottom, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint.init(item: resetButton, attribute: .width, relatedBy: .equal, toItem: cancelButton, attribute: .width, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint.init(item: doneButton, attribute: .left, relatedBy: .equal, toItem: resetButton, attribute: .right, multiplier: 1, constant: spacing)) self.addConstraint(NSLayoutConstraint.init(item: doneButton, attribute: .top, relatedBy: .equal, toItem: resetButton, attribute: .top, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint.init(item: doneButton, attribute: .bottom, relatedBy: .equal, toItem: resetButton, attribute: .bottom, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint.init(item: self, attribute: .right, relatedBy: .equal, toItem: doneButton, attribute: .right, multiplier: 1, constant: horizontalMargin)) self.addConstraint(NSLayoutConstraint.init(item: doneButton, attribute: .width, relatedBy: .equal, toItem: resetButton, attribute: .width, multiplier: 1, constant: 0)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private @objc private func cancel() { delegate?.editingControlsViewDidCancel(self) } @objc private func done() { delegate?.editingControlsViewDidFinish(self) } @objc private func reset() { delegate?.editingControlsViewDidReset(self) } // MARK: - Properties weak public var delegate: WTEditingControlsViewDelegate? public var resetButtonEnabled: Bool { get { return resetButton.isEnabled } set { resetButton.isEnabled = newValue } } lazy private var cancelButton: UIButton = { let button = UIButton(type: .custom) button.translatesAutoresizingMaskIntoConstraints = false button.backgroundColor = UIColor.clear button.setImage(UIImage.cancelImage(), for: .normal) button.addTarget(self, action: #selector(cancel), for: .touchUpInside) button.contentHorizontalAlignment = .left return button }() lazy private var doneButton: UIButton = { let button = UIButton(type: .custom) button.translatesAutoresizingMaskIntoConstraints = false button.backgroundColor = UIColor.clear button.setImage(UIImage.doneImage(), for: .normal) button.addTarget(self, action: #selector(done), for: .touchUpInside) button.contentHorizontalAlignment = .right return button }() lazy private var resetButton: UIButton = { let button = UIButton(type: .system) button.translatesAutoresizingMaskIntoConstraints = false button.backgroundColor = UIColor.clear button.titleLabel?.font = UIFont.systemFont(ofSize: 14) button.setTitleColor(UIColor.white, for: .normal) button.setTitleColor(UIColor.lightGray, for: .disabled) button.setTitle(self.WTIPLocalizedString("Reset"), for: .normal) button.addTarget(self, action: #selector(reset), for: .touchUpInside) button.isEnabled = false return button }() }
mit
Jnosh/swift
test/SILGen/super_init_refcounting.swift
3
4169
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s class Foo { init() {} init(_ x: Foo) {} init(_ x: Int) {} } class Bar: Foo { // CHECK-LABEL: sil hidden @_T022super_init_refcounting3BarC{{[_0-9a-zA-Z]*}}fc // CHECK: bb0([[INPUT_SELF:%.*]] : $Bar): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Bar } // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[PB_SELF_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[INPUT_SELF]] to [init] [[PB_SELF_BOX]] // CHECK: [[ORIG_SELF:%.*]] = load [take] [[PB_SELF_BOX]] // CHECK-NOT: copy_value [[ORIG_SELF]] // CHECK: [[ORIG_SELF_UP:%.*]] = upcast [[ORIG_SELF]] // CHECK-NOT: copy_value [[ORIG_SELF_UP]] // CHECK: [[SUPER_INIT:%[0-9]+]] = function_ref @_T022super_init_refcounting3FooCACycfc : $@convention(method) (@owned Foo) -> @owned Foo // CHECK: [[NEW_SELF:%.*]] = apply [[SUPER_INIT]]([[ORIG_SELF_UP]]) // CHECK: [[NEW_SELF_DOWN:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK: store [[NEW_SELF_DOWN]] to [init] [[PB_SELF_BOX]] override init() { super.init() } } extension Foo { // CHECK-LABEL: sil hidden @_T022super_init_refcounting3FooC{{[_0-9a-zA-Z]*}}fc // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Foo } // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_SELF_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[ORIG_SELF:%.*]] = load [take] [[PB_SELF_BOX]] // CHECK-NOT: copy_value [[ORIG_SELF]] // CHECK: [[SUPER_INIT:%.*]] = class_method // CHECK: [[NEW_SELF:%.*]] = apply [[SUPER_INIT]]([[ORIG_SELF]]) // CHECK: store [[NEW_SELF]] to [init] [[PB_SELF_BOX]] convenience init(x: Int) { self.init() } } class Zim: Foo { var foo = Foo() // CHECK-LABEL: sil hidden @_T022super_init_refcounting3ZimC{{[_0-9a-zA-Z]*}}fc // CHECK-NOT: copy_value // CHECK-NOT: destroy_value // CHECK: function_ref @_T022super_init_refcounting3FooCACycfc : $@convention(method) (@owned Foo) -> @owned Foo } class Zang: Foo { var foo: Foo override init() { foo = Foo() super.init() } // CHECK-LABEL: sil hidden @_T022super_init_refcounting4ZangC{{[_0-9a-zA-Z]*}}fc // CHECK-NOT: copy_value // CHECK-NOT: destroy_value // CHECK: function_ref @_T022super_init_refcounting3FooCACycfc : $@convention(method) (@owned Foo) -> @owned Foo } class Bad: Foo { // Invalid code, but it's not diagnosed till DI. We at least shouldn't // crash on it. override init() { super.init(self) } } class Good: Foo { let x: Int // CHECK-LABEL: sil hidden @_T022super_init_refcounting4GoodC{{[_0-9a-zA-Z]*}}fc // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Good } // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[PB_SELF_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store %0 to [init] [[PB_SELF_BOX]] // CHECK: [[SELF_OBJ:%.*]] = load_borrow [[PB_SELF_BOX]] // CHECK: [[X_ADDR:%.*]] = ref_element_addr [[SELF_OBJ]] : $Good, #Good.x // CHECK: assign {{.*}} to [[X_ADDR]] : $*Int // CHECK: [[SELF_OBJ:%.*]] = load [take] [[PB_SELF_BOX]] : $*Good // CHECK: [[SUPER_OBJ:%.*]] = upcast [[SELF_OBJ]] : $Good to $Foo // CHECK: [[SUPER_INIT:%.*]] = function_ref @_T022super_init_refcounting3FooCACSicfc : $@convention(method) (Int, @owned Foo) -> @owned Foo // CHECK: [[BORROWED_SUPER:%.*]] = begin_borrow [[SUPER_OBJ]] // CHECK: [[DOWNCAST_BORROWED_SUPER:%.*]] = unchecked_ref_cast [[BORROWED_SUPER]] : $Foo to $Good // CHECK: [[X_ADDR:%.*]] = ref_element_addr [[DOWNCAST_BORROWED_SUPER]] : $Good, #Good.x // CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]] : $*Int // CHECK: end_borrow [[BORROWED_SUPER]] from [[SUPER_OBJ]] // CHECK: apply [[SUPER_INIT]]([[X]], [[SUPER_OBJ]]) override init() { x = 10 super.init(x) } }
apache-2.0
Viddi/ios-process-button
ProcessButton/Util/Util.swift
1
652
// // Util.swift // ProcessButton // // Created by Vidar Ottosson on 2/7/15. // Copyright (c) 2015 Vidar Ottosson. All rights reserved. // import UIKit class Util { /** Randomizes the time it takes for the mocked request to process (2 - 6) seconds :returns: seconds */ class func randomProcessTime() -> Double { return Double(arc4random_uniform(4)) + 2 } /** A mocked response. Returns true if the request was successful, or false for error :returns: A Bool for if the response was successful or not */ class func randomResponse() -> Bool { return Int(arc4random_uniform(2)) == 1 ? true : false } }
mit
evgenyneu/ShareImageDemo
ShareImageDemo/ViewController.swift
1
282
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } // Change the status bar text color to white override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } }
mit
atl009/WordPress-iOS
WordPress/WordPressScreenshotGeneration/WordPressScreenshotGeneration.swift
1
3921
import UIKit import XCTest class WordPressScreenshotGeneration: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. let app = XCUIApplication() setupSnapshot(app) app.launch() let isPad = UIDevice.current.userInterfaceIdiom == .pad if isPad { XCUIDevice().orientation = UIDeviceOrientation.landscapeLeft } else { XCUIDevice().orientation = UIDeviceOrientation.portrait } // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testGenerateScreenshots() { let app = XCUIApplication() let logInExists = app.buttons["Log In"].exists // Logout first if needed if !logInExists { app.tabBars["Main Navigation"].buttons["meTabButton"].tap() app.tables.element(boundBy: 0).cells.element(boundBy: 5).tap() // Tap disconnect app.alerts.element(boundBy: 0).buttons.element(boundBy: 1).tap() // Tap disconnect } app.buttons["Log In"].tap() let email = "" let password = "" // Login step 1: email let emailTextField = app.textFields["Email address"] emailTextField.tap() emailTextField.typeText(email) app.buttons["Next Button"].tap() // Login step 2: ignore magic link app.buttons["Use Password"].tap() // Login step 3: password let passwordTextField = app.secureTextFields["Password"] passwordTextField.typeText(password) app.buttons["Log In Button"].tap() // Login step 4: epilogue, continue app.buttons["Continue"].tap() // Get Reader Screenshot app.tabBars["Main Navigation"].buttons["readerTabButton"].tap(withNumberOfTaps: 2, numberOfTouches: 2) sleep(1) app.tables.cells.element(boundBy: 1).tap() // tap Discover sleep(5) snapshot("1-Reader") // Get Notifications screenshot app.tabBars["Main Navigation"].buttons["notificationsTabButton"].tap() snapshot("2-Notifications") // Get Posts screenshot app.tabBars["Main Navigation"].buttons["mySitesTabButton"].tap() app.tables.cells.element(boundBy: 2).tap() // tap Blog Posts sleep(2) snapshot("3-BlogPosts") // Get Editor screenshot // Tap on the first post to bring up the editor app.tables["PostsTable"].tap() // The title field gets focus automatically sleep(2) snapshot("4-PostEditor") app.navigationBars["Azctec Editor Navigation Bar"].buttons["Close"].tap() // Dismiss Unsaved Changes Alert if it shows up if app.sheets.element(boundBy: 0).exists { app.sheets.element(boundBy: 0).buttons.element(boundBy: 0).tap() } // Get Stats screenshot // Tap the back button if on an iPhone screen if UIDevice.current.userInterfaceIdiom == .phone { app.navigationBars.element(boundBy: 0).buttons.element(boundBy: 0).tap() // back button } app.tables["Blog Details Table"].cells.element(boundBy: 0).tap() sleep(1) snapshot("5-Stats") } }
gpl-2.0
qasim/CDFLabs
CDFLabs/Computers/Lab.swift
1
703
// // Lab.swift // CDFLabs // // Created by Qasim Iqbal on 12/30/15. // Copyright © 2015 Qasim Iqbal. All rights reserved. // import Foundation public class Lab { var name: String var avail: Int var busy: Int var total: Int var percent: Int public init() { self.name = "" self.avail = 0 self.busy = 0 self.total = 0 self.percent = 0 } public init(name: String, avail: Int, busy: Int, total: Int) { self.name = name self.avail = avail self.busy = busy self.total = total self.percent = Int(Double(round(100 * (Double(busy) / Double(total))) / 100) * 100) } }
mit
noppoMan/aws-sdk-swift
Sources/Soto/Services/ComprehendMedical/ComprehendMedical_API.swift
1
14736
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. @_exported import SotoCore /* Client object for interacting with AWS ComprehendMedical service. Amazon Comprehend Medical extracts structured information from unstructured clinical text. Use these actions to gain insight in your documents. */ public struct ComprehendMedical: AWSService { // MARK: Member variables public let client: AWSClient public let config: AWSServiceConfig // MARK: Initialization /// Initialize the ComprehendMedical client /// - parameters: /// - client: AWSClient used to process requests /// - region: Region of server you want to communicate with. This will override the partition parameter. /// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov). /// - endpoint: Custom endpoint URL to use instead of standard AWS servers /// - timeout: Timeout value for HTTP requests public init( client: AWSClient, region: SotoCore.Region? = nil, partition: AWSPartition = .aws, endpoint: String? = nil, timeout: TimeAmount? = nil, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(), options: AWSServiceConfig.Options = [] ) { self.client = client self.config = AWSServiceConfig( region: region, partition: region?.partition ?? partition, amzTarget: "ComprehendMedical_20181030", service: "comprehendmedical", serviceProtocol: .json(version: "1.1"), apiVersion: "2018-10-30", endpoint: endpoint, errorType: ComprehendMedicalErrorType.self, timeout: timeout, byteBufferAllocator: byteBufferAllocator, options: options ) } // MARK: API Calls /// Gets the properties associated with a medical entities detection job. Use this operation to get the status of a detection job. public func describeEntitiesDetectionV2Job(_ input: DescribeEntitiesDetectionV2JobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeEntitiesDetectionV2JobResponse> { return self.client.execute(operation: "DescribeEntitiesDetectionV2Job", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Gets the properties associated with an InferICD10CM job. Use this operation to get the status of an inference job. public func describeICD10CMInferenceJob(_ input: DescribeICD10CMInferenceJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeICD10CMInferenceJobResponse> { return self.client.execute(operation: "DescribeICD10CMInferenceJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Gets the properties associated with a protected health information (PHI) detection job. Use this operation to get the status of a detection job. public func describePHIDetectionJob(_ input: DescribePHIDetectionJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribePHIDetectionJobResponse> { return self.client.execute(operation: "DescribePHIDetectionJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Gets the properties associated with an InferRxNorm job. Use this operation to get the status of an inference job. public func describeRxNormInferenceJob(_ input: DescribeRxNormInferenceJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeRxNormInferenceJobResponse> { return self.client.execute(operation: "DescribeRxNormInferenceJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// The DetectEntities operation is deprecated. You should use the DetectEntitiesV2 operation instead. Inspects the clinical text for a variety of medical entities and returns specific information about them such as entity category, location, and confidence score on that information . @available(*, deprecated, message: "This operation is deprecated, use DetectEntitiesV2 instead.") public func detectEntities(_ input: DetectEntitiesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DetectEntitiesResponse> { return self.client.execute(operation: "DetectEntities", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Inspects the clinical text for a variety of medical entities and returns specific information about them such as entity category, location, and confidence score on that information. Amazon Comprehend Medical only detects medical entities in English language texts. The DetectEntitiesV2 operation replaces the DetectEntities operation. This new action uses a different model for determining the entities in your medical text and changes the way that some entities are returned in the output. You should use the DetectEntitiesV2 operation in all new applications. The DetectEntitiesV2 operation returns the Acuity and Direction entities as attributes instead of types. public func detectEntitiesV2(_ input: DetectEntitiesV2Request, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DetectEntitiesV2Response> { return self.client.execute(operation: "DetectEntitiesV2", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Inspects the clinical text for protected health information (PHI) entities and returns the entity category, location, and confidence score for each entity. Amazon Comprehend Medical only detects entities in English language texts. public func detectPHI(_ input: DetectPHIRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DetectPHIResponse> { return self.client.execute(operation: "DetectPHI", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// InferICD10CM detects medical conditions as entities listed in a patient record and links those entities to normalized concept identifiers in the ICD-10-CM knowledge base from the Centers for Disease Control. Amazon Comprehend Medical only detects medical entities in English language texts. public func inferICD10CM(_ input: InferICD10CMRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<InferICD10CMResponse> { return self.client.execute(operation: "InferICD10CM", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// InferRxNorm detects medications as entities listed in a patient record and links to the normalized concept identifiers in the RxNorm database from the National Library of Medicine. Amazon Comprehend Medical only detects medical entities in English language texts. public func inferRxNorm(_ input: InferRxNormRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<InferRxNormResponse> { return self.client.execute(operation: "InferRxNorm", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Gets a list of medical entity detection jobs that you have submitted. public func listEntitiesDetectionV2Jobs(_ input: ListEntitiesDetectionV2JobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListEntitiesDetectionV2JobsResponse> { return self.client.execute(operation: "ListEntitiesDetectionV2Jobs", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Gets a list of InferICD10CM jobs that you have submitted. public func listICD10CMInferenceJobs(_ input: ListICD10CMInferenceJobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListICD10CMInferenceJobsResponse> { return self.client.execute(operation: "ListICD10CMInferenceJobs", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Gets a list of protected health information (PHI) detection jobs that you have submitted. public func listPHIDetectionJobs(_ input: ListPHIDetectionJobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListPHIDetectionJobsResponse> { return self.client.execute(operation: "ListPHIDetectionJobs", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Gets a list of InferRxNorm jobs that you have submitted. public func listRxNormInferenceJobs(_ input: ListRxNormInferenceJobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListRxNormInferenceJobsResponse> { return self.client.execute(operation: "ListRxNormInferenceJobs", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Starts an asynchronous medical entity detection job for a collection of documents. Use the DescribeEntitiesDetectionV2Job operation to track the status of a job. public func startEntitiesDetectionV2Job(_ input: StartEntitiesDetectionV2JobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<StartEntitiesDetectionV2JobResponse> { return self.client.execute(operation: "StartEntitiesDetectionV2Job", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Starts an asynchronous job to detect medical conditions and link them to the ICD-10-CM ontology. Use the DescribeICD10CMInferenceJob operation to track the status of a job. public func startICD10CMInferenceJob(_ input: StartICD10CMInferenceJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<StartICD10CMInferenceJobResponse> { return self.client.execute(operation: "StartICD10CMInferenceJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Starts an asynchronous job to detect protected health information (PHI). Use the DescribePHIDetectionJob operation to track the status of a job. public func startPHIDetectionJob(_ input: StartPHIDetectionJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<StartPHIDetectionJobResponse> { return self.client.execute(operation: "StartPHIDetectionJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Starts an asynchronous job to detect medication entities and link them to the RxNorm ontology. Use the DescribeRxNormInferenceJob operation to track the status of a job. public func startRxNormInferenceJob(_ input: StartRxNormInferenceJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<StartRxNormInferenceJobResponse> { return self.client.execute(operation: "StartRxNormInferenceJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Stops a medical entities detection job in progress. public func stopEntitiesDetectionV2Job(_ input: StopEntitiesDetectionV2JobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<StopEntitiesDetectionV2JobResponse> { return self.client.execute(operation: "StopEntitiesDetectionV2Job", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Stops an InferICD10CM inference job in progress. public func stopICD10CMInferenceJob(_ input: StopICD10CMInferenceJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<StopICD10CMInferenceJobResponse> { return self.client.execute(operation: "StopICD10CMInferenceJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Stops a protected health information (PHI) detection job in progress. public func stopPHIDetectionJob(_ input: StopPHIDetectionJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<StopPHIDetectionJobResponse> { return self.client.execute(operation: "StopPHIDetectionJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Stops an InferRxNorm inference job in progress. public func stopRxNormInferenceJob(_ input: StopRxNormInferenceJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<StopRxNormInferenceJobResponse> { return self.client.execute(operation: "StopRxNormInferenceJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } } extension ComprehendMedical { /// Initializer required by `AWSService.with(middlewares:timeout:byteBufferAllocator:options)`. You are not able to use this initializer directly as there are no public /// initializers for `AWSServiceConfig.Patch`. Please use `AWSService.with(middlewares:timeout:byteBufferAllocator:options)` instead. public init(from: ComprehendMedical, patch: AWSServiceConfig.Patch) { self.client = from.client self.config = from.config.with(patch: patch) } }
apache-2.0
barteljan/VISPER
Example/VISPER-Wireframe-Tests/Mocks/MockComposedRoutingObserver.swift
1
2476
// // MockComposedRoutingObserver.swift // VISPER-Wireframe_Tests // // Created by bartel on 22.11.17. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import VISPER_Core import VISPER_Wireframe class MockComposedRoutingObserver: NSObject, ComposedRoutingObserver { var invokedAdd = false var invokedAddCount = 0 var invokedAddParameters: (routingObserver: RoutingObserver, priority: Int, routePattern: String?)? var invokedAddParametersList = [(routingObserver: RoutingObserver, priority: Int, routePattern: String?)]() func add(routingObserver: RoutingObserver, priority: Int, routePattern: String?) { invokedAdd = true invokedAddCount += 1 invokedAddParameters = (routingObserver, priority, routePattern) invokedAddParametersList.append((routingObserver, priority, routePattern)) } var invokedWillPresent = false var invokedWillPresentCount = 0 var invokedWillPresentParameters: (controller: UIViewController, routeResult: RouteResult, routingPresenter: RoutingPresenter?, wireframe: Wireframe)? var invokedWillPresentParametersList = [(controller: UIViewController, routeResult: RouteResult, routingPresenter: RoutingPresenter?, wireframe: Wireframe)]() func willPresent(controller: UIViewController, routeResult: RouteResult, routingPresenter: RoutingPresenter?, wireframe: Wireframe) { invokedWillPresent = true invokedWillPresentCount += 1 invokedWillPresentParameters = (controller, routeResult, routingPresenter, wireframe) invokedWillPresentParametersList.append((controller, routeResult, routingPresenter, wireframe)) } var invokedDidPresent = false var invokedDidPresentCount = 0 var invokedDidPresentParameters: (controller: UIViewController, routeResult: RouteResult, routingPresenter: RoutingPresenter?, wireframe: Wireframe)? var invokedDidPresentParametersList = [(controller: UIViewController, routeResult: RouteResult, routingPresenter: RoutingPresenter?, wireframe: Wireframe)]() func didPresent(controller: UIViewController, routeResult: RouteResult, routingPresenter: RoutingPresenter?, wireframe: Wireframe) { invokedDidPresent = true invokedDidPresentCount += 1 invokedDidPresentParameters = (controller, routeResult, routingPresenter, wireframe) invokedDidPresentParametersList.append((controller, routeResult, routingPresenter, wireframe)) } }
mit
PiXeL16/SendToMe
SendToMeFramework/ShareContentExtractor.swift
1
5912
// // ShareContentExtractor.swift // SendToMe // // Created by Chris Jimenez on 1/30/16. // Copyright © 2016 Chris Jimenez. All rights reserved. // import Foundation import MobileCoreServices //Class in charge of extracting content of URL and pages using the extensionContext inputItems public class ShareContentExtractor{ public enum ExtractionTypes:String{ case PublicURL = "public.url" case PublicFileURL = "public.file-url" case PublicPlainText = "public.plain-text" } //Error Type public enum ExtractorError:ErrorType{ case NoContent case ExtractionError(description:String) } public init(){} /** Extract the content from a ExtentionItem - parameter extentionItem: Extention Item - parameter completionHandler: Response Closure */ public func extractContentFromNSExtensionItem(extentionItem:NSExtensionItem, completionHandler:(ShareContent?) -> Void) throws -> Void { if let itemProvider = extentionItem.attachments?.first as? NSItemProvider { let propertyList = String(kUTTypePropertyList) if itemProvider.hasItemConformingToTypeIdentifier(propertyList) { return extractPropertyList(itemProvider, completionHandler: completionHandler) } else if itemProvider.hasItemConformingToTypeIdentifier(ExtractionTypes.PublicURL.rawValue) { return extractPublicUrl(itemProvider, completionHandler: completionHandler) } else if itemProvider.hasItemConformingToTypeIdentifier(ExtractionTypes.PublicFileURL.rawValue) { return extractPublicFileUrl(itemProvider, completionHandler: completionHandler) } else if itemProvider.hasItemConformingToTypeIdentifier(ExtractionTypes.PublicPlainText.rawValue) { return extractPublicPlainText(itemProvider, completionHandler: completionHandler) } else { throw ExtractorError.NoContent } } } /** Extract the information of the item provider if it has a property list(Website) - parameter itemProvider: item provider - parameter completionHandler: completion handler */ public func extractPropertyList(itemProvider:NSItemProvider, completionHandler:(ShareContent?) -> Void) -> Void { let propertyList = String(kUTTypePropertyList) itemProvider.loadItemForTypeIdentifier(propertyList, options: nil, completionHandler: { (item, error) -> Void in let dictionary = item as! NSDictionary NSOperationQueue.mainQueue().addOperationWithBlock { if let results = dictionary[NSExtensionJavaScriptPreprocessingResultsKey] as? NSDictionary { let titleString = results["title"] as? String let urlString = results["currentUrl"] as? String let shareContent = ShareContent(title:titleString, url: urlString) return completionHandler(shareContent) }else{ return completionHandler(nil) } } }) } /** Extract the public url of an item provider - parameter itemProvider: itemProvider with the url content - parameter completionHandler: completion handler */ public func extractPublicUrl(itemProvider:NSItemProvider, completionHandler:(ShareContent?) -> Void) -> Void { itemProvider.loadItemForTypeIdentifier(ExtractionTypes.PublicURL.rawValue, options: nil, completionHandler: { (url, error) -> Void in if let shareURL = url as? NSURL { let urlString = shareURL.absoluteString let shareContent = ShareContent(title:nil, url: urlString) return completionHandler(shareContent) } else { return completionHandler(nil) } }) } /** Extract the public url of an item provider - parameter itemProvider: itemProvider with the url content - parameter completionHandler: completion handler */ public func extractPublicFileUrl(itemProvider:NSItemProvider, completionHandler:(ShareContent?) -> Void) -> Void { itemProvider.loadItemForTypeIdentifier(ExtractionTypes.PublicFileURL.rawValue, options: nil, completionHandler: { (url, error) -> Void in if let shareURL = url as? NSURL { let urlString = shareURL.absoluteString let shareContent = ShareContent(title:nil, url: urlString) return completionHandler(shareContent) } else { return completionHandler(nil) } }) } public func extractPublicPlainText(itemProvider:NSItemProvider, completionHandler:(ShareContent?) -> Void) -> Void { itemProvider.loadItemForTypeIdentifier(ExtractionTypes.PublicPlainText.rawValue, options: nil, completionHandler: { (decoder, error) -> Void in if let string = decoder as? String { let shareContent = ShareContent(title:nil, url: string) return completionHandler(shareContent) } else { return completionHandler(nil) } }) } }
mit
gewill/Feeyue
Feeyue/Main/Weibo/WeiboModel.swift
1
4868
// // Status.swift // Feeyue // // Created by Will on 1/16/16. // Copyright © 2016 gewill.org. All rights reserved. // import Foundation import RealmSwift import IGListKit import SwiftyJSON import Moya_SwiftyJSONMapper class User: BaseModel, ALSwiftyJSONAble { enum Property: String { case userId, screenName, avatarHd, isFriend, isFollower } @objc dynamic var userId: Int = 0 @objc dynamic var screenName: String? @objc dynamic var avatarHd: String? @objc dynamic var isFriend = false @objc dynamic var isFollower = false // Realm override static func primaryKey() -> String? { return Property.userId.rawValue } // MARK: - Object Mapper convenience required init(jsonData json: JSON) { self.init() self.userId = json["id"].intValue self.screenName = json["screen_name"].stringValue self.avatarHd = json["avatar_hd"].stringValue } } class Status: BaseModel, ALSwiftyJSONAble { enum Property: String { case statusId, text, source, createdAt, favorited, repostsCount, commentsCount, retweetedStatus, user, pics } @objc dynamic var statusId: Int = 0 @objc dynamic var text: String? @objc dynamic var source: String? @objc dynamic var createdAt: Date? @objc dynamic var favorited = false // 暂时如此处理,稍后还是要获取关注列表进行过滤数据库 // dynamic var isInHomeTimeline = false @objc dynamic var repostsCount = 0 @objc dynamic var commentsCount = 0 @objc dynamic var retweetedStatus: Status? @objc dynamic var user: User? let pics = List<String>() override static func primaryKey() -> String? { return "statusId" } // MARK: - Object Mapper convenience required init(jsonData json: JSON) { self.init() self.statusId = json["id"].intValue self.source = SourceHelper.convert(json["source"]) self.createdAt = DateHelper.convert(json["created_at"]) self.text = json["text"].stringValue self.favorited = json["favorited"].boolValue self.repostsCount = json["reposts_count"].intValue self.commentsCount = json["comments_count"].intValue if json["retweeted_status"] != JSON.null { self.retweetedStatus = Status(jsonData: json["retweeted_status"]) } if json["user"] != JSON.null { self.user = User(jsonData: json["user"]) } json["pic_urls"].arrayValue.forEach { self.pics.append($0["thumbnail_pic"].stringValue) } } // MARK: - CRUD methods static func all(in realm: Realm = try! Realm()) -> Results<Status> { return realm.objects(Status.self) .sorted(byKeyPath: Status.Property.createdAt.rawValue, ascending: false) } @discardableResult static func add(json: JSON, in realm: Realm = try! Realm()) -> Status { let model = Status(jsonData: json) try! realm.write { realm.add(model, update: true) } return model } // MARK: - Computer porperties var hasRetweetedPics: Bool { if let pics = self.retweetedStatus?.pics, pics.isEmpty == false { return true } return false } var thumbnailPics: [String] { var array = Array(pics) if let pics = self.retweetedStatus?.pics { array.append(contentsOf: Array(pics)) } return array } var middlePics: [String] { return thumbnailPics.map { $0.replacingOccurrences(of: "/thumbnail/", with: "/bmiddle/") } } var largePics: [String] { return thumbnailPics.map { $0.replacingOccurrences(of: "/thumbnail/", with: "/large/") } } } class Comment: BaseModel { enum Property: String { case commentId, text, source, createdAt, statusId, user } @objc dynamic var commentId: Int = 0 @objc dynamic var text: String? @objc dynamic var source: String? @objc dynamic var createdAt: Date? @objc dynamic var statusId: Int = 0 @objc dynamic var user: User? override static func primaryKey() -> String? { return Property.commentId.rawValue } // MARK: - Object Mapper convenience required init(jsonData json: JSON) { self.init() self.commentId = json["id"].intValue self.source = SourceHelper.convert(json["source"]) self.createdAt = DateHelper.convert(json["created_at"]) self.text = json["text"].stringValue self.statusId = json["status", "id"].intValue } @discardableResult static func add(json: JSON, in realm: Realm = try! Realm()) -> Comment { let model = Comment(jsonData: json) try! realm.write { realm.add(model, update: true) } return model } }
mit
PureSwift/Bluetooth
Sources/BluetoothHCI/HCILEReadLocalP256PublicKeyComplete.swift
1
1699
// // HCILEReadLocalP256PublicKeyComplete.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/15/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /// LE Read Local P-256 Public Key Complete Event /// /// This event is generated when local P-256 key generation is complete. @frozen public struct HCILEReadLocalP256PublicKeyComplete: HCIEventParameter { public static let event = LowEnergyEvent.readLocalP256PublicKeyComplete // 0x08 public static let length: Int = 65 public let status: HCIStatus public let localP256PublicKey: UInt512 public init?(data: Data) { guard data.count == type(of: self).length else { return nil } let statusByte = data[0] guard let status = HCIStatus(rawValue: statusByte) else { return nil } let localP256PublicKey = UInt512(littleEndian: UInt512(bytes: ((data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16], data[17], data[18], data[19], data[20], data[21], data[22], data[23], data[24], data[25], data[26], data[27], data[28], data[29], data[30], data[31], data[32], data[33], data[34], data[35], data[36], data[37], data[38], data[39], data[40], data[41], data[42], data[43], data[44], data[45], data[46], data[47], data[48], data[49], data[50], data[51], data[52], data[53], data[54], data[55], data[56], data[57], data[58], data[59], data[60], data[61], data[62], data[63], data[64])))) self.status = status self.localP256PublicKey = localP256PublicKey } }
mit
ijoshsmith/swift-tic-tac-toe
Framework/TicTacToeTests/PlayerTests.swift
1
998
// // PlayerTests.swift // TicTacToe // // Created by Joshua Smith on 11/28/15. // Copyright © 2015 iJoshSmith. All rights reserved. // import XCTest class PlayerTests: XCTestCase { func test_choosePositionWithCompletionHandler_strategyChoosesCenterPosition_choosesCenterPosition() { let board = GameBoard(), center = GameBoard.Position(row: 1, column: 1), script = ScriptedStrategy(positions: [center]), player = Player(mark: .X, gameBoard: board, strategy: script) // Use an expectation to avoid assuming the completion handler is immediately invoked. let expectation = expectationWithDescription("Player chooses center position") player.choosePositionWithCompletionHandler { position in XCTAssertEqual(position.row, center.row) XCTAssertEqual(position.column, center.column) expectation.fulfill() } waitForExpectationsWithTimeout(0.1, handler: nil) } }
mit
tristanchu/FlavorFinder
FlavorFinder/FlavorFinder/AddHotpotToList.swift
1
8549
// // addHotpotToList.swift // FlavorFinder // // Created by Courtney Ligh on 2/15/16. // Copyright © 2016 TeamFive. All rights reserved. // import UIKit import Parse class AddHotpotToListController: UITableViewController { // MARK: Properties: let listCellIdentifier = "listAddCellIdentifier" let createListCellIdentitfier = "createListCellIdentifier" var userLists = [PFList]() // Parse related: let listClassName = "List" let ingredientsColumnName = "ingredients" let userColumnName = "user" let ListTitleColumnName = "title" // Table itself: @IBOutlet var addToListTableView: UITableView! // Strings: let newListCellTitle = "Create new list with ingredients" let pageTitle = "Add To List" let newListTitle = "New Untitled List" // Navigation: var backBtn: UIBarButtonItem = UIBarButtonItem() let backBtnAction = "backBtnClicked:" let backBtnString = String.fontAwesomeIconWithName(.ChevronLeft) + " Cancel" // Segues: let segueToCreateNewListFromSearch = "segueToCreateNewListFromSearch" // MARK: Override methods: ---------------------------------------------- /* viewDidLoad: Additional setup after loading the view (upon open) */ override func viewDidLoad() { super.viewDidLoad() // Connect table view to this controller: addToListTableView.delegate = self addToListTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: listCellIdentifier) addToListTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: createListCellIdentitfier) // Table view visuals: addToListTableView.backgroundColor = BACKGROUND_COLOR // remove empty cells addToListTableView.tableFooterView = UIView(frame: CGRectZero) addToListTableView.rowHeight = UNIFORM_ROW_HEIGHT // Set up back button setUpBackButton() } /* viewDidAppear: Setup when user goes into page. */ override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // Get navigation bar on top: if let navi = self.tabBarController?.navigationController as? MainNavigationController { navi.reset_navigationBar(); self.tabBarController?.navigationItem.setLeftBarButtonItems( [self.backBtn], animated: true) self.tabBarController?.navigationItem.setRightBarButtonItems( [], animated: true) self.tabBarController?.navigationItem.title = pageTitle; self.backBtn.enabled = true } // Populate and display table: populateListsTable() // Update table view: addToListTableView.reloadData() print(currentIngredientToAdd) } /* tableView -> int returns number of cells to display */ override func tableView( tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.userLists.count + 1 // add 1 for the create new list row } /* tableView -> UITableViewCell creates cell for each index in favoriteCells */ override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // create new at first cell: if (indexPath.row == 0){ // set cell identifier: let cell = tableView.dequeueReusableCellWithIdentifier(createListCellIdentitfier, forIndexPath: indexPath) // set Cell label: cell.textLabel?.text = newListCellTitle // Give cell a chevron: cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator return cell // User lists at other cells: } else { // set cell identifier: let cell = tableView.dequeueReusableCellWithIdentifier( listCellIdentifier, forIndexPath: indexPath) // Set cell label: cell.textLabel?.text = userLists[indexPath.row - 1].objectForKey( ListTitleColumnName) as? String return cell } } /* tableView -> Add current search to selected list - adds either to existing list or creates new list with current search: */ override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // Create new list: if (indexPath.row == 0){ self.performSegueWithIdentifier(segueToCreateNewListFromSearch, sender: self) // Picked an existing list: } else { let listObject = userLists[indexPath.row - 1] // add 1 Ingredient: if (!currentIngredientToAdd.isEmpty) { addtoList(listObject, adding: currentIngredientToAdd) // clear global var: currentIngredientToAdd = [] // OR Add Current Search: } else { addtoList(listObject, adding: currentSearch) } // go back to search page: self.navigationController?.popViewControllerAnimated(true) } } // MARK: Functions ------------------------------------------------- /* populateListsTable: clears current userLists array; gets user lists from parse local db if user is logged in. */ func populateListsTable() { userLists.removeAll() // Get user's lists from Parse local db if user logged in: if let user = currentUser { userLists = getUserListsFromLocal(user) as! [PFList] } } // MARK: Back Button Functions ------------------------------------- /* setUpBackButton sets up the back button visuals for navigation */ func setUpBackButton() { backBtn.setTitleTextAttributes(attributes, forState: .Normal) backBtn.title = self.backBtnString backBtn.tintColor = NAVI_BUTTON_COLOR backBtn.target = self backBtn.action = "backBtnClicked" // refers to: backBtnClicked() } /* backBtnClicked - action for back button */ func backBtnClicked() { currentIngredientToAdd = [] self.navigationController?.popViewControllerAnimated(true) } // MARK: Appending to list --------------------------------------------- /* addToList can be called with current search or with the one ingredient to add */ func addtoList(listObject: PFList, adding: [PFIngredient]) { let list = listObject.objectForKey(ingredientsColumnName) as! [PFIngredient] let listName = listObject.objectForKey(ListTitleColumnName) as! String for ingredient in adding { if !list.contains(ingredient) { listObject.addIngredient(ingredient) } } // Toast Feedback: makeListToast(listName, iList: adding) } /* createNewList To be called on naming page - to create new list with a name */ func createNewList(listName: String, adding: [PFIngredient]) { var list = [PFIngredient]() for ingredient in adding{ list.append(ingredient) } createIngredientList(currentUser!, title: listName, ingredients: list) // toast feedback: makeListToast(newListTitle, iList: adding) } // MARK: Toast Message - -------------------------------------------------- /* addToListMsg - creates the message "Added __, __, __ to listname" */ func addToListMsg(listName: String, ingredients: [PFIngredient]) -> String { if ingredients.count == 1 { return "Added \(ingredients[0].name) to \(listName)" } let names: [String] = ingredients.map { return $0.name } let ingredientsString = names.joinWithSeparator(", ") return "Added \(ingredientsString) to \(listName)" } /* makeListToast - just to clean up the above code. */ func makeListToast(listTitle: String, iList: [PFIngredient]) { self.navigationController?.view.makeToast(addToListMsg( listTitle, ingredients: iList), duration: TOAST_DURATION, position: .AlmostBottom) } }
mit
obrichak/discounts
discounts/Classes/BarCodeGenerator/UIColorExtension.swift
1
1604
// // UIColorExtension.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/13/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import UIKit extension UIColor { convenience init(rgba: String) { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 if rgba.hasPrefix("#") { let index = advance(rgba.startIndex, 1) let hex = rgba.substringFromIndex(index) let scanner = NSScanner.scannerWithString(hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexLongLong(&hexValue) { if hex.length() == 6 { red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 } else if hex.length() == 8 { red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 } else { print("invalid rgb string, length should be 7 or 9") } } else { println("scan hex error") } } else { print("invalid rgb string, missing '#' as prefix") } self.init(red:red, green:green, blue:blue, alpha:alpha) } }
gpl-3.0
qpre/swifter
Sources/Swifter/DemoServer.swift
1
2235
// // DemoServer.swift // Swifter // Copyright (c) 2015 Damian Kołakowski. All rights reserved. // import Foundation public func demoServer(publicDir: String?) -> HttpServer { let server = HttpServer() if let publicDir = publicDir { server["/resources/:file"] = HttpHandlers.directory(publicDir) } server["/files/:path"] = HttpHandlers.directoryBrowser("~/") server["/"] = { r in var listPage = "Available services:<br><ul>" listPage += server.routes.map({ "<li><a href=\"\($0)\">\($0)</a></li>"}).joinWithSeparator("") return .OK(.Html(listPage)) } server["/magic"] = { .OK(.Html("You asked for " + $0.url)) } server["/test/:param1/:param2"] = { r in var headersInfo = "" for (name, value) in r.headers { headersInfo += "\(name) : \(value)<br>" } var queryParamsInfo = "" for (name, value) in r.urlParams { queryParamsInfo += "\(name) : \(value)<br>" } var pathParamsInfo = "" for token in r.params { pathParamsInfo += "\(token.0) : \(token.1)<br>" } return .OK(.Html("<h3>Address: \(r.address)</h3><h3>Url:</h3> \(r.url)<h3>Method: \(r.method)</h3><h3>Headers:</h3>\(headersInfo)<h3>Query:</h3>\(queryParamsInfo)<h3>Path params:</h3>\(pathParamsInfo)")) } server["/demo"] = { r in return .OK(.Html("<center><h2>Hello Swift</h2><img src=\"https://devimages.apple.com.edgekey.net/swift/images/swift-hero_2x.png\"/><br></center>")) } server["/raw"] = { request in return HttpResponse.RAW(200, "OK", ["XXX-Custom-Header": "value"], [UInt8]("Sample Response".utf8)) } server["/json"] = { request in let jsonObject: NSDictionary = [NSString(string: "foo"): NSNumber(int: 3), NSString(string: "bar"): NSString(string: "baz")] return .OK(.Json(jsonObject)) } server["/redirect"] = { request in return .MovedPermanently("http://www.google.com") } server["/long"] = { request in var longResponse = "" for k in 0..<1000 { longResponse += "(\(k)),->" } return .OK(.Html(longResponse)) } return server }
bsd-3-clause
itsaboutcode/WordPress-iOS
WordPress/WordPressDraftActionExtension/Tracks+DraftAction.swift
1
2420
import Foundation /// This extension implements helper tracking methods, meant for Draft Action Extension usage. /// extension Tracks { // MARK: - Public Methods public func trackExtensionLaunched(_ wpcomAvailable: Bool) { let properties = ["is_configured_dotcom": wpcomAvailable] trackExtensionEvent(.launched, properties: properties as [String: AnyObject]?) } public func trackExtensionPosted(_ status: String) { let properties = ["post_status": status] trackExtensionEvent(.posted, properties: properties as [String: AnyObject]?) } public func trackExtensionError(_ error: NSError) { let properties = ["error_code": String(error.code), "error_domain": error.domain, "error_description": error.description] trackExtensionEvent(.error, properties: properties as [String: AnyObject]?) } public func trackExtensionCancelled() { trackExtensionEvent(.canceled) } public func trackExtensionTagsOpened() { trackExtensionEvent(.tagsOpened) } public func trackExtensionTagsSelected(_ tags: String) { let properties = ["selected_tags": tags] trackExtensionEvent(.tagsSelected, properties: properties as [String: AnyObject]?) } public func trackExtensionCategoriesOpened() { trackExtensionEvent(.categoriesOpened) } public func trackExtensionCategoriesSelected(_ categories: String) { let properties = ["categories_tags": categories] trackExtensionEvent(.categoriesSelected, properties: properties as [String: AnyObject]?) } // MARK: - Private Helpers fileprivate func trackExtensionEvent(_ event: ExtensionEvents, properties: [String: AnyObject]? = nil) { track(event.rawValue, properties: properties) } // MARK: - Private Enums fileprivate enum ExtensionEvents: String { case launched = "wpios_draft_extension_launched" case posted = "wpios_draft_extension_posted" case tagsOpened = "wpios_draft_extension_tags_opened" case tagsSelected = "wpios_draft_extension_tags_selected" case canceled = "wpios_draft_extension_canceled" case error = "wpios_draft_extension_error" case categoriesOpened = "wpios_draft_extension_categories_opened" case categoriesSelected = "wpios_draft_extension_categories_selected" } }
gpl-2.0
merlos/iOS-Open-GPX-Tracker
Pods/CoreGPX/Classes/GPXMetadata.swift
1
4084
// // GPXMetadata.swift // GPXKit // // Created by Vincent on 22/11/18. // import Foundation /** A value type that represents the metadata header of a GPX file. Information about the GPX file should be stored here. - Supported Info types: - Name - Description - Author Info - Copyright - Date and Time - Keyword - Bounds - Also supports extensions */ public final class GPXMetadata: GPXElement, Codable { /// Name intended for the GPX file. public var name: String? /// Description about what the GPX file is about. public var desc: String? /// Author, or the person who created the GPX file. /// /// Includes other information regarding the author (see `GPXAuthor`) public var author: GPXAuthor? /// Copyright of the file, if required. public var copyright: GPXCopyright? /// A web link, usually one with information regarding the GPX file. @available(*, deprecated, message: "CoreGPX now support multiple links.", renamed: "links.first") public var link: GPXLink? { return links.first } /// Web links, usually containing information regarding the current GPX file which houses this metadata. public var links = [GPXLink]() /// Date and time of when the GPX file is created. public var time: Date? /// Keyword of the GPX file. public var keywords: String? /// Boundaries of coordinates of the GPX file. public var bounds: GPXBounds? /// Extensions to standard GPX, if any. public var extensions: GPXExtensions? // MARK:- Initializers /// Default initializer. required public init() { self.time = Date() super.init() } /// Inits native element from raw parser value /// /// - Parameters: /// - raw: Raw element expected from parser init(raw: GPXRawElement) { //super.init() for child in raw.children { //let text = child.text switch child.name { case "name": self.name = child.text case "desc": self.desc = child.text case "author": self.author = GPXAuthor(raw: child) case "copyright": self.copyright = GPXCopyright(raw: child) case "link": self.links.append(GPXLink(raw: child)) case "time": self.time = GPXDateParser().parse(date: child.text) case "keywords": self.keywords = child.text case "bounds": self.bounds = GPXBounds(raw: child) case "extensions": self.extensions = GPXExtensions(raw: child) default: continue } } } // MARK:- Tag override func tagName() -> String { return "metadata" } // MARK:- GPX override func addChildTag(toGPX gpx: NSMutableString, indentationLevel: Int) { super.addChildTag(toGPX: gpx, indentationLevel: indentationLevel) self.addProperty(forValue: name, gpx: gpx, tagName: "name", indentationLevel: indentationLevel) self.addProperty(forValue: desc, gpx: gpx, tagName: "desc", indentationLevel: indentationLevel) if author != nil { self.author?.gpx(gpx, indentationLevel: indentationLevel) } if copyright != nil { self.copyright?.gpx(gpx, indentationLevel: indentationLevel) } for link in links { link.gpx(gpx, indentationLevel: indentationLevel) } self.addProperty(forValue: Convert.toString(from: time), gpx: gpx, tagName: "time", indentationLevel: indentationLevel) self.addProperty(forValue: keywords, gpx: gpx, tagName: "keywords", indentationLevel: indentationLevel) if bounds != nil { self.bounds?.gpx(gpx, indentationLevel: indentationLevel) } if extensions != nil { self.extensions?.gpx(gpx, indentationLevel: indentationLevel) } } }
gpl-3.0
pixel-ink/PIImageCache
PIImageCache/PIImageCacheTests/PIImageCacheDiskCacheTests.swift
2
2230
// https://github.com/pixel-ink/PIImageCache import UIKit import XCTest class PIImageDiskCacheTests: XCTestCase { let max = PIImageCache.Config().maxMemorySum func testDiskCache() { let cache = PIImageCache() var image: UIImage?, result: PIImageCache.Result var urls :[NSURL] = [] for i in 0 ..< max * 2 { urls.append(NSURL(string: "http://place-hold.it/200x200/2ff&text=No.\(i)")!) } for i in 0 ..< max * 2 { (image, result) = cache.perform(urls[i]) XCTAssert(result != .MemoryHit, "Pass") XCTAssert(image!.size.width == 200 && image!.size.height == 200 , "Pass") } for i in 0 ..< max * 2 { (image, result) = cache.perform(urls[i]) XCTAssert(result == .DiskHit, "Pass") XCTAssert(image!.size.width == 200 && image!.size.height == 200 , "Pass") } } func testFileTimeStamp() { PIImageCache.shared.oldDiskCacheDelete() let config = PIImageCache.Config() let path = "\(config.cacheRootDirectory)\(config.cacheFolderName)/" let allFileName: [String]? = NSFileManager.defaultManager().contentsOfDirectoryAtPath(path, error: nil) as? [String] if let all = allFileName { for fileName in all { if let attr = NSFileManager.defaultManager().attributesOfItemAtPath(path + fileName, error: nil) { let diff = NSDate().timeIntervalSinceDate( (attr[NSFileModificationDate] as? NSDate) ?? NSDate(timeIntervalSince1970: 0) ) XCTAssert( Double(diff) <= Double(config.diskCacheExpireMinutes * 60) , "Pass") } } } } func testPrefetch() { let cache = PIImageCache() var image: UIImage?, result: PIImageCache.Result var urls :[NSURL] = [] for i in 0 ..< max * 2 { urls.append(NSURL(string: "http://place-hold.it/200x200/2ff&text=BackgroundNo.\(i)")!) } cache.prefetch(urls) for i in 0 ..< max * 2 { (image, result) = cache.perform(urls[i]) XCTAssert(image!.size.width == 200 && image!.size.height == 200 , "Pass") } for i in 0 ..< max * 2 { (image, result) = cache.perform(urls[i]) XCTAssert(result != .Mishit, "Pass") XCTAssert(image!.size.width == 200 && image!.size.height == 200 , "Pass") } } }
mit
abertelrud/swift-package-manager
IntegrationTests/Fixtures/XCBuild/SystemTargets/Foo/Sources/foo/main.swift
2
62
import SystemLib print(String(cString: GetSystemLibName()!))
apache-2.0
RuiAAPeres/TeamGen
TeamGenFoundation/Sources/Components/UI/Flow.swift
1
1759
import UIKit public protocol Flow { func present(_ viewController: UIViewController, animated: Bool) func dismiss(_ animated: Bool) } private struct ModalFlow: Flow { private let origin: UIViewController init(_ viewController: UIViewController) { self.origin = viewController } func present(_ viewController: UIViewController, animated: Bool) { origin.present(viewController, animated: animated, completion: nil) } func dismiss(_ animated: Bool) { origin.dismiss(animated: animated, completion: nil) } } private struct NavigationFlow: Flow { private let origin: UINavigationController init(_ viewController: UINavigationController) { self.origin = viewController } func present(_ viewController: UIViewController, animated: Bool) { origin.pushViewController(viewController, animated: animated) } func dismiss(_ animated: Bool) { origin.popViewController(animated: animated) } } private struct WindowFlow: Flow { private let window: UIWindow init(_ window: UIWindow) { self.window = window } func present(_ viewController: UIViewController, animated: Bool) { window.rootViewController = viewController window.makeKeyAndVisible() } func dismiss(_ animated: Bool) { window.rootViewController = nil } } public extension UIWindow { var flow: Flow { return WindowFlow(self) } } public extension UIViewController { var modalFlow: Flow { return ModalFlow(self) } var navigationFlow: Flow { guard let navigationController = self.navigationController else { return modalFlow } return NavigationFlow(navigationController) } }
mit
nalexn/ViewInspector
Tests/ViewInspectorTests/SwiftUI/MenuButtonTests.swift
1
2523
import XCTest import SwiftUI @testable import ViewInspector #if os(macOS) @available(macOS 10.15, *) @available(iOS, unavailable) @available(tvOS, unavailable) final class MenuButtonTests: XCTestCase { func testEnclosedView() throws { let sut = MenuButton(label: Text("")) { EmptyView() } XCTAssertNoThrow(try sut.inspect().menuButton().emptyView()) } func testResetsModifiers() throws { let view = MenuButton(label: Text("")) { EmptyView() }.padding() let sut = try view.inspect().menuButton().emptyView() XCTAssertEqual(sut.content.medium.viewModifiers.count, 0) } func testExtractionFromSingleViewContainer() throws { let view = AnyView(MenuButton(label: Text("")) { EmptyView() }) XCTAssertNoThrow(try view.inspect().anyView().menuButton()) } func testExtractionFromMultipleViewContainer() throws { let view = HStack { MenuButton(label: Text("")) { EmptyView() } MenuButton(label: Text("")) { EmptyView() } } XCTAssertNoThrow(try view.inspect().hStack().menuButton(0)) XCTAssertNoThrow(try view.inspect().hStack().menuButton(1)) } func testSearch() throws { let view = AnyView(MenuButton(label: Text("abc")) { Text("xyz") }) XCTAssertEqual(try view.inspect().find(ViewType.MenuButton.self).pathToRoot, "anyView().menuButton()") XCTAssertEqual(try view.inspect().find(text: "abc").pathToRoot, "anyView().menuButton().labelView().text()") XCTAssertEqual(try view.inspect().find(text: "xyz").pathToRoot, "anyView().menuButton().text()") } func testLabelView() throws { let sut = MenuButton(label: Text("abc")) { EmptyView() } let text = try sut.inspect().menuButton().labelView().text().string() XCTAssertEqual(text, "abc") } } // MARK: - View Modifiers @available(macOS 10.15, *) @available(iOS, unavailable) @available(tvOS, unavailable) final class GlobalModifiersForMenuButton: XCTestCase { func testMenuButtonStyle() throws { let sut = EmptyView().menuButtonStyle(PullDownMenuButtonStyle()) XCTAssertNoThrow(try sut.inspect().emptyView()) } func testMenuButtonStyleInspection() throws { let sut = EmptyView().menuButtonStyle(DefaultMenuButtonStyle()) XCTAssertTrue(try sut.inspect().menuButtonStyle() is DefaultMenuButtonStyle) } } #endif
mit
inket/MacSymbolicator
MacSymbolicatorTests/TestProject/AnotherTarget/CrashingClass.swift
1
237
// // CrashingClass.swift // AnotherTarget // import Foundation @objc public class CrashingClass: NSObject { @objc public static func crash() { NSException(name: .init(rawValue: "Crash"), reason: nil).raise() } }
gpl-2.0
ayvazj/BrundleflyiOS
Pod/Classes/Model/BtfyColor.swift
1
2067
/* * Copyright (c) 2015 James Ayvaz * * 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. */ struct BtfyColor { var r: Double var g: Double var b: Double var a: Double init () { self.r = 0 self.g = 0 self.b = 0 self.a = 1 } init (r: Double, g: Double, b: Double) { self.r = r self.g = g self.b = b self.a = 1 } init (a: Double, r: Double, g: Double, b: Double) { self.r = r self.g = g self.b = b self.a = a } static func parseRGBA(json: [String:AnyObject]) -> BtfyColor { var a = json["a"] as! Double? var r = json["r"] as! Double? var g = json["g"] as! Double? var b = json["b"] as! Double? if a == nil { a = 1.0 } if r == nil { r = 1.0 } if g == nil { g = 1.0 } if b == nil { b = 1.0 } return BtfyColor(a: a!, r: r!, g: g!, b: b!) } }
mit
clutter/Pelican
Tests/PelicanTests/PelicanTests.swift
1
10404
// // PelicanTests.swift // Pelican // // Created by Robert Manson on 4/5/17. // Copyright © 2017 CocoaPods. All rights reserved. // import XCTest @testable import Pelican private class TaskCollector { enum Task { case taskA(value: HouseAtreides) case taskB(value: HouseHarkonnen) var name: String { switch self { case .taskA(let value): return value.name case .taskB(let value): return value.name } } var houseAtreides: HouseAtreides? { switch self { case .taskA(let value): return value default: return nil } } var houseHarkonnen: HouseHarkonnen? { switch self { case .taskB(let value): return value default: return nil } } } static var shared = TaskCollector() var collected = [Task]() func collect(tasks: [PelicanBatchableTask]) { for task in tasks { if let task = task as? HouseAtreides { collected.append(.taskA(value: task)) } else if let task = task as? HouseHarkonnen { collected.append(.taskB(value: task)) } else { fatalError() } } } } private protocol DuneCharacter: PelicanGroupable { var name: String { get } } extension DuneCharacter where Self: PelicanBatchableTask { var group: String { return "Dune Character Group" } static func processGroup(tasks: [PelicanBatchableTask], didComplete: @escaping ((PelicanProcessResult) -> Void)) { TaskCollector.shared.collect(tasks: tasks) didComplete(PelicanProcessResult.done) } } private struct HouseAtreides: PelicanBatchableTask, DuneCharacter { let name: String let timeStamp: Date init(name: String, birthdate: Date) { self.timeStamp = birthdate self.name = name } // PelicanBatchableTask conformance, used to read and store task to storage static let taskType: String = String(describing: HouseAtreides.self) } private struct HouseHarkonnen: PelicanBatchableTask, DuneCharacter { let name: String let weapon: String init(name: String, weapon: String) { self.name = name self.weapon = weapon } // PelicanBatchableTask conformance, used to read and store task to storage static let taskType: String = String(describing: HouseHarkonnen.self) } /// Test the example code in the ReadMe class PelicanSavingAndRecoveringFromAppState: XCTestCase { let letosDate: Date = Date.distantFuture let paulsDate: Date = Date.distantFuture.addingTimeInterval(-6000) var storage: InMemoryStorage! override func setUp() { storage = InMemoryStorage() // Start by registering and immediately adding 2 tasks TaskCollector.shared.collected = [] var tasks = Pelican.RegisteredTasks() tasks.register(for: HouseAtreides.self) tasks.register(for: HouseHarkonnen.self) Pelican.initialize(tasks: tasks, storage: storage) } override func tearDown() { Pelican.shared.stop() storage = nil } func testSavesWhenBackgroundedRecoversWhenForegrounded() { Pelican.shared.gulp(task: HouseAtreides(name: "Duke Leto", birthdate: letosDate)) Pelican.shared.gulp(task: HouseHarkonnen(name: "Glossu Rabban", weapon: "brutishness")) let tasksGulped = expectation(description: "Tasks Gulped and Processed") DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + .seconds(6)) { let taskCount = TaskCollector.shared.collected.count XCTAssert(taskCount == 2, "Task count is \(taskCount)") XCTAssert(TaskCollector.shared.collected[0].name == "Duke Leto", "Task is \(TaskCollector.shared.collected[0].name)") XCTAssert(TaskCollector.shared.collected[1].name == "Glossu Rabban", "Task is \(TaskCollector.shared.collected[1].name)") tasksGulped.fulfill() } waitForExpectations(timeout: 7.0, handler: nil) XCTAssert(storage.store == nil) TaskCollector.shared.collected = [] XCTAssertTrue(Pelican.shared.groupedTasks.allTasks().isEmpty) // Add two more tasks and simulate backgrounding Pelican.shared.gulp(task: HouseAtreides(name: "Paul Atreides", birthdate: paulsDate)) Pelican.shared.gulp(task: HouseHarkonnen(name: "Baron Vladimir Harkonnen", weapon: "cunning")) Pelican.shared.didEnterBackground() XCTAssert(storage["Dune Character Group"].count == 2) Pelican.shared.willEnterForeground() let storageLoaded = expectation(description: "Wait for storage to load") DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + .seconds(1)) { storageLoaded.fulfill() } waitForExpectations(timeout: 2.0, handler: nil) XCTAssert(storage.store == nil) let moreTasksGulped = expectation(description: "More Tasks Gulped and Processed") DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + .seconds(6)) { let taskCount = TaskCollector.shared.collected.count XCTAssertEqual(taskCount, 2) let paul = TaskCollector.shared.collected[0].houseAtreides XCTAssertEqual(paul?.name, "Paul Atreides") XCTAssertEqual(paul?.timeStamp, self.paulsDate) let baron = TaskCollector.shared.collected[1].houseHarkonnen XCTAssertEqual(baron?.name, "Baron Vladimir Harkonnen") XCTAssertEqual(baron?.weapon, "cunning") moreTasksGulped.fulfill() } waitForExpectations(timeout: 7.0, handler: nil) Pelican.shared.didEnterBackground() XCTAssert(storage.store == nil) } } class PelicanStoresOnGulpTests: XCTestCase { var storage: InMemoryStorage! var pelican: Pelican! override func setUp() { storage = InMemoryStorage() var tasks = Pelican.RegisteredTasks() tasks.register(for: HouseAtreides.self) tasks.register(for: HouseHarkonnen.self) pelican = Pelican(tasks: tasks, storage: storage) } override func tearDown() { pelican.stop() pelican = nil storage = nil } func testArchiveWithNoTasksSucceeds() { pelican.archiveGroups() // This should be nil, since we didn't gulp anything XCTAssertNil(storage.store) } func testArchiveGroupsSavesTasksToStorage() { pelican.gulp(task: HouseAtreides(name: "Duke Leto", birthdate: .distantPast)) pelican.gulp(task: HouseHarkonnen(name: "Glossu Rabban", weapon: "brutishness")) pelican.archiveGroups() let duneCharacterGroup = storage["Dune Character Group"] guard duneCharacterGroup.count == 2 else { XCTFail("Storage does not contain correct number of tasks for \"Dune Character Group\"") return } if let taskOne = duneCharacterGroup[0].task as? HouseAtreides { XCTAssertEqual(taskOne.name, "Duke Leto") XCTAssertEqual(taskOne.timeStamp, .distantPast) } else { XCTFail("Expecting first task to be HouseAtreides") } if let taskTwo = duneCharacterGroup[1].task as? HouseHarkonnen { XCTAssertEqual(taskTwo.name, "Glossu Rabban") XCTAssertEqual(taskTwo.weapon, "brutishness") } else { XCTFail("Expecting second task to be HouseHarkonnen") } } } class PelicanLoadsFromStorageTests: XCTestCase { var storage: InMemoryStorage! var pelican: Pelican! override func setUp() { storage = InMemoryStorage() var tasks = Pelican.RegisteredTasks() tasks.register(for: HouseAtreides.self) tasks.register(for: HouseHarkonnen.self) pelican = Pelican(tasks: tasks, storage: storage) } override func tearDown() { pelican.stop() pelican = nil storage = nil } func testUnarchiveGroupsLoadsNoTaskGroupsFromEmptyStorage() { pelican.unarchiveGroups() XCTAssertTrue(pelican.groupedTasks.allTasks().isEmpty) XCTAssertNil(storage.store) } func testUnarchiveGroupsLoadsArchivedTasksFromStorage() { let task = TaskContainer(task: HouseAtreides(name: "Duke Leto", birthdate: Date.distantPast)) storage["Dune Character Group"] = [ task ] pelican.unarchiveGroups() let allGroups = pelican.groupedTasks.allTasks() XCTAssertEqual(allGroups.count, 1) if let duneCharacterGroup = allGroups.first(where: { $0.group == "Dune Character Group" }) { guard duneCharacterGroup.containers.count == 1 else { XCTFail("Storage does not contain correct number of tasks for \"Dune Character Group\"") return } let taskContainer = duneCharacterGroup.containers[0] XCTAssertEqual(taskContainer.identifier, task.identifier) XCTAssertEqual(taskContainer.taskType, HouseAtreides.taskType) if let task = taskContainer.task as? HouseAtreides { XCTAssertEqual(task.name, "Duke Leto") XCTAssertEqual(task.timeStamp, Date.distantPast) } else { XCTFail("Task is not correct type (expected \(HouseAtreides.self), got \(type(of: taskContainer.task))") } } else { XCTFail("Storage does not contain correct group") } } } extension InMemoryStorage { subscript(groupName: String) -> [TaskContainer] { get { guard let data = store, let taskGroups = try? JSONDecoder().decode([GroupedTasks.GroupAndContainers].self, from: data) else { return [] } return taskGroups.first(where: { $0.group == groupName })?.containers ?? [] } set { guard !newValue.isEmpty else { store = nil return } let group = GroupedTasks.GroupAndContainers(group: groupName, containers: newValue) store = try? JSONEncoder().encode([group]) } } }
mit
krzysztofzablocki/Sourcery
SourceryFramework/Sources/Parsing/Utils/InlineParser.swift
1
4284
// // Created by Krzysztof Zablocki on 16/01/2017. // Copyright (c) 2017 Pixle. All rights reserved. // import Foundation public enum TemplateAnnotationsParser { public typealias AnnotatedRanges = [String: [(range: NSRange, indentation: String)]] private static func regex(annotation: String) throws -> NSRegularExpression { let commentPattern = NSRegularExpression.escapedPattern(for: "//") let regex = try NSRegularExpression( pattern: "(^(?:\\s*?\\n)?(\\s*)\(commentPattern)\\s*?sourcery:\(annotation):)(\\S*)\\s*?(^.*?)(^\\s*?\(commentPattern)\\s*?sourcery:end)", options: [.allowCommentsAndWhitespace, .anchorsMatchLines, .dotMatchesLineSeparators] ) return regex } public static func parseAnnotations(_ annotation: String, contents: String, aggregate: Bool = false, forceParse: [String]) -> (contents: String, annotatedRanges: AnnotatedRanges) { let (annotatedRanges, rangesToReplace) = annotationRanges(annotation, contents: contents, aggregate: aggregate, forceParse: forceParse) let strigView = StringView(contents) var bridged = contents.bridge() rangesToReplace .sorted(by: { $0.location > $1.location }) .forEach { bridged = bridged.replacingCharacters(in: $0, with: String(repeating: " ", count: strigView.NSRangeToByteRange($0)!.length.value)) as NSString } return (bridged as String, annotatedRanges) } public static func annotationRanges(_ annotation: String, contents: String, aggregate: Bool = false, forceParse: [String]) -> (annotatedRanges: AnnotatedRanges, rangesToReplace: Set<NSRange>) { let bridged = contents.bridge() let regex = try? self.regex(annotation: annotation) var rangesToReplace = Set<NSRange>() var annotatedRanges = AnnotatedRanges() regex?.enumerateMatches(in: contents, options: [], range: bridged.entireRange) { result, _, _ in guard let result = result, result.numberOfRanges == 6 else { return } let indentationRange = result.range(at: 2) let nameRange = result.range(at: 3) let startLineRange = result.range(at: 4) let endLineRange = result.range(at: 5) let indentation = bridged.substring(with: indentationRange) let name = bridged.substring(with: nameRange) let range = NSRange( location: startLineRange.location, length: endLineRange.location - startLineRange.location ) if aggregate { var ranges = annotatedRanges[name] ?? [] ranges.append((range: range, indentation: indentation)) annotatedRanges[name] = ranges } else { annotatedRanges[name] = [(range: range, indentation: indentation)] } let rangeToBeRemoved = !forceParse.contains(where: { name.hasSuffix("." + $0) || name == $0 }) if rangeToBeRemoved { rangesToReplace.insert(range) } } return (annotatedRanges, rangesToReplace) } public static func removingEmptyAnnotations(from content: String) -> String { var bridged = content.bridge() let regex = try? self.regex(annotation: "\\S*") var rangesToReplace = [NSRange]() regex?.enumerateMatches(in: content, options: [], range: bridged.entireRange) { result, _, _ in guard let result = result, result.numberOfRanges == 6 else { return } let annotationStartRange = result.range(at: 1) let startLineRange = result.range(at: 4) let endLineRange = result.range(at: 5) if startLineRange.length == 0 { rangesToReplace.append(NSRange( location: annotationStartRange.location, length: NSMaxRange(endLineRange) - annotationStartRange.location )) } } rangesToReplace .reversed() .forEach { bridged = bridged.replacingCharacters(in: $0, with: "") as NSString } return bridged as String } }
mit
onevcat/Rainbow
Sources/ControlCode.swift
1
1530
// // ControlCode.swift // Rainbow // // Created by Wei Wang on 15/12/22. // // Copyright (c) 2018 Wei Wang <onevcat@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. enum ControlCode { static let ESC: Character = "\u{001B}" static let OPEN_BRACKET: Character = "[" static let CSI = "\(ESC)\(OPEN_BRACKET)" static let setColor: UInt8 = 38 static let setBackgroundColor: UInt8 = 48 static let set8Bit: UInt8 = 5 static let set24Bit: UInt8 = 2 }
mit
erosnick/SoftRenderer
SoftRenderer/DotMatrixFont.swift
1
159
// // DotMatrixFont.swift // SoftRenderer // // Created by Princerin on 4/9/16. // Copyright © 2016 Princerin. All rights reserved. // import Foundation
mit
lorentey/GlueKit
Sources/UIDevice Glue.swift
1
5911
// // UIDevice Glue.swift // GlueKit // // Created by Károly Lőrentey on 2016-03-13. // Copyright © 2015–2017 Károly Lőrentey. // #if os(iOS) import UIKit extension UIDevice { open override var glue: GlueForUIDevice { return _glue() } } open class GlueForUIDevice: GlueForNSObject { private var object: UIDevice { return owner as! UIDevice } public lazy var orientation: AnyObservableValue<UIDeviceOrientation> = ObservableDeviceOrientation(self.object).anyObservableValue public lazy var batteryState: AnyObservableValue<(UIDeviceBatteryState, Float)> = ObservableBatteryState(self.object).anyObservableValue public lazy var proximityState: AnyObservableValue<Bool> = ObservableDeviceProximity(self.object).anyObservableValue } private struct DeviceOrientationSink: UniqueOwnedSink { typealias Owner = ObservableDeviceOrientation unowned let owner: Owner func receive(_ notification: Notification) { owner.receive(notification) } } private final class ObservableDeviceOrientation: _BaseObservableValue<UIDeviceOrientation> { unowned let device: UIDevice var orientation: UIDeviceOrientation? = nil init(_ device: UIDevice) { self.device = device } override var value: UIDeviceOrientation { return device.orientation } lazy var notificationSource: AnySource<Notification> = NotificationCenter.default.glue.source(forName: .UIDeviceOrientationDidChange, sender: self.device, queue: OperationQueue.main) func receive(_ notification: Notification) { beginTransaction() let old = orientation! let new = device.orientation orientation = new sendChange(.init(from: old, to: new)) endTransaction() } override func activate() { device.beginGeneratingDeviceOrientationNotifications() orientation = device.orientation notificationSource.add(DeviceOrientationSink(owner: self)) } override func deactivate() { notificationSource.remove(DeviceOrientationSink(owner: self)) device.endGeneratingDeviceOrientationNotifications() orientation = nil } } private struct BatteryStateSink: UniqueOwnedSink { typealias Owner = ObservableBatteryState unowned let owner: Owner func receive(_ notification: Notification) { owner.receive(notification) } } private var batteryKey: UInt8 = 0 private final class ObservableBatteryState: _BaseObservableValue<(UIDeviceBatteryState, Float)> { typealias Value = (UIDeviceBatteryState, Float) unowned let device: UIDevice var state: Value? = nil var didEnableBatteryMonitoring = false lazy var batteryStateSource: AnySource<Notification> = NotificationCenter.default.glue.source(forName: .UIDeviceBatteryStateDidChange, sender: self.device, queue: OperationQueue.main) lazy var batteryLevelSource: AnySource<Notification> = NotificationCenter.default.glue.source(forName: .UIDeviceBatteryLevelDidChange, sender: self.device, queue: OperationQueue.main) init(_ device: UIDevice) { self.device = device } override var value: Value { return (device.batteryState, device.batteryLevel) } func receive(_ notification: Notification) { let old = state! let new = (device.batteryState, device.batteryLevel) if old != new { beginTransaction() state = new sendChange(.init(from: old, to: new)) endTransaction() } } override func activate() { if !device.isBatteryMonitoringEnabled { device.isBatteryMonitoringEnabled = true didEnableBatteryMonitoring = true } state = (device.batteryState, device.batteryLevel) batteryStateSource.add(BatteryStateSink(owner: self)) batteryLevelSource.add(BatteryStateSink(owner: self)) } override func deactivate() { batteryStateSource.remove(BatteryStateSink(owner: self)) batteryLevelSource.remove(BatteryStateSink(owner: self)) if didEnableBatteryMonitoring { device.isBatteryMonitoringEnabled = false didEnableBatteryMonitoring = false } state = nil } } private struct DeviceProximitySink: UniqueOwnedSink { typealias Owner = ObservableDeviceProximity unowned let owner: Owner func receive(_ notification: Notification) { owner.receive(notification) } } private var proximityKey: UInt8 = 0 private final class ObservableDeviceProximity: _BaseObservableValue<Bool> { unowned let device: UIDevice var state: Bool? = nil var didEnableProximityMonitoring = false lazy var notificationSource: AnySource<Notification> = NotificationCenter.default.glue.source(forName: .UIDeviceProximityStateDidChange, sender: self.device, queue: OperationQueue.main) init(_ device: UIDevice) { self.device = device } override var value: Bool { return device.proximityState } func receive(_ notification: Notification) { beginTransaction() let old = state! let new = device.proximityState state = new sendChange(.init(from: old, to: new)) endTransaction() } override func activate() { if !device.isProximityMonitoringEnabled { device.isProximityMonitoringEnabled = true didEnableProximityMonitoring = true } state = device.proximityState notificationSource.add(DeviceProximitySink(owner: self)) } override func deactivate() { notificationSource.remove(DeviceProximitySink(owner: self)) if didEnableProximityMonitoring { device.isProximityMonitoringEnabled = false didEnableProximityMonitoring = false } state = nil } } #endif
mit
lorentey/GlueKit
Package.swift
1
718
// swift-tools-version:4.0 import PackageDescription let package = Package( name: "GlueKit", products: [ .library(name: "GlueKit", type: .dynamic, targets: ["GlueKit"]) ], dependencies: [ .package(url: "https://github.com/attaswift/SipHash", from: "1.2.0"), .package(url: "https://github.com/attaswift/BTree", from: "4.1.0") ], targets: [ .target(name: "GlueKit", dependencies: ["BTree", "SipHash"], path: "Sources"), .testTarget(name: "GlueKitTests", dependencies: ["GlueKit"], path: "Tests/GlueKitTests"), .testTarget(name: "PerformanceTests", dependencies: ["GlueKit"], path: "Tests/PerformanceTests") ], swiftLanguageVersions: [4] )
mit
vbudhram/firefox-ios
ThirdParty/SQLite.swift/Tests/SQLiteTests/ConnectionTests.swift
2
13305
import XCTest @testable import SQLite #if SQLITE_SWIFT_STANDALONE import sqlite3 #elseif SQLITE_SWIFT_SQLCIPHER import SQLCipher #else import SQLite3 #endif class ConnectionTests : SQLiteTestCase { override func setUp() { super.setUp() CreateUsersTable() } func test_init_withInMemory_returnsInMemoryConnection() { let db = try! Connection(.inMemory) XCTAssertEqual("", db.description) } func test_init_returnsInMemoryByDefault() { let db = try! Connection() XCTAssertEqual("", db.description) } func test_init_withTemporary_returnsTemporaryConnection() { let db = try! Connection(.temporary) XCTAssertEqual("", db.description) } func test_init_withURI_returnsURIConnection() { let db = try! Connection(.uri("\(NSTemporaryDirectory())/SQLite.swift Tests.sqlite3")) XCTAssertEqual("\(NSTemporaryDirectory())/SQLite.swift Tests.sqlite3", db.description) } func test_init_withString_returnsURIConnection() { let db = try! Connection("\(NSTemporaryDirectory())/SQLite.swift Tests.sqlite3") XCTAssertEqual("\(NSTemporaryDirectory())/SQLite.swift Tests.sqlite3", db.description) } func test_readonly_returnsFalseOnReadWriteConnections() { XCTAssertFalse(db.readonly) } func test_readonly_returnsTrueOnReadOnlyConnections() { let db = try! Connection(readonly: true) XCTAssertTrue(db.readonly) } func test_changes_returnsZeroOnNewConnections() { XCTAssertEqual(0, db.changes) } func test_lastInsertRowid_returnsLastIdAfterInserts() { try! InsertUser("alice") XCTAssertEqual(1, db.lastInsertRowid) } func test_lastInsertRowid_doesNotResetAfterError() { XCTAssert(db.lastInsertRowid == 0) try! InsertUser("alice") XCTAssertEqual(1, db.lastInsertRowid) XCTAssertThrowsError( try db.run("INSERT INTO \"users\" (email, age, admin) values ('invalid@example.com', 12, 'invalid')") ) { error in if case SQLite.Result.error(_, let code, _) = error { XCTAssertEqual(SQLITE_CONSTRAINT, code) } else { XCTFail("expected error") } } XCTAssertEqual(1, db.lastInsertRowid) } func test_changes_returnsNumberOfChanges() { try! InsertUser("alice") XCTAssertEqual(1, db.changes) try! InsertUser("betsy") XCTAssertEqual(1, db.changes) } func test_totalChanges_returnsTotalNumberOfChanges() { XCTAssertEqual(0, db.totalChanges) try! InsertUser("alice") XCTAssertEqual(1, db.totalChanges) try! InsertUser("betsy") XCTAssertEqual(2, db.totalChanges) } func test_prepare_preparesAndReturnsStatements() { _ = try! db.prepare("SELECT * FROM users WHERE admin = 0") _ = try! db.prepare("SELECT * FROM users WHERE admin = ?", 0) _ = try! db.prepare("SELECT * FROM users WHERE admin = ?", [0]) _ = try! db.prepare("SELECT * FROM users WHERE admin = $admin", ["$admin": 0]) } func test_run_preparesRunsAndReturnsStatements() { try! db.run("SELECT * FROM users WHERE admin = 0") try! db.run("SELECT * FROM users WHERE admin = ?", 0) try! db.run("SELECT * FROM users WHERE admin = ?", [0]) try! db.run("SELECT * FROM users WHERE admin = $admin", ["$admin": 0]) AssertSQL("SELECT * FROM users WHERE admin = 0", 4) } func test_scalar_preparesRunsAndReturnsScalarValues() { XCTAssertEqual(0, try! db.scalar("SELECT count(*) FROM users WHERE admin = 0") as? Int64) XCTAssertEqual(0, try! db.scalar("SELECT count(*) FROM users WHERE admin = ?", 0) as? Int64) XCTAssertEqual(0, try! db.scalar("SELECT count(*) FROM users WHERE admin = ?", [0]) as? Int64) XCTAssertEqual(0, try! db.scalar("SELECT count(*) FROM users WHERE admin = $admin", ["$admin": 0]) as? Int64) AssertSQL("SELECT count(*) FROM users WHERE admin = 0", 4) } func test_execute_comment() { try! db.run("-- this is a comment\nSELECT 1") AssertSQL("-- this is a comment", 0) AssertSQL("SELECT 1", 0) } func test_transaction_executesBeginDeferred() { try! db.transaction(.deferred) {} AssertSQL("BEGIN DEFERRED TRANSACTION") } func test_transaction_executesBeginImmediate() { try! db.transaction(.immediate) {} AssertSQL("BEGIN IMMEDIATE TRANSACTION") } func test_transaction_executesBeginExclusive() { try! db.transaction(.exclusive) {} AssertSQL("BEGIN EXCLUSIVE TRANSACTION") } func test_transaction_beginsAndCommitsTransactions() { let stmt = try! db.prepare("INSERT INTO users (email) VALUES (?)", "alice@example.com") try! db.transaction { try stmt.run() } AssertSQL("BEGIN DEFERRED TRANSACTION") AssertSQL("INSERT INTO users (email) VALUES ('alice@example.com')") AssertSQL("COMMIT TRANSACTION") AssertSQL("ROLLBACK TRANSACTION", 0) } func test_transaction_beginsAndRollsTransactionsBack() { let stmt = try! db.prepare("INSERT INTO users (email) VALUES (?)", "alice@example.com") do { try db.transaction { try stmt.run() try stmt.run() } } catch { } AssertSQL("BEGIN DEFERRED TRANSACTION") AssertSQL("INSERT INTO users (email) VALUES ('alice@example.com')", 2) AssertSQL("ROLLBACK TRANSACTION") AssertSQL("COMMIT TRANSACTION", 0) } func test_savepoint_beginsAndCommitsSavepoints() { let db = self.db try! db.savepoint("1") { try db.savepoint("2") { try db.run("INSERT INTO users (email) VALUES (?)", "alice@example.com") } } AssertSQL("SAVEPOINT '1'") AssertSQL("SAVEPOINT '2'") AssertSQL("INSERT INTO users (email) VALUES ('alice@example.com')") AssertSQL("RELEASE SAVEPOINT '2'") AssertSQL("RELEASE SAVEPOINT '1'") AssertSQL("ROLLBACK TO SAVEPOINT '2'", 0) AssertSQL("ROLLBACK TO SAVEPOINT '1'", 0) } func test_savepoint_beginsAndRollsSavepointsBack() { let db = self.db let stmt = try! db.prepare("INSERT INTO users (email) VALUES (?)", "alice@example.com") do { try db.savepoint("1") { try db.savepoint("2") { try stmt.run() try stmt.run() try stmt.run() } try db.savepoint("2") { try stmt.run() try stmt.run() try stmt.run() } } } catch { } AssertSQL("SAVEPOINT '1'") AssertSQL("SAVEPOINT '2'") AssertSQL("INSERT INTO users (email) VALUES ('alice@example.com')", 2) AssertSQL("ROLLBACK TO SAVEPOINT '2'") AssertSQL("ROLLBACK TO SAVEPOINT '1'") AssertSQL("RELEASE SAVEPOINT '2'", 0) AssertSQL("RELEASE SAVEPOINT '1'", 0) } func test_updateHook_setsUpdateHook_withInsert() { async { done in db.updateHook { operation, db, table, rowid in XCTAssertEqual(Connection.Operation.insert, operation) XCTAssertEqual("main", db) XCTAssertEqual("users", table) XCTAssertEqual(1, rowid) done() } try! InsertUser("alice") } } func test_updateHook_setsUpdateHook_withUpdate() { try! InsertUser("alice") async { done in db.updateHook { operation, db, table, rowid in XCTAssertEqual(Connection.Operation.update, operation) XCTAssertEqual("main", db) XCTAssertEqual("users", table) XCTAssertEqual(1, rowid) done() } try! db.run("UPDATE users SET email = 'alice@example.com'") } } func test_updateHook_setsUpdateHook_withDelete() { try! InsertUser("alice") async { done in db.updateHook { operation, db, table, rowid in XCTAssertEqual(Connection.Operation.delete, operation) XCTAssertEqual("main", db) XCTAssertEqual("users", table) XCTAssertEqual(1, rowid) done() } try! db.run("DELETE FROM users WHERE id = 1") } } func test_commitHook_setsCommitHook() { async { done in db.commitHook { done() } try! db.transaction { try self.InsertUser("alice") } XCTAssertEqual(1, try! db.scalar("SELECT count(*) FROM users") as? Int64) } } func test_rollbackHook_setsRollbackHook() { async { done in db.rollbackHook(done) do { try db.transaction { try self.InsertUser("alice") try self.InsertUser("alice") // throw } } catch { } XCTAssertEqual(0, try! db.scalar("SELECT count(*) FROM users") as? Int64) } } func test_commitHook_withRollback_rollsBack() { async { done in db.commitHook { throw NSError(domain: "com.stephencelis.SQLiteTests", code: 1, userInfo: nil) } db.rollbackHook(done) do { try db.transaction { try self.InsertUser("alice") } } catch { } XCTAssertEqual(0, try! db.scalar("SELECT count(*) FROM users") as? Int64) } } func test_createFunction_withArrayArguments() { db.createFunction("hello") { $0[0].map { "Hello, \($0)!" } } XCTAssertEqual("Hello, world!", try! db.scalar("SELECT hello('world')") as? String) XCTAssert(try! db.scalar("SELECT hello(NULL)") == nil) } func test_createFunction_createsQuotableFunction() { db.createFunction("hello world") { $0[0].map { "Hello, \($0)!" } } XCTAssertEqual("Hello, world!", try! db.scalar("SELECT \"hello world\"('world')") as? String) XCTAssert(try! db.scalar("SELECT \"hello world\"(NULL)") == nil) } func test_createCollation_createsCollation() { try! db.createCollation("NODIACRITIC") { lhs, rhs in return lhs.compare(rhs, options: .diacriticInsensitive) } XCTAssertEqual(1, try! db.scalar("SELECT ? = ? COLLATE NODIACRITIC", "cafe", "café") as? Int64) } func test_createCollation_createsQuotableCollation() { try! db.createCollation("NO DIACRITIC") { lhs, rhs in return lhs.compare(rhs, options: .diacriticInsensitive) } XCTAssertEqual(1, try! db.scalar("SELECT ? = ? COLLATE \"NO DIACRITIC\"", "cafe", "café") as? Int64) } func test_interrupt_interruptsLongRunningQuery() { try! InsertUsers("abcdefghijklmnopqrstuvwxyz".map { String($0) }) db.createFunction("sleep") { args in usleep(UInt32((args[0] as? Double ?? Double(args[0] as? Int64 ?? 1)) * 1_000_000)) return nil } let stmt = try! db.prepare("SELECT *, sleep(?) FROM users", 0.1) try! stmt.run() let deadline = DispatchTime.now() + Double(Int64(10 * NSEC_PER_MSEC)) / Double(NSEC_PER_SEC) _ = DispatchQueue.global(priority: .background).asyncAfter(deadline: deadline, execute: db.interrupt) AssertThrows(try stmt.run()) } } class ResultTests : XCTestCase { let connection = try! Connection(.inMemory) func test_init_with_ok_code_returns_nil() { XCTAssertNil(Result(errorCode: SQLITE_OK, connection: connection, statement: nil) as Result?) } func test_init_with_row_code_returns_nil() { XCTAssertNil(Result(errorCode: SQLITE_ROW, connection: connection, statement: nil) as Result?) } func test_init_with_done_code_returns_nil() { XCTAssertNil(Result(errorCode: SQLITE_DONE, connection: connection, statement: nil) as Result?) } func test_init_with_other_code_returns_error() { if case .some(.error(let message, let code, let statement)) = Result(errorCode: SQLITE_MISUSE, connection: connection, statement: nil) { XCTAssertEqual("not an error", message) XCTAssertEqual(SQLITE_MISUSE, code) XCTAssertNil(statement) XCTAssert(self.connection === connection) } else { XCTFail() } } func test_description_contains_error_code() { XCTAssertEqual("not an error (code: 21)", Result(errorCode: SQLITE_MISUSE, connection: connection, statement: nil)?.description) } func test_description_contains_statement_and_error_code() { let statement = try! Statement(connection, "SELECT 1") XCTAssertEqual("not an error (SELECT 1) (code: 21)", Result(errorCode: SQLITE_MISUSE, connection: connection, statement: statement)?.description) } }
mpl-2.0
keitaito/HackuponApp
HackuponApp/Models/Person.swift
1
208
// // Person.swift // HackuponApp // // Created by Keita Ito on 3/14/16. // Copyright © 2016 Keita Ito. All rights reserved. // import Foundation struct Person { let name: String let id: Int }
mit
timgrohmann/vertretungsplan_ios
Vertretungsplan/ChangedLesson.swift
1
1686
// // ChangedLesson.swift // Vertretungsplan // // Created by Tim Grohmann on 15.08.16. // Copyright © 2016 Tim Grohmann. All rights reserved. // import Foundation import UIKit import CoreData class ChangedLesson: Equatable{ var subject: String = "" var origSubject: String? var teacher: String = "" var origTeacher: String? var room: String = "" var course: String = "" var info: String = "" var day: Int? var hour: Int? var identifier: String{ return subject+teacher+room+course+info+String(describing: day)+String(describing: hour) } init(subject: String, teacher: String, room: String, course: String, info: String, day: Int, hour: Int) { self.subject = subject self.teacher = teacher self.room = room self.course = course self.info = info self.day = day self.hour = hour } init(){} func applies(_ lesson: Lesson, user: User)->Bool{ if (course.lowercased() == lesson.course.lowercased()){ return true } if let oTeacher = self.origTeacher, let oSubject = self.origSubject { //print("asserting:",oTeacher.lowercased(),"==",lesson.teacher.lowercased()) return (oTeacher.lowercased() == lesson.teacher.lowercased()) && (oSubject.lowercased() == lesson.subject.lowercased()) } /*if klasse?.klassen.count == 1 && klasse?.klassen[0] == myKlasse{ return true }*/ return false } } func ==(lhs: ChangedLesson, rhs: ChangedLesson) -> Bool{ return lhs.identifier == rhs.identifier }
apache-2.0
jbennett/Bugology
Bugology/MockPresentationContext.swift
1
1207
// // MockPresentationContext.swift // Bugology // // Created by Jonathan Bennett on 2016-01-20. // Copyright © 2016 Jonathan Bennett. All rights reserved. // import UIKit // swiftlint:disable variable_name_min_length public class MockPresentationContext: PresentationContext { func adsfa() { // let a = UIViewController() } var shownViewControllers = [UIViewController]() public func showViewController(vc: UIViewController, sender: AnyObject?) { shownViewControllers.append(vc) } var shownDetailViewControllers = [UIViewController]() public func showDetailViewController(vc: UIViewController, sender: AnyObject?) { shownDetailViewControllers.append(vc) } typealias VCCallback = (() -> Void) var presentedViewControllers = [UIViewController]() var presentedViewControllerCallbacks = [VCCallback?]() public func presentViewController(viewControllerToPresent: UIViewController, animated: Bool, completion: (() -> Void)?) { presentedViewControllers.append(viewControllerToPresent) presentedViewControllerCallbacks.append(completion) } var styles = [Service?]() public func setStyleForService(service: Service?) { styles.append(service) } }
mit
IngmarStein/swift
test/attr/attr_noescape.swift
4
18654
// RUN: %target-parse-verify-swift @noescape var fn : () -> Int = { 4 } // expected-error {{@noescape may only be used on 'parameter' declarations}} {{1-11=}} func conflictingAttrs(_ fn: @noescape @escaping () -> Int) {} // expected-error {{@escaping conflicts with @noescape}} // expected-warning@-1{{@noescape is the default and is deprecated}} {{29-39=}} func doesEscape(_ fn : @escaping () -> Int) {} func takesGenericClosure<T>(_ a : Int, _ fn : @noescape () -> T) {} // expected-warning{{@noescape is the default and is deprecated}} {{47-57=}} func takesNoEscapeClosure(_ fn : () -> Int) { // expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }} // expected-note@-2{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }} // expected-note@-3{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }} // expected-note@-4{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }} takesNoEscapeClosure { 4 } // ok _ = fn() // ok var x = fn // expected-error {{non-escaping parameter 'fn' may only be called}} // This is ok, because the closure itself is noescape. takesNoEscapeClosure { fn() } // This is not ok, because it escapes the 'fn' closure. doesEscape { fn() } // expected-error {{closure use of non-escaping parameter 'fn' may allow it to escape}} // This is not ok, because it escapes the 'fn' closure. func nested_function() { _ = fn() // expected-error {{declaration closing over non-escaping parameter 'fn' may allow it to escape}} } takesNoEscapeClosure(fn) // ok doesEscape(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} takesGenericClosure(4, fn) // ok takesGenericClosure(4) { fn() } // ok. } class SomeClass { final var x = 42 func test() { // This should require "self." doesEscape { x } // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}} // Since 'takesNoEscapeClosure' doesn't escape its closure, it doesn't // require "self." qualification of member references. takesNoEscapeClosure { x } } @discardableResult func foo() -> Int { foo() func plain() { foo() } let plain2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} func multi() -> Int { foo(); return 0 } let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{31-31=self.}} doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}} takesNoEscapeClosure { foo() } // okay doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}} takesNoEscapeClosure { foo(); return 0 } // okay func outer() { func inner() { foo() } let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} func multi() -> Int { foo(); return 0 } let _: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{28-28=self.}} doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo() } doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo(); return 0 } } let outer2: () -> Void = { func inner() { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} func multi() -> Int { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{29-29=self.}} let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}} doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}} doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}} } doesEscape { func inner() { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} func multi() -> Int { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{29-29=self.}} let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}} doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}} doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}} return 0 } takesNoEscapeClosure { func inner() { foo() } let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} func multi() -> Int { foo(); return 0 } let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}} doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo() } // okay doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo(); return 0 } // okay return 0 } struct Outer { @discardableResult func bar() -> Int { bar() func plain() { bar() } let plain2 = { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}} func multi() -> Int { bar(); return 0 } let _: () -> Int = { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}} doesEscape { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} takesNoEscapeClosure { bar() } // okay doesEscape { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} takesNoEscapeClosure { bar(); return 0 } // okay return 0 } } func structOuter() { struct Inner { @discardableResult func bar() -> Int { bar() // no-warning func plain() { bar() } let plain2 = { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{26-26=self.}} func multi() -> Int { bar(); return 0 } let _: () -> Int = { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{32-32=self.}} doesEscape { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}} takesNoEscapeClosure { bar() } // okay doesEscape { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}} takesNoEscapeClosure { bar(); return 0 } // okay return 0 } } } return 0 } } // Implicit conversions (in this case to @convention(block)) are ok. @_silgen_name("whatever") func takeNoEscapeAsObjCBlock(_: @noescape @convention(block) () -> Void) // expected-warning{{@noescape is the default and is deprecated}} {{33-43=}} func takeNoEscapeTest2(_ fn : @noescape () -> ()) { // expected-warning{{@noescape is the default and is deprecated}} {{31-41=}} takeNoEscapeAsObjCBlock(fn) } // Autoclosure implies noescape, but produce nice diagnostics so people know // why noescape problems happen. func testAutoclosure(_ a : @autoclosure () -> Int) { // expected-note{{parameter 'a' is implicitly non-escaping because it was declared @autoclosure}} doesEscape { a() } // expected-error {{closure use of non-escaping parameter 'a' may allow it to escape}} } // <rdar://problem/19470858> QoI: @autoclosure implies @noescape, so you shouldn't be allowed to specify both func redundant(_ fn : @noescape // expected-error @+1 {{@noescape is implied by @autoclosure and should not be redundantly specified}} @autoclosure () -> Int) { // expected-warning@-2{{@noescape is the default and is deprecated}} {{23-33=}} } protocol P1 { associatedtype Element } protocol P2 : P1 { associatedtype Element } func overloadedEach<O: P1, T>(_ source: O, _ transform: @escaping (O.Element) -> (), _: T) {} func overloadedEach<P: P2, T>(_ source: P, _ transform: @escaping (P.Element) -> (), _: T) {} struct S : P2 { typealias Element = Int func each(_ transform: @noescape (Int) -> ()) { // expected-warning{{@noescape is the default and is deprecated}} {{26-36=}} overloadedEach(self, // expected-error {{cannot invoke 'overloadedEach' with an argument list of type '(S, (Int) -> (), Int)'}} transform, 1) // expected-note @-2 {{overloads for 'overloadedEach' exist with these partially matching parameter lists: (O, @escaping (O.Element) -> (), T), (P, @escaping (P.Element) -> (), T)}} } } // rdar://19763676 - False positive in @noescape analysis triggered by parameter label func r19763676Callee(_ f: @noescape (_ param: Int) -> Int) {} // expected-warning{{@noescape is the default and is deprecated}} {{27-37=}} func r19763676Caller(_ g: @noescape (Int) -> Int) { // expected-warning{{@noescape is the default and is deprecated}} {{27-37=}} r19763676Callee({ _ in g(1) }) } // <rdar://problem/19763732> False positive in @noescape analysis triggered by default arguments func calleeWithDefaultParameters(_ f: @noescape () -> (), x : Int = 1) {} // expected-warning {{closure parameter prior to parameters with default arguments will not be treated as a trailing closure}} // expected-warning@-1{{@noescape is the default and is deprecated}} {{39-49=}} func callerOfDefaultParams(_ g: @noescape () -> ()) { // expected-warning{{@noescape is the default and is deprecated}} {{33-43=}} calleeWithDefaultParameters(g) } // <rdar://problem/19773562> Closures executed immediately { like this }() are not automatically @noescape class NoEscapeImmediatelyApplied { func f() { // Shouldn't require "self.", the closure is obviously @noescape. _ = { return ivar }() } final var ivar = 42 } // Reduced example from XCTest overlay, involves a TupleShuffleExpr public func XCTAssertTrue(_ expression: @autoclosure () -> Bool, _ message: String = "", file: StaticString = #file, line: UInt = #line) -> Void { } public func XCTAssert(_ expression: @autoclosure () -> Bool, _ message: String = "", file: StaticString = #file, line: UInt = #line) -> Void { XCTAssertTrue(expression, message, file: file, line: line); } /// SR-770 - Currying and `noescape`/`rethrows` don't work together anymore func curriedFlatMap<A, B>(_ x: [A]) -> (@noescape (A) -> [B]) -> [B] { // expected-warning{{@noescape is the default and is deprecated}} {{41-50=}} return { f in x.flatMap(f) } } func curriedFlatMap2<A, B>(_ x: [A]) -> (@noescape (A) -> [B]) -> [B] { // expected-warning{{@noescape is the default and is deprecated}} {{42-51=}} return { (f : @noescape (A) -> [B]) in // expected-warning{{@noescape is the default and is deprecated}} {{17-27=}} x.flatMap(f) } } func bad(_ a : @escaping (Int)-> Int) -> Int { return 42 } func escapeNoEscapeResult(_ x: [Int]) -> (@noescape (Int) -> Int) -> Int { // expected-warning{{@noescape is the default and is deprecated}} {{43-52=}} return { f in // expected-note{{parameter 'f' is implicitly non-escaping}} bad(f) // expected-error {{passing non-escaping parameter 'f' to function expecting an @escaping closure}} } } // SR-824 - @noescape for Type Aliased Closures // // Old syntax -- @noescape is the default, and is redundant typealias CompletionHandlerNE = @noescape (_ success: Bool) -> () // expected-warning{{@noescape is the default and is deprecated}} {{33-43=}} // Explicit @escaping is not allowed here typealias CompletionHandlerE = @escaping (_ success: Bool) -> () // expected-error{{@escaping attribute may only be used in function parameter position}} {{32-42=}} // No @escaping -- it's implicit from context typealias CompletionHandler = (_ success: Bool) -> () var escape : CompletionHandlerNE var escapeOther : CompletionHandler func doThing1(_ completion: (_ success: Bool) -> ()) { // expected-note@-1{{parameter 'completion' is implicitly non-escaping}} // expected-error @+2 {{non-escaping value 'escape' may only be called}} // expected-error @+1 {{non-escaping parameter 'completion' may only be called}} escape = completion // expected-error {{declaration closing over non-escaping parameter 'escape' may allow it to escape}} } func doThing2(_ completion: CompletionHandlerNE) { // expected-note@-1{{parameter 'completion' is implicitly non-escaping}} // expected-error @+2 {{non-escaping value 'escape' may only be called}} // expected-error @+1 {{non-escaping parameter 'completion' may only be called}} escape = completion // expected-error {{declaration closing over non-escaping parameter 'escape' may allow it to escape}} } func doThing3(_ completion: CompletionHandler) { // expected-note@-1{{parameter 'completion' is implicitly non-escaping}} // expected-error @+2 {{non-escaping value 'escape' may only be called}} // expected-error @+1 {{non-escaping parameter 'completion' may only be called}} escape = completion // expected-error {{declaration closing over non-escaping parameter 'escape' may allow it to escape}} } func doThing4(_ completion: @escaping CompletionHandler) { escapeOther = completion } // <rdar://problem/19997680> @noescape doesn't work on parameters of function type func apply<T, U>(_ f: @noescape (T) -> U, g: @noescape (@noescape (T) -> U) -> U) -> U { // expected-warning@-1{{@noescape is the default and is deprecated}} {{23-33=}} // expected-warning@-2{{@noescape is the default and is deprecated}} {{46-56=}} // expected-warning@-3{{@noescape is the default and is deprecated}} {{57-66=}} return g(f) } // <rdar://problem/19997577> @noescape cannot be applied to locals, leading to duplication of code enum r19997577Type { case Unit case Function(() -> r19997577Type, () -> r19997577Type) case Sum(() -> r19997577Type, () -> r19997577Type) func reduce<Result>(_ initial: Result, _ combine: @noescape (Result, r19997577Type) -> Result) -> Result { // expected-warning{{@noescape is the default and is deprecated}} {{53-63=}} let binary: @noescape (r19997577Type, r19997577Type) -> Result = { combine(combine(combine(initial, self), $0), $1) } // expected-warning{{@noescape is the default and is deprecated}} {{17-27=}} switch self { case .Unit: return combine(initial, self) case let .Function(t1, t2): return binary(t1(), t2()) case let .Sum(t1, t2): return binary(t1(), t2()) } } } // type attribute and decl attribute func noescapeD(@noescape f: @escaping () -> Bool) {} // expected-error {{@noescape is now an attribute on a parameter type, instead of on the parameter itself}} {{16-25=}} {{29-29=@noescape }} func noescapeT(f: @noescape () -> Bool) {} // expected-warning{{@noescape is the default and is deprecated}} {{19-29=}} func autoclosureD(@autoclosure f: () -> Bool) {} // expected-error {{@autoclosure is now an attribute on a parameter type, instead of on the parameter itself}} {{19-31=}} {{35-35=@autoclosure }} func autoclosureT(f: @autoclosure () -> Bool) {} // ok func noescapeD_noescapeT(@noescape f: @noescape () -> Bool) {} // expected-error {{@noescape is now an attribute on a parameter type, instead of on the parameter itself}} // expected-warning@-1{{@noescape is the default and is deprecated}} {{39-49=}} func autoclosureD_noescapeT(@autoclosure f: @noescape () -> Bool) {} // expected-error {{@autoclosure is now an attribute on a parameter type, instead of on the parameter itself}} {{29-41=}} {{45-45=@autoclosure }} // expected-warning@-1{{@noescape is the default and is deprecated}} {{45-55=}}
apache-2.0
collegboi/MBaaSKit
Example/MBaaSKit/TestObject.swift
1
459
// // TestObject.swift // MBaaSKit // // Created by Timothy Barnard on 29/01/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import MBaaSKit //struct TestObject: JSONSerializable { // // var name: String! // // init() { // // } // // init(name: String) { // self.name = name // } // // // init( dict: [String:Any] ) { // self.name = dict["name"] as! String // } //}
mit
h-n-y/BigNerdRanch-SwiftProgramming
chapter-25/GoldChallenge.playground/Contents.swift
1
915
/* GOLD CHALLENGE The method indexOf(_:) is made available in an extension on `CollectionType` that requires the `CollectionType`s `Element`s to conform to the `Equatable` protocol. `Array<Person>` ( the type of *people*, below ) conforms to `CollectionType`, but `Person` must also conform to `Equatable` in order to access the indexOf(_:) method. Here, I've made two `Person` types considered equal if their name and age types are themselves equal. */ import Cocoa class Person: Equatable { let name: String var age: Int init(name: String, age: Int) { self.name = name self.age = age } } func ==(lhs: Person, rhs: Person) -> Bool { return ( lhs.name == rhs.name ) && ( lhs.age == rhs.age ) } let p1 = Person(name: "John", age: 26) let p2 = Person(name: "Jane", age: 22) var people: [Person] = [p1, p2] let p1Index = people.indexOf(p1)
mit
swift-lang/swift-k
tests/language-behaviour/mappers/075-array-mapper.swift
2
364
type messagefile; (messagefile t) write() { app { echo @filename(t) stdout=@filename(t); } } string fns[]=["075-array-mapper.first.out", "075-array-mapper.second.out", "075-array-mapper.third.out"]; messagefile outfile[] <array_mapper; files=fns>; outfile[0] = write(); outfile[1] = write(); outfile[2] = write();
apache-2.0
dnpp73/SimpleCamera
Package.swift
1
406
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "SimpleCamera", platforms: [ .iOS(.v12), .macOS(.v10_11), ], products: [ .library(name: "SimpleCamera", targets: ["SimpleCamera"]), ], targets: [ .target( name: "SimpleCamera", dependencies: [], path: "Sources" ), ] )
mit
LoganHollins/SuperStudent
SuperStudent/AddEventViewController.swift
1
2130
// // AddEventViewController.swift // SuperStudent // // Created by Logan Hollins on 2015-11-28. // Copyright © 2015 Logan Hollins. All rights reserved. // import UIKit import Alamofire class AddEventViewController: UIViewController { var eventObject = Event() @IBOutlet weak var descriptionField: UITextView! @IBOutlet weak var titleField: UITextField! @IBOutlet weak var endTimeField: UIDatePicker! @IBOutlet weak var startTimeField: UIDatePicker! @IBOutlet weak var dateField: UIDatePicker! @IBOutlet weak var locationField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.descriptionField.layer.borderWidth = 1 self.descriptionField.layer.borderColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0).CGColor self.descriptionField.layer.cornerRadius = 5 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func createEvent(sender: AnyObject) { let dFormatter = NSDateFormatter() dFormatter.dateFormat = "yyyy-MM-dd" let tFormatter = NSDateFormatter() tFormatter.dateFormat = "hh:mm a" let currentDate = NSDate() let parameters : [String : AnyObject] = [ "title": titleField.text!, "date": dFormatter.stringFromDate(dateField.date), "location": locationField.text!, "startTime": tFormatter.stringFromDate(startTimeField.date), "endTime": tFormatter.stringFromDate(startTimeField.date), "description": descriptionField.text! ] Alamofire.request(.POST, "https://api.mongolab.com/api/1/databases/rhythmictracks/collections/Events?apiKey=L4HrujTTG-XOamCKvRJp5RwYMpoJ6xCZ", parameters: parameters, encoding: .JSON) StudentInfo.EventCreated = true navigationController?.popViewControllerAnimated(true) } }
gpl-2.0
Chantalisima/Spirometry-app
EspiroGame/ResultViewController.swift
1
6616
// // ResultViewController.swift // BLEgame4 // // Created by Chantal de Leste on 25/3/17. // Copyright © 2017 Universidad de Sevilla. All rights reserved. // import Foundation import UIKit import CoreData import MessageUI struct cellData { var name: String! var value: Float! } class ResultViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MFMailComposeViewControllerDelegate { var FVC: Float = 0.0 var FEV1: Float = 0.0 var PEF: Float = 0.0 var ratio: Float = 0.0 var names = ["FVC","FEV1","ratio"] var results: [Float] = [] var arrayRPM1: [Int] = [] var arrayRPM2: [Int] = [] var arrayRPM3: [Int] = [] var arrayVol: [Float] = [] var arrayFlow: [Float] = [] var computeResult = ComputeResults() @IBOutlet weak var tableView: UITableView! @IBOutlet weak var lineChart: LineChart! @IBAction func saveDataButton(_ sender: Any) { saveData(fvc: FVC, fev1: FEV1, ratio: ratio) } @IBAction func sendEmailButton(_ sender: Any) { let mailComposeViewController = configureMailController() if MFMailComposeViewController.canSendMail(){ self.present(mailComposeViewController, animated: true, completion: nil) }else{ showMailError() } } override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self compute() setLineChart(xdata: arrayVol, ydata: arrayFlow) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = Bundle.main.loadNibNamed("CustomTableViewCell", owner: self, options: nil)?.first as! CustomTableViewCell cell.name.text = names[indexPath.row] // cell.nameLabel.text = names[indexPath.row] cell.value.text = String(results[indexPath.row]) return cell } func compute(){ var ev = computeResult.evaluatefvc(first: arrayRPM1, second: arrayRPM2, third: arrayRPM3) let flow1 = computeResult.convertToFlow(rpms: ev[0]) print("flujo:\(flow1)") let flow2 = computeResult.convertToFlow(rpms: ev[1]) let volumen1 = computeResult.convertToVolume(flow: flow1) print("volumen:\(volumen1)") //let volumen2 = computeResult.convertToVolume(flow: flow2) /*let volumes:[[Float]] = [volumen1,volumen2,volumen3] let maxvolumesfev1 = computeResult.evaluatefev1(volumes: volumes)*/ FVC = computeResult.computeFVC(volumes: volumen1) results.append(FVC) FEV1 = computeResult.computeFEV1(volume: volumen1) results.append(FEV1) ratio = computeResult.computeRatio(fvc: FVC, fev: FEV1) results.append(ratio) arrayVol = volumen1 arrayFlow = flow1 } func setLineChart(xdata: [Float], ydata:[Float]) { var charData: [CGPoint] = [] let length = xdata.count-1 print("length of xdata: \(xdata.count)") print("length of ydata: \(ydata.count)") for index in 0..<length { charData.append(CGPoint(x: Double(xdata[index]), y: Double(ydata[index]))) } print(charData as Any) lineChart.xMax = 6 lineChart.xMin = 0 lineChart.deltaX = 1 lineChart.yMax = 8 lineChart.yMin = 0 lineChart.deltaY = 1 lineChart.plot(charData) } func saveData(fvc: Float,fev1: Float,ratio: Float){ let appDelegate = (UIApplication.shared.delegate) as! AppDelegate let context = appDelegate.persistentContainer.viewContext let newTest = NSEntityDescription.insertNewObject(forEntityName: "Test", into: context) let date = Date() let calendar = Calendar.current let year = calendar.component(.year, from: date) let month = calendar.component(.month, from: date) let week = calendar.component(.weekday, from: date) let day = calendar.component(.day, from: date) let hour = calendar.component(.hour, from: date) let minute = calendar.component(.minute, from: date) newTest.setValue(fvc, forKey: "fvc") newTest.setValue(fev1, forKey: "fev1") newTest.setValue(ratio, forKey: "ratio") newTest.setValue(date, forKey: "date") newTest.setValue(year, forKey: "year") newTest.setValue(month, forKey: "month") newTest.setValue(week, forKey: "week") newTest.setValue(day, forKey: "day") newTest.setValue(hour, forKey: "hour") newTest.setValue(minute, forKey: "minute") //appDelegate.saveContext() do{ try newTest.managedObjectContext?.save() }catch{ print("error") } } func configureMailController() -> MFMailComposeViewController { let mailComposerVC = MFMailComposeViewController() mailComposerVC.mailComposeDelegate = self mailComposerVC.setCcRecipients(["medico@saludpublica.es"]) mailComposerVC.setSubject("Chart flow/volumen") mailComposerVC.setMessageBody("Hello, I attach to this email my results from today:", isHTML: false) //Create the UIImage UIGraphicsBeginImageContext(view.frame.size) view.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() //Save it to the camera roll //UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) let imageData = UIImageJPEGRepresentation(image!, 1.0) mailComposerVC.addAttachmentData(imageData!, mimeType: "image/jpeg", fileName: "My Image") return mailComposerVC } func showMailError() { let sendMailErrorAlert = UIAlertController(title: "Could not send email", message: "Your device could not send email", preferredStyle: .alert) let dismiss = UIAlertAction(title: "Ok", style: .default, handler: nil) sendMailErrorAlert.addAction(dismiss) self.present(sendMailErrorAlert, animated: true, completion: nil) } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true, completion: nil) } }
apache-2.0
steveholt55/metro
iOS/Pods/OHHTTPStubs/OHHTTPStubs/Sources/Swift/OHHTTPStubsSwift.swift
3
8086
/*********************************************************************************** * * Copyright (c) 2012 Olivier Halligon * * 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. * ***********************************************************************************/ /** * Swift Helpers */ // MARK: Syntaxic Sugar for OHHTTPStubs /** * Helper to return a `OHHTTPStubsResponse` given a fixture path, status code and optional headers. * * - Parameter filePath: the path of the file fixture to use for the response * - Parameter status: the status code to use for the response * - Parameter headers: the HTTP headers to use for the response * * - Returns: The `OHHTTPStubsResponse` instance that will stub with the given status code * & headers, and use the file content as the response body. */ public func fixture(filePath: String, status: Int32 = 200, headers: [NSObject: AnyObject]?) -> OHHTTPStubsResponse { return OHHTTPStubsResponse(fileAtPath: filePath, statusCode: status, headers: headers) } /** * Helper to call the stubbing function in a more concise way? * * - Parameter condition: the matcher block that determine if the request will be stubbed * - Parameter response: the stub reponse to use if the request is stubbed * * - Returns: The opaque `OHHTTPStubsDescriptor` that uniquely identifies the stub * and can be later used to remove it with `removeStub:` */ public func stub(condition: OHHTTPStubsTestBlock, response: OHHTTPStubsResponseBlock) -> OHHTTPStubsDescriptor { return OHHTTPStubs.stubRequestsPassingTest(condition, withStubResponse: response) } // MARK: Create OHHTTPStubsTestBlock matchers /** * Matcher testing that the `NSURLRequest` is using the **GET** `HTTPMethod` * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request * is using the GET method */ public func isMethodGET() -> OHHTTPStubsTestBlock { return { $0.HTTPMethod == "GET" } } /** * Matcher testing that the `NSURLRequest` is using the **POST** `HTTPMethod` * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request * is using the POST method */ public func isMethodPOST() -> OHHTTPStubsTestBlock { return { $0.HTTPMethod == "POST" } } /** * Matcher testing that the `NSURLRequest` is using the **PUT** `HTTPMethod` * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request * is using the PUT method */ public func isMethodPUT() -> OHHTTPStubsTestBlock { return { $0.HTTPMethod == "PUT" } } /** * Matcher testing that the `NSURLRequest` is using the **PATCH** `HTTPMethod` * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request * is using the PATCH method */ public func isMethodPATCH() -> OHHTTPStubsTestBlock { return { $0.HTTPMethod == "PATCH" } } /** * Matcher testing that the `NSURLRequest` is using the **DELETE** `HTTPMethod` * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request * is using the DELETE method */ public func isMethodDELETE() -> OHHTTPStubsTestBlock { return { $0.HTTPMethod == "DELETE" } } /** * Matcher for testing an `NSURLRequest`'s **scheme**. * * - Parameter scheme: The scheme to match * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request * has the given scheme */ public func isScheme(scheme: String) -> OHHTTPStubsTestBlock { return { req in req.URL?.scheme == scheme } } /** * Matcher for testing an `NSURLRequest`'s **host**. * * - Parameter host: The host to match * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request * has the given host */ public func isHost(host: String) -> OHHTTPStubsTestBlock { return { req in req.URL?.host == host } } /** * Matcher for testing an `NSURLRequest`'s **path**. * * - Parameter path: The path to match * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request * has exactly the given path * * - Note: URL paths are usually absolute and thus starts with a '/' (which you * should include in the `path` parameter unless you're testing relative URLs) */ public func isPath(path: String) -> OHHTTPStubsTestBlock { return { req in req.URL?.path == path } } /** * Matcher for testing an `NSURLRequest`'s **path extension**. * * - Parameter ext: The file extension to match (without the dot) * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request path * ends with the given extension */ public func isExtension(ext: String) -> OHHTTPStubsTestBlock { return { req in req.URL?.pathExtension == ext } } /** * Matcher for testing an `NSURLRequest`'s **query parameters**. * * - Parameter params: The dictionary of query parameters to check the presence for * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds if the request contains * the given query parameters with the given value. * * - Note: There is a difference between: * (1) using `[q:""]`, which matches a query parameter "?q=" with an empty value, and * (2) using `[q:nil]`, which matches a query parameter "?q" without a value at all */ @available(iOS 8.0, OSX 10.10, *) public func containsQueryParams(params: [String:String?]) -> OHHTTPStubsTestBlock { return { req in if let url = req.URL { let comps = NSURLComponents(URL: url, resolvingAgainstBaseURL: true) if let queryItems = comps?.queryItems { for (k,v) in params { if queryItems.filter({ qi in qi.name == k && qi.value == v }).count == 0 { return false } } return true } } return false } } // MARK: Operators on OHHTTPStubsTestBlock /** * Combine different `OHHTTPStubsTestBlock` matchers with an 'OR' operation. * * - Parameter lhs: the first matcher to test * - Parameter rhs: the second matcher to test * * - Returns: a matcher (`OHHTTPStubsTestBlock`) that succeeds if either of the given matchers succeeds */ public func || (lhs: OHHTTPStubsTestBlock, rhs: OHHTTPStubsTestBlock) -> OHHTTPStubsTestBlock { return { req in lhs(req) || rhs(req) } } /** * Combine different `OHHTTPStubsTestBlock` matchers with an 'AND' operation. * * - Parameter lhs: the first matcher to test * - Parameter rhs: the second matcher to test * * - Returns: a matcher (`OHHTTPStubsTestBlock`) that only succeeds if both of the given matchers succeeds */ public func && (lhs: OHHTTPStubsTestBlock, rhs: OHHTTPStubsTestBlock) -> OHHTTPStubsTestBlock { return { req in lhs(req) && rhs(req) } } /** * Create the opposite of a given `OHHTTPStubsTestBlock` matcher. * * - Parameter expr: the matcher to negate * * - Returns: a matcher (OHHTTPStubsTestBlock) that only succeeds if the expr matcher fails */ public prefix func ! (expr: OHHTTPStubsTestBlock) -> OHHTTPStubsTestBlock { return { req in !expr(req) } }
mit
cuappdev/eatery
Eatery/Onboarding/Controllers/OnboardingViewController.swift
1
5372
// // OnboardingViewController.swift // Eatery // // Created by Reade Plunkett on 11/11/19. // Copyright © 2019 CUAppDev. All rights reserved. // import UIKit protocol OnboardingViewControllerDelegate { func onboardingViewControllerDidTapNext(_ viewController: OnboardingViewController) } class OnboardingViewController: UIViewController { private let stackView = UIStackView() private var stackViewBottomConstraint: NSLayoutConstraint? private var skipButtonTopContraint: NSLayoutConstraint? private let titleLabel = UILabel() private let subtitleLabel = UILabel() private let onboardingTitle: String private let onboardingSubtitle: String private let skipButton = UIButton() let contentView = UIView() var delegate: OnboardingViewControllerDelegate? init(title: String, subtitle: String) { self.onboardingTitle = title self.onboardingSubtitle = subtitle super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .eateryBlue setUpStackView() setUpTitleLabel() setUpSubtitleLabel() setUpContentView() NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil) } private func setUpStackView() { stackView.axis = .vertical stackView.distribution = .fill stackView.alignment = .center stackView.spacing = 40 view.addSubview(stackView) stackView.snp.makeConstraints { make in make.leading.trailing.equalToSuperview().inset(32) make.centerY.equalToSuperview().priority(.high) } stackViewBottomConstraint = view.bottomAnchor.constraint(equalTo: stackView.bottomAnchor) stackViewBottomConstraint?.isActive = false } private func setUpTitleLabel() { titleLabel.text = onboardingTitle titleLabel.textColor = .white titleLabel.textAlignment = .center titleLabel.font = .systemFont(ofSize: 36, weight: .bold) stackView.addArrangedSubview(titleLabel) } private func setUpSubtitleLabel() { subtitleLabel.text = onboardingSubtitle subtitleLabel.textColor = .white subtitleLabel.numberOfLines = 0 subtitleLabel.textAlignment = .center subtitleLabel.font = .systemFont(ofSize: 24, weight: .medium) stackView.addArrangedSubview(subtitleLabel) } private func setUpContentView() { stackView.addArrangedSubview(contentView) } func setUpSkipButton(target: Any?, action: Selector) { skipButton.setTitle("SKIP", for: .normal) skipButton.titleLabel?.font = .systemFont(ofSize: 18, weight: .bold) skipButton.titleLabel?.textColor = .white skipButton.addTarget(target, action: action, for: .touchUpInside) view.addSubview(skipButton) skipButton.snp.makeConstraints { make in make.topMargin.equalToSuperview().offset(32) make.rightMargin.equalToSuperview().offset(-32) } skipButtonTopContraint = view.topAnchor.constraint(equalTo: skipButton.topAnchor) skipButtonTopContraint?.isActive = false } } extension OnboardingViewController { @objc private func keyboardWillShow(notification: NSNotification) { guard let userInfo = notification.userInfo, let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey] as? CGRect else { return } let actions: () -> Void = { self.stackViewBottomConstraint?.constant = keyboardFrame.height + 16 self.stackViewBottomConstraint?.isActive = true self.skipButtonTopContraint?.constant = keyboardFrame.height + 16 self.skipButtonTopContraint?.isActive = true self.view.layoutIfNeeded() } if let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval { UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: actions) } else { actions() } } @objc private func keyboardWillHide(notification: NSNotification) { guard let userInfo = notification.userInfo else { return } let actions: () -> Void = { self.stackViewBottomConstraint?.isActive = false self.skipButtonTopContraint?.isActive = false self.view.layoutIfNeeded() } if let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval { UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: actions) } else { actions() } } }
mit
JohnSundell/SwiftKit
Source/iOS/Animate.swift
1
356
import UIKit /// Perform a closure of animations with a certain duration, optionally attaching a completion handler public func Animate(animations: () -> Void, duration: NSTimeInterval = 0.3, onCompletion: (() -> Void)? = nil) { UIView.animateWithDuration(duration, animations: animations) { didComplete -> Void in onCompletion?() } }
mit
TJ-93/TestKitchen
TestKitchen/TestKitchen/classes/Ingredient/service(处理公共点击事件)/WebViewService.swift
1
193
// // WebViewService.swift // TestKitchen // // Created by qianfeng on 2016/11/3. // Copyright © 2016年 陶杰. All rights reserved. // import UIKit class WebViewService: NSObject { }
mit
saeta/penguin
Tests/PenguinStructuresTests/XCTestManifests.swift
1
1734
// Copyright 2020 Penguin Authors // // 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 XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ // Please maintain this list in alphabetical order. testCase(AnyArrayBufferTests.allTests), testCase(AnyValueTests.allTests), testCase(ArrayBufferTests.allTests), testCase(ArrayStorageExtensionTests.allTests), testCase(ArrayStorageTests.allTests), testCase(CollectionAlgorithmTests.allTests), testCase(ConcatenationTests.allTests), testCase(DequeTests.allTests), testCase(DoubleEndedBufferTests.allTests), testCase(EitherCollectionTests.allTests), testCase(EitherTests.allTests), testCase(FactoryInitializableTests.allTests), testCase(FixedSizeArrayTests.allTests), testCase(HeapTests.allTests), testCase(HierarchicalCollectionTests.allTests), testCase(NominalElementDictionaryTests.allTests), testCase(PCGRandomNumberGeneratorTests.allTests), testCase(RandomTests.allTests), testCase(TupleTests.allTests), testCase(TypeIDTests.allTests), testCase(UnsignedInteger_ReducedTests.allTests), ] } #endif
apache-2.0
zimcherDev/ios
Zimcher/UIKit Objects/MainScenes/TabBarViewController.swift
1
793
// // TabBarViewController.swift // SwiftPort // // Created by Weiyu Huang on 11/13/15. // Copyright © 2015 Kappa. All rights reserved. // import UIKit class TabBarViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //UITabBar.appearance().selectionIndicatorImage = UIImage.imageFromColorAndSize(UIColor.whiteColor(), size: CGSizeMake(200, tabBar.frame.size.height)) tabBar.tintColor = COLORSCHEME.TAB_BAR.TINT tabBar.barTintColor = COLORSCHEME.TAB_BAR.BAR_TINT tabBar.items?.forEach {item in item.setTitleTextAttributes([NSFontAttributeName: FONTS.SF_MEDIUM.fontWithSize(12)], forState: .Normal) } } }
apache-2.0
zpz1237/NirZhihuDaily2.0
zhihuDaily 2.0/ThemeViewController.swift
2
12746
// // ThemeViewController.swift // zhihuDaily 2.0 // // Created by Nirvana on 10/15/15. // Copyright © 2015 NSNirvana. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import SDWebImage class ThemeViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var navTitleLabel: UILabel! @IBOutlet weak var topConstant: NSLayoutConstraint! var id = "" var name = "" var firstDisplay = true var dragging = false var triggered = false var navImageView: UIImageView! var themeSubview: ParallaxHeaderView! var animator: ZFModalTransitionAnimator! var loadCircleView: PNCircleChart! var loadingView: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() self.automaticallyAdjustsScrollViewInsets = false //清空原数据 self.appCloud().themeContent = nil //拿到新数据 refreshData(nil) //创建leftBarButtonItem let leftButton = UIBarButtonItem(image: UIImage(named: "leftArrow"), style: .Plain, target: self.revealViewController(), action: "revealToggle:") leftButton.tintColor = UIColor.whiteColor() self.navigationItem.setLeftBarButtonItem(leftButton, animated: false) //为当前view添加手势识别 self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) self.view.addGestureRecognizer(self.revealViewController().tapGestureRecognizer()) //生成并配置HeaderImageView navImageView = UIImageView(frame: CGRectMake(0, 0, self.view.frame.width, 64)) navImageView.contentMode = UIViewContentMode.ScaleAspectFill navImageView.clipsToBounds = true //将其添加到ParallaxView themeSubview = ParallaxHeaderView.parallaxThemeHeaderViewWithSubView(navImageView, forSize: CGSizeMake(self.view.frame.width, 64), andImage: navImageView.image) as! ParallaxHeaderView themeSubview.delegate = self //将ParallaxView设置为tableHeaderView,主View添加tableView self.tableView.tableHeaderView = themeSubview self.view.addSubview(tableView) //设置NavigationBar为透明 self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor.clearColor()) self.navigationController?.navigationBar.shadowImage = UIImage() //初始化下拉加载loadCircleView let comp1 = self.navTitleLabel.frame.width/2 let comp2 = (self.navTitleLabel.text! as NSString).sizeWithAttributes(nil).width/2 let loadCircleViewXPosition = comp1 - comp2 - 35 loadCircleView = PNCircleChart(frame: CGRect(x: loadCircleViewXPosition, y: 3, width: 15, height: 15), total: 100, current: 0, clockwise: true, shadow: false, shadowColor: nil, displayCountingLabel: false, overrideLineWidth: 1) loadCircleView.backgroundColor = UIColor.clearColor() loadCircleView.strokeColor = UIColor.whiteColor() loadCircleView.strokeChart() loadCircleView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI)) self.navTitleLabel.addSubview(loadCircleView) //初始化下拉加载loadingView loadingView = UIActivityIndicatorView(frame: CGRect(x: loadCircleViewXPosition+2.5, y: 5.5, width: 10, height: 10)) self.navTitleLabel.addSubview(loadingView) //tableView基础设置 self.tableView.delegate = self self.tableView.dataSource = self self.tableView.separatorStyle = .None self.tableView.showsVerticalScrollIndicator = false } override func viewDidAppear(animated: Bool) { self.tableView.reloadData() if !firstDisplay { self.topConstant.constant = -44 } else { self.topConstant.constant = -64 firstDisplay = false } } func refreshData(completionHandler: (()->())?) { //更改标题 navTitleLabel.text = name //获取数据 Alamofire.request(.GET, "http://news-at.zhihu.com/api/4/theme/" + id).responseJSON { (_, _, dataResult) -> Void in guard dataResult.error == nil else { print("数据获取失败") return } let data = JSON(dataResult.value!) //取得Story let storyData = data["stories"] //暂时注入themeStory var themeStory: [ContentStoryModel] = [] for i in 0 ..< storyData.count { //判断是否含图 if storyData[i]["images"] != nil { themeStory.append(ContentStoryModel(images: [storyData[i]["images"][0].string!], id: String(storyData[i]["id"]), title: storyData[i]["title"].string!)) } else { //若不含图 themeStory.append(ContentStoryModel(images: [""], id: String(storyData[i]["id"]), title: storyData[i]["title"].string!)) } } //取得avatars let avatarsData = data["editors"] //暂时注入editorsAvatars var editorsAvatars: [String] = [] for i in 0 ..< avatarsData.count { editorsAvatars.append(avatarsData[i]["avatar"].string!) } //更新图片 self.navImageView.sd_setImageWithURL(NSURL(string: data["background"].string!), completed: { (image, _, _, _) -> Void in self.themeSubview.blurViewImage = image self.themeSubview.refreshBlurViewForNewImage() }) //注入themeContent self.appCloud().themeContent = ThemeContentModel(stories: themeStory, background: data["background"].string!, editorsAvatars: editorsAvatars) //刷新数据 self.tableView.reloadData() if let completionHandler = completionHandler { completionHandler() } } } //设置StatusBar颜色 override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } //获取总代理 func appCloud() -> AppDelegate { return UIApplication.sharedApplication().delegate as! AppDelegate } } extension ThemeViewController: UITableViewDelegate, UITableViewDataSource, ParallaxHeaderViewDelegate { //实现Parallax效果 func scrollViewDidScroll(scrollView: UIScrollView) { let header = self.tableView.tableHeaderView as! ParallaxHeaderView header.layoutThemeHeaderViewForScrollViewOffset(scrollView.contentOffset) let offsetY = scrollView.contentOffset.y if offsetY <= 0 { let ratio = -offsetY*2 if ratio <= 100 { if triggered == false && loadCircleView.hidden == true { loadCircleView.hidden = false } loadCircleView.updateChartByCurrent(ratio) } else { if loadCircleView.current != 100 { loadCircleView.updateChartByCurrent(100) } //第一次检测到松手 if !dragging && !triggered { loadCircleView.hidden = true loadingView.startAnimating() refreshData({ () -> () in self.loadingView.stopAnimating() }) triggered = true } } if triggered == true && offsetY == 0 { triggered = false } } else { if loadCircleView.hidden != true { loadCircleView.hidden = true } } } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { dragging = false } func scrollViewWillBeginDragging(scrollView: UIScrollView) { dragging = true } //设置滑动极限 func lockDirection() { self.tableView.contentOffset.y = -95 } //处理UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //如果还未获取到数据 if appCloud().themeContent == nil { return 0 } //如含有数据 return appCloud().themeContent!.stories.count + 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //取得已读新闻数组以供配置 let readNewsIdArray = NSUserDefaults.standardUserDefaults().objectForKey(Keys.readNewsId) as! [String] if indexPath.row == 0 { let cell = tableView.dequeueReusableCellWithIdentifier("themeEditorTableViewCell") as! ThemeEditorTableViewCell for (index, editorsAvatar) in appCloud().themeContent!.editorsAvatars.enumerate() { let avatar = UIImageView(frame: CGRectMake(62 + CGFloat(37 * index), 12.5, 20, 20)) avatar.contentMode = .ScaleAspectFill avatar.layer.cornerRadius = 10 avatar.clipsToBounds = true avatar.sd_setImageWithURL(NSURL(string: editorsAvatar)) cell.contentView.addSubview(avatar) } return cell } //取到Story数据 let tempContentStoryItem = appCloud().themeContent!.stories[indexPath.row - 1] //保证图片一定存在,选择合适的Cell类型 guard tempContentStoryItem.images[0] != "" else { let cell = tableView.dequeueReusableCellWithIdentifier("themeTextTableViewCell") as! ThemeTextTableViewCell //验证是否已被点击过 if let _ = readNewsIdArray.indexOf(tempContentStoryItem.id) { cell.themeTextLabel.textColor = UIColor.lightGrayColor() } else { cell.themeTextLabel.textColor = UIColor.blackColor() } cell.themeTextLabel.text = tempContentStoryItem.title return cell } //处理图片存在的情况 let cell = tableView.dequeueReusableCellWithIdentifier("themeContentTableViewCell") as! ThemeContentTableViewCell //验证是否已被点击过 if let _ = readNewsIdArray.indexOf(tempContentStoryItem.id) { cell.themeContentLabel.textColor = UIColor.lightGrayColor() } else { cell.themeContentLabel.textColor = UIColor.blackColor() } cell.themeContentLabel.text = tempContentStoryItem.title cell.themeContentImageView.sd_setImageWithURL(NSURL(string: tempContentStoryItem.images[0])) return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.row == 0 { return 45 } return 92 } //处理UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row == 0 { return } //拿到webViewController let webViewController = self.storyboard?.instantiateViewControllerWithIdentifier("webViewController") as! WebViewController webViewController.newsId = appCloud().themeContent!.stories[self.tableView.indexPathForSelectedRow!.row - 1].id webViewController.index = indexPath.row - 1 webViewController.isThemeStory = true //取得已读新闻数组以供修改 var readNewsIdArray = NSUserDefaults.standardUserDefaults().objectForKey(Keys.readNewsId) as! [String] //记录已被选中的id readNewsIdArray.append(webViewController.newsId) NSUserDefaults.standardUserDefaults().setObject(readNewsIdArray, forKey: Keys.readNewsId) //对animator进行初始化 animator = ZFModalTransitionAnimator(modalViewController: webViewController) self.animator.dragable = true self.animator.bounces = false self.animator.behindViewAlpha = 0.7 self.animator.behindViewScale = 0.9 self.animator.transitionDuration = 0.7 self.animator.direction = ZFModalTransitonDirection.Right //设置webViewController webViewController.transitioningDelegate = self.animator //实施转场 self.presentViewController(webViewController, animated: true) { () -> Void in } } }
mit
ps2/rileylink_ios
MinimedKit/Messages/PowerOnCarelinkMessageBody.swift
1
782
// // PowerOnCarelinkMessageBody.swift // Naterade // // Created by Nathan Racklyeft on 12/26/15. // Copyright © 2015 Nathan Racklyeft. All rights reserved. // import Foundation public struct PowerOnCarelinkMessageBody: MessageBody { public static var length: Int = 65 public var txData: Data let duration: TimeInterval public init(duration: TimeInterval) { self.duration = duration let numArgs = 2 let on = 1 let durationMinutes: Int = Int(ceil(duration / 60.0)) self.txData = Data(hexadecimalString: String(format: "%02x%02x%02x", numArgs, on, durationMinutes))!.paddedTo(length: PowerOnCarelinkMessageBody.length) } public var description: String { return "PowerOn(duration:\(duration))" } }
mit
feinstruktur/Nimble
Tests/Nimble/Matchers/ContainTest.swift
14
3466
import Foundation import XCTest import Nimble class ContainTest: XCTestCase, XCTestCaseProvider { var allTests: [(String, () throws -> Void)] { return [ ("testContain", testContain), ("testContainSubstring", testContainSubstring), ("testContainObjCSubstring", testContainObjCSubstring), ("testVariadicArguments", testVariadicArguments), ("testCollectionArguments", testCollectionArguments), ] } func testContain() { expect([1, 2, 3]).to(contain(1)) expect([1, 2, 3] as [CInt]).to(contain(1 as CInt)) expect([1, 2, 3] as Array<CInt>).to(contain(1 as CInt)) expect(["foo", "bar", "baz"]).to(contain("baz")) expect([1, 2, 3]).toNot(contain(4)) expect(["foo", "bar", "baz"]).toNot(contain("ba")) #if _runtime(_ObjC) expect(NSArray(array: ["a"])).to(contain(NSString(string: "a"))) expect(NSArray(array: ["a"])).toNot(contain(NSString(string:"b"))) expect(NSArray(object: 1) as NSArray?).to(contain(1)) #endif failsWithErrorMessage("expected to contain <bar>, got <[a, b, c]>") { expect(["a", "b", "c"]).to(contain("bar")) } failsWithErrorMessage("expected to not contain <b>, got <[a, b, c]>") { expect(["a", "b", "c"]).toNot(contain("b")) } failsWithErrorMessageForNil("expected to contain <bar>, got <nil>") { expect(nil as [String]?).to(contain("bar")) } failsWithErrorMessageForNil("expected to not contain <b>, got <nil>") { expect(nil as [String]?).toNot(contain("b")) } } func testContainSubstring() { expect("foo").to(contain("o")) expect("foo").to(contain("oo")) expect("foo").toNot(contain("z")) expect("foo").toNot(contain("zz")) failsWithErrorMessage("expected to contain <bar>, got <foo>") { expect("foo").to(contain("bar")) } failsWithErrorMessage("expected to not contain <oo>, got <foo>") { expect("foo").toNot(contain("oo")) } } func testContainObjCSubstring() { let str = NSString(string: "foo") expect(str).to(contain(NSString(string: "o"))) expect(str).to(contain(NSString(string: "oo"))) expect(str).toNot(contain(NSString(string: "z"))) expect(str).toNot(contain(NSString(string: "zz"))) } func testVariadicArguments() { expect([1, 2, 3]).to(contain(1, 2)) expect([1, 2, 3]).toNot(contain(1, 4)) failsWithErrorMessage("expected to contain <a, bar>, got <[a, b, c]>") { expect(["a", "b", "c"]).to(contain("a", "bar")) } failsWithErrorMessage("expected to not contain <bar, b>, got <[a, b, c]>") { expect(["a", "b", "c"]).toNot(contain("bar", "b")) } } func testCollectionArguments() { expect([1, 2, 3]).to(contain([1, 2])) expect([1, 2, 3]).toNot(contain([1, 4])) let collection = Array(1...10) let slice = Array(collection[3...5]) expect(collection).to(contain(slice)) failsWithErrorMessage("expected to contain <a, bar>, got <[a, b, c]>") { expect(["a", "b", "c"]).to(contain(["a", "bar"])) } failsWithErrorMessage("expected to not contain <bar, b>, got <[a, b, c]>") { expect(["a", "b", "c"]).toNot(contain(["bar", "b"])) } } }
apache-2.0
SakuragiTen/DYTV
DYTV/DYTV/AppDelegate.swift
1
2170
// // AppDelegate.swift // DYTV // // Created by 龚胜 on 16/10/10. // Copyright © 2016年 gongsheng. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { UITabBar.appearance().tintColor = UIColor.orange return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
benlangmuir/swift
test/Interop/SwiftToCxx/structs/swift-struct-in-cxx.swift
2
4450
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend %s -typecheck -module-name Structs -clang-header-expose-public-decls -emit-clang-header-path %t/structs.h // RUN: %FileCheck %s < %t/structs.h // RUN: %check-interop-cxx-header-in-clang(%t/structs.h -Wno-unused-private-field -Wno-unused-function) // CHECK: namespace Structs { // CHECK: namespace _impl { // CHECK: namespace Structs { // CHECK: namespace _impl { // CHECK-EMPTY: // CHECK-NEXT: class _impl_StructWithIntField; // CHECK-EMPTY: // CHECK-NEXT: // Type metadata accessor for StructWithIntField // CHECK-NEXT: SWIFT_EXTERN swift::_impl::MetadataResponseTy $s7Structs18StructWithIntFieldVMa(swift::_impl::MetadataRequestTy) SWIFT_NOEXCEPT SWIFT_CALL; // CHECK-EMPTY: // CHECK-EMPTY: // CHECK-NEXT: } // CHECK: class StructWithIntField final { // CHECK-NEXT: public: // CHECK-NEXT: inline ~StructWithIntField() { // CHECK: } // CHECK-NEXT: inline StructWithIntField(const StructWithIntField &other) { // CHECK: } // CHECK-NEXT: inline StructWithIntField(StructWithIntField &&) = default; // CHECK-NEXT: private: // CHECK-NEXT: inline StructWithIntField() {} // CHECK-NEXT: static inline StructWithIntField _make() { return StructWithIntField(); } // CHECK-NEXT: inline const char * _Nonnull _getOpaquePointer() const { return _storage; } // CHECK-NEXT: inline char * _Nonnull _getOpaquePointer() { return _storage; } // CHECK-EMPTY: // CHECK-NEXT: alignas(8) char _storage[8]; // CHECK-NEXT: friend class _impl::_impl_StructWithIntField; // CHECK-NEXT: }; // CHECK: namespace _impl { // CHECK-EMPTY: // CHECK-NEXT: class _impl_StructWithIntField { // CHECK-NEXT: public: // CHECK-NEXT: static inline char * _Nonnull getOpaquePointer(StructWithIntField &object) { return object._getOpaquePointer(); } // CHECK-NEXT: static inline const char * _Nonnull getOpaquePointer(const StructWithIntField &object) { return object._getOpaquePointer(); } // CHECK-NEXT: template<class T> // CHECK-NEXT: static inline StructWithIntField returnNewValue(T callable) { // CHECK-NEXT: auto result = StructWithIntField::_make(); // CHECK-NEXT: callable(result._getOpaquePointer()); // CHECK-NEXT: return result; // CHECK-NEXT: } // CHECK-NEXT: static inline void initializeWithTake(char * _Nonnull destStorage, char * _Nonnull srcStorage) { // CHECK-NEXT: auto metadata = _impl::$s7Structs18StructWithIntFieldVMa(0); // CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1; // CHECK-NEXT: #ifdef __arm64e__ // CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839))); // CHECK-NEXT: #else // CHECK-NEXT: auto *vwTable = *vwTableAddr; // CHECK-NEXT: #endif // CHECK-NEXT: vwTable->initializeWithTake(destStorage, srcStorage, metadata._0); // CHECK-NEXT: } // CHECK-NEXT: }; // CHECK-EMPTY: // CHECK-NEXT: } // CHECK-EMPTY: // CHECK-NEXT: } // end namespace // CHECK-EMPTY: // CHECK-NEXT: namespace swift { // CHECK-NEXT: #pragma clang diagnostic push // CHECK-NEXT: #pragma clang diagnostic ignored "-Wc++17-extensions" // CHECK-NEXT: template<> // CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<Structs::StructWithIntField> = true; // CHECK-NEXT: template<> // CHECK-NEXT: struct TypeMetadataTrait<Structs::StructWithIntField> // CHECK-NEXT: inline void * _Nonnull getTypeMetadata() { // CHECK-NEXT: return Structs::_impl::$s7Structs18StructWithIntFieldVMa(0)._0; // CHECK-NEXT: } // CHECK-NEXT: }; // CHECK-NEXT: namespace _impl{ // CHECK-NEXT: template<> // CHECK-NEXT: static inline const constexpr bool isValueType<Structs::StructWithIntField> = true; // CHECK-NEXT: template<> // CHECK-NEXT: struct implClassFor<Structs::StructWithIntField> { using type = Structs::_impl::_impl_StructWithIntField; }; // CHECK-NEXT: } // namespace // CHECK-NEXT: #pragma clang diagnostic pop // CHECK-NEXT: } // namespace swift // CHECK-EMPTY: // CHECK-NEXT: namespace Structs { public struct StructWithIntField { let field: Int64 } // Special name gets renamed in C++. // CHECK: class register_ final { // CHECK: alignas(8) char _storage[16]; // CHECK-NEXT: friend class // CHECK-NEXT: }; public struct register { let field1: Int64 let field2: Int64 } // CHECK: } // namespace Structs
apache-2.0
codepgq/LearningSwift
ListenKeyboard/ListenKeyboard/ViewController.swift
1
4231
// // ViewController.swift // ListenKeyboard // // Created by ios on 16/9/24. // Copyright © 2016年 ios. All rights reserved. // import UIKit class ViewController: UIViewController,UITextViewDelegate { @IBOutlet weak var toolBarConstraints: NSLayoutConstraint! @IBOutlet weak var toobar: UIToolbar! @IBOutlet weak var textView: UITextView! @IBOutlet weak var textCount: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() /* UIKeyboardWillHideNotification 将要隐藏 UIKeyboardWillShowNotification 将要显示 UIKeyboardDidChangeFrameNotification 已经修改frame UIKeyboardWillChangeFrameNotification 将要修改frame UIKeyboardDidHideNotification 已经隐藏 UIKeyboardDidShowNotification 已经显示 */ /* UIKeyboardFrameBeginUserInfoKey Rect UIKeyboardFrameEndUserInfoKey Rect UIKeyboardAnimationDurationUserInfoKey 动画时长 UIKeyboardAnimationCurveUserInfoKey 动画Options UIKeyboardIsLocalUserInfoKey NSNumber of BOOL */ /** 监听键盘将要出现通知 */ NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyboardWillShow(_:)), name:UIKeyboardWillShowNotification , object: nil) /** 监听键盘将要隐藏通知 */ NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyboardWillHide(_:)), name:UIKeyboardWillHideNotification , object: nil) /** 设置textView的背景颜色 - parameter white: 白色 0表示黑色 1表示白色 - parameter alpha: 透明度 */ textView.backgroundColor = UIColor(white: 0, alpha: 0.3) /** 代理 */ textView.delegate = self } /** 点击取消 - parameter sender: 取消 */ @IBAction func cancel(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } /** 点击其他的地方取消键盘编辑 - parameter touches: - parameter event: */ override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { view.endEditing(true) } /** 键盘将要显示 - parameter note: 通知 */ @objc private func keyboardWillShow(note:NSNotification){ //获取信息 let userInfo = note.userInfo //得到rect let endRect = (userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() //得到动画时长 let duration = (userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue //开始动画 UIView.animateWithDuration(duration, delay: 0, options: UIViewAnimationOptions(rawValue: UInt((userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue << 16)), animations: { self.toolBarConstraints.constant = endRect.height self.toobar.layoutIfNeeded() }, completion: nil) } /** 键盘将要隐藏 - parameter note: 通知 */ @objc private func keyboardWillHide(note:NSNotification){ let userInfo = note.userInfo let duration = (userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue UIView.animateWithDuration(duration, delay: 0, options: [], animations: { self.toolBarConstraints.constant = 0 self.toobar.layoutIfNeeded() }, completion: nil) } } //*********************** textView代理 ***************** extension ViewController{ func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool{ let text = textView.text as NSString if text.length >= 140 { textView.text = text.substringToIndex(140) } textCount.title = "\(140 - text.length)" //如果这里返回false,textView就不能编辑啦! return true } }
apache-2.0
PodBuilder/XcodeKit
SwiftXcodeKit/Resources/CopyResourcesBuildPhase.swift
1
1940
/* * The sources in the "XcodeKit" directory are based on the Ruby project Xcoder. * * Copyright (c) 2012 cisimple * * MIT License * * 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. */ public class CopyResourcesBuildPhase: BuildPhase { public override class var isaString: String { get { return "PBXResourcesBuildPhase" } } public class func create(inout inRegistry registry: ObjectRegistry) -> CopyResourcesBuildPhase { let properties = [ "isa": isaString, "buildActionMask": NSNumber(integer: 2147483647), "files": [AnyObject](), "runOnlyForDeploymentPreprocessing": "0" ] let phase = CopyResourcesBuildPhase(identifier: registry.generateOID(targetDescription: nil), inRegistry: registry, properties: properties) registry.putResource(phase) return phase } }
mit
tannernelson/hamburger-menu
Pod/Classes/DefaultMenuView.swift
1
2171
// // DefaultMenu.swift // Pods // // Created by Tanner Nelson on 1/16/16. // // import Foundation @available(iOS 9 , *) class DefaultMenuView: MenuView { override init(rootView: UIView, controller: MenuController) { super.init(rootView: rootView, controller: controller) self.backgroundColor = UIColor.whiteColor() let stackView = UIStackView() stackView.axis = .Vertical self.addSubview(stackView) stackView.translatesAutoresizingMaskIntoConstraints = false //align to edges of super view self.addConstraint( NSLayoutConstraint(item: stackView, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 20) ) self.addConstraint( NSLayoutConstraint(item: stackView, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1, constant: 0) ) self.addConstraint( NSLayoutConstraint(item: stackView, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 0) ) if let items = controller.tabBar.items { for (index, item) in items.enumerate() { let button = UIButton() button.contentHorizontalAlignment = .Left button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 0) button.setTitleColor(controller.view.tintColor, forState: .Normal) button.setTitle(item.title, forState: .Normal) button.tag = index button.addTarget(self, action: Selector("buttonTap:"), forControlEvents: .TouchUpInside) stackView.addArrangedSubview(button) } } } func buttonTap(sender: UIButton) { self.switchToTab(sender.tag, andClose: true) } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
rpitting/LGLinearFlow
Example/LGMagnifyingLinearFlowLayout/CollectionViewCell.swift
1
278
// // CollectionViewCell.swift // LGLinearFlowView // // Created by Luka Gabric on 16/08/15. // Copyright © 2015 Luka Gabric. All rights reserved. // import UIKit public class CollectionViewCell: UICollectionViewCell { @IBOutlet public weak var pageLabel: UILabel! }
mit
paulomendes/nextel-challange
nextel-challange/Source/DataProvider/MoviesConnector.swift
1
5084
import Alamofire import Gloss import UIKit protocol MoviesConnectorProtocol { func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) } enum MoviesConnectorError { case errorInSaveLocalFile case internetError } class MoviesConnector : MoviesConnectorProtocol { let moviesPersistence: Persistence static let formatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter }() init(moviesPersistence: Persistence) { self.moviesPersistence = moviesPersistence } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { let params = ["api_key" : DataProvider.apiKey, "query" : query] let utilityQueue = DispatchQueue.global(qos: .utility) Alamofire .request(DataProvider.searchMoviePath, parameters: params) .validate() .responseString (queue: utilityQueue) { response in switch response.result { case .success: DispatchQueue.main.async { success(response.data!) } case .failure: DispatchQueue.main.async { failure(.internetError) } } } } func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { let ago = Calendar.current.date(byAdding: .month, value: -1, to: Date())! let agoString = MoviesConnector.formatter.string(from: ago) let nowString = MoviesConnector.formatter.string(from: Date()) let params = ["api_key" : DataProvider.apiKey, "primary_release_date.gte" : agoString, "primary_release_date.lte" : nowString, "vote_average.gte" : "5"] let utilityQueue = DispatchQueue.global(qos: .utility) Alamofire .request(DataProvider.discoverMoviePath, parameters: params) .validate() .responseString(queue: utilityQueue) { response in switch response.result { case .success: if self.moviesPersistence.saveFile(stringJson: response.result.value!, file: .nowPlayingMovies) { DispatchQueue.main.async { success(response.data!) } } else { DispatchQueue.main.async { failure(.errorInSaveLocalFile) } } case .failure: DispatchQueue.main.async { failure(.internetError) } } } } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { let add = Calendar.current.date(byAdding: .month, value: 1, to: Date())! let add2 = Calendar.current.date(byAdding: .day, value: 1, to: Date())! let futureString = MoviesConnector.formatter.string(from: add) let nowString = MoviesConnector.formatter.string(from: add2) let params = ["api_key" : DataProvider.apiKey, "primary_release_date.gte" : nowString, "primary_release_date.lte" : futureString, "vote_average.gte" : "5"] let utilityQueue = DispatchQueue.global(qos: .utility) Alamofire .request(DataProvider.discoverMoviePath, parameters: params) .validate() .responseString(queue: utilityQueue) { response in switch response.result { case .success: if self.moviesPersistence.saveFile(stringJson: response.result.value!, file: .upcomingMovies) { DispatchQueue.main.async { success(response.data!) } } else { DispatchQueue.main.async { failure(.errorInSaveLocalFile) } } case .failure: DispatchQueue.main.async { failure(.internetError) } } } } }
mit
piwik/piwik-sdk-ios
MatomoTracker/Application.swift
1
2297
#if SWIFT_PACKAGE import Foundation #endif public struct Application { /// Creates an returns a new application object representing the current application public static func makeCurrentApplication() -> Application { let displayName = bundleDisplayNameForCurrentApplication() let name = bundleNameForCurrentApplication() let identifier = bundleIdentifierForCurrentApplication() let version = bundleVersionForCurrentApplication() let shortVersion = bundleShortVersionForCurrentApplication() return Application(bundleDisplayName: displayName, bundleName: name, bundleIdentifier: identifier, bundleVersion: version, bundleShortVersion: shortVersion) } /// The name of your app as displayed on the homescreen i.e. "My App" public let bundleDisplayName: String? /// The bundle name of your app i.e. "my-app" public let bundleName: String? /// The bundle identifier of your app i.e. "com.my-company.my-app" public let bundleIdentifier: String? /// The bundle version a.k.a. build number as String i.e. "149" public let bundleVersion: String? /// The app version as String i.e. "1.0.1" public let bundleShortVersion: String? } extension Application { /// Returns the name of the app as displayed on the homescreen private static func bundleDisplayNameForCurrentApplication() -> String? { return Bundle.main.infoDictionary?["CFBundleDisplayName"] as? String } /// Returns the bundle name of the app private static func bundleNameForCurrentApplication() -> String? { return Bundle.main.infoDictionary?["CFBundleName"] as? String } /// Returns the bundle identifier private static func bundleIdentifierForCurrentApplication() -> String? { return Bundle.main.infoDictionary?["CFBundleIdentifier"] as? String } /// Returns the bundle version private static func bundleVersionForCurrentApplication() -> String? { return Bundle.main.infoDictionary?["CFBundleVersion"] as? String } /// Returns the app version private static func bundleShortVersionForCurrentApplication() -> String? { return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String } }
mit
pabloroca/NewsApp
NewsApp/Controllers/ViewControllers/DetailViewController.swift
1
1921
// // DetailViewController.swift // NewsApp // // Created by Pablo Roca Rozas on 28/03/2017. // Copyright © 2017 PR2Studio. All rights reserved. // import UIKit class DetailViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var detailDescriptionLabel: UILabel! //UI @IBOutlet weak var viewWeb: UIWebView! @IBOutlet weak var viewActivity: UIActivityIndicatorView! //UI var link: String = "" func configureView() { // Update the user interface for the detail item. if let detail = self.detailItem { if let label = self.detailDescriptionLabel { label.text = detail.description } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureView() if !link.isEmpty { viewWeb.delegate = self viewWeb.loadRequest(NSURLRequest(url: NSURL(string: link)! as URL) as URLRequest) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var detailItem: NSDate? { didSet { // Update the view. self.configureView() } } func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { self.viewActivity.isHidden = false self.viewActivity.startAnimating() return true } func webViewDidFinishLoad(_ webView: UIWebView) { self.viewActivity.stopAnimating() self.viewActivity.isHidden = true } func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { self.viewActivity.stopAnimating() self.viewActivity.isHidden = true } }
mit
kunass2/BSTableViewReorder
Example/BSTableViewReorder/BSTableViewCell.swift
1
255
// // BSTableViewCell.swift // BSTableViewReorder // // Created by Bartłomiej Semańczyk on 12/08/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit class BSTableViewCell: UITableViewCell { @IBOutlet var label: UILabel! }
mit
i-schuetz/SwiftCharts
SwiftCharts/Axis/ChartAxisModel.swift
3
6047
// // ChartAxisModel.swift // SwiftCharts // // Created by ischuetz on 22/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public enum ChartAxisPadding { case label /// Add padding corresponding to half of leading / trailing label sizes case none case fixed(CGFloat) /// Set a fixed padding value case maxLabelFixed(CGFloat) /// Use max of padding value corresponding to .Label and a fixed value case labelPlus(CGFloat) /// Use .Label padding + a fixed value } public func ==(a: ChartAxisPadding, b: ChartAxisPadding) -> Bool { switch (a, b) { case (.label, .label): return true case (.fixed(let a), .fixed(let b)) where a == b: return true case (.maxLabelFixed(let a), .maxLabelFixed(let b)) where a == b: return true case (.labelPlus(let a), .labelPlus(let b)) where a == b: return true case (.none, .none): return true default: return false } } /// This class models the contents of a chart axis open class ChartAxisModel { let firstModelValue: Double let lastModelValue: Double let axisValuesGenerator: ChartAxisValuesGenerator let labelsGenerator: ChartAxisLabelsGenerator /// The color used to draw the axis lines let lineColor: UIColor /// The axis title lables let axisTitleLabels: [ChartAxisLabel] let labelsConflictSolver: ChartAxisLabelsConflictSolver? let leadingPadding: ChartAxisPadding let trailingPadding: ChartAxisPadding let labelSpaceReservationMode: AxisLabelsSpaceReservationMode let clipContents: Bool public convenience init(axisValues: [ChartAxisValue], lineColor: UIColor = UIColor.black, axisTitleLabel: ChartAxisLabel, labelsConflictSolver: ChartAxisLabelsConflictSolver? = nil, leadingPadding: ChartAxisPadding = .none, trailingPadding: ChartAxisPadding = .none, labelSpaceReservationMode: AxisLabelsSpaceReservationMode = .minPresentedSize, clipContents: Bool = false) { self.init(axisValues: axisValues, lineColor: lineColor, axisTitleLabels: [axisTitleLabel], labelsConflictSolver: labelsConflictSolver, leadingPadding: leadingPadding, trailingPadding: trailingPadding, labelSpaceReservationMode: labelSpaceReservationMode, clipContents: clipContents) } /// Convenience initializer to pass a fixed axis value array. The array is mapped to axis values and label generators. public convenience init(axisValues: [ChartAxisValue], lineColor: UIColor = UIColor.black, axisTitleLabels: [ChartAxisLabel] = [], labelsConflictSolver: ChartAxisLabelsConflictSolver? = nil, leadingPadding: ChartAxisPadding = .none, trailingPadding: ChartAxisPadding = .none, labelSpaceReservationMode: AxisLabelsSpaceReservationMode = .minPresentedSize, clipContents: Bool = false) { precondition(!axisValues.isEmpty, "Axis cannot be empty") var scalars: [Double] = [] var dict = [Double: [ChartAxisLabel]]() for axisValue in axisValues { scalars.append(axisValue.scalar) dict[axisValue.scalar] = axisValue.labels } let (firstModelValue, lastModelValue) = (axisValues.first!.scalar, axisValues.last!.scalar) let fixedArrayGenerator = ChartAxisValuesGeneratorFixed(values: scalars) let fixedLabelGenerator = ChartAxisLabelsGeneratorFixed(dict: dict) self.init(lineColor: lineColor, firstModelValue: firstModelValue, lastModelValue: lastModelValue, axisTitleLabels: axisTitleLabels, axisValuesGenerator: fixedArrayGenerator, labelsGenerator: fixedLabelGenerator, labelsConflictSolver: labelsConflictSolver, leadingPadding: leadingPadding, trailingPadding: trailingPadding, labelSpaceReservationMode: labelSpaceReservationMode, clipContents: clipContents) } public convenience init(lineColor: UIColor = UIColor.black, firstModelValue: Double, lastModelValue: Double, axisTitleLabel: ChartAxisLabel, axisValuesGenerator: ChartAxisValuesGenerator, labelsGenerator: ChartAxisLabelsGenerator, labelsConflictSolver: ChartAxisLabelsConflictSolver? = nil, leadingPadding: ChartAxisPadding = .none, trailingPadding: ChartAxisPadding = .none, labelSpaceReservationMode: AxisLabelsSpaceReservationMode = .minPresentedSize, clipContents: Bool = false) { self.init(lineColor: lineColor, firstModelValue: firstModelValue, lastModelValue: lastModelValue, axisTitleLabels: [axisTitleLabel], axisValuesGenerator: axisValuesGenerator, labelsGenerator: labelsGenerator, labelsConflictSolver: labelsConflictSolver, leadingPadding: leadingPadding, trailingPadding: trailingPadding, labelSpaceReservationMode: labelSpaceReservationMode, clipContents: clipContents) } public init(lineColor: UIColor = UIColor.black, firstModelValue: Double, lastModelValue: Double, axisTitleLabels: [ChartAxisLabel] = [], axisValuesGenerator: ChartAxisValuesGenerator, labelsGenerator: ChartAxisLabelsGenerator, labelsConflictSolver: ChartAxisLabelsConflictSolver? = nil, leadingPadding: ChartAxisPadding = .none, trailingPadding: ChartAxisPadding = .none, labelSpaceReservationMode: AxisLabelsSpaceReservationMode = .minPresentedSize, clipContents: Bool = false) { self.lineColor = lineColor self.firstModelValue = firstModelValue self.lastModelValue = lastModelValue self.axisTitleLabels = axisTitleLabels self.axisValuesGenerator = axisValuesGenerator self.labelsGenerator = labelsGenerator self.labelsConflictSolver = labelsConflictSolver self.leadingPadding = leadingPadding self.trailingPadding = trailingPadding self.labelSpaceReservationMode = labelSpaceReservationMode self.clipContents = clipContents } } extension ChartAxisModel: CustomDebugStringConvertible { public var debugDescription: String { return [ "firstModelValue": firstModelValue, "lastModelValue": lastModelValue, "axisTitleLabels": axisTitleLabels, ] .debugDescription } }
apache-2.0
digitalcatnip/Pace-SSS-iOS
SSSFreshmanApp/SSSFreshmanApp/RootGroup/RootVC.swift
1
3132
// // RootVC.swift // SSS Freshman App // // Created by James McCarthy on 8/15/16. // Copyright © 2016 Digital Catnip. All rights reserved. // import UIKit class RootVC: UIViewController { override func viewDidAppear(animated: Bool) { registerScreen("StartScreen") } override func viewWillAppear(animated: Bool) { self.navigationController?.setNavigationBarHidden(true, animated: animated) super.viewWillAppear(animated) } override func viewWillDisappear(animated: Bool) { self.navigationController?.setNavigationBarHidden(false, animated: animated) super.viewWillDisappear(animated) } func displayAlert(title: String, body: String) { let alertController = UIAlertController(title: title, message: body, preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } func displayPrompt(title: String, body: String, action: ((UIAlertAction)->(Void))?) { let alertController = UIAlertController(title: title, message: body, preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) let proceedAction = UIAlertAction(title: "OK", style: .Default, handler: action) alertController.addAction(proceedAction) alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } func goToBlackboard(action: UIAlertAction) { let url = NSURL(string: "itms-apps://itunes.apple.com/us/app/blackboard-mobile-learn/id376413870") if UIApplication.sharedApplication().canOpenURL(url!) { UIApplication.sharedApplication().openURL(url!) } else { displayAlert("Failed", body: "Cannot open iTunes for Blackboard Mobile Learn") } } func goToOutlook(action: UIAlertAction) { let url = NSURL(string: "https://itunes.apple.com/us/app/microsoft-outlook-email-calendar/id951937596") if UIApplication.sharedApplication().canOpenURL(url!) { UIApplication.sharedApplication().openURL(url!) } else { displayAlert("Failed", body: "Cannot open MS Outlook or iTunes for MS Outlook.") } } @IBAction func blackBoardPressed() { registerButtonAction("StartScreen", action: "Go To App", label: "Blackboard") displayPrompt("BlackBoard", body: "Go to App Store to open / download Blackboard?", action: goToBlackboard) } @IBAction func msOutlookPressed() { registerButtonAction("StartScreen", action: "Go To App", label: "Outlook") let url = NSURL(string: "ms-outlook://") if UIApplication.sharedApplication().canOpenURL(url!) { UIApplication.sharedApplication().openURL(url!) } else { displayPrompt("Outlook", body: "Go to App Store to download Outlook?", action: goToOutlook) } } }
mit
loganSims/wsdot-ios-app
wsdot/MountainPassesViewController.swift
1
6419
// // MountainPassesViewController.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // import UIKit import Foundation import GoogleMobileAds class MountainPassesViewController: RefreshViewController, UITableViewDelegate, UITableViewDataSource, GADBannerViewDelegate { let cellIdentifier = "PassCell" let segueMountainPassDetailsViewController = "MountainPassDetailsViewController" var passItems = [MountainPassItem]() @IBOutlet weak var bannerView: DFPBannerView! let refreshControl = UIRefreshControl() @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // refresh controller refreshControl.addTarget(self, action: #selector(MountainPassesViewController.refreshAction(_:)), for: .valueChanged) tableView.addSubview(refreshControl) showOverlay(self.view) self.passItems = MountainPassStore.getPasses() self.tableView.reloadData() refresh(false) tableView.rowHeight = UITableView.automaticDimension // Ad Banner bannerView.adUnitID = ApiKeys.getAdId() bannerView.adSize = getFullWidthAdaptiveAdSize() bannerView.rootViewController = self let request = DFPRequest() request.customTargeting = ["wsdotapp":"passes"] bannerView.load(request) bannerView.delegate = self } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) MyAnalytics.screenView(screenName: "PassReports") } func refresh(_ force: Bool){ DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async { [weak self] in MountainPassStore.updatePasses(force, completion: { error in if (error == nil) { // Reload tableview on UI thread DispatchQueue.main.async { [weak self] in if let selfValue = self{ selfValue.passItems = MountainPassStore.getPasses() selfValue.tableView.reloadData() selfValue.refreshControl.endRefreshing() selfValue.hideOverlayView() UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: selfValue.tableView) } } } else { DispatchQueue.main.async { [weak self] in if let selfValue = self{ selfValue.refreshControl.endRefreshing() selfValue.hideOverlayView() AlertMessages.getConnectionAlert(backupURL: WsdotURLS.passes, message: WSDOTErrorStrings.passReports) } } } }) } } @objc func refreshAction(_ sender: UIRefreshControl) { refresh(true) } // MARK: Table View Data Source Methods func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return passItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! MountainPassCell let passItem = passItems[indexPath.row] cell.nameLabel.text = passItem.name cell.forecastLabel.text = "" if (passItem.weatherCondition != ""){ cell.forecastLabel.text = passItem.weatherCondition } if (passItem.forecast.count > 0){ if (cell.forecastLabel.text == "") { cell.forecastLabel.text = WeatherUtils.getForecastBriefDescription(passItem.forecast[0].forecastText) } cell.weatherImage.image = UIImage(named: WeatherUtils.getIconName(passItem.forecast[0].forecastText, title: passItem.forecast[0].day)) } else { cell.forecastLabel.text = "" cell.weatherImage.image = nil } if passItem.dateUpdated as Date == Date.init(timeIntervalSince1970: 0){ cell.updatedLabel.text = "Not Available" }else { cell.updatedLabel.text = TimeUtils.timeAgoSinceDate(date: passItem.dateUpdated, numericDates: true) } return cell } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } // MARK: Table View Delegate Methods func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Perform Segue performSegue(withIdentifier: segueMountainPassDetailsViewController, sender: self) tableView.deselectRow(at: indexPath, animated: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == segueMountainPassDetailsViewController { if let indexPath = tableView.indexPathForSelectedRow { let passItem = self.passItems[indexPath.row] as MountainPassItem let destinationViewController = segue.destination as! MountainPassTabBarViewController destinationViewController.passItem = passItem let backItem = UIBarButtonItem() backItem.title = "Back" navigationItem.backBarButtonItem = backItem } } } }
gpl-3.0
e6-1/e6-1.github.io
iOS Class/Tic-Tac-Toe/Tic-Tac-ToeUITests/Tic_Tac_ToeUITests.swift
1
1258
// // Tic_Tac_ToeUITests.swift // Tic-Tac-ToeUITests // // Created by Ethan Petersen on 6/5/16. // Copyright © 2016 Rose-Hulman. All rights reserved. // import XCTest class Tic_Tac_ToeUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
toymachiner62/myezteam-ios
Myezteam/TeamDao.swift
1
1373
// // TeamDao.swift // Myezteam // // Created by Caflisch, Thomas J. (Tom) on 11/24/15. // Copyright (c) 2015 Tom Caflisch. All rights reserved. // import Foundation struct TeamDao { // MARK: Functions /** Gets the team info from the team id */ static func getTeamInfo(id: Int, callback: (NSDictionary?, String?) -> Void) throws { let request = NSMutableURLRequest(URL: NSURL(string: Constants.makeUrl("/teams/\(id)"))!) request.HTTPMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") let token = NSUserDefaults.standardUserDefaults().stringForKey("myezteamToken") request.addValue("Bearer \(token!)", forHTTPHeaderField: "Authorization") let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in if error != nil { callback(nil, error!.localizedDescription) } else { let teamInfo: NSDictionary = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary callback(teamInfo, nil) } } task.resume() } }
mit
iAmNaz/FormValidationKit
FormValidationKit/ValidatorIterator.swift
1
783
// // ArrayIteratorNZ.swift // FormValidator // // Created by JMariano on 11/11/14. // Copyright (c) 2014 JMariano. All rights reserved. // import UIKit public class ValidatorIterator: NSObject, IteratorNZ { var mutableList: Array<Validator>? var position: Int required public init(listItems: Array<Validator>) { mutableList = listItems position = 0; } func next() -> Validator { let object = mutableList?[position] position++; return object!; } func hasNext() -> Bool { if (position >= mutableList?.count || mutableList?[position] == nil) { return false; } else { return true; } } public func reset() { position = 0 } }
mit
deepak475121/JustForFun
justForFun/Archive/SecondCell.swift
1
998
// // SecondCell.swift // justForFun // // Created by Hari Crayond Digital Reach Pvt Ltd on 20/05/2017. // Copyright © 2017 Crayond Digital Reach Pvt Ltd. All rights reserved. // import UIKit class SecondCell: UITableViewCell { @IBOutlet weak var RegBt: UIButton! @IBOutlet weak var WhatTextView: UITextView! override func awakeFromNib() { super.awakeFromNib() // Initialization code let width = CGFloat(2.0) let border = CALayer() border.borderColor = UIColor.lightGray.cgColor border.frame = CGRect(x: 0, y: WhatTextView.frame.size.height - width, width: WhatTextView.frame.size.width, height: 1) border.borderWidth = width WhatTextView.layer.addSublayer(border) WhatTextView.layer.masksToBounds = true } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
apache-2.0
nguyenantinhbk77/practice-swift
CoreMotion/Retrieving Altitude Data/Retrieving Altitude Data/ViewController.swift
3
184
// // ViewController.swift // Retrieving Altitude Data // // Created by Domenico Solazzo on 20/05/15. // License MIT // import UIKit class ViewController: UIViewController { }
mit
OscarSwanros/swift
test/SILGen/testable-multifile-other.swift
4
2779
// This test is paired with testable-multifile.swift. // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module %S/Inputs/TestableMultifileHelper.swift -enable-testing -o %t // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -I %t %s %S/testable-multifile.swift -module-name main | %FileCheck %s // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -I %t %S/testable-multifile.swift %s -module-name main | %FileCheck %s // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -I %t -primary-file %s %S/testable-multifile.swift -module-name main | %FileCheck %s // Just make sure we don't crash later on. // RUN: %target-swift-frontend -emit-ir -enable-sil-ownership -I %t -primary-file %s %S/testable-multifile.swift -module-name main -o /dev/null // RUN: %target-swift-frontend -emit-ir -enable-sil-ownership -I %t -O -primary-file %s %S/testable-multifile.swift -module-name main -o /dev/null func use<F: Fooable>(_ f: F) { f.foo() } func test(internalFoo: FooImpl, publicFoo: PublicFooImpl) { use(internalFoo) use(publicFoo) internalFoo.foo() publicFoo.foo() } // CHECK-LABEL: sil hidden @_T04main4testyAA7FooImplV08internalC0_AA06PubliccD0V06publicC0tF // CHECK: [[USE_1:%.+]] = function_ref @_T04main3useyxAA7FooableRzlF // CHECK: = apply [[USE_1]]<FooImpl>({{%.+}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Fooable> (@in τ_0_0) -> () // CHECK: [[USE_2:%.+]] = function_ref @_T04main3useyxAA7FooableRzlF // CHECK: = apply [[USE_2]]<PublicFooImpl>({{%.+}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Fooable> (@in τ_0_0) -> () // CHECK: [[IMPL_1:%.+]] = function_ref @_T023TestableMultifileHelper13HasDefaultFooPAAE3fooyyF // CHECK: = apply [[IMPL_1]]<FooImpl>({{%.+}}) : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaultFoo> (@in_guaranteed τ_0_0) -> () // CHECK: [[IMPL_2:%.+]] = function_ref @_T023TestableMultifileHelper13HasDefaultFooPAAE3fooyyF // CHECK: = apply [[IMPL_2]]<PublicFooImpl>({{%.+}}) : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaultFoo> (@in_guaranteed τ_0_0) -> () // CHECK: } // end sil function '_T04main4testyAA7FooImplV08internalC0_AA06PubliccD0V06publicC0tF' func test(internalSub: Sub, publicSub: PublicSub) { internalSub.foo() publicSub.foo() } // CHECK-LABEL: sil hidden @_T04main4testyAA3SubC08internalC0_AA06PublicC0C06publicC0tF // CHECK: bb0([[ARG0:%.*]] : @owned $Sub, [[ARG1:%.*]] : @owned $PublicSub): // CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK: = class_method [[BORROWED_ARG0]] : $Sub, #Sub.foo!1 // CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]] // CHECK: = class_method [[BORROWED_ARG1]] : $PublicSub, #PublicSub.foo!1 // CHECK: } // end sil function '_T04main4testyAA3SubC08internalC0_AA06PublicC0C06publicC0tF'
apache-2.0
OscarSwanros/swift
test/IRGen/dynamic_self_metadata.swift
18
2000
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil %s -emit-ir -parse-as-library | %FileCheck %s // REQUIRES: CPU=x86_64 // FIXME: Not a SIL test because we can't parse dynamic Self in SIL. // <rdar://problem/16931299> // CHECK: [[TYPE:%.+]] = type <{ [8 x i8] }> @inline(never) func id<T>(_ t: T) -> T { return t } // CHECK-LABEL: define hidden swiftcc void @_T021dynamic_self_metadata2idxxlF class C { class func fromMetatype() -> Self? { return nil } // CHECK-LABEL: define hidden swiftcc i64 @_T021dynamic_self_metadata1CC12fromMetatypeACXDSgyFZ(%swift.type* swiftself) // CHECK: [[ALLOCA:%.+]] = alloca [[TYPE]], align 8 // CHECK: [[CAST1:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64* // CHECK: store i64 0, i64* [[CAST1]], align 8 // CHECK: [[CAST2:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64* // CHECK: [[LOAD:%.+]] = load i64, i64* [[CAST2]], align 8 // CHECK: ret i64 [[LOAD]] func fromInstance() -> Self? { return nil } // CHECK-LABEL: define hidden swiftcc i64 @_T021dynamic_self_metadata1CC12fromInstanceACXDSgyF(%T21dynamic_self_metadata1CC* swiftself) // CHECK: [[ALLOCA:%.+]] = alloca [[TYPE]], align 8 // CHECK: [[CAST1:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64* // CHECK: store i64 0, i64* [[CAST1]], align 8 // CHECK: [[CAST2:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64* // CHECK: [[LOAD:%.+]] = load i64, i64* [[CAST2]], align 8 // CHECK: ret i64 [[LOAD]] func dynamicSelfArgument() -> Self? { return id(nil) } // CHECK-LABEL: define hidden swiftcc i64 @_T021dynamic_self_metadata1CC0A12SelfArgumentACXDSgyF(%T21dynamic_self_metadata1CC* swiftself) // CHECK: [[CAST1:%.+]] = bitcast %T21dynamic_self_metadata1CC* %0 to [[METATYPE:%.+]] // CHECK: [[TYPE1:%.+]] = call %swift.type* @swift_getObjectType([[METATYPE]] [[CAST1]]) // CHECK: [[TYPE2:%.+]] = call %swift.type* @_T0SqMa(%swift.type* [[TYPE1]]) // CHECK: call swiftcc void @_T021dynamic_self_metadata2idxxlF({{.*}}, %swift.type* [[TYPE2]]) }
apache-2.0
leonereveel/Moya
Source/Moya+Internal.swift
1
12726
import Foundation import Result /// Internal extension to keep the inner-workings outside the main Moya.swift file. internal extension MoyaProvider { // Yup, we're disabling these. The function is complicated, but breaking it apart requires a large effort. // swiftlint:disable cyclomatic_complexity // swiftlint:disable function_body_length /// Performs normal requests. func requestNormal(target: Target, queue: dispatch_queue_t?, progress: Moya.ProgressBlock?, completion: Moya.Completion) -> Cancellable { let endpoint = self.endpoint(target) let stubBehavior = self.stubClosure(target) let cancellableToken = CancellableWrapper() if trackInflights { objc_sync_enter(self) var inflightCompletionBlocks = self.inflightRequests[endpoint] inflightCompletionBlocks?.append(completion) self.inflightRequests[endpoint] = inflightCompletionBlocks objc_sync_exit(self) if inflightCompletionBlocks != nil { return cancellableToken } else { objc_sync_enter(self) self.inflightRequests[endpoint] = [completion] objc_sync_exit(self) } } let performNetworking = { (requestResult: Result<NSURLRequest, Moya.Error>) in if cancellableToken.cancelled { self.cancelCompletion(completion, target: target) return } var request: NSURLRequest! switch requestResult { case .Success(let urlRequest): request = urlRequest case .Failure(let error): completion(result: .Failure(error)) return } switch stubBehavior { case .Never: let networkCompletion: Moya.Completion = { result in if self.trackInflights { self.inflightRequests[endpoint]?.forEach({ $0(result: result) }) objc_sync_enter(self) self.inflightRequests.removeValueForKey(endpoint) objc_sync_exit(self) } else { completion(result: result) } } switch target.task { case .Request: cancellableToken.innerCancellable = self.sendRequest(target, request: request, queue: queue, progress: progress, completion: networkCompletion) case .Upload(.File(let file)): cancellableToken.innerCancellable = self.sendUploadFile(target, request: request, queue: queue, file: file, progress: progress, completion: networkCompletion) case .Upload(.Multipart(let multipartBody)): guard !multipartBody.isEmpty && target.method.supportsMultipart else { fatalError("\(target) is not a multipart upload target.") } cancellableToken.innerCancellable = self.sendUploadMultipart(target, request: request, queue: queue, multipartBody: multipartBody, progress: progress, completion: networkCompletion) case .Download(.Request(let destination)): cancellableToken.innerCancellable = self.sendDownloadRequest(target, request: request, queue: queue, destination: destination, progress: progress, completion: networkCompletion) } default: cancellableToken.innerCancellable = self.stubRequest(target, request: request, completion: { result in if self.trackInflights { self.inflightRequests[endpoint]?.forEach({ $0(result: result) }) objc_sync_enter(self) self.inflightRequests.removeValueForKey(endpoint) objc_sync_exit(self) } else { completion(result: result) } }, endpoint: endpoint, stubBehavior: stubBehavior) } } requestClosure(endpoint, performNetworking) return cancellableToken } // swiftlint:enable cyclomatic_complexity // swiftlint:enable function_body_length func cancelCompletion(completion: Moya.Completion, target: Target) { let error = Moya.Error.Underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil)) plugins.forEach { $0.didReceiveResponse(.Failure(error), target: target) } completion(result: .Failure(error)) } /// Creates a function which, when called, executes the appropriate stubbing behavior for the given parameters. final func createStubFunction(token: CancellableToken, forTarget target: Target, withCompletion completion: Moya.Completion, endpoint: Endpoint<Target>, plugins: [PluginType]) -> (() -> ()) { return { if token.cancelled { self.cancelCompletion(completion, target: target) return } switch endpoint.sampleResponseClosure() { case .NetworkResponse(let statusCode, let data): let response = Moya.Response(statusCode: statusCode, data: data, response: nil) plugins.forEach { $0.didReceiveResponse(.Success(response), target: target) } completion(result: .Success(response)) case .NetworkError(let error): let error = Moya.Error.Underlying(error) plugins.forEach { $0.didReceiveResponse(.Failure(error), target: target) } completion(result: .Failure(error)) } } } /// Notify all plugins that a stub is about to be performed. You must call this if overriding `stubRequest`. final func notifyPluginsOfImpendingStub(request: NSURLRequest, target: Target) { let alamoRequest = manager.request(request) plugins.forEach { $0.willSendRequest(alamoRequest, target: target) } } } private extension MoyaProvider { private func sendUploadMultipart(target: Target, request: NSURLRequest, queue: dispatch_queue_t?, multipartBody: [MultipartFormData], progress: Moya.ProgressBlock? = nil, completion: Moya.Completion) -> CancellableWrapper { let cancellable = CancellableWrapper() let multipartFormData = { (form: RequestMultipartFormData) -> Void in for bodyPart in multipartBody { switch bodyPart.provider { case .Data(let data): self.append(data: data, bodyPart: bodyPart, to: form) case .File(let url): self.append(fileURL: url, bodyPart: bodyPart, to: form) case .Stream(let stream, let length): self.append(stream: stream, length: length, bodyPart: bodyPart, to: form) } } if let parameters = target.parameters { parameters .flatMap { (key, value) in multipartQueryComponents(key, value) } .forEach { (key, value) in if let data = value.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { form.appendBodyPart(data: data, name: key) } } } } manager.upload(request, multipartFormData: multipartFormData) { (result: MultipartFormDataEncodingResult) in switch result { case .Success(let alamoRequest, _, _): if cancellable.cancelled { self.cancelCompletion(completion, target: target) return } cancellable.innerCancellable = self.sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion) case .Failure(let error): completion(result: .Failure(Moya.Error.Underlying(error as NSError))) } } return cancellable } private func sendUploadFile(target: Target, request: NSURLRequest, queue: dispatch_queue_t?, file: NSURL, progress: ProgressBlock? = nil, completion: Completion) -> CancellableToken { let alamoRequest = manager.upload(request, file: file) return self.sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion) } private func sendDownloadRequest(target: Target, request: NSURLRequest, queue: dispatch_queue_t?, destination: DownloadDestination, progress: ProgressBlock? = nil, completion: Completion) -> CancellableToken { let alamoRequest = manager.download(request, destination: destination) return self.sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion) } private func sendRequest(target: Target, request: NSURLRequest, queue: dispatch_queue_t?, progress: Moya.ProgressBlock?, completion: Moya.Completion) -> CancellableToken { let alamoRequest = manager.request(request) return sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion) } private func sendAlamofireRequest(alamoRequest: Request, target: Target, queue: dispatch_queue_t?, progress: Moya.ProgressBlock?, completion: Moya.Completion) -> CancellableToken { // Give plugins the chance to alter the outgoing request let plugins = self.plugins plugins.forEach { $0.willSendRequest(alamoRequest, target: target) } // Perform the actual request if let progress = progress { alamoRequest .progress { (bytesWritten, totalBytesWritten, totalBytesExpected) in let sendProgress: () -> () = { progress(progress: ProgressResponse(totalBytes: totalBytesWritten, bytesExpected: totalBytesExpected)) } if let queue = queue { dispatch_async(queue, sendProgress) } else { sendProgress() } } } alamoRequest .response(queue: queue) { (_, response: NSHTTPURLResponse?, data: NSData?, error: NSError?) -> () in let result = convertResponseToResult(response, data: data, error: error) // Inform all plugins about the response plugins.forEach { $0.didReceiveResponse(result, target: target) } completion(result: result) } alamoRequest.resume() return CancellableToken(request: alamoRequest) } } // MARK: - RequestMultipartFormData appending private extension MoyaProvider { private func append(data data: NSData, bodyPart: MultipartFormData, to form: RequestMultipartFormData) { if let mimeType = bodyPart.mimeType { if let fileName = bodyPart.fileName { form.appendBodyPart(data: data, name: bodyPart.name, fileName: fileName, mimeType: mimeType) } else { form.appendBodyPart(data: data, name: bodyPart.name, mimeType: mimeType) } } else { form.appendBodyPart(data: data, name: bodyPart.name) } } private func append(fileURL url: NSURL, bodyPart: MultipartFormData, to form: RequestMultipartFormData) { if let fileName = bodyPart.fileName, mimeType = bodyPart.mimeType { form.appendBodyPart(fileURL: url, name: bodyPart.name, fileName: fileName, mimeType: mimeType) } else { form.appendBodyPart(fileURL: url, name: bodyPart.name) } } private func append(stream stream: NSInputStream, length: UInt64, bodyPart: MultipartFormData, to form: RequestMultipartFormData) { form.appendBodyPart(stream: stream, length: length, name: bodyPart.name, fileName: bodyPart.fileName ?? "", mimeType: bodyPart.mimeType ?? "") } } /// Encode parameters for multipart/form-data private func multipartQueryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += multipartQueryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += multipartQueryComponents("\(key)[]", value) } } else { components.append((key, "\(value)")) } return components }
mit
babumoshai-ankush/UITableView-Self-Sizing
TableViewSelfSizingDemo/ViewController.swift
1
3425
// // ViewController.swift // TableViewSelfSizingDemo // // Created by Ankush Chakraborty on 05/07/17. // Copyright © 2017 Ankush Chakraborty. All rights reserved. // import UIKit struct Data { var title: String? var description: String? init(title: String, description: String) { self.title = title self.description = description } } class ViewController: UIViewController, UITableViewDataSource { @IBOutlet weak var tblView: UITableView! @IBOutlet weak var sliderFont: UISlider! @IBOutlet weak var lblFontSize: UILabel! var arrData: [Data]? var fontSize: Int = UIDevice.current.userInterfaceIdiom == .pad ? 22 : 15 //MARK: - View Controller Life Cycle - override func viewDidLoad() { super.viewDidLoad() tblView.estimatedRowHeight = 64.0 tblView.rowHeight = UITableViewAutomaticDimension sliderFont.value = Float(fontSize) lblFontSize.text = "\(lblFontSize.text!) \(fontSize)" arrData = loadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - UITableViewDataSource Methods Implementation - func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (arrData?.count)! } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier") as! CustomTableViewCell let d = arrData?[indexPath.row] cell.lblTitle.text = d?.title cell.lblDescription.text = d?.description cell.lblTitle.font = UIFont(name: cell.lblTitle.font.fontName, size: CGFloat(fontSize)) cell.lblDescription.font = UIFont(name: cell.lblDescription.font.fontName, size: CGFloat(fontSize)) cell.contentView.backgroundColor = (indexPath.row % 2 == 0 ? UIColor.white : UIColor(red: 242.0/255.0, green: 244.0/255.0, blue: 244.0/255.0, alpha: 1.0)) return cell } //MARK: - Button Actions - @IBAction func sliderFontDidValueChange(_ sender: Any) { let slider = sender as! UISlider if fontSize != (Int(slider.value) / 1) { fontSize = Int(slider.value) / 1 lblFontSize.text = "Font Size \(fontSize)" let cells = self.tblView.visibleCells as! [CustomTableViewCell] for cell in cells { cell.lblTitle.font = UIFont(name: cell.lblTitle.font.fontName, size: CGFloat(fontSize)) cell.lblDescription.font = UIFont(name: cell.lblDescription.font.fontName, size: CGFloat(fontSize)) } tblView.reloadRows(at: tblView.indexPathsForVisibleRows!, with: .fade) } } //MARK: - Internal Methods - func loadData() -> [Data] { var aData = [Data]() let path = Bundle.main.path(forResource: "data", ofType: "plist") if let p = path { if let arr = NSArray(contentsOfFile: p) { for data in arr as! [Dictionary<String, String>] { aData.append(Data(title: data["title"]!, description: data["desc"]!)) } } } return aData } }
gpl-3.0
SASAbus/SASAbus-ios
SASAbus/Controller/About/Credits/CreditsViewController.swift
1
1276
import UIKit class CreditsViewController: UIViewController, UIToolbarDelegate { @IBOutlet weak var infoView: UITextView! @IBOutlet weak var infoTextView: UITextView! @IBOutlet weak var titleLabel: UILabel! init() { super.init(nibName: "CreditsViewController", bundle: nil) title = L10n.Credits.title } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = Theme.darkGrey let version = Bundle.main.versionName titleLabel.text = L10n.Credits.header(version) titleLabel.textColor = Theme.white infoTextView.text = L10n.Credits.copyright infoTextView.textColor = Theme.grey infoView.text = getAboutText() infoView.textColor = Theme.darkGrey infoView.isEditable = false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) Analytics.track("About") } func getAboutText() -> String { let thirdPartyTitle = L10n.Credits.Licenses.title let thirdPartyText = L10n.Credits.Licenses.subtitle return thirdPartyTitle + "\r\n\r\n" + thirdPartyText } }
gpl-3.0
infobip/mobile-messaging-sdk-ios
Classes/Core/PrivacySettings.swift
1
1865
// // PrivacySettings.swift // MobileMessaging // // Created by Andrey Kadochnikov on 01/11/2018. // import Foundation /// The `MMPrivacySettings` class incapsulates privacy settings that affect the SDK behaviour and business logic. @objcMembers public class MMPrivacySettings: NSObject { /// A boolean variable that indicates whether the MobileMessaging SDK will be sending the carrier information to the server. /// /// Default value is `false`. public var carrierInfoSendingDisabled: Bool = false /// A boolean variable that indicates whether the MobileMessaging SDK will be sending the system information such as OS version, device model, application version to the server. /// /// Default value is `false`. public var systemInfoSendingDisabled: Bool = false /// A boolean variable that indicates whether the MobileMessaging SDK will be persisting the application code locally. This feature is a convenience to maintain SDK viability during debugging and possible application code changes. /// /// Default value is `false`. /// - Warning: there might be situation when you want to switch between different Application Codes during development/testing. If you disable the application code persisting (value `true`), the SDK won't detect the application code changes, thus won't cleanup the old application code related data. You should manually invoke `MobileMessaging.cleanUpAndStop()` prior to start otherwise the SDK would not detect the application code change. public var applicationCodePersistingDisabled: Bool = false /// A boolean variable that indicates whether the MobileMessaging SDK will be persisting the user data locally. Persisting user data locally gives you quick access to the data and eliminates a need to implement it yourself. /// /// Default value is `false`. public var userDataPersistingDisabled: Bool = false }
apache-2.0
thiagotmb/BEPiD-Challenges-2016
2016-02-15-TimerWatch/TimerWatch/desafio_3 WatchKit Extension/InterfaceController.swift
2
4174
// // InterfaceController.swift // desafio_3 WatchKit Extension // // Created by Dennis Merli Rodrigues on 2/15/16. // Copyright © 2016 Dennis Merli Rodrigues. All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { //Outlets @IBOutlet var phraseLabel: WKInterfaceLabel! @IBOutlet var saveButton: WKInterfaceButton! @IBOutlet var passButton: WKInterfaceButton! @IBOutlet var phrasesTable: WKInterfaceTable! @IBOutlet var eventDate: WKInterfaceDate! @IBOutlet var eventTimer: WKInterfaceTimer! @IBOutlet var labelDate: WKInterfaceLabel! var currentEvent : Event! override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) // Configure interface objects here. } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() self.getPhrase() self.loadTable() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } //MARK: Table func loadTable() { self.phrasesTable.setNumberOfRows(CatchyPhrasesDAO.sharedInstance.getPhrasesArray().count, withRowType: "phTable") for (index, event) in CatchyPhrasesDAO.sharedInstance.getPhrasesArray().enumerate() { let row = self.phrasesTable.rowControllerAtIndex(index) as! PhrasesRowController row.rowLabel.setText(event.title) self.startATimer(event,label: row.rowLabel) } } //MARK: Acoes @IBAction func passAction() { self.getPhrase() } @IBAction func saveAction() { CatchyPhrasesDAO.sharedInstance.insertPhrase(self.currentEvent) { (status) -> Void in if(status){ //print("frase salva com sucesso!") self.passAction() self.loadTable() } } } //MARK: Carregar conteudo func getPhrase(){ if let value : NSInteger = NSInteger.random(Events.listOfEvents.count)(){ let eventTupla = Events.listOfEvents[value] self.currentEvent = Event(title: eventTupla.0, date: eventTupla.1) self.phraseLabel.setText(currentEvent.title) self.labelDate.setText(currentEvent.date) } } //MARK: Startar um timer func startATimer(event : Event, label: WKInterfaceLabel){ let dateFormat = NSDateFormatter() dateFormat.dateFormat = "HH:mm" dateFormat.timeZone = NSTimeZone(name: "America/Sao_Paulo") let date = dateFormat.dateFromString(event.date) let calendar = NSCalendar(calendarIdentifier:NSCalendarIdentifierGregorian) let componentNow = calendar?.components([.Hour, .Minute], fromDate: NSDate()) let componentEvent = calendar?.components([.Hour, .Minute], fromDate: date!) let hourInterval = (componentEvent!.hour - componentNow!.hour)*60 let minuteInterval = (componentEvent!.minute - componentNow!.minute) let timerInverval = Double( (hourInterval + minuteInterval) * 60) self.performSelector("highlightCurrentEvent:", withObject: label, afterDelay: timerInverval) } //MARK: func highlightCurrentEvent(label : WKInterfaceLabel?){ // let event = timer.userInfo as! Event label?.setTextColor(UIColor.greenColor()) // if let index = CatchyPhrasesDAO.sharedInstance.getPhrasesArray().indexOf(event){ // print(index) // // let tableRow = phrasesTable.rowControllerAtIndex(index) as! PhrasesRowController // tableRow.rowLabel.setTextColor(UIColor.greenColor()) // } } }
mit
RoverPlatform/rover-ios-beta
Sources/Rover.swift
1
310
// // Rover.swift // Rover // // Created by Andrew Clunis on 2019-03-13. // Copyright © 2019 Rover Labs Inc. All rights reserved. // import Foundation import UIKit /// Set your Rover Account Token (API Key) here. public var accountToken: String? { didSet { Analytics.shared.enable() } }
mit
rudkx/swift
test/Interop/Cxx/stdlib/use-std-string.swift
1
636
// RUN: %target-run-simple-swift(-I %S/Inputs -Xfrontend -enable-cxx-interop) // // REQUIRES: executable_test // // Enable this everywhere once we have a solution for modularizing libstdc++: rdar://87654514 // REQUIRES: OS=macosx import StdlibUnittest import StdString import std.string var StdStringTestSuite = TestSuite("StdString") StdStringTestSuite.test("init") { let s = CxxString() expectEqual(s.size(), 0) expectTrue(s.empty()) } StdStringTestSuite.test("push back") { var s = CxxString() s.push_back(42) expectEqual(s.size(), 1) expectFalse(s.empty()) expectEqual(s[0], 42) } runAllTests()
apache-2.0
BalestraPatrick/Tweetometer
TweetometerTests/MenuOptionsTests.swift
2
793
// // MenuOptionsTests.swift // TweetsCounter // // Created by Patrick Balestra on 2/5/16. // Copyright © 2016 Patrick Balestra. All rights reserved. // import XCTest @testable import TweetometerKit class MenuOptionsTests: XCTestCase { func testDataSource() { let options = MenuDataSource().options XCTAssertEqual(options.count, 4) XCTAssertEqual(options[0].title, "Refresh") XCTAssertEqual(options[0].image, "refresh") XCTAssertEqual(options[1].title, "Share") XCTAssertEqual(options[1].image, "share") XCTAssertEqual(options[2].title, "Logout") XCTAssertEqual(options[2].image, "logout") XCTAssertEqual(options[3].title, "Settings") XCTAssertEqual(options[3].image, "settings") } }
mit
tkrajacic/SampleCodeStalker
SampleCodeStalker/MainWindow.swift
1
1024
// // MainWindow.swift // SampleCodeStalker // // Created by Thomas Krajacic on 23.1.2016. // Copyright © 2016 Thomas Krajacic. All rights reserved. // import Cocoa class MainWindow: NSWindow { override init(contentRect: NSRect, styleMask aStyle: NSWindowStyleMask, backing bufferingType: NSBackingStoreType, defer flag: Bool) { super.init(contentRect: contentRect, styleMask: aStyle, backing: bufferingType, defer: flag) self.commonInit() } // required init?(coder: NSCoder) { // super.init(coder: coder) // // self.commonInit() // } func commonInit() { self.titlebarAppearsTransparent = true self.titleVisibility = .hidden self.isMovable = true self.isMovableByWindowBackground = true self.isOpaque = false self.backgroundColor = NSColor.white } override var canBecomeKey: Bool { return true } override var canBecomeMain: Bool { return true } }
mit
DevilWang/BlinkingLabel
Example/BlinkingLabel/ViewController.swift
1
1685
// // ViewController.swift // BlinkingLabel // // Created by DevilWang on 07/19/2017. // Copyright (c) 2017 DevilWang. All rights reserved. // import UIKit import BlinkingLabel class ViewController: UIViewController { var isBlinking = false; let blinkingLabel = BlinkingLabel(frame:CGRect(origin:CGPoint.init(x:10,y:20), size:CGSize.init(width:200,height:30))) override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //setup the blinkingLabel blinkingLabel.text = "I blink" blinkingLabel.font = UIFont.systemFont(ofSize: 20.0) view.addSubview(blinkingLabel) blinkingLabel.startBlinking() isBlinking = true //create a UIButton to toggle the blinking let toggleButton = UIButton.init(frame: CGRect(origin:CGPoint.init(x: 10, y: 60), size:CGSize.init(width: 125, height: 30))) toggleButton.setTitle("Toggle Blinkiing", for: .normal) toggleButton.setTitleColor(UIColor.red, for: .normal) toggleButton.addTarget(self, action: #selector(ViewController.ToggleBlinking), for: .touchUpInside) view.addSubview(toggleButton) } func ToggleBlinking() { if isBlinking { blinkingLabel.stopBlinking() } else{ blinkingLabel.startBlinking() } isBlinking = !isBlinking } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
lkzhao/ElasticTransition
Pods/MotionAnimation/MotionAnimation/NSObject+MotionAnimation.swift
1
4258
// // NSObject+MotionAnimation.swift // DynamicView // // Created by YiLun Zhao on 2016-01-17. // Copyright © 2016 lkzhao. All rights reserved. // import UIKit public extension NSObject{ fileprivate struct m_associatedKeys { static var m_propertyStates = "m_propertyStates_key" } // use NSMutableDictionary since swift dictionary requires a O(n) dynamic cast even when using as! fileprivate var m_propertyStates:NSMutableDictionary{ get { // never use `as?` in this case. it is very expensive let rtn = objc_getAssociatedObject(self, &m_associatedKeys.m_propertyStates) if rtn != nil{ return rtn as! NSMutableDictionary } self.m_propertyStates = NSMutableDictionary() return objc_getAssociatedObject(self, &m_associatedKeys.m_propertyStates) as! NSMutableDictionary } set { objc_setAssociatedObject( self, &m_associatedKeys.m_propertyStates, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) } } fileprivate func getPropertyState(_ key:String) -> MotionAnimationPropertyState{ if m_propertyStates[key] == nil { if let animatable = self as? MotionAnimationAnimatable, let (getter, setter) = animatable.defaultGetterAndSetterForKey(key){ m_propertyStates[key] = MotionAnimationPropertyState(getter: getter, setter: setter) } else { fatalError("\(key) is not animatable, you can define customAnimation property via m_defineCustomProperty or conform to MotionAnimationAnimatable") } } return m_propertyStates[key] as! MotionAnimationPropertyState } // define custom animatable property func m_setValues(_ values:[CGFloat], forCustomProperty key:String){ getPropertyState(key).setValues(values) } func m_defineCustomProperty<T:MotionAnimatableProperty>(_ key:String, initialValues:T, valueUpdateCallback:@escaping (T)->Void){ if m_propertyStates[key] != nil{ return } m_propertyStates[key] = MotionAnimationPropertyState(values: initialValues.CGFloatValues) let _ = getPropertyState(key).addValueUpdateCallback({ values in valueUpdateCallback(T.fromCGFloatValues(values)) }) } func m_defineCustomProperty(_ key:String, getter:@escaping CGFloatValueBlock, setter:@escaping CGFloatValueBlock){ if m_propertyStates[key] != nil{ return } m_propertyStates[key] = MotionAnimationPropertyState(getter: getter, setter: setter) } func m_removeAnimationForKey(_ key:String){ getPropertyState(key).stop() } // add callbacks func m_addValueUpdateCallback<T:MotionAnimatableProperty>(_ key:String, valueUpdateCallback:@escaping (T)->Void) -> MotionAnimationObserverKey{ return getPropertyState(key).addValueUpdateCallback({ values in valueUpdateCallback(T.fromCGFloatValues(values)) }) } func m_addVelocityUpdateCallback<T:MotionAnimatableProperty>(_ key:String, velocityUpdateCallback:@escaping (T)->Void) -> MotionAnimationObserverKey{ return getPropertyState(key).addVelocityUpdateCallback({ values in velocityUpdateCallback(T.fromCGFloatValues(values)) }) } func m_removeCallback(_ key:String, observerKey:MotionAnimationObserverKey){ let _ = getPropertyState(key).removeCallback(observerKey) } func m_isAnimating(_ key:String) -> Bool{ return getPropertyState(key).animation?.playing ?? false } func m_animate<T:MotionAnimatableProperty>( _ key:String, to:T, stiffness:CGFloat? = nil, damping:CGFloat? = nil, threshold:CGFloat? = nil, valueUpdate:((T) -> Void)? = nil, velocityUpdate:((T) -> Void)? = nil, completion:(() -> Void)? = nil) { let valueOb:MotionAnimationValueObserver? = valueUpdate == nil ? nil : { values in valueUpdate!(T.fromCGFloatValues(values)) } let velocityOb:MotionAnimationValueObserver? = velocityUpdate == nil ? nil : { values in velocityUpdate!(T.fromCGFloatValues(values)) } getPropertyState(key) .animate(to.CGFloatValues, stiffness: stiffness, damping: damping, threshold: threshold, valueUpdate:valueOb, velocityUpdate:velocityOb, completion: completion) } }
mit
watson-developer-cloud/ios-sdk
Sources/DiscoveryV1/Models/ListConfigurationsResponse.swift
1
1081
/** * (C) Copyright IBM Corp. 2018, 2020. * * 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 Foundation /** Object containing an array of available configurations. */ public struct ListConfigurationsResponse: Codable, Equatable { /** An array of configurations that are available for the service instance. */ public var configurations: [Configuration]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case configurations = "configurations" } }
apache-2.0
dreamsxin/swift
validation-test/compiler_crashers_fixed/00279-swift-nominaltypedecl-getdeclaredtypeincontext.swift
11
454
// 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 %target-swift-frontend %s -parse struct i<f : f, g: f where g.i == f.i> { b = i) { } let i { f
apache-2.0
emilstahl/swift
validation-test/compiler_crashers_fixed/26676-swift-parser-parsetoken.swift
13
253
// RUN: not %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 let s={{}{{{let a{struct B{class d{a}}
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/26620-swift-tupletype-get.swift
1
432
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class A{class a}}if a{class case,
apache-2.0
lrtitze/Swift-VectorBoolean
Swift VectorBoolean/CanvasView.swift
1
9584
// // CanvasView.swift // Swift VectorBoolean // // Created by Leslie Titze on 2015-07-12. // Copyright (c) 2015 Starside Softworks. All rights reserved. // import UIKit import VectorBoolean enum DisplayMode { case original case union case intersect case subtract case join } class PathItem { fileprivate var path: UIBezierPath fileprivate var color: UIColor init(path:UIBezierPath,color:UIColor) { self.path = path self.color = color } } class CanvasView: UIView { fileprivate var paths: [PathItem] = [] var boundsOfPaths: CGRect = CGRect.zero fileprivate var _unionPath: UIBezierPath? fileprivate var _intersectPath: UIBezierPath? fileprivate var _differencePath: UIBezierPath? fileprivate var _xorPath: UIBezierPath? var displayMode: DisplayMode = .original { didSet(previousMode) { if displayMode != previousMode { setNeedsDisplay() } } } var showPoints: Bool = false var showIntersections: Bool = true let vectorFillColor = UIColor(red: 0.4314, green:0.6784, blue:1.0000, alpha:1.0) let vectorStrokeColor = UIColor(red: 0.0392, green:0.3725, blue:1.0000, alpha:1.0) func clear() { paths = [] _unionPath = nil _intersectPath = nil _differencePath = nil _xorPath = nil } func addPath(_ path: UIBezierPath, withColor color: UIColor) { paths.append(PathItem(path: path, color: color)) // we clear these because they're no longer valid _unionPath = nil _intersectPath = nil _differencePath = nil _xorPath = nil } fileprivate var viewScale = 1.0 fileprivate var decorationLineWidth: CGFloat { return CGFloat(1.5 / viewScale) } func BoxFrame(_ point: CGPoint) -> CGRect { let visualWidth = CGFloat(9 / viewScale) let offset = visualWidth / 2 let left = point.x - offset //let right = point.x + offset //let top = point.y + offset let bottom = point.y - offset return CGRect(x: left, y: bottom, width: visualWidth, height: visualWidth) } override func draw(_ rect: CGRect) { // fill with white before going further let background = UIBezierPath(rect: rect) UIColor.white.setFill() background.fill() // When running my Xcode tests for geometry I want to // prevent the app shell from any geometry so I can // use breakpoints during test development. if paths.count == 0 { return } // calculate a useful scale and offset for drawing these paths // as large as possible in the middle of the display // expand size by 20 to provide a margin let expandedPathBounds = boundsOfPaths.insetBy(dx: -10, dy: -10) let pSz = expandedPathBounds.size let pOr = expandedPathBounds.origin let vSz = self.bounds.size let scaleX = vSz.width / pSz.width let scaleY = vSz.height / pSz.height let scale = min(scaleX, scaleY) viewScale = Double(scale) // obtain context let ctx = UIGraphicsGetCurrentContext() ctx?.saveGState(); if scale == scaleX { let xTranslate = -(pOr.x * scale) let yTranslate = vSz.height - ((vSz.height-pSz.height*scale)/2.0) + (pOr.y*scale) ctx?.translateBy(x: xTranslate, y: yTranslate) ctx?.scaleBy(x: scale, y: -scale); } else { let xTranslate = ((vSz.width - pSz.width*scale)/2.0) - (pOr.x*scale) let yTranslate = vSz.height + (pOr.y * scale) ctx?.translateBy(x: xTranslate, y: yTranslate) ctx?.scaleBy(x: scale, y: -scale); } // Draw shapes now switch displayMode { case .original: drawOriginal() case .union: drawUnion() case .intersect: drawIntersect() case .subtract: drawSubtract() case .join: drawJoin() } // All done ctx?.restoreGState() } fileprivate func drawOriginal() { // Draw shapes now for pathItem in paths { pathItem.color.setFill() pathItem.path.fill() pathItem.path.lineWidth = decorationLineWidth //pathItem.path.stroke() // was not in original } // Draw on the end and control points if showPoints { for pathItem in paths { let bezier = LRTBezierPathWrapper(pathItem.path) for item in bezier.elements { var showMe : UIBezierPath? switch item { case let .move(v): showMe = UIBezierPath(rect: BoxFrame(v)) case let .line(v): // Convert lines to bezier curves as well. // Just set control point to be in the line formed by the end points showMe = UIBezierPath(rect: BoxFrame(v)) case .quadCurve(let to, let cp): showMe = UIBezierPath(rect: BoxFrame(to)) UIColor.black.setStroke() let cp1 = UIBezierPath(ovalIn: BoxFrame(cp)) cp1.lineWidth = decorationLineWidth / 2 cp1.stroke() break case .cubicCurve(let to, let v1, let v2): showMe = UIBezierPath(rect: BoxFrame(to)) UIColor.black.setStroke() let cp1 = UIBezierPath(ovalIn: BoxFrame(v1)) cp1.lineWidth = decorationLineWidth / 2 cp1.stroke() let cp2 = UIBezierPath(ovalIn: BoxFrame(v2)) cp2.lineWidth = decorationLineWidth / 2 cp2.stroke() case .close: break } UIColor.red.setStroke() showMe?.lineWidth = decorationLineWidth showMe?.stroke() } } } // If we have exactly two objects, show where they intersect if showIntersections && paths.count == 2 { let path1 = paths[0].path let path2 = paths[1].path // get both [FBBezierCurve] sets let curves1 = FBBezierCurve.bezierCurvesFromBezierPath(path1) let curves2 = FBBezierCurve.bezierCurvesFromBezierPath(path2) for curve1 in curves1 { for curve2 in curves2 { var unused: FBBezierIntersectRange? curve1.intersectionsWithBezierCurve(curve2, overlapRange: &unused) { (intersection: FBBezierIntersection) -> (setStop: Bool, stopValue:Bool) in if intersection.isTangent { UIColor.purple.setStroke() } else { UIColor.green.setStroke() } let inter = UIBezierPath(ovalIn: self.BoxFrame(intersection.location)) inter.lineWidth = self.decorationLineWidth inter.stroke() return (false, false) } } } } } func drawEndPointsForPath(_ path: UIBezierPath) { let bezier = LRTBezierPathWrapper(path) //var previousPoint = CGPointZero for item in bezier.elements { var showMe : UIBezierPath? switch item { case let .move(v): showMe = UIBezierPath(rect: BoxFrame(v)) case let .line(v): // Convert lines to bezier curves as well. // Just set control point to be in the line formed by the end points showMe = UIBezierPath(rect: BoxFrame(v)) case .quadCurve(let to, let cp): showMe = UIBezierPath(rect: BoxFrame(to)) UIColor.black.setStroke() let cp1 = UIBezierPath(ovalIn: BoxFrame(cp)) cp1.lineWidth = decorationLineWidth / 2 cp1.stroke() break case .cubicCurve(let to, let v1, let v2): showMe = UIBezierPath(rect: BoxFrame(to)) UIColor.black.setStroke() let cp1 = UIBezierPath(ovalIn: BoxFrame(v1)) cp1.lineWidth = decorationLineWidth / 2 cp1.stroke() let cp2 = UIBezierPath(ovalIn: BoxFrame(v2)) cp2.lineWidth = decorationLineWidth / 2 cp2.stroke() case .close: break //previousPoint = CGPointZero } UIColor.red.setStroke() showMe?.lineWidth = decorationLineWidth showMe?.stroke() } } fileprivate func drawUnion() { if _unionPath == nil { if paths.count == 2 { _unionPath = paths[0].path.fb_union(paths[1].path) } } if let path = _unionPath { vectorFillColor.setFill() vectorStrokeColor.setStroke() path.fill() path.lineWidth = decorationLineWidth path.stroke() if showPoints { drawEndPointsForPath(path) } } } fileprivate func drawIntersect() { if _intersectPath == nil { if paths.count == 2 { _intersectPath = paths[0].path.fb_intersect(paths[1].path) } } if let path = _intersectPath { vectorFillColor.setFill() vectorStrokeColor.setStroke() path.fill() path.lineWidth = decorationLineWidth path.stroke() if showPoints { drawEndPointsForPath(path) } } } fileprivate func drawSubtract() { if _differencePath == nil { if paths.count == 2 { _differencePath = paths[0].path.fb_difference(paths[1].path) } } if let path = _differencePath { vectorFillColor.setFill() vectorStrokeColor.setStroke() path.fill() path.lineWidth = decorationLineWidth path.stroke() if showPoints { drawEndPointsForPath(path) } } } fileprivate func drawJoin() { if _xorPath == nil { if paths.count == 2 { _xorPath = paths[0].path.fb_xor(paths[1].path) } } if let path = _xorPath { vectorFillColor.setFill() vectorStrokeColor.setStroke() path.fill() path.lineWidth = decorationLineWidth path.stroke() if showPoints { drawEndPointsForPath(path) } } } }
mit
coreyjv/Emby.ApiClient.Swift
Emby.ApiClient/model/connect/ConnectPassword.swift
2
759
// // ConnectPassword.swift // Emby.ApiClient // // Created by Vedran Ozir on 07/10/15. // Copyright © 2015 Vedran Ozir. All rights reserved. // import Foundation //package mediabrowser.model.connect; extension String { func replace(what: String, with: String) -> String { return self.stringByReplacingOccurrencesOfString(what, withString: with) } } public final class ConnectPassword { public static func PerformPreHashFilter( password: String) -> String { return password.replace("&", with: "&amp;").replace("/", with: "&#092;").replace("!", with: "&#33;").replace("$", with: "&#036;").replace("\"", with: "&quot;").replace("<", with: "&lt;").replace(">", with: "&gt;").replace("'", with: "&#39;"); } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/00772-swift-substitutedtype-get.swift
1
438
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck [1] protocol C { typealias B : B func b
apache-2.0