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
khizkhiz/swift
test/SILGen/coverage_guard.swift
2
725
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -profile-generate -profile-coverage-mapping -emit-sorted-sil -emit-sil -module-name coverage_guard %s | FileCheck %s // CHECK-LABEL: sil_coverage_map {{.*}}// coverage_guard.foo func foo(x : Int32) { // CHECK: [[@LINE]]:21 -> [[END:[0-9]+:2]] : 0 guard x > 1 else { // CHECK: [[@LINE]]:20 -> [[@LINE+2]]:4 : 1 return } // CHECK: [[@LINE]]:4 -> [[END]] : (0 - 1) guard let y : Bool? = x == 3 ? true : nil else { // CHECK: [[@LINE]]:50 -> return } // CHECK: [[@LINE]]:4 -> [[END]] : ((0 - 1) - 2) guard y! else { // CHECK: [[@LINE]]:17 -> return } // CHECK: [[@LINE]]:4 -> [[END]] : (((0 - 1) - 2) - 4) let z = x } foo(1); foo(2); foo(3);
apache-2.0
khizkhiz/swift
test/SourceKit/DocumentStructure/Inputs/main.swift
8
1506
class Foo : Bar { var test : Int @IBOutlet var testOutlet : Int func testMethod() { if test { } } @IBAction func testAction() { } } @IBDesignable class Foo2 {} class Foo3 { @IBInspectable var testInspectable : Int } protocol MyProt {} class OuterCls { class InnerCls1 {} } extension OuterCls { class InnerCls2 {} } class GenCls<T1, T2> {} class TestParamAndCall { func testParams(arg1: Int, name: String) { if (arg1) { testParams(0, name:"testing") } } func testParamAndArg(arg1: Int, param par: Int) { } } // FIXME: Whatever. class TestMarkers { // TODO: Something. func test(arg1: Bool) -> Int { // FIXME: Blah. if (arg1) { // FIXME: Blah. return 0 } return 1 } } func test2(arg1: Bool) { if (arg1) { // http://whatever FIXME: http://whatever/fixme. } } extension Foo { func anExtendedFooFunction() { } } // rdar://19539259 var (sd2: Qtys) { 417(d: nil) } for i in 0...5 {} for var i = 0, i2 = 1; i == 0; ++i {} while var v = o, z = o where v > z {} repeat {} while v == 0 if var v = o, z = o where v > z {} switch v { case 1: break; case 2, 3: break; default: break; } let myArray = [1, 2, 3] let myDict = [1:1, 2:2, 3:3] // rdar://21203366 @objc class ClassObjcAttr : NSObject { @objc func m() {} } @objc(Blah) class ClassObjcAttr2 : NSObject { @objc(Foo) func m() {} }
apache-2.0
acort3255/Emby.ApiClient.Swift
Emby.ApiClient/apiinteraction/sync/server/FileUploadProgress.swift
4
2196
// // FileUploadProgress.swift // Emby.ApiClient // // Created by Vedran Ozir on 03/11/15. // Copyright © 2015 Vedran Ozir. All rights reserved. // import Foundation //package mediabrowser.apiinteraction.sync.server; // //import mediabrowser.apiinteraction.device.IDevice; //import mediabrowser.apiinteraction.sync.SyncProgress; //import mediabrowser.apiinteraction.tasks.CancellationToken; //import mediabrowser.apiinteraction.tasks.Progress; //import mediabrowser.model.devices.LocalFileInfo; // //import java.util.ArrayList; public class FileUploadProgress<T>: ProgressProtocol<T> { // extends Progress<Double> { // private ContentUploader contentUploader; // private IDevice device; // private ArrayList<LocalFileInfo> files; // private int index; // private SyncProgress progress; // private CancellationToken cancellationToken; // private LocalFileInfo file; // // public FileUploadProgress(ContentUploader contentUploader, IDevice device, ArrayList<LocalFileInfo> files, int index, SyncProgress progress, CancellationToken cancellationToken) { // this.contentUploader = contentUploader; // this.device = device; // this.files = files; // this.index = index; // this.progress = progress; // this.cancellationToken = cancellationToken; // // file = files.get(index); // } // // private void GoNext() { // // double numComplete = index+ 1; // numComplete /= files.size(); // progress.report(numComplete * 100); // // contentUploader.UploadNext(files, index + 1, device, cancellationToken, progress); // } // // @Override // public void onComplete() { // // progress.onFileUploaded(file); // GoNext(); // } // // @Override // public void onError(Exception ex) { // // progress.onFileUploadError(file, ex); // GoNext(); // } // // @Override // public void onCancelled() { // // GoNext(); // } // // @Override // public void onProgress(Double value) { // // // TODO: This is progress for the individual file // } }
mit
vicentesuarez/TransitionManager
TransitionManager/TransitionManager/TransitionSource.swift
1
1278
// // TransitionSource.swift // TransitionManager // // Created by Vicente Suarez on 11/9/16. // Copyright © 2016 Vicente Suarez. All rights reserved. // import Foundation /// Defines methods implemented by a presenting view controller to animate presenting and dismissing. @objc public protocol TransitionSource: class { /// Prepare the views to be animated for presentation. @objc optional func setupBeforePresenting() /// Animate the presentation. /// There is no need to call `UIView`'s animate methods. @objc optional func animatePresentation() /// Move views to their final states and perform cleanup after presentation. /// - Parameter completed: `true` if the presentation completed, `false` otherwise. @objc optional func cleanupAfterPresenting(completed: Bool) /// Prepare the views to be animated for dismissal. @objc optional func setupBeforeDismissing() /// Animate the dismissal. /// There is no need to call `UIView`'s animate methods. @objc optional func animateDismissal() /// Move views to their final states and perform cleanup after dismissal. /// - Parameter completed: `true` if the dismissal completed, `false` otherwise. @objc optional func cleanupAfterDismissing(completed: Bool) }
mit
jnwagstaff/PutItOnMyTabBar
Example/Tests/Tests.swift
1
767
import UIKit import XCTest //import PutItOnMyTabBar class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
mit
coryoso/HanekeSwift
Haneke/Format.swift
1
2648
// // Format.swift // Haneke // // Created by Hermes Pique on 8/27/14. // Copyright (c) 2014 Haneke. All rights reserved. // #if os(iOS) import UIKit #else import AppKit #endif public struct Format<T> { public let name: String public let diskCapacity : UInt64 public var transform : ((T) -> (T))? public var convertToData : (T -> NSData)? public init(name: String, diskCapacity : UInt64 = UINT64_MAX, transform: ((T) -> (T))? = nil) { self.name = name self.diskCapacity = diskCapacity self.transform = transform } public func apply(value : T) -> T { var transformed = value if let transform = self.transform { transformed = transform(value) } return transformed } var isIdentity : Bool { return self.transform == nil } } public struct ImageResizer { public enum ScaleMode: String { case Fill = "fill", AspectFit = "aspectfit", AspectFill = "aspectfill", None = "none" } public typealias T = Image public let allowUpscaling : Bool public let size : CGSize public let scaleMode: ScaleMode public let compressionQuality : Float public init(size: CGSize = CGSizeZero, scaleMode: ScaleMode = .None, allowUpscaling: Bool = true, compressionQuality: Float = 1.0) { self.size = size self.scaleMode = scaleMode self.allowUpscaling = allowUpscaling self.compressionQuality = compressionQuality } public func resizeImage(image: Image) -> Image { var resizeToSize: CGSize switch self.scaleMode { case .Fill: resizeToSize = self.size case .AspectFit: resizeToSize = image.size.hnk_aspectFitSize(self.size) case .AspectFill: resizeToSize = image.size.hnk_aspectFillSize(self.size) case .None: return image } assert(self.size.width > 0 && self.size.height > 0, "Expected non-zero size. Use ScaleMode.None to avoid resizing.") // If does not allow to scale up the image if (!self.allowUpscaling) { if (resizeToSize.width > image.size.width || resizeToSize.height > image.size.height) { return image } } // Avoid unnecessary computations if (resizeToSize.width == image.size.width && resizeToSize.height == image.size.height) { return image } let resizedImage = image.hnk_imageByScalingToSize(resizeToSize) return resizedImage } }
apache-2.0
Raizlabs/ios-template
PRODUCTNAME/app/Services/API/APISerialization.swift
1
2006
/// // APISerialization.swift // PRODUCTNAME // // Created by LEADDEVELOPER on TODAYSDATE. // Copyright © THISYEAR ORGANIZATION. All rights reserved. // import Alamofire import Swiftilities private func ResponseSerializer<T>(_ serializer: @escaping (Data) throws -> T) -> DataResponseSerializer<T> { return DataResponseSerializer { _, _, data, error in guard let data = data else { return .failure(error ?? APIError.noData) } if let error = error { do { let knownError = try JSONDecoder.default.decode(PRODUCTNAMEError.self, from: data) return .failure(knownError) } catch let decodeError { let string = String(data: data, encoding: .utf8) Log.info("Could not decode error, falling back to generic error: \(decodeError) \(String(describing: string))") } if let errorDictionary = (try? JSONSerialization.jsonObject(with: data, options: [.allowFragments])) as? [String: Any] { return .failure(PRODUCTNAMEError.unknown(errorDictionary)) } return .failure(error) } do { return .success(try serializer(data)) } catch let decodingError { return .failure(decodingError) } } } func APIObjectResponseSerializer<Endpoint: APIEndpoint>(_ endpoint: Endpoint) -> DataResponseSerializer<Void> where Endpoint.ResponseType == Payload.Empty { return ResponseSerializer { data in endpoint.log(data) } } /// Response serializer to import JSON Object using JSONDecoder and return an object func APIObjectResponseSerializer<Endpoint: APIEndpoint>(_ endpoint: Endpoint) -> DataResponseSerializer<Endpoint.ResponseType> where Endpoint.ResponseType: Decodable { return ResponseSerializer { data in endpoint.log(data) let decoder = JSONDecoder.default return try decoder.decode(Endpoint.ResponseType.self, from: data) } }
mit
kyouko-taiga/anzen
Sources/AST/ASTVisitor.swift
1
1622
public protocol ASTVisitor { func visit(_ node: ModuleDecl) throws func visit(_ node: Block) throws // MARK: Declarations func visit(_ node: PropDecl) throws func visit(_ node: FunDecl) throws func visit(_ node: ParamDecl) throws func visit(_ node: StructDecl) throws func visit(_ node: InterfaceDecl) throws // MARK: Type signatures func visit(_ node: QualTypeSign) throws func visit(_ node: TypeIdent) throws func visit(_ node: FunSign) throws func visit(_ node: ParamSign) throws // MARK: Statements func visit(_ node: Directive) throws func visit(_ node: WhileLoop) throws func visit(_ node: BindingStmt) throws func visit(_ node: ReturnStmt) throws // MARK: Expressions func visit(_ node: NullRef) throws func visit(_ node: IfExpr) throws func visit(_ node: LambdaExpr) throws func visit(_ node: CastExpr) throws func visit(_ node: BinExpr) throws func visit(_ node: UnExpr) throws func visit(_ node: CallExpr) throws func visit(_ node: CallArg) throws func visit(_ node: SubscriptExpr) throws func visit(_ node: SelectExpr) throws func visit(_ node: Ident) throws func visit(_ node: ArrayLiteral) throws func visit(_ node: SetLiteral) throws func visit(_ node: MapLiteral) throws func visit(_ node: Literal<Bool>) throws func visit(_ node: Literal<Int>) throws func visit(_ node: Literal<Double>) throws func visit(_ node: Literal<String>) throws }
apache-2.0
the-blue-alliance/the-blue-alliance-ios
the-blue-alliance-ios/View Elements/Teams/TeamHeaderView.swift
1
6857
import Foundation import UIKit class TeamHeaderView: UIView { var viewModel: TeamHeaderViewModel { didSet { configureView() } } private var baseAvatarColor: UIColor { // Some teams look better in Red, some teams look better in Blue. // One team looks better in Black. if viewModel.teamNumber == 148 { return UIColor.black } let redTeams = [1114, 2337] if redTeams.contains(viewModel.teamNumber) { return UIColor.avatarRed } return UIColor.avatarBlue } private lazy var rootStackView: UIStackView = { let stackView = UIStackView(arrangedSubviews: [avatarImageView, teamInfoStackView, yearStackView]) stackView.axis = .horizontal stackView.spacing = 8 stackView.alignment = .center return stackView }() private lazy var avatarImageView = AvatarImageView(baseColor: baseAvatarColor) private lazy var teamNumberLabel: UILabel = { let label = TeamHeaderView.teamHeaderLabel() let font = UIFont.preferredFont(forTextStyle: .title1) let fontMetrics = UIFontMetrics(forTextStyle: .title1) label.font = fontMetrics.scaledFont(for: UIFont.systemFont(ofSize: font.pointSize, weight: .semibold)) label.adjustsFontSizeToFitWidth = true return label }() private lazy var teamNameLabel: UILabel = { let label = TeamHeaderView.teamHeaderLabel() label.font = UIFont.preferredFont(forTextStyle: .title3) label.numberOfLines = 0 return label }() private lazy var teamInfoStackView: UIStackView = { let stackView = UIStackView(arrangedSubviews: [teamNumberLabel, teamNameLabel]) stackView.axis = .vertical return stackView }() let yearButton = YearButton() private lazy var yearStackView: UIStackView = { let spacerView = UIView() spacerView.setContentHuggingPriority(.defaultLow, for: .vertical) let stackView = UIStackView(arrangedSubviews: [spacerView, yearButton]) stackView.axis = .vertical yearButton.autoSetDimension(.width, toSize: 60, relation: .greaterThanOrEqual) yearButton.autoSetDimension(.height, toSize: 30, relation: .greaterThanOrEqual) yearButton.setContentCompressionResistancePriority(.required, for: .horizontal) return stackView }() init(_ viewModel: TeamHeaderViewModel) { self.viewModel = viewModel super.init(frame: .zero) backgroundColor = UIColor.navigationBarTintColor configureView() addSubview(rootStackView) rootStackView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16), excludingEdge: .top) rootStackView.autoSetDimension(.height, toSize: 55, relation: .greaterThanOrEqual) let topConstraint = rootStackView.autoPinEdge(toSuperviewEdge: .top, withInset: 16) // Allow our top spacing constraint to be unsatisfied - this will allow the view to glide under the navigation bar while scrolling topConstraint.priority = .defaultLow yearStackView.autoMatch(.height, to: .height, of: rootStackView) avatarImageView.autoSetDimensions(to: .init(width: 55, height: 55)) avatarImageView.setContentCompressionResistancePriority(.required, for: .vertical) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Private Methods private func configureView() { avatarImageView.image = viewModel.avatar avatarImageView.isHidden = viewModel.avatar == nil teamNumberLabel.text = viewModel.teamNumberNickname teamNameLabel.text = viewModel.nickname teamNumberLabel.isHidden = viewModel.nickname == nil let yearString: String = { if let year = viewModel.year { return String(year) } else { return "----" } }() yearButton.setTitle(yearString, for: .normal) } static func teamHeaderLabel() -> UILabel { let label = UILabel() label.adjustsFontForContentSizeCategory = true label.textColor = UIColor.white return label } func changeAvatarBorder() { avatarImageView.avatarTapped() } } private class AvatarImageView: UIView { private let imageView: UIImageView = { let imageView = UIImageView() imageView.backgroundColor = UIColor.clear return imageView }() var image: UIImage? { get { return imageView.image } set { imageView.image = newValue } } init(baseColor: UIColor) { super.init(frame: .zero) backgroundColor = baseColor isUserInteractionEnabled = true addSubview(imageView) imageView.autoPinEdgesToSuperviewEdges(with: .init(top: 5, left: 5, bottom: 5, right: 5)) layer.borderColor = baseColor.cgColor layer.borderWidth = 5 layer.masksToBounds = true layer.cornerRadius = 5 let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(avatarTapped)) addGestureRecognizer(tapGestureRecognizer) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UI Methods @objc func avatarTapped() { let newColor = backgroundColor == .avatarBlue ? UIColor.avatarRed : UIColor.avatarBlue backgroundColor = newColor layer.borderColor = newColor.cgColor } } class YearButton: UIButton { override open var isHighlighted: Bool { didSet { UIView.animate(withDuration: 0.125) { self.backgroundColor = self.isHighlighted ? UIColor.lightGray : UIColor.white } } } init() { super.init(frame: .zero) tintColor = UIColor.navigationBarTintColor backgroundColor = UIColor.white setTitle("----", for: .normal) setTitleColor(UIColor.navigationBarTintColor, for: .normal) setImage(UIImage(systemName: "chevron.down"), for: .normal) setContentHuggingPriority(.defaultHigh, for: .horizontal) titleLabel?.font = UIFont.preferredFont(forTextStyle: .callout, compatibleWith: nil).bold() layer.masksToBounds = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() contentEdgeInsets = UIEdgeInsets(top: 0, left: frame.size.height * 0.5, bottom: 0, right: frame.size.height * 0.5) layer.cornerRadius = frame.size.height * 0.5 } }
mit
YoungGary/30daysSwiftDemo
day22/day22/day22/RunViewController.swift
1
879
// // RunViewController.swift // 3DTouchQuickAction // // Created by Allen on 16/1/29. // Copyright © 2016年 Allen. All rights reserved. // import UIKit class RunViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() UIApplication.sharedApplication().statusBarHidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
mattiaberretti/MBControlli
MBControlli/Classes/BaseFotoViewController.swift
1
4996
// // BaseFotoViewController.swift // MBControlli // // Created by Mattia Berretti on 23/12/16. // Copyright © 2016 Mattia Berretti. All rights reserved. // import UIKit @IBDesignable open class BaseFotoViewController: BaseViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, AnteprimaFotoViewControllerDelegate { @IBOutlet public weak var immagine : UIImageView? @IBOutlet public weak var btnFoto : UIBarButtonItem? @IBInspectable open var mostraAnteprima : Bool = true public var fotoModificata = false open override func viewDidLoad() { super.viewDidLoad() if let immagine = self.immagine { immagine.isUserInteractionEnabled = true immagine.layer.borderWidth = 1 immagine.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.toccoFoto(_:)))) if let bottone = self.btnFoto { bottone.target = self bottone.action = #selector(self.toccoBottone(_:)) } } } func toccoFoto(_ sender : UITapGestureRecognizer){ if self.mostraAnteprima == true && self.immagine?.image != nil { let controller = AnteprimaFotoViewController() controller.immagine = self.immagine?.image controller.delegate = self controller.anteprimaFoto(controller: self) } else{ self.messaggioSelezione(bottone: false) } } func toccoBottone(_ sender : UIBarButtonItem){ self.messaggioSelezione(bottone: true) } func messaggioSelezione(bottone : Bool){ let msg = UIAlertController(title: "Seleziona immagine", message: "", preferredStyle: .actionSheet) msg.modalPresentationStyle = .popover if bottone { msg.popoverPresentationController?.barButtonItem = self.btnFoto } else{ msg.popoverPresentationController?.sourceRect = self.immagine!.frame msg.popoverPresentationController?.sourceView = self.immagine } msg.addAction(UIAlertAction(title: "Fotocamera", style: .default, handler: { (a) in self.selezionaImmagine(bottone: bottone, sorgente: .camera) })) msg.addAction(UIAlertAction(title: "Libreria immagini", style: .default, handler: { (a) in self.selezionaImmagine(bottone: bottone, sorgente: .photoLibrary) })) if self.immagine?.image != nil { msg.addAction(UIAlertAction(title: "Elimina foto", style: .destructive, handler: { (a) in self.immagine?.image = nil })) } msg.addAction(UIAlertAction(title: "Annulla", style: .cancel, handler: nil)) self.present(msg, animated: true, completion: nil) } func selezionaImmagine(bottone : Bool, sorgente : UIImagePickerControllerSourceType){ let picker = UIImagePickerController() picker.delegate = self picker.sourceType = sorgente if sorgente != .camera { picker.modalPresentationStyle = .popover if bottone { picker.popoverPresentationController?.barButtonItem = self.btnFoto } else{ picker.popoverPresentationController?.sourceView = self.immagine picker.popoverPresentationController?.sourceRect = self.immagine!.frame } } else{ picker.cameraCaptureMode = .photo } self.present(picker, animated: true, completion: nil) } //======================================= //image picher //======================================= open func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let immagine = (info[UIImagePickerControllerEditedImage] as? UIImage) ?? info[UIImagePickerControllerOriginalImage] as! UIImage picker.dismiss(animated: true) { self.immagine?.image = immagine self.fotoModificata = true } } //======================================= //AnteprimaFotoViewControllerDelegate //======================================= func immagineEliminata(controller: UIViewController) { controller.dismiss(animated: true) { self.immagine?.image = nil } } func fotoModificata(immagine: UIImage, controller: UIViewController) { controller.dismiss(animated: true) { self.immagine?.image = immagine self.fotoModificata = true } } public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
antonio081014/LeeCode-CodeBase
Swift/split-linked-list-in-parts.swift
2
2955
/** * https://leetcode.com/problems/split-linked-list-in-parts/ * * */ // Date: Wed Sep 29 19:25:43 PDT 2021 /** * Definition for singly-linked list. * public class ListNode { * public var val: Int * public var next: ListNode? * public init() { self.val = 0; self.next = nil; } * public init(_ val: Int) { self.val = val; self.next = nil; } * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } * } */ class Solution { func splitListToParts(_ head: ListNode?, _ k: Int) -> [ListNode?] { var count = 0 var node = head while node != nil { count += 1 node = node?.next } let size = count / k var pre = size == 0 ? 0 : count - k * size var result = [ListNode?]() node = head count = 0 var fooNode: ListNode? = ListNode() var cNode: ListNode? = fooNode var flag = false while node != nil { count += 1 cNode?.next = node if count < size { cNode = cNode?.next node = node?.next } else { if !flag, result.count < pre { cNode = cNode?.next node = node?.next flag = true } else { flag = false count = 0 result.append(fooNode?.next) fooNode = ListNode() cNode = fooNode let next = node?.next node?.next = nil node = next } } } if count > 0 { result.append(fooNode?.next) } if result.count < k { for _ in result.count ..< k { result.append(nil) } } return result } }/** * https://leetcode.com/problems/split-linked-list-in-parts/ * * */ // Date: Mon Oct 4 19:13:19 PDT 2021 class Solution { func canPartitionKSubsets(_ nums: [Int], _ k: Int) -> Bool { let sum = nums.reduce(0) { $0 + $1 } guard sum % k == 0 else { return false } let target = sum / k func dfs(_ candidates: inout [Bool], _ start: Int, _ cSum: Int, _ group: Int) -> Bool { if group == 1 { return true } if cSum == target { return dfs(&candidates, 0, 0, group - 1) } for index in start ..< nums.count { if candidates[index] == true || cSum + nums[index] > target { continue } candidates[index] = true if dfs(&candidates, index + 1, cSum + nums[index], group) { return true } candidates[index] = false } return false } var cand = Array(repeating: false, count: nums.count) return dfs(&cand, 0, 0, k) } }
mit
narner/AudioKit
AudioKit/Common/Nodes/Effects/Distortion/Decimator/AKDecimator.swift
1
3243
// // AKDecimator.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // /// AudioKit version of Apple's Decimator from the Distortion Audio Unit /// open class AKDecimator: AKNode, AKToggleable, AUEffect, AKInput { // MARK: - Properties /// Four letter unique description of the node public static let ComponentDescription = AudioComponentDescription(appleEffect: kAudioUnitSubType_Distortion) private var au: AUWrapper private var lastKnownMix: Double = 1 /// Decimation (Normalized Value) ranges from 0 to 1 (Default: 0.5) @objc open dynamic var decimation: Double = 0.5 { didSet { decimation = (0...1).clamp(decimation) au[kDistortionParam_Decimation] = decimation * 100 } } /// Rounding (Normalized Value) ranges from 0 to 1 (Default: 0) @objc open dynamic var rounding: Double = 0 { didSet { rounding = (0...1).clamp(rounding) au[kDistortionParam_Rounding] = rounding * 100 } } /// Mix (Normalized Value) ranges from 0 to 1 (Default: 1) @objc open dynamic var mix: Double = 1 { didSet { mix = (0...1).clamp(mix) au[kDistortionParam_FinalMix] = mix * 100 } } /// Tells whether the node is processing (ie. started, playing, or active) @objc open dynamic var isStarted = true // MARK: - Initialization /// Initialize the decimator node /// /// - Parameters: /// - input: Input node to process /// - decimation: Decimation (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// - rounding: Rounding (Normalized Value) ranges from 0 to 1 (Default: 0) /// - mix: Mix (Normalized Value) ranges from 0 to 1 (Default: 1) /// @objc public init( _ input: AKNode? = nil, decimation: Double = 0.5, rounding: Double = 0, mix: Double = 1) { self.decimation = decimation self.rounding = rounding self.mix = mix let effect = _Self.effect au = AUWrapper(effect) super.init(avAudioNode: effect, attach: true) input?.connect(to: self) // Since this is the Decimator, mix it to 100% and use the final mix as the mix parameter au[kDistortionParam_Decimation] = decimation * 100 au[kDistortionParam_Rounding] = rounding * 100 au[kDistortionParam_FinalMix] = mix * 100 au[kDistortionParam_PolynomialMix] = 0 au[kDistortionParam_RingModMix] = 0 au[kDistortionParam_DelayMix] = 0 } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing @objc open func start() { if isStopped { mix = lastKnownMix isStarted = true } } /// Function to stop or bypass the node, both are equivalent @objc open func stop() { if isPlaying { lastKnownMix = mix mix = 0 isStarted = false } } /// Disconnect the node override open func disconnect() { stop() AudioKit.detach(nodes: [self.avAudioNode]) } }
mit
metova/MetovaBase
MetovaBase/BaseViewController/BaseViewControllerKeyboard.swift
1
3366
// // BaseViewControllerKeyboard.swift // MetovaBase // // Created by Nick Griffith on 4/22/16. // Copyright (c) 2016 Metova Inc. // // 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. // import UIKit extension BaseViewController: KeyboardNotificationDelegate { func addKeyboardNotifications() { register(selector: #selector(KeyboardNotificationDelegate.keyboardWillShow(notification:)), forNotification: UIResponder.keyboardWillShowNotification) register(selector: #selector(KeyboardNotificationDelegate.keyboardDidShow(notification:)), forNotification: UIResponder.keyboardDidShowNotification) register(selector: #selector(KeyboardNotificationDelegate.keyboardWillChangeFrame(notification:)), forNotification: UIResponder.keyboardWillChangeFrameNotification) register(selector: #selector(KeyboardNotificationDelegate.keyboardDidChangeFrame(notification:)), forNotification: UIResponder.keyboardDidChangeFrameNotification) register(selector: #selector(KeyboardNotificationDelegate.keyboardWillHide(notification:)), forNotification: UIResponder.keyboardWillHideNotification) register(selector: #selector(KeyboardNotificationDelegate.keyboardDidHide(notification:)), forNotification: UIResponder.keyboardDidHideNotification) } func removeKeyboardNotifications() { NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillChangeFrameNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidChangeFrameNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidHideNotification, object: nil) } private func register(selector: Selector, forNotification name: Notification.Name) { if responds(to: selector) { NotificationCenter.default.addObserver(self, selector: selector, name: name, object: nil) } } }
mit
pantuspavel/PPEventRegistryAPI
PPEventRegistryAPI/PPEventRegistryAPITests/Classes/Transport/PPTransportMock.swift
1
984
// // PPTransportMock.swift // PPEventRegistryAPI // // Created by Pavel Pantus on 7/16/16. // Copyright © 2016 Pavel Pantus. All rights reserved. // import Foundation @testable import PPEventRegistryAPI class PPTransportMock { var mockSuccess = true var rejectInvocation = false var delay = 0.3 } // MARK: PPTransportProtocol extension PPTransportMock: PPTransportProtocol { internal func postRequest(controller: PPController, method: PPHttpMethod, parameters: [String: Any], completionHandler: @escaping (_ result: PPResult<[String: Any], PPError>) -> ()) { if (rejectInvocation) { fatalError("Unexpected method was invoked") } DispatchQueue.main.asyncAfter(deadline: .now() + delay) { if self.mockSuccess { completionHandler(.Success(["Result": "Success"])) } else { completionHandler(.Failure(.Error("Mocked Transport Failure"))) } } } }
mit
duycao2506/SASCoffeeIOS
SAS Coffee/Services/Style.swift
1
743
// // Style.swift // SAS Coffee // // Created by Duy Cao on 9/1/17. // Copyright © 2017 Duy Cao. All rights reserved. // import UIKit class Style: NSObject { static let colorPrimary : UIColor = .init(rgb: 0x00b9e6) static let colorPrimaryDark : UIColor = .init(rgb: 0x2f82c3) static let colorSecondary : UIColor = .init(rgb: 0xF5A623) static let colorWhite : UIColor = .init(rgb: 0xffffff) static let colorWhiteTrans : UIColor = .init(argb: 0xffffff) static let colorWhiteHard : UIColor = .init(rgb: 0xeeeeee) static let colorYellow : UIColor = .init(rgb: 0xF9DC15) static let colorPrimaryLight : UIColor = .init(rgb: 0xCBF0F9) static let colorSupplementary1 : UIColor = .init(rgb: 0x556080) }
gpl-3.0
GenerallyHelpfulSoftware/Scalar2D
Colour/Sources/ICCColourParser.swift
1
3740
// // ICCColourParser.swift // Scalar2D // // Created by Glenn Howes on 10/12/16. // Copyright © 2016-2019 Generally Helpful Software. All rights reserved. // // // // // The MIT License (MIT) // Copyright (c) 2016-2019 Generally Helpful Software // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // import Foundation public struct ICCColourParser : ColourParser { public func deserializeString(source: String, colorContext: ColorContext? = nil) throws -> Colour? { guard source.hasPrefix("icc-color") else { return nil } let leftParenComponents = source.components(separatedBy: "(") guard leftParenComponents.count == 2 else { throw ColourParsingError.unexpectedCharacter(source) } guard leftParenComponents.first!.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) == "icc-color" else { // something between the icc-color prefix and the leading ( throw ColourParsingError.unexpectedCharacter(source) } let rightSide = leftParenComponents.last! guard rightSide.hasSuffix(")") else { throw ColourParsingError.incomplete(source) } let rightParenComponents = rightSide.components(separatedBy: ")") // source is assumed to be trimmed so it should terminate on the ) guard rightParenComponents.count == 2 && rightParenComponents.last!.isEmpty else { throw ColourParsingError.unexpectedCharacter(source) } let payload = rightParenComponents.first! var stringComponents = payload.components(separatedBy: ",") guard stringComponents.count >= 2 else {// need at least a name and and at least 1 colour component throw ColourParsingError.incomplete(source) } let profileName = stringComponents.removeFirst().trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) let doubleComponents = stringComponents.map{Double($0.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines))} let noNullDoubleComponents = doubleComponents.compactMap{$0} guard noNullDoubleComponents.count == doubleComponents.count else { // one of the components was not convertable to a Double, so bad format throw ColourParsingError.unexpectedCharacter(source) } let colourFloatComponents = noNullDoubleComponents.map{ColourFloat($0)} return Colour.icc(profileName: profileName, components: colourFloatComponents, source: source) } public init() { } }
mit
larryhou/swift
URLoadingSystem/URLoadingSystemTests/URLoadingSystemTests.swift
1
896
// // URLoadingSystemTests.swift // URLoadingSystemTests // // Created by larryhou on 3/23/15. // Copyright (c) 2015 larryhou. All rights reserved. // import UIKit import XCTest class URLoadingSystemTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
xingfukun/IQKeyboardManager
IQKeyboardManagerSwift/Categories/IQNSArray+Sort.swift
18
2396
// // IQNSArray+Sort.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-15 Iftekhar Qurashi. // // 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 UIKit /** UIView.subviews sorting category. */ internal extension Array { ///-------------- /// MARK: Sorting ///-------------- /** Returns the array by sorting the UIView's by their tag property. */ internal func sortedArrayByTag() -> [T] { return sorted({ (obj1 : T, obj2 : T) -> Bool in let view1 = obj1 as! UIView let view2 = obj2 as! UIView return (view1.tag < view2.tag) }) } /** Returns the array by sorting the UIView's by their tag property. */ internal func sortedArrayByPosition() -> [T] { return sorted({ (obj1 : T, obj2 : T) -> Bool in let view1 = obj1 as! UIView let view2 = obj2 as! UIView let x1 = CGRectGetMinX(view1.frame) let y1 = CGRectGetMinY(view1.frame) let x2 = CGRectGetMinX(view2.frame) let y2 = CGRectGetMinY(view2.frame) if y1 != y2 { return y1 < y2 } else { return x1 < x2 } }) } }
mit
mohamede1945/quran-ios
Quran/UserDefaults+Keys.swift
1
1146
// // UserDefaults+Keys.swift // Quran // // Created by Mohamed Afifi on 5/2/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // 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. // extension PersistenceKeyBase { static let lastSelectedQariId = PersistenceKey<Int>(key: "LastSelectedQariId", defaultValue: 9) static let lastViewedPage = PersistenceKey<Int?>(key: "LastViewedPage", defaultValue: nil) static let showQuranTranslationView = PersistenceKey<Bool>(key: "showQuranTranslationView", defaultValue: false) static let selectedTranslations = PersistenceKey<[Int]>(key: "selectedTranslations", defaultValue: []) }
gpl-3.0
omondigeno/ActionablePushMessages
PushedActionableMessages/Utils.swift
1
896
// // Utils.swift // PushedActionableMessages // // Created by Samuel Geno on 10/04/2016. // Copyright © 2016 Geno. All rights reserved. // import Foundation class Utils { class func getString (name: String) -> String { return NSLocalizedString(name, comment: "") } class func saveData(name: String, value: String) { let defaults = NSUserDefaults.standardUserDefaults() defaults.setValue(value, forKey: name) } class func getData(name: String) -> String? { let defaults = NSUserDefaults.standardUserDefaults() return defaults.valueForKey(name) as? String } class func getUUID() -> String? { if let UUID = getData("UUID") { return UUID } else { let UUID = NSUUID().UUIDString saveData("UUID", value: UUID) return UUID } } }
apache-2.0
SwiftyVK/SwiftyVK
Library/Tests/UploadTests.swift
2
14391
import Foundation import XCTest import CoreLocation @testable import SwiftyVK final class UploadTests: XCTestCase { override func tearDown() { VKStack.removeAllMocks() } func test_photo_toWall() { // Given let exp = expectation(description: "") let media = Media.image(data: Data(), type: .jpg) var response: JSON? VKStack.mock( VK.API.Photos.getWallUploadServer([.userId: "1"]), fileName: "upload.getServer.success" ) VKStack.mock( .upload(url: "https://test.vk.com", media: [media], partType: .photo), fileName: "upload.photos.toWall.success" ) VKStack.mock( VK.API.Photos.saveWallPhoto([.userId: "1", .hash: "testHash", .server: "999", .photo: "testPhoto"]), fileName: "upload.save.success" ) // When VK.API.Upload.Photo.toWall(media, to: .user(id: "1")) .onSuccess { response = try? JSON(data: $0) exp.fulfill() } .send() // Then waitForExpectations(timeout: 5) XCTAssertTrue(response?.bool("result") ?? false) } func test_photo_toMain() { // Given let exp = expectation(description: "") let media = Media.image(data: Data(), type: .jpg) var response: JSON? VKStack.mock( VK.API.Photos.getOwnerPhotoUploadServer([.ownerId: "1"]), fileName: "upload.getServer.success" ) VKStack.mock( .upload(url: "https://test.vk.com&_square_crop=10,20,30", media: [media], partType: .photo), fileName: "upload.photos.ownerPhoto.success" ) VKStack.mock( VK.API.Photos.saveOwnerPhoto([.server: "999", .photo: "testPhoto", .hash: "testHash"]), fileName: "upload.save.success" ) // When VK.API.Upload.Photo.toMain(media, to: .user(id: "1"), crop: (x: "10", y: "20", w: "30")) .onSuccess { response = try? JSON(data: $0) exp.fulfill() } .send() // Then waitForExpectations(timeout: 5) XCTAssertTrue(response?.bool("result") ?? false) } func test_photo_toAlbum() { // Given let exp = expectation(description: "") let media = Media.image(data: Data(), type: .jpg) var response: JSON? VKStack.mock( VK.API.Photos.getUploadServer([.albumId: "testAlbumId", .groupId: "1"]), fileName: "upload.getServer.success" ) VKStack.mock( .upload( url: "https://test.vk.com", media: [media], partType: .indexedFile ), fileName: "upload.photos.toAlbum.success" ) VKStack.mock( VK.API.Photos.save([ .groupId: "1", .albumId: "testAlbumId", .server: "999", .photosList: "testPhotosList", .hash: "testHash", .aid: "888", .latitude: "1.0", .longitude: "2.0", .caption: "testCaption" ]), fileName: "upload.save.success" ) // When VK.API.Upload.Photo.toAlbum( [media], to: .group(id: "1"), albumId: "testAlbumId", caption: "testCaption", location: CLLocationCoordinate2D(latitude: 1, longitude: 2) ) .onSuccess { response = try? JSON(data: $0) exp.fulfill() } .send() // Then waitForExpectations(timeout: 5) XCTAssertTrue(response?.bool("result") ?? false) } func test_photo_toMessage() { // Given let exp = expectation(description: "") let media = Media.image(data: Data(), type: .jpg) var response: JSON? VKStack.mock( VK.API.Photos.getMessagesUploadServer([.peerId: "1"]), fileName: "upload.getServer.success" ) VKStack.mock( .upload(url: "https://test.vk.com", media: [media], partType: .photo), fileName: "upload.photos.toWall.success" ) VKStack.mock( VK.API.Photos.saveMessagesPhoto([.hash: "testHash", .server: "999", .photo: "testPhoto"]), fileName: "upload.save.success" ) // When VK.API.Upload.Photo.toMessage(media, peerId: "1") .onSuccess { response = try? JSON(data: $0) exp.fulfill() } .send() // Then waitForExpectations(timeout: 5) XCTAssertTrue(response?.bool("result") ?? false) } func test_photo_toChatMain() { // Given let exp = expectation(description: "") let media = Media.image(data: Data(), type: .jpg) var response: JSON? VKStack.mock( VK.API.Photos.getChatUploadServer([ .chatId: "1", .cropX: "10", .cropY: "20", .cropWidth: "30" ]), fileName: "upload.getServer.success" ) VKStack.mock( .upload(url: "https://test.vk.com", media: [media], partType: .file), fileName: "upload.photos.toChatMain.success" ) VKStack.mock( VK.API.Messages.setChatPhoto([.file: "testResponse"]), fileName: "upload.save.success" ) // When VK.API.Upload.Photo.toChatMain(media, to: 1, crop: (x: "10", y: "20", w: "30")) .onSuccess { response = try? JSON(data: $0) exp.fulfill() } .send() // Then waitForExpectations(timeout: 5) XCTAssertTrue(response?.bool("result") ?? false) } func test_photo_toMarket() { // Given let exp = expectation(description: "") let media = Media.image(data: Data(), type: .jpg) var response: JSON? VKStack.mock( VK.API.Photos.getMarketUploadServer([.groupId: "1"]), fileName: "upload.getServer.success" ) VKStack.mock( .upload(url: "https://test.vk.com", media: [media], partType: .file), fileName: "upload.photos.toMarket.success" ) VKStack.mock( VK.API.Photos.saveMarketPhoto([ .groupId: "1", .photo: "testPhoto", .server: "999", .hash: "testHash", .cropData: "testCropData", .cropHash: "testCropHash", .mainPhoto: "1", .cropX: "10", .cropY: "20", .cropWidth: "30" ]), fileName: "upload.save.success" ) // When VK.API.Upload.Photo.toMarket(media, mainPhotoCrop: (x: "10", y: "20", w: "30"), groupId: "1") .onSuccess { response = try? JSON(data: $0) exp.fulfill() } .send() // Then waitForExpectations(timeout: 5) XCTAssertTrue(response?.bool("result") ?? false) } func test_photo_toMarketAlbum() { // Given let exp = expectation(description: "") let media = Media.image(data: Data(), type: .jpg) var response: JSON? VKStack.mock( VK.API.Photos.getMarketAlbumUploadServer([.groupId: "1"]), fileName: "upload.getServer.success" ) VKStack.mock( .upload(url: "https://test.vk.com", media: [media], partType: .file), fileName: "upload.photos.toMarket.success" ) VKStack.mock( VK.API.Photos.saveMarketAlbumPhoto([ .groupId: "1", .photo: "testPhoto", .server: "999", .hash: "testHash", ]), fileName: "upload.save.success" ) // When VK.API.Upload.Photo.toMarketAlbum(media, groupId: "1") .onSuccess { response = try? JSON(data: $0) exp.fulfill() } .send() // Then waitForExpectations(timeout: 5) XCTAssertTrue(response?.bool("result") ?? false) } func test_audio() { // Given let exp = expectation(description: "") let media = Media.audio(data: Data(), type: .mp3) var response: JSON? VKStack.mock( VK.API.Audio.getUploadServer(.empty), fileName: "upload.getServer.success" ) VKStack.mock( .upload(url: "https://test.vk.com", media: [media], partType: .file), fileName: "upload.audio.success" ) VKStack.mock( VK.API.Audio.save([ .audio: "testAudio", .server: "999", .hash: "testHash", .artist: "testArtist", .title: "testTitle" ]), fileName: "upload.save.success" ) // When VK.API.Upload.audio(media, artist: "testArtist", title: "testTitle") .onSuccess { response = try? JSON(data: $0) exp.fulfill() } .send() // Then waitForExpectations(timeout: 5) XCTAssertTrue(response?.bool("result") ?? false) } func test_video() { // Given let exp = expectation(description: "") let media = Media.video(data: Data()) var response: JSON? VKStack.mock( VK.API.Video.save([.name: "testName"]), fileName: "upload.getServer.success" ) VKStack.mock( .upload(url: "https://test.vk.com", media: [media], partType: .video), fileName: "upload.save.success" ) // When VK.API.Upload.video(media, savingParams: [.name: "testName"]) .onSuccess { response = try? JSON(data: $0) exp.fulfill() } .send() // Then waitForExpectations(timeout: 5) XCTAssertTrue(response?.bool("result") ?? false) } func test_document() { // Given let exp = expectation(description: "") let media = Media.document(data: Data(), type: "testType") var response: JSON? VKStack.mock( VK.API.Docs.getUploadServer([.groupId: "1"]), fileName: "upload.getServer.success" ) VKStack.mock( .upload(url: "https://test.vk.com", media: [media], partType: .file), fileName: "upload.document.success" ) VKStack.mock( VK.API.Docs.save([ .file: "testFile", .title: "testTitle", .tags: "testTags" ]), fileName: "upload.save.success" ) // When VK.API.Upload.document(media, groupId: "1", title: "testTitle", tags: "testTags") .onSuccess { response = try? JSON(data: $0) exp.fulfill() } .send() // Then waitForExpectations(timeout: 5) XCTAssertTrue(response?.bool("result") ?? false) } func test_photo_toGroupCover() { // Given let exp = expectation(description: "") let media = Media.image(data: Data(), type: .jpg) var response: JSON? VKStack.mock( VK.API.Photos.getOwnerCoverPhotoUploadServer([ .groupId: "1", .cropX: "10", .cropY: "20", .cropX2: "30", .cropY2: "40" ]), fileName: "upload.getServer.success" ) VKStack.mock( .upload(url: "https://test.vk.com", media: [media], partType: .photo), fileName: "upload.photos.toMarket.success" ) VKStack.mock( VK.API.Photos.saveOwnerCoverPhoto([ .photo: "testPhoto", .hash: "testHash", ]), fileName: "upload.save.success" ) // When VK.API.Upload.Photo.toGroupCover(media, to: 1, crop: (x: "10", y: "20", x2: "30", y2: "40")) .onSuccess { response = try? JSON(data: $0) exp.fulfill() } .send() // Then waitForExpectations(timeout: 5) XCTAssertTrue(response?.bool("result") ?? false) } func test_toAudioMessage() { // Given let exp = expectation(description: "") let media = Media.audio(data: Data(), type: .ogg) var response: JSON? VKStack.mock( VK.API.Docs.getMessagesUploadServer([.type: "audio_message"]), fileName: "upload.getServer.success" ) VKStack.mock( .upload(url: "https://test.vk.com", media: [media], partType: .file), fileName: "upload.document.success" ) VKStack.mock( VK.API.Docs.save([ .file: "testFile", ]), fileName: "upload.save.success" ) // When VK.API.Upload.toAudioMessage(media) .onSuccess { response = try? JSON(data: $0) exp.fulfill() } .send() // Then waitForExpectations(timeout: 5) XCTAssertTrue(response?.bool("result") ?? false) } }
mit
jasonhenderson/examples-ios
WebServices/Pods/Toast-Swift/Toast/Toast.swift
2
28211
// // Toast.swift // Toast-Swift // // Copyright (c) 2017 Charles Scalesse. // // 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 UIKit import ObjectiveC /** Toast is a Swift extension that adds toast notifications to the `UIView` object class. It is intended to be simple, lightweight, and easy to use. Most toast notifications can be triggered with a single line of code. The `makeToast` methods create a new view and then display it as toast. The `showToast` methods display any view as toast. */ public extension UIView { /** Keys used for associated objects. */ private struct ToastKeys { static var timer = "com.toast-swift.timer" static var duration = "com.toast-swift.duration" static var point = "com.toast-swift.point" static var completion = "com.toast-swift.completion" static var activeToast = "com.toast-swift.activeToast" static var activityView = "com.toast-swift.activityView" static var queue = "com.toast-swift.queue" } /** Swift closures can't be directly associated with objects via the Objective-C runtime, so the (ugly) solution is to wrap them in a class that can be used with associated objects. */ private class ToastCompletionWrapper { var completion: ((Bool) -> Void)? init(_ completion: ((Bool) -> Void)?) { self.completion = completion } } private enum ToastError: Error { case insufficientData } private var queue: NSMutableArray { get { if let queue = objc_getAssociatedObject(self, &ToastKeys.queue) as? NSMutableArray { return queue } else { let queue = NSMutableArray() objc_setAssociatedObject(self, &ToastKeys.queue, queue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return queue } } } // MARK: - Make Toast Methods /** Creates and presents a new toast view. @param message The message to be displayed @param duration The toast duration @param position The toast's position @param title The title @param image The image @param style The style. The shared style will be used when nil @param completion The completion closure, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ public func makeToast(_ message: String?, duration: TimeInterval = ToastManager.shared.duration, position: ToastPosition = ToastManager.shared.position, title: String? = nil, image: UIImage? = nil, style: ToastStyle = ToastManager.shared.style, completion: ((_ didTap: Bool) -> Void)? = nil) { do { let toast = try toastViewForMessage(message, title: title, image: image, style: style) showToast(toast, duration: duration, position: position, completion: completion) } catch ToastError.insufficientData { print("Error: message, title, and image are all nil") } catch {} } /** Creates a new toast view and presents it at a given center point. @param message The message to be displayed @param duration The toast duration @param point The toast's center point @param title The title @param image The image @param style The style. The shared style will be used when nil @param completion The completion closure, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ public func makeToast(_ message: String?, duration: TimeInterval = ToastManager.shared.duration, point: CGPoint, title: String?, image: UIImage?, style: ToastStyle = ToastManager.shared.style, completion: ((_ didTap: Bool) -> Void)?) { do { let toast = try toastViewForMessage(message, title: title, image: image, style: style) showToast(toast, duration: duration, point: point, completion: completion) } catch ToastError.insufficientData { print("Error: message, title, and image cannot all be nil") } catch {} } // MARK: - Show Toast Methods /** Displays any view as toast at a provided position and duration. The completion closure executes when the toast view completes. `didTap` will be `true` if the toast view was dismissed from a tap. @param toast The view to be displayed as toast @param duration The notification duration @param position The toast's position @param completion The completion block, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ public func showToast(_ toast: UIView, duration: TimeInterval = ToastManager.shared.duration, position: ToastPosition = ToastManager.shared.position, completion: ((_ didTap: Bool) -> Void)? = nil) { let point = position.centerPoint(forToast: toast, inSuperview: self) showToast(toast, duration: duration, point: point, completion: completion) } /** Displays any view as toast at a provided center point and duration. The completion closure executes when the toast view completes. `didTap` will be `true` if the toast view was dismissed from a tap. @param toast The view to be displayed as toast @param duration The notification duration @param point The toast's center point @param completion The completion block, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ public func showToast(_ toast: UIView, duration: TimeInterval = ToastManager.shared.duration, point: CGPoint, completion: ((_ didTap: Bool) -> Void)? = nil) { objc_setAssociatedObject(toast, &ToastKeys.completion, ToastCompletionWrapper(completion), .OBJC_ASSOCIATION_RETAIN_NONATOMIC); if let _ = objc_getAssociatedObject(self, &ToastKeys.activeToast) as? UIView, ToastManager.shared.isQueueEnabled { objc_setAssociatedObject(toast, &ToastKeys.duration, NSNumber(value: duration), .OBJC_ASSOCIATION_RETAIN_NONATOMIC); objc_setAssociatedObject(toast, &ToastKeys.point, NSValue(cgPoint: point), .OBJC_ASSOCIATION_RETAIN_NONATOMIC); queue.add(toast) } else { showToast(toast, duration: duration, point: point) } } // MARK: - Hide Toast Methods /** Hides all toast views and clears the queue. // @TODO: FIXME: this doesn't work then there's more than 1 active toast in the view */ public func hideAllToasts() { queue.removeAllObjects() if let activeToast = objc_getAssociatedObject(self, &ToastKeys.activeToast) as? UIView { hideToast(activeToast) } } // MARK: - Activity Methods /** Creates and displays a new toast activity indicator view at a specified position. @warning Only one toast activity indicator view can be presented per superview. Subsequent calls to `makeToastActivity(position:)` will be ignored until `hideToastActivity()` is called. @warning `makeToastActivity(position:)` works independently of the `showToast` methods. Toast activity views can be presented and dismissed while toast views are being displayed. `makeToastActivity(position:)` has no effect on the queueing behavior of the `showToast` methods. @param position The toast's position */ public func makeToastActivity(_ position: ToastPosition) { // sanity if let _ = objc_getAssociatedObject(self, &ToastKeys.activityView) as? UIView { return } let toast = createToastActivityView() let point = position.centerPoint(forToast: toast, inSuperview: self) makeToastActivity(toast, point: point) } /** Creates and displays a new toast activity indicator view at a specified position. @warning Only one toast activity indicator view can be presented per superview. Subsequent calls to `makeToastActivity(position:)` will be ignored until `hideToastActivity()` is called. @warning `makeToastActivity(position:)` works independently of the `showToast` methods. Toast activity views can be presented and dismissed while toast views are being displayed. `makeToastActivity(position:)` has no effect on the queueing behavior of the `showToast` methods. @param point The toast's center point */ public func makeToastActivity(_ point: CGPoint) { // sanity if let _ = objc_getAssociatedObject(self, &ToastKeys.activityView) as? UIView { return } let toast = createToastActivityView() makeToastActivity(toast, point: point) } /** Dismisses the active toast activity indicator view. */ public func hideToastActivity() { if let toast = objc_getAssociatedObject(self, &ToastKeys.activityView) as? UIView { UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: { toast.alpha = 0.0 }) { _ in toast.removeFromSuperview() objc_setAssociatedObject(self, &ToastKeys.activityView, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } // MARK: - Private Activity Methods private func makeToastActivity(_ toast: UIView, point: CGPoint) { toast.alpha = 0.0 toast.center = point objc_setAssociatedObject(self, &ToastKeys.activityView, toast, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) self.addSubview(toast) UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: .curveEaseOut, animations: { toast.alpha = 1.0 }) } private func createToastActivityView() -> UIView { let style = ToastManager.shared.style let activityView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: style.activitySize.width, height: style.activitySize.height)) activityView.backgroundColor = style.backgroundColor activityView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin] activityView.layer.cornerRadius = style.cornerRadius if style.displayShadow { activityView.layer.shadowColor = style.shadowColor.cgColor activityView.layer.shadowOpacity = style.shadowOpacity activityView.layer.shadowRadius = style.shadowRadius activityView.layer.shadowOffset = style.shadowOffset } let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) activityIndicatorView.center = CGPoint(x: activityView.bounds.size.width / 2.0, y: activityView.bounds.size.height / 2.0) activityView.addSubview(activityIndicatorView) activityIndicatorView.startAnimating() return activityView } // MARK: - Private Show/Hide Methods private func showToast(_ toast: UIView, duration: TimeInterval, point: CGPoint) { toast.center = point toast.alpha = 0.0 if ToastManager.shared.isTapToDismissEnabled { let recognizer = UITapGestureRecognizer(target: self, action: #selector(UIView.handleToastTapped(_:))) toast.addGestureRecognizer(recognizer) toast.isUserInteractionEnabled = true toast.isExclusiveTouch = true } objc_setAssociatedObject(self, &ToastKeys.activeToast, toast, .OBJC_ASSOCIATION_RETAIN_NONATOMIC); self.addSubview(toast) UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseOut, .allowUserInteraction], animations: { toast.alpha = 1.0 }) { _ in let timer = Timer(timeInterval: duration, target: self, selector: #selector(UIView.toastTimerDidFinish(_:)), userInfo: toast, repeats: false) RunLoop.main.add(timer, forMode: RunLoopMode.commonModes) objc_setAssociatedObject(toast, &ToastKeys.timer, timer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private func hideToast(_ toast: UIView) { hideToast(toast, fromTap: false) } private func hideToast(_ toast: UIView, fromTap: Bool) { UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: { toast.alpha = 0.0 }) { _ in toast.removeFromSuperview() objc_setAssociatedObject(self, &ToastKeys.activeToast, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC); if let wrapper = objc_getAssociatedObject(toast, &ToastKeys.completion) as? ToastCompletionWrapper, let completion = wrapper.completion { completion(fromTap) } if let nextToast = self.queue.firstObject as? UIView, let duration = objc_getAssociatedObject(nextToast, &ToastKeys.duration) as? NSNumber, let point = objc_getAssociatedObject(nextToast, &ToastKeys.point) as? NSValue { self.queue.removeObject(at: 0) self.showToast(nextToast, duration: duration.doubleValue, point: point.cgPointValue) } } } // MARK: - Events func handleToastTapped(_ recognizer: UITapGestureRecognizer) { guard let toast = recognizer.view, let timer = objc_getAssociatedObject(toast, &ToastKeys.timer) as? Timer else { return } timer.invalidate() hideToast(toast, fromTap: true) } func toastTimerDidFinish(_ timer: Timer) { guard let toast = timer.userInfo as? UIView else { return } hideToast(toast) } // MARK: - Toast Construction /** Creates a new toast view with any combination of message, title, and image. The look and feel is configured via the style. Unlike the `makeToast` methods, this method does not present the toast view automatically. One of the `showToast` methods must be used to present the resulting view. @warning if message, title, and image are all nil, this method will throw `ToastError.InsufficientData` @param message The message to be displayed @param title The title @param image The image @param style The style. The shared style will be used when nil @throws `ToastError.InsufficientData` when message, title, and image are all nil @return The newly created toast view */ public func toastViewForMessage(_ message: String?, title: String?, image: UIImage?, style: ToastStyle) throws -> UIView { // sanity guard message != nil || title != nil || image != nil else { throw ToastError.insufficientData } var messageLabel: UILabel? var titleLabel: UILabel? var imageView: UIImageView? let wrapperView = UIView() wrapperView.backgroundColor = style.backgroundColor wrapperView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin] wrapperView.layer.cornerRadius = style.cornerRadius if style.displayShadow { wrapperView.layer.shadowColor = UIColor.black.cgColor wrapperView.layer.shadowOpacity = style.shadowOpacity wrapperView.layer.shadowRadius = style.shadowRadius wrapperView.layer.shadowOffset = style.shadowOffset } if let image = image { imageView = UIImageView(image: image) imageView?.contentMode = .scaleAspectFit imageView?.frame = CGRect(x: style.horizontalPadding, y: style.verticalPadding, width: style.imageSize.width, height: style.imageSize.height) } var imageRect = CGRect.zero if let imageView = imageView { imageRect.origin.x = style.horizontalPadding imageRect.origin.y = style.verticalPadding imageRect.size.width = imageView.bounds.size.width imageRect.size.height = imageView.bounds.size.height } if let title = title { titleLabel = UILabel() titleLabel?.numberOfLines = style.titleNumberOfLines titleLabel?.font = style.titleFont titleLabel?.textAlignment = style.titleAlignment titleLabel?.lineBreakMode = .byTruncatingTail titleLabel?.textColor = style.titleColor titleLabel?.backgroundColor = UIColor.clear titleLabel?.text = title; let maxTitleSize = CGSize(width: (self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, height: self.bounds.size.height * style.maxHeightPercentage) let titleSize = titleLabel?.sizeThatFits(maxTitleSize) if let titleSize = titleSize { titleLabel?.frame = CGRect(x: 0.0, y: 0.0, width: titleSize.width, height: titleSize.height) } } if let message = message { messageLabel = UILabel() messageLabel?.text = message messageLabel?.numberOfLines = style.messageNumberOfLines messageLabel?.font = style.messageFont messageLabel?.textAlignment = style.messageAlignment messageLabel?.lineBreakMode = .byTruncatingTail; messageLabel?.textColor = style.messageColor messageLabel?.backgroundColor = UIColor.clear let maxMessageSize = CGSize(width: (self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, height: self.bounds.size.height * style.maxHeightPercentage) let messageSize = messageLabel?.sizeThatFits(maxMessageSize) if let messageSize = messageSize { let actualWidth = min(messageSize.width, maxMessageSize.width) let actualHeight = min(messageSize.height, maxMessageSize.height) messageLabel?.frame = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight) } } var titleRect = CGRect.zero if let titleLabel = titleLabel { titleRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding titleRect.origin.y = style.verticalPadding titleRect.size.width = titleLabel.bounds.size.width titleRect.size.height = titleLabel.bounds.size.height } var messageRect = CGRect.zero if let messageLabel = messageLabel { messageRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding messageRect.origin.y = titleRect.origin.y + titleRect.size.height + style.verticalPadding messageRect.size.width = messageLabel.bounds.size.width messageRect.size.height = messageLabel.bounds.size.height } let longerWidth = max(titleRect.size.width, messageRect.size.width) let longerX = max(titleRect.origin.x, messageRect.origin.x) let wrapperWidth = max((imageRect.size.width + (style.horizontalPadding * 2.0)), (longerX + longerWidth + style.horizontalPadding)) let wrapperHeight = max((messageRect.origin.y + messageRect.size.height + style.verticalPadding), (imageRect.size.height + (style.verticalPadding * 2.0))) wrapperView.frame = CGRect(x: 0.0, y: 0.0, width: wrapperWidth, height: wrapperHeight) if let titleLabel = titleLabel { titleRect.size.width = longerWidth titleLabel.frame = titleRect wrapperView.addSubview(titleLabel) } if let messageLabel = messageLabel { messageRect.size.width = longerWidth messageLabel.frame = messageRect wrapperView.addSubview(messageLabel) } if let imageView = imageView { wrapperView.addSubview(imageView) } return wrapperView } } // MARK: - Toast Style /** `ToastStyle` instances define the look and feel for toast views created via the `makeToast` methods as well for toast views created directly with `toastViewForMessage(message:title:image:style:)`. @warning `ToastStyle` offers relatively simple styling options for the default toast view. If you require a toast view with more complex UI, it probably makes more sense to create your own custom UIView subclass and present it with the `showToast` methods. */ public struct ToastStyle { public init() {} /** The background color. Default is `UIColor.blackColor()` at 80% opacity. */ public var backgroundColor = UIColor.black.withAlphaComponent(0.8) /** The title color. Default is `UIColor.whiteColor()`. */ public var titleColor = UIColor.white /** The message color. Default is `UIColor.whiteColor()`. */ public var messageColor = UIColor.white /** A percentage value from 0.0 to 1.0, representing the maximum width of the toast view relative to it's superview. Default is 0.8 (80% of the superview's width). */ public var maxWidthPercentage: CGFloat = 0.8 { didSet { maxWidthPercentage = max(min(maxWidthPercentage, 1.0), 0.0) } } /** A percentage value from 0.0 to 1.0, representing the maximum height of the toast view relative to it's superview. Default is 0.8 (80% of the superview's height). */ public var maxHeightPercentage: CGFloat = 0.8 { didSet { maxHeightPercentage = max(min(maxHeightPercentage, 1.0), 0.0) } } /** The spacing from the horizontal edge of the toast view to the content. When an image is present, this is also used as the padding between the image and the text. Default is 10.0. */ public var horizontalPadding: CGFloat = 10.0 /** The spacing from the vertical edge of the toast view to the content. When a title is present, this is also used as the padding between the title and the message. Default is 10.0. */ public var verticalPadding: CGFloat = 10.0 /** The corner radius. Default is 10.0. */ public var cornerRadius: CGFloat = 10.0; /** The title font. Default is `UIFont.boldSystemFontOfSize(16.0)`. */ public var titleFont = UIFont.boldSystemFont(ofSize: 16.0) /** The message font. Default is `UIFont.systemFontOfSize(16.0)`. */ public var messageFont = UIFont.systemFont(ofSize: 16.0) /** The title text alignment. Default is `NSTextAlignment.Left`. */ public var titleAlignment = NSTextAlignment.left /** The message text alignment. Default is `NSTextAlignment.Left`. */ public var messageAlignment = NSTextAlignment.left /** The maximum number of lines for the title. The default is 0 (no limit). */ public var titleNumberOfLines = 0 /** The maximum number of lines for the message. The default is 0 (no limit). */ public var messageNumberOfLines = 0 /** Enable or disable a shadow on the toast view. Default is `false`. */ public var displayShadow = false /** The shadow color. Default is `UIColor.blackColor()`. */ public var shadowColor = UIColor.black /** A value from 0.0 to 1.0, representing the opacity of the shadow. Default is 0.8 (80% opacity). */ public var shadowOpacity: Float = 0.8 { didSet { shadowOpacity = max(min(shadowOpacity, 1.0), 0.0) } } /** The shadow radius. Default is 6.0. */ public var shadowRadius: CGFloat = 6.0 /** The shadow offset. The default is 4 x 4. */ public var shadowOffset = CGSize(width: 4.0, height: 4.0) /** The image size. The default is 80 x 80. */ public var imageSize = CGSize(width: 80.0, height: 80.0) /** The size of the toast activity view when `makeToastActivity(position:)` is called. Default is 100 x 100. */ public var activitySize = CGSize(width: 100.0, height: 100.0) /** The fade in/out animation duration. Default is 0.2. */ public var fadeDuration: TimeInterval = 0.2 } // MARK: - Toast Manager /** `ToastManager` provides general configuration options for all toast notifications. Backed by a singleton instance. */ public class ToastManager { /** The `ToastManager` singleton instance. */ public static let shared = ToastManager() /** The shared style. Used whenever toastViewForMessage(message:title:image:style:) is called with with a nil style. */ public var style = ToastStyle() /** Enables or disables tap to dismiss on toast views. Default is `true`. */ public var isTapToDismissEnabled = true /** Enables or disables queueing behavior for toast views. When `true`, toast views will appear one after the other. When `false`, multiple toast views will appear at the same time (potentially overlapping depending on their positions). This has no effect on the toast activity view, which operates independently of normal toast views. Default is `true`. */ public var isQueueEnabled = true /** The default duration. Used for the `makeToast` and `showToast` methods that don't require an explicit duration. Default is 3.0. */ public var duration: TimeInterval = 3.0 /** Sets the default position. Used for the `makeToast` and `showToast` methods that don't require an explicit position. Default is `ToastPosition.Bottom`. */ public var position = ToastPosition.bottom } // MARK: - ToastPosition public enum ToastPosition { case top case center case bottom fileprivate func centerPoint(forToast toast: UIView, inSuperview superview: UIView) -> CGPoint { let padding: CGFloat = ToastManager.shared.style.verticalPadding switch self { case .top: return CGPoint(x: superview.bounds.size.width / 2.0, y: (toast.frame.size.height / 2.0) + padding) case .center: return CGPoint(x: superview.bounds.size.width / 2.0, y: superview.bounds.size.height / 2.0) case .bottom: return CGPoint(x: superview.bounds.size.width / 2.0, y: (superview.bounds.size.height - (toast.frame.size.height / 2.0)) - padding) } } }
gpl-3.0
cdebortoli/JsonManagedObject-Swift
JsonManagedObject/JsonManagedObjectTests/JsonManagedObjectTests.swift
1
916
// // JsonManagedObjectTests.swift // JsonManagedObjectTests // // Created by christophe on 21/06/14. // Copyright (c) 2014 cdebortoli. All rights reserved. // import XCTest class JsonManagedObjectTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
bcbirkhauser/IQSideMenu
IQSideMenuDemo/IQSideMenuDemo/Sources/Content/IQDemoContentController.swift
1
809
// // IQDemoContentController.swift // IQSideMenuDemo // // Created by Alexander Orlov on 21/11/14. // Copyright (c) 2014 Alexander Orlov. All rights reserved. // import UIKit class IQDemoContentController: UIViewController { var sideMenu: IQSideMenuController? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func openSideMenu() { sideMenu?.openMenu(true); } @IBAction func closeSideMenu() { sideMenu?.closeMenu(true); } @IBAction func toggleSideMenu() { sideMenu?.toggleMenu(true); } }
mit
domenicosolazzo/practice-swift
CoreData/Performing Batch Updates/Performing Batch Updates/AppDelegate.swift
1
8494
// // AppDelegate.swift // Performing Batch Updates // // Created by Domenico Solazzo on 17/05/15. // License MIT // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let entityName = NSStringFromClass(Person.classForCoder()) //- MARK: Helper methods func populateDatabase(){ for counter in 0..<1000{ let person = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: managedObjectContext!) as! Person person.firstName = "First Name \(counter)" person.lastName = "Last Name \(counter)" person.age = NSNumber(unsignedInt: arc4random_uniform(120)) } var savingError: NSError? do { try managedObjectContext!.save() print("Managed to populate the database") } catch let error1 as NSError { savingError = error1 if let error = savingError{ print("Error populating the database. Error \(error)") } } } //- MARK: Application func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let batch = NSBatchUpdateRequest(entityName: entityName) // Properties to Update batch.propertiesToUpdate = ["age":18] // Predicate batch.predicate = NSPredicate(format:"age < %@", 18 as NSNumber) // Result type batch.resultType = NSBatchUpdateRequestResultType.UpdatedObjectsCountResultType var batchError: NSError? let result: NSPersistentStoreResult? do { result = try managedObjectContext!.executeRequest(batch) } catch let error as NSError { batchError = error result = nil } if result != nil{ if let theResult = result as? NSBatchUpdateResult{ if let numberOfAffectedPersons = theResult.result as? Int{ print("Number of people who were previously younger than " + "18 years old and whose age is now set to " + "18 is \(numberOfAffectedPersons)") } } }else{ if let error = batchError{ print("Could not perform batch request. Error = \(error)") } } 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 throttle down OpenGL ES frame rates. 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 inactive 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.domenicosolazzo.swift.Performing_Batch_Updates" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Performing_Batch_Updates", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Performing_Batch_Updates.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch var error1 as NSError { error = error1 coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } catch { fatalError() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges { do { try moc.save() } catch let error1 as NSError { error = error1 // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } } }
mit
RoRoche/iOSSwiftStarter
iOSSwiftStarter/Pods/CoreStore/CoreStore/Internal/NSManagedObjectContext+Transaction.swift
1
6536
// // NSManagedObjectContext+Transaction.swift // CoreStore // // Copyright © 2015 John Rommel Estropia // // 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 #if USE_FRAMEWORKS import GCDKit #endif // MARK: - NSManagedObjectContext internal extension NSManagedObjectContext { // MARK: Internal internal weak var parentTransaction: BaseDataTransaction? { get { return getAssociatedObjectForKey( &PropertyKeys.parentTransaction, inObject: self ) } set { setAssociatedWeakObject( newValue, forKey: &PropertyKeys.parentTransaction, inObject: self ) } } internal var isSavingSynchronously: Bool? { get { let value: NSNumber? = getAssociatedObjectForKey( &PropertyKeys.isSavingSynchronously, inObject: self ) return value?.boolValue } set { setAssociatedWeakObject( newValue.flatMap { NSNumber(bool: $0) }, forKey: &PropertyKeys.isSavingSynchronously, inObject: self ) } } internal func isRunningInAllowedQueue() -> Bool { guard let parentTransaction = self.parentTransaction else { return false } return parentTransaction.isRunningInAllowedQueue() } internal func temporaryContextInTransactionWithConcurrencyType(concurrencyType: NSManagedObjectContextConcurrencyType) -> NSManagedObjectContext { let context = NSManagedObjectContext(concurrencyType: concurrencyType) context.parentContext = self context.parentStack = self.parentStack context.setupForCoreStoreWithContextName("com.corestore.temporarycontext") context.shouldCascadeSavesToParent = (self.parentStack?.rootSavingContext == self) context.retainsRegisteredObjects = true return context } internal func saveSynchronously() -> SaveResult { var result = SaveResult(hasChanges: false) self.performBlockAndWait { guard self.hasChanges else { return } do { self.isSavingSynchronously = true try self.save() self.isSavingSynchronously = nil } catch { let saveError = error as NSError CoreStore.handleError( saveError, "Failed to save \(typeName(NSManagedObjectContext))." ) result = SaveResult(saveError) return } if let parentContext = self.parentContext where self.shouldCascadeSavesToParent { switch parentContext.saveSynchronously() { case .Success: result = SaveResult(hasChanges: true) case .Failure(let error): result = SaveResult(error) } } else { result = SaveResult(hasChanges: true) } } return result } internal func saveAsynchronouslyWithCompletion(completion: ((result: SaveResult) -> Void) = { _ in }) { self.performBlock { guard self.hasChanges else { GCDQueue.Main.async { completion(result: SaveResult(hasChanges: false)) } return } do { self.isSavingSynchronously = false try self.save() self.isSavingSynchronously = nil } catch { let saveError = error as NSError CoreStore.handleError( saveError, "Failed to save \(typeName(NSManagedObjectContext))." ) GCDQueue.Main.async { completion(result: SaveResult(saveError)) } return } if let parentContext = self.parentContext where self.shouldCascadeSavesToParent { parentContext.saveAsynchronouslyWithCompletion(completion) } else { GCDQueue.Main.async { completion(result: SaveResult(hasChanges: true)) } } } } internal func refreshAndMergeAllObjects() { if #available(iOS 8.3, OSX 10.11, *) { self.refreshAllObjects() } else { self.registeredObjects.forEach { self.refreshObject($0, mergeChanges: true) } } } // MARK: Private private struct PropertyKeys { static var parentTransaction: Void? static var isSavingSynchronously: Void? } }
apache-2.0
ps2/rileylink_ios
OmniKitUI/Views/PodLifeHUDView.swift
1
5680
// // PodLifeHUDView.swift // OmniKit // // Based on OmniKitUI/Views/PodLifeHUDView.swift // Created by Pete Schwamb on 10/22/18. // Copyright © 2021 LoopKit Authors. All rights reserved. // import UIKit import LoopKitUI import MKRingProgressView public enum PodAlertState { case none case warning case fault } public class PodLifeHUDView: BaseHUDView, NibLoadable { override public var orderPriority: HUDViewOrderPriority { return 12 } @IBOutlet private weak var timeLabel: UILabel! { didSet { // Setting this color in code because the nib isn't being applied correctly if #available(iOSApplicationExtension 13.0, *) { timeLabel.textColor = .label } } } @IBOutlet private weak var progressRing: RingProgressView! @IBOutlet private weak var alertLabel: UILabel! { didSet { alertLabel.alpha = 0 alertLabel.textColor = UIColor.white alertLabel.layer.cornerRadius = 9 alertLabel.clipsToBounds = true } } @IBOutlet private weak var backgroundRing: UIImageView! { didSet { if #available(iOSApplicationExtension 13.0, iOS 13.0, *) { backgroundRing.tintColor = .systemGray5 } else { backgroundRing.tintColor = UIColor(red: 198 / 255, green: 199 / 255, blue: 201 / 255, alpha: 1) } } } private var startTime: Date? private var lifetime: TimeInterval? private var timer: Timer? public var alertState: PodAlertState = .none { didSet { updateAlertStateLabel() } } public class func instantiate() -> PodLifeHUDView { return nib().instantiate(withOwner: nil, options: nil)[0] as! PodLifeHUDView } public func setPodLifeCycle(startTime: Date, lifetime: TimeInterval) { self.startTime = startTime self.lifetime = lifetime updateProgressCircle() if timer == nil { self.timer = Timer.scheduledTimer(withTimeInterval: .seconds(10), repeats: true) { [weak self] _ in self?.updateProgressCircle() } } } override open func stateColorsDidUpdate() { super.stateColorsDidUpdate() updateProgressCircle() updateAlertStateLabel() } private var endColor: UIColor? { didSet { let primaryColor = endColor ?? UIColor(red: 198 / 255, green: 199 / 255, blue: 201 / 255, alpha: 1) self.progressRing.endColor = primaryColor self.progressRing.startColor = primaryColor } } private lazy var timeFormatter: DateComponentsFormatter = { let formatter = DateComponentsFormatter() formatter.allowedUnits = [.hour, .minute] formatter.maximumUnitCount = 1 formatter.unitsStyle = .abbreviated return formatter }() private func updateAlertStateLabel() { var alertLabelAlpha: CGFloat = 1 if alertState == .fault { timer = nil } switch alertState { case .fault: alertLabel.text = "!" alertLabel.backgroundColor = stateColors?.error case .warning: alertLabel.text = "!" alertLabel.backgroundColor = stateColors?.warning case .none: alertLabelAlpha = 0 } alertLabel.alpha = alertLabelAlpha UIView.animate(withDuration: 0.25, animations: { self.alertLabel.alpha = alertLabelAlpha }) } private func updateProgressCircle() { if let startTime = startTime, let lifetime = lifetime { let age = -startTime.timeIntervalSinceNow let progress = Double(age / lifetime) progressRing.progress = progress if progress < 0.75 { self.endColor = stateColors?.normal progressRing.shadowOpacity = 0 } else if progress < 1.0 { self.endColor = stateColors?.warning progressRing.shadowOpacity = 0.5 } else { self.endColor = stateColors?.error progressRing.shadowOpacity = 0.8 } let remaining = (lifetime - age) // Update time label and caption if alertState == .fault { timeLabel.isHidden = true caption.text = LocalizedString("Fault", comment: "Pod life HUD view label") } else if remaining > .hours(24) { timeLabel.isHidden = true caption.text = LocalizedString("Pod Age", comment: "Label describing pod age view") } else if remaining > 0 { let remainingFlooredToHour = remaining > .hours(1) ? remaining - remaining.truncatingRemainder(dividingBy: .hours(1)) : remaining if let timeString = timeFormatter.string(from: remainingFlooredToHour) { timeLabel.isHidden = false timeLabel.text = timeString } caption.text = LocalizedString("Remaining", comment: "Label describing time remaining view") } else { timeLabel.isHidden = true caption.text = LocalizedString("Replace Pod", comment: "Label indicating pod replacement necessary") } } } func pauseUpdates() { timer?.invalidate() timer = nil } override public func awakeFromNib() { super.awakeFromNib() } }
mit
delannoyk/GIFRefreshControl
GIFRefreshControlExample/GIFRefreshControlExample/ViewController.swift
1
1550
// // ViewController.swift // GIFRefreshControlExample // // Created by Kevin DELANNOY on 01/06/15. // Copyright (c) 2015 Kevin Delannoy. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource { @IBOutlet private weak var tableView: UITableView! var count = 1 let refreshControl = GIFRefreshControl() //MARK: Refresh control override func viewDidLoad() { super.viewDidLoad() refreshControl.animatedImage = GIFAnimatedImage(data: try! Data(contentsOf: Bundle.main.url(forResource: "giphy", withExtension: "gif")!)) refreshControl.contentMode = .scaleAspectFill refreshControl.addTarget(self, action: #selector(ViewController.refresh), for: .valueChanged) tableView.addSubview(refreshControl) } //MARK: Refresh func refresh() { DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) { self.count += 1 self.refreshControl.endRefreshing() self.tableView.beginUpdates() self.tableView.insertRows(at: [IndexPath(item: 0, section: 0)], with: .none) self.tableView.endUpdates() } } //MARK: UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableView.dequeueReusableCell(withIdentifier: "TableViewCell")! } }
mit
wscqs/FMDemo-
FMDemo/Classes/Module/Course/CourceHeadTbView.swift
1
2881
// // CourceHeadTbView.swift // FMDemo // // Created by mba on 17/2/9. // Copyright © 2017年 mbalib. All rights reserved. // import UIKit //protocol CourceHeadTbViewDelegate: NSObjectProtocol{ // func clickOKChangceTitle(courceHeadTbView: CourceHeadTbView, title: String) //} class CourceHeadTbView: UIView { // weak var delegate: CourceHeadTbViewDelegate? var cid: String! @IBOutlet weak var tbHeadNormalView: BorderBackgroundView! @IBOutlet weak var tbHeadChangceView: BorderBackgroundView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var courceStatusLabel: UILabel! @IBOutlet weak var changceBtn: UIView! @IBOutlet weak var textView: BorderTextView! @IBOutlet weak var okBtn: UIButton! class func courceHeadTbView() -> CourceHeadTbView { let view: CourceHeadTbView = Bundle.main.loadNibNamed("CourceHeadTbView", owner: self, options: nil)!.last as! CourceHeadTbView view.frame.size.width = SCREEN_WIDTH view.backgroundColor = UIColor.colorWithHexString(kGlobalBgColor) return view } override init(frame: CGRect) { super.init(frame: frame) // setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // setupUI() } override func awakeFromNib() { superview?.awakeFromNib() tbHeadChangceView.isHidden = true // setupUI() textView.setPlaceholder(kCreatCourceTitleString, maxTip: 50) changceBtn.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(actionChangce(_:))) changceBtn.addGestureRecognizer(tapGes) } func actionChangce(_ sender: UIView) { textView.clearBorder = true tbHeadChangceView.isHidden = false textView.text = titleLabel.text } var isRequest: Bool = false @IBAction func actionOk(_ sender: UIButton) { if textView.text.isEmpty { MBAProgressHUD.showInfoWithStatus("课程标题不能为空") return } if titleLabel.text != textView.text { if isRequest { return } isRequest = true KeService.actionSaveCourse(title: textView.text, cid: cid, success: { (bean) in self.titleLabel.text = self.textView.text self.tbHeadChangceView.isHidden = true self.isRequest = false }) { (error) in MBAProgressHUD.showInfoWithStatus("课程标题修改失败,请重试") self.tbHeadChangceView.isHidden = true self.isRequest = false } } else { self.tbHeadChangceView.isHidden = true } endEditing(true) } }
apache-2.0
cottonBuddha/Qsic
Qsic/QSLoginWidget.swift
1
1499
// // QSLoginWidget.swift // Qsic // // Created by cottonBuddha on 2017/8/2. // Copyright © 2017年 cottonBuddha. All rights reserved. // import Foundation class QSLoginWidget: QSWidget { var accountInput: QSInputWidget? var passwordInput: QSInputWidget? var accountLength: Int = 0 var passwordLength: Int = 0 convenience init(startX:Int, startY:Int) { self.init(startX: startX, startY: startY, width: Int(COLS - Int32(startX + 1)), height: 3) } override func drawWidget() { super.drawWidget() self.drawLoginWidget() wrefresh(self.window) } private func drawLoginWidget() { mvwaddstr(self.window, 0, 0, "需要登录~") mvwaddstr(self.window, 1, 0, "账号:") mvwaddstr(self.window, 2, 0, "密码:") } public func getInputContent(completionHandler:(String,String)->()) { accountInput = QSInputWidget.init(startX: 6, startY: 1, width: 40, height: 1) self.addSubWidget(widget: accountInput!) let account = accountInput?.input() accountLength = account!.lengthInCurses() passwordInput = QSInputWidget.init(startX: 6, startY: 2, width: 40, height: 1) self.addSubWidget(widget: passwordInput!) let password = passwordInput?.input() passwordLength = password!.lengthInCurses() completionHandler(account!,password!) } public func hide() { eraseSelf() } }
mit
carolight/sample-code
swift/05-Lighting/Lighting/MBEMesh.swift
1
1396
// // MBEMesh.swift // Lighting // // Created by Caroline Begbie on 30/12/2015. // Copyright © 2015 Caroline Begbie. All rights reserved. // import Foundation import MetalKit class MBEMesh { let mesh: MTKMesh? var submeshes: [MBESubmesh] = [] init(mesh: MTKMesh, mdlMesh: MDLMesh, device: MTLDevice) { self.mesh = mesh for i in 0 ..< mesh.submeshes.count { let submesh = MBESubmesh(submesh: mesh.submeshes[i], mdlSubmesh: mdlMesh.submeshes?[i] as! MDLSubmesh, device: device) submeshes.append(submesh) } } func renderWithEncoder(encoder:MTLRenderCommandEncoder) { guard let mesh = mesh else { return } for (index, vertexBuffer) in mesh.vertexBuffers.enumerated() { encoder.setVertexBuffer(vertexBuffer.buffer, offset: vertexBuffer.offset, at: index) } for submesh in submeshes { submesh.renderWithEncoder(encoder: encoder) } } } class MBESubmesh { let submesh:MTKSubmesh? init(submesh:MTKSubmesh, mdlSubmesh:MDLSubmesh, device: MTLDevice) { self.submesh = submesh } func renderWithEncoder(encoder:MTLRenderCommandEncoder) { guard let submesh = submesh else { return } encoder.drawIndexedPrimitives(submesh.primitiveType, indexCount: submesh.indexCount, indexType: submesh.indexType, indexBuffer: submesh.indexBuffer.buffer, indexBufferOffset: submesh.indexBuffer.offset) } }
mit
gwyndurbridge/GDSilentDetector
Example/GDSilentDetector/ViewController.swift
1
1276
// // ViewController.swift // GDSilentDetector // // Created by Gwyn Durbridge on 09/16/2017. // Copyright (c) 2017 Gwyn Durbridge. All rights reserved. // import UIKit import GDSilentDetector struct Platform { static var isSimulator: Bool { return TARGET_OS_SIMULATOR != 0 } } class ViewController: UIViewController { var silentChecker: GDSilentDetector! @IBOutlet weak var statusLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() silentChecker = GDSilentDetector() silentChecker.delegate = self checkSilent(self) } @IBAction func checkSilent(_ sender: Any) { if Platform.isSimulator { self.statusLabel.text = "Cannot detect silent switch on simulator" } else { silentChecker.checkSilent() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: GDSilentDetectorDelegate { func gotSilentStatus(isSilent: Bool) { DispatchQueue.main.async { self.statusLabel.text = isSilent ? "SILENT ENABLED" : "SILENT DISABLED" } } }
mit
nathawes/swift
test/InterfaceHash/added_private_protocol_property.swift
8
542
// RUN: %empty-directory(%t) // RUN: %{python} %utils/split_file.py -o %t %s // RUN: %target-swift-frontend -disable-type-fingerprints -dump-interface-hash -primary-file %t/a.swift 2> %t/a.hash // RUN: %target-swift-frontend -disable-type-fingerprints -dump-interface-hash -primary-file %t/b.swift 2> %t/b.hash // RUN: not cmp %t/a.hash %t/b.hash // BEGIN a.swift private protocol P { func f2() -> Int var y: Int { get set } } // BEGIN b.swift private protocol P { func f2() -> Int var x: Int { get set } var y: Int { get set } }
apache-2.0
roambotics/swift
validation-test/compiler_crashers_2_fixed/0101-issue-47591.swift
2
257
// RUN: not %target-swift-frontend -emit-ir -primary-file %s // https://github.com/apple/swift/issues/47591 struct Version { } extension CountableRange where Bound == Version { func contains(_ element: Version) -> Bool { fatalError() } }
apache-2.0
amraboelela/SwiftPusher
Sources/NWHub.swift
1
13874
// Converted with Swiftify v1.0.6276 - https://objectivec2swift.com/ // // NWHub.swift // Pusher // // Copyright (c) 2014 noodlewerk. All rights reserved. // // Modified by: Amr Aboelela on 3/16/17. // import Foundation /** Allows callback on errors while pushing to and reading from server. Check out `NWHub` for more details. */ protocol NWHubDelegate: NSObjectProtocol { /** The notification failed during or after pushing. */ func notification(_ notification: NWNotification, didFailWithError error: Error?) } /** Helper on top of `NWPusher` that hides the details of pushing and reading. This class provides a more convenient way of pushing notifications to the APNs. It deals with the trouble of assigning a unique identifier to every notification and the handling of error responses from the server. It hides the latency that comes with transmitting the pushes, allowing you to simply push your notifications and getting notified of errors through the delegate. If this feels over-abstracted, then definitely check out the `NWPusher` class, which will give you full control. There are two set of methods for pushing notifications: the easy and the pros. The former will just do the pushing and reconnect if the connection breaks. This is your low-worry solution, provided that you call `readFailed` every so often (seconds) to handle error data from the server. The latter will give you a little more control and a little more responsibility. */ class NWHub: NSObject { /** @name Properties */ /** The pusher instance that does the actual work. */ var pusher: NWPusher! /** Assign a delegate to get notified when something fails during or after pushing. */ weak var delegate: NWHubDelegate? /** The type of notification serialization we'll be using. */ var type = NWNotificationType() /** The timespan we'll hold on to a notification after pushing, allowing the server to respond. */ var feedbackSpan = TimeInterval() /** The index incremented on every notification push, used as notification identifier. */ var index: Int = 0 /** @name Initialization */ /** Create and return a hub object with a delegate object assigned. */ convenience init(delegate: NWHubDelegate) { return self.init(NWPusher(), delegate: delegate) } /** Create and return a hub object with a delegate and pusher object assigned. */ override init(pusher: NWPusher, delegate: NWHubDelegate) { super.init() self.index = 1 self.feedbackSpan = 30 self.pusher = pusher self.delegate = delegate self.notificationForIdentifier = [:] self.type = kNWNotificationType2 } /** Create, connect and returns an instance with delegate and identity. */ class func connect(with delegate: NWHubDelegate, identity: NWIdentityRef, environment: NWEnvironment, error: Error?) -> Self { var hub = NWHub(delegate: delegate) return identity && (try? hub.connect(withIdentity: identity, environment: environment)) ? hub : nil! } /** Create, connect and returns an instance with delegate and identity. */ class func connect(with delegate: NWHubDelegate, pkcs12Data data: Data, password: String, environment: NWEnvironment, error: Error?) -> Self { var hub = NWHub(delegate: delegate) return data && (try? hub.connect(withPKCS12Data: data, password: password, environment: environment)) ? hub : nil! } /** @name Connecting */ /** Connect the pusher using the identity to setup the SSL connection. */ func connect(withIdentity identity: NWIdentityRef, environment: NWEnvironment) throws { return try? self.pusher.connect(withIdentity: identity, environment: environment)! } /** Connect the pusher using the PKCS #12 data to setup the SSL connection. */ func connect(withPKCS12Data data: Data, password: String, environment: NWEnvironment) throws { return try? self.pusher.connect(withPKCS12Data: data, password: password, environment: environment)! } /** Reconnect with the server, to recover from a closed or defect connection. */ func reconnect() throws { return try? self.pusher.reconnect()! } /** Close the connection, allows reconnecting. */ override func disconnect() { self.pusher.disconnect() } /** @name Pushing (easy) */ /** Push a JSON string payload to a device with token string. @see pushNotifications: */ func pushPayload(_ payload: String, token: String) -> Int { var notification = NWNotification(payload: payload, token: token, identifier: 0, expiration: nil, priority: 0) return self.pushNotifications([notification]) } /** Push a JSON string payload to multiple devices with token strings. @see pushNotifications: */ func pushPayload(_ payload: String, tokens: [Any]) -> Int { var notifications: [Any] = [] for token: String in tokens { var notification = NWNotification(payload: payload, token: token, identifier: 0, expiration: nil, priority: 0) notifications.append(notification) } return self.pushNotifications(notifications) } /** Push multiple JSON string payloads to a device with token string. @see pushNotifications: */ func pushPayloads(_ payloads: [Any], token: String) -> Int { var notifications: [Any] = [] for payload: String in payloads { var notification = NWNotification(payload: payload, token: token, identifier: 0, expiration: nil, priority: 0) notifications.append(notification) } return self.pushNotifications(notifications) } /** Push multiple notifications, each representing a payload and a device token. This will assign each notification a unique identifier if none was set yet. If pushing fails it will reconnect. This method can be used rather carelessly; any thing goes. However, this also means that a failed notification might break the connection temporarily, losing a notification here or there. If you are sending bulk and don't care too much about this, then you'll be fine. If not, consider using `pushNotification:autoReconnect:error:`. Make sure to call `readFailed` on a regular basis to allow server error responses to be handled and the delegate to be called. Returns the number of notifications that failed, preferably zero. @see readFailed */ func pushNotifications(_ notifications: [Any]) -> Int { var fails: Int = 0 for notification: NWNotification in notifications { var success: Bool? = try? self.push(notification, autoReconnect: true) if success == nil { fails += 1 } } return fails } /** Read the response from the server to see if any pushes have failed. Due to transmission latency it usually takes a couple of milliseconds for the server to respond to errors. This methods reads the server response and handles the errors. Make sure to call this regularly to catch up on malformed notifications. @see pushNotifications: */ func readFailed() -> Int { var failed: [Any]? = nil try? self.readFailed(failed, max: 1000, autoReconnect: true) return failed?.count! } /** @name Pushing (pros) */ /** Push a notification and reconnect if anything failed. This will assign the notification a unique (incremental) identifier and feed it to the internal pusher. If this succeeds, the notification is stored for later lookup by `readFailed:autoReconnect:error:`. If it fails, the delegate will be invoked and it will reconnect if set to auto-reconnect. @see readFailed:autoReconnect:error: */ func push(_ notification: NWNotification, autoReconnect reconnect: Bool) throws { if !notification.identifier { notification.identifier = self.index += 1 } var e: Error? = nil var pushed: Bool? = try? self.pusher.push(notification, type: self.type) if pushed == nil { if error != nil { error = e } if self.delegate.responds(to: Selector("notification:didFailWithError:")) { self.delegate.notification(notification, didFailWithError: e) } if reconnect && e?.code == kNWErrorWriteClosedGraceful { try? self.reconnect() } return pushed! } self.notificationForIdentifier[(notification.identifier)] = [notification, Date()] return true } /** Read the response from the server and reconnect if anything failed. If the APNs finds something wrong with a notification, it will write back the identifier and error code. As this involves transmission to and from the server, it takes just a little while to get this failure info. This method should therefore be invoked a little (say a second) after pushing to see if anything was wrong. On a slow connection this might take longer than the interval between push messages, in which case the reported notification was *not* the last one sent. From the server we only get the notification identifier and the error message. This method translates this back into the original notification by keeping track of all notifications sent in the past 30 seconds. If somehow the original notification cannot be found, it will assign `NSNull`. Usually, when a notification fails, the server will drop the connection. To prevent this from causing any more problems, the connection can be reestablished by setting it to reconnect automatically. @see trimIdentifiers @see feedbackSpan */ func readFailed(_ notification: NWNotification, autoReconnect reconnect: Bool) throws { var identifier: Int = 0 var apnError: Error? = nil var read: Bool? = try? self.pusher.readFailedIdentifier(identifier, apnError: apnError) if read == nil { return read! } if apnError != nil { var n: NWNotification? = self.notificationForIdentifier[(identifier)][0] if notification { notification = n ?? (NSNull() as? NWNotification) } if self.delegate.responds(to: Selector("notification:didFailWithError:")) { self.delegate.notification(n, didFailWithError: apnError) } if reconnect { try? self.reconnect() } } return true } /** Let go of old notification, after you read the failed notifications. This class keeps track of all notifications sent so we can look them up later based on their identifier. This allows it to translate identifiers back into the original notification. To limit the amount of memory all older notifications should be trimmed from this lookup, which is done by this method. This is done based on the `feedbackSpan`, which defaults to 30 seconds. Be careful not to call this function without first reading all failed notifications, using `readFailed:autoReconnect:error:`. @see readFailed:autoReconnect:error: @see feedbackSpan */ func trimIdentifiers() -> Bool { var oldBefore = Date(timeIntervalSinceNow: -self.feedbackSpan) var old: [Any] = Array(self.notificationForIdentifier.keysOfEntries(passingTest: {(_ key: Any, _ obj: Any, _ stop: Bool) -> BOOL in return oldBefore.compare(obj[1]) == .orderedDescending })) for k in old { self.notificationForIdentifier.removeValueForKey(k) } return !!old.count } // deprecated class func connect(with delegate: NWHubDelegate, identity: NWIdentityRef, error: Error?) -> Self { return try? self.connect(with: delegate, identity: identity, environment: NWEnvironmentAuto)! } class func connect(with delegate: NWHubDelegate, pkcs12Data data: Data, password: String, error: Error?) -> Self { return try? self.connect(with: delegate, identity: data, environment: NWEnvironmentAuto)! } func connect(withIdentity identity: NWIdentityRef) throws { return try? self.connect(withIdentity: identity, environment: NWEnvironmentAuto)! } func connect(withPKCS12Data data: Data, password: String) throws { return try? self.connect(withPKCS12Data: data, password: password, environment: NWEnvironmentAuto)! } var notificationForIdentifier = [AnyHashable: Any]() convenience override init() { return self.init(NWPusher(), delegate: nil) } // MARK: - Connecting // MARK: - Pushing without NSError // MARK: - Pushing with NSError func pushNotifications(_ notifications: [Any], autoReconnect reconnect: Bool) throws { for notification: NWNotification in notifications { var success: Bool? = try? self.push(notification, autoReconnect: reconnect) if success == nil { return success! } } return true } // MARK: - Reading failed func readFailed(_ notifications: [Any], max: Int, autoReconnect reconnect: Bool) throws { var n: [Any] = [] for i in 0..<max { var notification: NWNotification? = nil var read: Bool? = try? self.readFailed(notification, autoReconnect: reconnect) if read == nil { return read! } if notification == nil { break } n.append(notification) } if !notifications.isEmpty { notifications = n } self.trimIdentifiers() return true } // MARK: - Deprecated }
bsd-2-clause
sschiau/swift
validation-test/Sema/type_checker_perf/fast/rdar21398466.swift
3
5178
// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 // REQUIRES: OS=macosx // REQUIRES: asserts // REQUIRES: rdar48061151 // This problem is related to renaming, // as soon as `init(truncatingBitPattern:)` is changed // to `init(truncatingIfNeeded:)` this example is no longer "too complex" func getUInt8(u: UInt) -> [UInt8] { let values: [UInt8] values = [ UInt8(truncatingBitPattern: (u >> 1) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 2) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 3) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 4) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 1) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 2) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 3) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 4) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 1) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 2) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 3) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 4) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 1) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 2) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 3) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 4) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 1) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 2) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 3) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 4) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 1) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 2) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 3) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 4) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 1) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 2) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 3) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 4) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 1) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 2) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 3) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} UInt8(truncatingBitPattern: (u >> 4) & 0xf), // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}} ] return values }
apache-2.0
LawrenceHan/ActionStageSwift
ActionStageSwift/AppDelegate.swift
1
4569
// // AppDelegate.swift // ActionStageSwift // // Created by Hanguang on 2017/3/7. // Copyright © 2017年 Hanguang. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. LHWActor.registerActorClass(AddCellActor.self) LHWActor.registerActorClass(BlockActor.self) // let stageQueueSpecific = "com.hanguang.app.ActionStageSwift.StageDispatchQueue" // let stageQueueSpecificKey = DispatchSpecificKey<String>() // let mainStageQueue: DispatchQueue // let globalStageQueue: DispatchQueue // let highPriorityStageQueue: DispatchQueue // // // var str1: [String] = [] // var str2: [String] = [] // for i in 0..<30 { // str1.append("\(i)") // } // let item1: [String] = str1 // // for i in 30..<60 { // str2.append("\(i)") // } // let item2: [String] = str2 // // for text in item1 { // globalGraphQueue.async { // print(text) // } // } // // for text in item2 { // highPriorityGraphQueue.async { // print(text) // } // } // let house1Folks = ["Joe", "Jack", "Jill"]; // let house2Folks = ["Irma", "Irene", "Ian"]; // // let partyLine = DispatchQueue(label: "party line") // let house1Queue = DispatchQueue(label: "house 1", attributes: .concurrent, target: partyLine) // let house2Queue = DispatchQueue(label: "house 2", attributes: .concurrent, target: partyLine) // // for caller in house1Folks { // house1Queue.async { [unowned self] in // self.makeCall(queue: house1Queue, caller: caller, callees: house2Folks) // } // } // // for caller in house2Folks { // house2Queue.async { [unowned self] in // self.makeCall(queue: house1Queue, caller: caller, callees: house1Folks) // } // } return true } func makeCall(queue: DispatchQueue, caller: String, callees: [String]) { let targetIndex: Int = Int(arc4random()) % callees.count let callee = callees[targetIndex] print("\(caller) is calling \(callee)") sleep(1) print("...\(caller) is done calling \(callee)") queue.asyncAfter(deadline: .now() + (Double(Int(arc4random()) % 1000)) * 0.001) { [unowned self] in self.makeCall(queue: queue, caller: caller, callees: callees) } } 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
alexames/flatbuffers
swift/Sources/FlatBuffers/Constants.swift
1
3103
/* * Copyright 2021 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !os(WASI) #if os(Linux) import CoreFoundation #else import Foundation #endif #else import SwiftOverlayShims #endif /// A boolean to see if the system is littleEndian let isLitteEndian: Bool = { let number: UInt32 = 0x12345678 return number == number.littleEndian }() /// Constant for the file id length let FileIdLength = 4 /// Type aliases public typealias Byte = UInt8 public typealias UOffset = UInt32 public typealias SOffset = Int32 public typealias VOffset = UInt16 /// Maximum size for a buffer public let FlatBufferMaxSize = UInt32 .max << ((MemoryLayout<SOffset>.size * 8 - 1) - 1) /// Protocol that All Scalars should conform to /// /// Scalar is used to conform all the numbers that can be represented in a FlatBuffer. It's used to write/read from the buffer. public protocol Scalar: Equatable { associatedtype NumericValue var convertedEndian: NumericValue { get } } extension Scalar where Self: Verifiable {} extension Scalar where Self: FixedWidthInteger { /// Converts the value from BigEndian to LittleEndian /// /// Converts values to little endian on machines that work with BigEndian, however this is NOT TESTED yet. public var convertedEndian: NumericValue { self as! Self.NumericValue } } extension Double: Scalar, Verifiable { public typealias NumericValue = UInt64 public var convertedEndian: UInt64 { bitPattern.littleEndian } } extension Float32: Scalar, Verifiable { public typealias NumericValue = UInt32 public var convertedEndian: UInt32 { bitPattern.littleEndian } } extension Bool: Scalar, Verifiable { public var convertedEndian: UInt8 { self == true ? 1 : 0 } public typealias NumericValue = UInt8 } extension Int: Scalar, Verifiable { public typealias NumericValue = Int } extension Int8: Scalar, Verifiable { public typealias NumericValue = Int8 } extension Int16: Scalar, Verifiable { public typealias NumericValue = Int16 } extension Int32: Scalar, Verifiable { public typealias NumericValue = Int32 } extension Int64: Scalar, Verifiable { public typealias NumericValue = Int64 } extension UInt8: Scalar, Verifiable { public typealias NumericValue = UInt8 } extension UInt16: Scalar, Verifiable { public typealias NumericValue = UInt16 } extension UInt32: Scalar, Verifiable { public typealias NumericValue = UInt32 } extension UInt64: Scalar, Verifiable { public typealias NumericValue = UInt64 } public func FlatBuffersVersion_22_10_26() {}
apache-2.0
WhisperSystems/Signal-iOS
Signal/src/UserInterface/Notifications/AppNotifications.swift
1
27150
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import PromiseKit /// There are two primary components in our system notification integration: /// /// 1. The `NotificationPresenter` shows system notifications to the user. /// 2. The `NotificationActionHandler` handles the users interactions with these /// notifications. /// /// The NotificationPresenter is driven by the adapter pattern to provide a unified interface to /// presenting notifications on iOS9, which uses UINotifications vs iOS10+ which supports /// UNUserNotifications. /// /// The `NotificationActionHandler`s also need slightly different integrations for UINotifications /// vs. UNUserNotifications, but because they are integrated at separate system defined callbacks, /// there is no need for an Adapter, and instead the appropriate NotificationActionHandler is /// wired directly into the appropriate callback point. enum AppNotificationCategory: CaseIterable { case incomingMessage case incomingMessageFromNoLongerVerifiedIdentity case infoOrErrorMessage case threadlessErrorMessage case incomingCall case missedCall case missedCallFromNoLongerVerifiedIdentity } enum AppNotificationAction: CaseIterable { case answerCall case callBack case declineCall case markAsRead case reply case showThread } struct AppNotificationUserInfoKey { static let threadId = "Signal.AppNotificationsUserInfoKey.threadId" static let callBackAddress = "Signal.AppNotificationsUserInfoKey.callBackAddress" static let localCallId = "Signal.AppNotificationsUserInfoKey.localCallId" } extension AppNotificationCategory { var identifier: String { switch self { case .incomingMessage: return "Signal.AppNotificationCategory.incomingMessage" case .incomingMessageFromNoLongerVerifiedIdentity: return "Signal.AppNotificationCategory.incomingMessageFromNoLongerVerifiedIdentity" case .infoOrErrorMessage: return "Signal.AppNotificationCategory.infoOrErrorMessage" case .threadlessErrorMessage: return "Signal.AppNotificationCategory.threadlessErrorMessage" case .incomingCall: return "Signal.AppNotificationCategory.incomingCall" case .missedCall: return "Signal.AppNotificationCategory.missedCall" case .missedCallFromNoLongerVerifiedIdentity: return "Signal.AppNotificationCategory.missedCallFromNoLongerVerifiedIdentity" } } var actions: [AppNotificationAction] { switch self { case .incomingMessage: return [.markAsRead, .reply] case .incomingMessageFromNoLongerVerifiedIdentity: return [.markAsRead, .showThread] case .infoOrErrorMessage: return [.showThread] case .threadlessErrorMessage: return [] case .incomingCall: return [.answerCall, .declineCall] case .missedCall: return [.callBack, .showThread] case .missedCallFromNoLongerVerifiedIdentity: return [.showThread] } } } extension AppNotificationAction { var identifier: String { switch self { case .answerCall: return "Signal.AppNotifications.Action.answerCall" case .callBack: return "Signal.AppNotifications.Action.callBack" case .declineCall: return "Signal.AppNotifications.Action.declineCall" case .markAsRead: return "Signal.AppNotifications.Action.markAsRead" case .reply: return "Signal.AppNotifications.Action.reply" case .showThread: return "Signal.AppNotifications.Action.showThread" } } } // Delay notification of incoming messages when it's likely to be read by a linked device to // avoid notifying a user on their phone while a conversation is actively happening on desktop. let kNotificationDelayForRemoteRead: TimeInterval = 5 let kAudioNotificationsThrottleCount = 2 let kAudioNotificationsThrottleInterval: TimeInterval = 5 protocol NotificationPresenterAdaptee: class { func registerNotificationSettings() -> Promise<Void> func notify(category: AppNotificationCategory, title: String?, body: String, threadIdentifier: String?, userInfo: [AnyHashable: Any], sound: OWSSound?) func notify(category: AppNotificationCategory, title: String?, body: String, threadIdentifier: String?, userInfo: [AnyHashable: Any], sound: OWSSound?, replacingIdentifier: String?) func cancelNotifications(threadId: String) func clearAllNotifications() var hasReceivedSyncMessageRecently: Bool { get } } extension NotificationPresenterAdaptee { var hasReceivedSyncMessageRecently: Bool { return OWSDeviceManager.shared().hasReceivedSyncMessage(inLastSeconds: 60) } } @objc(OWSNotificationPresenter) public class NotificationPresenter: NSObject, NotificationsProtocol { private let adaptee: NotificationPresenterAdaptee @objc public override init() { if #available(iOS 10, *) { self.adaptee = UserNotificationPresenterAdaptee() } else { self.adaptee = LegacyNotificationPresenterAdaptee() } super.init() AppReadiness.runNowOrWhenAppDidBecomeReady { NotificationCenter.default.addObserver(self, selector: #selector(self.handleMessageRead), name: .incomingMessageMarkedAsRead, object: nil) } SwiftSingletons.register(self) } // MARK: - Dependencies var contactsManager: OWSContactsManager { return Environment.shared.contactsManager } var identityManager: OWSIdentityManager { return OWSIdentityManager.shared() } var preferences: OWSPreferences { return Environment.shared.preferences } var previewType: NotificationType { return preferences.notificationPreviewType() } // MARK: - // It is not safe to assume push token requests will be acknowledged until the user has // registered their notification settings. // // e.g. in the case that Background Fetch is disabled, token requests will be ignored until // we register user notification settings. // // For modern UNUserNotificationSettings, the registration takes a callback, so "waiting" for // notification settings registration is straight forward, however for legacy UIUserNotification // settings, the settings request is confirmed in the AppDelegate, where we call this method // to inform the adaptee it's safe to proceed. @objc public func didRegisterLegacyNotificationSettings() { guard let legacyAdaptee = adaptee as? LegacyNotificationPresenterAdaptee else { owsFailDebug("unexpected notifications adaptee: \(adaptee)") return } legacyAdaptee.didRegisterUserNotificationSettings() } @objc func handleMessageRead(notification: Notification) { AssertIsOnMainThread() switch notification.object { case let incomingMessage as TSIncomingMessage: Logger.debug("canceled notification for message: \(incomingMessage)") cancelNotifications(threadId: incomingMessage.uniqueThreadId) default: break } } // MARK: - Presenting Notifications func registerNotificationSettings() -> Promise<Void> { return adaptee.registerNotificationSettings() } func presentIncomingCall(_ call: SignalCall, callerName: String) { let remoteAddress = call.remoteAddress let thread = TSContactThread.getOrCreateThread(contactAddress: remoteAddress) let notificationTitle: String? let threadIdentifier: String? switch previewType { case .noNameNoPreview: notificationTitle = nil threadIdentifier = nil case .nameNoPreview, .namePreview: notificationTitle = callerName threadIdentifier = thread.uniqueId } let notificationBody = NotificationStrings.incomingCallBody let userInfo = [ AppNotificationUserInfoKey.threadId: thread.uniqueId, AppNotificationUserInfoKey.localCallId: call.localId.uuidString ] DispatchQueue.main.async { self.adaptee.notify(category: .incomingCall, title: notificationTitle, body: notificationBody, threadIdentifier: threadIdentifier, userInfo: userInfo, sound: .defaultiOSIncomingRingtone, replacingIdentifier: call.localId.uuidString) } } func presentMissedCall(_ call: SignalCall, callerName: String) { let remoteAddress = call.remoteAddress let thread = TSContactThread.getOrCreateThread(contactAddress: remoteAddress) let notificationTitle: String? let threadIdentifier: String? switch previewType { case .noNameNoPreview: notificationTitle = nil threadIdentifier = nil case .nameNoPreview, .namePreview: notificationTitle = callerName threadIdentifier = thread.uniqueId } let notificationBody = NotificationStrings.missedCallBody let userInfo: [String: Any] = [ AppNotificationUserInfoKey.threadId: thread.uniqueId, AppNotificationUserInfoKey.callBackAddress: remoteAddress ] DispatchQueue.main.async { let sound = self.requestSound(thread: thread) self.adaptee.notify(category: .missedCall, title: notificationTitle, body: notificationBody, threadIdentifier: threadIdentifier, userInfo: userInfo, sound: sound, replacingIdentifier: call.localId.uuidString) } } public func presentMissedCallBecauseOfNoLongerVerifiedIdentity(call: SignalCall, callerName: String) { let remoteAddress = call.remoteAddress let thread = TSContactThread.getOrCreateThread(contactAddress: remoteAddress) let notificationTitle: String? let threadIdentifier: String? switch previewType { case .noNameNoPreview: notificationTitle = nil threadIdentifier = nil case .nameNoPreview, .namePreview: notificationTitle = callerName threadIdentifier = thread.uniqueId } let notificationBody = NotificationStrings.missedCallBecauseOfIdentityChangeBody let userInfo = [ AppNotificationUserInfoKey.threadId: thread.uniqueId ] DispatchQueue.main.async { let sound = self.requestSound(thread: thread) self.adaptee.notify(category: .missedCallFromNoLongerVerifiedIdentity, title: notificationTitle, body: notificationBody, threadIdentifier: threadIdentifier, userInfo: userInfo, sound: sound, replacingIdentifier: call.localId.uuidString) } } public func presentMissedCallBecauseOfNewIdentity(call: SignalCall, callerName: String) { let remoteAddress = call.remoteAddress let thread = TSContactThread.getOrCreateThread(contactAddress: remoteAddress) let notificationTitle: String? let threadIdentifier: String? switch previewType { case .noNameNoPreview: notificationTitle = nil threadIdentifier = nil case .nameNoPreview, .namePreview: notificationTitle = callerName threadIdentifier = thread.uniqueId } let notificationBody = NotificationStrings.missedCallBecauseOfIdentityChangeBody let userInfo: [String: Any] = [ AppNotificationUserInfoKey.threadId: thread.uniqueId, AppNotificationUserInfoKey.callBackAddress: remoteAddress ] DispatchQueue.main.async { let sound = self.requestSound(thread: thread) self.adaptee.notify(category: .missedCall, title: notificationTitle, body: notificationBody, threadIdentifier: threadIdentifier, userInfo: userInfo, sound: sound, replacingIdentifier: call.localId.uuidString) } } public func notifyUser(for incomingMessage: TSIncomingMessage, in thread: TSThread, transaction: SDSAnyReadTransaction) { guard !thread.isMuted else { return } // While batch processing, some of the necessary changes have not been commited. let rawMessageText = incomingMessage.previewText(with: transaction) let messageText = rawMessageText.filterStringForDisplay() let senderName = contactsManager.displayName(for: incomingMessage.authorAddress) let notificationTitle: String? let threadIdentifier: String? switch previewType { case .noNameNoPreview: notificationTitle = nil threadIdentifier = nil case .nameNoPreview, .namePreview: switch thread { case is TSContactThread: notificationTitle = senderName case let groupThread as TSGroupThread: notificationTitle = String(format: NotificationStrings.incomingGroupMessageTitleFormat, senderName, groupThread.groupNameOrDefault) default: owsFailDebug("unexpected thread: \(thread)") return } threadIdentifier = thread.uniqueId } let notificationBody: String? switch previewType { case .noNameNoPreview, .nameNoPreview: notificationBody = NotificationStrings.incomingMessageBody case .namePreview: notificationBody = messageText } assert((notificationBody ?? notificationTitle) != nil) var category = AppNotificationCategory.incomingMessage // Don't reply from lockscreen if anyone in this conversation is // "no longer verified". for address in thread.recipientAddresses { if self.identityManager.verificationState(for: address) == .noLongerVerified { category = AppNotificationCategory.incomingMessageFromNoLongerVerifiedIdentity break } } let userInfo = [ AppNotificationUserInfoKey.threadId: thread.uniqueId ] DispatchQueue.main.async { let sound = self.requestSound(thread: thread) self.adaptee.notify(category: category, title: notificationTitle, body: notificationBody ?? "", threadIdentifier: threadIdentifier, userInfo: userInfo, sound: sound) } } public func notifyForFailedSend(inThread thread: TSThread) { let notificationTitle: String? switch previewType { case .noNameNoPreview: notificationTitle = nil case .nameNoPreview, .namePreview: notificationTitle = contactsManager.displayNameWithSneakyTransaction(thread: thread) } let notificationBody = NotificationStrings.failedToSendBody let threadId = thread.uniqueId let userInfo = [ AppNotificationUserInfoKey.threadId: threadId ] DispatchQueue.main.async { let sound = self.requestSound(thread: thread) self.adaptee.notify(category: .infoOrErrorMessage, title: notificationTitle, body: notificationBody, threadIdentifier: nil, // show ungrouped userInfo: userInfo, sound: sound) } } public func notifyUser(for errorMessage: TSErrorMessage, thread: TSThread, transaction: SDSAnyWriteTransaction) { notifyUser(for: errorMessage as TSMessage, thread: thread, wantsSound: true, transaction: transaction) } public func notifyUser(for infoMessage: TSInfoMessage, thread: TSThread, wantsSound: Bool, transaction: SDSAnyWriteTransaction) { notifyUser(for: infoMessage as TSMessage, thread: thread, wantsSound: wantsSound, transaction: transaction) } private func notifyUser(for infoOrErrorMessage: TSMessage, thread: TSThread, wantsSound: Bool, transaction: SDSAnyWriteTransaction) { let notificationTitle: String? let threadIdentifier: String? switch self.previewType { case .noNameNoPreview: notificationTitle = nil threadIdentifier = nil case .namePreview, .nameNoPreview: notificationTitle = contactsManager.displayName(for: thread, transaction: transaction) threadIdentifier = thread.uniqueId } let notificationBody = infoOrErrorMessage.previewText(with: transaction) let threadId = thread.uniqueId let userInfo = [ AppNotificationUserInfoKey.threadId: threadId ] transaction.addCompletion { let sound = wantsSound ? self.requestSound(thread: thread) : nil self.adaptee.notify(category: .infoOrErrorMessage, title: notificationTitle, body: notificationBody, threadIdentifier: threadIdentifier, userInfo: userInfo, sound: sound) } } public func notifyUser(for errorMessage: ThreadlessErrorMessage, transaction: SDSAnyWriteTransaction) { let notificationBody = errorMessage.previewText(with: transaction) transaction.addCompletion { let sound = self.checkIfShouldPlaySound() ? OWSSounds.globalNotificationSound() : nil self.adaptee.notify(category: .threadlessErrorMessage, title: nil, body: notificationBody, threadIdentifier: nil, userInfo: [:], sound: sound) } } @objc public func cancelNotifications(threadId: String) { self.adaptee.cancelNotifications(threadId: threadId) } @objc public func clearAllNotifications() { adaptee.clearAllNotifications() } // MARK: - var mostRecentNotifications = TruncatedList<UInt64>(maxLength: kAudioNotificationsThrottleCount) private func requestSound(thread: TSThread) -> OWSSound? { guard checkIfShouldPlaySound() else { return nil } return OWSSounds.notificationSound(for: thread) } private func checkIfShouldPlaySound() -> Bool { AssertIsOnMainThread() guard UIApplication.shared.applicationState == .active else { return true } guard preferences.soundInForeground() else { return false } let now = NSDate.ows_millisecondTimeStamp() let recentThreshold = now - UInt64(kAudioNotificationsThrottleInterval * Double(kSecondInMs)) let recentNotifications = mostRecentNotifications.filter { $0 > recentThreshold } guard recentNotifications.count < kAudioNotificationsThrottleCount else { return false } mostRecentNotifications.append(now) return true } } class NotificationActionHandler { static let shared: NotificationActionHandler = NotificationActionHandler() // MARK: - Dependencies var signalApp: SignalApp { return SignalApp.shared() } var messageSender: MessageSender { return SSKEnvironment.shared.messageSender } var callUIAdapter: CallUIAdapter { return AppEnvironment.shared.callService.callUIAdapter } var notificationPresenter: NotificationPresenter { return AppEnvironment.shared.notificationPresenter } private var databaseStorage: SDSDatabaseStorage { return SDSDatabaseStorage.shared } // MARK: - func answerCall(userInfo: [AnyHashable: Any]) throws -> Promise<Void> { guard let localCallIdString = userInfo[AppNotificationUserInfoKey.localCallId] as? String else { throw NotificationError.failDebug("localCallIdString was unexpectedly nil") } guard let localCallId = UUID(uuidString: localCallIdString) else { throw NotificationError.failDebug("unable to build localCallId. localCallIdString: \(localCallIdString)") } callUIAdapter.answerCall(localId: localCallId) return Promise.value(()) } func callBack(userInfo: [AnyHashable: Any]) throws -> Promise<Void> { guard let address = userInfo[AppNotificationUserInfoKey.callBackAddress] as? SignalServiceAddress else { throw NotificationError.failDebug("address was unexpectedly nil") } callUIAdapter.startAndShowOutgoingCall(address: address, hasLocalVideo: false) return Promise.value(()) } func declineCall(userInfo: [AnyHashable: Any]) throws -> Promise<Void> { guard let localCallIdString = userInfo[AppNotificationUserInfoKey.localCallId] as? String else { throw NotificationError.failDebug("localCallIdString was unexpectedly nil") } guard let localCallId = UUID(uuidString: localCallIdString) else { throw NotificationError.failDebug("unable to build localCallId. localCallIdString: \(localCallIdString)") } callUIAdapter.localHangupCall(localId: localCallId) return Promise.value(()) } private func threadWithSneakyTransaction(threadId: String) -> TSThread? { return databaseStorage.readReturningResult { transaction in return TSThread.anyFetch(uniqueId: threadId, transaction: transaction) } } func markAsRead(userInfo: [AnyHashable: Any]) throws -> Promise<Void> { guard let threadId = userInfo[AppNotificationUserInfoKey.threadId] as? String else { throw NotificationError.failDebug("threadId was unexpectedly nil") } guard let thread = threadWithSneakyTransaction(threadId: threadId) else { throw NotificationError.failDebug("unable to find thread with id: \(threadId)") } return markAsRead(thread: thread) } func reply(userInfo: [AnyHashable: Any], replyText: String) throws -> Promise<Void> { guard let threadId = userInfo[AppNotificationUserInfoKey.threadId] as? String else { throw NotificationError.failDebug("threadId was unexpectedly nil") } guard let thread = threadWithSneakyTransaction(threadId: threadId) else { throw NotificationError.failDebug("unable to find thread with id: \(threadId)") } return markAsRead(thread: thread).then { () -> Promise<Void> in let sendPromise = ThreadUtil.sendMessageNonDurably(text: replyText, thread: thread, quotedReplyModel: nil, messageSender: self.messageSender) return sendPromise.recover { error in Logger.warn("Failed to send reply message from notification with error: \(error)") self.notificationPresenter.notifyForFailedSend(inThread: thread) } } } func showThread(userInfo: [AnyHashable: Any]) throws -> Promise<Void> { guard let threadId = userInfo[AppNotificationUserInfoKey.threadId] as? String else { throw NotificationError.failDebug("threadId was unexpectedly nil") } // If this happens when the the app is not, visible we skip the animation so the thread // can be visible to the user immediately upon opening the app, rather than having to watch // it animate in from the homescreen. let shouldAnimate = UIApplication.shared.applicationState == .active signalApp.presentConversationAndScrollToFirstUnreadMessage(forThreadId: threadId, animated: shouldAnimate) return Promise.value(()) } private func markAsRead(thread: TSThread) -> Promise<Void> { return databaseStorage.writePromise { transaction in thread.markAllAsRead(with: transaction) } } } extension ThreadUtil { static var databaseStorage: SDSDatabaseStorage { return SSKEnvironment.shared.databaseStorage } class func sendMessageNonDurably(text: String, thread: TSThread, quotedReplyModel: OWSQuotedReplyModel?, messageSender: MessageSender) -> Promise<Void> { return Promise { resolver in self.databaseStorage.read { transaction in _ = self.sendMessageNonDurably(withText: text, in: thread, quotedReplyModel: quotedReplyModel, transaction: transaction, messageSender: messageSender, completion: resolver.resolve) } } } } enum NotificationError: Error { case assertionError(description: String) } extension NotificationError { static func failDebug(_ description: String) -> NotificationError { owsFailDebug(description) return NotificationError.assertionError(description: description) } } struct TruncatedList<Element> { let maxLength: Int private var contents: [Element] = [] init(maxLength: Int) { self.maxLength = maxLength } mutating func append(_ newElement: Element) { var newElements = self.contents newElements.append(newElement) self.contents = Array(newElements.suffix(maxLength)) } } extension TruncatedList: Collection { typealias Index = Int var startIndex: Index { return contents.startIndex } var endIndex: Index { return contents.endIndex } subscript (position: Index) -> Element { return contents[position] } func index(after i: Index) -> Index { return contents.index(after: i) } }
gpl-3.0
drumbart/SwiftyHTML
SwiftyHTML/Classes/Models/Protocols/StringRepresentable.swift
1
179
// // StringRepresentable.swift // Pods // // Created by Bartosz Tułodziecki on 19/10/2016. // // public protocol HTMLStringRepresentable { func htmlString() -> String }
mit
AbooJan/AJ_UIKit
AJ_UIKit/AJ_UIKit/Classes/CommonButton.swift
1
2201
// // CommonButton.swift // AJ_UIKit // // Created by aboojan on 16/4/10. // Copyright © 2016年 aboojan. All rights reserved. // import UIKit class CommonButton: UIButton { //MARK: 重写 override init(frame: CGRect) { super.init(frame: frame); setupView(); } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); setupView(); } override var backgroundColor: UIColor?{ didSet{ let btnImgSize = CGSizeMake(5.0, 5.0); let normalColor = backgroundColor; let highlightColor = darkedColor(normalColor!); let normalImg = imageWithColor(normalColor!, size: btnImgSize); let highlightImg = imageWithColor(highlightColor, size: btnImgSize); super.setBackgroundImage(normalImg, forState: .Normal); super.setBackgroundImage(highlightImg, forState: .Selected); super.setBackgroundImage(highlightImg, forState: .Highlighted) } } //MARK: 自定义 private func setupView() { self.layer.cornerRadius = CommonDefine().CORNER_RADIUS; self.layer.masksToBounds = true; } private func darkedColor(originalColor:UIColor) -> UIColor{ let components = CGColorGetComponents(originalColor.CGColor); let r = Float.init(components[0]); let g = Float.init(components[1]) - 0.2; let b = Float.init(components[2]) - 0.1; let changedColor = UIColor.init(colorLiteralRed: r, green: g, blue: b, alpha: 1.0); return changedColor; } private func imageWithColor(color:UIColor, size:CGSize) -> UIImage{ let rect = CGRectMake(0.0, 0.0, size.width, size.height); UIGraphicsBeginImageContext(rect.size); let context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, color.CGColor); CGContextFillRect(context, rect); let theImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return theImage; } }
mit
huonw/swift
validation-test/IDE/crashers_fixed/066-swift-conformancelookuptable-expandimpliedconformances.swift
79
144
// RUN: %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s class#^A^#{ protocol e:A protocol A:A protocol c:e
apache-2.0
iOSWizards/AwesomeMedia
Example/Pods/AwesomeCore/AwesomeCore/Classes/AwesomeCoreStorage.swift
1
705
// // AwesomeCoreStorage.swift // AwesomeCore // // Created by Leonardo Vinicius Kaminski Ferreira on 20/09/17. // import Foundation struct AwesomeCoreStorage { static var lastCourseId: Int { get { return UserDefaults.standard.integer(forKey: "AwesomeCoreLastCourseId") } set { UserDefaults.standard.set(newValue, forKey: "AwesomeCoreLastCourseId") } } static var isMembership: Bool { get { return UserDefaults.standard.bool(forKey: "AwesomeCoreUserMeIsMembership") } set { UserDefaults.standard.set(newValue, forKey: "AwesomeCoreUserMeIsMembership") } } }
mit
huonw/swift
test/IRGen/protocol_metadata.swift
1
7155
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s // REQUIRES: CPU=x86_64 protocol A { func a() } protocol B { func b() } protocol C : class { func c() } @objc protocol O { func o() } @objc protocol OPT { @objc optional func opt() @objc optional static func static_opt() @objc optional var prop: O { get } @objc optional subscript (x: O) -> O { get } } protocol AB : A, B { func ab() } protocol ABO : A, B, O { func abo() } // CHECK: @"$S17protocol_metadata1AMp" = hidden constant %swift.protocol { // -- size 72 // -- flags: 1 = Swift | 2 = Not Class-Constrained | 4 = Needs Witness Table // CHECK-SAME: i32 72, i32 7, // CHECK-SAME: i32 1, // CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint ([1 x %swift.protocol_requirement]* [[A_REQTS:@".*"]] to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.protocol, %swift.protocol* @"$S17protocol_metadata1AMp", i32 0, i32 11) to i64)) to i32) // CHECK-SAME: } // CHECK: @"$S17protocol_metadata1BMp" = hidden constant %swift.protocol { // CHECK-SAME: i32 72, i32 7, // CHECK-SAME: i32 1, // CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint ([1 x %swift.protocol_requirement]* [[B_REQTS:@".*"]] to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.protocol, %swift.protocol* @"$S17protocol_metadata1BMp", i32 0, i32 11) to i64)) to i32) // CHECK: } // CHECK: @"$S17protocol_metadata1CMp" = hidden constant %swift.protocol { // -- flags: 1 = Swift | 4 = Needs Witness Table // CHECK-SAME: i32 72, i32 5, // CHECK-SAME: i32 1, // CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint ([1 x %swift.protocol_requirement]* [[C_REQTS:@".*"]] to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.protocol, %swift.protocol* @"$S17protocol_metadata1CMp", i32 0, i32 11) to i64)) to i32) // CHECK-SAME: } // -- @objc protocol O uses ObjC symbol mangling and layout // CHECK: @_PROTOCOL__TtP17protocol_metadata1O_ = private constant { {{.*}} i32, [1 x i8*]*, i8*, i8* } { // CHECK-SAME: @_PROTOCOL_INSTANCE_METHODS__TtP17protocol_metadata1O_, // -- size, flags: 1 = Swift // CHECK-SAME: i32 96, i32 1 // CHECK-SAME: @_PROTOCOL_METHOD_TYPES__TtP17protocol_metadata1O_ // CHECK-SAME: } // CHECK: [[A_REQTS]] = internal constant [1 x %swift.protocol_requirement] [%swift.protocol_requirement { i32 17, i32 0, i32 0 }] // CHECK: [[B_REQTS]] = internal constant [1 x %swift.protocol_requirement] [%swift.protocol_requirement { i32 17, i32 0, i32 0 }] // CHECK: [[C_REQTS]] = internal constant [1 x %swift.protocol_requirement] [%swift.protocol_requirement { i32 17, i32 0, i32 0 }] // -- @objc protocol OPT uses ObjC symbol mangling and layout // CHECK: @_PROTOCOL__TtP17protocol_metadata3OPT_ = private constant { {{.*}} i32, [4 x i8*]*, i8*, i8* } { // CHECK-SAME: @_PROTOCOL_INSTANCE_METHODS_OPT__TtP17protocol_metadata3OPT_, // CHECK-SAME: @_PROTOCOL_CLASS_METHODS_OPT__TtP17protocol_metadata3OPT_, // -- size, flags: 1 = Swift // CHECK-SAME: i32 96, i32 1 // CHECK-SAME: @_PROTOCOL_METHOD_TYPES__TtP17protocol_metadata3OPT_ // CHECK-SAME: } // -- inheritance lists for refined protocols // CHECK: [[AB_INHERITED:@.*]] = private constant { {{.*}}* } { // CHECK: i64 2, // CHECK: %swift.protocol* @"$S17protocol_metadata1AMp", // CHECK: %swift.protocol* @"$S17protocol_metadata1BMp" // CHECK: } // CHECK: [[AB_REQTS:@".*"]] = internal constant [3 x %swift.protocol_requirement] [%swift.protocol_requirement zeroinitializer, %swift.protocol_requirement zeroinitializer, %swift.protocol_requirement { i32 17, i32 0, i32 0 }] // CHECK: @"$S17protocol_metadata2ABMp" = hidden constant %swift.protocol { // CHECK-SAME: [[AB_INHERITED]] // CHECK-SAME: i32 72, i32 7, // CHECK-SAME: i32 3, // CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint ([3 x %swift.protocol_requirement]* [[AB_REQTS]] to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.protocol, %swift.protocol* @"$S17protocol_metadata2ABMp", i32 0, i32 11) to i64)) to i32) // CHECK-SAME: } // CHECK: [[ABO_INHERITED:@.*]] = private constant { {{.*}}* } { // CHECK: i64 3, // CHECK: %swift.protocol* @"$S17protocol_metadata1AMp", // CHECK: %swift.protocol* @"$S17protocol_metadata1BMp", // CHECK: {{.*}}* @_PROTOCOL__TtP17protocol_metadata1O_ // CHECK: } protocol Comprehensive { associatedtype Assoc : A init() func instanceMethod() static func staticMethod() var instance: Assoc { get set } static var global: Assoc { get set } } // CHECK: [[COMPREHENSIVE_REQTS:@".*"]] = internal constant [11 x %swift.protocol_requirement] // CHECK-SAME: [%swift.protocol_requirement { i32 6, i32 0, i32 0 }, // CHECK-SAME: %swift.protocol_requirement { i32 7, i32 0, i32 0 }, // CHECK-SAME: %swift.protocol_requirement { i32 2, i32 0, i32 0 }, // CHECK-SAME: %swift.protocol_requirement { i32 17, i32 0, i32 0 }, // CHECK-SAME: %swift.protocol_requirement { i32 1, i32 0, i32 0 }, // CHECK-SAME: %swift.protocol_requirement { i32 19, i32 0, i32 0 }, // CHECK-SAME: %swift.protocol_requirement { i32 20, i32 0, i32 0 }, // CHECK-SAME: %swift.protocol_requirement { i32 21, i32 0, i32 0 }, // CHECK-SAME: %swift.protocol_requirement { i32 3, i32 0, i32 0 }, // CHECK-SAME: %swift.protocol_requirement { i32 4, i32 0, i32 0 }, // CHECK-SAME: %swift.protocol_requirement { i32 5, i32 0, i32 0 }] // CHECK: [[COMPREHENSIVE_ASSOC_NAME:@.*]] = private constant [6 x i8] c"Assoc\00" // CHECK: @"$S17protocol_metadata13ComprehensiveMp" = hidden constant %swift.protocol // CHECK-SAME: i32 72, i32 7, i32 11, // CHECK-SAME: [11 x %swift.protocol_requirement]* [[COMPREHENSIVE_REQTS]] // CHECK-SAME: i32 0 // CHECK-SAME: i32 trunc // CHECK-SAME: [6 x i8]* [[COMPREHENSIVE_ASSOC_NAME]] func reify_metadata<T>(_ x: T) {} // CHECK: define hidden swiftcc void @"$S17protocol_metadata0A6_types{{[_0-9a-zA-Z]*}}F" func protocol_types(_ a: A, abc: A & B & C, abco: A & B & C & O) { // CHECK: store %swift.protocol* @"$S17protocol_metadata1AMp" // CHECK: call %swift.type* @swift_getExistentialTypeMetadata(i1 true, %swift.type* null, i64 1, %swift.protocol** {{%.*}}) reify_metadata(a) // CHECK: store %swift.protocol* @"$S17protocol_metadata1AMp" // CHECK: store %swift.protocol* @"$S17protocol_metadata1BMp" // CHECK: store %swift.protocol* @"$S17protocol_metadata1CMp" // CHECK: call %swift.type* @swift_getExistentialTypeMetadata(i1 false, %swift.type* null, i64 3, %swift.protocol** {{%.*}}) reify_metadata(abc) // CHECK: store %swift.protocol* @"$S17protocol_metadata1AMp" // CHECK: store %swift.protocol* @"$S17protocol_metadata1BMp" // CHECK: store %swift.protocol* @"$S17protocol_metadata1CMp" // CHECK: [[O_REF:%.*]] = load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP17protocol_metadata1O_" // CHECK: [[O_REF_BITCAST:%.*]] = bitcast i8* [[O_REF]] to %swift.protocol* // CHECK: store %swift.protocol* [[O_REF_BITCAST]] // CHECK: call %swift.type* @swift_getExistentialTypeMetadata(i1 false, %swift.type* null, i64 4, %swift.protocol** {{%.*}}) reify_metadata(abco) }
apache-2.0
peteratseneca/dps923winter2015
Week_10/Places/Classes/CDStack.swift
1
6341
// // CDStack.swift // Classes // // Created by Peter McIntyre on 2015-02-01. // Copyright (c) 2015 School of ICT, Seneca College. All rights reserved. // import CoreData class CDStack { // MARK: - Public property with lazy initializer lazy var managedObjectContext: NSManagedObjectContext? = { // Create the MOC var moc = NSManagedObjectContext() // Configure it if self.persistentStoreCoordinator != nil { moc.persistentStoreCoordinator = self.persistentStoreCoordinator return moc } else { // If this code block executes, there's a problem in the MOM or PSC return nil } }() // MARK: - Internal properties with lazy initializers lazy private var applicationDocumentsDirectory: NSURL = { return NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as! NSURL }() lazy private var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // Create the PSC var psc: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) // Get the NSURL to the store file let storeURL: NSURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("ObjectStore.sqlite") // Configure lightweight migration let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true] // Prepare an error object var error: NSError? = nil // Configure the PSC with the store file if (psc!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: options, error: &error) == nil) { // This code block will run if there is an error assert(false, "Persistent store coordinator is nil") println("Persistent store coordinator could not be created (CDStack)") println("Error \(error), \(error!.userInfo)") } return psc }() lazy private var managedObjectModel: NSManagedObjectModel = { // Get the NSURL to the data model file let modelURL = NSBundle.mainBundle().URLForResource("ObjectModel", withExtension: "momd")! if let mom = NSManagedObjectModel(contentsOfURL: modelURL) { // Return the result return mom } else { // This code block will run if there is an error assert(false, "Managed object model is nil") println("Object model was not found (CDStack)") } }() // MARK: - Public methods // Save the managed object context func saveContext() { // Create an error object var error: NSError? = nil // If there are changes to save, attempt to save them if self.managedObjectContext!.hasChanges && !self.managedObjectContext!.save(&error) { // This code block will run if there is an error assert(false, "Unable to save the changes") println("Unable to save the changes (CDStack)") println("Error \(error), \(error!.userInfo)") } } // Fetched results controller factory func frcForEntityNamed(entityName: String, withPredicateFormat predicate: String?, predicateObject: [AnyObject]?, sortDescriptors: String?, andSectionNameKeyPath sectionName: String?) -> NSFetchedResultsController { // This method will create and return a fully-configured fetched results controller (frc) // Its arguments are simple strings, for entity name, predicate, and sort descriptors // sortDescriptors can be nil, or a comma-separated list of attribute-boolean (true or false) pairs // After initialization, the code can change the configuration if needed // Before using an frc, you must call the performFetch method // Create the fetch request //NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; var fetchRequest: NSFetchRequest = NSFetchRequest() // Configure the entity name let entity: NSEntityDescription = NSEntityDescription.entityForName(entityName, inManagedObjectContext: self.managedObjectContext!)! fetchRequest.entity = entity // Set the batch size to a reasonable number fetchRequest.fetchBatchSize = 20 // Configure the predicate if predicate != nil { fetchRequest.predicate = NSPredicate(format: predicate!, argumentArray: predicateObject!) } // Configure the sort descriptors if sortDescriptors != nil { // Create an array to accumulate the sort descriptors var sdArray: [NSSortDescriptor] = [] // Make an array from the passed-in string // Examples include... // nil // attribute1,true // attribute1,true,attribute2,false // etc. var sdStrings: [String] = sortDescriptors!.componentsSeparatedByString(",") // Iterate through the sdStrings array, and make sort descriptor objects for var i = 0; i < sdStrings.count; i+=2 { let sd: NSSortDescriptor = NSSortDescriptor(key: sdStrings[i], ascending: NSString(string: sdStrings[i + 1]).boolValue) // Add to the sort descriptors array sdArray.append(sd) } fetchRequest.sortDescriptors = sdArray } // Important note! // This factory does NOT configure a cache for the fetched results controller // Therefore, if your app is complex and you need the cache, // replace "nil" with "entityName" in the following statement return NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: sectionName, cacheName: nil) } }
mit
samwyndham/DictateSRS
Pods/CSV.swift/Sources/CSV+init.swift
1
1074
// // CSV+init.swift // CSV // // Created by Yasuhiro Hatta on 2016/06/13. // Copyright © 2016 yaslab. All rights reserved. // import Foundation extension CSV { // TODO: Documentation /// No overview available. public init( stream: InputStream, hasHeaderRow: Bool = defaultHasHeaderRow, trimFields: Bool = defaultTrimFields, delimiter: UnicodeScalar = defaultDelimiter) throws { try self.init(stream: stream, codecType: UTF8.self, hasHeaderRow: hasHeaderRow, trimFields: trimFields, delimiter: delimiter) } } extension CSV { // TODO: Documentation /// No overview available. public init( string: String, hasHeaderRow: Bool = defaultHasHeaderRow, trimFields: Bool = defaultTrimFields, delimiter: UnicodeScalar = defaultDelimiter) throws { let iterator = string.unicodeScalars.makeIterator() try self.init(iterator: iterator, hasHeaderRow: hasHeaderRow, trimFields: trimFields, delimiter: delimiter) } }
mit
StYaphet/firefox-ios
UITests/SecurityTests.swift
6
7029
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit import EarlGrey @testable import Client class SecurityTests: KIFTestCase { fileprivate var webRoot: String! override func setUp() { webRoot = SimplePageServer.start() BrowserUtils.configEarlGrey() BrowserUtils.dismissFirstRunUI() super.setUp() } override func beforeEach() { let testURL = "\(webRoot!)/localhostLoad.html" //enterUrl(url: testURL) BrowserUtils.enterUrlAddressBar(typeUrl: testURL) tester().waitForView(withAccessibilityLabel: "Web content") tester().waitForWebViewElementWithAccessibilityLabel("Session exploit") } /// Tap the Session exploit button, which tries to load the session restore page on localhost /// in the current tab. Make sure nothing happens. func testSessionExploit() { tester().tapWebViewElementWithAccessibilityLabel("Session exploit") tester().wait(forTimeInterval: 1) // Make sure the URL doesn't change. let webView = tester().waitForView(withAccessibilityLabel: "Web content") as! WKWebView XCTAssertEqual(webView.url!.path, "/localhostLoad.html") // Also make sure the XSS alert doesn't appear. XCTAssertFalse(tester().viewExistsWithLabel("Local page loaded")) } /// Tap the Error exploit button, which tries to load the error page on localhost /// in a new tab via window.open(). Make sure nothing happens. func testErrorExploit() { // We should only have one tab open. let tabcount:String? if BrowserUtils.iPad() { tabcount = tester().waitForView(withAccessibilityIdentifier: "TopTabsViewController.tabsButton")?.accessibilityValue } else { tabcount = tester().waitForView(withAccessibilityIdentifier: "TabToolbar.tabsButton")?.accessibilityValue } // make sure a new tab wasn't opened. tester().tapWebViewElementWithAccessibilityLabel("Error exploit") tester().wait(forTimeInterval: 1.0) let newTabcount:String? if BrowserUtils.iPad() { newTabcount = tester().waitForView(withAccessibilityIdentifier: "TopTabsViewController.tabsButton")?.accessibilityValue } else { newTabcount = tester().waitForView(withAccessibilityIdentifier: "TabToolbar.tabsButton")?.accessibilityValue } XCTAssert(tabcount != nil && tabcount == newTabcount) } /// Tap the New tab exploit button, which tries to piggyback off of an error page /// to load the session restore exploit. A new tab will load showing an error page, /// but we shouldn't be able to load session restore. func testWindowExploit() { tester().tapWebViewElementWithAccessibilityLabel("New tab exploit") tester().wait(forTimeInterval: 5) let webView = tester().waitForView(withAccessibilityLabel: "Web content") as! WKWebView // Make sure the URL doesn't change. XCTAssert(webView.url == nil) // Also make sure the XSS alert doesn't appear. XCTAssertFalse(tester().viewExistsWithLabel("Local page loaded")) } /// Tap the URL spoof button, which opens a new window to a host with an invalid port. /// Since the window has no origin before load, the page is able to modify the document, /// so make sure we don't show the URL. func testSpoofExploit() { tester().tapWebViewElementWithAccessibilityLabel("URL spoof") // Wait for the window to open. tester().waitForTappableView(withAccessibilityLabel: "Show Tabs", value: "2", traits: UIAccessibilityTraits.button) tester().waitForAnimationsToFinish() // Make sure the URL bar doesn't show the URL since it hasn't loaded. XCTAssertFalse(tester().viewExistsWithLabel("http://1.2.3.4:1234/")) // Since the newly opened tab doesn't have a URL/title we can't find its accessibility // element to close it in teardown. Workaround: load another page first. BrowserUtils.enterUrlAddressBar(typeUrl: webRoot!) } // For blob URLs, just show "blob:" to the user (see bug 1446227) func testBlobUrlShownAsSchemeOnly() { let url = "\(webRoot!)/blobURL.html" // script that will load a blob url BrowserUtils.enterUrlAddressBar(typeUrl: url) tester().wait(forTimeInterval: 1) let webView = tester().waitForView(withAccessibilityLabel: "Web content") as! WKWebView XCTAssert(webView.url!.absoluteString.starts(with: "blob:http://")) // webview internally has "blob:<rest of url>" let bvc = UIApplication.shared.keyWindow!.rootViewController?.children[0] as! BrowserViewController XCTAssertEqual(bvc.urlBar.locationView.urlTextField.text, "blob:") // only display "blob:" } // Web pages can't have firefox: urls, these should be used external to the app only (see bug 1447853) func testFirefoxSchemeBlockedOnWebpages() { let url = "\(webRoot!)/firefoxScheme.html" BrowserUtils.enterUrlAddressBar(typeUrl: url) tester().tapWebViewElementWithAccessibilityLabel("go") tester().wait(forTimeInterval: 1) let webView = tester().waitForView(withAccessibilityLabel: "Web content") as! WKWebView // Make sure the URL doesn't change. XCTAssertEqual(webView.url!.absoluteString, url) } func closeAllTabs() { let closeButtonMatchers: [GREYMatcher] = [grey_accessibilityID("TabTrayController.deleteButton.closeAll"), grey_kindOfClass(NSClassFromString("_UIAlertControllerActionView")!)] EarlGrey.selectElement(with: grey_accessibilityID("TabTrayController.removeTabsButton")).perform(grey_tap()) EarlGrey.selectElement(with: grey_allOf(closeButtonMatchers)).perform(grey_tap()) } func testDataURL() { // Check data urls that are valid ["data-url-ok-1", "data-url-ok-2"].forEach { buttonName in tester().tapWebViewElementWithAccessibilityLabel(buttonName) tester().wait(forTimeInterval: 1) let webView = tester().waitForView(withAccessibilityLabel: "Web content") as! WKWebView XCTAssert(webView.url!.absoluteString.hasPrefix("data:")) // indicates page loaded ok BrowserUtils.resetToAboutHome() beforeEach() } // Check data url that is not allowed tester().tapWebViewElementWithAccessibilityLabel("data-url-html-bad") tester().wait(forTimeInterval: 1) let webView = tester().waitForView(withAccessibilityLabel: "Web content") as! WKWebView XCTAssert(webView.url == nil) // indicates page load was blocked } override func tearDown() { BrowserUtils.resetToAboutHome() super.tearDown() } }
mpl-2.0
alsedi/RippleEffectView
Demo/RippleEffectDemo/RippleEffectView.swift
1
9981
// // RippleEffectView.swift // RippleEffectView // // Created by Alex Sergeev on 8/14/16. // Copyright © 2016 ALSEDI Group. All rights reserved. // // 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 UIKit enum RippleType { case oneWave case heartbeat } @IBDesignable class RippleEffectView: UIView { typealias CustomizationClosure = (_ totalRows:Int, _ totalColumns:Int, _ currentRow:Int, _ currentColumn:Int, _ originalImage:UIImage)->(UIImage) typealias VoidClosure = () -> () var cellSize:CGSize? var rippleType: RippleType = .oneWave var tileImage:UIImage! var magnitude: CGFloat = -0.6 var animationDuration: Double = 3.5 var isAnimating: Bool = false fileprivate var tiles = [GridItemView]() fileprivate var isGridRendered: Bool = false var tileImageCustomizationClosure: CustomizationClosure? = nil { didSet { stopAnimating() removeGrid() renderGrid() } } var animationDidStop: VoidClosure? func setupView() { if isAnimating { stopAnimating() } removeGrid() renderGrid() } } // MARK: View operations extension RippleEffectView { override func willMove(toSuperview newSuperview: UIView?) { if let parent = newSuperview, newSuperview != nil { self.frame = CGRect(x: 0, y: 0, width: parent.frame.width, height: parent.frame.height) } } override func layoutSubviews() { guard let parent = superview else { return } self.frame = CGRect(x: 0, y: 0, width: parent.frame.width, height: parent.frame.height) setupView() } } //MARK: Animations extension RippleEffectView { func stopAnimating() { isAnimating = false layer.removeAllAnimations() } func simulateAnimationEnd() { waitAndRun(animationDuration){ if let callback = self.animationDidStop { callback() } if self.isAnimating { self.simulateAnimationEnd() } } } func startAnimating() { guard superview != nil else { return } if isGridRendered == false { renderGrid() } isAnimating = true layer.shouldRasterize = true simulateAnimationEnd() for tile in tiles { let distance = self.distance(fromPoint:tile.position, toPoint:self.center) var vector = self.normalizedVector(fromPoint:tile.position, toPoint:self.center) vector = CGPoint(x:vector.x * magnitude * distance, y: vector.y * magnitude * distance) tile.startAnimatingWithDuration(animationDuration, rippleDelay: animationDuration - 0.0006666 * TimeInterval(distance), rippleOffset: vector) } } } //MARK: Grid operations extension RippleEffectView { func removeGrid() { for tile in tiles { tile.removeAllAnimations() tile.removeFromSuperlayer() } tiles.removeAll() isGridRendered = false } func renderGrid() { guard isGridRendered == false else { return } guard tileImage != nil else { return } isGridRendered = true let itemWidth = (cellSize == nil) ? tileImage.size.width : cellSize!.width let itemHeight = (cellSize == nil) ? tileImage.size.height : cellSize!.height let rows = ((self.rows % 2 == 0) ? self.rows + 3 : self.rows + 2) let columns = ((self.columns % 2 == 0) ? self.columns + 3 : self.columns + 2) let offsetX = columns / 2 let offsetY = rows / 2 let startPoint = CGPoint(x: center.x - (CGFloat(offsetX) * itemWidth), y: center.y - (CGFloat(offsetY) * itemHeight)) for row in 0..<rows { for column in 0..<columns { let tileLayer = GridItemView() if let imageCustomization = tileImageCustomizationClosure { tileLayer.tileImage = imageCustomization(self.rows, self.columns, row, column, (tileLayer.tileImage == nil) ? tileImage : tileLayer.tileImage!) tileLayer.contents = tileLayer.tileImage?.cgImage } else { tileLayer.contents = tileImage.cgImage } tileLayer.rippleType = rippleType tileLayer.frame.size = CGSize(width: itemWidth, height: itemHeight) tileLayer.contentsScale = contentScaleFactor tileLayer.contentsGravity = kCAGravityResize tileLayer.position = startPoint tileLayer.position.x = tileLayer.position.x + (CGFloat(column) * itemWidth) tileLayer.position.y = tileLayer.position.y + (CGFloat(row) * itemHeight) tileLayer.shouldRasterize = true layer.addSublayer(tileLayer) tiles.append(tileLayer) } } } var rows: Int { var size = tileImage.size if let _ = cellSize { size = cellSize! } return Int(self.frame.height / size.height) } var columns: Int { var size = tileImage.size if let _ = cellSize { size = cellSize! } return Int(self.frame.width / size.width) } } //MARK: Helper methods private extension UIView { func distance(fromPoint:CGPoint,toPoint:CGPoint)->CGFloat { let nX = (fromPoint.x - toPoint.x) let nY = (fromPoint.y - toPoint.y) return sqrt(nX*nX + nY*nY) } func normalizedVector(fromPoint:CGPoint,toPoint:CGPoint)->CGPoint { let length = distance(fromPoint:fromPoint, toPoint:toPoint) guard length > 0 else { return CGPoint.zero } return CGPoint(x:(fromPoint.x - toPoint.x)/length, y:(fromPoint.y - toPoint.y)/length) } } private class GridItemView: CALayer { var tileImage:UIImage? var rippleType:RippleType = .oneWave func startAnimatingWithDuration(_ duration: TimeInterval, rippleDelay: TimeInterval, rippleOffset: CGPoint) { let timingFunction = CAMediaTimingFunction(controlPoints: 0.25, 0, 0.2, 1) let linearFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) let zeroPointValue = NSValue(cgPoint: CGPoint.zero) var animations = [CAAnimation]() let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") if rippleType == .heartbeat { scaleAnimation.keyTimes = [0, 0.3, 0.4, 0.5, 0.6, 0.69, 0.735, 1] scaleAnimation.timingFunctions = [linearFunction, timingFunction, timingFunction, timingFunction, timingFunction, timingFunction] scaleAnimation.values = [1, 1, 1.35, 1.05, 1.20, 0.95, 1, 1] } else { scaleAnimation.keyTimes = [0, 0.5, 0.6, 1] scaleAnimation.values = [1, 1, 1.15, 1] scaleAnimation.timingFunctions = [linearFunction, timingFunction, timingFunction] } scaleAnimation.beginTime = 0.0 scaleAnimation.duration = duration animations.append(scaleAnimation) let positionAnimation = CAKeyframeAnimation(keyPath: "position") positionAnimation.duration = duration if rippleType == .heartbeat { let secondBeat = CGPoint(x:rippleOffset.x, y:rippleOffset.y) positionAnimation.timingFunctions = [linearFunction, timingFunction, timingFunction, timingFunction, timingFunction, linearFunction] positionAnimation.keyTimes = [0, 0.3, 0.4, 0.5, 0.6, 0.7, 0.75, 1] positionAnimation.values = [zeroPointValue, zeroPointValue, NSValue(cgPoint:rippleOffset), zeroPointValue, NSValue(cgPoint:secondBeat), NSValue(cgPoint:CGPoint(x:-rippleOffset.x*0.3,y:-rippleOffset.y*0.3)),zeroPointValue, zeroPointValue] } else { positionAnimation.timingFunctions = [linearFunction, timingFunction, timingFunction] positionAnimation.keyTimes = [0, 0.5, 0.6, 1] positionAnimation.values = [zeroPointValue, zeroPointValue, NSValue(cgPoint:rippleOffset), zeroPointValue] } positionAnimation.isAdditive = true animations.append(positionAnimation) let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") opacityAnimation.duration = duration if rippleType == .heartbeat { opacityAnimation.timingFunctions = [linearFunction, timingFunction, timingFunction, linearFunction] opacityAnimation.keyTimes = [0, 0.3, 0.4, 0.5, 0.6, 0.69, 1] opacityAnimation.values = [1, 1, 0.85, 0.75, 0.90, 1, 1] } else { opacityAnimation.timingFunctions = [linearFunction, timingFunction, timingFunction, linearFunction] opacityAnimation.keyTimes = [0, 0.5, 0.6, 0.94, 1] opacityAnimation.values = [1, 1, 0.45, 1, 1] } animations.append(opacityAnimation) let groupAnimation = CAAnimationGroup() groupAnimation.repeatCount = Float.infinity groupAnimation.fillMode = kCAFillModeBackwards groupAnimation.duration = duration groupAnimation.beginTime = rippleDelay groupAnimation.isRemovedOnCompletion = false groupAnimation.animations = animations groupAnimation.timeOffset = 0.35 * duration shouldRasterize = true add(groupAnimation, forKey: "ripple") } func stopAnimating() { removeAllAnimations() } } func waitAndRun(_ delay:Double, closure:@escaping ()->()) { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure) }
mit
puttin/Curator
Curator/CuratorLocation.swift
1
916
import Foundation public protocol CuratorLocation { func asURL() throws -> URL } extension CuratorLocation { func fileReferenceURL() throws -> URL { let url = try self.standardizedFileURL() as NSURL guard let fileReferenceURL = url.fileReferenceURL() else { throw Curator.Error.unableToObtainFileReferenceURL(from: self) } return fileReferenceURL as URL } func standardizedFileURL() throws -> URL { let location = self let url = try location.asURL() guard url.isFileURL else { throw Curator.Error.unableToConvertToFileURL(from: location) } let standardizedURL = url.standardized let path = standardizedURL.path guard !path.isEmpty else { throw Curator.Error.invalidLocation(location) } return standardizedURL } }
mit
dflax/CookieCrunch
CookieCrunch/Array2D.swift
1
521
// // Array2D.swift // CookieCrunch // // Created by Daniel Flax on 5/1/15. // Copyright (c) 2015 Daniel Flax. All rights reserved. // struct Array2D<T> { let columns: Int let rows: Int private var array: Array<T?> init(columns: Int, rows: Int) { self.columns = columns self.rows = rows array = Array<T?>(count: rows*columns, repeatedValue: nil) } subscript(column: Int, row: Int) -> T? { get { return array[row*columns + column] } set { array[row*columns + column] = newValue } } }
mit
simonwhitehouse/SWHQuickConstraints
Example/Example/AppDelegate.swift
1
2145
// // AppDelegate.swift // Example // // Created by Robert Nash on 27/09/2015. // Copyright © 2015 Robert Nash. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. 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 throttle down OpenGL ES frame rates. 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 inactive 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
artyom-stv/TextInputKit
Example/Example/macOS/Code/AppDelegate.swift
1
389
// // AppDelegate.swift // Example-macOS // // Created by Artem Starosvetskiy on 19/11/2016. // Copyright © 2016 Artem Starosvetskiy. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } }
mit
Alexiuce/Tip-for-day
XCWebook/XCWebook/DIVModel.swift
1
761
// // DIVModel.swift // XCWebook // // Created by alexiuce  on 2017/8/15. // Copyright © 2017年 alexiuce . All rights reserved. // import UIKit class DIVModel: NSObject { var href = "" var text = "" init(div: String) { super.init() let begingRange = (div as NSString).range(of: "href=") let endRange = (div as NSString).range(of: "</a>") let hrefLocation = begingRange.location + begingRange.length + 1 href = (div as NSString).substring(with: NSMakeRange(hrefLocation, 20)) let textLocation = hrefLocation + 22 let textLenght = endRange.location - textLocation text = (div as NSString).substring(with: NSMakeRange(textLocation, textLenght)) } }
mit
justinhester/hacking-with-swift
src/Project14/Project14/AppDelegate.swift
1
2165
// // AppDelegate.swift // Project14 // // Created by Justin Lawrence Hester on 2/1/16. // Copyright © 2016 Justin Lawrence Hester. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. 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 throttle down OpenGL ES frame rates. 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 inactive 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:. } }
gpl-3.0
mspvirajpatel/SwiftyBase
SwiftyBase/Classes/SwiftImageLoader/UIImageViewExtensions.swift
1
11124
#if os(iOS) import UIKit // MARK: - UIImageView Associated Value Keys fileprivate var indexPathIdentifierAssociationKey: UInt8 = 0 fileprivate var completionAssociationKey: UInt8 = 0 // MARK: - UIImageView Extensions extension UIImageView: AssociatedValue {} public extension UIImageView { // MARK: - Associated Values final internal var indexPathIdentifier: Int { get { return getAssociatedValue(key: &indexPathIdentifierAssociationKey, defaultValue: -1) } set { setAssociatedValue(key: &indexPathIdentifierAssociationKey, value: newValue) } } final internal var completion: ((_ finished: Bool, _ error: Error?) -> Void)? { get { return getAssociatedValue(key: &completionAssociationKey, defaultValue: nil) } set { setAssociatedValue(key: &completionAssociationKey, value: newValue) } } // MARK: - Image Loading Methods /** Asynchronously downloads an image and loads it into the `UIImageView` using a URL `String`. - parameter urlString: The image URL in the form of a `String`. - parameter placeholder: `UIImage?` representing a placeholder image that is loaded into the view while the asynchronous download takes place. The default value is `nil`. - parameter completion: An optional closure that is called to indicate completion of the intended purpose of this method. It returns two values: the first is a `Bool` indicating whether everything was successful, and the second is `Error?` which will be non-nil should an error occur. The default value is `nil`. */ final func loadImage(urlString: String, placeholder: UIImage? = nil, completion: ((_ success: Bool, _ error: Error?) -> Void)? = nil) { guard let url = URL(string: urlString) else { DispatchQueue.main.async { completion?(false, nil) } return } loadImage(url: url, placeholder: placeholder, completion: completion) } /** Asynchronously downloads an image and loads it into the `UIImageView` using a `URL`. - parameter url: The image `URL`. - parameter placeholder: `UIImage?` representing a placeholder image that is loaded into the view while the asynchronous download takes place. The default value is `nil`. - parameter completion: An optional closure that is called to indicate completion of the intended purpose of this method. It returns two values: the first is a `Bool` indicating whether everything was successful, and the second is `Error?` which will be non-nil should an error occur. The default value is `nil`. */ final func loadImage(url: URL, placeholder: UIImage? = nil, completion: ((_ success: Bool, _ error: Error?) -> Void)? = nil) { let cacheManager = ImageCacheManager.shared var request = URLRequest(url: url, cachePolicy: cacheManager.session.configuration.requestCachePolicy, timeoutInterval: cacheManager.session.configuration.timeoutIntervalForRequest) request.addValue("image/*", forHTTPHeaderField: "Accept") loadImage(request: request, placeholder: placeholder, completion: completion) } /** Asynchronously downloads an image and loads it into the `UIImageView` using a `URLRequest`. - parameter request: The image URL in the form of a `URLRequest`. - parameter placeholder: `UIImage?` representing a placeholder image that is loaded into the view while the asynchronous download takes place. The default value is `nil`. - parameter completion: An optional closure that is called to indicate completion of the intended purpose of this method. It returns two values: the first is a `Bool` indicating whether everything was successful, and the second is `Error?` which will be non-nil should an error occur. The default value is `nil`. */ final func loadImage(request: URLRequest, placeholder: UIImage? = nil, completion: ((_ success: Bool, _ error: Error?) -> Void)? = nil) { self.completion = completion self.indexPathIdentifier = -1 guard let urlAbsoluteString = request.url?.absoluteString else { self.completion?(false, nil) return } let cacheManager = ImageCacheManager.shared let fadeAnimationDuration = cacheManager.fadeAnimationDuration let sharedURLCache = URLCache.shared func loadImage(_ image: UIImage) -> Void { UIView.transition(with: self, duration: fadeAnimationDuration, options: .transitionCrossDissolve, animations: { self.image = image }) self.completion?(true, nil) } // If there's already a cached image, load it into the image view. if let image = cacheManager[urlAbsoluteString] { loadImage(image) } // If there's already a cached response, load the image data into the image view. else if let cachedResponse = sharedURLCache.cachedResponse(for: request), let image = UIImage(data: cachedResponse.data), let creationTimestamp = cachedResponse.userInfo?["creationTimestamp"] as? CFTimeInterval, (Date.timeIntervalSinceReferenceDate - creationTimestamp) < Double(cacheManager.diskCacheMaxAge) { loadImage(image) cacheManager[urlAbsoluteString] = image } // Either begin downloading the image or become an observer for an existing request. else { // Remove the stale disk-cached response (if any). sharedURLCache.removeCachedResponse(for: request) // Set the placeholder image if it was provided. if let placeholder = placeholder { self.image = placeholder } var parentView = self.superview // Should the image be shown in a cell, walk the view hierarchy to retrieve the index path from the tableview or collectionview. while parentView != nil { switch parentView { case let tableViewCell as UITableViewCell: // Every tableview cell must be directly embedded within a tableview. if let tableView = tableViewCell.superview as? UITableView, let indexPath = tableView.indexPathForRow(at: tableViewCell.center) { self.indexPathIdentifier = indexPath.hashValue } case let collectionViewCell as UICollectionViewCell: // Every collectionview cell must be directly embedded within a collectionview. if let collectionView = collectionViewCell.superview as? UICollectionView, let indexPath = collectionView.indexPathForItem(at: collectionViewCell.center) { self.indexPathIdentifier = indexPath.hashValue } default: break } parentView = parentView?.superview } let initialIndexIdentifier = self.indexPathIdentifier // If the image isn't already being downloaded, begin downloading the image. if cacheManager.isDownloadingFromURL(urlAbsoluteString) == false { cacheManager.setIsDownloadingFromURL(true, urlString: urlAbsoluteString) let dataTask = cacheManager.session.dataTask(with: request) { taskData, taskResponse, taskError in guard let data = taskData, let response = taskResponse, let image = UIImage(data: data), taskError == nil else { DispatchQueue.main.async { cacheManager.setIsDownloadingFromURL(false, urlString: urlAbsoluteString) cacheManager.removeImageCacheObserversForKey(urlAbsoluteString) self.completion?(false, taskError) } return } DispatchQueue.main.async { if initialIndexIdentifier == self.indexPathIdentifier { UIView.transition(with: self, duration: fadeAnimationDuration, options: .transitionCrossDissolve, animations: { self.image = image }) } cacheManager[urlAbsoluteString] = image let responseDataIsCacheable = cacheManager.diskCacheMaxAge > 0 && Double(data.count) <= 0.05 * Double(sharedURLCache.diskCapacity) && (cacheManager.session.configuration.requestCachePolicy == .returnCacheDataElseLoad || cacheManager.session.configuration.requestCachePolicy == .returnCacheDataDontLoad) && (request.cachePolicy == .returnCacheDataElseLoad || request.cachePolicy == .returnCacheDataDontLoad) if let httpResponse = response as? HTTPURLResponse, let url = httpResponse.url, responseDataIsCacheable { if var allHeaderFields = httpResponse.allHeaderFields as? [String: String] { allHeaderFields["Cache-Control"] = "max-age=\(cacheManager.diskCacheMaxAge)" if let cacheControlResponse = HTTPURLResponse(url: url, statusCode: httpResponse.statusCode, httpVersion: "HTTP/1.1", headerFields: allHeaderFields) { let cachedResponse = CachedURLResponse(response: cacheControlResponse, data: data, userInfo: ["creationTimestamp": Date.timeIntervalSinceReferenceDate], storagePolicy: .allowed) sharedURLCache.storeCachedResponse(cachedResponse, for: request) } } } self.completion?(true, nil) } } dataTask.resume() } // Since the image is already being downloaded and hasn't been cached, register the image view as a cache observer. else { weak var weakSelf = self cacheManager.addImageCacheObserver(weakSelf!, initialIndexIdentifier: initialIndexIdentifier, key: urlAbsoluteString) } } } } #endif
mit
hovansuit/FoodAndFitness
FoodAndFitness/Controllers/Analysis/AnalysisViewModel.swift
1
6944
// // AnalysisViewModel.swift // FoodAndFitness // // Created by Mylo Ho on 4/30/17. // Copyright © 2017 SuHoVan. All rights reserved. // import UIKit import RealmS import RealmSwift import SwiftDate fileprivate enum FoodNutritionType { case calories case protein case carbs case fat } fileprivate enum ExerciseType { case calories case duration } fileprivate enum TrackingType { case calories case duration case distance } class AnalysisViewModel { private var eatenCalories: [Int] = [Int]() private var burnedCalories: [Int] = [Int]() private var proteins: [Int] = [Int]() private var carbs: [Int] = [Int]() private var fat: [Int] = [Int]() private var durations: [Int] = [Int]() private var distances: [Int] = [Int]() init() { let now = DateInRegion(absoluteDate: Date()) for i in 0..<7 { let date = now - (7 - i).days let eaten = AnalysisViewModel.nutritionValue(at: date.absoluteDate, type: .calories) let burned = AnalysisViewModel.burnedCalories(at: date.absoluteDate) let protein = AnalysisViewModel.nutritionValue(at: date.absoluteDate, type: .protein) let carbs = AnalysisViewModel.nutritionValue(at: date.absoluteDate, type: .carbs) let fat = AnalysisViewModel.nutritionValue(at: date.absoluteDate, type: .fat) let durationsValue = AnalysisViewModel.durationFitness(at: date.absoluteDate) let distancesValue = AnalysisViewModel.distanceFitness(at: date.absoluteDate) self.eatenCalories.append(eaten) self.burnedCalories.append(burned) self.proteins.append(protein) self.carbs.append(carbs) self.fat.append(fat) self.durations.append(durationsValue) self.distances.append(distancesValue) } } func dataForChartView() -> ChartViewCell.Data { return ChartViewCell.Data(eatenCalories: eatenCalories, burnedCalories: burnedCalories) } func dataForFitnessCell() -> AnalysisFitnessCell.Data? { let caloriesBurnSum = burnedCalories.reduce(0) { (result, value) -> Int in return result + value } let calories = "\(caloriesBurnSum)\(Strings.kilocalories)" let durationsSum = durations.reduce(0) { (result, value) -> Int in return result + value } let minutes = durationsSum.toMinutes var duration = "" if minutes < 1 { duration = "\(durationsSum)\(Strings.seconds)" } else { duration = "\(minutes)\(Strings.minute)" } let distanceSum = distances.reduce(0) { (result, value) -> Int in return result + value } let distance = "\(distanceSum)\(Strings.metters)" return AnalysisFitnessCell.Data(calories: calories, duration: duration, distance: distance) } func dataForNutritionCell() -> AnalysisNutritionCell.Data? { let caloriesSum = eatenCalories.reduce(0) { (result, value) -> Int in return result + value } let calories = "\(caloriesSum)\(Strings.kilocalories)" let proteinSum = proteins.reduce(0) { (result, value) -> Int in return result + value } let protein = "\(proteinSum)\(Strings.gam)" let carbsSum = self.carbs.reduce(0) { (result, value) -> Int in return result + value } let carbs = "\(carbsSum)\(Strings.gam)" let fatSum = self.fat.reduce(0) { (result, value) -> Int in return result + value } let fat = "\(fatSum)\(Strings.gam)" return AnalysisNutritionCell.Data(calories: calories, protein: protein, carbs: carbs, fat: fat) } private class func exerciseValue(at date: Date, type: ExerciseType) -> Int { let userExercises = RealmS().objects(UserExercise.self).filter { (userExercise) -> Bool in guard let me = User.me, let user = userExercise.userHistory?.user else { return false } return me.id == user.id && userExercise.createdAt.isInSameDayOf(date: date) } let value = userExercises.map { (userExercise) -> Int in switch type { case .calories: return userExercise.calories case .duration: return userExercise.duration } }.reduce(0) { (result, value) -> Int in return result + value } return value } private class func trackingValue(at date: Date, type: TrackingType) -> Int { let trackings = RealmS().objects(Tracking.self).filter { (tracking) -> Bool in guard let me = User.me, let user = tracking.userHistory?.user else { return false } return me.id == user.id && tracking.createdAt.isInSameDayOf(date: date) } let value = trackings.map { (tracking) -> Int in switch type { case .calories: return tracking.caloriesBurn case .duration: return tracking.duration case .distance: return tracking.distance } }.reduce(0) { (result, value) -> Int in return result + value } return value } private class func nutritionValue(at date: Date, type: FoodNutritionType) -> Int { let userFoods = RealmS().objects(UserFood.self).filter { (userFood) -> Bool in guard let me = User.me, let user = userFood.userHistory?.user else { return false } return me.id == user.id && userFood.createdAt.isInSameDayOf(date: date) } let value = userFoods.map { (userFood) -> Int in switch type { case .calories: return userFood.calories case .protein: return userFood.protein case .carbs: return userFood.carbs case .fat: return userFood.fat } }.reduce(0) { (result, value) -> Int in return result + value } return value } private class func burnedCalories(at date: Date) -> Int { let exercisesBurn = AnalysisViewModel.exerciseValue(at: date, type: .calories) let trackingsBurn = AnalysisViewModel.trackingValue(at: date, type: .calories) return exercisesBurn + trackingsBurn } private class func durationFitness(at date: Date) -> Int { let exerciseDuration = AnalysisViewModel.exerciseValue(at: date, type: .duration) let trackingDuration = AnalysisViewModel.trackingValue(at: date, type: .duration) return exerciseDuration + trackingDuration } private class func distanceFitness(at date: Date) -> Int { let distace = AnalysisViewModel.trackingValue(at: date, type: .distance) return distace } }
mit
stripe/stripe-ios
StripePaymentSheet/StripePaymentSheet/Internal/Link/Controllers/PayWithLinkViewController-WalletViewModel.swift
1
9638
// // PayWithLinkViewController-WalletViewModel.swift // StripePaymentSheet // // Created by Ramon Torres on 3/30/22. // Copyright © 2022 Stripe, Inc. All rights reserved. // import Foundation @_spi(STP) import StripeUICore @_spi(STP) import StripePaymentsUI protocol PayWithLinkWalletViewModelDelegate: AnyObject { func viewModelDidChange(_ viewModel: PayWithLinkViewController.WalletViewModel) } extension PayWithLinkViewController { final class WalletViewModel { let context: Context let linkAccount: PaymentSheetLinkAccount private(set) var paymentMethods: [ConsumerPaymentDetails] weak var delegate: PayWithLinkWalletViewModelDelegate? /// Index of currently selected payment method. var selectedPaymentMethodIndex: Int { didSet { if oldValue != selectedPaymentMethodIndex { delegate?.viewModelDidChange(self) } } } var supportedPaymentMethodTypes: Set<ConsumerPaymentDetails.DetailsType> { return linkAccount.supportedPaymentDetailsTypes(for: context.intent) } var cvc: String? { didSet { if oldValue != cvc { delegate?.viewModelDidChange(self) } } } var expiryDate: CardExpiryDate? { didSet { if oldValue != expiryDate { delegate?.viewModelDidChange(self) } } } /// Currently selected payment method. var selectedPaymentMethod: ConsumerPaymentDetails? { guard paymentMethods.indices.contains(selectedPaymentMethodIndex) else { return nil } return paymentMethods[selectedPaymentMethodIndex] } /// Whether or not the view should show the instant debit mandate text. var shouldShowInstantDebitMandate: Bool { switch selectedPaymentMethod?.details { case .bankAccount(_): // Instant debit mandate should be shown when paying with bank account. return true default: return false } } var noticeText: String? { if shouldRecollectCardExpiryDate { return STPLocalizedString( "This card has expired. Update your card info or choose a different payment method.", "A text notice shown when the user selects an expired card." ) } if shouldRecollectCardCVC { return STPLocalizedString( "For security, please re-enter your card’s security code.", """ A text notice shown when the user selects a card that requires re-entering the security code (CVV/CVC). """ ) } return nil } var shouldShowNotice: Bool { return noticeText != nil } var shouldShowRecollectionSection: Bool { return ( shouldRecollectCardCVC || shouldRecollectCardExpiryDate ) } var shouldShowApplePayButton: Bool { return ( context.shouldOfferApplePay && context.configuration.isApplePayEnabled ) } var shouldUseCompactConfirmButton: Bool { // We should use a compact confirm button whenever we display the Apple Pay button. return shouldShowApplePayButton } var cancelButtonConfiguration: Button.Configuration { return shouldShowApplePayButton ? .linkPlain() : .linkSecondary() } /// Whether or not we must re-collect the card CVC. var shouldRecollectCardCVC: Bool { switch selectedPaymentMethod?.details { case .card(let card): return card.shouldRecollectCardCVC || card.hasExpired default: // Only cards have CVC. return false } } var shouldRecollectCardExpiryDate: Bool { switch selectedPaymentMethod?.details { case .card(let card): return card.hasExpired case .bankAccount(_), .none: // Only cards have expiry date. return false } } /// CTA var confirmButtonCallToAction: ConfirmButton.CallToActionType { return context.intent.callToAction } var confirmButtonStatus: ConfirmButton.Status { if selectedPaymentMethod == nil { return .disabled } if !selectedPaymentMethodIsSupported { // Selected payment method not supported return .disabled } if shouldRecollectCardCVC && cvc == nil { return .disabled } if shouldRecollectCardExpiryDate && expiryDate == nil { return .disabled } return .enabled } var cardBrand: STPCardBrand? { switch selectedPaymentMethod?.details { case .card(let card): return card.brand default: return nil } } var selectedPaymentMethodIsSupported: Bool { guard let selectedPaymentMethod = selectedPaymentMethod else { return false } return supportedPaymentMethodTypes.contains(selectedPaymentMethod.type) } init( linkAccount: PaymentSheetLinkAccount, context: Context, paymentMethods: [ConsumerPaymentDetails] ) { self.linkAccount = linkAccount self.context = context self.paymentMethods = paymentMethods self.selectedPaymentMethodIndex = Self.determineInitiallySelectedPaymentMethod( context: context, paymentMethods: paymentMethods ) } func deletePaymentMethod(at index: Int, completion: @escaping (Result<Void, Error>) -> Void) { let paymentMethod = paymentMethods[index] linkAccount.deletePaymentDetails(id: paymentMethod.stripeID) { [self] result in switch result { case .success: paymentMethods.remove(at: index) delegate?.viewModelDidChange(self) case .failure(_): break } completion(result) } } func setDefaultPaymentMethod( at index: Int, completion: @escaping (Result<ConsumerPaymentDetails, Error>) -> Void ) { let paymentMethod = paymentMethods[index] linkAccount.updatePaymentDetails( id: paymentMethod.stripeID, updateParams: UpdatePaymentDetailsParams(isDefault: true, details: nil) ) { [self] result in if case let .success(updatedPaymentDetails) = result { paymentMethods.forEach({ $0.isDefault = false }) paymentMethods[index] = updatedPaymentDetails } completion(result) } } func updatePaymentMethod(_ paymentMethod: ConsumerPaymentDetails) -> Int? { guard let index = paymentMethods.firstIndex(where: {$0.stripeID == paymentMethod.stripeID}) else { return nil } if paymentMethod.isDefault { paymentMethods.forEach({ $0.isDefault = false }) } paymentMethods[index] = paymentMethod delegate?.viewModelDidChange(self) return index } func updateExpiryDate(completion: @escaping (Result<ConsumerPaymentDetails, Error>) -> Void) { guard let id = selectedPaymentMethod?.stripeID, let expiryDate = self.expiryDate else { assertionFailure("Called with no selected payment method or expiry date provided.") return } linkAccount.updatePaymentDetails( id: id, updateParams: UpdatePaymentDetailsParams(details: .card(expiryDate: expiryDate)), completion: completion ) } } } private extension PayWithLinkViewController.WalletViewModel { static func determineInitiallySelectedPaymentMethod( context: PayWithLinkViewController.Context, paymentMethods: [ConsumerPaymentDetails] ) -> Int { var indexOfLastAddedPaymentMethod: Int? { guard let lastAddedID = context.lastAddedPaymentDetails?.stripeID else { return nil } return paymentMethods.firstIndex(where: { $0.stripeID == lastAddedID }) } var indexOfDefaultPaymentMethod: Int? { return paymentMethods.firstIndex(where: { $0.isDefault }) } return indexOfLastAddedPaymentMethod ?? indexOfDefaultPaymentMethod ?? 0 } } /// Helper functions for ConsumerPaymentDetails private extension ConsumerPaymentDetails { var paymentMethodType: PaymentSheet.PaymentMethodType { switch details { case .card: return .card case .bankAccount: return .linkInstantDebit } } }
mit
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Controller/SLVBaseStatusHiddenController.swift
1
587
// // SLVBaseStatusHiddenController.swift // selluv-ios // // Created by 조백근 on 2017. 2. 17.. // Copyright © 2017년 BitBoy Labs. All rights reserved. // import Foundation import UIKit class SLVBaseStatusHiddenController: SLVBaseController { override func viewDidLoad() { super.viewDidLoad() self.setupNavigationHeight() } override var prefersStatusBarHidden: Bool { return true } func setupNavigationHeight() { self.navigationBar?.barHeight = 64 _ = self.navigationBar?.sizeThatFits(.zero) } }
mit
yisimeng/YSMFactory-swift
YSMFactory-swift/Vendor/YSMWaterFallFlowLayout/YSMWaterFallFlowReadMe.swift
1
2853
// // YSMWaterFallFlowReadMe.swift // YSMFactory-swift // // Created by 忆思梦 on 2016/12/8. // Copyright © 2016年 忆思梦. All rights reserved. // /* 瀑布流布局快速使用 class ViewController: UIViewController { //item的信息(现在为每个item的高度) var modelArray:[CGFloat] = [CGFloat]() var collectionView:UICollectionView! override func viewDidLoad() { super.viewDidLoad() automaticallyAdjustsScrollViewInsets = false let flowLayout = YSMFlowLayout() //最小的行间距 flowLayout.minimumLineSpacing = 10 //最小的列间距 flowLayout.minimumInteritemSpacing = 10 //内边距 flowLayout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) //设置数据源 flowLayout.dataSource = self collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height), collectionViewLayout: flowLayout) collectionView.dataSource = self collectionView.backgroundColor = .white collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCellId") view.addSubview(collectionView) let blackView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) blackView.backgroundColor = .black view.addSubview(blackView) let tap = UITapGestureRecognizer(target: self, action: #selector(tapg)) blackView.addGestureRecognizer(tap) loadData() } func loadData() { for _ in 0...4 { let num = CGFloat(arc4random_uniform(200)+50) modelArray.append(num) } collectionView.reloadData() } func tapg() { loadData() } } extension ViewController:UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 2 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return modelArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCellId", for: indexPath) cell.backgroundColor = UIColor.randomColor() return cell } } extension ViewController : YSMWaterFallLayoutDataSource{ //返回列数 func numberOfRows(in layout: YSMFlowLayout) -> Int { return 2 } //获取每个item的高度 func layout(_ layout: YSMFlowLayout, heightForRowAt indexPath: IndexPath) -> CGFloat { return modelArray[indexPath.row] } } */
mit
aidenluo177/GitHubber
GitHubber/Pods/CoreStore/CoreStore/Importing Data/BaseDataTransaction+Importing.swift
2
9572
// // BaseDataTransaction+Importing.swift // CoreStore // // Copyright (c) 2015 John Rommel Estropia // // 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 // MARK: - BaseDataTransaction public extension BaseDataTransaction { // MARK: Public /** Creates an `ImportableObject` by importing from the specified import source. - parameter into: an `Into` clause specifying the entity type - parameter source: the object to import values from - returns: the created `ImportableObject` instance, or `nil` if the import was ignored */ public func importObject<T where T: NSManagedObject, T: ImportableObject>( into: Into<T>, source: T.ImportSource) throws -> T? { CoreStore.assert( self.bypassesQueueing || self.transactionQueue.isCurrentExecutionContext(), "Attempted to import an object of type \(typeName(into.entityClass)) outside the transaction's designated queue." ) return try autoreleasepool { guard T.shouldInsertFromImportSource(source, inTransaction: self) else { return nil } let object = self.create(into) try object.didInsertFromImportSource(source, inTransaction: self) return object } } /** Creates multiple `ImportableObject`s by importing from the specified array of import sources. - parameter into: an `Into` clause specifying the entity type - parameter sourceArray: the array of objects to import values from - returns: the array of created `ImportableObject` instances */ public func importObjects<T, S: SequenceType where T: NSManagedObject, T: ImportableObject, S.Generator.Element == T.ImportSource>( into: Into<T>, sourceArray: S) throws -> [T] { CoreStore.assert( self.bypassesQueueing || self.transactionQueue.isCurrentExecutionContext(), "Attempted to import an object of type \(typeName(into.entityClass)) outside the transaction's designated queue." ) return try autoreleasepool { return try sourceArray.flatMap { (source) -> T? in guard T.shouldInsertFromImportSource(source, inTransaction: self) else { return nil } return try autoreleasepool { let object = self.create(into) try object.didInsertFromImportSource(source, inTransaction: self) return object } } } } /** Updates an existing `ImportableUniqueObject` or creates a new instance by importing from the specified import source. - parameter into: an `Into` clause specifying the entity type - parameter source: the object to import values from - returns: the created/updated `ImportableUniqueObject` instance, or `nil` if the import was ignored */ public func importUniqueObject<T where T: NSManagedObject, T: ImportableUniqueObject>( into: Into<T>, source: T.ImportSource) throws -> T? { CoreStore.assert( self.bypassesQueueing || self.transactionQueue.isCurrentExecutionContext(), "Attempted to import an object of type \(typeName(into.entityClass)) outside the transaction's designated queue." ) return try autoreleasepool { let uniqueIDKeyPath = T.uniqueIDKeyPath guard let uniqueIDValue = try T.uniqueIDFromImportSource(source, inTransaction: self) else { return nil } if let object = self.fetchOne(From(T), Where(uniqueIDKeyPath, isEqualTo: uniqueIDValue)) { try object.updateFromImportSource(source, inTransaction: self) return object } else { guard T.shouldInsertFromImportSource(source, inTransaction: self) else { return nil } let object = self.create(into) object.uniqueIDValue = uniqueIDValue try object.didInsertFromImportSource(source, inTransaction: self) return object } } } /** Updates existing `ImportableUniqueObject`s or creates them by importing from the specified array of import sources. - parameter into: an `Into` clause specifying the entity type - parameter sourceArray: the array of objects to import values from - parameter preProcess: a closure that lets the caller tweak the internal `UniqueIDType`-to-`ImportSource` mapping to be used for importing. Callers can remove from/add to/update `mapping` and return the updated array from the closure. - returns: the array of created/updated `ImportableUniqueObject` instances */ public func importUniqueObjects<T, S: SequenceType where T: NSManagedObject, T: ImportableUniqueObject, S.Generator.Element == T.ImportSource>( into: Into<T>, sourceArray: S, @noescape preProcess: (mapping: [T.UniqueIDType: T.ImportSource]) throws -> [T.UniqueIDType: T.ImportSource] = { $0 }) throws -> [T] { CoreStore.assert( self.bypassesQueueing || self.transactionQueue.isCurrentExecutionContext(), "Attempted to import an object of type \(typeName(into.entityClass)) outside the transaction's designated queue." ) return try autoreleasepool { var mapping = Dictionary<T.UniqueIDType, T.ImportSource>() let sortedIDs = try autoreleasepool { return try sourceArray.flatMap { (source) -> T.UniqueIDType? in guard let uniqueIDValue = try T.uniqueIDFromImportSource(source, inTransaction: self) else { return nil } mapping[uniqueIDValue] = source return uniqueIDValue } } mapping = try autoreleasepool { try preProcess(mapping: mapping) } var objects = Dictionary<T.UniqueIDType, T>() for object in self.fetchAll(From(T), Where(T.uniqueIDKeyPath, isMemberOf: mapping.keys)) ?? [] { try autoreleasepool { let uniqueIDValue = object.uniqueIDValue guard let source = mapping.removeValueForKey(uniqueIDValue) where T.shouldUpdateFromImportSource(source, inTransaction: self) else { return } try object.updateFromImportSource(source, inTransaction: self) objects[uniqueIDValue] = object } } for (uniqueIDValue, source) in mapping { try autoreleasepool { guard T.shouldInsertFromImportSource(source, inTransaction: self) else { return } let object = self.create(into) object.uniqueIDValue = uniqueIDValue try object.didInsertFromImportSource(source, inTransaction: self) objects[uniqueIDValue] = object } } return sortedIDs.flatMap { objects[$0] } } } }
mit
nikHowlett/WatchHealthMedicalDoctor
mobile/GraphView.swift
1
5458
import UIKit @IBDesignable class GraphView: UIView { //Weekly sample data var graphPoints:[Int] = [0, 1, 2, 3, 4, 5, 6] //1 - the properties for the gradient @IBInspectable var startColor: UIColor = UIColor.redColor() @IBInspectable var endColor: UIColor = UIColor.greenColor() override func drawRect(rect: CGRect) { let width = rect.width let height = rect.height //set up background clipping area let path = UIBezierPath(roundedRect: rect, byRoundingCorners: UIRectCorner.AllCorners, cornerRadii: CGSize(width: 8.0, height: 8.0)) path.addClip() //2 - get the current context let context = UIGraphicsGetCurrentContext() let colors = [startColor.CGColor, endColor.CGColor] //3 - set up the color space let colorSpace = CGColorSpaceCreateDeviceRGB() //4 - set up the color stops let colorLocations:[CGFloat] = [0.0, 1.0] //5 - create the gradient let gradient = CGGradientCreateWithColors(colorSpace, colors, colorLocations) //6 - draw the gradient var startPoint = CGPoint.zeroPoint var endPoint = CGPoint(x:0, y:self.bounds.height) CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0) //calculate the x point let margin:CGFloat = 20.0 let columnXPoint = { (column:Int) -> CGFloat in //Calculate gap between points let spacer = (width - margin*2 - 4) / CGFloat((self.graphPoints.count - 1)) var x:CGFloat = CGFloat(column) * spacer x += margin + 2 return x } // calculate the y point let topBorder:CGFloat = 60 let bottomBorder:CGFloat = 50 let graphHeight = height - topBorder - bottomBorder let maxValue = graphPoints.maxElement() let columnYPoint = { (graphPoint:Int) -> CGFloat in var y:CGFloat = CGFloat(graphPoint) / CGFloat(maxValue!) * graphHeight y = graphHeight + topBorder - y // Flip the graph return y } // draw the line graph UIColor.whiteColor().setFill() UIColor.whiteColor().setStroke() //set up the points line let graphPath = UIBezierPath() //go to start of line graphPath.moveToPoint(CGPoint(x:columnXPoint(0), y:columnYPoint(graphPoints[0]))) //add points for each item in the graphPoints array //at the correct (x, y) for the point for i in 1..<graphPoints.count { let nextPoint = CGPoint(x:columnXPoint(i), y:columnYPoint(graphPoints[i])) graphPath.addLineToPoint(nextPoint) } //Create the clipping path for the graph gradient //1 - save the state of the context (commented out for now) CGContextSaveGState(context) //2 - make a copy of the path let clippingPath = graphPath.copy() as! UIBezierPath //3 - add lines to the copied path to complete the clip area clippingPath.addLineToPoint(CGPoint( x: columnXPoint(graphPoints.count - 1), y:height)) clippingPath.addLineToPoint(CGPoint( x:columnXPoint(0), y:height)) clippingPath.closePath() //4 - add the clipping path to the context clippingPath.addClip() let highestYPoint = columnYPoint(maxValue!) startPoint = CGPoint(x:margin, y: highestYPoint) endPoint = CGPoint(x:margin, y:self.bounds.height) CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0) CGContextRestoreGState(context) //draw the line on top of the clipped gradient graphPath.lineWidth = 2.0 graphPath.stroke() //Draw the circles on top of graph stroke for i in 0..<graphPoints.count { var point = CGPoint(x:columnXPoint(i), y:columnYPoint(graphPoints[i])) point.x -= 5.0/2 point.y -= 5.0/2 let circle = UIBezierPath(ovalInRect: CGRect(origin: point, size: CGSize(width: 5.0, height: 5.0))) circle.fill() } //Draw horizontal graph lines on the top of everything let linePath = UIBezierPath() //top line linePath.moveToPoint(CGPoint(x:margin, y: topBorder)) linePath.addLineToPoint(CGPoint(x: width - margin, y:topBorder)) //center line linePath.moveToPoint(CGPoint(x:margin, y: graphHeight/2 + topBorder)) linePath.addLineToPoint(CGPoint(x:width - margin, y:graphHeight/2 + topBorder)) //bottom line linePath.moveToPoint(CGPoint(x:margin, y:height - bottomBorder)) linePath.addLineToPoint(CGPoint(x:width - margin, y:height - bottomBorder)) let color = UIColor(white: 1.0, alpha: 0.3) color.setStroke() linePath.lineWidth = 1.0 linePath.stroke() } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/24729-swift-functiontype-get.swift
9
227
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing extension String{let:e.h protocol a{ typealias d:d func a
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/08619-swift-protocoltype-canonicalizeprotocols.swift
11
226
// 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( ) { protocol b { func b(g<T> { } func g<T: b
mit
eurofurence/ef-app_ios
Packages/EurofurenceModel/Tests/EurofurenceModelTests/Events/Specifications/EventsOccurringOnDaySpecificationTests.swift
1
1006
import EurofurenceModel import XCTest import XCTEurofurenceModel class EventsOccurringOnDaySpecificationTests: XCTestCase { func testEventOccursOnSameDay() { let day = Day(date: Date(), identifier: "ID") let event = FakeEvent.random event.startDate = day.date event.day = day let specification = EventsOccurringOnDaySpecification(day: day) XCTAssertTrue(specification.isSatisfied(by: event), "Event occurs on the same day") } func testEventDoesNotOccursOnSameDay() { let eventDay = Day(date: Date(), identifier: "ID") let event = FakeEvent.random event.startDate = eventDay.date event.day = eventDay let criteriaDay = Day(date: Date(), identifier: "ID 2") let specification = EventsOccurringOnDaySpecification(day: criteriaDay) XCTAssertFalse(specification.isSatisfied(by: event), "Event does not occur on the same day") } }
mit
CoderJackyHuang/iOSLoadWebViewImage
iOSLoadWebviewImageSwift/Pods/AlamofireImage/Source/ImageCache.swift
23
12396
// ImageCache.swift // // Copyright (c) 2015 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 Alamofire import Foundation #if os(iOS) || os(watchOS) import UIKit #elseif os(OSX) import Cocoa #endif // MARK: ImageCache /// The `ImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache. public protocol ImageCache { /// Adds the image to the cache with the given identifier. func addImage(image: Image, withIdentifier identifier: String) /// Removes the image from the cache matching the given identifier. func removeImageWithIdentifier(identifier: String) -> Bool /// Removes all images stored in the cache. func removeAllImages() -> Bool /// Returns the image in the cache associated with the given identifier. func imageWithIdentifier(identifier: String) -> Image? } /// The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and /// fetching images from a cache given an `NSURLRequest` and additional identifier. public protocol ImageRequestCache: ImageCache { /// Adds the image to the cache using an identifier created from the request and additional identifier. func addImage(image: Image, forRequest request: NSURLRequest, withAdditionalIdentifier identifier: String?) /// Removes the image from the cache using an identifier created from the request and additional identifier. func removeImageForRequest(request: NSURLRequest, withAdditionalIdentifier identifier: String?) -> Bool /// Returns the image from the cache associated with an identifier created from the request and additional identifier. func imageForRequest(request: NSURLRequest, withAdditionalIdentifier identifier: String?) -> Image? } // MARK: - /// The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When /// the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously /// purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the /// internal access date of the image is updated. public class AutoPurgingImageCache: ImageRequestCache { private class CachedImage { let image: Image let identifier: String let totalBytes: UInt64 var lastAccessDate: NSDate init(_ image: Image, identifier: String) { self.image = image self.identifier = identifier self.lastAccessDate = NSDate() self.totalBytes = { #if os(iOS) || os(watchOS) let size = CGSize(width: image.size.width * image.scale, height: image.size.height * image.scale) #elseif os(OSX) let size = CGSize(width: image.size.width, height: image.size.height) #endif let bytesPerPixel: CGFloat = 4.0 let bytesPerRow = size.width * bytesPerPixel let totalBytes = UInt64(bytesPerRow) * UInt64(size.height) return totalBytes }() } func accessImage() -> Image { lastAccessDate = NSDate() return image } } // MARK: Properties /// The current total memory usage in bytes of all images stored within the cache. public var memoryUsage: UInt64 { var memoryUsage: UInt64 = 0 dispatch_sync(synchronizationQueue) { memoryUsage = self.currentMemoryUsage } return memoryUsage } /// The total memory capacity of the cache in bytes. public let memoryCapacity: UInt64 /// The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory /// capacity drops below this limit. public let preferredMemoryUsageAfterPurge: UInt64 private let synchronizationQueue: dispatch_queue_t private var cachedImages: [String: CachedImage] private var currentMemoryUsage: UInt64 // MARK: Initialization /** Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage after purge limit. - parameter memoryCapacity: The total memory capacity of the cache in bytes. `100 MB` by default. - parameter preferredMemoryUsageAfterPurge: The preferred memory usage after purge in bytes. `60 MB` by default. - returns: The new `AutoPurgingImageCache` instance. */ public init(memoryCapacity: UInt64 = 100 * 1024 * 1024, preferredMemoryUsageAfterPurge: UInt64 = 60 * 1024 * 1024) { self.memoryCapacity = memoryCapacity self.preferredMemoryUsageAfterPurge = preferredMemoryUsageAfterPurge self.cachedImages = [:] self.currentMemoryUsage = 0 self.synchronizationQueue = { let name = String(format: "com.alamofire.autopurgingimagecache-%08%08", arc4random(), arc4random()) return dispatch_queue_create(name, DISPATCH_QUEUE_CONCURRENT) }() #if os(iOS) NSNotificationCenter.defaultCenter().addObserver( self, selector: "removeAllImages", name: UIApplicationDidReceiveMemoryWarningNotification, object: nil ) #endif } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: Add Image to Cache /** Adds the image to the cache using an identifier created from the request and optional identifier. - parameter image: The image to add to the cache. - parameter request: The request used to generate the image's unique identifier. - parameter identifier: The additional identifier to append to the image's unique identifier. */ public func addImage(image: Image, forRequest request: NSURLRequest, withAdditionalIdentifier identifier: String? = nil) { let requestIdentifier = imageCacheKeyFromURLRequest(request, withAdditionalIdentifier: identifier) addImage(image, withIdentifier: requestIdentifier) } /** Adds the image to the cache with the given identifier. - parameter image: The image to add to the cache. - parameter identifier: The identifier to use to uniquely identify the image. */ public func addImage(image: Image, withIdentifier identifier: String) { dispatch_barrier_async(synchronizationQueue) { let cachedImage = CachedImage(image, identifier: identifier) if let previousCachedImage = self.cachedImages[identifier] { self.currentMemoryUsage -= previousCachedImage.totalBytes } self.cachedImages[identifier] = cachedImage self.currentMemoryUsage += cachedImage.totalBytes } dispatch_barrier_async(synchronizationQueue) { if self.currentMemoryUsage > self.memoryCapacity { let bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge var sortedImages = [CachedImage](self.cachedImages.values) sortedImages.sortInPlace { let date1 = $0.lastAccessDate let date2 = $1.lastAccessDate return date1.timeIntervalSinceDate(date2) < 0.0 } var bytesPurged = UInt64(0) for cachedImage in sortedImages { self.cachedImages.removeValueForKey(cachedImage.identifier) bytesPurged += cachedImage.totalBytes if bytesPurged >= bytesToPurge { break } } self.currentMemoryUsage -= bytesPurged } } } // MARK: Remove Image from Cache /** Removes the image from the cache using an identifier created from the request and optional identifier. - parameter request: The request used to generate the image's unique identifier. - parameter identifier: The additional identifier to append to the image's unique identifier. - returns: `true` if the image was removed, `false` otherwise. */ public func removeImageForRequest(request: NSURLRequest, withAdditionalIdentifier identifier: String?) -> Bool { let requestIdentifier = imageCacheKeyFromURLRequest(request, withAdditionalIdentifier: identifier) return removeImageWithIdentifier(requestIdentifier) } /** Removes the image from the cache matching the given identifier. - parameter identifier: The unique identifier for the image. - returns: `true` if the image was removed, `false` otherwise. */ public func removeImageWithIdentifier(identifier: String) -> Bool { var removed = false dispatch_barrier_async(synchronizationQueue) { if let cachedImage = self.cachedImages.removeValueForKey(identifier) { self.currentMemoryUsage -= cachedImage.totalBytes removed = true } } return removed } /** Removes all images stored in the cache. - returns: `true` if images were removed from the cache, `false` otherwise. */ @objc public func removeAllImages() -> Bool { var removed = false dispatch_sync(synchronizationQueue) { if !self.cachedImages.isEmpty { self.cachedImages.removeAll() self.currentMemoryUsage = 0 removed = true } } return removed } // MARK: Fetch Image from Cache /** Returns the image from the cache associated with an identifier created from the request and optional identifier. - parameter request: The request used to generate the image's unique identifier. - parameter identifier: The additional identifier to append to the image's unique identifier. - returns: The image if it is stored in the cache, `nil` otherwise. */ public func imageForRequest(request: NSURLRequest, withAdditionalIdentifier identifier: String? = nil) -> Image? { let requestIdentifier = imageCacheKeyFromURLRequest(request, withAdditionalIdentifier: identifier) return imageWithIdentifier(requestIdentifier) } /** Returns the image in the cache associated with the given identifier. - parameter identifier: The unique identifier for the image. - returns: The image if it is stored in the cache, `nil` otherwise. */ public func imageWithIdentifier(identifier: String) -> Image? { var image: Image? dispatch_sync(synchronizationQueue) { if let cachedImage = self.cachedImages[identifier] { image = cachedImage.accessImage() } } return image } // MARK: Private - Helper Methods private func imageCacheKeyFromURLRequest( request: NSURLRequest, withAdditionalIdentifier identifier: String?) -> String { var key = request.URLString if let identifier = identifier { key += "-\(identifier)" } return key } }
mit
LucianoPAlmeida/SwifterSwift
Sources/Extensions/SwiftStdlib/SignedNumericExtensions.swift
1
611
// // SignedNumberExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/15/17. // Copyright © 2017 SwifterSwift // // MARK: - Properties public extension SignedNumeric { /// SwifterSwift: String. public var string: String { return String(describing: self) } /// SwifterSwift: String with number and current locale currency. public var asLocaleCurrency: String { let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.locale = Locale.current guard let number = self as? NSNumber else { return "" } return formatter.string(from: number) ?? "" } }
mit
kdw9/TIY-Assignments
The Grial Diary/The Grial DiaryTests/The_Grial_DiaryTests.swift
1
1012
// // The_Grial_DiaryTests.swift // The Grial DiaryTests // // Created by Keron Williams on 10/19/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import XCTest @testable import The_Grial_Diary class The_Grial_DiaryTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
cc0-1.0
ccwuzhou/WWZSwift
Source/Views/WWZTableViewCell.swift
1
8159
// // WWZTableViewCell.swift // wwz_swift // // Created by wwz on 17/2/28. // Copyright © 2017年 tijio. All rights reserved. // import UIKit public enum WWZTableViewCellStyle : Int { case none = 0 case subTitle = 1 case rightTitle = 2 case switchView = 4 case subAndRight = 3 case subAndSwitch = 5 } public protocol WWZTableViewCellDelegate: NSObjectProtocol { func tableViewCell(cell: WWZTableViewCell, didChangedSwitch isOn: Bool) } open class WWZTableViewCell: UITableViewCell { // MARK: -属性 public weak var tableViewCellDelegate : WWZTableViewCellDelegate? /// sub label public var subLabel : UILabel? /// right label public var rightLabel : UILabel? /// switch public var mySwitch : UISwitch? /// text label 与 sub label 间距 public var titleSpaceH : CGFloat = 4.0 /// 是否为最后一行cell public var isLastCell : Bool = false /// line public lazy var lineView : UIView = { let line = UIView() line.backgroundColor = UIColor.colorFromRGBA(0, 0, 0, 0.1) return line }() // MARK: -类方法 class public func wwz_cell(tableView: UITableView, style: WWZTableViewCellStyle) -> WWZTableViewCell { let reuseID = "WWZ_REUSE_CELL_ID" var cell = tableView.dequeueReusableCell(withIdentifier: reuseID) if cell == nil { cell = self.init(style: style, reuseIdentifier: reuseID) } return cell as! WWZTableViewCell } public required init(style: WWZTableViewCellStyle, reuseIdentifier: String?) { super.init(style: .default, reuseIdentifier: reuseIdentifier) self.p_setupCell() self.p_addSubTitleLabel(style: style) self.p_addRightTitleLabel(style: style) self.p_addSwitchView(style: style) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: -布局 override open func layoutSubviews() { super.layoutSubviews() // imageView let imageX : CGFloat = 15.0 let imageY : CGFloat = 7.0 let imageWH : CGFloat = self.height - imageY*2 var imageSize = CGSize(width: imageWH, height: imageWH) if self.imageView?.image != nil { if self.imageView!.image!.size.width > imageWH || self.imageView!.image!.size.height > imageWH { self.imageView?.contentMode = .scaleAspectFit }else{ self.imageView?.contentMode = .center imageSize = self.imageView!.image!.size } self.imageView?.frame = CGRect(x: imageX, y: (self.height-imageSize.height)*0.5, width: imageSize.width, height: imageSize.height) } // textLabel guard let titleLabel = self.textLabel else { return } titleLabel.sizeToFit() titleLabel.x = self.imageView?.image == nil ? 15.0 : self.imageView!.right + 10 titleLabel.y = (self.height-titleLabel.height)*0.5 // text label 右边距 let textLabelRightSpace : CGFloat = 10.0 // text label 最大宽度 var textLMaxWidth = self.contentView.width - titleLabel.x - textLabelRightSpace titleLabel.width = titleLabel.width < textLMaxWidth ? titleLabel.width : textLMaxWidth // right label if let rightTitleLabel = self.rightLabel, let _ = self.rightLabel!.text, self.rightLabel!.text!.characters.count > 0 { rightTitleLabel.sizeToFit() // 右边距 let rightSpacing : CGFloat = self.accessoryType == .none ? 16.0 : 0 // right label 最小宽度 let rightLMinWidth : CGFloat = 60.0; // right label 最大宽度 let rightLMaxWidth = self.contentView.width - titleLabel.right - textLabelRightSpace - rightSpacing if rightLMaxWidth < rightLMinWidth { rightTitleLabel.width = rightTitleLabel.width < rightLMinWidth ? rightTitleLabel.width : rightLMinWidth }else{ rightTitleLabel.width = rightTitleLabel.width < rightLMaxWidth ? rightTitleLabel.width : rightLMaxWidth } rightTitleLabel.x = self.contentView.width - rightTitleLabel.width - rightSpacing rightTitleLabel.y = (self.height - rightTitleLabel.height) * 0.5 textLMaxWidth = rightTitleLabel.x - titleLabel.x - textLabelRightSpace } titleLabel.width = titleLabel.width < textLMaxWidth ? titleLabel.width : textLMaxWidth // sub label if let subTitleLabel = self.subLabel, let _ = self.subLabel!.text, self.subLabel!.text!.characters.count > 0{ subTitleLabel.sizeToFit() subTitleLabel.width = subTitleLabel.width < textLMaxWidth ? subTitleLabel.width : textLMaxWidth titleLabel.y = (self.height - titleLabel.height - subTitleLabel.height - self.titleSpaceH) * 0.5 subTitleLabel.x = titleLabel.x subTitleLabel.y = titleLabel.bottom + self.titleSpaceH } self.selectedBackgroundView?.frame = self.bounds let leftX = self.isLastCell ? 0 : self.textLabel!.x let lineH : CGFloat = 0.5 self.lineView.frame = CGRect(x: leftX, y: self.height - lineH, width: self.width-leftX, height: lineH) } } // MARK: -私有方法 extension WWZTableViewCell { // MARK: -设置cell fileprivate func p_setupCell() { self.backgroundColor = UIColor.white // text label self.textLabel?.backgroundColor = UIColor.clear self.textLabel?.font = UIFont.systemFont(ofSize: 17) self.textLabel?.textColor = UIColor.black // selected background color self.selectedBackgroundView = UIView() self.selectedBackgroundView?.backgroundColor = UIColor.colorFromRGBA(217, 217, 217, 1) // line self.contentView.addSubview(self.lineView) } // MARK: -添加sub label fileprivate func p_addSubTitleLabel(style: WWZTableViewCellStyle) { guard (style.rawValue & WWZTableViewCellStyle.subTitle.rawValue) > 0 else { return } let label = UILabel() label.font = UIFont.systemFont(ofSize: 14.0) label.textColor = UIColor.colorFromRGBA(153, 153, 153, 1) label.textAlignment = .left label.numberOfLines = 1 self.addSubview(label) self.subLabel = label } // MARK: -添加right label fileprivate func p_addRightTitleLabel(style: WWZTableViewCellStyle) { guard (style.rawValue & WWZTableViewCellStyle.rightTitle.rawValue) > 0 else { return } let label = UILabel() label.font = UIFont.systemFont(ofSize: 14.0) label.textColor = UIColor.colorFromRGBA(153, 153, 153, 1) label.textAlignment = .right label.numberOfLines = 1 self.addSubview(label) self.rightLabel = label } // MARK: -添加switch fileprivate func p_addSwitchView(style: WWZTableViewCellStyle) { guard (style.rawValue & WWZTableViewCellStyle.switchView.rawValue) > 0 else { return } let onSwitch = UISwitch() onSwitch.addTarget(self, action: #selector(WWZTableViewCell.p_changeSwitch), for: .valueChanged) self.accessoryView = onSwitch self.mySwitch = onSwitch } // MARK: -点击事件 @objc fileprivate func p_changeSwitch(sender: UISwitch) { self.tableViewCellDelegate?.tableViewCell(cell: self, didChangedSwitch: sender.isOn) } }
mit
brave/browser-ios
UITests/LoginInputTests.swift
3
4562
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Storage @testable import Client class LoginInputTests: KIFTestCase { private var webRoot: String! private var profile: Profile! override func setUp() { super.setUp() profile = (UIApplication.sharedApplication().delegate as! AppDelegate).profile! webRoot = SimplePageServer.start() } override func tearDown() { super.tearDown() BrowserUtils.resetToAboutHome(tester()) clearLogins() } private func clearLogins() { profile.logins.removeAll().value } func testLoginFormDisplaysNewSnackbar() { tester().tapViewWithAccessibilityIdentifier("url") let url = "\(webRoot)/loginForm.html" let username = "test@user.com" tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n") tester().enterText(username, intoWebViewInputWithName: "username") tester().enterText("password", intoWebViewInputWithName: "password") tester().tapWebViewElementWithAccessibilityLabel("submit_btn") tester().waitForViewWithAccessibilityLabel("Do you want to save the password for \(username) on \(webRoot)?") tester().tapViewWithAccessibilityLabel("Not now") } func testLoginFormDisplaysUpdateSnackbarIfPreviouslySaved() { tester().tapViewWithAccessibilityIdentifier("url") let url = "\(webRoot)/loginForm.html" let username = "test@user.com" let password1 = "password1" let password2 = "password2" tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n") tester().enterText(username, intoWebViewInputWithName: "username") tester().enterText(password1, intoWebViewInputWithName: "password") tester().tapWebViewElementWithAccessibilityLabel("submit_btn") tester().waitForViewWithAccessibilityLabel("Do you want to save the password for \(username) on \(webRoot)?") tester().tapViewWithAccessibilityLabel("Yes") tester().enterText(username, intoWebViewInputWithName: "username") tester().enterText(password2, intoWebViewInputWithName: "password") tester().tapWebViewElementWithAccessibilityLabel("submit_btn") tester().waitForViewWithAccessibilityLabel("Do you want to update the password for \(username) on \(webRoot)?") tester().tapViewWithAccessibilityLabel("Update") } func testLoginFormDoesntOfferSaveWhenEmptyPassword() { tester().tapViewWithAccessibilityIdentifier("url") let url = "\(webRoot)/loginForm.html" let username = "test@user.com" tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n") tester().enterText(username, intoWebViewInputWithName: "username") tester().enterText("", intoWebViewInputWithName: "password") tester().tapWebViewElementWithAccessibilityLabel("submit_btn") // Wait a bit then verify that we haven't shown the prompt tester().waitForTimeInterval(2) XCTAssertFalse(tester().viewExistsWithLabel("Do you want to save the password for \(username) on \(webRoot)?")) } func testLoginFormDoesntOfferUpdateWhenEmptyPassword() { tester().tapViewWithAccessibilityIdentifier("url") let url = "\(webRoot)/loginForm.html" let username = "test@user.com" let password1 = "password1" let password2 = "" tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n") tester().enterText(username, intoWebViewInputWithName: "username") tester().enterText(password1, intoWebViewInputWithName: "password") tester().tapWebViewElementWithAccessibilityLabel("submit_btn") tester().waitForViewWithAccessibilityLabel("Do you want to save the password for \(username) on \(webRoot)?") tester().tapViewWithAccessibilityLabel("Yes") tester().enterText(username, intoWebViewInputWithName: "username") tester().enterText(password2, intoWebViewInputWithName: "password") tester().tapWebViewElementWithAccessibilityLabel("submit_btn") // Wait a bit then verify that we haven't shown the prompt tester().waitForTimeInterval(2) XCTAssertFalse(tester().viewExistsWithLabel("Do you want to update the password for \(username) on \(webRoot)?")) } }
mpl-2.0
mathcamp/swiftz
swiftzTests/ImArrayTests.swift
2
3164
// // ImArrayTests.swift // swiftz // // Created by Terry Lewis II on 6/9/14. // Copyright (c) 2014 Maxwell Swadling. All rights reserved. // import XCTest import swiftz class ImArrayTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testScanl() { let withArray = [1,2,3,4] let scanned = scanl(0, withArray, +) XCTAssert(scanned == [0,1,3,6,10], "Should be equal") XCTAssert(withArray == [1,2,3,4], "Should be equal(immutablility test)") } func testIntersperse() { let withArray = [1,2,3,4] let inter = intersperse(1, withArray) XCTAssert(inter == [1,1,2,1,3,1,4], "Should be equal") XCTAssert(withArray == [1,2,3,4], "Should be equal(immutablility test)") let single = [1] XCTAssert(intersperse(1, single) == [1], "Should be equal") } func testFind() { let withArray = [1,2,3,4] if let found = find(withArray, {$0 == 4}) { XCTAssert(found == 4, "Should be found") } } func testSplitAt() { let withArray = [1,2,3,4] let tuple = splitAt(2,withArray) XCTAssert(tuple.0 == [1,2] && tuple.1 == [3,4], "Should be equal") XCTAssert(splitAt(0,withArray).0 == Array() && splitAt(0, withArray).1 == [1,2,3,4], "Should be equal") XCTAssert(withArray == [1,2,3,4], "Should be equal(immutablility test)") } func testAnd() { let withArray = [true, true, false, true] XCTAssertFalse(and(withArray), "Should be false") } func testOr() { let withArray = [true, true, false, true] XCTAssert(or(withArray), "Should be true") } func testAny() { let withArray = Array([1,4,5,7]) XCTAssert(any(withArray) {$0 > 4}, "Should be false") } func testAll() { let array = [1,3,24,5] XCTAssert(all(array){$0 <= 24}, "Should be true") } func testConcat() { let array = [[1,2,3],[4,5,6],[7],[8,9]] XCTAssert(concat(array) == [1,2,3,4,5,6,7,8,9], "Should be equal") } func testConcatMap() { let array = [1,2,3,4,5,6,7,8,9] XCTAssert(concatMap(array) {a in [a + 1]} == [2,3,4,5,6,7,8,9,10], "Should be equal") } func testIntercalate() { let result = intercalate([1,2,3], [[4,5],[6,7]]) XCTAssert(result == [4,5,1,2,3,6,7], "Should be equal") } func testSpan() { let withArray = [1,2,3,4,1,2,3,4] let tuple = span(withArray, {a in {b in b < a}}(3)) XCTAssert(tuple.0 == [1,2] && tuple.1 == [3,4,1,2,3,4], "Should be equal") } func testGroup() { let array = [1,2,3,3,4,5,6,7,7,8,9,9,0] let result = group(array) XCTAssert(result == [[1],[2],[3,3],[4],[5],[6],[7,7],[8],[9,9],[0]], "Should be equal") } func testDropWhile() { let array = [1,2,3,4,5] XCTAssert(dropWhile(array, {$0 <= 3}) == [4,5], "Should be equal") } func testTakeWhile() { let array = [1,2,3,4,5] XCTAssert(takeWhile(array, {$0 <= 3}) == [1,2,3], "Should be equal") } }
bsd-3-clause
qvacua/vimr
VimR/VimR/MainWindow+Delegates.swift
1
8753
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Cocoa import NvimView import RxPack import RxSwift import RxNeovim import Workspace // MARK: - NvimViewDelegate extension MainWindow { // Use only when Cmd-Q'ing func waitTillNvimExits() { self.neoVimView.waitTillNvimExits() } func neoVimStopped() { if self.isClosing { return } self.prepareClosing() self.windowController.close() self.set(dirtyStatus: false) self.emit(self.uuidAction(for: .close)) } func prepareClosing() { self.isClosing = true // If we close the window in the full screen mode, either by clicking the close button or by invoking :q // the main thread crashes. We exit the full screen mode here as a quick and dirty hack. if self.window.styleMask.contains(.fullScreen) { self.window.toggleFullScreen(nil) } guard let cliPipePath = self.cliPipePath, FileManager.default.fileExists(atPath: cliPipePath) else { return } let fd = Darwin.open(cliPipePath, O_RDWR) guard fd != -1 else { return } let handle = FileHandle(fileDescriptor: fd) handle.closeFile() _ = Darwin.close(fd) } func set(title: String) { self.window.title = title self.set(repUrl: self.window.representedURL, themed: self.titlebarThemed) } func set(dirtyStatus: Bool) { self.emit(self.uuidAction(for: .setDirtyStatus(dirtyStatus))) } func cwdChanged() { self.emit(self.uuidAction(for: .cd(to: self.neoVimView.cwd))) } func bufferListChanged() { self.neoVimView .allBuffers() .subscribe(onSuccess: { buffers in self.emit(self.uuidAction(for: .setBufferList(buffers.filter { $0.isListed }))) }) .disposed(by: self.disposeBag) } func bufferWritten(_ buffer: NvimView.Buffer) { self.emit(self.uuidAction(for: .bufferWritten(buffer))) } func newCurrentBuffer(_ currentBuffer: NvimView.Buffer) { self.emit(self.uuidAction(for: .newCurrentBuffer(currentBuffer))) } func tabChanged() { self.neoVimView .currentBuffer() .subscribe(onSuccess: { self.newCurrentBuffer($0) }) .disposed(by: self.disposeBag) } func colorschemeChanged(to nvimTheme: NvimView.Theme) { self .updateCssColors() .subscribe(onSuccess: { colors in self.emit( self.uuidAction( for: .setTheme(Theme(from: nvimTheme, additionalColorDict: colors)) ) ) }) .disposed(by: self.disposeBag) } func guifontChanged(to font: NSFont) { self.emit(self.uuidAction(for: .setFont(font))) } func ipcBecameInvalid(reason: String) { let alert = NSAlert() alert.addButton(withTitle: "Close") alert.messageText = "Sorry, an error occurred." alert .informativeText = "VimR encountered an error from which it cannot recover. This window will now close.\n" + reason alert.alertStyle = .critical alert.beginSheetModal(for: self.window) { _ in self.windowController.close() } } func scroll() { self.scrollDebouncer.call(.scroll(to: Marked(self.neoVimView.currentPosition))) } func cursor(to position: Position) { if position == self.editorPosition.payload { return } self.editorPosition = Marked(position) self.cursorDebouncer.call(.setCursor(to: self.editorPosition)) } private func updateCssColors() -> Single<[String: CellAttributes]> { let colorNames = [ "Normal", // color and background-color "Directory", // a "Question", // blockquote foreground "CursorColumn", // code background and foreground ] typealias HlResult = [String: RxNeovimApi.Value] typealias ColorNameHlResultTuple = (colorName: String, hlResult: HlResult) typealias ColorNameObservableTuple = (colorName: String, observable: Observable<HlResult>) return Observable .from(colorNames.map { colorName -> ColorNameObservableTuple in ( colorName: colorName, observable: self.neoVimView.api .getHlByName(name: colorName, rgb: true) .asObservable() ) }) .flatMap { tuple -> Observable<(String, HlResult)> in Observable.zip(Observable.just(tuple.colorName), tuple.observable) } .reduce([ColorNameHlResultTuple]()) { (result, element: ColorNameHlResultTuple) in result + [element] } .map { (array: [ColorNameHlResultTuple]) in Dictionary(uniqueKeysWithValues: array) .mapValues { value in CellAttributes(withDict: value, with: self.neoVimView.defaultCellAttributes) } } .asSingle() } } // MARK: - NSWindowDelegate extension MainWindow { func windowWillEnterFullScreen(_: Notification) { self.unthemeTitlebar(dueFullScreen: true) } func windowDidExitFullScreen(_: Notification) { if self.titlebarThemed { self.themeTitlebar(grow: true) } } func windowDidBecomeMain(_: Notification) { self .emit( self .uuidAction(for: .becomeKey(isFullScreen: self.window.styleMask.contains(.fullScreen))) ) self.neoVimView.didBecomeMain().subscribe().disposed(by: self.disposeBag) } func windowDidResignMain(_: Notification) { self.neoVimView.didResignMain().subscribe().disposed(by: self.disposeBag) } func windowDidMove(_: Notification) { self.emit(self.uuidAction(for: .frameChanged(to: self.window.frame))) } func windowDidResize(_: Notification) { if self.window.styleMask.contains(.fullScreen) { return } self.emit(self.uuidAction(for: .frameChanged(to: self.window.frame))) } func windowShouldClose(_: NSWindow) -> Bool { defer { self.closeWindow = false } if self.neoVimView.isBlocked().syncValue() ?? false { let alert = NSAlert() alert.messageText = "Nvim is waiting for your input." alert.alertStyle = .informational alert.runModal() return false } if self.closeWindow { if self.neoVimView.hasDirtyBuffers().syncValue() == true { self.discardCloseActionAlert().beginSheetModal(for: self.window) { response in if response == .alertSecondButtonReturn { try? self.neoVimView.quitNeoVimWithoutSaving().wait() } } } else { try? self.neoVimView.quitNeoVimWithoutSaving().wait() } return false } guard self.neoVimView.isCurrentBufferDirty().syncValue() ?? false else { try? self.neoVimView.closeCurrentTab().wait() return false } self.discardCloseActionAlert().beginSheetModal(for: self.window) { response in if response == .alertSecondButtonReturn { try? self.neoVimView.closeCurrentTabWithoutSaving().wait() } } return false } private func discardCloseActionAlert() -> NSAlert { let alert = NSAlert() let cancelButton = alert.addButton(withTitle: "Cancel") let discardAndCloseButton = alert.addButton(withTitle: "Discard and Close") cancelButton.keyEquivalent = "\u{1b}" alert.messageText = "The current buffer has unsaved changes!" alert.alertStyle = .warning discardAndCloseButton.keyEquivalentModifierMask = .command discardAndCloseButton.keyEquivalent = "d" return alert } } // MARK: - WorkspaceDelegate extension MainWindow { func resizeWillStart(workspace _: Workspace, tool _: WorkspaceTool?) { self.neoVimView.enterResizeMode() } func resizeDidEnd(workspace _: Workspace, tool: WorkspaceTool?) { self.neoVimView.exitResizeMode() if let workspaceTool = tool, let toolIdentifier = self.toolIdentifier(for: workspaceTool) { self.emit(self.uuidAction(for: .setState(for: toolIdentifier, with: workspaceTool))) } } func toggled(tool: WorkspaceTool) { if let toolIdentifier = self.toolIdentifier(for: tool) { self.emit(self.uuidAction(for: .setState(for: toolIdentifier, with: tool))) } } func moved(tool: WorkspaceTool) { let tools = self.workspace.orderedTools .compactMap { (tool: WorkspaceTool) -> (Tools, WorkspaceTool)? in guard let toolId = self.toolIdentifier(for: tool) else { return nil } return (toolId, tool) } self.emit(self.uuidAction(for: .setToolsState(tools))) } private func toolIdentifier(for tool: WorkspaceTool) -> Tools? { if tool == self.fileBrowserContainer { return .fileBrowser } if tool == self.buffersListContainer { return .buffersList } if tool == self.previewContainer { return .preview } if tool == self.htmlPreviewContainer { return .htmlPreview } return nil } }
mit
codestergit/swift
stdlib/public/core/Collection.swift
3
76619
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A type that provides subscript access to its elements, with forward /// index traversal. /// /// In most cases, it's best to ignore this protocol and use the `Collection` /// protocol instead, because it has a more complete interface. @available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'Collection' instead") public typealias IndexableBase = _IndexableBase public protocol _IndexableBase { // FIXME(ABI)#24 (Recursive Protocol Constraints): there is no reason for this protocol // to exist apart from missing compiler features that we emulate with it. // rdar://problem/20531108 // // This protocol is almost an implementation detail of the standard // library; it is used to deduce things like the `SubSequence` and // `Iterator` type from a minimal collection, but it is also used in // exposed places like as a constraint on `IndexingIterator`. /// A type that represents a position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript /// argument. /// /// - SeeAlso: endIndex associatedtype Index : Comparable /// The position of the first element in a nonempty collection. /// /// If the collection is empty, `startIndex` is equal to `endIndex`. var startIndex: Index { get } /// The collection's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// When you need a range that includes the last element of a collection, use /// the half-open range operator (`..<`) with `endIndex`. The `..<` operator /// creates a range that doesn't include the upper bound, so it's always /// safe to use with `endIndex`. For example: /// /// let numbers = [10, 20, 30, 40, 50] /// if let index = numbers.index(of: 30) { /// print(numbers[index ..< numbers.endIndex]) /// } /// // Prints "[30, 40, 50]" /// /// If the collection is empty, `endIndex` is equal to `startIndex`. var endIndex: Index { get } // The declaration of _Element and subscript here is a trick used to // break a cyclic conformance/deduction that Swift can't handle. We // need something other than a Collection.Iterator.Element that can // be used as IndexingIterator<T>'s Element. Here we arrange for // the Collection itself to have an Element type that's deducible from // its subscript. Ideally we'd like to constrain this Element to be the same // as Collection.Iterator.Element (see below), but we have no way of // expressing it today. associatedtype _Element /// Accesses the element at the specified position. /// /// The following example accesses an element of an array through its /// subscript to print its value: /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// print(streets[1]) /// // Prints "Bryant" /// /// You can subscript a collection with any valid index other than the /// collection's end index. The end index refers to the position one past /// the last element of a collection, so it doesn't correspond with an /// element. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the collection that is not equal to the /// `endIndex` property. /// /// - Complexity: O(1) subscript(position: Index) -> _Element { get } // WORKAROUND: rdar://25214066 // FIXME(ABI)#178 (Type checker) /// A sequence that represents a contiguous subrange of the collection's /// elements. associatedtype SubSequence /// Accesses the subsequence bounded by the given range. /// /// - Parameter bounds: A range of the collection's indices. The upper and /// lower bounds of the range must be valid indices of the collection. /// /// - Complexity: O(1) subscript(bounds: Range<Index>) -> SubSequence { get } /// Performs a range check in O(1), or a no-op when a range check is not /// implementable in O(1). /// /// The range check, if performed, is equivalent to: /// /// precondition(bounds.contains(index)) /// /// Use this function to perform a cheap range check for QoI purposes when /// memory safety is not a concern. Do not rely on this range check for /// memory safety. /// /// The default implementation for forward and bidirectional indices is a /// no-op. The default implementation for random access indices performs a /// range check. /// /// - Complexity: O(1). func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>) /// Performs a range check in O(1), or a no-op when a range check is not /// implementable in O(1). /// /// The range check, if performed, is equivalent to: /// /// precondition( /// bounds.contains(range.lowerBound) || /// range.lowerBound == bounds.upperBound) /// precondition( /// bounds.contains(range.upperBound) || /// range.upperBound == bounds.upperBound) /// /// Use this function to perform a cheap range check for QoI purposes when /// memory safety is not a concern. Do not rely on this range check for /// memory safety. /// /// The default implementation for forward and bidirectional indices is a /// no-op. The default implementation for random access indices performs a /// range check. /// /// - Complexity: O(1). func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) /// Returns the position immediately after the given index. /// /// The successor of an index must be well defined. For an index `i` into a /// collection `c`, calling `c.index(after: i)` returns the same index every /// time. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index value immediately after `i`. func index(after i: Index) -> Index /// Replaces the given index with its successor. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// /// - SeeAlso: `index(after:)` func formIndex(after i: inout Index) } /// A type that provides subscript access to its elements, with forward index /// traversal. /// /// In most cases, it's best to ignore this protocol and use the `Collection` /// protocol instead, because it has a more complete interface. @available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'Collection' instead") public typealias Indexable = _Indexable public protocol _Indexable : _IndexableBase { /// A type that represents the number of steps between two indices, where /// one value is reachable from the other. /// /// In Swift, *reachability* refers to the ability to produce one value from /// the other through zero or more applications of `index(after:)`. associatedtype IndexDistance : SignedInteger = Int /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// /// let s = "Swift" /// let i = s.index(s.startIndex, offsetBy: 4) /// print(s[i]) /// // Prints "t" /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// - Returns: An index offset by `n` from the index `i`. If `n` is positive, /// this is the same value as the result of `n` calls to `index(after:)`. /// If `n` is negative, this is the same value as the result of `-n` calls /// to `index(before:)`. /// /// - SeeAlso: `index(_:offsetBy:limitedBy:)`, `formIndex(_:offsetBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. func index(_ i: Index, offsetBy n: IndexDistance) -> Index /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// The operation doesn't require going beyond the limiting `s.endIndex` /// value, so it succeeds. /// /// let s = "Swift" /// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) { /// print(s[i]) /// } /// // Prints "t" /// /// The next example attempts to retrieve an index six positions from /// `s.startIndex` but fails, because that distance is beyond the index /// passed as `limit`. /// /// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// - limit: A valid index of the collection to use as a limit. If `n > 0`, /// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a /// limit that is greater than `i` has no effect. /// - Returns: An index offset by `n` from the index `i`, unless that index /// would be beyond `limit` in the direction of movement. In that case, /// the method returns `nil`. /// /// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? /// Offsets the given index by the specified distance. /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// /// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. func formIndex(_ i: inout Index, offsetBy n: IndexDistance) /// Offsets the given index by the specified distance, or so that it equals /// the given limiting index. /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// - limit: A valid index of the collection to use as a limit. If `n > 0`, /// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a /// limit that is greater than `i` has no effect. /// - Returns: `true` if `i` has been offset by exactly `n` steps without /// going beyond `limit`; otherwise, `false`. When the return value is /// `false`, the value of `i` is equal to `limit`. /// /// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. func formIndex( _ i: inout Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Bool /// Returns the distance between two indices. /// /// Unless the collection conforms to the `BidirectionalCollection` protocol, /// `start` must be less than or equal to `end`. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. The result can be /// negative only if the collection conforms to the /// `BidirectionalCollection` protocol. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the /// resulting distance. func distance(from start: Index, to end: Index) -> IndexDistance } /// A type that iterates over a collection using its indices. /// /// The `IndexingIterator` type is the default iterator for any collection that /// doesn't declare its own. It acts as an iterator by using a collection's /// indices to step over each value in the collection. Most collections in the /// standard library use `IndexingIterator` as their iterator. /// /// By default, any custom collection type you create will inherit a /// `makeIterator()` method that returns an `IndexingIterator` instance, /// making it unnecessary to declare your own. When creating a custom /// collection type, add the minimal requirements of the `Collection` /// protocol: starting and ending indices and a subscript for accessing /// elements. With those elements defined, the inherited `makeIterator()` /// method satisfies the requirements of the `Sequence` protocol. /// /// Here's an example of a type that declares the minimal requirements for a /// collection. The `CollectionOfTwo` structure is a fixed-size collection /// that always holds two elements of a specific type. /// /// struct CollectionOfTwo<Element>: Collection { /// let elements: (Element, Element) /// /// init(_ first: Element, _ second: Element) { /// self.elements = (first, second) /// } /// /// var startIndex: Int { return 0 } /// var endIndex: Int { return 2 } /// /// subscript(index: Int) -> Element { /// switch index { /// case 0: return elements.0 /// case 1: return elements.1 /// default: fatalError("Index out of bounds.") /// } /// } /// /// func index(after i: Int) -> Int { /// precondition(i < endIndex, "Can't advance beyond endIndex") /// return i + 1 /// } /// } /// /// The `CollectionOfTwo` type uses the default iterator type, /// `IndexingIterator`, because it doesn't define its own `makeIterator()` /// method or `Iterator` associated type. This example shows how a /// `CollectionOfTwo` instance can be created holding the values of a point, /// and then iterated over using a `for`-`in` loop. /// /// let point = CollectionOfTwo(15.0, 20.0) /// for element in point { /// print(element) /// } /// // Prints "15.0" /// // Prints "20.0" @_fixed_layout public struct IndexingIterator< Elements : _IndexableBase // FIXME(ABI)#97 (Recursive Protocol Constraints): // Should be written as: // Elements : Collection > : IteratorProtocol, Sequence { @_inlineable /// Creates an iterator over the given collection. public /// @testable init(_elements: Elements) { self._elements = _elements self._position = _elements.startIndex } /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Repeatedly calling this method returns all the elements of the underlying /// sequence in order. As soon as the sequence has run out of elements, all /// subsequent calls return `nil`. /// /// This example shows how an iterator can be used explicitly to emulate a /// `for`-`in` loop. First, retrieve a sequence's iterator, and then call /// the iterator's `next()` method until it returns `nil`. /// /// let numbers = [2, 3, 5, 7] /// var numbersIterator = numbers.makeIterator() /// /// while let num = numbersIterator.next() { /// print(num) /// } /// // Prints "2" /// // Prints "3" /// // Prints "5" /// // Prints "7" /// /// - Returns: The next element in the underlying sequence if a next element /// exists; otherwise, `nil`. @_inlineable public mutating func next() -> Elements._Element? { if _position == _elements.endIndex { return nil } let element = _elements[_position] _elements.formIndex(after: &_position) return element } @_versioned internal let _elements: Elements @_versioned internal var _position: Elements.Index } /// A sequence whose elements can be traversed multiple times, /// nondestructively, and accessed by indexed subscript. /// /// Collections are used extensively throughout the standard library. When you /// use arrays, dictionaries, views of a string's contents and other types, /// you benefit from the operations that the `Collection` protocol declares /// and implements. /// /// In addition to the methods that collections inherit from the `Sequence` /// protocol, you gain access to methods that depend on accessing an element /// at a specific position when using a collection. /// /// For example, if you want to print only the first word in a string, search /// for the index of the first space and then create a subsequence up to that /// position. /// /// let text = "Buffalo buffalo buffalo buffalo." /// if let firstSpace = text.characters.index(of: " ") { /// print(String(text.characters.prefix(upTo: firstSpace))) /// } /// // Prints "Buffalo" /// /// The `firstSpace` constant is an index into the `text.characters` /// collection. `firstSpace` is the position of the first space in the /// collection. You can store indices in variables, and pass them to /// collection algorithms or use them later to access the corresponding /// element. In the example above, `firstSpace` is used to extract the prefix /// that contains elements up to that index. /// /// You can pass only valid indices to collection operations. You can find a /// complete set of a collection's valid indices by starting with the /// collection's `startIndex` property and finding every successor up to, and /// including, the `endIndex` property. All other values of the `Index` type, /// such as the `startIndex` property of a different collection, are invalid /// indices for this collection. /// /// Saved indices may become invalid as a result of mutating operations; for /// more information about index invalidation in mutable collections, see the /// reference for the `MutableCollection` and `RangeReplaceableCollection` /// protocols, as well as for the specific type you're using. /// /// Accessing Individual Elements /// ============================= /// /// You can access an element of a collection through its subscript with any /// valid index except the collection's `endIndex` property, a "past the end" /// index that does not correspond with any element of the collection. /// /// Here's an example of accessing the first character in a string through its /// subscript: /// /// let firstChar = text.characters[text.characters.startIndex] /// print(firstChar) /// // Prints "B" /// /// The `Collection` protocol declares and provides default implementations for /// many operations that depend on elements being accessible by their /// subscript. For example, you can also access the first character of `text` /// using the `first` property, which has the value of the first element of /// the collection, or `nil` if the collection is empty. /// /// print(text.characters.first) /// // Prints "Optional("B")" /// /// Accessing Slices of a Collection /// ================================ /// /// You can access a slice of a collection through its ranged subscript or by /// calling methods like `prefix(_:)` or `suffix(from:)`. A slice of a /// collection can contain zero or more of the original collection's elements /// and shares the original collection's semantics. /// /// The following example, creates a `firstWord` constant by using the /// `prefix(_:)` method to get a slice of the `text` string's `characters` /// view. /// /// let firstWord = text.characters.prefix(7) /// print(String(firstWord)) /// // Prints "Buffalo" /// /// You can retrieve the same slice using other methods, such as finding the /// terminating index, and then using the `prefix(upTo:)` method, which takes /// an index as its parameter, or by using the view's ranged subscript. /// /// if let firstSpace = text.characters.index(of: " ") { /// print(text.characters.prefix(upTo: firstSpace)) /// // Prints "Buffalo" /// /// let start = text.characters.startIndex /// print(text.characters[start..<firstSpace]) /// // Prints "Buffalo" /// } /// /// The retrieved slice of `text.characters` is equivalent in each of these /// cases. /// /// Slices Share Indices /// -------------------- /// /// A collection and its slices share the same indices. An element of a /// collection is located under the same index in a slice as in the base /// collection, as long as neither the collection nor the slice has been /// mutated since the slice was created. /// /// For example, suppose you have an array holding the number of absences from /// each class during a session. /// /// var absences = [0, 2, 0, 4, 0, 3, 1, 0] /// /// You're tasked with finding the day with the most absences in the second /// half of the session. To find the index of the day in question, follow /// these steps: /// /// 1) Create a slice of the `absences` array that holds the second half of the /// days. /// 2) Use the `max(by:)` method to determine the index of the day with the /// most absences. /// 3) Print the result using the index found in step 2 on the original /// `absences` array. /// /// Here's an implementation of those steps: /// /// let secondHalf = absences.suffix(absences.count / 2) /// if let i = secondHalf.indices.max(by: { secondHalf[$0] < secondHalf[$1] }) { /// print("Highest second-half absences: \(absences[i])") /// } /// // Prints "Highest second-half absences: 3" /// /// Slice Inherit Collection Semantics /// ---------------------------------- /// /// A slice inherits the value or reference semantics of its base collection. /// That is, when working with a slice of a mutable /// collection that has value semantics, such as an array, mutating the /// original collection triggers a copy of that collection, and does not /// affect the contents of the slice. /// /// For example, if you update the last element of the `absences` array from /// `0` to `2`, the `secondHalf` slice is unchanged. /// /// absences[7] = 2 /// print(absences) /// // Prints "[0, 2, 0, 4, 0, 3, 1, 2]" /// print(secondHalf) /// // Prints "[0, 3, 1, 0]" /// /// Traversing a Collection /// ======================= /// /// Although a sequence can be consumed as it is traversed, a collection is /// guaranteed to be multipass: Any element may be repeatedly accessed by /// saving its index. Moreover, a collection's indices form a finite range of /// the positions of the collection's elements. This guarantees the safety of /// operations that depend on a sequence being finite, such as checking to see /// whether a collection contains an element. /// /// Iterating over the elements of a collection by their positions yields the /// same elements in the same order as iterating over that collection using /// its iterator. This example demonstrates that the `characters` view of a /// string returns the same characters in the same order whether the view's /// indices or the view itself is being iterated. /// /// let word = "Swift" /// for character in word.characters { /// print(character) /// } /// // Prints "S" /// // Prints "w" /// // Prints "i" /// // Prints "f" /// // Prints "t" /// /// for i in word.characters.indices { /// print(word.characters[i]) /// } /// // Prints "S" /// // Prints "w" /// // Prints "i" /// // Prints "f" /// // Prints "t" /// /// Conforming to the Collection Protocol /// ===================================== /// /// If you create a custom sequence that can provide repeated access to its /// elements, make sure that its type conforms to the `Collection` protocol in /// order to give a more useful and more efficient interface for sequence and /// collection operations. To add `Collection` conformance to your type, you /// must declare at least the four following requirements: /// /// - the `startIndex` and `endIndex` properties, /// - a subscript that provides at least read-only access to your type's /// elements, and /// - the `index(after:)` method for advancing an index into your collection. /// /// Expected Performance /// ==================== /// /// Types that conform to `Collection` are expected to provide the `startIndex` /// and `endIndex` properties and subscript access to elements as O(1) /// operations. Types that are not able to guarantee that expected performance /// must document the departure, because many collection operations depend on /// O(1) subscripting performance for their own performance guarantees. /// /// The performance of some collection operations depends on the type of index /// that the collection provides. For example, a random-access collection, /// which can measure the distance between two indices in O(1) time, will be /// able to calculate its `count` property in O(1) time. Conversely, because a /// forward or bidirectional collection must traverse the entire collection to /// count the number of contained elements, accessing its `count` property is /// an O(*n*) operation. public protocol Collection : _Indexable, Sequence { /// A type that represents the number of steps between a pair of /// indices. associatedtype IndexDistance = Int /// A type that provides the collection's iteration interface and /// encapsulates its iteration state. /// /// By default, a collection conforms to the `Sequence` protocol by /// supplying `IndexingIterator` as its associated `Iterator` /// type. associatedtype Iterator = IndexingIterator<Self> // FIXME(ABI)#179 (Type checker): Needed here so that the `Iterator` is properly deduced from // a custom `makeIterator()` function. Otherwise we get an // `IndexingIterator`. <rdar://problem/21539115> /// Returns an iterator over the elements of the collection. func makeIterator() -> Iterator /// A sequence that represents a contiguous subrange of the collection's /// elements. /// /// This associated type appears as a requirement in the `Sequence` /// protocol, but it is restated here with stricter constraints. In a /// collection, the subsequence should also conform to `Collection`. associatedtype SubSequence : _IndexableBase, Sequence = Slice<Self> // FIXME(ABI)#98 (Recursive Protocol Constraints): // FIXME(ABI)#99 (Associated Types with where clauses): // associatedtype SubSequence : Collection // where // Iterator.Element == SubSequence.Iterator.Element, // SubSequence.Index == Index, // SubSequence.Indices == Indices, // SubSequence.SubSequence == SubSequence // // (<rdar://problem/20715009> Implement recursive protocol // constraints) // // These constraints allow processing collections in generic code by // repeatedly slicing them in a loop. /// Accesses the element at the specified position. /// /// The following example accesses an element of an array through its /// subscript to print its value: /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// print(streets[1]) /// // Prints "Bryant" /// /// You can subscript a collection with any valid index other than the /// collection's end index. The end index refers to the position one past /// the last element of a collection, so it doesn't correspond with an /// element. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the collection that is not equal to the /// `endIndex` property. /// /// - Complexity: O(1) subscript(position: Index) -> Iterator.Element { get } /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection uses. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.index(of: "Evarts") // 4 /// print(streets[index!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. /// /// - Complexity: O(1) subscript(bounds: Range<Index>) -> SubSequence { get } /// A type that represents the indices that are valid for subscripting the /// collection, in ascending order. associatedtype Indices : _Indexable, Sequence = DefaultIndices<Self> // FIXME(ABI)#68 (Associated Types with where clauses): // FIXME(ABI)#100 (Recursive Protocol Constraints): // associatedtype Indices : Collection // where // Indices.Iterator.Element == Index, // Indices.Index == Index, // Indices.SubSequence == Indices // = DefaultIndices<Self> /// The indices that are valid for subscripting the collection, in ascending /// order. /// /// A collection's `indices` property can hold a strong reference to the /// collection itself, causing the collection to be nonuniquely referenced. /// If you mutate the collection while iterating over its indices, a strong /// reference can result in an unexpected copy of the collection. To avoid /// the unexpected copy, use the `index(after:)` method starting with /// `startIndex` to produce indices instead. /// /// var c = MyFancyCollection([10, 20, 30, 40, 50]) /// var i = c.startIndex /// while i != c.endIndex { /// c[i] /= 5 /// i = c.index(after: i) /// } /// // c == MyFancyCollection([2, 4, 6, 8, 10]) var indices: Indices { get } /// Returns a subsequence from the start of the collection up to, but not /// including, the specified position. /// /// The resulting subsequence *does not include* the element at the position /// `end`. The following example searches for the index of the number `40` /// in an array of integers, and then prints the prefix of the array up to, /// but not including, that index: /// /// let numbers = [10, 20, 30, 40, 50, 60] /// if let i = numbers.index(of: 40) { /// print(numbers.prefix(upTo: i)) /// } /// // Prints "[10, 20, 30]" /// /// Passing the collection's starting index as the `end` parameter results in /// an empty subsequence. /// /// print(numbers.prefix(upTo: numbers.startIndex)) /// // Prints "[]" /// /// - Parameter end: The "past the end" index of the resulting subsequence. /// `end` must be a valid index of the collection. /// - Returns: A subsequence up to, but not including, the `end` position. /// /// - Complexity: O(1) /// - SeeAlso: `prefix(through:)` func prefix(upTo end: Index) -> SubSequence /// Returns a subsequence from the specified position to the end of the /// collection. /// /// The following example searches for the index of the number `40` in an /// array of integers, and then prints the suffix of the array starting at /// that index: /// /// let numbers = [10, 20, 30, 40, 50, 60] /// if let i = numbers.index(of: 40) { /// print(numbers.suffix(from: i)) /// } /// // Prints "[40, 50, 60]" /// /// Passing the collection's `endIndex` as the `start` parameter results in /// an empty subsequence. /// /// print(numbers.suffix(from: numbers.endIndex)) /// // Prints "[]" /// /// - Parameter start: The index at which to start the resulting subsequence. /// `start` must be a valid index of the collection. /// - Returns: A subsequence starting at the `start` position. /// /// - Complexity: O(1) func suffix(from start: Index) -> SubSequence /// Returns a subsequence from the start of the collection through the /// specified position. /// /// The resulting subsequence *includes* the element at the position `end`. /// The following example searches for the index of the number `40` in an /// array of integers, and then prints the prefix of the array up to, and /// including, that index: /// /// let numbers = [10, 20, 30, 40, 50, 60] /// if let i = numbers.index(of: 40) { /// print(numbers.prefix(through: i)) /// } /// // Prints "[10, 20, 30, 40]" /// /// - Parameter end: The index of the last element to include in the /// resulting subsequence. `end` must be a valid index of the collection /// that is not equal to the `endIndex` property. /// - Returns: A subsequence up to, and including, the `end` position. /// /// - Complexity: O(1) /// - SeeAlso: `prefix(upTo:)` func prefix(through position: Index) -> SubSequence /// A Boolean value indicating whether the collection is empty. /// /// When you need to check whether your collection is empty, use the /// `isEmpty` property instead of checking that the `count` property is /// equal to zero. For collections that don't conform to /// `RandomAccessCollection`, accessing the `count` property iterates /// through the elements of the collection. /// /// let horseName = "Silver" /// if horseName.characters.isEmpty { /// print("I've been through the desert on a horse with no name.") /// } else { /// print("Hi ho, \(horseName)!") /// } /// // Prints "Hi ho, Silver!") /// /// - Complexity: O(1) var isEmpty: Bool { get } /// The number of elements in the collection. /// /// To check whether a collection is empty, use its `isEmpty` property /// instead of comparing `count` to zero. Unless the collection guarantees /// random-access performance, calculating `count` can be an O(*n*) /// operation. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. var count: IndexDistance { get } // The following requirement enables dispatching for index(of:) when // the element type is Equatable. /// Returns `Optional(Optional(index))` if an element was found /// or `Optional(nil)` if an element was determined to be missing; /// otherwise, `nil`. /// /// - Complexity: O(*n*) func _customIndexOfEquatableElement(_ element: Iterator.Element) -> Index?? /// The first element of the collection. /// /// If the collection is empty, the value of this property is `nil`. /// /// let numbers = [10, 20, 30, 40, 50] /// if let firstNumber = numbers.first { /// print(firstNumber) /// } /// // Prints "10" var first: Iterator.Element? { get } /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// /// let s = "Swift" /// let i = s.index(s.startIndex, offsetBy: 4) /// print(s[i]) /// // Prints "t" /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// - Returns: An index offset by `n` from the index `i`. If `n` is positive, /// this is the same value as the result of `n` calls to `index(after:)`. /// If `n` is negative, this is the same value as the result of `-n` calls /// to `index(before:)`. /// /// - SeeAlso: `index(_:offsetBy:limitedBy:)`, `formIndex(_:offsetBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. func index(_ i: Index, offsetBy n: IndexDistance) -> Index /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// The operation doesn't require going beyond the limiting `s.endIndex` /// value, so it succeeds. /// /// let s = "Swift" /// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) { /// print(s[i]) /// } /// // Prints "t" /// /// The next example attempts to retrieve an index six positions from /// `s.startIndex` but fails, because that distance is beyond the index /// passed as `limit`. /// /// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// - limit: A valid index of the collection to use as a limit. If `n > 0`, /// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a /// limit that is greater than `i` has no effect. /// - Returns: An index offset by `n` from the index `i`, unless that index /// would be beyond `limit` in the direction of movement. In that case, /// the method returns `nil`. /// /// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? /// Returns the distance between two indices. /// /// Unless the collection conforms to the `BidirectionalCollection` protocol, /// `start` must be less than or equal to `end`. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. The result can be /// negative only if the collection conforms to the /// `BidirectionalCollection` protocol. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the /// resulting distance. func distance(from start: Index, to end: Index) -> IndexDistance } /// Default implementation for forward collections. extension _Indexable { /// Replaces the given index with its successor. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. @inline(__always) public func formIndex(after i: inout Index) { i = index(after: i) } @_inlineable public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) { // FIXME: swift-3-indexing-model: tests. _precondition( bounds.lowerBound <= index, "out of bounds: index < startIndex") _precondition( index < bounds.upperBound, "out of bounds: index >= endIndex") } @_inlineable public func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>) { // FIXME: swift-3-indexing-model: tests. _precondition( bounds.lowerBound <= index, "out of bounds: index < startIndex") _precondition( index <= bounds.upperBound, "out of bounds: index > endIndex") } @_inlineable public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) { // FIXME: swift-3-indexing-model: tests. _precondition( bounds.lowerBound <= range.lowerBound, "out of bounds: range begins before startIndex") _precondition( range.lowerBound <= bounds.upperBound, "out of bounds: range ends after endIndex") _precondition( bounds.lowerBound <= range.upperBound, "out of bounds: range ends before bounds.lowerBound") _precondition( range.upperBound <= bounds.upperBound, "out of bounds: range begins after bounds.upperBound") } /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// /// let s = "Swift" /// let i = s.index(s.startIndex, offsetBy: 4) /// print(s[i]) /// // Prints "t" /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// - Returns: An index offset by `n` from the index `i`. If `n` is positive, /// this is the same value as the result of `n` calls to `index(after:)`. /// If `n` is negative, this is the same value as the result of `-n` calls /// to `index(before:)`. /// /// - SeeAlso: `index(_:offsetBy:limitedBy:)`, `formIndex(_:offsetBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. @_inlineable public func index(_ i: Index, offsetBy n: IndexDistance) -> Index { return self._advanceForward(i, by: n) } /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// The operation doesn't require going beyond the limiting `s.endIndex` /// value, so it succeeds. /// /// let s = "Swift" /// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) { /// print(s[i]) /// } /// // Prints "t" /// /// The next example attempts to retrieve an index six positions from /// `s.startIndex` but fails, because that distance is beyond the index /// passed as `limit`. /// /// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// - limit: A valid index of the collection to use as a limit. If `n > 0`, /// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a /// limit that is greater than `i` has no effect. /// - Returns: An index offset by `n` from the index `i`, unless that index /// would be beyond `limit` in the direction of movement. In that case, /// the method returns `nil`. /// /// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. @_inlineable public func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? { return self._advanceForward(i, by: n, limitedBy: limit) } /// Offsets the given index by the specified distance. /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// /// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. @_inlineable public func formIndex(_ i: inout Index, offsetBy n: IndexDistance) { i = index(i, offsetBy: n) } /// Offsets the given index by the specified distance, or so that it equals /// the given limiting index. /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// - limit: A valid index of the collection to use as a limit. If `n > 0`, /// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a /// limit that is greater than `i` has no effect. /// - Returns: `true` if `i` has been offset by exactly `n` steps without /// going beyond `limit`; otherwise, `false`. When the return value is /// `false`, the value of `i` is equal to `limit`. /// /// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. @_inlineable public func formIndex( _ i: inout Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Bool { if let advancedIndex = index(i, offsetBy: n, limitedBy: limit) { i = advancedIndex return true } i = limit return false } /// Returns the distance between two indices. /// /// Unless the collection conforms to the `BidirectionalCollection` protocol, /// `start` must be less than or equal to `end`. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. The result can be /// negative only if the collection conforms to the /// `BidirectionalCollection` protocol. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the /// resulting distance. @_inlineable public func distance(from start: Index, to end: Index) -> IndexDistance { _precondition(start <= end, "Only BidirectionalCollections can have end come before start") var start = start var count: IndexDistance = 0 while start != end { count = count + 1 formIndex(after: &start) } return count } /// Do not use this method directly; call advanced(by: n) instead. @_inlineable @_versioned @inline(__always) internal func _advanceForward(_ i: Index, by n: IndexDistance) -> Index { _precondition(n >= 0, "Only BidirectionalCollections can be advanced by a negative amount") var i = i for _ in stride(from: 0, to: n, by: 1) { formIndex(after: &i) } return i } /// Do not use this method directly; call advanced(by: n, limit) instead. @_inlineable @_versioned @inline(__always) internal func _advanceForward( _ i: Index, by n: IndexDistance, limitedBy limit: Index ) -> Index? { _precondition(n >= 0, "Only BidirectionalCollections can be advanced by a negative amount") var i = i for _ in stride(from: 0, to: n, by: 1) { if i == limit { return nil } formIndex(after: &i) } return i } } /// Supply the default `makeIterator()` method for `Collection` models /// that accept the default associated `Iterator`, /// `IndexingIterator<Self>`. extension Collection where Iterator == IndexingIterator<Self> { /// Returns an iterator over the elements of the collection. @inline(__always) public func makeIterator() -> IndexingIterator<Self> { return IndexingIterator(_elements: self) } } /// Supply the default "slicing" `subscript` for `Collection` models /// that accept the default associated `SubSequence`, `Slice<Self>`. extension Collection where SubSequence == Slice<Self> { /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection uses. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.index(of: "Evarts") // 4 /// print(streets[index!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. /// /// - Complexity: O(1) @_inlineable public subscript(bounds: Range<Index>) -> Slice<Self> { _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex) return Slice(base: self, bounds: bounds) } } extension Collection where SubSequence == Self { /// Removes and returns the first element of the collection. /// /// - Returns: The first element of the collection if the collection is /// not empty; otherwise, `nil`. /// /// - Complexity: O(1) @_inlineable public mutating func popFirst() -> Iterator.Element? { // TODO: swift-3-indexing-model - review the following guard !isEmpty else { return nil } let element = first! self = self[index(after: startIndex)..<endIndex] return element } } /// Default implementations of core requirements extension Collection { /// A Boolean value indicating whether the collection is empty. /// /// When you need to check whether your collection is empty, use the /// `isEmpty` property instead of checking that the `count` property is /// equal to zero. For collections that don't conform to /// `RandomAccessCollection`, accessing the `count` property iterates /// through the elements of the collection. /// /// let horseName = "Silver" /// if horseName.characters.isEmpty { /// print("I've been through the desert on a horse with no name.") /// } else { /// print("Hi ho, \(horseName)!") /// } /// // Prints "Hi ho, Silver!") /// /// - Complexity: O(1) @_inlineable public var isEmpty: Bool { return startIndex == endIndex } /// The first element of the collection. /// /// If the collection is empty, the value of this property is `nil`. /// /// let numbers = [10, 20, 30, 40, 50] /// if let firstNumber = numbers.first { /// print(firstNumber) /// } /// // Prints "10" @_inlineable public var first: Iterator.Element? { // NB: Accessing `startIndex` may not be O(1) for some lazy collections, // so instead of testing `isEmpty` and then returning the first element, // we'll just rely on the fact that the iterator always yields the // first element first. var i = makeIterator() return i.next() } // TODO: swift-3-indexing-model - uncomment and replace above ready (or should we still use the iterator one?) /// Returns the first element of `self`, or `nil` if `self` is empty. /// /// - Complexity: O(1) // public var first: Iterator.Element? { // return isEmpty ? nil : self[startIndex] // } /// A value less than or equal to the number of elements in the collection. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. @_inlineable public var underestimatedCount: Int { // TODO: swift-3-indexing-model - review the following return numericCast(count) } /// The number of elements in the collection. /// /// To check whether a collection is empty, use its `isEmpty` property /// instead of comparing `count` to zero. Unless the collection guarantees /// random-access performance, calculating `count` can be an O(*n*) /// operation. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. @_inlineable public var count: IndexDistance { return distance(from: startIndex, to: endIndex) } // TODO: swift-3-indexing-model - rename the following to _customIndexOfEquatable(element)? /// Customization point for `Collection.index(of:)`. /// /// Define this method if the collection can find an element in less than /// O(*n*) by exploiting collection-specific knowledge. /// /// - Returns: `nil` if a linear search should be attempted instead, /// `Optional(nil)` if the element was not found, or /// `Optional(Optional(index))` if an element was found. /// /// - Complexity: O(`count`). @_inlineable public // dispatching func _customIndexOfEquatableElement(_: Iterator.Element) -> Index?? { return nil } } //===----------------------------------------------------------------------===// // Default implementations for Collection //===----------------------------------------------------------------------===// extension Collection { /// Returns an array containing the results of mapping the given closure /// over the sequence's elements. /// /// In this example, `map` is used first to convert the names in the array /// to lowercase strings and then to count their characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let lowercaseNames = cast.map { $0.lowercaseString } /// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"] /// let letterCounts = cast.map { $0.characters.count } /// // 'letterCounts' == [6, 6, 3, 4] /// /// - Parameter transform: A mapping closure. `transform` accepts an /// element of this sequence as its parameter and returns a transformed /// value of the same or of a different type. /// - Returns: An array containing the transformed elements of this /// sequence. @_inlineable public func map<T>( _ transform: (Iterator.Element) throws -> T ) rethrows -> [T] { // TODO: swift-3-indexing-model - review the following let count: Int = numericCast(self.count) if count == 0 { return [] } var result = ContiguousArray<T>() result.reserveCapacity(count) var i = self.startIndex for _ in 0..<count { result.append(try transform(self[i])) formIndex(after: &i) } _expectEnd(of: self, is: i) return Array(result) } /// Returns a subsequence containing all but the given number of initial /// elements. /// /// If the number of elements to drop exceeds the number of elements in /// the collection, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst(2)) /// // Prints "[3, 4, 5]" /// print(numbers.dropFirst(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop from the beginning of /// the collection. `n` must be greater than or equal to zero. /// - Returns: A subsequence starting after the specified number of /// elements. /// /// - Complexity: O(*n*), where *n* is the number of elements to drop from /// the beginning of the collection. @_inlineable public func dropFirst(_ n: Int) -> SubSequence { _precondition(n >= 0, "Can't drop a negative number of elements from a collection") let start = index(startIndex, offsetBy: numericCast(n), limitedBy: endIndex) ?? endIndex return self[start..<endIndex] } /// Returns a subsequence containing all but the specified number of final /// elements. /// /// If the number of elements to drop exceeds the number of elements in the /// collection, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the /// collection. `n` must be greater than or equal to zero. /// - Returns: A subsequence that leaves off the specified number of elements /// at the end. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public func dropLast(_ n: Int) -> SubSequence { _precondition( n >= 0, "Can't drop a negative number of elements from a collection") let amount = Swift.max(0, numericCast(count) - n) let end = index(startIndex, offsetBy: numericCast(amount), limitedBy: endIndex) ?? endIndex return self[startIndex..<end] } /// Returns a subsequence by skipping elements while `predicate` returns /// `true` and returning the remaining elements. /// /// - Parameter predicate: A closure that takes an element of the /// sequence as its argument and returns `true` if the element should /// be skipped or `false` if it should be included. Once the predicate /// returns `false` it will not be called again. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public func drop( while predicate: (Iterator.Element) throws -> Bool ) rethrows -> SubSequence { var start = startIndex while try start != endIndex && predicate(self[start]) { formIndex(after: &start) } return self[start..<endIndex] } /// Returns a subsequence, up to the specified maximum length, containing /// the initial elements of the collection. /// /// If the maximum length exceeds the number of elements in the collection, /// the result contains all the elements in the collection. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.prefix(2)) /// // Prints "[1, 2]" /// print(numbers.prefix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. /// `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence starting at the beginning of this collection /// with at most `maxLength` elements. @_inlineable public func prefix(_ maxLength: Int) -> SubSequence { _precondition( maxLength >= 0, "Can't take a prefix of negative length from a collection") let end = index(startIndex, offsetBy: numericCast(maxLength), limitedBy: endIndex) ?? endIndex return self[startIndex..<end] } /// Returns a subsequence containing the initial elements until `predicate` /// returns `false` and skipping the remaining elements. /// /// - Parameter predicate: A closure that takes an element of the /// sequence as its argument and returns `true` if the element should /// be included or `false` if it should be excluded. Once the predicate /// returns `false` it will not be called again. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public func prefix( while predicate: (Iterator.Element) throws -> Bool ) rethrows -> SubSequence { var end = startIndex while try end != endIndex && predicate(self[end]) { formIndex(after: &end) } return self[startIndex..<end] } /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the collection. /// /// If the maximum length exceeds the number of elements in the collection, /// the result contains all the elements in the collection. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence terminating at the end of the collection with at /// most `maxLength` elements. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public func suffix(_ maxLength: Int) -> SubSequence { _precondition( maxLength >= 0, "Can't take a suffix of negative length from a collection") let amount = Swift.max(0, numericCast(count) - maxLength) let start = index(startIndex, offsetBy: numericCast(amount), limitedBy: endIndex) ?? endIndex return self[start..<endIndex] } /// Returns a subsequence from the start of the collection up to, but not /// including, the specified position. /// /// The resulting subsequence *does not include* the element at the position /// `end`. The following example searches for the index of the number `40` /// in an array of integers, and then prints the prefix of the array up to, /// but not including, that index: /// /// let numbers = [10, 20, 30, 40, 50, 60] /// if let i = numbers.index(of: 40) { /// print(numbers.prefix(upTo: i)) /// } /// // Prints "[10, 20, 30]" /// /// Passing the collection's starting index as the `end` parameter results in /// an empty subsequence. /// /// print(numbers.prefix(upTo: numbers.startIndex)) /// // Prints "[]" /// /// - Parameter end: The "past the end" index of the resulting subsequence. /// `end` must be a valid index of the collection. /// - Returns: A subsequence up to, but not including, the `end` position. /// /// - Complexity: O(1) /// - SeeAlso: `prefix(through:)` @_inlineable public func prefix(upTo end: Index) -> SubSequence { return self[startIndex..<end] } /// Returns a subsequence from the specified position to the end of the /// collection. /// /// The following example searches for the index of the number `40` in an /// array of integers, and then prints the suffix of the array starting at /// that index: /// /// let numbers = [10, 20, 30, 40, 50, 60] /// if let i = numbers.index(of: 40) { /// print(numbers.suffix(from: i)) /// } /// // Prints "[40, 50, 60]" /// /// Passing the collection's `endIndex` as the `start` parameter results in /// an empty subsequence. /// /// print(numbers.suffix(from: numbers.endIndex)) /// // Prints "[]" /// /// - Parameter start: The index at which to start the resulting subsequence. /// `start` must be a valid index of the collection. /// - Returns: A subsequence starting at the `start` position. /// /// - Complexity: O(1) @_inlineable public func suffix(from start: Index) -> SubSequence { return self[start..<endIndex] } /// Returns a subsequence from the start of the collection through the /// specified position. /// /// The resulting subsequence *includes* the element at the position `end`. /// The following example searches for the index of the number `40` in an /// array of integers, and then prints the prefix of the array up to, and /// including, that index: /// /// let numbers = [10, 20, 30, 40, 50, 60] /// if let i = numbers.index(of: 40) { /// print(numbers.prefix(through: i)) /// } /// // Prints "[10, 20, 30, 40]" /// /// - Parameter end: The index of the last element to include in the /// resulting subsequence. `end` must be a valid index of the collection /// that is not equal to the `endIndex` property. /// - Returns: A subsequence up to, and including, the `end` position. /// /// - Complexity: O(1) /// - SeeAlso: `prefix(upTo:)` @_inlineable public func prefix(through position: Index) -> SubSequence { return prefix(upTo: index(after: position)) } /// Returns the longest possible subsequences of the collection, in order, /// that don't contain elements satisfying the given predicate. /// /// The resulting array consists of at most `maxSplits + 1` subsequences. /// Elements that are used to split the sequence are not returned as part of /// any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string using a /// closure that matches spaces. The first use of `split` returns each word /// that was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.characters.split(whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print( /// line.characters.split( /// maxSplits: 1, whereSeparator: { $0 == " " } /// ).map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `false` for the `omittingEmptySubsequences` /// parameter, so the returned array contains empty strings where spaces /// were repeated. /// /// print(line.characters.split(omittingEmptySubsequences: false, whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - maxSplits: The maximum number of times to split the collection, or /// one less than the number of subsequences to return. If /// `maxSplits + 1` subsequences are returned, the last one is a suffix /// of the original collection containing the remaining elements. /// `maxSplits` must be greater than or equal to zero. The default value /// is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each pair of consecutive elements /// satisfying the `isSeparator` predicate and for each element at the /// start or end of the collection satisfying the `isSeparator` /// predicate. The default value is `true`. /// - isSeparator: A closure that takes an element as an argument and /// returns a Boolean value indicating whether the collection should be /// split at that element. /// - Returns: An array of subsequences, split from this collection's /// elements. @_inlineable public func split( maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Iterator.Element) throws -> Bool ) rethrows -> [SubSequence] { // TODO: swift-3-indexing-model - review the following _precondition(maxSplits >= 0, "Must take zero or more splits") var result: [SubSequence] = [] var subSequenceStart: Index = startIndex func appendSubsequence(end: Index) -> Bool { if subSequenceStart == end && omittingEmptySubsequences { return false } result.append(self[subSequenceStart..<end]) return true } if maxSplits == 0 || isEmpty { _ = appendSubsequence(end: endIndex) return result } var subSequenceEnd = subSequenceStart let cachedEndIndex = endIndex while subSequenceEnd != cachedEndIndex { if try isSeparator(self[subSequenceEnd]) { let didAppend = appendSubsequence(end: subSequenceEnd) formIndex(after: &subSequenceEnd) subSequenceStart = subSequenceEnd if didAppend && result.count == maxSplits { break } continue } formIndex(after: &subSequenceEnd) } if subSequenceStart != cachedEndIndex || !omittingEmptySubsequences { result.append(self[subSequenceStart..<cachedEndIndex]) } return result } } extension Collection where Iterator.Element : Equatable { /// Returns the longest possible subsequences of the collection, in order, /// around elements equal to the given element. /// /// The resulting array consists of at most `maxSplits + 1` subsequences. /// Elements that are used to split the collection are not returned as part /// of any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string at each /// space character (" "). The first use of `split` returns each word that /// was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.characters.split(separator: " ") /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print(line.characters.split(separator: " ", maxSplits: 1) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `false` for the `omittingEmptySubsequences` /// parameter, so the returned array contains empty strings where spaces /// were repeated. /// /// print(line.characters.split(separator: " ", omittingEmptySubsequences: false) /// .map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - separator: The element that should be split upon. /// - maxSplits: The maximum number of times to split the collection, or /// one less than the number of subsequences to return. If /// `maxSplits + 1` subsequences are returned, the last one is a suffix /// of the original collection containing the remaining elements. /// `maxSplits` must be greater than or equal to zero. The default value /// is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each consecutive pair of `separator` /// elements in the collection and for each instance of `separator` at /// the start or end of the collection. If `true`, only nonempty /// subsequences are returned. The default value is `true`. /// - Returns: An array of subsequences, split from this collection's /// elements. @_inlineable public func split( separator: Iterator.Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true ) -> [SubSequence] { // TODO: swift-3-indexing-model - review the following return split( maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, whereSeparator: { $0 == separator }) } } extension Collection where SubSequence == Self { /// Removes and returns the first element of the collection. /// /// The collection must not be empty. /// /// - Returns: The first element of the collection. /// /// - Complexity: O(1) /// - SeeAlso: `popFirst()` @_inlineable @discardableResult public mutating func removeFirst() -> Iterator.Element { // TODO: swift-3-indexing-model - review the following _precondition(!isEmpty, "can't remove items from an empty collection") let element = first! self = self[index(after: startIndex)..<endIndex] return element } /// Removes the specified number of elements from the beginning of the /// collection. /// /// - Parameter n: The number of elements to remove. `n` must be greater than /// or equal to zero, and must be less than or equal to the number of /// elements in the collection. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*). @_inlineable public mutating func removeFirst(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "can't remove more items from a collection than it contains") self = self[index(startIndex, offsetBy: numericCast(n))..<endIndex] } } extension Collection { @_inlineable public func _preprocessingPass<R>( _ preprocess: () throws -> R ) rethrows -> R? { return try preprocess() } } @available(*, unavailable, message: "Bit enum has been removed. Please use Int instead.") public enum Bit {} @available(*, unavailable, renamed: "IndexingIterator") public struct IndexingGenerator<Elements : _IndexableBase> {} @available(*, unavailable, renamed: "Collection") public typealias CollectionType = Collection extension Collection { @available(*, unavailable, renamed: "Iterator") public typealias Generator = Iterator @available(*, unavailable, renamed: "makeIterator()") public func generate() -> Iterator { Builtin.unreachable() } @available(*, unavailable, renamed: "getter:underestimatedCount()") public func underestimateCount() -> Int { Builtin.unreachable() } @available(*, unavailable, message: "Please use split(maxSplits:omittingEmptySubsequences:whereSeparator:) instead") public func split( _ maxSplit: Int = Int.max, allowEmptySlices: Bool = false, whereSeparator isSeparator: (Iterator.Element) throws -> Bool ) rethrows -> [SubSequence] { Builtin.unreachable() } } extension Collection where Iterator.Element : Equatable { @available(*, unavailable, message: "Please use split(separator:maxSplits:omittingEmptySubsequences:) instead") public func split( _ separator: Iterator.Element, maxSplit: Int = Int.max, allowEmptySlices: Bool = false ) -> [SubSequence] { Builtin.unreachable() } } @available(*, unavailable, message: "PermutationGenerator has been removed in Swift 3") public struct PermutationGenerator<C : Collection, Indices : Sequence> {}
apache-2.0
modnovolyk/MAVLinkSwift
Sources/FenceBreachCommonEnum.swift
1
943
// // FenceBreachCommonEnum.swift // MAVLink Protocol Swift Library // // Generated from ardupilotmega.xml, common.xml, uAvionix.xml on Tue Jan 17 2017 by mavgen_swift.py // https://github.com/modnovolyk/MAVLinkSwift // public enum FenceBreach: UInt8 { /// No last fence breach case none = 0 /// Breached minimum altitude case minalt = 1 /// Breached maximum altitude case maxalt = 2 /// Breached fence boundary case boundary = 3 } extension FenceBreach: Enumeration { public static var typeName = "FENCE_BREACH" public static var typeDescription = "" public static var allMembers = [none, minalt, maxalt, boundary] public static var membersDescriptions = [("FENCE_BREACH_NONE", "No last fence breach"), ("FENCE_BREACH_MINALT", "Breached minimum altitude"), ("FENCE_BREACH_MAXALT", "Breached maximum altitude"), ("FENCE_BREACH_BOUNDARY", "Breached fence boundary")] public static var enumEnd = UInt(4) }
mit
PoissonBallon/EasyRealm
Example/Tests/TestDelete.swift
1
2777
// // Test_Delete.swift // EasyRealm // // Created by Allan Vialatte on 10/03/2017. // import XCTest import RealmSwift import EasyRealm class TestDelete: XCTestCase { let testPokemon = ["Bulbasaur", "Ivysaur", "Venusaur","Charmander","Charmeleon","Charizard"] override func setUp() { super.setUp() Realm.Configuration.defaultConfiguration.inMemoryIdentifier = self.name } override func tearDown() { super.tearDown() let realm = try! Realm() try! realm.write { realm.deleteAll() } } func testDeleteAll() { HelpPokemon.pokemons(with: self.testPokemon).forEach { try! $0.er.save(update: true) } try! Pokemon.er.deleteAll() let count = try! Pokemon.er.all().count XCTAssertEqual(count, 0) } func testDeleteUnmanaged() { let pokemons = HelpPokemon.pokemons(with: self.testPokemon) pokemons.forEach { try! $0.er.save(update: true) } pokemons.forEach { pokemon in XCTAssert(pokemon.realm == nil) try! pokemon.er.delete() } let count = try! Pokemon.er.all().count XCTAssertEqual(count, 0) } func testDeleteManaged() { HelpPokemon.pokemons(with: self.testPokemon).forEach { try! $0.er.save(update: true) } let pokemons = try! Pokemon.er.all() pokemons.forEach { XCTAssert($0.realm != nil) try! $0.er.delete() } let count = try! Pokemon.er.all().count XCTAssertEqual(count, 0) } func testDeleteCascadeComplexManagedObject() { let trainer = Trainer() let pokedex = Pokedex() trainer.pokemons.append(objectsIn: HelpPokemon.allPokedex()) trainer.pokedex = pokedex try! trainer.er.save(update: true) XCTAssertEqual(try! Trainer.er.all().count, 1) XCTAssertEqual(try! Pokedex.er.all().count, 1) XCTAssertEqual(try! Pokemon.er.all().count, HelpPokemon.allPokedex().count) let managed = trainer.er.managed! try! managed.er.delete(with: .cascade) XCTAssertEqual(try! Trainer.er.all().count, 0) XCTAssertEqual(try! Pokedex.er.all().count, 0) XCTAssertEqual(try! Pokemon.er.all().count, 0) } func testDeleteCascadeComplexUnManagedObject() { let trainer = Trainer() let pokedex = Pokedex() trainer.pokemons.append(objectsIn: HelpPokemon.allPokedex()) trainer.pokedex = pokedex try! trainer.er.save(update: true) XCTAssertEqual(try! Trainer.er.all().count, 1) XCTAssertEqual(try! Pokedex.er.all().count, 1) XCTAssertEqual(try! Pokemon.er.all().count, HelpPokemon.allPokedex().count) try! trainer.er.delete(with: .cascade) XCTAssertEqual(try! Trainer.er.all().count, 0) XCTAssertEqual(try! Pokedex.er.all().count, 0) XCTAssertEqual(try! Pokemon.er.all().count, 0) } }
mit
rnystrom/GitHawk
Local Pods/GitHubAPI/Pods/Apollo/Sources/Apollo/ApolloClient.swift
1
10019
import Foundation import Dispatch /// An object that can be used to cancel an in progress action. public protocol Cancellable: class { /// Cancel an in progress action. func cancel() } /// A cache policy that specifies whether results should be fetched from the server or loaded from the local cache. public enum CachePolicy { /// Return data from the cache if available, else fetch results from the server. case returnCacheDataElseFetch /// Always fetch results from the server. case fetchIgnoringCacheData /// Return data from the cache if available, else return nil. case returnCacheDataDontFetch /// Return data from the cache if available, and always fetch results from the server. case returnCacheDataAndFetch } /// A handler for operation results. /// /// - Parameters: /// - result: The result of the performed operation, or `nil` if an error occurred. /// - error: An error that indicates why the mutation failed, or `nil` if the mutation was succesful. public typealias OperationResultHandler<Operation: GraphQLOperation> = (_ result: GraphQLResult<Operation.Data>?, _ error: Error?) -> Void /// The `ApolloClient` class provides the core API for Apollo. This API provides methods to fetch and watch queries, and to perform mutations. public class ApolloClient { let networkTransport: NetworkTransport let store: ApolloStore public var cacheKeyForObject: CacheKeyForObject? { get { return store.cacheKeyForObject } set { store.cacheKeyForObject = newValue } } private let queue: DispatchQueue private let operationQueue: OperationQueue /// Creates a client with the specified network transport and store. /// /// - Parameters: /// - networkTransport: A network transport used to send operations to a server. /// - store: A store used as a local cache. Defaults to an empty store backed by an in memory cache. public init(networkTransport: NetworkTransport, store: ApolloStore = ApolloStore(cache: InMemoryNormalizedCache())) { self.networkTransport = networkTransport self.store = store queue = DispatchQueue(label: "com.apollographql.ApolloClient", attributes: .concurrent) operationQueue = OperationQueue() } /// Creates a client with an HTTP network transport connecting to the specified URL. /// /// - Parameter url: The URL of a GraphQL server to connect to. public convenience init(url: URL) { self.init(networkTransport: HTTPNetworkTransport(url: url)) } /// Clears apollo cache /// /// - Returns: Promise public func clearCache() -> Promise<Void> { return store.clearCache() } /// Fetches a query from the server or from the local cache, depending on the current contents of the cache and the specified cache policy. /// /// - Parameters: /// - query: The query to fetch. /// - cachePolicy: A cache policy that specifies when results should be fetched from the server and when data should be loaded from the local cache. /// - queue: A dispatch queue on which the result handler will be called. Defaults to the main queue. /// - resultHandler: An optional closure that is called when query results are available or when an error occurs. /// - Returns: An object that can be used to cancel an in progress fetch. @discardableResult public func fetch<Query: GraphQLQuery>(query: Query, cachePolicy: CachePolicy = .returnCacheDataElseFetch, queue: DispatchQueue = DispatchQueue.main, resultHandler: OperationResultHandler<Query>? = nil) -> Cancellable { return _fetch(query: query, cachePolicy: cachePolicy, queue: queue, resultHandler: resultHandler) } func _fetch<Query: GraphQLQuery>(query: Query, cachePolicy: CachePolicy, context: UnsafeMutableRawPointer? = nil, queue: DispatchQueue, resultHandler: OperationResultHandler<Query>?) -> Cancellable { // If we don't have to go through the cache, there is no need to create an operation // and we can return a network task directly if cachePolicy == .fetchIgnoringCacheData { return send(operation: query, context: context, handlerQueue: queue, resultHandler: resultHandler) } else { let operation = FetchQueryOperation(client: self, query: query, cachePolicy: cachePolicy, context: context, handlerQueue: queue, resultHandler: resultHandler) operationQueue.addOperation(operation) return operation } } /// Watches a query by first fetching an initial result from the server or from the local cache, depending on the current contents of the cache and the specified cache policy. After the initial fetch, the returned query watcher object will get notified whenever any of the data the query result depends on changes in the local cache, and calls the result handler again with the new result. /// /// - Parameters: /// - query: The query to fetch. /// - cachePolicy: A cache policy that specifies when results should be fetched from the server or from the local cache. /// - queue: A dispatch queue on which the result handler will be called. Defaults to the main queue. /// - resultHandler: An optional closure that is called when query results are available or when an error occurs. /// - Returns: A query watcher object that can be used to control the watching behavior. public func watch<Query: GraphQLQuery>(query: Query, cachePolicy: CachePolicy = .returnCacheDataElseFetch, queue: DispatchQueue = DispatchQueue.main, resultHandler: @escaping OperationResultHandler<Query>) -> GraphQLQueryWatcher<Query> { let watcher = GraphQLQueryWatcher(client: self, query: query, handlerQueue: queue, resultHandler: resultHandler) watcher.fetch(cachePolicy: cachePolicy) return watcher } /// Performs a mutation by sending it to the server. /// /// - Parameters: /// - mutation: The mutation to perform. /// - queue: A dispatch queue on which the result handler will be called. Defaults to the main queue. /// - resultHandler: An optional closure that is called when mutation results are available or when an error occurs. /// - Returns: An object that can be used to cancel an in progress mutation. @discardableResult public func perform<Mutation: GraphQLMutation>(mutation: Mutation, queue: DispatchQueue = DispatchQueue.main, resultHandler: OperationResultHandler<Mutation>? = nil) -> Cancellable { return _perform(mutation: mutation, queue: queue, resultHandler: resultHandler) } func _perform<Mutation: GraphQLMutation>(mutation: Mutation, context: UnsafeMutableRawPointer? = nil, queue: DispatchQueue, resultHandler: OperationResultHandler<Mutation>?) -> Cancellable { return send(operation: mutation, context: context, handlerQueue: queue, resultHandler: resultHandler) } fileprivate func send<Operation: GraphQLOperation>(operation: Operation, context: UnsafeMutableRawPointer?, handlerQueue: DispatchQueue, resultHandler: OperationResultHandler<Operation>?) -> Cancellable { func notifyResultHandler(result: GraphQLResult<Operation.Data>?, error: Error?) { guard let resultHandler = resultHandler else { return } handlerQueue.async { resultHandler(result, error) } } return networkTransport.send(operation: operation) { (response, error) in guard let response = response else { notifyResultHandler(result: nil, error: error) return } firstly { try response.parseResult(cacheKeyForObject: self.store.cacheKeyForObject) }.andThen { (result, records) in notifyResultHandler(result: result, error: nil) if let records = records { self.store.publish(records: records, context: context).catch { error in preconditionFailure(String(describing: error)) } } }.catch { error in notifyResultHandler(result: nil, error: error) } } } } private final class FetchQueryOperation<Query: GraphQLQuery>: AsynchronousOperation, Cancellable { let client: ApolloClient let query: Query let cachePolicy: CachePolicy let context: UnsafeMutableRawPointer? let handlerQueue: DispatchQueue let resultHandler: OperationResultHandler<Query>? private var networkTask: Cancellable? init(client: ApolloClient, query: Query, cachePolicy: CachePolicy, context: UnsafeMutableRawPointer?, handlerQueue: DispatchQueue, resultHandler: OperationResultHandler<Query>?) { self.client = client self.query = query self.cachePolicy = cachePolicy self.context = context self.handlerQueue = handlerQueue self.resultHandler = resultHandler } override public func start() { if isCancelled { state = .finished return } state = .executing if cachePolicy == .fetchIgnoringCacheData { fetchFromNetwork() return } client.store.load(query: query) { (result, error) in if error == nil { self.notifyResultHandler(result: result, error: nil) if self.cachePolicy != .returnCacheDataAndFetch { self.state = .finished return } } if self.isCancelled { self.state = .finished return } if self.cachePolicy == .returnCacheDataDontFetch { self.notifyResultHandler(result: nil, error: nil) self.state = .finished return } self.fetchFromNetwork() } } func fetchFromNetwork() { networkTask = client.send(operation: query, context: context, handlerQueue: handlerQueue) { (result, error) in self.notifyResultHandler(result: result, error: error) self.state = .finished return } } override public func cancel() { super.cancel() networkTask?.cancel() } func notifyResultHandler(result: GraphQLResult<Query.Data>?, error: Error?) { guard let resultHandler = resultHandler else { return } handlerQueue.async { resultHandler(result, error) } } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/26198-swift-inflightdiagnostic.swift
1
447
// 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 enum S<T where h=i{class B<w{func f:B<T>struct B
apache-2.0
cnoon/swift-compiler-crashes
crashes-duplicates/14748-resolvetypedecl.swift
11
233
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct S<T where g: b if true { class A { { } var : b func b: S
mit
congncif/PagingDataController
Example/Pods/SiFUtilities/Core/UIViewController++.swift
1
268
// // UIViewController++.swift // SiFUtilities // // Created by NGUYEN CHI CONG on 7/13/19. // import Foundation import UIKit extension UIViewController { public var navigationBar: UINavigationBar? { return navigationController?.navigationBar } }
mit
cnoon/swift-compiler-crashes
fixed/14968-swift-nominaltypedecl-getprotocols.swift
11
217
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol c{ func a protocol c func a(e:c } Void{
mit
cnoon/swift-compiler-crashes
crashes-duplicates/03159-swift-sourcemanager-getmessage.swift
11
324
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var e(h(v: C { protocol a { enum S<T { struct S<T where g: AnyObject) { func g: a { struct S<T.h(v: d = a struct Q<T where g<D> Void>(") class case c, var
mit
bharat-madept/AnimatedSegmentedControl
Segment/ViewController.swift
1
960
// // ViewController.swift // Segment // // Created by Bharat Lal on 27/08/17. // Copyright © 2017 Bharat Lal. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var selectedItem: UILabel! @IBOutlet weak var segmentedControl: CustomSegmentedControl! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //segmentedControl.items = ["My item", "Your item", "Our item"] segmentedControl.addTarget(self, action: #selector(ViewController.segmentedValueChanged(_:)), for: .valueChanged) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func segmentedValueChanged(_ sender: CustomSegmentedControl){ selectedItem.text = "\(sender.selectedIndex) selected" } }
mit
ra1028/OwnKit
OwnKit/Extension/Array+OwnKit.swift
1
449
// // Array+OwnKit.swift // OwnKit // // Created by Ryo Aoyama on 12/10/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // public extension Array { var isEmpty: Bool { return count <= 0 } var isNotEmpty: Bool { return !isEmpty } func get(safeIndex: Int) -> Element? { if count > safeIndex && safeIndex >= 0 { return self[safeIndex] } return nil } }
mit
riteshhgupta/RGListKit
Pods/ProtoKit/Source/ListableView/UIKit/ListableView+UICollectionView.swift
1
1425
// // ListableView+UICollectionView.swift // RGListKit // // Created by Ritesh Gupta on 07/12/17. // Copyright © 2017 Ritesh. All rights reserved. // import Foundation import UIKit extension UICollectionView: ListableView { public var listDelegate: ListableViewDelegate? { get { return delegate as? ListableViewDelegate } set { delegate = newValue as? UICollectionViewDelegateFlowLayout } } public var listDatasource: ListableViewDatasource? { get { return dataSource as? ListableViewDatasource } set { dataSource = newValue as? UICollectionViewDataSource } } public func registerItem(with nib: UINib, for identifier: String) { register(nib, forCellWithReuseIdentifier: identifier) } public func registerHeaderFooterItem(with nib: UINib, for identifier: String, of kind: String) { register(nib, forSupplementaryViewOfKind: kind, withReuseIdentifier: identifier) } public func reusableItem<Item: ReusableView>(withIdentifier identifier: String, for indexPath: IndexPath) -> Item { return dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! Item } public func reusableHeaderFooterItem<Item: ReusableView>(withIdentifier identifier: String, for indexPath: IndexPath, of kind: String) -> Item? { return dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: identifier, for: indexPath) as? Item } public func reloadItems() { reloadData() } }
mit
LuAndreCast/iOS_WatchProjects
watchOS2/time Notification/timezoneModel.swift
1
1584
// // timezones.swift // timeNotification // // Created by Luis Castillo on 1/21/16. // Copyright © 2016 LC. All rights reserved. // import UIKit class timezoneModel: NSObject { private var timezones:NSArray? override init() { if let pathOfFile = NSBundle .mainBundle() .pathForResource("timezones", ofType: "plist") { if let timezonesFromFile = NSArray(contentsOfFile: pathOfFile) { timezones = timezonesFromFile }// }// } //MARK: - Load Timezones func reloadTimeZones() { if let pathOfFile = NSBundle .mainBundle() .pathForResource("timezones", ofType: "plist") { if let timezonesFromFile = NSArray(contentsOfFile: pathOfFile) { timezones = timezonesFromFile }// }// }//eom func getTimeZones()->NSArray? { let copyOfTimezones:NSArray? = timezones?.mutableCopy() as? NSArray return copyOfTimezones } func getTimeZoneByAbbrev(abbrev: String)-> String { var timeString:String = "" // let time:NSDate = NSDate() let timeZone = NSTimeZone(abbreviation: abbrev) let formatter:NSDateFormatter = NSDateFormatter() formatter.timeZone = timeZone formatter.dateFormat = "h:mm a" timeString = formatter.stringFromDate(time) return timeString }//eom }
mit
box/box-ios-sdk
Sources/Modules/FileRequestsModule.swift
1
4010
// // FileRequestsModule.swift // BoxSDK-iOS // // Created by Artur Jankowski on 09/08/2022. // Copyright © 2022 box. All rights reserved. // import Foundation /// Provides management of FileRequests public class FileRequestsModule { /// Required for communicating with Box APIs. weak var boxClient: BoxClient! // swiftlint:disable:previous implicitly_unwrapped_optional /// Initializer /// /// - Parameter boxClient: Required for communicating with Box APIs. init(boxClient: BoxClient) { self.boxClient = boxClient } /// Retrieves the information about a file request by ID. /// /// - Parameters: /// - fileRequestId: The unique identifier that represent a file request. /// - completion: Returns a FileRequest response object if successful otherwise a BoxSDKError. public func get( fileRequestId: String, completion: @escaping Callback<FileRequest> ) { boxClient.get( url: URL.boxAPIEndpoint("/2.0/file_requests/\(fileRequestId)", configuration: boxClient.configuration), completion: ResponseHandler.default(wrapping: completion) ) } /// Updates a file request. This can be used to activate or deactivate a file request. /// /// - Parameters: /// - fileRequestId: The unique identifier that represent a file request. /// - ifMatch: Ensures this item hasn't recently changed before making changes. /// Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `412 Precondition Failed` if it has changed since. (optional) /// - updateRequest: The `FileRequestUpdateRequest` object which provides the fields that can be updated. /// - completion: Returns a FileRequest response object if successful otherwise a BoxSDKError. public func update( fileRequestId: String, ifMatch: String? = nil, updateRequest: FileRequestUpdateRequest, completion: @escaping Callback<FileRequest> ) { var headers: BoxHTTPHeaders = [:] if let unwrappedIfMatch = ifMatch { headers[BoxHTTPHeaderKey.ifMatch] = unwrappedIfMatch } boxClient.put( url: URL.boxAPIEndpoint("/2.0/file_requests/\(fileRequestId)", configuration: boxClient.configuration), httpHeaders: headers, json: updateRequest.bodyDict, completion: ResponseHandler.default(wrapping: completion) ) } /// Copies an existing file request that is already present on one folder, and applies it to another folder. /// /// - Parameters: /// - fileRequestId: The unique identifier that represent a file request. /// - copyRequest: The `FileRequestCopyRequest` object which provides required and optional fields used when copying, like: folder(required), title(optional), etc. /// - completion: Returns a FileRequest response object if successful otherwise a BoxSDKError. public func copy( fileRequestId: String, copyRequest: FileRequestCopyRequest, completion: @escaping Callback<FileRequest> ) { boxClient.post( url: URL.boxAPIEndpoint("/2.0/file_requests/\(fileRequestId)/copy", configuration: boxClient.configuration), json: copyRequest.bodyDict, completion: ResponseHandler.default(wrapping: completion) ) } /// Deletes a file request permanently. /// /// - Parameters: /// - fileRequestId: The unique identifier that represent a file request. /// - completion: Returns response object if successful otherwise a BoxSDKError. public func delete( fileRequestId: String, completion: @escaping Callback<Void> ) { boxClient.delete( url: URL.boxAPIEndpoint("/2.0/file_requests/\(fileRequestId)", configuration: boxClient.configuration), completion: ResponseHandler.default(wrapping: completion) ) } }
apache-2.0
boluomeng/Charts
ChartsRealm/Classes/Data/RealmBarDataSet.swift
1
8946
// // RealmBarDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics import Charts import Realm import Realm.Dynamic open class RealmBarDataSet: RealmBarLineScatterCandleBubbleDataSet, IBarChartDataSet { open override func initialize() { self.highlightColor = NSUIColor.black } public required init() { super.init() } public override init(results: RLMResults<RLMObject>?, yValueField: String, xIndexField: String?, label: String?) { super.init(results: results, yValueField: yValueField, xIndexField: xIndexField, label: label) } public init(results: RLMResults<RLMObject>?, yValueField: String, xIndexField: String?, stackValueField: String, label: String?) { _stackValueField = stackValueField super.init(results: results, yValueField: yValueField, xIndexField: xIndexField, label: label) } public convenience init(results: RLMResults<RLMObject>?, yValueField: String, xIndexField: String?, stackValueField: String) { self.init(results: results, yValueField: yValueField, xIndexField: xIndexField, stackValueField: stackValueField, label: "DataSet") } public convenience init(results: RLMResults<RLMObject>?, yValueField: String, stackValueField: String, label: String) { self.init(results: results, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField, label: label) } public convenience init(results: RLMResults<RLMObject>?, yValueField: String, stackValueField: String) { self.init(results: results, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField) } public override init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, xIndexField: String?, label: String?) { super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: xIndexField, label: label) } public init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, xIndexField: String?, stackValueField: String, label: String?) { _stackValueField = stackValueField super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: xIndexField, label: label) } public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, xIndexField: String?, stackValueField: String) { self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField) } public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, stackValueField: String, label: String?) { self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField, label: label) } public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, stackValueField: String) { self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField, label: nil) } open override func notifyDataSetChanged() { _cache.removeAll() ensureCache(start: 0, end: entryCount - 1) self.calcStackSize(_cache as! [BarChartDataEntry]) super.notifyDataSetChanged() } // MARK: - Data functions and accessors internal var _stackValueField: String? /// the maximum number of bars that are stacked upon each other, this value /// is calculated from the Entries that are added to the DataSet private var _stackSize = 1 internal override func buildEntryFromResultObject(_ object: RLMObject, atIndex: UInt) -> ChartDataEntry { let value = object[_yValueField!] let entry: BarChartDataEntry if value is RLMArray { var values = [Double]() for val in value as! RLMArray { values.append(val[_stackValueField!] as! Double) } entry = BarChartDataEntry(values: values, xIndex: _xIndexField == nil ? Int(atIndex) : object[_xIndexField!] as! Int) } else { entry = BarChartDataEntry(value: value as! Double, xIndex: _xIndexField == nil ? Int(atIndex) : object[_xIndexField!] as! Int) } return entry } /// calculates the maximum stacksize that occurs in the Entries array of this DataSet private func calcStackSize(_ yVals: [BarChartDataEntry]!) { for i in 0 ..< yVals.count { if let vals = yVals[i].values { if vals.count > _stackSize { _stackSize = vals.count } } } } open override func calcMinMax(start : Int, end: Int) { let yValCount = self.entryCount if yValCount == 0 { return } var endValue : Int if end == 0 || end >= yValCount { endValue = yValCount - 1 } else { endValue = end } ensureCache(start: start, end: endValue) if _cache.count == 0 { return } _lastStart = start _lastEnd = endValue _yMin = DBL_MAX _yMax = -DBL_MAX for i in stride(from: start, through: endValue, by: 1) { if let e = _cache[i - _cacheFirst] as? BarChartDataEntry { if !e.value.isNaN { if e.values == nil { if e.value < _yMin { _yMin = e.value } if e.value > _yMax { _yMax = e.value } } else { if -e.negativeSum < _yMin { _yMin = -e.negativeSum } if e.positiveSum > _yMax { _yMax = e.positiveSum } } } } } if (_yMin == DBL_MAX) { _yMin = 0.0 _yMax = 0.0 } } /// - returns: the maximum number of bars that can be stacked upon another in this DataSet. open var stackSize: Int { return _stackSize } /// - returns: true if this DataSet is stacked (stacksize > 1) or not. open var isStacked: Bool { return _stackSize > 1 ? true : false } /// array of labels used to describe the different values of the stacked bars open var stackLabels: [String] = ["Stack"] // MARK: - Styling functions and accessors /// space indicator between the bars in percentage of the whole width of one value (0.15 == 15% of bar width) open var barSpace: CGFloat = 0.15 /// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value open var barShadowColor = NSUIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0) /// the width used for drawing borders around the bars. If borderWidth == 0, no border will be drawn. open var barBorderWidth : CGFloat = 0.0 /// the color drawing borders around the bars. open var barBorderColor = NSUIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0) /// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque) open var highlightAlpha = CGFloat(120.0 / 255.0) // MARK: - NSCopying open override func copyWithZone(_ zone: NSZone?) -> Any { let copy = super.copyWithZone(zone) as! RealmBarDataSet copy._stackSize = _stackSize copy.stackLabels = stackLabels copy.barSpace = barSpace copy.barShadowColor = barShadowColor copy.highlightAlpha = highlightAlpha return copy } }
apache-2.0
plutoless/fgo-pluto
FgoPluto/FgoPluto/model/Material.swift
1
2266
// // Material.swift // FgoPluto // // Created by Zhang, Qianze on 17/09/2017. // Copyright © 2017 Plutoless Studio. All rights reserved. // import Foundation import UIKit import RealmSwift class Material:BaseObject { dynamic var id:Int = 0 dynamic var text:String = "" dynamic var quantity:Int64 = 0 dynamic var kind:Int{ get{ return self.kindFromId() } } dynamic lazy var image:UIImage? = { return UIImage(named: "material-\(self.id).jpg") }() override func fillvalues(realm: Realm, data: [String : AnyObject]) { super.fillvalues(realm: realm, data: data) guard let id = Int(data["id"] as? String ?? "0") else {return} self.id = id } override static func primaryKey() -> String? { return "id" } override static func indexedProperties() -> [String] { return ["id"] } override static func ignoredProperties() -> [String] { return ["image", "kind"] } private func kindFromId() -> Int{ let mid = self.id if(mid >= 100 && mid < 110){ return 0 } else if(mid >= 110 && mid < 120){ return 1 } else if(mid >= 200 && mid < 210){ return 2 } else if(mid >= 210 && mid < 220){ return 3 } else if(mid >= 220 && mid < 230){ return 4 } else if(mid >= 300 && mid < 400){ return 5 } else if(mid >= 400 && mid < 500){ return 6 } else if(mid >= 500 && mid < 600){ return 7 } else if(mid == 800 || mid == 900){ return 8 } return -1 } internal static func kind_name(kind:Int) -> String{ switch kind { case 0: return "银棋" case 1: return "金棋" case 2: return "辉石" case 3: return "魔石" case 4: return "秘石" case 5: return "铜素材" case 6: return "银素材" case 7: return "金素材" case 8: return "特殊素材" default: return "\(kind)" } } }
apache-2.0
viviancrs/fanboy
FanBoy/Source/Infrastructure/Error Handling/ErrorTypes/TechnicalError.swift
1
272
// // TechnicalError.swift // FanBoy // // Created by SalmoJunior on 8/17/16. // Copyright © 2016 CI&T. All rights reserved. // enum TechnicalError: Error { case parse(String) case httpError(Int) case requestError case invalidURL case notFound }
gpl-3.0
atl009/WordPress-iOS
WordPress/Classes/ViewRelated/System/FancyAlertViewController.swift
1
14526
import UIKit /// A small card-like view displaying helpful information or prompts to the user. /// Initialize using the `controllerWithConfiguration` static method. /// class FancyAlertViewController: UIViewController { /// Intended method of initialization static func controllerWithConfiguration(configuration: Config) -> FancyAlertViewController { let infoController = controller() infoController.configuration = configuration return infoController } private static func controller() -> FancyAlertViewController { return UIStoryboard(name: "FancyAlerts", bundle: Bundle.main) .instantiateInitialViewController() as! FancyAlertViewController } enum DividerPosition { case top case bottom } /// Enapsulates values for all UI components of the info dialog. /// struct Config { /// Convenience alias for a title and a handler for a UIButton typealias ButtonConfig = (title: String, handler: FancyAlertButtonHandler?) /// The title of the dialog let titleText: String? /// The body text of the dialog let bodyText: String? /// The image displayed at the top of the dialog let headerImage: UIImage? /// The position of the horizontal rule let dividerPosition: DividerPosition? /// Title / handler for the primary button on the dialog let defaultButton: ButtonConfig? /// Title / handler for the de-emphasised cancel button on the dialog let cancelButton: ButtonConfig? /// Title / handler for a link-style button displayed beneath the body text let moreInfoButton: ButtonConfig? /// Title handler for a small 'tag' style button displayed next to the title let titleAccessoryButton: ButtonConfig? /// A block to execute after this view controller has been dismissed let dismissAction: (() -> Void)? } // MARK: - Constants private struct Constants { static let cornerRadius: CGFloat = 15.0 static let buttonFont = WPStyleGuide.fontForTextStyle(.headline) static let moreInfoFont = WPStyleGuide.fontForTextStyle(.subheadline, fontWeight: UIFontWeightSemibold) static let bodyFont = WPStyleGuide.fontForTextStyle(.body) static let headerImageVerticalConstraintCompact: CGFloat = 0.0 static let headerImageVerticalConstraintRegular: CGFloat = 20.0 static let headerBackgroundColor = WPStyleGuide.lightGrey() static let fadeAnimationDuration: TimeInterval = 0.3 static let resizeAnimationDuration: TimeInterval = 0.3 static let resizeAnimationDelay: TimeInterval = 0.3 } // MARK: - IBOutlets /// Wraps the entire view to give it a background and rounded corners @IBOutlet private weak var wrapperView: UIView! @IBOutlet private weak var headerImageWrapperView: UIView! @IBOutlet private(set) weak var headerImageView: UIImageView! private var headerImageViewHeightConstraint: NSLayoutConstraint? @IBOutlet private weak var headerImageViewTopConstraint: NSLayoutConstraint! @IBOutlet private weak var headerImageViewBottomConstraint: NSLayoutConstraint! @IBOutlet private weak var headerImageViewWrapperBottomConstraint: NSLayoutConstraint? @IBOutlet private weak var buttonWrapperViewTopConstraint: NSLayoutConstraint? @IBOutlet private var titleAccessoryButtonTrailingConstraint: NSLayoutConstraint! @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var bodyLabel: UILabel! /// Divides the primary buttons from the rest of the dialog @IBOutlet private weak var topDividerView: UIView! @IBOutlet private weak var bottomDividerView: UIView! @IBOutlet private weak var buttonWrapperView: UIView! @IBOutlet private weak var buttonStackView: UIStackView! @IBOutlet private weak var cancelButton: UIButton! @IBOutlet private weak var defaultButton: UIButton! @IBOutlet private weak var moreInfoButton: UIButton! @IBOutlet private weak var titleAccessoryButton: UIButton! @IBOutlet private var contentViews: [UIView]! /// Gesture recognizer for taps on the dialog if no buttons are present /// fileprivate var dismissGestureRecognizer: UITapGestureRecognizer! /// Allows compact alerts to be dismissed by 'flinging' them offscreen /// fileprivate var handler: FlingableViewHandler! /// Stores handlers for buttons passed in the current configuration /// private var buttonHandlers = [UIButton: FancyAlertButtonHandler]() typealias FancyAlertButtonHandler = (FancyAlertViewController, UIButton) -> Void private(set) var configuration: Config? /// The configuration determines the content and visibility of all UI /// components in the dialog. Changing this value after presenting the /// dialog is supported, and will result in the view (optionally) fading /// to the new values and resizing itself to fit. /// /// - parameters: /// - configuration: A new configuration to display. /// - animated: If true, the UI will animate as it updates to reflect the new configuration. /// - alongside: An optional animation block which will be animated /// alongside the new configuration's fade in animation. /// func setViewConfiguration(_ configuration: Config, animated: Bool, alongside animation: ((FancyAlertViewController) -> Void)? = nil) { self.configuration = configuration if animated { fadeAllViews(visible: false, completion: { _ in UIView.animate(withDuration: Constants.resizeAnimationDuration, delay: Constants.resizeAnimationDelay, options: [], animations: { self.updateViewConfiguration() }, completion: { _ in self.fadeAllViews(visible: true, alongside: animation) }) }) } else { updateViewConfiguration() } } override func viewDidLoad() { super.viewDidLoad() accessibilityViewIsModal = true view.backgroundColor = .clear dismissGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissTapped)) view.addGestureRecognizer(dismissGestureRecognizer) wrapperView.layer.masksToBounds = true wrapperView.layer.cornerRadius = Constants.cornerRadius headerImageWrapperView.backgroundColor = Constants.headerBackgroundColor topDividerView.backgroundColor = WPStyleGuide.greyLighten30() bottomDividerView.backgroundColor = WPStyleGuide.lightGrey() WPStyleGuide.configureLabel(titleLabel, textStyle: .title2, fontWeight: UIFontWeightSemibold) titleLabel.textColor = WPStyleGuide.darkGrey() WPStyleGuide.configureLabel(bodyLabel, textStyle: .body) bodyLabel.textColor = WPStyleGuide.darkGrey() WPStyleGuide.configureBetaButton(titleAccessoryButton) defaultButton.titleLabel?.font = Constants.buttonFont cancelButton.titleLabel?.font = Constants.buttonFont moreInfoButton.titleLabel?.font = Constants.moreInfoFont moreInfoButton.tintColor = WPStyleGuide.wordPressBlue() updateViewConfiguration() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) updateFlingableViewHandler() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if traitCollection.containsTraits(in: UITraitCollection(verticalSizeClass: .compact)) { headerImageWrapperView.isHiddenInStackView = true } else if let _ = configuration?.headerImage { headerImageWrapperView.isHiddenInStackView = false } } /// MARK: - View configuration private func updateViewConfiguration() { guard isViewLoaded else { return } guard let configuration = configuration else { return } buttonHandlers.removeAll() titleLabel.text = configuration.titleText bodyLabel.text = configuration.bodyText updateDivider() updateHeaderImage() update(defaultButton, with: configuration.defaultButton) update(cancelButton, with: configuration.cancelButton) update(moreInfoButton, with: configuration.moreInfoButton) update(titleAccessoryButton, with: configuration.titleAccessoryButton) // If we have no title accessory button, we need to // disable the trailing constraint to allow the title to flow correctly titleAccessoryButtonTrailingConstraint.isActive = (configuration.titleAccessoryButton != nil) // If both primary buttons are hidden, we'll hide the bottom area of the dialog buttonWrapperView.isHiddenInStackView = isButtonless // If both primary buttons are hidden, we'll shrink the header image view down a little let constant = isImageCompact ? Constants.headerImageVerticalConstraintCompact : Constants.headerImageVerticalConstraintRegular headerImageViewTopConstraint.constant = constant headerImageViewBottomConstraint.constant = constant updateFlingableViewHandler() // If both primary buttons are hidden, the user can tap anywhere on the dialog to dismiss it dismissGestureRecognizer.isEnabled = isButtonless view.layoutIfNeeded() titleLabel.accessibilityHint = (isButtonless) ? NSLocalizedString("Double tap to dismiss", comment: "Voiceover accessibility hint informing the user they can double tap a modal alert to dismiss it") : nil UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, titleLabel) } private func updateHeaderImage() { if let headerImage = configuration?.headerImage { headerImageView.image = headerImage headerImageWrapperView.isHiddenInStackView = false if let heightConstraint = headerImageViewHeightConstraint { headerImageView.removeConstraint(heightConstraint) } // set the aspect ratio constraint let imageAspectRatio = headerImage.size.height / headerImage.size.width headerImageViewHeightConstraint = headerImageView.heightAnchor.constraint(equalTo: headerImageView.widthAnchor, multiplier: imageAspectRatio) headerImageViewHeightConstraint?.isActive = true } else { headerImageWrapperView.isHiddenInStackView = true } } private func updateDivider() { topDividerView.isHiddenInStackView = configuration?.dividerPosition == .bottom bottomDividerView.isHiddenInStackView = isButtonless || configuration?.dividerPosition == .top // the image touches the divider if it is at the top headerImageViewWrapperBottomConstraint?.constant = configuration?.dividerPosition == .top ? 0.0 : Constants.headerImageVerticalConstraintRegular buttonWrapperViewTopConstraint?.constant = configuration?.dividerPosition == .top ? 0.0 : Constants.headerImageVerticalConstraintRegular } private func update(_ button: UIButton, with buttonConfig: Config.ButtonConfig?) { guard let buttonConfig = buttonConfig else { button.isHiddenInStackView = true return } button.isHiddenInStackView = false button.setTitle(buttonConfig.title, for: .normal) buttonHandlers[button] = buttonConfig.handler } private func updateFlingableViewHandler() { guard view.superview != nil else { return } if handler == nil { handler = FlingableViewHandler(targetView: view) handler.delegate = self } // Flingable handler is active if both buttons are hidden handler.isActive = isButtonless } /// An alert is buttonless if both of the bottom buttons are hidden /// private var isButtonless: Bool { return defaultButton.isHiddenInStackView && cancelButton.isHiddenInStackView } /// The header image is compact if the divider is at the top or the alert is buttonless /// private var isImageCompact: Bool { return configuration?.dividerPosition == .top || isButtonless } // MARK: - Animation func fadeAllViews(visible: Bool, alongside animation: ((FancyAlertViewController) -> Void)? = nil, completion: ((Bool) -> Void)? = nil) { UIView.animate(withDuration: Constants.fadeAnimationDuration, animations: { self.contentViews.forEach({ $0.alpha = (visible) ? WPAlphaFull : WPAlphaZero }) animation?(self) }, completion: completion) } // MARK: - Actions @objc fileprivate func dismissTapped() { dismiss(animated: true, completion: { self.configuration?.dismissAction?() }) } @IBAction private func buttonTapped(_ sender: UIButton) { // Offload to a handler if one is configured for this button if let handler = buttonHandlers[sender] { handler(self, sender) } } override func accessibilityPerformEscape() -> Bool { dismissTapped() return true } } // MARK: - FlingableViewHandlerDelegate extension FancyAlertViewController: FlingableViewHandlerDelegate { func flingableViewHandlerDidBeginRecognizingGesture(_ handler: FlingableViewHandler) { dismissGestureRecognizer.isEnabled = false } func flingableViewHandlerWasCancelled(_ handler: FlingableViewHandler) { dismissGestureRecognizer.isEnabled = true } func flingableViewHandlerDidEndRecognizingGesture(_ handler: FlingableViewHandler) { dismissTapped() } } private extension UIView { /// Required to work around a bug in UIStackView where items don't become /// hidden / unhidden correctly if you set their `isHidden` property /// to the same value twice in a row. See http://www.openradar.me/22819594 /// var isHiddenInStackView: Bool { set { if isHidden != newValue { isHidden = newValue } } get { return isHidden } } }
gpl-2.0
WeltN24/PiedPiper
Sources/PiedPiper/Promise.swift
1
6622
import Foundation /// This class is a Future computation, where you can attach failure and success callbacks. open class Promise<T>: Async { public typealias Value = T private var failureListeners: [(Error) -> Void] = [] private var successListeners: [(T) -> Void] = [] private var cancelListeners: [() -> Void] = [] private var error: Error? private var value: T? private var canceled = false private let successLock: ReadWriteLock = PThreadReadWriteLock() private let failureLock: ReadWriteLock = PThreadReadWriteLock() private let cancelLock: ReadWriteLock = PThreadReadWriteLock() /// The Future associated to this Promise private weak var _future: Future<T>? public var future: Future<T> { if let _future = _future { return _future } let newFuture = Future(promise: self) _future = newFuture return newFuture } /** Creates a new Promise */ public init() {} convenience init(_ value: T) { self.init() succeed(value) } convenience init(value: T?, error: Error) { self.init() if let value = value { succeed(value) } else { fail(error) } } convenience init(_ error: Error) { self.init() fail(error) } /** Mimics the given Future, so that it fails or succeeds when the stamps does so (in addition to its pre-existing behavior) Moreover, if the mimiced Future is canceled, the Promise will also cancel itself - parameter stamp: The Future to mimic - returns: The Promise itself */ @discardableResult public func mimic(_ stamp: Future<T>) -> Promise<T> { stamp.onCompletion { result in switch result { case .success(let value): self.succeed(value) case .error(let error): self.fail(error) case .cancelled: self.cancel() } } return self } /** Mimics the given Result, so that it fails or succeeds when the stamps does so (in addition to its pre-existing behavior) Moreover, if the mimiced Result is canceled, the Promise will also cancel itself - parameter stamp: The Result to mimic - returns: The Promise itself */ @discardableResult public func mimic(_ stamp: Result<T>) -> Promise<T> { switch stamp { case .success(let value): self.succeed(value) case .error(let error): self.fail(error) case .cancelled: self.cancel() } return self } private func clearListeners() { successLock.withWriteLock { successListeners.removeAll() } failureLock.withWriteLock { failureListeners.removeAll() } cancelLock.withWriteLock { cancelListeners.removeAll() } } /** Makes the Promise succeed with a value - parameter value: The value found for the Promise Calling this method makes all the listeners get the onSuccess callback */ public func succeed(_ value: T) { guard self.error == nil else { return } guard self.value == nil else { return } guard self.canceled == false else { return } self.value = value successLock.withReadLock { successListeners.forEach { listener in listener(value) } } clearListeners() } /** Makes the Promise fail with an error - parameter error: The optional error that caused the Promise to fail Calling this method makes all the listeners get the onFailure callback */ public func fail(_ error: Error) { guard self.error == nil else { return } guard self.value == nil else { return } guard self.canceled == false else { return } self.error = error failureLock.withReadLock { failureListeners.forEach { listener in listener(error) } } clearListeners() } /** Cancels the Promise Calling this method makes all the listeners get the onCancel callback (but not the onFailure callback) */ public func cancel() { guard self.error == nil else { return } guard self.value == nil else { return } guard self.canceled == false else { return } canceled = true cancelLock.withReadLock { cancelListeners.forEach { listener in listener() } } clearListeners() } /** Adds a listener for the cancel event of this Promise - parameter cancel: The closure that should be called when the Promise is canceled - returns: The updated Promise */ @discardableResult public func onCancel(_ callback: @escaping () -> Void) -> Promise<T> { if canceled { callback() } else { cancelLock.withWriteLock { cancelListeners.append(callback) } } return self } /** Adds a listener for the success event of this Promise - parameter success: The closure that should be called when the Promise succeeds, taking the value as a parameter - returns: The updated Promise */ @discardableResult public func onSuccess(_ callback: @escaping (T) -> Void) -> Promise<T> { if let value = value { callback(value) } else { successLock.withWriteLock { successListeners.append(callback) } } return self } /** Adds a listener for the failure event of this Promise - parameter success: The closure that should be called when the Promise fails, taking the error as a parameter - returns: The updated Promise */ @discardableResult public func onFailure(_ callback: @escaping (Error) -> Void) -> Promise<T> { if let error = error { callback(error) } else { failureLock.withWriteLock { failureListeners.append(callback) } } return self } /** Adds a listener for both success and failure events of this Promise - parameter completion: The closure that should be called when the Promise completes (succeeds or fails), taking a result with value .Success in case the Promise succeeded and .error in case the Promise failed as parameter. If the Promise is canceled, the result will be .Cancelled - returns: The updated Promise */ @discardableResult public func onCompletion(_ completion: @escaping (Result<T>) -> Void) -> Promise<T> { if let error = error { completion(.error(error)) } else if let value = value { completion(.success(value)) } else if canceled { completion(.cancelled) } else { onSuccess { completion(.success($0)) } onFailure { completion(.error($0)) } onCancel { completion(.cancelled) } } return self } }
mit
lorentey/swift
test/Constraints/super_method.swift
47
1171
// RUN: %target-typecheck-verify-swift -parse-as-library struct S { func foo() { super.foo() // expected-error{{'super' cannot be used outside of class members}} } } class D : B { func b_foo() -> Int { return super.foo } override func bar(_ a: Float) -> Int { return super.bar(a) } func bas() -> (Int, UnicodeScalar, String) { return (super.zim(), super.zang(), super.zung()) } override var zippity : Int { return super.zippity } } extension D { func d_ext_foo() -> Int { return super.foo } } class B { var foo : Int = 0 func bar(_ a: Float) -> Int {} func zim() -> Int {} func zang() -> UnicodeScalar {} func zung() -> String {} var zippity : Int { return 123 } func zoo() { super.zoo() } // expected-error{{'super' members cannot be referenced in a root class}} } class X<T> { func method<U>(_ x: T, y: U) { } } class Y<U> : X<Int> { func otherMethod<U>(_ x: Int, y: U) { super.method(x, y: y) } } func use_d(_ d: D) -> Int { _ = d.b_foo() _ = d.bar(1.0) _ = d.bas() return d.zippity } func not_method() { super.foo() // expected-error{{'super' cannot be used outside of class members}} }
apache-2.0
amirzia/MyTodoList
MyTodoList/TasksViewController.swift
1
2947
// // TasksViewController.swift // MyTodoList // // Created by AmirMohammad Ziaei on 6/5/1395 AP. // Copyright © 1395 :). All rights reserved. // import UIKit import CoreData class TasksViewController: UIViewController { @IBOutlet weak var tabScrollView: ACTabScrollView! static var viewControllers: [ContentViewController] = [] var contentViews: [UIView] = [] let categories = ["Todo", "Completed"] override func viewDidLoad() { super.viewDidLoad() tabScrollView.arrowIndicator = true tabScrollView.delegate = self tabScrollView.dataSource = self tabScrollView.backgroundColor = UIColor(red: 61.0 / 255, green: 66.0 / 255, blue: 77.0 / 255, alpha: 1.0) let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) for category in categories { let vc = storyboard.instantiateViewControllerWithIdentifier("ContentViewController") as! ContentViewController TasksViewController.viewControllers.append(vc) vc.category = category addChildViewController(vc) contentViews.append(vc.view) } if let navigationBar = self.navigationController?.navigationBar { navigationBar.translucent = false navigationBar.tintColor = UIColor.whiteColor() navigationBar.barTintColor = UIColor(red: 90.0 / 255, green: 200.0 / 255, blue: 250.0 / 255, alpha: 1) navigationBar.titleTextAttributes = NSDictionary(object: UIColor.whiteColor(), forKey: NSForegroundColorAttributeName) as? [String : AnyObject] navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) navigationBar.shadowImage = UIImage() } UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent } } extension TasksViewController: ACTabScrollViewDelegate, ACTabScrollViewDataSource { func tabScrollView(tabScrollView: ACTabScrollView, didChangePageTo index: Int) { } func tabScrollView(tabScrollView: ACTabScrollView, didScrollPageTo index: Int) { } func numberOfPagesInTabScrollView(tabScrollView: ACTabScrollView) -> Int { return categories.count } func tabScrollView(tabScrollView: ACTabScrollView, tabViewForPageAtIndex index: Int) -> UIView { let label = UILabel() label.text = categories[index].uppercaseString label.font = UIFont.systemFontOfSize(16, weight: UIFontWeightThin) label.textColor = UIColor(red: 77.0 / 255, green: 79.0 / 255, blue: 84.0 / 255, alpha: 1) label.textAlignment = .Center label.sizeToFit() label.frame.size = CGSize(width: label.frame.size.width + 28, height: label.frame.size.height + 36) return label } func tabScrollView(tabScrollView: ACTabScrollView, contentViewForPageAtIndex index: Int) -> UIView { return contentViews[index] } }
mit
lbkchen/cvicu-app
complicationsapp/complicationsapp/ComplicationForms.swift
1
78764
// // ComplicationForms.swift // complicationsapp // // Created by Ken Chen on 6/7/16. // Copyright © 2016 cvicu. All rights reserved. // import Eureka // Creates a variable to hold all the forms generated for each complication class ComplicationForms { // Keeps a reference to the view controller being used to display var vc: FormViewController? // Instantiates an empty Form dictionary var formDict = [String : Form]() // var nonsenseKeys = Complications.getEmptyDictArray(Complications.data) var nonsenseKeys = [String : [String]]() init(vc: FormViewController) { self.vc = vc } func createForm(logName: String) -> Form { var thisForm : Form switch logName { case "arrhythmialog": thisForm = createArr() case "cprlog": thisForm = createCPR() case "dsclog": thisForm = createDSC() case "infeclog": thisForm = createINFEC() case "lcoslog": thisForm = createLCOS() case "mcslog": thisForm = createMCS() case "odlog": thisForm = createOD() case "phlog": thisForm = createPH() case "reslog": thisForm = createRES() case "uoplog": thisForm = createUOP() default: thisForm = Form() } formDict[logName] = thisForm return thisForm } func createArr() -> Form { // ---------------------- Arrhythmia form ---------------------- // let arrForm = Form() arrForm +++ Section("Dates and times") <<< DateTimeInlineRow("date_1") { $0.title = "Start date/time" $0.value = NSDate() } // Need to remove tag in form-processing <<< SLabelRow("Therapies present at discharge?") { $0.title = $0.tag $0.value = "YES" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("StopDate") { $0.title = "Stop date/time" $0.value = NSDate() $0.hidden = .Function(["Therapies present at discharge?"], { form -> Bool in let row : RowOf! = form.rowByTag("Therapies present at discharge?") as! SLabelRow return row.value! == "YES" ? true : false }) } +++ Section("Details") <<< AlertRow<String>("Type") { $0.title = "Type" $0.selectorTitle = "Which type of arrhythmia?" $0.options = [ "Atrial tachycardia", "Ventricular tachycardia", "Junctional tachycardia", "Complete heart block", "Second degree heart block", "Sinus or junctional bradycardia" ] $0.value = "Enter" }.onChange { row in print(row.value) } // <<< AlertRow<String>("Therapy") { // $0.title = "Therapy" // $0.value = "Enter" // $0.selectorTitle = "Which type of arrhythmia therapy?\n\nDefinition: Treatment with intravenous therapy (continuous infusion, bolus dosing, or electrolyte therapy)" // $0.options = [ // "Drug", // "Electrical Cardioversion/Defibrillation", // "Permanent Pacemaker / AICD", // "Temporary Pacemaker", // "Cooling < 35 degrees" // ] // } <<< MultipleSelectorRow<String>("Therapy") { $0.title = "Therapy" $0.options = [ "Drug", "Electrical Cardioversion/Defibrillation", "Permanent Pacemaker / AICD", "Temporary Pacemaker", "Cooling < 35 degrees" ] $0.selectorTitle = "Which type of arrhythmia therapy?\n\nDefinition: Treatment with intravenous therapy (continuous infusion, bolus dosing, or electrolyte therapy)" } return arrForm } func createCPR() -> Form { // ---------------------- CPR form ---------------------- // let cprForm = Form() cprForm +++ Section("Dates and times") <<< LabelRow() { $0.title = "USE CODE SHEET FOR ACCURATE TIMES" } <<< DateTimeInlineRow("startDate") { $0.title = "Start date/time" $0.value = NSDate() } <<< DateTimeInlineRow("endDate") { $0.title = "End date/time" $0.value = NSDate() } +++ Section("Details") <<< AlertRow<String>("outcome") { $0.title = "CPR Outcome" $0.selectorTitle = "CPR Outcome" $0.options = ["ROSC", "ECMO", "DEATH"] $0.value = "Enter" } <<< AlertRow<String>("Hypothermia") { $0.title = "Hypothermia protocol" $0.selectorTitle = "Hypothermia protocol (<34 degrees)?\n\nNo implies hypothermia" $0.options = ["Yes", "No"] $0.value = "Enter" } return cprForm } func createDSC() -> Form { // ---------------------- dsc form ---------------------- // let dscForm = Form() dscForm +++ Section("Definitions") <<< AlertRow<String>() { $0.title = "Planned" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Planned:\n\nSternum left open post-op with preop plans to leave sternum open" } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "Unplanned" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Unplanned:\n\nSternum left open post-op without preop plans to leave sternum open" } .onChange { row in row.value = "Press to view" } +++ Section("Dates and times") <<< DateTimeInlineRow("date_1") { $0.title = "Date/Time" $0.value = NSDate() } +++ Section("Details") <<< AlertRow<String>("Plan") { $0.title = "Planned or Unplanned" $0.selectorTitle = "Planned or Unplanned?" $0.options = ["Planned", "Unplanned"] $0.value = "Enter" } return dscForm } func createINFEC() -> Form { // ---------------------- Infections form ---------------------- // let infecForm = Form() infecForm +++ Section("Definitions") <<< AlertRow<String>() { $0.title = "Endocarditis" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Endocarditis:\n\nDefined by modified Duke criteria." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "CLABSI" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "CLABSI:\n\nDefined by the CDC." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "Sepsis" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Sepsis:\n\nPresence of SIRS resulting from suspected or proven infection. If within the first 48 hours post-op, SIRS due to sepsis is defined as hypo- or hyperthermia (>38.5 or <36), tachycardia, leukocytosis or leukopenia, and thrombocytopenia." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "Superficial SSI" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Superficial Surgical Site Infection:\n\nAs defined by the CDC. Mark if only it has been adjudicated by the local infection control personnel. Must meet the following numbered criteria: 1) The infection involves only the skin and the subcutaneous tissue of the incision and 2) The patient has at least ONE of the following lettered features: A) purulent drainage from the superficial portion of the incision, B) organisms isolated from an aseptically obtained culture of fluid or tissue from the superficial portion of the incision, C) at least ONE of the following numbered signs or symptoms: [1] pain or tenderness, [2] localized swelling, redness, or heat, and [3] the superficial portion of the incision is deliberately opened by a surgeon, unless the incision is culture negative, or D) a diagnosis of superficial wound." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "Deep SSI" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Deep Surgical Site Infection:\n\nAs defined by the CDC. Mark if only it has been adjudicated by the local infection control personnel. Involves the deep soft tissues (e.g., fascial and muscle layers) of the incision AND the patient has at least ONE of the following numbered features: 1) Purulent drainage from the deep portion of the incision (but not from the organ/space component of the surgical site and no evidence of sternal osteomyelitis), 2) The deep incision spontaneously dehisces or is deliberately opened by a surgeon when the patient has ONE of the following lettered signs or symptoms (unless the incision is culture negative): A) fever, B) localized pain, or C) tenderness, 3) An abscess or other evidence of infection involving the deep incision is found on direct examination, during reoperation, or by histopathologic or radiologic examination, or 4) A diagnosis of a deep wound infection by a surgeon or by an attending physician." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "Mediastinits SSI" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Mediastinits Surgical Site Infection:\n\nCriterion 1: Patient has organisms cultured from mediastinal tissue or fluid that is obtained during a surgicaloperation or by needle aspiration. Criterion 2. Patient has evidence of mediastinitis by histopathologic examination or visual evidence of mediastinitis seen during a surgical operation. Criterion 3: Patient has at least ONE of the following numbered signs or symptoms with no other recognized cause: 1) fever, 2) chest pain, or 3) sternal instability AND at least one of the following numbered features: 1) purulent mediastinal drainage, 2) organisms cultured from mediastinal blood, drainage or tissue, or 3) widening of the cardio-mediastinal silhouette. Criterion 4: Patient ≤ 1 year of age has at least one of the following numbered signs or symptoms with no other recognized cause: 1) fever, 2) hypothermia, 3) apnea, 4) bradycardia, or 5) sternal instability AND at least one of the following numbered features: 1) purulent mediastinal discharge, 2) organisms cultured from mediastinal blood, drainage or tissue, or 3) widening of the cardio-mediastinal silhouette. Infections of the sternum (sternal osteomyelitis) should be classified as mediastinitis. Sternal instability that is not associated with a wound infection or mediastinitis is documented as \"Sternal instability." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "Meningitis" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Meningitis:\n\nAs defined by the CDC. Mark if only it has been adjudicated by the local infection control personnel." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "UTI" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "UTI:\n\nAs defined by the CDC. Mark if only it has been adjudicated by the local infection control personnel." } .onChange { row in row.value = "Press to view" } +++ Section("Endocarditis") // Remove tag in form-processing <<< SLabelRow("Endocarditis") { $0.title = $0.tag $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("END") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["Endocarditis"], { form -> Bool in let row : RowOf! = form.rowByTag("Endocarditis") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Pneumonia") // Remove tag in form-processing <<< SLabelRow("Pneumonia") { $0.title = $0.tag $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("PNE") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["Pneumonia"], { form -> Bool in let row : RowOf! = form.rowByTag("Pneumonia") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("CLABSI") // Remove tag in form-processing <<< SLabelRow("CLABSI") { $0.title = $0.tag $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("CLA") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["CLABSI"], { form -> Bool in let row : RowOf! = form.rowByTag("CLABSI") as! SLabelRow return row.value! == "NO" ? true : false }) } // Remove tag in form-processing <<< AlertRow<String>("CLA Type") { $0.title = "CLABSI Type" $0.value = "Enter" $0.selectorTitle = "What type of CLABSI?" $0.options = [ "Gram negative", "Gram positive", "Mixed", "Fungal", "Unknown" ] $0.hidden = .Function(["CLABSI"], { form -> Bool in let row : RowOf! = form.rowByTag("CLABSI") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Sepsis") // Remove tag in form-processing <<< SLabelRow("Sepsis") { $0.title = $0.tag $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("SEP") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["Sepsis"], { form -> Bool in let row : RowOf! = form.rowByTag("Sepsis") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Surgical Site Infection") // Remove tag in form-processing <<< SLabelRow("Surgical Site Infection") { $0.title = $0.tag $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("SSI") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["Surgical Site Infection"], { form -> Bool in let row : RowOf! = form.rowByTag("Surgical Site Infection") as! SLabelRow return row.value! == "NO" ? true : false }) } // Remove tag in form-processing <<< AlertRow<String>("SSI Type") { $0.title = "SSI Type" $0.value = "Enter" $0.selectorTitle = "What type of Surgical Site Infection?" $0.options = [ "Superficial", "Deep", "Mediastinits", "Deep - Gram negative", "Deep - Gram positive", "Deep - Mixed", "Deep - Fungal", "Deep - Unknown" ] $0.hidden = .Function(["Surgical Site Infection"], { form -> Bool in let row : RowOf! = form.rowByTag("Surgical Site Infection") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Meningitis") // Remove tag in form-processing <<< SLabelRow("Meningitis") { $0.title = $0.tag $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("MEN") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["Meningitis"], { form -> Bool in let row : RowOf! = form.rowByTag("Meningitis") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("UTI") // Remove tag in form-processing <<< SLabelRow("UTIinfec") { $0.title = "UTI" $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("UTI") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["UTIinfec"], { form -> Bool in let row : RowOf! = form.rowByTag("UTIinfec") as! SLabelRow return row.value! == "NO" ? true : false }) } // Remove tag in form-processing <<< AlertRow<String>("UTI Type") { $0.title = "UTI Type" $0.value = "Enter" $0.selectorTitle = "What type of UTI?" $0.options = [ "Gram negative", "Gram positive", "Mixed", "Fungal", "Unknown" ] $0.hidden = .Function(["UTIinfec"], { form -> Bool in let row : RowOf! = form.rowByTag("UTIinfec") as! SLabelRow return row.value! == "NO" ? true : false }) } return infecForm } func createLCOS() -> Form { // ---------------------- LCOS form ---------------------- // let lcosForm = Form() lcosForm +++ Section("Definitions") <<< AlertRow<String>() { $0.title = "LCOS" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Low Cardiac Output Syndrome:\n\nLCOS defined by at least one of the following:\n1. VIS > 15 at any time,\n2. Addition of new vasoactive agent (not esmolol or nirpride) for patients already on vasopressor support,\n3. New initiation of vasactive support after a 24 hour period with no support,\n4. Widened A-V difference by physician,\n5. Clinical diagnosis of LCOS." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "Severe Cardiac Failure" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Severe Cardiac Failure:\n\nLow cardiac output state characterized by some of the following: tachycardia, oliguria, decreased skin perfusion, need for increased inotropic support (10% above baseline at admission), metabolic acidosis, widened Arterial - Venous oxygen saturation, need to open the chest, or need for mechanical support. This complication should be selected if the cardiac dysfunction is of a severity that results in inotrope dependence, mechanical circulatory support, or listing for cardiac transplantation. A patient will be considered to have “inotrope dependence” if they cannot be weaned from inotropic support (10% above baseline at admission) after any period of 48 consecutive hours that occurs after the time of OR Exit Date and Time and either (1) within 30 days after surgery in or out of the hospital, and (2) after 30 days during the same hospitalization subsequent to the operation." } .onChange { row in row.value = "Press to view" } +++ Section("Confirmation") // Remove tag in form-processing <<< SLabelRow("Confirmation") { $0.title = "Are you a Data Manager?" $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } +++ Section("Dates and times"){ $0.hidden = .Function(["Confirmation"], { form -> Bool in let row : RowOf! = form.rowByTag("Confirmation") as! SLabelRow return row.value! == "NO" ? true : false }) } <<< LabelRow () { $0.title = "Do not enter: to be adjudicated by Data Manager" $0.hidden = .Function(["Confirmation"], { form -> Bool in let row : RowOf! = form.rowByTag("Confirmation") as! SLabelRow return row.value! == "NO" ? true : false }) }.onCellSelection {cell, row in self.displayAlert(row.title!, message: "") } <<< DateTimeInlineRow("date_1") { $0.title = "Start date/time" $0.value = NSDate() } +++ Section("Details"){ $0.hidden = .Function(["Confirmation"], { form -> Bool in let row : RowOf! = form.rowByTag("Confirmation") as! SLabelRow return row.value! == "NO" ? true : false }) } <<< LabelRow () { $0.title = "Do not enter: to be adjudicated by Data Manager" $0.hidden = .Function(["Confirmation"], { form -> Bool in let row : RowOf! = form.rowByTag("Confirmation") as! SLabelRow return row.value! == "NO" ? true : false }) }.onCellSelection {cell, row in self.displayAlert(row.title!, message: "") } <<< AlertRow<String>("LCOST") { $0.title = "LCOS Timing" $0.selectorTitle = "LCOS Timing" $0.options = ["Pre-Op", "Post-Op", "Both", "N/A"] $0.value = "Enter" } <<< SLabelRow("SCF") { $0.title = "Severe cardiac failure?" $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } return lcosForm } func createMCS() -> Form { // ---------------------- MCS form ---------------------- // let mcsForm = Form() mcsForm +++ Section("Dates and times") <<< DateTimeInlineRow("date_1") { $0.title = "Start date/time" $0.value = NSDate() } // Remove tag in form-processing <<< SLabelRow("Confirmation") { $0.title = "Are you a Data Manager?" $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< LabelRow() { $0.title = "Do not enter: to be adjudicated by Data Manager" $0.hidden = .Function(["Confirmation"], { form -> Bool in let row : RowOf! = form.rowByTag("Confirmation") as! SLabelRow return row.value! == "NO" ? true : false }) }.onCellSelection {cell, row in self.displayAlert(row.title!, message: "") } // FIXME: nil results in unwrapping error, so need to hide this <<< DateTimeInlineRow("MCSE") { $0.title = "MCS end date/time" $0.value = NSDate() $0.hidden = .Function(["Confirmation"], { form -> Bool in let row : RowOf! = form.rowByTag("Confirmation") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Details") <<< SLabelRow("In post-ope period") { $0.title = "In post-operative period?" $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< AlertRow<String>("SupportType") { $0.title = "Support type" $0.value = "Enter" $0.selectorTitle = "Select support type" $0.options = ["VAD", "ECMO", "Both VAD and ECMO"] } <<< AlertRow<String>("Reason") { $0.title = "Primary reason" $0.value = "Enter" $0.selectorTitle = "Select primary reason for MCS" $0.options = [ "LCOS/Cardiac failure", "Ventricular dysfunction", "Hypoxemia", "Hypercardic respiratory failure", "Shunt occlusion", "Arrhythmia", "Bleeding", "Multisystem organ failure" ] } <<< AlertRow<String>("ECPR") { $0.title = "ECPR" $0.value = "Enter" $0.selectorTitle = "Enter ECPR" $0.options = [ "Active CPR at cannulation", "Active CPR within 2 hours of cannulation" ] } <<< SLabelRow("MCSS") { $0.title = "MCS present at start..." $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< AlertRow<String>() { $0.title = "Full description" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "MCS present at start of CICU encounter?" } .onChange { row in row.value = "Press to view" } return mcsForm } func createOD() -> Form { // ---------------------- ORGAN DYSFUNCTION form ---------------------- // let odForm = Form() odForm +++ Section("Definitions") <<< AlertRow<String>() { $0.title = "MSOF" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Multi-System Organ Failure/Dysfunction:\n\nMulti-System Organ Failure (MSOF) is a condition where more than one organ system has failed (for example, respiratory failure requiring mechanical ventilation combined with renal failure requiring dialysis). Please code the individual organ system failures as well. If MSOF is associated with sepsis as well, please also code: Sepsis, Multi-system Organ Failure. Multi-System Organ Failure (MSOF) is synonymous with Multi-Organ Dysfunction Syndrome (MODS). Only code this complication if the patient has failure of two or more than two organs. Do not code MSOF if only failing organs are the heart and lungs." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "RFRD" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Renal failure requiring dialysis at the time of hospital discharge:\n\nCode if patient requires dialysis at the time of hospital discharge or death in the hospital. (Acute renal failure defined as new onset oliguria with sustained urine output < 0.5 cc/kg/hr for 24 hours and/or a rise in creatinine > 1.5 time upper limits of normal for age (or twice the most recent preop/preprocedural values, with eventual need for dialysis (including peritoneal) or hemofiltration. Within 30 days of operation/procedure in or out of the hospital or anytime during same hospitalzation. Code if the patient required dialysis, but the treatment was not instiuted due to patient or family refusal." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "Transient" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Transient:\n\nNot present at discharge." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "Seizure" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Seizure:\n\nClinical and/or EEG evidence." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "Stroke" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Stroke:\n\nAny confirmed neurological deficit of abrupt onset caused by a disturbance in blood flow to the brain, when the neurological definict does not resolve within 24 hours." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "Wound dehiscence (sterile)" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Wound dehiscence (sterile):\n\nSeparation can be superficial or deep." } .onChange { row in row.value = "Press to view" } +++ Section("Multi-System Organ Failure") // Remove tag in form-processing <<< SLabelRow("MSOF") { $0.title = $0.tag $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("msof") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["MSOF"], { form -> Bool in let row : RowOf! = form.rowByTag("MSOF") as! SLabelRow return row.value! == "NO" ? true : false }) } // Remove tag in form-processing <<< AlertRow<String>("MSOF Type") { $0.title = $0.tag $0.value = "Enter" $0.selectorTitle = "What type of MSOF?" $0.options = [ "Sepsis, MSOF", "Renal Failure requiring dialysis", "Liver failure", "Neurological", "Other" ] $0.hidden = .Function(["MSOF"], { form -> Bool in let row : RowOf! = form.rowByTag("MSOF") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Renal failure requiring dialysis at the time of hospital discharge") // Remove tag in form-processing <<< SLabelRow("Renal failure requiring dialysis at the time of hospital discharge") { $0.title = "RFRD" $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("RFRD") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["Renal failure requiring dialysis at the time of hospital discharge"], { form -> Bool in let row : RowOf! = form.rowByTag("Renal failure requiring dialysis at the time of hospital discharge") as! SLabelRow return row.value! == "NO" ? true : false }) } // Remove tag in form-processing <<< AlertRow<String>("RFRD Type") { $0.title = $0.tag $0.value = "Enter" $0.selectorTitle = "What type of RFRD?" $0.options = [ "Requiring dialysis at time of hospital discharge", "Requiring temporary dialysis", "Requiring temporary hemofiltration" ] $0.hidden = .Function(["Renal failure requiring dialysis at the time of hospital discharge"], { form -> Bool in let row : RowOf! = form.rowByTag("Renal failure requiring dialysis at the time of hospital discharge") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Neurological deficit") // Remove tag in form-processing <<< SLabelRow("Neurological deficit") { $0.title = $0.tag $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("ND") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["Neurological deficit"], { form -> Bool in let row : RowOf! = form.rowByTag("Neurological deficit") as! SLabelRow return row.value! == "NO" ? true : false }) } // Remove tag in form-processing <<< AlertRow<String>("ND Presence") { $0.title = "Transient?" $0.value = "Enter" $0.selectorTitle = "Transient?" $0.options = [ "Persistenting at discharge", "Transient" ] $0.hidden = .Function(["Neurological deficit"], { form -> Bool in let row : RowOf! = form.rowByTag("Neurological deficit") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Peripheral nerve injury, persistenting at discharge") // Remove tag in form-processing <<< SLabelRow("Peripheral nerve injury, persistenting at discharge") { $0.title = "Peripheral nerve injury..." $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("PNI") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["Peripheral nerve injury, persistenting at discharge"], { form -> Bool in let row : RowOf! = form.rowByTag("Peripheral nerve injury, persistenting at discharge") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Seizure") // Remove tag in form-processing <<< SLabelRow("Seizure") { $0.title = $0.tag $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("seizure") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["Seizure"], { form -> Bool in let row : RowOf! = form.rowByTag("Seizure") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Spinal cord injury") // Remove tag in form-processing <<< SLabelRow("Spinal cord injury") { $0.title = $0.tag $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("SCI") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["Spinal cord injury"], { form -> Bool in let row : RowOf! = form.rowByTag("Spinal cord injury") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Stroke") // Remove tag in form-processing <<< SLabelRow("Stroke") { $0.title = $0.tag $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("stroke") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["Stroke"], { form -> Bool in let row : RowOf! = form.rowByTag("Stroke") as! SLabelRow return row.value! == "NO" ? true : false }) } <<< SLabelRow("SB") { $0.title = "Subdural bleed" $0.value = "NO" $0.cell.selectionStyle = .Default $0.hidden = .Function(["Stroke"], { form -> Bool in let row : RowOf! = form.rowByTag("Stroke") as! SLabelRow return row.value! == "NO" ? true : false }) }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< SLabelRow("IH") { $0.title = "Interventricular hemorrhage..." $0.value = "NO" $0.cell.selectionStyle = .Default $0.hidden = .Function(["Stroke"], { form -> Bool in let row : RowOf! = form.rowByTag("Stroke") as! SLabelRow return row.value! == "NO" ? true : false }) }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< AlertRow<String>() { $0.title = "Full description" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Interventricular hemorrhage (IVH > 2)" $0.hidden = .Function(["Stroke"], { form -> Bool in let row : RowOf! = form.rowByTag("Stroke") as! SLabelRow return row.value! == "NO" ? true : false }) } .onChange { row in row.value = "Press to view" } +++ Section("Wound dehiscence (sterile)") // Remove tag in form-processing <<< SLabelRow("Wound dehiscence (sterile)") { $0.title = $0.tag $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("wound") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["Wound dehiscence (sterile)"], { form -> Bool in let row : RowOf! = form.rowByTag("Wound dehiscence (sterile)") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Median sternotomy") // Remove tag in form-processing <<< SLabelRow("Median sternotomy") { $0.title = $0.tag $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("MS") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["Median sternotomy"], { form -> Bool in let row : RowOf! = form.rowByTag("Median sternotomy") as! SLabelRow return row.value! == "NO" ? true : false }) } return odForm } func createPH() -> Form { // ---------------------- ph form ---------------------- // let phForm = Form() phForm +++ Section("Definitions") <<< AlertRow<String>() { $0.title = "Pulmonary Hypertension" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Pulmonary Hypertension:\n\nClinically significant elevation of PA pressure, requiring intervention such as iNO or other therapies. This does not include iNO given for hypoxemia when there was clearly no PHTN." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "PHC" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Pulmonary hypertensive crisis (Acute state of PAp > Systemic pressure):\n\nAn acute state of inadequate systemic perfusion associated with pulmonary hypertension, when the pulmonary arterial pressure is greater than the systemic arterial pressure." } .onChange { row in row.value = "Press to view" } +++ Section("Dates and times") <<< DateTimeInlineRow("date_1") { $0.title = "Start date/time" $0.value = NSDate() } // Need to remove tag in form-processing <<< SLabelRow("Therapy present at discharge?") { $0.title = $0.tag $0.value = "YES" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } // Remove tag in form-processing <<< SLabelRow("Confirmation") { $0.title = "Are you a Data Manager?" $0.value = "NO" $0.cell.selectionStyle = .Default $0.hidden = .Function(["Therapy present at discharge?"], { form -> Bool in let row : RowOf! = form.rowByTag("Therapy present at discharge?") as! SLabelRow return row.value! == "YES" ? true : false }) }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< LabelRow () { $0.title = "Do not enter: to be adjudicated by Data Manager" $0.hidden = .Function(["Confirmation"], { form -> Bool in let row : RowOf! = form.rowByTag("Confirmation") as! SLabelRow return row.value! == "NO" ? true : false }) }.onCellSelection {cell, row in self.displayAlert(row.title!, message: "") } <<< DateTimeInlineRow("endDate") { $0.title = "Stop date/time" $0.value = NSDate() $0.hidden = .Function(["Confirmation"], { form -> Bool in let row : RowOf! = form.rowByTag("Confirmation") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Details") <<< AlertRow<String>("Treatment") { $0.title = "Treatment" $0.selectorTitle = "Treatment" $0.options = [ "iNO", "Inhaled iloprost", "Prostacyclin", "Remodulin" ] $0.value = "Enter" }.onChange { row in print(row.value) } // Need to remove tag in form-processing <<< SLabelRow("PHC") { $0.title = $0.tag $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } return phForm } func createRES() -> Form { // ---------------------- RESPIRATORY form ---------------------- // let resForm = Form() resForm +++ Section("Definitions") <<< AlertRow<String>() { $0.title = "Chylothorax" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Chylothorax requiring intervention:\n\nChylothorax defined as presence of lymphatic fluid in the pleural space (predominance of lymphocytes and/or a triglyceride level greater than 110 mg/dL). Change in diet is considered an intervention." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "ARDS" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "ARDS:\n\nARDS is defined as a clinical syndrome with a variety of etiologies characterized by refractory hypoxemia and bilateral diffuse interstitial infiltrates on CXR, as well as stiff lungs with decreased compliance, increased intrapulmonary shunting, and decreased airway dead space." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "Pulmonary embolism" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Pulmonary embolism:\n\nEmbolization of clot or other foreign material to the pulmonary vasculature documented by CT angiogram, nuclear medicine scan or other accepted objective study." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "Reintubation..." $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Post-operative/Post-procedureal respiratory insufficiency requiring reintubation:\n\nWithin 30 days of surgery. Not intended to capture situations where a patient may undergo elective intubations." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "Paralyzed Diaphragm" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Paralyzed Diaphragm:\n\nPresence of elevated hemi-diaphragm(s) on chest radiograph in conjunction with evidence of weak, immobile or paradoxical movement assessed by ultrasound or fluoroscopy." } .onChange { row in row.value = "Press to view" } +++ Section("Necessary to place a chest tube?") // Remove tag in form-processing <<< SLabelRow("NPCT") { $0.title = "Necessary to place a chest tube?" $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() //self.displayAlert(row.title!, message: "") } <<< DateTimeInlineRow("Necessary to place a chest tube?") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["NPCT"], { form -> Bool in let row : RowOf! = form.rowByTag("NPCT") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Chylothorax requiring intervention") // Remove tag in form-processing <<< SLabelRow("chylothorax") { $0.title = "Chylothorax requiring intervention" $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() //self.displayAlert(row.title!, message: "") } <<< DateTimeInlineRow("Chylothorax requiring intervention") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["chylothorax"], { form -> Bool in let row : RowOf! = form.rowByTag("chylothorax") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Pleural effusion requiring drainage") // Remove tag in form-processing <<< SLabelRow("pleuraleffusion") { $0.title = "Pleural effusion requiring drainage" $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() //self.displayAlert(row.title!, message: "") } <<< DateTimeInlineRow("Pleural effusion requiring drainage") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["pleuraleffusion"], { form -> Bool in let row : RowOf! = form.rowByTag("pleuraleffusion") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Pneumothorax requiring drainage") // Remove tag in form-processing <<< SLabelRow("pneumothorax") { $0.title = "Pneumothorax requiring drainage" $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() //self.displayAlert(row.title!, message: "") } <<< DateTimeInlineRow("Pneumothorax requiring drainage") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["pneumothorax"], { form -> Bool in let row : RowOf! = form.rowByTag("pneumothorax") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Hemothorax requiring drainage") // Remove tag in form-processing <<< SLabelRow("hemothorax") { $0.title = "Hemothorax requiring drainage" $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() //self.displayAlert(row.title!, message: "") } <<< DateTimeInlineRow("Hemothorax requiring drainage") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["hemothorax"], { form -> Bool in let row : RowOf! = form.rowByTag("hemothorax") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("ARDS") // Remove tag in form-processing <<< SLabelRow("ards") { $0.title = "ARDS" $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("ARDS") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["ards"], { form -> Bool in let row : RowOf! = form.rowByTag("ards") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Pulmonary embolism") // Remove tag in form-processing <<< SLabelRow("pulmembol") { $0.title = "Pulmonary embolism" $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("Pulmonary embolism") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["pulmembol"], { form -> Bool in let row : RowOf! = form.rowByTag("pulmembol") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Post-operative/Post-procedural respiratory insufficiency requiring mechanical ventilatory support") // Remove tag in form-processing <<< SLabelRow("Post-operative/Post-procedureal respiratory insufficiency requiring mechanical ventilatory support") { $0.title = "Mechanical ventilatory support..." $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() //self.displayAlert(row.title!, message: "") } // <<< AlertRow<String>() { // $0.title = "Full description" // $0.value = "Press to view" // $0.options = ["Accept"] // $0.selectorTitle = "Mechanical ventilatory support: Post-operative/Post-procedureal respiratory insufficiency requiring mechanical ventilatory support" // } .onChange { row in // row.value = "Press to view" // } <<< DateTimeInlineRow("pprirmvs") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["Post-operative/Post-procedureal respiratory insufficiency requiring mechanical ventilatory support"], { form -> Bool in let row : RowOf! = form.rowByTag("Post-operative/Post-procedureal respiratory insufficiency requiring mechanical ventilatory support") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Post-operative/Post-procedural respiratory insufficiency requiring reintubation") // Remove tag in form-processing <<< SLabelRow("Post-operative/Post-procedureal respiratory insufficiency requiring reintubation") { $0.title = "Reintubation..." $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() //self.displayAlert(row.title!, message: "") } // <<< AlertRow<String>() { // $0.title = "Full description" // $0.value = "Press to view" // $0.options = ["Accept"] // $0.selectorTitle = "Reintubation: Post-operative/Post-procedureal respiratory insufficiency requiring reintubation" // } .onChange { row in // row.value = "Press to view" // } <<< DateTimeInlineRow("pprirr") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["Post-operative/Post-procedureal respiratory insufficiency requiring reintubation"], { form -> Bool in let row : RowOf! = form.rowByTag("Post-operative/Post-procedureal respiratory insufficiency requiring reintubation") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Respiratory failure requiring tracheostomy") // Remove tag in form-processing <<< SLabelRow("rfrt") { $0.title = "Respiratory failure req..." $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() //self.displayAlert(row.title!, message: "") } // <<< AlertRow<String>() { // $0.title = "Full description" // $0.value = "Press to view" // $0.options = ["Accept"] // $0.selectorTitle = "Respiratory failure requiring tracheostomy" // } .onChange { row in // row.value = "Press to view" // } <<< DateTimeInlineRow("Respiratory failure requiring tracheostomy") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["rfrt"], { form -> Bool in let row : RowOf! = form.rowByTag("rfrt") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Paralyzed diaphragm") // Remove tag in form-processing <<< SLabelRow("pd") { $0.title = "Paralyzed diaphragm" $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("Paralyzed diaphragm") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["pd"], { form -> Bool in let row : RowOf! = form.rowByTag("pd") as! SLabelRow return row.value! == "NO" ? true : false }) } +++ Section("Vocal cord dysfunction") // Remove tag in form-processing <<< SLabelRow("vcd") { $0.title = "Vocal cord dysfunction" $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } <<< DateTimeInlineRow("Vocal cord dysfunction") { $0.title = "Date/Time" $0.value = NSDate() $0.hidden = .Function(["vcd"], { form -> Bool in let row : RowOf! = form.rowByTag("vcd") as! SLabelRow return row.value! == "NO" ? true : false }) } return resForm } func createUOP() -> Form { // ---------------------- Unplanned operation/Procedure form ---------------------- // let uopForm = Form() uopForm +++ Section("Definitions") <<< AlertRow<String>() { $0.title = "UCR" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Unplanned cardiac reoperation:\n\nAdditional unplanned cardiac reoperation during the hospital encounter or within 30 days after surgery in or out of the hospital. Delayed sternal closure, ECMO decannulation, VAD decannulation, and removal of Broviac catheter should not be included. Unplanned reoperations include Mediastinal exploration for infection or hemodynamic instability, initiation of ECMO or VAD." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "UICC" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Unplanned interventional cardiovascular catheterization in the post-op period:\n\nDuring the hospital encounter or within 30 days after procedure in or out of the hospital." } .onChange { row in row.value = "Press to view" } <<< AlertRow<String>() { $0.title = "UNR" $0.value = "Press to view" $0.options = ["Accept"] $0.selectorTitle = "Unplanned non-cardiac reoperation during the post-op period:\n\nDuring the hospital encounter or within 30 days after procedure in or out of the hospital." } .onChange { row in row.value = "Press to view" } +++ Section("Dates and times") <<< DateTimeInlineRow("date_1") { $0.title = "Date/Time" $0.value = NSDate() } +++ Section("Details") // Need to remove tag in form-processing <<< SLabelRow("UCR") { $0.title = $0.tag $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } // Need to remove tag in form-processing <<< SLabelRow("UICC") { $0.title = $0.tag $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } // Need to remove tag in form-processing <<< SLabelRow("UNR") { $0.title = $0.tag $0.value = "NO" $0.cell.selectionStyle = .Default }.onCellSelection {cell, row in row.value = row.value! == "YES" ? "NO" : "YES" row.deselect() row.updateCell() } return uopForm } // Cleans tags and combines multiple values of form in formDict associated with logName func cleanTagsAndGetCombinedValues(logName: String) -> [String : String] { var values = convertAllValuesToString(formDict[logName]!.values()) switch logName { case "arrhythmialog": values.removeValueForKey("Therapies present at discharge?") case "cprlog": break case "dsclog": break case "infeclog": // If CLABSI was filled out if (values.keys.contains("CLABSI") && values["CLABSI"]! == "YES") { values["CLA"] = values["CLA Type"]! + " (\(values["CLA"]!))" values.removeValueForKey("CLA Type") } // If SSI was filled out if (values.keys.contains("Surgical Site Infection") && values["Surgical Site Infection"]! == "YES") { values["SSI"] = "\(values["SSI Type"]!) (\(values["SSI"]!))" values.removeValueForKey("SSI Type") } // If UTI was filled out if (values.keys.contains("UTIinfec") && values["UTIinfec"]! == "YES") { values["UTI"] = "\(values["UTI Type"]!) (\(values["UTI"]!))" values.removeValueForKey("UTI Type") } let toChange = [ "Endocarditis" : "END", "Pneumonia" : "PNE", "CLABSI" : "CLA", "Sepsis" : "SEP", "Surgical Site Infection" : "SSI", "Meningitis" : "MEN", "UTIinfec" : "UTI" ] for (key, value) in toChange { if (values[key]! == "NO") { values[value] = "NO" } values.removeValueForKey(key) } case "lcoslog": values.removeValueForKey("Confirmation") case "mcslog": values.removeValueForKey("Confirmation") case "odlog": // If MSOF was filled out if (values.keys.contains("MSOF") && values["MSOF"]! == "YES") { values["msof"] = "\(values["MSOF Type"]!) (\(values["msof"]!))" values.removeValueForKey("MSOF Type") } // If RFRD was filled out let RFRD = "Renal failure requiring dialysis at the time of hospital discharge" if (values.keys.contains(RFRD) && values[RFRD]! == "YES") { values["RFRD"] = "\(values["RFRD Type"]!) (\(values["RFRD"]!))" values.removeValueForKey("RFRD Type") } // If ND was filled out if (values.keys.contains("Neurological deficit") && values["Neurological deficit"]! == "YES") { values["ND"] = "\(values["ND Presence"]!) (\(values["ND"]!))" values.removeValueForKey("ND Presence") } let toChange = [ "MSOF" : "msof", RFRD : "RFRD", "Neurological deficit" : "ND", "Peripheral nerve injury, persistenting at discharge" : "PNI", "Seizure" : "seizure", "Spinal cord injury" : "SCI", "Stroke" : "stroke", "Wound dehiscence (sterile)" : "wound", "Median sternotomy" : "MS"] for (key, value) in toChange { if (values[key]! == "NO") { values[value] = "NO" } values.removeValueForKey(key) } case "phlog": values.removeValueForKey("Therapy present at discharge?") values.removeValueForKey("Confirmation") case "reslog": let toChange = [ "NPCT" : "Necessary to place a chest tube?", "chylothorax" : "Chylothorax requiring intervention", "pleuraleffusion" : "Pleural effusion requiring drainage", "pneumothorax" : "Pneumothorax requiring drainage", "hemothorax" : "Hemothorax requiring drainage", "ards" : "ARDS", "pulmembol" : "Pulmonary embolism", "Post-operative/Post-procedureal respiratory insufficiency requiring mechanical ventilatory support" : "pprirmvs", "Post-operative/Post-procedureal respiratory insufficiency requiring reintubation" : "pprirr", "rfrt" : "Respiratory failure requiring tracheostomy", "pd" : "Paralyzed diaphragm", "vcd" : "Vocal cord dysfunction" ] for (key, value) in toChange { if (values[key]! == "NO") { values[value] = "NO" } values.removeValueForKey(key) } case "uoplog": break default: print("Invalid log to cleanTagsAndGetCombinedValues: \(logName)") } return values } func extractDataAndCleanForms() { for key in formDict.keys { // reset confirmObject to postObject let data = SessionData.sharedInstance data.confirmObject = data.postObject let toAdd = cleanTagsAndGetCombinedValues(key) data.confirmObject = data.addData(data.confirmObject, toAdd: toAdd) // check for any concurrent logging date conflicts let isDisabled = Complications.disabledDate.contains(data.confirmObject["Table"]!) let dateVariable = Complications.mainDate[SessionData.sharedInstance.postObject["Table"]!]! let dateToCheck = isDisabled ? SessionData.getCurrentTimeString() : data.confirmObject[dateVariable]! let responseString = SessionData.sharedInstance.checkDateFromServer(dateToCheck) if (responseString.characters.count > 0) { displayAlert("Warning", message: "This patient was already logged for this complication on \(dateToCheck) at these times:\n\n\(responseString)\n\nAre you sure you want to continue?") } } } // MARK: - Helper functions func displayAlert(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil)) self.vc!.presentViewController(alert, animated: true, completion: nil) } func convertAllValuesToString(dict: [String : Any?]) -> [String : String] { var result = [String : String]() for key in dict.keys { var thisValue = dict[key]! if (thisValue == nil) { result[key] = "null" } else { thisValue = thisValue! } if (thisValue is Int) { result[key] = String(thisValue) } else if (thisValue is Bool) { result[key] = (thisValue as! Bool == true) ? "YES" : "NO" } else if (thisValue is NSDate) { let df = NSDateFormatter() df.timeZone = NSTimeZone(abbreviation: "PST") df.dateFormat = "MM/dd/yyyy HH:mm" result[key] = df.stringFromDate(thisValue as! NSDate) } else if (thisValue is String?) { result[key] = (thisValue as! String?)! } if (thisValue is Set<String>) { var arrayValue = [String]() for element in (thisValue as! Set<String>) { arrayValue.append(element) } result[key] = arrayValue.joinWithSeparator(" + ") } } return result } }
mit
classmere/app
Classmere/Classmere/Models/Course.swift
1
891
import Foundation /** A model representation of a course at OSU. Reference Docs - https://github.com/classmere/api */ struct Course: Decodable { let subjectCode: String let courseNumber: Int let title: String? let credits: String? let description: String? let sections: [Section] var abbr: String { return subjectCode + " " + String(courseNumber) } init(subjectCode: String, courseNumber: Int) { self.subjectCode = subjectCode self.courseNumber = courseNumber self.title = nil self.credits = nil self.description = nil self.sections = [] } } extension Course: Hashable { var hashValue: Int { return subjectCode.hashValue ^ courseNumber.hashValue &* 16777619 } static func == (lhs: Course, rhs: Course) -> Bool { return lhs.hashValue == rhs.hashValue } }
gpl-3.0
fhsjaagshs/FHSTwitterEngine
FHSTwitterEngineDemoSwift/Demo-SwiftTests/Demo_SwiftTests.swift
2
911
// // Demo_SwiftTests.swift // Demo-SwiftTests // // Created by Daniel Khamsing on 1/14/15. // Copyright (c) 2015 dkhamsing. All rights reserved. // import UIKit import XCTest class Demo_SwiftTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
cocoascientist/Passengr
Passengr/ShowDetailAnimator.swift
1
3772
// // ShowDetailAnimator.swift // Passengr // // Created by Andrew Shepard on 10/19/14. // Copyright (c) 2014 Andrew Shepard. All rights reserved. // import UIKit final class ShowDetailAnimator: NSObject, UIViewControllerAnimatedTransitioning { private let duration = 0.75 func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? UICollectionViewController else { return } guard let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? UICollectionViewController else { return } guard let fromCollectionView = fromViewController.collectionView else { return } guard let toCollectionView = toViewController.collectionView else { return } let containerView = transitionContext.containerView containerView.backgroundColor = AppStyle.Color.lightBlue guard let indexPath = fromCollectionView.indexPathsForSelectedItems?.first else { return } let originAttributes = fromCollectionView.layoutAttributesForItem(at: indexPath) let destinationAttributes = toCollectionView.layoutAttributesForItem(at: indexPath) let itemSize = DetailViewLayout.detailLayoutItemSize(for: UIScreen.main.bounds) let toViewMargins = toCollectionView.layoutMargins // let fromViewMargins = fromCollectionView.layoutMargins guard let originRect = originAttributes?.frame else { return } guard var destinationRect = destinationAttributes?.frame else { return } destinationRect = CGRect(x: originRect.minX, y: destinationRect.minY + toViewMargins.top, width: itemSize.width, height: itemSize.height) let firstRect = CGRect(x: destinationRect.origin.x, y: destinationRect.origin.y, width: destinationRect.size.width, height: originRect.size.height) // let secondRect = CGRect(x: destinationRect.origin.x, y: destinationRect.origin.y, width: destinationRect.size.width, height: destinationRect.size.height) let insets = UIEdgeInsets(top: 73.0, left: 0.0, bottom: 1.0, right: 0.0) guard let snapshot = fromCollectionView.resizableSnapshotView(from: originRect, afterScreenUpdates: false, withCapInsets: insets) else { return } snapshot.frame = containerView.convert(originRect, from: fromCollectionView) containerView.addSubview(snapshot) let animations: () -> Void = { UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.33, animations: { fromViewController.view.alpha = 0.0 }) UIView.addKeyframe(withRelativeStartTime: 0.23, relativeDuration: 0.73, animations: { snapshot.frame = firstRect }) // UIView.addKeyframe(withRelativeStartTime: 0.36, relativeDuration: 0.64, animations: { // snapshot.frame = secondRect // }) } let completion: (Bool) -> Void = { finished in transitionContext.completeTransition(finished) toViewController.view.alpha = 1.0 fromViewController.view.removeFromSuperview() containerView.addSubview(toViewController.view) snapshot.removeFromSuperview() } UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: [], animations: animations, completion: completion) } }
mit
remaerd/Keys
Keys/AsymmetricKeys-iOS.swift
1
9852
// // AsymmetricKeys.swift // Keys // // Created by Sean Cheng on 8/8/15. // // import Foundation import CommonCrypto public extension PublicKey { func encrypt(_ data: Data) throws -> Data { let dataPointer = (data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count) var encryptedDataLength = SecKeyGetBlockSize(self.key) var encryptedData = [UInt8](repeating: 0, count: Int(encryptedDataLength)) let result = SecKeyEncrypt(self.key, self.options.cryptoPadding, dataPointer, data.count, &encryptedData, &encryptedDataLength) if result != noErr { throw Exception.cannotEncryptData } return Data(bytes: UnsafePointer<UInt8>(encryptedData), count: encryptedDataLength) } func verify(_ data: Data, signature: Data) throws -> Bool { let hash = data.SHA1 var result : OSStatus var pointer : UnsafePointer<UInt8>? = nil hash.withUnsafeBytes({ (ptr) in pointer = ptr}) let signaturePointer = (signature as NSData).bytes.bindMemory(to: UInt8.self, capacity: signature.count) result = SecKeyRawVerify(self.key, self.options.signaturePadding, pointer!, hash.count, signaturePointer, signature.count) if result != 0 { return false } else { return true } } } public extension PrivateKey { func decrypt(_ data: Data) throws -> Data { let dataPointer = (data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count) var decryptedDataLength = SecKeyGetBlockSize(self.key) var decryptedData = [UInt8](repeating: 0, count: Int(decryptedDataLength)) let result = SecKeyDecrypt(self.key, self.options.cryptoPadding, dataPointer, data.count, &decryptedData, &decryptedDataLength) if result != noErr { throw Exception.cannotDecryptData } return Data(bytes: UnsafePointer<UInt8>(decryptedData), count: decryptedDataLength) } func signature(_ data: Data) throws -> Data { let hash = data.SHA1 var signatureDataLength = SecKeyGetBlockSize(self.key) var signatureData = [UInt8](repeating: 0, count: Int(signatureDataLength)) var pointer : UnsafePointer<UInt8>? = nil hash.withUnsafeBytes({ (ptr) in pointer = ptr}) let status = SecKeyRawSign(self.key, self.options.signaturePadding, pointer!, hash.count, &signatureData, &signatureDataLength) if status != OSStatus(kCCSuccess) { throw Exception.cannotSignData } return Data(bytes: UnsafePointer<UInt8>(signatureData), count: signatureDataLength) } } public extension AsymmetricKeys { static func secKeyFromData(_ data:Data, publicKey:Bool) throws -> SecKey { func SecKeyBelowiOS9() throws -> SecKey { var query :[String:AnyObject] = [ String(kSecClass): kSecClassKey, String(kSecAttrKeyType): kSecAttrKeyTypeRSA, String(kSecAttrApplicationTag): TemporaryKeyTag as AnyObject ] SecItemDelete(query as CFDictionary) query[String(kSecValueData)] = data as AnyObject? if publicKey == true { query[String(kSecAttrKeyClass)] = kSecAttrKeyClassPublic } else { query[String(kSecAttrKeyClass)] = kSecAttrKeyClassPrivate } var persistentKey : CFTypeRef? var result : OSStatus = 0 result = SecItemAdd(query as CFDictionary, &persistentKey) print(result) if result != noErr { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } query[String(kSecValueData)] = nil query[String(kSecReturnPersistentRef)] = nil query[String(kSecReturnRef)] = true as AnyObject? var keyPointer: AnyObject? result = SecItemCopyMatching(query as CFDictionary, &keyPointer) if result != noErr { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } return keyPointer as! SecKey } func SecKeyFromiOS10() throws -> SecKey { let error : UnsafeMutablePointer<Unmanaged<CFError>?>? = nil var query :[String:AnyObject] = [ String(kSecAttrKeyType): kSecAttrKeyTypeRSA, String(kSecAttrKeySizeInBits): 1024 as CFNumber ] if publicKey == true { query[String(kSecAttrKeyClass)] = kSecAttrKeyClassPublic } else { query[String(kSecAttrKeyClass)] = kSecAttrKeyClassPrivate } if #available(iOS 10.0, *) { let key = SecKeyCreateWithData(data as CFData, query as CFDictionary, error) if ((error) != nil || key == nil) { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } return key! } else { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } } if #available(iOS 10.0, *) { return try SecKeyFromiOS10() } else { return try SecKeyBelowiOS9() } } } public extension PublicKey { init(publicKey key: Data, options: AsymmetricKeys.Options = AsymmetricKeys.Options.Default) throws { func stripPublicKeyHeader(_ data:Data) throws -> Data { var buffer = [UInt8](repeating: 0, count: data.count) (data as NSData).getBytes(&buffer, length: data.count) var index = 0 if buffer[index] != 0x30 { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } index += 1 if buffer[index] > 0x80 { index += Int(buffer[index] - UInt8(0x80) + UInt8(1)) } else { index += 1 } let seqiod : [UInt8] = [0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00] if memcmp(&buffer, seqiod, 15) == 1 { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } index += 15 if buffer[index] != 0x03 { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } index += 1 if buffer[index] > 0x80 { index += Int(buffer[index] - UInt8(0x80) + UInt8(1)) } else { index += 1 } if buffer[index] != 0 { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } index += 1 var noHeaderBuffer = [UInt8](repeating: 0, count: data.count - index) (data as NSData).getBytes(&noHeaderBuffer, range: NSRange(location: index, length: data.count - index)) return Data(bytes: UnsafePointer<UInt8>(noHeaderBuffer), count: noHeaderBuffer.count) } func generatePublicKeyFromData() throws -> SecKey { guard var keyString = String(data: key, encoding: String.Encoding.utf8) else { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } if (keyString.hasPrefix("-----BEGIN PUBLIC KEY-----\n") && ( keyString.hasSuffix("-----END PUBLIC KEY-----\n") || keyString.hasSuffix("-----END PUBLIC KEY-----"))) { keyString = keyString.replacingOccurrences(of: "-----BEGIN PUBLIC KEY-----", with: "") keyString = keyString.replacingOccurrences(of: "-----END PUBLIC KEY-----", with: "") keyString = keyString.replacingOccurrences(of: "\r", with: "") keyString = keyString.replacingOccurrences(of: "\n", with: "") keyString = keyString.replacingOccurrences(of: "\t", with: "") keyString = keyString.replacingOccurrences(of: " ", with: "") guard let data = Data(base64Encoded: keyString) else { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } let noHeaderKey = try stripPublicKeyHeader(data) return try AsymmetricKeys.secKeyFromData(noHeaderKey, publicKey: true) } throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } do { self.key = try generatePublicKeyFromData() } catch { throw error } self.options = options self.tag = nil } } public extension PrivateKey { init(privateKey key: Data, options: AsymmetricKeys.Options = AsymmetricKeys.Options.Default) throws { func stripPrivateKeyHeader(_ data: Data) throws -> Data { var buffer = [UInt8](repeating: 0, count: data.count) (data as NSData).getBytes(&buffer, length: data.count) var index = 22 if buffer[index] != 0x04 { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } index += 1 var length = buffer[index] index += 1 let det = length & 0x80 if det == 0 { length = length & 0x7f } else { var byteCount = length & 0x7f if Int(byteCount) + index > data.count { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } var accum : UInt8 = 0 var char = buffer[index] index += Int(byteCount) while byteCount != 0 { accum = (accum << 8) + char char += 1 byteCount -= 1 } length = accum } return data.subdata(in: Range<Data.Index>(uncheckedBounds: (index,index + Int(length)))) } func generatePrivateKeyFromData() throws -> SecKey { guard var keyString = String(data: key, encoding: String.Encoding.utf8) else { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } if (keyString.hasPrefix("-----BEGIN RSA PRIVATE KEY-----\n") && ( keyString.hasSuffix("-----END RSA PRIVATE KEY-----\n") || keyString.hasSuffix("-----END RSA PRIVATE KEY-----"))) { keyString = keyString.replacingOccurrences(of:"-----BEGIN RSA PRIVATE KEY-----", with: "") keyString = keyString.replacingOccurrences(of:"-----END RSA PRIVATE KEY-----", with: "") keyString = keyString.replacingOccurrences(of:"\r", with: "") keyString = keyString.replacingOccurrences(of:"\n", with: "") keyString = keyString.replacingOccurrences(of:"\t", with: "") keyString = keyString.replacingOccurrences(of:" ", with: "") guard let data = Data(base64Encoded: keyString) else { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } return try AsymmetricKeys.secKeyFromData(data, publicKey: false) } else { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } } self.key = try generatePrivateKeyFromData() self.options = options self.tag = nil } }
bsd-3-clause
Jude309307972/JudeTest
Calculator/CalculatorTests/CalculatorTests.swift
1
903
// // CalculatorTests.swift // CalculatorTests // // Created by 徐遵成 on 15/10/1. // Copyright (c) 2015年 Jude. All rights reserved. // import UIKit import XCTest class CalculatorTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
apache-2.0
bingoogolapple/SwiftNote-PartOne
天猫抽屉/天猫抽屉/AppDelegate.swift
1
2379
// // AppDelegate.swift // 天猫抽屉 // // Created by bingoogol on 14/10/2. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) // Override point for customization after application launch. self.window?.rootViewController = MainViewController() self.window?.backgroundColor = UIColor.whiteColor() self.window?.makeKeyAndVisible() 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 throttle down OpenGL ES frame rates. 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 inactive 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:. } }
apache-2.0