repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
caolsen/CircularSlider
CircularSlider/CircularSlider.swift
1
14775
// // CircularSlider.swift // // Created by Christopher Olsen on 03/03/16. // Copyright © 2016 Christopher Olsen. All rights reserved. // import UIKit import QuartzCore import Foundation enum CircularSliderHandleType { case semiTransparentWhiteSmallCircle, semiTransparentWhiteCircle, semiTransparentBlackCircle, bigCircle } class CircularSlider: UIControl { // MARK: Values // Value at North/midnight (start) var minimumValue: Float = 0.0 { didSet { setNeedsDisplay() } } // Value at North/midnight (end) var maximumValue: Float = 100.0 { didSet { setNeedsDisplay() } } // value for end of arc. This allows for incomplete circles to be created var maximumAngle: CGFloat = 360.0 { didSet { if maximumAngle > 360.0 { print("Warning: Maximum angle should be 360 or less.") maximumAngle = 360.0 } setNeedsDisplay() } } // Current value between North/midnight (start) and North/midnight (end) - clockwise direction var currentValue: Float { set { assert(newValue <= maximumValue && newValue >= minimumValue, "current value \(newValue) must be between minimumValue \(minimumValue) and maximumValue \(maximumValue)") // Update the angleFromNorth to match this newly set value angleFromNorth = Int((newValue * Float(maximumAngle)) / (maximumValue - minimumValue)) moveHandle(CGFloat(angleFromNorth)) sendActions(for: UIControlEvents.valueChanged) } get { return (Float(angleFromNorth) * (maximumValue - minimumValue)) / Float(maximumAngle) } } // MARK: Handle let circularSliderHandle = CircularSliderHandle() /** * Note: If this property is not set, filledColor will be used. * If handleType is semiTransparent*, specified color will override this property. * * Color of the handle */ var handleColor: UIColor? { didSet { setNeedsDisplay() } } // Type of the handle to display to represent draggable current value var handleType: CircularSliderHandleType = .semiTransparentWhiteSmallCircle { didSet { setNeedsUpdateConstraints() setNeedsDisplay() } } // MARK: Labels // BOOL indicating whether values snap to nearest label var snapToLabels: Bool = false /** * Note: The LAST label will appear at North/midnight * The FIRST label will appear at the first interval after North/midnight * * NSArray of strings used to render labels at regular intervals within the circle */ var innerMarkingLabels: [String]? { didSet { setNeedsUpdateConstraints() setNeedsDisplay() } } // MARK: Visual Customisation // property Width of the line to draw for slider var lineWidth: Int = 5 { didSet { setNeedsUpdateConstraints() // This could affect intrinsic content size invalidateIntrinsicContentSize() // Need to update intrinsice content size setNeedsDisplay() // Need to redraw with new line width } } // Color of filled portion of line (from North/midnight start to currentValue) var filledColor: UIColor = .red { didSet { setNeedsDisplay() } } // Color of unfilled portion of line (from currentValue to North/midnight end) var unfilledColor: UIColor = .black { didSet { setNeedsDisplay() } } // Font of the inner marking labels within the circle var labelFont: UIFont = .systemFont(ofSize: 10.0) { didSet { setNeedsDisplay() } } // Color of the inner marking labels within the circle var labelColor: UIColor = .red { didSet { setNeedsDisplay() } } /** * Note: A negative value will move the label closer to the center. A positive value will move the label closer to the circumference * Value with which to displace all labels along radial line from center to slider circumference. */ var labelDisplacement: CGFloat = 0 // type of LineCap to use for the unfilled arc // NOTE: user CGLineCap.Butt for full circles var unfilledArcLineCap: CGLineCap = .butt // type of CGLineCap to use for the arc that is filled in as the handle moves var filledArcLineCap: CGLineCap = .butt // MARK: Computed Public Properties var computedRadius: CGFloat { if (radius == -1.0) { // Slider is being used in frames - calculate the max radius based on the frame // (constrained by smallest dimension so it fits within view) let minimumDimension = min(bounds.size.height, bounds.size.width) let halfLineWidth = ceilf(Float(lineWidth) / 2.0) let halfHandleWidth = ceilf(Float(handleWidth) / 2.0) return minimumDimension * 0.5 - CGFloat(max(halfHandleWidth, halfLineWidth)) } return radius } var centerPoint: CGPoint { return CGPoint(x: bounds.size.width * 0.5, y: bounds.size.height * 0.5) } var angleFromNorth: Int = 0 { didSet { assert(angleFromNorth >= 0, "angleFromNorth \(angleFromNorth) must be greater than 0") } } var handleWidth: CGFloat { switch handleType { case .semiTransparentWhiteSmallCircle: return CGFloat(lineWidth / 2) case .semiTransparentWhiteCircle, .semiTransparentBlackCircle: return CGFloat(lineWidth) case .bigCircle: return CGFloat(lineWidth + 5) // 5 points bigger than standard handles } } // MARK: Private Variables fileprivate var radius: CGFloat = -1.0 { didSet { setNeedsUpdateConstraints() setNeedsDisplay() } } fileprivate var computedHandleColor: UIColor? { var newHandleColor = handleColor switch (handleType) { case .semiTransparentWhiteSmallCircle, .semiTransparentWhiteCircle: newHandleColor = UIColor(white: 1.0, alpha: 0.7) case .semiTransparentBlackCircle: newHandleColor = UIColor(white: 0.0, alpha: 0.7) case .bigCircle: newHandleColor = filledColor } return newHandleColor } fileprivate var innerLabelRadialDistanceFromCircumference: CGFloat { // Labels should be moved far enough to clear the line itself plus a fixed offset (relative to radius). var distanceToMoveInwards = 0.1 * -(radius) - 0.5 * CGFloat(lineWidth) distanceToMoveInwards -= 0.5 * labelFont.pointSize // Also account for variable font size. return distanceToMoveInwards } // MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) backgroundColor = .clear } // TODO: initializer for autolayout /** * Initialise the class with a desired radius * This initialiser should be used for autolayout - use initWithFrame otherwise * Note: Intrinsic content size will be based on this parameter, lineWidth and handleType * * radiusToSet Desired radius of circular slider */ // convenience init(radiusToSet: CGFloat) { // // } // MARK: - Function Overrides override var intrinsicContentSize : CGSize { // Total width is: diameter + (2 * MAX(halfLineWidth, halfHandleWidth)) let diameter = radius * 2 let halfLineWidth = ceilf(Float(lineWidth) / 2.0) let halfHandleWidth = ceilf(Float(handleWidth) / 2.0) let widthWithHandle = diameter + CGFloat(2 * max(halfHandleWidth, halfLineWidth)) return CGSize(width: widthWithHandle, height: widthWithHandle) } override func draw(_ rect: CGRect) { super.draw(rect) let ctx = UIGraphicsGetCurrentContext() // Draw the circular lines that slider handle moves along drawLine(ctx!) // Draw the draggable 'handle' let handleCenter = pointOnCircleAtAngleFromNorth(angleFromNorth) circularSliderHandle.frame = drawHandle(ctx!, atPoint: handleCenter) // Draw inner labels drawInnerLabels(ctx!, rect: rect) } override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { guard event != nil else { return false } if pointInsideHandle(point, withEvent: event!) { return true } else { return pointInsideCircle(point, withEvent: event!) } } fileprivate func pointInsideCircle(_ point: CGPoint, withEvent event: UIEvent) -> Bool { let p1 = centerPoint let p2 = point let xDist = p2.x - p1.x let yDist = p2.y - p1.y let distance = sqrt((xDist * xDist) + (yDist * yDist)) return distance < computedRadius + CGFloat(lineWidth) * 0.5 } fileprivate func pointInsideHandle(_ point: CGPoint, withEvent event: UIEvent) -> Bool { let handleCenter = pointOnCircleAtAngleFromNorth(angleFromNorth) // Adhere to apple's design guidelines - avoid making touch targets smaller than 44 points let handleRadius = max(handleWidth, 44.0) * 0.5 // Treat handle as a box around it's center let pointInsideHorzontalHandleBounds = (point.x >= handleCenter.x - handleRadius && point.x <= handleCenter.x + handleRadius) let pointInsideVerticalHandleBounds = (point.y >= handleCenter.y - handleRadius && point.y <= handleCenter.y + handleRadius) return pointInsideHorzontalHandleBounds && pointInsideVerticalHandleBounds } // MARK: - Drawing methods func drawLine(_ ctx: CGContext) { unfilledColor.set() // Draw an unfilled circle (this shows what can be filled) CircularTrig.drawUnfilledCircleInContext(ctx, center: centerPoint, radius: computedRadius, lineWidth: CGFloat(lineWidth), maximumAngle: maximumAngle, lineCap: unfilledArcLineCap) filledColor.set() // Draw an unfilled arc up to the currently filled point CircularTrig.drawUnfilledArcInContext(ctx, center: centerPoint, radius: computedRadius, lineWidth: CGFloat(lineWidth), fromAngleFromNorth: 0, toAngleFromNorth: CGFloat(angleFromNorth), lineCap: filledArcLineCap) } func drawHandle(_ ctx: CGContext, atPoint handleCenter: CGPoint) -> CGRect { ctx.saveGState() var frame: CGRect! // Ensure that handle is drawn in the correct color handleColor = computedHandleColor handleColor!.set() frame = CircularTrig.drawFilledCircleInContext(ctx, center: handleCenter, radius: 0.5 * handleWidth) ctx.saveGState() return frame } func drawInnerLabels(_ ctx: CGContext, rect: CGRect) { if let labels = innerMarkingLabels, labels.count > 0 { let attributes = [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelColor] as [String : Any] // Enumerate through labels clockwise for (index, label) in labels.enumerated() { let labelFrame = contextCoordinatesForLabel(atIndex: index) ctx.saveGState() // invert transformation used on arc ctx.concatenate(CGAffineTransform(translationX: labelFrame.origin.x + (labelFrame.width / 2), y: labelFrame.origin.y + (labelFrame.height / 2))) ctx.concatenate(getRotationalTransform().inverted()) ctx.concatenate(CGAffineTransform(translationX: -(labelFrame.origin.x + (labelFrame.width / 2)), y: -(labelFrame.origin.y + (labelFrame.height / 2)))) // draw label label.draw(in: labelFrame, withAttributes: attributes) ctx.restoreGState() } } } func contextCoordinatesForLabel(atIndex index: Int) -> CGRect { let label = innerMarkingLabels![index] var percentageAlongCircle: CGFloat! // Determine how many degrees around the full circle this label should go if maximumAngle == 360.0 { percentageAlongCircle = ((100.0 / CGFloat(innerMarkingLabels!.count)) * CGFloat(index + 1)) / 100.0 } else { percentageAlongCircle = ((100.0 / CGFloat(innerMarkingLabels!.count - 1)) * CGFloat(index)) / 100.0 } let degreesFromNorthForLabel = percentageAlongCircle * maximumAngle let pointOnCircle = pointOnCircleAtAngleFromNorth(Int(degreesFromNorthForLabel)) let labelSize = sizeOfString(label, withFont: labelFont) let offsetFromCircle = offsetFromCircleForLabelAtIndex(index, withSize: labelSize) return CGRect(x: pointOnCircle.x + offsetFromCircle.x, y: pointOnCircle.y + offsetFromCircle.y, width: labelSize.width, height: labelSize.height) } func offsetFromCircleForLabelAtIndex(_ index: Int, withSize labelSize: CGSize) -> CGPoint { // Determine how many degrees around the full circle this label should go let percentageAlongCircle = ((100.0 / CGFloat(innerMarkingLabels!.count - 1)) * CGFloat(index)) / 100.0 let degreesFromNorthForLabel = percentageAlongCircle * maximumAngle let radialDistance = innerLabelRadialDistanceFromCircumference + labelDisplacement let inwardOffset = CircularTrig.pointOnRadius(radialDistance, atAngleFromNorth: CGFloat(degreesFromNorthForLabel)) return CGPoint(x: -labelSize.width * 0.5 + inwardOffset.x, y: -labelSize.height * 0.5 + inwardOffset.y) } // MARK: - UIControl Functions override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { let lastPoint = touch.location(in: self) let lastAngle = floor(CircularTrig.angleRelativeToNorthFromPoint(centerPoint, toPoint: lastPoint)) moveHandle(lastAngle) sendActions(for: UIControlEvents.valueChanged) return true } fileprivate func moveHandle(_ newAngleFromNorth: CGFloat) { // prevent slider from moving past maximumAngle if newAngleFromNorth > maximumAngle { if angleFromNorth < Int(maximumAngle / 2) { angleFromNorth = 0 setNeedsDisplay() } else if angleFromNorth > Int(maximumAngle / 2) { angleFromNorth = Int(maximumAngle) setNeedsDisplay() } } else { angleFromNorth = Int(newAngleFromNorth) } setNeedsDisplay() } // MARK: - Helper Functions func pointOnCircleAtAngleFromNorth(_ angleFromNorth: Int) -> CGPoint { let offset = CircularTrig.pointOnRadius(computedRadius, atAngleFromNorth: CGFloat(angleFromNorth)) return CGPoint(x: centerPoint.x + offset.x, y: centerPoint.y + offset.y) } func sizeOfString(_ string: String, withFont font: UIFont) -> CGSize { let attributes = [NSFontAttributeName: font] return NSAttributedString(string: string, attributes: attributes).size() } func getRotationalTransform() -> CGAffineTransform { if maximumAngle == 360 { // do not perform a rotation if using a full circle slider let transform = CGAffineTransform.identity.rotated(by: CGFloat(0)) return transform } else { // rotate slider view so "north" is at the start let radians = Double(-(maximumAngle / 2)) / 180.0 * Double.pi let transform = CGAffineTransform.identity.rotated(by: CGFloat(radians)) return transform } } }
mit
809d9076dc120b3e992303526b1bca25
33.680751
215
0.692906
4.659098
false
false
false
false
banxi1988/Staff
Pods/BXModel/Pod/Classes/forms.swift
1
1817
// // forms.swift // Pods // // Created by Haizhen Lee on 15/11/30. // // import Foundation public typealias BXParams = [String:AnyObject] public class BXField{ public let name:String public let valueType:String public var value:AnyObject? // MARK: Validate // Taken from public var required:Bool = true public var label:String? public var label_suffix:String? public var help_text:String? public init(name:String,valueType:String){ self.name = name self.valueType = valueType } public static func fieldsAsParams(fields:[BXField]) -> BXParams{ var params = BXParams() for field in fields{ if let value = field.value{ params[field.name] = value } } return params } } public class BXCharField:BXField{ public var strip = true public var max_length = Int.max public var min_length = 0 } public enum ValidateError:ErrorType{ case TextIsBlank case UnsupportValueType case WrongValueType case NoValue } public struct InvalidFieldError:ErrorType{ public let field:BXField public let error:ValidateError public init(field:BXField,error:ValidateError){ self.field = field self.error = error } } public struct Validators { public static func checkText(text:String) throws { if text.isEmpty{ throw ValidateError.TextIsBlank } } public static func checkField(field:BXField) throws { do{ switch field.valueType{ case "String": if let value = field.value as? String{ try checkText(value) }else{ throw ValidateError.WrongValueType } default: throw ValidateError.UnsupportValueType } }catch let error as ValidateError{ throw InvalidFieldError(field: field, error: error) } } }
mit
4d57470067f3668e97fbe83ff8e5913a
19.659091
66
0.669235
3.958606
false
false
false
false
TomasVanRoose/SportsCalendarPlanner
SportsCalendarPlanner/SeasonsTableViewController.swift
1
3411
// // SeasonsTableViewController.swift // SportsCalendarPlanner // // Created by Tomas Van Roose on 03/09/16. // Copyright © 2016 Tomas Van Roose. All rights reserved. // import UIKit import CoreData class SeasonsTableViewController: CoreDataTableViewController { var managedObjectContext: NSManagedObjectContext? override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } // MARK: - Table view data source override func configureCell(indexPath: NSIndexPath) -> (UITableViewCell) { let cell = self.tableView.dequeueReusableCellWithIdentifier("season")! let season = self.fetchedResultsController.objectAtIndexPath(indexPath) as! SeasonMO cell.textLabel!.text! = season.name! return cell } // 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?) { if let destination = segue.destinationViewController as? UINavigationController { if let newSeasonController = destination.topViewController as? CreateSeasonViewController { newSeasonController.didSaveFunc = seasonCreatorDidReturn } } else if let destination = segue.destinationViewController as? TeamsViewController { let indexPath = self.tableView.indexPathForCell(sender as! UITableViewCell)! let season = self.fetchedResultsController.objectAtIndexPath(indexPath) as! SeasonMO destination.season = season destination.managedObjectContext = self.managedObjectContext let detailNavController = self.splitViewController?.viewControllers.last as? UINavigationController let detailViewController = detailNavController?.topViewController if let detail = detailViewController as? CalendarPresenterViewController { detail.selectSeason(season) } } } // MARK: - Core Data func seasonCreatorDidReturn(name : String, startDate : NSDate, endDate : NSDate) { _ = SeasonMO.createNewSeason(name, startDate: startDate, endDate: endDate, forContext: self.managedObjectContext!) do { try self.managedObjectContext!.save() } catch { fatalError("Failure to save context: \(error)") } } override func initializeFetchedResultsController() { let request = NSFetchRequest(entityName: "Season") let nameSort = NSSortDescriptor(key: "name", ascending: true) request.sortDescriptors = [ nameSort ] self.fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil) self.fetchedResultsController.delegate = self do { try fetchedResultsController.performFetch() } catch { fatalError("Failed to initialize FetchedResultsController: \(error)") } } }
mit
483a2f74ebb629385d9d3cb31a9b208e
35.666667
180
0.664223
6.035398
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat.ShareExtension/Helpers/VideoInfo.swift
1
1170
// // FirstVideoFrame.swift // Rocket.Chat.ShareExtension // // Created by Matheus Cardoso on 3/14/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import AVFoundation import UIKit struct VideoInfo { let thumbnail: UIImage let duration: Double var durationText: String { let duration = Int(self.duration) let minutes: Int = duration/60 let hours: Int = minutes/60 let seconds: Int = duration%60 return String(format: " ▶ %02d:%02d:%02d", hours, minutes, seconds) //" ▶ " + ((hours < 10) ? "0" : "") + "\(hours):" + ((minutes < 10) ? "0" : "") + "\(minutes):" + ((seconds < 10) ? "0" : "") + "\(seconds) " } init?(videoURL: URL) { let asset = AVURLAsset(url: videoURL, options: nil) let generator = AVAssetImageGenerator(asset: asset) generator.appliesPreferredTrackTransform = true guard let cgImage = try? generator.copyCGImage(at: CMTimeMake(value: 0, timescale: 1), actualTime: nil) else { return nil } self.thumbnail = UIImage(cgImage: cgImage) self.duration = Double(CMTimeGetSeconds(asset.duration)) } }
mit
0fe787cb8f0775501d5d3831a9573fbf
30.486486
217
0.612017
3.935811
false
false
false
false
gmoral/SwiftTraining2016
Pods/ImageLoader/ImageLoader/UIImageView+ImageLoader.swift
1
3773
// // UIImageView+ImageLoader.swift // ImageLoader // // Created by Hirohisa Kawasaki on 10/17/14. // Copyright © 2014 Hirohisa Kawasaki. All rights reserved. // import Foundation import UIKit private var ImageLoaderURLKey = 0 private var ImageLoaderBlockKey = 0 /** Extension using ImageLoader sends a request, receives image and displays. */ extension UIImageView { public static var imageLoader = Manager() // MARK: - properties private static let _ioQueue = dispatch_queue_create("swift.imageloader.queues.io", DISPATCH_QUEUE_CONCURRENT) private var URL: NSURL? { get { var URL: NSURL? dispatch_sync(UIImageView._ioQueue) { URL = objc_getAssociatedObject(self, &ImageLoaderURLKey) as? NSURL } return URL } set(newValue) { dispatch_barrier_async(UIImageView._ioQueue) { objc_setAssociatedObject(self, &ImageLoaderURLKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } private static let _Queue = dispatch_queue_create("swift.imageloader.queues.request", DISPATCH_QUEUE_SERIAL) // MARK: - functions public func load(URL: URLLiteralConvertible, placeholder: UIImage? = nil, completionHandler:CompletionHandler? = nil) { let block: () -> Void = { [weak self] in guard let wSelf = self else { return } wSelf.cancelLoading() } enqueue(block) image = placeholder imageLoader_load(URL.imageLoaderURL, completionHandler: completionHandler) } public func cancelLoading() { if let URL = URL { UIImageView.imageLoader.cancel(URL, identifier: hash) } } // MARK: - private private func imageLoader_load(URL: NSURL, completionHandler: CompletionHandler?) { let handler: CompletionHandler = { [weak self] URL, image, error, cacheType in if let wSelf = self, thisURL = wSelf.URL, image = image where thisURL.isEqual(URL) { wSelf.imageLoader_setImage(image, cacheType) } dispatch_async(dispatch_get_main_queue()) { completionHandler?(URL, image, error, cacheType) } } // caching if let data = UIImageView.imageLoader.cache[URL] { self.URL = URL handler(URL, UIImage.decode(data), nil, .Cache) return } let identifier = hash let block: () -> Void = { [weak self] in guard let wSelf = self else { return } let block = Block(identifier: identifier, completionHandler: handler) UIImageView.imageLoader.load(URL).appendBlock(block) wSelf.URL = URL } enqueue(block) } private func enqueue(block: () -> Void) { dispatch_async(UIImageView._Queue, block) } private func imageLoader_setImage(image: UIImage, _ cacheType: CacheType) { dispatch_async(dispatch_get_main_queue()) { [weak self] in guard let wSelf = self else { return } // Add a transition if UIImageView.imageLoader.automaticallyAddTransition && cacheType == CacheType.None { let transition = CATransition() transition.duration = 0.5 transition.type = kCATransitionFade wSelf.layer.addAnimation(transition, forKey: nil) } // Set an image if UIImageView.imageLoader.automaticallyAdjustsSize { wSelf.image = image.adjusts(wSelf.frame.size, scale: UIScreen.mainScreen().scale, contentMode: wSelf.contentMode) } else { wSelf.image = image } } } }
mit
61ae32411f602ae95405e0eed8d8a4ed
29.674797
129
0.602333
4.780735
false
false
false
false
vselpublic/booksheet
clients/booksheet-ios/Rectrec/BookmarkTableViewController.swift
1
4945
// // BookmarkTableViewController.swift // Rectrec // // Created by Volodymyr Selyukh on 26.04.15. // Copyright (c) 2015 D4F. All rights reserved. // import UIKit class BookmarkTableViewController: UITableViewController { //Primer ot Andreya pro class DataSources!!!! /* var bookmarks = [["text" : "iseyJhbGciOiJIUzI1NiIsImV4cCI6MTQzMDQxMTMzOCwiaWF0IjoxNDMwMDUxMzM4fQ.eyJpZCI6Mn0.-8Zshxuwut58k0c9FlkCI9V1SMhx44QkBmBPxQFLxHUiseyJhbGciOiJIUzI1NiIsImV4cCI6MTQzMDQxMTMzOCwiaWF0IjoxNDMwMDUxMzM4fQ.eyJpZCI6Mn0.-8Zshxuwut58k0c9FlkCI9V1SMhx44QkBmBPxQFLxHUiseyJhbGciOiJIUzI1NiIsImV4cCI6MTQzMDQxMTMzOCwiaWF0IjoxNDMwMDUxMzM4fQ.eyJpZCI6Mn0.-8Zshxuwut58k0c9FlkCI9V1SMhx44QkBmBPxQFLxHU", "bookname" : "test", "timestamp" : "Tue, 07 Apr 2015 10:00:37 GMT", "page" : "1"],["text" : "Греховность", "bookname" : "test2", "timestamp" : "Tue, 08 Apr 2015 10:00:37 GMT", "page" : "1"]] */ var bookmarks: JSON? override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = UITableViewAutomaticDimension BasicNetworkJSONSender.reciveAllBookmarksFromAPI2(){ (data, error) in if data != nil { println(data) self.bookmarks = data self.tableView.reloadData() } else { // Handle error / nil accessKey here println("FUCK") } } // 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 didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. //println(bookmarks.count) //return bookmarks.count return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return bookmarks?.count ?? 0 //return 1 } let BookmarkReuseIdentifier: String = "Bookmark" override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(BookmarkReuseIdentifier, forIndexPath: indexPath) as! BookmarkTableViewCell //as UITableViewCell // Configure the cell... var bookmark = Bookmark().initWithJSON(bookmarks![indexPath.row]) // cell.updateWithBookmark(bookmark) cell.bookmark = bookmark return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO 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, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .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, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
apache-2.0
13cf613a3611aea45529f284aaf89f8e
36.378788
406
0.67045
4.534926
false
false
false
false
OSzhou/MyTestDemo
PerfectDemoProject(swift写服务端)/.build/checkouts/Perfect-HTTPServer.git--6671958091389663080/Sources/PerfectHTTPServer/HTTP2/HTTP2Request.swift
1
10818
// // HTTP2.swift // PerfectLib // // Created by Kyle Jessup on 2016-02-18. // Copyright © 2016 PerfectlySoft. All rights reserved. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import PerfectHTTP import PerfectNet import PerfectLib import PerfectThread final class HTTP2Request: HTTPRequest, HeaderListener { var method: HTTPMethod = .get var path: String { get { var accum = "" var lastSlashExplicit = false for p in pathComponents { if p == "/" { accum += p lastSlashExplicit = true } else { if !lastSlashExplicit { accum += "/" } accum += p.stringByEncodingURL lastSlashExplicit = false } } return accum } set { let components = newValue.filePathComponents.map { $0 == "/" ? "/" : $0.stringByDecodingURL ?? "" } pathComponents = components } } var pathComponents = [String]() var queryString = "" var scheme = "" var authority = "" var queryParams: [(String, String)] = [] var protocolVersion = (2, 0) var remoteAddress: (host: String, port: UInt16) { guard let remote = connection.remoteAddress else { return ("", 0) } return (remote.host, remote.port) } var serverAddress: (host: String, port: UInt16) { guard let local = connection.localAddress else { return ("", 0) } return (local.host, local.port) } var serverName: String { return session?.server.serverName ?? "" } var documentRoot: String { return session?.server.documentRoot ?? "./" } var connection: NetTCP var urlVariables: [String:String] = [:] var scratchPad: [String:Any] = [:] private var headerStore = Dictionary<HTTPRequestHeader.Name, [UInt8]>() var headers: AnyIterator<(HTTPRequestHeader.Name, String)> { var g = self.headerStore.makeIterator() return AnyIterator<(HTTPRequestHeader.Name, String)> { guard let n = g.next() else { return nil } return (n.key, UTF8Encoding.encode(bytes: n.value)) } } func header(_ named: HTTPRequestHeader.Name) -> String? { guard let v = headerStore[named] else { return nil } return UTF8Encoding.encode(bytes: v) } func addHeader(_ named: HTTPRequestHeader.Name, value: String) { guard let existing = headerStore[named] else { self.headerStore[named] = [UInt8](value.utf8) return } let valueBytes = [UInt8](value.utf8) let newValue: [UInt8] if named == .cookie { newValue = existing + "; ".utf8 + valueBytes } else { newValue = existing + ", ".utf8 + valueBytes } self.headerStore[named] = newValue } func setHeader(_ named: HTTPRequestHeader.Name, value: String) { headerStore[named] = [UInt8](value.utf8) } lazy var postParams: [(String, String)] = { if let mime = self.mimes { return mime.bodySpecs.filter { $0.file == nil }.map { ($0.fieldName, $0.fieldValue) } } else if let bodyString = self.postBodyString { return self.deFormURLEncoded(string: bodyString) } return [(String, String)]() }() var postBodyBytes: [UInt8]? = nil var postBodyString: String? { guard let bytes = postBodyBytes else { return nil } if bytes.isEmpty { return "" } return UTF8Encoding.encode(bytes: bytes) } var postFileUploads: [MimeReader.BodySpec]? { guard let mimes = self.mimes else { return nil } return mimes.bodySpecs } weak var session: HTTP2Session? var decoder: HPACKDecoder { return session!.decoder } let streamId: UInt32 var streamState = HTTP2StreamState.idle var streamFlowWindows: HTTP2FlowWindows var encodedHeadersBlock = [UInt8]() var endOfHeaders = false var unblockCallback: (() -> ())? var debug: Bool { return session?.debug ?? false } var mimes: MimeReader? init(_ streamId: UInt32, session: HTTP2Session) { connection = session.net self.streamId = streamId self.session = session streamFlowWindows = HTTP2FlowWindows(serverWindowSize: session.serverSettings.initialWindowSize, clientWindowSize: session.clientSettings.initialWindowSize) } deinit { if debug { print("~HTTP2Request \(streamId)") } } func decodeHeadersBlock() { do { decoder.reset() try decoder.decode(input: Bytes(existingBytes: encodedHeadersBlock), headerListener: self) } catch { session?.fatalError(streamId: streamId, error: .compressionError, msg: "error while decoding headers \(error)") streamState = .closed } encodedHeadersBlock = [] } func headersFrame(_ frame: HTTP2Frame) { let endOfStream = (frame.flags & flagEndStream) != 0 if endOfStream { streamState = .halfClosed } else { streamState = .open } endOfHeaders = (frame.flags & flagEndHeaders) != 0 if debug { print("\tstream: \(streamId)") } let padded = (frame.flags & flagPadded) != 0 let priority = (frame.flags & flagPriority) != 0 if let ba = frame.payload, ba.count > 0 { let bytes = Bytes(existingBytes: ba) var padLength: UInt8 = 0 if padded { padLength = bytes.export8Bits() bytes.data.removeLast(Int(padLength)) } if priority { let _/*streamDep*/ = bytes.export32Bits() let _/*weight*/ = bytes.export8Bits() } encodedHeadersBlock += bytes.exportBytes(count: bytes.availableExportBytes) } if endOfHeaders { decodeHeadersBlock() } if endOfHeaders && endOfStream { processRequest() } else { session?.increaseServerWindow(stream: streamId, by: receiveWindowTopOff) } } func continuationFrame(_ frame: HTTP2Frame) { guard !endOfHeaders, streamState == .open else { session?.fatalError(streamId: streamId, error: .protocolError, msg: "Invalid frame") return } let endOfStream = (frame.flags & flagEndStream) != 0 if endOfStream { streamState = .halfClosed } endOfHeaders = (frame.flags & flagEndHeaders) != 0 if debug { print("\tstream: \(streamId)") } if let ba = frame.payload, ba.count > 0 { encodedHeadersBlock += ba } if endOfHeaders { decodeHeadersBlock() } if endOfHeaders && endOfStream { processRequest() } else { session?.increaseServerWindow(stream: streamId, by: receiveWindowTopOff) } } // session handles window adjustments func dataFrame(_ frame: HTTP2Frame) { let endOfStream = (frame.flags & flagEndStream) != 0 let bytes = frame.payload ?? [] let padded = (frame.flags & flagPadded) != 0 if debug { print("request \(streamId) POST bytes: \(bytes.count), recv window: \(streamFlowWindows.serverWindowSize), EOS: \(endOfStream), padded: \(padded)") } if padded { let padSize = Int(bytes[0]) let lastIndex = bytes.count - padSize putPostData(Array(bytes[1..<lastIndex])) } else { putPostData(bytes) } if endOfStream { processRequest() } } func priorityFrame(_ frame: HTTP2Frame) { } func cancelStreamFrame(_ frame: HTTP2Frame) { streamState = .closed if let u = unblockCallback { unblockCallback = nil u() } } func putPostData(_ b: [UInt8]) { if let mimes = self.mimes { return mimes.addToBuffer(bytes: b) } else { if nil == postBodyBytes { postBodyBytes = b } else { postBodyBytes?.append(contentsOf: b) } } } func processRequest() { let response = HTTP2Response(self) Threading.dispatch { // get off the frame read thread self.routeRequest(response: response) } } func routeRequest(response: HTTPResponse) { session?.server.filterAndRun(request: self, response: response) } // scheme, authority func addHeader(name: [UInt8], value: [UInt8], sensitive: Bool) { let n = String(validatingUTF8: name) ?? "" switch n { case ":method": method = HTTPMethod.from(string: String(validatingUTF8: value) ?? "") case ":path": (self.pathComponents, self.queryString) = parseURI(pathBuffer: value) case ":scheme": scheme = UTF8Encoding.encode(bytes: value) case ":authority": authority = UTF8Encoding.encode(bytes: value) default: let headerName = HTTPRequestHeader.Name.fromStandard(name: n) if headerName == .contentType { let contentType = String(validatingUTF8: value) ?? "" if contentType.characters.starts(with: "multipart/form-data".characters) { self.mimes = MimeReader(contentType) } } headerStore[headerName] = value } if debug { print("\t\(n): \(UTF8Encoding.encode(bytes: value))") } } } extension HTTP2Request { func deFormURLEncoded(string: String) -> [(String, String)] { return string.characters.split(separator: "&").map(String.init).flatMap { let d = $0.characters.split(separator: "=", maxSplits: 1).flatMap { String($0).stringByDecodingURL } if d.count == 2 { return (d[0], d[1]) } if d.count == 1 { return (d[0], "") } return nil } } // parse from workingBuffer contents func parseURI(pathBuffer: [UInt8]) -> ([String], String) { enum ParseURLState { case slash, component, query } var state = ParseURLState.slash var gen = pathBuffer.makeIterator() var decoder = UTF8() var pathComponents = ["/"] var component = "" var queryString = "" let question = UnicodeScalar(63) let slash = UnicodeScalar(47) loopy: repeat { let res = decoder.decode(&gen) switch res { case .scalarValue(let uchar): switch state { case .slash: if uchar == question { state = .query pathComponents.append("/") } else if uchar != slash { state = .component component = String(Character(uchar)) } case .component: if uchar == question { state = .query pathComponents.append(component.stringByDecodingURL ?? "") } else if uchar == slash { state = .slash pathComponents.append(component.stringByDecodingURL ?? "") } else { component.append(Character(uchar)) } case .query: queryString.append(Character(uchar)) } case .emptyInput, .error: switch state { case .slash: if pathComponents.count > 1 { pathComponents.append("/") } case .component: pathComponents.append(component.stringByDecodingURL ?? "") case .query: () } break loopy } } while true return (pathComponents, queryString) } } extension HTTP2Request { func canSend(count: Int) -> Bool { return session!.connectionFlowWindows.clientWindowSize - count > 0 && streamFlowWindows.clientWindowSize - count > 0 } func canRecv(count: Int) -> Bool { return session!.connectionFlowWindows.serverWindowSize - count > 0 && streamFlowWindows.serverWindowSize - count > 0 } }
apache-2.0
54154518753642aa6fe9c88ee0536512
26.38481
150
0.654248
3.450399
false
false
false
false
FoodForTech/Handy-Man
HandyMan/HandyMan/Features/Login/Controllers/LoginViewController.swift
1
6339
// // LoginViewController.swift // HandyMan // // Created by Don Johnson on 12/6/15. // Copyright © 2015 Don Johnson. All rights reserved. // import UIKit final class LoginViewController: HMViewController { // MARK: IBOutlets @IBOutlet fileprivate weak var userNameTextField: DesignableTextField! @IBOutlet fileprivate weak var passwordTextField: DesignableTextField! @IBOutlet private weak var logOnButton: SpringButton! @IBOutlet private weak var loginCredentialsView: SpringView! @IBOutlet private weak var brandingLabel: SpringLabel! // MARK: General Properties private var registerUserCredentials: UserCredentials? private var handyDoList = HandyDoList() // MARK: - Business Services private lazy var loginBusinessService: LoginBusinessService = { return LoginBusinessService(uiDelegate: self) }() private lazy var handyDoBusinessService: HandyDoBusinessService = { return HandyDoBusinessService(uiDelegate: self) }() // MARK: Lifecycle Methods override func viewDidLoad() { super.viewDidLoad() self.userNameTextField.delegate = self self.passwordTextField.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.brandingLabel.isHidden = true delay(1.0) { self.brandingLabel.isHidden = false self.brandingLabel.animation = "slideLeft" self.brandingLabel.animate() } } // MARK: IBActions @IBAction private func logOn(_ sender: UIButton) { logOn() } @IBAction private func register(_ sender: UIButton) { guard let emailAddress = self.userNameTextField.text, let password = self.passwordTextField.text else { return } self.registerUserCredentials = UserCredentials(emailAddress: emailAddress, password: password) self.performSegue(withIdentifier: "LoginRegisterViewControllerSegue", sender: self) } // MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let navigationController = segue.destination as? UINavigationController { if let handyDoListViewController: HandyDoListViewController = navigationController.topViewController as? HandyDoListViewController { handyDoListViewController.configureWithHandyDoList(self.handyDoList) return } } if let loginRegisterViewController = segue.destination as? LoginRegisterViewController { loginRegisterViewController.userCredentials = registerUserCredentials return } } // MARK: - Helper Methods fileprivate func logOn() { guard let userNameTextField = self.userNameTextField, var emailAddress = userNameTextField.text, let passwordTextField = self.passwordTextField, var password = passwordTextField.text else { return } self.decorate(userNameTextField, withBorderWidth: 0, usingColor: UIColor.black) self.decorate(passwordTextField, withBorderWidth: 0, usingColor: UIColor.black) let userCredentials = UserCredentials(emailAddress: emailAddress, password: password) if (userCredentials.isValid()) { self.loginBusinessService.authorizeUser(userCredentials) { (user: User) in if (user.isEmpty()) { self.presentUIAlertController(LoginStrings.AuthErrorTitle.localized, message: LoginStrings.AuthErrorMessage.localized) } else { emailAddress = "" password = "" self.handyDoBusinessService.retrieveHandyDoList(AssignmentType.assignee) { handyDoList in switch handyDoList { case .items(let handyDoList): self.handyDoList.handyDoList = handyDoList self.performSegue(withIdentifier: "HandyDoListViewControllerSegue", sender: self) case .failure(_): break; default: break; } } } } } else { loginCredentialsView.animateWithAnimation("shake") if emailAddress.isEmpty { decorate(self.userNameTextField, withBorderWidth: 2, usingColor: UIColor.red) } if password.isEmpty { decorate(self.passwordTextField, withBorderWidth: 2, usingColor: UIColor.red) } } } private func decorate(_ textField: DesignableTextField, withBorderWidth borderWidth: CGFloat, usingColor color: UIColor) { textField.borderWidth = borderWidth textField.borderColor = color } private func presentUIAlertController(_ title: String, message:String) { let alertController: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: UIDevice.current.userInterfaceIdiom == .phone ? .actionSheet: .alert) let okAction = UIAlertAction(title: LoginStrings.AuthErrorOkButtonTitle.localized, style: .default) { (action: UIAlertAction) in self.presentingViewController?.dismiss(animated: true, completion: nil) } alertController.addAction(okAction) self.present(alertController, animated: true, completion: nil) } } // MARK: UITextField Delegate extension LoginViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { guard let emailAddress = self.userNameTextField?.text, let password = self.passwordTextField?.text else { return true } self.userNameTextField.resignFirstResponder() self.passwordTextField.resignFirstResponder() if !emailAddress.isEmpty && !password.isEmpty { logOn() return true } return false } }
mit
f7921da65ccc0460dc14d55eb9a87693
36.064327
184
0.623698
5.663986
false
false
false
false
OSzhou/MyTestDemo
17_SwiftTestCode/TestCode/CustomAlbum/Source/Extension/UIView+HE.swift
1
2997
// // NSObjectExtension.swift // SwiftPhotoSelector // // Created by heyode on 2018/9/19. // Copyright (c) 2018 heyode <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit extension UIView { @IBInspectable var he_cornerRadius: CGFloat { get { return layer.cornerRadius } // also set(newValue) set { layer.cornerRadius = newValue } } @IBInspectable var he_maskToBounds: Bool { get { return layer.masksToBounds } // also set(newValue) set { layer.masksToBounds = newValue } } @IBInspectable var he_borderColor: UIColor { get { return UIColor.init(cgColor: layer.borderColor!) } // also set(newValue) set { layer.borderColor = newValue.cgColor } } @IBInspectable var he_borderWidth: CGFloat { get { return layer.borderWidth } // also set(newValue) set { layer.borderWidth = newValue } } } public extension UIViewController { /// 自定义present方法 /// /// - Parameters: /// - picker: 图片选择器 /// - animated: 是否需要动画 func hePresentPhotoPickerController(picker:HEPhotoPickerViewController,animated: Bool){ let nav = UINavigationController.init(rootViewController: picker) nav.modalPresentationStyle = .fullScreen present(nav, animated: animated, completion: nil) } func presentAlert(title:String){ let title = title let alertView = UIAlertController.init(title: "提示", message: title, preferredStyle: .alert) let okAction = UIAlertAction.init(title:"确定", style: .default) { okAction in } alertView.addAction(okAction) self.present(alertView, animated: true, completion: nil) } }
apache-2.0
fef3846f8b6a2f4a9b4b3cc8a516bf3c
32.988506
99
0.648969
4.563272
false
false
false
false
adrfer/swift
test/Sema/Inputs/availability_multi_other.swift
3
3130
// This file is used by Sema/availability_versions_multi.swift to // test that we build enough of the type refinement context as needed to // validate declarations when resolving declaration signatures. // This file relies on the minimum deployment target for OS X being 10.9. @available(OSX, introduced=10.52) private class PrivateIntroduced10_52 { } class OtherIntroduced10_9 { } @available(OSX, introduced=10.51) class OtherIntroduced10_51 { func uses10_52() { // If this were the primary file then the below would emit an error, because // PrivateIntroduced10_53 is not available on 10.52. But since we only // run the first pass of the type checker on these declarations, // the body is not checked. _ = PrivateIntroduced10_52() } // This method uses a 10_52 only type in its signature, so validating // the declaration should produce an availability error func returns10_52() -> OtherIntroduced10_52 { // expected-error {{'OtherIntroduced10_52' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add @available attribute to enclosing instance method}} // Body is not type checked (by design) so no error is expected for unavailable type used in return. return OtherIntroduced10_52() } @available(OSX, introduced=10.52) func returns10_52Introduced10_52() -> OtherIntroduced10_52 { return OtherIntroduced10_52() } func takes10_52(o: OtherIntroduced10_52) { } @available(OSX, introduced=10.52) func takes10_52Introduced10_52(o: OtherIntroduced10_52) { } var propOf10_52: OtherIntroduced10_52 = OtherIntroduced10_52() // We don't expect an error here because the initializer is not type checked (by design). @available(OSX, introduced=10.52) var propOf10_52Introduced10_52: OtherIntroduced10_52 = OtherIntroduced10_52() @available(OSX, introduced=10.52) class NestedIntroduced10_52 : OtherIntroduced10_52 { override func returns10_52() -> OtherIntroduced10_52 { } @available(OSX, introduced=10.53) func returns10_53() -> OtherIntroduced10_53 { } } } @available(OSX, introduced=10.51) class SubOtherIntroduced10_51 : OtherIntroduced10_51 { } @available(OSX, introduced=10.52) class OtherIntroduced10_52 : OtherIntroduced10_51 { } extension OtherIntroduced10_51 { // expected-error {{'OtherIntroduced10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add @available attribute to enclosing extension}} } extension OtherIntroduced10_9 { @available(OSX, introduced=10.51) func extensionMethodOnOtherIntroduced10_9AvailableOn10_51(p: OtherIntroduced10_51) { } } @available(OSX, introduced=10.51) extension OtherIntroduced10_51 { func extensionMethodOnOtherIntroduced10_51() { } @available(OSX, introduced=10.52) func extensionMethodOnOtherIntroduced10_51AvailableOn10_52() { } } @available(OSX, introduced=10.53) class OtherIntroduced10_53 { } var globalFromOtherOn10_52 : OtherIntroduced10_52? = nil // expected-error {{'OtherIntroduced10_52' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add @available attribute to enclosing var}}
apache-2.0
4fa4498482918d4de9c63e176fc7ce04
33.395604
142
0.736741
3.68669
false
false
false
false
adevelopers/prosvet
Prosvet/Common/Models/Post.swift
1
1075
// // Post.swift // Prosvet // // Created by adeveloper on 21.05.17. // Copyright © 2017 adeveloper. All rights reserved. // import UIKit typealias ID = Int typealias PDate = Date protocol AuthorProtocol { var authorId: ID { get } var authorName: String { get set } } struct Author: AuthorProtocol { var authorName: String var authorId: ID } protocol PostProtocol { var dataCreate: PDate { get set } var title: String { get set } var text: String { get set } var author: AuthorProtocol {get set} var numberOfRead: Int { get } } struct Post: PostProtocol { var id:ID var title: String var author: AuthorProtocol var text: String var dataCreate: PDate init(){ self.id = 0 self.title = "" self.text = "" let newAuthor = Author(authorName: "Кирилл", authorId: 1) let date: PDate = PDate(timeIntervalSinceNow: 10) self.dataCreate = date self.author = newAuthor self.numberOfRead = 0 } internal var numberOfRead: Int }
mit
b6a5a1e85001f454236e4a3f6d6242c0
18.418182
65
0.624532
3.734266
false
false
false
false
giacgbj/UIImageSwiftExtensions
Source/UIImage+Alpha.swift
2
4322
// // UIImage+Alpha.swift // // Created by Trevor Harmon on 09/20/09. // Swift 3 port by Giacomo Boccardo on 09/15/2016. // // Free for personal or commercial use, with or without modification // No warranty is expressed or implied. // import UIKit public extension UIImage { public func hasAlpha() -> Bool { let alpha: CGImageAlphaInfo = (self.cgImage)!.alphaInfo return alpha == CGImageAlphaInfo.first || alpha == CGImageAlphaInfo.last || alpha == CGImageAlphaInfo.premultipliedFirst || alpha == CGImageAlphaInfo.premultipliedLast } public func imageWithAlpha() -> UIImage { if self.hasAlpha() { return self } let imageRef:CGImage = self.cgImage! let width = imageRef.width let height = imageRef.height // The bitsPerComponent and bitmapInfo values are hard-coded to prevent an "unsupported parameter combination" error let offscreenContext: CGContext = CGContext( data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: imageRef.colorSpace!, bitmapInfo: 0 /*CGImageByteOrderInfo.orderMask.rawValue*/ | CGImageAlphaInfo.premultipliedFirst.rawValue )! // Draw the image into the context and retrieve the new image, which will now have an alpha layer offscreenContext.draw(imageRef, in: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))) let imageRefWithAlpha:CGImage = offscreenContext.makeImage()! return UIImage(cgImage: imageRefWithAlpha) } public func transparentBorderImage(_ borderSize: Int) -> UIImage { let image = self.imageWithAlpha() let newRect = CGRect( x: 0, y: 0, width: image.size.width + CGFloat(borderSize) * 2, height: image.size.height + CGFloat(borderSize) * 2 ) // Build a context that's the same dimensions as the new size let bitmap: CGContext = CGContext( data: nil, width: Int(newRect.size.width), height: Int(newRect.size.height), bitsPerComponent: (self.cgImage)!.bitsPerComponent, bytesPerRow: 0, space: (self.cgImage)!.colorSpace!, bitmapInfo: (self.cgImage)!.bitmapInfo.rawValue )! // Draw the image in the center of the context, leaving a gap around the edges let imageLocation = CGRect(x: CGFloat(borderSize), y: CGFloat(borderSize), width: image.size.width, height: image.size.height) bitmap.draw(self.cgImage!, in: imageLocation) let borderImageRef: CGImage = bitmap.makeImage()! // Create a mask to make the border transparent, and combine it with the image let maskImageRef: CGImage = self.newBorderMask(borderSize, size: newRect.size) let transparentBorderImageRef: CGImage = borderImageRef.masking(maskImageRef)! return UIImage(cgImage:transparentBorderImageRef) } fileprivate func newBorderMask(_ borderSize: Int, size: CGSize) -> CGImage { let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceGray() // Build a context that's the same dimensions as the new size let maskContext: CGContext = CGContext( data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, // 8-bit grayscale bytesPerRow: 0, space: colorSpace, bitmapInfo: CGBitmapInfo().rawValue | CGImageAlphaInfo.none.rawValue )! // Start with a mask that's entirely transparent maskContext.setFillColor(UIColor.black.cgColor) maskContext.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height)) // Make the inner part (within the border) opaque maskContext.setFillColor(UIColor.white.cgColor) maskContext.fill(CGRect( x: CGFloat(borderSize), y: CGFloat(borderSize), width: size.width - CGFloat(borderSize) * 2, height: size.height - CGFloat(borderSize) * 2) ) // Get an image of the context return maskContext.makeImage()! } }
mit
f1e40daccaf4354e09e2bf50f32911d5
39.773585
134
0.625636
4.818283
false
false
false
false
wilsonpage/magnet-client
ios/LocationChangeReceiver.swift
1
1230
// // LocationChangeReceiver.swift // Magnet // // Created by Francisco Jordano on 24/10/2016. // import Foundation import CoreLocation @objc(LocationChangeReceiver) class LocationChangeReceiver: NSObject, CLLocationManagerDelegate { let locationManager:CLLocationManager = CLLocationManager() var scanner: MagnetScanner! = nil @objc override init() { super.init() scanner = MagnetScanner(callback: self.onItemFound) } private func onItemFound(item: Dictionary<String, AnyObject>) { let url = item["url"] as! String NotificationsHelper.notifyUser(url) } @objc func startSignificantLocationChanges() { self.locationManager.delegate = self self.locationManager.requestAlwaysAuthorization() self.locationManager.startMonitoringSignificantLocationChanges() } @objc func stopSignificantLocationChanges() { self.locationManager.stopMonitoringSignificantLocationChanges() } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { // Scan just if we are in background guard UIApplication.sharedApplication().applicationState == UIApplicationState.Background else { return; } scanner!.start() } }
mpl-2.0
1ee04c19b3cd34b6840d3b6759bfc8a0
27.604651
100
0.746341
5.103734
false
false
false
false
davetrux/1DevDayDetroit-2014
ios/ToDo/ToDo/AppDelegate.swift
1
6121
// // AppDelegate.swift // ToDo // // Created by David Truxall on 11/3/14. // Copyright (c) 2014 Hewlett-Packard Company. All rights reserved. // import UIKit import CoreData @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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.onedevday.ToDo" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("ToDo", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("ToDo.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
ad674cb2a6acd7fe636868b6825e8088
54.144144
290
0.715896
5.747418
false
false
false
false
tkremenek/swift
test/Concurrency/async_sequence_syntax.swift
1
3081
// RUN: %target-typecheck-verify-swift -enable-experimental-concurrency -disable-availability-checking // REQUIRES: concurrency // expected-note@+2{{add 'async' to function 'missingAsync' to make it asynchronous}} @available(SwiftStdlib 5.5, *) func missingAsync<T : AsyncSequence>(_ seq: T) throws { for try await _ in seq { } // expected-error{{'async' in a function that does not support concurrency}} } @available(SwiftStdlib 5.5, *) func missingThrows<T : AsyncSequence>(_ seq: T) async { for try await _ in seq { } // expected-error{{error is not handled because the enclosing function is not declared 'throws'}} } @available(SwiftStdlib 5.5, *) func executeAsync(_ work: () async -> Void) { } @available(SwiftStdlib 5.5, *) func execute(_ work: () -> Void) { } @available(SwiftStdlib 5.5, *) func missingThrowingInBlock<T : AsyncSequence>(_ seq: T) { executeAsync { // expected-error{{invalid conversion from throwing function of type '() async throws -> Void' to non-throwing function type '() async -> Void'}} for try await _ in seq { } } } @available(SwiftStdlib 5.5, *) func missingTryInBlock<T : AsyncSequence>(_ seq: T) { executeAsync { for await _ in seq { } // expected-error{{call can throw, but the error is not handled}} } } @available(SwiftStdlib 5.5, *) func missingAsyncInBlock<T : AsyncSequence>(_ seq: T) { execute { // expected-error{{cannot pass function of type '() async -> Void' to parameter expecting synchronous function type}} do { for try await _ in seq { } // expected-note {{'async' inferred from asynchronous operation used here}} } catch { } } } @available(SwiftStdlib 5.5, *) func doubleDiagCheckGeneric<T : AsyncSequence>(_ seq: T) async { var it = seq.makeAsyncIterator() // expected-note@+2{{call is to 'rethrows' function, but a conformance has a throwing witness}} // expected-error@+1{{call can throw, but it is not marked with 'try' and the error is not handled}} let _ = await it.next() } @available(SwiftStdlib 5.5, *) struct ThrowingAsyncSequence: AsyncSequence, AsyncIteratorProtocol { typealias Element = Int typealias AsyncIterator = Self mutating func next() async throws -> Int? { return nil } func makeAsyncIterator() -> Self { return self } } @available(SwiftStdlib 5.5, *) func doubleDiagCheckConcrete(_ seq: ThrowingAsyncSequence) async { var it = seq.makeAsyncIterator() // expected-error@+1{{call can throw, but it is not marked with 'try' and the error is not handled}} let _ = await it.next() } // rdar://75274975 @available(SwiftStdlib 5.5, *) func forAwaitInsideDoCatch<Source: AsyncSequence>(_ source: Source) async { do { for try await item in source { print(item) } } catch {} // no-warning } @available(SwiftStdlib 5.5, *) func forAwaitWithConcreteType(_ seq: ThrowingAsyncSequence) throws { // expected-note {{add 'async' to function 'forAwaitWithConcreteType' to make it asynchronous}} for try await elt in seq { // expected-error {{'async' in a function that does not support concurrency}} _ = elt } }
apache-2.0
d59778d3e773660f7b2c2f93da5ce5ef
35.678571
164
0.695553
3.85125
false
false
false
false
yuezaixz/UPillow
UPillow/Classes/View/SwitchCell.swift
2
553
// // SwitchCell.swift // TodayMind // // Created by cyan on 2017/2/21. // Copyright © 2017 cyan. All rights reserved. // import UIKit import TMKit class SwitchCell: BaseCell { let switcher = UISwitch() init(title: String, identifier: String, on: Bool) { super.init(style: .default, reuseIdentifier: identifier) textLabel?.text = title switcher.isOn = on accessoryView = switcher selectionStyle = .none } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-3.0
44e488d36fdec6b252ee8b01f4a9296e
19.444444
60
0.67029
3.887324
false
false
false
false
yichizhang/YZQuickLayout
YZQuickLayoutDemo/YZQuickLayoutDemo/DemoSegmentedView.swift
1
3369
// // DemoSegmentedView.swift // YZQuickLayoutDemo // // Created by Yichi on 14/12/2014. // Copyright (c) 2014 Yichi Zhang. All rights reserved. // import UIKit @objc class DemoSegmentedView: YZQuickLayoutView { var segmentItems: Array<AnyObject>! var optionViews: Array<UIView>! var optionViewsSettings: Array<Float>! var setUpViewForNormalState: ((UIView)->())! var setUpViewForSelectedState: ((UIView)->())! var tapGestureRecognizer: UITapGestureRecognizer! private var privateViewAtIndexIsTapped: ((UIView, Int)->())! var viewAtIndexIsTapped: ((UIView, Int)->())! override func setUp() { super.setUp() tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "thisViewIsTapped:") self.addGestureRecognizer(tapGestureRecognizer) } override func removeFromSuperview() { self.removeGestureRecognizer(tapGestureRecognizer) super.removeFromSuperview() } func updateDemoSegmentViews() { //segmentItems = [DemoStyleKit.imageOfPDF, "Duck", "Penguin"] optionViews = [] optionViewsSettings = [] for obj in segmentItems { if( obj.isKindOfClass(NSString) ){ var label = UILabel() label.text = obj as? String optionViews.append(label) optionViewsSettings.append(2) }else if( obj.isKindOfClass(UIImage) ){ var imageView = UIImageView(image: obj as? UIImage) optionViews.append(imageView) optionViewsSettings.append(1) }else{ var label = UILabel() label.text = "?" optionViews.append(label) optionViewsSettings.append(2) } } /* setUpViewForNormalState = { (view: UIView)->() in if (view.isKindOfClass(UILabel)){ let label = view as UILabel label.backgroundColor = UIColor.blueColor() label.textColor = UIColor.whiteColor() label.textAlignment = NSTextAlignment.Center }else if (view.isKindOfClass(UIImageView)){ let imageView = view as UIImageView imageView.backgroundColor = UIColor.blueColor() imageView.contentMode = UIViewContentMode.Center } } setUpViewForSelectedState = { (view: UIView)->() in if (view.isKindOfClass(UILabel)){ let label = view as UILabel label.backgroundColor = UIColor.redColor() label.textColor = UIColor.whiteColor() }else if (view.isKindOfClass(UIImageView)){ let imageView = view as UIImageView imageView.backgroundColor = UIColor.redColor() imageView.contentMode = UIViewContentMode.Center } } */ privateViewAtIndexIsTapped = { (view:UIView, idx:Int)->() in for view1: UIView in self.optionViews { self.setUpViewForNormalState?(view1); } self.setUpViewForSelectedState?(view); } self.setQuickLayoutMode( YZQuickLayoutModeHorizontal, forViews: optionViews, withPadding: 5, andSettings: optionViewsSettings ); for view: UIView in optionViews { setUpViewForNormalState?(view); } } func thisViewIsTapped(recognizer: UITapGestureRecognizer)->(){ let touchInView:CGPoint = recognizer.locationInView(self) let touchRect:CGRect = CGRectMake(touchInView.x, touchInView.y, 1, 1) var idx:Int = 0 for view: UIView in optionViews { if CGRectIntersectsRect(view.frame, touchRect){ privateViewAtIndexIsTapped?(view, idx); } idx++; } } }
mit
8e9bfc2c54dc0313610a959bacd776e0
21.164474
90
0.683882
3.991706
false
false
false
false
morpheby/aTarantula
aTarantula/views/WebViewViewController.swift
1
4502
// // WebViewViewController.swift // aTarantula // // Created by Ilya Mikhaltsou on 9/24/17. // Copyright © 2017 morpheby. All rights reserved. // import Cocoa import WebKit import TarantulaPluginCore class WebViewViewController: NSViewController { @IBOutlet var webViewContainer: NSView! @objc dynamic var webView: WKWebView let pool = WKProcessPool() let configuration = WKWebViewConfiguration() var dataStore: WKWebsiteDataStore! var plugin: TarantulaCrawlingPlugin! var cookies: [HTTPCookie] = [] var oldCookies: [HTTPCookie] = [] required init?(coder: NSCoder) { configuration.processPool = pool webView = WKWebView(frame: .zero, configuration: configuration) super.init(coder: coder) if #available(OSX 10.13, *) { dataStore = WKWebsiteDataStore.nonPersistent() dataStore.httpCookieStore.add(self) } else { dataStore = WKWebsiteDataStore.default() } configuration.websiteDataStore = dataStore } var url: URL? @objc dynamic var urlString: String? { set { guard let v = newValue else { return } guard let url = URL(string: v) else { let alert = NSAlert() alert.messageText = "Invalid URL" alert.addButton(withTitle: "OK") alert.runModal() return } self.url = url } get { return url?.absoluteString } } deinit { if #available(OSX 10.13, *) { dataStore.httpCookieStore.remove(self) } } @IBAction func load(_ sender: Any) { guard let url = url else { return } webView.load(URLRequest(url: url)) } @IBAction func done(_ sender: Any) { availability: if #available(OSX 10.13, *) { } else { // Find difference with initial value guard let newCookies = URLSession.shared.configuration.httpCookieStorage?.cookies else { break availability } let difference = newCookies.filter({ (c) -> Bool in !self.oldCookies.contains(c) }) cookies = difference } NSApplication.shared.controller.setCookies(cookies, inPlugin: plugin) dismiss(sender) } override func viewDidLoad() { super.viewDidLoad() if #available(OSX 10.13, *) { for cookie in NSApplication.shared.controller.cookies(inPlugin: plugin) { dataStore.httpCookieStore.setCookie(cookie, completionHandler: nil) } } else { // Rely on shared cookies only if URLSession.shared.configuration.httpCookieStorage == nil { URLSession.shared.configuration.httpCookieStorage = HTTPCookieStorage.shared } for cookie in NSApplication.shared.controller.cookies(inPlugin: plugin) { URLSession.shared.configuration.httpCookieStorage?.setCookie(cookie) } oldCookies = URLSession.shared.configuration.httpCookieStorage?.cookies ?? [] } webViewContainer.addSubview(webView) webView.frame = webViewContainer.bounds webViewContainer.addConstraints([ NSLayoutConstraint(item: webViewContainer, attribute: .top, relatedBy: .equal, toItem: webView, attribute: .top, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: webViewContainer, attribute: .bottom, relatedBy: .equal, toItem: webView, attribute: .bottom, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: webViewContainer, attribute: .left, relatedBy: .equal, toItem: webView, attribute: .left, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: webViewContainer, attribute: .right, relatedBy: .equal, toItem: webView, attribute: .right, multiplier: 1.0, constant: 0.0), ]) } @objc dynamic override var title: String? { get { return webView.title } set { // Ignore } } @objc static func keyPathsForValuesAffectingTitle() -> Set<String> { return Set(["\(#keyPath(webView.title))"]) } } extension WebViewViewController: WKHTTPCookieStoreObserver { @available(OSX 10.13, *) func cookiesDidChange(in cookieStore: WKHTTPCookieStore) { cookieStore.getAllCookies({ c in self.cookies = c }) } }
gpl-3.0
fa363dba0f213ccd8b2588bce4ef23cd
30.921986
163
0.61142
4.788298
false
true
false
false
xwu/swift
stdlib/private/StdlibUnittest/OpaqueIdentityFunctions.swift
4
2678
//===--- OpaqueIdentityFunctions.swift ------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 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 // //===----------------------------------------------------------------------===// @_silgen_name("getPointer") func _getPointer(_ x: OpaquePointer) -> OpaquePointer public func _opaqueIdentity<T>(_ x: T) -> T { let ptr = UnsafeMutablePointer<T>.allocate(capacity: 1) ptr.initialize(to: x) let result = UnsafeMutablePointer<T>(_getPointer(OpaquePointer(ptr))).pointee ptr.deinitialize(count: 1) ptr.deallocate() return result } func _blackHolePtr<T>(_ x: UnsafePointer<T>) { _ = _getPointer(OpaquePointer(x)) } public func _blackHole<T>(_ x: T) { var x = x _blackHolePtr(&x) } @inline(never) public func getBool(_ x: Bool) -> Bool { return _opaqueIdentity(x) } @inline(never) public func getInt8(_ x: Int8) -> Int8 { return _opaqueIdentity(x) } @inline(never) public func getInt16(_ x: Int16) -> Int16 { return _opaqueIdentity(x) } @inline(never) public func getInt32(_ x: Int32) -> Int32 { return _opaqueIdentity(x) } @inline(never) public func getInt64(_ x: Int64) -> Int64 { return _opaqueIdentity(x) } @inline(never) public func getInt(_ x: Int) -> Int { return _opaqueIdentity(x) } @inline(never) public func getUInt8(_ x: UInt8) -> UInt8 { return _opaqueIdentity(x) } @inline(never) public func getUInt16(_ x: UInt16) -> UInt16 { return _opaqueIdentity(x) } @inline(never) public func getUInt32(_ x: UInt32) -> UInt32 { return _opaqueIdentity(x) } @inline(never) public func getUInt64(_ x: UInt64) -> UInt64 { return _opaqueIdentity(x) } @inline(never) public func getUInt(_ x: UInt) -> UInt { return _opaqueIdentity(x) } #if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64)) @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) @inline(never) public func getFloat16(_ x: Float16) -> Float16 { return _opaqueIdentity(x) } #endif @inline(never) public func getFloat32(_ x: Float32) -> Float32 { return _opaqueIdentity(x) } @inline(never) public func getFloat64(_ x: Float64) -> Float64 { return _opaqueIdentity(x) } #if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64)) @inline(never) public func getFloat80(_ x: Float80) -> Float80 { return _opaqueIdentity(x) } #endif public func getPointer(_ x: OpaquePointer) -> OpaquePointer { return _opaqueIdentity(x) }
apache-2.0
f3a126b96053b84affd28cb92ee341ff
29.781609
80
0.665049
3.446589
false
false
false
false
xwu/swift
test/SILOptimizer/definite-init-convert-to-escape.swift
3
6212
// RUN: %target-swift-frontend -module-name A -verify -emit-sil -import-objc-header %S/Inputs/Closure.h -disable-copy-propagation -disable-objc-attr-requires-foundation-module %s | %FileCheck %s // RUN: %target-swift-frontend -module-name A -verify -emit-sil -import-objc-header %S/Inputs/Closure.h -disable-copy-propagation -disable-objc-attr-requires-foundation-module -Xllvm -sil-disable-convert-escape-to-noescape-switch-peephole %s | %FileCheck %s --check-prefix=NOPEEPHOLE // // Using -disable-copy-propagation to pattern match against older SIL // output. At least until -enable-copy-propagation has been around // long enough in the same form to be worth rewriting CHECK lines. // REQUIRES: objc_interop import Foundation // Make sure that we keep the escaping closures alive across the ultimate call. // CHECK-LABEL: sil @$s1A19bridgeNoescapeBlock5optFn0D3Fn2yySSSgcSg_AFtF // CHECK: bb0 // CHECK: retain_value %0 // CHECK: retain_value %0 // CHECK: bb1 // CHECK: convert_escape_to_noescape % // CHECK: strong_release // CHECK: bb5 // CHECK: retain_value %1 // CHECK: retain_value %1 // CHECK: bb6 // CHECK: convert_escape_to_noescape % // CHECK: strong_release // CHECK: bb10 // CHECK: [[F:%.*]] = function_ref @noescapeBlock3 // CHECK: apply [[F]] // CHECK: release_value {{.*}} : $Optional<NSString> // CHECK: release_value %1 : $Optional<@callee_guaranteed (@guaranteed Optional<String>) -> ()> // CHECK: release_value {{.*}} : $Optional<@convention(block) @noescape (Optional<NSString>) -> ()> // CHECK: release_value %0 : $Optional<@callee_guaranteed (@guaranteed Optional<String>) -> ()> // CHECK: release_value {{.*}} : $Optional<@convention(block) @noescape (Optional<NSString>) public func bridgeNoescapeBlock( optFn: ((String?) -> ())?, optFn2: ((String?) -> ())?) { noescapeBlock3(optFn, optFn2, "Foobar") } @_silgen_name("_returnOptionalEscape") public func returnOptionalEscape() -> (() ->())? // Make sure that we keep the escaping closure alive across the ultimate call. // CHECK-LABEL: sil @$s1A19bridgeNoescapeBlockyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: [[NONE:%.*]] = enum $Optional<{{.*}}>, #Optional.none!enumelt // CHECK: [[V0:%.*]] = function_ref @_returnOptionalEscape // CHECK: [[V1:%.*]] = apply [[V0]] // CHECK: retain_value [[V1]] // CHECK: switch_enum [[V1]] : $Optional<{{.*}}>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[V2:%.*]] : $@callee_guaranteed () -> ()): // CHECK: [[V1_UNWRAPPED:%.*]] = unchecked_enum_data [[V1]] // CHECK: [[CVT:%.*]] = convert_escape_to_noescape [[V1_UNWRAPPED]] // CHECK: [[SOME:%.*]] = enum $Optional<{{.*}}>, #Optional.some!enumelt, [[CVT]] // CHECK: strong_release [[V2]] // CHECK: br [[NEXT_BB:bb[0-9]+]]([[SOME]] : // // CHECK: [[NEXT_BB]]([[SOME_PHI:%.*]] : // CHECK: switch_enum [[SOME_PHI]] : $Optional<{{.*}}>, case #Optional.some!enumelt: [[SOME_BB_2:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB_2:bb[0-9]+]] // // CHECK: [[SOME_BB_2]]([[SOME_PHI_PAYLOAD:%.*]] : // CHECK: [[PAI:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[SOME_PHI_PAYLOAD]]) // CHECK: [[MDI:%.*]] = mark_dependence [[PAI]] // CHECK: strong_retain [[MDI]] // CHECK: [[BLOCK_SLOT:%.*]] = alloc_stack // CHECK: [[BLOCK_PROJ:%.*]] = project_block_storage [[BLOCK_SLOT]] // CHECK: store [[MDI]] to [[BLOCK_PROJ]] // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_SLOT]] // CHECK: release_value [[NONE]] // CHECK: [[SOME_2:%.*]] = enum $Optional<{{.*}}>, #Optional.some!enumelt, [[MDI]] // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK: [[BLOCK_SOME:%.*]] = enum $Optional<{{.*}}>, #Optional.some!enumelt, [[BLOCK_COPY]] // CHECK: br bb5([[BLOCK_SOME]] : ${{.*}}, [[SOME_2]] : // // CHECK: bb4: // CHECK: [[NONE_BLOCK:%.*]] = enum $Optional<{{.*}}>, #Optional.none!enumelt // CHECK: br bb5([[NONE_BLOCK]] : {{.*}}, [[NONE]] : // // CHECK: bb5([[BLOCK_PHI:%.*]] : $Optional<{{.*}}>, [[SWIFT_CLOSURE_PHI:%.*]] : // CHECK: [[F:%.*]] = function_ref @noescapeBlock // CHECK: apply [[F]]([[BLOCK_PHI]]) // CHECK: release_value [[BLOCK_PHI]] // CHECK: release_value [[SWIFT_CLOSURE_PHI]] // CHECK-NEXT: return // NOPEEPHOLE-LABEL: sil @$s1A19bridgeNoescapeBlockyyF : $@convention(thin) () -> () { // NOPEEPHOLE: bb0: // NOPEEPHOLE: [[NONE_1:%.*]] = enum $Optional<{{.*}}>, #Optional.none!enumelt // NOPEEPHOLE: [[NONE_2:%.*]] = enum $Optional<{{.*}}>, #Optional.none!enumelt // NOPEEPHOLE: [[V0:%.*]] = function_ref @_returnOptionalEscape // NOPEEPHOLE: [[V1:%.*]] = apply [[V0]] // NOPEEPHOLE: switch_enum [[V1]] : $Optional<{{.*}}>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // NOPEEPHOLE: [[SOME_BB]]([[V2:%.*]]: $@callee_guaranteed () -> ()): // NOPEEPHOLE-NEXT: release_value [[NONE_2]] // NOPEEPHOLE-NEXT: [[CVT:%.*]] = convert_escape_to_noescape [[V2]] // NOPEEPHOLE-NEXT: [[SOME:%.*]] = enum $Optional<{{.*}}>, #Optional.some!enumelt, [[V2]] // NOPEEPHOLE-NEXT: [[NOESCAPE_SOME:%.*]] = enum $Optional<{{.*}}>, #Optional.some!enumelt, [[CVT]] // NOPEEPHOLE-NEXT: br bb2([[NOESCAPE_SOME]] : $Optional<{{.*}}>, [[SOME]] : // // NOPEEPHOLE: bb2([[NOESCAPE_SOME:%.*]] : $Optional<{{.*}}>, [[SOME:%.*]] : // NOPEEPHOLE: switch_enum [[NOESCAPE_SOME]] : $Optional<{{.*}}>, case #Optional.some!enumelt: [[SOME_BB_2:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB_2:bb[0-9]+]] // // NOPEEPHOLE: [[SOME_BB_2]]( // NOPEEPHOLE: br bb5 // // NOPEEPHOLE: [[NONE_BB_2]]: // NOPEEPHOLE: br bb5 // // NOPEEPHOLE: bb5([[BLOCK_PHI:%.*]] : $Optional<{{.*}}>, [[SWIFT_CLOSURE_PHI:%.*]] : // NOPEEPHOLE-NEXT: function_ref noescapeBlock // NOPEEPHOLE-NEXT: [[F:%.*]] = function_ref @noescapeBlock : // NOPEEPHOLE-NEXT: apply [[F]]([[BLOCK_PHI]]) // NOPEEPHOLE-NEXT: release_value [[BLOCK_PHI]] // NOPEEPHOLE-NEXT: tuple // NOPEEPHOLE-NEXT: release_value [[SOME]] // NOPEEPHOLE-NEXT: release_value [[SWIFT_CLOSURE_PHI]] // NOPEEPHOLE-NEXT: return // NOPEEPHOLE: } // end sil function '$s1A19bridgeNoescapeBlockyyF' public func bridgeNoescapeBlock() { noescapeBlock(returnOptionalEscape()) }
apache-2.0
cad639ac932a018db166541e583f5ab0
48.696
283
0.620895
3.095167
false
false
false
false
steven851007/ShoppingCart
ShoppingCart/ShoppingCart/GoodsTableViewController.swift
1
4058
// // GoodsTableViewController.swift // ShoppingCart // // Created by Istvan Balogh on 2017. 08. 10.. // Copyright © 2017. Balogh István. All rights reserved. // import UIKit class GoodsTableViewController: UITableViewController { var goodDetailViewController: GoodDetailViewController? = nil var goods = [Good]() let shoppingCart = ShoppingCart() private var selectedCurrency = Currencies.selectedCurrency override func viewDidLoad() { super.viewDidLoad() self.title = "Goods" // This should be set from outside, but for simplicity I just create it here. goods = [Good(name: "Peas", price: NSDecimalNumber(decimal: 0.95), unit: .bag), Good(name: "Eggs", price: NSDecimalNumber(decimal: 2.1), unit: .dozen), Good(name: "Milk", price: NSDecimalNumber(decimal: 1.30), unit: .bottle), Good(name: "Beans", price: NSDecimalNumber(decimal: 0.73), unit: .can) ] navigationItem.leftBarButtonItem = editButtonItem let addButton = UIBarButtonItem(image: UIImage(named: "ShoppingBag"), style: .plain, target: self, action: #selector(showShoppingCart(_:))) navigationItem.rightBarButtonItem = addButton if let split = splitViewController { let controllers = split.viewControllers goodDetailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? GoodDetailViewController } } private func updateView() { self.tableView.reloadRows(at: self.tableView.indexPathsForVisibleRows ?? [], with: .automatic) } override func viewWillAppear(_ animated: Bool) { clearsSelectionOnViewWillAppear = splitViewController!.isCollapsed super.viewWillAppear(animated) if self.selectedCurrency != Currencies.selectedCurrency { self.selectedCurrency = Currencies.selectedCurrency self.updateView() } } func showShoppingCart(_ sender: Any) { self.performSegue(withIdentifier: "shoppingCart", sender: sender) } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { if let indexPath = tableView.indexPathForSelectedRow { let good = self.goods[indexPath.row] let controller = (segue.destination as! UINavigationController).topViewController as! GoodDetailViewController controller.goodViewModel = GoodDetailsViewModel(good: good) controller.shoppingCart = self.shoppingCart controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem controller.navigationItem.leftItemsSupplementBackButton = true } } else if segue.identifier == "shoppingCart" { let controller = segue.destination as! ShoppingCartTableViewController controller.shoppingCart = self.shoppingCart } } // MARK: - Table View override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.goods.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let good = GoodCellViewModel(good: self.goods[indexPath.row]) cell.textLabel?.text = good.name cell.detailTextLabel?.text = good.pricePerUnit return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { goods.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } } }
mit
88df526d6293ae0930a6a6610fde210a
38.764706
147
0.66716
5.295039
false
false
false
false
bangslosan/CVCalendar
CVCalendar Demo/CVCalendar Demo/ViewController.swift
2
4663
// // ViewController.swift // CVCalendar Demo // // Created by Мак-ПК on 1/3/15. // Copyright (c) 2015 GameApp. All rights reserved. // import UIKit class ViewController: UIViewController, CVCalendarViewDelegate { @IBOutlet weak var calendarView: CVCalendarView! @IBOutlet weak var menuView: CVCalendarMenuView! @IBOutlet weak var monthLabel: UILabel! @IBOutlet weak var daysOutSwitch: UISwitch! var shouldShowDaysOut = true var animationFinished = true override func viewDidLoad() { super.viewDidLoad() self.monthLabel.text = CVDate(date: NSDate()).description() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.calendarView.commitCalendarViewUpdate() self.menuView.commitMenuViewUpdate() } // MARK: - IB Actions @IBAction func switchChanged(sender: UISwitch) { if sender.on { self.calendarView!.changeDaysOutShowingState(false) self.shouldShowDaysOut = true } else { self.calendarView!.changeDaysOutShowingState(true) self.shouldShowDaysOut = false } } @IBAction func todayMonthView() { self.calendarView.toggleTodayMonthView() } // MARK: Calendar View Delegate func shouldShowWeekdaysOut() -> Bool { return self.shouldShowDaysOut } func didSelectDayView(dayView: CVCalendarDayView) { // TODO: } func dotMarker(colorOnDayView dayView: CVCalendarDayView) -> UIColor { if dayView.date?.day == 3 { return .redColor() } else if dayView.date?.day == 5 { return .blackColor() } else if dayView.date?.day == 2 { return .blueColor() } return .greenColor() } func dotMarker(shouldShowOnDayView dayView: CVCalendarDayView) -> Bool { if dayView.date?.day == 3 || dayView.date?.day == 5 || dayView.date?.day == 2 { return true } else { return false } } func dotMarker(shouldMoveOnHighlightingOnDayView dayView: CVCalendarDayView) -> Bool { return false } func topMarker(shouldDisplayOnDayView dayView: CVCalendarDayView) -> Bool { return true } func presentedDateUpdated(date: CVDate) { if self.monthLabel.text != date.description() && self.animationFinished { let updatedMonthLabel = UILabel() updatedMonthLabel.textColor = monthLabel.textColor updatedMonthLabel.font = monthLabel.font updatedMonthLabel.textAlignment = .Center updatedMonthLabel.text = date.description updatedMonthLabel.sizeToFit() updatedMonthLabel.alpha = 0 updatedMonthLabel.center = self.monthLabel.center let offset = CGFloat(48) updatedMonthLabel.transform = CGAffineTransformMakeTranslation(0, offset) updatedMonthLabel.transform = CGAffineTransformMakeScale(1, 0.1) UIView.animateWithDuration(0.35, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in self.animationFinished = false self.monthLabel.transform = CGAffineTransformMakeTranslation(0, -offset) self.monthLabel.transform = CGAffineTransformMakeScale(1, 0.1) self.monthLabel.alpha = 0 updatedMonthLabel.alpha = 1 updatedMonthLabel.transform = CGAffineTransformIdentity }) { (finished) -> Void in self.animationFinished = true self.monthLabel.frame = updatedMonthLabel.frame self.monthLabel.text = updatedMonthLabel.text self.monthLabel.transform = CGAffineTransformIdentity self.monthLabel.alpha = 1 updatedMonthLabel.removeFromSuperview() } self.view.insertSubview(updatedMonthLabel, aboveSubview: self.monthLabel) } } func toggleMonthViewWithMonthOffset(offset: Int) { let calendar = NSCalendar.currentCalendar() let calendarManager = CVCalendarManager.sharedManager let components = calendarManager.componentsForDate(NSDate()) // from today components.month += offset let resultDate = calendar.dateFromComponents(components)! self.calendarView.toggleMonthViewWithDate(resultDate) } }
mit
a302d3dae3a730a819282fbb9728fc5e
33.257353
127
0.613568
5.646061
false
false
false
false
JohnCoates/Aerial
Aerial/Source/Models/Cache/VideoDownload.swift
1
10921
// // VideoDownload.swift // Aerial // // Created by John Coates on 10/31/15. // Copyright © 2015 John Coates. All rights reserved. // import Foundation protocol VideoDownloadDelegate: NSObjectProtocol { func videoDownload(_ videoDownload: VideoDownload, finished success: Bool, errorMessage: String?) // bytes received for bytes/second count func videoDownload(_ videoDownload: VideoDownload, receivedBytes: Int, progress: Float) } final class VideoDownloadStream { var connection: NSURLConnection var response: URLResponse? var contentInformationRequest: Bool = false var downloadOffset = 0 init(connection: NSURLConnection) { self.connection = connection } deinit { connection.cancel() } } final class VideoDownload: NSObject, NSURLConnectionDataDelegate { var streams: [VideoDownloadStream] = [] weak var delegate: VideoDownloadDelegate! let queue = DispatchQueue.main let video: AerialVideo var data: NSMutableData? var downloadedData: Int = 0 var contentLength: Int = 0 init(video: AerialVideo, delegate: VideoDownloadDelegate) { self.video = video self.delegate = delegate } deinit { print("deinit VideoDownload") } func startDownload() { // first start content information download startDownloadForContentInformation() } // download a couple bytes to get the content length func startDownloadForContentInformation() { startDownloadForChunk(nil) } func cancel() { for stream in streams { stream.connection.cancel() } infoLog("Video download cancelled") delegate.videoDownload(self, finished: false, errorMessage: nil) } func startDownloadForChunk(_ chunk: NSRange?) { let request = NSMutableURLRequest(url: video.url as URL) request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData if let requestedRange = chunk { // set Range: bytes=startOffset-endOffset let requestRangeField = "bytes=\(requestedRange.location)-\(requestedRange.location+requestedRange.length)" request.setValue(requestRangeField, forHTTPHeaderField: "Range") debugLog("Starting download for range \(requestRangeField)") } guard let connection = NSURLConnection(request: request as URLRequest, delegate: self, startImmediately: false) else { errorLog("Error creating connection with request: \(request)") return } let stream = VideoDownloadStream(connection: connection) if chunk == nil { debugLog("Starting download for content information") stream.contentInformationRequest = true } connection.start() streams.append(stream) } func streamForConnection(_ connection: NSURLConnection) -> VideoDownloadStream? { return streams.first(where: { $0.connection == connection }) } func createStreamsBasedOnContentLength(_ contentLength: Int) { self.contentLength = contentLength // remove content length request stream streams.removeFirst() data = NSMutableData(length: contentLength) // start 4 streams for maximum throughput let streamCount = 1 // TODO let pace = 0.2; // pace stream creation a little bit let streamPiece = Int(floor(Double(contentLength) / Double(streamCount))) debugLog("Starting \(streamCount) streams with \(streamPiece) each, for content length of \(contentLength)") var offset = 0 var delayTime: Double = 0 // let queue = DispatchQueue.main for idx in 0 ..< streamCount { let isLastStream: Bool = idx == (streamCount - 1) var range = NSRange(location: offset, length: streamPiece) if isLastStream { let bytesLeft = contentLength - offset range = NSRange(location: offset, length: bytesLeft) debugLog("last stream range: \(range)") } let delay = DispatchTime.now() + Double(Int64(delayTime * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) queue.asyncAfter(deadline: delay) { self.startDownloadForChunk(range) } // increase delay delayTime += pace // increase offset offset += range.length } } func receiveDataForStream(_ stream: VideoDownloadStream, receivedData: Data) { guard let videoData = self.data else { errorLog("Aerial error: video data missing!") return } let replaceRange = NSRange(location: stream.downloadOffset, length: receivedData.count) videoData.replaceBytes(in: replaceRange, withBytes: (receivedData as NSData).bytes) stream.downloadOffset += receivedData.count } func finishedDownload() { var tentativeCachePath: String? if video.source.isCachable { tentativeCachePath = VideoCache.cachePath(forVideo: video) } else { tentativeCachePath = VideoCache.sourcePathFor(video) } guard let videoCachePath = tentativeCachePath else { errorLog("Couldn't save video because couldn't get cache path\n") failedDownload("Couldn't get cache path") return } if self.data == nil { errorLog("video data missing!\n") return } var success: Bool = true var errorMessage: String? do { try self.data!.write(toFile: videoCachePath, options: .atomicWrite) self.data = nil } catch let error { errorLog("Couldn't write cache file: \(error)") errorMessage = "Couldn't write to cache file!" success = false } // notify delegate delegate.videoDownload(self, finished: success, errorMessage: errorMessage) } func failedDownload(_ errorMessage: String) { delegate.videoDownload(self, finished: false, errorMessage: errorMessage) } // MARK: - NSURLConnection Delegate func connection(_ connection: NSURLConnection, didReceive response: URLResponse) { guard let stream = streamForConnection(connection) else { errorLog("No matching stream for connection: \(connection) with response: \(response)") return } stream.response = response as? HTTPURLResponse if stream.contentInformationRequest == true { connection.cancel() queue.async(execute: { () -> Void in let contentLength = Int(response.expectedContentLength) self.createStreamsBasedOnContentLength(contentLength) }) return } else { // get real offset of receiving data queue.async(execute: { () -> Void in guard let offset = self.startOffsetFromResponse(response) else { errorLog("Couldn't get start offset from response: \(response)") return } stream.downloadOffset = offset }) } } func connection(_ connection: NSURLConnection, didReceive data: Data) { guard let delegate = self.delegate else { return } queue.async { () -> Void in self.downloadedData += data.count let progress: Float = Float(self.downloadedData) / Float(self.contentLength) delegate.videoDownload(self, receivedBytes: data.count, progress: progress) guard let stream = self.streamForConnection(connection) else { errorLog("No matching stream for connection: \(connection)") return } self.receiveDataForStream(stream, receivedData: data) } } func connectionDidFinishLoading(_ connection: NSURLConnection) { queue.async { () -> Void in debugLog("connectionDidFinishLoading") guard let stream = self.streamForConnection(connection) else { errorLog("No matching stream for connection: \(connection)") return } guard let index = self.streams.firstIndex(where: { $0.connection == stream.connection }) else { errorLog("Couldn't find index of stream for finished connection!") return } self.streams.remove(at: index) if self.streams.isEmpty { debugLog("Finished downloading!") self.finishedDownload() } } } func connection(_ connection: NSURLConnection, didFailWithError error: Error) { errorLog("Couldn't download video: \(error.localizedDescription)") queue.async { () -> Void in self.failedDownload("Connection fail: \(error.localizedDescription)") } } func connection(_ connection: NSURLConnection, didReceive challenge: URLAuthenticationChallenge) { errorLog("Didn't expect authentication challenge while downloading videos!") queue.async { () -> Void in self.failedDownload("Connection fail: Received authentication request!") } } // MARK: - Range func startOffsetFromResponse(_ response: URLResponse) -> Int? { // get range response var regex: NSRegularExpression! do { // Check to see if the server returned a valid byte-range regex = try NSRegularExpression(pattern: "bytes (\\d+)-\\d+/\\d+", options: NSRegularExpression.Options.caseInsensitive) } catch let error as NSError { errorLog("Error formatting regex: \(error)") return nil } let httpResponse = response as! HTTPURLResponse guard let contentRange = httpResponse.allHeaderFields["Content-Range"] as? NSString else { errorLog("Weird, no byte response: \(response)") return nil } guard let match = regex.firstMatch(in: contentRange as String, options: NSRegularExpression.MatchingOptions.anchored, range: NSRange(location: 0, length: contentRange.length)) else { errorLog("Weird, couldn't make a regex match for byte offset: \(contentRange)") return nil } let offsetMatchRange = match.range(at: 1) let offsetString = contentRange.substring(with: offsetMatchRange) as NSString let offset = offsetString.longLongValue return Int(offset) } }
mit
e8bdee155d3d34a86fd86ef42436737b
33.018692
119
0.607692
5.408618
false
false
false
false
Coledunsby/TwitterClient
TwitterClient/TweetsViewModel.swift
1
2786
// // TweetsViewModel.swift // TwitterClient // // Created by Cole Dunsby on 2017-06-06. // Copyright © 2017 Cole Dunsby. All rights reserved. // import RxSwift protocol TweetsViewModelInputs { var loadNewer: PublishSubject<Void> { get } var logout: PublishSubject<Void> { get } var compose: PublishSubject<Void> { get } } protocol TweetsViewModelOutputs { var tweets: Observable<TweetChangeset> { get } var composeViewModel: Observable<ComposeViewModel> { get } var isLoading: Observable<Bool> { get } var loggedOut: Observable<Void> { get } var errors: Observable<Error> { get } } protocol TweetsViewModelIO { var inputs: TweetsViewModelInputs { get } var outputs: TweetsViewModelOutputs { get } } struct TweetsViewModel: TweetsViewModelIO, TweetsViewModelInputs, TweetsViewModelOutputs { // MARK: - Inputs var inputs: TweetsViewModelInputs { return self } let loadNewer = PublishSubject<Void>() let logout = PublishSubject<Void>() let compose = PublishSubject<Void>() // MARK: - Outputs var outputs: TweetsViewModelOutputs { return self } let tweets: Observable<TweetChangeset> let composeViewModel: Observable<ComposeViewModel> let isLoading: Observable<Bool> let loggedOut: Observable<Void> let errors: Observable<Error> // MARK: - Init init<T>(loginProvider: AnyLoginProvider<T>, tweetProvider: TweetProviding) { let isLoadingSubject = PublishSubject<Bool>() let loadNewer = self.loadNewer .startWith(()) .flatMapLatest { tweetProvider.fetcher .fetch() .do(onNext: { Cache.shared.addTweets($0) }, onSubscribe: { isLoadingSubject.onNext(true) }, onDispose: { isLoadingSubject.onNext(false) }) .mapTo(()) .asObservable() .materialize() } .share() let logout = self.logout .flatMapLatest { loginProvider .logout() .asSingle() .do(onNext: { Cache.shared.invalidateCurrentUser() }) .asObservable() .materialize() } .share() tweets = Cache.shared.tweets isLoading = isLoadingSubject loggedOut = logout.elements() errors = Observable.merge([loadNewer.errors(), logout.errors()]) composeViewModel = compose.mapTo(ComposeViewModel(provider: tweetProvider)) } }
mit
99de1fd74d2028c8293db6a2c260041b
27.71134
90
0.566607
5.138376
false
false
false
false
modocache/Gift
Gift/Status/StatusDelta/Options/StatusDeltaOptions.swift
1
1134
/** Options for enumerating status deltas. */ public struct StatusDeltaOptions { /** Indicates what should be compared when enumerating file status deltas. */ public let between: StatusDeltaBetween /** A set of options to customize the behavior of status delta enumeration. */ public let behavior: StatusDeltaBehavior /** A list of path or path patterns to files that should be included in the status delta enumeration. If none are provided, all files in the repository (excluding those specifically excluded by the `behavior` options) are enumerated. */ public let path: [String] public init( between: StatusDeltaBetween = StatusDeltaBetween.All, behavior: StatusDeltaBehavior = StatusDeltaBehavior.IncludeIgnored | StatusDeltaBehavior.IncludeUntracked | StatusDeltaBehavior.RecurseUntrackedDirectories | StatusDeltaBehavior.DetectRenamesBetweenHeadAndIndex | StatusDeltaBehavior.DetectRenamesBetweenIndexAndWorkingDirectory | StatusDeltaBehavior.DetectRenamesAmongRewrittenFiles, path: [String] = [] ) { self.between = between self.behavior = behavior self.path = path } }
mit
47f8514eef1952780bb39e34d4b0ac57
44.36
337
0.775132
4.805085
false
false
false
false
Sadmansamee/quran-ios
Quran/Files.swift
1
1885
// // Files.swift // Quran // // Created by Mohamed Afifi on 4/30/16. // Copyright © 2016 Quran.com. All rights reserved. // import Foundation struct Files { static let audioExtension = "mp3" static let downloadResumeDataExtension = "resume" static let databaseRemoteFileExtension = "zip" static let databaseLocalFileExtension = "db" static let quarterPrefixArray = fileURL("quarter_prefix_array", withExtension: "plist") static let readers = fileURL("readers", withExtension: "plist") static let ayahInfoPath: String = filePath("images_\(quranImagesSize)/databases/ayahinfo_\(quranImagesSize)", ofType: "db") static let quranTextPath = filePath("images_\(quranImagesSize)/databases/quran.ar", ofType: "db") } private func fileURL(_ fileName: String, withExtension `extension`: String) -> URL { guard let url = Bundle.main.url(forResource: fileName, withExtension: `extension`) else { fatalError("Couldn't find file `\(fileName).\(`extension`)` locally ") } return url } private func filePath(_ fileName: String, ofType type: String) -> String { guard let path = Bundle.main.path(forResource: fileName, ofType: type) else { fatalError("Couldn't find file `\(fileName).\(type)` locally ") } return path } extension Qari { func localFolder() -> URL { return FileManager.default.documentsURL.appendingPathComponent(path) } } extension URL { func resumeURL() -> URL { return appendingPathExtension(Files.downloadResumeDataExtension) } } extension String { func stringByAppendingPath(_ path: String) -> String { return (self as NSString).appendingPathComponent(path) } func stringByAppendingExtension(_ pathExtension: String) -> String { return (self as NSString).appendingPathExtension(pathExtension) ?? (self + "." + pathExtension) } }
mit
451f966037eedf52bfc0073557f726e2
30.932203
127
0.694798
4.351039
false
false
false
false
Webtrekk/webtrekk-ios-sdk
Source/Public/Utility/Logger.swift
1
2567
import Foundation import os.log public final class DefaultTrackingLogger: TrackingLogger { /** Enable or disable logging completly */ public var enabled = true /** In test mode logging is always done independed on level with .info type to print all in console*/ public var testMode = false /** Filter the amount of log output by setting different `TrackingLogLevel` */ public var minimumLevel = TrackingLogLevel.warning /** Attach a message to the log output with a spezific `TackingLogLevel` */ public func log(message: @autoclosure () -> String, level: TrackingLogLevel) { guard enabled && (level.rawValue >= minimumLevel.rawValue || testMode) else { return } if #available(iOS 10.0, *), #available(watchOSApplicationExtension 3.0, *), #available(tvOS 10.0, *) { let logType = testMode ? .info : level.type! os_log("%@", dso: #dsohandle, log: OSLog.default, type: logType, "[Webtrekk] [\(level.title)] \(message())") } else { NSLog("%@", "[Webtrekk] [\(level.title)] \(message())") } } } public enum TrackingLogLevel: Int { case debug = 1 case info = 2 case warning = 3 case error = 4 case fault = 5 fileprivate var title: String { switch self { case .debug: return "Debug" case .info: return "Info" case .warning: return "Warning" case .error: return "ERROR" case .fault: return "FAULT" } } fileprivate var type: OSLogType? { guard #available(iOS 10.0, *), #available(watchOSApplicationExtension 3.0, *), #available(tvOS 10.0, *) else { return nil } switch self { case .debug: return .debug case .info: return .info case .warning: return .info case .error: return .error case .fault: return .fault } } } public protocol TrackingLogger: class { func log (message: @autoclosure () -> String, level: TrackingLogLevel) } public extension TrackingLogger { func logDebug(_ message: @autoclosure () -> String) { log(message: message(), level: .debug) } func logError(_ message: @autoclosure () -> String) { log(message: message(), level: .error) } func logInfo(_ message: @autoclosure () -> String) { log(message: message(), level: .info) } func logWarning(_ message: @autoclosure () -> String) { log(message: message(), level: .warning) } }
mit
d1cc272d1ba79ae77a43f35becab70b6
28.505747
120
0.59252
4.292642
false
false
false
false
yarec/FeedParser
FeedParserTests/FeedParserTests.swift
1
2412
// // FeedParserTests.swift // FeedParserTests // // Created by Andreas Geitmann on 18.11.14. // Copyright (c) 2014 simutron IT-Service. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* import Foundation import XCTest import FeedParser class FeedParserTests: 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 testAtomFeedParsingFromFile() { let urlString = "./atom.xml" var feedParserDelegate = TestAtomFeedParserDelegate() var feedParser = FeedParser() feedParser.delegate = feedParserDelegate feedParser.parseFeedFromUrl(urlString) } func testSimpleRssFeedParsingFromFile() { let urlString = "./sample-feed.xml.rss" var feedParserDelegate = TestSimpleRSSFeedParserDelegate() var feedParser = FeedParser() feedParser.delegate = feedParserDelegate feedParser.parseFeedFromUrl(urlString) } func testSampleRssFeedParsingFromFile() { let urlString = "./sample.xml.rss" var feedParserDelegate = TestSimpleRSSFeedParserDelegate() var feedParser = FeedParser() feedParser.delegate = feedParserDelegate feedParser.parseFeedFromUrl(urlString) } func testRssFeedParsingFromFile() { let urlString = "http://www.ifanr.com/feed" var feedParserDelegate = TestRSSFeedParserDelegate() var feedParser = FeedParser() feedParser.delegate = feedParserDelegate feedParser.parseFeedFromUrl(urlString) } } */
apache-2.0
6616d77fe0a2aa54c145267cf06409ea
30.324675
111
0.677032
4.892495
false
true
false
false
emodeqidao/TextFieldEffects
TextFieldEffects/TextFieldEffects/IsaoTextField.swift
11
5319
// // IsaoTextField.swift // TextFieldEffects // // Created by Raúl Riera on 29/01/2015. // Copyright (c) 2015 Raul Riera. All rights reserved. // import UIKit @IBDesignable public class IsaoTextField: TextFieldEffects { @IBInspectable public var inactiveColor: UIColor? { didSet { updateBorder() } } @IBInspectable public var activeColor: UIColor? { didSet { updateBorder() } } override public var placeholder: String? { didSet { updatePlaceholder() } } override public var bounds: CGRect { didSet { updateBorder() updatePlaceholder() } } private let borderThickness: (active: CGFloat, inactive: CGFloat) = (4, 2) private let placeholderInsets = CGPoint(x: 6, y: 6) private let textFieldInsets = CGPoint(x: 6, y: 6) private let borderLayer = CALayer() // MARK: - TextFieldsEffectsProtocol override func drawViewsForRect(rect: CGRect) { let frame = CGRect(origin: CGPointZero, size: CGSize(width: rect.size.width, height: rect.size.height)) placeholderLabel.frame = CGRectInset(frame, placeholderInsets.x, placeholderInsets.y) placeholderLabel.font = placeholderFontFromFont(font) updateBorder() updatePlaceholder() layer.addSublayer(borderLayer) addSubview(placeholderLabel) } private func updateBorder() { borderLayer.frame = rectForBorder(frame) borderLayer.backgroundColor = isFirstResponder() ? activeColor?.CGColor : inactiveColor?.CGColor } private func updatePlaceholder() { placeholderLabel.text = placeholder placeholderLabel.textColor = inactiveColor placeholderLabel.sizeToFit() layoutPlaceholderInTextRect() if isFirstResponder() { animateViewsForTextEntry() } } private func placeholderFontFromFont(font: UIFont) -> UIFont! { let smallerFont = UIFont(name: font.fontName, size: font.pointSize * 0.7) return smallerFont } private func rectForBorder(bounds: CGRect) -> CGRect { var newRect:CGRect if isFirstResponder() { newRect = CGRect(x: 0, y: bounds.size.height - font.lineHeight + textFieldInsets.y - borderThickness.active, width: bounds.size.width, height: borderThickness.active) } else { newRect = CGRect(x: 0, y: bounds.size.height - font.lineHeight + textFieldInsets.y - borderThickness.inactive, width: bounds.size.width, height: borderThickness.inactive) } return newRect } private func layoutPlaceholderInTextRect() { if !text.isEmpty { return } let textRect = textRectForBounds(bounds) var originX = textRect.origin.x switch textAlignment { case .Center: originX += textRect.size.width/2 - placeholderLabel.bounds.width/2 case .Right: originX += textRect.size.width - placeholderLabel.bounds.width default: break } placeholderLabel.frame = CGRect(x: originX, y: bounds.height - placeholderLabel.frame.height, width: placeholderLabel.frame.size.width, height: placeholderLabel.frame.size.height) } override func animateViewsForTextEntry() { updateBorder() if let activeColor = activeColor { performPlacerholderAnimationWithColor(activeColor) } } override func animateViewsForTextDisplay() { updateBorder() if let inactiveColor = inactiveColor { performPlacerholderAnimationWithColor(inactiveColor) } } private func performPlacerholderAnimationWithColor(color: UIColor) { let yOffset:CGFloat = 4 UIView.animateWithDuration(0.15, animations: { () -> Void in self.placeholderLabel.transform = CGAffineTransformMakeTranslation(0, -yOffset) self.placeholderLabel.alpha = 0 }) { (completed) -> Void in self.placeholderLabel.transform = CGAffineTransformIdentity self.placeholderLabel.transform = CGAffineTransformMakeTranslation(0, yOffset) UIView.animateWithDuration(0.15, animations: { self.placeholderLabel.textColor = color self.placeholderLabel.transform = CGAffineTransformIdentity self.placeholderLabel.alpha = 1 }) } } // MARK: - Overrides override public func editingRectForBounds(bounds: CGRect) -> CGRect { let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font.lineHeight + textFieldInsets.y) return CGRectInset(newBounds, textFieldInsets.x, 0) } override public func textRectForBounds(bounds: CGRect) -> CGRect { let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font.lineHeight + textFieldInsets.y) return CGRectInset(newBounds, textFieldInsets.x, 0) } }
mit
6e165a4e5954a70a73d3f57f402ec3b1
32.872611
182
0.618654
5.382591
false
false
false
false
Nike-Inc/Elevate
Tests/PropertyExtractionTests.swift
1
5937
// // PropertyExtractionTests.swift // // Copyright (c) 2015-present Nike, Inc. (https://www.nike.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Elevate import Foundation import XCTest class PropertyExtractionTestCase: BaseTestCase { // MARK: - Properties let properties: [String: Any] = [ "string": "string_value", "int": Int(-10), "uint": UInt(45), "float": Float(12.34), "double": Double(1234.5678), "bool": true, "array": ["value_0", "value_1"], "array_of_any_values": ["value_0" as Any, "value_1" as Any], "dictionary": ["key": "value"], "url": URL(string: "https://httpbin.org/get")! ] // MARK: - Tests - Operators func testValueForKeyPathOperator() { // Given, When let stringValue: String = properties <-! "string" let intValue: Int = properties <-! "int" let uintValue: UInt = properties <-! "uint" let floatValue: Float = properties <-! "float" let doubleValue: Double = properties <-! "double" let boolValue: Bool = properties <-! "bool" let arrayValue: [String] = properties <-! "array" let dictionaryValue: [String: String] = properties <-! "dictionary" let urlValue: URL = properties <-! "url" // Then XCTAssertEqual(stringValue, "string_value") XCTAssertEqual(intValue, -10) XCTAssertEqual(uintValue, 45) XCTAssertEqual(floatValue, 12.34) XCTAssertEqual(doubleValue, 1234.5678) XCTAssertEqual(boolValue, true) XCTAssertEqual(arrayValue, ["value_0", "value_1"]) XCTAssertEqual(dictionaryValue, ["key": "value"]) XCTAssertEqual(urlValue, URL(string: "https://httpbin.org/get")!) } func testOptionalValueForKeyPathOperator() { // Given, When let stringValue: String? = properties <-? "string" let stringNilValue: String? = properties <-? "string_nil" let intValue: Int? = properties <-? "int" let intNilValue: Int? = properties <-? "int_nil" let uintValue: UInt? = properties <-? "uint" let uintNilValue: UInt? = properties <-? "uint_nil" let floatValue: Float? = properties <-? "float" let floatNilValue: Float? = properties <-? "float_nil" let doubleValue: Double? = properties <-? "double" let doubleNilValue: Double? = properties <-? "double_nil" let boolValue: Bool? = properties <-? "bool" let boolNilValue: Bool? = properties <-? "bool_nil" let arrayValue: [String]? = properties <-? "array" let arrayNilValue: [String]? = properties <-? "array_nil" let dictionaryValue: [String: String]? = properties <-? "dictionary" let dictionaryNilValue: [String: String]? = properties <-? "dictionary_nil" let urlValue: URL? = properties <-? "url" let urlNilValue: URL? = properties <-? "url_nil" // Then XCTAssertEqual(stringValue, "string_value") XCTAssertNil(stringNilValue) XCTAssertEqual(intValue, -10) XCTAssertNil(intNilValue) XCTAssertEqual(uintValue, 45) XCTAssertNil(uintNilValue) XCTAssertEqual(floatValue, 12.34) XCTAssertNil(floatNilValue) XCTAssertEqual(doubleValue, 1234.5678) XCTAssertNil(doubleNilValue) XCTAssertEqual(boolValue, true) XCTAssertNil(boolNilValue) XCTAssertEqual(arrayValue ?? [], ["value_0", "value_1"]) XCTAssertNil(arrayNilValue) XCTAssertEqual(dictionaryValue ?? [:], ["key": "value"]) XCTAssertNil(dictionaryNilValue) XCTAssertEqual(urlValue, URL(string: "https://httpbin.org/get")!) XCTAssertNil(urlNilValue) } func testArrayForKeyPathOperator() { // Given, When let anyArray: [String] = properties <--! "array_of_any_values" // Then XCTAssertEqual(anyArray, ["value_0", "value_1"]) } func testOptionalArrayForKeyPathOperator() { // Given, When let stringsArray: [String]? = properties <--? "array" let anyArray: [String]? = properties <--? "array_of_any_values" let missingKey: [String]? = properties <--? "key_does_not_exist" // Then XCTAssertEqual(stringsArray ?? [], ["value_0", "value_1"]) XCTAssertEqual(anyArray ?? [], ["value_0", "value_1"]) XCTAssertNil(missingKey) } func testExtractionPrecedence() { // Given, When let string: String = properties <-? "nope" ?? "default string" let stringsArray: [String] = properties <--? "nope" ?? ["default", "value"] // Then XCTAssertEqual(string, "default string") XCTAssertEqual(stringsArray.count, 2) XCTAssertEqual(stringsArray[0], "default") XCTAssertEqual(stringsArray[1], "value") } }
mit
9afaa9c3244f2d7fea437c84ab15ecda
35.875776
83
0.630116
4.262024
false
true
false
false
RxSwiftCommunity/RxSwiftExt
Tests/RxCocoa/UIViewPropertyAnimatorTests+Rx.swift
2
1642
// // UIViewPropertyAnimatorTests+Rx.swift // RxSwiftExt // // Created by Thibault Wittemberg on 3/4/18. // Copyright © 2017 RxSwift Community. All rights reserved. // #if canImport(UIKit) import XCTest import RxSwift import RxCocoa import RxSwiftExt import RxTest import UIKit @available(iOS 10.0, *) class UIViewPropertyAnimatorTests: XCTestCase { var disposeBag: DisposeBag! override func setUp() { disposeBag = DisposeBag() } func testAnimationCompleted() { let expectations = expectation(description: "Animation completed") let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) let animator = UIViewPropertyAnimator(duration: 0.5, curve: .linear) { view.transform = CGAffineTransform(translationX: 100, y: 100) } animator .rx.animate() .subscribe(onCompleted: { XCTAssertEqual(100, view.frame.origin.x) XCTAssertEqual(100, view.frame.origin.y) expectations.fulfill() }) .disposed(by: disposeBag) waitForExpectations(timeout: 1) } func testBindToFractionCompleted() { let animator = UIViewPropertyAnimator( duration: 0, curve: .linear, animations: { } ) let subject = PublishSubject<CGFloat>() subject .bind(to: animator.rx.fractionComplete) .disposed(by: disposeBag) subject.onNext(0.3) XCTAssertEqual(animator.fractionComplete, 0.3) subject.onNext(0.5) XCTAssertEqual(animator.fractionComplete, 0.5) } } #endif
mit
00e7222a7de542b24fb126f316c9f048
25.047619
78
0.627666
4.49589
false
true
false
false
bilogub/Chirrup
ChirrupTests/ChirrupSpec.swift
1
10109
// // ChirrupSpec.swift // Chirrup // // Created by Yuriy Bilogub on 2016-01-25. // Copyright © 2016 Yuriy Bilogub. All rights reserved. // import Quick import Nimble import Chirrup class ChirrupSpec: QuickSpec { override func spec() { let chirrup = Chirrup() var fieldName = "" describe("Single validation rule") { describe(".isTrue") { beforeEach { fieldName = "Activate" } context("When `Activate` is switched Off") { it("should return an error") { let error = chirrup.validate(fieldName, value: false, with: ValidationRule(.IsTrue)) expect(error!.errorMessageFor(fieldName)) .to(equal("Activate should be true")) } context("When rule evaluation is skipped") { it("should not return an error") { let error = chirrup.validate(fieldName, value: false, with: ValidationRule(.IsTrue, on: { false })) expect(error).to(beNil()) } } } context("When `Activate` is switched On") { it("should not return an error") { let error = chirrup.validate(fieldName, value: true, with: ValidationRule(.IsTrue)) expect(error).to(beNil()) } } } describe(".NonEmpty") { beforeEach { fieldName = "Greeting" } context("When `Greeting` is empty") { it("should return an error") { let error = chirrup.validate(fieldName, value: "", with: ValidationRule(.NonEmpty)) expect(error!.errorMessageFor(fieldName)) .to(equal("Greeting should not be empty")) } } context("When `Greeting` is set to value") { it("should not return an error") { let error = chirrup.validate(fieldName, value: "hey there!", with: ValidationRule(.NonEmpty)) expect(error).to(beNil()) } } } describe(".Greater") { beforeEach { fieldName = "Min. Price" } context("When `Min. Price` is empty") { context("When rule evaluation is skipped") { it("should not return an error because validation is skipped") { let val = "" let error = chirrup.validate(fieldName, value: val, with: ValidationRule(.Greater(than: "5499.98"), on: { !val.isEmpty })) expect(error).to(beNil()) } } context("When rule evaluation is not skipped") { it("should return an error") { let error = chirrup.validate(fieldName, value: "", with: ValidationRule(.Greater(than: "5499.98"))) expect(error!.errorMessageFor(fieldName)) .to(equal("Min. Price should be a number")) } } } context("When `Min. Price` is set to a NaN value") { it("should return an error") { let error = chirrup.validate(fieldName, value: "two hundred", with: ValidationRule(.Greater(than: "5499.98"))) expect(error!.errorMessageFor(fieldName)) .to(equal("Min. Price should be a number")) } } context("When `Min. Price` is set to a equal value") { it("should return an error") { let val = "5499.98" let error = chirrup.validate(fieldName, value: val, with: ValidationRule(.Greater(than: val))) expect(error!.errorMessageFor(fieldName)) .to(equal("Min. Price should be greater than \(val)")) } } context("When `Min. Price` is set to a greater value") { it("should return an error") { let error = chirrup.validate(fieldName, value: "5499.99", with: ValidationRule(.Greater(than: "5499.98"))) expect(error).to(beNil()) } } } } describe(".Lower") { beforeEach { fieldName = "Max. Price" } context("When `Max. Price` is empty") { context("When rule evaluation is skipped") { it("should not return an error") { let val = "" let error = chirrup.validate(fieldName, value: val, with: ValidationRule(.Lower(than: "10000.00"), on: { !val.isEmpty })) expect(error).to(beNil()) } } context("When rule evaluation is not skipped") { it("should return an error") { let error = chirrup.validate(fieldName, value: "", with: ValidationRule(.Lower(than: "10000.00"))) expect(error!.errorMessageFor(fieldName)) .to(equal("Max. Price should be a number")) } } } context("When `Max. Price` is set to a NaN value") { it("should return an error") { let error = chirrup.validate(fieldName, value: "ten thousand", with: ValidationRule(.Lower(than: "10000.00"))) expect(error!.errorMessageFor(fieldName)) .to(equal("Max. Price should be a number")) } } context("When `Max. Price` is set to a equal value") { it("should return an error") { let val = "10000.00" let error = chirrup.validate(fieldName, value: val, with: ValidationRule(.Lower(than: val))) expect(error!.errorMessageFor(fieldName)) .to(equal("Max. Price should be lower than \(val)")) } } context("When `Max. Price` is set to a greater value") { it("should return an error") { let error = chirrup.validate(fieldName, value: "9999.99", with: ValidationRule(.Lower(than: "10000.00"))) expect(error).to(beNil()) } } } describe(".Between") { beforeEach { fieldName = "Gear Number" } context("When `Gear Number` is set to a lower value than possible") { it("should return an error") { let error = chirrup.validate(fieldName, value: "0", with: ValidationRule(.Between(from: "4", to: "6"))) expect(error!.errorMessageFor(fieldName)) .to(equal("Gear Number should be between 4 and 6")) } it("should not return an error") { let error = chirrup.validate(fieldName, value: "5", with: ValidationRule(.Between(from: "4", to: "6"))) expect(error).to(beNil()) } } } describe(".IsNumeric") { beforeEach { fieldName = "Gear Number" } context("When `Gear Number` is set to a NaN value") { it("should return an error") { let error = chirrup.validate(fieldName, value: "five", with: ValidationRule(.IsNumeric)) expect(error!.errorMessageFor(fieldName)) .to(equal("Gear Number should be a number")) } } context("When `Gear Number` is empty") { it("should return an error") { let error = chirrup.validate(fieldName, value: "", with: ValidationRule(.IsNumeric)) expect(error!.errorMessageFor(fieldName, should: "be a positive number")) .to(equal("Gear Number should be a positive number")) } } context("When `Gear Number` is a number") { it("should not return an error") { let error = chirrup.validate(fieldName, value: "5", with: ValidationRule(.IsNumeric)) expect(error).to(beNil()) } } } describe("Multiple validation rules") { describe(".Contains .NonBlank") { beforeEach { fieldName = "Greeting" } it("should return .Contains and .NonEmpty errors") { let errors = chirrup.validate(fieldName, value: "", with: [ValidationRule(.NonEmpty, message: "Couple greeting words here?"), ValidationRule(.Contains(value: "hey there!"))]) expect(chirrup.formatMessagesFor(fieldName, from: errors)) .to(equal("Couple greeting words here?\nGreeting should contain `hey there!`")) } context("When we have a greeting but not the one we expect") { it("should return .Contains error only") { let errors = chirrup.validate(fieldName, value: "hey!", with: [ValidationRule(.NonEmpty), ValidationRule(.Contains(value: "hey there!"))]) expect(chirrup.formatMessagesFor(fieldName, from: errors)) .to(equal("Greeting should contain `hey there!`")) } context("When rule evaluation is skipped") { it("should return empty error array") { let errors = chirrup.validate(fieldName, value: "hey!", with: [ValidationRule(.NonEmpty), ValidationRule(.Contains(value: "hey there!"), on: { 1 < 0 })]) expect(errors).to(beEmpty()) } } context("When rule evaluation is not skipped") { it("should return .Contains error only") { let errors = chirrup.validate(fieldName, value: "hey!", with: [ValidationRule(.NonEmpty), ValidationRule(.Contains(value: "hey there!"), on: { 1 > 0 })]) expect(chirrup.formatMessagesFor(fieldName, from: errors)) .to(equal("Greeting should contain `hey there!`")) } } } } } } }
mit
3c16ffcdca38e40f4db4ae04ad4d64bd
31.928339
91
0.510586
4.67963
false
false
false
false
linkedin/ConsistencyManager-iOS
SampleApp/ConsistencyManagerDemo/Models/StreamModel.swift
2
1376
// © 2016 LinkedIn Corp. All rights reserved. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import Foundation import ConsistencyManager final class StreamModel: ConsistencyManagerModel, Equatable { let id: String let updates: [UpdateModel] init(id: String, updates: [UpdateModel]) { self.id = id self.updates = updates } var modelIdentifier: String? { return id } func map(_ transform: (ConsistencyManagerModel) -> ConsistencyManagerModel?) -> ConsistencyManagerModel? { let newUpdates: [UpdateModel] = updates.compactMap { model in return transform(model) as? UpdateModel } return StreamModel(id: id, updates: newUpdates) } func forEach(_ function: (ConsistencyManagerModel) -> ()) { for model in updates { function(model) } } } func ==(lhs: StreamModel, rhs: StreamModel) -> Bool { return lhs.id == rhs.id && lhs.updates == rhs.updates }
apache-2.0
0e08131ef3613de6e7eed6fd429806f0
30.976744
110
0.673455
4.296875
false
false
false
false
XDislikeCode/Yepic
Yepic/Application/Support/TextFieldEffects/YokoTextField.swift
1
8144
// // YokoTextField.swift // TextFieldEffects // // Created by Raúl Riera on 30/01/2015. // Copyright (c) 2015 Raul Riera. All rights reserved. // import UIKit /** A YokoTextField is a subclass of the TextFieldEffects object, is a control that displays an UITextField with a customizable 3D visual effect on the background of the control. */ @IBDesignable open class YokoTextField: TextFieldEffects { /** The color of the placeholder text. This property applies a color to the complete placeholder string. The default value for this property is a black color. */ @IBInspectable dynamic open var placeholderColor: UIColor? { didSet { updatePlaceholder() } } /** The scale of the placeholder font. This property determines the size of the placeholder label relative to the font size of the text field. */ @IBInspectable dynamic open var placeholderFontScale: CGFloat = 0.7 { didSet { updatePlaceholder() } } /** The view’s foreground color. The default value for this property is a clear color. */ @IBInspectable dynamic open var foregroundColor: UIColor = .black { didSet { updateForeground() } } override open var placeholder: String? { didSet { updatePlaceholder() } } override open var bounds: CGRect { didSet { updateForeground() updatePlaceholder() } } private let foregroundView = UIView() private let foregroundLayer = CALayer() private let borderThickness: CGFloat = 3 private let placeholderInsets = CGPoint(x: 6, y: 6) private let textFieldInsets = CGPoint(x: 6, y: 6) // MARK: - TextFieldEffects override open func drawViewsForRect(_ rect: CGRect) { updateForeground() updatePlaceholder() addSubview(foregroundView) addSubview(placeholderLabel) layer.addSublayer(foregroundLayer) } override open func animateViewsForTextEntry() { UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.6, options: .beginFromCurrentState, animations: { self.foregroundView.layer.transform = CATransform3DIdentity }, completion: { _ in self.animationCompletionHandler?(.textEntry) }) foregroundLayer.frame = rectForBorder(foregroundView.frame, isFilled: false) } override open func animateViewsForTextDisplay() { if text!.isEmpty { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.6, options: .beginFromCurrentState, animations: { self.foregroundLayer.frame = self.rectForBorder(self.foregroundView.frame, isFilled: true) self.foregroundView.layer.transform = self.rotationAndPerspectiveTransformForView(self.foregroundView) }, completion: { _ in self.animationCompletionHandler?(.textDisplay) }) } } // MARK: - Private private func updateForeground() { foregroundView.frame = rectForForeground(frame) foregroundView.isUserInteractionEnabled = false foregroundView.layer.transform = rotationAndPerspectiveTransformForView(foregroundView) foregroundView.backgroundColor = foregroundColor foregroundLayer.borderWidth = borderThickness foregroundLayer.borderColor = colorWithBrightnessFactor(foregroundColor, factor: 0.8).cgColor foregroundLayer.frame = rectForBorder(foregroundView.frame, isFilled: true) } private func updatePlaceholder() { placeholderLabel.font = placeholderFontFromFont(font!) placeholderLabel.text = placeholder placeholderLabel.textColor = placeholderColor placeholderLabel.sizeToFit() layoutPlaceholderInTextRect() if isFirstResponder || text!.isNotEmpty { animateViewsForTextEntry() } } private func placeholderFontFromFont(_ font: UIFont) -> UIFont! { let smallerFont = UIFont(name: font.fontName, size: font.pointSize * placeholderFontScale) return smallerFont } private func rectForForeground(_ bounds: CGRect) -> CGRect { let newRect = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y - borderThickness) return newRect } private func rectForBorder(_ bounds: CGRect, isFilled: Bool) -> CGRect { var newRect = CGRect(x: 0, y: bounds.size.height, width: bounds.size.width, height: isFilled ? borderThickness : 0) if !CATransform3DIsIdentity(foregroundView.layer.transform) { newRect.origin = CGPoint(x: 0, y: bounds.origin.y) } return newRect } private func layoutPlaceholderInTextRect() { let textRect = self.textRect(forBounds: bounds) var originX = textRect.origin.x switch textAlignment { case .center: originX += textRect.size.width/2 - placeholderLabel.bounds.width/2 case .right: originX += textRect.size.width - placeholderLabel.bounds.width default: break } placeholderLabel.frame = CGRect(x: originX, y: bounds.height - placeholderLabel.frame.height, width: placeholderLabel.frame.size.width, height: placeholderLabel.frame.size.height) } // MARK: - private func setAnchorPoint(_ anchorPoint:CGPoint, forView view:UIView) { var newPoint:CGPoint = CGPoint(x: view.bounds.size.width * anchorPoint.x, y: view.bounds.size.height * anchorPoint.y) var oldPoint:CGPoint = CGPoint(x: view.bounds.size.width * view.layer.anchorPoint.x, y: view.bounds.size.height * view.layer.anchorPoint.y) newPoint = newPoint.applying(view.transform) oldPoint = oldPoint.applying(view.transform) var position = view.layer.position position.x -= oldPoint.x position.x += newPoint.x position.y -= oldPoint.y position.y += newPoint.y view.layer.position = position view.layer.anchorPoint = anchorPoint } private func colorWithBrightnessFactor(_ color: UIColor, factor: CGFloat) -> UIColor { var hue : CGFloat = 0 var saturation : CGFloat = 0 var brightness : CGFloat = 0 var alpha : CGFloat = 0 if color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) { return UIColor(hue: hue, saturation: saturation, brightness: brightness * factor, alpha: alpha) } else { return color; } } private func rotationAndPerspectiveTransformForView(_ view: UIView) -> CATransform3D { setAnchorPoint(CGPoint(x: 0.5, y: 1.0), forView:view) var rotationAndPerspectiveTransform = CATransform3DIdentity rotationAndPerspectiveTransform.m34 = 1.0/800 let radians = ((-90) / 180.0 * CGFloat(M_PI)) rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, radians, 1.0, 0.0, 0.0) return rotationAndPerspectiveTransform } // MARK: - Overrides override open func editingRect(forBounds bounds: CGRect) -> CGRect { let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y) return newBounds.insetBy(dx: textFieldInsets.x, dy: 0) } override open func textRect(forBounds bounds: CGRect) -> CGRect { let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y) return newBounds.insetBy(dx: textFieldInsets.x, dy: 0) } }
mit
f0d14d1c7397ff7eb68564e3f52e5420
35.837104
175
0.639356
5.094493
false
false
false
false
huonw/swift
test/SILGen/toplevel.swift
1
3473
// RUN: %target-swift-emit-silgen -Xllvm -sil-full-demangle -enable-sil-ownership %s | %FileCheck %s func markUsed<T>(_ t: T) {} func trap() -> Never { fatalError() } // CHECK-LABEL: sil @main // CHECK: bb0({{%.*}} : @trivial $Int32, {{%.*}} : @trivial $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): // -- initialize x // CHECK: alloc_global @$S8toplevel1xSiv // CHECK: [[X:%[0-9]+]] = global_addr @$S8toplevel1xSivp : $*Int // CHECK: integer_literal $Builtin.Int2048, 999 // CHECK: store {{.*}} to [trivial] [[X]] var x = 999 func print_x() { markUsed(x) } // -- assign x // CHECK: integer_literal $Builtin.Int2048, 0 // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X]] : $*Int // CHECK: assign {{.*}} to [[WRITE]] // CHECK: [[PRINT_X:%[0-9]+]] = function_ref @$S8toplevel7print_xyyF : // CHECK: apply [[PRINT_X]] x = 0 print_x() // <rdar://problem/19770775> Deferred initialization of let bindings rejected at top level in playground // CHECK: alloc_global @$S8toplevel5countSiv // CHECK: [[COUNTADDR:%[0-9]+]] = global_addr @$S8toplevel5countSivp : $*Int // CHECK-NEXT: [[COUNTMUI:%[0-9]+]] = mark_uninitialized [var] [[COUNTADDR]] : $*Int let count: Int // CHECK: cond_br if x == 5 { count = 0 // CHECK: assign {{.*}} to [[COUNTMUI]] // CHECK: br [[MERGE:bb[0-9]+]] } else { count = 10 // CHECK: assign {{.*}} to [[COUNTMUI]] // CHECK: br [[MERGE]] } // CHECK: [[MERGE]]: // CHECK: load [trivial] [[COUNTMUI]] markUsed(count) var y : Int func print_y() { markUsed(y) } // -- assign y // CHECK: alloc_global @$S8toplevel1ySiv // CHECK: [[Y1:%[0-9]+]] = global_addr @$S8toplevel1ySivp : $*Int // CHECK: [[Y:%[0-9]+]] = mark_uninitialized [var] [[Y1]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[Y]] // CHECK: assign {{.*}} to [[WRITE]] // CHECK: [[PRINT_Y:%[0-9]+]] = function_ref @$S8toplevel7print_yyyF y = 1 print_y() // -- treat 'guard' vars as locals // CHECK-LABEL: function_ref toplevel.A.__allocating_init // CHECK: switch_enum {{%.+}} : $Optional<A>, case #Optional.some!enumelt.1: [[SOME_CASE:.+]], case #Optional.none! // CHECK: [[SOME_CASE]]([[VALUE:%.+]] : @owned $A): // CHECK: store [[VALUE]] to [init] [[BOX:%.+]] : $*A // CHECK-NOT: destroy_value // CHECK: [[SINK:%.+]] = function_ref @$S8toplevel8markUsedyyxlF // CHECK-NOT: destroy_value // CHECK: apply [[SINK]]<A>({{%.+}}) class A {} guard var a = Optional(A()) else { trap() } markUsed(a) // CHECK: alloc_global @$S8toplevel21NotInitializedIntegerSiv // CHECK-NEXT: [[VARADDR:%[0-9]+]] = global_addr @$S8toplevel21NotInitializedIntegerSiv // CHECK-NEXT: [[VARMUI:%[0-9]+]] = mark_uninitialized [var] [[VARADDR]] : $*Int // CHECK-NEXT: mark_function_escape [[VARMUI]] : $*Int // <rdar://problem/21753262> Bug in DI when it comes to initialization of global "let" variables let NotInitializedInteger : Int func fooUsesUninitializedValue() { _ = NotInitializedInteger } fooUsesUninitializedValue() NotInitializedInteger = 10 fooUsesUninitializedValue() // CHECK: [[RET:%[0-9]+]] = struct $Int32 // CHECK: return [[RET]] // CHECK-LABEL: sil hidden @$S8toplevel7print_xyyF // CHECK-LABEL: sil hidden @$S8toplevel7print_yyyF // CHECK: sil hidden @$S8toplevel13testGlobalCSESiyF // CHECK-NOT: global_addr // CHECK: %0 = global_addr @$S8toplevel1xSivp : $*Int // CHECK-NOT: global_addr // CHECK: return func testGlobalCSE() -> Int { // We should only emit one global_addr in this function. return x + x }
apache-2.0
a30dd4e6b35932d4b15bbdac4c15e299
26.563492
121
0.635474
3.134477
false
false
false
false
mattiasjahnke/arduino-projects
matrix-painter/iOS/PixelDrawer/Carthage/Checkouts/flow/Flow/ReadWriteSignal.swift
1
3637
// // ReadWriteSignal.swift // Flow // // Created by Måns Bernhardt on 2018-03-12. // Copyright © 2018 iZettle. All rights reserved. // import Foundation /// An abstraction for observing events over time where `self` as a notion of a mutable current value. /// /// A `ReadWriteSignal<T>` is like a `ReadSignal<T>` where the current `value` property is mutable. /// /// - Note: Most transforms on writable signals will return a read-only or plain signal, as most transforms are not reversable or cannot guarantee to provide a current value. /// - Note: You can demote a `ReadWriteSignal<T>` to a `ReadSignal<T>` using `readOnly()`. /// - Note: You can demote a `ReadWriteSignal<T>` to a `Signal<T>` using `plain()`. /// - Note: `ReadWriteSignal<Value>` is a type alias for `CoreSignal<ReadWrite, Value>` to allow sharing common functionality with the other signal types`. public typealias ReadWriteSignal<Value> = CoreSignal<ReadWrite, Value> public extension CoreSignal where Kind == ReadWrite { /// Creates a new instance with an initial `value` and where updates to `self.value` will be signaled. /// /// - Paramenter willSet: Will be called the new value, but before `self.value` is updated and the new value is being signaled. /// - Paramenter didSet: Will be called the new value, after `self.value` has been updated and the new value has been signaled. convenience init(_ value: Value, willSet: @escaping (Value) -> () = { _ in }, didSet: @escaping (Value) -> () = { _ in }) { var _value = value let callbacker = Callbacker<Value>() self.init(getValue: { _value }, setValue: { val in willSet(val) _value = val callbacker.callAll(with: val) didSet(val) }, options: [], onInternalEvent: { c in return callbacker.addCallback { c(.value($0)) } }) } /// Creates a new instance getting its current value from `getValue` and where `setValue` is called when `self.value` is updated, whereafter the new value is signaled. /// /// - Paramenter getValue: Called to get the current value. /// - Paramenter setValue: Called when `self.value` is updated, but before the new value is signaled. convenience init(getValue: @escaping () -> Value, setValue: @escaping (Value) -> ()) { let callbacker = Callbacker<Value>() self.init(getValue: getValue, setValue: { setValue($0); callbacker.callAll(with: $0) }, options: [], onInternalEvent: { c in return callbacker.addCallback { c(.value($0)) } }) } } public extension SignalProvider where Kind == ReadWrite { /// Returns a new signal with a read-only `value`. func readOnly() -> ReadSignal<Value> { return CoreSignal(self) } } public extension SignalProvider where Kind == ReadWrite { // The current value of `self`. var value: Value { get { return providedSignal.getter()! } nonmutating set { providedSignal.setter!(newValue) } } } private var propertySetterKey = false internal extension SignalProvider { var setter: ((Value) -> ())? { return objc_getAssociatedObject(providedSignal, &propertySetterKey) as? (Value) -> () } } internal extension CoreSignal { convenience init(setValue: ((Value) -> ())?, onEventType: @escaping (@escaping (EventType) -> Void) -> Disposable) { self.init(onEventType: onEventType) if let setter = setValue { objc_setAssociatedObject(self, &propertySetterKey, setter, .OBJC_ASSOCIATION_RETAIN) } } }
mit
ded63156389bd1544414e219646cfbd9
41.267442
174
0.649519
4.093468
false
false
false
false
hachinobu/CleanQiitaClient
DomainLayer/UseCase/ItemListUseCase.swift
1
2051
// // ItemListUseCase.swift // CleanQiitaClient // // Created by Takahiro Nishinobu on 2016/09/23. // Copyright © 2016年 hachinobu. All rights reserved. // import Foundation import APIKit import Result import DataLayer public protocol ItemListUseCase { func fetchItemList(page: Int?, perPage: Int?, handler: @escaping (Result<[ListItemModel], SessionTaskError>) -> Void) } public struct AllItemListUseCaseImpl: ItemListUseCase { let repository: ItemListRepository public init(repository: ItemListRepository) { self.repository = repository } public func fetchItemList(page: Int?, perPage: Int?, handler: @escaping (Result<[ListItemModel], SessionTaskError>) -> Void) { repository.fetchItemList(page: page, perPage: perPage) { result in let r = generateItemModelsResultFromItemEntitiesResult(result: result) handler(r) } } } public struct UserItemListUseCaseImpl: ItemListUseCase { let repository: UserItemListRepository let userId: String public init(repository: UserItemListRepository, userId: String) { self.repository = repository self.userId = userId } public func fetchItemList(page: Int?, perPage: Int?, handler: @escaping (Result<[ListItemModel], SessionTaskError>) -> Void) { repository.fetchUserItemList(page: page, perPage: perPage, userId: userId) { result in let r = generateItemModelsResultFromItemEntitiesResult(result: result) handler(r) } } } fileprivate func generateItemModelsResultFromItemEntitiesResult(result: Result<[ItemEntity], SessionTaskError>) -> Result<[ListItemModel], SessionTaskError> { guard let itemEntities = result.value else { return Result.failure(result.error!) } let listItemModels = ListItemModelsTranslator().translate(itemEntities) return Result.success(listItemModels) }
mit
b9e6287f094747476ec328fdc8f29f2e
27.84507
158
0.666016
4.796253
false
false
false
false
PerfectlySoft/Perfect-Authentication
Sources/OAuth2/makeRequest.swift
1
3154
// // makeRequest.swift // Perfect-Authentication // // Created by Jonathan Guthrie on 2017-01-18. // Branched from CouchDB Version import PerfectLib import PerfectCURL import cURL import SwiftString import PerfectHTTP extension OAuth2 { /// The function that triggers the specific interaction with a remote server /// Parameters: /// - method: The HTTP Method enum, i.e. .get, .post /// - route: The route required /// - body: The JSON formatted sring to sent to the server /// Response: /// (HTTPResponseStatus, "data" - [String:Any], "raw response" - [String:Any], HTTPHeaderParser) func makeRequest( _ method: HTTPMethod, _ url: String, body: String = "", encoding: String = "JSON", bearerToken: String = "" // ) -> (Int, [String:Any], [String:Any], HTTPHeaderParser) { ) -> ([String:Any]) { let curlObject = CURL(url: url) curlObject.setOption(CURLOPT_HTTPHEADER, s: "Accept: application/json") curlObject.setOption(CURLOPT_HTTPHEADER, s: "Cache-Control: no-cache") curlObject.setOption(CURLOPT_USERAGENT, s: "PerfectAPI2.0") if !bearerToken.isEmpty { curlObject.setOption(CURLOPT_HTTPHEADER, s: "Authorization: Bearer \(bearerToken)") } switch method { case .post : let byteArray = [UInt8](body.utf8) curlObject.setOption(CURLOPT_POST, int: 1) curlObject.setOption(CURLOPT_POSTFIELDSIZE, int: byteArray.count) curlObject.setOption(CURLOPT_COPYPOSTFIELDS, v: UnsafeMutablePointer(mutating: byteArray)) if encoding == "form" { curlObject.setOption(CURLOPT_HTTPHEADER, s: "Content-Type: application/x-www-form-urlencoded") } else { curlObject.setOption(CURLOPT_HTTPHEADER, s: "Content-Type: application/json") } default: //.get : curlObject.setOption(CURLOPT_HTTPGET, int: 1) } var header = [UInt8]() var bodyIn = [UInt8]() var code = 0 var data = [String: Any]() var raw = [String: Any]() var perf = curlObject.perform() defer { curlObject.close() } while perf.0 { if let h = perf.2 { header.append(contentsOf: h) } if let b = perf.3 { bodyIn.append(contentsOf: b) } perf = curlObject.perform() } if let h = perf.2 { header.append(contentsOf: h) } if let b = perf.3 { bodyIn.append(contentsOf: b) } let _ = perf.1 // Parsing now: // assember the header from a binary byte array to a string // let headerStr = String(bytes: header, encoding: String.Encoding.utf8) // parse the header // let http = HTTPHeaderParser(header:headerStr!) // assamble the body from a binary byte array to a string let content = String(bytes:bodyIn, encoding:String.Encoding.utf8) // prepare the failsafe content. // raw = ["status": http.status, "header": headerStr!, "body": content!] // parse the body data into a json convertible do { if (content?.count)! > 0 { if (content?.startsWith("["))! { let arr = try content?.jsonDecode() as! [Any] data["response"] = arr } else { data = try content?.jsonDecode() as! [String : Any] } } return data // return (http.code, data, raw, http) } catch { return [:] // return (http.code, [:], raw, http) } } }
apache-2.0
fbada286d261882310021d44d80e6e14
25.283333
98
0.663285
3.122772
false
false
false
false
ChinaPicture/ZXYRefresh
RefreshDemo/Refresh/RefreshBaseHeaderView.swift
1
1462
// // RefreshHeaderView.swift // RefreshDemo // // Created by developer on 15/03/2017. // Copyright © 2017 developer. All rights reserved. // import UIKit protocol RefreshHeaderStatusChangeDelegate: class { func headerRefreshViewStatusChange(_ status: RefreshStatus) } class RefreshBaseHeaderView: UIView , RefreshHeaderProtocol { private var _state: RefreshStatus = .initial weak var delegate: RefreshHeaderStatusChangeDelegate? var activeOff: CGFloat = 0.0 { didSet{} } var activeAction: RefreshStatusChangedAction? { didSet{} } var state: RefreshStatus { set{ self._state = newValue ; self.delegate?.headerRefreshViewStatusChange(self._state) } get{ return self._state } } required init(activeOff: CGFloat , action: RefreshStatusChangedAction?) { super.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: activeOff)) self.activeOff = activeOff self.activeAction = action } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func prepareRefreshViewLayout() { } func refreshViewOffset(scroll: UIScrollView, offset: CGPoint) { } func refreshViewStateChanged(scroll: UIScrollView, currentState: RefreshStatus) { self.activeAction?(currentState) } func refreshRatioChange(scroll: UIScrollView , ratio: CGFloat) { } }
apache-2.0
3d2ae3e4f2c426548edffb0631b096d0
30.085106
121
0.689254
4.374251
false
false
false
false
SwipeCellKit/SwipeCellKit
Source/SwipeFeedback.swift
10
1298
// // SwipeFeedback.swift // // Created by Jeremy Koch // Copyright © 2017 Jeremy Koch. All rights reserved. // import UIKit final class SwipeFeedback { enum Style { case light case medium case heavy } @available(iOS 10.0.1, *) private var feedbackGenerator: UIImpactFeedbackGenerator? { get { return _feedbackGenerator as? UIImpactFeedbackGenerator } set { _feedbackGenerator = newValue } } private var _feedbackGenerator: Any? init(style: Style) { if #available(iOS 10.0.1, *) { switch style { case .light: feedbackGenerator = UIImpactFeedbackGenerator(style: .light) case .medium: feedbackGenerator = UIImpactFeedbackGenerator(style: .medium) case .heavy: feedbackGenerator = UIImpactFeedbackGenerator(style: .heavy) } } else { _feedbackGenerator = nil } } func prepare() { if #available(iOS 10.0.1, *) { feedbackGenerator?.prepare() } } func impactOccurred() { if #available(iOS 10.0.1, *) { feedbackGenerator?.impactOccurred() } } }
mit
5b4b621b94fc24e5978177f2b21c6d34
22.160714
77
0.538936
5.066406
false
false
false
false
mitchtreece/Spider
Example/Spider/UIKitViewController.swift
1
1689
// // UIKitViewController.swift // Spider // // Created by Mitch Treece on 5/27/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import SnapKit import Spider class UIKitViewController: LoadingViewController { private var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() self.title = "UIKit" self.view.backgroundColor = UIColor.groupTableViewBackground self.imageView = UIImageView() self.imageView.backgroundColor = UIColor.white self.imageView.layer.cornerRadius = 4 self.imageView.clipsToBounds = true self.imageView.isUserInteractionEnabled = true self.view.insertSubview(self.imageView, at: 0) self.imageView.snp.makeConstraints { make in make.width.height.equalTo(view.snp.width).multipliedBy(0.9) make.center.equalTo(view) } loadRandomImage() self.imageView.addGestureRecognizer(UITapGestureRecognizer( target: self, action: #selector(handleTap(_:)) )) } @objc private func handleTap(_ recognizer: UITapGestureRecognizer) { loadRandomImage() } private func loadRandomImage() { guard self.isLoading == false else { return } self.imageView.image = nil self.startLoading() self.imageView.web.setImage("https://unsplash.it/500/?random", cacheImage: false) { (image, isCached, error) in self.imageView.image = image self.stopLoading() } } }
mit
bd5311d719ad955953bc028a780a478b
25.793651
119
0.600711
5.084337
false
false
false
false
kevinmbeaulieu/Signal-iOS
Signal/src/call/OutboundCallInitiator.swift
1
3489
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation /** * Creates an outbound call via WebRTC. */ @objc class OutboundCallInitiator: NSObject { let TAG = "[OutboundCallInitiator]" let contactsManager: OWSContactsManager let contactsUpdater: ContactsUpdater init(contactsManager: OWSContactsManager, contactsUpdater: ContactsUpdater) { self.contactsManager = contactsManager self.contactsUpdater = contactsUpdater super.init() } /** * |handle| is a user formatted phone number, e.g. from a system contacts entry */ public func initiateCall(handle: String) -> Bool { Logger.info("\(TAG) in \(#function) with handle: \(handle)") guard let recipientId = PhoneNumber(fromUserSpecifiedText: handle)?.toE164() else { Logger.warn("\(TAG) unable to parse signalId from phone number: \(handle)") return false } return initiateCall(recipientId: recipientId) } /** * |recipientId| is a e164 formatted phone number. */ public func initiateCall(recipientId: String) -> Bool { // Rather than an init-assigned dependency property, we access `callUIAdapter` via Environment // because it can change after app launch due to user settings guard let callUIAdapter = Environment.getCurrent().callUIAdapter else { assertionFailure() Logger.error("\(TAG) can't initiate call because callUIAdapter is nil") return false } // Check for microphone permissions // Alternative way without prompting for permissions: // if AVAudioSession.sharedInstance().recordPermission() == .denied { AVAudioSession.sharedInstance().requestRecordPermission { isGranted in // Here the permissions are either granted or denied guard isGranted == true else { Logger.warn("\(self.TAG) aborting due to missing microphone permissions.") self.showNoMicrophonePermissionAlert() return } callUIAdapter.startAndShowOutgoingCall(recipientId: recipientId) } return true } /// Cleanup and present alert for no permissions private func showNoMicrophonePermissionAlert() { let alertTitle = NSLocalizedString("CALL_AUDIO_PERMISSION_TITLE", comment:"Alert title when calling and permissions for microphone are missing") let alertMessage = NSLocalizedString("CALL_AUDIO_PERMISSION_MESSAGE", comment:"Alert message when calling and permissions for microphone are missing") let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert) let dismiss = NSLocalizedString("DISMISS_BUTTON_TEXT", comment: "Generic short text for button to dismiss a dialog") let dismissAction = UIAlertAction(title: dismiss, style: .cancel) let settingsString = NSLocalizedString("OPEN_SETTINGS_BUTTON", comment: "Button text which opens the settings app") let settingsAction = UIAlertAction(title: settingsString, style: .default) { _ in UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!) } alertController.addAction(dismissAction) alertController.addAction(settingsAction) UIApplication.shared.frontmostViewController?.present(alertController, animated: true, completion: nil) } }
gpl-3.0
e13ddbc0af8fdf34c9c50d5512948922
43.164557
158
0.686156
5.417702
false
false
false
false
MartinOSix/DemoKit
dSwift/SwiftDemoKit/SwiftDemoKit/QRCodeViewController.swift
1
8719
// // QRCodeViewController.swift // SwiftDemoKit // // Created by runo on 17/5/18. // Copyright © 2017年 com.runo. All rights reserved. // import UIKit import AVFoundation class QRCodeViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { let tableview = UITableView.init(frame: kScreenBounds, style: .plain) var dataSource = ["扫描二维码","长按识别二维码"] var cuurentVersionName: String = "1.0" func funname(args: Array<String>) { } override func viewDidLoad() { super.viewDidLoad() tableview.delegate = self tableview.dataSource = self tableview.register(UITableViewCell.self, forCellReuseIdentifier: "cell") self.view.addSubview(tableview) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableview.dequeueReusableCell(withIdentifier: "cell") cell?.textLabel?.text = dataSource[indexPath.row] return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.row { case 0: self.navigationController?.pushViewController(QRScanViewController(), animated: true) default: self.navigationController?.pushViewController(ImageViewController(), animated: true) break } } } class QRScanViewController: UIViewController,AVCaptureMetadataOutputObjectsDelegate { var session: AVCaptureSession? var animationView = UIView.init(frame: CGRect.zero) func getsession() { if let turesession = session { } } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.black //judgeCapture() //initScanView() setupAnimationView() } func setupAnimationView() { self.animationView.frame.size = CGSize.init(width: 300, height: 300) self.animationView.center = CGPoint.init(x: kScreenWidth/2, y: kScreenHeight/2) animationView.layer.borderWidth = 4; animationView.layer.borderColor = UIColor.green.cgColor self.view.addSubview(animationView) let lineLayer = CALayer() lineLayer.backgroundColor = UIColor.green.cgColor lineLayer.frame = CGRect.init(x: 20, y: 20, width: 260, height: 4) self.animationView.layer.addSublayer(lineLayer) let baseAnimation = CABasicAnimation.init(keyPath: "position") baseAnimation.fromValue = NSValue.init(cgPoint:CGPoint.init(x: 150, y: 20.0)) baseAnimation.toValue = NSValue.init(cgPoint:CGPoint.init(x: 150, y: 280.0)) baseAnimation.repeatCount = Float(NSIntegerMax) baseAnimation.duration = 2.0 baseAnimation.repeatDuration = 0.0 lineLayer.add(baseAnimation, forKey: "anima") /*//没用 let lineView = UIView.init(frame: CGRect(x: 20, y: 20, width: 260, height: 4)) lineView.backgroundColor = UIColor.green self.animationView.addSubview(lineView) UIView.beginAnimations(nil, context: nil) lineView.frame = CGRect(x: 20, y: 280, width: 260, height: 4) UIView.setAnimationRepeatCount(Float(NSIntegerMax)) UIView.setAnimationDuration(6) UIView.setAnimationRepeatAutoreverses(true) UIView.commitAnimations() */ } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.session?.startRunning() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.session?.stopRunning() } //结果输出 func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) { if metadataObjects.count > 0 { let metadata = metadataObjects.first as! AVMetadataMachineReadableCodeObject if metadata.stringValue! .hasPrefix("http") { UIApplication.shared.openURL(URL.init(string: metadata.stringValue!)!) return } let alert = UIAlertController(title: "扫描结果", message: metadata.stringValue!, preferredStyle: .alert) let action = UIAlertAction(title: "确定", style: .default, handler: nil) alert.addAction(action) present(alert, animated: true, completion: nil) } } func initScanView() { let layer = AVCaptureVideoPreviewLayer.init(session: session) layer?.videoGravity = AVLayerVideoGravityResizeAspectFill layer?.frame = kScreenBounds view.layer.insertSublayer(layer!, at: 0) } func initSession() { let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) do { let input = try AVCaptureDeviceInput(device: device)//输入流 let output = AVCaptureMetadataOutput() //输出流 output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) //扫描区域 //let widthS = 300/kScreenHeight //let heightS = 300/kScreenWidth //output.rectOfInterest = //CGRect(x: (1-widthS)/2, y: (1-heightS)/2, width: widthS, height: heightS) session = AVCaptureSession() //采集质量 session?.sessionPreset = AVCaptureSessionPresetHigh session?.addInput(input) session?.addOutput(output) output.metadataObjectTypes = [AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code] } catch let err as NSError { print("位置错误 \(err.localizedFailureReason)") } } deinit { print("\(self.description) 销毁了") } //权限判断 func judgeCapture() { let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) if status == AVAuthorizationStatus.notDetermined {//没权限 AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (allow) in if allow { print("同意") }else{ print("拒绝") _ = self.navigationController?.popViewController(animated: true) } }) }else if(status == AVAuthorizationStatus.authorized){//被拒绝 print("有权限") initSession() }else { let alert = UIAlertController.init(title: "提示", message: "请在iPhone的“设置”->“隐私”->“相机”中授权微信访问您的相机", preferredStyle: .alert) let action = UIAlertAction.init(title: "确定", style: UIAlertActionStyle.default, handler: { (act) in _ = self.navigationController?.popViewController(animated: true) }) alert.addAction(action) self.present(alert, animated: true, completion: nil) } } } class ImageViewController: UIViewController { let imageView: UIImageView = UIImageView.init(frame: kScreenBounds) override func viewDidLoad() { super.viewDidLoad() imageView.image = UIImage.init(named: "IMG_0776") self.view .addSubview(imageView) let ges = UILongPressGestureRecognizer.init(target: self, action: #selector(scanImage)) self.view.addGestureRecognizer(ges) } func scanImage() { /*CIDetector:iOS自带的识别图片的类*/ let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh]) let arr = detector?.features(in: CIImage(cgImage: (imageView.image?.cgImage)!)) var detail = "" if (arr?.count)! > 0 { detail = (arr?.first as! CIQRCodeFeature).messageString! }else { detail = "未扫描到结果!" } let alert = UIAlertController(title: "扫描结果", message: detail, preferredStyle: .alert) let action = UIAlertAction(title: "确定", style: .default, handler: nil) alert.addAction(action) present(alert, animated: true, completion: nil) } }
apache-2.0
9df032be8f66d2c8a4e0c27d972c9532
31.891473
160
0.622437
5.012404
false
false
false
false
hweetty/TitledActivitiesDemo
TitledActivitiesDemo/UIActivityViewController+Title.swift
1
1938
// // UIActivityViewController+Title.swift // TitledActivitiesDemo // // Created by Jerry Yu on 2016-02-15. // Copyright © 2016 Jerry Yu. All rights reserved. // import UIKit // Identify the fxView to fade out title when disappearing private let myTag = 3141592 extension UIActivityViewController { func addTitle(title: String) { // Container for title label, used to get blur effect. let fxView = UIVisualEffectView(effect: UIBlurEffect(style: .ExtraLight)) fxView.translatesAutoresizingMaskIntoConstraints = false fxView.tag = myTag fxView.layer.cornerRadius = 8 fxView.clipsToBounds = true // Pretty hacky self.view.subviews.first!.subviews.first!.addSubview(fxView) // Actual title label let titleLabel = UILabel() titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.backgroundColor = UIColor.clearColor() titleLabel.font = UIFont.systemFontOfSize(19) titleLabel.text = title titleLabel.textColor = UIColor.darkTextColor() fxView.addSubview(titleLabel) // Autolayout the views let views = [ "fx": fxView, "label": titleLabel, ] let formatStrings = [ // fx has full width, negative `y` origin "H:|[fx]|", "V:|-(-56)-[fx(50)]", // Title label has horizontal padding "H:|-13-[label]-13-|", "V:|[label]|" ] formatStrings.forEach { format in let constraints = NSLayoutConstraint.constraintsWithVisualFormat(format, options:[] , metrics: nil, views: views) NSLayoutConstraint.activateConstraints(constraints) } } public override func viewWillDisappear(animated: Bool) { // Animate the alpha, otherwise the title label will peek out self.transitionCoordinator()?.animateAlongsideTransition({ (context) -> Void in if let containerView = self.view.subviews.first!.subviews.first!.viewWithTag(myTag) { // Definitely hacky containerView.alpha = 0 } }, completion: nil) super.viewWillDisappear(animated) } }
mit
0c48f9586a9c2792203108d94adba3a2
26.28169
116
0.725865
3.961145
false
false
false
false
ronaldho/smartlittlefoodie
characterfeeder/KDCircularProgress.swift
3
17264
// // KDCircularProgress.swift // KDCircularProgress // // Created by Kaan Dedeoglu on 1/14/15. // Copyright (c) 2015 Kaan Dedeoglu. All rights reserved. // import UIKit public enum KDCircularProgressGlowMode { case Forward, Reverse, Constant, NoGlow } @IBDesignable public class KDCircularProgress: UIView { private struct ConversionFunctions { static func DegreesToRadians (value:CGFloat) -> CGFloat { return value * CGFloat(M_PI) / 180.0 } static func RadiansToDegrees (value:CGFloat) -> CGFloat { return value * 180.0 / CGFloat(M_PI) } } private struct UtilityFunctions { static func Clamp<T: Comparable>(value: T, minMax: (T, T)) -> T { let (min, max) = minMax if value < min { return min } else if value > max { return max } else { return value } } static func Mod(value: Int, range: Int, minMax: (Int, Int)) -> Int { let (min, max) = minMax assert(abs(range) <= abs(max - min), "range should be <= than the interval") if value >= min && value <= max { return value } else if value < min { return Mod(value + range, range: range, minMax: minMax) } else { return Mod(value - range, range: range, minMax: minMax) } } } private var progressLayer: KDCircularProgressViewLayer! { get { return layer as! KDCircularProgressViewLayer } } private var radius: CGFloat! { didSet { progressLayer.radius = radius } } @IBInspectable public var angle: Int = 0 { didSet { if self.isAnimating() { self.pauseAnimation() } progressLayer.angle = angle } } @IBInspectable public var startAngle: Int = 0 { didSet { progressLayer.startAngle = UtilityFunctions.Mod(startAngle, range: 360, minMax: (0,360)) progressLayer.setNeedsDisplay() } } @IBInspectable public var clockwise: Bool = true { didSet { progressLayer.clockwise = clockwise progressLayer.setNeedsDisplay() } } @IBInspectable public var roundedCorners: Bool = true { didSet { progressLayer.roundedCorners = roundedCorners } } @IBInspectable public var gradientRotateSpeed: CGFloat = 0 { didSet { progressLayer.gradientRotateSpeed = gradientRotateSpeed } } @IBInspectable public var glowAmount: CGFloat = 1.0 {//Between 0 and 1 didSet { progressLayer.glowAmount = UtilityFunctions.Clamp(glowAmount, minMax: (0, 1)) } } @IBInspectable public var glowMode: KDCircularProgressGlowMode = .Forward { didSet { progressLayer.glowMode = glowMode } } @IBInspectable public var progressThickness: CGFloat = 0.4 {//Between 0 and 1 didSet { progressThickness = UtilityFunctions.Clamp(progressThickness, minMax: (0, 1)) progressLayer.progressThickness = progressThickness/2 } } @IBInspectable public var trackThickness: CGFloat = 0.5 {//Between 0 and 1 didSet { trackThickness = UtilityFunctions.Clamp(trackThickness, minMax: (0, 1)) progressLayer.trackThickness = trackThickness/2 } } @IBInspectable public var trackColor: UIColor = UIColor.blackColor() { didSet { progressLayer.trackColor = trackColor progressLayer.setNeedsDisplay() } } @IBInspectable public var progressColors: [UIColor]! { get { return progressLayer.colorsArray } set(newValue) { setColors(newValue) } } //These are used only from the Interface-Builder. Changing these from code will have no effect. //Also IB colors are limited to 3, whereas programatically we can have an arbitrary number of them. @objc @IBInspectable private var IBColor1: UIColor? @objc @IBInspectable private var IBColor2: UIColor? @objc @IBInspectable private var IBColor3: UIColor? private var animationCompletionBlock: ((Bool) -> Void)? override public init(frame: CGRect) { super.init(frame: frame) userInteractionEnabled = false setInitialValues() refreshValues() checkAndSetIBColors() } convenience public init(frame:CGRect, colors: UIColor...) { self.init(frame: frame) setColors(colors) } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setTranslatesAutoresizingMaskIntoConstraints(false) userInteractionEnabled = false setInitialValues() refreshValues() } public override func awakeFromNib() { checkAndSetIBColors() } override public class func layerClass() -> AnyClass { return KDCircularProgressViewLayer.self } private func setInitialValues() { radius = (frame.size.width/2.0) * 0.8 //We always apply a 20% padding, stopping glows from being clipped backgroundColor = .clearColor() setColors(UIColor.whiteColor(), UIColor.redColor()) } private func refreshValues() { progressLayer.angle = angle progressLayer.startAngle = UtilityFunctions.Mod(startAngle, range: 360, minMax: (0,360)) progressLayer.clockwise = clockwise progressLayer.roundedCorners = roundedCorners progressLayer.gradientRotateSpeed = gradientRotateSpeed progressLayer.glowAmount = UtilityFunctions.Clamp(glowAmount, minMax: (0, 1)) progressLayer.glowMode = glowMode progressLayer.progressThickness = progressThickness/2 progressLayer.trackColor = trackColor progressLayer.trackThickness = trackThickness/2 } private func checkAndSetIBColors() { let nonNilColors = [IBColor1, IBColor2, IBColor3].filter { $0 != nil}.map { $0! } if nonNilColors.count > 0 { setColors(nonNilColors) } } public func setColors(colors: UIColor...) { setColors(colors) } private func setColors(colors: [UIColor]) { progressLayer.colorsArray = colors progressLayer.setNeedsDisplay() } public func animateFromAngle(fromAngle: Int, toAngle: Int, duration: NSTimeInterval, completion: ((Bool) -> Void)?) { if isAnimating() { pauseAnimation() } let animation = CABasicAnimation(keyPath: "angle") animation.fromValue = fromAngle animation.toValue = toAngle animation.duration = duration animation.delegate = self angle = toAngle animationCompletionBlock = completion progressLayer.addAnimation(animation, forKey: "angle") } public func animateToAngle(toAngle: Int, duration: NSTimeInterval, completion: ((Bool) -> Void)?) { if isAnimating() { pauseAnimation() } animateFromAngle(angle, toAngle: toAngle, duration: duration, completion: completion) } public func pauseAnimation() { let presentationLayer = progressLayer.presentationLayer() as! KDCircularProgressViewLayer let currentValue = presentationLayer.angle progressLayer.removeAllAnimations() animationCompletionBlock = nil angle = currentValue } public func stopAnimation() { let presentationLayer = progressLayer.presentationLayer() as! KDCircularProgressViewLayer progressLayer.removeAllAnimations() angle = 0 } public func isAnimating() -> Bool { return progressLayer.animationForKey("angle") != nil } override public func animationDidStop(anim: CAAnimation!, finished flag: Bool) { if let completionBlock = animationCompletionBlock { completionBlock(flag) animationCompletionBlock = nil } } public override func didMoveToWindow() { if let window = window { progressLayer.contentsScale = window.screen.scale } } public override func willMoveToSuperview(newSuperview: UIView?) { if newSuperview == nil && isAnimating() { pauseAnimation() } } public override func prepareForInterfaceBuilder() { setInitialValues() refreshValues() checkAndSetIBColors() progressLayer.setNeedsDisplay() } private class KDCircularProgressViewLayer: CALayer { @NSManaged var angle: Int var radius: CGFloat! var startAngle: Int! var clockwise: Bool! var roundedCorners: Bool! var gradientRotateSpeed: CGFloat! var glowAmount: CGFloat! var glowMode: KDCircularProgressGlowMode! var progressThickness: CGFloat! var trackThickness: CGFloat! var trackColor: UIColor! var colorsArray: [UIColor]! { didSet { gradientCache = nil locationsCache = nil } } var gradientCache: CGGradientRef? var locationsCache: [CGFloat]? struct GlowConstants { static let sizeToGlowRatio: CGFloat = 0.00015 static func glowAmountForAngle(angle: Int, glowAmount: CGFloat, glowMode: KDCircularProgressGlowMode, size: CGFloat) -> CGFloat { switch glowMode { case .Forward: return CGFloat(angle) * size * sizeToGlowRatio * glowAmount case .Reverse: return CGFloat(360 - angle) * size * sizeToGlowRatio * glowAmount case .Constant: return 360 * size * sizeToGlowRatio * glowAmount default: return 0 } } } override class func needsDisplayForKey(key: String!) -> Bool { return key == "angle" ? true : super.needsDisplayForKey(key) } override init!(layer: AnyObject!) { super.init(layer: layer) let progressLayer = layer as! KDCircularProgressViewLayer radius = progressLayer.radius angle = progressLayer.angle startAngle = progressLayer.startAngle clockwise = progressLayer.clockwise roundedCorners = progressLayer.roundedCorners gradientRotateSpeed = progressLayer.gradientRotateSpeed glowAmount = progressLayer.glowAmount glowMode = progressLayer.glowMode progressThickness = progressLayer.progressThickness trackThickness = progressLayer.trackThickness trackColor = progressLayer.trackColor colorsArray = progressLayer.colorsArray } override init!() { super.init() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func drawInContext(ctx: CGContext!) { UIGraphicsPushContext(ctx) let rect = bounds let size = rect.size let trackLineWidth: CGFloat = radius * trackThickness let progressLineWidth = radius * progressThickness let arcRadius = max(radius - trackLineWidth/2, radius - progressLineWidth/2) CGContextAddArc(ctx, CGFloat(size.width/2.0), CGFloat(size.height/2.0), arcRadius, 0, CGFloat(M_PI * 2), 0) trackColor.set() CGContextSetLineWidth(ctx, trackLineWidth) CGContextSetLineCap(ctx, kCGLineCapButt) CGContextDrawPath(ctx, kCGPathStroke) UIGraphicsBeginImageContextWithOptions(size, false, 0.0) let imageCtx = UIGraphicsGetCurrentContext() let reducedAngle = UtilityFunctions.Mod(angle, range: 360, minMax: (0, 360)) let fromAngle = ConversionFunctions.DegreesToRadians(CGFloat(-startAngle)) let toAngle = ConversionFunctions.DegreesToRadians(CGFloat((clockwise == true ? -reducedAngle : reducedAngle) - startAngle)) CGContextAddArc(imageCtx, CGFloat(size.width/2.0),CGFloat(size.height/2.0), arcRadius, fromAngle, toAngle, clockwise == true ? 1 : 0) let glowValue = GlowConstants.glowAmountForAngle(reducedAngle, glowAmount: glowAmount, glowMode: glowMode, size: size.width) if glowValue > 0 { CGContextSetShadowWithColor(imageCtx, CGSizeZero, glowValue, UIColor.blackColor().CGColor) } CGContextSetLineCap(imageCtx, roundedCorners == true ? kCGLineCapRound : kCGLineCapButt) CGContextSetLineWidth(imageCtx, progressLineWidth) CGContextDrawPath(imageCtx, kCGPathStroke) let drawMask: CGImageRef = CGBitmapContextCreateImage(UIGraphicsGetCurrentContext()) UIGraphicsEndImageContext() CGContextSaveGState(ctx) CGContextClipToMask(ctx, bounds, drawMask) //Gradient - Fill if colorsArray.count > 1 { var componentsArray: [CGFloat] = [] let rgbColorsArray: [UIColor] = colorsArray.map {c in // Make sure every color in colors array is in RGB color space if CGColorGetNumberOfComponents(c.CGColor) == 2 { let whiteValue = CGColorGetComponents(c.CGColor)[0] return UIColor(red: whiteValue, green: whiteValue, blue: whiteValue, alpha: 1.0) } else { return c } } for color in rgbColorsArray { let colorComponents: UnsafePointer<CGFloat> = CGColorGetComponents(color.CGColor) componentsArray.extend([colorComponents[0],colorComponents[1],colorComponents[2],1.0]) } drawGradientWithContext(ctx, componentsArray: componentsArray) } else { if colorsArray.count == 1 { fillRectWithContext(ctx, color: colorsArray[0]) } else { fillRectWithContext(ctx, color: UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)) } } CGContextRestoreGState(ctx) UIGraphicsPopContext() } func fillRectWithContext(ctx: CGContext!, color: UIColor) { CGContextSetFillColorWithColor(ctx, color.CGColor) CGContextFillRect(ctx, bounds) } func drawGradientWithContext(ctx: CGContext!, componentsArray: [CGFloat]) { let baseSpace = CGColorSpaceCreateDeviceRGB() let locations = locationsCache ?? gradientLocationsFromColorCount(componentsArray.count/4, gradientWidth: bounds.size.width) let gradient: CGGradient if let g = self.gradientCache { gradient = g } else { let g = CGGradientCreateWithColorComponents(baseSpace, componentsArray, locations,componentsArray.count / 4) self.gradientCache = g gradient = g } let halfX = bounds.size.width/2.0 let floatPi = CGFloat(M_PI) let rotateSpeed = clockwise == true ? gradientRotateSpeed : gradientRotateSpeed * -1 let angleInRadians = ConversionFunctions.DegreesToRadians(rotateSpeed * CGFloat(angle) - 90) var oppositeAngle = angleInRadians > floatPi ? angleInRadians - floatPi : angleInRadians + floatPi let startPoint = CGPoint(x: (cos(angleInRadians) * halfX) + halfX, y: (sin(angleInRadians) * halfX) + halfX) let endPoint = CGPoint(x: (cos(oppositeAngle) * halfX) + halfX, y: (sin(oppositeAngle) * halfX) + halfX) CGContextDrawLinearGradient(ctx, gradient, startPoint, endPoint, 0) } func gradientLocationsFromColorCount(colorCount: Int, gradientWidth: CGFloat) -> [CGFloat] { if colorCount == 0 || gradientWidth == 0 { return [] } else { var locationsArray: [CGFloat] = [] let progressLineWidth = radius * progressThickness let firstPoint = gradientWidth/2 - (radius - progressLineWidth/2) let increment = (gradientWidth - (2*firstPoint))/CGFloat(colorCount - 1) for i in 0..<colorCount { locationsArray.append(firstPoint + (CGFloat(i) * increment)) } assert(locationsArray.count == colorCount, "color counts should be equal") let result = locationsArray.map { $0 / gradientWidth } locationsCache = result return result } } } }
mit
00f7b309287e8fba7c69dc6654d405d4
36.449024
145
0.596617
5.30547
false
false
false
false
bastienFalcou/ContactSync
ContactSyncing/Controllers/EntranceViewController.swift
1
1577
// // ViewController.swift // ContactSyncing // // Created by Bastien Falcou on 1/6/17. // Copyright © 2017 Bastien Falcou. All rights reserved. // import UIKit import ReactiveSwift import DataSource final class EntranceViewController: UIViewController { @IBOutlet private var tableView: UITableView! @IBOutlet private var removeAllContactsButton: UIButton! @IBOutlet private var syncingProgressView: UIProgressView! @IBOutlet private var syncingStatusLabel: UILabel! let viewModel = EntranceViewModel() let tableDataSource = TableViewDataSource() override func viewDidLoad() { super.viewDidLoad() ContactFetcher.shared.requestContactsPermission() self.tableDataSource.reuseIdentifierForItem = { _ in return ContactTableViewCellModel.reuseIdentifier } self.tableView.dataSource = self.tableDataSource self.tableView.delegate = self self.tableDataSource.tableView = self.tableView self.tableDataSource.dataSource.innerDataSource <~ self.viewModel.dataSource self.removeAllContactsButton.reactive.isEnabled <~ self.viewModel.isSyncing.map { !$0 } self.syncingStatusLabel.reactive.text <~ self.viewModel.isSyncing.map { $0 ? "Syncing in background" : "Inactive" } self.syncingProgressView.reactive.progress <~ self.viewModel.syncingProgress.map { Float($0) } } @IBAction func removeAllContactsButtonTapped(_ sender: AnyObject) { self.viewModel.removeAllContacts() } @IBAction func syncContactsButtonTapped(_ sender: AnyObject) { self.viewModel.syncContacts() } } extension EntranceViewController: UITableViewDelegate { }
mit
b95297fcd6fd9397ed2f0031fe8edd9b
28.735849
117
0.785533
4.169312
false
false
false
false
nkirby/Humber
_lib/HMCore/_src/Resolver/Resolver.swift
1
1270
// ======================================================= // HMCore // Nathaniel Kirby // ======================================================= import Foundation // ======================================================= public class ResolverContainer<Context: AnyObject> { public typealias ResolverBlock = ((Context) -> AnyObject?) private var blocks = [ResolverBlock]() public init() { } public func registerBuilder(block block: ResolverBlock) { self.blocks.append(block) } internal func build(context context: Context) -> [AnyObject] { return self.blocks.flatMap { $0(context) } } } // ======================================================= public class Resolver<Context: AnyObject>: NSObject { public typealias ResolverBlock = ((Context) -> AnyObject?) private var owned = [AnyObject]() public init(context: Context, container: ResolverContainer<Context>) { self.owned = container.build(context: context) super.init() } public func components<T: Any>(type: T.Type) -> [T] { return self.owned.flatMap { return ($0 as? T) } } public func component<T: Any>(type: T.Type) -> T? { return self.components(type).first } }
mit
5d6d67e8e52d771515eed8554f29104b
27.863636
74
0.513386
4.8659
false
false
false
false
bananafish911/SmartReceiptsiOS
SmartReceipts/Persistence/Helpers/Database+Trips.swift
1
1356
// // Database+Trips.swift // SmartReceipts // // Created by Jaanus Siim on 31/05/16. // Copyright © 2016 Will Baumann. All rights reserved. // import Foundation extension Database: RefreshTripPriceHandler { func createUpdatingAdapterForAllTrips() -> FetchedModelAdapter { let query = DatabaseQueryBuilder.selectAllStatement(forTable: TripsTable.Name) query?.order(by: TripsTable.Column.To, ascending: false) let adapter = FetchedModelAdapter(database: self) adapter.setQuery((query?.buildStatement())!, parameters: (query?.parameters())!) adapter.modelClass = WBTrip.self adapter.afterFetchHandler = { model, database in guard let trip = model as? WBTrip else { return } self.refreshPriceForTrip(trip, inDatabase: database) } adapter.fetch() return adapter } func tripWithName(_ name: String) -> WBTrip? { var trip: WBTrip? inDatabase() { database in trip = database.tripWithName(name) } return trip } func refreshPriceForTrip(_ trip: WBTrip) { inDatabase { (db) in self.refreshPriceForTrip(trip, inDatabase: db) } } }
agpl-3.0
1ddf2355b9fc8b91dc35c635422143c5
26.1
88
0.577122
4.640411
false
false
false
false
abavisg/BarsAroundMe
BarsAroundMe/BarsAroundMeTests/MockData.swift
1
7833
// // MockData.swift // BarsAroundMe // // Created by Giorgos Ampavis on 19/03/2017. // Copyright © 2017 Giorgos Ampavis. All rights reserved. // import Foundation import SwiftyJSON @testable import BarsAroundMe struct MockData{ //MARK - Places Around Location With 2 Data struct placesAroundLocationResponseWithData { static let responseData: [AnyHashable: Any] = [ "html_attributions" : [], "next_page_token" : "CoQCAAEAAFX5ePdqojtvmDuzuQb8uEH33-QB2Cvy9BVWDWOK4BGvL6ZXPVUOkyHNQjrnW2qHhwRnYW26s8mf5IiQMwPZ9ljyR1m3jwr0I090t5UhbenKZp48wT8kVA3Ozd72BKM_2ILMamoa7aBcbcDQW1-3ngfpORxLfpVZruSE2kPHKerWCK831SOoZr7AyWwEABPNJUggX2_ZiwzJXMnaW-u2k9rU6E0S0FVknu0PzNbOwaUUu36WeK5bivBvkjW2sJY8ImJapGArIFctY94GsoeAMbIh0rTqlbNKlm1HT7mh5HElxqkX3r6UxA1zmYJbrsI4TXjvnJowcwlyVU1VYVEmEc4SEDG8uriQcRCFiHJnVMTjjrsaFIho10Z2Pop3n41D7P-GWkMsu2BY", "results" : [ [ "geometry" : [ "location" : [ "lat" : -33.8627642, "lng" : 151.1951861 ], "viewport" : [ "northeast" : [ "lat" : -33.86172500000001, "lng" : 151.1958665302915 ], "southwest" : [ "lat" : -33.8658818, "lng" : 151.1931685697085 ] ] ], "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png", "id" : "05bf6e9aa18b35f174f5076c348ce8e91e328aba", "name" : "Flying Fish Restaurant & Bar", "opening_hours" : [ "exceptional_date" : [], "open_now" : false, "weekday_text" : [] ], "photos" : [ [ "height" : 3036, "html_attributions" : ["" ], "photo_reference" : "CoQBdwAAAK5zYjUHvEB34CQ5-nEHW72sQaSw3EG6yVZnGxw_szU1v3PRJoEAolaW7nyhoS3SZcQzUyT-ut7MYbrFnNYX3WqzPCIh9NE2heLrSiLXue4X3vDw3js61u5_kkaeiasyW4inGKZQWPAEKbK_UjVkq8rv272D-E6UbF9X_9iB9pUJEhD8t8CJ82o_l3RqF-0J_JXGGhRYkSWTwn0XRtxNS6bwonAkKtUtWg", "width" : 4048 ] ], "place_id" : "ChIJm7Ex8UmuEmsR37p4Hm0D0VI", "price_level" : 4, "rating" : 4.4, "reference" : "CmRRAAAAFkJuDar4iJpuEEErYY3tWMG9DpGOHrwK4Zv2kOXEcxSYQj655LGZu4sAMZRwvFzRvJXE8fiuJPjoYOmPcXhhvq4jPO8Ww6Vp20oMEPmTfQurlMe3GKhHctKeWYA2RI2HEhCT6RhxIRAXafiJyEABjpQ2GhRjtNQBIXlJoHZrWbrScBMgVkecBg", "scope" : "GOOGLE", "types" : [ "bar", "restaurant", "food", "point_of_interest", "establishment" ], "vicinity" : "Lower Deck, Jones Bay Wharf, 19-21 Pirrama Road, Pyrmont" ], [ "geometry" : [ "location" : [ "lat" : -33.8698537, "lng" : 151.1977208 ], "viewport" : [ "northeast" : [ "lat" : -33.8685348697085, "lng" : 151.1991237802915 ], "southwest" : [ "lat" : -33.8712328302915, "lng" : 151.1964258197085 ] ] ], "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/bar-71.png", "id" : "c2075046e4cb0763631f4d8a562f88fe8500ba25", "name" : "Pyrmont Bridge Hotel", "opening_hours" : [ "exceptional_date" : [], "open_now" : true, "weekday_text" : [] ], "photos" : [ [ "height" : 536, "html_attributions" : [ "" ], "photo_reference" : "CoQBdwAAAODHYS76RanHn1Wfa0cMePQz8MP44Twi7URRMIY_U3zYXXBZpH2cINqACL9gFgMN6CnyMlzTrLrWHcTwZHQYj_dfr2tc7P5AZDcqUCNvrOxnU9iEOs_X5an4WQhKlYNfKw66cNeITjY7quZiw3p35DVRdZiOsFs67f6cs0DuwTMEEhDGXyMNMTyzdGWpYI_dSJDdGhSgfjLxCdXGg5hQ9FdI2sPG48Zv0w", "width" : 800 ] ], "place_id" : "ChIJAzQBQzeuEmsRh4OdJApC4MU", "price_level" : 1, "rating" : 3.7, "reference" : "CmRSAAAAEXsRJxxzDVDUyzheGw_lQqZN8YPgei6VvBFaBvB7bMCj5RibzdHusQSA3X3j8746H-4SVUgBu4F-ibHAYOngz3T4nzpT6ez2fNMemYRqs_VJSFIArU0vmxYVqGc_IniEEhC4P5uf3KJ1pT7uJxONLJ_dGhQgUY5iOmeUvO3SzncxKkbb5dUvFA", "scope" : "GOOGLE", "types" : [ "bar", "point_of_interest", "establishment" ], "vicinity" : "96 Union Street, Pyrmont" ] ], "status" : "OK" ] private static let json1:JSON = ["name": "Flying Fish Restaurant & Bar", "id": "05bf6e9aa18b35f174f5076c348ce8e91e328aba", "place_id": "ChIJm7Ex8UmuEmsR37p4Hm0D0VI", "geometry" : ["location" : ["lat" : -33.8627642,"lng" : 151.1951861]] ] private static let place1:Place = Place(withJSON: json1) private static let json2:JSON = ["name": "Pyrmont Bridge Hotel", "id": "c2075046e4cb0763631f4d8a562f88fe8500ba25", "place_id": "ChIJAzQBQzeuEmsRh4OdJApC4MU", "geometry" : ["location" : ["lat" : -33.8627642,"lng" : 151.1951861]] ] private static let place2:Place = Place(withJSON: json2) static let places: [Place] = [place1, place2] } //MARK - Places Around Location With No Data struct placesAroundLocationResponseWithNoData { static let responseData: [AnyHashable: Any] = [ "html_attributions" : [], "next_page_token" : "CoQCAAEAAFX5ePdqojtvmDuzuQb8uEH33-QB2Cvy9BVWDWOK4BGvL6ZXPVUOkyHNQjrnW2qHhwRnYW26s8mf5IiQMwPZ9ljyR1m3jwr0I090t5UhbenKZp48wT8kVA3Ozd72BKM_2ILMamoa7aBcbcDQW1-3ngfpORxLfpVZruSE2kPHKerWCK831SOoZr7AyWwEABPNJUggX2_ZiwzJXMnaW-u2k9rU6E0S0FVknu0PzNbOwaUUu36WeK5bivBvkjW2sJY8ImJapGArIFctY94GsoeAMbIh0rTqlbNKlm1HT7mh5HElxqkX3r6UxA1zmYJbrsI4TXjvnJowcwlyVU1VYVEmEc4SEDG8uriQcRCFiHJnVMTjjrsaFIho10Z2Pop3n41D7P-GWkMsu2BY", "results" : [], "status" : "OK" ] static let places: [Place] = [Place]() } //MARK - Single Place private static let json:JSON = ["name": "Flying Fish Restaurant & Bar", "id": "05bf6e9aa18b35f174f5076c348ce8e91e328aba", "place_id": "ChIJm7Ex8UmuEmsR37p4Hm0D0VI", "geometry" : ["location" : ["lat" : -33.8627642,"lng" : 151.1951861]] ] static let place:Place = Place(withJSON: json) }
mit
6a2c5069b119edaec12737611d72f78c
50.86755
439
0.491318
3.154249
false
false
false
false
CartoDB/mobile-ios-samples
AdvancedMap.Swift/Feature Demo/Banner.swift
1
2022
// // Banner.swift // AdvancedMap.Swift // // Created by Aare Undo on 24/07/2017. // Copyright © 2017 CARTO. All rights reserved. // import Foundation import UIKit class Banner: AlertBaseView { let imageView = UIImageView() let label = UILabel() var rightItem: UIImageView? convenience init() { self.init(frame: CGRect.zero) backgroundColor = Colors.darkTransparentGray imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.image = UIImage(named: "banner_icon_info.png") addSubview(imageView) label.font = UIFont(name: "HelveticaNeue", size: 12) label.textAlignment = .center label.textColor = UIColor.white label.numberOfLines = 0 label.lineBreakMode = .byWordWrapping addSubview(label) } override func layoutSubviews() { let padding: CGFloat = frame.height / 4 var x = padding var y = padding var w = frame.height - 2 * padding var h = w imageView.frame = CGRect(x: x, y: y, width: w, height: h) if (rightItem != nil) { x = frame.width - (w + 2 * padding) rightItem?.frame = CGRect(x: x, y: y, width: w, height: h) } x += w + padding y = 0 w = frame.width - (2 * x) h = frame.height label.frame = CGRect(x: x, y: y, width: w, height: h) } func addRightItem(item: UIImageView) { rightItem = item addSubview(rightItem!) layoutSubviews() } func show(text: String) { label.text = text show() } func showInformation(text: String, autoclose: Bool) { show(text: text) if (autoclose) { Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.hide), userInfo: nil, repeats: false) } } }
bsd-2-clause
01332fd5ab56c0e456168cb2ee3195a7
24.2625
126
0.546264
4.309168
false
false
false
false
apple/swift
test/refactoring/ConvertToComputedProperty/basic.swift
23
2248
struct S { var field1 = 2 var field2 = "2" var field3 = String() static var field4 = 4 var y: Int! = 45 } class C { static var field1 = S() public var field2 = 2 private dynamic var field3 = 5 @available(macOS 10.12, *) private static dynamic var field4 = 4 let field5 = 5 } // RUN: %empty-directory(%t.result) // RUN: %refactor -convert-to-computed-property -source-filename %s -pos=2:3 -end-pos=2:17 > %t.result/L2-3.swift // RUN: diff -u %S/Outputs/basic/L2-3.swift.expected %t.result/L2-3.swift // RUN: %refactor -convert-to-computed-property -source-filename %s -pos=3:3 -end-pos=3:19 > %t.result/L3-3.swift // RUN: diff -u %S/Outputs/basic/L3-3.swift.expected %t.result/L3-3.swift // RUN: %refactor -convert-to-computed-property -source-filename %s -pos=4:3 -end-pos=4:24 > %t.result/L4-3.swift // RUN: diff -u %S/Outputs/basic/L4-3.swift.expected %t.result/L4-3.swift // RUN: %refactor -convert-to-computed-property -source-filename %s -pos=5:3 -end-pos=5:24 > %t.result/L5-3.swift // RUN: diff -u %S/Outputs/basic/L5-3.swift.expected %t.result/L5-3.swift // RUN: %refactor -convert-to-computed-property -source-filename %s -pos=6:3 -end-pos=6:19 > %t.result/L6-3.swift // RUN: diff -u %S/Outputs/basic/L6-3.swift.expected %t.result/L6-3.swift // RUN: %refactor -convert-to-computed-property -source-filename %s -pos=10:3 -end-pos=10:26 > %t.result/L10-3.swift // RUN: diff -u %S/Outputs/basic/L10-3.swift.expected %t.result/L10-3.swift // RUN: %refactor -convert-to-computed-property -source-filename %s -pos=11:3 -end-pos=11:24 > %t.result/L11-3.swift // RUN: diff -u %S/Outputs/basic/L11-3.swift.expected %t.result/L11-3.swift // RUN: %refactor -convert-to-computed-property -source-filename %s -pos=12:3 -end-pos=12:33 > %t.result/L12-3.swift // RUN: diff -u %S/Outputs/basic/L12-3.swift.expected %t.result/L12-3.swift // RUN: %refactor -convert-to-computed-property -source-filename %s -pos=13:3 -end-pos=13:67 > %t.result/L13-3.swift // RUN: diff -u %S/Outputs/basic/L13-3.swift.expected %t.result/L13-3.swift // RUN: %refactor -convert-to-computed-property -source-filename %s -pos=14:3 -end-pos=14:17 > %t.result/L14-3.swift // RUN: diff -u %S/Outputs/basic/L14-3.swift.expected %t.result/L14-3.swift
apache-2.0
03dd7e3bcf725c9eb8b0c120559bea00
46.829787
116
0.692171
2.47033
false
false
false
false
IFTTT/RazzleDazzle
Example/RazzleDazzleTests/RAZTranslationAnimationSpec.swift
1
2667
// // TranslationAnimationSpec.swift // RazzleDazzle // // Created by Laura Skelton on 6/17/15. // Copyright (c) 2015 IFTTT. All rights reserved. // import RazzleDazzle import Nimble import Quick class TranslationAnimationSpec: QuickSpec { override func spec() { var view: UIView! var animation: TranslationAnimation! beforeEach { view = UIView() animation = TranslationAnimation(view: view) } describe("TranslationAnimation") { it("should add and retrieve keyframes") { animation[2] = CGPoint(x: 1, y: 2) expect(animation[2].equalTo(CGPoint(x: 1, y: 2))).to(beTruthy()) } it("should add and retrieve negative keyframes") { animation[-2] = CGPoint(x: 1, y: 2) expect(animation[-2].equalTo(CGPoint(x: 1, y: 2))).to(beTruthy()) } it("should add and retrieve multiple keyframes") { animation[-2] = CGPoint(x: 1, y: 2) animation[2] = CGPoint(x: 3, y: 4) expect(animation[-2].equalTo(CGPoint(x: 1, y: 2))).to(beTruthy()) expect(animation[2].equalTo(CGPoint(x: 3, y: 4))).to(beTruthy()) } it("should return the first value for times before the start time") { animation[2] = CGPoint(x: 1, y: 2) animation[4] = CGPoint(x: 3, y: 4) expect(animation[1].equalTo(CGPoint(x: 1, y: 2))).to(beTruthy()) expect(animation[0].equalTo(CGPoint(x: 1, y: 2))).to(beTruthy()) } it("should return the last value for times after the end time") { animation[2] = CGPoint(x: 1, y: 2) animation[4] = CGPoint(x: 3, y: 4) expect(animation[5].equalTo(CGPoint(x: 3, y: 4))).to(beTruthy()) expect(animation[6].equalTo(CGPoint(x: 3, y: 4))).to(beTruthy()) } it("should apply changes to the view's translation transform") { animation[2] = CGPoint(x: 1, y: 2) animation[4] = CGPoint(x: 3, y: 4) animation.animate(2) expect(view.transform == CGAffineTransform(translationX: 1, y: 2)).to(beTruthy()) animation.animate(4) expect(view.transform == CGAffineTransform(translationX: 3, y: 4)).to(beTruthy()) } it("should do nothing if no keyframes have been set") { animation.animate(5) expect(view.transform == CGAffineTransform.identity).to(beTruthy()) } } } }
mit
bf8ffb393033af5f7bdddac6d7545d3e
40.671875
97
0.532808
4.034796
false
false
false
false
fgulan/letter-ml
project/LetterML/Frameworks/framework/Source/Operations/SphereRefraction.swift
9
661
public class SphereRefraction: BasicOperation { public var radius:Float = 0.25 { didSet { uniformSettings["radius"] = radius } } public var refractiveIndex:Float = 0.71 { didSet { uniformSettings["refractiveIndex"] = refractiveIndex } } public var center:Position = Position.center { didSet { uniformSettings["center"] = center } } public init() { super.init(fragmentShader:SphereRefractionFragmentShader, numberOfInputs:1) ({radius = 0.25})() ({refractiveIndex = 0.71})() ({center = Position.center})() self.backgroundColor = Color(red:0.0, green:0.0, blue:0.0, alpha:0.0) } }
mit
d8a36b787f43e646d99c922368709e95
43.066667
111
0.641452
4.055215
false
false
false
false
Joywii/RichLabel
Swift/RichLabel/KZLinkLabel.swift
2
23432
// // KZLinkLabel.swift // RichLabelDemo // // Created by joywii on 14/12/22. // Copyright (c) 2014年 joywii. All rights reserved. // import UIKit enum KZLinkType : UInt { case UserHandle = 1 //用户昵称 eg: @kingzwt case HashTag = 2 //内容标签 eg: #hello case URL = 3 //链接地址 eg: http://www.baidu.com case PhoneNumber = 4 //电话号码 eg: 13888888888 } enum KZLinkDetectionTypes : UInt8 { case UserHandle = 1 case HashTag = 2 case URL = 3 case PhoneNumber = 4 case None = 0 case All = 255 } struct KZLinkDetectionType : RawOptionSetType { typealias RawValue = UInt private var value: UInt = 0 init(_ value: UInt) { self.value = value } init(rawValue value: UInt) { self.value = value } init(nilLiteral: ()) { self.value = 0 } static var allZeros: KZLinkDetectionType { return self(0) } static func fromMask(raw: UInt) -> KZLinkDetectionType { return self(raw) } var rawValue: UInt { return self.value } static var None: KZLinkDetectionType { return self(0) } static var UserHandle: KZLinkDetectionType { return self(1 << 0) } static var HashTag: KZLinkDetectionType { return self(1 << 1) } static var URL: KZLinkDetectionType { return self(1 << 2) } static var PhoneNumber: KZLinkDetectionType { return self(1 << 2) } static var All: KZLinkDetectionType { return self(UInt.max) } } typealias KZLinkHandler = (linkType:KZLinkType, string:String, range:NSRange) -> () class KZLinkLabel: UILabel , NSLayoutManagerDelegate { var linkTapHandler:KZLinkHandler? var linkLongPressHandle:KZLinkHandler? var layoutManager:NSLayoutManager! var textContainer:NSTextContainer! var textStorage:NSTextStorage! var linkRanges:NSArray! var isTouchMoved:Bool? var automaticLinkDetectionEnabled:Bool? { didSet { self.updateTextStoreWithText() } } var linkDetectionType:KZLinkDetectionType? { didSet { self.updateTextStoreWithText() } } var linkColor:UIColor? { didSet { self.updateTextStoreWithText() } } var linkHightlightColor:UIColor? { didSet { self.updateTextStoreWithText() } } var linkBackgroundColor:UIColor? { didSet { self.updateTextStoreWithText() } } var selectedRange:NSRange? { willSet { if (self.selectedRange?.length > 0 && !NSEqualRanges(self.selectedRange!,newValue!)) { self.textStorage.removeAttribute(NSBackgroundColorAttributeName, range: self.selectedRange!) self.textStorage.addAttribute(NSForegroundColorAttributeName, value: self.linkColor!, range: self.selectedRange!) } if (newValue?.length > 0) { self.textStorage.addAttribute(NSBackgroundColorAttributeName, value: self.linkBackgroundColor!, range: newValue!) self.textStorage.addAttribute(NSForegroundColorAttributeName, value: self.linkHightlightColor!, range: newValue!) } } didSet { self.setNeedsDisplay() } } //属性 override var frame: CGRect { didSet { //self.textContainer.size = self.bounds.size } } override var bounds: CGRect { didSet { self.textContainer.size = self.bounds.size } } override var numberOfLines:Int { get { return super.numberOfLines } set { super.numberOfLines = newValue self.textContainer.maximumNumberOfLines = numberOfLines } } override var text:String? { get { return super.text } set { super.text = newValue var attributedText:NSAttributedString = NSAttributedString(string: newValue!, attributes:self.attributesFromProperties()) self.updateTextStoreWithAttributedString(attributedText) } } override var attributedText:NSAttributedString? { get { return super.attributedText } set { super.attributedText = newValue self.updateTextStoreWithAttributedString(newValue!) } } override func layoutSubviews() { super.layoutSubviews() self.textContainer.size = self.bounds.size } //初始化方法 override init(frame: CGRect) { super.init(frame: frame) self.setupTextSystem() } required init(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } func setupTextSystem() { self.textContainer = NSTextContainer() self.textContainer.lineFragmentPadding = 0 self.textContainer.maximumNumberOfLines = self.numberOfLines self.textContainer.lineBreakMode = self.lineBreakMode self.textContainer.size = self.frame.size self.layoutManager = NSLayoutManager() self.layoutManager.delegate = self self.layoutManager.addTextContainer(self.textContainer) self.textContainer.layoutManager = self.layoutManager self.userInteractionEnabled = true self.automaticLinkDetectionEnabled = true self.linkDetectionType = KZLinkDetectionType.All self.linkBackgroundColor = UIColor(white: 0.95, alpha: 1.0) self.linkColor = UIColor.blueColor() self.linkHightlightColor = UIColor.redColor() self.updateTextStoreWithText() var longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressLabel:") self.addGestureRecognizer(longPressGesture) //默认回调 self.linkTapHandler = { (linkType:KZLinkType, string:String, range:NSRange) -> () in NSLog("Link Tap Handler") } self.linkLongPressHandle = { (linkType:KZLinkType, string:String, range:NSRange) -> () in NSLog("Link Long Press Handler"); } } /* * linkType : 链接类型 * range : 链接区域 * link : 链接文本 */ func getLinkAtLocation(var location:CGPoint) -> Dictionary<String, AnyObject>? { if (self.textStorage.string.isEmpty) { return nil } var textOffset:CGPoint var glyphRange = self.layoutManager.glyphRangeForTextContainer(self.textContainer) textOffset = self.calcTextOffsetForGlyphRange(glyphRange) location.x -= textOffset.x location.y -= textOffset.y var touchedChar:Int = self.layoutManager.glyphIndexForPoint(location, inTextContainer: self.textContainer) var lineRange:NSRange = NSMakeRange(0, 0) var lineRect:CGRect = self.layoutManager .lineFragmentRectForGlyphAtIndex(touchedChar, effectiveRange: &lineRange) if (!CGRectContainsPoint(lineRect, location)) { return nil } for dictionary in linkRanges as [Dictionary<String, AnyObject>] { var rangeValue:NSValue = dictionary["range"] as NSValue var range:NSRange = rangeValue.rangeValue if (touchedChar >= range.location && touchedChar < (range.location + range.length)) { return dictionary } } return nil } func updateTextStoreWithText() { if (self.attributedText != nil) { self.updateTextStoreWithAttributedString(self.attributedText!) } else if (self.text != nil) { var attributeText:NSAttributedString = NSAttributedString(string: self.text!, attributes: self.attributesFromProperties()) self.updateTextStoreWithAttributedString(attributeText) } else { var attributeText:NSAttributedString = NSAttributedString(string: "", attributes: self.attributesFromProperties()) self.updateTextStoreWithAttributedString(attributeText) } self.setNeedsDisplay() } func updateTextStoreWithAttributedString(var attributedString:NSAttributedString) { var myAttributedString:NSAttributedString = attributedString if(attributedString.length != 0) { attributedString = KZLinkLabel.sanitizeAttributedString(attributedString) } if (self.automaticLinkDetectionEnabled! && (attributedString.length != 0)) { self.linkRanges = self.getRangesForLinks(attributedString) attributedString = self.addLinkAttributesToAttributedString(attributedString, linkRanges: self.linkRanges) } else { self.linkRanges = nil; } if (self.textStorage != nil) { self.textStorage.setAttributedString(attributedString) } else { self.textStorage = NSTextStorage(attributedString: attributedString) self.textStorage.addLayoutManager(self.layoutManager) self.layoutManager.textStorage = self.textStorage } } /* * 链接文本属性 */ func addLinkAttributesToAttributedString(string:NSAttributedString, linkRanges:NSArray) -> NSAttributedString { var attributedString:NSMutableAttributedString = NSMutableAttributedString(attributedString: string) var attributeDic:Dictionary<String,AnyObject> = Dictionary<String,AnyObject>() attributeDic.updateValue(self.linkColor!, forKey: NSForegroundColorAttributeName) for dictionary in linkRanges as [Dictionary<String, AnyObject>] { var rangeValue:NSValue = dictionary["range"] as NSValue var range:NSRange = rangeValue.rangeValue attributedString.addAttributes(attributeDic, range: range) } return attributedString } /* * 普通文本属性 */ func attributesFromProperties() -> NSDictionary { //阴影属性 var shadow:NSShadow = NSShadow(); if((self.shadowColor) != nil){ shadow.shadowColor = self.shadowColor shadow.shadowOffset = self.shadowOffset } else { shadow.shadowOffset = CGSizeMake(0, -1) shadow.shadowColor = nil } //颜色属性 var color:UIColor = self.textColor if(!self.enabled) { color = UIColor.lightGrayColor() } else { //color = self.highlightedTextColor } //段落属性 var paragraph:NSMutableParagraphStyle = NSMutableParagraphStyle() paragraph.alignment = self.textAlignment //属性字典 var attributes:Dictionary<String,AnyObject> = [ NSFontAttributeName : self.font, NSForegroundColorAttributeName : color, NSShadowAttributeName : shadow, NSParagraphStyleAttributeName : paragraph ] return attributes } /* * 修正换行模式 */ class func sanitizeAttributedString(attributedString:NSAttributedString) -> NSAttributedString { var range:NSRange = NSMakeRange(0, 0) var paragraphStyle:NSParagraphStyle? = attributedString.attribute(NSParagraphStyleAttributeName, atIndex: 0, effectiveRange:&range) as? NSParagraphStyle if(paragraphStyle == nil) { return attributedString } var mutableParagraphStyle:NSMutableParagraphStyle = paragraphStyle?.mutableCopy() as NSMutableParagraphStyle mutableParagraphStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping var restyled:NSMutableAttributedString = NSMutableAttributedString(attributedString: attributedString) restyled.addAttribute(NSParagraphStyleAttributeName, value: mutableParagraphStyle, range: NSMakeRange(0, restyled.length)) return restyled } /* * 可扩展部分,不同的Link类型 */ func getRangesForLinks(text:NSAttributedString) -> NSArray { var rangesForLinks:NSMutableArray = NSMutableArray() //用户昵称 if (self.linkDetectionType! & .UserHandle != nil) { rangesForLinks.addObjectsFromArray(self.getRangesForUserHandles(text.string)) } //内容标签 if (self.linkDetectionType! & .HashTag != nil) { rangesForLinks.addObjectsFromArray(self.getRangesForHashTags(text.string)) } //链接地址 if (self.linkDetectionType! & .URL != nil) { rangesForLinks.addObjectsFromArray(self.getRangesForURLs(text)) } //电话号码 if (self.linkDetectionType! & .PhoneNumber != nil) { rangesForLinks.addObjectsFromArray(self.getRangesForPhoneNumbers(text.string)) } //...... return rangesForLinks } /* * 所有用户昵称 */ func getRangesForUserHandles(text:NSString) -> NSArray { var rangesForUserHandles:NSMutableArray = NSMutableArray() var regex:NSRegularExpression = NSRegularExpression(pattern : "(?<!\\w)@([\\w\\_]+)?", options: nil, error: nil)! var matches:NSArray = regex.matchesInString(text, options: nil, range: NSMakeRange(0, text.length)) for match in matches { var matchRange = match.range var matchString:NSString = text.substringWithRange(matchRange) var dictionary:Dictionary<String, AnyObject> = [ "linkType" : NSNumber(unsignedLong: KZLinkType.UserHandle.rawValue), "range" : NSValue(range : matchRange), "link" : matchString ]; rangesForUserHandles.addObject(dictionary) } return rangesForUserHandles } /* * 所有内容标签 */ func getRangesForHashTags(text:NSString) -> NSArray { var rangesForHashTags:NSMutableArray = NSMutableArray() var regex:NSRegularExpression = NSRegularExpression(pattern : "(?<!\\w)#([\\w\\_]+)?", options: nil, error: nil)! var matches:NSArray = regex.matchesInString(text, options: nil, range: NSMakeRange(0, text.length)) for match in matches { var matchRange = match.range var matchString:NSString = text.substringWithRange(matchRange) var dictionary:Dictionary<String, AnyObject> = [ "linkType" : NSNumber(unsignedLong: KZLinkType.HashTag.rawValue), "range" : NSValue(range: matchRange), "link" : matchString ]; rangesForHashTags.addObject(dictionary) } return rangesForHashTags } /* * 所有链接地址 */ func getRangesForURLs(text:NSAttributedString) -> NSArray { var rangesForURLs:NSMutableArray = NSMutableArray() var detector:NSDataDetector? = NSDataDetector(types: NSTextCheckingType.Link.rawValue, error: nil) var plainText:NSString = text.string var matchs:NSArray = detector!.matchesInString(plainText, options: nil, range: NSMakeRange(0, text.length)) for match in matchs { var matchRange:NSRange = match.range var realURL:NSString? = text.attribute(NSLinkAttributeName, atIndex: 0, effectiveRange: nil) as NSString? if realURL == nil { realURL = plainText.substringWithRange(matchRange) } if (match.resultType == NSTextCheckingType.Link) { var dictionary:Dictionary<String, AnyObject> = [ "linkType" : NSNumber(unsignedLong: KZLinkType.URL.rawValue), "range" : NSValue(range : matchRange), "link" : realURL! ]; rangesForURLs.addObject(dictionary) } } return rangesForURLs } /* * 所有电话号码 */ func getRangesForPhoneNumbers(text:NSString) -> NSArray { var rangesForPhoneNumbers:NSMutableArray = NSMutableArray() var detector:NSDataDetector? = NSDataDetector(types: NSTextCheckingType.PhoneNumber.rawValue, error: nil) var matchs:NSArray = detector!.matchesInString(text, options: nil, range: NSMakeRange(0, text.length)) for match in matchs { var matchRange:NSRange = match.range var matchString:NSString = text.substringWithRange(matchRange) var dictionary:Dictionary<String, AnyObject> = [ "linkType" : NSNumber(unsignedLong: KZLinkType.PhoneNumber.rawValue), "range" : NSValue(range : matchRange), "link" : matchString ]; rangesForPhoneNumbers.addObject(dictionary) } return rangesForPhoneNumbers } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * 绘制文本相关方法 */ override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect { var savedTextContainerSize:CGSize = self.textContainer.size var savedTextContainerNumberOfLines:Int = self.textContainer.maximumNumberOfLines self.textContainer.size = bounds.size self.textContainer.maximumNumberOfLines = numberOfLines var textBounds:CGRect = CGRectZero SwiftTryCatch.try({ () -> Void in var glyphRange:NSRange = self.layoutManager.glyphRangeForTextContainer(self.textContainer) textBounds = self.layoutManager.boundingRectForGlyphRange(glyphRange, inTextContainer: self.textContainer) textBounds.origin = bounds.origin textBounds.size.width = CGFloat(ceilf(Float(textBounds.size.width))) textBounds.size.height = CGFloat(ceilf(Float(textBounds.size.height))) }, catch: { (error) -> Void in //handle error }, finally: { () -> Void in //close resources self.textContainer.size = savedTextContainerSize self.textContainer.maximumNumberOfLines = savedTextContainerNumberOfLines }) return textBounds } override func drawTextInRect(rect: CGRect) { var textOffset:CGPoint var glyphRange:NSRange = self.layoutManager.glyphRangeForTextContainer(self.textContainer) textOffset = self.calcTextOffsetForGlyphRange(glyphRange) self.layoutManager.drawBackgroundForGlyphRange(glyphRange, atPoint: textOffset) self.layoutManager.drawGlyphsForGlyphRange(glyphRange, atPoint: textOffset) } func calcTextOffsetForGlyphRange(glyphRange:NSRange) -> CGPoint { var textOffset:CGPoint = CGPointZero var textBounds:CGRect = self.layoutManager.boundingRectForGlyphRange(glyphRange, inTextContainer: self.textContainer) var paddingHeight:CGFloat = (self.bounds.size.height - textBounds.size.height) / 2.0 if (paddingHeight > 0) { textOffset.y = paddingHeight } return textOffset } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// func layoutManager(layoutManager: NSLayoutManager, shouldBreakLineByWordBeforeCharacterAtIndex charIndex: Int) -> Bool { for dictionary in linkRanges as [Dictionary<String, AnyObject>] { var rangeValue:NSValue = dictionary["range"] as NSValue var range:NSRange = rangeValue.rangeValue var linkTypeNum:NSNumber = dictionary["linkType"] as NSNumber //有可能初始化不了 var linkType:KZLinkType = KZLinkType(rawValue: linkTypeNum.unsignedLongValue)! if (linkType == .URL) { if ((charIndex > range.location) && charIndex <= (range.location + range.length)) { return false } } } return true } func longPressLabel(recognizer:UILongPressGestureRecognizer) { if (recognizer.view != self || (recognizer.state != UIGestureRecognizerState.Began)) { return } var location:CGPoint = recognizer.locationInView(self) var touchedLink:Dictionary<String, AnyObject>? = self.getLinkAtLocation(location) if (touchedLink != nil) { //range var rangeValue:NSValue = touchedLink!["range"] as NSValue var range:NSRange = rangeValue.rangeValue //link string var touchedSubstring:NSString = touchedLink!["link"] as NSString //link type var linkTypeNum:NSNumber = touchedLink!["linkType"] as NSNumber var linkType:KZLinkType = KZLinkType(rawValue: linkTypeNum.unsignedLongValue)! self.linkLongPressHandle!(linkType: linkType,string:touchedSubstring,range:range) } else { return } } /* * 触摸事件 */ override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { self.isTouchMoved = false var touchLocation:CGPoint = touches.anyObject()!.locationInView(self) var touchedLink:Dictionary<String, AnyObject>? = self.getLinkAtLocation(touchLocation) if (touchedLink != nil) { var rangeValue:NSValue = touchedLink!["range"] as NSValue var range:NSRange = rangeValue.rangeValue self.selectedRange = range } else { super.touchesBegan(touches, withEvent: event) } } override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { super.touchesMoved(touches, withEvent: event) self.isTouchMoved = true } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { super.touchesEnded(touches, withEvent: event) if (self.isTouchMoved!) { self.selectedRange = NSMakeRange(0, 0) return } var touchLocation:CGPoint = touches.anyObject()!.locationInView(self) var touchedLink:Dictionary<String, AnyObject>? = self.getLinkAtLocation(touchLocation) if (touchedLink != nil) { //range var rangeValue:NSValue = touchedLink!["range"] as NSValue var range:NSRange = rangeValue.rangeValue //link string var touchedSubstring:NSString = touchedLink!["link"] as NSString //link type var linkTypeNum:NSNumber = touchedLink!["linkType"] as NSNumber var linkType:KZLinkType = KZLinkType(rawValue: linkTypeNum.unsignedLongValue)! self.linkTapHandler!(linkType: linkType,string:touchedSubstring,range:range) } else { super.touchesBegan(touches, withEvent: event) } self.selectedRange = NSMakeRange(0, 0) } override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) { super.touchesCancelled(touches, withEvent: event) self.selectedRange = NSMakeRange(0, 0) } }
mit
8f9b6599a09993ce00da39c4a6c6b884
38.766323
160
0.618951
5.136263
false
false
false
false
yaobanglin/viossvc
viossvc/Scenes/User/ServerSuccessController.swift
2
958
// // ServerSuccessController.swift // viossvc // // Created by 木柳 on 2016/12/1. // Copyright © 2016年 com.yundian. All rights reserved. // import UIKit class ServerSuccessController: UIViewController { @IBOutlet weak var iconImage: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subTitleLabel: UILabel! //MARK: --LIFECYCLE override func viewDidLoad() { super.viewDidLoad() iconImage.layer.cornerRadius = 40 iconImage.layer.masksToBounds = true subTitleLabel.text = "我们会在一个工作日内通过审 \n核,审核完毕后我们会通过短 \n信进行通知" navigationItem.backBarButtonItem = nil navigationItem.hidesBackButton = true } @IBAction func finishItemTapped(sender: AnyObject) { navigationController?.popToViewController((navigationController?.viewControllers[1])!, animated: true) } }
apache-2.0
f03a6336d76b8c5c9f790baac681711f
27.741935
110
0.684624
4.432836
false
false
false
false
tardieu/swift
validation-test/stdlib/HashingAvalanche.swift
28
1680
// RUN: %target-build-swift -Xfrontend -disable-access-control -module-name a %s -o %t.out -O // RUN: %target-run %t.out // REQUIRES: executable_test import SwiftPrivate import StdlibUnittest var HashingTestSuite = TestSuite("Hashing") func avalancheTest( _ bits: Int, _ hashUnderTest: @escaping (UInt64) -> UInt64, _ pValue: Double ) { let testsInBatch = 100000 let testData = randArray64(testsInBatch) let testDataHashed = Array(testData.lazy.map { hashUnderTest($0) }) for inputBit in 0..<bits { // Using an array here makes the test too slow. var bitFlips = UnsafeMutablePointer<Int>.allocate(capacity: bits) for i in 0..<bits { bitFlips[i] = 0 } for i in testData.indices { let inputA = testData[i] let outputA = testDataHashed[i] let inputB = inputA ^ (1 << UInt64(inputBit)) let outputB = hashUnderTest(inputB) var delta = outputA ^ outputB for outputBit in 0..<bits { if delta & 1 == 1 { bitFlips[outputBit] += 1 } delta = delta >> 1 } } for outputBit in 0..<bits { expectTrue( chiSquaredUniform2(testsInBatch, bitFlips[outputBit], pValue), "inputBit: \(inputBit), outputBit: \(outputBit)") } bitFlips.deallocate(capacity: bits) } } // White-box testing: assume that the other N-bit to N-bit mixing functions // just dispatch to these. (Avalanche test is relatively expensive.) HashingTestSuite.test("_mixUInt64/avalanche") { avalancheTest(64, _mixUInt64, 0.02) } HashingTestSuite.test("_mixUInt32/avalanche") { avalancheTest(32, { UInt64(_mixUInt32(UInt32($0 & 0xffff_ffff))) }, 0.02) } runAllTests()
apache-2.0
190e315dcc513a4bf515d1387d81bdd2
27.474576
93
0.656548
3.5
false
true
false
false
Ming-Lau/DouyuTV
DouyuTV/DouyuTV/Classes/Main/View/CollectionBaseCell.swift
1
1035
// // CollectionBaseCell.swift // DouyuTV // // Created by 刘明 on 16/11/1. // Copyright © 2016年 刘明. All rights reserved. // import UIKit class CollectionBaseCell: UICollectionViewCell { //昵称 @IBOutlet weak var nameLable: UILabel! //图片 @IBOutlet weak var iconImage: UIImageView! //在线人数 @IBOutlet weak var onLineBtn: UIButton! var anchor :AnchorModel?{ didSet{ guard let anchor = anchor else { return } //设置在线人数 var onLineStr : String = "" if anchor.online >= 10000 { onLineStr = "\(anchor.online/10000)万在线" }else{ onLineStr = "\(anchor.online)在线" } onLineBtn.setTitle(onLineStr, for: .normal) //设置名字 nameLable.text = anchor.nickname //icon let url = URL(string: anchor.vertical_src) iconImage.kf.setImage(with: url) } } }
mit
5fae1f7550be9e073d3c695696d67791
24.736842
55
0.535787
4.38565
false
false
false
false
adib/Core-ML-Playgrounds
Photo-Explorations/EnlargeImages.playground/Pages/Test Enlarge.xcplaygroundpage/Contents.swift
1
1854
/*: # Enlarge Image This playground is a proof-of-concept to enlarge images using an ML Model. It's a port of [waifu2x-ios](https://github.com/imxieyi/waifu2x-ios/tree/master/waifu2x) to macOS / AppKit. */ import Foundation import AppKit func CGImage(nsImage: NSImage) -> CGImage { let startTime = Date.timeIntervalSinceReferenceDate let imageSize = nsImage.size let width = Int(ceil(imageSize.width)) let height = Int(ceil(imageSize.height)); let bitsPerComponent = 8 let componentsPerPixel = 4 let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipLast.rawValue) let colorSpace = CGColorSpace(name: CGColorSpace.sRGB)! let bitmapContext = CGContext(data:nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: componentsPerPixel * width,space: colorSpace, bitmapInfo:bitmapInfo.rawValue)! let graphicsContext = NSGraphicsContext(cgContext:bitmapContext, flipped:false) let oldContext = NSGraphicsContext.current defer { NSGraphicsContext.current = oldContext } NSGraphicsContext.current = graphicsContext nsImage.draw(in: NSRect(x: 0, y: 0, width: width, height: height)) let cgImage = bitmapContext.makeImage()! let endTime = Date.timeIntervalSinceReferenceDate print("convert-nsimage-to-cgimage: ",endTime - startTime) return cgImage } extension NSImage { convenience init(cgImage:CGImage) { self.init(cgImage: cgImage, size: NSMakeSize(CGFloat(cgImage.width), CGFloat(cgImage.height))) } } let image = #imageLiteral(resourceName: "Hollister_Municipal_Airport_photo_D_Ramey_Logan.jpg") let cgImage = CGImage(nsImage: image) NSImage(cgImage:cgImage) let model = Model.photo_noise1_scale2x let enlargedImage = cgImage.run(model: model,scale: 2 )! let resultImage = NSImage(cgImage: enlargedImage)
bsd-3-clause
5cc0eef2549b25708a2585209d2d1336
36.836735
201
0.745955
4.056893
false
false
false
false
lorentey/swift
test/decl/overload.swift
2
22430
// RUN: %target-typecheck-verify-swift var var_redecl1: Int // expected-note {{previously declared here}} var_redecl1 = 0 var var_redecl1: UInt // expected-error {{invalid redeclaration of 'var_redecl1'}} var var_redecl2: Int // expected-note {{previously declared here}} // expected-note@-1 {{found this candidate}} var_redecl2 = 0 // expected-error {{ambiguous use of 'var_redecl2'}} var var_redecl2: Int // expected-error {{invalid redeclaration of 'var_redecl2'}} // expected-note@-1 {{found this candidate}} var var_redecl3: (Int) -> () { get {} } // expected-note {{previously declared here}} var var_redecl3: () -> () { get {} } // expected-error {{invalid redeclaration of 'var_redecl3'}} var var_redecl4: Int // expected-note 2{{previously declared here}} var var_redecl4: Int // expected-error {{invalid redeclaration of 'var_redecl4'}} var var_redecl4: Int // expected-error {{invalid redeclaration of 'var_redecl4'}} let let_redecl1: Int = 0 // expected-note {{previously declared here}} let let_redecl1: UInt = 0 // expected-error {{invalid redeclaration}} let let_redecl2: Int = 0 // expected-note {{previously declared here}} let let_redecl2: Int = 0 // expected-error {{invalid redeclaration}} class class_redecl1 {} // expected-note {{previously declared here}} class class_redecl1 {} // expected-error {{invalid redeclaration}} class class_redecl2<T> {} // expected-note {{previously declared here}} class class_redecl2 {} // expected-error {{invalid redeclaration}} class class_redecl3 {} // expected-note {{previously declared here}} class class_redecl3<T> {} // expected-error {{invalid redeclaration}} struct struct_redecl1 {} // expected-note {{previously declared here}} struct struct_redecl1 {} // expected-error {{invalid redeclaration}} struct struct_redecl2<T> {} // expected-note {{previously declared here}} struct struct_redecl2 {} // expected-error {{invalid redeclaration}} struct struct_redecl3 {} // expected-note {{previously declared here}} struct struct_redecl3<T> {} // expected-error {{invalid redeclaration}} enum enum_redecl1 {} // expected-note {{previously declared here}} enum enum_redecl1 {} // expected-error {{invalid redeclaration}} enum enum_redecl2<T> {} // expected-note {{previously declared here}} enum enum_redecl2 {} // expected-error {{invalid redeclaration}} enum enum_redecl3 {} // expected-note {{previously declared here}} enum enum_redecl3<T> {} // expected-error {{invalid redeclaration}} protocol protocol_redecl1 {} // expected-note {{previously declared here}} protocol protocol_redecl1 {} // expected-error {{invalid redeclaration}} typealias typealias_redecl1 = Int // expected-note {{previously declared here}} typealias typealias_redecl1 = Int // expected-error {{invalid redeclaration}} typealias typealias_redecl2 = Int // expected-note {{previously declared here}} typealias typealias_redecl2 = UInt // expected-error {{invalid redeclaration}} var mixed_redecl1: Int // expected-note {{previously declared here}} class mixed_redecl1 {} // expected-error {{invalid redeclaration}} class mixed_redecl1a : mixed_redecl1 {} class mixed_redecl2 {} // expected-note {{previously declared here}} struct mixed_redecl2 {} // expected-error {{invalid redeclaration}} class mixed_redecl3 {} // expected-note {{previously declared here}} // expected-note @-1 2{{found this candidate}} enum mixed_redecl3 {} // expected-error {{invalid redeclaration}} // expected-note @-1 2{{found this candidate}} enum mixed_redecl3a : mixed_redecl3 {} // expected-error {{'mixed_redecl3' is ambiguous for type lookup in this context}} // expected-error@-1 {{an enum with no cases cannot declare a raw type}} // expected-error@-2 {{raw type}} class mixed_redecl3b : mixed_redecl3 {} // expected-error {{'mixed_redecl3' is ambiguous for type lookup in this context}} class mixed_redecl4 {} // expected-note {{previously declared here}} // expected-note@-1{{found this candidate}} protocol mixed_redecl4 {} // expected-error {{invalid redeclaration}} // expected-note@-1{{found this candidate}} protocol mixed_redecl4a : mixed_redecl4 {} // expected-error {{'mixed_redecl4' is ambiguous for type lookup in this context}} class mixed_redecl5 {} // expected-note {{previously declared here}} typealias mixed_redecl5 = Int // expected-error {{invalid redeclaration}} typealias mixed_redecl5a = mixed_redecl5 func mixed_redecl6() {} // expected-note {{'mixed_redecl6()' previously declared here}} var mixed_redecl6: Int // expected-error {{invalid redeclaration of 'mixed_redecl6'}} var mixed_redecl7: Int // expected-note {{'mixed_redecl7' previously declared here}} func mixed_redecl7() {} // expected-error {{invalid redeclaration of 'mixed_redecl7()'}} func mixed_redecl8() {} // expected-note {{previously declared here}} class mixed_redecl8 {} // expected-error {{invalid redeclaration}} class mixed_redecl8a : mixed_redecl8 {} class mixed_redecl9 {} // expected-note {{previously declared here}} func mixed_redecl9() {} // expected-error {{invalid redeclaration}} func mixed_redecl10() {} // expected-note {{previously declared here}} typealias mixed_redecl10 = Int // expected-error {{invalid redeclaration}} typealias mixed_redecl11 = Int // expected-note {{previously declared here}} func mixed_redecl11() {} // expected-error {{invalid redeclaration}} var mixed_redecl12: Int // expected-note {{previously declared here}} let mixed_redecl12: Int = 0 // expected-error {{invalid redeclaration}} let mixed_redecl13: Int = 0 // expected-note {{previously declared here}} var mixed_redecl13: Int // expected-error {{invalid redeclaration}} var mixed_redecl14 : Int func mixed_redecl14(_ i: Int) {} // okay func mixed_redecl15(_ i: Int) {} var mixed_redecl15 : Int // okay var mixed_redecl16: Int // expected-note {{'mixed_redecl16' previously declared here}} func mixed_redecl16() -> Int {} // expected-error {{invalid redeclaration of 'mixed_redecl16()'}} class OverloadStaticFromBase { class func create() {} } class OverloadStaticFromBase_Derived : OverloadStaticFromBase { class func create(_ x: Int) {} } // Overloading of functions based on argument names only. func ovl_argname1(x: Int, y: Int) { } func ovl_argname1(y: Int, x: Int) { } func ovl_argname1(a: Int, b: Int) { } // Overloading with generics protocol P1 { } protocol P2 { } func ovl_generic1<T: P1 & P2>(t: T) { } // expected-note{{previous}} func ovl_generic1<U: P1 & P2>(t: U) { } // expected-error{{invalid redeclaration of 'ovl_generic1(t:)'}} func ovl_generic2<T : P1>(_: T) {} // expected-note{{previously declared here}} func ovl_generic2<T : P1>(_: T) {} // expected-error{{invalid redeclaration of 'ovl_generic2'}} func ovl_generic3<T : P1>(_ x: T) {} // OK func ovl_generic3<T : P2>(_ x: T) {} // OK // Redeclarations within nominal types struct X { } struct Y { } struct Z { var a : X, // expected-note{{previously declared here}} a : Y // expected-error{{invalid redeclaration of 'a'}} var b: X // expected-note{{previously declared here}} } extension Z { var b: Int { return 0 } // expected-error{{invalid redeclaration of 'b'}} } struct X1 { func f(a : Int) {} // expected-note{{previously declared here}} func f(a : Int) {} // expected-error{{invalid redeclaration of 'f(a:)'}} } struct X2 { func f(a : Int) {} // expected-note{{previously declared here}} typealias IntAlias = Int func f(a : IntAlias) {} // expected-error{{invalid redeclaration of 'f(a:)'}} } struct X3 { func f(a : Int) {} // expected-note{{previously declared here}} func f(a : IntAlias) {} // expected-error{{invalid redeclaration of 'f(a:)'}} typealias IntAlias = Int } struct X4 { typealias i = Int // expected-note@-1 {{previously declared}} // expected-note@-2 {{previously declared}} static var i: String { return "" } // expected-error{{invalid redeclaration of 'i'}} static func i() {} // expected-error{{invalid redeclaration of 'i()'}} static var j: Int { return 0 } // expected-note{{previously declared here}} struct j {} // expected-error{{invalid redeclaration of 'j'}} var i: Int { return 0 } func i(x: String) {} } extension X4 { static var k: Int { return 0 } // expected-note{{previously declared here}} struct k {} // expected-error{{invalid redeclaration of 'k'}} } // Generic Placeholders struct X5<t, u, v> { static var t: Int { return 0 } static func u() {} typealias v = String func foo<t>(_ t: t) { let t = t _ = t } } struct X6<T> { var foo: T // expected-note{{previously declared here}} func foo() -> T {} // expected-error{{invalid redeclaration of 'foo()'}} func foo(_ x: T) {} static var j: Int { return 0 } // expected-note{{previously declared here}} struct j {} // expected-error{{invalid redeclaration of 'j'}} } extension X6 { var k: Int { return 0 } // expected-note{{previously declared here}} func k() // expected-error@-1{{invalid redeclaration of 'k()'}} // expected-error@-2{{expected '{' in body of function declaration}} } // Subscripting struct Subscript1 { subscript (a: Int) -> Int { get { return a } } subscript (a: Float) -> Int { get { return Int(a) } } subscript (a: Int) -> Float { get { return Float(a) } } } struct Subscript2 { subscript (a: Int) -> Int { // expected-note{{previously declared here}} get { return a } } subscript (a: Int) -> Int { // expected-error{{invalid redeclaration of 'subscript(_:)'}} get { return a } } var `subscript`: Int { return 0 } } struct Subscript3 { typealias `subscript` = Int // expected-note{{previously declared here}} static func `subscript`(x: Int) -> String { return "" } // expected-error{{invalid redeclaration of 'subscript(x:)'}} func `subscript`(x: Int) -> String { return "" } subscript(x x: Int) -> String { return "" } } struct Subscript4 { subscript(f: @escaping (Int) -> Int) -> Int { // expected-note{{previously declared here}} get { return f(0) } } subscript(f: (Int) -> Int) -> Int { // expected-error{{invalid redeclaration of 'subscript(_:)'}} get { return f(0) } } } struct GenericSubscripts { subscript<T>(x: T) -> Int { return 0 } // expected-note{{previously declared here}} } extension GenericSubscripts { subscript<U>(x: U) -> Int { return 0 } // expected-error{{invalid redeclaration of 'subscript(_:)'}} subscript<T, U>(x: T) -> U { fatalError() } subscript<T>(x: T) -> T { fatalError() } subscript(x: Int) -> Int { return 0 } } struct GenericSubscripts2<T> { subscript(x: T) -> Int { return 0 } // expected-note{{previously declared here}} } extension GenericSubscripts2 { subscript(x: T) -> Int { return 0 } // expected-error{{invalid redeclaration of 'subscript(_:)'}} subscript<U>(x: U) -> Int { return 0 } subscript(x: T) -> T { fatalError() } subscript<U>(x: T) -> U { fatalError() } subscript<U, V>(x: U) -> V { fatalError() } subscript(x: Int) -> Int { return 0 } } struct GenericSubscripts3<T> { subscript<U>(x: T) -> U { fatalError() } // expected-note{{previously declared here}} } extension GenericSubscripts3 { subscript<U>(x: T) -> U { fatalError() } // expected-error{{invalid redeclaration of 'subscript(_:)'}} subscript<U, V>(x: U) -> V { fatalError() } subscript<U>(x: U) -> U { fatalError() } subscript(x: Int) -> Int { return 0 } } // Initializers class Initializers { init(x: Int) { } // expected-note{{previously declared here}} convenience init(x: Int) { } // expected-error{{invalid redeclaration of 'init(x:)'}} static func `init`(x: Int) -> Initializers { fatalError() } func `init`(x: Int) -> Initializers { fatalError() } } // Default arguments // <rdar://problem/13338746> func sub(x:Int64, y:Int64) -> Int64 { return x - y } // expected-note 2{{'sub(x:y:)' previously declared here}} func sub(x:Int64, y:Int64 = 1) -> Int64 { return x - y } // expected-error{{invalid redeclaration of 'sub(x:y:)'}} func sub(x:Int64 = 0, y:Int64 = 1) -> Int64 { return x - y } // expected-error{{invalid redeclaration of 'sub(x:y:)'}} // <rdar://problem/13783231> struct NoneType { } func != <T>(lhs : T, rhs : NoneType) -> Bool { // expected-note{{'!=' previously declared here}} return true } func != <T>(lhs : T, rhs : NoneType) -> Bool { // expected-error{{invalid redeclaration of '!=}} return true } // throws func throwsFunc(code: Int) { } // expected-note{{previously declared}} func throwsFunc(code: Int) throws { } // expected-error{{invalid redeclaration of 'throwsFunc(code:)'}} // throws function parameter -- OK func throwsFuncParam(_ fn: () throws -> ()) { } func throwsFuncParam(_ fn: () -> ()) { } // @escaping func escaping(x: @escaping (Int) -> Int) { } // expected-note{{previously declared}} func escaping(x: (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping(x:)'}} func escaping(_ x: @escaping (Int) -> Int) { } // expected-note{{previously declared}} func escaping(_ x: (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping'}} func escaping(a: Int, _ x: @escaping (Int) -> Int) { } // expected-note{{previously declared}} func escaping(a: Int, _ x: (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping(a:_:)'}} func escaping(_ a: (Int) -> Int, _ x: (Int) -> Int) { } // expected-note@-1{{previously declared}} // expected-note@-2{{previously declared}} // expected-note@-3{{previously declared}} func escaping(_ a: (Int) -> Int, _ x: @escaping (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping'}} func escaping(_ a: @escaping (Int) -> Int, _ x: (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping'}} func escaping(_ a: @escaping (Int) -> Int, _ x: @escaping (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping'}} struct Escaping { func escaping(_ x: @escaping (Int) -> Int) { } // expected-note{{previously declared}} func escaping(_ x: (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping'}} func escaping(a: Int, _ x: @escaping (Int) -> Int) { } // expected-note{{previously declared}} func escaping(a: Int, _ x: (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping(a:_:)'}} } // @autoclosure func autoclosure(f: () -> Int) { } func autoclosure(f: @autoclosure () -> Int) { } // @_nonEphemeral func nonEphemeral(x: UnsafeMutableRawPointer) {} // expected-note {{'nonEphemeral(x:)' previously declared here}} func nonEphemeral(@_nonEphemeral x: UnsafeMutableRawPointer) {} // expected-error {{invalid redeclaration of 'nonEphemeral(x:)'}} // inout func inout2(x: Int) { } func inout2(x: inout Int) { } // optionals func optional(x: Int?) { } // expected-note{{previously declared}} func optional(x: Int!) { } // expected-error{{invalid redeclaration of 'optional(x:)'}} func optionalInOut(x: inout Int?) { } // expected-note{{previously declared}} func optionalInOut(x: inout Int!) { } // expected-error{{invalid redeclaration of 'optionalInOut(x:)}} class optionalOverloads { class func optionalInOut(x: inout Int?) { } // expected-note{{previously declared}} class func optionalInOut(x: inout Int!) { } // expected-error{{invalid redeclaration of 'optionalInOut(x:)'}} func optionalInOut(x: inout Int?) { } // expected-note{{previously declared}} func optionalInOut(x: inout Int!) { } // expected-error{{invalid redeclaration of 'optionalInOut(x:)}} } func optional_3() -> Int? { } // expected-note{{previously declared}} func optional_3() -> Int! { } // expected-error{{invalid redeclaration of 'optional_3()'}} // mutating / nonmutating protocol ProtocolWithMutating { mutating func test1() // expected-note {{previously declared}} func test1() // expected-error{{invalid redeclaration of 'test1()'}} mutating func test2(_ a: Int?) // expected-note {{previously declared}} func test2(_ a: Int!) // expected-error{{invalid redeclaration of 'test2'}} mutating static func classTest1() // expected-error {{static functions must not be declared mutating}} {{3-12=}} expected-note {{previously declared}} static func classTest1() // expected-error{{invalid redeclaration of 'classTest1()'}} } struct StructWithMutating { mutating func test1() { } // expected-note {{previously declared}} func test1() { } // expected-error{{invalid redeclaration of 'test1()'}} mutating func test2(_ a: Int?) { } // expected-note {{previously declared}} func test2(_ a: Int!) { } // expected-error{{invalid redeclaration of 'test2'}} } enum EnumWithMutating { mutating func test1() { } // expected-note {{previously declared}} func test1() { } // expected-error{{invalid redeclaration of 'test1()'}} } protocol ProtocolWithAssociatedTypes { associatedtype t // expected-note@-1 {{previously declared}} // expected-note@-2 {{previously declared}} static var t: Int { get } // expected-error{{invalid redeclaration of 't'}} static func t() // expected-error{{invalid redeclaration of 't()'}} associatedtype u associatedtype v // Instance requirements are fine. var t: Int { get } func u() mutating func v() associatedtype W func foo<W>(_ x: W) } // <rdar://problem/21783216> Ban members named Type and Protocol without backticks // https://twitter.com/jadengeller/status/619989059046240256 protocol r21783216a { // expected-error @+2 {{type member must not be named 'Type', since it would conflict with the 'foo.Type' expression}} // expected-note @+1 {{if this name is unavoidable, use backticks to escape it}} {{18-22=`Type`}} associatedtype Type // expected-error @+2 {{type member must not be named 'Protocol', since it would conflict with the 'foo.Protocol' expression}} // expected-note @+1 {{if this name is unavoidable, use backticks to escape it}} {{18-26=`Protocol`}} associatedtype Protocol } protocol r21783216b { associatedtype `Type` // ok associatedtype `Protocol` // ok } struct SR7249<T> { var x: T { fatalError() } // expected-note {{previously declared}} var y: Int // expected-note {{previously declared}} var z: Int // expected-note {{previously declared}} } extension SR7249 { var x: Int { fatalError() } // expected-warning{{redeclaration of 'x' is deprecated and will be an error in Swift 5}} var y: T { fatalError() } // expected-warning{{redeclaration of 'y' is deprecated and will be an error in Swift 5}} var z: Int { fatalError() } // expected-error{{invalid redeclaration of 'z'}} } // A constrained extension is okay. extension SR7249 where T : P1 { var x: Int { fatalError() } var y: T { fatalError() } var z: Int { fatalError() } } protocol P3 { var i: Int { get } subscript(i: Int) -> String { get } } extension P3 { var i: Int { return 0 } subscript(i: Int) -> String { return "" } } struct SR7250<T> : P3 {} extension SR7250 where T : P3 { var i: Int { return 0 } subscript(i: Int) -> String { return "" } } // SR-10084 struct SR_10084_S { let name: String } enum SR_10084_E { case foo(SR_10084_S) // expected-note {{'foo' previously declared here}} static func foo(_ name: String) -> SR_10084_E { // Okay return .foo(SR_10084_S(name: name)) } func foo(_ name: Bool) -> SR_10084_E { // Okay return .foo(SR_10084_S(name: "Test")) } static func foo(_ value: SR_10084_S) -> SR_10084_E { // expected-error {{invalid redeclaration of 'foo'}} return .foo(value) } } enum SR_10084_E_1 { static func foo(_ name: String) -> SR_10084_E_1 { // Okay return .foo(SR_10084_S(name: name)) } static func foo(_ value: SR_10084_S) -> SR_10084_E_1 { // expected-note {{'foo' previously declared here}} return .foo(value) } case foo(SR_10084_S) // expected-error {{invalid redeclaration of 'foo'}} } enum SR_10084_E_2 { case fn(() -> Void) // expected-note {{'fn' previously declared here}} static func fn(_ x: @escaping () -> Void) -> SR_10084_E_2 { // expected-error {{invalid redeclaration of 'fn'}} fatalError() } static func fn(_ x: @escaping () -> Int) -> SR_10084_E_2 { // Okay fatalError() } static func fn(_ x: @escaping () -> Bool) -> SR_10084_E_2 { // Okay fatalError() } } // N.B. Redeclaration checks don't see this case because `protocol A` is invalid. enum SR_10084_E_3 { protocol A {} //expected-error {{protocol 'A' cannot be nested inside another declaration}} case A } enum SR_10084_E_4 { class B {} // expected-note {{'B' previously declared here}} case B // expected-error {{invalid redeclaration of 'B'}} } enum SR_10084_E_5 { struct C {} // expected-note {{'C' previously declared here}} case C // expected-error {{invalid redeclaration of 'C'}} } // N.B. Redeclaration checks don't see this case because `protocol D` is invalid. enum SR_10084_E_6 { case D protocol D {} //expected-error {{protocol 'D' cannot be nested inside another declaration}} } enum SR_10084_E_7 { case E // expected-note {{'E' previously declared here}} class E {} // expected-error {{invalid redeclaration of 'E'}} } enum SR_10084_E_8 { case F // expected-note {{'F' previously declared here}} struct F {} // expected-error {{invalid redeclaration of 'F'}} } enum SR_10084_E_9 { case A // expected-note {{'A' previously declared here}} static let A: SR_10084_E_9 = .A // expected-error {{invalid redeclaration of 'A'}} } enum SR_10084_E_10 { static let A: SR_10084_E_10 = .A // expected-note {{'A' previously declared here}} case A // expected-error {{invalid redeclaration of 'A'}} } enum SR_10084_E_11 { case A // expected-note {{'A' previously declared here}} static var A: SR_10084_E_11 = .A // expected-error {{invalid redeclaration of 'A'}} } enum SR_10084_E_12 { static var A: SR_10084_E_12 = .A // expected-note {{'A' previously declared here}} case A // expected-error {{invalid redeclaration of 'A'}} } enum SR_10084_E_13 { case X // expected-note {{'X' previously declared here}} struct X<T> {} // expected-error {{invalid redeclaration of 'X'}} } enum SR_10084_E_14 { struct X<T> {} // expected-note {{'X' previously declared here}} case X // expected-error {{invalid redeclaration of 'X'}} } enum SR_10084_E_15 { case Y // expected-note {{'Y' previously declared here}} typealias Y = Int // expected-error {{invalid redeclaration of 'Y'}} } enum SR_10084_E_16 { typealias Z = Int // expected-note {{'Z' previously declared here}} case Z // expected-error {{invalid redeclaration of 'Z'}} }
apache-2.0
26fba9841c0e082f7cacd47567ca6eb7
35.353323
152
0.670932
3.516776
false
false
false
false
lorentey/swift
test/SILOptimizer/definite_init_failable_initializers.swift
3
68119
// RUN: %target-swift-frontend -emit-sil %s | %FileCheck %s // High-level tests that DI handles early returns from failable and throwing // initializers properly. The main complication is conditional release of self // and stored properties. // FIXME: not all of the test cases have CHECKs. Hopefully the interesting cases // are fully covered, though. //// // Structs with failable initializers //// protocol Pachyderm { init() } class Canary : Pachyderm { required init() {} } // <rdar://problem/20941576> SILGen crash: Failable struct init cannot delegate to another failable initializer struct TrivialFailableStruct { init?(blah: ()) { } init?(wibble: ()) { self.init(blah: wibble) } } struct FailableStruct { let x, y: Canary init(noFail: ()) { x = Canary() y = Canary() } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers14FailableStructV24failBeforeInitializationACSgyt_tcfC // CHECK: bb0(%0 : $@thin FailableStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: return [[SELF]] init?(failBeforeInitialization: ()) { return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers14FailableStructV30failAfterPartialInitializationACSgyt_tcfC // CHECK: bb0(%0 : $@thin FailableStruct.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[CANARY:%.*]] = apply // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]] // CHECK-NEXT: store [[CANARY]] to [[X_ADDR]] // CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[X_ADDR]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: return [[SELF]] init?(failAfterPartialInitialization: ()) { x = Canary() return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers14FailableStructV27failAfterFullInitializationACSgyt_tcfC // CHECK: bb0 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[CANARY1:%.*]] = apply // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]] // CHECK-NEXT: store [[CANARY1]] to [[X_ADDR]] // CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct // CHECK: [[CANARY2:%.*]] = apply // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct // CHECK-NEXT: [[Y_ADDR:%.*]] = struct_element_addr [[WRITE]] // CHECK-NEXT: store [[CANARY2]] to [[Y_ADDR]] // CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: return [[NEW_SELF]] init?(failAfterFullInitialization: ()) { x = Canary() y = Canary() return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers14FailableStructV46failAfterWholeObjectInitializationByAssignmentACSgyt_tcfC // CHECK: bb0 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[CANARY]] = apply // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct // CHECK-NEXT: store [[CANARY]] to [[WRITE]] // CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[SELF_VALUE:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: return [[SELF_VALUE]] init?(failAfterWholeObjectInitializationByAssignment: ()) { self = FailableStruct(noFail: ()) return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers14FailableStructV46failAfterWholeObjectInitializationByDelegationACSgyt_tcfC // CHECK: bb0 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14FailableStructV6noFailACyt_tcfC // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%0) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: return [[NEW_SELF]] init?(failAfterWholeObjectInitializationByDelegation: ()) { self.init(noFail: ()) return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers14FailableStructV20failDuringDelegationACSgyt_tcfC // CHECK: bb0 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14FailableStructV24failBeforeInitializationACSgyt_tcfC // CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]](%0) // CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]] // CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]] // // CHECK: [[FAIL_BB]]: // CHECK-NEXT: release_value [[SELF_OPTIONAL]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<FailableStruct>) // // CHECK: [[SUCC_BB]]: // CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]] // CHECK-NEXT: retain_value [[SELF_VALUE]] // CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.some!enumelt.1, [[SELF_VALUE]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<FailableStruct>) // // CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<FailableStruct>) // CHECK-NEXT: return [[NEW_SELF]] // Optional to optional init?(failDuringDelegation: ()) { self.init(failBeforeInitialization: ()) } // IUO to optional init!(failDuringDelegation2: ()) { self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!' } // IUO to IUO init!(failDuringDelegation3: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } // non-optional to optional init(failDuringDelegation4: ()) { self.init(failBeforeInitialization: ())! // necessary '!' } // non-optional to IUO init(failDuringDelegation5: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } } extension FailableStruct { init?(failInExtension: ()) { self.init(failInExtension: failInExtension) } init?(assignInExtension: ()) { self = FailableStruct(noFail: ()) } } struct FailableAddrOnlyStruct<T : Pachyderm> { var x, y: T init(noFail: ()) { x = T() y = T() } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers22FailableAddrOnlyStructV{{[_0-9a-zA-Z]*}}failBeforeInitialization{{.*}}tcfC // CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T> // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: inject_enum_addr %0 // CHECK: return init?(failBeforeInitialization: ()) { return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers22FailableAddrOnlyStructV{{[_0-9a-zA-Z]*}}failAfterPartialInitialization{{.*}}tcfC // CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T> // CHECK: [[X_BOX:%.*]] = alloc_stack $T // CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type // CHECK: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1 // CHECK-NEXT: apply [[T_INIT_FN]]<T>([[X_BOX]], [[T_TYPE]]) // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableAddrOnlyStruct<T> // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]] // CHECK-NEXT: copy_addr [take] [[X_BOX]] to [initialization] [[X_ADDR]] // CHECK-NEXT: end_access [[WRITE]] : $*FailableAddrOnlyStruct<T> // CHECK-NEXT: dealloc_stack [[X_BOX]] // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[X_ADDR]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: inject_enum_addr %0 // CHECK: return init?(failAfterPartialInitialization: ()) { x = T() return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers22FailableAddrOnlyStructV{{[_0-9a-zA-Z]*}}failAfterFullInitialization{{.*}}tcfC // CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T> // CHECK: [[X_BOX:%.*]] = alloc_stack $T // CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type // CHECK: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1 // CHECK-NEXT: apply [[T_INIT_FN]]<T>([[X_BOX]], [[T_TYPE]]) // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableAddrOnlyStruct<T> // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]] // CHECK-NEXT: copy_addr [take] [[X_BOX]] to [initialization] [[X_ADDR]] // CHECK-NEXT: end_access [[WRITE]] : $*FailableAddrOnlyStruct<T> // CHECK-NEXT: dealloc_stack [[X_BOX]] // CHECK-NEXT: [[Y_BOX:%.*]] = alloc_stack $T // CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type // CHECK-NEXT: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1 // CHECK-NEXT: apply [[T_INIT_FN]]<T>([[Y_BOX]], [[T_TYPE]]) // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableAddrOnlyStruct<T> // CHECK-NEXT: [[Y_ADDR:%.*]] = struct_element_addr [[WRITE]] // CHECK-NEXT: copy_addr [take] [[Y_BOX]] to [initialization] [[Y_ADDR]] // CHECK-NEXT: end_access [[WRITE]] : $*FailableAddrOnlyStruct<T> // CHECK-NEXT: dealloc_stack [[Y_BOX]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: inject_enum_addr %0 // CHECK: return init?(failAfterFullInitialization: ()) { x = T() y = T() return nil } init?(failAfterWholeObjectInitializationByAssignment: ()) { self = FailableAddrOnlyStruct(noFail: ()) return nil } init?(failAfterWholeObjectInitializationByDelegation: ()) { self.init(noFail: ()) return nil } // Optional to optional init?(failDuringDelegation: ()) { self.init(failBeforeInitialization: ()) } // IUO to optional init!(failDuringDelegation2: ()) { self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!' } // non-optional to optional init(failDuringDelegation3: ()) { self.init(failBeforeInitialization: ())! // necessary '!' } // non-optional to IUO init(failDuringDelegation4: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } } extension FailableAddrOnlyStruct { init?(failInExtension: ()) { self.init(failBeforeInitialization: failInExtension) } init?(assignInExtension: ()) { self = FailableAddrOnlyStruct(noFail: ()) } } //// // Structs with throwing initializers //// func unwrap(_ x: Int) throws -> Int { return x } struct ThrowStruct { var x: Canary init(fail: ()) throws { x = Canary() } init(noFail: ()) { x = Canary() } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV20failBeforeDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: retain_value [[NEW_SELF]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeDelegation: Int) throws { try unwrap(failBeforeDelegation) self.init(noFail: ()) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV28failBeforeOrDuringDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: retain_value [[NEW_SELF]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb4([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb5([[ERROR:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeOrDuringDelegation: Int) throws { try unwrap(failBeforeOrDuringDelegation) try self.init(fail: ()) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV29failBeforeOrDuringDelegation2ACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV20failBeforeDelegationACSi_tKcfC // CHECK-NEXT: try_apply [[INIT_FN]]([[RESULT]], %1) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: retain_value [[NEW_SELF]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb4([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb5([[ERROR:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeOrDuringDelegation2: Int) throws { try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2)) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV20failDuringDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: retain_value [[NEW_SELF]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failDuringDelegation: Int) throws { try self.init(fail: ()) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV19failAfterDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: retain_value [[NEW_SELF]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failAfterDelegation: Int) throws { self.init(noFail: ()) try unwrap(failAfterDelegation) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV27failDuringOrAfterDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack [dynamic_lifetime] $ThrowStruct // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb1([[NEW_SELF:.*]] : $ThrowStruct): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: retain_value [[NEW_SELF]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb4([[ERROR:%.*]] : $Error): // CHECK-NEXT: release_value [[NEW_SELF]] // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb5([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failDuringOrAfterDelegation: Int) throws { try self.init(fail: ()) try unwrap(failDuringOrAfterDelegation) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV27failBeforeOrAfterDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack [dynamic_lifetime] $ThrowStruct // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: retain_value [[NEW_SELF]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb4([[ERROR:%.*]] : $Error): // CHECK-NEXT: release_value [[NEW_SELF]] // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb5([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeOrAfterDelegation: Int) throws { try unwrap(failBeforeOrAfterDelegation) self.init(noFail: ()) try unwrap(failBeforeOrAfterDelegation) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV16throwsToOptionalACSgSi_tcfC // CHECK: bb0([[ARG1:%.*]] : $Int, [[ARG2:%.*]] : $@thin ThrowStruct.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV20failDuringDelegationACSi_tKcfC // CHECK-NEXT: try_apply [[INIT_FN]]([[ARG1]], [[ARG2]]) : $@convention(method) (Int, @thin ThrowStruct.Type) -> (@owned ThrowStruct, @error Error), normal [[TRY_APPLY_SUCC_BB:bb[0-9]+]], error [[TRY_APPLY_FAIL_BB:bb[0-9]+]] // // CHECK: [[TRY_APPLY_SUCC_BB]]([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt.1, [[NEW_SELF]] // CHECK-NEXT: br [[TRY_APPLY_CONT:bb[0-9]+]]([[SELF_OPTIONAL]] : $Optional<ThrowStruct>) // // CHECK: [[TRY_APPLY_CONT]]([[SELF_OPTIONAL:%.*]] : $Optional<ThrowStruct>): // CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]] // CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]] // // CHECK: [[FAIL_BB]]: // CHECK: release_value [[SELF_OPTIONAL]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt // CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<ThrowStruct>) // // CHECK: [[SUCC_BB]]: // CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]] // CHECK-NEXT: retain_value [[SELF_VALUE]] // CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt.1, [[SELF_VALUE]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<ThrowStruct>) // // CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<ThrowStruct>): // CHECK-NEXT: return [[NEW_SELF]] : $Optional<ThrowStruct> // // CHECK: [[TRY_APPLY_FAIL_BB]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: strong_release [[ERROR]] : $Error // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt // CHECK-NEXT: br [[TRY_APPLY_CONT]]([[NEW_SELF]] : $Optional<ThrowStruct>) init?(throwsToOptional: Int) { try? self.init(failDuringDelegation: throwsToOptional) } init(throwsToIUO: Int) { try! self.init(failDuringDelegation: throwsToIUO) } init?(throwsToOptionalThrows: Int) throws { try? self.init(fail: ()) } init(throwsOptionalToThrows: Int) throws { self.init(throwsToOptional: throwsOptionalToThrows)! } init?(throwsOptionalToOptional: Int) { try! self.init(throwsToOptionalThrows: throwsOptionalToOptional) } init(failBeforeSelfReplacement: Int) throws { try unwrap(failBeforeSelfReplacement) self = ThrowStruct(noFail: ()) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV25failDuringSelfReplacementACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[SELF_TYPE:%.*]] = metatype $@thin ThrowStruct.Type // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC // CHECK-NEXT: try_apply [[INIT_FN]]([[SELF_TYPE]]) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*ThrowStruct // CHECK-NEXT: retain_value [[NEW_SELF]] // CHECK-NEXT: store [[NEW_SELF]] to [[WRITE]] // CHECK-NEXT: end_access [[WRITE]] : $*ThrowStruct // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failDuringSelfReplacement: Int) throws { try self = ThrowStruct(fail: ()) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV24failAfterSelfReplacementACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[SELF_TYPE:%.*]] = metatype $@thin ThrowStruct.Type // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[SELF_TYPE]]) // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*ThrowStruct // CHECK-NEXT: retain_value [[NEW_SELF]] // CHECK-NEXT: store [[NEW_SELF]] to [[WRITE]] // CHECK-NEXT: end_access [[WRITE]] : $*ThrowStruct // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: release_value [[NEW_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failAfterSelfReplacement: Int) throws { self = ThrowStruct(noFail: ()) try unwrap(failAfterSelfReplacement) } } extension ThrowStruct { init(failInExtension: ()) throws { try self.init(fail: failInExtension) } init(assignInExtension: ()) throws { try self = ThrowStruct(fail: ()) } } struct ThrowAddrOnlyStruct<T : Pachyderm> { var x : T init(fail: ()) throws { x = T() } init(noFail: ()) { x = T() } init(failBeforeDelegation: Int) throws { try unwrap(failBeforeDelegation) self.init(noFail: ()) } init(failBeforeOrDuringDelegation: Int) throws { try unwrap(failBeforeOrDuringDelegation) try self.init(fail: ()) } init(failBeforeOrDuringDelegation2: Int) throws { try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2)) } init(failDuringDelegation: Int) throws { try self.init(fail: ()) } init(failAfterDelegation: Int) throws { self.init(noFail: ()) try unwrap(failAfterDelegation) } init(failDuringOrAfterDelegation: Int) throws { try self.init(fail: ()) try unwrap(failDuringOrAfterDelegation) } init(failBeforeOrAfterDelegation: Int) throws { try unwrap(failBeforeOrAfterDelegation) self.init(noFail: ()) try unwrap(failBeforeOrAfterDelegation) } init?(throwsToOptional: Int) { try? self.init(failDuringDelegation: throwsToOptional) } init(throwsToIUO: Int) { try! self.init(failDuringDelegation: throwsToIUO) } init?(throwsToOptionalThrows: Int) throws { try? self.init(fail: ()) } init(throwsOptionalToThrows: Int) throws { self.init(throwsToOptional: throwsOptionalToThrows)! } init?(throwsOptionalToOptional: Int) { try! self.init(throwsOptionalToThrows: throwsOptionalToOptional) } init(failBeforeSelfReplacement: Int) throws { try unwrap(failBeforeSelfReplacement) self = ThrowAddrOnlyStruct(noFail: ()) } init(failAfterSelfReplacement: Int) throws { self = ThrowAddrOnlyStruct(noFail: ()) try unwrap(failAfterSelfReplacement) } } extension ThrowAddrOnlyStruct { init(failInExtension: ()) throws { try self.init(fail: failInExtension) } init(assignInExtension: ()) throws { self = ThrowAddrOnlyStruct(noFail: ()) } } //// // Classes with failable initializers //// class FailableBaseClass { var member: Canary init(noFail: ()) { member = Canary() } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17FailableBaseClassC28failBeforeFullInitializationACSgyt_tcfc // CHECK: bb0(%0 : $FailableBaseClass): // CHECK: [[METATYPE:%.*]] = metatype $@thick FailableBaseClass.Type // CHECK: dealloc_partial_ref %0 : $FailableBaseClass, [[METATYPE]] // CHECK: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK: return [[RESULT]] init?(failBeforeFullInitialization: ()) { return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17FailableBaseClassC27failAfterFullInitializationACSgyt_tcfc // CHECK: bb0(%0 : $FailableBaseClass): // CHECK: [[CANARY:%.*]] = apply // CHECK-NEXT: [[MEMBER_ADDR:%.*]] = ref_element_addr %0 // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[MEMBER_ADDR]] : $*Canary // CHECK-NEXT: store [[CANARY]] to [[WRITE]] // CHECK-NEXT: end_access [[WRITE]] : $*Canary // CHECK-NEXT: strong_release %0 // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK-NEXT: return [[NEW_SELF]] init?(failAfterFullInitialization: ()) { member = Canary() return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17FailableBaseClassC20failBeforeDelegationACSgyt_tcfC // CHECK: bb0(%0 : $@thick FailableBaseClass.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK-NEXT: return [[RESULT]] convenience init?(failBeforeDelegation: ()) { return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17FailableBaseClassC19failAfterDelegationACSgyt_tcfC // CHECK: bb0(%0 : $@thick FailableBaseClass.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass // CHECK: [[INIT_FN:%.*]] = class_method %0 // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%0) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK-NEXT: return [[RESULT]] convenience init?(failAfterDelegation: ()) { self.init(noFail: ()) return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17FailableBaseClassC20failDuringDelegationACSgyt_tcfC // CHECK: bb0(%0 : $@thick FailableBaseClass.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass // CHECK: [[INIT_FN:%.*]] = class_method %0 // CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]](%0) // CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]] // CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]] // // CHECK: [[FAIL_BB]]: // CHECK: release_value [[SELF_OPTIONAL]] // CHECK: br [[FAIL_TRAMPOLINE_BB:bb[0-9]+]] // // CHECK: [[SUCC_BB]]: // CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]] // CHECK-NEXT: strong_retain [[SELF_VALUE]] // CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.some!enumelt.1, [[SELF_VALUE]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<FailableBaseClass>) // // CHECK: [[FAIL_TRAMPOLINE_BB]]: // CHECK: dealloc_stack [[SELF_BOX]] // CHECK: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK-NEXT: br [[EPILOG_BB]]([[NEW_SELF]] : $Optional<FailableBaseClass>) // // CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<FailableBaseClass>): // CHECK-NEXT: return [[NEW_SELF]] // Optional to optional convenience init?(failDuringDelegation: ()) { self.init(failBeforeFullInitialization: ()) } // IUO to optional convenience init!(failDuringDelegation2: ()) { self.init(failBeforeFullInitialization: ())! // unnecessary-but-correct '!' } // IUO to IUO convenience init!(noFailDuringDelegation: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } // non-optional to optional convenience init(noFailDuringDelegation2: ()) { self.init(failBeforeFullInitialization: ())! // necessary '!' } } extension FailableBaseClass { convenience init?(failInExtension: ()) throws { self.init(failBeforeFullInitialization: failInExtension) } } // Chaining to failable initializers in a superclass class FailableDerivedClass : FailableBaseClass { var otherMember: Canary // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers20FailableDerivedClassC27derivedFailBeforeDelegationACSgyt_tcfc // CHECK: bb0(%0 : $FailableDerivedClass): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableDerivedClass // CHECK: store %0 to [[SELF_BOX]] // CHECK-NEXT: [[RELOAD_FROM_SELF_BOX:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick FailableDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref [[RELOAD_FROM_SELF_BOX]] : $FailableDerivedClass, [[METATYPE]] : $@thick FailableDerivedClass.Type // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt // CHECK-NEXT: return [[RESULT]] // CHECK: } // end sil function '$s35definite_init_failable_initializers20FailableDerivedClassC27derivedFailBeforeDelegationACSgyt_tcfc' init?(derivedFailBeforeDelegation: ()) { return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers20FailableDerivedClassC27derivedFailDuringDelegationACSgyt_tcfc // CHECK: bb0([[SELF:%.*]] : $FailableDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableDerivedClass // CHECK: store [[SELF]] to [[SELF_BOX]] // CHECK: [[CANARY_FUN:%.*]] = function_ref @$s35definite_init_failable_initializers6CanaryCACycfC : // CHECK: [[CANARY:%.*]] = apply [[CANARY_FUN]]( // CHECK-NEXT: [[MEMBER_ADDR:%.*]] = ref_element_addr [[SELF]] // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[MEMBER_ADDR]] : $*Canary // CHECK-NEXT: store [[CANARY]] to [[WRITE]] // CHECK-NEXT: end_access [[WRITE]] : $*Canary // CHECK-NEXT: strong_release [[SELF]] // CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[RELOAD_SELF]] // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17FailableBaseClassC28failBeforeFullInitializationACSgyt_tcfc // CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) // CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]] // CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]] // // CHECK: [[FAIL_BB]]: // CHECK-NEXT: release_value [[SELF_OPTIONAL]] // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt // CHECK-NEXT: br [[EPILOG_BB]]([[NEW_SELF]] : $Optional<FailableDerivedClass>) // // CHECK: [[SUCC_BB]]: // CHECK-NEXT: [[BASE_SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]] // CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_ref_cast [[BASE_SELF_VALUE]] // CHECK-NEXT: strong_retain [[SELF_VALUE]] // CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.some!enumelt.1, [[SELF_VALUE]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<FailableDerivedClass>) // // CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<FailableDerivedClass>): // CHECK-NEXT: return [[NEW_SELF]] : $Optional<FailableDerivedClass> // CHECK: } // end sil function '$s35definite_init_failable_initializers20FailableDerivedClassC27derivedFailDuringDelegationACSgyt_tcfc' init?(derivedFailDuringDelegation: ()) { self.otherMember = Canary() super.init(failBeforeFullInitialization: ()) } init?(derivedFailAfterDelegation: ()) { self.otherMember = Canary() super.init(noFail: ()) return nil } // non-optional to IUO init(derivedNoFailDuringDelegation: ()) { self.otherMember = Canary() super.init(failAfterFullInitialization: ())! // necessary '!' } // IUO to IUO init!(derivedFailDuringDelegation2: ()) { self.otherMember = Canary() super.init(failAfterFullInitialization: ())! // unnecessary-but-correct '!' } } extension FailableDerivedClass { convenience init?(derivedFailInExtension: ()) throws { self.init(derivedFailDuringDelegation: derivedFailInExtension) } } //// // Classes with throwing initializers //// class ThrowBaseClass { required init() throws {} init(noFail: ()) {} } class ThrowDerivedClass : ThrowBaseClass { // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassCACyKcfc // CHECK: bb0([[SELF:%.*]] : $ThrowDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: store [[SELF]] to [[SELF_BOX]] // CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[RELOAD_SELF]] // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassCACyKcfc // CHECK-NEXT: try_apply [[INIT_FN]]([[BASE_SELF]]) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowBaseClass): // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: strong_retain [[DERIVED_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] required init() throws { try super.init() } override init(noFail: ()) { try! super.init() } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitializationACSi_tKcfc // CHECK: bb0(%0 : $Int, [[SELF:%.*]] : $ThrowDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: store [[SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[RELOAD_SELF]] // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassC6noFailACyt_tcfc // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: strong_retain [[DERIVED_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] : $ThrowDerivedClass // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref [[RELOAD_SELF]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeFullInitialization: Int) throws { try unwrap(failBeforeFullInitialization) super.init(noFail: ()) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitialization0h6DuringjK0ACSi_SitKcfc // CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack [dynamic_lifetime] $ThrowDerivedClass // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %2 to [[SELF_BOX]] : $*ThrowDerivedClass // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int) // CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[RELOAD_SELF]] // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassCACyKcfc // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK: try_apply [[INIT_FN]]([[BASE_SELF]]) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowBaseClass): // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: strong_retain [[DERIVED_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb3([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb4([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb5([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref [[RELOAD_SELF]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeFullInitialization: Int, failDuringFullInitialization: Int) throws { try unwrap(failBeforeFullInitialization) try super.init() } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC27failAfterFullInitializationACSi_tKcfc // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: store %1 to [[SELF_BOX]] // CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[RELOAD_SELF]] // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassC6noFailACyt_tcfc // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: strong_retain [[DERIVED_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: strong_release [[DERIVED_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failAfterFullInitialization: Int) throws { super.init(noFail: ()) try unwrap(failAfterFullInitialization) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC27failAfterFullInitialization0h6DuringjK0ACSi_SitKcfc // CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack [dynamic_lifetime] $ThrowDerivedClass // CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %2 to [[SELF_BOX]] // CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[DERIVED_SELF:%.*]] = upcast [[RELOAD_SELF]] // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassCACyKcfc // CHECK: try_apply [[INIT_FN]]([[DERIVED_SELF]]) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowBaseClass): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: strong_retain [[DERIVED_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb3([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb4([[ERROR:%.*]] : $Error): // CHECK-NEXT: strong_release [[DERIVED_SELF]] // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb5([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2) // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failAfterFullInitialization: Int, failDuringFullInitialization: Int) throws { try super.init() try unwrap(failAfterFullInitialization) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitialization0h5AfterjK0ACSi_SitKcfc // CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack [dynamic_lifetime] $ThrowDerivedClass // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %2 to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: [[TWO:%.*]] = integer_literal $Builtin.Int2, -2 // CHECK-NEXT: store [[TWO]] to [[BITMAP_BOX]] // CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[RELOAD_SELF]] // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassC6noFailACyt_tcfc // CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, -1 // CHECK-NEXT: store [[ONE]] to [[BITMAP_BOX]] // CHECK: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: strong_retain [[DERIVED_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%1) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb3([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb4([[ERROR:%.*]] : $Error): // CHECK-NEXT: strong_release [[DERIVED_SELF]] // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb5([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP]] : $Builtin.Int2) : $Builtin.Int1 // CHECK-NEXT: cond_br [[COND]], bb6, bb10 // CHECK: bb6: // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: [[SHIFTED:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2) : $Builtin.Int2 // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[SHIFTED]] : $Builtin.Int2) : $Builtin.Int1 // CHECK-NEXT: cond_br [[COND]], bb7, bb8 // CHECK: bb7: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb9 // CHECK: bb8: // CHECK-NEXT: br bb9 // CHECK: bb9: // CHECK-NEXT: br bb11 // CHECK: bb10: // CHECK-NEXT: [[BITMAP:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref [[BITMAP]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: br bb11 // CHECK: bb11: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] : $Error init(failBeforeFullInitialization: Int, failAfterFullInitialization: Int) throws { try unwrap(failBeforeFullInitialization) super.init(noFail: ()) try unwrap(failAfterFullInitialization) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitialization0h6DuringjK00h5AfterjK0ACSi_S2itKcfc // CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $Int, %3 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack [dynamic_lifetime] $ThrowDerivedClass // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %3 to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[RELOAD_SELF]] // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassCACyKcfc // CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: store [[ONE]] to [[BITMAP_BOX]] // CHECK: try_apply [[INIT_FN]]([[BASE_SELF]]) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowBaseClass): // CHECK-NEXT: [[NEG_ONE:%.*]] = integer_literal $Builtin.Int2, -1 // CHECK-NEXT: store [[NEG_ONE]] to [[BITMAP_BOX]] // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: strong_retain [[DERIVED_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%2) // CHECK: bb3([[RESULT:%.*]] : $Int): // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb4([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb7([[ERROR]] : $Error) // CHECK: bb5([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb7([[ERROR]] : $Error) // CHECK: bb6([[ERROR:%.*]] : $Error): // CHECK-NEXT: strong_release [[DERIVED_SELF]] // CHECK-NEXT: br bb7([[ERROR]] : $Error) // CHECK: bb7([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[COND]], bb8, bb12 // CHECK: bb8: // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2) // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[COND]], bb9, bb10 // CHECK: bb9: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb11 // CHECK: bb10: // CHECK-NEXT: br bb11 // CHECK: bb11: // CHECK-NEXT: br bb13 // CHECK: bb12: // CHECK-NEXT: [[SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref [[SELF]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: br bb13 // CHECK: bb13: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeFullInitialization: Int, failDuringFullInitialization: Int, failAfterFullInitialization: Int) throws { try unwrap(failBeforeFullInitialization) try super.init() try unwrap(failAfterFullInitialization) } convenience init(noFail2: ()) { try! self.init() } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC20failBeforeDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[ARG:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassC6noFailACyt_tcfC // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: strong_retain [[NEW_SELF]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] convenience init(failBeforeDelegation: Int) throws { try unwrap(failBeforeDelegation) self.init(noFail: ()) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC20failDuringDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassCACyKcfC // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowDerivedClass): // CHECK-NEXT: strong_retain [[NEW_SELF]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] : $Error convenience init(failDuringDelegation: Int) throws { try self.init() } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeOrDuringDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[ARG:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassCACyKcfC // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowDerivedClass): // CHECK-NEXT: strong_retain [[NEW_SELF]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR1:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR1]] : $Error) // CHECK: bb4([[ERROR2:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR2]] : $Error) // CHECK: bb5([[ERROR3:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR3]] convenience init(failBeforeOrDuringDelegation: Int) throws { try unwrap(failBeforeOrDuringDelegation) try self.init() } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC29failBeforeOrDuringDelegation2ACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[ARG:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassC20failBeforeDelegationACSi_tKcfC // CHECK-NEXT: try_apply [[INIT_FN]]([[ARG]], %1) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowDerivedClass): // CHECK-NEXT: strong_retain [[NEW_SELF]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR1]] : $Error) // CHECK: bb4([[ERROR2:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR2]] : $Error) // CHECK: bb5([[ERROR3:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR3]] convenience init(failBeforeOrDuringDelegation2: Int) throws { try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2)) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC19failAfterDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassC6noFailACyt_tcfC // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: strong_retain [[NEW_SELF]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: strong_release [[NEW_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] convenience init(failAfterDelegation: Int) throws { self.init(noFail: ()) try unwrap(failAfterDelegation) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC27failDuringOrAfterDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type): // CHECK: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1 // CHECK: [[SELF_BOX:%.*]] = alloc_stack [dynamic_lifetime] $ThrowDerivedClass // CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassCACyKcfC // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowDerivedClass): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: strong_retain [[NEW_SELF]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR1:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR1]] : $Error) // CHECK: bb4([[ERROR2:%.*]] : $Error): // CHECK-NEXT: strong_release [[NEW_SELF]] // CHECK-NEXT: br bb5([[ERROR2]] : $Error) // CHECK: bb5([[ERROR3:%.*]] : $Error): // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK: cond_br {{.*}}, bb6, bb7 // CHECK: bb6: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR3]] convenience init(failDuringOrAfterDelegation: Int) throws { try self.init() try unwrap(failDuringOrAfterDelegation) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC27failBeforeOrAfterDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack [dynamic_lifetime] $ThrowDerivedClass // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassC6noFailACyt_tcfC // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: strong_retain [[NEW_SELF]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb4([[ERROR:%.*]] : $Error): // CHECK-NEXT: strong_release [[NEW_SELF]] // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb5([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK: cond_br {{.*}}, bb6, bb7 // CHECK: bb6: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] convenience init(failBeforeOrAfterDelegation: Int) throws { try unwrap(failBeforeOrAfterDelegation) self.init(noFail: ()) try unwrap(failBeforeOrAfterDelegation) } } //// // Enums with failable initializers //// enum FailableEnum { case A init?(a: Int64) { self = .A } init!(b: Int64) { self.init(a: b)! // unnecessary-but-correct '!' } init(c: Int64) { self.init(a: c)! // necessary '!' } init(d: Int64) { self.init(b: d)! // unnecessary-but-correct '!' } } //// // Protocols and protocol extensions //// // Delegating to failable initializers from a protocol extension to a // protocol. protocol P1 { init?(p1: Int64) } extension P1 { init!(p1a: Int64) { self.init(p1: p1a)! // unnecessary-but-correct '!' } init(p1b: Int64) { self.init(p1: p1b)! // necessary '!' } } protocol P2 : class { init?(p2: Int64) } extension P2 { init!(p2a: Int64) { self.init(p2: p2a)! // unnecessary-but-correct '!' } init(p2b: Int64) { self.init(p2: p2b)! // necessary '!' } } // Delegating to failable initializers from a protocol extension to a // protocol extension. extension P1 { init?(p1c: Int64) { self.init(p1: p1c) } init!(p1d: Int64) { self.init(p1c: p1d)! // unnecessary-but-correct '!' } init(p1e: Int64) { self.init(p1c: p1e)! // necessary '!' } } extension P2 { init?(p2c: Int64) { self.init(p2: p2c) } init!(p2d: Int64) { self.init(p2c: p2d)! // unnecessary-but-correct '!' } init(p2e: Int64) { self.init(p2c: p2e)! // necessary '!' } } //// // type(of: self) with uninitialized self //// func use(_ a : Any) {} class DynamicTypeBase { var x: Int init() { use(type(of: self)) x = 0 } convenience init(a : Int) { use(type(of: self)) self.init() } } class DynamicTypeDerived : DynamicTypeBase { override init() { use(type(of: self)) super.init() } convenience init(a : Int) { use(type(of: self)) self.init() } } struct DynamicTypeStruct { var x: Int init() { use(type(of: self)) x = 0 } init(a : Int) { use(type(of: self)) self.init() } }
apache-2.0
fdad353bf9072d51143fe5e9b39260d4
42.498723
227
0.622792
3.263811
false
false
false
false
cacawai/Tap2Read
tap2read/tap2read/DashedBorderView.swift
1
6434
// // DashedRoundrectView.swift // DashedRoundedRectView // // Created by Baglan on 7/16/16. // Copyright © 2016 Mobile Creators. All rights reserved. // import Foundation import UIKit /// UIView with a dashed rounded rect outline; pattern of the dashes is adjusted to fit nicely. @IBDesignable class DashedRoundedRectView: UIView { @IBInspectable var cornerRadius: CGFloat = 10 { didSet { setNeedsDisplay() } } @IBInspectable var strokeWidth: CGFloat = 1 { didSet { setNeedsDisplay() } } @IBInspectable var strokeColor: UIColor? { didSet { setNeedsDisplay() } } @IBInspectable var isFilled: Bool = false { didSet { setNeedsDisplay() } } @IBInspectable var fillColor: UIColor? { didSet { setNeedsDisplay() } } /** A general way to set a pattern is to populate this array with dash/gap pattern. (see _UIBezierPath.setLineDash()_ for the details) The _dashPattern_ is initially populated with _firstDashSize_, _firstGapSize_, _secondDashSize_ and _secondGapSize_. If any of these properties is updated, _dashPattern_ will be re-populated with values of these properties. */ var dashPattern: [CGFloat]! { didSet { setNeedsDisplay() } } @IBInspectable var firstDashSize: CGFloat = 3 { didSet { updateDashPatternFromInspectables() } } @IBInspectable var firstGapSize: CGFloat = 3 { didSet { updateDashPatternFromInspectables() } } @IBInspectable var secondDashSize: CGFloat = 0 { didSet { updateDashPatternFromInspectables() } } @IBInspectable var secondGapSize: CGFloat = 0 { didSet { updateDashPatternFromInspectables() } } override init(frame: CGRect) { super.init(frame: frame) updateDashPatternFromInspectables() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) updateDashPatternFromInspectables() } override func prepareForInterfaceBuilder() { updateDashPatternFromInspectables() super.prepareForInterfaceBuilder() } /** Replaces _dashPattern_ with the one using values from _firstDashSize_, _firstGapSize_, _secondDashSize_ and _secondGapSize_ */ func updateDashPatternFromInspectables() { dashPattern = [firstDashSize, firstGapSize, secondDashSize, secondGapSize] } /** Phase of the pattern. (see _UIBezierPath.setLineDash()_ for the details) */ @IBInspectable var phase: CGFloat = 0 { didSet { setNeedsDisplay() } } override func draw(_ rect: CGRect) { super.draw(rect) // Calculate rounded rect size for drawing to avoid clipping let offsetFromEdge = ceil(1 + strokeWidth / 2) let roundedRect = CGRect.init( x:offsetFromEdge, y:offsetFromEdge, width:bounds.width - offsetFromEdge * 2, height:bounds.height - offsetFromEdge * 2 ) // Calculate corner radius to avoid overlap let smallerDimension = min(roundedRect.width, roundedRect.height) let radius = cornerRadius * 2 < smallerDimension ? cornerRadius : smallerDimension / 2 // Construct the path // Using the following code would be much simpler but it overshoots in some conditions, // drawing a part of the line twice, which defeats the purpose of this project: // // let path = UIBezierPath(roundedRect: roundedRect, cornerRadius: radius) // // Instead, we need to reproduce the rounded rect ourselves: // // For starters, let's calculate corrdinates for centers of rounded corners. // The pattern is as following: // A B // D C let pointA = CGPoint(x: roundedRect.minX + radius, y: roundedRect.minY + radius) let pointB = CGPoint(x: roundedRect.maxX - radius, y: roundedRect.minY + radius) let pointC = CGPoint(x: roundedRect.maxX - radius, y: roundedRect.maxY - radius) let pointD = CGPoint(x: roundedRect.minX + radius, y: roundedRect.maxY - radius) let path = UIBezierPath() // Start before the top left arc, drawing clockwise: path.move(to: CGPoint(x: pointA.x - radius, y: pointA.y)) // Top left arc: path.addArc( withCenter: pointA, radius: radius, startAngle: CGFloat.pi, endAngle: CGFloat(M_PI + M_PI / 2), clockwise: true ) // Top segment: path.addLine(to: CGPoint(x: pointB.x, y: pointB.y - radius)) // Top right arc: path.addArc( withCenter: pointB, radius: radius, startAngle: CGFloat(M_PI + M_PI / 2), endAngle: CGFloat(2 * M_PI), clockwise: true ) // Right segment: path.addLine(to: CGPoint(x: pointC.x + radius, y: pointC.y)) // Bottom right arc: path.addArc( withCenter: pointC, radius: radius, startAngle: 0, endAngle: CGFloat(M_PI / 2), clockwise: true ) // Bottom segment: path.addLine(to: CGPoint(x: pointD.x, y: pointD.y + radius)) // Bottom left arc: path.addArc( withCenter: pointD, radius: radius, startAngle: CGFloat(M_PI / 2), endAngle: CGFloat(M_PI), clockwise: true ) path.close() // Fill the path if necessary if let fillColor = fillColor, isFilled { fillColor.setFill() path.fill() } // Stroke the path if let strokeColor = strokeColor { path.lineWidth = strokeWidth // Dash and gap pattern let pathLength = CGFloat(M_PI) * radius * 2 + roundedRect.width * 2 + roundedRect.height * 2 - radius * 8 let patternLength = dashPattern.reduce(0) { (sum, value) -> CGFloat in return sum + value } if patternLength != 0 { let numberOfPatterns = Int(round(pathLength / patternLength)) let stretchRatio = pathLength / (patternLength * CGFloat(numberOfPatterns)) let finalPattern = dashPattern.map { (value) -> CGFloat in return value * stretchRatio } path.setLineDash(finalPattern, count: finalPattern.count, phase: phase) } strokeColor.setStroke() path.stroke() } } }
mit
a03da566e938294a3d0755df336bf84e
36.401163
128
0.614954
4.555949
false
false
false
false
georgepstaylor/QuantumKit
Tests/All/QKColorPurpleInitializationTests.swift
1
5216
// // QKColorPurpleInitializationTests.swift // QuantumKit // // Created by Søren Mortensen on 04/03/2017. // Copyright © 2017 George Taylor. All rights reserved. // import XCTest import QuantumKit /// Tests to verify the correct functioning of `QKColor.init(palette:shade:)` for all shades of the /// `.purple` palette. class QKColorPurpleInitializationTests: XCTestCase { /// Test that an instance of `QKColor` initialised with palette `.purple` and shade `.s50` has the /// correct hex value `0xF3E5F5`. func test_purple_s50_initialisesCorrectly() { let color = QKColor(palette: .purple, shade: .s50) XCTAssertNotNil(color) XCTAssertEqual(color?.hexValue, 0xF3E5F5) } /// Test that an instance of `QKColor` initialised with palette `.purple` and shade `.s100` has /// the correct hex value `0xE1BEE7`. func test_purple_s100_initialisesCorrectly() { let color = QKColor(palette: .purple, shade: .s100) XCTAssertNotNil(color) XCTAssertEqual(color?.hexValue, 0xE1BEE7) } /// Test that an instance of `QKColor` initialised with palette `.purple` and shade `.s200` has /// the correct hex value `0xCE93D8`. func test_purple_s200_initialisesCorrectly() { let color = QKColor(palette: .purple, shade: .s200) XCTAssertNotNil(color) XCTAssertEqual(color?.hexValue, 0xCE93D8) } /// Test that an instance of `QKColor` initialised with palette `.purple` and shade `.s300` has /// the correct hex value `0xBA68C8`. func test_purple_s300_initialisesCorrectly() { let color = QKColor(palette: .purple, shade: .s300) XCTAssertNotNil(color) XCTAssertEqual(color?.hexValue, 0xBA68C8) } /// Test that an instance of `QKColor` initialised with palette `.purple` and shade `.s400` has /// the correct hex value `0xAB47BC`. func test_purple_s400_initialisesCorrectly() { let color = QKColor(palette: .purple, shade: .s400) XCTAssertNotNil(color) XCTAssertEqual(color?.hexValue, 0xAB47BC) } /// Test that an instance of `QKColor` initialised with palette `.purple` and shade `.s500` has /// the correct hex value `0x9C27B0`. func test_purple_s500_initialisesCorrectly() { let color = QKColor(palette: .purple, shade: .s500) XCTAssertNotNil(color) XCTAssertEqual(color?.hexValue, 0x9C27B0) } /// Test that an instance of `QKColor` initialised with palette `.purple` and shade `.s600` has /// the correct hex value `0x8E24AA`. func test_purple_s600_initialisesCorrectly() { let color = QKColor(palette: .purple, shade: .s600) XCTAssertNotNil(color) XCTAssertEqual(color?.hexValue, 0x8E24AA) } /// Test that an instance of `QKColor` initialised with palette `.purple` and shade `.s700` has /// the correct hex value `0x7B1FA2`. func test_purple_s700_initialisesCorrectly() { let color = QKColor(palette: .purple, shade: .s700) XCTAssertNotNil(color) XCTAssertEqual(color?.hexValue, 0x7B1FA2) } /// Test that an instance of `QKColor` initialised with palette `.purple` and shade `.s800` has /// the correct hex value `0x6A1B9A`. func test_purple_s800_initialisesCorrectly() { let color = QKColor(palette: .purple, shade: .s800) XCTAssertNotNil(color) XCTAssertEqual(color?.hexValue, 0x6A1B9A) } /// Test that an instance of `QKColor` initialised with palette `.purple` and shade `.s900` has /// the correct hex value `0x4A148C`. func test_purple_s900_initialisesCorrectly() { let color = QKColor(palette: .purple, shade: .s900) XCTAssertNotNil(color) XCTAssertEqual(color?.hexValue, 0x4A148C) } /// Test that an instance of `QKColor` initialised with palette `.purple` and shade `.a100` has /// the correct hex value `0xEA80FC`. func test_purple_a100_initialisesCorrectly() { let color = QKColor(palette: .purple, shade: .a100) XCTAssertNotNil(color) XCTAssertEqual(color?.hexValue, 0xEA80FC) } /// Test that an instance of `QKColor` initialised with palette `.purple` and shade `.a200` has /// the correct hex value `0xE040FB`. func test_purple_a200_initialisesCorrectly() { let color = QKColor(palette: .purple, shade: .a200) XCTAssertNotNil(color) XCTAssertEqual(color?.hexValue, 0xE040FB) } /// Test that an instance of `QKColor` initialised with palette `.purple` and shade `.a400` has /// the correct hex value `0xD500F9`. func test_purple_a400_initialisesCorrectly() { let color = QKColor(palette: .purple, shade: .a400) XCTAssertNotNil(color) XCTAssertEqual(color?.hexValue, 0xD500F9) } /// Test that an instance of `QKColor` initialised with palette `.purple` and shade `.a700` has /// the correct hex value `0xAA00FF`. func test_purple_a700_initialisesCorrectly() { let color = QKColor(palette: .purple, shade: .a700) XCTAssertNotNil(color) XCTAssertEqual(color?.hexValue, 0xAA00FF) } }
mit
f2e821c2e9af56a3e293af4239184ace
39.734375
102
0.661105
3.995402
false
true
false
false
SmallPlanetSwift/Saturn
Source/TypeExtensions/CGRect+String.swift
1
1405
// // CGRect+String.swift // Saturn // // Created by Quinn McHenry on 11/14/15. // Copyright © 2015 Small Planet. All rights reserved. // extension CGRect: StringLiteralConvertible { public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType public typealias UnicodeScalarLiteralType = Character public init(stringLiteral value: String) { let (origin, size) = CGRect.componentsFromString(value) self.init(origin: origin, size: size) } public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { self.init(stringLiteral: value) } public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { self.init(stringLiteral: "\(value)") } public static func componentsFromString(string: String) -> (CGPoint, CGSize) { var x:Float=0.0, y:Float=0.0, w:Float=0.0, h:Float=0.0 var components = string.componentsSeparatedByString(",") if components.count == 4 { x = (components[0] as NSString).floatValue y = (components[1] as NSString).floatValue w = (components[2] as NSString).floatValue h = (components[3] as NSString).floatValue } let origin = CGPoint(x: CGFloat(x), y: CGFloat(y)) let size = CGSize(width: CGFloat(w), height: CGFloat(h)) return (origin, size) } }
mit
cf36df06bcd3ab5ac48d918e9cb41504
35
91
0.655271
4.457143
false
false
false
false
nohana/NohanaImagePicker
NohanaImagePicker/PhotoKitAlbumList.swift
1
3256
/* * Copyright (C) 2016 nohana, Inc. * * 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 &quot;AS IS&quot; 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 Photos public class PhotoKitAlbumList: ItemList { private var albumList: [Item] = [] private let assetCollectionTypes: [PHAssetCollectionType] private let assetCollectionSubtypes: [PHAssetCollectionSubtype] private let mediaType: MediaType private var shouldShowEmptyAlbum: Bool private let ascending: Bool // MARK: - init init(assetCollectionTypes: [PHAssetCollectionType], assetCollectionSubtypes: [PHAssetCollectionSubtype], mediaType: MediaType, shouldShowEmptyAlbum: Bool, ascending: Bool, handler:(() -> Void)?) { self.assetCollectionTypes = assetCollectionTypes self.assetCollectionSubtypes = assetCollectionSubtypes self.mediaType = mediaType self.shouldShowEmptyAlbum = shouldShowEmptyAlbum self.ascending = ascending update { () -> Void in if let handler = handler { handler() } } } // MARK: - ItemList public typealias Item = PhotoKitAssetList open var title: String { return "PhotoKit" } open func update(_ handler:(() -> Void)?) { DispatchQueue.global(qos: .default).async { var albumListFetchResult: [PHFetchResult<PHAssetCollection>] = [] for type in self.assetCollectionTypes { albumListFetchResult = albumListFetchResult + [PHAssetCollection.fetchAssetCollections(with: type, subtype: .any, options: nil)] } self.albumList = [] let isAssetCollectionSubtypeAny = self.assetCollectionSubtypes.contains(.any) for fetchResult in albumListFetchResult { Array(0..<fetchResult.count).chunked(by: 20).map({ IndexSet($0) }).forEach { fetchResult.enumerateObjects(at: $0, options: []) { (album, index, stop) in if self.assetCollectionSubtypes.contains(album.assetCollectionSubtype) || isAssetCollectionSubtypeAny { let assets = PhotoKitAssetList(album: album, mediaType: self.mediaType, ascending: self.ascending) if self.shouldShowEmptyAlbum || assets.count > 0 { self.albumList.append(assets) } } } handler?() } } } } open subscript (index: Int) -> Item { return albumList[index] as Item } // MARK: - CollectionType open var startIndex: Int { return albumList.startIndex } open var endIndex: Int { return albumList.endIndex } }
apache-2.0
e893973b0a4f9ab761713537203ab193
36
200
0.628378
4.970992
false
false
false
false
nathanlentz/rivals
Rivals/Rivals/FindUserTableViewController.swift
1
4947
// // FindUserTableViewController.swift // Rivals // // Created by Nate Lentz on 4/16/17. // Copyright © 2017 ntnl.design. All rights reserved. // import UIKit import Firebase class FindUserTableViewController: UITableViewController, UISearchResultsUpdating { let searchController = UISearchController(searchResultsController: nil) @IBOutlet var addPlayerTableView: UITableView! var users = [NSDictionary?]() var filteredUsers = [NSDictionary?]() var selectedUser = User() var alreadySelectedUsers = [NSDictionary?]() var ref = FIRDatabase.database().reference() override func viewDidLoad() { super.viewDidLoad() // Allows class to know when text in search bar has changed searchController.searchResultsUpdater = self // Dim view when user types in search bar searchController.dimsBackgroundDuringPresentation = false // Ensures that searchbar shows only on this view definesPresentationContext = true self.tableView.tableHeaderView = searchController.searchBar self.extendedLayoutIncludesOpaqueBars = true; let currentUserId = FIRAuth.auth()?.currentUser?.uid ref.child("profiles").queryOrdered(byChild: "name").observe(.childAdded, with: { (snapshot) in // Check if user in snapshot has current user in friends list let user = snapshot.value as? NSDictionary if user?["uid"] as? String == currentUserId { self.users.append(snapshot.value as? NSDictionary) self.addPlayerTableView.insertRows(at: [IndexPath(row:self.users.count-1, section: 0)], with: UITableViewRowAnimation.automatic) } if let friends = user?["friends"] as! [String : Any]? { for (key, _) in friends { if key == currentUserId { self.users.append(snapshot.value as? NSDictionary) self.addPlayerTableView.insertRows(at: [IndexPath(row:self.users.count-1, section: 0)], with: UITableViewRowAnimation.automatic) } } } }) { (error) in print(error.localizedDescription) } /* Theme Colors */ } func filterUsers(searchText: String){ self.filteredUsers = self.users.filter{ user in let username = user!["name"] as? String // If name is in search text, return that to filter array return(username?.lowercased().contains(searchText.lowercased()))! } tableView.reloadData() } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if searchController.isActive && searchController.searchBar.text != "" { return filteredUsers.count } else { return users.count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath) let user : NSDictionary? // Check if user is typing or nah if searchController.isActive && searchController.searchBar.text != "" { user = filteredUsers[indexPath.row] } else { user = self.users[indexPath.row] } cell.textLabel?.text = user?["name"] as? String cell.detailTextLabel?.text = user?["email"] as? String return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // need to unwind segue here let user: NSDictionary? if searchController.isActive && searchController.searchBar.text != "" { user = filteredUsers[indexPath.row]! } else { user = users[indexPath.row]! } self.selectedUser.uid = user?["uid"] as? String self.selectedUser.name = user?["name"] as? String self.selectedUser.wins = user?["wins"] as? Int self.selectedUser.losses = user?["losses"] as? Int self.selectedUser.profileImageUrl = user?["profileImageUrl"] as? String dismiss(animated: true, completion: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { } @IBAction func cancelDidPress(_ sender: Any) { dismiss(animated: true, completion: nil) } func updateSearchResults(for searchController: UISearchController) { // Update our search results filterUsers(searchText: self.searchController.searchBar.text!) } }
apache-2.0
23d0abe57ef7fb0cee82671ac092767b
33.110345
152
0.604933
5.306867
false
false
false
false
caicai0/ios_demo
load/thirdpart/SwiftSoup/Parser.swift
3
6607
// // Parser.swift // SwifSoup // // Created by Nabil Chatbi on 29/09/16. // Copyright © 2016 Nabil Chatbi.. All rights reserved. // import Foundation /** * Parses HTML into a {@link org.jsoup.nodes.Document}. Generally best to use one of the more convenient parse methods * in {@link org.jsoup.Jsoup}. */ public class Parser { private static let DEFAULT_MAX_ERRORS: Int = 0 // by default, error tracking is disabled. private var _treeBuilder: TreeBuilder private var _maxErrors: Int = DEFAULT_MAX_ERRORS private var _errors: ParseErrorList = ParseErrorList(16, 16) private var _settings: ParseSettings /** * Create a new Parser, using the specified TreeBuilder * @param treeBuilder TreeBuilder to use to parse input into Documents. */ init(_ treeBuilder: TreeBuilder) { self._treeBuilder = treeBuilder _settings = treeBuilder.defaultSettings() } public func parseInput(_ html: String, _ baseUri: String)throws->Document { _errors = isTrackErrors() ? ParseErrorList.tracking(_maxErrors) : ParseErrorList.noTracking() return try _treeBuilder.parse(html, baseUri, _errors, _settings) } // gets & sets /** * Get the TreeBuilder currently in use. * @return current TreeBuilder. */ public func getTreeBuilder() -> TreeBuilder { return _treeBuilder } /** * Update the TreeBuilder used when parsing content. * @param treeBuilder current TreeBuilder * @return this, for chaining */ @discardableResult public func setTreeBuilder(_ treeBuilder: TreeBuilder) -> Parser { self._treeBuilder = treeBuilder return self } /** * Check if parse error tracking is enabled. * @return current track error state. */ public func isTrackErrors() -> Bool { return _maxErrors > 0 } /** * Enable or disable parse error tracking for the next parse. * @param maxErrors the maximum number of errors to track. Set to 0 to disable. * @return this, for chaining */ @discardableResult public func setTrackErrors(_ maxErrors: Int) -> Parser { self._maxErrors = maxErrors return self } /** * Retrieve the parse errors, if any, from the last parse. * @return list of parse errors, up to the size of the maximum errors tracked. */ public func getErrors() -> ParseErrorList { return _errors } @discardableResult public func settings(_ settings: ParseSettings) -> Parser { self._settings = settings return self } public func settings() -> ParseSettings { return _settings } // static parse functions below /** * Parse HTML into a Document. * * @param html HTML to parse * @param baseUri base URI of document (i.e. original fetch location), for resolving relative URLs. * * @return parsed Document */ public static func parse(_ html: String, _ baseUri: String)throws->Document { let treeBuilder: TreeBuilder = HtmlTreeBuilder() return try treeBuilder.parse(html, baseUri, ParseErrorList.noTracking(), treeBuilder.defaultSettings()) } /** * Parse a fragment of HTML into a list of nodes. The context element, if supplied, supplies parsing context. * * @param fragmentHtml the fragment of HTML to parse * @param context (optional) the element that this HTML fragment is being parsed for (i.e. for inner HTML). This * provides stack context (for implicit element creation). * @param baseUri base URI of document (i.e. original fetch location), for resolving relative URLs. * * @return list of nodes parsed from the input HTML. Note that the context element, if supplied, is not modified. */ public static func parseFragment(_ fragmentHtml: String, _ context: Element?, _ baseUri: String)throws->Array<Node> { let treeBuilder = HtmlTreeBuilder() return try treeBuilder.parseFragment(fragmentHtml, context, baseUri, ParseErrorList.noTracking(), treeBuilder.defaultSettings()) } /** * Parse a fragment of XML into a list of nodes. * * @param fragmentXml the fragment of XML to parse * @param baseUri base URI of document (i.e. original fetch location), for resolving relative URLs. * @return list of nodes parsed from the input XML. */ public static func parseXmlFragment(_ fragmentXml: String, _ baseUri: String)throws->Array<Node> { let treeBuilder: XmlTreeBuilder = XmlTreeBuilder() return try treeBuilder.parseFragment(fragmentXml, baseUri, ParseErrorList.noTracking(), treeBuilder.defaultSettings()) } /** * Parse a fragment of HTML into the {@code body} of a Document. * * @param bodyHtml fragment of HTML * @param baseUri base URI of document (i.e. original fetch location), for resolving relative URLs. * * @return Document, with empty head, and HTML parsed into body */ public static func parseBodyFragment(_ bodyHtml: String, _ baseUri: String)throws->Document { let doc: Document = Document.createShell(baseUri) if let body: Element = doc.body() { let nodeList: Array<Node> = try parseFragment(bodyHtml, body, baseUri) //var nodes: [Node] = nodeList.toArray(Node[nodeList.size()]) // the node list gets modified when re-parented for i in 1..<nodeList.count{ try nodeList[i].remove() } for node: Node in nodeList { try body.appendChild(node) } } return doc } /** * Utility method to unescape HTML entities from a string * @param string HTML escaped string * @param inAttribute if the string is to be escaped in strict mode (as attributes are) * @return an unescaped string */ public static func unescapeEntities(_ string: String, _ inAttribute: Bool)throws->String { let tokeniser: Tokeniser = Tokeniser(CharacterReader(string), ParseErrorList.noTracking()) return try tokeniser.unescapeEntities(inAttribute) } /** * @param bodyHtml HTML to parse * @param baseUri baseUri base URI of document (i.e. original fetch location), for resolving relative URLs. * * @return parsed Document * @deprecated Use {@link #parseBodyFragment} or {@link #parseFragment} instead. */ public static func parseBodyFragmentRelaxed(_ bodyHtml: String, _ baseUri: String)throws->Document { return try parse(bodyHtml, baseUri) } // builders /** * Create a new HTML parser. This parser treats input as HTML5, and enforces the creation of a normalised document, * based on a knowledge of the semantics of the incoming tags. * @return a new HTML parser. */ public static func htmlParser() -> Parser { return Parser(HtmlTreeBuilder()) } /** * Create a new XML parser. This parser assumes no knowledge of the incoming tags and does not treat it as HTML, * rather creates a simple tree directly from the input. * @return a new simple XML parser. */ public static func xmlParser() -> Parser { return Parser(XmlTreeBuilder()) } }
mit
89f76e629b3c80b8524444e2f5a9bd7d
32.19598
130
0.725704
3.73854
false
false
false
false
elm4ward/BlackNest
BlackNest/ExpectCombinators.swift
1
7294
// // XCAssertCombinators.swift // BlackNest // // Created by Elmar Kretzer on 26.08.16. // Copyright © 2016 Elmar Kretzer. All rights reserved. // import XCTest // -------------------------------------------------------------------------------- // MARK: - 2 Level // -------------------------------------------------------------------------------- @discardableResult public func expect<I, B, E>(_ input: I, in breeding: B, is expected: E, line: UInt = #line, file: StaticString = #file) -> B.R.O? where E: IsPair, B: IsPair, B.L: HasRun, B.R: HasRun, B.L.I == I, B.L.E == E.L, B.R.I == B.L.O, B.R.E == E.R { do { let m1 = try breeding.left.run(input, expected.left) let m2 = try breeding.right.run(m1, expected.right) return m2 } catch let error { XCTAssert(false, "\(error)", file: file, line: line) } return nil } @discardableResult public func expect<T>(_ tree: T, line: UInt = #line, file: StaticString = #file) -> T.R.O? where T: IsPair, T.L: EvaluatableSpec, T.R: HasRunAndExpected, T.L.O == T.R.I { do { let m1 = try tree.left.evaluate() let m2 = try tree.right.run(m1, tree.right.expected) return m2 } catch let error { XCTAssert(false, "\(error)", file: file, line: line) } return nil } // -------------------------------------------------------------------------------- // MARK: - 3 Level // -------------------------------------------------------------------------------- @discardableResult public func expect<I, B, E>(_ input: I, in breeding: B, is expected: E, line: UInt = #line, file: StaticString = #file) -> B.R.R.O? where E: IsPair, B: IsPair, E.R: IsPair, B.R: IsPair, B.L: HasRun, B.R.L: HasRun, B.R.R: HasRun, B.L.I == I, B.L.E == E.L, B.R.L.I == B.L.O, B.R.L.E == E.R.L, B.R.R.I == B.R.L.O, B.R.R.E == E.R.R { do { let m1 = try breeding.left.run(input, expected.left) let m2 = try breeding.right.left.run(m1, expected.right.left) let m3 = try breeding.right.right.run(m2, expected.right.right) return m3 } catch let error { XCTAssert(false, "\(error)", file: file, line: line) } return nil } @discardableResult public func expect<T>(_ tree: T, line: UInt = #line, file: StaticString = #file) -> T.R.R.O? where T: IsPair, T.R: IsPair, T.L: EvaluatableSpec, T.R.L: HasRunAndExpected, T.R.R: HasRunAndExpected, T.L.O == T.R.L.I, T.R.L.O == T.R.R.I { do { let m1 = try tree.left.evaluate() let m2 = try tree.right.left.evaluate(m1) let m3 = try tree.right.right.evaluate(m2) return m3 } catch let error { XCTAssert(false, "\(error)", file: file, line: line) } return nil } // -------------------------------------------------------------------------------- // MARK: - 4 Level // -------------------------------------------------------------------------------- @discardableResult public func expect<I, B, E>(_ input: I, in breeding: B, is expected: E, line: UInt = #line, file: StaticString = #file) -> B.R.R.R.O? where E: IsPair, B: IsPair, E.R: IsPair, E.R.R: IsPair, B.R: IsPair, B.R.R: IsPair, B.L: HasRun, B.R.L: HasRun, B.R.R.L: HasRun, B.R.R.R: HasRun, B.L.I == I, B.L.E == E.L, B.R.L.I == B.L.O, B.R.L.E == E.R.L, B.R.R.L.I == B.R.L.O, B.R.R.L.E == E.R.R.L, B.R.R.R.I == B.R.R.L.O, B.R.R.R.E == E.R.R.R { do { let m1 = try breeding.left.run(input, expected.left) let m2 = try breeding.right.left.run(m1, expected.right.left) let m3 = try breeding.right.right.left.run(m2, expected.right.right.left) let m4 = try breeding.right.right.right.run(m3, expected.right.right.right) return m4 } catch let error { XCTAssert(false, "\(error)", file: file, line: line) } return nil } @discardableResult public func expect<T>(_ tree: T, line: UInt = #line, file: StaticString = #file) -> T.R.R.R.O? where T: IsPair, T.L: EvaluatableSpec, T.R: IsPair, T.R.R: IsPair, T.R.L: HasRunAndExpected, T.R.R.L: HasRunAndExpected, T.R.R.R: HasRunAndExpected, T.L.O == T.R.L.I, T.R.L.O == T.R.R.L.I, T.R.R.L.O == T.R.R.R.I { do { let m1 = try tree.left.evaluate() let m2 = try tree.right.left.evaluate(m1) let m3 = try tree.right.right.left.evaluate(m2) let m4 = try tree.right.right.right.evaluate(m3) return m4 } catch let error { XCTAssert(false, "\(error)", file: file, line: line) } return nil } // -------------------------------------------------------------------------------- // MARK: - 5 Level // -------------------------------------------------------------------------------- @discardableResult public func expect<I, B, E>(_ input: I, in breeding: B, is expected: E, line: UInt = #line, file: StaticString = #file) -> B.R.R.R.R.O? where E: IsPair, B: IsPair, E.R: IsPair, E.R.R: IsPair, E.R.R.R: IsPair, B.R: IsPair, B.R.R: IsPair, B.R.R.R: IsPair, B.L: HasRun, B.R.L: HasRun, B.R.R.L: HasRun, B.R.R.R.L: HasRun, B.R.R.R.R: HasRun, B.L.I == I, B.L.E == E.L, B.R.L.I == B.L.O, B.R.L.E == E.R.L, B.R.R.L.I == B.R.L.O, B.R.R.L.E == E.R.R.L, B.R.R.R.L.I == B.R.R.L.O, B.R.R.R.L.E == E.R.R.R.L, B.R.R.R.R.I == B.R.R.R.L.O, B.R.R.R.R.E == E.R.R.R.R { do { let m1 = try breeding.left.run(input, expected.left) let m2 = try breeding.right.left.run(m1, expected.right.left) let m3 = try breeding.right.right.left.run(m2, expected.right.right.left) let m4 = try breeding.right.right.right.left.run(m3, expected.right.right.right.left) let m5 = try breeding.right.right.right.right.run(m4, expected.right.right.right.right) return m5 } catch let error { XCTAssert(false, "\(error)", file: file, line: line) } return nil } @discardableResult public func expect<T>(_ tree: T, line: UInt = #line, file: StaticString = #file) -> T.R.R.R.R.O? where T: IsPair, T.L: EvaluatableSpec, T.R: IsPair, T.R.R: IsPair, T.R.R.R: IsPair, T.R.L: HasRunAndExpected, T.R.R.L: HasRunAndExpected, T.R.R.R.L: HasRunAndExpected, T.R.R.R.R: HasRunAndExpected, T.L.O == T.R.L.I, T.R.L.O == T.R.R.L.I, T.R.R.L.O == T.R.R.R.L.I, T.R.R.R.L.O == T.R.R.R.R.I { do { let m1 = try tree.left.evaluate() let m2 = try tree.right.left.evaluate(m1) let m3 = try tree.right.right.left.evaluate(m2) let m4 = try tree.right.right.right.left.evaluate(m3) let m5 = try tree.right.right.right.right.evaluate(m4) return m5 } catch let error { XCTAssert(false, "\(error)", file: file, line: line) } return nil }
mit
66110226a4963098123efe20980b8b2f
26.942529
93
0.48238
2.851056
false
false
false
false
xwu/swift
test/Interop/Cxx/operators/member-inline.swift
1
4938
// RUN: %target-run-simple-swift(-I %S/Inputs -Xfrontend -enable-cxx-interop) // // REQUIRES: executable_test // // We can't yet call member functions correctly on Windows (SR-13129). // XFAIL: OS=windows-msvc import MemberInline import StdlibUnittest var OperatorsTestSuite = TestSuite("Operators") OperatorsTestSuite.test("LoadableIntWrapper.plus (inline)") { var lhs = LoadableIntWrapper(value: 42) let rhs = LoadableIntWrapper(value: 23) let result = lhs - rhs expectEqual(19, result.value) } OperatorsTestSuite.test("LoadableIntWrapper.call (inline)") { var wrapper = LoadableIntWrapper(value: 42) let resultNoArgs = wrapper() let resultOneArg = wrapper(23) let resultTwoArgs = wrapper(3, 5) expectEqual(42, resultNoArgs) expectEqual(65, resultOneArg) expectEqual(57, resultTwoArgs) } OperatorsTestSuite.test("AddressOnlyIntWrapper.call (inline)") { var wrapper = AddressOnlyIntWrapper(42) let resultNoArgs = wrapper() let resultOneArg = wrapper(23) let resultTwoArgs = wrapper(3, 5) expectEqual(42, resultNoArgs) expectEqual(65, resultOneArg) expectEqual(57, resultTwoArgs) } OperatorsTestSuite.test("ReadWriteIntArray.subscript (inline)") { var arr = ReadWriteIntArray() let resultBefore = arr[1] expectEqual(2, resultBefore) arr[1] = 234 let resultAfter = arr[1] expectEqual(234, resultAfter) } OperatorsTestSuite.test("ReadOnlyIntArray.subscript (inline)") { let arr = ReadOnlyIntArray(1) let result0 = arr[0] let result2 = arr[2] let result4 = arr[4] expectEqual(1, result0) expectEqual(3, result2) expectEqual(5, result4) } OperatorsTestSuite.test("WriteOnlyIntArray.subscript (inline)") { var arr = WriteOnlyIntArray() let resultBefore = arr[0] expectEqual(1, resultBefore) arr[0] = 654 let resultAfter = arr[0] expectEqual(654, resultAfter) } OperatorsTestSuite.test("DifferentTypesArray.subscript (inline)") { let arr = DifferentTypesArray() let resultInt: Int32 = arr[2] let resultDouble: Double = arr[0.1] expectEqual(3, resultInt) expectEqual(1.5.rounded(.down), resultDouble.rounded(.down)) expectEqual(1.5.rounded(.up), resultDouble.rounded(.up)) } OperatorsTestSuite.test("IntArrayByVal.subscript (inline)") { var arr = IntArrayByVal() let result0 = arr[0] let result1 = arr[1] let result2 = arr[2] expectEqual(1, result0) expectEqual(2, result1) expectEqual(3, result2) arr.setValueAtIndex(42, 2) let result3 = arr[2] expectEqual(42, result3) } OperatorsTestSuite.test("NonTrivialIntArrayByVal.subscript (inline)") { var arr = NonTrivialIntArrayByVal(1) let result0 = arr[0] let result2 = arr[2] let result4 = arr[4] expectEqual(1, result0) expectEqual(3, result2) expectEqual(5, result4) arr.setValueAtIndex(42, 2) let result5 = arr[2] expectEqual(42, result5) } OperatorsTestSuite.test("DifferentTypesArrayByVal.subscript (inline)") { var arr = DifferentTypesArrayByVal() let resultInt: Int32 = arr[2] let resultDouble: Double = arr[0.1] expectEqual(3, resultInt) expectEqual(1.5.rounded(.down), resultDouble.rounded(.down)) expectEqual(1.5.rounded(.up), resultDouble.rounded(.up)) } OperatorsTestSuite.test("NonTrivialArrayByVal.subscript (inline)") { var arr = NonTrivialArrayByVal() let NonTrivialByVal = arr[0]; let cStr = NonTrivialByVal.Str! expectEqual("Non-Trivial", String(cString: cStr)) expectEqual(1, NonTrivialByVal.a) expectEqual(2, NonTrivialByVal.b) expectEqual(3, NonTrivialByVal.c) expectEqual(4, NonTrivialByVal.d) expectEqual(5, NonTrivialByVal.e) expectEqual(6, NonTrivialByVal.f) } OperatorsTestSuite.test("PtrByVal.subscript (inline)") { var arr = PtrByVal() expectEqual(64, arr[0]![0]) arr[0]![0] = 23 expectEqual(23, arr[0]![0]) } OperatorsTestSuite.test("ConstOpPtrByVal.subscript (inline)") { var arr = ConstOpPtrByVal() expectEqual(64, arr[0]![0]) } OperatorsTestSuite.test("ConstPtrByVal.subscript (inline)") { var arr = ConstPtrByVal() expectEqual(64, arr[0]![0]) } OperatorsTestSuite.test("RefToPtr.subscript (inline)") { var arr = RefToPtr() let ptr: UnsafeMutablePointer<Int32> = UnsafeMutablePointer<Int32>.allocate(capacity: 64) ptr[0] = 23 expectEqual(64, arr[0]![0]) arr[0] = ptr expectEqual(23, arr[0]![0]) } OperatorsTestSuite.test("PtrToPtr.subscript (inline)") { var arr = PtrToPtr() let ptr: UnsafeMutablePointer<Int32> = UnsafeMutablePointer<Int32>.allocate(capacity: 64) ptr[0] = 23 expectEqual(64, arr[0]![0]![0]) arr[0]![0] = ptr expectEqual(23, arr[0]![0]![0]) } // TODO: this causes a crash (does it also crash on main?) //OperatorsTestSuite.test("TemplatedSubscriptArrayByVal.subscript (inline)") { // let ptr: UnsafeMutablePointer<Int32> = // UnsafeMutablePointer<Int32>.allocate(capacity: 64) // ptr[0] = 23 // var arr = TemplatedSubscriptArrayByVal(ptr: ptr) // expectEqual(23, arr[0]) //} runAllTests()
apache-2.0
b205309e1c616567c940316b4a2c7983
24.06599
78
0.718712
3.36147
false
true
false
false
adyrda2/Exercism.io
swift/leap/Leap.swift
1
356
import Foundation class Year { var calendarYear: Int = 0 init(calendarYear: Int) { self.calendarYear = calendarYear } func isLeapYear() -> Bool { if calendarYear % 4 == 0 && (calendarYear % 100 != 0 || calendarYear % 400 == 0) { return true } else { return false } } }
mit
34bcdff6a2d07787314b7887625480af
18.833333
90
0.511236
4.188235
false
false
false
false
GuyKahlon/UICollaborativeFilteringServer
Sources/App/Models/Matrix.swift
1
1341
// // Matrix.swift // ToDo // // Created by Guy Kahlon on 11/23/16. // Copyright © 2016 Guy. All rights reserved. // import Foundation func * (left: UInt, right: UInt) -> UInt { let result = Int(left) * Int(right) return UInt(result) } struct Matrix { let rows: UInt let columns: UInt var grid: [UInt] init(rows: UInt, columns: UInt) { self.rows = rows self.columns = columns let count = Int(rows * columns) grid = Array(repeating: 0, count: count) } init(grid: [UInt], rows: UInt, columns: UInt) { self.rows = rows self.columns = columns self.grid = grid } func indexIsValid(_ row: UInt, column: UInt) -> Bool { return row >= 0 && row < rows && column >= 0 && column < columns } subscript(row: UInt, column: UInt) -> UInt { get { assert(indexIsValid(row, column: column), "Index out of range") return grid[Int((row * columns) + column)] } set { assert(indexIsValid(row, column: column), "Index out of range") grid[Int((row * columns) + column)] = newValue } } } extension Matrix: CustomStringConvertible { var description: String { var str = String() for r in 0..<rows { for c in 0..<columns { str += "\(self[r,c]) " } str += "\n" } return str } }
mit
a1af2a53f09a387a0fb95fc3594440b8
18.142857
69
0.569403
3.544974
false
false
false
false
Orphe-OSS/Orphe-Piano
OrphePiano/MainViewController/CustomCircle.swift
1
3382
// // DoubleCircle.swift // OrpheSynth // // Created by kyosuke on 2017/02/09. // Copyright © 2017 no new folk studio Inc. All rights reserved. // import C4 class CustomCircle:Shape{ var firstDiameter:Double = 0 var preDiameter:Double = 0 var vibrateTimer: Foundation.Timer? var initPoint = Point(0,0) var centerXAverage = averageCalculator(elementCount:10) var centerYAverage = averageCalculator(elementCount:10) public override init(frame: Rect) { super.init() view.frame = CGRect(frame) let newPath = Path() newPath.addEllipse(bounds) path = newPath } convenience public init(center: Point, radius: Double) { let frame = Rect(center.x-radius, center.y-radius, radius * 2, radius * 2) self.init(frame: frame) self.initPoint = center preDiameter = radius*2 firstDiameter = preDiameter self.shadow.radius = 10 self.shadow.opacity = 0.2 } func updateDiameter(_ diameter:Double){ let scale = diameter/preDiameter self.transform.scale(scale, scale) preDiameter = diameter } func updateCenterX(_ x:Double){ centerXAverage.update(value: x) self.center.x = centerXAverage.result } func updateCenterY(_ y:Double){ centerYAverage.update(value: y) self.center.y = centerYAverage.result } var vibrateCounter:Double = 1 var isVibrating = false func vibrateShape(duration:Double, amplitude:Double, cycleDuration:Double = 0.1){ if !isVibrating{ let d = firstDiameter let counterMax:Double = duration/(cycleDuration*2) vibrateCounter = 1 let fanim = ViewAnimation(duration: cycleDuration){ self.updateDiameter(d-amplitude*(1-(self.vibrateCounter/counterMax))) } let banim = ViewAnimation(duration: cycleDuration){ self.updateDiameter(d) } fanim.addCompletionObserver { banim.animate() } banim.addCompletionObserver { self.vibrateCounter += 1 if self.vibrateCounter < counterMax{ fanim.animate() } else{ self.isVibrating = false } } fanim.animate() } } func startFade(duration:Double){ let fadeAnim = ViewAnimation(duration: duration){ self.fillColor = clear self.strokeColor = clear self.transform.scale(0.8, 0.8) } fadeAnim.addCompletionObserver { self.removeFromSuperview() } fadeAnim.animate() } } class averageCalculator{ var array = [Double]() var result:Double = 0 var elementCount = 1 init(elementCount:Int) { self.elementCount = elementCount } func update(value:Double){ array.append(value) if array.count > elementCount{ array.remove(at: 0) } result = calcAverage(array: array) } func calcAverage(array: [Double])->Double{ var sum = 0.0 for val in array{ sum += val } return sum / Double(array.count) } }
mit
eab1ab6fd4de4f7a56531eb76e951004
26.487805
85
0.5664
4.437008
false
false
false
false
jamesdouble/JDGamesLoading
JDGamesLoading/JDGamesLoading/JDBreaksScene.swift
1
10705
// // JDBreaksScene.swift // JDBreaksLoading // // Created by 郭介騵 on 2016/12/14. // Copyright © 2016年 james12345. All rights reserved. // import SpriteKit import GameplayKit struct BreaksBasicSetting { static let BallCategoryName = "ball" static let PaddleCategoryName = "paddle" static let BlockCategoryName = "block" static let GameMessageName = "gameMessage" static let BallCategory : UInt32 = 0x1 << 0 static let BlockCategory : UInt32 = 0x1 << 1 static let PaddleCategory : UInt32 = 0x1 << 2 static let BorderCategory : UInt32 = 0x1 << 3 } class JDBreaksBrick:SKShapeNode { init(size:CGSize,color:UIColor) { super.init() let rect = CGRect(origin: CGPoint.zero, size: size) self.path = CGPath(rect: rect, transform: nil) self.strokeColor = UIColor.black self.fillColor = color self.physicsBody = SKPhysicsBody(rectangleOf: self.frame.size) self.physicsBody!.allowsRotation = false self.physicsBody!.friction = 0.0 self.physicsBody!.affectedByGravity = false self.physicsBody!.isDynamic = false self.name = BreaksBasicSetting.BlockCategoryName self.physicsBody!.categoryBitMask = BreaksBasicSetting.BlockCategory self.zPosition = 2 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class JDBallNode:SKShapeNode { init(size:CGSize,color:UIColor) { super.init() let rect = CGRect(origin: CGPoint.zero, size: size) self.path = CGPath(roundedRect: rect, cornerWidth: size.width * 0.5, cornerHeight: size.width * 0.5, transform: nil) // self.fillColor = color self.position = CGPoint(x: self.frame.width * 0.5, y: self.frame.width * 0.5) self.name = BreaksBasicSetting.BallCategoryName self.physicsBody = SKPhysicsBody(circleOfRadius: self.frame.width * 0.5) self.physicsBody!.categoryBitMask = BreaksBasicSetting.BallCategory self.physicsBody!.isDynamic = true self.physicsBody!.friction = 0.0 self.physicsBody!.restitution = 1.0 self.physicsBody!.linearDamping = 0.0 self.physicsBody!.angularDamping = 0.0 self.physicsBody!.allowsRotation = false self.physicsBody!.contactTestBitMask = BreaksBasicSetting.BlockCategory } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } enum JDPaddleSide { case Own case Enemy } class JDBreakPaddle:SKShapeNode { var side:JDPaddleSide = .Own init(size:CGSize,color:UIColor,radius:CGFloat) { super.init() let rect = CGRect(origin: CGPoint.zero, size: size) self.path = CGPath(roundedRect: rect, cornerWidth: radius, cornerHeight: radius, transform: nil) // self.fillColor = color self.name = BreaksBasicSetting.PaddleCategoryName self.physicsBody = SKPhysicsBody(rectangleOf: size) self.physicsBody!.categoryBitMask = BreaksBasicSetting.PaddleCategory self.physicsBody!.isDynamic = false self.physicsBody!.allowsRotation = true self.physicsBody!.angularDamping = 0.1 self.physicsBody!.linearDamping = 0.1 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class JDBreaksScene: SKScene { var isFingerOnPaddle = false var ball:JDBallNode! var gameWon : Bool = false { didSet { if(gameWon) { let holdQuene:DispatchQueue = DispatchQueue.global() let seconds = 0.5 let delay = seconds * Double(NSEC_PER_SEC) let dispatchTime = DispatchTime.now() + Double(Int64(delay)) / Double(NSEC_PER_SEC) holdQuene.asyncAfter(deadline: dispatchTime, execute: { DispatchQueue.main.async(execute: { self.addBlock() }) }) } } } var d_ballwidth:CGFloat = 20.0 var ballwidth:CGFloat = 0.0 var ballcolor:UIColor = UIColor.white var d_paddlewidth:CGFloat = 60 var paddlewidth:CGFloat = 0.0 var paddlecolor:UIColor = UIColor.white var defaultwindowwidth:CGFloat = 200.0 var windowscale:CGFloat = 1.0 var d_blockwidth:CGFloat = 40.0 var blockwidth:CGFloat = 0.0 var blockscolor:UIColor = UIColor.white var RowCount:Int = 2 var ColumnCount:Int = 3 override func update(_ currentTime: TimeInterval) { } override init(size: CGSize) { super.init(size: size) } init(size: CGSize,configuration:JDBreaksGameConfiguration) { super.init(size: size) ballcolor = configuration.ball_color paddlecolor = configuration.paddle_color blockscolor = configuration.block_color RowCount = configuration.RowCount ColumnCount = configuration.ColumnCount } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMove(to view: SKView) { super.didMove(to: view) windowscale = (self.frame.width / defaultwindowwidth) ballwidth = d_ballwidth * windowscale paddlewidth = d_paddlewidth * windowscale blockwidth = d_blockwidth * windowscale //Set Border let borderBody = SKPhysicsBody(edgeLoopFrom: self.frame) borderBody.friction = 0 self.physicsBody = borderBody //Add Ball ball = JDBallNode(size: CGSize(width: ballwidth, height: ballwidth), color: ballcolor) self.addChild(ball) //No gravity self.physicsWorld.gravity = CGVector.zero physicsWorld.contactDelegate = self ball.physicsBody!.applyImpulse(CGVector(dx: 2.0, dy: -2.0)) //Add Paddle let paddlesize:CGSize = CGSize(width: paddlewidth, height: 15) let paddle:JDBreakPaddle = JDBreakPaddle(size: paddlesize, color: paddlecolor, radius: 5) paddle.position = CGPoint(x: self.frame.width * 0.5, y: self.frame.width * 0.2) self.addChild(paddle) addBlock() borderBody.categoryBitMask = BreaksBasicSetting.BorderCategory // } func addBlock() { // 新增方塊 let blockWidth:CGFloat = blockwidth let totalBlocksWidth = blockWidth * CGFloat(ColumnCount) // 2 let xOffset = (frame.width - totalBlocksWidth) / 2 // var FirstY:CGFloat = frame.height * 0.8 for _ in 0..<RowCount { for col in 0..<ColumnCount { let size = CGSize(width: blockWidth, height: 15) let block = JDBreaksBrick(size: size, color: blockscolor) block.position = CGPoint(x: xOffset + CGFloat(CGFloat(col)) * blockWidth, y: FirstY) block.alpha = 0.0 let fade:SKAction = SKAction.fadeAlpha(to: 1.0, duration: 2) block.run(fade) addChild(block) } FirstY -= 15 } } func breakBlock(node: SKNode) { if( SKEmitterNode(fileNamed: "BrokenPlatform") != nil) { let particles = SKEmitterNode(fileNamed: "BrokenPlatform")! particles.position = node.position particles.zPosition = 3 addChild(particles) particles.run(SKAction.sequence([SKAction.wait(forDuration: 1.0), SKAction.removeFromParent()])) } node.removeFromParent() } func randomFloat(from: CGFloat, to: CGFloat) -> CGFloat { let rand: CGFloat = CGFloat(Float(arc4random()) / 0xFFFFFFFF) return (rand) * (to - from) + from } func isGameWon() -> Bool { var numberOfBricks = 0 self.enumerateChildNodes(withName: BreaksBasicSetting.BlockCategoryName) { node, stop in numberOfBricks = numberOfBricks + 1 //有磚塊存在就+1 } return numberOfBricks == 0 } } extension JDBreaksScene { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first let touchLocation = touch!.location(in: self) if let body = physicsWorld.body(at: touchLocation) { if body.node!.name == BreaksBasicSetting.PaddleCategoryName { isFingerOnPaddle = true } } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { // 是否壓著Bar if isFingerOnPaddle { // 2 let touch = touches.first let touchLocation = touch!.location(in: self) let previousLocation = touch!.previousLocation(in: self) // 3 let paddle = childNode(withName: BreaksBasicSetting.PaddleCategoryName) as! SKShapeNode // Take the current position and add the difference between the new and the previous touch locations. var paddleX = paddle.position.x + (touchLocation.x - previousLocation.x) // Before repositioning the paddle, limit the position so that the paddle will not go off the screen to the left or right. paddleX = max(paddleX, paddle.frame.size.width/2) paddleX = min(paddleX, size.width - paddle.frame.size.width/2) // 6 paddle.position = CGPoint(x: paddleX, y: paddle.position.y) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { isFingerOnPaddle = false } } extension JDBreaksScene:SKPhysicsContactDelegate { /* Delegate */ func didBegin(_ contact: SKPhysicsContact) { // 1 var firstBody: SKPhysicsBody var secondBody: SKPhysicsBody // 2 if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask { firstBody = contact.bodyA secondBody = contact.bodyB } else { firstBody = contact.bodyB secondBody = contact.bodyA } // 球碰到磚塊 if firstBody.categoryBitMask == BreaksBasicSetting.BallCategory && secondBody.categoryBitMask == BreaksBasicSetting.BlockCategory { breakBlock(node: secondBody.node!) gameWon = isGameWon() } } }
mit
6cbd2fd42f8876c0bf2107dc26494377
31.58104
139
0.607565
4.343253
false
false
false
false
GatorNation/HackGT
HackGT2016/HackGT2016/ViewController.swift
1
1398
// // ViewController.swift // HackGT2016 // // Created by David Yeung on 9/24/16. // // import UIKit import WatchConnectivity class ViewController: UIViewController, WCSessionDelegate { @IBOutlet weak var counterLabel: UILabel! var counterData = [String]() var session: WCSession! func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?){ } func sessionDidBecomeInactive(_ session: WCSession){ } func sessionDidDeactivate(_ session: WCSession){ } override func viewDidLoad() { super.viewDidLoad() if (WCSession.isSupported()) { session = WCSession.default() session.delegate = self; session.activate() } self.counterLabel.reloadInputViews() } func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) { let counterValue = message["counterValue"] as? String //Use this to update the UI instantaneously (otherwise, takes a little while) DispatchQueue.main.async { self.counterLabel.text = counterValue!; print(counterValue!) self.counterLabel.reloadInputViews() } } }
mit
5c0cb4c6644bd7c4a1e8b964b5a9a9e2
21.548387
133
0.606581
5.10219
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/UI/Inventory/Stable/StableOverviewViewController.swift
1
1483
// // StableOverviewViewController.swift // Habitica // // Created by Phillip Thelen on 16.04.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models class StableOverviewViewController<DS>: BaseCollectionViewController { var datasource: DS? var organizeByColor = false private let headerView = NPCBannerView(frame: CGRect(x: 0, y: -124, width: UIScreen.main.bounds.size.width, height: 124)) override func viewDidLoad() { let headerXib = UINib.init(nibName: "StableSectionHeader", bundle: .main) collectionView?.register(headerXib, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "SectionHeader") let layout = collectionViewLayout as? UICollectionViewFlowLayout layout?.headerReferenceSize = CGSize(width: collectionView?.bounds.size.width ?? 50, height: 60) super.viewDidLoad() headerView.npcNameLabel.text = "Matt the Beast Master" headerView.setSprites(identifier: "stable") collectionView?.addSubview(headerView) collectionView?.contentInset = UIEdgeInsets(top: 124, left: 0, bottom: 0, right: 0) } override func applyTheme(theme: Theme) { super.applyTheme(theme: theme) collectionView.backgroundColor = theme.contentBackgroundColor headerView.applyTheme(backgroundColor: theme.contentBackgroundColor) } }
gpl-3.0
59e0f0b0350b25afe8b6e73473e0449f
36.05
152
0.707152
4.989899
false
false
false
false
mylifeasdog/iOSDevTH-Meetup-24-Nov-2015
Future.playground/Pages/Future.xcplaygroundpage/Contents.swift
1
2744
//: Future import UIKit struct User { let avatarURL: NSURL } enum UserErrorDomain: ErrorType { case UserNotFound } enum DownloadErrorDomain: ErrorType { case ServerTimeout } func downloadFile(URL: NSURL) -> Future<ErrorType, NSData> { return Future() { callback in if let data = NSData(contentsOfURL: URL) { callback(.Success(data)) } else { callback(.Failure(DownloadErrorDomain.ServerTimeout)) } } } func requestUserInfo(userID: String) -> Future<ErrorType, User> { return Future() { callback in let imagePath = NSBundle.mainBundle().pathForResource(userID.lowercaseString, ofType: "jpeg") let imageURLPath = imagePath.map() { NSURL(fileURLWithPath: $0) } let user = imageURLPath.map() { User(avatarURL: $0) } if let user = user { callback(.Success(user)) } else { callback(.Failure(UserErrorDomain.UserNotFound)) } } } func downloadImage(URL: NSURL) -> Future<ErrorType, UIImage> { return Future() { callback in downloadFile(URL).start() { result in switch result { case .Failure(let error): callback(.Failure(error)) case .Success(let data): callback(.Success(UIImage(data: data)!)) } } } } func loadAvatar(userID: String) -> Future<ErrorType, UIImage> { return Future() { callback in requestUserInfo(userID).start() { result in switch result { case .Failure(let error): callback(.Failure(error)) case .Success(let user): downloadImage(user.avatarURL).start(callback) } } } } // Fail loadAvatar("Grumpy_Cat").start { result in switch result { case .Failure(let error): do { throw error } catch DownloadErrorDomain.ServerTimeout { print("ServerTimeout") } catch UserErrorDomain.UserNotFound { print("UserNotFound") } catch _ { print("There is an error.") } case .Success(let image): image } } // Success loadAvatar("Nyan_Cat").start { result in switch result { case .Failure(let error): do { throw error } catch DownloadErrorDomain.ServerTimeout { print("ServerTimeout") } catch UserErrorDomain.UserNotFound { print("UserNotFound") } catch _ { print("There is an error.") } case .Success(let image): image } } //: [Future with Map and Then](@next)
mit
82057b3b9f9941ade1073c2009d72258
17.052632
99
0.550292
4.36248
false
false
false
false
JasonPan/ADSSocialFeedScrollView
ADSSocialFeedScrollView/Providers/Youtube/UI/YoutubePlaylistItemView.swift
1
6765
// // YoutubePlaylistItemView.swift // ADSSocialFeedScrollView // // Created by Jason Pan on 14/02/2016. // Copyright © 2016 ANT Development Studios. All rights reserved. // import UIKit import MBProgressHUD import XCDYouTubeKit class YoutubePlaylistItemView: ADSFeedPostView, PostViewProtocol { private let BASIC_PLAYLIST_ITEM_HEIGHT: CGFloat = 88 var playlistItem: YoutubeVideo! private var isPlaying: Bool = false //********************************************************************************************************* // MARK: - Interface Builder Objects //********************************************************************************************************* @IBOutlet weak var playlistItemThumbnailImageView : UIImageView! @IBOutlet weak var playlistItemTitleLabel : UILabel! @IBOutlet weak var playlistItemPublishedDateLabel : UILabel! //********************************************************************************************************* // MARK: - Constructors //********************************************************************************************************* override func initialize() { super.initialize() self.frame.size.height = BASIC_PLAYLIST_ITEM_HEIGHT self.backgroundColor = UIColor.whiteColor() if debugColours { self.playlistItemThumbnailImageView.backgroundColor = UIColor.greenColor() } self.clipsToBounds = true self.playlistItemThumbnailImageView.clipsToBounds = true self.playlistItemTitleLabel.text = self.playlistItem.title self.playlistItemThumbnailImageView.downloadedFrom(link: self.playlistItem.thumbnailImageURL, contentMode: .ScaleToFill, handler: nil) self.playlistItemPublishedDateLabel.text = ADSSocialDateFormatter.stringFromString(self.playlistItem.publishedAt, provider: .Youtube) self.playlistItemThumbnailImageView.backgroundColor = UIColor(white: 0.9, alpha: 1.0) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init(frame: CGRect, playlistItem: YoutubeVideo) { self.playlistItem = playlistItem super.init(frame: frame) } //********************************************************************************************************* // MARK: - PostViewProtocol //********************************************************************************************************* var provider: ADSSocialFeedProvider { return ADSSocialFeedProvider.Youtube } var postData: PostProtocol { return self.playlistItem } func refreshView() { // Do nothing. } //********************************************************************************************************* // MARK: - Touch handlers //********************************************************************************************************* var originalColor: UIColor? = nil override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.originalColor = self.backgroundColor self.backgroundColor = UIColor(red: 242/255, green: 242/255, blue: 242/255, alpha: 1.0) } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { self.backgroundColor = self.originalColor let videoPlayerViewController = XCDYouTubeVideoPlayerViewController(videoIdentifier: self.playlistItem.id) NSNotificationCenter.defaultCenter().addObserver(self, selector: "moviePlayerPlaybackDidFinish:", name: MPMoviePlayerPlaybackDidFinishNotification, object: videoPlayerViewController.moviePlayer) videoPlayerViewController.moviePlayer.play() ADSSocialFeedGlobal.HUD_DISPLAY_WINDOW.hidden = false let hud = MBProgressHUD.showHUDAddedTo(ADSSocialFeedGlobal.HUD_DISPLAY_WINDOW, animated: true) hud.backgroundView.style = .SolidColor//.Blur hud.backgroundView.color = UIColor(white: 0, alpha: 0.7) hud.label.text = "Loading video..." self.isPlaying = true dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { repeat {} while !videoPlayerViewController.moviePlayer.isPreparedToPlay && self.isPlaying == true dispatch_async(dispatch_get_main_queue(), { hud.hideAnimated(true) self.isPlaying = false ADSSocialFeedGlobal.HUD_DISPLAY_WINDOW.hidden = true if videoPlayerViewController.moviePlayer.isPreparedToPlay { ADSSocialFeedGlobal.ROOT_VIEW_CONTROLLER?.presentMoviePlayerViewControllerAnimated(videoPlayerViewController) } }) }) } override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { self.backgroundColor = self.originalColor } //********************************************************************************************************* // MARK: - MPMoviePlayerPlaybackDidFinishNotification //********************************************************************************************************* func moviePlayerPlaybackDidFinish(notification: NSNotification) { NSNotificationCenter.defaultCenter().removeObserver(self, name: MPMoviePlayerPlaybackDidFinishNotification, object: notification.object) let finishReason: MPMovieFinishReason = MPMovieFinishReason(rawValue: notification.userInfo![MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] as! Int)! if (finishReason == MPMovieFinishReason.PlaybackError) { if let error = notification.userInfo?[XCDMoviePlayerPlaybackDidFinishErrorUserInfoKey] as? NSError { NSLog("[ADSSocialFeedScrollView][Youtube] An error occurred while playing video: \(error.description)") let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil)) ADSSocialFeedGlobal.ROOT_VIEW_CONTROLLER?.presentViewController(alert, animated: true, completion: nil) } // Handle error self.isPlaying = false } } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ }
mit
89dadb3a5e36ee0bd307b4325f67b823
42.922078
202
0.56165
6.160291
false
false
false
false
prolificinteractive/simcoe
Simcoe/SimcoeProduct.swift
1
1097
// // SimcoeProduct.swift // Simcoe // // Created by Michael Campbell on 10/25/16. // Copyright © 2016 Prolific Interactive. All rights reserved. // /// The product. public struct SimcoeProduct { /// The product name. public let productName: String /// The product Id. public let productId: String /// The quantity. public let quantity: Int /// The price. public let price: Double? /// The properties. public let properties: Properties? /// The default initializer. /// /// - Parameters: /// - productName: The product name. /// - productId: The product Id. /// - quantity: The quantity. /// - price: The price. /// - properties: The properties. public init(productName: String, productId: String, quantity: Int, price: Double?, properties: Properties?) { self.productName = productName self.productId = productId self.quantity = quantity self.price = price self.properties = properties } }
mit
8fc8dbf9eba730aee07afb247a96d07c
22.826087
63
0.583029
4.566667
false
false
false
false
abertelrud/swift-package-manager
Sources/PackageCollections/Model/Search.swift
2
1958
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2020-2022 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 struct Foundation.URL extension PackageCollectionsModel { /// A representation of package in search result public struct PackageSearchResult { /// Result items of the search public let items: [Item] /// Represents a search result item public struct Item: Encodable { // Merged package metadata from across collections /// The matching package public let package: PackageCollectionsModel.Package /// Package collections that contain the package public internal(set) var collections: [PackageCollectionsModel.CollectionIdentifier] /// Package indexes that contain the package public internal(set) var indexes: [URL] init( package: PackageCollectionsModel.Package, collections: [PackageCollectionsModel.CollectionIdentifier] = [], indexes: [URL] = [] ) { self.package = package self.collections = collections self.indexes = indexes } } } /// An enum of target search types public enum TargetSearchType { case prefix case exactMatch } /// A representation of target in search result public struct TargetSearchResult { /// Result items of the search public let items: [TargetListItem] } }
apache-2.0
827fdd4b6246e2072f299835963a30d5
33.964286
96
0.573034
6.04321
false
false
false
false
Raiden9000/Sonarus
MusicCell.swift
1
4531
// // MusicCell.swift // Sonarus // // Created by Christopher Arciniega on 7/13/17. // Copyright © 2017 HQZenithLabs. All rights reserved. // import Foundation class MusicCell:UITableViewCell{ let topLabel = UILabel() let lowerLabel = UILabel() let singleLabel = UILabel() let artView = UIImageView() let button = UIButton() private let bottomLine = UIButton() //Info var smallArt = UIImage() var largeArt = UIImage() var link = URL(string:"") //playableURI var songName = "" var artistName = "" var trackID = "" override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.backgroundColor = UIColor.black self.topLabel.textColor = UIColor.white self.lowerLabel.textColor = UIColor.gray self.singleLabel.textColor = UIColor.white self.clipsToBounds = true self.contentView.clipsToBounds = true //AUTO-LAYOUT //Remove Autoresizing Mask so Autolayout does not declare positioning at runtime, but we do artView.translatesAutoresizingMaskIntoConstraints = false topLabel.translatesAutoresizingMaskIntoConstraints = false lowerLabel.translatesAutoresizingMaskIntoConstraints = false singleLabel.translatesAutoresizingMaskIntoConstraints = false button.translatesAutoresizingMaskIntoConstraints = false //Adding views self.contentView.addSubview(artView) self.contentView.addSubview(topLabel) self.contentView.addSubview(lowerLabel) self.contentView.addSubview(singleLabel) self.contentView.addSubview(button) self.contentView.addSubview(bottomLine) //button.setImage(UIImage(named: "qButton"), for: UIControlState.normal) button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside) //Options artView.sizeToFit() artView.contentMode = .scaleAspectFit lowerLabel.font = lowerLabel.font.withSize(11) //Constraints NSLayoutConstraint.activate([ topLabel.leftAnchor.constraint(equalTo: artView.rightAnchor, constant: 3), topLabel.topAnchor.constraint(equalTo: self.contentView.topAnchor), lowerLabel.leftAnchor.constraint(equalTo: artView.rightAnchor, constant: 3), lowerLabel.topAnchor.constraint(equalTo: topLabel.bottomAnchor, constant: 2), singleLabel.leftAnchor.constraint(equalTo: self.contentView.leftAnchor, constant: 8), singleLabel.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor), artView.leftAnchor.constraint(equalTo: self.contentView.leftAnchor), artView.topAnchor.constraint(equalTo: self.contentView.topAnchor), button.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor), button.rightAnchor.constraint(equalTo: self.contentView.rightAnchor, constant: -5), button.heightAnchor.constraint(equalTo: self.contentView.heightAnchor) ]) } func turnOnLines(){ bottomLine.translatesAutoresizingMaskIntoConstraints = false bottomLine.setImage(UIImage(named: "lineSeparator"), for: .normal) bottomLine.tintColor = UIColor.init(red: 0.0, green: 195/255, blue: 229.0, alpha: 0.5) bottomLine.backgroundColor = UIColor.clear NSLayoutConstraint.activate([ bottomLine.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor), bottomLine.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor), bottomLine.widthAnchor.constraint(equalTo: self.contentView.widthAnchor), bottomLine.heightAnchor.constraint(equalToConstant: 1) ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func buttonPressed(_ sender: AnyObject?){ preconditionFailure("This method must be overridden") } func hideButton(){ button.isHidden = true } 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
a252fa1bc65229494a1805d0bbbc9795
37.389831
99
0.67064
5.249131
false
false
false
false
blakemerryman/Swift-Scripts
Intro Examples/5-DynamicInput.swift
1
640
#!/usr/bin/env xcrun swift import Foundation let userInput = Process.arguments if userInput.count > 1 { let flag = userInput[1] if flag == "--print" { print("\nPrinting Args: \(Process.arguments)\n") } if flag == "--help" { print("\nWhat would you like help with?\n") let stdin = NSFileHandle.fileHandleWithStandardInput() let inputString = NSString(data: stdin.availableData, encoding: NSUTF8StringEncoding) as! String if inputString.isEmpty == false { print("\nYou're going to need a lot of help with that...\n") } } // Handle other flags... }
mit
8f6081bcabdd7ae0e5dcaf1e17da0336
21.857143
104
0.614063
4.183007
false
false
false
false
EugeneVegner/sws-copyleaks-sdk-test
PlagiarismChecker/Classes/CopyleaksToken.swift
1
4009
/* * The MIT License(MIT) * * Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ import Foundation private let copyleaksToken = "copyleaksToken" class CopyleaksToken: NSObject, NSCoding { var accessToken: String? var issued: String? var expires: String? private let copyleaksTokenKey = "copyleaksTokenKey" private let copyleaksTokenIssued = "copyleaksTokenIssued" private let copyleaksTokenExpired = "copyleaksTokenExpired" init(response: CopyleaksResponse<AnyObject, NSError>) { if let accessTokenVal = response.result.value?["access_token"] as? String, let issuedVal = response.result.value?[".issued"] as? String, let expiresVal = response.result.value?[".expires"] as? String { accessToken = accessTokenVal issued = issuedVal expires = expiresVal } } required init(coder aDecoder: NSCoder) { accessToken = aDecoder.decodeObjectForKey(copyleaksTokenKey) as? String issued = aDecoder.decodeObjectForKey(copyleaksTokenIssued) as? String expires = aDecoder.decodeObjectForKey(copyleaksTokenExpired) as? String } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(accessToken, forKey: copyleaksTokenKey) aCoder.encodeObject(issued, forKey: copyleaksTokenIssued) aCoder.encodeObject(expires, forKey: copyleaksTokenExpired) } func save() { let data = NSKeyedArchiver.archivedDataWithRootObject(self) let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(data, forKey:copyleaksToken ) } func isValid() -> Bool { guard let accessTokenVal = accessToken, issuedVal = issued, expiresVal = expires else { return false } let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = CopyleaksConst.dateTimeFormat dateFormatter.timeZone = NSTimeZone(name: "UTC") let issuedDate = dateFormatter.dateFromString(issuedVal) let expiresDate = dateFormatter.dateFromString(expiresVal) return true } func generateAccessToken() -> String { if self.isValid() { return "Bearer " + accessToken! } else { return "" } } class func hasAccessToken() -> Bool { guard let _ = getAccessToken() else { return false } return true } class func getAccessToken() -> CopyleaksToken? { if let data = NSUserDefaults.standardUserDefaults().objectForKey(copyleaksToken) as? NSData { return (NSKeyedUnarchiver.unarchiveObjectWithData(data) as? CopyleaksToken)! } return nil } class func clear() { NSUserDefaults.standardUserDefaults().removeObjectForKey(copyleaksToken) } }
mit
d741a0a9b515ab9c308665b84932f6df
33.86087
101
0.676727
4.992528
false
false
false
false
kickstarter/ios-oss
Library/ViewModels/CancelPledgeViewModel.swift
1
6601
import KsApi import Prelude import ReactiveSwift import UIKit public struct CancelPledgeViewData { public let project: Project // TODO: remove once tracking is updated. public let projectName: String public let omitUSCurrencyCode: Bool public let backingId: String public let pledgeAmount: Double } public protocol CancelPledgeViewModelInputs { func cancelPledgeButtonTapped() func configure(with data: CancelPledgeViewData) func goBackButtonTapped() func textFieldDidEndEditing(with text: String?) func textFieldShouldReturn() func traitCollectionDidChange() func viewDidLoad() func viewTapped() } public protocol CancelPledgeViewModelOutputs { var cancellationDetailsAttributedText: Signal<NSAttributedString, Never> { get } var cancelPledgeButtonEnabled: Signal<Bool, Never> { get } var cancelPledgeError: Signal<String, Never> { get } var dismissKeyboard: Signal<Void, Never> { get } var isLoading: Signal<Bool, Never> { get } var notifyDelegateCancelPledgeSuccess: Signal<String, Never> { get } var popCancelPledgeViewController: Signal<Void, Never> { get } } public protocol CancelPledgeViewModelType { var inputs: CancelPledgeViewModelInputs { get } var outputs: CancelPledgeViewModelOutputs { get } } public final class CancelPledgeViewModel: CancelPledgeViewModelType, CancelPledgeViewModelInputs, CancelPledgeViewModelOutputs { public init() { let data = Signal.combineLatest( self.configureWithDataProperty.signal.skipNil(), self.viewDidLoadProperty.signal ) .map(first) self.cancellationDetailsAttributedText = Signal.merge( data, data.takeWhen(self.traitCollectionDidChangeProperty.signal) ) .map { data in let projectCurrencyCountry = projectCountry(forCurrency: data.project.stats.currency) ?? data.project .country let formattedAmount = Format.currency( data.pledgeAmount, country: projectCurrencyCountry, omitCurrencyCode: data.omitUSCurrencyCode ) return (formattedAmount, data.projectName) } .map(createCancellationDetailsAttributedText(with:projectName:)) self.popCancelPledgeViewController = self.goBackButtonTappedProperty.signal self.dismissKeyboard = Signal.merge( self.textFieldShouldReturnProperty.signal, self.viewTappedProperty.signal ) let cancellationNote = Signal.merge( self.viewDidLoadProperty.signal.mapConst(nil), self.textFieldDidEndEditingTextProperty.signal ) let cancelPledgeSubmit = Signal.combineLatest( data.map { $0.backingId }, cancellationNote ) .takeWhen(self.cancelPledgeButtonTappedProperty.signal) let cancelPledgeEvent = cancelPledgeSubmit .map(CancelBackingInput.init(backingId:cancellationReason:)) .switchMap { input in AppEnvironment.current.apiService.cancelBacking(input: input) .ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler) .materialize() } self.isLoading = Signal.merge( self.cancelPledgeButtonTappedProperty.signal.mapConst(true), cancelPledgeEvent.filter { $0.isTerminating }.mapConst(false) ) self.notifyDelegateCancelPledgeSuccess = cancelPledgeEvent.values() .map { _ in Strings.Youve_canceled_your_pledge() } self.cancelPledgeError = cancelPledgeEvent .errors() .map { $0.localizedDescription } self.cancelPledgeButtonEnabled = Signal.merge( data.mapConst(true), cancelPledgeSubmit.mapConst(false), cancelPledgeEvent.map { $0.isTerminating }.mapConst(true) ) .skipRepeats() } private let cancelPledgeButtonTappedProperty = MutableProperty(()) public func cancelPledgeButtonTapped() { self.cancelPledgeButtonTappedProperty.value = () } private let configureWithDataProperty = MutableProperty<CancelPledgeViewData?>(nil) public func configure(with data: CancelPledgeViewData) { self.configureWithDataProperty.value = data } private let goBackButtonTappedProperty = MutableProperty(()) public func goBackButtonTapped() { self.goBackButtonTappedProperty.value = () } private let textFieldDidEndEditingTextProperty = MutableProperty<String?>(nil) public func textFieldDidEndEditing(with text: String?) { self.textFieldDidEndEditingTextProperty.value = text } private let textFieldShouldReturnProperty = MutableProperty(()) public func textFieldShouldReturn() { self.textFieldShouldReturnProperty.value = () } private let traitCollectionDidChangeProperty = MutableProperty(()) public func traitCollectionDidChange() { self.traitCollectionDidChangeProperty.value = () } private let viewDidLoadProperty = MutableProperty(()) public func viewDidLoad() { self.viewDidLoadProperty.value = () } private let viewTappedProperty = MutableProperty(()) public func viewTapped() { self.viewTappedProperty.value = () } public let cancellationDetailsAttributedText: Signal<NSAttributedString, Never> public let cancelPledgeButtonEnabled: Signal<Bool, Never> public let cancelPledgeError: Signal<String, Never> public let dismissKeyboard: Signal<Void, Never> public let isLoading: Signal<Bool, Never> public let notifyDelegateCancelPledgeSuccess: Signal<String, Never> public let popCancelPledgeViewController: Signal<Void, Never> public var inputs: CancelPledgeViewModelInputs { return self } public var outputs: CancelPledgeViewModelOutputs { return self } } private func createCancellationDetailsAttributedText(with amount: String, projectName: String) -> NSAttributedString { let fullString = Strings .Are_you_sure_you_wish_to_cancel_your_amount_pledge_to_project_name( amount: amount, project_name: projectName ) let attributedString: NSMutableAttributedString = NSMutableAttributedString.init(string: fullString) let regularFontAttribute = [NSAttributedString.Key.font: UIFont.ksr_callout()] let boldFontAttribute = [NSAttributedString.Key.font: UIFont.ksr_callout().bolded] let fullRange = (fullString as NSString).localizedStandardRange(of: fullString) let rangeAmount: NSRange = (fullString as NSString).localizedStandardRange(of: amount) let rangeProjectName: NSRange = (fullString as NSString).localizedStandardRange(of: projectName) attributedString.addAttributes(regularFontAttribute, range: fullRange) attributedString.addAttributes(boldFontAttribute, range: rangeAmount) attributedString.addAttributes(boldFontAttribute, range: rangeProjectName) return attributedString }
apache-2.0
4eed80880e63919e233425372e942ff6
35.071038
107
0.763369
4.981887
false
false
false
false
a1exb1/ABToolKit-pod
Pod/Classes/CompresJSON/CompresJSON.swift
1
1742
// // CompresJSON.swift // EncryptionTests3 // // Created by Alex Bechmann on 08/05/2015. // Copyright (c) 2015 Alex Bechmann. All rights reserved. // import UIKit let kCompresJSONSharedInstance = CompresJSON() public class CompresJSON: NSObject { public class func sharedInstance() -> CompresJSON { return kCompresJSONSharedInstance } public var settings: CompresJSONSettings = CompresJSONSettings() public class func encryptAndCompressAsNecessary(str: String, shouldEncrypt: Bool, shouldCompress: Bool) -> String { var rc = str if shouldCompress { rc = rc.compress() } if shouldEncrypt { CompresJSON.printErrorIfEncryptionKeyIsNotSet() rc = Encryptor.encrypt(rc, key: CompresJSON.sharedInstance().settings.encryptionKey) } return rc } public class func decryptAndDecompressAsNecessary(str: String, shouldEncrypt: Bool, shouldCompress: Bool) -> String { var rc = str if shouldEncrypt { CompresJSON.printErrorIfEncryptionKeyIsNotSet() rc = Encryptor.decrypt(rc, key: CompresJSON.sharedInstance().settings.encryptionKey) } if shouldCompress { rc = rc.decompress() } return rc } public class func printErrorIfEncryptionKeyIsNotSet() { if CompresJSON.sharedInstance().settings.encryptionKey == "" { println("Encryption key not set: add to appdelegate: CompresJSON.sharedInstance().settings.encryptionKey = xxxx") } } }
mit
25c9b6d32c8aa2d9a49a84354a330e7e
24.617647
125
0.595867
5.005747
false
false
false
false
stubbornnessness/EasySwift
Carthage/Checkouts/YXJImageCompressor/YXJImageCompressorTest/YXJImageCompressorTest/ViewController.swift
2
3574
// // ViewController.swift // YXJImageCompressorTest // // Created by yuanxiaojun on 16/8/11. // Copyright © 2016年 袁晓钧. All rights reserved. // import UIKit import YXJImageCompressor class ViewController: UIViewController { var ScreenWidth: CGFloat { return UIScreen.main.bounds.width } var ScreenHeight: CGFloat { return UIScreen.main.bounds.height } override func viewDidLoad() { super.viewDidLoad() let tv = UITextView(frame: CGRect(x: 0, y: 20, width: ScreenWidth, height: ScreenHeight - 20)) tv.font = UIFont.systemFont(ofSize: 14) self.view.addSubview(tv) /// 原图 let oldImg = UIImage(named: "img.JPG") let oldData = UIImageJPEGRepresentation(oldImg!, 0.7) tv.text.append("原图大小 \(M(Double(oldData!.count))) M \n") tv.text.append("原图宽度 \(oldImg?.size.width) \n") tv.text.append("原图高度 \(oldImg?.size.height) \n\n") tv.text.append("-------------------------------\n") /// 压缩方式一:最大边不超过某个值等比例压缩 let px_1000_img = YXJImageCompressor.yxjImage(with: _1000PX, sourceImage: oldImg) let px_1000_data = UIImageJPEGRepresentation(px_1000_img!, 0.7) tv.text.append("最大边不超过1000PX的大小 \(M(Double(px_1000_data!.count))) M \n") tv.text.append("最大边不超过1000PX宽度 \(px_1000_img?.size.width)\n") tv.text.append("最大边不超过1000PX高度 \(px_1000_img?.size.height)\n\n") tv.text.append("-------------------------------\n") let px_100_img = YXJImageCompressor.yxjImage(with: _100PX, sourceImage: oldImg) let px_100_data = UIImageJPEGRepresentation(px_100_img!, 0.7) tv.text.append("最大边不超过100PX的大小 \(M(Double(px_100_data!.count))) M\n") tv.text.append("最大边不超过100PX宽度 \(px_100_img?.size.width)\n") tv.text.append("最大边不超过100PX高度 \(px_100_img?.size.height)\n\n") tv.text.append("-------------------------------\n") /// 压缩方式二:图片大小不超过某个值已经最大边不超过某个像素等比例压缩 YXJImageCompressor.yxjCompressImage(oldImg, limitSize: _1M, maxSide: _1000PX) { (data) in let img = UIImage(data: data!) tv.text.append("图片最大值不超过最大边1M 以及 最大边不超过1000PX的大小 \(self.M(Double((data?.count)!))) M\n") tv.text.append("图片最大值不超过最大边1M 以及 最大边不超过1000PX的宽度 \(img!.size.width)\n") tv.text.append("图片最大值不超过最大边1M 以及 最大边不超过1000PX的高度 \(img!.size.height)\n\n") tv.text.append("-------------------------------\n") } YXJImageCompressor.yxjCompressImage(oldImg, limitSize: _64K, maxSide: _100PX) { (data) in let img = UIImage(data: data!) tv.text.append("图片最大值不超过最大边64K 以及 最大边不超过100PX的大小 \(self.M(Double((data?.count)!))) M\n") tv.text.append("图片最大值不超过最大边64K 以及 最大边不超过100PX的宽度 \(img!.size.width)\n") tv.text.append("图片最大值不超过最大边64K 以及 最大边不超过100PX的高度 \(img!.size.height)\n\n") } } func M(_ k: Double) -> Double { return k / Double(_1M.rawValue) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
apache-2.0
fd255fbd02e6a004e6a8fd5cc8238b26
37.3375
102
0.603195
3.211518
false
false
false
false
onevcat/CotEditor
CotEditor/Sources/SeparatorTextField.swift
2
1811
// // SeparatorTextField.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2014-04-13. // // --------------------------------------------------------------------------- // // © 2014-2021 1024jp // // 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 // // https://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 Cocoa final class SeparatorTextField: NSTextField { // MARK: Text Field Methods override var intrinsicContentSize: NSSize { var size = super.intrinsicContentSize if self.isSeparator { size.height = (size.height / 2).rounded(.up) } return size } override func draw(_ dirtyRect: NSRect) { guard self.isSeparator else { return super.draw(dirtyRect) } NSGraphicsContext.saveGraphicsState() let separatorRect = NSRect(x: dirtyRect.minX, y: self.frame.midY, width: dirtyRect.width, height: 1) NSColor.gridColor.setFill() self.centerScanRect(separatorRect).fill() NSGraphicsContext.restoreGraphicsState() } // MARK: Private Properties /// whether it is a separator item private var isSeparator: Bool { return self.stringValue == .separator } }
apache-2.0
1c937651679d9ab33dec2ae9a63f9c2e
25.231884
108
0.6
4.725849
false
false
false
false
maarten/Ximian
Ximian/String-Extras.swift
1
775
// // String-Extras.swift // Swift Tools // // Created by Fahim Farook on 23/7/14. // Copyright (c) 2014 RookSoft Pte. Ltd. All rights reserved. // import AppKit extension String { func positionOf(sub:String)->Int { var pos = -1 if let range = range(of:sub) { if !range.isEmpty { pos = characters.distance(from:startIndex, to:range.lowerBound) } } return pos } func subString(start:Int, length:Int = -1)->String { var len = length if len == -1 { len = characters.count - start } let st = characters.index(startIndex, offsetBy:start) let en = characters.index(st, offsetBy:len) let range = st ..< en return substring(with:range) } func range()->Range<String.Index> { return Range<String.Index>(startIndex ..< endIndex) } }
mit
69cd7257fdf2b576a25ae0c191d8cfb3
19.945946
67
0.656774
3.015564
false
false
false
false
mathiasquintero/GitHub
GitHub/Classes/Model/Owner.swift
1
1337
// // Owner.swift // Sweeft // // Created by Mathias Quintero on 9/27/17. // import Foundation public enum Owner: Codable { case user(User) case organization(Organization) public enum CodingKeys: String, CodingKey { case type } enum `Type`: String, Codable { case user = "User" case organization = "Organization" } } extension Owner { private var type: Type { switch self { case .user: return .user case .organization: return .organization } } public init(from decoder: Decoder) throws { switch try decoder.container(keyedBy: CodingKeys.self).decode(Type.self, forKey: .type) { case .user: self = .user(try User(from: decoder)) case .organization: self = .organization(try Organization(from: decoder)) } } public func encode(to encoder: Encoder) throws { switch self { case .user(let user): try user.encode(to: encoder) case .organization(let organization): try organization.encode(to: encoder) } var containter = encoder.container(keyedBy: CodingKeys.self) try containter.encode(type, forKey: .type) } }
mit
67d7467031e5404871a7b3c29c48118c
21.661017
97
0.559461
4.486577
false
false
false
false
zxpLearnios/MyProject
test_projectDemo1/TVC && NAV/TabBar/MyTabBar.swift
1
2436
// // MyTabBar.swift // test_projectDemo1 // // Created by Jingnan Zhang on 16/5/30. // Copyright © 2016年 Jingnan Zhang. All rights reserved. // 虽然替换了tabbar,但设置tabbar自身的属性时,还需在TVC里进行 import UIKit class MyTabBar: UITabBar { fileprivate let totalCount:CGFloat = 4 // 必须自己来修改,这样其实会更方便 var buttonW:CGFloat = 0.0 // 方便外界的加号按钮来设置 var onceToken:Int = 0 // MARK: 初始化 override init(frame: CGRect) { super.init(frame: frame) self.doInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } fileprivate func doInit() { } // 有几个子控件就会调用几次 override func layoutSubviews() { super.layoutSubviews() let buttonY:CGFloat = 0 buttonW = self.frame.width / totalCount let buttonH = self.frame.height var index:CGFloat = 0 debugPrint("layoutSubviews-------tabbar") // dispatch_once(&onceToken) { for item in self.subviews { var buttonX = index * self.buttonW // 只找出 所有的UITabBarItem, if item.isKind(of: UIControl.classForCoder()) { if index > 0 { buttonX = (index + 1) * self.buttonW } item.frame = CGRect(x: buttonX, y: buttonY, width: self.buttonW, height: buttonH) index += 1 // 最后一个加的控制器多对应的item, 此时将此item放在第二个的位置处; if index == self.totalCount { let rVC = kwindow!.rootViewController as! MyCustomTVC if rVC.isCompleteAnimate { // 在按钮动画结束后, 移除并加新的按钮 rVC.plusBtn.removeFromSuperview() buttonX = self.buttonW item.frame = CGRect(x: buttonX, y: buttonY, width: self.buttonW, height: buttonH) } } } // } } } }
mit
1e14da73182dfd96de4b07818dea8b51
26.5375
109
0.470268
4.657505
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/VideoStickerContentView.swift
1
9132
// // VideoStickerContentView.swift // Telegram-Mac // // Created by keepcoder on 10/11/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa import TelegramCore import TGUIKit import Postbox import SwiftSignalKit class VideoStickerContentView: ChatMediaContentView { private var player:GifPlayerBufferView private var placeholderView: StickerShimmerEffectView? private let fetchDisposable = MetaDisposable() private let playerDisposable = MetaDisposable() private let statusDisposable = MetaDisposable() override var backgroundColor: NSColor { set { super.backgroundColor = .clear } get { return super.backgroundColor } } override func previewMediaIfPossible() -> Bool { guard let context = self.context, let window = self.kitWindow, let table = self.table else {return false} startModalPreviewHandle(table, window: window, context: context) return true } required init(frame frameRect: NSRect) { player = GifPlayerBufferView(frame: frameRect.size.bounds) super.init(frame: frameRect) addSubview(player) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func clean() { playerDisposable.dispose() statusDisposable.dispose() removeNotificationListeners() } override func cancel() { fetchDisposable.set(nil) } override func fetch(userInitiated: Bool) { if let context = context, let media = media as? TelegramMediaFile { if let parent = parent { fetchDisposable.set(messageMediaFileInteractiveFetched(context: context, messageId: parent.id, messageReference: .init(parent), file: media, userInitiated: false).start()) } else { fetchDisposable.set(freeMediaFileInteractiveFetched(context: context, fileReference: FileMediaReference.standalone(media: media)).start()) } } } override func layout() { super.layout() player.frame = bounds self.player.positionFlags = positionFlags updatePlayerIfNeeded() } func removeNotificationListeners() { NotificationCenter.default.removeObserver(self) } override func viewDidUpdatedDynamicContent() { super.viewDidUpdatedDynamicContent() updatePlayerIfNeeded() } @objc func updatePlayerIfNeeded() { let accept = window != nil && window!.isKeyWindow && !NSIsEmptyRect(visibleRect) && !self.isDynamicContentLocked player.ticking = accept } func updateListeners() { if let window = window { NotificationCenter.default.removeObserver(self) NotificationCenter.default.addObserver(self, selector: #selector(updatePlayerIfNeeded), name: NSWindow.didBecomeKeyNotification, object: window) NotificationCenter.default.addObserver(self, selector: #selector(updatePlayerIfNeeded), name: NSWindow.didResignKeyNotification, object: window) NotificationCenter.default.addObserver(self, selector: #selector(updatePlayerIfNeeded), name: NSView.boundsDidChangeNotification, object: table?.clipView) NotificationCenter.default.addObserver(self, selector: #selector(updatePlayerIfNeeded), name: NSView.frameDidChangeNotification, object: table?.view) } else { removeNotificationListeners() } } override func willRemove() { super.willRemove() updateListeners() updatePlayerIfNeeded() } override func viewDidMoveToWindow() { updateListeners() updatePlayerIfNeeded() } deinit { //player.set(data: nil) } var blurBackground: Bool { return (parent != nil && parent?.groupingKey == nil) || parent == nil } override func update(with media: Media, size: NSSize, context: AccountContext, parent: Message?, table: TableView?, parameters:ChatMediaLayoutParameters? = nil, animated: Bool = false, positionFlags: LayoutPositionFlags? = nil, approximateSynchronousValue: Bool = false) { let mediaUpdated = self.media == nil || !self.media!.isSemanticallyEqual(to: media) super.update(with: media, size: size, context: context, parent:parent,table:table, parameters:parameters, animated: animated, positionFlags: positionFlags) var topLeftRadius: CGFloat = .cornerRadius var bottomLeftRadius: CGFloat = .cornerRadius var topRightRadius: CGFloat = .cornerRadius var bottomRightRadius: CGFloat = .cornerRadius if let positionFlags = positionFlags { if positionFlags.contains(.top) && positionFlags.contains(.left) { topLeftRadius = topLeftRadius * 3 + 2 } if positionFlags.contains(.top) && positionFlags.contains(.right) { topRightRadius = topRightRadius * 3 + 2 } if positionFlags.contains(.bottom) && positionFlags.contains(.left) { bottomLeftRadius = bottomLeftRadius * 3 + 2 } if positionFlags.contains(.bottom) && positionFlags.contains(.right) { bottomRightRadius = bottomRightRadius * 3 + 2 } } updateListeners() self.player.positionFlags = positionFlags if let media = media as? TelegramMediaFile { let dimensions = media.dimensions?.size ?? size let reference = parent != nil ? FileMediaReference.message(message: MessageReference(parent!), media: media) : FileMediaReference.standalone(media: media) let fitted = dimensions.aspectFilled(size) player.setVideoLayerGravity(.resizeAspect) let arguments = TransformImageArguments(corners: ImageCorners(topLeft: .Corner(topLeftRadius), topRight: .Corner(topRightRadius), bottomLeft: .Corner(bottomLeftRadius), bottomRight: .Corner(bottomRightRadius)), imageSize: fitted, boundingSize: size, intrinsicInsets: NSEdgeInsets(), resizeMode: .blurBackground) player.update(reference, context: context, resizeInChat: blurBackground) if !player.isRendering { let hasPlaceholder = (parent == nil || media.immediateThumbnailData != nil) && self.player.image == nil if hasPlaceholder { let current: StickerShimmerEffectView if let local = self.placeholderView { current = local } else { current = StickerShimmerEffectView() current.frame = bounds self.placeholderView = current addSubview(current, positioned: .below, relativeTo: player) if animated { current.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) } } current.update(backgroundColor: nil, foregroundColor: NSColor(rgb: 0x748391, alpha: 0.2), shimmeringColor: NSColor(rgb: 0x748391, alpha: 0.35), data: media.immediateThumbnailData, size: size) current.updateAbsoluteRect(bounds, within: size) } else { self.removePlaceholder(animated: animated) } self.player.imageUpdated = { [weak self] value in if value != nil { self?.removePlaceholder(animated: animated) } } player.setSignal(signal: cachedMedia(media: media, arguments: arguments, scale: backingScaleFactor, positionFlags: positionFlags), clearInstantly: mediaUpdated) let signal = chatMessageSticker(postbox: context.account.postbox, file: reference, small: size.width < 120, scale: backingScaleFactor) player.setSignal(signal, animate: animated, cacheImage: { [weak media] result in if let media = media { cacheMedia(result, media: media, arguments: arguments, scale: System.backingScale, positionFlags: positionFlags) } }) player.set(arguments: arguments) } else { self.removePlaceholder(animated: animated) } } fetch(userInitiated: false) } private func removePlaceholder(animated: Bool) { if let view = self.placeholderView { performSubviewRemoval(view, animated: animated) self.placeholderView = nil } } override var contents: Any? { return player.layer?.contents } override open func copy() -> Any { return player.copy() } }
gpl-2.0
f6dcde47fdde0ed28484cdc5182c82d7
38.528139
323
0.611543
5.399763
false
false
false
false
huangboju/Eyepetizer
Eyepetizer/Eyepetizer/Lib/GuillotineMenu/GuillotineMenuTransitionAnimation.swift
1
13819
// // GuillotineTransitionAnimation.swift // GuillotineMenu // // Created by Maksym Lazebnyi on 3/24/15. // Copyright (c) 2015 Yalantis. All rights reserved. // import UIKit @objc protocol GuillotineMenu: NSObjectProtocol { optional var dismissButton: UIButton! { get } optional var titleLabel: UILabel! { get } } @objc protocol GuillotineAnimationDelegate: NSObjectProtocol { optional func animatorDidFinishPresentation(animator: GuillotineTransitionAnimation) optional func animatorDidFinishDismissal(animator: GuillotineTransitionAnimation) optional func animatorWillStartPresentation(animator: GuillotineTransitionAnimation) optional func animatorWillStartDismissal(animator: GuillotineTransitionAnimation) } class GuillotineTransitionAnimation: NSObject { enum Mode { case Presentation, Dismissal } //MARK: - Public properties weak var animationDelegate: GuillotineAnimationDelegate? var mode: Mode = .Presentation var supportView: UIView? var presentButton: UIView? var duration = 0.6 //MARK: - Private properties private var chromeView: UIView? private var containerMenuButton: UIButton? { didSet { presentButton?.addObserver(self, forKeyPath: "frame", options: .New, context: myContext) } } private var displayLink: CADisplayLink! private var vectorDY: CGFloat = 1500 private var fromYPresentationLandscapeAdjustment: CGFloat = 1.0 private var fromYDismissalLandscapeAdjustment: CGFloat = 1.0 private var toYDismissalLandscapeAdjustment: CGFloat = 1.0 private var fromYPresentationAdjustment: CGFloat = 1.0 private var fromYDismissalAdjustment: CGFloat = 1.0 private var toXPresentationLandscapeAdjustment: CGFloat = 1.0 private let initialMenuRotationAngle: CGFloat = -90 private let menuElasticity: CGFloat = 0.6 private let vectorDYCoefficient: Double = 2 / M_PI private var topOffset: CGFloat = 0 private var anchorPoint: CGPoint! private var menu: UIViewController! private var animationContext: UIViewControllerContextTransitioning! private var animator: UIDynamicAnimator! private let myContext: UnsafeMutablePointer<()> = nil //MARK: - Deinitialization deinit { displayLink.invalidate() presentButton?.removeObserver(self, forKeyPath: "frame") } //MARK: - Initialization override init() { super.init() setupDisplayLink() setupSystemVersionAdjustment() } //MARK: - Private methods private func animatePresentation(context: UIViewControllerContextTransitioning) { menu = context.viewControllerForKey(UITransitionContextToViewControllerKey)! context.containerView()!.addSubview(menu.view) if UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight { updateChromeView() menu.view.addSubview(chromeView!) } if menu is GuillotineMenu { if supportView != nil && presentButton != nil { let guillotineMenu = menu as! GuillotineMenu containerMenuButton = guillotineMenu.dismissButton setupContainerMenuButtonFrameAndTopOffset() context.containerView()!.addSubview(containerMenuButton!) } } let fromVC = context.viewControllerForKey(UITransitionContextFromViewControllerKey) fromVC?.beginAppearanceTransition(false, animated: true) animationDelegate?.animatorWillStartPresentation?(self) animateMenu(menu.view, context: context) } private func animateDismissal(context: UIViewControllerContextTransitioning) { menu = context.viewControllerForKey(UITransitionContextFromViewControllerKey)! if menu.navigationController != nil { let toVC = context.viewControllerForKey(UITransitionContextToViewControllerKey)! context.containerView()!.addSubview(toVC.view) context.containerView()!.sendSubviewToBack(toVC.view) } if UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight { updateChromeView() menu.view.addSubview(chromeView!) } let toVC = context.viewControllerForKey(UITransitionContextToViewControllerKey) toVC?.beginAppearanceTransition(true, animated: true) animationDelegate?.animatorWillStartDismissal?(self) animateMenu(menu.view, context: context) } private func animateMenu(view: UIView, context:UIViewControllerContextTransitioning) { animationContext = context animator = UIDynamicAnimator(referenceView: context.containerView()!) animator.delegate = self vectorDY = CGFloat(vectorDYCoefficient * Double(UIScreen.mainScreen().bounds.size.height) / duration) var rotationDirection = CGVectorMake(0, -vectorDY) var fromX: CGFloat var fromY: CGFloat var toX: CGFloat var toY: CGFloat if self.mode == .Presentation { if supportView != nil { showHostTitleLabel(false, animated: true) } view.transform = CGAffineTransformRotate(CGAffineTransformIdentity, degreesToRadians(initialMenuRotationAngle)); view.frame = CGRectMake(0, -CGRectGetHeight(view.frame)+topOffset, CGRectGetWidth(view.frame), CGRectGetHeight(view.frame)) rotationDirection = CGVectorMake(0, vectorDY) if UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight { fromX = CGRectGetWidth(context.containerView()!.frame) - 1 fromY = CGRectGetHeight(context.containerView()!.frame) + fromYPresentationLandscapeAdjustment toX = fromX + toXPresentationLandscapeAdjustment toY = fromY } else { fromX = -1 fromY = CGRectGetHeight(context.containerView()!.frame) + fromYPresentationAdjustment toX = fromX toY = fromY + 1 } } else { if supportView != nil { showHostTitleLabel(true, animated: true) } if UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight { fromX = -1 fromY = -CGRectGetWidth(context.containerView()!.frame) + topOffset + fromYDismissalLandscapeAdjustment toX = fromX toY = fromY + toYDismissalLandscapeAdjustment } else { fromX = CGRectGetHeight(context.containerView()!.frame) - 1 fromY = -CGRectGetWidth(context.containerView()!.frame) + topOffset + fromYDismissalAdjustment toX = fromX + 1 toY = fromY } } let anchorPoint = CGPointMake(topOffset / 2, topOffset / 2) let viewOffset = UIOffsetMake(-view.bounds.size.width / 2 + anchorPoint.x, -view.bounds.size.height / 2 + anchorPoint.y) let attachmentBehaviour = UIAttachmentBehavior(item: view, offsetFromCenter: viewOffset, attachedToAnchor: anchorPoint) animator.addBehavior(attachmentBehaviour) let collisionBehaviour = UICollisionBehavior() collisionBehaviour.addBoundaryWithIdentifier("collide", fromPoint: CGPointMake(fromX, fromY), toPoint: CGPointMake(toX, toY)) collisionBehaviour.addItem(view) animator.addBehavior(collisionBehaviour) let itemBehaviour = UIDynamicItemBehavior(items: [view]) itemBehaviour.elasticity = menuElasticity animator.addBehavior(itemBehaviour) let fallBehaviour = UIPushBehavior(items:[view], mode: .Continuous) fallBehaviour.pushDirection = rotationDirection animator.addBehavior(fallBehaviour) //Start displayLink displayLink.paused = false } private func showHostTitleLabel(show: Bool, animated: Bool) { if let guillotineMenu = menu as? GuillotineMenu { guard guillotineMenu.titleLabel != nil else { return } guillotineMenu.titleLabel!.center = CGPointMake(CGRectGetHeight(supportView!.frame) / 2, CGRectGetWidth(supportView!.frame) / 2) guillotineMenu.titleLabel!.transform = CGAffineTransformMakeRotation(degreesToRadians(90)); menu.view.addSubview(guillotineMenu.titleLabel!) if mode == .Presentation { guillotineMenu.titleLabel!.alpha = 1; } else { guillotineMenu.titleLabel!.alpha = 0; } if animated { UIView.animateWithDuration(duration, animations: { guillotineMenu.titleLabel!.alpha = CGFloat(show) }, completion: nil) } else { guillotineMenu.titleLabel!.alpha = CGFloat(show) } } } private func updateChromeView() { chromeView = UIView(frame: CGRectMake(0, CGRectGetHeight(menu.view.frame), CGRectGetWidth(menu.view.frame), CGRectGetHeight(menu.view.frame))) chromeView!.backgroundColor = menu.view.backgroundColor } private func setupDisplayLink() { displayLink = CADisplayLink(target: self, selector: #selector(updateContainerMenuButton)) displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes) displayLink.paused = true } private func setupSystemVersionAdjustment() { let device = UIDevice.currentDevice() let iosVersion = Double(device.systemVersion) ?? 0 let iOS9 = iosVersion >= 9 if (iOS9) { fromYPresentationLandscapeAdjustment = 1.5 fromYDismissalLandscapeAdjustment = 1.0 fromYPresentationAdjustment = -1.0 fromYDismissalAdjustment = -1.0 toXPresentationLandscapeAdjustment = 1.0 toYDismissalLandscapeAdjustment = -1.0 } else { fromYPresentationLandscapeAdjustment = 0.5 fromYDismissalLandscapeAdjustment = 0.0 fromYPresentationAdjustment = -1.5 fromYDismissalAdjustment = 1.0 toXPresentationLandscapeAdjustment = -1.0 toYDismissalLandscapeAdjustment = 1.5 } } private func degreesToRadians(degrees: CGFloat) -> CGFloat { return degrees / 180.0 * CGFloat(M_PI) } private func radiansToDegrees(radians: CGFloat) -> CGFloat { return radians * 180.0 / CGFloat(M_PI) } @objc private func updateContainerMenuButton() { let rotationTransform: CATransform3D = menu.view.layer.presentationLayer()!.transform var angle: CGFloat = 0 if (rotationTransform.m11 < 0.0) { angle = 180.0 - radiansToDegrees(asin(rotationTransform.m12)) } else { angle = radiansToDegrees(asin(rotationTransform.m12)) } let degrees: CGFloat = 90 - abs(angle) containerMenuButton?.layer.transform = CATransform3DRotate(CATransform3DIdentity, degreesToRadians(degrees), 0, 0, 1) } func setupContainerMenuButtonFrameAndTopOffset() { topOffset = supportView!.frame.origin.y + CGRectGetHeight(supportView!.bounds) let senderRect = supportView!.convertRect(presentButton!.frame, toView: nil) containerMenuButton?.frame = senderRect } //MARK: - Observer override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if context == myContext { setupContainerMenuButtonFrameAndTopOffset() } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } } //MARK: - UIViewControllerAnimatedTransitioning protocol implementation extension GuillotineTransitionAnimation: UIViewControllerAnimatedTransitioning { func animateTransition(context: UIViewControllerContextTransitioning) { switch mode { case .Presentation: animatePresentation(context) case .Dismissal: animateDismissal(context) } } func transitionDuration(context: UIViewControllerContextTransitioning?) -> NSTimeInterval { return duration } } //MARK: - UIDynamicAnimatorDelegate protocol implementation extension GuillotineTransitionAnimation: UIDynamicAnimatorDelegate { func dynamicAnimatorDidPause(animator: UIDynamicAnimator) { if self.mode == .Presentation { self.animator.removeAllBehaviors() menu.view.transform = CGAffineTransformIdentity menu.view.frame = animationContext.containerView()!.bounds anchorPoint = CGPointZero } chromeView?.removeFromSuperview() animationContext.completeTransition(true) if self.mode == .Presentation { let fromVC = animationContext.viewControllerForKey(UITransitionContextFromViewControllerKey) fromVC?.endAppearanceTransition() animationDelegate?.animatorDidFinishPresentation?(self) } else { let toVC = animationContext.viewControllerForKey(UITransitionContextToViewControllerKey) toVC?.endAppearanceTransition() animationDelegate?.animatorDidFinishDismissal?(self) } //Stop displayLink displayLink.paused = true } }
mit
53277190dcca0378cf59b6106718d864
41.262997
157
0.664592
5.545345
false
false
false
false
russbishop/swift
test/ClangModules/enum.swift
1
6396
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-sil %s -verify // -- Check that we can successfully round-trip. // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -D IRGEN -emit-ir %s >/dev/null // REQUIRES: objc_interop import Foundation import user_objc // NS_ENUM var mince = RuncingMode.mince var quince = RuncingMode.quince var rawMince: UInt = RuncingMode.mince.rawValue var rawFoo: CInt = UnderlyingType.foo.rawValue var rawNegativeOne: CUnsignedInt = UnsignedUnderlyingTypeNegativeValue.negativeOne.rawValue var rawWordBreakA: Int = PrefixWordBreak.banjo.rawValue var rawWordBreakB: Int = PrefixWordBreak.bandana.rawValue var rawWordBreak2A: Int = PrefixWordBreak2.breakBarBas.rawValue var rawWordBreak2B: Int = PrefixWordBreak2.breakBareBass.rawValue var rawWordBreak3A: Int = PrefixWordBreak3.break1Bob.rawValue var rawWordBreak3B: Int = PrefixWordBreak3.break1Ben.rawValue var singleConstant = SingleConstantEnum.value var myCoolWaterMelon = MyCoolEnum.waterMelon var hashMince: Int = RuncingMode.mince.hashValue if RuncingMode.mince != .quince { } var numberBehavior: NumberFormatter.Behavior = .default numberBehavior = .behavior10_4 var postingStyle: NotificationQueue.PostingStyle = .whenIdle postingStyle = .asap func handler(_ formatter: ByteCountFormatter) { // Ensure that the Equality protocol is properly added to an // imported ObjC enum type before the type is referenced by name if (formatter.countStyle == .file) {} } // Unfortunate consequence of treating runs of capitals as a single word. // See <rdar://problem/16768954>. var pathStyle: CFURLPathStyle = .cfurlposixPathStyle pathStyle = .cfurlWindowsPathStyle var URLOrUTI: CFURLOrUTI = .cfurlKind URLOrUTI = .cfutiKind let magnitude: Magnitude = .k2 let magnitude2: MagnitudeWords = .two let objcABI: objc_abi = .v2 let underscoreSuffix: ALL_CAPS_ENUM = .ENUM_CASE_ONE let underscoreSuffix2: ALL_CAPS_ENUM2 = .CASE_TWO var alias1 = AliasesEnum.bySameValue var alias2 = AliasesEnum.byEquivalentValue var alias3 = AliasesEnum.byName var aliasOriginal = AliasesEnum.original switch aliasOriginal { case .original: break case .differentValue: break } switch aliasOriginal { case .original: break default: break } switch aliasOriginal { case .bySameValue: break case .differentValue: break } switch aliasOriginal { case .bySameValue: break default: break } switch aliasOriginal { case AliasesEnum.bySameValue: break case AliasesEnum.differentValue: break } extension AliasesEnum { func test() { switch aliasOriginal { case .bySameValue: break case .differentValue: break } } } // Test NS_SWIFT_NAME: _ = XMLNode.Kind.DTDKind == .invalid _ = PrefixWordBreakCustom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}} _ = PrefixWordBreak2Custom.problemCase == .goodCase _ = PrefixWordBreak2Custom.problemCase == .PrefixWordBreak2DeprecatedBadCase // expected-warning {{deprecated}} _ = PrefixWordBreak2Custom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}} _ = PrefixWordBreakReversedCustom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}} _ = PrefixWordBreakReorderedCustom.problemCase == .goodCase _ = PrefixWordBreakReorderedCustom.problemCase == .PrefixWordBreakReorderedDeprecatedBadCase // expected-warning {{deprecated}} _ = PrefixWordBreakReorderedCustom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}} _ = PrefixWordBreakReordered2Custom.problemCase == .goodCase _ = PrefixWordBreakReordered2Custom.problemCase == .PrefixWordBreakReordered2DeprecatedBadCase // expected-warning {{deprecated}} _ = PrefixWordBreakReordered2Custom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}} _ = SwiftNameAllTheThings.Foo == .Bar _ = SwiftNameBad.`class` #if !IRGEN var qualifiedName = RuncingMode.mince var topLevelCaseName = RuncingMince // expected-error{{}} #endif // NS_OPTIONS var withMince: RuncingOptions = .enableMince var withQuince: RuncingOptions = .enableQuince // When there is a single enum constant, compare it against the type name to // derive the namespaced name. var singleValue: SingleOptions = .value // Check OptionSet conformance. var minceAndQuince: RuncingOptions = RuncingOptions.enableMince.intersection(RuncingOptions.enableQuince) var minceOrQuince: RuncingOptions = [.enableMince, .enableQuince] minceOrQuince.formIntersection(minceAndQuince) minceOrQuince.formUnion(minceAndQuince) var minceValue: UInt = minceAndQuince.rawValue var minceFromMask: RuncingOptions = [] // Strip leading 'k' in "kConstant". let calendarUnit: CFCalendarUnit = [.year, .weekday] // ...unless the next character is a non-identifier. let curve3D: AU3DMixerAttenuationCurve = .k3DMixerAttenuationCurve_Exponential // Match various plurals. let observingOpts: NSKeyValueObservingOptions = [.new, .old] let bluetoothProps: CBCharacteristicProperties = [.write, .writeWithoutResponse] let buzzFilter: AlertBuzzes = [.funk, .sosumi] // Match multi-capital acronym. let bitmapFormat: BitmapFormat = [.NSAlphaFirstBitmapFormat, .NS32BitBigEndianBitmapFormat]; let bitmapFormatR: BitmapFormatReversed = [.NSAlphaFirstBitmapFormatR, .NS32BitBigEndianBitmapFormatR]; let bitmapFormat2: BitmapFormat2 = [.NSU16a , .NSU32a] let bitmapFormat3: BitmapFormat3 = [.NSU16b , .NSS32b] let bitmapFormat4: UBitmapFormat4 = [.NSU16c , .NSU32c] let bitmapFormat5: ABitmapFormat5 = [.NSAA16d , .NSAB32d] // Drop trailing underscores when possible. let timeFlags: CMTimeFlags = [.valid , .hasBeenRounded] let timeFlags2: CMTimeFlagsWithNumber = [._Valid, ._888] let audioComponentOpts: AudioComponentInstantiationOptions = [.loadOutOfProcess] let audioComponentFlags: AudioComponentFlags = [.sandboxSafe] let audioComponentFlags2: FakeAudioComponentFlags = [.loadOutOfProcess] let objcFlags: objc_flags = [.taggedPointer, .swiftRefcount] let optionsWithSwiftName: OptionsAlsoGetSwiftName = .Case // <rdar://problem/25168818> Don't import None members in NS_OPTIONS types #if !IRGEN let _ = RuncingOptions.none // expected-error {{'none' is unavailable: use [] to construct an empty option set}} #endif // ...but do if they have a custom name _ = EmptySet1.default // ...even if the custom name is the same as the name they would have had _ = EmptySet2.none // ...or the original name. _ = EmptySet3.None
apache-2.0
8e01fe6b85d957fb80393da6b08a6e14
32.3125
129
0.780488
3.636157
false
false
false
false
taxibeat/ios-conference
iOS.Conf Extension/InterfaceController.swift
1
3019
// // InterfaceController.swift // iOS.Conf Extension // // Created by Nikos Maounis on 05/02/2017. // Copyright © 2017 Taxibeat Ltd. All rights reserved. // import WatchKit import Foundation import CloudKit import TBConfFrameworkWatch class InterfaceController: WKInterfaceController { @IBOutlet var fetchDataLabel: WKInterfaceLabel! @IBOutlet var scheduleTable: WKInterfaceTable! var talksArray = [ScheduleItem]() enum ScheduleTableRowType: String { case scheduleRow = "scheduleRow" case noSpeakerRow = "noSpeakerRow" } override func awake(withContext context: Any?) { super.awake(withContext: context) CloudKitManager.sharedInstance.fetchTalks { (talks, error) in if error != nil { self.fetchDataLabel.setText("Something went wrong") } else { if let theTalks = talks { self.talksArray = theTalks var rowTypes = [String]() for talk in theTalks { if talk.hasSpeaker == true { rowTypes.append(ScheduleTableRowType.scheduleRow.rawValue) } else { rowTypes.append(ScheduleTableRowType.noSpeakerRow.rawValue) } } DispatchQueue.main.async { self.fetchDataLabel.setAlpha(0.0) self.scheduleTable.setRowTypes(rowTypes) for (index, value) in self.talksArray.enumerated() { if value.hasSpeaker == true { if let row = self.scheduleTable.rowController(at: index) as? ScheduleRowController { row.talkSpeakerLabel.setText(value.speakerName) row.talkTimeLabel.setText(value.timeString) row.talkTitleLabel.setText(value.description) } } else { if let row = self.scheduleTable.rowController(at: index) as? TalkRowController { row.talkTime.setText(value.timeString) row.talkTitle.setText(value.description) } } } } } } } } @IBAction func openVenuController() { self.pushController(withName: "venueInterfaceController", context: nil) } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } }
mit
a153b423a1e4021230a2188db5687da8
35.804878
116
0.517893
5.588889
false
false
false
false
yuyedaidao/YQTabBarController
Classes/YQNavigationController.swift
1
2291
// // YQNavigationController.swift // YQTabBarController // // Created by Wang on 14-9-26. // Copyright (c) 2014年 Wang. All rights reserved. // import UIKit class YQNavigationController: UINavigationController { var shouldHideTabBarWhenPushed:Bool = false override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func pushViewController(viewController: UIViewController, animated: Bool) { super.pushViewController(viewController, animated:animated) NSLog("hello") if(self.shouldHideTabBarWhenPushed){ NSLog("next Hello") self.yqTabBar.showTabBar(false, animated: true) } } override func popViewControllerAnimated(animated: Bool) -> UIViewController? { var vc = super.popViewControllerAnimated(animated) if(self.shouldHideTabBarWhenPushed && self.viewControllers.count==1){ self.yqTabBar.showTabBar(true, animated: true) } return vc } override func popToRootViewControllerAnimated(animated: Bool) -> [AnyObject]? { var objs = super.popToRootViewControllerAnimated(animated) if(self.shouldHideTabBarWhenPushed && self.viewControllers.count==1){ self.yqTabBar.showTabBar(true, animated: true) } return objs } override func popToViewController(viewController: UIViewController, animated: Bool) -> [AnyObject]? { var objs = super.popToViewController(viewController, animated: animated) if(self.shouldHideTabBarWhenPushed && self.viewControllers.count==1){ self.yqTabBar.showTabBar(true, animated: true) } return objs } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
800a87fc645ed49aef20ff4d9a4aed31
32.173913
106
0.672783
5.04185
false
false
false
false
mcjcloud/Show-And-Sell
Show And Sell/SettingsTableViewController.swift
1
4580
// // SettingsViewController.swift // Show And Sell // // Created by Brayden Cloud on 10/11/16. // Copyright © 2016 Brayden Cloud. All rights reserved. // import UIKit import MessageUI class SettingsTableViewController: UITableViewController, UIPopoverPresentationControllerDelegate, MFMailComposeViewControllerDelegate { @IBOutlet var manageCell: UITableViewCell! @IBOutlet var reportBugCell: UITableViewCell! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { tableView.reloadData() } // MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? LoginViewController { // prepare for the login screen. destination.autoLogin = false } else if let destination = segue.destination as? FindGroupTableViewController { destination.navigationItem.rightBarButtonItem = destination.navigationItem.leftBarButtonItem destination.navigationItem.leftBarButtonItem = nil } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 0 { switch(indexPath.row) { case 0: // Manage Group if let _ = AppData.myGroup { self.performSegue(withIdentifier: "settingsToManage", sender: self) } else { let alertController = UIAlertController(title: "Group not found", message: "A group with your user was not found.", preferredStyle: .alert) let createAction = UIAlertAction(title: "Create", style: .default) { action in // go to Create Group self.performSegue(withIdentifier: "settingsToCreateGroup", sender: self) } let reloadAction = UIAlertAction(title: "Reload", style: .default) { action in print("reloading myGroup") DispatchQueue.main.async { self.manageCell.isUserInteractionEnabled = false } // get myGroup HttpRequestManager.group(withAdminId: AppData.user!.userId) { group, response, error in print("got myGroup") AppData.myGroup = group AppData.saveData() DispatchQueue.main.async { self.manageCell.isUserInteractionEnabled = true tableView.reloadData() } } } alertController.addAction(createAction) alertController.addAction(reloadAction) self.present(alertController, animated: true, completion: nil) } case 1: // Account Settings // segue to account settings self.performSegue(withIdentifier: "settingsToAccount", sender: self) default: break } } else { if indexPath.row == 0 { self.tableView.reloadData() // compose email let mailComposerVC = MFMailComposeViewController() mailComposerVC.mailComposeDelegate = self mailComposerVC.setToRecipients(["[email protected]"]) mailComposerVC.setSubject("Bug Report") mailComposerVC.setMessageBody("I found a bug!", isHTML: false) if MFMailComposeViewController.canSendMail() { self.present(mailComposerVC, animated: true, completion: nil) } } } } // MARK: MFMailViewController delegate func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { dismiss(animated: true, completion: nil) } @IBAction func unwindToSettings(segue: UIStoryboardSegue) { // do nothing } @IBAction func done(_ sender: UIBarButtonItem) { // release vc self.dismiss(animated: true, completion: nil) } }
apache-2.0
d7f17cf1a7257bc78af9627a4f84b53e
40.627273
159
0.557109
6.213026
false
false
false
false
VideonaTalentum/TalentumVideonaSwift
VideonaTalentum/Libraries/ActionButton/ActionButton.swift
2
10763
// ActionButton.swift // // The MIT License (MIT) // // Copyright (c) 2015 ActionButton // // 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 public typealias ActionButtonAction = (ActionButton) -> Void public class ActionButton: NSObject { /// The action the button should perform when tapped public var action: ActionButtonAction? /// The button's background color : set default color and selected color public var backgroundColor: UIColor = UIColor(red: 238.0/255.0, green: 130.0/255.0, blue: 34.0/255.0, alpha:1.0) { willSet { floatButton.backgroundColor = newValue backgroundColorSelected = newValue } } /// The button's background color : set default color public var backgroundColorSelected: UIColor = UIColor(red: 238.0/255.0, green: 130.0/255.0, blue: 34.0/255.0, alpha:1.0) /// Indicates if the buttons is active (showing its items) private(set) public var active: Bool = false /// An array of items that the button will present internal var items: [ActionButtonItem]? { willSet { for abi in self.items! { abi.view.removeFromSuperview() } } didSet { placeButtonItems() showActive(true) } } /// The button that will be presented to the user private var floatButton: UIButton! /// View that will hold the placement of the button's actions private var contentView: UIView! /// View where the *floatButton* will be displayed private var parentView: UIView! /// Blur effect that will be presented when the button is active private var blurVisualEffect: UIVisualEffectView! // Distance between each item action private let itemOffset = -55 /// the float button's radius private let floatButtonRadius = 50 public init(attachedToView view: UIView, items: [ActionButtonItem]?) { super.init() self.parentView = view self.items = items let bounds = self.parentView.bounds self.floatButton = UIButton(type: .Custom) self.floatButton.layer.cornerRadius = CGFloat(floatButtonRadius / 2) self.floatButton.layer.shadowOpacity = 1 self.floatButton.layer.shadowRadius = 2 self.floatButton.layer.shadowOffset = CGSize(width: 1, height: 1) self.floatButton.layer.shadowColor = UIColor.grayColor().CGColor self.floatButton.setTitle("+", forState: .Normal) self.floatButton.setImage(nil, forState: .Normal) self.floatButton.backgroundColor = self.backgroundColor self.floatButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Light", size: 35) self.floatButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 8, right: 0) self.floatButton.userInteractionEnabled = true self.floatButton.translatesAutoresizingMaskIntoConstraints = false self.floatButton.addTarget(self, action: #selector(ActionButton.buttonTapped(_:)), forControlEvents: .TouchUpInside) self.floatButton.addTarget(self, action: #selector(ActionButton.buttonTouchDown(_:)), forControlEvents: .TouchDown) self.parentView.addSubview(self.floatButton) self.contentView = UIView(frame: bounds) self.blurVisualEffect = UIVisualEffectView(effect: UIBlurEffect(style: .ExtraLight)) self.blurVisualEffect.frame = self.contentView.frame self.contentView.addSubview(self.blurVisualEffect) let tap = UITapGestureRecognizer(target: self, action: #selector(ActionButton.backgroundTapped(_:))) self.contentView.addGestureRecognizer(tap) self.installConstraints() } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - Set Methods public func setTitle(title: String?, forState state: UIControlState) { floatButton.setImage(nil, forState: state) floatButton.setTitle(title, forState: state) floatButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 8, right: 0) } public func setImage(image: UIImage?, forState state: UIControlState) { setTitle(nil, forState: state) floatButton.setImage(image, forState: state) floatButton.adjustsImageWhenHighlighted = false floatButton.contentEdgeInsets = UIEdgeInsetsZero } //MARK: - Auto Layout Methods /** Install all the necessary constraints for the button. By the default the button will be placed at 15pts from the bottom and the 15pts from the right of its *parentView* */ private func installConstraints() { let views = ["floatButton":self.floatButton, "parentView":self.parentView] let width = NSLayoutConstraint.constraintsWithVisualFormat("H:[floatButton(\(floatButtonRadius))]", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: views) let height = NSLayoutConstraint.constraintsWithVisualFormat("V:[floatButton(\(floatButtonRadius))]", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: views) self.floatButton.addConstraints(width) self.floatButton.addConstraints(height) let trailingSpacing = NSLayoutConstraint.constraintsWithVisualFormat("V:[floatButton]-15-|", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: views) let bottomSpacing = NSLayoutConstraint.constraintsWithVisualFormat("H:[floatButton]-15-|", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: views) self.parentView.addConstraints(trailingSpacing) self.parentView.addConstraints(bottomSpacing) } //MARK: - Button Actions Methods func buttonTapped(sender: UIControl) { animatePressingWithScale(1.0) if let unwrappedAction = self.action { unwrappedAction(self) } } func buttonTouchDown(sender: UIButton) { animatePressingWithScale(0.9) } //MARK: - Gesture Recognizer Methods func backgroundTapped(gesture: UIGestureRecognizer) { if self.active { self.toggle() } } //MARK: - Custom Methods /** Presents or hides all the ActionButton's actions */ public func toggleMenu() { self.placeButtonItems() self.toggle() } //MARK: - Action Button Items Placement /** Defines the position of all the ActionButton's actions */ private func placeButtonItems() { if let optionalItems = self.items { for item in optionalItems { item.view.center = CGPoint(x: self.floatButton.center.x - 83, y: self.floatButton.center.y) item.view.removeFromSuperview() self.contentView.addSubview(item.view) } } } //MARK - Float Menu Methods /** Presents or hides all the ActionButton's actions and changes the *active* state */ private func toggle() { self.animateMenu() self.showBlur() self.active = !self.active self.floatButton.backgroundColor = self.active ? backgroundColorSelected : backgroundColor self.floatButton.selected = self.active } private func animateMenu() { let rotation = self.active ? 0 : CGFloat(M_PI_4) UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: UIViewAnimationOptions.AllowAnimatedContent, animations: { if self.floatButton.imageView?.image == nil { self.floatButton.transform = CGAffineTransformMakeRotation(rotation) } self.showActive(false) }, completion: {completed in if self.active == false { self.hideBlur() } }) } private func showActive(active: Bool) { if self.active == active { self.contentView.alpha = 1.0 if let optionalItems = self.items { for (index, item) in optionalItems.enumerate() { let offset = index + 1 let translation = self.itemOffset * offset item.view.transform = CGAffineTransformMakeTranslation(0, CGFloat(translation)) item.view.alpha = 1 } } } else { self.contentView.alpha = 0.0 if let optionalItems = self.items { for item in optionalItems { item.view.transform = CGAffineTransformMakeTranslation(0, 0) item.view.alpha = 0 } } } } private func showBlur() { self.parentView.insertSubview(self.contentView, belowSubview: self.floatButton) } private func hideBlur() { self.contentView.removeFromSuperview() } /** Animates the button pressing, by the default this method just scales the button down when it's pressed and returns to its normal size when the button is no longer pressed - parameter scale: how much the button should be scaled */ private func animatePressingWithScale(scale: CGFloat) { UIView.animateWithDuration(0.2, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: UIViewAnimationOptions.AllowAnimatedContent, animations: { self.floatButton.transform = CGAffineTransformMakeScale(scale, scale) }, completion: nil) } }
mit
c55d78ceeee001e069ec66c527893fb9
39.462406
184
0.655486
5.060179
false
false
false
false
rechsteiner/Parchment
Parchment/Classes/PageViewController.swift
1
14055
import UIKit /// PageViewController is a replacement for `UIPageViewController` /// using `UIScrollView`. It provides detailed delegate methods, which /// is the main issue with `UIPageViewController`. public final class PageViewController: UIViewController { // MARK: Public Properties public weak var dataSource: PageViewControllerDataSource? public weak var delegate: PageViewControllerDelegate? public override var shouldAutomaticallyForwardAppearanceMethods: Bool { return false } /// The view controller before the selected view controller. public var beforeViewController: UIViewController? { return manager.previousViewController } /// The currently selected view controller. Can be `nil` if no view /// controller is selected. public var selectedViewController: UIViewController? { return manager.selectedViewController } /// The view controller after the selected view controller. private var afterViewController: UIViewController? { return manager.nextViewController } /// The underlying scroll view where the page view controllers are /// added. Changing the properties on this scroll view might cause /// undefined behaviour. public private(set) lazy var scrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.isPagingEnabled = true scrollView.autoresizingMask = [ .flexibleTopMargin, .flexibleRightMargin, .flexibleBottomMargin, .flexibleLeftMargin, ] scrollView.scrollsToTop = false scrollView.bounces = true scrollView.translatesAutoresizingMaskIntoConstraints = true scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false return scrollView }() public var options: PagingOptions { didSet { switch options.contentNavigationOrientation { case .vertical: scrollView.alwaysBounceHorizontal = false scrollView.alwaysBounceVertical = true case .horizontal: scrollView.alwaysBounceHorizontal = true scrollView.alwaysBounceVertical = false } } } // MARK: Private Properties private let manager = PageViewManager() /// The size of a single page. private var pageSize: CGFloat { switch options.contentNavigationOrientation { case .vertical: return view.bounds.height case .horizontal: return view.bounds.width } } /// The size of all the pages in the scroll view. private var contentSize: CGSize { switch options.contentNavigationOrientation { case .horizontal: return CGSize( width: CGFloat(manager.state.count) * view.bounds.width, height: view.bounds.height ) case .vertical: return CGSize( width: view.bounds.width, height: CGFloat(manager.state.count) * view.bounds.height ) } } /// The content offset of the scroll view, adjusted for the current /// navigation orientation. private var contentOffset: CGFloat { get { switch options.contentNavigationOrientation { case .horizontal: return scrollView.contentOffset.x case .vertical: return scrollView.contentOffset.y } } set { scrollView.contentOffset = point(newValue) } } private var isRightToLeft: Bool { switch options.contentNavigationOrientation { case .vertical: return false case .horizontal: if #available(iOS 9.0, *), UIView.userInterfaceLayoutDirection(for: view.semanticContentAttribute) == .rightToLeft { return true } else { return false } } } public init(options: PagingOptions = PagingOptions()) { self.options = options super.init(nibName: nil, bundle: nil) manager.delegate = self manager.dataSource = self } public required init?(coder: NSCoder) { options = PagingOptions() super.init(coder: coder) manager.delegate = self manager.dataSource = self } public override func viewDidLoad() { super.viewDidLoad() view.addSubview(scrollView) scrollView.delegate = self if #available(iOS 11.0, *) { scrollView.contentInsetAdjustmentBehavior = .never } } public override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() scrollView.frame = view.bounds manager.viewWillLayoutSubviews() } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) manager.viewWillAppear(animated) } public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) manager.viewDidAppear(animated) } public override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) manager.viewWillDisappear(animated) } public override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) manager.viewDidDisappear(animated) } public override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { _ in self.manager.viewWillTransitionSize() }) } // MARK: Public Methods public func selectViewController(_ viewController: UIViewController, direction: PageViewDirection, animated: Bool = true) { manager.select(viewController: viewController, direction: direction, animated: animated) } public func selectNext(animated: Bool) { manager.selectNext(animated: animated) } public func selectPrevious(animated: Bool) { manager.selectPrevious(animated: animated) } public func removeAll() { manager.removeAll() } // MARK: Private Methods private func setContentOffset(_ value: CGFloat, animated: Bool) { scrollView.setContentOffset(point(value), animated: animated) } private func point(_ value: CGFloat) -> CGPoint { switch options.contentNavigationOrientation { case .horizontal: return CGPoint(x: value, y: 0) case .vertical: return CGPoint(x: 0, y: value) } } } // MARK: - UIScrollViewDelegate extension PageViewController: UIScrollViewDelegate { public func scrollViewWillBeginDragging(_: UIScrollView) { manager.willBeginDragging() } public func scrollViewWillEndDragging(_: UIScrollView, withVelocity _: CGPoint, targetContentOffset _: UnsafeMutablePointer<CGPoint>) { manager.willEndDragging() } public func scrollViewDidScroll(_: UIScrollView) { let distance = pageSize var progress: CGFloat if isRightToLeft { switch manager.state { case .last, .empty, .single: progress = -(contentOffset / distance) case .center, .first: progress = -((contentOffset - distance) / distance) } } else { switch manager.state { case .first, .empty, .single: progress = contentOffset / distance case .center, .last: progress = (contentOffset - distance) / distance } } manager.didScroll(progress: progress) } } // MARK: - PageViewManagerDataSource extension PageViewController: PageViewManagerDataSource { func viewControllerAfter(_ viewController: UIViewController) -> UIViewController? { return dataSource?.pageViewController(self, viewControllerAfterViewController: viewController) } func viewControllerBefore(_ viewController: UIViewController) -> UIViewController? { return dataSource?.pageViewController(self, viewControllerBeforeViewController: viewController) } } // MARK: - PageViewManagerDelegate extension PageViewController: PageViewManagerDelegate { func scrollForward() { if isRightToLeft { switch manager.state { case .first, .center: setContentOffset(.zero, animated: true) case .single, .empty, .last: break } } else { switch manager.state { case .first: setContentOffset(pageSize, animated: true) case .center: setContentOffset(pageSize * 2, animated: true) case .single, .empty, .last: break } } } func scrollReverse() { if isRightToLeft { switch manager.state { case .last: setContentOffset(pageSize, animated: true) case .center: setContentOffset(pageSize * 2, animated: true) case .single, .empty, .first: break } } else { switch manager.state { case .last, .center: scrollView.setContentOffset(.zero, animated: true) case .single, .empty, .first: break } } } func layoutViews(for viewControllers: [UIViewController], keepContentOffset: Bool) { let viewControllers = isRightToLeft ? viewControllers.reversed() : viewControllers // Need to trigger a layout here to ensure that the scroll view // bounds is updated before we use its frame for calculations. view.layoutIfNeeded() for (index, viewController) in viewControllers.enumerated() { switch options.contentNavigationOrientation { case .horizontal: viewController.view.frame = CGRect( x: CGFloat(index) * scrollView.bounds.width, y: 0, width: scrollView.bounds.width, height: scrollView.bounds.height ) case .vertical: viewController.view.frame = CGRect( x: 0, y: CGFloat(index) * scrollView.bounds.height, width: scrollView.bounds.width, height: scrollView.bounds.height ) } } // When updating the content offset we need to account for the // current content offset as well. This ensures that the selected // page is fully centered when swiping so fast that you get the // bounce effect in the scroll view. var diff: CGFloat = 0 if keepContentOffset { if contentOffset > pageSize * 2 { diff = contentOffset - pageSize * 2 } else if contentOffset > pageSize, contentOffset < pageSize * 2 { diff = contentOffset - pageSize } else if contentOffset < pageSize, contentOffset < 0 { diff = contentOffset } } // Need to set content size before updating content offset. If not // the views will be misplaced when overshooting. scrollView.contentSize = contentSize if isRightToLeft { switch manager.state { case .first, .center: contentOffset = pageSize + diff case .single, .empty, .last: contentOffset = diff } } else { switch manager.state { case .first, .single, .empty: contentOffset = diff case .last, .center: contentOffset = pageSize + diff } } } func addViewController(_ viewController: UIViewController) { viewController.willMove(toParent: self) addChild(viewController) scrollView.addSubview(viewController.view) viewController.didMove(toParent: self) } func removeViewController(_ viewController: UIViewController) { viewController.willMove(toParent: nil) viewController.removeFromParent() viewController.view.removeFromSuperview() viewController.didMove(toParent: nil) } func beginAppearanceTransition(isAppearing: Bool, viewController: UIViewController, animated: Bool) { viewController.beginAppearanceTransition(isAppearing, animated: animated) } func endAppearanceTransition(viewController: UIViewController) { viewController.endAppearanceTransition() } func willScroll( from selectedViewController: UIViewController, to destinationViewController: UIViewController ) { delegate?.pageViewController( self, willStartScrollingFrom: selectedViewController, destinationViewController: destinationViewController ) } func didFinishScrolling( from selectedViewController: UIViewController, to destinationViewController: UIViewController, transitionSuccessful: Bool ) { delegate?.pageViewController( self, didFinishScrollingFrom: selectedViewController, destinationViewController: destinationViewController, transitionSuccessful: transitionSuccessful ) } func isScrolling( from selectedViewController: UIViewController, to destinationViewController: UIViewController?, progress: CGFloat ) { delegate?.pageViewController( self, isScrollingFrom: selectedViewController, destinationViewController: destinationViewController, progress: progress ) } }
mit
41c1a46d37c50a05e9ebe1a8925a6e45
31.992958
139
0.61793
5.915404
false
false
false
false
aleph7/Surge
Sources/Upsurge/TensorSlice.swift
2
5025
// Copyright © 2015 Venture Media Labs. // // 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. open class TensorSlice<Element: Value>: MutableTensorType, Equatable { public typealias Index = [Int] public typealias Slice = TensorSlice<Element> public let base: Tensor<Element> public let span: Span open var count: Int { return span.count } open func withUnsafeBufferPointer<R>(_ body: (UnsafeBufferPointer<Element>) throws -> R) rethrows -> R { return try base.withUnsafeBufferPointer(body) } open func withUnsafePointer<R>(_ body: (UnsafePointer<Element>) throws -> R) rethrows -> R { return try base.withUnsafePointer(body) } open func withUnsafeMutableBufferPointer<R>(_ body: (UnsafeMutableBufferPointer<Element>) throws -> R) rethrows -> R { return try base.withUnsafeMutableBufferPointer(body) } open func withUnsafeMutablePointer<R>(_ body: (UnsafeMutablePointer<Element>) throws -> R) rethrows -> R { return try base.withUnsafeMutablePointer(body) } init(base: Tensor<Element>, span: Span) { assert(span.rank == base.rank) self.base = base self.span = span } open subscript(indices: Int...) -> Element { get { return self[indices] } set { self[indices] = newValue } } open subscript(indices: Index) -> Element { get { var index = span.startIndex let indexReplacementRage: CountableClosedRange<Int> = span.startIndex.count - indices.count ... span.startIndex.count - 1 index.replaceSubrange(indexReplacementRage, with: indices) assert(indexIsValid(index)) return base[index] } set { var index = span.startIndex let indexReplacementRage: CountableClosedRange<Int> = span.startIndex.count - indices.count ... span.startIndex.count - 1 index.replaceSubrange(indexReplacementRage, with: indices) assert(indexIsValid(index)) base[index] = newValue } } open subscript(slice: [IntervalType]) -> Slice { get { let span = Span(base: self.span, intervals: slice) return TensorSlice(base: base, span: span) } set { let span = Span(base: self.span, intervals: slice) assert(span ≅ newValue.span) for index in span { base[index] = newValue[index] } } } open subscript(slice: IntervalType...) -> Slice { get { return self[slice] } set { self[slice] = newValue } } subscript(span: Span) -> Slice { get { assert(span.contains(span)) return TensorSlice(base: base, span: span) } set { assert(span.contains(span)) assert(span ≅ newValue.span) for (lhsIndex, rhsIndex) in zip(span, newValue.span) { base[lhsIndex] = newValue[rhsIndex] } } } open var isContiguous: Bool { let onesCount: Int = (dimensions.firstIndex { $0 != 1 }) ?? rank let diff = (0..<rank).map { dimensions[$0] - base.dimensions[$0] }.reversed() let fullCount: Int if let index = (diff.firstIndex { $0 != 0 }), index.base < count { fullCount = rank - index.base } else { fullCount = rank } return rank - fullCount - onesCount <= 1 } open func indexIsValid(_ indices: [Int]) -> Bool { assert(indices.count == dimensions.count) return indices.enumerated().all { (i, index) in self.span[i].contains(index) } } } // MARK: - Equatable public func ==<L: TensorType, R: TensorType>(lhs: L, rhs: R) -> Bool where L.Element == R.Element, L.Element: Equatable { return lhs.span ≅ rhs.span && zip(lhs.span, rhs.span).all { lhs[$0] == rhs[$1] } }
mit
d65b65a261011f989d02516604701557
34.588652
133
0.618573
4.460444
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Conversation/Content/Cells/ConfigurationMessageCell/Content/Text/ConversationTextMessageCell.swift
1
8295
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireSyncEngine import UIKit final class ConversationTextMessageCell: UIView, ConversationMessageCell, TextViewInteractionDelegate { struct Configuration: Equatable { let attributedText: NSAttributedString let isObfuscated: Bool } private lazy var messageTextView: LinkInteractionTextView = { let view = LinkInteractionTextView() view.isEditable = false view.isSelectable = true view.backgroundColor = .clear view.isScrollEnabled = false view.textContainerInset = UIEdgeInsets.zero view.textContainer.lineFragmentPadding = 0 view.isUserInteractionEnabled = true view.accessibilityIdentifier = "Message" view.accessibilityElementsHidden = false view.dataDetectorTypes = [.link, .address, .phoneNumber, .flightNumber, .calendarEvent, .shipmentTrackingNumber] view.linkTextAttributes = [.foregroundColor: UIColor.accent()] view.setContentHuggingPriority(.required, for: .vertical) view.setContentCompressionResistancePriority(.required, for: .vertical) view.interactionDelegate = self view.textDragInteraction?.isEnabled = false return view }() var isSelected: Bool = false weak var message: ZMConversationMessage? weak var delegate: ConversationMessageCellDelegate? weak var menuPresenter: ConversationMessageCellMenuPresenter? var ephemeralTimerTopInset: CGFloat { guard let font = messageTextView.font else { return 0 } return font.lineHeight / 2 } var selectionView: UIView? { return messageTextView } var selectionRect: CGRect { return messageTextView.layoutManager.usedRect(for: messageTextView.textContainer) } override init(frame: CGRect) { super.init(frame: frame) setup() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setup() { addSubview(messageTextView) configureConstraints() } private func configureConstraints() { messageTextView.translatesAutoresizingMaskIntoConstraints = false messageTextView.fitIn(view: self) } func configure(with object: Configuration, animated: Bool) { messageTextView.attributedText = object.attributedText if object.isObfuscated { messageTextView.accessibilityIdentifier = "Obfuscated message" } else { messageTextView.accessibilityIdentifier = "Message" } } func textView(_ textView: LinkInteractionTextView, open url: URL) -> Bool { // Open mention link if url.isMention { if let message = self.message, let mention = message.textMessageData?.mentions.first(where: { $0.location == url.mentionLocation }) { return self.openMention(mention) } else { return false } } // Open the URL return url.open() } func openMention(_ mention: Mention) -> Bool { delegate?.conversationMessageWantsToOpenUserDetails(self, user: mention.user, sourceView: messageTextView, frame: selectionRect) return true } func textViewDidLongPress(_ textView: LinkInteractionTextView) { if !UIMenuController.shared.isMenuVisible { menuPresenter?.showMenu() } } } // MARK: - Description final class ConversationTextMessageCellDescription: ConversationMessageCellDescription { typealias View = ConversationTextMessageCell let configuration: View.Configuration weak var message: ZMConversationMessage? weak var delegate: ConversationMessageCellDelegate? weak var actionController: ConversationMessageActionController? var showEphemeralTimer: Bool = false var topMargin: Float = 8 let isFullWidth: Bool = false let supportsActions: Bool = true let containsHighlightableContent: Bool = true let accessibilityIdentifier: String? = nil let accessibilityLabel: String? = nil init(attributedString: NSAttributedString, isObfuscated: Bool) { configuration = View.Configuration(attributedText: attributedString, isObfuscated: isObfuscated) } func makeCell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueConversationCell(with: self, for: indexPath) cell.accessibilityCustomActions = actionController?.makeAccessibilityActions() cell.cellView.delegate = self.delegate cell.cellView.message = self.message cell.cellView.menuPresenter = cell return cell } } // MARK: - Factory extension ConversationTextMessageCellDescription { static func cells(for message: ZMConversationMessage, searchQueries: [String]) -> [AnyConversationMessageCellDescription] { guard let textMessageData = message.textMessageData else { preconditionFailure("Invalid text message") } return cells(textMessageData: textMessageData, message: message, searchQueries: searchQueries) } static func cells(textMessageData: ZMTextMessageData, message: ZMConversationMessage, searchQueries: [String]) -> [AnyConversationMessageCellDescription] { var cells: [AnyConversationMessageCellDescription] = [] // Refetch the link attachments if needed if !Settings.disableLinkPreviews { ZMUserSession.shared()?.enqueue { message.refetchLinkAttachmentsIfNeeded() } } // Text parsing let attachments = message.linkAttachments ?? [] var messageText = NSAttributedString.format(message: textMessageData, isObfuscated: message.isObfuscated) // Search queries if !searchQueries.isEmpty { let highlightStyle: [NSAttributedString.Key: AnyObject] = [.backgroundColor: UIColor.accentDarken] messageText = messageText.highlightingAppearances(of: searchQueries, with: highlightStyle, upToWidth: 0, totalMatches: nil) } // Quote if textMessageData.hasQuote { let quotedMessage = textMessageData.quoteMessage let quoteCell = ConversationReplyCellDescription(quotedMessage: quotedMessage) cells.append(AnyConversationMessageCellDescription(quoteCell)) } // Text if !messageText.string.isEmpty { let textCell = ConversationTextMessageCellDescription(attributedString: messageText, isObfuscated: message.isObfuscated) cells.append(AnyConversationMessageCellDescription(textCell)) } guard !message.isObfuscated else { return cells } // Links if let attachment = attachments.first { // Link Attachment let attachmentCell = ConversationLinkAttachmentCellDescription(attachment: attachment, thumbnailResource: message.linkAttachmentImage) cells.append(AnyConversationMessageCellDescription(attachmentCell)) } else if textMessageData.linkPreview != nil { // Link Preview let linkPreviewCell = ConversationLinkPreviewArticleCellDescription(message: message, data: textMessageData) cells.append(AnyConversationMessageCellDescription(linkPreviewCell)) } return cells } }
gpl-3.0
15020fea7e1943155e16b1976a9f5484
34.448718
146
0.684147
5.43222
false
false
false
false
patrickmontalto/SwiftNetworking
Example/Tests/NetworkClientTests.swift
1
1788
import XCTest @testable import SwiftNetworking final class NetworkClientTests: XCTestCase { // MARK: - Properties let baseURL = URL(string: "http://example.com/api/v1/")! // MARK: - Tests func testBuildRequest() { let client = NetworkClient(baseURL: baseURL) // Request without parameters let url1 = URL(string: "http://example.com/api/v1/me")! let request1 = client.buildRequest(method: .get, path: "me") XCTAssertEqual("GET", request1.httpMethod!) XCTAssertEqual(url1, request1.url) // Request with parameters let params = ["username": "archimedes"] let request2 = client.buildRequest(method: .post, path: "users", parameters: params) XCTAssertEqual("POST", request2.httpMethod) XCTAssertEqual(try! JSONSerialization.data(withJSONObject: params, options: []), request2.httpBody) // Request with query items let url3 = URL(string: "http://example.com/api/v1/search?query=science")! let queryItems = [URLQueryItem(name: "query", value: "science")] let request3 = client.buildRequest(path: "search", queryItems: queryItems) XCTAssertEqual(url3, request3.url) } func testRequest() { let session = MockSession { (request) -> (NetworkResult) in return .failure(NetworkClient.Error.unknown) } let client = NetworkClient(baseURL: baseURL, session: session) client.request(path: "me") let url1 = URL(string: "http://example.com/api/v1/me")! let request = session.interactions.first!.0 XCTAssertEqual("GET", request.httpMethod) XCTAssertEqual(url1, request.url) } }
mit
b80a16a915385db3227e61041c250164
34.76
107
0.615772
4.458853
false
true
false
false
luanlzsn/EasyPass
EasyPass/Classes/Home/View/PlayerVideoView.swift
1
13837
// // PlayerVideoView.swift // EasyPass // // Created by luan on 2017/8/3. // Copyright © 2017年 luan. All rights reserved. // import UIKit import AVFoundation import MediaPlayer class PlayerVideoView: UIView,UIGestureRecognizerDelegate { @IBOutlet weak var coverImg: UIImageView! @IBOutlet weak var playBtn: UIButton!//播放按钮 @IBOutlet weak var controlView: UIView! @IBOutlet weak var playerTime: UILabel! @IBOutlet weak var totalTime: UILabel! @IBOutlet weak var progress: UIProgressView!//缓冲进度 @IBOutlet weak var progressSlider: UISlider!//播放进度 @IBOutlet weak var zoomBtn: UIButton!//缩放按钮 @IBOutlet weak var activityView: UIActivityIndicatorView! var player: AVPlayer? var playerItem: AVPlayerItem? var playerLayer: AVPlayerLayer? var timeObserver: Any? var timer: Timer? var videoUrl: String?//视频播放地址 var courseId: Int?//课程ID var courseHourId: Int?//课时ID weak var oldView: UIView? weak var superController: UIViewController? let fullController = FullPlayerVideoController() var isFull = false deinit { player?.currentItem?.cancelPendingSeeks() player?.currentItem?.asset.cancelLoading() if playerTime.text != "00:00" { player?.removeTimeObserver(timeObserver!) } playerItem?.removeObserver(self, forKeyPath: "status") playerItem?.removeObserver(self, forKeyPath: "loadedTimeRanges") playerItem?.removeObserver(self, forKeyPath: "playbackBufferEmpty") playerItem?.removeObserver(self, forKeyPath: "playbackLikelyToKeepUp") NotificationCenter.default.removeObserver(self) } override func awakeFromNib() { super.awakeFromNib() NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(moviePlayDidEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player?.currentItem) NotificationCenter.default.addObserver(self, selector: #selector(appwillResignActive), name: NSNotification.Name.UIApplicationWillResignActive, object: nil) progressSlider.setThumbImage(UIImage(named: "player_slider"), for: .normal) activityView.isHidden = true } func willDisappearController() { if isFull { return } player?.pause() playBtn.isHidden = false playBtn.isSelected = false controlView.isHidden = true } override func layoutSubviews() { super.layoutSubviews() playerLayer?.frame = bounds activityView.center = center } // MARK: - 转屏通知 func deviceOrientationDidChange() { if !Common.isVisibleWithController(viewController()!) || playerItem?.status != .readyToPlay { return } let orient = UIDevice.current.orientation weak var weakSelf = self if orient == .landscapeLeft || orient == .landscapeRight { if !isFull { isFull = true superController?.present(fullController, animated: false, completion: { weakSelf?.fullController.view.addSubview(weakSelf!) weakSelf?.landscapeLayout() }) } } else if orient == .portrait || orient == .portraitUpsideDown { if isFull { isFull = false fullController.dismiss(animated: false, completion: { weakSelf?.oldView?.addSubview(weakSelf!) weakSelf?.portraitLayout() }) } } } func landscapeLayout() { UIApplication.shared.isStatusBarHidden = true frame = UIScreen.main.bounds zoomBtn.isSelected = true } func portraitLayout() { UIApplication.shared.isStatusBarHidden = false frame = oldView!.bounds zoomBtn.isSelected = false } @IBAction func tapGestureClick() { controlView.isHidden = !controlView.isHidden if controlView.isHidden { timer?.invalidate() timer = nil } else { timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(hiddenControlView), userInfo: nil, repeats: false) } if playBtn.isSelected { playBtn.isHidden = controlView.isHidden } else { playBtn.isHidden = false } } func hiddenControlView() { controlView.isHidden = true playBtn.isHidden = playBtn.isSelected } // MARK: - 播放课时视频 func playerCourseHourVideo(_ courseHourVideoUrl: String) { if videoUrl == courseHourVideoUrl { return } if playerItem == nil { videoUrl = courseHourVideoUrl playerVideo() } else { player?.pause() playBtn.isHidden = false playBtn.isSelected = false controlView.isHidden = true if courseHourVideoUrl.isEmpty { AntManage.showDelayToast(message: "还没有视频") return } videoUrl = courseHourVideoUrl player?.currentItem?.cancelPendingSeeks() player?.currentItem?.asset.cancelLoading() if playerTime.text != "00:00" { player?.removeTimeObserver(timeObserver!) } playerItem?.removeObserver(self, forKeyPath: "status") playerItem?.removeObserver(self, forKeyPath: "loadedTimeRanges") playerItem?.removeObserver(self, forKeyPath: "playbackBufferEmpty") playerItem?.removeObserver(self, forKeyPath: "playbackLikelyToKeepUp") playerItem = nil playerLayer?.removeFromSuperlayer() playerLayer = nil player = nil playerVideo() } } // MARK: - 播放 @IBAction func playClick(_ sender: UIButton) { if playerItem == nil { playerVideo() } else { if playBtn.isSelected { player?.pause() playBtn.isHidden = false playBtn.isSelected = false controlView.isHidden = true } else { player?.play() playBtn.isHidden = true playBtn.isSelected = true controlView.isHidden = true } } } func playerVideo() { if videoUrl != nil, !(videoUrl?.isEmpty)! { playerItem = AVPlayerItem(url: URL(string: videoUrl!)!) playerItem?.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil) playerItem?.addObserver(self, forKeyPath: "loadedTimeRanges", options: NSKeyValueObservingOptions.new, context: nil) playerItem?.addObserver(self, forKeyPath: "playbackBufferEmpty", options: NSKeyValueObservingOptions.new, context: nil) playerItem?.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: NSKeyValueObservingOptions.new, context: nil) player = AVPlayer(playerItem: playerItem) playerLayer = AVPlayerLayer(player: player) playerLayer?.frame = bounds playerLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill layer.insertSublayer(playerLayer!, at: 0) player?.play() playBtn.isHidden = true playBtn.isSelected = true activityView.isHidden = false activityView.startAnimating() countVideoClick() coverImg.isHidden = true } else { AntManage.showDelayToast(message: "还没有视频") } } // MARK: - 统计点击量 func countVideoClick() { if courseHourId == nil { return } AntManage.postRequest(path: "course/countVideoClick", params: ["token":AntManage.userModel!.token!, "courseId":courseId!, "courseHourId":courseHourId!], successResult: { (_) in }, failureResult: {}) } // MARK: - 开始拖动视频进度条 @IBAction func beginProgressClick(_ sender: UISlider) { player?.pause() timer?.invalidate() timer = nil } // MARK: - 视频进度条拖动中 @IBAction func progressClick(_ sender: UISlider) { let total = TimeInterval((playerItem?.duration.value)!) / TimeInterval((playerItem?.duration.timescale)!) let dragedSeconds = floorf(Float(total * Double(progressSlider.value))) let dragedCMTime = CMTimeMake(Int64(dragedSeconds), 1) player?.seek(to: dragedCMTime) } // MARK: - 结束拖动视频进度条 @IBAction func endProgressClick(_ sender: UISlider) { player?.play() timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(hiddenControlView), userInfo: nil, repeats: false) } // MARK: - 缩放按钮点击事件 @IBAction func zoomClick(_ sender: UIButton) { if isFull { UIDevice.setOrientation(.portrait) } else { UIDevice.setOrientation(.landscapeRight) } } // MARK: - 视频播放完成 func moviePlayDidEnd() { playBtn.isHidden = false playBtn.isSelected = false player?.pause() player?.seek(to: CMTimeMake(0, 1)) progressSlider.value = 0 playerTime.text = "00:00" } // MARK: - 程序被挂起 func appwillResignActive() { playBtn.isHidden = false playBtn.isSelected = false player?.pause() } // MARK: - override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let item = object as? AVPlayerItem else { return } if keyPath == "status" { if item.status == AVPlayerItemStatus.readyToPlay { playBtn.isHidden = true playBtn.isSelected = true activityView.stopAnimating() activityView.isHidden = true monitoringPlayback() if Common.isVisibleWithController(viewController()!) { player?.play() } } else { playBtn.isHidden = false playBtn.isSelected = false AntManage.showDelayToast(message: "视频加载失败,请重试!") } } else if keyPath == "loadedTimeRanges" { let timeInterval = availableDuration() let duration = playerItem?.duration let totalDuration = CMTimeGetSeconds(duration!) progress.progress = Float(timeInterval / totalDuration) } else if keyPath == "playbackBufferEmpty" { activityView.startAnimating() activityView.isHidden = false } else if keyPath == "playbackLikelyToKeepUp" { activityView.stopAnimating() activityView.isHidden = true if playBtn.isSelected { player?.play() } } } // MARK: - 计算缓冲进度 func availableDuration() -> TimeInterval { let loadedTimeRanges = player?.currentItem?.loadedTimeRanges let timeRange = loadedTimeRanges?.first?.timeRangeValue//获取缓冲区域 let startSeconds = CMTimeGetSeconds((timeRange?.start)!) let durationSeconds = CMTimeGetSeconds((timeRange?.duration)!) return startSeconds + durationSeconds } // MARK: - 监听播放状态 func monitoringPlayback() { weak var weakSelf = self timeObserver = player?.addPeriodicTimeObserver(forInterval: CMTimeMake(1, 1), queue: nil, using: { (time) in if weakSelf == nil { return } //当前进度 weakSelf?.progressSlider.value = Float(CMTimeGetSeconds((weakSelf?.playerItem?.currentTime())!) / (TimeInterval((weakSelf?.playerItem?.duration.value)!) / TimeInterval((weakSelf?.playerItem?.duration.timescale)!))) //duration 总时长 let durMin = Int((TimeInterval((weakSelf?.playerItem?.duration.value)!) / TimeInterval((weakSelf?.playerItem?.duration.timescale)!)) / 60) let durSec = Int(((TimeInterval((weakSelf?.playerItem?.duration.value)!) / TimeInterval((weakSelf?.playerItem?.duration.timescale)!))).truncatingRemainder(dividingBy: 60)) weakSelf?.totalTime.text = NSString.init(format: "%02ld:%02ld", durMin, durSec) as String //当前时长进度progress let proMin = Int(CMTimeGetSeconds((weakSelf?.playerItem?.currentTime())!) / 60) let proSec = Int(CMTimeGetSeconds((weakSelf?.playerItem?.currentTime())!).truncatingRemainder(dividingBy: 60)) weakSelf?.playerTime.text = NSString.init(format: "%02ld:%02ld", proMin, proSec) as String }) } // MARK: - UIGestureRecognizerDelegate func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if touch.view == controlView { return false } return true } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
mit
f8569d835676d61f89980c5dd0a8f64f
36.754875
226
0.603733
5.329925
false
false
false
false