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
qbalsdon/br.cd
brcd/brcd/Model/CoreDataStackManager.swift
1
2715
// // CoreDataStackManager.swift // brcd // // Created by Quintin Balsdon on 2016/01/17. // Copyright © 2016 Balsdon. All rights reserved. // import Foundation import CoreData private let SQLITE_FILE_NAME = "brcd.sqlite" class CoreDataStackManager { // MARK: - Shared Instance static let sharedInstance = CoreDataStackManager() // MARK: - The Core Data stack. The code has been moved, unaltered, from the AppDelegate. lazy var applicationDocumentsDirectory: NSURL = { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { let modelURL = NSBundle.mainBundle().URLForResource("brcd", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { let coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(SQLITE_FILE_NAME) 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 dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "br.cd", code: 9999, userInfo: dict) print("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
farshidce/RKMultiUnitRuler
Example/RKMultiUnitRuler/ViewController.swift
1
6585
// // ViewController.swift // RKMultiUnitRulerDemo // // Created by Farshid Ghods on 12/29/16. // Copyright © 2016 Rekovery. All rights reserved. // import UIKit import RKMultiUnitRuler class ViewController: UIViewController, RKMultiUnitRulerDataSource, RKMultiUnitRulerDelegate { @IBOutlet weak var ruler: RKMultiUnitRuler? @IBOutlet weak var controlHConstraint: NSLayoutConstraint? @IBOutlet weak var colorSwitch: UISwitch? var backgroundColor: UIColor = UIColor(red: 0.22, green: 0.74, blue: 0.86, alpha: 1.0) @IBOutlet weak var directionSwitch: UISwitch? @IBOutlet weak var moreMarkersSwitch: UISwitch? var rangeStart = Measurement(value: 30.0, unit: UnitMass.kilograms) var rangeLength = Measurement(value: Double(90), unit: UnitMass.kilograms) var colorOverridesEnabled = false var moreMarkers = false var direction: RKLayerDirection = .horizontal var segments = Array<RKSegmentUnit>() override func viewDidLoad() { super.viewDidLoad() self.colorSwitch?.addTarget(self, action: #selector(ViewController.colorSwitchValueChanged(sender:)), for: .valueChanged) self.directionSwitch?.addTarget(self, action: #selector(ViewController.directionSwitchValueChanged(sender:)), for: .valueChanged) self.moreMarkersSwitch?.addTarget(self, action: #selector(ViewController.moreMarkersSwitchValueChanged(sender:)), for: .valueChanged) ruler?.direction = direction ruler?.tintColor = UIColor(red: 0.15, green: 0.18, blue: 0.48, alpha: 1.0) controlHConstraint?.constant = 200.0 segments = self.createSegments() ruler?.delegate = self ruler?.dataSource = self let initialValue = (self.rangeForUnit(UnitMass.kilograms).location + self.rangeForUnit(UnitMass.kilograms).length) / 2 ruler?.measurement = NSMeasurement( doubleValue: Double(initialValue), unit: UnitMass.kilograms) self.view.layoutSubviews() // Do any additional setup after loading the view, typically from a nib. } private func createSegments() -> Array<RKSegmentUnit> { let formatter = MeasurementFormatter() formatter.unitStyle = .medium formatter.unitOptions = .providedUnit let kgSegment = RKSegmentUnit(name: "Kilograms", unit: UnitMass.kilograms, formatter: formatter) kgSegment.name = "Kilogram" kgSegment.unit = UnitMass.kilograms let kgMarkerTypeMax = RKRangeMarkerType(color: UIColor.white, size: CGSize(width: 1.0, height: 50.0), scale: 5.0) kgMarkerTypeMax.labelVisible = true kgSegment.markerTypes = [ RKRangeMarkerType(color: UIColor.white, size: CGSize(width: 1.0, height: 35.0), scale: 0.5), RKRangeMarkerType(color: UIColor.white, size: CGSize(width: 1.0, height: 50.0), scale: 1.0)] let lbsSegment = RKSegmentUnit(name: "Pounds", unit: UnitMass.pounds, formatter: formatter) let lbsMarkerTypeMax = RKRangeMarkerType(color: UIColor.white, size: CGSize(width: 1.0, height: 50.0), scale: 10.0) lbsSegment.markerTypes = [ RKRangeMarkerType(color: UIColor.white, size: CGSize(width: 1.0, height: 35.0), scale: 1.0)] if moreMarkers { kgSegment.markerTypes.append(kgMarkerTypeMax) lbsSegment.markerTypes.append(lbsMarkerTypeMax) } kgSegment.markerTypes.last?.labelVisible = true lbsSegment.markerTypes.last?.labelVisible = true return [kgSegment, lbsSegment] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func unitForSegmentAtIndex(index: Int) -> RKSegmentUnit { return segments[index] } var numberOfSegments: Int { get { return segments.count } set { } } func rangeForUnit(_ unit: Dimension) -> RKRange<Float> { let locationConverted = rangeStart.converted(to: unit as! UnitMass) let lengthConverted = rangeLength.converted(to: unit as! UnitMass) return RKRange<Float>(location: ceilf(Float(locationConverted.value)), length: ceilf(Float(lengthConverted.value))) } func styleForUnit(_ unit: Dimension) -> RKSegmentUnitControlStyle { let style: RKSegmentUnitControlStyle = RKSegmentUnitControlStyle() style.scrollViewBackgroundColor = UIColor(red: 0.22, green: 0.74, blue: 0.86, alpha: 1.0) let range = self.rangeForUnit(unit) if unit == UnitMass.pounds { style.textFieldBackgroundColor = UIColor.clear // color override location:location+40% red , location+60%:location.100% green } else { style.textFieldBackgroundColor = UIColor.red } if (colorOverridesEnabled) { style.colorOverrides = [ RKRange<Float>(location: range.location, length: 0.1 * (range.length)): UIColor.red, RKRange<Float>(location: range.location + 0.4 * (range.length), length: 0.2 * (range.length)): UIColor.green] } style.textFieldBackgroundColor = UIColor.clear style.textFieldTextColor = UIColor.white return style } func valueChanged(measurement: NSMeasurement) { print("value changed to \(measurement.doubleValue)") } func colorSwitchValueChanged(sender: UISwitch) { colorOverridesEnabled = sender.isOn ruler?.refresh() } func directionSwitchValueChanged(sender: UISwitch) { if sender.isOn { direction = .vertical controlHConstraint?.constant = 400 } else { direction = .horizontal controlHConstraint?.constant = 200 } ruler?.direction = direction ruler?.refresh() self.view.layoutSubviews() } func moreMarkersSwitchValueChanged(sender: UISwitch) { moreMarkers = sender.isOn if moreMarkers { self.rangeLength = Measurement(value: Double(90), unit: UnitMass.kilograms) } else { self.rangeLength = Measurement(value: Double(130), unit: UnitMass.kilograms) } segments = self.createSegments() ruler?.refresh() self.view.layoutSubviews() } }
mit
hanpanpan200/Tropos
Tropos/Models/Precipitation.swift
5
513
import Foundation @objc enum PrecipitationChance: Int { case None, Slight, Good } @objc class Precipitation: NSObject { let type: String let probability: Float var chance: PrecipitationChance { switch probability { case _ where probability > 30.0: return .Good case _ where probability > 0: return .Slight default: return .None } } init(probability: Float, type: String) { self.probability = probability self.type = type } }
mit
theodinspire/FingerBlade
FingerBlade/MenuTableViewController.swift
1
4226
// // MenuTableViewController.swift // FingerBlade // // Created by Cormack on 3/8/17. // Copyright © 2017 the Odin Spire. All rights reserved. // import UIKit class MenuTableViewController: UITableViewController { @IBOutlet weak var handednessLabel: UILabel! @IBOutlet weak var emailLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) handednessLabel.text = UserDefaults.standard.string(forKey: HAND) ?? "None" emailLabel.text = UserDefaults.standard.string(forKey: EMAIL) ?? "None" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } */ /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if var destination = segue.destination as? OptionViewController { destination.fromMenu = true } } /// For use in unwinding from sample cutting screen /// /// - Parameter segue: Segue of return @IBAction func unwindToMenu(segue: UIStoryboardSegue) { } /// Function for clearing defaults, debug only /// /// - Parameter sender: Object that sends the clear request @IBAction func clearDefaults(_ sender: Any) { UserDefaults.standard.removeObject(forKey: HAND) UserDefaults.standard.removeObject(forKey: EMAIL) UserDefaults.standard.removeObject(forKey: STORE) UserDefaults.standard.removeObject(forKey: COMPLETE) } }
gpl-3.0
adilbenmoussa/ABCircularProgressView
ABCircularProgressView/ABCircularProgressView.swift
1
5975
// // ABCircularProgressView.swift // Simple UIView for showing a circular progress view and the stop button when the pregress is stopped. // // Created by Adil Ben Moussa on 11/9/15. // // import UIKit class ABCircularProgressView: UIView { /** * The color of the progress view and the stop icon */ let tintCGColor: CGColor = UIColor.blueColor().CGColor /** * Size ratio of the stop button related to the progress view * @default 1/3 of the progress view */ let stopSizeRatio: CGFloat = 0.3 /** * The Opacity of the progress background layer */ let progressBackgroundOpacity: Float = 0.1 /** * The width of the line used to draw the progress view. */ let lineWidth: CGFloat = 1.0 //define the shape layers private let progressBackgroundLayer = CAShapeLayer() private let circlePathLayer = CAShapeLayer() private let iconLayer = CAShapeLayer() private var _isSpinning = false var progress: CGFloat { get { return circlePathLayer.strokeEnd } set { if (newValue > 1) { circlePathLayer.strokeEnd = 1 } else if (newValue <= 0) { circlePathLayer.strokeEnd = 0 clearStopIcon() } else { circlePathLayer.strokeEnd = newValue stopSpinning() drawStopIcon() } } } override init(frame: CGRect) { super.init(frame: frame) setup() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! setup() } private func setup() { progress = 0 progressBackgroundLayer.frame = bounds progressBackgroundLayer.strokeColor = tintCGColor progressBackgroundLayer.fillColor = nil progressBackgroundLayer.lineCap = kCALineCapRound progressBackgroundLayer.lineWidth = lineWidth progressBackgroundLayer.opacity = progressBackgroundOpacity layer.addSublayer(progressBackgroundLayer) circlePathLayer.frame = bounds circlePathLayer.lineWidth = lineWidth circlePathLayer.fillColor = UIColor.clearColor().CGColor circlePathLayer.strokeColor = tintCGColor layer.addSublayer(circlePathLayer) iconLayer.frame = bounds iconLayer.lineWidth = lineWidth iconLayer.lineCap = kCALineCapButt iconLayer.fillColor = nil layer.addSublayer(iconLayer) backgroundColor = UIColor.whiteColor() } private func circlePath() -> UIBezierPath { let circleRadius = (self.bounds.size.width - lineWidth)/2 var cgRect = CGRect(x: 0, y: 0, width: 2*circleRadius, height: 2*circleRadius) cgRect.origin.x = CGRectGetMidX(circlePathLayer.bounds) - CGRectGetMidX(cgRect) cgRect.origin.y = CGRectGetMidY(circlePathLayer.bounds) - CGRectGetMidY(cgRect) return UIBezierPath(ovalInRect: cgRect) } private func stopPath() -> UIBezierPath { let radius = bounds.size.width/2 let sideSize = bounds.size.width * stopSizeRatio let stopPath : UIBezierPath = UIBezierPath() stopPath.moveToPoint(CGPointMake(0, 0)) stopPath.addLineToPoint(CGPointMake(sideSize, 0.0)) stopPath.addLineToPoint(CGPointMake(sideSize, sideSize)) stopPath.addLineToPoint(CGPointMake(0.0, sideSize)) stopPath.closePath() stopPath.applyTransform(CGAffineTransformMakeTranslation((radius * (1-stopSizeRatio)), (radius * (1-stopSizeRatio)))) return stopPath; } private func drawStopIcon() { iconLayer.fillColor = tintCGColor iconLayer.path = stopPath().CGPath } private func clearStopIcon() { iconLayer.fillColor = nil iconLayer.path = nil } private func backgroundCirclePath(partial: Bool=false) -> UIBezierPath{ let startAngle: CGFloat = -(CGFloat)(M_PI / 2); // 90 degrees var endAngle: CGFloat = CGFloat(2 * M_PI) + startAngle let center: CGPoint = CGPointMake(bounds.size.width/2, bounds.size.height/2) let radius: CGFloat = (bounds.size.width - lineWidth)/2 // Draw background let processBackgroundPath: UIBezierPath = UIBezierPath() processBackgroundPath.lineWidth = lineWidth processBackgroundPath.lineCapStyle = CGLineCap.Round if (partial) { endAngle = (1.8 * CGFloat(M_PI)) + startAngle; progressBackgroundLayer.opacity = progressBackgroundOpacity + 0.1 } else{ progressBackgroundLayer.opacity = progressBackgroundOpacity } processBackgroundPath.addArcWithCenter(center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) return processBackgroundPath } override func layoutSubviews() { super.layoutSubviews() progressBackgroundLayer.path = backgroundCirclePath().CGPath circlePathLayer.path = circlePath().CGPath } func startSpinning() { _isSpinning = true progressBackgroundLayer.path = backgroundCirclePath(true).CGPath let rotationAnimation: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z") rotationAnimation.toValue = M_PI * 2.0 rotationAnimation.duration = 1 rotationAnimation.cumulative = true rotationAnimation.repeatCount = Float.infinity; progressBackgroundLayer.addAnimation(rotationAnimation, forKey: "rotationAnimation") } func stopSpinning(){ progressBackgroundLayer.path = backgroundCirclePath(false).CGPath progressBackgroundLayer.removeAllAnimations() _isSpinning = false } func isSpinning()->Bool { return _isSpinning } }
mit
rudkx/swift
test/IDE/complete_unresolved_members.swift
1
32463
// RUN: %empty-directory(%t) // RUN: %target-swift-ide-test -batch-code-completion -source-filename %s %S/Inputs/EnumFromOtherFile.swift -filecheck %raw-FileCheck -completion-output-dir %t // NOCRASH: Token enum SomeEnum1 { case South case North } enum SomeEnum2 { case East case West } enum SomeEnum3: Hashable { case Payload(SomeEnum1) } struct NotOptions1 { static let NotSet = 1 } struct SomeOptions1 : OptionSet { let rawValue : Int static let Option1 = SomeOptions1(rawValue: 1 << 1) static let Option2 = SomeOptions1(rawValue: 1 << 2) static let Option3 = SomeOptions1(rawValue: 1 << 3) let NotStaticOption = SomeOptions1(rawValue: 1 << 4) static let NotOption = 1 } struct SomeOptions2 : OptionSet { let rawValue : Int static let Option4 = SomeOptions2(rawValue: 1 << 1) static let Option5 = SomeOptions2(rawValue: 1 << 2) static let Option6 = SomeOptions2(rawValue: 1 << 3) } enum EnumAvail1 { case aaa @available(*, unavailable) case AAA @available(*, deprecated) case BBB } struct OptionsAvail1 : OptionSet { let rawValue: Int static let aaa = OptionsAvail1(rawValue: 1 << 0) @available(*, unavailable) static let AAA = OptionsAvail1(rawValue: 1 << 0) @available(*, deprecated) static let BBB = OptionsAvail1(rawValue: 1 << 1) } func OptionSetTaker1(_ Op : SomeOptions1) {} func OptionSetTaker2(_ Op : SomeOptions2) {} func OptionSetTaker3(_ Op1: SomeOptions1, _ Op2: SomeOptions2) {} func OptionSetTaker4(_ Op1: SomeOptions2, _ Op2: SomeOptions1) {} func OptionSetTaker5(_ Op1: SomeOptions1, _ Op2: SomeOptions2, _ En1 : SomeEnum1, _ En2: SomeEnum2) {} func OptionSetTaker6(_ Op1: SomeOptions1, _ Op2: SomeOptions2) {} func OptionSetTaker6(_ Op1: SomeOptions2, _ Op2: SomeOptions1) {} func OptionSetTaker7(_ Op1: SomeOptions1, _ Op2: SomeOptions2) -> Int {return 0} func EnumTaker1(_ E : SomeEnum1) {} func optionalEnumTaker1(_ : SomeEnum1?) {} class OptionTakerContainer1 { func OptionSetTaker1(_ op : SomeOptions1) {} func EnumTaker1(_ E : SomeEnum1) {} } class C1 { func f1() { var f : SomeOptions1 f = .#^UNRESOLVED_1^# } func f2() { var f : SomeOptions1 f = [.#^UNRESOLVED_2?check=UNRESOLVED_1^# } func f3() { var f : SomeOptions1 f = [.Option1, .#^UNRESOLVED_3?check=UNRESOLVED_1^# } } class C2 { func f1() { OptionSetTaker1(.#^UNRESOLVED_4?check=UNRESOLVED_1^#) } func f2() { OptionSetTaker1([.Option1, .#^UNRESOLVED_5?check=UNRESOLVED_1^#]) } // UNRESOLVED_1: Begin completions // UNRESOLVED_1-NOT: SomeEnum1 // UNRESOLVED_1-NOT: SomeEnum2 // UNRESOLVED_1-DAG: Decl[StaticVar]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: Option1[#SomeOptions1#]; name=Option1 // UNRESOLVED_1-DAG: Decl[StaticVar]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: Option2[#SomeOptions1#]; name=Option2 // UNRESOLVED_1-DAG: Decl[StaticVar]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: Option3[#SomeOptions1#]; name=Option3 // UNRESOLVED_1-DAG: Decl[StaticVar]/CurrNominal: NotOption[#Int#]; name=NotOption // UNRESOLVED_1-NOT: NotStaticOption } class C3 { func f1() { OptionSetTaker2(.#^UNRESOLVED_6?check=UNRESOLVED_2^#) } func f2() { OptionSetTaker2([.Option4, .#^UNRESOLVED_7?check=UNRESOLVED_2^#]) } // UNRESOLVED_2: Begin completions // UNRESOLVED_2-NOT: SomeEnum1 // UNRESOLVED_2-NOT: SomeEnum2 // UNRESOLVED_2-DAG: Decl[StaticVar]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: Option4[#SomeOptions2#]; name=Option4 // UNRESOLVED_2-DAG: Decl[StaticVar]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: Option5[#SomeOptions2#]; name=Option5 // UNRESOLVED_2-DAG: Decl[StaticVar]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: Option6[#SomeOptions2#]; name=Option6 // UNRESOLVED_2-NOT: Not } class C4 { func f1() { var E : SomeEnum1 E = .#^UNRESOLVED_8?check=UNRESOLVED_3^# } func f2() { EnumTaker1(.#^UNRESOLVED_9?check=UNRESOLVED_3^#) } func f3() { OptionSetTaker5(.Option1, .Option4, .#^UNRESOLVED_12?check=UNRESOLVED_3^#, .West) } func f4() { var _: SomeEnum1? = .#^UNRESOLVED_OPT_1?check=UNRESOLVED_3_OPT^# } func f5() { optionalEnumTaker1(.#^UNRESOLVED_OPT_2?check=UNRESOLVED_3_OPT^#) } func f6() { var _: SomeEnum1??? = .#^UNRESOLVED_OPT_3?check=UNRESOLVED_3_OPTOPTOPT^# } } // Exhaustive to make sure we don't include `SomeOptions1`, `SomeOptions2`, `none` or `some` entries. // UNRESOLVED_3: Begin completions, 3 items // UNRESOLVED_3-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: North[#SomeEnum1#]; name=North // UNRESOLVED_3-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: South[#SomeEnum1#]; name=South // UNRESOLVED_3-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: hash({#(self): SomeEnum1#})[#(into: inout Hasher) -> Void#]; name=hash(:) // UNRESOLVED_3: End completions // Exhaustive to make sure we don't include `init({#(some):` or `init({#nilLiteral:` entries // UNRESOLVED_3_OPT: Begin completions, 9 items // UNRESOLVED_3_OPT-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Convertible]: North[#SomeEnum1#]; // UNRESOLVED_3_OPT-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Convertible]: South[#SomeEnum1#]; // UNRESOLVED_3_OPT-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: hash({#(self): SomeEnum1#})[#(into: inout Hasher) -> Void#]; // UNRESOLVED_3_OPT-DAG: Keyword[nil]/None/Erase[1]/TypeRelation[Identical]: nil[#SomeEnum1?#]; name=nil // UNRESOLVED_3_OPT-DAG: Decl[EnumElement]/CurrNominal/IsSystem/TypeRelation[Identical]: none[#Optional<SomeEnum1>#]; name=none // UNRESOLVED_3_OPT-DAG: Decl[EnumElement]/CurrNominal/IsSystem/TypeRelation[Identical]: some({#SomeEnum1#})[#Optional<SomeEnum1>#]; // UNRESOLVED_3_OPT-DAG: Decl[InstanceMethod]/CurrNominal/IsSystem: map({#(self): Optional<SomeEnum1>#})[#((SomeEnum1) throws -> U) -> U?#]; // UNRESOLVED_3_OPT-DAG: Decl[InstanceMethod]/CurrNominal/IsSystem: flatMap({#(self): Optional<SomeEnum1>#})[#((SomeEnum1) throws -> U?) -> U?#]; // UNRESOLVED_3_OPT-DAG: Decl[InstanceMethod]/CurrNominal/IsSystem/TypeRelation[Invalid]: hash({#(self): Optional<SomeEnum1>#})[#(into: inout Hasher) -> Void#]; // UNRESOLVED_3_OPT: End completions // Exhaustive to make sure we don't include `init({#(some):` or `init({#nilLiteral:` entries // UNRESOLVED_3_OPTOPTOPT: Begin completions, 9 items // UNRESOLVED_3_OPTOPTOPT-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Convertible]: North[#SomeEnum1#]; // UNRESOLVED_3_OPTOPTOPT-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Convertible]: South[#SomeEnum1#]; // UNRESOLVED_3_OPTOPTOPT-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: hash({#(self): SomeEnum1#})[#(into: inout Hasher) -> Void#]; // UNRESOLVED_3_OPTOPTOPT-DAG: Keyword[nil]/None/Erase[1]/TypeRelation[Identical]: nil[#SomeEnum1???#]; name=nil // UNRESOLVED_3_OPTOPTOPT-DAG: Decl[EnumElement]/CurrNominal/IsSystem/TypeRelation[Identical]: none[#Optional<SomeEnum1??>#]; name=none // UNRESOLVED_3_OPTOPTOPT-DAG: Decl[EnumElement]/CurrNominal/IsSystem/TypeRelation[Identical]: some({#SomeEnum1??#})[#Optional<SomeEnum1??>#]; // UNRESOLVED_3_OPTOPTOPT-DAG: Decl[InstanceMethod]/CurrNominal/IsSystem: map({#(self): Optional<SomeEnum1??>#})[#((SomeEnum1??) throws -> U) -> U?#]; // UNRESOLVED_3_OPTOPTOPT-DAG: Decl[InstanceMethod]/CurrNominal/IsSystem: flatMap({#(self): Optional<SomeEnum1??>#})[#((SomeEnum1??) throws -> U?) -> U?#]; // UNRESOLVED_3_OPTOPTOPT-DAG: Decl[InstanceMethod]/CurrNominal/IsSystem/TypeRelation[Invalid]: hash({#(self): Optional<SomeEnum1??>#})[#(into: inout Hasher) -> Void#]; // UNRESOLVED_3_OPTOPTOPT: End completions enum Somewhere { case earth, mars } extension Optional where Wrapped == Somewhere { init(str: String) { fatalError() } static var nowhere: Self { return nil } } func testOptionalWithCustomExtension() { var _: Somewhere? = .#^UNRESOLVED_OPT_4^# // UNRESOLVED_OPT_4: Begin completions, 11 items // UNRESOLVED_OPT_4-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Convertible]: earth[#Somewhere#]; // UNRESOLVED_OPT_4-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Convertible]: mars[#Somewhere#]; // UNRESOLVED_OPT_4-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: hash({#(self): Somewhere#})[#(into: inout Hasher) -> Void#]; // UNRESOLVED_OPT_4-DAG: Keyword[nil]/None/Erase[1]/TypeRelation[Identical]: nil[#Somewhere?#]; name=nil // UNRESOLVED_OPT_4-DAG: Decl[EnumElement]/CurrNominal/IsSystem/TypeRelation[Identical]: none[#Optional<Somewhere>#]; name=none // UNRESOLVED_OPT_4-DAG: Decl[EnumElement]/CurrNominal/IsSystem/TypeRelation[Identical]: some({#Somewhere#})[#Optional<Somewhere>#]; // UNRESOLVED_OPT_4-DAG: Decl[Constructor]/CurrNominal/TypeRelation[Identical]: init({#str: String#})[#Optional<Somewhere>#]; name=init(str:) // UNRESOLVED_OPT_4-DAG: Decl[StaticVar]/CurrNominal/TypeRelation[Identical]: nowhere[#Optional<Somewhere>#]; name=nowhere // UNRESOLVED_OPT_4-DAG: Decl[InstanceMethod]/CurrNominal/IsSystem: map({#(self): Optional<Somewhere>#})[#((Somewhere) throws -> U) -> U?#]; // UNRESOLVED_OPT_4-DAG: Decl[InstanceMethod]/CurrNominal/IsSystem: flatMap({#(self): Optional<Somewhere>#})[#((Somewhere) throws -> U?) -> U?#]; // UNRESOLVED_OPT_4-DAG: Decl[InstanceMethod]/CurrNominal/IsSystem/TypeRelation[Invalid]: hash({#(self): Optional<Somewhere>#})[#(into: inout Hasher) -> Void#]; // UNRESOLVED_OPT_4-NOT: init({#(some): // UNRESOLVED_OPT_4-NOT: init({#nilLiteral: // UNRESOLVED_OPT_4: End completions } class C5 { func f1() { OptionSetTaker3(.Option1, .#^UNRESOLVED_10?check=UNRESOLVED_2^#) } func f2() { OptionSetTaker4(.#^UNRESOLVED_11?check=UNRESOLVED_2^#, .Option1) } } OptionSetTaker5(.Option1, .Option4, .#^UNRESOLVED_13?check=UNRESOLVED_3^#, .West) OptionSetTaker5(.#^UNRESOLVED_14?check=UNRESOLVED_1^#, .Option4, .South, .West) OptionSetTaker5([.#^UNRESOLVED_15?check=UNRESOLVED_1^#], .Option4, .South, .West) OptionSetTaker6(.#^UNRESOLVED_16^#, .Option4) // UNRESOLVED_16: Begin completions // UNRESOLVED_16-DAG: Decl[StaticVar]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: Option1[#SomeOptions1#]; // UNRESOLVED_16-DAG: Decl[StaticVar]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: Option2[#SomeOptions1#]; // UNRESOLVED_16-DAG: Decl[StaticVar]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: Option3[#SomeOptions1#]; // UNRESOLVED_16-DAG: Decl[StaticVar]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: Option4[#SomeOptions2#]; // UNRESOLVED_16-DAG: Decl[StaticVar]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: Option5[#SomeOptions2#]; // UNRESOLVED_16-DAG: Decl[StaticVar]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: Option6[#SomeOptions2#]; // UNRESOLVED_16-DAG: Decl[StaticVar]/CurrNominal: NotOption[#Int#]; name=NotOption // UNRESOLVED_16: End completion OptionSetTaker6(.Option4, .#^UNRESOLVED_17?check=UNRESOLVED_4^#,) var a = {() in OptionSetTaker5([.#^UNRESOLVED_18?check=UNRESOLVED_1^#], .Option4, .South, .West) } var Container = OptionTakerContainer1() Container.OptionSetTaker1(.#^UNRESOLVED_19?check=UNRESOLVED_1^#) Container.EnumTaker1(.#^UNRESOLVED_20?check=UNRESOLVED_3^# func parserSync() {} // UNRESOLVED_4: Begin completions // UNRESOLVED_4-DAG: Decl[StaticVar]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: Option1[#SomeOptions1#]; name=Option1 // UNRESOLVED_4-DAG: Decl[StaticVar]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: Option2[#SomeOptions1#]; name=Option2 // UNRESOLVED_4-DAG: Decl[StaticVar]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: Option3[#SomeOptions1#]; name=Option3 // UNRESOLVED_4-NOT: Option4 // UNRESOLVED_4-NOT: Option5 // UNRESOLVED_4-NOT: Option6 var OpIns1 : SomeOptions1 = .#^UNRESOLVED_21?check=UNRESOLVED_1^# var c1 = {() -> SomeOptions1 in return .#^UNRESOLVED_22?check=UNRESOLVED_1^# } var c1_noreturn = {() -> SomeOptions1 in .#^UNRESOLVED_22_noreturn?check=UNRESOLVED_1^# } class C6 { func f1() -> SomeOptions1 { return .#^UNRESOLVED_23?check=UNRESOLVED_1^# } func f2(p : SomeEnum3) { switch p { case .Payload(.#^UNRESOLVED_24?check=UNRESOLVED_3^#) } } } class C6 { func f1(e: SomeEnum1) { if let x = Optional(e) where x == .#^UNRESOLVED_25?check=UNRESOLVED_3^# } } class C7 {} extension C7 { func extendedf1(_ e :SomeEnum1) {} } var cInst1 = C7() cInst1.extendedf1(.#^UNRESOLVED_26?check=UNRESOLVED_3^# func nocrash1() -> SomeEnum1 { return .#^UNRESOLVED_27_NOCRASH?check=NOCRASH^# } func resetParser1() {} func f() -> SomeEnum1 { return .#^UNRESOLVED_27?check=UNRESOLVED_3^# } let TopLevelVar1 = OptionSetTaker7([.#^UNRESOLVED_28?check=UNRESOLVED_1^#], [.Option4]) let TopLevelVar2 = OptionSetTaker1([.#^UNRESOLVED_29?check=UNRESOLVED_1^#]) let TopLevelVar3 = OptionSetTaker7([.Option1], [.#^UNRESOLVED_30?check=UNRESOLVED_2^#]) let TopLevelVar4 = OptionSetTaker7([.Option1], [.Option4, .#^UNRESOLVED_31?check=UNRESOLVED_2^#]) let _: [SomeEnum1] = [.#^UNRESOLVED_32?check=UNRESOLVED_3^#] let _: [SomeEnum1] = [.South, .#^UNRESOLVED_33?check=UNRESOLVED_3^#] let _: [SomeEnum1] = [.South, .#^UNRESOLVED_34?check=UNRESOLVED_3^# .South] let _: [SomeEnum1:SomeOptions1] = [.South:.Option1, .South:.#^UNRESOLVED_35?check=UNRESOLVED_1^#] let _: [SomeEnum1:SomeOptions1] = [.South:.Option1, .#^UNRESOLVED_36?check=UNRESOLVED_3^#:.Option1] let _: [SomeEnum1:SomeOptions1] = [.South:.Option1, .#^UNRESOLVED_37?check=UNRESOLVED_3^#] let _: [SomeEnum1:SomeOptions1] = [.South:.Option1, .#^UNRESOLVED_38?check=UNRESOLVED_3^#:] let _: [SomeEnum1:SomeOptions1] = [.#^UNRESOLVED_39?check=UNRESOLVED_3^#] let _: [SomeEnum1:SomeOptions1] = [.#^UNRESOLVED_40?check=UNRESOLVED_3^#:] let _: [SomeEnum1:SomeEnum3] = [.South:.Payload(.South), .South: .Payload(.#^UNRESOLVED_41?check=UNRESOLVED_3^#)] let _: [SomeEnum3:SomeEnum1] = [.Payload(.South):.South, .Payload(.#^UNRESOLVED_42?check=UNRESOLVED_3^#):.South] let _: [SomeEnum3:SomeEnum1] = [.Payload(.South):.South, .Payload(.#^UNRESOLVED_43?check=UNRESOLVED_3^#):] let _: [SomeEnum3:SomeEnum1] = [.Payload(.South):.South, .Payload(.#^UNRESOLVED_44?check=UNRESOLVED_3^#)] func testAvail1(_ x: EnumAvail1) { testAvail1(.#^ENUM_AVAIL_1^#) } // ENUM_AVAIL_1: Begin completions, 3 items // ENUM_AVAIL_1-NOT: AAA // ENUM_AVAIL_1-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: aaa[#EnumAvail1#]; // ENUM_AVAIL_1-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/NotRecommended/TypeRelation[Identical]: BBB[#EnumAvail1#]; // ENUM_AVAIL_1-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: hash({#(self): EnumAvail1#})[#(into: inout Hasher) -> Void#]; // ENUM_AVAIL_1-NOT: AAA // ENUM_AVAIL_1: End completions func testAvail2(_ x: OptionsAvail1) { testAvail2(.#^OPTIONS_AVAIL_1^#) } // OPTIONS_AVAIL_1: Begin completions // OPTIONS_AVAIL_1-NOT: AAA // OPTIONS_AVAIL_1-DAG: Decl[StaticVar]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: aaa[#OptionsAvail1#]; // OPTIONS_AVAIL_1-DAG: Decl[StaticVar]/CurrNominal/Flair[ExprSpecific]/NotRecommended/TypeRelation[Identical]: BBB[#OptionsAvail1#]; // OPTIONS_AVAIL_1-DAG: Decl[Constructor]/CurrNominal/TypeRelation[Identical]: init({#rawValue: Int#})[#OptionsAvail1#] // OPTIONS_AVAIL_1-NOT: AAA // OPTIONS_AVAIL_1: End completions func testWithLiteral1() { struct S { enum MyEnum { case myCase } enum Thing { case thingCase } var thing: Thing func takeEnum(thing: MyEnum, other: Double) {} } let s: S _ = s.takeEnum(thing: .#^WITH_LITERAL_1^#, other: 1.0) // WITH_LITERAL_1: Begin completions, 2 items // WITH_LITERAL_1-NEXT: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: myCase[#S.MyEnum#]; // WITH_LITERAL_1-NEXT: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: hash({#(self): S.MyEnum#})[#(into: inout Hasher) -> Void#]; // WITH_LITERAL_1-NEXT: End completions } func testWithLiteral2() { struct S { enum MyEnum { case myCase } enum Thing { case thingCase } var thing: Thing func takeEnum(thing: MyEnum, other: Int) {} func takeEnum(thing: MyEnum, other: Double) {} } let s: S _ = s.takeEnum(thing: .#^WITH_LITERAL_2?check=WITH_LITERAL_1^#, other: 1.0) } func testWithLiteral3() { struct S { enum MyEnum { case myCase } enum Thing { case thingCase } var thing: Thing func takeEnum(thing: MyEnum, other: Int) {} func takeEnum(thing: MyEnum, other: Double) {} func test(s: S) { _ = s.takeEnum(thing: .#^WITH_LITERAL_3^#, other: 1.0) // WITH_LITERAL_3: Begin completions, 2 items // WITH_LITERAL_3-NEXT: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: myCase[#MyEnum#]; // WITH_LITERAL_3-NEXT: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: hash({#(self): MyEnum#})[#(into: inout Hasher) -> Void#]; // WITH_LITERAL_3-NEXT: End completions } } } func testInvalid1() { func invalid() -> NoSuchEnum { return .#^INVALID_1?check=NOCRASH^# // Don't crash. } } func enumFromOtherFile() -> EnumFromOtherFile { return .#^OTHER_FILE_1^# // Don't crash. } // OTHER_FILE_1: Begin completions // OTHER_FILE_1-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: b({#String#})[#EnumFromOtherFile#]; // OTHER_FILE_1-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: a({#Int#})[#EnumFromOtherFile#]; // OTHER_FILE_1-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: c[#EnumFromOtherFile#]; // OTHER_FILE_1: End completions struct NonOptSet { static let a = NonOptSet() static let wrongType = 1 let notStatic = NonOptSet() init(x: Int, y: Int) {} init() {} static func b() -> NonOptSet { return NonOptSet() } static func wrongType() -> Int { return 0 } func notStatic() -> NonOptSet { return NonOptSet() } } func testNonOptSet() { let x: NonOptSet x = .#^NON_OPT_SET_1^# } // NON_OPT_SET_1: Begin completions, 6 items // NON_OPT_SET_1-DAG: Decl[StaticVar]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: a[#NonOptSet#] // NON_OPT_SET_1-DAG: Decl[StaticVar]/CurrNominal: wrongType[#Int#]; // NON_OPT_SET_1-DAG: Decl[Constructor]/CurrNominal/TypeRelation[Identical]: init({#x: Int#}, {#y: Int#})[#NonOptSet#] // NON_OPT_SET_1-DAG: Decl[Constructor]/CurrNominal/TypeRelation[Identical]: init()[#NonOptSet#] // NON_OPT_SET_1-DAG: Decl[StaticMethod]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: b()[#NonOptSet#] // NON_OPT_SET_1-DAG: Decl[InstanceMethod]/CurrNominal: notStatic({#(self): NonOptSet#})[#() -> NonOptSet#]; // NON_OPT_SET_1: End completions func testNonOptSet() { let x: NonOptSet = .#^NON_OPT_SET_2?check=NON_OPT_SET_1^# } func testNonOptSet() -> NonOptSet { return .#^NON_OPT_SET_3?check=NON_OPT_SET_1^# } func testInStringInterpolation() { enum MyEnum { case foo, bar } func takeEnum(_ e: MyEnum) -> MyEnum { return e } let x = "enum: \(takeEnum(.#^STRING_INTERPOLATION_1^#))" let y = "enum: \(.#^STRING_INTERPOLATION_INVALID?check=NOCRASH^#)" // Dont'crash. } // STRING_INTERPOLATION_1: Begin completions // STRING_INTERPOLATION_1-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: foo[#MyEnum#]; // STRING_INTERPOLATION_1-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: bar[#MyEnum#]; // STRING_INTERPOLATION_1: End completions class BaseClass { class SubClass : BaseClass { init() {} } static var subInstance: SubClass = SubClass() init() {} init?(failable: Void) {} } protocol MyProtocol { typealias Concrete1 = BaseClass typealias Concrete2 = AnotherTy } extension BaseClass : MyProtocol {} struct AnotherTy: MyProtocol {} func testSubType() { var _: BaseClass = .#^SUBTYPE_1^# } // SUBTYPE_1: Begin completions, 6 items // SUBTYPE_1-DAG: Decl[Constructor]/CurrNominal/TypeRelation[Identical]: init()[#BaseClass#]; // SUBTYPE_1-DAG: Decl[Class]/CurrNominal/TypeRelation[Convertible]: SubClass[#BaseClass.SubClass#]; // SUBTYPE_1-DAG: Decl[StaticVar]/CurrNominal/TypeRelation[Convertible]: subInstance[#BaseClass.SubClass#]; // SUBTYPE_1-DAG: Decl[Constructor]/CurrNominal: init({#failable: Void#})[#BaseClass?#]; // SUBTYPE_1-DAG: Decl[TypeAlias]/Super/TypeRelation[Identical]: Concrete1[#BaseClass#]; // SUBTYPE_1-DAG: Decl[TypeAlias]/Super: Concrete2[#AnotherTy#]; // SUBTYPE_1: End completions func testMemberTypealias() { var _: MyProtocol = .#^SUBTYPE_2^# } // SUBTYPE_2: Begin completions, 2 items // SUBTYPE_2-DAG: Decl[TypeAlias]/CurrNominal/TypeRelation[Convertible]: Concrete1[#BaseClass#]; // SUBTYPE_2-DAG: Decl[TypeAlias]/CurrNominal/TypeRelation[Convertible]: Concrete2[#AnotherTy#]; // SUBTYPE_2: End completions enum Generic<T> { case contains(content: T) case empty static func create(_: T) -> Generic<T> { fatalError() } } func takeGenericInt(_: Generic<Int>) { } func takeGenericU<U>(_: Generic<U>) { } func testGeneric() { do { let _: Generic<Int> = .#^GENERIC_1?check=GENERIC_1_INT^# } takeGenericInt(.#^GENERIC_2?check=GENERIC_1_INT^#) takeGenericU(.#^GENERIC_3?check=GENERIC_1_U^#) } switch Generic<Int>.empty { case let .#^GENERIC_4?check=GENERIC_1_INT^# } // GENERIC_1_INT: Begin completions // GENERIC_1_INT-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: contains({#content: Int#})[#Generic<Int>#]; // GENERIC_1_INT-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: empty[#Generic<Int>#]; // GENERIC_1_INT: End completions // GENERIC_1_U: Begin completions // GENERIC_1_U-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: contains({#content: U#})[#Generic<U>#]; // GENERIC_1_U-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: empty[#Generic<U>#]; // GENERIC_1_U-DAG: Decl[StaticMethod]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: create({#U#})[#Generic<U>#]; // GENERIC_1_U: End completions struct HasCreator { static var create: () -> HasCreator = { fatalError() } static var create_curried: () -> () -> HasCreator = { fatalError() } } func testHasStaticClosure() { let _: HasCreator = .#^STATIC_CLOSURE_1^# } // STATIC_CLOSURE_1: Begin completions, 3 items // STATIC_CLOSURE_1-DAG: Decl[Constructor]/CurrNominal/TypeRelation[Identical]: init()[#HasCreator#]; // FIXME: Suggest 'create()[#HasCreateor#]', not 'create'. // STATIC_CLOSURE_1-DAG: Decl[StaticVar]/CurrNominal: create[#() -> HasCreator#]; // STATIC_CLOSURE_1-DAG: Decl[StaticVar]/CurrNominal: create_curried[#() -> () -> HasCreator#]; // STATIC_CLOSURE_1: End completions struct HasOverloaded { init(e: SomeEnum1) {} init(e: SomeEnum2) {} func takeEnum(_ e: SomeEnum1) -> Int { return 0 } func takeEnum(_ e: SomeEnum2) -> Int { return 0 } } func testOverload(val: HasOverloaded) { let _ = val.takeEnum(.#^OVERLOADED_METHOD_1^#) // OVERLOADED_METHOD_1: Begin completions, 6 items // OVERLOADED_METHOD_1-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: South[#SomeEnum1#]; name=South // OVERLOADED_METHOD_1-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: North[#SomeEnum1#]; name=North // OVERLOADED_METHOD_1-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: hash({#(self): SomeEnum1#})[#(into: inout Hasher) -> Void#]; // OVERLOADED_METHOD_1-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: East[#SomeEnum2#]; name=East // OVERLOADED_METHOD_1-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: West[#SomeEnum2#]; name=West // OVERLOADED_METHOD_1-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: hash({#(self): SomeEnum2#})[#(into: inout Hasher) -> Void#]; // OVERLOADED_METHOD_1: End completions let _ = HasOverloaded.init(e: .#^OVERLOADED_INIT_1?check=OVERLOADED_METHOD_1^#) // Same as OVERLOADED_METHOD_1. let _ = HasOverloaded(e: .#^OVERLOADED_INIT_2?check=OVERLOADED_METHOD_1^#) // Same as OVERLOADED_METHOD_1. } protocol HasStatic: Equatable { static var instance: Self { get } } func receiveHasStatic<T: HasStatic>(x: T) {} func testingGenericParam1<T: HasStatic>(x: inout T, fn: (T) -> Void) -> T { x = .#^GENERICPARAM_1^# // GENERICPARAM_1: Begin completions, 1 items // GENERICPARAM_1: Decl[StaticVar]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: instance[#HasStatic#]; name=instance // GENERICPARAM_1: End completions /* Parser sync. */; let _: (Int, T) = (1, .#^GENERICPARAM_2?check=GENERICPARAM_1^#) // Same as GENERICPARAM_1. (_, x) = (1, .#^GENERICPARAM_3?check=GENERICPARAM_1^#) // Same as GENERICPARAM_1. let _ = fn(.#^GENERICPARAM_4?check=GENERICPARAM_1^#) // Same as GENERICPARAM_1. let _ = receiveHasStatic(x: .#^GENERICPARAM_5?check=GENERICPARAM_1^#) // Same as GENERICPARAM_1. let _ = { () -> T in return .#^GENERICPARAM_6?check=GENERICPARAM_1^# // Same as GENERICPARAM_1. } let _: () -> T = { return .#^GENERICPARAM_7?check=GENERICPARAM_1^# // Same as GENERICPARAM_1. } let _ = { (_: InvalidTy) -> T in return .#^GENERICPARAM_8?check=GENERICPARAM_1^# // Same as GENERICPARAM_1. } if case .#^GENERICPARAM_9?check=GENERICPARAM_1^# = x {} // Same as GENERICPARAM_1. return .#^GENERICPARAM_10?check=GENERICPARAM_1^# // Same as GENERICPARAM_1. } class C<T: HasStatic> { var t: T = .instance func foo(x: T) -> T { return .#^GENERICPARAM_11?check=GENERICPARAM_1^# // Same as GENERICPARAM_1. } func bar<U: HasStatic>(x: U) -> U { return .#^GENERICPARAM_12?check=GENERICPARAM_1^# // Same as GENERICPARAM_1. } func testing() { let _ = foo(x: .#^GENERICPARAM_13?check=GENERICPARAM_1^#) // Same as GENERICPARAM_1. let _ = bar(x: .#^GENERICPARAM_14?check=GENERICPARAM_1^#) // Same as GENERICPARAM_1. t = .#^GENERICPARAM_15?check=GENERICPARAM_1^# // Same as GENERICPARAM_1. /* Parser sync. */; func sync1() {} self.t = .#^GENERICPARAM_16?check=GENERICPARAM_1^# // Same as GENERICPARAM_1. /* Parser sync. */; func sync2() {} (_, t) = (1, .#^GENERICPARAM_17?check=GENERICPARAM_1^#) // Same as GENERICPARAM_1. (_, self.t) = (1, .#^GENERICPARAM_18?check=GENERICPARAM_1^#) // Same as GENERICPARAM_1. } } func testingGenericParam2<X>(obj: C<X>) { let _ = obj.foo(x: .#^GENERICPARAM_19?check=GENERICPARAM_1^#) // Same as GENERICPARAM_1. let _ = obj.bar(x: .#^GENERICPARAM_20?check=GENERICPARAM_1^#) // Same as GENERICPARAM_1. obj.t = .#^GENERICPARAM_21?check=GENERICPARAM_1^# // Same as GENERICPARAM_1. } struct TestingStruct { var value: SomeEnum1 = .#^DECL_MEMBER_INIT_1?check=UNRESOLVED_3^# } func testDefaultArgument(arg: SomeEnum1 = .#^DEFAULT_ARG_1?check=UNRESOLVED_3^#) {} class TestDefalutArg { func method(arg: SomeEnum1 = .#^DEFAULT_ARG_2?check=UNRESOLVED_3^#) {} init(arg: SomeEnum1 = .#^DEFAULT_ARG_3?check=UNRESOLVED_3^#) {} } struct ConcreteMyProtocol: MyProtocol {} struct OtherProtocol {} struct ConcreteOtherProtocol: OtherProtocol {} struct MyStruct<T> {} extension MyStruct where T: MyProtocol { static var myProtocolOption: MyStruct<ConcreteMyProtocol> { fatalError() } } extension MyStruct where T: OtherProtocol { static var otherProtocolOption: MyStruct<ConcreteOtherProtocol> { fatalError() } } func receiveMyStructOfMyProtocol<T: MyProtocol>(value: MyStruct<T>) {} func testTypeParamInContextType() { receiveMyStructOfMyProtocol(value: .#^TYPEPARAM_IN_CONTEXTTYPE_1^#) // TYPEPARAM_IN_CONTEXTTYPE_1: Begin completions, 3 items // TYPEPARAM_IN_CONTEXTTYPE_1-DAG: Decl[Constructor]/CurrNominal/TypeRelation[Identical]: init()[#MyStruct<MyProtocol>#]; // TYPEPARAM_IN_CONTEXTTYPE_1-DAG: Decl[StaticVar]/CurrNominal/TypeRelation[Convertible]: myProtocolOption[#MyStruct<ConcreteMyProtocol>#]; // TYPEPARAM_IN_CONTEXTTYPE_1-DAG: Decl[StaticVar]/CurrNominal: otherProtocolOption[#MyStruct<ConcreteOtherProtocol>#]; // TYPEPARAM_IN_CONTEXTTYPE_1: End completions } func testTernaryOperator(cond: Bool) { let _: SomeEnum1 = cond ? .#^TERNARY_1?check=UNRESOLVED_3^# func sync(){} let _: SomeEnum1 = cond ? .#^TERNARY_2?check=UNRESOLVED_3^# : func sync(){} let _: SomeEnum1 = cond ? .#^TERNARY_3?check=UNRESOLVED_3^# : .South func sync(){} let _: SomeEnum1 = cond ? .South : .#^TERNARY_4?check=UNRESOLVED_3^# } func testTernaryOperator2(cond: Bool) { let _: SomeEnum1 = cond ? .#^TERNARY_5?check=UNRESOLVED_3^# : .bogus func sync(){} let _: SomeEnum1 = cond ? .bogus : .#^TERNARY_6?check=UNRESOLVED_3^# func sync(){} let _: SomeEnum1 = .#^TERNARY_CONDITION^# ? .bogus : .bogus // TERNARY_CONDITION: Begin completions // TERNARY_CONDITION-DAG: Decl[Constructor]/CurrNominal/IsSystem/TypeRelation[Identical]: init()[#Bool#]; name=init() // TERNARY_CONDITION: End completions } func overloadedClosureRcv(_: () -> SomeEnum1) {} func overloadedClosureRcv(_: () -> SomeEnum2) {} func testClosureReturnTypeForOverloaded() { overloadedClosureRcv { .#^OVERLOADED_CLOSURE_RETURN^# } // OVERLOADED_CLOSURE_RETURN: Begin completions, 6 items // OVERLOADED_CLOSURE_RETURN-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: South[#SomeEnum1#]; // OVERLOADED_CLOSURE_RETURN-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: North[#SomeEnum1#]; // OVERLOADED_CLOSURE_RETURN-DAG: Decl[InstanceMethod]/CurrNominal: hash({#(self): SomeEnum1#})[#(into: inout Hasher) -> Void#]; // OVERLOADED_CLOSURE_RETURN-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: East[#SomeEnum2#]; // OVERLOADED_CLOSURE_RETURN-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: West[#SomeEnum2#]; // OVERLOADED_CLOSURE_RETURN-DAG: Decl[InstanceMethod]/CurrNominal: hash({#(self): SomeEnum2#})[#(into: inout Hasher) -> Void#]; // OVERLOADED_CLOSURE_RETURN: End completions } func receiveAutoclosure(_: @autoclosure () -> SomeEnum1) {} func receiveAutoclosureOpt(_: @autoclosure () -> SomeEnum1?) {} func testAutoclosre() { receiveAutoclosure(.#^AUTOCLOSURE?check=UNRESOLVED_3^#) // Same as UNRESOLVED_3 receiveAutoclosureOpt(.#^AUTOCLOSURE_OPT?check=UNRESOLVED_3_OPT^#) // Same as UNRESOLVED_3_OPT } func testAutoclosreFuncTy(fn: (@autoclosure () -> SomeEnum1) -> Void, fnOpt: (@autoclosure () -> SomeEnum1?) -> Void) { fn(.#^AUTOCLOSURE_FUNCTY?check=UNRESOLVED_3^#) // Same as UNRESOLVED_3 fnOpt(.#^AUTOCLOSURE_FUNCTY_OPT?check=UNRESOLVED_3_OPT^#) // Same as UNRESOLVED_3_OPT } func testSameType() { typealias EnumAlias = SomeEnum1 func testSugarType(_ arg: Optional<SomeEnum1>, arg2: Int8) {} func testSugarType(_ arg: SomeEnum1?, arg2: Int16) {} func testSugarType(_ arg: Optional<EnumAlias>, arg2: Int32) {} func testSugarType(_ arg: EnumAlias?, arg2: Int64) {} func testSugarType(_ arg: SomeEnum1, arg2: Int) {} func testSugarType(_ arg: EnumAlias, arg2: String) {} testSugarType(.#^SUGAR_TYPE^# // Ensure results aren't duplicated. // SUGAR_TYPE: Begin completions, 9 items // SUGAR_TYPE-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: South[#SomeEnum1#]; // SUGAR_TYPE-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: North[#SomeEnum1#]; // SUGAR_TYPE-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: hash({#(self): SomeEnum1#})[#(into: inout Hasher) -> Void#]; // SUGAR_TYPE-DAG: Keyword[nil]/None/Erase[1]/TypeRelation[Identical]: nil[#SomeEnum1?#]; // SUGAR_TYPE-DAG: Decl[EnumElement]/CurrNominal/IsSystem/TypeRelation[Identical]: none[#Optional<SomeEnum1>#]; // SUGAR_TYPE-DAG: Decl[EnumElement]/CurrNominal/IsSystem/TypeRelation[Identical]: some({#SomeEnum1#})[#Optional<SomeEnum1>#]; // SUGAR_TYPE-DAG: Decl[InstanceMethod]/CurrNominal/IsSystem: map({#(self): Optional<SomeEnum1>#})[#((SomeEnum1) throws -> U) -> U?#]; // SUGAR_TYPE-DAG: Decl[InstanceMethod]/CurrNominal/IsSystem: flatMap({#(self): Optional<SomeEnum1>#})[#((SomeEnum1) throws -> U?) -> U?#]; // SUGAR_TYPE-DAG: Decl[InstanceMethod]/CurrNominal/IsSystem/TypeRelation[Invalid]: hash({#(self): Optional<SomeEnum1>#})[#(into: inout Hasher) -> Void#]; // SUGAR_TYPE: End completions }
apache-2.0
alfiehanssen/VideoCamera
VideoCamera/Extensions/AVCaptureDevice+Extensions.swift
1
1674
// // AVCaptureDevice+Extensions.swift // VideoCamera // // Created by Alfred Hanssen on 2/25/17. // Copyright © 2017 Alfie Hanssen. All rights reserved. // import Foundation import AVFoundation extension AVCaptureDevice { private static let AudioDeviceTypes: [AVCaptureDeviceType] = [.builtInMicrophone] private static let VideoDeviceTypes: [AVCaptureDeviceType] = [.builtInDuoCamera, .builtInTelephotoCamera, .builtInWideAngleCamera] // TODO: Will more than one device ever be returned if we always specify a camera position? e.g. front / back. static func microphone() throws -> AVCaptureDevice { return try AVCaptureDevice.device(deviceTypes: AVCaptureDevice.AudioDeviceTypes, mediaType: AVMediaTypeAudio, position: .unspecified) } static func frontCamera() throws -> AVCaptureDevice { return try AVCaptureDevice.device(deviceTypes: AVCaptureDevice.VideoDeviceTypes, mediaType: AVMediaTypeVideo, position: .front) } static func backCamera() throws -> AVCaptureDevice { return try AVCaptureDevice.device(deviceTypes: AVCaptureDevice.VideoDeviceTypes, mediaType: AVMediaTypeVideo, position: .back) } private static func device(deviceTypes: [AVCaptureDeviceType], mediaType: String, position: AVCaptureDevicePosition) throws -> AVCaptureDevice { let discoverySession = AVCaptureDeviceDiscoverySession(deviceTypes: deviceTypes, mediaType: mediaType, position: position) guard let device = discoverySession?.devices.first else { throw CameraError.discoverySessionFoundNoEligibleDevices } return device } }
mit
lmkerr/Swiftris
SwiftrisTests/SwiftrisTests.swift
1
911
// // SwiftrisTests.swift // SwiftrisTests // // Created by Loren M. Kerr on 8/6/15. // Copyright (c) 2015 Apportunities, LLC. All rights reserved. // import UIKit import XCTest class SwiftrisTests: 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. } } }
unlicense
ahoppen/swift
test/Index/Store/unit-one-sourcefile-remapped.swift
1
1240
// RUN: rm -rf %t // RUN: mkdir -p %t/BuildRoot && cd %t/BuildRoot // RUN: %target-swift-frontend -index-store-path %t/idx -file-prefix-map %S=REMAPPED_SRC_ROOT -file-prefix-map %t=REMAPPED_OUT_DIR %s -o %t/file1.o -typecheck // RUN: c-index-test core -print-unit %t/idx | %FileCheck %s --dump-input-filter all // CHECK: file1.o-1AYKXZF3HH50A // CHECK: -------- // CHECK: main-path: REMAPPED_SRC_ROOT{{/|\\}}unit-one-sourcefile-remapped.swift // CHECK: work-dir: REMAPPED_OUT_DIR{{/|\\}}BuildRoot // CHECK: out-file: REMAPPED_OUT_DIR{{/|\\}}file1.o // CHECK: DEPEND START // CHECK: Unit | system | Swift | {{BUILD_DIR|.*lib\\swift\\windows}}{{.*}}Swift.swiftmodule // CHECK: DEPEND END // Check round-trip remapping to make sure they're converted back to the local paths. // RUN: c-index-test core -print-unit %t/idx -index-store-prefix-map REMAPPED_SRC_ROOT=%S -index-store-prefix-map REMAPPED_OUT_DIR=%t | %FileCheck %s -check-prefix=ROUNDTRIP --dump-input-filter all // ROUNDTRIP: file1.o-1AYKXZF3HH50A // ROUNDTRIP: -------- // ROUNDTRIP: main-path: SOURCE_DIR{{/|\\}}test{{/|\\}}Index{{/|\\}}Store{{/|\\}}unit-one-sourcefile-remapped.swift // ROUNDTRIP-NOT: work-dir: REMAPPED_OUT_DIR // ROUNDTRIP-NOT: out-file: REMAPPED_OUT_DIR
apache-2.0
swifteroid/reactiveoauth
source/ReactiveOAuth/Detalisator/Detalisator.Imgur.swift
1
773
import Alamofire import ReactiveSwift import SwiftyJSON open class ImgurDetalisator<Detail>: JsonDetalisator<Detail> { open override func detail(credential: Credential) { let headers: HTTPHeaders = ["Authorization": "Bearer \(credential.accessToken)"] // Todo: check for json errors… AF.request(Imgur.url.detail, method: HTTPMethod.get, headers: headers).reactive.responded .attemptMap({ try JSON(data: $0) }) .observe({ [weak self] in if case .value(let value) = $0 { self?.detail(json: value) } else if case .failed(let error) = $0 { self?.fail(Error.unknown(description: error.localizedDescription)) } }) } }
mit
ahoppen/swift
test/incrParse/inserted_text_starts_identifier.swift
32
204
// RUN: %empty-directory(%t) // RUN: %validate-incrparse %s --test-case STRING // SR-8995 rdar://problem/45259469 self = <<STRING<|||_ _>>>foo(1)[object1, object2] + o bar(1)
apache-2.0
haskellswift/swift-package-manager
Tests/GetTests/VersionGraphTests.swift
2
14841
/* This source file is part of the Swift.org open source project Copyright 2015 - 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import Utility @testable import Get class VersionGraphTests: XCTestCase { func testNoGraph() { class MockFetcher: _MockFetcher { override func fetch(url: String) throws -> Fetchable { switch MockProject(rawValue: url)! { case .A: return MockCheckout(.A, [v1]) default: fatalError() } } } let rv: [MockCheckout] = try! MockFetcher().recursivelyFetch([(MockProject.A.url, v1..<v1.successor())]) XCTAssertEqual(rv, [ MockCheckout(.A, v1) ]) } func testOneDependency() { class MockFetcher: _MockFetcher { override func fetch(url: String) throws -> Fetchable { switch MockProject(rawValue: url)! { case .A: return MockCheckout(.A, [v1], (MockProject.B.url, v1..<v1.successor())) case .B: return MockCheckout(.B, [v1]) default: fatalError() } } } let rv: [MockCheckout] = try! MockFetcher().recursivelyFetch([(MockProject.A.url, v1..<v1.successor())]) XCTAssertEqual(rv, [ MockCheckout(.B, v1), MockCheckout(.A, v1), ]) } func testOneDepenencyWithMultipleAvailableVersions() { class MockFetcher: _MockFetcher { override func fetch(url: String) throws -> Fetchable { switch MockProject(rawValue: url)! { case .A: return MockCheckout(.A, [v1], (MockProject.B.url, v1..<v2)) case .B: return MockCheckout(.B, [v1, v199, v2, "3.0.0"]) default: fatalError() } } } let rv: [MockCheckout] = try! MockFetcher().recursivelyFetch([(MockProject.A.url, v1..<v1.successor())]) XCTAssertEqual(rv, [ MockCheckout(.B, v199), MockCheckout(.A, v1), ]) } func testTwoDependencies() { class MockFetcher: _MockFetcher { override func fetch(url: String) throws -> Fetchable { switch MockProject(rawValue: url)! { case .A: return MockCheckout(.A, [v1], (MockProject.B.url, v1..<v1.successor())) case .B: return MockCheckout(.B, [v1], (MockProject.C.url, v1..<v1.successor())) case .C: return MockCheckout(.C, [v1]) default: fatalError() } } } let rv: [MockCheckout] = try! MockFetcher().recursivelyFetch([(MockProject.A.url, v1..<v1.successor())]) XCTAssertEqual(rv, [ MockCheckout(.C, v1), MockCheckout(.B, v1), MockCheckout(.A, v1) ]) } func testTwoDirectDependencies() { class MockFetcher: _MockFetcher { override func fetch(url: String) throws -> Fetchable { switch MockProject(rawValue: url)! { case .A: return MockCheckout(.A, [v1], (MockProject.B.url, v1..<v1.successor()), (MockProject.C.url, v1..<v1.successor())) case .B: return MockCheckout(.B, [v1]) case .C: return MockCheckout(.C, [v1]) default: fatalError() } } } let rv: [MockCheckout] = try! MockFetcher().recursivelyFetch([(MockProject.A.url, v1..<v1.successor())]) XCTAssertEqual(rv, [ MockCheckout(.B, v1), MockCheckout(.C, v1), MockCheckout(.A, v1) ]) } func testTwoDirectDependenciesWhereOneAlsoDependsOnTheOther() { class MockFetcher: _MockFetcher { override func fetch(url: String) throws -> Fetchable { switch MockProject(rawValue: url)! { case .A: return MockCheckout(.A, [v1], (MockProject.B.url, v1..<v1.successor()), (MockProject.C.url, v1..<v1.successor())) case .B: return MockCheckout(.B, [v1], (MockProject.C.url, v1..<v1.successor())) case .C: return MockCheckout(.C, [v1]) default: fatalError() } } } let rv: [MockCheckout] = try! MockFetcher().recursivelyFetch([(MockProject.A.url, v1..<v1.successor())]) XCTAssertEqual(rv, [ MockCheckout(.C, v1), MockCheckout(.B, v1), MockCheckout(.A, v1) ]) } func testSimpleVersionRestrictedGraph() { class MockFetcher: _MockFetcher { override func fetch(url: String) throws -> Fetchable { switch MockProject(rawValue: url)! { case .A: return MockCheckout(.A, [v1], (MockProject.C.url, v123..<v2)) case .B: return MockCheckout(.B, [v2], (MockProject.C.url, v123..<v126.successor())) case .C: return MockCheckout(.C, [v126]) default: fatalError() } } } let rv: [MockCheckout] = try! MockFetcher().recursivelyFetch([ (MockProject.A.url, v1..<v1.successor()), (MockProject.B.url, v2..<v2.successor()) ]) XCTAssertEqual(rv, [ MockCheckout(.C, v126), MockCheckout(.A, v1), MockCheckout(.B, v2) ]) } func testComplexVersionRestrictedGraph() { class MyMockFetcher: _MockFetcher { override func fetch(url: String) throws -> Fetchable { switch MockProject(rawValue: url)! { case .A: return MockCheckout(.A, [v1], (MockProject.C.url, Version(1,2,3)..<v2), (MockProject.D.url, v126..<v2.successor()), (MockProject.B.url, v1..<v2.successor())) case .B: return MockCheckout(.B, [v2], (MockProject.C.url, Version(1,2,3)..<v126.successor()), (MockProject.E.url, v2..<v2.successor())) case .C: return MockCheckout(.C, [v126], (MockProject.D.url, v2..<v2.successor()), (MockProject.E.url, v1..<Version(2,1,0))) case .D: return MockCheckout(.D, [v2], (MockProject.F.url, v1..<v2)) case .E: return MockCheckout(.E, [v2], (MockProject.F.url, v1..<v1.successor())) case .F: return MockCheckout(.F, [v1]) } } } let rv: [MockCheckout] = try! MyMockFetcher().recursivelyFetch([ (MockProject.A.url, v1..<v1.successor()), ]) XCTAssertEqual(rv, [ MockCheckout(.F, v1), MockCheckout(.D, v2), MockCheckout(.E, v2), MockCheckout(.C, v126), MockCheckout(.B, v2), MockCheckout(.A, v1) ]) } func testVersionConstrain() { let r1 = Version(1,2,3)..<Version(1,2,5).successor() let r2 = Version(1,2,6)..<Version(1,2,6).successor() let r3 = Version(1,2,4)..<Version(1,2,4).successor() XCTAssertNil(r1.constrain(to: r2)) XCTAssertNotNil(r1.constrain(to: r3)) let r4 = Version(2,0,0)..<Version(2,0,0).successor() let r5 = Version(1,2,6)..<Version(2,0,0).successor() XCTAssertNotNil(r4.constrain(to: r5)) let r6 = Version(1,2,3)..<Version(1,2,3).successor() XCTAssertEqual(r6.constrain(to: r6), r6) } func testTwoDependenciesRequireMutuallyExclusiveVersionsOfTheSameDependency_Simple() { class MyMockFetcher: _MockFetcher { override func fetch(url: String) throws -> Fetchable { switch MockProject(rawValue: url)! { case .A: return MockCheckout(.A, [v1], (MockProject.C.url, Version(1,2,3)..<v2)) case .B: return MockCheckout(.B, [v1], (MockProject.C.url, v2..<v2.successor())) // this is outside the above bounds case .C: return MockCheckout(.C, ["1.2.3", "1.9.9", "2.0.1"]) default: fatalError() } } } var invalidGraph = false do { _ = try MyMockFetcher().recursivelyFetch([ (MockProject.A.url, Version.maxRange), (MockProject.B.url, Version.maxRange) ]) } catch Get.Error.invalidDependencyGraph(let url) { invalidGraph = true XCTAssertEqual(url, MockProject.C.url) } catch { XCTFail() } XCTAssertTrue(invalidGraph) } func testTwoDependenciesRequireMutuallyExclusiveVersionsOfTheSameDependency_Complex() { class MyMockFetcher: _MockFetcher { override func fetch(url: String) throws -> Fetchable { switch MockProject(rawValue: url)! { case .A: return MockCheckout(.A, [v1], (MockProject.C.url, Version(1,2,3)..<v2), (MockProject.D.url, v126..<v2.successor()), (MockProject.B.url, v1..<v2.successor())) case .B: return MockCheckout(.B, [v2], (MockProject.C.url, Version(1,2,3)..<v126.successor()), (MockProject.E.url, v2..<v2.successor())) case .C: return MockCheckout(.C, ["1.2.4"], (MockProject.D.url, v2..<v2.successor()), (MockProject.E.url, v1..<Version(2,1,0))) case .D: return MockCheckout(.D, [v2], (MockProject.F.url, v1..<v2)) case .E: return MockCheckout(.E, ["2.0.1"], (MockProject.F.url, v2..<v2.successor())) case .F: return MockCheckout(.F, [v2]) } } } var invalidGraph = false do { _ = try MyMockFetcher().recursivelyFetch([ (MockProject.A.url, v1..<v1.successor()), ]) } catch Get.Error.invalidDependencyGraphMissingTag(let url, _, _) { XCTAssertEqual(url, MockProject.F.url) invalidGraph = true } catch { XCTFail() } XCTAssertTrue(invalidGraph) } func testVersionUnavailable() { class MyMockFetcher: _MockFetcher { override func fetch(url: String) throws -> Fetchable { return MockCheckout(.A, [v2]) } } var success = false do { _ = try MyMockFetcher().recursivelyFetch([(MockProject.A.url, v1..<v2)]) } catch Get.Error.invalidDependencyGraphMissingTag { success = true } catch { XCTFail() } XCTAssertTrue(success) } // // func testGetRequiresUpdateToAlreadyInstalledPackage() { // class MyMockFetcher: MockFetcher { // override func specsForCheckout(_ checkout: MockCheckout) -> [(String, Range<Version>)] { // switch checkout.project { // case .A: return [(MockProject.C.url, Version(1,2,3)..<v2), (MockProject.D.url, v126..<v2.successor()), (MockProject.B.url, v1..<v2.successor())] // case .B: return [(MockProject.C.url, Version(1,2,3)..<v126.successor()), (MockProject.E.url, v2..<v2.successor())] // case .C: return [(MockProject.D.url, v2..<v2.successor()), (MockProject.E.url, v1..<Version(2,1,0))] // case .D: return [(MockProject.F.url, v1..<v2)] // case .E: return [(MockProject.F.url, v2..<v2.successor())] // case .F: return [] // } // } // } // // } static var allTests = [ ("testNoGraph", testNoGraph), ("testOneDependency", testOneDependency), ("testOneDepenencyWithMultipleAvailableVersions", testOneDepenencyWithMultipleAvailableVersions), ("testTwoDependencies", testTwoDependencies), ("testTwoDirectDependencies", testTwoDirectDependencies), ("testTwoDirectDependenciesWhereOneAlsoDependsOnTheOther", testTwoDirectDependenciesWhereOneAlsoDependsOnTheOther), ("testSimpleVersionRestrictedGraph", testSimpleVersionRestrictedGraph), ("testComplexVersionRestrictedGraph", testComplexVersionRestrictedGraph), ("testVersionConstrain", testVersionConstrain), ("testTwoDependenciesRequireMutuallyExclusiveVersionsOfTheSameDependency_Simple", testTwoDependenciesRequireMutuallyExclusiveVersionsOfTheSameDependency_Simple), ("testTwoDependenciesRequireMutuallyExclusiveVersionsOfTheSameDependency_Complex", testTwoDependenciesRequireMutuallyExclusiveVersionsOfTheSameDependency_Complex), ("testVersionUnavailable", testVersionUnavailable) ] } ///////////////////////////////////////////////////////////////// private private let v1 = Version(1,0,0) private let v2 = Version(2,0,0) private let v123 = Version(1,2,3) private let v126 = Version(1,2,6) private let v199 = Version(1,9,9) private enum MockProject: String { case A case B case C case D case E case F var url: String { return rawValue } } private class MockCheckout: Equatable, CustomStringConvertible, Fetchable { let project: MockProject let children: [(String, Range<Version>)] var availableVersions: [Version] var _version: Version? init(_ project: MockProject, _ availableVersions: [Version], _ dependencies: (String, Range<Version>)...) { self.availableVersions = availableVersions self.project = project self.children = dependencies } init(_ project: MockProject, _ version: Version) { self._version = version self.project = project self.children = [] self.availableVersions = [] } var description: String { return "\(project)\(currentVersion)" } func constrain(to versionRange: Range<Version>) -> Version? { return availableVersions.filter{ versionRange ~= $0 }.last } var currentVersion: Version { return _version! } func setCurrentVersion(_ newValue: Version) throws { _version = newValue } } private func ==(lhs: MockCheckout, rhs: MockCheckout) -> Bool { return lhs.project == rhs.project && lhs.currentVersion == rhs.currentVersion } private class _MockFetcher: Fetcher { typealias T = MockCheckout func find(url: String) throws -> Fetchable? { return nil } func finalize(_ fetchable: Fetchable) throws -> MockCheckout { return fetchable as! T } func fetch(url: String) throws -> Fetchable { fatalError("This must be implemented in each test") } }
apache-2.0
GalinaCode/Nutriction-Cal
NutritionCal/Nutrition Cal/HealthStore.swift
1
9976
// // HealthStore.swift // Nutrition Cal // // Created by Galina Petrova on 03/25/16. // Copyright © 2015 Galina Petrova. All rights reserved. // import Foundation import HealthKit class HealthStore { class func sharedInstance() -> HealthStore { struct Singleton { static let instance = HealthStore() } return Singleton.instance } let healthStore: HKHealthStore? = HKHealthStore() func addNDBItemToHealthStore(item: NDBItem,selectedMeasure: NDBMeasure , qty: Int, completionHandler: (success: Bool, errorString: String?) -> Void) { let timeFoodWasEntered = NSDate() let foodMetaData = [ HKMetadataKeyFoodType : item.name, "Group": item.group!, "USDA id": item.ndbNo, "Quantity": "\(qty) \(selectedMeasure.label!)", ] func getCalcium() -> HKQuantitySample? { // check if calcium nutrient available if let calcium = item.nutrients?.find({$0.id == 301}) { // check if selected measure available if let measure = calcium.measures?.find({$0.label == selectedMeasure.label}) { let value: Double = Double(qty) * (measure.value as! Double) let unit = HKQuantity(unit: HKUnit.gramUnitWithMetricPrefix(HKMetricPrefix.Milli), doubleValue: value) let calciumSample = HKQuantitySample(type: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCalcium)!, quantity: unit, startDate: timeFoodWasEntered, endDate: timeFoodWasEntered, metadata: foodMetaData) return calciumSample } return nil } return nil } func getCarbohydrate() -> HKQuantitySample? { // check if carbohydrate nutrient available if let carbohydrate = item.nutrients?.find({$0.id == 205}) { // check if selected measure available if let measure = carbohydrate.measures?.find({$0.label == selectedMeasure.label}) { let value: Double = Double(qty) * (measure.value as! Double) let unit = HKQuantity(unit: HKUnit.gramUnit(), doubleValue: value) let carbohydrateSample = HKQuantitySample(type: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCarbohydrates)!, quantity: unit, startDate: timeFoodWasEntered, endDate: timeFoodWasEntered, metadata: foodMetaData) return carbohydrateSample } return nil } return nil } func getCholesterol() -> HKQuantitySample? { // check if cholesterol nutrient available if let cholesterol = item.nutrients?.find({$0.id == 601}) { // check if selected measure available if let measure = cholesterol.measures?.find({$0.label == selectedMeasure.label}) { let value: Double = Double(qty) * (measure.value as! Double) let unit = HKQuantity(unit: HKUnit.gramUnitWithMetricPrefix(HKMetricPrefix.Milli), doubleValue: value) let cholesterolSample = HKQuantitySample(type: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCholesterol)!, quantity: unit, startDate: timeFoodWasEntered, endDate: timeFoodWasEntered, metadata: foodMetaData) return cholesterolSample } return nil } return nil } func getEnergy() -> HKQuantitySample? { // check if energy nutrient available if let energy = item.nutrients?.find({$0.id == 208}) { // check if selected measure available if let measure = energy.measures?.find({$0.label == selectedMeasure.label}) { let value: Double = Double(qty) * (measure.value as! Double) let unit = HKQuantity(unit: HKUnit.kilocalorieUnit(), doubleValue: value) let energySample = HKQuantitySample(type: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryEnergyConsumed)!, quantity: unit, startDate: timeFoodWasEntered, endDate: timeFoodWasEntered, metadata: foodMetaData) return energySample } return nil } return nil } func getFatTotal() -> HKQuantitySample? { // check if fatTotal nutrient available if let fatTotal = item.nutrients?.find({$0.id == 204}) { // check if selected measure available if let measure = fatTotal.measures?.find({$0.label == selectedMeasure.label}) { let value: Double = Double(qty) * (measure.value as! Double) let unit = HKQuantity(unit: HKUnit.gramUnit(), doubleValue: value) let fatTotalSample = HKQuantitySample(type: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatTotal)!, quantity: unit, startDate: timeFoodWasEntered, endDate: timeFoodWasEntered, metadata: foodMetaData) return fatTotalSample } return nil } return nil } func getProtein() -> HKQuantitySample? { // check if protein nutrient available if let protein = item.nutrients?.find({$0.id == 203}) { // check if selected measure available if let measure = protein.measures?.find({$0.label == selectedMeasure.label}) { let value: Double = Double(qty) * (measure.value as! Double) let unit = HKQuantity(unit: HKUnit.gramUnit(), doubleValue: value) let proteinSample = HKQuantitySample(type: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryProtein)!, quantity: unit, startDate: timeFoodWasEntered, endDate: timeFoodWasEntered, metadata: foodMetaData) return proteinSample } return nil } return nil } func getSugar() -> HKQuantitySample? { // check if sugar nutrient available if let sugar = item.nutrients?.find({$0.id == 269}) { // check if selected measure available if let measure = sugar.measures?.find({$0.label == selectedMeasure.label}) { let value: Double = Double(qty) * (measure.value as! Double) let unit = HKQuantity(unit: HKUnit.gramUnit(), doubleValue: value) let sugarSample = HKQuantitySample(type: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietarySugar)!, quantity: unit, startDate: timeFoodWasEntered, endDate: timeFoodWasEntered, metadata: foodMetaData) return sugarSample } return nil } return nil } func getVitaminC() -> HKQuantitySample? { // check if vitamin C nutrient available if let vitaminC = item.nutrients?.find({$0.id == 401}) { // check if selected measure available if let measure = vitaminC.measures?.find({$0.label == selectedMeasure.label}) { let value: Double = Double(qty) * (measure.value as! Double) let unit = HKQuantity(unit: HKUnit.gramUnitWithMetricPrefix(HKMetricPrefix.Milli), doubleValue: value) let vitaminCSample = HKQuantitySample(type: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryVitaminC)!, quantity: unit, startDate: timeFoodWasEntered, endDate: timeFoodWasEntered, metadata: foodMetaData) return vitaminCSample } return nil } return nil } if HKHealthStore.isHealthDataAvailable() { var nutrientsArray: [HKQuantitySample] = [] if let calcium = getCalcium() { nutrientsArray.append(calcium) } if let carbohydrates = getCarbohydrate() { nutrientsArray.append(carbohydrates) } if let cholesterol = getCholesterol() { nutrientsArray.append(cholesterol) } if let energy = getEnergy() { nutrientsArray.append(energy) } if let fatTotal = getFatTotal() { nutrientsArray.append(fatTotal) } if let protein = getProtein() { nutrientsArray.append(protein) } if let sugar = getSugar() { nutrientsArray.append(sugar) } if let vitaminC = getVitaminC() { nutrientsArray.append(vitaminC) } let foodDataSet = NSSet(array: nutrientsArray) let foodCoorelation = HKCorrelation(type: HKCorrelationType.correlationTypeForIdentifier(HKCorrelationTypeIdentifierFood)!, startDate: timeFoodWasEntered, endDate: timeFoodWasEntered, objects: foodDataSet as! Set<HKSample>, metadata : foodMetaData) healthStore?.saveObject(foodCoorelation, withCompletion: { (success, error) -> Void in if success { print("Item saved to Heath App successfully") completionHandler(success: true, errorString: nil) } else { print(error?.localizedDescription) if error!.code == 4 { completionHandler(success: false, errorString: "Access to Health App denied, You can allow access from Health App -> Sources -> NutritionDiary. or disable sync with Health App in settings tab.") } else { completionHandler(success: false, errorString: "\(error!.code)") } } }) } else { completionHandler(success: false, errorString: "Health App is not available, Device is not compatible.") } } func requestAuthorizationForHealthStore() { let dataTypesToWrite: [AnyObject] = [ HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCalcium)!, HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCarbohydrates)!, HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCholesterol)!, HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryEnergyConsumed)!, HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatTotal)!, HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryProtein)!, HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietarySugar)!, HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryVitaminC)! ] healthStore?.requestAuthorizationToShareTypes(NSSet(array: dataTypesToWrite) as? Set<HKSampleType>, readTypes: nil, completion: { (success, error) -> Void in if success { print("User completed authorization request.") } else { print("User canceled the request \(error!.localizedDescription)") } }) } }
apache-2.0
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Models/Mapping/LoginServiceModelMapping.swift
1
4718
// // LoginServiceModelMapping.swift // Rocket.Chat // // Created by Matheus Cardoso on 10/17/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import Foundation import SwiftyJSON import RealmSwift extension LoginService: ModelMappeable { // swiftlint:disable cyclomatic_complexity func map(_ values: JSON, realm: Realm?) { if identifier == nil { identifier = values["_id"].string ?? values["id"].string } service = values["name"].string ?? values["service"].string clientId = values["appId"].string ?? values["clientId"].string custom = values["custom"].boolValue serverUrl = values["serverURL"].string tokenPath = values["tokenPath"].string authorizePath = values["authorizePath"].string scope = values["scope"].string buttonLabelText = values["buttonLabelText"].stringValue buttonLabelColor = values["buttonLabelColor"].stringValue tokenSentVia = values["tokenSentVia"].stringValue usernameField = values["usernameField"].stringValue mergeUsers = values["mergeUsers"].boolValue loginStyle = values["loginStyle"].string buttonColor = values["buttonColor"].string // CAS loginUrl = values["login_url"].string // SAML entryPoint = values["entryPoint"].string issuer = values["issuer"].string provider = values["clientConfig"]["provider"].string switch type { case .google: mapGoogle() case .facebook: mapFacebook() case .gitlab: mapGitLab() case .github: mapGitHub() case .linkedin: mapLinkedIn() case .wordpress: break // not mapped here since it needs a public setting for type case .saml: break case .cas: break case .custom: break case .invalid: break } } // swiftlint:enable cyclomatic_complexity func mapGoogle() { service = "google" scope = "email profile" serverUrl = "https://accounts.google.com" tokenPath = "/login/oauth/access_token" authorizePath = "/o/oauth2/v2/auth" buttonLabelText = "google" buttonLabelColor = "#ffffff" buttonColor = "#dd4b39" callbackPath = "google?close" } func mapGitHub() { service = "github" scope = "" serverUrl = "https://github.com" tokenPath = "/login/oauth/access_token" authorizePath = "/login/oauth/authorize" buttonLabelText = "github" buttonLabelColor = "#ffffff" buttonColor = "#4c4c4c" } func mapGitLab() { service = "gitlab" scope = "read_user" serverUrl = "https://gitlab.com" tokenPath = "/oauth/token" authorizePath = "/oauth/authorize" buttonLabelText = "gitlab" buttonLabelColor = "#ffffff" buttonColor = "#373d47" callbackPath = "gitlab?close" } func mapFacebook() { service = "facebook" scope = "" serverUrl = "https://facebook.com" scope = "email" tokenPath = "https://graph.facebook.com/oauth/v2/accessToken" authorizePath = "/v2.9/dialog/oauth" buttonLabelText = "facebook" buttonLabelColor = "#ffffff" buttonColor = "#325c99" callbackPath = "facebook?close" } func mapLinkedIn() { service = "linkedin" scope = "" serverUrl = "https://linkedin.com" tokenPath = "/oauth/v2/accessToken" authorizePath = "/oauth/v2/authorization" buttonLabelText = "linkedin" buttonLabelColor = "#ffffff" buttonColor = "#1b86bc" callbackPath = "linkedin?close" } func mapWordPress() { service = "wordpress" scope = scope ?? "auth" serverUrl = "https://public-api.wordpress.com" tokenPath = "/oauth2/token" authorizePath = "/oauth2/authorize" buttonLabelText = "wordpress" buttonLabelColor = "#ffffff" buttonColor = "#1e8cbe" callbackPath = "wordpress?close" } func mapWordPressCustom() { service = "wordpress" scope = scope ?? "openid" serverUrl = serverUrl ?? "https://public-api.wordpress.com" tokenPath = tokenPath ?? "/oauth/token" authorizePath = authorizePath ?? "/oauth/authorize" buttonLabelText = "wordpress" buttonLabelColor = "#ffffff" buttonColor = "#1e8cbe" callbackPath = "wordpress?close" } func mapCAS() { service = "cas" buttonLabelText = "CAS" buttonLabelColor = "#ffffff" buttonColor = "#13679a" } }
mit
betacamp/HiliteUI
HiliteUI/Classes/Alert.swift
1
1249
import Foundation import UIKit open class Alert { open class func error(_ title: String!, message: String!) -> UIAlertController { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) return alert } open class func info(_ title: String!, message: String!) -> UIAlertController { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) return alert } open class func confirm(_ title: String!, message: String!, onConfirm: @escaping ()->()) -> UIAlertController { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.destructive, handler: { (alertAction) -> Void in onConfirm() })) return alert } }
mit
0x7fffffff/Stone
Carthage/Checkouts/unbox/Package.swift
3
94
import PackageDescription let package = Package( name: "Unbox", exclude: ["Tests"] )
mit
macemmi/HBCI4Swift
HBCI4Swift/HBCI4Swift/Source/Syntax/HBCISyntax.swift
1
9803
// // HBCISyntax.swift // HBCIBackend // // Created by Frank Emminghaus on 18.12.14. // Copyright (c) 2014 Frank Emminghaus. All rights reserved. // import Foundation enum HBCIChar: CChar { case plus = 0x2B case dpoint = 0x3A case qmark = 0x3F case quote = 0x27 case amper = 0x40 } let HBCIChar_plus:CChar = 0x2B let HBCIChar_dpoint:CChar = 0x3A let HBCIChar_qmark:CChar = 0x3F let HBCIChar_quote:CChar = 0x27 let HBCIChar_amper:CChar = 0x40 var syntaxVersions = Dictionary<String,HBCISyntax>(); extension XMLElement { func valueForAttribute(_ name: String)->String? { let attrNode = self.attribute(forName: name) if attrNode != nil { return attrNode!.stringValue } return nil } } class HBCISyntax { var document: XMLDocument! // todo: change to let once Xcode bug is fixed var degs: Dictionary<String, HBCIDataElementGroupDescription> = [:] var segs: Dictionary<String, HBCISegmentVersions> = [:] var codes: Dictionary<String, HBCISegmentVersions> = [:] var msgs: Dictionary<String, HBCISyntaxElementDescription> = [:] init(path: String) throws { var xmlDoc: XMLDocument? let furl = URL(fileURLWithPath: path); do { xmlDoc = try XMLDocument(contentsOf: furl, options:XMLNode.Options(rawValue: XMLNode.Options.RawValue(Int(XMLNode.Options.nodePreserveWhitespace.rawValue|XMLNode.Options.nodePreserveCDATA.rawValue)))); if xmlDoc == nil { xmlDoc = try XMLDocument(contentsOf: furl, options: XMLNode.Options(rawValue: XMLNode.Options.RawValue(Int(XMLDocument.Options.documentTidyXML.rawValue)))); } } catch let err as NSError { logInfo("HBCI Syntax file error: \(err.localizedDescription)"); logInfo("HBCI syntax file issue at path \(path)"); throw HBCIError.syntaxFileError; } if xmlDoc == nil { logInfo("HBCI syntax file not found (xmlDoc=nil) at path \(path)"); throw HBCIError.syntaxFileError; } else { document = xmlDoc!; } try buildDegs(); try buildSegs(); try buildMsgs(); } func buildDegs() throws { if let root = document.rootElement() { if let degs = root.elements(forName: "DEGs").first { for deg in degs.elements(forName: "DEGdef") { if let identifier = deg.valueForAttribute("id") { let elem = try HBCIDataElementGroupDescription(syntax: self, element: deg); elem.syntaxElement = deg; self.degs[identifier] = elem; } else { // syntax error logInfo("Syntax file error: invalid DEGdef element found"); throw HBCIError.syntaxFileError; } } return; } else { // error logInfo("Syntax file error: DEGs element not found"); throw HBCIError.syntaxFileError; } } else { // error logInfo("Synax file error: root element not found"); throw HBCIError.syntaxFileError; } } func buildSegs() throws { if let root = document.rootElement() { if let segs = root.elements(forName: "SEGs").first { for seg in segs.elements(forName: "SEGdef") { let segv = try HBCISegmentVersions(syntax: self, element: seg); self.segs[segv.identifier] = segv; self.codes[segv.code] = segv; } return; } else { // error logInfo("Syntax file error: SEGs element not found"); throw HBCIError.syntaxFileError; } } else { // error logInfo("Synax file error: root element not found"); throw HBCIError.syntaxFileError; } } func buildMsgs() throws { if let root = document.rootElement() { if let msgs = root.elements(forName: "MSGs").first { for msg in msgs.elements(forName: "MSGdef") { if let identifier = msg.valueForAttribute("id") { let elem = try HBCIMessageDescription(syntax: self, element: msg); elem.syntaxElement = msg; self.msgs[identifier] = elem; } } return; } else { // error logInfo("Syntax file error: MSGs element not found"); throw HBCIError.syntaxFileError; } } else { // error logInfo("Synax file error: root element not found"); throw HBCIError.syntaxFileError; } } func parseSegment(_ segData:Data, binaries:Array<Data>) throws ->HBCISegment? { if let headerDescr = self.degs["SegHead"] { if let headerData = headerDescr.parse((segData as NSData).bytes.bindMemory(to: CChar.self, capacity: segData.count), length: segData.count, binaries: binaries) { if let code = headerData.elementValueForPath("code") as? String { if let version = headerData.elementValueForPath("version") as? Int { if let segVersion = self.codes[code] { if let segDescr = segVersion.segmentWithVersion(version) { if let seg = segDescr.parse(segData, binaries: binaries) { return seg; } else { throw HBCIError.parseError; } } } //logDebug("Segment code \(code) with version \(version) is not supported"); return nil; // code and/or version are not supported, just continue } } } logInfo("Parse error: segment code or segment version could not be determined"); throw HBCIError.parseError; } else { logInfo("Syntax file error: segment SegHead is missing"); throw HBCIError.syntaxFileError; } } func customMessageForSegment(_ segName:String, user:HBCIUser) ->HBCIMessage? { if let md = self.msgs["CustomMsg"] { if let msg = md.compose() as? HBCIMessage { if let segVersions = self.segs[segName] { // now find the right segment version // check which segment versions are supported by the bank var supportedVersions = Array<Int>(); for seg in user.parameters.bpSegments { if seg.name == segName { // check if this version is also supported by us if segVersions.isVersionSupported(seg.version) { supportedVersions.append(seg.version); } } } if supportedVersions.count == 0 { // this process is not supported by the bank logInfo("Process \(segName) is not supported for custom message"); // In some cases the bank does not send any Parameter but the process is still supported // let's just try it out supportedVersions = segVersions.versionNumbers; } // now sort the versions - we take the latest supported version supportedVersions.sort(by: >); if let sd = segVersions.segmentWithVersion(supportedVersions.first!) { if let segment = sd.compose() { segment.name = segName; msg.children.insert(segment, at: 2); return msg; } } } else { logInfo("Segment \(segName) is not supported by HBCI4Swift"); } } } return nil; } func addExtension(_ extSyntax:HBCISyntax) { for key in extSyntax.degs.keys { if !degs.keys.contains(key) { degs[key] = extSyntax.degs[key]; } } for key in extSyntax.segs.keys { if !segs.keys.contains(key) { if let segv = extSyntax.segs[key] { segs[key] = segv; codes[segv.code] = segv; } } } } class func syntaxWithVersion(_ version:String) throws ->HBCISyntax { if !["220", "300"].contains(version) { throw HBCIError.invalidHBCIVersion(version); } if let syntax = syntaxVersions[version] { return syntax; } else { // load syntax var path = Bundle.main.bundlePath; path = path + "/Contents/Frameworks/HBCI4Swift.framework/Resources/hbci\(version).xml"; let syntax = try HBCISyntax(path: path); if let extSyntax = HBCISyntaxExtension.instance.extensions[version] { syntax.addExtension(extSyntax); } syntaxVersions[version] = syntax; return syntax; } } }
gpl-2.0
emilstahl/swift
validation-test/compiler_crashers_fixed/26081-std-function-func-swift-constraints-constraintsystem-simplifytype.swift
13
266
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing d< struct A{func f{{}func g{{ let a<{ { class case,
apache-2.0
DiegoSan1895/Smartisan-Notes
Smartisan-Notes/Constants.swift
1
2360
// // Configs.swift // Smartisan-Notes // // Created by DiegoSan on 3/4/16. // Copyright © 2016 DiegoSan. All rights reserved. // import UIKit let isNotFirstOpenSmartisanNotes = "isNotFirstOpenSmartisanNotes" let ueAgreeOrNot = "userAgreeToJoinUEPlan" let NSBundleURL = NSBundle.mainBundle().bundleURL struct AppID { static let notesID = 867934588 static let clockID = 828812911 static let syncID = 880078620 static let calenderID = 944154964 } struct AppURL { static let clockURL = NSURL(string: "smartisanclock://")! static let syncURL = NSURL(string: "smartisansync://")! static let calenderURL = NSURL(string: "smartisancalendar://")! static let smartisanWeb = NSURL(string: "https://store.smartisan.com")! } struct AppItunsURL { let baseURLString = "http://itunes.apple.com/us/app/id" static let calenderURL = NSURL(string: "http://itunes.apple.com/us/app/id\(AppID.calenderID)")! static let syncURL = NSURL(string: "http://itunes.apple.com/us/app/id\(AppID.syncID)")! static let clockURL = NSURL(string: "http://itunes.apple.com/us/app/id\(AppID.clockID)")! static let notesURL = NSURL(string: "http://itunes.apple.com/us/app/id\(AppID.notesID)")! } struct AppShareURL { static let notesURL = NSURL(string: "https://itunes.apple.com/us/app/smartisan-notes/id867934588?ls=1&mt=8")! } struct iPhoneInfo{ static let iOS_Version = UIDevice.currentDevice().systemVersion static let deviceName = NSString.deviceName() as String } struct AppInfo{ static let App_Version = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String } struct Configs { struct Weibo { static let appID = "1682079354" static let appKey = "94c42dacce2401ad73e5080ccd743052" static let redirectURL = "http://www.limon.top" } struct Wechat { static let appID = "wx4868b35061f87885" static let appKey = "64020361b8ec4c99936c0e3999a9f249" } struct QQ { static let appID = "1104881792" } struct Pocket { static let appID = "48363-344532f670a052acff492a25" static let redirectURL = "pocketapp48363:authorizationFinished" // pocketapp + $prefix + :authorizationFinished } struct Alipay { static let appID = "2016012101112529" } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/25899-swift-tupleexpr-tupleexpr.swift
1
472
// 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 import b class c{struct c var f:D struct c<T where f:a{ class d }struct D
apache-2.0
iOS-mamu/SS
P/Pods/PSOperations/PSOperations/OperationQueue.swift
1
5612
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file contains an NSOperationQueue subclass. */ import Foundation /** The delegate of an `OperationQueue` can respond to `Operation` lifecycle events by implementing these methods. In general, implementing `OperationQueueDelegate` is not necessary; you would want to use an `OperationObserver` instead. However, there are a couple of situations where using `OperationQueueDelegate` can lead to simpler code. For example, `GroupOperation` is the delegate of its own internal `OperationQueue` and uses it to manage dependencies. */ @objc public protocol OperationQueueDelegate: NSObjectProtocol { @objc optional func operationQueue(_ operationQueue: OperationQueue, willAddOperation operation: Foundation.Operation) @objc optional func operationQueue(_ operationQueue: OperationQueue, operationDidFinish operation: Foundation.Operation, withErrors errors: [NSError]) } /** `OperationQueue` is an `NSOperationQueue` subclass that implements a large number of "extra features" related to the `Operation` class: - Notifying a delegate of all operation completion - Extracting generated dependencies from operation conditions - Setting up dependencies to enforce mutual exclusivity */ open class OperationQueue: Foundation.OperationQueue { open weak var delegate: OperationQueueDelegate? override open func addOperation(_ operation: Foundation.Operation) { if let op = operation as? Operation { // Set up a `BlockObserver` to invoke the `OperationQueueDelegate` method. let delegate = BlockObserver( startHandler: nil, produceHandler: { [weak self] in self?.addOperation($1) }, finishHandler: { [weak self] finishedOperation, errors in if let q = self { q.delegate?.operationQueue?(q, operationDidFinish: finishedOperation, withErrors: errors) //Remove deps to avoid cascading deallocation error //http://stackoverflow.com/questions/19693079/nsoperationqueue-bug-with-dependencies finishedOperation.dependencies.forEach { finishedOperation.removeDependency($0) } } } ) op.addObserver(delegate) // Extract any dependencies needed by this operation. let dependencies = op.conditions.flatMap { $0.dependencyForOperation(op) } for dependency in dependencies { op.addDependency(dependency) self.addOperation(dependency) } /* With condition dependencies added, we can now see if this needs dependencies to enforce mutual exclusivity. */ let concurrencyCategories: [String] = op.conditions.flatMap { condition in if !type(of: condition).isMutuallyExclusive { return nil } return "\(type(of: condition))" } if !concurrencyCategories.isEmpty { // Set up the mutual exclusivity dependencies. let exclusivityController = ExclusivityController.sharedExclusivityController exclusivityController.addOperation(op, categories: concurrencyCategories) op.addObserver(BlockObserver { operation, _ in exclusivityController.removeOperation(operation, categories: concurrencyCategories) }) } } else { /* For regular `NSOperation`s, we'll manually call out to the queue's delegate we don't want to just capture "operation" because that would lead to the operation strongly referencing itself and that's the pure definition of a memory leak. */ operation.addCompletionBlock { [weak self, weak operation] in guard let queue = self, let operation = operation else { return } queue.delegate?.operationQueue?(queue, operationDidFinish: operation, withErrors: []) //Remove deps to avoid cascading deallocation error //http://stackoverflow.com/questions/19693079/nsoperationqueue-bug-with-dependencies operation.dependencies.forEach { operation.removeDependency($0) } } } delegate?.operationQueue?(self, willAddOperation: operation) super.addOperation(operation) /* Indicate to the operation that we've finished our extra work on it and it's now it a state where it can proceed with evaluating conditions, if appropriate. */ if let op = operation as? Operation { op.didEnqueue() } } override open func addOperations(_ ops: [Foundation.Operation], waitUntilFinished wait: Bool) { /* The base implementation of this method does not call `addOperation()`, so we'll call it ourselves. */ for operation in ops { addOperation(operation) } if wait { for operation in ops { operation.waitUntilFinished() } } } }
mit
adrfer/swift
test/ClangModules/simd_sans_simd.swift
24
469
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -verify %s import c_simd // Ensure that the SIMD types from the imported module get mapped into the // SIMD Swift module, even if we in the importing module don't import SIMD. takes_float4(makes_float4()) takes_int3(makes_int3()) takes_double2(makes_double2()) // FIXME: float4 should not have been transitively imported. let x: float4 = makes_float4() // fixme-error{{undeclared type 'float4'}}
apache-2.0
avito-tech/Paparazzo
Paparazzo/Core/VIPER/PhotoLibraryV2/Interactor/PhotoLibraryV2Interactor.swift
1
1260
import Foundation import ImageSource protocol PhotoLibraryV2Interactor: class { var mediaPickerData: MediaPickerData { get } var currentAlbum: PhotoLibraryAlbum? { get } var selectedItems: [MediaPickerItem] { get } var selectedPhotosStorage: SelectedImageStorage { get } func observeDeviceOrientation(handler: @escaping (DeviceOrientation) -> ()) func getOutputParameters(completion: @escaping (CameraOutputParameters?) -> ()) func observeAuthorizationStatus(handler: @escaping (_ accessGranted: Bool) -> ()) func observeAlbums(handler: @escaping ([PhotoLibraryAlbum]) -> ()) func observeCurrentAlbumEvents(handler: @escaping (PhotoLibraryAlbumEvent, PhotoLibraryItemSelectionState) -> ()) func isSelected(_: MediaPickerItem) -> Bool func selectItem(_: MediaPickerItem) -> PhotoLibraryItemSelectionState func replaceSelectedItem(at index: Int, with: MediaPickerItem) func deselectItem(_: MediaPickerItem) -> PhotoLibraryItemSelectionState func moveSelectedItem(at sourceIndex: Int, to destinationIndex: Int) func prepareSelection() -> PhotoLibraryItemSelectionState func setCurrentAlbum(_: PhotoLibraryAlbum) func observeSelectedItemsChange(_: @escaping () -> ()) }
mit
ipmobiletech/firefox-ios
UITests/ClearPrivateDataTests.swift
1
11507
/* 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 Shared import WebKit import UIKit // Needs to be in sync with Client Clearables. private enum Clearable: String { case History = "Browsing History" case Logins = "Saved Logins" case Cache = "Cache" case OfflineData = "Offline Website Data" case Cookies = "Cookies" } private let AllClearables = Set([Clearable.History, Clearable.Logins, Clearable.Cache, Clearable.OfflineData, Clearable.Cookies]) class ClearPrivateDataTests: KIFTestCase, UITextFieldDelegate { private var webRoot: String! override func setUp() { webRoot = SimplePageServer.start() } override func tearDown() { BrowserUtils.clearHistoryItems(tester()) } private func clearPrivateData(clearables: Set<Clearable>) { let webView = tester().waitForViewWithAccessibilityLabel("Web content") as! WKWebView let lastTabLabel = webView.title!.isEmpty ? "home" : webView.title! tester().tapViewWithAccessibilityLabel("Show Tabs") tester().tapViewWithAccessibilityLabel("Settings") tester().tapViewWithAccessibilityLabel("Clear Private Data") // Disable all items that we don't want to clear. for clearable in AllClearables.subtract(clearables) { // If we don't wait here, setOn:forSwitchWithAccessibilityLabel tries to use the UITableViewCell // instead of the UISwitch. KIF bug? tester().waitForViewWithAccessibilityLabel(clearable.rawValue) tester().setOn(false, forSwitchWithAccessibilityLabel: clearable.rawValue) } tester().tapViewWithAccessibilityLabel("Clear Private Data", traits: UIAccessibilityTraitButton) tester().tapViewWithAccessibilityLabel("Settings") tester().tapViewWithAccessibilityLabel("Done") tester().tapViewWithAccessibilityLabel(lastTabLabel) } func visitSites(noOfSites noOfSites: Int) -> [(title: String, domain: String, url: String)] { var urls: [(title: String, domain: String, url: String)] = [] for pageNo in 1...noOfSites { tester().tapViewWithAccessibilityIdentifier("url") let url = "\(webRoot)/numberedPage.html?page=\(pageNo)" tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n") tester().waitForWebViewElementWithAccessibilityLabel("Page \(pageNo)") let tuple: (title: String, domain: String, url: String) = ("Page \(pageNo)", NSURL(string: url)!.normalizedHost()!, url) urls.append(tuple) } BrowserUtils.resetToAboutHome(tester()) return urls } func anyDomainsExistOnTopSites(domains: Set<String>) { for domain in domains { if self.tester().viewExistsWithLabel(domain) { return } } XCTFail("Couldn't find any domains in top sites.") } func testClearsTopSitesPanel() { let urls = visitSites(noOfSites: 2) let domains = Set<String>(urls.map { $0.domain }) tester().tapViewWithAccessibilityLabel("Top sites") // Only one will be found -- we collapse by domain. anyDomainsExistOnTopSites(domains) clearPrivateData([Clearable.History]) XCTAssertFalse(tester().viewExistsWithLabel(urls[0].title), "Expected to have removed top site panel \(urls[0])") XCTAssertFalse(tester().viewExistsWithLabel(urls[1].title), "We shouldn't find the other URL, either.") } func testDisabledHistoryDoesNotClearTopSitesPanel() { let urls = visitSites(noOfSites: 2) let domains = Set<String>(urls.map { $0.domain }) anyDomainsExistOnTopSites(domains) clearPrivateData(AllClearables.subtract([Clearable.History])) anyDomainsExistOnTopSites(domains) } func testClearsHistoryPanel() { let urls = visitSites(noOfSites: 2) tester().tapViewWithAccessibilityLabel("History") let url1 = "\(urls[0].title), \(urls[0].url)" let url2 = "\(urls[1].title), \(urls[1].url)" XCTAssertTrue(tester().viewExistsWithLabel(url1), "Expected to have history row \(url1)") XCTAssertTrue(tester().viewExistsWithLabel(url2), "Expected to have history row \(url2)") clearPrivateData([Clearable.History]) tester().tapViewWithAccessibilityLabel("History") XCTAssertFalse(tester().viewExistsWithLabel(url1), "Expected to have removed history row \(url1)") XCTAssertFalse(tester().viewExistsWithLabel(url2), "Expected to have removed history row \(url2)") } func testDisabledHistoryDoesNotClearHistoryPanel() { let urls = visitSites(noOfSites: 2) tester().tapViewWithAccessibilityLabel("History") let url1 = "\(urls[0].title), \(urls[0].url)" let url2 = "\(urls[1].title), \(urls[1].url)" XCTAssertTrue(tester().viewExistsWithLabel(url1), "Expected to have history row \(url1)") XCTAssertTrue(tester().viewExistsWithLabel(url2), "Expected to have history row \(url2)") clearPrivateData(AllClearables.subtract([Clearable.History])) XCTAssertTrue(tester().viewExistsWithLabel(url1), "Expected to not have removed history row \(url1)") XCTAssertTrue(tester().viewExistsWithLabel(url2), "Expected to not have removed history row \(url2)") } func testClearsCookies() { tester().tapViewWithAccessibilityIdentifier("url") let url = "\(webRoot)/numberedPage.html?page=1" tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n") tester().waitForWebViewElementWithAccessibilityLabel("Page 1") let webView = tester().waitForViewWithAccessibilityLabel("Web content") as! WKWebView // Set and verify a dummy cookie value. setCookies(webView, cookie: "foo=bar") var cookies = getCookies(webView) XCTAssertEqual(cookies.cookie, "foo=bar") XCTAssertEqual(cookies.localStorage, "foo=bar") XCTAssertEqual(cookies.sessionStorage, "foo=bar") // Verify that cookies are not cleared when Cookies is deselected. clearPrivateData(AllClearables.subtract([Clearable.Cookies])) cookies = getCookies(webView) XCTAssertEqual(cookies.cookie, "foo=bar") XCTAssertEqual(cookies.localStorage, "foo=bar") XCTAssertEqual(cookies.sessionStorage, "foo=bar") // Verify that cookies are cleared when Cookies is selected. clearPrivateData([Clearable.Cookies]) cookies = getCookies(webView) XCTAssertEqual(cookies.cookie, "") XCTAssertNil(cookies.localStorage) XCTAssertNil(cookies.sessionStorage) } @available(iOS 9.0, *) func testClearsCache() { let cachedServer = CachedPageServer() let cacheRoot = cachedServer.start() let url = "\(cacheRoot)/cachedPage.html" tester().tapViewWithAccessibilityIdentifier("url") tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n") tester().waitForWebViewElementWithAccessibilityLabel("Cache test") let webView = tester().waitForViewWithAccessibilityLabel("Web content") as! WKWebView let requests = cachedServer.requests // Verify that clearing non-cache items will keep the page in the cache. clearPrivateData(AllClearables.subtract([Clearable.Cache])) webView.reload() XCTAssertEqual(cachedServer.requests, requests) // Verify that clearing the cache will fire a new request. clearPrivateData([Clearable.Cache]) webView.reload() XCTAssertEqual(cachedServer.requests, requests + 1) } func testClearsLogins() { tester().tapViewWithAccessibilityIdentifier("url") let url = "\(webRoot)/loginForm.html" tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n") tester().waitForWebViewElementWithAccessibilityLabel("Submit") // The form should be empty when we first load it. XCTAssertFalse(tester().hasWebViewElementWithAccessibilityLabel("foo")) XCTAssertFalse(tester().hasWebViewElementWithAccessibilityLabel("bar")) // Fill it in and submit. tester().enterText("foo", intoWebViewInputWithName: "username") tester().enterText("bar", intoWebViewInputWithName: "password") tester().tapWebViewElementWithAccessibilityLabel("Submit") // Say "Yes" to the remember password prompt. tester().tapViewWithAccessibilityLabel("Yes") // Verify that the form is autofilled after reloading. tester().tapViewWithAccessibilityLabel("Reload") XCTAssert(tester().hasWebViewElementWithAccessibilityLabel("foo")) XCTAssert(tester().hasWebViewElementWithAccessibilityLabel("bar")) // Ensure that clearing other data has no effect on the saved logins. clearPrivateData(AllClearables.subtract([Clearable.Logins])) tester().tapViewWithAccessibilityLabel("Reload") XCTAssert(tester().hasWebViewElementWithAccessibilityLabel("foo")) XCTAssert(tester().hasWebViewElementWithAccessibilityLabel("bar")) // Ensure that clearing logins clears the form. clearPrivateData([Clearable.Logins]) tester().tapViewWithAccessibilityLabel("Reload") XCTAssertFalse(tester().hasWebViewElementWithAccessibilityLabel("foo")) XCTAssertFalse(tester().hasWebViewElementWithAccessibilityLabel("bar")) } private func setCookies(webView: WKWebView, cookie: String) { let expectation = expectationWithDescription("Set cookie") webView.evaluateJavaScript("document.cookie = \"\(cookie)\"; localStorage.cookie = \"\(cookie)\"; sessionStorage.cookie = \"\(cookie)\";") { result, _ in expectation.fulfill() } waitForExpectationsWithTimeout(10, handler: nil) } private func getCookies(webView: WKWebView) -> (cookie: String, localStorage: String?, sessionStorage: String?) { var cookie: (String, String?, String?)! let expectation = expectationWithDescription("Got cookie") webView.evaluateJavaScript("JSON.stringify([document.cookie, localStorage.cookie, sessionStorage.cookie])") { result, _ in let cookies = JSON.parse(result as! String).asArray! cookie = (cookies[0].asString!, cookies[1].asString, cookies[2].asString) expectation.fulfill() } waitForExpectationsWithTimeout(10, handler: nil) return cookie } } /// Server that keeps track of requests. private class CachedPageServer { var requests = 0 func start() -> String { let webServer = GCDWebServer() webServer.addHandlerForMethod("GET", path: "/cachedPage.html", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in self.requests++ return GCDWebServerDataResponse(HTML: "<html><head><title>Cached page</title></head><body>Cache test</body></html>") } webServer.startWithPort(0, bonjourName: nil) // We use 127.0.0.1 explicitly here, rather than localhost, in order to avoid our // history exclusion code (Bug 1188626). let webRoot = "http://127.0.0.1:\(webServer.port)" return webRoot } }
mpl-2.0
kusl/swift
validation-test/compiler_crashers_fixed/1922-getselftypeforcontainer.swift
13
492
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let x { var b = 1][Any) -> Self { f(")) { let i(x) { } let v: A, self.A> Any) -> { func c] = [unowned self] { return { self.f == A<B : Any) -> : AnyObject, 3] == { var d { } } } } return z: NSObject { func x: B, range.<T, U) -> () { }) } } protocol b { func a typealias d: a {
apache-2.0
kusl/swift
validation-test/compiler_crashers_fixed/0181-swift-parser-parseexprclosure.swift
12
2657
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func f<T : BooleanType>(b: T) { } f(true as BooleanType) class k { func l((Any, k))(m } } func j<f: l: e -> e = { { l) { m } } protocol k { class func j() } class e: k{ class func j func i(c: () -> ()) { } class a { var _ = i() { } } func ^(a: BooleanType, Bool) -> Bool { return !(a) } ({}) struct A<T> { let a: [(T, () -> ())] = [] } var f = 1 var e: Int -> Int = { return $0 } let d: Int = { c, b in }(f, e) d "" e} class d { func b((Any, d)typealias b = b func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) { return { (m: (Any, Any) -> Any) -> Any in return m(x, y) } } func b(z: (((Any, Any) -> Any) -> Any)) -> Any { return z({ (p: Any, q:Any) -> Any in return p }) } b(a(1, a(2, 3))) protocol a : a { } a } struct e : f { i f = g } func i<g : g, e : f where e.f == g> (c: e) { } func i<h : f where h.f == c> (c: h) { } i(e()) class a<f : g, g : g where f.f == g> { } protocol g { typealias f typealias e } struct c<h : g> : g { typealias f = h typealias e = a<c<h>, f> ({}) func prefix(with: String) -> <T>(() -> T) -> String { func b clanType, Bool) -> Bool { ) } strs d typealias b> : b { typealias d = h typealias e = a<c<h>, d> } class a<f : b, g : b where f.d == g> { } protocol b { typealias d typealias e } struct c<h : b> : b { typealias d = h typealias e = a<c<h>, d> } func prefi(with: String-> <T>() -> T)t protocol l : p { } protocol m { j f = p } f m : m { j f = o } func i<o : o, m : m n m.f == o> (l: m) { } k: m } func p<m>() -> [l<m>] { return [] } f m) func f<o>() -> (o, o -> o) -> o { m o m.i = { } { o) { p } } protocol f { class func i() } class m: f{ class func i {} protocol p { class func l() } class o: p { class func l() { } struct A<T> { let a: [(T, () -> ())] = [] } f e) func f<g>() -> (g, g -> g) -> g { d j d.i 1, a(2, 3))) class a { typealias ((t, t) -> t) -> t)) -> t { return r({ return k }) () { g g h g } } func e(i: d) -> <f>(() -> f)> func m(c: b) -> <h>(() -> h) -> b { f) -> j) -> > j { l i !(k) } d l) func d<m>-> (m, m - struct c<d, e: b where d.c ==e> var x1 =I Bool !(a) } func prefix(with: Strin) -> <T>(() -> T) in // Distributed under the terms oclass a { typealias b = b func b((Any, e))(e: (Any) -> <d>(()-> d) -> f func f() { ({}) }
apache-2.0
cikelengfeng/Jude
Jude/Antlr4/atn/EmptyPredictionContext.swift
2
932
/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. public class EmptyPredictionContext: SingletonPredictionContext { public init() { super.init(nil, PredictionContext.EMPTY_RETURN_STATE) } override public func isEmpty() -> Bool { return true } override public func size() -> Int { return 1 } override public func getParent(_ index: Int) -> PredictionContext? { return nil } override public func getReturnState(_ index: Int) -> Int { return returnState } override public var description: String { return "$" } } public func ==(lhs: EmptyPredictionContext, rhs: EmptyPredictionContext) -> Bool { if lhs === rhs { return true } return false }
mit
STShenZhaoliang/STWeiBo
STWeiBo/STWeiBo/Classes/Home/Status.swift
1
7014
// // Status.swift // STWeiBo // // Created by ST on 15/11/17. // Copyright © 2015年 ST. All rights reserved. // import UIKit import SDWebImage class Status: NSObject { /// 微博创建时间 var created_at: String? { didSet{ // 1.将字符串转换为时间 let createdDate = NSDate.dateWithStr(created_at!) // 2.获取格式化之后的时间字符串 created_at = createdDate.descDate } } /// 微博ID var id: Int = 0 /// 微博信息内容 var text: String? /// 微博来源 var source: String? { didSet{ // 1.截取字符串 if let str = source { if str == "" { return } // 1.1获取开始截取的位置 let startLocation = (str as NSString).rangeOfString(">").location + 1 // 1.2获取截取的长度 let length = (str as NSString).rangeOfString("<", options: NSStringCompareOptions.BackwardsSearch).location - startLocation // 1.3截取字符串 source = "来自:" + (str as NSString).substringWithRange(NSMakeRange(startLocation, length)) } } } /// 配图数组 var pic_urls: [[String: AnyObject]]? { didSet{ // 1.初始化数组 storedPicURLS = [NSURL]() // 2遍历取出所有的图片路径字符串 storedLargePicURLS = [NSURL]() for dict in pic_urls! { if let urlStr = dict["thumbnail_pic"] as? String { // 1.将字符串转换为URL保存到数组中 storedPicURLS!.append(NSURL(string: urlStr)!) // 2.处理大图 let largeURLStr = urlStr.stringByReplacingOccurrencesOfString("thumbnail", withString: "large") storedLargePicURLS!.append(NSURL(string: largeURLStr)!) } } } } /// 保存当前微博所有配图的URL var storedPicURLS: [NSURL]? /// 保存当前微博所有配图"大图"的URL var storedLargePicURLS: [NSURL]? /// 用户信息 var user: User? /// 转发微博 var retweeted_status: Status? // 如果有转发, 原创就没有配图 /// 定义一个计算属性, 用于返回原创获取转发配图的URL数组 var pictureURLS:[NSURL]? { return retweeted_status != nil ? retweeted_status?.storedPicURLS : storedPicURLS } /// 定义一个计算属性, 用于返回原创或者转发配图的大图URL数组 var LargePictureURLS:[NSURL]? { return retweeted_status != nil ? retweeted_status?.storedLargePicURLS : storedLargePicURLS } /// 加载微博数据 class func loadStatuses(since_id: Int, finished: (models:[Status]?, error:NSError?)->()){ let path = "2/statuses/home_timeline.json" var params = ["access_token": UserAccount.loadAccount()!.access_token!] print("\(__FUNCTION__) \(self)") // 下拉刷新 if since_id > 0 { params["since_id"] = "\(since_id)" } NetworkTools.shareNetworkTools().GET(path, parameters: params, success: { (_, JSON) -> Void in // 1.取出statuses key对应的数组 (存储的都是字典) // 2.遍历数组, 将字典转换为模型 let models = dict2Model(JSON["statuses"] as! [[String: AnyObject]]) // 3.缓存微博配图 cacheStatusImages(models, finished: finished) }) { (_, error) -> Void in print(error) finished(models: nil, error: error) } } /// 缓存配图 class func cacheStatusImages(list: [Status], finished: (models:[Status]?, error:NSError?)->()) { if list.count == 0 { finished(models: list, error: nil) return } // 1.创建一个组 let group = dispatch_group_create() // 1.缓存图片 for status in list { // 1.1判断当前微博是否有配图, 如果没有就直接跳过 // Swift2.0新语法, 如果条件为nil, 那么就会执行else后面的语句 guard let _ = status.pictureURLS else { continue } for url in status.pictureURLS! { // 将当前的下载操作添加到组中 dispatch_group_enter(group) // 缓存图片 SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) -> Void in // 离开当前组 dispatch_group_leave(group) }) } } // 2.当所有图片都下载完毕再通过闭包通知调用者 dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in // 能够来到这个地方, 一定是所有图片都下载完毕 finished(models: list, error: nil) } } /// 将字典数组转换为模型数组 class func dict2Model(list: [[String: AnyObject]]) -> [Status] { var models = [Status]() for dict in list { models.append(Status(dict: dict)) } return models } // 字典转模型 init(dict: [String: AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } // setValuesForKeysWithDictionary内部会调用以下方法 override func setValue(value: AnyObject?, forKey key: String) { // 1.判断当前是否正在给微博字典中的user字典赋值 if "user" == key { // 2.根据user key对应的字典创建一个模型 user = User(dict: value as! [String : AnyObject]) return } // 2.判断是否是转发微博, 如果是就自己处理 if "retweeted_status" == key { retweeted_status = Status(dict: value as! [String : AnyObject]) return } // 3,调用父类方法, 按照系统默认处理 super.setValue(value, forKey: key) } override func setValue(value: AnyObject?, forUndefinedKey key: String) { } // 打印当前模型 var properties = ["created_at", "id", "text", "source", "pic_urls"] override var description: String { let dict = dictionaryWithValuesForKeys(properties) return "\(dict)" } }
mit
CJGitH/QQMusic
QQMusic/Classes/Other/Tool/QQImageTool.swift
1
1274
// // QQImageTool.swift // QQMusic // // Created by chen on 16/5/18. // Copyright © 2016年 chen. All rights reserved. // import UIKit class QQImageTool: NSObject { class func getNewImage(sourceImage: UIImage, str: String) -> UIImage { let size = sourceImage.size // 1. 开启图形上下文 UIGraphicsBeginImageContext(size) // 2. 绘制大的图片 sourceImage.drawInRect(CGRectMake(0, 0, size.width, size.height)) // 3. 绘制文字 let style: NSMutableParagraphStyle = NSMutableParagraphStyle() style.alignment = .Center let dic: [String : AnyObject] = [ NSForegroundColorAttributeName: UIColor.whiteColor(), NSParagraphStyleAttributeName: style, NSFontAttributeName: UIFont.systemFontOfSize(20) ] (str as NSString).drawInRect(CGRectMake(0, 0, size.width, 26), withAttributes: dic) // 4. 获取结果图片 let resultImage = UIGraphicsGetImageFromCurrentImageContext() // 5. 关闭上下文 UIGraphicsEndImageContext() // 6. 返回结果 return resultImage } }
mit
PD-Jell/Swift_study
SwiftStudy/FastCampus/FCLuffyView.swift
1
1257
// // FCLuppyView.swift // SwiftStudy // // Created by yoohg on 2021/07/08. // Copyright © 2021 Jell PD. All rights reserved. // import SwiftUI struct FCLuffyView: View { @State var price = 100000 @State private var showingAlert = false var body: some View { if #available(iOS 14.0, *) { VStack { Spacer() Text("Wanted").font(.system(size: 50)) Image(systemName: "paperplane.fill") .resizable() .frame(width: 200, height: 200) Text("₩\(price)").font(.system(size: 50)) Spacer() Button(action: { self.showingAlert = true self.price = 2000000 }, label: { Text("reload") }).alert(isPresented: $showingAlert, content: { .init(title: Text("hello"), message: Text("First App!"), dismissButton: .default(Text("ok"))) }) } } else { // Fallback on earlier versions } } } struct FCLuffyView_Previews: PreviewProvider { static var previews: some View { FCLuffyView() } }
mit
yeahdongcn/RSBarcodes_Swift
Source/StringExtension.swift
1
1094
// // Ext.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/10/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import UIKit extension String { func length() -> Int { return self.count } func trim() -> String { return self.trimmingCharacters(in: .whitespacesAndNewlines) } func substring(_ location:Int, length:Int) -> String! { return (self as NSString).substring(with: NSMakeRange(location, length)) } subscript(index: Int) -> String! { get { return self.substring(index, length: 1) } } func location(_ other: String) -> Int { return (self as NSString).range(of: other).location } func contains(_ other: String) -> Bool { return (self as NSString).contains(other) } // http://stackoverflow.com/questions/6644004/how-to-check-if-nsstring-is-contains-a-numeric-value func isNumeric() -> Bool { return (self as NSString).rangeOfCharacter(from: CharacterSet.decimalDigits.inverted).location == NSNotFound } }
mit
mitochrome/complex-gestures-demo
apps/GestureRecognizer/Carthage/Checkouts/RxSwift/RxExample/RxExample-iOSTests/UIImagePickerController+RxTests.swift
12
1953
// // UIImagePickerController+RxTests.swift // RxExample // // Created by Segii Shulga on 1/6/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // #if os(iOS) import RxSwift import RxCocoa import XCTest import UIKit import RxExample_iOS class UIImagePickerControllerTests: RxTest { } extension UIImagePickerControllerTests { func testDidFinishPickingMediaWithInfo() { var completed = false var info:[String:AnyObject]? let pickedInfo = [UIImagePickerControllerOriginalImage : UIImage()] autoreleasepool { let imagePickerController = UIImagePickerController() _ = imagePickerController.rx.didFinishPickingMediaWithInfo .subscribe(onNext: { (i) -> Void in info = i }, onCompleted: { completed = true }) imagePickerController.delegate! .imagePickerController!(imagePickerController,didFinishPickingMediaWithInfo:pickedInfo) } XCTAssertTrue(info?[UIImagePickerControllerOriginalImage] === pickedInfo[UIImagePickerControllerOriginalImage]) XCTAssertTrue(completed) } func testDidCancel() { var completed = false var canceled = false autoreleasepool { let imagePickerController = UIImagePickerController() _ = imagePickerController.rx.didCancel .subscribe(onNext: { (i) -> Void in canceled = true }, onCompleted: { completed = true }) imagePickerController.delegate!.imagePickerControllerDidCancel!(imagePickerController) } XCTAssertTrue(canceled) XCTAssertTrue(completed) } } #endif
mit
lcddhr/BSImagePicker
Pod/Classes/Model/AssetsModel.swift
2
5403
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // 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 Photos final class AssetsModel<T: AnyEquatableObject> : Selectable { var delegate: AssetsDelegate? subscript (idx: Int) -> PHFetchResult { return _results[idx] } var count: Int { return _results.count } private var _selections = [T]() private var _results: [PHFetchResult] required init(fetchResult aFetchResult: [PHFetchResult]) { _results = aFetchResult } // MARK: PHPhotoLibraryChangeObserver func photoLibraryDidChange(changeInstance: PHChange!) { for (index, fetchResult) in enumerate(_results) { // Check if there are changes to our fetch result if let collectionChanges = changeInstance.changeDetailsForFetchResult(fetchResult) { // Get the new fetch result let newResult = collectionChanges.fetchResultAfterChanges as PHFetchResult // Replace old result _results[index] = newResult // Sometimes the properties on PHFetchResultChangeDetail are nil // Work around it for now let incrementalChange = collectionChanges.hasIncrementalChanges && collectionChanges.removedIndexes != nil && collectionChanges.insertedIndexes != nil && collectionChanges.changedIndexes != nil let removedIndexPaths: [NSIndexPath] let insertedIndexPaths: [NSIndexPath] let changedIndexPaths: [NSIndexPath] if incrementalChange { // Incremental change, tell delegate what has been deleted, inserted and changed removedIndexPaths = indexPathsFromIndexSet(collectionChanges.removedIndexes, inSection: index) insertedIndexPaths = indexPathsFromIndexSet(collectionChanges.insertedIndexes, inSection: index) changedIndexPaths = indexPathsFromIndexSet(collectionChanges.changedIndexes, inSection: index) } else { // No incremental change. Set empty arrays removedIndexPaths = [] insertedIndexPaths = [] changedIndexPaths = [] } // Notify delegate delegate?.didUpdateAssets(self, incrementalChange: incrementalChange, insert: insertedIndexPaths, delete: removedIndexPaths, change: changedIndexPaths) } } } private func indexPathsFromIndexSet(indexSet: NSIndexSet, inSection section: Int) -> [NSIndexPath] { var indexPaths: [NSIndexPath] = [] indexSet.enumerateIndexesUsingBlock { (index, _) -> Void in indexPaths.append(NSIndexPath(forItem: index, inSection: section)) } return indexPaths } // MARK: Selectable func selectObjectAtIndexPath(indexPath: NSIndexPath) { if let object = _results[indexPath.section][indexPath.row] as? T where contains(_selections, object) == false { _selections.append(object) } } func deselectObjectAtIndexPath(indexPath: NSIndexPath) { if let object = _results[indexPath.section][indexPath.row] as? T, let index = find(_selections, object) { _selections.removeAtIndex(index) } } func selectionCount() -> Int { return _selections.count } func selectedIndexPaths() -> [NSIndexPath] { var indexPaths: [NSIndexPath] = [] for object in _selections { for (resultIndex, fetchResult) in enumerate(_results) { let index = fetchResult.indexOfObject(object) if index != NSNotFound { let indexPath = NSIndexPath(forItem: index, inSection: resultIndex) indexPaths.append(indexPath) } } } return indexPaths } func selections() -> [T] { return _selections } func setSelections(newSelections: [T]) { _selections = newSelections } func removeSelections() { _selections.removeAll(keepCapacity: true) } }
mit
voyages-sncf-technologies/Collor
Example/Collor/MenuSample/MenuCollectionData.swift
1
745
// // MenuCollectionData.swift // Collor // // Created by Guihal Gwenn on 14/08/2017. // Copyright (c) 2017-present, Voyages-sncf.com. All rights reserved.. All rights reserved. // import Foundation import Collor final class MenuCollectionData : CollectionData { let examples:[Example] init(examples:[Example]) { self.examples = examples super.init() } override func reloadData() { super.reloadData() let section = MenuSectionDescriptor().reloadSection { cells in self.examples.forEach { cells.append( MenuItemDescriptor(adapter: MenuItemAdapter(example: $0 ) )) } } sections.append(section) } }
bsd-3-clause
MobileFirstInc/MFCard
MFCard/Card /Toast/Toast.swift
1
31043
// // Toast.swift // Toast-Swift // // Copyright (c) 2015 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 public enum ToastPosition { case top case center case bottom } /** 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 = "CSToastTimerKey" static var Duration = "CSToastDurationKey" static var Position = "CSToastPositionKey" static var Completion = "CSToastCompletionKey" static var ActiveToast = "CSToastActiveToastKey" static var ActivityView = "CSToastActivityViewKey" static var Queue = "CSToastQueueKey" } /** 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 with a message and displays it with the default duration and position. Styled using the shared style. @param message The message to be displayed */ func makeToast(_ message: String) { self.makeToast(message, duration: ToastManager.shared.duration, position: ToastManager.shared.position) } /** Creates and presents a new toast view with a message. Duration and position can be set explicitly. Styled using the shared style. @param message The message to be displayed @param duration The toast duration @param position The toast's position */ func makeToast(_ message: String, duration: TimeInterval, position: ToastPosition) { self.makeToast(message, duration: duration, position: position, style: nil) } /** Creates and presents a new toast view with a message. Duration and position can be set explicitly. Styled using the shared style. @param message The message to be displayed @param duration The toast duration @param position The toast's center point */ func makeToast(_ message: String, duration: TimeInterval, position: CGPoint) { self.makeToast(message, duration: duration, position: position, style: nil) } /** Creates and presents a new toast view with a message. Duration, position, and style can be set explicitly. @param message The message to be displayed @param duration The toast duration @param position The toast's position @param style The style. The shared style will be used when nil */ func makeToast(_ message: String, duration: TimeInterval, position: ToastPosition, style: ToastStyle?) { self.makeToast(message, duration: duration, position: position, title: nil, image: nil, style: style, completion: nil) } /** Creates and presents a new toast view with a message. Duration, position, and style can be set explicitly. @param message The message to be displayed @param duration The toast duration @param position The toast's center point @param style The style. The shared style will be used when nil */ func makeToast(_ message: String, duration: TimeInterval, position: CGPoint, style: ToastStyle?) { self.makeToast(message, duration: duration, position: position, title: nil, image: nil, style: style, completion: nil) } /** Creates and presents a new toast view with a message, title, and image. Duration, position, and style can be set explicitly. The completion closure executes when the toast completes presentation. `didTap` will be `true` if the toast view was dismissed from a tap. @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. */ func makeToast(_ message: String?, duration: TimeInterval, position: ToastPosition, title: String?, image: UIImage?, style: ToastStyle?, completion: ((_ didTap: Bool) -> Void)?) { var toastStyle = ToastManager.shared.style if let style = style { toastStyle = style } do { let toast = try self.toastViewForMessage(message, title: title, image: image, style: toastStyle) self.showToast(toast, duration: duration, position: position, completion: completion) } catch ToastError.insufficientData { print("Error: message, title, and image are all nil") } catch {} } /** Creates and presents a new toast view with a message, title, and image. Duration, position, and style can be set explicitly. The completion closure executes when the toast completes presentation. `didTap` will be `true` if the toast view was dismissed from a tap. @param message The message to be displayed @param duration The toast duration @param position 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. */ func makeToast(_ message: String?, duration: TimeInterval, position: CGPoint, title: String?, image: UIImage?, style: ToastStyle?, completion: ((_ didTap: Bool) -> Void)?) { var toastStyle = ToastManager.shared.style if let style = style { toastStyle = style } do { let toast = try self.toastViewForMessage(message, title: title, image: image, style: toastStyle) self.showToast(toast, duration: duration, position: position, 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 using the default duration and position. @param toast The view to be displayed as toast */ func showToast(_ toast: UIView) { self.showToast(toast, duration: ToastManager.shared.duration, position: ToastManager.shared.position, completion: nil) } /** 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. */ func showToast(_ toast: UIView, duration: TimeInterval, position: ToastPosition, completion: ((_ didTap: Bool) -> Void)?) { let point = self.centerPointForPosition(position, toast: toast) self.showToast(toast, duration: duration, position: point, completion: completion) } /** 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 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. */ func showToast(_ toast: UIView, duration: TimeInterval, position: CGPoint, completion: ((_ didTap: Bool) -> Void)?) { objc_setAssociatedObject(toast, &ToastKeys.Completion, ToastCompletionWrapper(completion), .OBJC_ASSOCIATION_RETAIN_NONATOMIC); if let _ = objc_getAssociatedObject(self, &ToastKeys.ActiveToast) as? UIView, ToastManager.shared.queueEnabled { objc_setAssociatedObject(toast, &ToastKeys.Duration, NSNumber(value: duration), .OBJC_ASSOCIATION_RETAIN_NONATOMIC); objc_setAssociatedObject(toast, &ToastKeys.Position, NSValue(cgPoint: position), .OBJC_ASSOCIATION_RETAIN_NONATOMIC); self.queue.add(toast) } else { self.showToast(toast, duration: duration, position: position) } } // 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 */ func makeToastActivity(_ position: ToastPosition) { // sanity if let _ = objc_getAssociatedObject(self, &ToastKeys.ActivityView) as? UIView { return } let toast = self.createToastActivityView() let point = self.centerPointForPosition(position, toast: toast) self.makeToastActivity(toast, position: 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 position The toast's center point */ func makeToastActivity(_ position: CGPoint) { // sanity if let _ = objc_getAssociatedObject(self, &ToastKeys.ActivityView) as? UIView { return } let toast = self.createToastActivityView() self.makeToastActivity(toast, position: position) } /** Dismisses the active toast activity indicator view. */ 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: { () -> Void in toast.alpha = 0.0 }, completion: { (finished: Bool) -> Void in toast.removeFromSuperview() objc_setAssociatedObject(self, &ToastKeys.ActivityView, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }) } } // MARK: - Private Activity Methods private func makeToastActivity(_ toast: UIView, position: CGPoint) { toast.alpha = 0.0 toast.center = position 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: { () -> Void in toast.alpha = 1.0 }, completion: nil) } 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(style: .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, position: CGPoint) { toast.center = position toast.alpha = 0.0 if ToastManager.shared.tapToDismissEnabled { 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: { () -> Void in toast.alpha = 1.0 }) { (finished) -> Void in let timer = Timer(timeInterval: duration, target: self, selector: #selector(UIView.toastTimerDidFinish(_:)), userInfo: toast, repeats: false) RunLoop.main.add(timer, forMode: RunLoop.Mode.common) objc_setAssociatedObject(toast, &ToastKeys.Timer, timer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private func hideToast(_ toast: UIView) { self.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: { () -> Void in toast.alpha = 0.0 }) { (didFinish: Bool) -> Void 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 position = objc_getAssociatedObject(nextToast, &ToastKeys.Position) as? NSValue { self.queue.removeObject(at: 0) self.showToast(nextToast, duration: duration.doubleValue, position: position.cgPointValue) } } } // MARK: - Events @objc func handleToastTapped(_ recognizer: UITapGestureRecognizer) { if let toast = recognizer.view, let timer = objc_getAssociatedObject(toast, &ToastKeys.Timer) as? Timer { timer.invalidate() self.hideToast(toast, fromTap: true) } } @objc func toastTimerDidFinish(_ timer: Timer) { if let toast = timer.userInfo as? UIView { self.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 */ func toastViewForMessage(_ message: String?, title: String?, image: UIImage?, style: ToastStyle) throws -> UIView { // sanity if message == nil && title == nil && image == nil { 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 { titleLabel.frame = titleRect wrapperView.addSubview(titleLabel) } if let messageLabel = messageLabel { messageLabel.frame = messageRect wrapperView.addSubview(messageLabel) } if let imageView = imageView { wrapperView.addSubview(imageView) } return wrapperView } // MARK: - Helpers private func centerPointForPosition(_ position: ToastPosition, toast: UIView) -> CGPoint { let padding: CGFloat = ToastManager.shared.style.verticalPadding switch(position) { case .top: return CGPoint(x: self.bounds.size.width / 2.0, y: (toast.frame.size.height / 2.0) + padding) case .center: return CGPoint(x: self.bounds.size.width / 2.0, y: self.bounds.size.height / 2.0) case .bottom: return CGPoint(x: self.bounds.size.width / 2.0, y: (self.bounds.size.height - (toast.frame.size.height / 2.0)) - padding) } } } // 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.center /** 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 tapToDismissEnabled = 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 queueEnabled = 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 }
mit
michael-lehew/swift-corelibs-foundation
Foundation/Locale.swift
1
17976
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import CoreFoundation internal func __NSLocaleIsAutoupdating(_ locale: NSLocale) -> Bool { return false // Auto-updating is only on Darwin } internal func __NSLocaleCurrent() -> NSLocale { return CFLocaleCopyCurrent()._nsObject } /** `Locale` encapsulates information about linguistic, cultural, and technological conventions and standards. Examples of information encapsulated by a locale include the symbol used for the decimal separator in numbers and the way dates are formatted. Locales are typically used to provide, format, and interpret information about and according to the user’s customs and preferences. They are frequently used in conjunction with formatters. Although you can use many locales, you usually use the one associated with the current user. */ public struct Locale : CustomStringConvertible, CustomDebugStringConvertible, Hashable, Equatable, ReferenceConvertible { public typealias ReferenceType = NSLocale public typealias LanguageDirection = NSLocale.LanguageDirection internal var _wrapped : NSLocale internal var _autoupdating : Bool /// Returns the user's current locale. public static var current : Locale { return Locale(adoptingReference: __NSLocaleCurrent(), autoupdating: false) } @available(*, unavailable, message: "Consider using the user's locale or nil instead, depending on use case") public static var system : Locale { fatalError() } // MARK: - // /// Return a locale with the specified identifier. public init(identifier: String) { _wrapped = NSLocale(localeIdentifier: identifier) _autoupdating = false } internal init(reference: NSLocale) { _wrapped = reference.copy() as! NSLocale if __NSLocaleIsAutoupdating(reference) { _autoupdating = true } else { _autoupdating = false } } private init(adoptingReference reference: NSLocale, autoupdating: Bool) { _wrapped = reference _autoupdating = autoupdating } // MARK: - // /// Returns a localized string for a specified identifier. /// /// For example, in the "en" locale, the result for `"es"` is `"Spanish"`. public func localizedString(forIdentifier identifier: String) -> String? { return _wrapped.displayName(forKey: .identifier, value: identifier) } /// Returns a localized string for a specified language code. /// /// For example, in the "en" locale, the result for `"es"` is `"Spanish"`. public func localizedString(forLanguageCode languageCode: String) -> String? { return _wrapped.displayName(forKey: .languageCode, value: languageCode) } /// Returns a localized string for a specified region code. /// /// For example, in the "en" locale, the result for `"fr"` is `"France"`. public func localizedString(forRegionCode regionCode: String) -> String? { return _wrapped.displayName(forKey: .countryCode, value: regionCode) } /// Returns a localized string for a specified script code. /// /// For example, in the "en" locale, the result for `"Hans"` is `"Simplified Han"`. public func localizedString(forScriptCode scriptCode: String) -> String? { return _wrapped.displayName(forKey: .scriptCode, value: scriptCode) } /// Returns a localized string for a specified variant code. /// /// For example, in the "en" locale, the result for `"POSIX"` is `"Computer"`. public func localizedString(forVariantCode variantCode: String) -> String? { return _wrapped.displayName(forKey: .variantCode, value: variantCode) } /// Returns a localized string for a specified `Calendar.Identifier`. /// /// For example, in the "en" locale, the result for `.buddhist` is `"Buddhist Calendar"`. public func localizedString(for calendarIdentifier: Calendar.Identifier) -> String? { // NSLocale doesn't export a constant for this let result = CFLocaleCopyDisplayNameForPropertyValue(unsafeBitCast(_wrapped, to: CFLocale.self), kCFLocaleCalendarIdentifier, Calendar._toNSCalendarIdentifier(calendarIdentifier).rawValue._cfObject)._swiftObject return result } /// Returns a localized string for a specified ISO 4217 currency code. /// /// For example, in the "en" locale, the result for `"USD"` is `"US Dollar"`. /// - seealso: `Locale.isoCurrencyCodes` public func localizedString(forCurrencyCode currencyCode: String) -> String? { return _wrapped.displayName(forKey: .currencyCode, value: currencyCode) } /// Returns a localized string for a specified ICU collation identifier. /// /// For example, in the "en" locale, the result for `"phonebook"` is `"Phonebook Sort Order"`. public func localizedString(forCollationIdentifier collationIdentifier: String) -> String? { return _wrapped.displayName(forKey: .collationIdentifier, value: collationIdentifier) } /// Returns a localized string for a specified ICU collator identifier. public func localizedString(forCollatorIdentifier collatorIdentifier: String) -> String? { return _wrapped.displayName(forKey: .collatorIdentifier, value: collatorIdentifier) } // MARK: - // /// Returns the identifier of the locale. public var identifier: String { return _wrapped.localeIdentifier } /// Returns the language code of the locale, or nil if has none. /// /// For example, for the locale "zh-Hant-HK", returns "zh". public var languageCode: String? { return _wrapped.object(forKey: .languageCode) as? String } /// Returns the region code of the locale, or nil if it has none. /// /// For example, for the locale "zh-Hant-HK", returns "HK". public var regionCode: String? { // n.b. this is called countryCode in ObjC if let result = _wrapped.object(forKey: .countryCode) as? String { if result.isEmpty { return nil } else { return result } } else { return nil } } /// Returns the script code of the locale, or nil if has none. /// /// For example, for the locale "zh-Hant-HK", returns "Hant". public var scriptCode: String? { return _wrapped.object(forKey: .scriptCode) as? String } /// Returns the variant code for the locale, or nil if it has none. /// /// For example, for the locale "en_POSIX", returns "POSIX". public var variantCode: String? { if let result = _wrapped.object(forKey: .variantCode) as? String { if result.isEmpty { return nil } else { return result } } else { return nil } } /// Returns the exemplar character set for the locale, or nil if has none. public var exemplarCharacterSet: CharacterSet? { return _wrapped.object(forKey: .exemplarCharacterSet) as? CharacterSet } /// Returns the calendar for the locale, or the Gregorian calendar as a fallback. public var calendar: Calendar { // NSLocale should not return nil here if let result = _wrapped.object(forKey: .calendar) as? Calendar { return result } else { return Calendar(identifier: .gregorian) } } /// Returns the collation identifier for the locale, or nil if it has none. /// /// For example, for the locale "en_US@collation=phonebook", returns "phonebook". public var collationIdentifier: String? { return _wrapped.object(forKey: .collationIdentifier) as? String } /// Returns true if the locale uses the metric system. /// /// -seealso: MeasurementFormatter public var usesMetricSystem: Bool { // NSLocale should not return nil here, but just in case if let result = (_wrapped.object(forKey: .usesMetricSystem) as? NSNumber)?.boolValue { return result } else { return false } } /// Returns the decimal separator of the locale. /// /// For example, for "en_US", returns ".". public var decimalSeparator: String? { return _wrapped.object(forKey: .decimalSeparator) as? String } /// Returns the grouping separator of the locale. /// /// For example, for "en_US", returns ",". public var groupingSeparator: String? { return _wrapped.object(forKey: .groupingSeparator) as? String } /// Returns the currency symbol of the locale. /// /// For example, for "zh-Hant-HK", returns "HK$". public var currencySymbol: String? { return _wrapped.object(forKey: .currencySymbol) as? String } /// Returns the currency code of the locale. /// /// For example, for "zh-Hant-HK", returns "HKD". public var currencyCode: String? { return _wrapped.object(forKey: .currencyCode) as? String } /// Returns the collator identifier of the locale. public var collatorIdentifier: String? { return _wrapped.object(forKey: .collatorIdentifier) as? String } /// Returns the quotation begin delimiter of the locale. /// /// For example, returns `“` for "en_US", and `「` for "zh-Hant-HK". public var quotationBeginDelimiter: String? { return _wrapped.object(forKey: .quotationBeginDelimiterKey) as? String } /// Returns the quotation end delimiter of the locale. /// /// For example, returns `”` for "en_US", and `」` for "zh-Hant-HK". public var quotationEndDelimiter: String? { return _wrapped.object(forKey: .quotationEndDelimiterKey) as? String } /// Returns the alternate quotation begin delimiter of the locale. /// /// For example, returns `‘` for "en_US", and `『` for "zh-Hant-HK". public var alternateQuotationBeginDelimiter: String? { return _wrapped.object(forKey: .alternateQuotationBeginDelimiterKey) as? String } /// Returns the alternate quotation end delimiter of the locale. /// /// For example, returns `’` for "en_US", and `』` for "zh-Hant-HK". public var alternateQuotationEndDelimiter: String? { return _wrapped.object(forKey: .alternateQuotationEndDelimiterKey) as? String } // MARK: - // /// Returns a list of available `Locale` identifiers. public static var availableIdentifiers: [String] { return NSLocale.availableLocaleIdentifiers } /// Returns a list of available `Locale` language codes. public static var isoLanguageCodes: [String] { return NSLocale.isoLanguageCodes } /// Returns a list of available `Locale` region codes. public static var isoRegionCodes: [String] { // This was renamed from Obj-C return NSLocale.isoCountryCodes } /// Returns a list of available `Locale` currency codes. public static var isoCurrencyCodes: [String] { return NSLocale.isoCurrencyCodes } /// Returns a list of common `Locale` currency codes. public static var commonISOCurrencyCodes: [String] { return NSLocale.commonISOCurrencyCodes } /// Returns a list of the user's preferred languages. /// /// - note: `Bundle` is responsible for determining the language that your application will run in, based on the result of this API and combined with the languages your application supports. /// - seealso: `Bundle.preferredLocalizations(from:)` /// - seealso: `Bundle.preferredLocalizations(from:forPreferences:)` public static var preferredLanguages: [String] { return NSLocale.preferredLanguages } /// Returns a dictionary that splits an identifier into its component pieces. public static func components(fromIdentifier string: String) -> [String : String] { return NSLocale.components(fromLocaleIdentifier: string) } /// Constructs an identifier from a dictionary of components. public static func identifier(fromComponents components: [String : String]) -> String { return NSLocale.localeIdentifier(fromComponents: components) } /// Returns a canonical identifier from the given string. public static func canonicalIdentifier(from string: String) -> String { return NSLocale.canonicalLocaleIdentifier(from: string) } /// Returns a canonical language identifier from the given string. public static func canonicalLanguageIdentifier(from string: String) -> String { return NSLocale.canonicalLanguageIdentifier(from: string) } /// Returns the `Locale` identifier from a given Windows locale code, or nil if it could not be converted. public static func identifier(fromWindowsLocaleCode code: Int) -> String? { return NSLocale.localeIdentifier(fromWindowsLocaleCode: UInt32(code)) } /// Returns the Windows locale code from a given identifier, or nil if it could not be converted. public static func windowsLocaleCode(fromIdentifier identifier: String) -> Int? { let result = NSLocale.windowsLocaleCode(fromLocaleIdentifier: identifier) if result == 0 { return nil } else { return Int(result) } } /// Returns the character direction for a specified language code. public static func characterDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection { return NSLocale.characterDirection(forLanguage: isoLangCode) } /// Returns the line direction for a specified language code. public static func lineDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection { return NSLocale.lineDirection(forLanguage: isoLangCode) } // MARK: - @available(*, unavailable, renamed: "init(identifier:)") public init(localeIdentifier: String) { fatalError() } @available(*, unavailable, renamed: "identifier") public var localeIdentifier: String { fatalError() } @available(*, unavailable, renamed: "localizedString(forIdentifier:)") public func localizedString(forLocaleIdentifier localeIdentifier: String) -> String { fatalError() } @available(*, unavailable, renamed: "availableIdentifiers") public static var availableLocaleIdentifiers: [String] { fatalError() } @available(*, unavailable, renamed: "components(fromIdentifier:)") public static func components(fromLocaleIdentifier string: String) -> [String : String] { fatalError() } @available(*, unavailable, renamed: "identifier(fromComponents:)") public static func localeIdentifier(fromComponents dict: [String : String]) -> String { fatalError() } @available(*, unavailable, renamed: "canonicalIdentifier(from:)") public static func canonicalLocaleIdentifier(from string: String) -> String { fatalError() } @available(*, unavailable, renamed: "identifier(fromWindowsLocaleCode:)") public static func localeIdentifier(fromWindowsLocaleCode lcid: UInt32) -> String? { fatalError() } @available(*, unavailable, renamed: "windowsLocaleCode(fromIdentifier:)") public static func windowsLocaleCode(fromLocaleIdentifier localeIdentifier: String) -> UInt32 { fatalError() } @available(*, unavailable, message: "use regionCode instead") public var countryCode: String { fatalError() } @available(*, unavailable, message: "use localizedString(forRegionCode:) instead") public func localizedString(forCountryCode countryCode: String) -> String { fatalError() } @available(*, unavailable, renamed: "isoRegionCodes") public static var isoCountryCodes: [String] { fatalError() } // MARK: - // public var description: String { return _wrapped.description } public var debugDescription : String { return _wrapped.debugDescription } public var hashValue : Int { if _autoupdating { return 1 } else { return _wrapped.hash } } } public func ==(lhs: Locale, rhs: Locale) -> Bool { if lhs._autoupdating || rhs._autoupdating { return lhs._autoupdating == rhs._autoupdating } else { return lhs._wrapped.isEqual(rhs._wrapped) } } extension Locale : _ObjectTypeBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSLocale { return _wrapped } public static func _forceBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) { if !_conditionallyBridgeFromObjectiveC(input, result: &result) { fatalError("Unable to bridge \(NSLocale.self) to \(self)") } } public static func _conditionallyBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) -> Bool { result = Locale(reference: input) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSLocale?) -> Locale { var result: Locale? = nil _forceBridgeFromObjectiveC(source!, result: &result) return result! } }
apache-2.0
flomerz/iOS-IUToDo
IUToDoTests/IUToDoTests.swift
1
882
// // IUToDoTests.swift // IUToDoTests // // Created by Flo on 22/12/14. // Copyright (c) 2014 Flo. All rights reserved. // import UIKit import XCTest class IUToDoTests: 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. } } }
gpl-2.0
gyro-n/PaymentsIos
GyronPayments/Classes/Models/Cancel.swift
1
2381
// // Cancel.swift // GyronPayments // // Created by David Ye on 2017/08/31. // Copyright © 2016 gyron. All rights reserved. // import Foundation /** The CancelStatus enum is a list of cancel statuses. */ public enum CancelStatus: String { case pending = "pending" case successful = "successful" case failed = "failed" case error = "error" } /** The Cancel class stores the information about cancelations for a charge. */ open class Cancel: BaseModel { /** The unique identifier for the cancel. */ public var id: String /** The unique identifier for the charge. */ public var chargeId: String /** The unique identifier for the store. */ public var storeId: String? /** The status of the cancel. One of pending, successful, failed, or errored. */ public var status: CancelStatus /** The error for the cancel (if any) - code: The error code of why a cancel failed or errored. - message: A short description of why a cancel failed. - detail: Additional details of why a cancel failed */ public var error: PaymentError? /** Any metadata to associate with the cancel. */ public var metadata: Metadata? /** live or test */ public var mode: ProcessingMode /** The date the cancel was created. */ public var createdOn: String /** Initializes the Cancel object */ override init() { id = "" chargeId = "" storeId = nil status = CancelStatus.pending error = nil metadata = nil mode = ProcessingMode.test createdOn = "" } /** Maps the values from a hash map object into the Cancel. */ override open func mapFromObject(map: ResponseData) { id = map["id"] as? String ?? "" chargeId = map["charge_id"] as? String ?? "" storeId = map["store_id"] as? String status = CancelStatus(rawValue: map["status"] as? String ?? CancelStatus.pending.rawValue)! createdOn = map["created_on"] as? String ?? "" error = map["error"] as? PaymentError metadata = map["metadata"] as? Metadata mode = ProcessingMode(rawValue: map["mode"] as? String ?? ProcessingMode.test.rawValue)! createdOn = map["created_on"] as? String ?? "" } }
mit
Allow2CEO/browser-ios
Client/Frontend/Browser/BrowserViewController/BrowserViewController+KeyCommands.swift
1
4548
/* 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 Shared extension BrowserViewController { func reloadTab(){ if homePanelController == nil { tabManager.selectedTab?.reload() } } func goBack(){ if tabManager.selectedTab?.canGoBack == true && homePanelController == nil { tabManager.selectedTab?.goBack() } } func goForward(){ if tabManager.selectedTab?.canGoForward == true && homePanelController == nil { tabManager.selectedTab?.goForward() } } func findOnPage(){ if let tab = tabManager.selectedTab, homePanelController == nil { browser(tab, didSelectFindInPageForSelection: "") } } func selectLocationBar() { urlBar.browserLocationViewDidTapLocation(urlBar.locationView) } func newTab() { openBlankNewTabAndFocus(isPrivate: PrivateBrowsing.singleton.isOn) self.selectLocationBar() } func newPrivateTab() { openBlankNewTabAndFocus(isPrivate: true) if PinViewController.isBrowserLockEnabled { self.selectLocationBar() } } func closeTab() { guard let tab = tabManager.selectedTab else { return } let priv = tab.isPrivate nextOrPrevTabShortcut(false) tabManager.removeTab(tab, createTabIfNoneLeft: !priv) if priv && tabManager.tabs.privateTabs.count == 0 { urlBarDidPressTabs(urlBar) } } fileprivate func nextOrPrevTabShortcut(_ isNext: Bool) { guard let tab = tabManager.selectedTab else { return } let step = isNext ? 1 : -1 let tabList: [Browser] = tabManager.tabs.displayedTabsForCurrentPrivateMode func wrappingMod(_ val:Int, mod:Int) -> Int { return ((val % mod) + mod) % mod } assert(wrappingMod(-1, mod: 10) == 9) let index = wrappingMod((tabList.index(of: tab)! + step), mod: tabList.count) tabManager.selectTab(tabList[index]) } func nextTab() { nextOrPrevTabShortcut(true) } func previousTab() { nextOrPrevTabShortcut(false) } override var keyCommands: [UIKeyCommand]? { let result = [ UIKeyCommand(input: "r", modifierFlags: .command, action: #selector(BrowserViewController.reloadTab), discoverabilityTitle: Strings.ReloadPageTitle), UIKeyCommand(input: "[", modifierFlags: .command, action: #selector(BrowserViewController.goBack), discoverabilityTitle: Strings.BackTitle), UIKeyCommand(input: "]", modifierFlags: .command, action: #selector(BrowserViewController.goForward), discoverabilityTitle: Strings.ForwardTitle), UIKeyCommand(input: "f", modifierFlags: .command, action: #selector(BrowserViewController.findOnPage), discoverabilityTitle: Strings.FindTitle), UIKeyCommand(input: "l", modifierFlags: .command, action: #selector(BrowserViewController.selectLocationBar), discoverabilityTitle: Strings.SelectLocationBarTitle), UIKeyCommand(input: "t", modifierFlags: .command, action: #selector(BrowserViewController.newTab), discoverabilityTitle: Strings.NewTabTitle), //#if DEBUG UIKeyCommand(input: "t", modifierFlags: .control, action: #selector(BrowserViewController.newTab), discoverabilityTitle: Strings.NewTabTitle), //#endif UIKeyCommand(input: "p", modifierFlags: [.command, .shift], action: #selector(BrowserViewController.newPrivateTab), discoverabilityTitle: Strings.NewPrivateTabTitle), UIKeyCommand(input: "w", modifierFlags: .command, action: #selector(BrowserViewController.closeTab), discoverabilityTitle: Strings.CloseTabTitle), UIKeyCommand(input: "\t", modifierFlags: .control, action: #selector(BrowserViewController.nextTab), discoverabilityTitle: Strings.ShowNextTabTitle), UIKeyCommand(input: "\t", modifierFlags: [.control, .shift], action: #selector(BrowserViewController.previousTab), discoverabilityTitle: Strings.ShowPreviousTabTitle), ] #if DEBUG // in simulator, CMD+t is slow-mo animation return result + [ UIKeyCommand(input: "t", modifierFlags: [.command, .shift], action: #selector(BrowserViewController.newTab))] #else return result #endif } }
mpl-2.0
jarrroo/MarkupKitLint
Tools/Pods/Nimble/Sources/Nimble/Matchers/AsyncMatcherWrapper.swift
28
10966
import Foundation /// If you are running on a slower machine, it could be useful to increase the default timeout value /// or slow down poll interval. Default timeout interval is 1, and poll interval is 0.01. public struct AsyncDefaults { public static var Timeout: TimeInterval = 1 public static var PollInterval: TimeInterval = 0.01 } fileprivate func async<T>(style: ExpectationStyle, predicate: Predicate<T>, timeout: TimeInterval, poll: TimeInterval, fnName: String) -> Predicate<T> { return Predicate { actualExpression in let uncachedExpression = actualExpression.withoutCaching() let fnName = "expect(...).\(fnName)(...)" var lastPredicateResult: PredicateResult? let result = pollBlock( pollInterval: poll, timeoutInterval: timeout, file: actualExpression.location.file, line: actualExpression.location.line, fnName: fnName) { lastPredicateResult = try predicate.satisfies(uncachedExpression) return lastPredicateResult!.toBoolean(expectation: style) } switch result { case .completed: return lastPredicateResult! case .timedOut: return PredicateResult(status: .fail, message: lastPredicateResult!.message) case let .errorThrown(error): return PredicateResult(status: .fail, message: .fail("unexpected error thrown: <\(error)>")) case let .raisedException(exception): return PredicateResult(status: .fail, message: .fail("unexpected exception raised: \(exception)")) case .blockedRunLoop: return PredicateResult(status: .fail, message: lastPredicateResult!.message.appended(message: " (timed out, but main thread was unresponsive).")) case .incomplete: internalError("Reached .incomplete state for toEventually(...).") } } } // Deprecated internal struct AsyncMatcherWrapper<T, U>: Matcher where U: Matcher, U.ValueType == T { let fullMatcher: U let timeoutInterval: TimeInterval let pollInterval: TimeInterval init(fullMatcher: U, timeoutInterval: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval) { self.fullMatcher = fullMatcher self.timeoutInterval = timeoutInterval self.pollInterval = pollInterval } func matches(_ actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool { let uncachedExpression = actualExpression.withoutCaching() let fnName = "expect(...).toEventually(...)" let result = pollBlock( pollInterval: pollInterval, timeoutInterval: timeoutInterval, file: actualExpression.location.file, line: actualExpression.location.line, fnName: fnName) { try self.fullMatcher.matches(uncachedExpression, failureMessage: failureMessage) } switch result { case let .completed(isSuccessful): return isSuccessful case .timedOut: return false case let .errorThrown(error): failureMessage.stringValue = "an unexpected error thrown: <\(error)>" return false case let .raisedException(exception): failureMessage.stringValue = "an unexpected exception thrown: <\(exception)>" return false case .blockedRunLoop: failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)." return false case .incomplete: internalError("Reached .incomplete state for toEventually(...).") } } func doesNotMatch(_ actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool { let uncachedExpression = actualExpression.withoutCaching() let result = pollBlock( pollInterval: pollInterval, timeoutInterval: timeoutInterval, file: actualExpression.location.file, line: actualExpression.location.line, fnName: "expect(...).toEventuallyNot(...)") { try self.fullMatcher.doesNotMatch(uncachedExpression, failureMessage: failureMessage) } switch result { case let .completed(isSuccessful): return isSuccessful case .timedOut: return false case let .errorThrown(error): failureMessage.stringValue = "an unexpected error thrown: <\(error)>" return false case let .raisedException(exception): failureMessage.stringValue = "an unexpected exception thrown: <\(exception)>" return false case .blockedRunLoop: failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)." return false case .incomplete: internalError("Reached .incomplete state for toEventuallyNot(...).") } } } private let toEventuallyRequiresClosureError = FailureMessage(stringValue: "expect(...).toEventually(...) requires an explicit closure (eg - expect { ... }.toEventually(...) )\nSwift 1.2 @autoclosure behavior has changed in an incompatible way for Nimble to function") extension Expectation { /// Tests the actual value using a matcher to match by checking continuously /// at each pollInterval until the timeout is reached. /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toEventually(_ predicate: Predicate<T>, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) { nimblePrecondition(expression.isClosure, "NimbleInternalError", toEventuallyRequiresClosureError.stringValue) let (pass, msg) = execute( expression, .toMatch, async(style: .toMatch, predicate: predicate, timeout: timeout, poll: pollInterval, fnName: "toEventually"), to: "to eventually", description: description, captureExceptions: false ) verify(pass, msg) } /// Tests the actual value using a matcher to not match by checking /// continuously at each pollInterval until the timeout is reached. /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toEventuallyNot(_ predicate: Predicate<T>, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) { nimblePrecondition(expression.isClosure, "NimbleInternalError", toEventuallyRequiresClosureError.stringValue) let (pass, msg) = execute( expression, .toNotMatch, async(style: .toNotMatch, predicate: predicate, timeout: timeout, poll: pollInterval, fnName: "toEventuallyNot"), to: "to eventually not", description: description, captureExceptions: false ) verify(pass, msg) } /// Tests the actual value using a matcher to not match by checking /// continuously at each pollInterval until the timeout is reached. /// /// Alias of toEventuallyNot() /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toNotEventually(_ predicate: Predicate<T>, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) { return toEventuallyNot(predicate, timeout: timeout, pollInterval: pollInterval, description: description) } } // Deprecated extension Expectation { /// Tests the actual value using a matcher to match by checking continuously /// at each pollInterval until the timeout is reached. /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toEventually<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) where U: Matcher, U.ValueType == T { if expression.isClosure { let (pass, msg) = expressionMatches( expression, matcher: AsyncMatcherWrapper( fullMatcher: matcher, timeoutInterval: timeout, pollInterval: pollInterval), to: "to eventually", description: description ) verify(pass, msg) } else { verify(false, toEventuallyRequiresClosureError) } } /// Tests the actual value using a matcher to not match by checking /// continuously at each pollInterval until the timeout is reached. /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toEventuallyNot<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) where U: Matcher, U.ValueType == T { if expression.isClosure { let (pass, msg) = expressionDoesNotMatch( expression, matcher: AsyncMatcherWrapper( fullMatcher: matcher, timeoutInterval: timeout, pollInterval: pollInterval), toNot: "to eventually not", description: description ) verify(pass, msg) } else { verify(false, toEventuallyRequiresClosureError) } } /// Tests the actual value using a matcher to not match by checking /// continuously at each pollInterval until the timeout is reached. /// /// Alias of toEventuallyNot() /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toNotEventually<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) where U: Matcher, U.ValueType == T { return toEventuallyNot(matcher, timeout: timeout, pollInterval: pollInterval, description: description) } }
mit
radex/swift-compiler-crashes
crashes-fuzzing/06842-swift-removeshadoweddecls.swift
11
265
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class c{class a{protocol A{struct c>struct c:b class b}func g->{class c<T where B:a{struct B<T:C
mit
asm-products/automated-ios
Automated/ActivityAction.swift
1
334
// // ActivityAction.swift // Automated // // Created by Nick Babenko on 23/11/2014. // Copyright (c) 2014 Automated. All rights reserved. // import Foundation import CoreData class ActivityAction: NSManagedObject { @NSManaged var method: String @NSManaged var arguments: AnyObject @NSManaged var device: Device }
agpl-3.0
DeveloperPans/PSCarouselView
CarouselDemo/CarouselDemo/CarouselWithSwift/SwiftViewController.swift
1
1323
// // SwiftViewController.swift // CarouselDemo // // Created by Pan on 16/4/18. // Copyright © 2016年 Pan. All rights reserved. // import UIKit import PSCarouselView let IMAGE_URLSTRING0 = "http://img.hb.aicdn.com/0f14ad30f6c0b4e4cf96afcad7a0f9d6332e5b061b5f3c-uSUEUC_fw658" let IMAGE_URLSTRING1 = "http://img.hb.aicdn.com/3f9d1434ba618579d50ae8c8476087f1a04d7ee3169f8e-zD2u09_fw658" let IMAGE_URLSTRING2 = "http://img.hb.aicdn.com/81427fb53bed38bf1b6a0c5da1c5d5a485e00bd1149232-gn4CO1_fw658" let ScreenWidth = UIScreen.main.bounds.size.width class SwiftViewController: UIViewController { var carouselView: PSCarouselView = PSCarouselView() override func viewDidLoad() { super.viewDidLoad() automaticallyAdjustsScrollViewInsets = false setupCarouselView() view.addSubview(carouselView) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) carouselView.startMoving() } func setupCarouselView() { carouselView.frame = CGRect(x: 0,y: 64,width: ScreenWidth,height: 0.382 * ScreenWidth) carouselView.imageURLs = [IMAGE_URLSTRING0,IMAGE_URLSTRING1,IMAGE_URLSTRING2] carouselView.placeholder = UIImage(named: "placeholder") carouselView.isAutoMoving = true } }
mit
sbooth/SFBAudioEngine
Player/SFBAudioPlayer.swift
1
2746
// // Copyright (c) 2020 - 2022 Stephen F. Booth <me@sbooth.org> // Part of https://github.com/sbooth/SFBAudioEngine // MIT license // import Foundation extension AudioPlayer { /// Playback position information for `AudioPlayer` public typealias PlaybackPosition = AudioPlayerNode.PlaybackPosition /// Playback time information for `AudioPlayer` public typealias PlaybackTime = AudioPlayerNode.PlaybackTime /// Returns the frame position in the current decoder or `nil` if the current decoder is `nil` public var framePosition: AVAudioFramePosition? { let framePosition = __framePosition return framePosition == unknownFramePosition ? nil : framePosition } /// Returns the frame length of the current decoder or `nil` if the current decoder is `nil` public var frameLength: AVAudioFramePosition? { let frameLength = __frameLength return frameLength == unknownFrameLength ? nil : frameLength } /// Returns the playback position in the current decoder or `nil` if the current decoder is `nil` public var position: PlaybackPosition? { var position = SFBAudioPlayerPlaybackPosition() guard __getPlaybackPosition(&position, andTime: nil) else { return nil } return PlaybackPosition(position) } /// Returns the current time in the current decoder or `nil` if the current decoder is `nil` public var currentTime: TimeInterval? { let currentTime = __currentTime return currentTime == unknownTime ? nil : currentTime } /// Returns the total time of the current decoder or `nil` if the current decoder is `nil` public var totalTime: TimeInterval? { let totalTime = __totalTime return totalTime == unknownTime ? nil : totalTime } /// Returns the playback time in the current decoder or `nil` if the current decoder is `nil` public var time: PlaybackTime? { var time = SFBAudioPlayerPlaybackTime() guard __getPlaybackPosition(nil, andTime: &time) else { return nil } return PlaybackTime(time) } /// Returns the playback position and time in the current decoder or `nil` if the current decoder is `nil` public var positionAndTime: (position: PlaybackPosition, time: PlaybackTime)? { var position = SFBAudioPlayerPlaybackPosition() var time = SFBAudioPlayerPlaybackTime() guard __getPlaybackPosition(&position, andTime: &time) else { return nil } return (position: PlaybackPosition(position), time: PlaybackTime(time)) } } extension AudioPlayer.PlaybackState: CustomDebugStringConvertible { // A textual representation of this instance, suitable for debugging. public var debugDescription: String { switch self { case .playing: return ".playing" case .paused: return ".paused" case .stopped: return ".stopped" @unknown default: fatalError() } } }
mit
jlandon/Alexandria
Sources/Alexandria/ImageEffects/UIImage+Effects.swift
1
14492
/* File: UIImage+ImageEffects.m Abstract: This is a category of UIImage that adds methods to apply blur and tint effects to an image. This is the code you’ll want to look out to find out how to use vImage to efficiently calculate a blur. Version: 1.0 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2013 Apple Inc. All Rights Reserved. Copyright © 2013 Apple Inc. All rights reserved. WWDC 2013 License NOTE: This Apple Software was supplied by Apple as part of a WWDC 2013 Session. Please refer to the applicable WWDC 2013 Session for further information. IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. EA1002 5/3/2013 */ // // UIImage.swift // Today // // Created by Alexey Globchastyy on 15/09/14. // Copyright (c) 2014 Alexey Globchastyy. All rights reserved. // import UIKit import Accelerate extension UIImage { /** Applies a lightening (blur) effect to the image - returns: The lightened image, or nil if error. */ public func applyLightEffect() -> UIImage? { return applyBlur(withRadius: 30, tintColor: UIColor(white: 1.0, alpha: 0.3), saturationDeltaFactor: 1.0) } /** Applies an extra lightening (blur) effect to the image - returns: The extra lightened image, or nil if error. */ public func applyExtraLightEffect() -> UIImage? { return applyBlur(withRadius: 20, tintColor: UIColor(white: 0.97, alpha: 0.82), saturationDeltaFactor: 1.8) } /** Applies a darkening (blur) effect to the image. - returns: The darkened image, or nil if error. */ public func applyDarkEffect() -> UIImage? { return applyBlur(withRadius: 20, tintColor: UIColor(white: 0.11, alpha: 0.73), saturationDeltaFactor: 1.8) } /** Tints the image with the given color. - parameter tintColor: The tint color - returns: The tinted image, or nil if error. */ public func applyTintEffect(withColor tintColor: UIColor) -> UIImage? { let effectColorAlpha: CGFloat = 0.6 var effectColor = tintColor let componentCount = tintColor.cgColor.numberOfComponents if componentCount == 2 { var b: CGFloat = 0 if tintColor.getWhite(&b, alpha: nil) { effectColor = UIColor(white: b, alpha: effectColorAlpha) } } else { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 if tintColor.getRed(&red, green: &green, blue: &blue, alpha: nil) { effectColor = UIColor(red: red, green: green, blue: blue, alpha: effectColorAlpha) } } return applyBlur(withRadius: 10, tintColor: effectColor, saturationDeltaFactor: -1.0, maskImage: nil) } /** Core function to create a new image with the given blur. - parameter blurRadius: The blur radius - parameter tintColor: The color to tint the image; optional. - parameter saturationDeltaFactor: The delta by which to change the image saturation - parameter maskImage: An optional image mask. - returns: The adjusted image, or nil if error. */ public func applyBlur(withRadius blurRadius: CGFloat, tintColor: UIColor?, saturationDeltaFactor: CGFloat, maskImage: UIImage? = nil) -> UIImage? { // Check pre-conditions. guard size.width >= 1 && size.height >= 1 else { print("*** error: invalid size: \(size.width) x \(size.height). Both dimensions must be >= 1: \(self)") return nil } guard let cgImage = self.cgImage else { print("*** error: image must be backed by a CGImage: \(self)") return nil } if maskImage != nil && maskImage!.cgImage == nil { print("*** error: maskImage must be backed by a CGImage: \(String(describing: maskImage))") return nil } defer { UIGraphicsEndImageContext() } let epsilon = CGFloat(Float.ulpOfOne) let screenScale = UIScreen.main.scale let imageRect = CGRect(origin: .zero, size: size) var effectImage: UIImage? = self let hasBlur = blurRadius > epsilon let hasSaturationChange = abs(saturationDeltaFactor - 1.0) > epsilon if hasBlur || hasSaturationChange { func createEffectBuffer(_ context: CGContext) -> vImage_Buffer { let data = context.data let width = context.width let height = context.height let rowBytes = context.bytesPerRow return vImage_Buffer(data: data, height: UInt(height), width: UInt(width), rowBytes: rowBytes) } UIGraphicsBeginImageContextWithOptions(size, false, screenScale) guard let effectInContext = UIGraphicsGetCurrentContext() else { return self } effectInContext.scaleBy(x: 1, y: -1) effectInContext.translateBy(x: 0, y: -size.height) effectInContext.draw(cgImage, in: imageRect) var effectInBuffer = createEffectBuffer(effectInContext) UIGraphicsBeginImageContextWithOptions(size, false, screenScale) guard let effectOutContext = UIGraphicsGetCurrentContext() else { return self } var effectOutBuffer = createEffectBuffer(effectOutContext) if hasBlur { // A description of how to compute the box kernel width from the Gaussian // radius (aka standard deviation) appears in the SVG spec: // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement // // For larger values of 's' (s >= 2.0), an approximation can be used: Three // successive box-blurs build a piece-wise quadratic convolution kernel, which // approximates the Gaussian kernel to within roughly 3%. // // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) // // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel. // let inputRadius = blurRadius * screenScale let input = inputRadius * 3 * sqrt(2 * .pi) / 4 + 0.5 var radius = UInt32(floor(input)) if radius % 2 != 1 { radius += 1 // force radius to be odd so that the three box-blur methodology works. } let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend) vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) } var effectImageBuffersAreSwapped = false if hasSaturationChange { let s: CGFloat = saturationDeltaFactor let floatingPointSaturationMatrix: [CGFloat] = [ 0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0, 0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0, 0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0, 0, 0, 0, 1 ] let divisor: CGFloat = 256 let saturationMatrix = floatingPointSaturationMatrix.map { Int16(round($0) * divisor) } if hasBlur { vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags)) effectImageBuffersAreSwapped = true } else { vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags)) } } if !effectImageBuffersAreSwapped { effectImage = UIGraphicsGetImageFromCurrentImageContext() } UIGraphicsEndImageContext() if effectImageBuffersAreSwapped { effectImage = UIGraphicsGetImageFromCurrentImageContext() } UIGraphicsEndImageContext() } // Set up output context. UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let outputContext = UIGraphicsGetCurrentContext() outputContext?.scaleBy(x: 1, y: -1) outputContext?.translateBy(x: 0, y: -size.height) // Draw base image. outputContext?.draw(cgImage, in: imageRect) // Draw effect image. if let effectImage = effectImage?.cgImage, hasBlur { outputContext?.saveGState() if let image = maskImage?.cgImage { outputContext?.clip(to: imageRect, mask: image) } outputContext?.draw(effectImage, in: imageRect) outputContext?.restoreGState() } // Add in color tint. if let color = tintColor { outputContext?.saveGState() outputContext?.setFillColor(color.cgColor) outputContext?.fill(imageRect) outputContext?.restoreGState() } // Output image is ready. return UIGraphicsGetImageFromCurrentImageContext() } }
mit
Rag0n/QuNotes
QuNotes/Library/LibraryViewController.swift
1
4906
// // LibraryViewController.swift // QuNotes // // Created by Alexander Guschin on 21.09.17. // Copyright © 2017 Alexander Guschin. All rights reserved. // import UIKit import Prelude final public class LibraryViewController: UIViewController { public func perform(effect: Library.ViewEffect) { switch effect { case .updateAllNotebooks(let notebooks): self.notebooks = notebooks tableView.reloadData() case .addNotebook(let index, let notebooks): self.notebooks = notebooks let indexPath = IndexPath(row: index, section: 0) tableView.insertRows(at: [indexPath], with: .automatic) case .deleteNotebook(let index, let notebooks): self.notebooks = notebooks let indexPath = IndexPath(row: index, section: 0) tableView.deleteRows(at: [indexPath], with: .automatic) } } public init(withDispatch dispatch: @escaping Library.ViewDispacher) { self.dispatch = dispatch super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func loadView() { view = UIView() view.flex.alignItems(.center).define { $0.addItem(tableView).grow(1) $0.addItem(addButton).position(.absolute).bottom(20) } navigationItem.title = "library_title".localized tableView.dataSource = self tableView.delegate = self } override public func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() view.flex.layout() } override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) guard traitCollection.preferredContentSizeCategory != previousTraitCollection?.preferredContentSizeCategory else { return } addButton.flex.markDirty() } // MARK: - Private fileprivate enum Constants { static let estimatedCellHeight: CGFloat = 44 static let libraryCellReuseIdentifier = "libraryCellReuseIdentifier" } fileprivate var notebooks: [Library.NotebookViewModel] = [] fileprivate var dispatch: Library.ViewDispacher private let tableView: UITableView = { let t = UITableView() LibraryTableViewCell.registerFor(tableView: t, reuseIdentifier: Constants.libraryCellReuseIdentifier) let theme = AppEnvironment.current.theme t.backgroundColor = theme.ligherDarkColor t.separatorColor = theme.textColor.withAlphaComponent(0.5) t.estimatedRowHeight = Constants.estimatedCellHeight return t }() private let addButton: UIButton = { let b = UIButton(type: .system) b.setTitle("library_add_notebook_button".localized, for: .normal) b.titleLabel!.font = UIFont.preferredFont(forTextStyle: .headline) b.titleLabel!.adjustsFontForContentSizeCategory = true b.addTarget(self, action: #selector(addNotebookButtonDidTap), for: .touchUpInside) return b }() @objc private func addNotebookButtonDidTap() { dispatch <| .addNotebook } } // MARK: - UITableViewDataSource extension LibraryViewController: UITableViewDataSource { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return notebooks.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: Constants.libraryCellReuseIdentifier, for: indexPath) as! LibraryTableViewCell cell.render(viewModel: notebooks[indexPath.row]) return cell } } // MARK: - UITableViewDelegate extension LibraryViewController: UITableViewDelegate { public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { dispatch <| .selectNotebook(index: indexPath.row) tableView.deselectRow(at: indexPath, animated: true) } public func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let deleteAction = deleteContextualAction(forIndexPath: indexPath) let configuration = UISwipeActionsConfiguration(actions: [deleteAction]) return configuration } private func deleteContextualAction(forIndexPath indexPath: IndexPath) -> UIContextualAction { let action = UIContextualAction(style: .destructive, title: "library_delete_notebook_button".localized) { [unowned self] (action, view, success) in self.dispatch <| .deleteNotebook(index: indexPath.row) success(true) } action.backgroundColor = .red return action } }
gpl-3.0
wenghengcong/Coderpursue
BeeFun/BeeFun/ToolKit/JSToolKit/JSFoundation/JSObject.swift
1
436
// // JSObject.swift // LoveYou // // Created by WengHengcong on 2017/2/27. // Copyright © 2017年 JungleSong. All rights reserved. // import UIKit import ObjectMapper class JSObject: NSObject, Mappable { var version: Int? override init() { super.init() version = 1 } required init?(map: Map) { } // Mappable func mapping(map: Map) { version <- map["version"] } }
mit
LouisZhu/Gatling
Gatling/Classes/TimeStrategy.swift
1
2939
// // TimeStrategy.swift // // Copyright (c) 2016 Louis Zhu (http://github.com/LouisZhu) // // 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 private struct TimeBaseInfo { static let timebase_info: mach_timebase_info_data_t = { var info = mach_timebase_info_data_t() mach_timebase_info(&info) return info }() static var denom: UInt32 { return timebase_info.denom } static var numer: UInt32 { return timebase_info.numer } } private func gatling_time_absolute_to_nanoseconds(absoluteTime: UInt64) -> UInt64 { return absoluteTime * UInt64(TimeBaseInfo.numer) / UInt64(TimeBaseInfo.denom) } private func gatling_time_nanoseconds_to_absolute(nanoseconds: UInt64) -> UInt64 { return nanoseconds * UInt64(TimeBaseInfo.denom) / UInt64(TimeBaseInfo.numer) } internal func gatling_dispatch_when(when: UInt64, _ queue: dispatch_queue_t, _ block: dispatch_block_t) { let now = mach_absolute_time() if when < now { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), queue, block) return } let delta = gatling_time_absolute_to_nanoseconds(when - now) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delta)), queue, block) } internal class TimeStrategy { private let startTime: UInt64 private let timeInterval: NSTimeInterval private(set) var nextFireTime: UInt64 init(timeInterval: NSTimeInterval) { let now = mach_absolute_time() self.startTime = now self.timeInterval = timeInterval self.nextFireTime = now self.updateNextFireTime() } internal func updateNextFireTime() { let delta = gatling_time_nanoseconds_to_absolute(UInt64(self.timeInterval * Double(NSEC_PER_SEC))) self.nextFireTime = self.nextFireTime + delta } }
mit
jacobwhite/firefox-ios
Client/Frontend/Browser/ButtonToast.swift
1
6969
/* 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 Shared import SnapKit struct ButtonToastUX { static let ToastPadding = 15.0 static let TitleSpacing = 2.0 static let ToastButtonPadding: CGFloat = 10.0 static let TitleButtonPadding: CGFloat = 5.0 static let ToastDelay = DispatchTimeInterval.milliseconds(900) static let ToastButtonBorderRadius: CGFloat = 5 static let ToastButtonBorderWidth: CGFloat = 1 } private class HighlightableButton: UIButton { override var isHighlighted: Bool { didSet { self.backgroundColor = isHighlighted ? .white : .clear } } } class ButtonToast: UIView { fileprivate var dismissed = false fileprivate var completionHandler: ((Bool) -> Void)? fileprivate lazy var toast: UIView = { let toast = UIView() toast.backgroundColor = SimpleToastUX.ToastDefaultColor return toast }() fileprivate var animationConstraint: Constraint? fileprivate lazy var gestureRecognizer: UITapGestureRecognizer = { let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap)) gestureRecognizer.cancelsTouchesInView = false return gestureRecognizer }() init(labelText: String, descriptionText: String? = nil, buttonText: String, completion:@escaping (_ buttonPressed: Bool) -> Void) { super.init(frame: .zero) completionHandler = completion self.clipsToBounds = true self.addSubview(createView(labelText, descriptionText: descriptionText, buttonText: buttonText)) toast.snp.makeConstraints { make in make.left.right.height.equalTo(self) animationConstraint = make.top.equalTo(self).offset(SimpleToastUX.ToastHeight).constraint } self.snp.makeConstraints { make in make.height.equalTo(SimpleToastUX.ToastHeight) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func createView(_ labelText: String, descriptionText: String?, buttonText: String) -> UIView { let label = UILabel() label.textColor = UIColor.white label.font = SimpleToastUX.ToastFont label.text = labelText label.lineBreakMode = .byWordWrapping label.numberOfLines = 0 toast.addSubview(label) let button = HighlightableButton() button.layer.cornerRadius = ButtonToastUX.ToastButtonBorderRadius button.layer.borderWidth = ButtonToastUX.ToastButtonBorderWidth button.layer.borderColor = UIColor.white.cgColor button.setTitle(buttonText, for: []) button.setTitleColor(self.toast.backgroundColor, for: .highlighted) button.titleLabel?.font = SimpleToastUX.ToastFont button.titleLabel?.numberOfLines = 1 button.titleLabel?.lineBreakMode = .byClipping button.titleLabel?.adjustsFontSizeToFitWidth = true button.titleLabel?.minimumScaleFactor = 0.1 let recognizer = UITapGestureRecognizer(target: self, action: #selector(buttonPressed)) button.addGestureRecognizer(recognizer) toast.addSubview(button) var descriptionLabel: UILabel? if let text = descriptionText { let textLabel = UILabel() textLabel.textColor = UIColor.white textLabel.font = SimpleToastUX.ToastFont textLabel.text = text textLabel.lineBreakMode = .byTruncatingTail toast.addSubview(textLabel) descriptionLabel = textLabel } if let description = descriptionLabel { label.numberOfLines = 1 // if showing a description we cant wrap to the second line label.lineBreakMode = .byClipping label.adjustsFontSizeToFitWidth = true label.snp.makeConstraints { (make) in make.leading.equalTo(toast).offset(ButtonToastUX.ToastPadding) make.top.equalTo(toast).offset(ButtonToastUX.TitleButtonPadding) make.trailing.equalTo(button.snp.leading).offset(-ButtonToastUX.TitleButtonPadding) } description.snp.makeConstraints { (make) in make.leading.equalTo(toast).offset(ButtonToastUX.ToastPadding) make.top.equalTo(label.snp.bottom).offset(ButtonToastUX.TitleSpacing) make.trailing.equalTo(button.snp.leading).offset(-ButtonToastUX.TitleButtonPadding) } } else { label.snp.makeConstraints { (make) in make.leading.equalTo(toast).offset(ButtonToastUX.ToastPadding) make.centerY.equalTo(toast) make.trailing.equalTo(button.snp.leading).offset(-ButtonToastUX.TitleButtonPadding) } } button.snp.makeConstraints { (make) in make.trailing.equalTo(toast).offset(-ButtonToastUX.ToastPadding) make.centerY.equalTo(toast) make.width.equalTo(button.titleLabel!.intrinsicContentSize.width + 2*ButtonToastUX.ToastButtonPadding) } return toast } fileprivate func dismiss(_ buttonPressed: Bool) { guard dismissed == false else { return } dismissed = true superview?.removeGestureRecognizer(gestureRecognizer) UIView.animate(withDuration: SimpleToastUX.ToastAnimationDuration, animations: { self.animationConstraint?.update(offset: SimpleToastUX.ToastHeight) self.layoutIfNeeded() }, completion: { finished in self.removeFromSuperview() if !buttonPressed { self.completionHandler?(false) } } ) } func showToast(duration: DispatchTimeInterval = SimpleToastUX.ToastDismissAfter) { layoutIfNeeded() UIView.animate(withDuration: SimpleToastUX.ToastAnimationDuration, animations: { self.animationConstraint?.update(offset: 0) self.layoutIfNeeded() }, completion: { finished in DispatchQueue.main.asyncAfter(deadline: .now() + duration) { self.dismiss(false) } } ) } @objc func buttonPressed(_ gestureRecognizer: UIGestureRecognizer) { self.completionHandler?(true) self.dismiss(true) } override func didMoveToSuperview() { super.didMoveToSuperview() superview?.addGestureRecognizer(gestureRecognizer) } @objc func handleTap(_ gestureRecognizer: UIGestureRecognizer) { dismiss(false) } }
mpl-2.0
wu890608/wu89
wu89/wu89/Classes/Tools/Common.swift
1
214
// // Common.swift // wu89 // // Created by wu on 2017/6/17. // Copyright © 2017年 wu. All rights reserved. // import UIKit let sWidth = UIScreen.main.bounds.width let sHeight = UIScreen.main.bounds.height
mit
syoung-smallwisdom/ResearchUXFactory-iOS
ResearchUXFactoryTests/ConsentTests.swift
1
3945
// // SBAConsentDocumentFactoryTests.swift // ResearchUXFactory // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import XCTest @testable import ResearchUXFactory class SBAConsentDocumentFactoryTests: ResourceTestCase { 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 testBuildConsentFactory() { guard let consentFactory = createConsentFactory() else { return } XCTAssertNotNil(consentFactory.steps) guard let steps = consentFactory.steps else { return } let expectedSteps: [ORKStep] = [SBAInstructionStep(identifier: "reconsentIntroduction"), ORKVisualConsentStep(identifier: "consentVisual"), SBANavigationSubtaskStep(identifier: "consentQuiz"), SBAInstructionStep(identifier: "consentFailedQuiz"), SBAInstructionStep(identifier: "consentPassedQuiz"), ORKConsentSharingStep(identifier: "consentSharingOptions"), ORKConsentReviewStep(identifier: "consentReview"), SBAInstructionStep(identifier: "consentCompletion")] XCTAssertEqual(steps.count, expectedSteps.count) for (idx, expectedStep) in expectedSteps.enumerated() { if idx < steps.count { XCTAssertEqual(steps[idx].identifier, expectedStep.identifier) let stepClass = NSStringFromClass(steps[idx].classForCoder) let expectedStepClass = NSStringFromClass(expectedStep.classForCoder) XCTAssertEqual(stepClass, expectedStepClass) } } if (steps.count < expectedSteps.count) { return } } // MARK: helper methods func createConsentFactory() -> SBABaseSurveyFactory? { guard let input = jsonForResource("Consent") else { return nil } return SBABaseSurveyFactory(dictionary: input) } }
bsd-3-clause
migue1s/habitica-ios
HabitRPG/TableviewCells/SubscriptionOptionView.swift
2
1115
// // SubscriptionOptionView.swift // Habitica // // Created by Phillip Thelen on 07/02/2017. // Copyright © 2017 Phillip Thelen. All rights reserved. // import UIKit class SubscriptionOptionView: UITableViewCell { //swiftlint:disable private_outlet @IBOutlet weak var selectionView: UIImageView! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! //swiftlint:enable private_outlet override func setSelected(_ selected: Bool, animated: Bool) { let animDuration = 0.3 if selected { UIView.animate(withDuration: animDuration, animations: {[weak self] () in self?.selectionView.backgroundColor = .purple300() self?.selectionView.image = #imageLiteral(resourceName: "circle_selected") }) } else { UIView.animate(withDuration: animDuration, animations: {[weak self] () in self?.selectionView.backgroundColor = .purple600() self?.selectionView.image = #imageLiteral(resourceName: "circle_unselected") }) } } }
gpl-3.0
narner/AudioKit
AudioKit/Common/Nodes/Effects/Reverb/Flat Frequency Response Reverb/AKFlatFrequencyResponseReverb.swift
1
4133
// // AKFlatFrequencyResponseReverb.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // /// This filter reiterates the input with an echo density determined by loop /// time. The attenuation rate is independent and is determined by the /// reverberation time (defined as the time in seconds for a signal to decay to /// 1/1000, or 60dB down from its original amplitude). Output will begin to /// appear immediately. /// open class AKFlatFrequencyResponseReverb: AKNode, AKToggleable, AKComponent, AKInput { public typealias AKAudioUnitType = AKFlatFrequencyResponseReverbAudioUnit /// Four letter unique description of the node public static let ComponentDescription = AudioComponentDescription(effect: "alps") // MARK: - Properties private var internalAU: AKAudioUnitType? private var token: AUParameterObserverToken? fileprivate var reverbDurationParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change @objc open dynamic var rampTime: Double = AKSettings.rampTime { willSet { internalAU?.rampTime = newValue } } /// The duration in seconds for a signal to decay to 1/1000, or 60dB down from its original amplitude. @objc open dynamic var reverbDuration: Double = 0.5 { willSet { if reverbDuration != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { reverbDurationParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.reverbDuration = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) @objc open dynamic var isStarted: Bool { return internalAU?.isPlaying() ?? false } // MARK: - Initialization /// Initialize this reverb node /// /// - Parameters: /// - input: Input node to process /// - reverbDuration: The duration in seconds for a signal to decay to 1/1000, /// or 60dB down from its original amplitude. /// - loopDuration: The loop duration of the filter, in seconds. This can also be thought of as the /// delay time or “echo density” of the reverberation. /// @objc public init( _ input: AKNode? = nil, reverbDuration: Double = 0.5, loopDuration: Double = 0.1) { self.reverbDuration = reverbDuration _Self.register() super.init() AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in self?.avAudioNode = avAudioUnit self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType input?.connect(to: self!) if let au = self?.internalAU { au.setLoopDuration(Float(loopDuration)) } } guard let tree = internalAU?.parameterTree else { AKLog("Parameter Tree Failed") return } reverbDurationParameter = tree["reverbDuration"] token = tree.token(byAddingParameterObserver: { [weak self] _, _ in guard let _ = self else { AKLog("Unable to create strong reference to self") return } // Replace _ with strongSelf if needed DispatchQueue.main.async { // This node does not change its own values so we won't add any // value observing, but if you need to, this is where that goes. } }) internalAU?.reverbDuration = Float(reverbDuration) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing @objc open func start() { internalAU?.start() } /// Function to stop or bypass the node, both are equivalent @objc open func stop() { internalAU?.stop() } }
mit
SeaHub/ImgTagging
ImgTagger/ImgTagger/AuthenticationViewController.swift
1
10340
// // AuthenticationViewController.swift // ImgTagger // // Created by SeaHub on 2017/6/29. // Copyright © 2017年 SeaCluster. All rights reserved. // import UIKit import NotificationBannerSwift import NVActivityIndicatorView enum AMLoginSignupViewMode { case login case signup } class AuthenticationViewController: UIViewController { let animationDuration = 0.25 var mode: AMLoginSignupViewMode = .signup // MARK: - Constraints @IBOutlet weak var backImageLeftConstraint: NSLayoutConstraint! @IBOutlet weak var backImageBottomConstraint: NSLayoutConstraint! @IBOutlet weak var loginView: UIView! @IBOutlet weak var loginContentView: UIView! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var loginButtonVerticalCenterConstraint: NSLayoutConstraint! @IBOutlet weak var loginButtonTopConstraint: NSLayoutConstraint! @IBOutlet weak var loginWidthConstraint: NSLayoutConstraint! @IBOutlet weak var signupView: UIView! @IBOutlet weak var signupContentView: UIView! @IBOutlet weak var signupButton: UIButton! @IBOutlet weak var signupButtonVerticalCenterConstraint: NSLayoutConstraint! @IBOutlet weak var signupButtonTopConstraint: NSLayoutConstraint! @IBOutlet weak var logoView: UIView! @IBOutlet weak var logoTopConstraint: NSLayoutConstraint! @IBOutlet weak var logoHeightConstraint: NSLayoutConstraint! @IBOutlet weak var logoBottomConstraint: NSLayoutConstraint! @IBOutlet weak var logoButtomInSingupConstraint: NSLayoutConstraint! @IBOutlet weak var logoCenterConstraint: NSLayoutConstraint! @IBOutlet weak var forgotPassTopConstraint: NSLayoutConstraint! @IBOutlet weak var socialsView: UIView! @IBOutlet weak var loginEmailInputView: AMInputView! @IBOutlet weak var loginPasswordInputView: AMInputView! @IBOutlet weak var signupEmailInputView: AMInputView! @IBOutlet weak var signupPasswordInputView: AMInputView! @IBOutlet weak var signupPasswordConfirmInputView: AMInputView! @IBOutlet weak var maskView: UIView! @IBOutlet weak var sendVcodeButton: UIButton! private var indicator: NVActivityIndicatorView! = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 100, height: 100), type: .ballTrianglePath, color: .white, padding: nil) // MARK: - controller override func viewDidLoad() { super.viewDidLoad() configureIndicator() toggleViewMode(animated: false) NotificationCenter.default.addObserver(self, selector: #selector(keyboarFrameChange(notification:)), name: .UIKeyboardWillChangeFrame, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - button actions @IBAction func loginButtonTouchUpInside(_ sender: AnyObject) { if mode == .signup { toggleViewMode(animated: true) } else { self.indicatorStartAnimating() APIManager.login(username: loginEmailInputView.textFieldView.text!, password: loginPasswordInputView.textFieldView.text!, success: { (user) in self.indicatorStopAnimating() let homeViewController = ImgTaggerUtil.mainStoryborad.instantiateViewController(withIdentifier: ConstantStroyboardIdentifier.kHomeViewControllerIdentifier) let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.window?.rootViewController = homeViewController UserDefaults.standard.setValue(user.token, forKey: AppConstant.kUserTokenIdentifier) }) { (error) in self.indicatorStopAnimating() let banner = StatusBarNotificationBanner(title: "An error occurer, please retry later!", style: .danger) banner.show() } } } @IBAction func signupButtonTouchUpInside(_ sender: AnyObject) { if mode == .login { toggleViewMode(animated: true) } else { self.indicatorStartAnimating() APIManager.register(username: signupEmailInputView.textFieldView.text!, password: signupPasswordInputView.textFieldView.text!, email: nil, vcode: signupPasswordConfirmInputView.textFieldView.text!, success: { self.indicatorStopAnimating() self.toggleViewMode(animated: true) }, failure: { (error) in self.indicatorStopAnimating() let banner = StatusBarNotificationBanner(title: "An error occurer, please retry later!", style: .danger) banner.show() }) } } // MARK: - toggle view func toggleViewMode(animated:Bool){ mode = mode == .login ? .signup:.login backImageLeftConstraint.constant = mode == .login ? 0 : -self.view.frame.size.width loginWidthConstraint.isActive = mode == .signup ? true : false logoCenterConstraint.constant = (mode == .login ? -1:1) * (loginWidthConstraint.multiplier * self.view.frame.size.width) / 2 loginButtonVerticalCenterConstraint.priority = mode == .login ? 300 : 900 signupButtonVerticalCenterConstraint.priority = mode == .signup ? 300 : 900 // animate self.view.endEditing(true) UIView.animate(withDuration:animated ? animationDuration:0) { // animate constraints self.view.layoutIfNeeded() // hide or show views self.loginContentView.alpha = self.mode == .login ? 1 : 0 self.signupContentView.alpha = self.mode == .signup ? 1 : 0 // rotate and scale login button let scaleLogin: CGFloat = self.mode == .login ? 1 : 0.4 let rotateAngleLogin: CGFloat = self.mode == .login ? 0 : CGFloat(-CGFloat.pi / 2) var transformLogin = CGAffineTransform(scaleX: scaleLogin, y: scaleLogin) transformLogin = transformLogin.rotated(by: rotateAngleLogin) self.loginButton.transform = transformLogin // rotate and scale signup button let scaleSignup:CGFloat = self.mode == .signup ? 1:0.4 let rotateAngleSignup:CGFloat = self.mode == .signup ? 0:CGFloat(-CGFloat.pi / 2) var transformSignup = CGAffineTransform(scaleX: scaleSignup, y: scaleSignup) transformSignup = transformSignup.rotated(by: rotateAngleSignup) self.signupButton.transform = transformSignup } } // MARK: - keyboard func keyboarFrameChange(notification: NSNotification) { let userInfo = notification.userInfo as! [String: AnyObject] // get top of keyboard in view let topOfKetboard = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue .origin.y // get animation curve for animate view like keyboard animation var animationDuration: TimeInterval = 0.25 var animationCurve: UIViewAnimationCurve = .easeOut if let animDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber { animationDuration = animDuration.doubleValue } if let animCurve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber { animationCurve = UIViewAnimationCurve.init(rawValue: animCurve.intValue)! } // check keyboard is showing let keyboardShow = topOfKetboard != self.view.frame.size.height //hide logo in little devices let hideLogo = self.view.frame.size.height < 667 // set constraints backImageBottomConstraint.constant = self.view.frame.size.height - topOfKetboard logoTopConstraint.constant = keyboardShow ? (hideLogo ? 0:20):50 logoHeightConstraint.constant = keyboardShow ? (hideLogo ? 0:40):60 logoBottomConstraint.constant = keyboardShow ? 20:32 logoButtomInSingupConstraint.constant = keyboardShow ? 20:32 forgotPassTopConstraint.constant = keyboardShow ? 30:45 loginButtonTopConstraint.constant = keyboardShow ? 25:30 signupButtonTopConstraint.constant = keyboardShow ? 23:35 loginButton.alpha = keyboardShow ? 1:0.7 signupButton.alpha = keyboardShow ? 1:0.7 // animate constraints changes UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(animationDuration) UIView.setAnimationCurve(animationCurve) self.view.layoutIfNeeded() UIView.commitAnimations() } // MARK: - hide status bar override var prefersStatusBarHidden: Bool { return true } // MARK: - Custom private func indicatorStartAnimating() { UIView.animate(withDuration: 0.5) { self.maskView.alpha = 0.5 } } private func indicatorStopAnimating() { UIView.animate(withDuration: 0.5) { self.maskView.alpha = 0 self.indicator.stopAnimating() } } private func configureIndicator() { self.indicator.center = CGPoint(x: self.view.bounds.width / 2, y: self.view.bounds.height / 2) self.maskView.addSubview(self.indicator) self.indicator.startAnimating() } @IBAction func sendVCodeButtonClicked(_ sender: Any) { if mode == .login { toggleViewMode(animated: true) } else { APIManager.getVCode(phone: signupEmailInputView.textFieldView.text!, success: { self.indicatorStopAnimating() self.sendVcodeButton.isHidden = true }) { (error) in self.indicatorStopAnimating() let banner = StatusBarNotificationBanner(title: "An error occurer, please retry later!", style: .danger) banner.show() } } } }
gpl-3.0
goldenplan/Pattern-on-Swift
AstractFactory/AstractFactory/AbstractBottle.swift
1
334
// // AbstractBottle.swift // StateMashine // // Created by Snake on 14/07/2017. // Copyright © 2017 Snake. All rights reserved. // import UIKit class AbstractBottle: NSObject { var label:String? override init() { super.init() label = String(describing: type(of: self)) } }
mit
MegaBits/SelfieBits
SelfieBits/Stickers/StickerCellView.swift
1
3369
// // StickerCellView.swift // SelfieBits // // Created by Patrick Perini on 12/21/14. // Copyright (c) 2014 megabits. All rights reserved. // import UIKit class StickerCellView: UICollectionViewCell { // MARK: Classes internal struct Position { var originalCenter: CGPoint = CGPointZero var lastCenter: CGPoint = CGPointZero var originalSuperView: UIView var photoView: UIView func overView(view: UIView?) -> Bool { var viewFrame = self.photoView.convertRect(view?.frame ?? CGRectZero, fromView: view) return CGRectContainsPoint(viewFrame, self.lastCenter) } } // MARK: Properties @IBOutlet var imageView: UIImageView? var photoView: UIImageView? private lazy var longPressGestureRecognizer: UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressGestureRecognized:") private var position: Position? override func awakeFromNib() { // Add long press gesture recognizer self.longPressGestureRecognizer.allowableMovement = CGFloat.max self.longPressGestureRecognizer.minimumPressDuration = 0.10 self.addGestureRecognizer(self.longPressGestureRecognizer) } func longPressGestureRecognized(gestureRecognizer: UIGestureRecognizer) { switch (gestureRecognizer.state) { case UIGestureRecognizerState.Began: // Pick up var position = Position(originalCenter: self.center, lastCenter: self.center, originalSuperView: self.superview!, photoView: self.photoView!) self.layer.shadowColor = UIColor.blackColor().CGColor self.layer.shadowRadius = 1.0 self.layer.shadowOpacity = 0.50 self.layer.shadowOffset = CGSizeZero self.photoView?.addSubview(self) self.transform = CGAffineTransformMakeScale(1.25, 1.25) position.lastCenter = self.photoView!.convertPoint(self.center, fromView: position.originalSuperView) self.center = position.lastCenter self.position = position case UIGestureRecognizerState.Changed: // Drag if var position = self.position { position.lastCenter = gestureRecognizer.locationInView(self.superview) self.center = position.lastCenter self.position = position } case UIGestureRecognizerState.Ended, UIGestureRecognizerState.Cancelled: // Put down if var position = self.position { self.transform = CGAffineTransformIdentity self.center = position.originalCenter position.originalSuperView.addSubview(self) self.layer.shadowOpacity = 0.00 if position.overView(self.photoView) { var newImageView: StickerView = StickerView(imageView: self.imageView!) newImageView.center = position.lastCenter self.photoView?.addSubview(newImageView) } self.position = nil } default: break } } }
mit
milseman/swift
test/stdlib/Renames.swift
4
46302
// RUN: %target-typecheck-verify-swift func _Algorithm<I : IteratorProtocol, S : Sequence>(i: I, s: S) { func fn1(_: EnumerateGenerator<I>) {} // expected-error {{'EnumerateGenerator' has been renamed to 'EnumeratedIterator'}} {{15-33=EnumeratedIterator}} {{none}} func fn2(_: EnumerateSequence<S>) {} // expected-error {{'EnumerateSequence' has been renamed to 'EnumeratedSequence'}} {{15-32=EnumeratedSequence}} {{none}} _ = EnumeratedIterator(i) // expected-error {{use the 'enumerated()' method on the sequence}} {{none}} _ = EnumeratedSequence(s) // expected-error {{use the 'enumerated()' method on the sequence}} {{none}} } func _Arrays<T>(e: T) { // _ = ContiguousArray(count: 1, repeatedValue: e) // xpected-error {{Please use init(repeating:count:) instead}} {{none}} // _ = ArraySlice(count: 1, repeatedValue: e) // xpected-error {{Please use init(repeating:count:) instead}} {{none}} // _ = Array(count: 1, repeatedValue: e) // xpected-error {{Please use init(repeating:count:) instead}} {{none}} // The actual error is: {{argument 'repeatedValue' must precede argument 'count'}} var a = ContiguousArray<T>() _ = a.removeAtIndex(0) // expected-error {{'removeAtIndex' has been renamed to 'remove(at:)'}} {{9-22=remove}} {{23-23=at: }} {{none}} _ = a.replaceRange(0..<1, with: []) // expected-error {{'replaceRange(_:with:)' has been renamed to 'replaceSubrange(_:with:)'}} {{9-21=replaceSubrange}} {{none}} _ = a.appendContentsOf([]) // expected-error {{'appendContentsOf' has been renamed to 'append(contentsOf:)'}} {{9-25=append}} {{26-26=contentsOf: }} {{none}} var b = ArraySlice<T>() _ = b.removeAtIndex(0) // expected-error {{'removeAtIndex' has been renamed to 'remove(at:)'}} {{9-22=remove}} {{23-23=at: }} {{none}} _ = b.replaceRange(0..<1, with: []) // expected-error {{'replaceRange(_:with:)' has been renamed to 'replaceSubrange(_:with:)'}} {{9-21=replaceSubrange}} {{none}} _ = b.appendContentsOf([]) // expected-error {{'appendContentsOf' has been renamed to 'append(contentsOf:)'}} {{9-25=append}} {{26-26=contentsOf: }} {{none}} var c = Array<T>() _ = c.removeAtIndex(0) // expected-error {{'removeAtIndex' has been renamed to 'remove(at:)'}} {{9-22=remove}} {{23-23=at: }} {{none}} _ = c.replaceRange(0..<1, with: []) // expected-error {{'replaceRange(_:with:)' has been renamed to 'replaceSubrange(_:with:)'}} {{9-21=replaceSubrange}} {{none}} _ = c.appendContentsOf([]) // expected-error {{'appendContentsOf' has been renamed to 'append(contentsOf:)'}} {{9-25=append}} {{26-26=contentsOf: }} {{none}} } func _Builtin(o: AnyObject, oo: AnyObject?) { _ = unsafeAddressOf(o) // expected-error {{Removed in Swift 3. Use Unmanaged.passUnretained(x).toOpaque() instead.}} {{none}} _ = unsafeAddress(of: o) // expected-error {{Removed in Swift 3. Use Unmanaged.passUnretained(x).toOpaque() instead.}} {{none}} _ = unsafeUnwrap(oo) // expected-error {{Removed in Swift 3. Please use Optional.unsafelyUnwrapped instead.}} {{none}} } func _CString() { _ = String.fromCString([]) // expected-error {{'fromCString' is unavailable: Please use String.init?(validatingUTF8:) instead. Note that it no longer accepts NULL as a valid input. Also consider using String(cString:), that will attempt to repair ill-formed code units.}} {{none}} _ = String.fromCStringRepairingIllFormedUTF8([]) // expected-error {{'fromCStringRepairingIllFormedUTF8' is unavailable: Please use String.init(cString:) instead. Note that it no longer accepts NULL as a valid input. See also String.decodeCString if you need more control.}} {{none}} } func _CTypes<T>(x: Unmanaged<T>) { func fn(_: COpaquePointer) {} // expected-error {{'COpaquePointer' has been renamed to 'OpaquePointer'}} {{14-28=OpaquePointer}} {{none}} _ = OpaquePointer(bitPattern: x) // expected-error {{'init(bitPattern:)' is unavailable: use 'Unmanaged.toOpaque()' instead}} {{none}} } func _ClosedRange(x: ClosedRange<Int>) { _ = x.startIndex // expected-error {{'startIndex' has been renamed to 'lowerBound'}} {{9-19=lowerBound}} {{none}} _ = x.endIndex // expected-error {{'endIndex' has been renamed to 'upperBound'}} {{9-17=upperBound}} {{none}} } func _Collection() { func fn(a: Bit) {} // expected-error {{'Bit' is unavailable: Bit enum has been removed. Please use Int instead.}} {{none}} func fn<T>(b: IndexingGenerator<T>) {} // expected-error {{'IndexingGenerator' has been renamed to 'IndexingIterator'}} {{17-34=IndexingIterator}} {{none}} func fn<T : CollectionType>(c: T) {} // expected-error {{'CollectionType' has been renamed to 'Collection'}} {{15-29=Collection}} {{none}} func fn<T>(d: PermutationGenerator<T, T>) {} // expected-error {{'PermutationGenerator' is unavailable: PermutationGenerator has been removed in Swift 3}} } func _Collection<C : Collection>(c: C) { func fn<T : Collection, U>(_: T, _: U) where T.Generator == U {} // expected-error {{'Generator' has been renamed to 'Iterator'}} {{50-59=Iterator}} {{none}} _ = c.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}} _ = c.underestimateCount() // expected-error {{'underestimateCount()' has been replaced by 'underestimatedCount'}} {{9-27=underestimatedCount}} {{27-29=}} {{none}} _ = c.split(1) { _ in return true} // expected-error {{split(maxSplits:omittingEmptySubsequences:whereSeparator:) instead}} {{none}} } func _Collection<C : Collection, E>(c: C, e: E) where C.Iterator.Element: Equatable, C.Iterator.Element == E { _ = c.split(e) // expected-error {{'split(_:maxSplit:allowEmptySlices:)' is unavailable: Please use split(separator:maxSplits:omittingEmptySubsequences:) instead}} {{none}} } func _CollectionAlgorithms<C : MutableCollection, I>(c: C, i: I) where C : RandomAccessCollection, C.Index == I { var c = c _ = c.partition(i..<i) { _, _ in true } // expected-error {{slice the collection using the range, and call partition(by:)}} {{none}} c.sortInPlace { _, _ in true } // expected-error {{'sortInPlace' has been renamed to 'sort(by:)'}} {{5-16=sort}} {{none}} _ = c.partition { _, _ in true } // expected-error {{call partition(by:)}} {{none}} } func _CollectionAlgorithms<C : MutableCollection, I>(c: C, i: I) where C : RandomAccessCollection, C.Iterator.Element : Comparable, C.Index == I { var c = c _ = c.partition() // expected-error {{call partition(by:)}} {{none}} _ = c.partition(i..<i) // expected-error {{slice the collection using the range, and call partition(by:)}} {{none}} c.sortInPlace() // expected-error {{'sortInPlace()' has been renamed to 'sort()'}} {{5-16=sort}} {{none}} } func _CollectionAlgorithms<C : Collection, E>(c: C, e: E) where C.Iterator.Element : Equatable, C.Iterator.Element == E { _ = c.indexOf(e) // expected-error {{'indexOf' has been renamed to 'index(of:)'}} {{9-16=index}} {{17-17=of: }} {{none}} } func _CollectionAlgorithms<C : Collection>(c: C) { _ = c.indexOf { _ in true } // expected-error {{'indexOf' has been renamed to 'index(where:)'}} {{9-16=index}} {{none}} } func _CollectionAlgorithms<C : Sequence>(c: C) { _ = c.sort { _, _ in true } // expected-error {{'sort' has been renamed to 'sorted(by:)'}} {{9-13=sorted}} {{none}} _ = c.sort({ _, _ in true }) // expected-error {{'sort' has been renamed to 'sorted(by:)'}} {{9-13=sorted}} {{14-14=by: }} {{none}} } func _CollectionAlgorithms<C : Sequence>(c: C) where C.Iterator.Element : Comparable { _ = c.sort() // expected-error {{'sort()' has been renamed to 'sorted()'}} {{9-13=sorted}} {{none}} } func _CollectionAlgorithms<C : MutableCollection>(c: C) { _ = c.sort { _, _ in true } // expected-error {{'sort' has been renamed to 'sorted(by:)'}} {{9-13=sorted}} {{none}} _ = c.sort({ _, _ in true }) // expected-error {{'sort' has been renamed to 'sorted(by:)'}} {{9-13=sorted}} {{14-14=by: }} {{none}} } func _CollectionAlgorithms<C : MutableCollection>(c: C) where C.Iterator.Element : Comparable { _ = c.sort() // expected-error {{'sort()' has been renamed to 'sorted()'}} {{9-13=sorted}} {{none}} var a: [Int] = [1,2,3] var _: [Int] = a.sort() // expected-error {{'sort()' has been renamed to 'sorted()'}} {{20-24=sorted}} {{none}} var _: [Int] = a.sort { _, _ in true } // expected-error {{'sort' has been renamed to 'sorted(by:)'}} {{20-24=sorted}} {{none}} var _: [Int] = a.sort({ _, _ in true }) // expected-error {{'sort' has been renamed to 'sorted(by:)'}} {{20-24=sorted}} {{25-25=by: }} {{none}} _ = a.sort() // OK, in `Void`able context, `sort()` is a renamed `sortInPlace()`. _ = a.sort { _, _ in true } // OK, `Void`able context, `sort(by:)` is a renamed `sortInPlace(_:)`. } func _CollectionOfOne<T>(i: IteratorOverOne<T>) { func fn(_: GeneratorOfOne<T>) {} // expected-error {{'GeneratorOfOne' has been renamed to 'IteratorOverOne'}} {{14-28=IteratorOverOne}} {{none}} _ = i.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}} } func _CompilerProtocols() { func fn(_: BooleanType) {} // expected-error {{'BooleanType' has been renamed to 'Bool'}} {{14-25=Bool}} {{none}} } func _EmptyCollection<T>(i: EmptyIterator<T>) { func fn(_: EmptyGenerator<T>) {} // expected-error {{'EmptyGenerator' has been renamed to 'EmptyIterator'}} {{14-28=EmptyIterator}} {{none}} _ = i.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}} } func _ErrorType() { func fn(_: ErrorType) {} // expected-error {{'ErrorType' has been renamed to 'Error'}} {{14-23=Error}} } func _ExistentialCollection<T>(i: AnyIterator<T>) { func fn1<T>(_: AnyGenerator<T>) {} // expected-error {{'AnyGenerator' has been renamed to 'AnyIterator'}} {{18-30=AnyIterator}} {{none}} func fn2<T : AnyCollectionType>(_: T) {} // expected-error {{'AnyCollectionType' has been renamed to '_AnyCollectionProtocol'}} {{16-33=_AnyCollectionProtocol}} {{none}} func fn3(_: AnyForwardIndex) {} // expected-error {{'AnyForwardIndex' has been renamed to 'AnyIndex'}} {{15-30=AnyIndex}} {{none}} func fn4(_: AnyBidirectionalIndex) {} // expected-error {{'AnyBidirectionalIndex' has been renamed to 'AnyIndex'}} {{15-36=AnyIndex}} {{none}} func fn5(_: AnyRandomAccessIndex) {} // expected-error {{'AnyRandomAccessIndex' has been renamed to 'AnyIndex'}} {{15-35=AnyIndex}} {{none}} _ = anyGenerator(i) // expected-error {{'anyGenerator' has been replaced by 'AnyIterator.init(_:)'}} {{7-19=AnyIterator}} {{none}} _ = anyGenerator { i.next() } // expected-error {{'anyGenerator' has been replaced by 'AnyIterator.init(_:)'}} {{7-19=AnyIterator}} {{none}} } func _ExistentialCollection<T>(s: AnySequence<T>) { _ = s.underestimateCount() // expected-error {{'underestimateCount()' has been replaced by 'underestimatedCount'}} {{9-27=underestimatedCount}} {{27-29=}} {{none}} } func _ExistentialCollection<T>(c: AnyCollection<T>) { _ = c.underestimateCount() // expected-error {{'underestimateCount()' has been replaced by 'underestimatedCount'}} {{9-27=underestimatedCount}} {{27-29=}} {{none}} } func _ExistentialCollection<T>(c: AnyBidirectionalCollection<T>) { _ = c.underestimateCount() // expected-error {{'underestimateCount()' has been replaced by 'underestimatedCount'}} {{9-27=underestimatedCount}} {{27-29=}} {{none}} } func _ExistentialCollection<T>(c: AnyRandomAccessCollection<T>) { _ = c.underestimateCount() // expected-error {{'underestimateCount()' has been replaced by 'underestimatedCount'}} {{9-27=underestimatedCount}} {{27-29=}} {{none}} } func _ExistentialCollection<C : _AnyCollectionProtocol>(c: C) { _ = c.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}} } func _Filter() { func fn<T>(_: LazyFilterGenerator<T>) {} // expected-error {{'LazyFilterGenerator' has been renamed to 'LazyFilterIterator'}} {{17-36=LazyFilterIterator}} {{none}} } func _Filter<I : IteratorProtocol>(i: I) { _ = LazyFilterIterator(i) { _ in true } // expected-error {{'init(_:whereElementsSatisfy:)' is unavailable: use '.lazy.filter' on the sequence}} } func _Filter<S : Sequence>(s: S) { _ = LazyFilterSequence(s) { _ in true } // expected-error {{'init(_:whereElementsSatisfy:)' is unavailable: use '.lazy.filter' on the sequence}} } func _Filter<S>(s: LazyFilterSequence<S>) { _ = s.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}} } func _Filter<C : Collection>(c: C) { _ = LazyFilterCollection(c) { _ in true} // expected-error {{'init(_:whereElementsSatisfy:)' is unavailable: use '.lazy.filter' on the collection}} } func _Filter<C>(c: LazyFilterCollection<C>) { _ = c.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}} } func _Flatten() { func fn<T>(i: FlattenGenerator<T>) {} // expected-error {{'FlattenGenerator' has been renamed to 'FlattenIterator'}} {{17-33=FlattenIterator}} {{none}} } func _Flatten<T>(s: FlattenSequence<T>) { _ = s.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}} } func _Flatten<T>(c: FlattenCollection<T>) { _ = c.underestimateCount() // expected-error {{'underestimateCount()' has been replaced by 'underestimatedCount'}} {{9-27=underestimatedCount}} {{27-29=}} {{none}} } func _Flatten<T>(c: FlattenBidirectionalCollection<T>) { _ = c.underestimateCount() // expected-error {{'underestimateCount()' has been replaced by 'underestimatedCount'}} {{9-27=underestimatedCount}} {{27-29=}} {{none}} } func _FloatingPoint() { func fn<F : FloatingPointType>(f: F) {} // expected-error {{'FloatingPointType' has been renamed to 'FloatingPoint'}} {{15-32=FloatingPoint}} {{none}} } func _FloatingPoint<F : BinaryFloatingPoint>(f: F) { _ = f.isSignaling // expected-error {{'isSignaling' has been renamed to 'isSignalingNaN'}} {{9-20=isSignalingNaN}} {{none}} } func _FloatingPointTypes() { var x: Float = 1, y: Float = 1 x += 1 y += 1 // FIXME: isSignMinus -> sign is OK? different type. _ = x.isSignMinus // expected-error {{'isSignMinus' has been renamed to 'sign'}} {{9-20=sign}} {{none}} _ = x % y // expected-error {{'%' is unavailable: Use truncatingRemainder instead}} {{none}} x %= y // expected-error {{'%=' is unavailable: Use formTruncatingRemainder instead}} {{none}} ++x // expected-error {{'++' is unavailable: it has been removed in Swift 3}} {{3-5=}} {{6-6= += 1}} {{none}} --x // expected-error {{'--' is unavailable: it has been removed in Swift 3}} {{3-5=}} {{6-6= -= 1}} {{none}} x++ // expected-error {{'++' is unavailable: it has been removed in Swift 3}} {{4-6= += 1}} {{none}} x-- // expected-error {{'--' is unavailable: it has been removed in Swift 3}} {{4-6= -= 1}} {{none}} } func _HashedCollection<T>(x: Set<T>, i: Set<T>.Index, e: T) { var x = x _ = x.removeAtIndex(i) // expected-error {{'removeAtIndex' has been renamed to 'remove(at:)'}} {{9-22=remove}} {{23-23=at: }} {{none}} _ = x.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}} _ = x.indexOf(e) // expected-error {{'indexOf' has been renamed to 'index(of:)'}} {{9-16=index}} {{17-17=of: }} {{none}} } func _HashedCollection<K, V>(x: Dictionary<K, V>, i: Dictionary<K, V>.Index, k: K) { var x = x _ = x.removeAtIndex(i) // expected-error {{'removeAtIndex' has been renamed to 'remove(at:)'}} {{9-22=remove}} {{23-23=at: }} {{none}} _ = x.indexForKey(k) // expected-error {{'indexForKey' has been renamed to 'index(forKey:)'}} {{9-20=index}} {{21-21=forKey: }} {{none}} _ = x.removeValueForKey(k) // expected-error {{'removeValueForKey' has been renamed to 'removeValue(forKey:)'}} {{9-26=removeValue}} {{27-27=forKey: }} {{none}} _ = x.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}} } func _ImplicitlyUnwrappedOptional<T>(x: ImplicitlyUnwrappedOptional<T>) { _ = ImplicitlyUnwrappedOptional<T>() // expected-error {{'init()' is unavailable: Please use nil literal instead.}} {{none}} _ = ImplicitlyUnwrappedOptional<T>.map(x)() { _ in true } // expected-error {{'map' is unavailable: Has been removed in Swift 3.}} _ = ImplicitlyUnwrappedOptional<T>.flatMap(x)() { _ in true } // expected-error {{'flatMap' is unavailable: Has been removed in Swift 3.}} // FIXME: No way to call map and flatMap as method? // _ = (x as ImplicitlyUnwrappedOptional).map { _ in true } // xpected-error {{}} {{none}} // _ = (x as ImplicitlyUnwrappedOptional).flatMap { _ in true } // xpected-error {{}} {{none}} } func _Index<T : _Incrementable>(i: T) { var i = i --i // expected-error {{'--' is unavailable: it has been removed in Swift 3}} {{3-5=}} {{6-6= = i.predecessor()}} {{none}} i-- // expected-error {{'--' is unavailable: it has been removed in Swift 3}} {{4-6= = i.predecessor()}} {{none}} ++i // expected-error {{'++' is unavailable: it has been removed in Swift 3}} {{3-5=}} {{6-6= = i.successor()}} {{none}} i++ // expected-error {{'++' is unavailable: it has been removed in Swift 3}} {{4-6= = i.successor()}} {{none}} } func _Index() { func fn1<T : ForwardIndexType>(_: T) {} // expected-error {{'ForwardIndexType' has been renamed to 'Comparable'}} {{16-32=Comparable}} {{none}} func fn2<T : BidirectionalIndexType>(_: T) {} // expected-error {{'BidirectionalIndexType' has been renamed to 'Comparable'}} {{16-38=Comparable}} {{none}} func fn3<T : RandomAccessIndexType>(_: T) {} // expected-error {{'RandomAccessIndexType' has been renamed to 'Strideable'}} {{16-37=Strideable}} {{none}} } func _InputStream() { _ = readLine(stripNewline: true) // expected-error {{'readLine(stripNewline:)' has been renamed to 'readLine(strippingNewline:)'}} {{7-15=readLine}} {{16-28=strippingNewline}} {{none}} _ = readLine() // ok } func _Join() { func fn<T>(_: JoinGenerator<T>) {} // expected-error {{'JoinGenerator' has been renamed to 'JoinedIterator'}} {{17-30=JoinedIterator}} {{none}} } func _Join<T>(s: JoinedSequence<T>) { _ = s.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}} } func _Join<S : Sequence>(s: S) where S.Iterator.Element : Sequence { _ = s.joinWithSeparator(s) // expected-error {{'joinWithSeparator' has been renamed to 'joined(separator:)'}} {{9-26=joined}} {{27-27=separator: }} {{none}} } func _LazyCollection() { func fn<T : LazyCollectionType>(_: T) {} // expected-error {{'LazyCollectionType' has been renamed to 'LazyCollectionProtocol'}} {{15-33=LazyCollectionProtocol}} {{none}} } func _LazySequence() { func fn<T : LazySequenceType>(_: T) {} // expected-error {{'LazySequenceType' has been renamed to 'LazySequenceProtocol'}} {{15-31=LazySequenceProtocol}} {{none}} } func _LazySequence<S : LazySequenceProtocol>(s: S) { _ = s.array // expected-error {{'array' is unavailable: Please use Array initializer instead.}} {{none}} } func _LifetimeManager<T>(x: T) { var x = x _ = withUnsafeMutablePointer(&x) { _ in } // expected-error {{'withUnsafeMutablePointer' has been renamed to 'withUnsafeMutablePointer(to:_:)'}} {{7-31=withUnsafeMutablePointer}} {{32-32=to: }} {{none}} _ = withUnsafeMutablePointers(&x, &x) { _, _ in } // expected-error {{'withUnsafeMutablePointers' is unavailable: use nested withUnsafeMutablePointer(to:_:) instead}} {{none}} _ = withUnsafeMutablePointers(&x, &x, &x) { _, _, _ in } // expected-error {{'withUnsafeMutablePointers' is unavailable: use nested withUnsafeMutablePointer(to:_:) instead}} {{none}} _ = withUnsafePointer(&x) { _ in } // expected-error {{'withUnsafePointer' has been renamed to 'withUnsafePointer(to:_:)'}} {7-24=withUnsafePointer}} {{25-25=to: }} {{none}} _ = withUnsafePointers(&x, &x) { _, _ in } // expected-error {{'withUnsafePointers' is unavailable: use nested withUnsafePointer(to:_:) instead}} {{none}} _ = withUnsafePointers(&x, &x, &x) { _, _, _ in } // expected-error {{'withUnsafePointers' is unavailable: use nested withUnsafePointer(to:_:) instead}} {{none}} } func _ManagedBuffer<H, E>(x: ManagedBufferPointer<H, E>, h: H, bc: AnyClass) { _ = x.allocatedElementCount // expected-error {{'allocatedElementCount' has been renamed to 'capacity'}} {{9-30=capacity}} {{none}} _ = ManagedBuffer<H, E>.create(1) { _ in h } // expected-error {{'create(_:initialValue:)' has been renamed to 'create(minimumCapacity:makingHeaderWith:)'}} {{27-33=create}} {{34-34=minimumCapacity: }} {{none}} _ = ManagedBuffer<H, E>.create(1, initialValue: { _ in h }) // expected-error {{'create(_:initialValue:)' has been renamed to 'create(minimumCapacity:makingHeaderWith:)'}} {{27-33=create}} {{34-34=minimumCapacity: }} {{37-49=makingHeaderWith}} {{none}} _ = ManagedBufferPointer<H, E>(bufferClass: bc, minimumCapacity: 1, initialValue: { _, _ in h }) // expected-error {{'init(bufferClass:minimumCapacity:initialValue:)' has been renamed to 'init(bufferClass:minimumCapacity:makingHeaderWith:)'}} {{71-83=makingHeaderWith}} {{none}} _ = ManagedBufferPointer<H, E>(bufferClass: bc, minimumCapacity: 1) { _, _ in h } // OK func fn(_: ManagedProtoBuffer<H, E>) {} // expected-error {{'ManagedProtoBuffer' has been renamed to 'ManagedBuffer'}} {{14-32=ManagedBuffer}} {{none}} } func _Map() { func fn<B, E>(_: LazyMapGenerator<B, E>) {} // expected-error {{'LazyMapGenerator' has been renamed to 'LazyMapIterator'}} {{20-36=LazyMapIterator}} {{none}} } func _Map<S : Sequence>(s: S) { _ = LazyMapSequence(s) { _ in true } // expected-error {{'init(_:transform:)' is unavailable: use '.lazy.map' on the sequence}} {{none}} } func _Map<C : Collection>(c: C) { _ = LazyMapCollection(c) { _ in true } // expected-error {{'init(_:transform:)' is unavailable: use '.lazy.map' on the collection}} {{none}} } func _MemoryLayout<T>(t: T) { _ = sizeof(T.self) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-14=MemoryLayout<}} {{15-21=>.size}} {{none}} _ = alignof(T.self) // expected-error {{'alignof' is unavailable: use MemoryLayout<T>.alignment instead.}} {{7-15=MemoryLayout<}} {{16-22=>.alignment}} {{none}} _ = strideof(T.self) // expected-error {{'strideof' is unavailable: use MemoryLayout<T>.stride instead.}} {{7-16=MemoryLayout<}} {{17-23=>.stride}} {{none}} _ = sizeofValue(t) // expected-error {{'sizeofValue' has been replaced by 'MemoryLayout.size(ofValue:)'}} {{7-18=MemoryLayout.size}} {{19-19=ofValue: }} {{none}} _ = alignofValue(t) // expected-error {{'alignofValue' has been replaced by 'MemoryLayout.alignment(ofValue:)'}} {{7-19=MemoryLayout.alignment}} {{20-20=ofValue: }} {{none}} _ = strideofValue(t) // expected-error {{'strideofValue' has been replaced by 'MemoryLayout.stride(ofValue:)'}} {{7-20=MemoryLayout.stride}} {{21-21=ofValue: }} {{none}} } func _Mirror() { func fn<M : MirrorPathType>(_: M) {} // expected-error {{'MirrorPathType' has been renamed to 'MirrorPath'}} {{15-29=MirrorPath}} {{none}} } func _MutableCollection() { func fn1<C : MutableCollectionType>(_: C) {} // expected-error {{'MutableCollectionType' has been renamed to 'MutableCollection'}} {{16-37=MutableCollection}} {{none}} func fn2<C : MutableSliceable>(_: C) {} // expected-error {{'MutableSliceable' is unavailable: Please use 'Collection where SubSequence : MutableCollection'}} {{none}} } func _OptionSet() { func fn<O : OptionSetType>(_: O) {} // expected-error {{'OptionSetType' has been renamed to 'OptionSet'}} {{15-28=OptionSet}} {{none}} } func _Optional<T>(x: T) { _ = Optional<T>.None // expected-error {{'None' has been renamed to 'none'}} {{19-23=none}} {{none}} _ = Optional<T>.Some(x) // expected-error {{'Some' has been renamed to 'some'}} {{19-23=some}} {{none}} } func _TextOutputStream() { func fn<S : OutputStreamType>(_: S) {} // expected-error {{'OutputStreamType' has been renamed to 'TextOutputStream'}} {{15-31=TextOutputStream}} {{none}} } func _TextOutputStream<S : TextOutputStreamable, O : TextOutputStream>(s: S, o: O) { var o = o s.writeTo(&o) // expected-error {{'writeTo' has been renamed to 'write(to:)'}} {{5-12=write}} {{13-13=to: }} {{none}} } func _Print<T, O : TextOutputStream>(x: T, out: O) { var out = out print(x, toStream: &out) // expected-error {{'print(_:separator:terminator:toStream:)' has been renamed to 'print(_:separator:terminator:to:)'}} {{3-8=print}} {{12-20=to}} {{none}} print(x, x, separator: "/", toStream: &out) // expected-error {{'print(_:separator:terminator:toStream:)' has been renamed to 'print(_:separator:terminator:to:)'}} {{3-8=print}} {{31-39=to}} {{none}} print(terminator: "|", toStream: &out) // expected-error {{'print(_:separator:terminator:toStream:)' has been renamed to 'print(_:separator:terminator:to:)'}} {{3-8=print}} {{26-34=to}} {{none}} print(x, separator: "*", terminator: "$", toStream: &out) // expected-error {{'print(_:separator:terminator:toStream:)' has been renamed to 'print(_:separator:terminator:to:)'}} {{3-8=print}} {{45-53=to}} {{none}} debugPrint(x, toStream: &out) // expected-error {{'debugPrint(_:separator:terminator:toStream:)' has been renamed to 'debugPrint(_:separator:terminator:to:)'}} {{3-13=debugPrint}} {{17-25=to}} {{none}} } func _Print<T>(x: T) { print(x, appendNewline: true) // expected-error {{'print(_:appendNewline:)' is unavailable: Please use 'terminator: ""' instead of 'appendNewline: false': 'print((...), terminator: "")'}} {{none}} debugPrint(x, appendNewline: true) // expected-error {{'debugPrint(_:appendNewline:)' is unavailable: Please use 'terminator: ""' instead of 'appendNewline: false': 'debugPrint((...), terminator: "")'}} {{none}} } func _Print<T, O : TextOutputStream>(x: T, o: O) { // FIXME: Not working due to <rdar://22101775> //var o = o //print(x, &o) // xpected-error {{}} {{none}} //debugPrint(x, &o) // xpected-error {{}} {{none}} //print(x, &o, appendNewline: true) // xpected-error {{}} {{none}} //debugPrint(x, &o, appendNewline: true) // xpected-error {{}} {{none}} } func _Range() { func fn1<B>(_: RangeGenerator<B>) {} // expected-error {{'RangeGenerator' has been renamed to 'IndexingIterator'}} {{18-32=IndexingIterator}} {{none}} func fn2<I : IntervalType>(_: I) {} // expected-error {{'IntervalType' is unavailable: IntervalType has been removed in Swift 3. Use ranges instead.}} {{none}} func fn3<B>(_: HalfOpenInterval<B>) {} // expected-error {{'HalfOpenInterval' has been renamed to 'Range'}} {{18-34=Range}} {{none}} func fn4<B>(_: ClosedInterval<B>) {} // expected-error {{'ClosedInterval' has been renamed to 'ClosedRange'}} {{18-32=ClosedRange}} {{none}} } func _Range<T>(r: Range<T>) { _ = r.startIndex // expected-error {{'startIndex' has been renamed to 'lowerBound'}} {{9-19=lowerBound}} {{none}} _ = r.endIndex // expected-error {{'endIndex' has been renamed to 'upperBound'}} {{9-17=upperBound}} {{none}} } func _Range<T>(r: ClosedRange<T>) { _ = r.clamp(r) // expected-error {{'clamp' is unavailable: Call clamped(to:) and swap the argument and the receiver. For example, x.clamp(y) becomes y.clamped(to: x) in Swift 3.}} {{none}} } func _Range<T>(r: CountableClosedRange<T>) { _ = r.clamp(r) // expected-error {{'clamp' is unavailable: Call clamped(to:) and swap the argument and the receiver. For example, x.clamp(y) becomes y.clamped(to: x) in Swift 3.}} {{none}} } func _RangeReplaceableCollection() { func fn<I : RangeReplaceableCollectionType>(_: I) {} // expected-error {{'RangeReplaceableCollectionType' has been renamed to 'RangeReplaceableCollection'}} {{15-45=RangeReplaceableCollection}} {{none}} } func _RangeReplaceableCollection<C : RangeReplaceableCollection>(c: C, i: C.Index) { var c = c c.replaceRange(i..<i, with: []) // expected-error {{'replaceRange(_:with:)' has been renamed to 'replaceSubrange(_:with:)'}} {{5-17=replaceSubrange}} {{none}} _ = c.removeAtIndex(i) // expected-error {{'removeAtIndex' has been renamed to 'remove(at:)'}} {{9-22=remove}} {{23-23=at: }} {{none}} c.removeRange(i..<i) // expected-error {{'removeRange' has been renamed to 'removeSubrange'}} {{5-16=removeSubrange}} {{none}} c.appendContentsOf([]) // expected-error {{'appendContentsOf' has been renamed to 'append(contentsOf:)'}} {{5-21=append}} {{22-22=contentsOf: }} {{none}} c.insertContentsOf(c, at: i) // expected-error {{'insertContentsOf(_:at:)' has been renamed to 'insert(contentsOf:at:)'}} {{5-21=insert}} {{22-22=contentsOf: }} {{none}} } func _Reflection(x: ObjectIdentifier) { _ = x.uintValue // expected-error {{'uintValue' is unavailable: use the 'UInt(_:)' initializer}} {{none}} } func _Repeat() { func fn<E>(_: Repeat<E>) {} // expected-error {{'Repeat' has been renamed to 'Repeated'}} {{17-23=Repeated}} {{none}} } func _Repeat<E>(e: E) { _ = Repeated(count: 0, repeatedValue: e) // expected-error {{'init(count:repeatedValue:)' is unavailable: Please use repeatElement(_:count:) function instead}} {{none}} } func _Reverse<C : BidirectionalCollection>(c: C) { _ = ReverseCollection(c) // expected-error {{'ReverseCollection' has been renamed to 'ReversedCollection'}} {{7-24=ReversedCollection}} {{none}} _ = ReversedCollection(c) // expected-error {{'init' has been replaced by instance method 'BidirectionalCollection.reversed()'}} {{7-25=c.reversed}} {{26-27=}} {{none}} _ = c.reverse() // expected-error {{'reverse()' has been renamed to 'reversed()'}} {{9-16=reversed}} {{none}} } func _Reverse<C : RandomAccessCollection>(c: C) { _ = ReverseRandomAccessCollection(c) // expected-error {{'ReverseRandomAccessCollection' has been renamed to 'ReversedRandomAccessCollection'}} {{7-36=ReversedRandomAccessCollection}} {{none}} _ = ReversedRandomAccessCollection(c) // expected-error {{'init' has been replaced by instance method 'RandomAccessCollection.reversed()'}} {{7-37=c.reversed}} {{38-39=}} {{none}} _ = c.reverse() // expected-error {{'reverse()' has been renamed to 'reversed()'}} {{9-16=reversed}} {{none}} } func _Reverse<C : LazyCollectionProtocol>(c: C) where C : BidirectionalCollection, C.Elements : BidirectionalCollection { _ = c.reverse() // expected-error {{'reverse()' has been renamed to 'reversed()'}} {{9-16=reversed}} {{none}} } func _Reverse<C : LazyCollectionProtocol>(c: C) where C : RandomAccessCollection, C.Elements : RandomAccessCollection { _ = c.reverse() // expected-error {{'reverse()' has been renamed to 'reversed()'}} {{9-16=reversed}} {{none}} } func _Sequence() { func fn1<G : GeneratorType>(_: G) {} // expected-error {{'GeneratorType' has been renamed to 'IteratorProtocol'}} {{16-29=IteratorProtocol}} {{none}} func fn2<S : SequenceType>(_: S) {} // expected-error {{'SequenceType' has been renamed to 'Sequence'}} {{16-28=Sequence}} {{none}} func fn3<I : IteratorProtocol>(_: GeneratorSequence<I>) {} // expected-error {{'GeneratorSequence' has been renamed to 'IteratorSequence'}} {{37-54=IteratorSequence}} {{none}} } func _Sequence<S : Sequence>(s: S) { _ = s.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}} _ = s.underestimateCount() // expected-error {{'underestimateCount()' has been replaced by 'underestimatedCount'}} {{9-27=underestimatedCount}} {{27-29=}} {{none}} _ = s.split(1, allowEmptySlices: true) { _ in true } // expected-error {{'split(_:allowEmptySlices:isSeparator:)' is unavailable: call 'split(maxSplits:omittingEmptySubsequences:whereSeparator:)' and invert the 'allowEmptySlices' argument}} {{none}} } func _Sequence<S : Sequence>(s: S, e: S.Iterator.Element) where S.Iterator.Element : Equatable { _ = s.split(e, maxSplit: 1, allowEmptySlices: true) // expected-error {{'split(_:maxSplit:allowEmptySlices:)' is unavailable: call 'split(separator:maxSplits:omittingEmptySubsequences:)' and invert the 'allowEmptySlices' argument}} {{none}} } func _SequenceAlgorithms<S : Sequence>(x: S) { _ = x.enumerate() // expected-error {{'enumerate()' has been renamed to 'enumerated()'}} {{9-18=enumerated}} {{none}} _ = x.minElement { _, _ in true } // expected-error {{'minElement' has been renamed to 'min(by:)'}} {{9-19=min}} {{none}} _ = x.maxElement { _, _ in true } // expected-error {{'maxElement' has been renamed to 'max(by:)'}} {{9-19=max}} {{none}} _ = x.reverse() // expected-error {{'reverse()' has been renamed to 'reversed()'}} {{9-16=reversed}} {{none}} _ = x.startsWith([]) { _ in true } // expected-error {{'startsWith(_:isEquivalent:)' has been renamed to 'starts(with:by:)'}} {{9-19=starts}} {{20-20=with: }} {{none}} _ = x.elementsEqual([], isEquivalent: { _, _ in true }) // expected-error {{'elementsEqual(_:isEquivalent:)' has been renamed to 'elementsEqual(_:by:)'}} {{9-22=elementsEqual}} {{27-39=by}} {{none}} _ = x.elementsEqual([]) { _, _ in true } // OK _ = x.lexicographicalCompare([]) { _, _ in true } // expected-error {{'lexicographicalCompare(_:isOrderedBefore:)' has been renamed to 'lexicographicallyPrecedes(_:by:)'}} {{9-31=lexicographicallyPrecedes}}{{none}} _ = x.contains({ _ in true }) // expected-error {{'contains' has been renamed to 'contains(where:)'}} {{9-17=contains}} {{18-18=where: }} {{none}} _ = x.contains { _ in true } // OK _ = x.reduce(1, combine: { _, _ in 1 }) // expected-error {{'reduce(_:combine:)' has been renamed to 'reduce(_:_:)'}} {{9-15=reduce}} {{19-28=}} {{none}} _ = x.reduce(1) { _, _ in 1 } // OK } func _SequenceAlgorithms<S : Sequence>(x: S) where S.Iterator.Element : Comparable { _ = x.minElement() // expected-error {{'minElement()' has been renamed to 'min()'}} {{9-19=min}} {{none}} _ = x.maxElement() // expected-error {{'maxElement()' has been renamed to 'max()'}} {{9-19=max}} {{none}} _ = x.startsWith([]) // expected-error {{'startsWith' has been renamed to 'starts(with:)'}} {{9-19=starts}} {{20-20=with: }} {{none}} _ = x.lexicographicalCompare([]) // expected-error {{'lexicographicalCompare' has been renamed to 'lexicographicallyPrecedes'}} {{9-31=lexicographicallyPrecedes}}{{none}} } func _SetAlgebra() { func fn<S : SetAlgebraType>(_: S) {} // expected-error {{'SetAlgebraType' has been renamed to 'SetAlgebra'}} {{15-29=SetAlgebra}} {{none}} } func _SetAlgebra<S : SetAlgebra>(s: S) { var s = s _ = s.intersect(s) // expected-error {{'intersect' has been renamed to 'intersection(_:)'}} {{9-18=intersection}} {{none}} _ = s.exclusiveOr(s) // expected-error {{'exclusiveOr' has been renamed to 'symmetricDifference(_:)'}} {{9-20=symmetricDifference}} {{none}} s.unionInPlace(s) // expected-error {{'unionInPlace' has been renamed to 'formUnion(_:)'}} {{5-17=formUnion}} {{none}} s.intersectInPlace(s) // expected-error {{'intersectInPlace' has been renamed to 'formIntersection(_:)'}} {{5-21=formIntersection}} {{none}} s.exclusiveOrInPlace(s) // expected-error {{'exclusiveOrInPlace' has been renamed to 'formSymmetricDifference(_:)'}} {{5-23=formSymmetricDifference}} {{none}} _ = s.isSubsetOf(s) // expected-error {{'isSubsetOf' has been renamed to 'isSubset(of:)'}} {{9-19=isSubset}} {{20-20=of: }} {{none}} _ = s.isDisjointWith(s) // expected-error {{'isDisjointWith' has been renamed to 'isDisjoint(with:)'}} {{9-23=isDisjoint}} {{24-24=with: }} {{none}} s.subtractInPlace(s) // expected-error {{'subtractInPlace' has been renamed to 'subtract(_:)'}} {{5-20=subtract}} {{none}} _ = s.isStrictSupersetOf(s) // expected-error {{'isStrictSupersetOf' has been renamed to 'isStrictSuperset(of:)'}} {{9-27=isStrictSuperset}} {{28-28=of: }} {{none}} _ = s.isStrictSubsetOf(s) // expected-error {{'isStrictSubsetOf' has been renamed to 'isStrictSubset(of:)'}} {{9-25=isStrictSubset}} {{26-26=of: }} {{none}} } func _StaticString(x: StaticString) { _ = x.byteSize // expected-error {{'byteSize' has been renamed to 'utf8CodeUnitCount'}} {{9-17=utf8CodeUnitCount}} {{none}} _ = x.stringValue // expected-error {{'stringValue' is unavailable: use the 'String(_:)' initializer}} {{none}} } func _Stride<T : Strideable>(x: T, d: T.Stride) { func fn1<T>(_: StrideToGenerator<T>) {} // expected-error {{'StrideToGenerator' has been renamed to 'StrideToIterator'}} {{18-35=StrideToIterator}} {{none}} func fn2<T>(_: StrideThroughGenerator<T>) {} // expected-error {{'StrideThroughGenerator' has been renamed to 'StrideThroughIterator'}} {{18-40=StrideThroughIterator}} {{none}} _ = x.stride(to: x, by: d) // expected-error {{'stride(to:by:)' is unavailable: Use stride(from:to:by:) free function instead}} {{none}} _ = x.stride(through: x, by: d) // expected-error {{'stride(through:by:)' is unavailable: Use stride(from:through:by:) free function instead}} } func _String<S, C>(x: String, s: S, c: C, i: String.Index) where S : Sequence, S.Iterator.Element == Character, C : Collection, C.Iterator.Element == Character { var x = x x.appendContentsOf(x) // expected-error {{'appendContentsOf' has been renamed to 'append(_:)'}} {{5-21=append}} {{none}} x.appendContentsOf(s) // expected-error {{'appendContentsOf' has been renamed to 'append(contentsOf:)'}} {{5-21=append}} {{22-22=contentsOf: }} {{none}} x.insertContentsOf(c, at: i) // expected-error {{'insertContentsOf(_:at:)' has been renamed to 'insert(contentsOf:at:)'}} {{5-21=insert}} {{22-22=contentsOf: }} {{none}} x.replaceRange(i..<i, with: c) // expected-error {{'replaceRange(_:with:)' has been renamed to 'replaceSubrange'}} {{5-17=replaceSubrange}} {{none}} x.replaceRange(i..<i, with: x) // expected-error {{'replaceRange(_:with:)' has been renamed to 'replaceSubrange'}} {{5-17=replaceSubrange}} {{none}} _ = x.removeAtIndex(i) // expected-error {{'removeAtIndex' has been renamed to 'remove(at:)'}} {{9-22=remove}} {{23-23=at: }} {{none}} x.removeRange(i..<i) // expected-error {{'removeRange' has been renamed to 'removeSubrange'}} {{5-16=removeSubrange}} {{none}} _ = x.lowercaseString // expected-error {{'lowercaseString' has been renamed to 'lowercased()'}} {{9-24=lowercased()}} {{none}} _ = x.uppercaseString // expected-error {{'uppercaseString' has been renamed to 'uppercased()'}} {{9-24=uppercased()}} {{none}} // FIXME: SR-1649 <rdar://problem/26563343>; We should suggest to add '()' } func _String<S : Sequence>(s: S, sep: String) where S.Iterator.Element == String { _ = s.joinWithSeparator(sep) // expected-error {{'joinWithSeparator' has been renamed to 'joined(separator:)'}} {{9-26=joined}} {{27-27=separator: }} {{none}} } func _StringCharacterView<S, C>(x: String, s: S, c: C, i: String.Index) where S : Sequence, S.Iterator.Element == Character, C : Collection, C.Iterator.Element == Character { var x = x x.replaceRange(i..<i, with: c) // expected-error {{'replaceRange(_:with:)' has been renamed to 'replaceSubrange'}} {{5-17=replaceSubrange}} {{none}} x.appendContentsOf(s) // expected-error {{'appendContentsOf' has been renamed to 'append(contentsOf:)'}} {{5-21=append}} {{22-22=contentsOf: }} {{none}} } func _StringAppend(s: inout String, u: UnicodeScalar) { s.append(u) // expected-error {{'append' is unavailable: Replaced by append(_: String)}} {{none}} } func _StringLegacy(c: Character, u: UnicodeScalar) { _ = String(count: 1, repeatedValue: c) // expected-error {{'init(count:repeatedValue:)' is unavailable: Renamed to init(repeating:count:) and reordered parameters}} {{none}} _ = String(count: 1, repeatedValue: u) // expected-error {{'init(count:repeatedValue:)' is unavailable: Renamed to init(repeating:count:) and reordered parameters}} {{none}} _ = String(repeating: c, count: 1) // no more error, since String conforms to BidirectionalCollection _ = String(repeating: u, count: 1) // expected-error {{'init(repeating:count:)' is unavailable: Replaced by init(repeating: String, count: Int)}} {{none}} } func _Unicode<C : UnicodeCodec>(s: UnicodeScalar, c: C.Type, out: (C.CodeUnit) -> Void) { func fn<T : UnicodeCodecType>(_: T) {} // expected-error {{'UnicodeCodecType' has been renamed to 'UnicodeCodec'}} {{15-31=UnicodeCodec}} {{none}} c.encode(s, output: out) // expected-error {{encode(_:output:)' has been renamed to 'encode(_:into:)}} {{5-11=encode}} {{15-21=into}} {{none}} c.encode(s) { _ in } // OK UTF8.encode(s, output: { _ in }) // expected-error {{'encode(_:output:)' has been renamed to 'encode(_:into:)'}} {{8-14=encode}} {{18-24=into}} {{none}} UTF16.encode(s, output: { _ in }) // expected-error {{'encode(_:output:)' has been renamed to 'encode(_:into:)'}} {{9-15=encode}} {{19-25=into}} {{none}} UTF32.encode(s, output: { _ in }) // expected-error {{'encode(_:output:)' has been renamed to 'encode(_:into:)'}} {{9-15=encode}} {{19-25=into}} {{none}} } func _Unicode<I : IteratorProtocol, E : UnicodeCodec>(i: I, e: E.Type) where I.Element == E.CodeUnit { _ = transcode(e, e, i, { _ in }, stopOnError: true) // expected-error {{'transcode(_:_:_:_:stopOnError:)' is unavailable: use 'transcode(_:from:to:stoppingOnError:into:)'}} {{none}} _ = UTF16.measure(e, input: i, repairIllFormedSequences: true) // expected-error {{'measure(_:input:repairIllFormedSequences:)' is unavailable: use 'transcodedLength(of:decodedAs:repairingIllFormedSequences:)'}} {{none}} } func _UnicodeScalar(s: UnicodeScalar) { _ = UnicodeScalar() // expected-error {{'init()' is unavailable: use 'Unicode.Scalar(0)'}} {{none}} _ = s.escape(asASCII: true) // expected-error {{'escape(asASCII:)' has been renamed to 'escaped(asASCII:)'}} {{9-15=escaped}} {{none}} } func _Unmanaged<T>(x: Unmanaged<T>, p: OpaquePointer) { _ = Unmanaged<T>.fromOpaque(p) // expected-error {{'fromOpaque' is unavailable: use 'fromOpaque(_: UnsafeRawPointer)' instead}} {{none}} let _: OpaquePointer = x.toOpaque() // expected-error {{'toOpaque()' is unavailable: use 'toOpaque() -> UnsafeRawPointer' instead}} {{none}} } func _UnsafeBufferPointer() { func fn<T>(x: UnsafeBufferPointerGenerator<T>) {} // expected-error {{'UnsafeBufferPointerGenerator' has been renamed to 'UnsafeBufferPointerIterator'}} {{17-45=UnsafeBufferPointerIterator}} {{none}} } func _UnsafePointer<T>(x: UnsafePointer<T>) { _ = UnsafePointer<T>.Memory.self // expected-error {{'Memory' has been renamed to 'Pointee'}} {{24-30=Pointee}} {{none}} _ = UnsafePointer<T>() // expected-error {{'init()' is unavailable: use 'nil' literal}} {{none}} _ = x.memory // expected-error {{'memory' has been renamed to 'pointee'}} {{9-15=pointee}} {{none}} } func _UnsafePointer<T>(x: UnsafeMutablePointer<T>, e: T) { var x = x _ = UnsafeMutablePointer<T>.Memory.self // expected-error {{'Memory' has been renamed to 'Pointee'}} {{31-37=Pointee}} {{none}} _ = UnsafeMutablePointer<T>() // expected-error {{'init()' is unavailable: use 'nil' literal}} {{none}} _ = x.memory // expected-error {{'memory' has been renamed to 'pointee'}} {{9-15=pointee}} {{none}} _ = UnsafeMutablePointer<T>.alloc(1) // expected-error {{'alloc' has been renamed to 'allocate(capacity:)'}} {{31-36=allocate}} {{37-37=capacity: }} {{none}} x.dealloc(1) // expected-error {{'dealloc' has been renamed to 'deallocate(capacity:)'}} {{5-12=deallocate}} {{13-13=capacity: }} {{none}} x.memory = e // expected-error {{'memory' has been renamed to 'pointee'}} {{5-11=pointee}} {{none}} x.initialize(e) // expected-error {{'initialize' has been renamed to 'initialize(to:)'}} {{5-15=initialize}} {{16-16=to: }} {{none}} x.destroy() // expected-error {{'destroy()' has been renamed to 'deinitialize(count:)'}} {{5-12=deinitialize}} {{none}} x.destroy(1) // expected-error {{'destroy' has been renamed to 'deinitialize(count:)'}} {{5-12=deinitialize}} {{13-13=count: }} {{none}} x.initialize(with: e) // expected-error {{'initialize(with:count:)' has been renamed to 'initialize(to:count:)'}} {{5-15=initialize}} {{16-20=to}} {{none}} let ptr1 = UnsafeMutablePointer<T>(allocatingCapacity: 1) // expected-error {{'init(allocatingCapacity:)' is unavailable: use 'UnsafeMutablePointer.allocate(capacity:)'}} {{none}} ptr1.initialize(with: e, count: 1) // expected-error {{'initialize(with:count:)' has been renamed to 'initialize(to:count:)'}} {{8-18=initialize}} {{19-23=to}} {{none}} let ptr2 = UnsafeMutablePointer<T>.allocate(capacity: 1) ptr2.initializeFrom(ptr1, count: 1) // expected-error {{'initializeFrom(_:count:)' has been renamed to 'initialize(from:count:)'}} {{8-22=initialize}} {{23-23=from: }} {{none}} ptr1.assignFrom(ptr2, count: 1) // expected-error {{'assignFrom(_:count:)' has been renamed to 'assign(from:count:)'}} {{8-18=assign}} {{19-19=from: }} {{none}} ptr2.assignBackwardFrom(ptr1, count: 1) // expected-error {{'assignBackwardFrom(_:count:)' has been renamed to 'assign(from:count:)'}} {{8-26=assign}} {{27-27=from: }} {{none}} ptr1.moveAssignFrom(ptr2, count: 1) // expected-error {{'moveAssignFrom(_:count:)' has been renamed to 'moveAssign(from:count:)'}} {{8-22=moveAssign}} {{23-23=from: }} {{none}} ptr2.moveInitializeFrom(ptr1, count: 1) // expected-error {{'moveInitializeFrom(_:count:)' has been renamed to 'moveInitialize(from:count:)'}} {{8-26=moveInitialize}} {{27-27=from: }} {{none}} ptr1.moveInitializeBackwardFrom(ptr1, count: 1) // expected-error {{'moveInitializeBackwardFrom(_:count:)' has been renamed to 'moveInitialize(from:count:)'}} {{8-34=moveInitialize}} {{35-35=from: }} {{none}} ptr1.deinitialize(count:1) ptr1.deallocateCapacity(1) // expected-error {{'deallocateCapacity' has been renamed to 'deallocate(capacity:)'}} {{8-26=deallocate}} {{27-27=capacity: }} {{none}} ptr2.deallocate(capacity: 1) } func _UnsafePointer<T, C : Collection>(x: UnsafeMutablePointer<T>, c: C) where C.Iterator.Element == T { x.initializeFrom(c) // expected-error {{'initializeFrom' has been renamed to 'initialize(from:)'}} } func _VarArgs() { func fn1(_: CVarArgType) {} // expected-error {{'CVarArgType' has been renamed to 'CVarArg'}} {{15-26=CVarArg}}{{none}} func fn2(_: VaListBuilder) {} // expected-error {{'VaListBuilder' is unavailable}} {{none}} } func _Zip<S1 : Sequence, S2: Sequence>(s1: S1, s2: S2) { _ = Zip2Sequence(s1, s2) // expected-error {{use zip(_:_:) free function instead}} {{none}} _ = Zip2Sequence<S1, S2>.Generator.self // expected-error {{'Generator' has been renamed to 'Iterator'}} {{28-37=Iterator}} {{none}} }
apache-2.0
skonmeme/Reservation
Reservation/ReservationDatePickerTableViewCell.swift
1
582
// // ReservationDatePickerTableViewCell.swift // Reservation // // Created by Sung Gon Yi on 23/12/2016. // Copyright © 2016 skon. All rights reserved. // import UIKit class ReservationDatePickerTableViewCell: UITableViewCell { @IBOutlet weak var datePicker: UIDatePicker! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
xzhangyueqian/JinJiangZhiChuang
JJZC/Pods/WMPageController-Swift/PageController/MenuView.swift
1
12436
// // MenuView.swift // PageController // // Created by Mark on 15/10/20. // Copyright © 2015年 Wecan Studio. All rights reserved. // import UIKit @objc public protocol MenuViewDelegate: NSObjectProtocol { func menuView(menuView: MenuView, widthForItemAtIndex index: Int) -> CGFloat optional func menuView(menuView: MenuView, didSelectedIndex index: Int, fromIndex currentIndex: Int) optional func menuView(menuView: MenuView, itemMarginAtIndex index: Int) -> CGFloat } @objc public protocol MenuViewDataSource: NSObjectProtocol { func menuView(menuView: MenuView, titleAtIndex index: Int) -> String func numbersOfTitlesInMenuView(menuView: MenuView) -> Int } public enum MenuViewStyle { case Default, Line, Flood, FooldHollow } public class MenuView: UIView, MenuItemDelegate { // MARK: - Public vars override public var frame: CGRect { didSet { guard contentView != nil else { return } let rightMargin = (rightView == nil) ? contentMargin : contentMargin + rightView!.frame.width let leftMargin = (leftView == nil) ? contentMargin : contentMargin + leftView!.frame.width let contentWidth = CGRectGetWidth(contentView.frame) + leftMargin + rightMargin let startX = (leftView != nil) ? leftView!.frame.origin.x : (contentView.frame.origin.x - contentMargin) // Make the contentView center, because system will change menuView's frame if it's a titleView. if (startX + contentWidth / 2 != bounds.width / 2) { let xOffset = (contentWidth - bounds.width) / 2 contentView.frame.origin.x -= xOffset rightView?.frame.origin.x -= xOffset leftView?.frame.origin.x -= xOffset } } } public weak var leftView: UIView? { willSet { leftView?.removeFromSuperview() } didSet { if let lView = leftView { addSubview(lView) } resetFrames() } } public weak var rightView: UIView? { willSet { rightView?.removeFromSuperview() } didSet { if let rView = rightView { addSubview(rView) } resetFrames() } } public var contentMargin: CGFloat = 0.0 { didSet { guard contentView != nil else { return } resetFrames() } } public var style = MenuViewStyle.Default public var fontName: String? public var progressHeight: CGFloat = 2.0 public var normalSize: CGFloat = 15.0 public var selectedSize: CGFloat = 18.0 public var progressColor: UIColor? public weak var delegate: MenuViewDelegate? public weak var dataSource: MenuViewDataSource! public lazy var normalColor = UIColor.blackColor() public lazy var selectedColor = UIColor(red: 168.0/255.0, green: 20.0/255.0, blue: 4/255.0, alpha: 1.0) // MARK: - Private vars private weak var contentView: UIScrollView! private weak var progressView: ProgressView? private weak var selectedItem: MenuItem! private var itemFrames = [CGRect]() private let tagGap = 6250 private var itemsCount: Int { return dataSource.numbersOfTitlesInMenuView(self) } public func reload() { itemFrames.removeAll() progressView?.removeFromSuperview() for subview in contentView.subviews { subview.removeFromSuperview() } addMenuItems() addProgressView() } // MARK: - Public funcs public func slideMenuAtProgress(progress: CGFloat) { progressView?.progress = progress let tag = Int(progress) + tagGap var rate = progress - CGFloat(tag - tagGap) let currentItem = viewWithTag(tag) as? MenuItem let nextItem = viewWithTag(tag + 1) as? MenuItem if rate == 0.0 { rate = 1.0 selectedItem.selected = false selectedItem = currentItem selectedItem.selected = true refreshContentOffset() return } currentItem?.rate = 1.0 - rate nextItem?.rate = rate } public func selectItemAtIndex(index: Int) { let tag = index + tagGap let currentIndex = selectedItem.tag - tagGap guard currentIndex != index && selectedItem != nil else { return } let menuItem = viewWithTag(tag) as! MenuItem selectedItem.selected = false selectedItem = menuItem selectedItem.selected = true progressView?.moveToPosition(index, animation: false) delegate?.menuView?(self, didSelectedIndex: index, fromIndex: currentIndex) refreshContentOffset() } // MARK: - Update Title public func updateTitle(title: String, atIndex index: Int, andWidth update: Bool) { guard index >= 0 && index < itemsCount else { return } let item = viewWithTag(tagGap + index) as? MenuItem item?.text = title guard update else { return } resetFrames() } // MARK: - Update Frames public func resetFrames() { var contentFrame = bounds if let rView = rightView { var rightFrame = rView.frame rightFrame.origin.x = contentFrame.width - rightFrame.width rightView?.frame = rightFrame contentFrame.size.width -= rightFrame.width } if let lView = leftView { var leftFrame = lView.frame leftFrame.origin.x = 0 leftView?.frame = leftFrame contentFrame.origin.x += leftFrame.width contentFrame.size.width -= leftFrame.width } contentFrame.origin.x += contentMargin contentFrame.size.width -= contentMargin * 2 contentView.frame = contentFrame resetFramesFromIndex(0) refreshContentOffset() } public func resetFramesFromIndex(index: Int) { itemFrames.removeAll() calculateFrames() for i in index ..< itemsCount { let item = viewWithTag(tagGap + i) as? MenuItem item?.frame = itemFrames[i] } if let progress = progressView { var pFrame = progress.frame pFrame.size.width = contentView.contentSize.width if progress.isKindOfClass(FooldView.self) { pFrame.origin.y = 0 } else { pFrame.origin.y = frame.size.height - progressHeight } progress.frame = pFrame progress.itemFrames = itemFrames progress.setNeedsDisplay() } } // MARK: - Private funcs override public func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) guard contentView == nil else { return } addScollView() addMenuItems() addProgressView() } private func refreshContentOffset() { let itemFrame = selectedItem.frame let itemX = itemFrame.origin.x let width = contentView.frame.size.width let contentWidth = contentView.contentSize.width if itemX > (width / 2) { var targetX: CGFloat = itemFrame.origin.x - width/2 + itemFrame.size.width/2 if (contentWidth - itemX) <= (width / 2) { targetX = contentWidth - width } if (targetX + width) > contentWidth { targetX = contentWidth - width } contentView.setContentOffset(CGPointMake(targetX, 0), animated: true) } else { contentView.setContentOffset(CGPointZero, animated: true) } } // MARK: - Create Views private func addScollView() { let scrollViewFrame = CGRect(x: contentMargin, y: 0, width: frame.size.width - contentMargin * 2, height: frame.size.height) let scrollView = UIScrollView(frame: scrollViewFrame) scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false scrollView.backgroundColor = .clearColor() scrollView.scrollsToTop = false addSubview(scrollView) contentView = scrollView } private func addMenuItems() { calculateFrames() for index in 0 ..< itemsCount { let menuItemFrame = itemFrames[index] let menuItem = MenuItem(frame: menuItemFrame) menuItem.tag = index + tagGap menuItem.delegate = self menuItem.text = dataSource.menuView(self, titleAtIndex: index) menuItem.textColor = normalColor if let optionalFontName = fontName { menuItem.font = UIFont(name: optionalFontName, size: selectedSize) } else { menuItem.font = UIFont.systemFontOfSize(selectedSize) } menuItem.normalSize = normalSize menuItem.selectedSize = selectedSize menuItem.normalColor = normalColor menuItem.selectedColor = selectedColor menuItem.selected = (index == 0) ? true : false if index == 0 { selectedItem = menuItem } contentView.addSubview(menuItem) } } private func addProgressView() { var optionalType: ProgressView.Type? var hollow = false switch style { case .Default: break case .Line: optionalType = ProgressView.self case .FooldHollow: optionalType = FooldView.self hollow = true case .Flood: optionalType = FooldView.self } if let viewType = optionalType { let pView = viewType.init() let height = (style == .Line) ? progressHeight : frame.size.height let progressY = (style == .Line) ? (frame.size.height - progressHeight) : 0 pView.frame = CGRect(x: 0, y: progressY, width: contentView.contentSize.width, height: height) pView.itemFrames = itemFrames if (progressColor == nil) { progressColor = selectedColor } pView.color = (progressColor?.CGColor)! pView.backgroundColor = .clearColor() if let fooldView = pView as? FooldView { fooldView.hollow = hollow } contentView.insertSubview(pView, atIndex: 0) progressView = pView } } // MARK: - Calculate Frames private func calculateFrames() { var contentWidth: CGFloat = itemMarginAtIndex(0) for index in 0 ..< itemsCount { let itemWidth = delegate!.menuView(self, widthForItemAtIndex: index) let itemFrame = CGRect(x: contentWidth, y: 0, width: itemWidth, height: frame.size.height) itemFrames.append(itemFrame) contentWidth += itemWidth + itemMarginAtIndex(index + 1) } if contentWidth < contentView.frame.size.width { let distance = contentView.frame.size.width - contentWidth let itemMargin = distance / CGFloat(itemsCount + 1) for index in 0 ..< itemsCount { var itemFrame = itemFrames[index] itemFrame.origin.x += itemMargin * CGFloat(index + 1) itemFrames[index] = itemFrame } contentWidth = contentView.frame.size.width } contentView.contentSize = CGSize(width: contentWidth, height: frame.size.height) } private func itemMarginAtIndex(index: Int) -> CGFloat { if let itemMargin = delegate?.menuView?(self, itemMarginAtIndex: index) { return itemMargin } return 0.0 } // MARK: - MenuItemDelegate func didSelectedMenuItem(menuItem: MenuItem) { if selectedItem == menuItem { return } let position = menuItem.tag - tagGap let currentIndex = selectedItem.tag - tagGap progressView?.moveToPosition(position, animation: true) delegate?.menuView?(self, didSelectedIndex: position, fromIndex: currentIndex) menuItem.selectWithAnimation(true) selectedItem.selectWithAnimation(false) selectedItem = menuItem refreshContentOffset() } }
apache-2.0
TwoRingSoft/SemVer
Vendor/Swiftline/SwiftlineTests/SwiftlineTests/ENVTests.swift
4
2018
import Foundation import Quick import Nimble @testable import Swiftline class ENVTests: QuickSpec { override func spec() { beforeEach { CommandExecutor.currentTaskExecutor = ActualTaskExecutor() } it("returns nil when key does not exists") { expect(Env.get("AAAAA")) .to(beNil()) } it("Reads environment variables") { Env.set("SomeKey", "SomeValue") expect(Env.get("SomeKey")).to(equal("SomeValue")) } it("clears key when nil is passed") { Env.set("SomeKey", "SomeValue") expect(Env.get("SomeKey")).to(equal("SomeValue")) Env.set("SomeKey", nil) expect(Env.get("SomeKey")).to(beNil()) } it("clears all env vars") { Env.set("SomeKey", "SomeValue") expect(Env.get("SomeKey")).to(equal("SomeValue")) Env.clear() expect(Env.get("SomeKey")).to(beNil()) } it("return all keys") { Env.clear() Env.set("key1", "value1") Env.set("key2", "value2") expect(Env.keys).to(equal(["key1", "key2"])) Env.clear() expect(Env.keys.count).to(equal(0)) } it("return all values") { Env.clear() Env.set("key1", "value1") Env.set("key2", "value2") expect(Env.values).to(equal(["value1", "value2"])) } it("checks if key exists") { Env.set("key1", "value1") expect(Env.hasKey("key1")).to(beTrue()) Env.clear() expect(Env.hasKey("key1")).to(beFalse()) } it("checks if value exists") { Env.set("key1", "value1") expect(Env.hasValue("value1")).to(beTrue()) Env.clear() expect(Env.hasValue("value1")).to(beFalse()) } it("enumerates keys and values") { Env.clear() Env.set("key1", "value1") Env.set("key2", "value2") Env.eachPair { expect(["key1", "key2"]).to(contain($0)) expect(["value1", "value2"]).to(contain($1)) } } } }
apache-2.0
skylib/SnapImagePicker
SnapImagePicker_Unit_Tests/SnapImagePickerPresenterTests.swift
1
11483
@testable import SnapImagePicker import XCTest class SnapImagePickerPresenterTests: XCTestCase, SnapImagePickerTestExpectationDelegate { private var interactor: SnapImagePickerInteractorSpy? private var viewController: SnapImagePickerViewControllerSpy? private var connector: SnapImagePickerConnectorSpy? private var presenter: SnapImagePickerPresenter? private var asyncExpectation: XCTestExpectation? var fulfillExpectation: (Void -> Void)? { get { return asyncExpectation?.fulfill } } override func setUp() { super.setUp() interactor = SnapImagePickerInteractorSpy(delegate: self) viewController = SnapImagePickerViewControllerSpy() connector = SnapImagePickerConnectorSpy() presenter = SnapImagePickerPresenter(view: viewController!) presenter?.interactor = interactor! presenter?.connector = connector } override func tearDown() { interactor = nil viewController = nil connector = nil presenter = nil super.tearDown() } private func createImage() -> UIImage? { return UIImage(named: "dummy.jpeg", inBundle: NSBundle(forClass: SnapImagePicker.self), compatibleWithTraitCollection: nil) } func testPresentInitialAlbum() { if let rawImage = createImage() { var image = SnapImagePickerImage(image: rawImage, localIdentifier: "localIdentifier", createdDate: NSDate()) var albumSize = 30 presenter?.presentInitialAlbum(image, albumSize: albumSize) XCTAssertEqual(1, viewController?.displayCount, "Presenter.presentInitialAlbum does not trigger ViewController.display") let viewModel = viewController?.displayViewModel XCTAssertNotNil(viewModel, "Presenter.presentInitialAlbum does not send a ViewModel to ViewController") XCTAssertEqual(AlbumType.AllPhotos.getAlbumName(), viewModel?.albumTitle, "Presenter does not default to \"All Photos\" as a title") XCTAssertEqual(image.image, viewModel?.mainImage?.image, "ViewModel contains wrong image after Presenter.presentInitialAlbum") XCTAssertEqual(image.localIdentifier, viewModel?.mainImage?.localIdentifier, "ViewModel contains wrong image after Presenter.presentInitialAlbum") XCTAssertEqual(image.createdDate, viewModel?.mainImage?.createdDate, "ViewModel contains wrong image after Presenter.presentInitialAlbum") XCTAssertEqual(0, viewModel?.selectedIndex, "ViewModel.selectedIndex is not 0 when presenting initial album with size \(albumSize)") XCTAssertFalse(viewModel?.isLoading ?? true, "ViewModel.isLoading is true when presenting initial album image") XCTAssertEqual(5, presenter?.numberOfSectionsForNumberOfColumns(6), "Presenter returned wrong number of sections") XCTAssertEqual(6, presenter?.numberOfItemsInSection(0, withColumns: 6), "Presenter returned wrong number of columns for a non-last section") XCTAssertEqual(0, presenter?.numberOfItemsInSection(100, withColumns: 6), "Presenter returned a number of columns for an invalid section") XCTAssertEqual(2, presenter?.numberOfItemsInSection(4, withColumns: 7), "Presenter returned wrong number of columns in the last section") image = SnapImagePickerImage(image: rawImage, localIdentifier: "localIdentifier2", createdDate: NSDate()) albumSize = 20 presenter?.presentInitialAlbum(image, albumSize: albumSize) XCTAssertEqual(2, viewController?.displayCount, "Presenter.presentInitialAlbum did not trigger ViewController.display") } else { XCTAssertTrue(false, "Unable to load image") } } func testPresentMainImage() { if let rawImage = createImage() { let image = SnapImagePickerImage(image: rawImage, localIdentifier: "localIdentifier", createdDate: NSDate()) let mainImage = SnapImagePickerImage(image: rawImage, localIdentifier: "mainImage", createdDate: NSDate()) var result = presenter?.presentMainImage(image) XCTAssertEqual(0, viewController?.displayCount, "Presenter.presentMainImage with invalid main image did trigger ViewController.display") XCTAssertFalse(result ?? true, "Presenter returned true when setting a non-requested main image") let size = 5 let index = size - 1 presenter?.presentInitialAlbum(image, albumSize: size) XCTAssertEqual(1, viewController?.displayCount, "Presenter.presentInitialAlbum did not trigger ViewController.display") presenter?.presentAlbumImage(mainImage, atIndex: index) presenter?.albumImageClicked(index) XCTAssertEqual(3, viewController?.displayCount, "Presenter.albumImageClicked did not trigger ViewController.display") XCTAssertEqual(index, viewController?.displayViewModel?.selectedIndex, "ViewModel.selectedImage does not match last clicked index") XCTAssertTrue(viewController?.displayViewModel?.isLoading ?? false, "ViewModel.isLoading set to false after requesting a new image") result = presenter?.presentMainImage(mainImage) XCTAssertTrue(result ?? false, "Presenter returned false when setting a requested main image") XCTAssertEqual(4, viewController?.displayCount, "Presenter.presentMainImage did not trigger ViewController.display") XCTAssertEqual(mainImage.image, viewController?.displayViewModel?.mainImage?.image, "ViewModel did not contain the latest requested main image") XCTAssertEqual(mainImage.localIdentifier, viewController?.displayViewModel?.mainImage?.localIdentifier, "ViewModel did not contain the latest requested main image") XCTAssertFalse(viewController?.displayViewModel?.isLoading ?? true, "ViewModel.isLoading set to true when displaying the currently requested main image") } else { XCTAssertTrue(false, "Unable to load image") } } func testPresentAlbumImage() { if let rawImage = createImage() { let image = SnapImagePickerImage(image: rawImage, localIdentifier: "localIdentifier", createdDate: NSDate()) let size = 5 let index = size - 1 presenter?.presentInitialAlbum(image, albumSize: size) XCTAssertEqual(1, viewController?.displayCount, "Presenter.presentInitialAlbum did no trigger ViewController.display") var result = presenter?.presentAlbumImage(image, atIndex: size + 1) XCTAssertFalse(result ?? true, "Presenter was able to present an album image at an index outside of album size range") result = presenter?.presentAlbumImage(image, atIndex: -1) XCTAssertFalse(result ?? true, "Presenter was able to present an album image at a negative index") result = presenter?.presentAlbumImage(image, atIndex: index) XCTAssertTrue(result ?? false, "Presenter was unable to present an image in valid album range") let cell = ImageCellMock() presenter?.presentCell(cell, atIndex: index) XCTAssertNotNil(cell.imageView?.image, "Presenter returned a cell without an image for a valid index") } else { XCTAssertTrue(false, "Unable to load image") } } func testViewWillAppearWithCellSize() { if let rawImage = createImage() { let image = SnapImagePickerImage(image: rawImage, localIdentifier: "localIdentifier", createdDate: NSDate()) let cellSize = CGFloat(0.0) presenter?.viewWillAppearWithCellSize(cellSize) presenter?.presentInitialAlbum(image, albumSize: 1) presenter?.scrolledToCells(0...1, increasing: true, fromOldRange: nil) XCTAssertEqual(1, interactor?.loadAlbumImageWithTypeCount, "Presenter.presentCell did not trigger Interactor.loadAlbumImageWithType") XCTAssertEqual(CGSize(width: cellSize, height: cellSize), interactor?.loadAlbumImageSize ?? CGSize(width: cellSize + 1000, height: cellSize + 1000), "Presenter did not store use cell width from viewWillAppearWithCellSize when requesting album images") } else { XCTAssertTrue(false, "Unable to load image") } } func testAlbumImageClicked() { if let rawImage = createImage() { let image = SnapImagePickerImage(image: rawImage, localIdentifier: "localIdentifier", createdDate: NSDate()) var result = presenter?.albumImageClicked(0) XCTAssertFalse(result ?? true, "Presenter properly handled click on album image before loading albums") let size = 5 let index = size - 1 presenter?.presentInitialAlbum(image, albumSize: size) result = presenter?.albumImageClicked(size + 1) XCTAssertFalse(result ?? true, "Presenter properly handled click on album image outside of album range") result = presenter?.albumImageClicked(index) XCTAssertFalse(result ?? true, "Presenter properly handled click on an album image which is yet not loaded") presenter?.presentAlbumImage(image, atIndex: index) result = presenter?.albumImageClicked(index) XCTAssertTrue(result ?? false, "Presenter was unable to handle click on loaded album image") XCTAssertEqual(1, interactor?.loadImageWithLocalIdentifierCount, "Presenter.albumImageClicked did not trigger Interactor.loadImageWithLocalIdentifier") XCTAssertEqual(image.localIdentifier, interactor?.loadImageWithLocalIdentifier, "Presenter.albumImageClicked triggered Interactor.loadImageWithLocalIdentifier with the wrong localIdentifier") } } func testSelectButtonPressed() { if let rawImage = createImage() { let options = ImageOptions(cropRect: CGRectZero, rotation: 0) presenter?.selectButtonPressed(rawImage, withImageOptions: options) XCTAssertEqual(1, connector?.setChosenImageCount, "Presenter.selectButtonPressed did not trigger Connector.setChosenImage") XCTAssertEqual(rawImage, connector?.setChosenImage, "Presenter.selectButtonPressed triggered Connector.setChosenImage with the wrong image") if let connectorOptions = connector?.setChosenImageOptions { XCTAssertEqual(options.cropRect, connectorOptions.cropRect, "Presenter.selectButtonPressed triggered Connector.setChosenImage with the wrong options") XCTAssertEqual(options.rotation, connectorOptions.rotation, "Presenter.selectButtonPressed triggered Connector.setChosenImage with the wrong options") } else { XCTAssertTrue(false, "Presenter.selectButtonPressed with options triggered Connector.setChosenImage without options") } } } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
bsd-3-clause
ryanspillsbury90/OmahaTutorial
ios/OmahaPokerTutorial/OmahaPokerTutorial/Constants.swift
1
432
// // Constants.swift // OmahaPokerTutorial // // Created by Ryan Pillsbury on 6/14/15. // Copyright (c) 2015 koait. All rights reserved. // import Foundation class Constants { enum ENVIRONMENT { case LOCAL case PROD }; static let ENV: ENVIRONMENT = .PROD static let API_ROOT = (ENV == .LOCAL ) ? "http://localhost:3000" : "http://ec2-52-26-229-215.us-west-2.compute.amazonaws.com" }
mit
wowiwj/Yeep
Yeep/Yeep/Extensions/NSURL+Yeep.swift
1
855
// // NSURL+Yeep.swift // Yeep // // Created by wangju on 16/7/19. // Copyright © 2016年 wangju. All rights reserved. // import UIKit extension NSURL { var yeep_isNetworkURL: Bool { switch scheme { case "http", "https": return true default: return false } } /// 判断是否为有效的网络地址 var yep_validSchemeNetworkURL: NSURL? { if scheme.isEmpty { guard let urlCompoments = NSURLComponents(URL: self, resolvingAgainstBaseURL: false) else{ return nil } urlCompoments.scheme = "http" return urlCompoments.URL }else { if yeep_isNetworkURL { return self } } return nil } }
mit
Conaaando/vector-texture-atlas
VectorTextureAtlas/AppDelegate.swift
1
428
// // AppDelegate.swift // VectorTextureAtlas // // Created by Fernando Fernandes on 3/5/15. // Copyright (c) 2015 Bigorna. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { return true } }
mit
zhangxigithub/Bonjour
Bonjour.swift
1
4891
// // AppDelegate.swift // demo // // Created by zhangxi on 12/25/15. // Copyright © 2015 http://zhangxi.me. All rights reserved. // import UIKit import MultipeerConnectivity let BonjourNotificationPeerKey = "BonjourNotificationPeerKey" let BonjourNotificationMessageKey = "BonjourNotificationMessageKey" protocol BonjourDelegate { func didConnectPeer(peerID:MCPeerID) func didDisconnectPeer(peerID:MCPeerID) func didReceiveMessage(message:String,peerID:MCPeerID) func didLost(peerID:MCPeerID) } class Bonjour : NSObject,MCSessionDelegate,MCNearbyServiceBrowserDelegate,MCNearbyServiceAdvertiserDelegate { var delegate:BonjourDelegate? var advertisier:MCNearbyServiceAdvertiser! var browser:MCNearbyServiceBrowser! var session:MCSession! var peerID : MCPeerID? let serviceType = "zx-bonjour" func bonjour(name:String? = nil) { if name == nil { peerID = MCPeerID(displayName: UIDevice.current.name) }else { peerID = MCPeerID(displayName: name!) } browser = MCNearbyServiceBrowser(peer: peerID!, serviceType: serviceType) browser.delegate = self browser.startBrowsingForPeers() advertisier = MCNearbyServiceAdvertiser(peer: peerID!, discoveryInfo: nil, serviceType: serviceType) advertisier.delegate = self advertisier.startAdvertisingPeer() session = MCSession(peer: peerID!) session.delegate = self } func sendMessage(message:String,mode:MCSessionSendDataMode = MCSessionSendDataMode.reliable) { do { if let data = message.data(using: .utf8) { try session.send(data, toPeers: session.connectedPeers, with: mode) } } catch{} } func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) { browser.invitePeer(peerID, to: session, withContext: nil, timeout: 20) } func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) { self.delegate?.didLost(peerID: peerID) } func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: Data?, invitationHandler: @escaping (Bool, MCSession?) -> Void) { invitationHandler(true,session) } func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) { } func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) { DispatchQueue.main.async { if let message = String(data: data, encoding: .utf8) { self.delegate?.didReceiveMessage(message: message, peerID: peerID) } } } func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) { } func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) { } func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) { } } /* //MARK: - MCNearbyServiceBrowserDelegate func browser(browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) { browser.invitePeer(peerID, toSession: session, withContext: nil, timeout: 20) } func browser(browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) { browser.invitePeer(peerID, toSession: session, withContext: nil, timeout: 20) } //MARK: - MCSessionDelegate func session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState) { switch state { case .NotConnected: dispatch_async(dispatch_get_main_queue()) { () -> Void in self.delegate?.didDisconnectPeer?(peerID) } case .Connecting: break case .Connected: dispatch_async(dispatch_get_main_queue()) { () -> Void in self.delegate?.didConnectPeer?(peerID) } } } func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID) { dispatch_async(dispatch_get_main_queue()) { () -> Void in if let message = String(data: data, encoding: NSUTF8StringEncoding) { self.delegate?.didReceiveMessage?(message, peerID: peerID) } } } */
apache-2.0
hgani/ganilib-ios
glib/Classes/View/Layout/GVerticalPanel.swift
1
7000
import UIKit open class GVerticalPanel: UIView, IView { private var helper: ViewHelper! private var previousViewElement: UIView! private var previousConstraint: NSLayoutConstraint! private var event: EventHelper<GVerticalPanel>! private var totalGap = Float(0.0) public var size: CGSize { return helper.size } private var paddings: Paddings { return helper.paddings } public init() { super.init(frame: .zero) initialize() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } private func initialize() { helper = ViewHelper(self) event = EventHelper(self) _ = paddings(top: 0, left: 0, bottom: 0, right: 0) addInitialBottomConstraint() } private func addInitialBottomConstraint() { previousConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0) previousConstraint.priority = UILayoutPriority(rawValue: 900) // Lower priority than fixed height addConstraint(previousConstraint) } open override func didMoveToSuperview() { super.didMoveToSuperview() helper.didMoveToSuperview() } public func clearViews() { // Remove it explicitly because it's not necessarily related to a child view, thus won't be removed // as part of view.removeFromSuperview() removeConstraint(previousConstraint) addInitialBottomConstraint() previousViewElement = nil for view in subviews { view.removeFromSuperview() } } public func addView(_ child: UIView, top: Float = 0) { totalGap += top // The hope is this makes things more predictable child.translatesAutoresizingMaskIntoConstraints = false super.addSubview(child) initChildConstraints(child: child, top: top) adjustSelfConstraints(child: child) previousViewElement = child } public func clear() -> Self { clearViews() return self } @discardableResult public func append(_ child: UIView, top: Float = 0) -> Self { addView(child, top: top) return self } // See https://github.com/zaxonus/AutoLayScroll/blob/master/AutoLayScroll/ViewController.swift private func initChildConstraints(child: UIView, top: Float) { child.snp.makeConstraints { make in if previousViewElement == nil { make.top.equalTo(self.snp.topMargin).offset(top) } else { make.top.equalTo(previousViewElement.snp.bottom).offset(top) } // make.left.equalTo(self.snp.leftMargin) switch horizontalAlign { case .center: make.centerX.equalTo(self) case .right: make.right.equalTo(self.snp.rightMargin) case .left: make.left.equalTo(self.snp.leftMargin) } } } private func adjustSelfConstraints(child: UIView) { snp.makeConstraints { (make) -> Void in make.rightMargin.greaterThanOrEqualTo(child.snp.right) } if !helper.shouldHeightMatchParent() { removeConstraint(previousConstraint) previousConstraint = NSLayoutConstraint(item: child, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottomMargin, multiplier: 1.0, constant: 0.0) previousConstraint.priority = UILayoutPriority(rawValue: 900) // At this point previousViewElement refers to the last subview, that is the one at the bottom. addConstraint(previousConstraint) } } @discardableResult public func width(_ width: Int) -> Self { helper.width(width) return self } @discardableResult public func width(_ width: LayoutSize) -> Self { helper.width(width) return self } @discardableResult public func width(weight: Float) -> Self { helper.width(weight: weight) return self } @discardableResult public func height(_ height: Int) -> Self { helper.height(height) return self } @discardableResult public func height(_ height: LayoutSize) -> Self { helper.height(height) return self } @discardableResult public func paddings(top: Float? = nil, left: Float? = nil, bottom: Float? = nil, right: Float? = nil) -> Self { helper.paddings(t: top, l: left, b: bottom, r: right) return self } @discardableResult public func color(bg: UIColor) -> Self { backgroundColor = bg return self } open override func addSubview(_: UIView) { fatalError("Use addView() instead") } public func border(color: UIColor?, width: Float = 1, corner: Float = 6) -> Self { helper.border(color: color, width: width, corner: corner) return self } public func hidden(_ hidden: Bool) -> Self { isHidden = hidden return self } public func onClick(_ command: @escaping (GVerticalPanel) -> Void) -> Self { event.onClick(command) return self } public func tap(_ command: (GVerticalPanel) -> Void) -> Self { command(self) return self } @discardableResult public func bg(image: UIImage?, repeatTexture: Bool) -> Self { helper.bg(image: image, repeatTexture: repeatTexture) return self } public func split() -> Self { let count = subviews.count GLog.i("Splitting \(count) views ...") let weight = 1.0 / Float(count) let offset = -(totalGap + paddings.top + paddings.bottom) / Float(count) for view in subviews { if let weightable = view as? GWeightable { _ = weightable.height(weight: weight, offset: offset) } else { GLog.e("Invalid child view: \(view)") } } return self } // MARK: - Alignment private var horizontalAlign: GAligner.GAlignerHorizontalGravity = .left public func align(_ align: GAligner.GAlignerHorizontalGravity) -> Self { horizontalAlign = align return self } public func done() { // Ends chaining } }
mit
matthew-healy/TableControlling
TableControllingTests/ProtocolTests/DynamicTableUpdatingTests.swift
1
1470
import XCTest @testable import TableControlling class DynamicTableUpdatingTests: XCTestCase { private let mockView = MockDataReloadable() // MARK: model: DynamicTable update() tests func test_update_dynamicTable_displaying_callsReloadData() { let sut = PartialMockDynamicTableUpdating( model: .displaying(.create()), view: mockView ) sut.update() XCTAssertTrue(mockView.didReloadData) } func test_update_dynamicTable_ready_doesNotCallReloadData() { let sut = PartialMockDynamicTableUpdating( model: .ready, view: mockView ) sut.update() XCTAssertFalse(mockView.didReloadData) } } private typealias BlankDynamicTable = DynamicTable<None, None, None, None, None> private class PartialMockDynamicTableUpdating: DynamicTableUpdating { typealias Model = BlankDynamicTable typealias View = MockDataReloadable typealias Header = None typealias SectionHeader = None typealias Cell = None typealias SectionFooter = None typealias Footer = None var model: BlankDynamicTable let view: MockDataReloadable init(model: BlankDynamicTable, view: MockDataReloadable) { self.model = model self.view = view } var didCallTableViewDidBeginLoading = false func tableViewDidBeginLoading() { didCallTableViewDidBeginLoading = true } }
mit
matthew-healy/TableControlling
TableControllingTests/StateTests/StaticTableTests.swift
1
3345
import XCTest @testable import TableControlling class StaticTableTests: XCTestCase { // MARK: equals tests var lhs: StaticTable<None, None, String, None, None>! var rhs: StaticTable<None, None, String, None, None>! func test_equals_bothReady_true() { (lhs, rhs) = (.ready, .ready) AssertSymmetricallyEqual(lhs, rhs) } func test_equals_oneReadyOneDisplay_false() { (lhs, rhs) = (.ready, .displaying(.create())) AssertSymmetricallyNotEqual(lhs, rhs) } func test_equals_bothDisplayMatchingTables_true() { lhs = .displaying(.create()) rhs = .displaying(.create()) AssertSymmetricallyEqual(lhs, rhs) } func test_equals_bothDisplayDifferentTables_false() { lhs = .displaying(.create(sections: [.create()])) rhs = .displaying(.create()) AssertSymmetricallyNotEqual(lhs, rhs) } // MARK: numberOfSections tests typealias StringStaticTable = StaticTable<None, None, String, None, None> typealias StringTable = Table<None, None, String, None, None> typealias StringTableSection = TableSection<None, String, None> var sut: StringStaticTable! func test_numberOfSections_ready_returns0() { sut = .ready XCTAssertEqual(0, sut.numberOfSections) } func test_numberOfSections_display_with1Section_returns1() { sut = .displaying(.create(sections: [.create()])) XCTAssertEqual(1, sut.numberOfSections) } func test_numberOfSections_display_with0Sections_returns0() { sut = .displaying(.create()) XCTAssertEqual(0, sut.numberOfSections) } // MARK: numberOfItems(inSection:_) tests func test_numberOfItemsInSection_0_ready_returns0() { sut = .ready XCTAssertEqual(0, sut.numberOfItems(inSection: 0)) } func test_numberOfItemsInSection_0_display_2CellsInSection0_returns2() { let twoCellSection: StringTableSection = .create(cells: ["", ""]) sut = .displaying(.create(sections: [twoCellSection])) XCTAssertEqual(2, sut.numberOfItems(inSection: 0)) } func test_numberOfItemsInSection_3_display_1CellInSection3_returns3() { let oneCellSection: StringTableSection = .create(cells: [""]) sut = .displaying( .create(sections: [.create(), .create(), .create(), oneCellSection]) ) XCTAssertEqual(1, sut.numberOfItems(inSection: 3)) } // MARK: item(at:) tests func test_itemAt_row0section1_ready_returnsNil() { sut = .ready XCTAssertNil(sut.item(at: IndexPath(row: 0, section: 1))) } func test_itemAt_row2Section0_display_cellHEYYAAtRow2Section0_returnsHEYYA() { let threeCellSection: StringTableSection = .create(cells: ["", "", "HEY YA"]) sut = .displaying(.create(sections: [threeCellSection])) XCTAssertEqual("HEY YA", sut.item(at: IndexPath(row: 2, section: 0))) } func test_itemAt_row1section2_display_cellSupAtRow1Section2_returnsSup() { let twoCellSection: StringTableSection = .create(cells: ["", "Sup"]) sut = .displaying(.create(sections: [.create(), .create(), twoCellSection])) XCTAssertEqual("Sup", sut.item(at: IndexPath(row: 1, section: 2))) } }
mit
SwiftGen/SwiftGen
Sources/SwiftGenKit/Parsers/Strings/FileTypeParser/StringsFileParser.swift
1
1063
// // SwiftGenKit // Copyright © 2022 SwiftGen // MIT Licence // import Foundation import PathKit extension Strings { final class StringsFileParser: StringsFileTypeParser { private let options: ParserOptionValues init(options: ParserOptionValues) { self.options = options } static let extensions = ["strings"] // Localizable.strings files are generally UTF16, not UTF8! func parseFile(at path: Path) throws -> [Strings.Entry] { guard let data = try? path.read() else { throw ParserError.failureOnLoading(path: path) } let entries = try PropertyListDecoder() .decode([String: String].self, from: data) .map { key, translation in try Entry(key: key, translation: translation, keyStructureSeparator: options[Option.separator]) } var dict = Dictionary(uniqueKeysWithValues: entries.map { ($0.key, $0) }) if let parser = StringsFileWithCommentsParser(file: path) { parser.enrich(entries: &dict) } return Array(dict.values) } } }
mit
ikait/KernLabel
KernLabel/KernLabel/Extensions/NSAttributedString+Extension.swift
1
3473
// // NSAttributedString+Extension.swift // KernLabel // // Created by ikai on 2016/05/26. // Copyright © 2016年 Taishi Ikai. All rights reserved. // import UIKit extension NSAttributedString { var lineHeight: CGFloat { guard let paragraphStyle = self.attributes[NSParagraphStyleAttributeName] as? NSParagraphStyle else { return self.font.lineHeight } let lineHeightMultiple = paragraphStyle.lineHeightMultiple return self.font.lineHeight * ((lineHeightMultiple.isZero) ? 1 : lineHeightMultiple) } var textAlignment: NSTextAlignment? { guard let paragraphStyle = self.attributes[NSParagraphStyleAttributeName] as? NSParagraphStyle else { return nil } return paragraphStyle.alignment } var backgroundColor: UIColor? { return self.attributes[NSBackgroundColorAttributeName] as? UIColor } var attributes: [String : Any] { if self.length != 0 { return self.attributes(at: 0, effectiveRange: nil) } else { return [:] } } var font: UIFont { if let font = self.attributes[NSFontAttributeName] as? UIFont { return font } return UIFont.systemFont(ofSize: UIFont.systemFontSize) } func substring(_ range: NSRange) -> String { return self.attributedSubstring(from: range).string } func substring(_ location: Int, _ length: Int) -> String { return self.substring(NSMakeRange(location, length)) } func getFont(_ location: Int) -> UIFont? { if let font = self.attributes(at: location, effectiveRange: nil)[NSFontAttributeName] as? UIFont { return font } return nil } func getLineHeight(_ location: Int) -> CGFloat { guard let paragraphStyle = self.attributes(at: location, effectiveRange: nil)[NSParagraphStyleAttributeName] as? NSParagraphStyle, let font = self.getFont(location) else { return self.font.lineHeight } let lineHeightMultiple = paragraphStyle.lineHeightMultiple return font.lineHeight * ((lineHeightMultiple.isZero) ? 1 : lineHeightMultiple) } func getTextAlignment(_ location: Int) -> NSTextAlignment? { guard let paragraphStyle = self.attributes(at: location, effectiveRange: nil)[NSParagraphStyleAttributeName] as? NSParagraphStyle else { return nil } return paragraphStyle.alignment } func mutableAttributedString(from range: NSRange) -> NSMutableAttributedString { return NSMutableAttributedString(attributedString: self.attributedSubstring(from: range)) } func boundingWidth(options: NSStringDrawingOptions, context: NSStringDrawingContext?) -> CGFloat { return self.boundingRect(options: options, context: context).size.width } func boundingRect(options: NSStringDrawingOptions, context: NSStringDrawingContext?) -> CGRect { return self.boundingRect(with: CGSize(width: kCGFloatHuge, height: kCGFloatHuge), options: options, context: context) } func boundingRectWithSize(_ size: CGSize, options: NSStringDrawingOptions, numberOfLines: Int, context: NSStringDrawingContext?) -> CGRect { let boundingRect = self.boundingRect( with: CGSize(width: size.width, height: self.lineHeight * CGFloat(numberOfLines)), options: options, context: context) return boundingRect } }
mit
nathawes/swift
test/NameLookup/stdlib-case-sensitive.swift
66
234
// RUN: not %target-swift-frontend %s -typecheck // RUN: not %target-swift-frontend -parse-stdlib %s -typecheck // Just don't crash when accidentally importing "SWIFT" instead of "Swift". import SWIFT print("hi") SWIFT.print("hi")
apache-2.0
necrowman/CRLAlamofireFuture
Examples/SimpleTvOSCarthage/Carthage/Checkouts/RunLoop/RunLoop/Sync.swift
111
1914
//===--- Sync.swift ----------------------------------------------===// //Copyright (c) 2016 Daniel Leping (dileping) // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //===----------------------------------------------------------------------===// import Foundation import Boilerplate import Result public extension RunLoopType { private func syncThroughAsync<ReturnType>(task:() throws -> ReturnType) throws -> ReturnType { if let settled = self as? SettledType where settled.isHome { return try task() } var result:Result<ReturnType, AnyError>? let sema = RunLoop.current.semaphore() self.execute { defer { sema.signal() } result = materializeAny(task) } sema.wait() return try result!.dematerializeAny() } private func syncThroughAsync2<ReturnType>(task:() throws -> ReturnType) rethrows -> ReturnType { //rethrow hack return try { try self.syncThroughAsync(task) }() } /*public func sync<ReturnType>(@autoclosure(escaping) task:() throws -> ReturnType) rethrows -> ReturnType { return try syncThroughAsync2(task) }*/ public func sync<ReturnType>(task:() throws -> ReturnType) rethrows -> ReturnType { return try syncThroughAsync2(task) } }
mit
Piwigo/Piwigo-Mobile
piwigo/Settings/Help/Help01ViewController.swift
1
3024
// // Help01ViewController.swift // piwigo // // Created by Eddy Lelièvre-Berna on 30/11/2020. // Copyright © 2020 Piwigo.org. All rights reserved. // import UIKit import piwigoKit class Help01ViewController: UIViewController { @IBOutlet weak var legend: UILabel! @IBOutlet weak var imageView: UIImageView! private let helpID: UInt16 = 0b00000000_00000001 // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() // Initialise mutable attributed string let legendAttributedString = NSMutableAttributedString(string: "") // Title let titleString = "\(NSLocalizedString("help01_header", comment: "Multiple Selection"))\n" let titleAttributedString = NSMutableAttributedString(string: titleString) titleAttributedString.addAttribute(.font, value: view.bounds.size.width > 320 ? UIFont.piwigoFontBold() : UIFont.piwigoFontSemiBold(), range: NSRange(location: 0, length: titleString.count)) legendAttributedString.append(titleAttributedString) // Text let textString = NSLocalizedString("help01_text", comment: "Slide your finger from left to right (or right to left) then down, etc.") let textAttributedString = NSMutableAttributedString(string: textString) textAttributedString.addAttribute(.font, value: view.bounds.size.width > 320 ? UIFont.piwigoFontNormal() : UIFont.piwigoFontSmall(), range: NSRange(location: 0, length: textString.count)) legendAttributedString.append(textAttributedString) // Set legend legend.attributedText = legendAttributedString // Set image view guard let imageUrl = Bundle.main.url(forResource: "help01", withExtension: "png") else { fatalError("!!! Could not find help01 image !!!") } imageView.layoutIfNeeded() // Ensure imageView is in its final size. let size = imageView.bounds.size let scale = imageView.traitCollection.displayScale imageView.image = ImageUtilities.downsample(imageAt: imageUrl, to: size, scale: scale) // Remember that this view was watched AppVars.shared.didWatchHelpViews = AppVars.shared.didWatchHelpViews | helpID } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Set colors, fonts, etc. applyColorPalette() // Register palette changes NotificationCenter.default.addObserver(self, selector: #selector(applyColorPalette), name: .pwgPaletteChanged, object: nil) } @objc func applyColorPalette() { // Background color of the view view.backgroundColor = .piwigoColorBackground() // Legend color legend.textColor = .piwigoColorText() } deinit { // Unregister palette changes NotificationCenter.default.removeObserver(self, name: .pwgPaletteChanged, object: nil) } }
mit
sschiau/swift
test/APINotes/versioned-objc.swift
2
9050
// RUN: %empty-directory(%t) // RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 5 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-5 %s // RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 4 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-4 %s // REQUIRES: objc_interop import APINotesFrameworkTest // CHECK-DIAGS-5-NOT: versioned-objc.swift:[[@LINE-1]]: class ProtoWithVersionedUnavailableMemberImpl: ProtoWithVersionedUnavailableMember { // CHECK-DIAGS-4: versioned-objc.swift:[[@LINE-1]]:7: error: type 'ProtoWithVersionedUnavailableMemberImpl' cannot conform to protocol 'ProtoWithVersionedUnavailableMember' because it has requirements that cannot be satisfied func requirement() -> Any? { return nil } } func testNonGeneric() { // CHECK-DIAGS-4:[[@LINE+1]]:{{[0-9]+}}: error: cannot convert value of type 'Any' to specified type 'Int' let _: Int = NewlyGenericSub.defaultElement() // CHECK-DIAGS-5:[[@LINE-1]]:{{[0-9]+}}: error: generic parameter 'Element' could not be inferred // CHECK-DIAGS-4:[[@LINE+1]]:{{[0-9]+}}: error: cannot specialize non-generic type 'NewlyGenericSub' let _: Int = NewlyGenericSub<Base>.defaultElement() // CHECK-DIAGS-5:[[@LINE-1]]:{{[0-9]+}}: error: cannot convert value of type 'Base' to specified type 'Int' } func testRenamedGeneric() { // CHECK-DIAGS-4-NOT: 'RenamedGeneric' has been renamed to 'OldRenamedGeneric' let _: OldRenamedGeneric<Base> = RenamedGeneric<Base>() // CHECK-DIAGS-5:[[@LINE-1]]:{{[0-9]+}}: error: 'OldRenamedGeneric' has been renamed to 'RenamedGeneric' // CHECK-DIAGS-4-NOT: 'RenamedGeneric' has been renamed to 'OldRenamedGeneric' let _: RenamedGeneric<Base> = OldRenamedGeneric<Base>() // CHECK-DIAGS-5:[[@LINE-1]]:{{[0-9]+}}: error: 'OldRenamedGeneric' has been renamed to 'RenamedGeneric' class SwiftClass {} // CHECK-DIAGS-4:[[@LINE+1]]:{{[0-9]+}}: error: 'OldRenamedGeneric' requires that 'SwiftClass' inherit from 'Base' let _: OldRenamedGeneric<SwiftClass> = RenamedGeneric<SwiftClass>() // CHECK-DIAGS-5:[[@LINE-1]]:{{[0-9]+}}: error: 'OldRenamedGeneric' requires that 'SwiftClass' inherit from 'Base' // CHECK-DIAGS-4:[[@LINE+1]]:{{[0-9]+}}: error: 'RenamedGeneric' requires that 'SwiftClass' inherit from 'Base' let _: RenamedGeneric<SwiftClass> = OldRenamedGeneric<SwiftClass>() // CHECK-DIAGS-5:[[@LINE-1]]:{{[0-9]+}}: error: 'RenamedGeneric' requires that 'SwiftClass' inherit from 'Base' } func testRenamedClassMembers(obj: ClassWithManyRenames) { // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'classWithManyRenamesForInt' has been replaced by 'init(swift4Factory:)' _ = ClassWithManyRenames.classWithManyRenamesForInt(0) // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'classWithManyRenamesForInt' has been replaced by 'init(for:)' // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'init(forInt:)' has been renamed to 'init(swift4Factory:)' _ = ClassWithManyRenames(forInt: 0) // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'init(forInt:)' has been renamed to 'init(for:)' // CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}: _ = ClassWithManyRenames(swift4Factory: 0) // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'init(swift4Factory:)' has been renamed to 'init(for:)' // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'init(for:)' has been renamed to 'init(swift4Factory:)' _ = ClassWithManyRenames(for: 0) // CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}: // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(swift4Boolean:)' _ = ClassWithManyRenames(boolean: false) // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(finalBoolean:)' // CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}: _ = ClassWithManyRenames(swift4Boolean: false) // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'init(swift4Boolean:)' has been renamed to 'init(finalBoolean:)' // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'init(finalBoolean:)' has been renamed to 'init(swift4Boolean:)' _ = ClassWithManyRenames(finalBoolean: false) // CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}: // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'swift4DoImportantThings()' obj.doImportantThings() // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'finalDoImportantThings()' // CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}: obj.swift4DoImportantThings() // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'swift4DoImportantThings()' has been renamed to 'finalDoImportantThings()' // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'finalDoImportantThings()' has been renamed to 'swift4DoImportantThings()' obj.finalDoImportantThings() // CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}: // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'swift4ClassProperty' _ = ClassWithManyRenames.importantClassProperty // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'finalClassProperty' // CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}: _ = ClassWithManyRenames.swift4ClassProperty // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'swift4ClassProperty' has been renamed to 'finalClassProperty' // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'finalClassProperty' has been renamed to 'swift4ClassProperty' _ = ClassWithManyRenames.finalClassProperty // CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}: } func testRenamedProtocolMembers(obj: ProtoWithManyRenames) { // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(swift4Boolean:)' _ = type(of: obj).init(boolean: false) // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(finalBoolean:)' // CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}: _ = type(of: obj).init(swift4Boolean: false) // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'init(swift4Boolean:)' has been renamed to 'init(finalBoolean:)' // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'init(finalBoolean:)' has been renamed to 'init(swift4Boolean:)' _ = type(of: obj).init(finalBoolean: false) // CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}: // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'swift4DoImportantThings()' obj.doImportantThings() // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'finalDoImportantThings()' // CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}: obj.swift4DoImportantThings() // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'swift4DoImportantThings()' has been renamed to 'finalDoImportantThings()' // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'finalDoImportantThings()' has been renamed to 'swift4DoImportantThings()' obj.finalDoImportantThings() // CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}: // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'swift4ClassProperty' _ = type(of: obj).importantClassProperty // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'finalClassProperty' // CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}: _ = type(of: obj).swift4ClassProperty // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'swift4ClassProperty' has been renamed to 'finalClassProperty' // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'finalClassProperty' has been renamed to 'swift4ClassProperty' _ = type(of: obj).finalClassProperty // CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}: } extension PrintingRenamed { func testDroppingRenamedPrints() { // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: warning: use of 'print' treated as a reference to instance method print() // CHECK-DIAGS-5-NOT: [[@LINE-1]]:{{[0-9]+}}: // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: warning: use of 'print' treated as a reference to instance method print(self) // CHECK-DIAGS-5-NOT: [[@LINE-1]]:{{[0-9]+}}: } static func testDroppingRenamedPrints() { // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: warning: use of 'print' treated as a reference to class method print() // CHECK-DIAGS-5-NOT: [[@LINE-1]]:{{[0-9]+}}: // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: warning: use of 'print' treated as a reference to class method print(self) // CHECK-DIAGS-5-NOT: [[@LINE-1]]:{{[0-9]+}}: } } extension PrintingInterference { func testDroppingRenamedPrints() { // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: warning: use of 'print' treated as a reference to instance method print(self) // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: missing argument for parameter 'extra' in call // CHECK-DIAGS-4-NOT: [[@LINE+1]]:{{[0-9]+}}: print(self, extra: self) // CHECK-DIAGS-5-NOT: [[@LINE-1]]:{{[0-9]+}}: } } let unrelatedDiagnostic: Int = nil
apache-2.0
practicalswift/swift
test/Interpreter/unresolvable_dynamic_metadata_cycles.swift
4
1908
// RUN: %empty-directory(%t) // RUN: %target-build-swift-dylib(%t/%target-library-name(resil)) -Xfrontend -enable-resilience %S/Inputs/resilient_generic_struct_v1.swift -emit-module -emit-module-path %t/resil.swiftmodule -module-name resil // RUN: %target-codesign %t/%target-library-name(resil) // RUN: %target-build-swift %s -L %t -I %t -lresil -o %t/main %target-rpath(%t) // RUN: %target-codesign %t/main // RUN: %target-build-swift-dylib(%t/%target-library-name(resil)) -Xfrontend -enable-resilience %S/Inputs/resilient_generic_struct_v2.swift -emit-module -emit-module-path %t/resil.swiftmodule -module-name resil // RUN: %target-codesign %t/%target-library-name(resil) // RUN: %target-run %t/main %t/%target-library-name(resil) // REQUIRES: executable_test import StdlibUnittest // We build this code against a version of 'resil' where // ResilientGenericStruct<T> doesn't store a T, then switch the // dynamic library to a new version where it does, introducing // an unresolvable dynamic cycle. // // It would also be sufficient to demonstrate this crash if the // compiler *actually* didn't know about the internal implementation // details of 'resil' when building this file, but since it currently // still does, it'll report a cycle immediately if we don't pull // this switcharoo. import resil var DynamicMetadataCycleTests = TestSuite("Unresolvable dynamic metadata cycle tests") enum test0_Node { case link(ResilientGenericStruct<test0_Node>) } DynamicMetadataCycleTests.test("cycle through enum") .crashOutputMatches("runtime error: unresolvable type metadata dependency cycle detected") .crashOutputMatches(" main.test0_Node") .crashOutputMatches(" depends on layout of resil.ResilientGenericStruct<main.test0_Node") .crashOutputMatches(" depends on layout of main.test0_Node") .code { expectCrashLater() _blackHole(test0_Node.self) } runAllTests()
apache-2.0
3lvis/NetworkActivityIndicator
Demo/AppDelegate.swift
1
282
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { return true } }
mit
blockchain/My-Wallet-V3-iOS
Modules/FeatureCardIssuing/Sources/FeatureCardIssuingDomain/Model/Card.swift
1
3119
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation public struct Card: Codable, Equatable, Identifiable { public let id: String public let type: CardType public let last4: String /// Expiry date of the card in mm/yy format public let expiry: String public let brand: Brand public let status: Status public let orderStatus: [OrderStatus]? public let createdAt: String public init( id: String, type: Card.CardType, last4: String, expiry: String, brand: Card.Brand, status: Card.Status, orderStatus: [Card.OrderStatus]?, createdAt: String ) { self.id = id self.type = type self.last4 = last4 self.expiry = expiry self.brand = brand self.status = status self.orderStatus = orderStatus self.createdAt = createdAt } } extension Card { public enum CardType: String, Codable { case virtual = "VIRTUAL" case physical = "PHYSICAL" } public enum Brand: String, Codable { case visa = "VISA" case mastercard = "MASTERCARD" } public enum Status: String, Codable { case initiated = "INITIATED" case created = "CREATED" case active = "ACTIVE" case terminated = "TERMINATED" case suspended = "SUSPENDED" case unsupported = "UNSUPPORTED" case unactivated = "UNACTIVATED" case limited = "LIMITED" case locked = "LOCKED" } public struct OrderStatus: Codable, Equatable { let status: Status let date: Date } public struct Address: Codable, Hashable { public enum Constants { static let usIsoCode = "US" public static let usPrefix = "US-" } public let line1: String? public let line2: String? public let city: String? public let postCode: String? public let state: String? /// Country code in ISO-2 public let country: String? public init( line1: String?, line2: String?, city: String?, postCode: String?, state: String?, country: String? ) { self.line1 = line1 self.line2 = line2 self.city = city self.postCode = postCode self.country = country if let state = state, country == Constants.usIsoCode, !state.hasPrefix(Constants.usPrefix) { self.state = Constants.usPrefix + state } else { self.state = state } } } } extension Card.OrderStatus { public enum Status: String, Codable { case ordered = "ORDERED" case shipped = "SHIPPED" case delivered = "DELIVERED" } } extension Card { public var creationDate: Date? { DateFormatter.iso8601Format.date(from: createdAt) } public var isLocked: Bool { status == .locked } }
lgpl-3.0
farion/eloquence
Eloquence/Core/EloConnection.swift
1
11978
import Foundation import XMPPFramework @objc protocol EloConnectionDelegate: NSObjectProtocol { } class EloConnection: NSObject, XMPPRosterDelegate,XMPPStreamDelegate, XMPPCapabilitiesDelegate, MulticastDelegateContainer { private let account:EloAccount private let xmppStream:XMPPStream private let xmppRoster:XMPPRoster private let xmppCapabilities:XMPPCapabilities private let xmppMessageArchiveManagement: EloXMPPMessageArchiveManagement // let xmppvCardTempModule:XMPPvCardTempModule typealias DelegateType = EloConnectionDelegate; var multicastDelegate = [EloConnectionDelegate]() init(account:EloAccount){ self.account = account xmppStream = XMPPStream(); xmppRoster = XMPPRoster(rosterStorage: EloXMPPRosterCoreDataStorage.sharedInstance()) // xmppvCardTempModule = XMPPvCardTempModule.init(withvCardStorage: XMPPvCardCoreDataStorage.sharedInstance()) // xmppvCardTempModule!.activate(xmppStream) xmppRoster.autoFetchRoster = true; xmppRoster.autoAcceptKnownPresenceSubscriptionRequests = true; xmppRoster.activate(xmppStream); xmppCapabilities = XMPPCapabilities(capabilitiesStorage: XMPPCapabilitiesCoreDataStorage.sharedInstance()); //get server capabilities => XEP0030 xmppCapabilities.autoFetchMyServerCapabilities = true; xmppCapabilities.activate(xmppStream) xmppMessageArchiveManagement = EloXMPPMessageArchiveManagement(messageArchiveManagementStorage: EloXMPPMessageArchiveManagementWithContactCoreDataStorage.sharedInstance()) xmppMessageArchiveManagement.activate(xmppStream) super.init(); xmppRoster.addDelegate(self, delegateQueue: dispatch_get_main_queue()) xmppStream.addDelegate(self, delegateQueue: dispatch_get_main_queue()) xmppCapabilities.addDelegate(self, delegateQueue: dispatch_get_main_queue()) xmppMessageArchiveManagement.addDelegate(self, delegateQueue: dispatch_get_main_queue()) } func isConnected() -> Bool { return xmppStream.isConnected(); } func getXMPPStream() -> XMPPStream { return xmppStream; } func getArchive() -> EloXMPPMessageArchiveManagement { return xmppMessageArchiveManagement; } func connect(){ NSLog("Connect"); if(!xmppStream.isConnected()){ // var presence = XMPPPresence(); // let priority = DDXMLElement.elementWithName("priority", stringValue: "1") as! DDXMLElement; var resource = account.getResource(); if(resource == nil || resource!.isEmpty){ resource = "Eloquence"; } xmppStream.myJID = XMPPJID.jidWithString(account.getJid().jid,resource:resource); let port = account.getPort(); if(port != nil && port > 0){ xmppStream.hostPort = UInt16.init(port!); } let domain = account.getServer(); if(domain != nil && domain!.isEmpty){ xmppStream.hostName = domain; } do { try xmppStream.connectWithTimeout(XMPPStreamTimeoutNone); }catch { NSLog("error"); print(error); } } } //MARK: XMPP Delegates func xmppStreamDidConnect(sender: XMPPStream!) { NSLog("Did Connect"); do { try xmppStream.authenticateWithPassword(account.getPassword()); }catch { NSLog("error"); print(error); } } func xmppStreamWillConnect(sender:XMPPStream) { NSLog("Will Connect"); } func xmppStream(sender: XMPPStream!, alternativeResourceForConflictingResource conflictingResource: String!) -> String! { NSLog("alternativeResourceForConflictingResource"); return conflictingResource; } func xmppStream(sender: XMPPStream!, didFailToSendIQ iq: XMPPIQ!, error: NSError!) { NSLog("didFailToSendIQ"); } func xmppStream(sender: XMPPStream!, didFailToSendMessage message: XMPPMessage!, error: NSError!) { NSLog("didFailToSendMessage"); } func xmppStream(sender: XMPPStream!, didFailToSendPresence presence: XMPPPresence!, error: NSError!) { NSLog("didFailToSendPresence"); } #if os(iOS) func xmppStream(sender: XMPPStream!, didNotAuthenticate error: DDXMLElement!) { NSLog("didNotAuthenticate"); } #else func xmppStream(sender: XMPPStream!, didNotAuthenticate error: NSXMLElement!) { NSLog("didNotAuthenticate"); } #endif #if os(iOS) func xmppStream(sender: XMPPStream!, didNotRegister error: DDXMLElement!) { NSLog("didNotRegister"); } #else func xmppStream(sender: XMPPStream!, didNotRegister error: NSXMLElement!) { NSLog("didNotRegister"); } #endif #if os(iOS) func xmppStream(sender: XMPPStream!, didReceiveCustomElement element: DDXMLElement!) { NSLog("didReceiveCustomElement"); } #else func xmppStream(sender: XMPPStream!, didReceiveCustomElement element: NSXMLElement!) { NSLog("didReceiveCustomElement"); } #endif #if os(iOS) func xmppStream(sender: XMPPStream!, didReceiveError error: DDXMLElement!) { NSLog("didReceiveError"); } #else func xmppStream(sender: XMPPStream!, didReceiveError error: NSXMLElement!) { NSLog("didReceiveError"); } #endif func xmppStream(sender: XMPPStream!, didReceiveIQ iq: XMPPIQ!) -> Bool { NSLog("didReceiveIQ"); /* let queryElement = iq.elementForName("query",xmlns:"jabber:iq:roster"); if(queryElement != nil){ let itemElements = queryElement!.elementsForName("item"); for var i = 0; i < itemElements.count; ++i { let jid = itemElements[i].attributeForName("jid")!.stringValue; NSLog("%@",jid!); } } */ return true; } func xmppStream(sender: XMPPStream!, didReceiveMessage message: XMPPMessage!) { NSLog("didReceiveMessage"); } #if os(iOS) func xmppStream(sender: XMPPStream!, didReceiveP2PFeatures streamFeatures: DDXMLElement!) { NSLog("didReceiveP2PFeatures"); } #else func xmppStream(sender: XMPPStream!, didReceiveP2PFeatures streamFeatures: NSXMLElement!) { NSLog("didReceiveP2PFeatures"); } #endif func xmppStream(sender: XMPPStream!, didReceivePresence presence: XMPPPresence!) { NSLog("didReceivePresence"); } func xmppStream(sender: XMPPStream!, didReceiveTrust trust: SecTrust!, completionHandler: ((Bool) -> Void)!) { NSLog("didReceiveTrust"); } func xmppStream(sender: XMPPStream!, didRegisterModule module: AnyObject!) { NSLog("didRegisterModule"); } #if os(iOS) func xmppStream(sender: XMPPStream!, didSendCustomElement element: DDXMLElement!) { NSLog("didSendCustomElement"); } #else func xmppStream(sender: XMPPStream!, didSendCustomElement element: NSXMLElement!) { NSLog("didSendCustomElement"); } #endif func xmppStream(sender: XMPPStream!, didSendIQ iq: XMPPIQ!) { NSLog("didSendIQ"); } func xmppStream(sender: XMPPStream!, didSendMessage message: XMPPMessage!) { NSLog("didSendMessage"); } func xmppStream(sender: XMPPStream!, didSendPresence presence: XMPPPresence!) { NSLog("didSendPresence"); } func xmppStream(sender: XMPPStream!, willReceiveIQ iq: XMPPIQ!) -> XMPPIQ! { NSLog("willReceiveIQ"); return iq; } func xmppStream(sender: XMPPStream!, willReceiveMessage message: XMPPMessage!) -> XMPPMessage! { NSLog("willReceiveMessage"); return message; } func xmppStream(sender: XMPPStream!, willReceivePresence presence: XMPPPresence!) -> XMPPPresence! { NSLog("willReceivePresence"); return presence; } func xmppStream(sender: XMPPStream!, willSecureWithSettings settings: NSMutableDictionary!) { NSLog("willSecureWithSettings"); } func xmppStream(sender: XMPPStream!, willSendIQ iq: XMPPIQ!) -> XMPPIQ! { NSLog("willSendIQ"); return iq; } func xmppStream(sender: XMPPStream!, willSendMessage message: XMPPMessage!) -> XMPPMessage! { NSLog("willSendMessage"); return message; } #if os(iOS) func xmppStream(sender: XMPPStream!, willSendP2PFeatures streamFeatures: DDXMLElement!) { NSLog("willSendP2PFeatures"); } #else func xmppStream(sender: XMPPStream!, willSendP2PFeatures streamFeatures: NSXMLElement!) { NSLog("willSendP2PFeatures"); } #endif func xmppStream(sender: XMPPStream!, willSendPresence presence: XMPPPresence!) -> XMPPPresence! { NSLog("willSendPresence"); return presence; } func xmppStream(sender: XMPPStream!, willUnregisterModule module: AnyObject!) { NSLog("willUnregisterModule"); } func xmppStreamConnectDidTimeout(sender: XMPPStream!) { NSLog("xmppStreamConnectDidTimeout"); } func xmppStreamDidAuthenticate(sender: XMPPStream!) { NSLog("xmppStreamDidAuthenticate"); NSNotificationCenter.defaultCenter().postNotificationName(EloConstants.CONNECTION_ONLINE, object: self); // EloXMPPMessageArchiveManagement.mamQueryWith(sender.myJID , andStart: nil, andEnd: nil, andResultSet: nil) } func xmppStreamDidChangeMyJID(xmppStream: XMPPStream!) { NSLog("xmppStreamDidChangeMyJID"); } func xmppStreamDidDisconnect(sender: XMPPStream!, withError error: NSError!) { NSLog("xmppStreamDidDisconnect"); } func xmppStreamDidFilterStanza(sender: XMPPStream!) { NSLog("xmppStreamDidFilterStanza"); } func xmppStreamDidRegister(sender: XMPPStream!) { NSLog("xmppStreamDidRegister"); } func xmppStreamDidSecure(sender: XMPPStream!) { NSLog("xmppStreamDidSecure"); } func xmppStreamDidSendClosingStreamStanza(sender: XMPPStream!) { NSLog("xmppStreamDidSendClosingStreamStanza"); } func xmppStreamDidStartNegotiation(sender: XMPPStream!) { NSLog("xmppStreamDidStartNegotiation"); } func xmppStreamWasToldToDisconnect(sender: XMPPStream!) { NSLog("xmppStreamWasToldToDisconnect"); } func xmppRosterDidEndPopulating(sender: XMPPRoster!) { NSLog("xmppRosterDidEndPopulating"); } func xmppRoster(sender: XMPPRoster!, didReceiveRosterPush iq: XMPPIQ!) { } #if os(iOS) func xmppRoster(sender: XMPPRoster!, didReceiveRosterItem item: DDXMLElement!) { } #else func xmppRoster(sender: XMPPRoster!, didReceiveRosterItem item: NSXMLElement!) { } #endif func xmppRoster(sender: XMPPRoster!, didReceivePresenceSubscriptionRequest presence: XMPPPresence!) { NSLog("xmppRosterdidReceivePresenceSubscriptionRequest"); } func xmppRosterDidBeginPopulating(sender: XMPPRoster!, withVersion version: String!) { NSLog("xmppRosterdidReceivePresenceSubscriptionRequest"); } #if os(iOS) func xmppCapabilities(sender: XMPPCapabilities!, didDiscoverCapabilities caps: DDXMLElement!, forJID jid: XMPPJID!) { NSLog("xmppCapabilities %@",jid.bare()); } #else func xmppCapabilities(sender: XMPPCapabilities!, didDiscoverCapabilities caps: NSXMLElement!, forJID jid: XMPPJID!) { NSLog("xmppCapabilities %@",jid.bare()); } #endif }
apache-2.0
object-kazu/JabberwockProtoType
JabberWock/JabberWock/ViewController.swift
1
1867
// // ViewController.swift // JabberWock // // Created by 清水 一征 on 2016/12/01. // Copyright © 2016年 momiji-mac. All rights reserved. // import UIKit class ViewController: UIViewController,UIWebViewDelegate { @IBOutlet weak var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() webView.delegate = self jqueryLoad() // パスを取得する // ドキュメントパス let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String // ファイル名 let fileName = EXPORT_TEST_File // // 保存する場所 let path = documentsPath + "/" + fileName let url = NSURL(string: path)! // リクエストを生成する let request = NSURLRequest(url: url as URL) // リクエストを投げる webView.loadRequest(request as URLRequest) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // ロード時にインジケータをまわす func webViewDidStartLoad(_ webView: UIWebView) { UIApplication.shared.isNetworkActivityIndicatorVisible = true print("indicator on") } // ロード完了でインジケータ非表示 func webViewDidFinishLoad(_ webView: UIWebView) { UIApplication.shared.isNetworkActivityIndicatorVisible = false print("indicator off") } // js load func jqueryLoad(){ let path = Bundle.main.path(forResource: "jquery-3.1.1.min", ofType: "js") let jsCode = try? String(contentsOfFile: path!, encoding: String.Encoding.utf8) webView.stringByEvaluatingJavaScript(from: jsCode!) } }
mit
vector-im/riot-ios
Riot/Categories/String.swift
1
1528
/* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation extension String { /// Calculates a numeric hash same as Riot Web /// See original function here https://github.com/matrix-org/matrix-react-sdk/blob/321dd49db4fbe360fc2ff109ac117305c955b061/src/utils/FormattingUtils.js#L47 var vc_hashCode: Int32 { var hash: Int32 = 0 for character in self { let shiftedHash = hash << 5 hash = shiftedHash.subtractingReportingOverflow(hash).partialValue + Int32(character.vc_unicodeScalarCodePoint) } return abs(hash) } /// Locale-independent case-insensitive contains /// Note: Prefer use `localizedCaseInsensitiveContains` when locale matters /// /// - Parameter other: The other string. /// - Returns: true if current string contains other string. func vc_caseInsensitiveContains(_ other: String) -> Bool { return self.range(of: other, options: .caseInsensitive) != nil } }
apache-2.0
jad6/CV
Swift/Jad's CV/Other/Subclasses/DynamicType/DynamicTypeCollectionViewCell.swift
1
1038
// // DynamicTypeCollectionViewCell.swift // Jad's CV // // Created by Jad Osseiran on 29/07/2014. // Copyright (c) 2014 Jad. All rights reserved. // import UIKit class DynamicTypeCollectionViewCell: UICollectionViewCell { //MARK:- Init required init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) NSNotificationCenter.defaultCenter().addObserver(self, selector: "didChangePreferredContentSize:", name: UIContentSizeCategoryDidChangeNotification, object: nil) self.reloadDynamicTypeContent() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } //MARK:- Abstract Method func reloadDynamicTypeContent() { } func optimalCellSize() -> CGSize { return CGSizeZero } //MARK:- Notification func didChangePreferredContentSize(notification: NSNotification) { reloadDynamicTypeContent() } }
bsd-3-clause
kuririnz/KkListActionSheet-Swift
KkListActionSheetSwift/source/KkListActionSheet.swift
1
16178
// // KkListActionSheet.swift // KkListActionSheetSwift // // Created by keisuke kuribayashi on 2015/10/11. // Copyright © 2015年 keisuke kuribayashi. All rights reserved. // import UIKit let ANIM_ALPHA_KEY = "animAlpha" let ANIM_MOVE_KEY = "animMove" let ORIENT_VERTICAL = "PORTRAIT" let ORIENT_HORIZONTAL = "LANDSCAPE" var styleIndex = HIGHSTYLE.DEFAULT public enum HIGHSTYLE : Int { case DEFAULT = 0 case MIDDLE = 1 case LOW = 2 } @objc public protocol KkListActionSheetDelegate: class { // required Delegate MEthod // set row index func kkTableView(tableView: UITableView, rowsInSection section: NSInteger) -> NSInteger // create row cell instance func kkTableView(tableView: UITableView, currentIndx indexPath: NSIndexPath) -> UITableViewCell // oprional Delegate Method // set the selected item Action in this tableview optional func kkTableView(tableView: UITableView, selectIndex indexPath: NSIndexPath) // set each row height in this tableview optional func kkTableView(tableView: UITableView, heightRowIndex indexPath: NSIndexPath) -> CGFloat } public class KkListActionSheet: UIView, UITableViewDelegate, UITableViewDataSource { // MARK: self delegate public weak var delegate : KkListActionSheetDelegate! = nil // MARK: Member Variable @IBOutlet weak var kkTableView : UITableView! @IBOutlet weak var kkActionSheetBackGround : UIView! @IBOutlet weak var kkActionSheet : UIView! @IBOutlet weak var titleLabel : UILabel! @IBOutlet weak var kkCloseButton : KkListCloseButton! var displaySize : CGRect = CGRectMake(0, 0, 0, 0) var centerY : CGFloat = 0.0 var orientList : NSArray = [] var supportOrientList : NSArray = [] var animatingFlg : Bool = false var screenStyle : CGSize = CGSizeMake(0, 0) // MARK: initialized required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // init process displaySize = UIScreen.mainScreen().bounds self.setHighPosition() orientList = ["UIInterfaceOrientationPortrait", "UIInterfaceOrientationPortraitUpsideDown", "UIInterfaceOrientationLandscapeLeft", "UIInterfaceOrientationLandscapeRight"] if Float(UIDevice.currentDevice().systemVersion) > 8.0 { supportOrientList = NSBundle.mainBundle().objectForInfoDictionaryKey("UISupportedInterfaceOrientations") as! NSArray } else { let infoDictionary = NSBundle.mainBundle().infoDictionary! as Dictionary supportOrientList = infoDictionary["UISupportedInterfaceOrientations"]! as! NSArray } self.hidden = true } override public func awakeFromNib() { super.awakeFromNib() self.initialKkListActionSheet() } public class func createInit(parent: UIViewController) -> KkListActionSheet { let className = NSStringFromClass(KkListActionSheet) let currentIdx = className.rangeOfString(".") styleIndex = HIGHSTYLE.DEFAULT // NSBundleを調べる let frameworkBundle = NSBundle(forClass: KkListActionSheet.self) let nib = UINib(nibName: className.substringFromIndex(currentIdx!.endIndex), bundle: frameworkBundle) let initClass = nib.instantiateWithOwner(nil, options: nil).first as! KkListActionSheet parent.view.addSubview(initClass) return initClass } public class func createInit(parent: UIViewController, style styleIdx:HIGHSTYLE) -> KkListActionSheet { let className = NSStringFromClass(KkListActionSheet) let currentIdx = className.rangeOfString(".") styleIndex = styleIdx let initClass = NSBundle.mainBundle().loadNibNamed(className.substringFromIndex(currentIdx!.endIndex), owner: nil, options: nil).first as! KkListActionSheet parent.view.addSubview(initClass) return initClass } // initial Method private func initialKkListActionSheet() { animatingFlg = false // Set BackGround Alpha kkActionSheetBackGround.alpha = 0.0 let largeOrientation = displaySize.size.width > displaySize.size.height ? displaySize.size.width:displaySize.size.height // Setting BackGround Layout kkActionSheetBackGround.translatesAutoresizingMaskIntoConstraints = true var kkActionSheetBgRect = kkActionSheetBackGround.frame as CGRect kkActionSheetBgRect.size.width = largeOrientation kkActionSheetBgRect.size.height = largeOrientation kkActionSheetBackGround.frame = kkActionSheetBgRect // Setting ListActionSheet Layout kkActionSheet.translatesAutoresizingMaskIntoConstraints = true var kkActionSheetRect = kkActionSheet.frame as CGRect kkActionSheetRect.origin = CGPointMake(0, displaySize.size.height - screenStyle.height) kkActionSheetRect.size.width = displaySize.size.width kkActionSheetRect.size.height = screenStyle.height kkActionSheet.frame = kkActionSheetRect // Setting CloseButton Layout kkCloseButton.translatesAutoresizingMaskIntoConstraints = true var closeBtnRect = kkCloseButton.frame closeBtnRect.size.width = largeOrientation closeBtnRect.size.height = displaySize.size.height * 0.085 let tmpX = closeBtnRect.size.width - displaySize.size.width closeBtnRect.origin = CGPointMake(tmpX > 0 ? tmpX / 2 : 0, 0) kkCloseButton.frame = closeBtnRect centerY = kkActionSheet.center.y // TapGesuture Event let backGroundGesture = UITapGestureRecognizer(target: self, action: Selector("onTapGesture:")) let tapGesture = UITapGestureRecognizer(target: self, action: Selector("onTapGesture:")) kkActionSheetBackGround.addGestureRecognizer(backGroundGesture) kkCloseButton.addGestureRecognizer(tapGesture) // PanGesture Event if styleIndex != HIGHSTYLE.LOW { let panGesture = UIPanGestureRecognizer(target: self, action: Selector("onPanGesture:")) kkCloseButton.addGestureRecognizer(panGesture) } // set device change notification center if supportOrientList.count > 1 { NSNotificationCenter.defaultCenter().addObserver(self, selector: "didRotation:", name: "UIDeviceOrientationDidChangeNotification", object: nil) } } func setHighPosition () { screenStyle.width = displaySize.width if displaySize.size.width > displaySize.size.height { screenStyle.height = styleIndex == HIGHSTYLE.DEFAULT ? displaySize.size.height * 2 / 3 : displaySize.size.height / 2 } else { if styleIndex == HIGHSTYLE.MIDDLE { screenStyle.height = displaySize.size.height / 2 } else if styleIndex == HIGHSTYLE.LOW { screenStyle.height = displaySize.size.height / 3 } else { screenStyle.height = displaySize.size.height * 2 / 3 } } } public func setHiddenTitle () { titleLabel.translatesAutoresizingMaskIntoConstraints = true titleLabel.hidden = true var tmpRect = titleLabel.frame tmpRect.size.height = 0 titleLabel.frame = tmpRect } public func setHiddenScrollbar (value: Bool) { kkTableView.showsVerticalScrollIndicator = value kkTableView.showsHorizontalScrollIndicator = value } // MARK: Customize Method public func setTitle (title: String) { self.titleLabel.text = title } public func setAttrTitle (attrTitle: NSAttributedString) { self.titleLabel.attributedText = attrTitle } // MARK: Gesture Recognizer Action func onTapGesture(recognizer: UITapGestureRecognizer) { self.showHide() } func onPanGesture(recognizer: UIPanGestureRecognizer) { let location = recognizer.translationInView(self) var moveRect = self.kkActionSheet.frame let afterPosition = moveRect.origin.y + location.y if recognizer.state == UIGestureRecognizerState.Ended { if centerY > afterPosition { self.kkListActionSheetReturenAnimation(afterPosition) } else { self.kkListActionSheetAnimation(afterPosition) } } else { let checkHeight = styleIndex == HIGHSTYLE.DEFAULT ? displaySize.size.height / 3 : screenStyle.height if checkHeight < afterPosition { moveRect.origin = CGPointMake(0, afterPosition) self.kkActionSheet.frame = moveRect } } recognizer.setTranslation(CGPointZero, inView: self) } // MARK: KkListAction Animation Method public func showHide () { self.kkListActionSheetAnimation(self.kkActionSheet.frame.size.height) } private func kkListActionSheetAnimation (param: CGFloat) { if animatingFlg { return } animatingFlg = true var fromPositionY :CGFloat var toPositionY :CGFloat var toAlpha :CGFloat let currentAlpha = kkActionSheetBackGround.alpha if currentAlpha == 0.0 { fromPositionY = param toPositionY = 0 toAlpha = 0.8 } else { fromPositionY = 0.0 toPositionY = param toAlpha = 0.0 } let moveAnim = CABasicAnimation(keyPath: "transform.translation.y") moveAnim.duration = 0.5 moveAnim.repeatCount = 1 moveAnim.autoreverses = false moveAnim.removedOnCompletion = false moveAnim.fillMode = kCAFillModeForwards moveAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) moveAnim.fromValue = fromPositionY as NSNumber moveAnim.toValue = toPositionY as NSNumber let alphaAnim = CABasicAnimation(keyPath: "opacity") alphaAnim.delegate = self alphaAnim.duration = 0.4 alphaAnim.repeatCount = 1 alphaAnim.autoreverses = false alphaAnim.removedOnCompletion = false alphaAnim.fillMode = kCAFillModeForwards alphaAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) alphaAnim.fromValue = currentAlpha as NSNumber alphaAnim.toValue = toAlpha self.hidden = false kkActionSheet.layer.addAnimation(moveAnim, forKey: ANIM_MOVE_KEY) kkActionSheetBackGround.layer.addAnimation(alphaAnim, forKey: ANIM_ALPHA_KEY) } private func kkListActionSheetReturenAnimation(param: CGFloat) { if animatingFlg { return } animatingFlg = true UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { var tmp = self.kkActionSheet.frame as CGRect tmp.origin = CGPointMake(0, self.displaySize.height - self.screenStyle.height) self.kkActionSheet.frame = tmp }, completion: {(finish: Bool) in self.animatingFlg = false } ) } // MARK: CABasicAnimation Inheritance Method override public func animationDidStop(anim: CAAnimation, finished flag: Bool) { if anim == kkActionSheetBackGround.layer.animationForKey(ANIM_ALPHA_KEY) { let currentAnimation = anim as! CABasicAnimation kkActionSheetBackGround.alpha = currentAnimation.toValue as! CGFloat kkActionSheetBackGround.layer.removeAnimationForKey(ANIM_ALPHA_KEY) if kkActionSheetBackGround.alpha == 0.0 { self.hidden = true var tmpPosition = kkActionSheet.frame tmpPosition.origin = CGPointMake(0, displaySize.size.height - screenStyle.height) kkActionSheet.frame = tmpPosition } animatingFlg = false } } // MARK: Change Device Rotate Method func didRotation(notification: NSNotification) { let orientation = UIDevice.currentDevice().orientation as UIDeviceOrientation if !orientation.isPortrait && !orientation.isLandscape { return } let nowRotate = orientList.objectAtIndex(orientation.rawValue - 1) as! String if orientation.isPortrait { if self.supportOrientList.indexOfObject(nowRotate) != NSNotFound { self.changeOrientationTransform(nowRotate) } } else if orientation.isLandscape { if self.supportOrientList.indexOfObject(nowRotate) != NSNotFound { self.changeOrientationTransform(nowRotate) } } } private func changeOrientationTransform (orientState: String) { if !animatingFlg { UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { if Float(UIDevice.currentDevice().systemVersion) > 9.0 { self.displaySize.size = UIScreen.mainScreen().bounds.size } else { let tmpWidth = UIScreen.mainScreen().bounds.size.width let tmpHeight = UIScreen.mainScreen().bounds.size.height let isLargeWidth = tmpWidth > tmpHeight if orientState == ORIENT_VERTICAL { self.displaySize.size.width = isLargeWidth ? tmpHeight: tmpWidth self.displaySize.size.height = isLargeWidth ? tmpWidth : tmpHeight } else if orientState == ORIENT_HORIZONTAL { self.displaySize.size.width = isLargeWidth ? tmpWidth : tmpHeight self.displaySize.size.height = isLargeWidth ? tmpHeight : tmpWidth } } self.setHighPosition() let tmpX = self.kkCloseButton.frame.size.width - self.displaySize.size.width self.kkActionSheet.translatesAutoresizingMaskIntoConstraints = true self.kkActionSheet.frame.origin = CGPointMake(0, self.displaySize.size.height - self.screenStyle.height) self.kkActionSheet.frame.size.width = self.displaySize.size.width self.kkActionSheet.frame.size.height = self.screenStyle.height self.kkCloseButton.frame.origin = CGPointMake(tmpX > 0 ? -(tmpX / 2) : 0, 0) self.centerY = self.kkActionSheet.center.y; }, completion: {(finish: Bool) in self.animatingFlg = false }) } } // MARK: UITableView Delegate / Datasource public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return self.delegate.kkTableView(tableView, currentIndx: indexPath) } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.delegate.kkTableView(tableView, rowsInSection: section) } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.delegate.kkTableView!(tableView, selectIndex: indexPath) tableView.deselectRowAtIndexPath(indexPath, animated: false) } public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var tmpHeight = self.delegate.kkTableView?(tableView, heightRowIndex: indexPath) if tmpHeight == nil { let cell = self.tableView(tableView, cellForRowAtIndexPath: indexPath) tmpHeight = cell.frame.size.height } return tmpHeight! } }
mit
Jnosh/swift
test/expr/closure/closures.swift
6
13781
// RUN: %target-typecheck-verify-swift var func6 : (_ fn : (Int,Int) -> Int) -> () var func6a : ((Int, Int) -> Int) -> () var func6b : (Int, (Int, Int) -> Int) -> () func func6c(_ f: (Int, Int) -> Int, _ n: Int = 0) {} // Expressions can be auto-closurified, so that they can be evaluated separately // from their definition. var closure1 : () -> Int = {4} // Function producing 4 whenever it is called. var closure2 : (Int,Int) -> Int = { 4 } // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{36-36= _,_ in}} var closure3a : () -> () -> (Int,Int) = {{ (4, 2) }} // multi-level closing. var closure3b : (Int,Int) -> (Int) -> (Int,Int) = {{ (4, 2) }} // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{52-52=_,_ in }} var closure4 : (Int,Int) -> Int = { $0 + $1 } var closure5 : (Double) -> Int = { $0 + 1.0 // expected-error {{cannot convert value of type 'Double' to closure result type 'Int'}} } var closure6 = $0 // expected-error {{anonymous closure argument not contained in a closure}} var closure7 : Int = { 4 } // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{9-9=()}} var capturedVariable = 1 var closure8 = { [capturedVariable] in capturedVariable += 1 // expected-error {{left side of mutating operator isn't mutable: 'capturedVariable' is an immutable capture}} } func funcdecl1(_ a: Int, _ y: Int) {} func funcdecl3() -> Int {} func funcdecl4(_ a: ((Int) -> Int), _ b: Int) {} func funcdecl5(_ a: Int, _ y: Int) { // Pass in a closure containing the call to funcdecl3. funcdecl4({ funcdecl3() }, 12) // expected-error {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{14-14= _ in}} func6({$0 + $1}) // Closure with two named anonymous arguments func6({($0) + $1}) // Closure with sequence expr inferred type func6({($0) + $0}) // // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}} var testfunc : ((), Int) -> Int // expected-note {{'testfunc' declared here}} testfunc({$0+1}) // expected-error {{missing argument for parameter #2 in call}} funcdecl5(1, 2) // recursion. // Element access from a tuple. var a : (Int, f : Int, Int) var b = a.1+a.f // Tuple expressions with named elements. var i : (y : Int, x : Int) = (x : 42, y : 11) funcdecl1(123, 444) // Calls. 4() // expected-error {{cannot call value of non-function type 'Int'}}{{4-6=}} // rdar://12017658 - Infer some argument types from func6. func6({ a, b -> Int in a+b}) // Return type inference. func6({ a,b in a+b }) // Infer incompatible type. func6({a,b -> Float in 4.0 }) // expected-error {{declared closure result 'Float' is incompatible with contextual type 'Int'}} {{17-22=Int}} // Pattern doesn't need to name arguments. func6({ _,_ in 4 }) func6({a,b in 4.0 }) // expected-error {{cannot convert value of type 'Double' to closure result type 'Int'}} // TODO: This diagnostic can be improved: rdar://22128205 func6({(a : Float, b) in 4 }) // expected-error {{cannot convert value of type '(Float, _) -> Int' to expected argument type '(Int, Int) -> Int'}} var fn = {} var fn2 = { 4 } var c : Int = { a,b -> Int in a+b} // expected-error{{cannot convert value of type '(Int, Int) -> Int' to specified type 'Int'}} } func unlabeledClosureArgument() { func add(_ x: Int, y: Int) -> Int { return x + y } func6a({$0 + $1}) // single closure argument func6a(add) func6b(1, {$0 + $1}) // second arg is closure func6b(1, add) func6c({$0 + $1}) // second arg is default int func6c(add) } // rdar://11935352 - closure with no body. func closure_no_body(_ p: () -> ()) { return closure_no_body({}) } // rdar://12019415 func t() { let u8 : UInt8 = 1 let x : Bool = true if 0xA0..<0xBF ~= Int(u8) && x { } } // <rdar://problem/11927184> func f0(_ a: Any) -> Int { return 1 } assert(f0(1) == 1) var selfRef = { selfRef() } // expected-error {{variable used within its own initial value}} var nestedSelfRef = { var recursive = { nestedSelfRef() } // expected-error {{variable used within its own initial value}} recursive() } var shadowed = { (shadowed: Int) -> Int in let x = shadowed return x } // no-warning var shadowedShort = { (shadowedShort: Int) -> Int in shadowedShort+1 } // no-warning func anonymousClosureArgsInClosureWithArgs() { func f(_: String) {} var a1 = { () in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}} var a2 = { () -> Int in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}} var a3 = { (z: Int) in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{26-28=z}} var a4 = { (z: [Int], w: [Int]) in f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{7-9=z}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}} f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}} } var a5 = { (_: [Int], w: [Int]) in f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}} f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}} } } func doStuff(_ fn : @escaping () -> Int) {} func doVoidStuff(_ fn : @escaping () -> ()) {} // <rdar://problem/16193162> Require specifying self for locations in code where strong reference cycles are likely class ExplicitSelfRequiredTest { var x = 42 func method() -> Int { // explicit closure requires an explicit "self." base. doVoidStuff({ self.x += 1 }) doStuff({ x+1 }) // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{15-15=self.}} doVoidStuff({ x += 1 }) // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{19-19=self.}} // Methods follow the same rules as properties, uses of 'self' must be marked with "self." doStuff { method() } // expected-error {{call to method 'method' in closure requires explicit 'self.' to make capture semantics explicit}} {{15-15=self.}} doVoidStuff { _ = method() } // expected-error {{call to method 'method' in closure requires explicit 'self.' to make capture semantics explicit}} {{23-23=self.}} doStuff { self.method() } // <rdar://problem/18877391> "self." shouldn't be required in the initializer expression in a capture list // This should not produce an error, "x" isn't being captured by the closure. doStuff({ [myX = x] in myX }) // This should produce an error, since x is used within the inner closure. doStuff({ [myX = {x}] in 4 }) // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{23-23=self.}} // expected-warning @-1 {{capture 'myX' was never used}} return 42 } } class SomeClass { var field : SomeClass? func foo() -> Int {} } func testCaptureBehavior(_ ptr : SomeClass) { // Test normal captures. weak var wv : SomeClass? = ptr unowned let uv : SomeClass = ptr unowned(unsafe) let uv1 : SomeClass = ptr unowned(safe) let uv2 : SomeClass = ptr doStuff { wv!.foo() } doStuff { uv.foo() } doStuff { uv1.foo() } doStuff { uv2.foo() } // Capture list tests let v1 : SomeClass? = ptr let v2 : SomeClass = ptr doStuff { [weak v1] in v1!.foo() } // expected-warning @+2 {{variable 'v1' was written to, but never read}} doStuff { [weak v1, // expected-note {{previous}} weak v1] in v1!.foo() } // expected-error {{definition conflicts with previous value}} doStuff { [unowned v2] in v2.foo() } doStuff { [unowned(unsafe) v2] in v2.foo() } doStuff { [unowned(safe) v2] in v2.foo() } doStuff { [weak v1, weak v2] in v1!.foo() + v2!.foo() } let i = 42 // expected-warning @+1 {{variable 'i' was never mutated}} {{19-20=let}} doStuff { [weak i] in i! } // expected-error {{'weak' may only be applied to class and class-bound protocol types, not 'Int'}} } extension SomeClass { func bar() { doStuff { [unowned self] in self.foo() } doStuff { [unowned xyz = self.field!] in xyz.foo() } doStuff { [weak xyz = self.field] in xyz!.foo() } // rdar://16889886 - Assert when trying to weak capture a property of self in a lazy closure doStuff { [weak self.field] in field!.foo() } // expected-error {{fields may only be captured by assigning to a specific name}} expected-error {{reference to property 'field' in closure requires explicit 'self.' to make capture semantics explicit}} {{36-36=self.}} // expected-warning @+1 {{variable 'self' was written to, but never read}} doStuff { [weak self&field] in 42 } // expected-error {{expected ']' at end of capture list}} } func strong_in_capture_list() { // <rdar://problem/18819742> QOI: "[strong self]" in capture list generates unhelpful error message _ = {[strong self] () -> () in return } // expected-error {{expected 'weak', 'unowned', or no specifier in capture list}} } } // <rdar://problem/16955318> Observed variable in a closure triggers an assertion var closureWithObservedProperty: () -> () = { var a: Int = 42 { willSet { _ = "Will set a to \(newValue)" } didSet { _ = "Did set a with old value of \(oldValue)" } } } ; {}() // expected-error{{top-level statement cannot begin with a closure expression}} // rdar://19179412 - Crash on valid code. func rdar19179412() -> (Int) -> Int { return { x in class A { let d : Int = 0 } } } // Test coercion of single-expression closure return types to void. func takesVoidFunc(_ f: () -> ()) {} var i: Int = 1 // expected-warning @+1 {{expression of type 'Int' is unused}} takesVoidFunc({i}) // expected-warning @+1 {{expression of type 'Int' is unused}} var f1: () -> () = {i} var x = {return $0}(1) func returnsInt() -> Int { return 0 } takesVoidFunc(returnsInt) // expected-error {{cannot convert value of type '() -> Int' to expected argument type '() -> ()'}} takesVoidFunc({() -> Int in 0}) // expected-error {{declared closure result 'Int' is incompatible with contextual type '()'}} {{22-25=()}} // These used to crash the compiler, but were fixed to support the implementation of rdar://problem/17228969 Void(0) // expected-error{{argument passed to call that takes no arguments}} _ = {0} // <rdar://problem/22086634> "multi-statement closures require an explicit return type" should be an error not a note let samples = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{16-16= () -> Bool in }} if (i > 10) { return true } else { return false } }() // <rdar://problem/19756953> Swift error: cannot capture '$0' before it is declared func f(_ fp : (Bool, Bool) -> Bool) {} f { $0 && !$1 } // <rdar://problem/18123596> unexpected error on self. capture inside class method func TakesIntReturnsVoid(_ fp : ((Int) -> ())) {} struct TestStructWithStaticMethod { static func myClassMethod(_ count: Int) { // Shouldn't require "self." TakesIntReturnsVoid { _ in myClassMethod(0) } } } class TestClassWithStaticMethod { class func myClassMethod(_ count: Int) { // Shouldn't require "self." TakesIntReturnsVoid { _ in myClassMethod(0) } } } // Test that we can infer () as the result type of these closures. func genericOne<T>(_ a: () -> T) {} func genericTwo<T>(_ a: () -> T, _ b: () -> T) {} genericOne {} genericTwo({}, {}) // <rdar://problem/22344208> QoI: Warning for unused capture list variable should be customized class r22344208 { func f() { let q = 42 let _: () -> Int = { [unowned self, // expected-warning {{capture 'self' was never used}} q] in // expected-warning {{capture 'q' was never used}} 1 } } } var f = { (s: Undeclared) -> Int in 0 } // expected-error {{use of undeclared type 'Undeclared'}} // <rdar://problem/21375863> Swift compiler crashes when using closure, declared to return illegal type. func r21375863() { var width = 0 var height = 0 var bufs: [[UInt8]] = (0..<4).map { _ -> [asdf] in // expected-error {{use of undeclared type 'asdf'}} [UInt8](repeating: 0, count: width*height) } } // <rdar://problem/25993258> // Don't crash if we infer a closure argument to have a tuple type containing inouts. func r25993258_helper(_ fn: (inout Int, Int) -> ()) {} func r25993258a() { r25993258_helper { x in () } // expected-error {{named parameter has type '(inout Int, Int)' which includes nested inout parameters}} } func r25993258b() { r25993258_helper { _ in () } } // We have to map the captured var type into the right generic environment. class GenericClass<T> {} func lvalueCapture<T>(c: GenericClass<T>) { var cc = c weak var wc = c func innerGeneric<U>(_: U) { _ = cc _ = wc cc = wc! } }
apache-2.0
simonnarang/Fandom
Desktop/Fandom-IOS-master/Fandomm/TabBarViewController.swift
1
1973
// // TabBarViewController.swift // Fandomm // // Created by Simon Narang on 11/29/15. // Copyright © 2015 Simon Narang. All rights reserved. // import UIKit class TabBarViewController: UITabBarController { var usernameTwo = String() override func viewDidLoad() { super.viewDidLoad() let dataTransferViewControllerOne = (self.viewControllers?[0] as! UINavigationController).viewControllers[0] as! FeedTableViewController dataTransferViewControllerOne.usernameTwoTextOne = usernameTwo let dataTransferViewControllerTwo = (self.viewControllers?[1] as! UINavigationController).viewControllers[0] as! SearchTableViewController dataTransferViewControllerTwo.usernameTwoTextTwo = usernameTwo let dataTransferViewControllerThree = (self.viewControllers?[2] as! UINavigationController).viewControllers[0] as! PostViewController dataTransferViewControllerThree.usernameTwoTextThree = usernameTwo let dataTransferViewControllerFour = (self.viewControllers?[3] as! UINavigationController).viewControllers[0] as! ProfileViewController dataTransferViewControllerFour.usernameTwoTextFour = usernameTwo let dataTransferViewControllerFive = (self.viewControllers?[4] as! UINavigationController).viewControllers[0] as! PreferecesTableViewController dataTransferViewControllerFive.userameTwoTextFive = usernameTwo } 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. } */ }
unlicense
devcarlos/NSDateUtils.swift
NSDateUtilsTests/NSDateUtilsTests.swift
1
993
// // NSDateUtilsTests.swift // NSDateUtilsTests // // Created by Carlos Alcala on 6/2/16. // Copyright © 2016 Carlos Alcala. All rights reserved. // import XCTest @testable import NSDateUtils class NSDateUtilsTests: 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. } } }
mit
amrap-labs/TeamupKit
Sources/TeamupKit/Controllers/Sessions/Waitlists/WaitlistsController.swift
1
1445
// // WaitlistsController.swift // TeamupKit // // Created by Merrick Sapsford on 20/06/2017. // Copyright © 2017 Merrick Sapsford. All rights reserved. // import Foundation public protocol WaitlistsController: class { /// Load the waitlist for a session. /// /// - Parameters: /// - session: The session to load the waitlist for. /// - success: Closure to execute on successful request. /// - failure: Closure to execute of failed request. func load(forSession session: Session, success: ((Session.Waitlist) -> Void)?, failure: Controller.MethodFailure?) /// Join the waitlist for a session. /// /// - Parameters: /// - session: The session to join the waitlist for. /// - success: Closure to execute on successful request. /// - failure: Closure to execute of failed request. func join(forSession session: Session, success: ((Session.Waitlist) -> Void)?, failure: Controller.MethodFailure?) /// Leave the waitlist for a session. /// /// - Parameters: /// - session: The session to leave the waitlist for. /// - success: Closure to execute on successful request. /// - failure: Closure to execute of failed request. func leave(forSession session: Session, success: ((Session.Waitlist) -> Void)?, failure: Controller.MethodFailure?) }
mit
Jnosh/swift
test/Interpreter/subclass_existentials.swift
15
10882
//===--- subclass_existentials.swift --------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %target-build-swift %s -o %t/a.out // RUN: %target-run %t/a.out // REQUIRES: executable_test import StdlibUnittest protocol P { init(protocolInit: ()) func protocolMethodReturnsSelf() -> Self static func staticProtocolMethodReturnsSelf() -> Self var protocolProperty: Int { get set } static var staticProtocolProperty: Int { get set } subscript<U : Hashable>(protocolKey protocolKey: U) -> Int { get set } } protocol R {} extension R { func extensionMethod() -> Self { return self } } var globalVar = 8 class Base<T> : R { var x: T var y: T var token = LifetimeTracked(0) var dict: [AnyHashable : T] = [:] required init(x: T, y: T) { self.x = x self.y = y } func classMethodReturnsSelf() -> Self { return self } func finalClassMethod() -> (T, T) { return (x, y) } func nonFinalClassMethod() -> (T, T) { return (x, y) } var propertyToOverride: Int = -8 class var classPropertyToOverride: Int { get { return globalVar } set { globalVar = newValue } } subscript<U : Hashable>(key: U) -> T { get { return dict[key]! } set { self.dict[key] = newValue } } } class Derived : Base<Int>, P { required init(x: Int, y: Int) { super.init(x: x, y: y) } override func nonFinalClassMethod() -> (Int, Int) { return (y, x) } override var propertyToOverride: Int { get { return super.propertyToOverride * 2 } set { super.propertyToOverride = newValue / 2 } } class override var classPropertyToOverride: Int { get { return super.classPropertyToOverride * 2 } set { super.classPropertyToOverride = newValue / 2 } } convenience required init(protocolInit: ()) { self.init(x: 10, y: 20) } func protocolMethodReturnsSelf() -> Self { return self } static func staticProtocolMethodReturnsSelf() -> Self { return self.init(x: -1000, y: -2000) } var protocolProperty: Int = 100 static var staticProtocolProperty: Int = 2000 subscript<U : Hashable>(protocolKey protocolKey: U) -> Int { get { return dict[protocolKey]! } set { self.dict[protocolKey] = newValue } } } protocol Q : class {} var SubclassExistentialsTestSuite = TestSuite("SubclassExistentials") SubclassExistentialsTestSuite.test("Metadata instantiation") { expectTrue((Base<String> & Base<String>).self == Base<String>.self) expectTrue((Base<String> & Any).self == Base<String>.self) expectTrue((Base<Int> & Q).self == (Q & Base<Int>).self) expectTrue((Base<Int> & P & Q).self == (P & Base<Int> & Q).self) expectTrue((P & Q & Base<Int>).self == (Q & Base<Int> & P).self) expectTrue((P & Q).self == (P & Q & AnyObject).self) expectTrue((P & Q).self == (Q & P & AnyObject).self) expectTrue((Base<Int> & Q).self == (Q & Base<Int> & AnyObject).self) expectFalse((R & AnyObject).self == R.self) } SubclassExistentialsTestSuite.test("Metadata to string") { expectEqual("Base<Int> & P", String(describing: (Base<Int> & P).self)) expectEqual("Base<Int> & P & Q", String(describing: (Base<Int> & P & Q).self)) } SubclassExistentialsTestSuite.test("Call instance methods") { do { let value: Base<Int> & P = Derived(x: 123, y: 321) // Basic method calls expectTrue(value === value.classMethodReturnsSelf()) expectTrue((123, 321) == value.finalClassMethod()) expectTrue((321, 123) == value.nonFinalClassMethod()) expectTrue(value === value.extensionMethod()) // Partial application do { let fn = value.classMethodReturnsSelf expectTrue(value === fn()) } do { let fn = value.finalClassMethod expectTrue((123, 321) == fn()) } do { let fn = value.nonFinalClassMethod expectTrue((321, 123) == fn()) } } expectEqual(0, LifetimeTracked.instances) } SubclassExistentialsTestSuite.test("Access instance properties") { do { let value: Base<Int> & P = Derived(x: 123, y: 321) expectEqual(-16, value.propertyToOverride) value.propertyToOverride += 4 expectEqual(-12, value.propertyToOverride) value.propertyToOverride += 1 expectEqual(-10, value.propertyToOverride) } expectEqual(0, LifetimeTracked.instances) } SubclassExistentialsTestSuite.test("Access subscript") { do { let value: Base<Int> & P = Derived(x: 123, y: 321) value[1] = 2 value["hi"] = 20 expectEqual(2, value[1]) expectEqual(20, value["hi"]) value[1] += 1 value["hi"] += 1 expectEqual(3, value[1]) expectEqual(21, value["hi"]) } expectEqual(0, LifetimeTracked.instances) } SubclassExistentialsTestSuite.test("Call static methods") { do { let value: Base<Int> & P = Derived(x: 123, y: 321) let metatype: (Base<Int> & P).Type = type(of: value) let newValue = metatype.init(x: 256, y: 512) expectTrue(newValue === newValue.classMethodReturnsSelf()) expectTrue((256, 512) == newValue.finalClassMethod()) expectTrue((512, 256) == newValue.nonFinalClassMethod()) do { let fn = metatype.init(x:y:) let newValue = fn(1, 2) expectTrue((1, 2) == newValue.finalClassMethod()) } } expectEqual(0, LifetimeTracked.instances) } SubclassExistentialsTestSuite.test("Access static properties") { do { let value: Base<Int> & P = Derived(x: 123, y: 321) expectEqual(16, type(of: value).classPropertyToOverride) type(of: value).classPropertyToOverride += 4 expectEqual(20, type(of: value).classPropertyToOverride) type(of: value).classPropertyToOverride += 1 expectEqual(20, type(of: value).classPropertyToOverride) } expectEqual(0, LifetimeTracked.instances) } SubclassExistentialsTestSuite.test("Call protocol instance methods") { do { let value: Base<Int> & P = Derived(x: 123, y: 321) // Basic method calls expectTrue(value === value.protocolMethodReturnsSelf()) // Partial application do { let fn = value.protocolMethodReturnsSelf expectTrue(value === fn()) } } expectEqual(0, LifetimeTracked.instances) } SubclassExistentialsTestSuite.test("Access protocol instance properties") { do { var value: Base<Int> & P = Derived(x: 123, y: 321) expectEqual(100, value.protocolProperty) value.protocolProperty += 1 expectEqual(101, value.protocolProperty) } expectEqual(0, LifetimeTracked.instances) } SubclassExistentialsTestSuite.test("Access protocol subscript") { do { var value: Base<Int> & P = Derived(x: 123, y: 321) value[protocolKey: 1] = 2 value[protocolKey: "hi"] = 20 expectEqual(2, value[protocolKey: 1]) expectEqual(20, value[protocolKey: "hi"]) value[protocolKey: 1] += 1 value[protocolKey: "hi"] += 1 expectEqual(3, value[protocolKey: 1]) expectEqual(21, value[protocolKey: "hi"]) } expectEqual(0, LifetimeTracked.instances) } // Note: in optimized builds, these tests will get optimized down and // exercise a totally different code path. That's fine. SubclassExistentialsTestSuite.test("Scalar downcast to subclass existential") { do { let baseInt: Base<Int> = Derived(x: 123, y: 321) let derived = baseInt as? (Base<Int> & P) expectEqual(123, derived!.x) expectEqual(321, derived!.y) } do { let p: P = Derived(x: 123, y: 321) let result = p as? (Base<Int> & P) expectEqual(123, result!.x) expectEqual(321, result!.y) } do { let r: R = Derived(x: 123, y: 321) let result = r as? (Base<Int> & P) expectEqual(123, result!.x) expectEqual(321, result!.y) } do { let baseInt: Base<Int> = Derived(x: 123, y: 321) let result = baseInt as? (Base<Int> & P) expectEqual(123, result!.x) expectEqual(321, result!.y) } expectEqual(0, LifetimeTracked.instances) } func cast<T, U>(_ t: T, to: U.Type) -> U? { return t as? U } // Note: in optimized builds, these tests will get optimized down and // exercise a totally different code path. That's fine. SubclassExistentialsTestSuite.test("Dynamic downcast to subclass existential") { do { let baseInt: Base<Int> = Derived(x: 123, y: 321) let derived = cast(baseInt, to: (Base<Int> & P).self) expectEqual(123, derived!.x) expectEqual(321, derived!.y) } do { let p: P = Derived(x: 123, y: 321) let result = cast(p, to: (Base<Int> & P).self) expectEqual(123, result!.x) expectEqual(321, result!.y) } do { let r: R = Derived(x: 123, y: 321) let result = cast(r, to: (Base<Int> & P).self) expectEqual(123, result!.x) expectEqual(321, result!.y) } do { let baseInt: Base<Int> = Derived(x: 123, y: 321) let result = cast(baseInt, to: (Base<Int> & P).self) expectEqual(123, result!.x) expectEqual(321, result!.y) } expectEqual(0, LifetimeTracked.instances) } class ConformsToP : P { var token = LifetimeTracked(0) required init(protocolInit: ()) {} func protocolMethodReturnsSelf() -> Self { return self } static func staticProtocolMethodReturnsSelf() -> Self { return self.init(protocolInit: ()) } var protocolProperty: Int = 100 static var staticProtocolProperty: Int = 2000 subscript<U : Hashable>(protocolKey protocolKey: U) -> Int { get { return 0 } set {} } } SubclassExistentialsTestSuite.test("Failing scalar downcast to subclass existential") { do { let baseInt: Base<Int> = Base<Int>(x: 123, y: 321) expectNil(baseInt as? (Base<Int> & P)) expectFalse(baseInt is (Base<Int> & P)) } do { let r: R = Base<Int>(x: 123, y: 321) expectNil(r as? (Base<Int> & P)) expectFalse(r is (Base<Int> & P)) } do { let conformsToP = ConformsToP(protocolInit: ()) expectNil(conformsToP as? (Base<Int> & P)) expectFalse(conformsToP is (Base<Int> & P)) } } SubclassExistentialsTestSuite.test("Failing dynamic downcast to subclass existential") { do { let baseInt: Base<Int> = Base<Int>(x: 123, y: 321) expectNil(cast(baseInt, to: (Base<Int> & P).self)) } do { let r: R = Base<Int>(x: 123, y: 321) expectNil(cast(r, to: (Base<Int> & P).self)) } do { let conformsToP = ConformsToP(protocolInit: ()) expectNil(cast(conformsToP, to: (Base<Int> & P).self)) } } runAllTests()
apache-2.0
onebytecode/krugozor-iOSVisitors
krugozor-visitorsApp/Visit.swift
1
432
// // Visit.swift // krugozor-visitorsApp // // Created by Alexander Danilin on 21/10/2017. // Copyright © 2017 oneByteCode. All rights reserved. // import Foundation import RealmSwift class Visit: Object { @objc dynamic var id = 0 @objc dynamic var startAt = "" @objc dynamic var startDate = "" @objc dynamic var finishDate = "" @objc dynamic var duration = 0 @objc dynamic var totalPrice = 0 }
apache-2.0
jwalsh/mal
swift3/Sources/types.swift
3
6077
enum MalError: ErrorType { case Reader(msg: String) case General(msg: String) case MalException(obj: MalVal) } class MutableAtom { var val: MalVal init(val: MalVal) { self.val = val } } enum MalVal { case MalNil case MalTrue case MalFalse case MalInt(Int) case MalFloat(Float) case MalString(String) case MalSymbol(String) case MalList(Array<MalVal>, meta: Array<MalVal>?) case MalVector(Array<MalVal>, meta: Array<MalVal>?) case MalHashMap(Dictionary<String,MalVal>, meta: Array<MalVal>?) // TODO: internal MalVals are wrapped in arrays because otherwise // compiler throws a fault case MalFunc((Array<MalVal>) throws -> MalVal, ast: Array<MalVal>?, env: Env?, params: Array<MalVal>?, macro: Bool, meta: Array<MalVal>?) case MalAtom(MutableAtom) } typealias MV = MalVal // General functions func wraptf(a: Bool) -> MalVal { return a ? MV.MalTrue : MV.MalFalse } // equality functions func cmp_seqs(a: Array<MalVal>, _ b: Array<MalVal>) -> Bool { if a.count != b.count { return false } var idx = a.startIndex while idx < a.endIndex { if !equal_Q(a[idx], b[idx]) { return false } idx = idx.successor() } return true } func cmp_maps(a: Dictionary<String,MalVal>, _ b: Dictionary<String,MalVal>) -> Bool { if a.count != b.count { return false } for (k,v1) in a { if b[k] == nil { return false } if !equal_Q(v1, b[k]!) { return false } } return true } func equal_Q(a: MalVal, _ b: MalVal) -> Bool { switch (a, b) { case (MV.MalNil, MV.MalNil): return true case (MV.MalFalse, MV.MalFalse): return true case (MV.MalTrue, MV.MalTrue): return true case (MV.MalInt(let i1), MV.MalInt(let i2)): return i1 == i2 case (MV.MalString(let s1), MV.MalString(let s2)): return s1 == s2 case (MV.MalSymbol(let s1), MV.MalSymbol(let s2)): return s1 == s2 case (MV.MalList(let l1,_), MV.MalList(let l2,_)): return cmp_seqs(l1, l2) case (MV.MalList(let l1,_), MV.MalVector(let l2,_)): return cmp_seqs(l1, l2) case (MV.MalVector(let l1,_), MV.MalList(let l2,_)): return cmp_seqs(l1, l2) case (MV.MalVector(let l1,_), MV.MalVector(let l2,_)): return cmp_seqs(l1, l2) case (MV.MalHashMap(let d1,_), MV.MalHashMap(let d2,_)): return cmp_maps(d1, d2) default: return false } } // list and vector functions func list(lst: Array<MalVal>) -> MalVal { return MV.MalList(lst, meta:nil) } func list(lst: Array<MalVal>, meta: MalVal) -> MalVal { return MV.MalList(lst, meta:[meta]) } func vector(lst: Array<MalVal>) -> MalVal { return MV.MalVector(lst, meta:nil) } func vector(lst: Array<MalVal>, meta: MalVal) -> MalVal { return MV.MalVector(lst, meta:[meta]) } // hash-map functions func _assoc(src: Dictionary<String,MalVal>, _ mvs: Array<MalVal>) throws -> Dictionary<String,MalVal> { var d = src if mvs.count % 2 != 0 { throw MalError.General(msg: "Odd number of args to assoc_BANG") } var pos = mvs.startIndex while pos < mvs.count { switch (mvs[pos], mvs[pos+1]) { case (MV.MalString(let k), let mv): d[k] = mv default: throw MalError.General(msg: "Invalid _assoc call") } pos += 2 } return d } func _dissoc(src: Dictionary<String,MalVal>, _ mvs: Array<MalVal>) throws -> Dictionary<String,MalVal> { var d = src for mv in mvs { switch mv { case MV.MalString(let k): d.removeValueForKey(k) default: throw MalError.General(msg: "Invalid _dissoc call") } } return d } func hash_map(dict: Dictionary<String,MalVal>) -> MalVal { return MV.MalHashMap(dict, meta:nil) } func hash_map(dict: Dictionary<String,MalVal>, meta:MalVal) -> MalVal { return MV.MalHashMap(dict, meta:[meta]) } func hash_map(arr: Array<MalVal>) throws -> MalVal { let d = Dictionary<String,MalVal>(); return MV.MalHashMap(try _assoc(d, arr), meta:nil) } // function functions func malfunc(fn: (Array<MalVal>) throws -> MalVal) -> MalVal { return MV.MalFunc(fn, ast: nil, env: nil, params: nil, macro: false, meta: nil) } func malfunc(fn: (Array<MalVal>) throws -> MalVal, ast: Array<MalVal>?, env: Env?, params: Array<MalVal>?) -> MalVal { return MV.MalFunc(fn, ast: ast, env: env, params: params, macro: false, meta: nil) } func malfunc(fn: (Array<MalVal>) throws -> MalVal, ast: Array<MalVal>?, env: Env?, params: Array<MalVal>?, macro: Bool, meta: MalVal?) -> MalVal { return MV.MalFunc(fn, ast: ast, env: env, params: params, macro: macro, meta: meta != nil ? [meta!] : nil) } func malfunc(fn: (Array<MalVal>) throws -> MalVal, ast: Array<MalVal>?, env: Env?, params: Array<MalVal>?, macro: Bool, meta: Array<MalVal>?) -> MalVal { return MV.MalFunc(fn, ast: ast, env: env, params: params, macro: macro, meta: meta) } // sequence functions func _rest(a: MalVal) throws -> Array<MalVal> { switch a { case MV.MalList(let lst,_): let slc = lst[lst.startIndex.successor()..<lst.endIndex] return Array(slc) case MV.MalVector(let lst,_): let slc = lst[lst.startIndex.successor()..<lst.endIndex] return Array(slc) default: throw MalError.General(msg: "Invalid rest call") } } func rest(a: MalVal) throws -> MalVal { return list(try _rest(a)) } func _nth(a: MalVal, _ idx: Int) throws -> MalVal { switch a { case MV.MalList(let l,_): return l[l.startIndex.advancedBy(idx)] case MV.MalVector(let l,_): return l[l.startIndex.advancedBy(idx)] default: throw MalError.General(msg: "Invalid nth call") } }
mpl-2.0
EZ-NET/ESGists
Tests/LinuxMain.swift
1
116
import XCTest import ESGistsTests var tests = [XCTestCaseEntry]() tests += ESGistsTests.allTests() XCTMain(tests)
mit
bridger/SwiftVisualFormat
SwiftVisualFormatTests/SwiftVisualFormatTests.swift
1
5414
// // SwiftVisualFormatTests.swift // SwiftVisualFormatTests // // Created by Bridger Maxwell on 8/1/14. // Copyright (c) 2014 Bridger Maxwell. All rights reserved. // import UIKit import XCTest class SwiftVisualFormatTests: XCTestCase { var containerView: UIView! var redView: UIView! var greenView: UIView! var blueView: UIView! override func setUp() { super.setUp() let containerView = UIView() containerView.translatesAutoresizingMaskIntoConstraints = false self.containerView = containerView let redView = UIView() redView.backgroundColor = UIColor.redColor() redView.translatesAutoresizingMaskIntoConstraints = false self.containerView.addSubview(redView) self.redView = redView let greenView = UIView() greenView.backgroundColor = UIColor.greenColor() greenView.translatesAutoresizingMaskIntoConstraints = false self.containerView.addSubview(greenView) self.greenView = greenView let blueView = UIView() blueView.backgroundColor = UIColor.blueColor() blueView.translatesAutoresizingMaskIntoConstraints = false self.containerView.addSubview(blueView) self.blueView = blueView } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func compareConstraints(visualFormatString: String, checkedConstraints: [NSLayoutConstraint]) { let views = ["redView" : redView, "blueView" : blueView, "greenView" : greenView] let referenceConstraints = NSLayoutConstraint.constraintsWithVisualFormat(visualFormatString, options: [], metrics: nil, views: views) as [NSLayoutConstraint] XCTAssertEqual(checkedConstraints.count, referenceConstraints.count, "The correct amount of constraints wasn't created") for constraint in referenceConstraints { var foundMatch = false for checkConstraint in checkedConstraints { if (constraint.firstItem === checkConstraint.firstItem && constraint.firstAttribute == checkConstraint.firstAttribute && constraint.relation == checkConstraint.relation && constraint.secondItem === checkConstraint.secondItem && constraint.secondAttribute == checkConstraint.secondAttribute && constraint.multiplier == checkConstraint.multiplier && constraint.constant == checkConstraint.constant && constraint.priority == checkConstraint.priority) { foundMatch = true break; } } XCTAssert(foundMatch, "The reference constraint \( constraint ) was not found in the created constraints: \(checkedConstraints)") } } func compareHorizontalAndVerticalConstraints(formatString: String, constraintAble: [ConstraintAble]) { compareConstraints("H:" + formatString, checkedConstraints: constraints(.Horizontal, constraintAble: constraintAble)) compareConstraints("V:" + formatString, checkedConstraints: constraints(.Vertical, constraintAble: constraintAble)) } func testSuperviewSpace() { compareHorizontalAndVerticalConstraints("|-5-[redView]", constraintAble: |-5-[redView] ) compareHorizontalAndVerticalConstraints("|[redView]", constraintAble: |[redView] ) compareHorizontalAndVerticalConstraints("[redView]-5-|", constraintAble: [redView]-5-| ) compareHorizontalAndVerticalConstraints("[redView]|", constraintAble: [redView]| ) compareHorizontalAndVerticalConstraints("|[redView]|", constraintAble: |[redView]| ) compareHorizontalAndVerticalConstraints("|-5-[redView]|", constraintAble: |-5-[redView]| ) compareHorizontalAndVerticalConstraints("|[redView]-5-|", constraintAble: |[redView]-5-| ) } func testWidthConstraints() { compareHorizontalAndVerticalConstraints("[redView(==greenView)]", constraintAble: [redView==greenView] ) compareHorizontalAndVerticalConstraints("[redView(>=greenView)]", constraintAble: [redView>=greenView] ) compareHorizontalAndVerticalConstraints("[redView(<=greenView)]", constraintAble: [redView<=greenView] ) } func testSpaceConstraints() { compareHorizontalAndVerticalConstraints("[redView]-5-[greenView]", constraintAble: [redView]-5-[greenView] ) compareHorizontalAndVerticalConstraints("[redView]-0-[greenView]", constraintAble: [redView]-0-[greenView] ) } func testCombinedConstraints() { compareHorizontalAndVerticalConstraints("|-5-[redView(>=blueView)]-10-[greenView]-15-[blueView]-20-|", constraintAble: |-5-[redView >= blueView]-10-[greenView]-15-[blueView]-20-| ) compareHorizontalAndVerticalConstraints("|[redView(>=blueView)]-10-[greenView]-15-[blueView]-20-|", constraintAble: |[redView >= blueView]-10-[greenView]-15-[blueView]-20-| ) compareHorizontalAndVerticalConstraints("|-5-[redView(>=blueView)]-10-[greenView]-15-[blueView]|", constraintAble: |-5-[redView >= blueView]-10-[greenView]-15-[blueView]| ) } }
mit
MetalheadSanya/SideMenuController
Example/Example/AppDelegate.swift
3
2729
// // AppDelegate.swift // Example // // Created by Teodor Patras on 16/06/16. // Copyright © 2016 teodorpatras. All rights reserved. // import UIKit import SideMenuController @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. SideMenuController.preferences.drawing.menuButtonImage = UIImage(named: "menu") SideMenuController.preferences.drawing.sidePanelPosition = .underCenterPanelLeft SideMenuController.preferences.drawing.sidePanelWidth = 300 SideMenuController.preferences.drawing.centerPanelShadow = true SideMenuController.preferences.animating.statusBarBehaviour = .horizontalPan SideMenuController.preferences.animating.transitionAnimator = FadeAnimator.self return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
ksmandersen/SwiftyExtensions
Swift/Array+Extensions.swift
1
308
import Foundation extension Array { /// The first element in the array or nil if empty var first: T? { if isEmpty { return nil } return self[startIndex] } /// The last element in the array or nil if empty var last: T? { if isEmpty { return nil } return self[endIndex - 1] } }
unlicense
sudeepag/Phobia
Phobia/Word.swift
1
714
// // Word.swift // Phobia // // Created by Sudeep Agarwal on 11/21/15. // Copyright © 2015 Sudeep Agarwal. All rights reserved. // import Foundation import UIKit enum WordType { case Neutral case TriggerSpiders case TriggerSnakes case TriggerHeights } enum ColorType { case Red case Blue case Green } class Word: Hashable { var color: ColorType! var text: String! var type: WordType! var hashValue: Int { return text.hashValue } init(text: String, color: ColorType, type: WordType) { self.text = text self.color = color self.type = type } } func ==(lhs: Word, rhs: Word) -> Bool { return lhs == rhs }
mit
Antondomashnev/Sourcery
SourceryTests/Stub/Result/BasicFooExcluded.swift
1
335
// Generated using Sourcery Major.Minor.Patch — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT extension Bar: Equatable {} // Bar has Annotations func == (lhs: Bar, rhs: Bar) -> Bool { if lhs.parent != rhs.parent { return false } if lhs.otherVariable != rhs.otherVariable { return false } return true }
mit
AbelSu131/SimpleMemo
Memo/印象便签 WatchKit Extension/MemoInterfaceController.swift
1
3717
// // MemoInterfaceController.swift // Memo // // Created by  李俊 on 15/8/8. // Copyright (c) 2015年  李俊. All rights reserved. // import WatchKit import Foundation import WatchConnectivity class MemoInterfaceController: WKInterfaceController { @IBOutlet weak var memoTable: WKInterfaceTable! var newMemo = [String: AnyObject]() var memos = [[String: AnyObject]]() var isPush = false var wcSession: WCSession? lazy var sharedDefaults: NSUserDefaults? = { return NSUserDefaults(suiteName: "group.likumb.com.Memo") }() override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) wcSession = sharedSession() loadData(sharedDefaults) // setTable() } @IBAction func addMemo() { self.presentTextInputControllerWithSuggestions(nil, allowedInputMode: .Plain, completion: { (content) -> Void in if content == nil { return } if let text = content?[0] as? String { self.saveNewMemo(text) self.setTable() } }) } private func saveNewMemo(content: String){ var memo = [String: AnyObject]() memo["text"] = content memo["changeDate"] = NSDate() memos.insert(memo, atIndex: 0) shareMessage(memo) // 将新笔记共享给iPhone let sharedDefaults = NSUserDefaults(suiteName: "group.likumb.com.Memo") var results = sharedDefaults?.objectForKey("MemoContent") as? [AnyObject] if results != nil { results!.append(memo) sharedDefaults?.setObject(results, forKey: "MemoContent") } else{ let contents = [memo] sharedDefaults?.setObject(contents, forKey: "MemoContent") } // 共享apple watch共享数据池里的数据 sharedDefaults?.setObject(memos, forKey: "WatchMemo") sharedDefaults!.synchronize() } func setTable(){ memoTable.setNumberOfRows(memos.count, withRowType: "memoRow") for (index, memo) in memos.enumerate() { let controller = memoTable.rowControllerAtIndex(index) as! MemoRowController let text = memo["text"] as! String let memoText = text.deleteBlankLine() controller.memoLabel.setText(memoText) } } func loadData(userDefaults: NSUserDefaults?){ let data = userDefaults?.objectForKey("WatchMemo") as? [[String: AnyObject]] if let memoList = data { memos = memoList } setTable() } override func willActivate() { super.willActivate() if !isPush { loadData(sharedDefaults) // setTable() } isPush = false } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } override func contextForSegueWithIdentifier(segueIdentifier: String, inTable table: WKInterfaceTable, rowIndex: Int) -> AnyObject? { if segueIdentifier == "memoDetail" { isPush = true let memo = memos[rowIndex] return (memo["text"] as! String) } return nil } }
mit
remirobert/LoginProvider
LoginProviderExample/AppDelegate.swift
1
2156
// // AppDelegate.swift // LoginProviderExample // // Created by Remi Robert on 03/03/16. // Copyright © 2016 Remi Robert. 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
otto-schnurr/FileInput-swift
Source/FileInput.swift
1
6019
// // FileInput.swift // // Created by Otto Schnurr on 8/23/2014. // Copyright (c) 2014 Otto Schnurr. All rights reserved. // // MIT License // file: ../../LICENSE.txt // http://opensource.org/licenses/MIT // import Darwin /// Creates a FileInput sequence to iterate over lines of all files listed /// in command line arguments. If that list is empty then standard input is /// used. /// /// A file path of "-" is replaced with standard input. public func input() -> FileInput { let arguments = CommandLine.arguments.dropFirst() guard !arguments.isEmpty else { return FileInput() } return FileInput(filePaths: Array(arguments)) } // MARK: - /// A collection of characters typically ending with a newline. /// The last line of a file might not contain a newline. public typealias LineOfText = String /// A sequence that vends LineOfText objects. open class FileInput: Sequence { public typealias Iterator = AnyIterator<LineOfText> open func makeIterator() -> Iterator { return AnyIterator { return self.nextLine() } } /// Constructs a sequence to iterate lines of standrd input. convenience public init() { self.init(filePath: "-") } /// Constructs a sequence to iterate lines of a file. /// A filePath of "-" is replaced with standard input. convenience public init(filePath: String) { self.init(filePaths: [filePath]) } /// Constructs a sequence to iterate lines over a collection of files. /// Each filePath of "-" is replaced with standard input. public init(filePaths: [String]) { self.filePaths = filePaths self.openNextFile() } /// The file used in the previous call to nextLine(). open var filePath: String? { return filePaths.count > 0 ? filePaths[0] : nil } /// Newline characters that delimit lines are not removed. open func nextLine() -> LineOfText? { var result: LineOfText? = self.lines?.nextLine() while result == nil && self.filePath != nil { filePaths.remove(at: 0) self.openNextFile() result = self.lines?.nextLine() } return result } // MARK: Private fileprivate var filePaths: [String] fileprivate var lines: _FileLines? = nil fileprivate func openNextFile() { if let filePath = self.filePath { self.lines = _FileLines.linesForFilePath(filePath) } } } // MARK: - extension String { /// Creates a copy of this string with no white space at the beginning. public func removeLeadingSpace() -> String { let characters = self.unicodeScalars var start = characters.startIndex while start < characters.endIndex { if !characters[start].isSpace() { break } start = characters.index(after: start) } return String(characters[start..<characters.endIndex]) } /// Creates a copy of this string with no white space at the end. public func removeTrailingSpace() -> String { let characters = self.unicodeScalars var end = characters.endIndex while characters.startIndex < end { let previousIndex = characters.index(before: end) if !characters[previousIndex].isSpace() { break } end = previousIndex } return String(characters[characters.startIndex..<end]) } /// - returns: An index of the first white space character in this string. public func findFirstSpace() -> String.Index? { var result: String.Index? = nil for index in self.indices { if self[index].isSpace() { result = index break } } return result } } // MARK: - Private private let _stdinPath = "-" private class _FileLines: Sequence { typealias Iterator = AnyIterator<LineOfText> let file: UnsafeMutablePointer<FILE>? var charBuffer = [CChar](repeating: 0, count: 512) init(file: UnsafeMutablePointer<FILE>) { self.file = file } deinit { if file != nil { fclose(file) } } class func linesForFilePath(_ filePath: String) -> _FileLines? { var lines: _FileLines? = nil if filePath == _stdinPath { lines = _FileLines(file: __stdinp) } else { let file = fopen(filePath, "r") if file == nil { print("can't open \(filePath)") } else { lines = _FileLines(file: file!) } } return lines } func makeIterator() -> Iterator { return AnyIterator { self.nextLine() } } func nextChunk() -> String? { var result: String? = nil; if file != nil { if fgets(&charBuffer, Int32(charBuffer.count), file) != nil { result = String(cString: charBuffer) } } return result } func nextLine() -> LineOfText? { var line: LineOfText = LineOfText() while let nextChunk = self.nextChunk() { line += nextChunk if line.hasSuffix("\n") { break } } return line.isEmpty ? nil : line } } // MARK: - Private extension Character { fileprivate func isSpace() -> Bool { let characterString = String(self) for uCharacter in characterString.unicodeScalars { if !uCharacter.isSpace() { return false } } return true } } extension UnicodeScalar { fileprivate func isSpace() -> Bool { let wCharacter = wint_t(self.value) return iswspace(wCharacter) != 0 } }
mit
eebean2/RS_Combat
RS Combat/OSMain.swift
1
15368
// // OSMain.swift // RS Combat // // Created by Erik Bean on 2/8/17. // Copyright © 2017 Erik Bean. All rights reserved. // import UIKit import GoogleMobileAds class OSMain: UIViewController, UITextFieldDelegate { // Static Get Levels @IBOutlet var staticAttack: UILabel! @IBOutlet var staticStrength: UILabel! @IBOutlet var staticDefence: UILabel! @IBOutlet var staticMagic: UILabel! @IBOutlet var staticRange: UILabel! @IBOutlet var staticPrayer: UILabel! @IBOutlet var staticHP: UILabel! // Get Level TextFields @IBOutlet var attackIn: UITextField! @IBOutlet var strengthIn: UITextField! @IBOutlet var defenceIn: UITextField! @IBOutlet var magicIn: UITextField! @IBOutlet var rangeIn: UITextField! @IBOutlet var prayerIn: UITextField! @IBOutlet var hpIn: UITextField! // Static Set Levels @IBOutlet var staticSetAttack: UILabel! @IBOutlet var staticSetStrength: UILabel! @IBOutlet var staticSetDefence: UILabel! @IBOutlet var staticSetMagic: UILabel! @IBOutlet var staticSetRange: UILabel! @IBOutlet var staticSetPrayer: UILabel! @IBOutlet var staticSetHP: UILabel! // Set Level Labels @IBOutlet var attackOut: UILabel! @IBOutlet var strengthOut: UILabel! @IBOutlet var defenceOut: UILabel! @IBOutlet var magicOut: UILabel! @IBOutlet var rangeOut: UILabel! @IBOutlet var prayerOut: UILabel! @IBOutlet var hpOut: UILabel! // Other @IBOutlet var button: UIButton! @IBOutlet var scroll: UIScrollView! @IBOutlet var currentLevel: UILabel! @IBOutlet var currentStatic: UILabel! @IBOutlet var nextLevel: UILabel! @IBOutlet var nextStatic: UILabel! @IBOutlet var needStatic: UILabel! // Variable Management var calculated = false var activeField: UITextField? = nil var lvl: Int = 0 var fightTitle: FightTitle! var state: ButtonState = .calculate var attack: Int { if attackIn.text != "" { return Int(attackIn.text!)! } else { return 1 } } var strength: Int { if strengthIn.text != "" { return Int(strengthIn.text!)! } else { return 1 } } var defence: Int { if defenceIn.text != "" { return Int(defenceIn.text!)! } else { return 1 } } var magic: Int { if magicIn.text != "" { return Int(magicIn.text!)! } else { return 1 } } var range: Int { if rangeIn.text != "" { return Int(rangeIn.text!)! } else { return 1 } } var prayer: Int { if prayerIn.text != "" { return Int(prayerIn.text!)! } else { return 1 } } var hp: Int { if hpIn.text != "" { return Int(hpIn.text!)! } else { return 10 } } // melee = floor(0.25(Defence + Hits + floor(Prayer/2)) + 0.325(Attack + Strength)) var sumPrayer: Float { return floor(Float(prayer / 2)) } var base: Float { return (Float(defence) + Float(hp) + sumPrayer) / 4 } var warrior: Float { return (Float(attack) + Float(strength)) * 0.325 } var ranger: Float { return floor(Float(range) * 1.5) * 0.325 } var mage: Float { return floor(Float(magic) * 1.5) * 0.325 } // View Setup, Destruction, and Keyboard Management override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: .UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide), name: .UIKeyboardDidHide, object: nil) } override func viewDidLoad() { super.viewDidLoad() button.layer.cornerRadius = 5 view.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "768osBackground.png")) if UIDevice().model == "iPad" { visible() calcuate(self) } let dv = UIToolbar() dv.sizeToFit() let db = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(donePressed)) dv.setItems([db], animated: false) attackIn.inputAccessoryView = dv strengthIn.inputAccessoryView = dv defenceIn.inputAccessoryView = dv magicIn.inputAccessoryView = dv rangeIn.inputAccessoryView = dv prayerIn.inputAccessoryView = dv hpIn.inputAccessoryView = dv let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) view.addGestureRecognizer(tap) scroll.addGestureRecognizer(tap) let bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait) bannerView.adUnitID = "ca-app-pub-9515262034988468/4212206831" bannerView.rootViewController = self view.addSubview(bannerView) bannerView.translatesAutoresizingMaskIntoConstraints = false view.addConstraint(NSLayoutConstraint(item: bannerView, attribute: .bottom, relatedBy: .equal, toItem: scroll, attribute: .bottom, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: bannerView, attribute: .bottom, relatedBy: .equal, toItem: scroll, attribute: .bottom, multiplier: 1, constant: 0)) let request = GADRequest() request.testDevices = [kGADSimulatorID] bannerView.load(request) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NotificationCenter.default.removeObserver(self, name: .UIKeyboardDidShow, object: nil) NotificationCenter.default.removeObserver(self, name: .UIKeyboardDidHide, object: nil) } @objc func keyboardDidShow(_ sender: Notification) { if let userInfo = sender.userInfo { if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { let buttonOrigin = activeField!.frame.origin let buttonHeight = activeField!.frame.size.height var visibleRect = view.frame visibleRect.size.height -= keyboardSize.height if !visibleRect.contains(buttonOrigin) { let scrollPoint = CGPoint(x: 0, y: buttonOrigin.y - visibleRect.size.height + buttonHeight) scroll.setContentOffset(scrollPoint, animated: true) } } else { print("Scroll Error! No Keyboard Data") } } else { print("Scroll Error! No Notification Information") } } @objc func keyboardDidHide(_ sender: Notification) { scroll.setContentOffset(CGPoint.zero, animated: true) } @objc func donePressed(_ sender: UIBarButtonItem) { view.endEditing(true) } @objc func dismissKeyboard(_ sender: UITapGestureRecognizer) { if activeField != nil { activeField!.resignFirstResponder() } } func textFieldDidBeginEditing(_ textField: UITextField) { activeField = textField } // View Management @IBAction func buttonDidPress(_ sender: UIButton) { if !calculated { calcuate(sender) } visible() staticAttack.isHidden = !staticAttack.isHidden staticStrength.isHidden = !staticStrength.isHidden staticDefence.isHidden = !staticDefence.isHidden staticMagic.isHidden = !staticMagic.isHidden staticRange.isHidden = !staticRange.isHidden staticPrayer.isHidden = !staticPrayer.isHidden staticHP.isHidden = !staticHP.isHidden attackIn.isHidden = !attackIn.isHidden strengthIn.isHidden = !strengthIn.isHidden defenceIn.isHidden = !defenceIn.isHidden magicIn.isHidden = !magicIn.isHidden rangeIn.isHidden = !rangeIn.isHidden prayerIn.isHidden = !prayerIn.isHidden hpIn.isHidden = !hpIn.isHidden if state == .calculate { button.setTitle(NSLocalizedString("Done", comment: ""), for: .normal) state = .done } else { button.setTitle(NSLocalizedString("Calculate", comment: ""), for: .normal) state = .calculate } } func visible() { staticSetAttack.isHidden = !staticSetAttack.isHidden staticSetStrength.isHidden = !staticSetStrength.isHidden staticSetDefence.isHidden = !staticSetDefence.isHidden staticSetMagic.isHidden = !staticSetMagic.isHidden staticSetRange.isHidden = !staticSetRange.isHidden staticSetPrayer.isHidden = !staticSetPrayer.isHidden staticSetHP.isHidden = !staticSetHP.isHidden attackOut.isHidden = !attackOut.isHidden strengthOut.isHidden = !strengthOut.isHidden defenceOut.isHidden = !defenceOut.isHidden magicOut.isHidden = !magicOut.isHidden rangeOut.isHidden = !rangeOut.isHidden prayerOut.isHidden = !prayerOut.isHidden hpOut.isHidden = !hpOut.isHidden needStatic.isHidden = !needStatic.isHidden currentLevel.isHidden = !currentLevel.isHidden currentStatic.isHidden = !currentStatic.isHidden nextLevel.isHidden = !nextLevel.isHidden nextStatic.isHidden = !nextStatic.isHidden } // Combact Calculation @IBAction func calcuate(_ sender: AnyObject) { if !calculated { calculated = true } if floor(warrior + base) > floor(ranger + base) && floor(warrior + base) > floor(mage + base) { lvl = Int(base + warrior) fightTitle = .melee } else if floor(ranger + base) > floor(warrior + base) && floor(ranger + base) > floor(mage + base) { lvl = Int(base + ranger) fightTitle = .range } else if floor(mage + base) > floor(warrior + base) && floor(mage + base) > floor(ranger + base) { lvl = Int(base + mage) fightTitle = .mage } else { if floor(warrior + base) < floor(mage + base) && floor(warrior + base) < floor(ranger + base) { lvl = Int(base + mage) fightTitle = .mage } else { lvl = Int(base + warrior) fightTitle = .skiller } } currentLevel.text = String(lvl) if lvl == 126 { nextLevel.text = "Maxed" nextLevel.sizeToFit() } else { nextLevel.text = String(lvl + 1) } // Attack var i: Int = 1 var c: Int = 0 var temp: Int = attack if temp == 99 { attackOut.text = "-" } else { while i <= lvl { temp += 1 let a = (Float(temp) + Float(strength)) * 0.325 i = Int(base + a) c += 1 if i > lvl { if c > (99 - attack) { attackOut.text = "-" } else { attackOut.text = String(c) } } } } // Strength i = 1 c = 0 temp = strength if temp == 99 { strengthOut.text = "-" } else { while i <= lvl { temp += 1 let a = (Float(temp) + Float(attack)) * 0.325 i = Int(base + a) c += 1 if i > lvl { if c > (99 - strength) { strengthOut.text = "-" } else { strengthOut.text = String(c) } } } } // Defence i = 1 c = 0 temp = defence if temp == 99 { defenceOut.text = "-" } else { while i <= lvl { temp += 1 let a = (Float(temp) + Float(hp) + sumPrayer) / 4 switch fightTitle! { case .melee, .skiller: i = Int(a + warrior) case .range: i = Int(a + ranger) case .mage: i = Int(a + mage) } c += 1 if i > lvl { if c > (99 - defence) { defenceOut.text = "-" } else { defenceOut.text = String(c) } } } } // Magic i = 1 c = 0 temp = magic if temp == 99 { magicOut.text = "-" } else { while i <= lvl { temp += 1 let a = Float(Int(Float(temp) * 1.5)) * 0.325 i = Int(base + a) c += 1 if i > lvl { if c > (99 - magic) { magicOut.text = "-" } else { magicOut.text = String(c) } } } } // Range i = 1 c = 0 temp = range if temp == 99 { rangeOut.text = "-" } else { while i <= lvl { temp += 1 let a = Float(Int(Float(temp) * 1.5)) * 0.325 i = Int(base + a) c += 1 if i > lvl { if c > (99 - range) { rangeOut.text = "-" } else { rangeOut.text = String(c) } } } } // Prayer i = 1 c = 0 temp = prayer if temp == 99 { prayerOut.text = "-" } else { while i <= lvl { temp += 1 let a = (Float(Int(temp / 2)) + Float(defence) + Float(hp)) / 4 switch fightTitle! { case .melee, .skiller: i = Int(a + warrior) case .range: i = Int(a + ranger) case .mage: i = Int(a + mage) } c += 1 if i > lvl { if c > (99 - prayer) { prayerOut.text = "-" } else { prayerOut.text = String(c) } } } } // HP i = 1 c = 0 temp = hp if temp == 99 { hpOut.text = "-" } else { while i <= lvl { temp += 1 let a = (Float(defence) + Float(temp) + sumPrayer) / 4 switch fightTitle! { case .melee, .skiller: i = Int(a + warrior) case .range: i = Int(a + ranger) case .mage: i = Int(a + mage) } c += 1 if i > lvl { if c > (99 - hp) { hpOut.text = "-" } else { hpOut.text = String(c) } } } } } }
mit
ArturAzarau/chatter
Chatter/Chatter/ChatVC.swift
1
1688
// // ChatVC.swift // Chatter // // Created by Artur Azarov on 08.09.17. // Copyright © 2017 Artur Azarov. All rights reserved. // import Cocoa final class ChatVC: NSViewController { // MARK: - Outlets @IBOutlet weak var channelTitleLabel: NSTextField! @IBOutlet weak var channelDescriptionLabel: NSTextField! @IBOutlet weak var tableView: NSScrollView! @IBOutlet weak var typingUserLabel: NSTextField! @IBOutlet weak var messageOutlineView: NSView! @IBOutlet weak var messageTextView: NSTextField! @IBOutlet weak var sendMessageButton: NSButton! // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear() { super.viewWillAppear() setUpView() } // MARK: - View methods private func setUpView() { // setup main view view.wantsLayer = true view.layer?.backgroundColor = CGColor.white // setup message outline view messageOutlineView.wantsLayer = true messageOutlineView.layer?.backgroundColor = CGColor.white messageOutlineView.layer?.borderColor = NSColor.controlHighlightColor.cgColor messageOutlineView.layer?.borderWidth = 2 messageOutlineView.layer?.cornerRadius = 5 // setup send message button sendMessageButton.styleButtonText(button: sendMessageButton, buttonName: "Send", fontColor: .darkGray, alignment: .center, font: Fonts.avenirRegular, size: 13) } // MARK: - Actions @IBAction func sendMessageButtonClicked(_ sender: NSButton) { } }
mit