repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
mitchellporter/SVGPath
SVGPath/SVGPath.swift
1
8787
// // SVGPath.swift // SVGPath // // Created by Tim Wood on 1/21/15. // Copyright (c) 2015 Tim Wood. All rights reserved. // import Foundation import CoreGraphics // MARK: UIBezierPath public extension UIBezierPath { convenience init (svgPath: String) { self.init() applyCommands(svgPath, self) } } private func applyCommands (svgPath: String, path: UIBezierPath) { for command in SVGPath(svgPath).commands { switch command.type { case .Move: path.moveToPoint(command.point) case .Line: path.addLineToPoint(command.point) case .QuadCurve: path.addQuadCurveToPoint(command.point, controlPoint: command.control1) case .CubeCurve: path.addCurveToPoint(command.point, controlPoint1: command.control1, controlPoint2: command.control2) case .Close: path.closePath() } } } // MARK: Enums private enum Coordinates { case Absolute case Relative } // MARK: Class public class SVGPath { public var commands: [SVGCommand] = [] private var builder: SVGCommandBuilder = moveTo private var coords: Coordinates = .Absolute private var stride: Int = 2 private var numbers = "" public init (_ string: String) { for char in string { switch char { case "M": use(.Absolute, 2, moveTo) case "m": use(.Relative, 2, moveTo) case "L": use(.Absolute, 2, lineTo) case "l": use(.Relative, 2, lineTo) case "V": use(.Absolute, 1, lineToVertical) case "v": use(.Relative, 1, lineToVertical) case "H": use(.Absolute, 1, lineToHorizontal) case "h": use(.Relative, 1, lineToHorizontal) case "Q": use(.Absolute, 4, quadBroken) case "q": use(.Relative, 4, quadBroken) case "T": use(.Absolute, 2, quadSmooth) case "t": use(.Relative, 2, quadSmooth) case "C": use(.Absolute, 6, cubeBroken) case "c": use(.Relative, 6, cubeBroken) case "S": use(.Absolute, 4, cubeSmooth) case "s": use(.Relative, 4, cubeSmooth) case "Z": use(.Absolute, 1, close) case "z": use(.Absolute, 1, close) default: numbers.append(char) } } finishLastCommand() } private func use (coords: Coordinates, _ stride: Int, _ builder: SVGCommandBuilder) { finishLastCommand() self.builder = builder self.coords = coords self.stride = stride } private func finishLastCommand () { for command in take(SVGPath.parseNumbers(numbers), stride, coords, commands.last, builder) { commands.append(coords == .Relative ? command.relativeTo(commands.last) : command) } numbers = "" } } // MARK: Numbers private let numberSet = NSCharacterSet(charactersInString: "-.0123456789eE") private let numberFormatter = NSNumberFormatter() public extension SVGPath { class func parseNumbers (numbers: String) -> [CGFloat] { var all:[String] = [] var curr = "" var last = "" for char in numbers.unicodeScalars { var next = String(char) if next == "-" && last != "" && last != "E" && last != "e" { if count(curr.utf16) > 0 { all.append(curr) } curr = next } else if numberSet.longCharacterIsMember(char.value) { curr += next } else if count(curr.utf16) > 0 { all.append(curr) curr = "" } last = next } all.append(curr) return all.map() { (number: String) -> CGFloat in if let num = numberFormatter.numberFromString(number)?.doubleValue { return CGFloat(num) } return 0.0 } } } // MARK: Commands public struct SVGCommand { public var point:CGPoint public var control1:CGPoint public var control2:CGPoint public var type:Kind public enum Kind { case Move case Line case CubeCurve case QuadCurve case Close } public init () { let point = CGPoint() self.init(point, point, point, type: .Close) } public init (_ x: CGFloat, _ y: CGFloat, type: Kind) { let point = CGPoint(x: x, y: y) self.init(point, point, point, type: type) } public init (_ cx: CGFloat, _ cy: CGFloat, _ x: CGFloat, _ y: CGFloat) { let control = CGPoint(x: cx, y: cy) self.init(control, control, CGPoint(x: x, y: y), type: .QuadCurve) } public init (_ cx1: CGFloat, _ cy1: CGFloat, _ cx2: CGFloat, _ cy2: CGFloat, _ x: CGFloat, _ y: CGFloat) { self.init(CGPoint(x: cx1, y: cy1), CGPoint(x: cx2, y: cy2), CGPoint(x: x, y: y), type: .CubeCurve) } public init (_ control1: CGPoint, _ control2: CGPoint, _ point: CGPoint, type: Kind) { self.point = point self.control1 = control1 self.control2 = control2 self.type = type } private func relativeTo (other:SVGCommand?) -> SVGCommand { if let otherPoint = other?.point { return SVGCommand(control1 + otherPoint, control2 + otherPoint, point + otherPoint, type: type) } return self } } // MARK: CGPoint helpers private func +(a:CGPoint, b:CGPoint) -> CGPoint { return CGPoint(x: a.x + b.x, y: a.y + b.y) } private func -(a:CGPoint, b:CGPoint) -> CGPoint { return CGPoint(x: a.x - b.x, y: a.y - b.y) } // MARK: Command Builders private typealias SVGCommandBuilder = (ArraySlice<CGFloat>, SVGCommand?, Coordinates) -> SVGCommand private func take (numbers: [CGFloat], stride: Int, coords: Coordinates, last: SVGCommand?, callback: SVGCommandBuilder) -> [SVGCommand] { var out: [SVGCommand] = [] var lastCommand:SVGCommand? = last let count = (numbers.count / stride) * stride for var i = 0; i < count; i += stride { let nums = numbers[i..<i + stride] lastCommand = callback(nums, lastCommand, coords) out.append(lastCommand!) } return out } // MARK: Mm - Move private func moveTo (numbers: ArraySlice<CGFloat>, last: SVGCommand?, coords: Coordinates) -> SVGCommand { return SVGCommand(numbers[0], numbers[1], type: .Move) } // MARK: Ll - Line private func lineTo (numbers: ArraySlice<CGFloat>, last: SVGCommand?, coords: Coordinates) -> SVGCommand { return SVGCommand(numbers[0], numbers[1], type: .Line) } // MARK: Vv - Vertical Line private func lineToVertical (numbers: ArraySlice<CGFloat>, last: SVGCommand?, coords: Coordinates) -> SVGCommand { return SVGCommand(coords == .Absolute ? last?.point.x ?? 0 : 0, numbers[0], type: .Line) } // MARK: Hh - Horizontal Line private func lineToHorizontal (numbers: ArraySlice<CGFloat>, last: SVGCommand?, coords: Coordinates) -> SVGCommand { return SVGCommand(numbers[0], coords == .Absolute ? last?.point.y ?? 0 : 0, type: .Line) } // MARK: Qq - Quadratic Curve To private func quadBroken (numbers: ArraySlice<CGFloat>, last: SVGCommand?, coords: Coordinates) -> SVGCommand { return SVGCommand(numbers[0], numbers[1], numbers[2], numbers[3]) } // MARK: Tt - Smooth Quadratic Curve To private func quadSmooth (numbers: ArraySlice<CGFloat>, last: SVGCommand?, coords: Coordinates) -> SVGCommand { var lastControl = last?.control1 ?? CGPoint() let lastPoint = last?.point ?? CGPoint() if (last?.type ?? .Line) != .QuadCurve { lastControl = lastPoint } var control = lastPoint - lastControl if coords == .Absolute { control = control + lastPoint } return SVGCommand(control.x, control.y, numbers[0], numbers[1]) } // MARK: Cc - Cubic Curve To private func cubeBroken (numbers: ArraySlice<CGFloat>, last: SVGCommand?, coords: Coordinates) -> SVGCommand { return SVGCommand(numbers[0], numbers[1], numbers[2], numbers[3], numbers[4], numbers[5]) } // MARK: Ss - Smooth Cubic Curve To private func cubeSmooth (numbers: ArraySlice<CGFloat>, last: SVGCommand?, coords: Coordinates) -> SVGCommand { var lastControl = last?.control2 ?? CGPoint() let lastPoint = last?.point ?? CGPoint() if (last?.type ?? .Line) != .CubeCurve { lastControl = lastPoint } var control = lastPoint - lastControl if coords == .Absolute { control = control + lastPoint } return SVGCommand(control.x, control.y, numbers[0], numbers[1], numbers[2], numbers[3]) } // MARK: Zz - Close Path private func close (numbers: ArraySlice<CGFloat>, last: SVGCommand?, coords: Coordinates) -> SVGCommand { return SVGCommand() }
mit
cb6f9c7faabe0cc6c7ef3c59ce1c6f88
30.494624
138
0.604188
3.965253
false
false
false
false
AlanHasty/SwiftSensorTag
SwiftSensorTag/SensorTagTableViewCell.swift
1
1672
// // SensorTagTableViewCell.swift // SwiftSensorTag // // Created by Anas Imtiaz on 27/01/2015. // Copyright (c) 2015 Anas Imtiaz. All rights reserved. // import UIKit class SensorTagTableViewCell: UITableViewCell { var sensorNameLabel = UILabel() var sensorValueLabel = UILabel() 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 } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) // sensor name self.addSubview(sensorNameLabel) sensorNameLabel.font = UIFont(name: "HelveticaNeue", size: 18) sensorNameLabel.frame = CGRect(x: self.bounds.origin.x+self.layoutMargins.left*2, y: self.bounds.origin.y, width: self.frame.width, height: self.frame.height) sensorNameLabel.textAlignment = NSTextAlignment.Left sensorNameLabel.text = "Sensor Name Label" // sensor value self.addSubview(sensorValueLabel) sensorValueLabel.font = UIFont(name: "HelveticaNeue", size: 18) sensorValueLabel.frame = CGRect(x: self.bounds.origin.x, y: self.bounds.origin.y, width: self.frame.width, height: self.frame.height) sensorValueLabel.textAlignment = NSTextAlignment.Right sensorValueLabel.text = "Value" } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
bd77225c746f999f8438b79cf2f78cb4
33.122449
166
0.67823
4.4
false
false
false
false
github/Nimble
Nimble/Matchers/RaisesException.swift
77
2875
import Foundation func _raiseExceptionMatcher<T>(message: String, matches: (NSException?) -> Bool) -> MatcherFunc<T> { return MatcherFunc { actualExpression, failureMessage in failureMessage.actualValue = nil failureMessage.postfixMessage = message // It would be better if this was part of Expression, but // Swift compiler crashes when expect() is inside a closure. var exception: NSException? var result: T? var capture = NMBExceptionCapture(handler: ({ e in exception = e }), finally: nil) capture.tryBlock { actualExpression.evaluate() return } return matches(exception) } } public func raiseException(#named: String, #reason: String?) -> MatcherFunc<Any> { var theReason = "" if let reason = reason { theReason = reason } return _raiseExceptionMatcher("raise exception named <\(named)> and reason <\(theReason)>") { exception in return exception?.name == named && exception?.reason == reason } } public func raiseException(#named: String) -> MatcherFunc<Any> { return _raiseExceptionMatcher("raise exception named <\(named)>") { exception in return exception?.name == named } } public func raiseException() -> MatcherFunc<Any> { return _raiseExceptionMatcher("raise any exception") { exception in return exception != nil } } @objc public class NMBObjCRaiseExceptionMatcher : NMBMatcher { var _name: String? var _reason: String? init(name: String?, reason: String?) { _name = name _reason = reason } public func matches(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { let block: () -> Any? = ({ actualBlock(); return nil }) let expr = Expression(expression: block, location: location) if _name != nil && _reason != nil { return raiseException(named: _name!, reason: _reason).matches(expr, failureMessage: failureMessage) } else if _name != nil { return raiseException(named: _name!).matches(expr, failureMessage: failureMessage) } else { return raiseException().matches(expr, failureMessage: failureMessage) } } var named: (name: String) -> NMBObjCRaiseExceptionMatcher { return ({ name in return NMBObjCRaiseExceptionMatcher(name: name, reason: self._reason) }) } var reason: (reason: String?) -> NMBObjCRaiseExceptionMatcher { return ({ reason in return NMBObjCRaiseExceptionMatcher(name: self._name, reason: reason) }) } } extension NMBObjCMatcher { public class func raiseExceptionMatcher() -> NMBObjCRaiseExceptionMatcher { return NMBObjCRaiseExceptionMatcher(name: nil, reason: nil) } }
apache-2.0
1b1688e0c3cb3e34fca28290bdee3db5
33.638554
121
0.638957
4.956897
false
false
false
false
MaximKotliar/Bindy
Sources/Observable.swift
1
3326
// // Observable.swift // Bindy // // Created by Maxim Kotliar on 10/31/17. // Copyright © 2017 Maxim Kotliar. All rights reserved. // import Foundation #if swift(>=5.1) @propertyWrapper public final class Observable<T>: ObservableValueHolder<T> { let equalityClosure: ((T, T) -> Bool)? public override var value: T { didSet { let isEqual = equalityClosure?(oldValue, value) ?? false guard !isEqual else { return } fireBindings(with: .oldValueNewValue(oldValue, value)) } } public required init(_ value: T, options: [ObservableValueHolderOptionKey: Any]? = nil) { self.equalityClosure = options.flatMap { $0[.equalityClosure] as? (T, T) -> Bool } super.init(value, options: options) } public convenience init(_ value: T, equalityCheck: ((T, T) -> Bool)?) { self.init(value, options: equalityCheck.flatMap { [.equalityClosure: $0] } ) } public convenience init(wrappedValue: T) { self.init(wrappedValue) } public var wrappedValue: T { get { return value } set { value = newValue } } public var projectedValue: Observable<T> { return self } } #else public final class Observable<T>: ObservableValueHolder<T> { let equalityClosure: ((T, T) -> Bool)? public override var value: T { didSet { let isEqual = equalityClosure?(oldValue, value) ?? false guard !isEqual else { return } fireBindings(with: .oldValueNewValue(oldValue, value)) } } public required init(_ value: T, options: [ObservableValueHolderOptionKey: Any]? = nil) { self.equalityClosure = options.flatMap { $0[.equalityClosure] as? (T, T) -> Bool } super.init(value, options: options) } public convenience init(_ value: T, equalityCheck: ((T, T) -> Bool)?) { self.init(value, options: equalityCheck.flatMap { [.equalityClosure: $0] } ) } } #endif extension Observable { public func transform<U>(_ transform: @escaping (T) -> U, options: [ObservableValueHolderOptionKey: Any]? = nil) -> Observable<U> { let transformedObserver = Observable<U>(transform(value), options: options) observe(transformedObserver) { [unowned transformedObserver] value in retain(self) transformedObserver.value = transform(value) } return transformedObserver } public func transform<U>(_ transform: @escaping (T) -> U, equalityCheck: ((U, U) -> Bool)?) -> Observable<U> { return self.transform(transform, options: equalityCheck.flatMap { [.equalityClosure: $0] }) } public func transform<U: Equatable>(_ transform: @escaping (T) -> U) -> Observable<U> { return self.transform(transform, equalityCheck: ==) } } public extension Observable where T: Equatable { convenience init(_ value: T) { self.init(value, equalityCheck: ==) } } public protocol ExtendableClass: class {} extension NSObject: ExtendableClass {} public extension ExtendableClass { func attach<T>(to observable: Observable<T>, callback: @escaping (Self, T) -> Void) { observable.observe(self) { [unowned self] value in callback(self, value) } } }
mit
817a047950c63aa3508b9ea5c7418145
28.6875
135
0.621053
4.099877
false
false
false
false
steelwheels/KiwiGraphics
Source/Primitives/KGVertices.swift
1
1165
/** * @file KGVertices.swift * @brief Define KGVertices data structure * @par Copyright * Copyright (C) 2016 Steel Wheels Project */ import Foundation public struct KGVertices { private var mVertices : Array<CGPoint> private var mBounds : CGRect public init(){ mVertices = [] mBounds = CGRect.zero } public var vertices: Array<CGPoint> { return mVertices } public init(veritces vs: Array<CGPoint>){ if vs.count > 0 { mVertices = vs mBounds = KGVertices.allocateBoundRect(vertices: vs) } else { mVertices = [] mBounds = CGRect.zero } } private static func allocateBoundRect(vertices vs: Array<CGPoint>) -> CGRect { if vs.count == 0 { return CGRect.zero } /* Check 1st point */ let o0 = vs[0] var xmin = o0.x var xmax = xmin var ymin = o0.y var ymax = ymin /* Check 2nd, 3rd, ... */ let count = vs.count for i in 1..<count { let on = vs[i] if on.x < xmin { xmin = on.x } else if xmax < on.x { xmax = on.x } if on.y < ymin { ymin = on.y } else if ymax < on.y { ymax = on.y } } return CGRect(x: xmin, y: ymin, width: xmax-xmin, height: ymax-ymin) } }
gpl-2.0
a429d3cb937ea6b15eada6e3f62f609a
18.745763
79
0.612876
2.82767
false
false
false
false
codesman/toolbox
Sources/VaporToolbox/DockerEnter.swift
1
1529
import Console public final class DockerEnter: Command { public let id = "enter" public let signature: [Argument] = [] public let help: [String] = [ "Enters the Docker image container.", "Useful for debugging." ] public let console: ConsoleProtocol public init(console: ConsoleProtocol) { self.console = console } public func run(arguments: [String]) throws { do { _ = try console.backgroundExecute("which docker") } catch ConsoleError.subexecute(_, _) { console.info("Visit https://www.docker.com/products/docker-toolbox") throw ToolboxError.general("Docker not installed.") } do { let contents = try console.backgroundExecute("ls .") if !contents.contains("Dockerfile") { throw ToolboxError.general("No Dockerfile found") } } catch ConsoleError.subexecute(_) { throw ToolboxError.general("Could not check for Dockerfile") } let swiftVersion: String do { swiftVersion = try console.backgroundExecute("cat .swift-version").trim() } catch { throw ToolboxError.general("Could not determine Swift version from .swift-version file.") } let imageName = DockerBuild.imageName(version: swiftVersion) console.info("Copy and run the following line:") console.print("docker run --rm -it -v $(PWD):/vapor --entrypoint bash \(imageName)") } }
mit
3423e1168512cad25e01d0dbc15af9ba
30.854167
101
0.604971
4.778125
false
false
false
false
haawa799/WaniKani-iOS
WaniKani/ViewControllers/ApiKeyPickerController.swift
1
2712
// // ApiKeyPickerController.swift // // // Created by Andriy K. on 8/23/15. // // import UIKit import WaniKit class ApiKeyPickerController: SetupStepViewController { let keyLength = 32 var shouldShowShiba = true // MARK: - IBOutlets and Actions @IBOutlet weak var keyTextField: UITextField! @IBOutlet weak var dogeHintView: DogeHintView! { didSet { dogeHintView.message = "Hope you'll have much good time here.\nI need you to log into your WaniKani account." } } @IBAction func getMyKeyPressed(sender: UIButton) { dogeHintView.hide { (success) -> Void in self.performSegueWithIdentifier("getKey", sender: self) } } @IBAction func textDidChange(textField: UITextField) { let text = textField.text! if text.characters.count == keyLength { appDelegate.keychainManager.setNewApiKey(text) appDelegate.waniApiManager.setApiKey(text) performSegueWithIdentifier("nextPage", sender: self) DataFetchManager.sharedInstance.fetchAllData() } } @objc private func tap() { keyTextField?.resignFirstResponder() } } // MARK: - UIViewController extension ApiKeyPickerController { override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // Use key from clipboard if it's valid let pateboard = UIPasteboard.generalPasteboard() if let string = pateboard.string where string.characters.count == keyLength { keyTextField.text = string textDidChange(keyTextField) } delay(0.5) { () -> () in if self.shouldShowShiba { self.dogeHintView.show() } } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) } override func viewDidLoad() { super.viewDidLoad() let tap = UITapGestureRecognizer(target: self, action: "tap") view.addGestureRecognizer(tap) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { guard let loginVC = segue.destinationViewController as? LoginWebViewController else {return} loginVC.delegate = self } } // MARK: - LoginWebViewControllerDelegate extension ApiKeyPickerController: LoginWebViewControllerDelegate { func apiKeyReceived(apiKey: String) { shouldShowShiba = false keyTextField?.text = apiKey delay(0.9) { () -> () in self.textDidChange(self.keyTextField) } } } // MARK: - SetupStepViewController extension ApiKeyPickerController { override func nextStep() { } override func previousStep() { } override func needsPreviousStep() -> Bool { return false } override func needsNextButton() -> Bool { return false } }
gpl-3.0
e987dcdc27f8158cb743c8b9bf905bf1
23.00885
115
0.686947
4.467875
false
false
false
false
Raizlabs/SketchyCode
SketchyCode/Generation/FunctionDeclaration.swift
1
2088
// // FunctionDeclaration.swift // SketchyCode // // Created by Brian King on 10/15/17. // Copyright © 2017 Brian King. All rights reserved. // import Foundation struct Parameter { let tag: String var variable: VariableRef let _name: String? init(tag: String, variable: VariableRef, name: String? = nil) { self.tag = tag self.variable = variable self._name = name } var name: String { return _name ?? tag } var swiftRepresentation: String { return "\(tag): \(variable.type.name)" } } struct DeclarationOptions: OptionSet { var rawValue: Int static var publicDeclaration = DeclarationOptions(rawValue: 1 << 0) static var overrideDeclaration = DeclarationOptions(rawValue: 1 << 1) static var requiredDeclaration = DeclarationOptions(rawValue: 1 << 2) var swiftPrefix: String { var values: [String] = [] if contains(.publicDeclaration) { values.append("public") } if contains(.overrideDeclaration) { values.append("override") } if contains(.requiredDeclaration) { values.append("required") } if values.count > 0 { values.append("") } return values.joined(separator: " ") } } class FunctionDeclaration { enum Definition { case initializer case function(name: String, result: TypeRef) } let definition: Definition var options: DeclarationOptions var parameters: [Parameter] var block: BlockExpression init(name: String, options: DeclarationOptions, parameters: [Parameter], result: TypeRef, block: BlockExpression) { self.definition = .function(name: name, result: result) self.options = options self.parameters = parameters self.block = block block.invoke = false } init(initializerWith options: DeclarationOptions, parameters: [Parameter], block: BlockExpression) { self.definition = .initializer self.options = options self.parameters = parameters self.block = block block.invoke = false } }
mit
4a9f3906da8bd16264019ab8b5f89505
28.394366
119
0.650216
4.42161
false
false
false
false
cjbeauchamp/tvOSDashboard
Charts/Classes/Charts/PieRadarChartViewBase.swift
1
30881
// // PieRadarChartViewBase.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif /// Base class of PieChartView and RadarChartView. public class PieRadarChartViewBase: ChartViewBase { /// holds the normalized version of the current rotation angle of the chart private var _rotationAngle = CGFloat(270.0) /// holds the raw version of the current rotation angle of the chart private var _rawRotationAngle = CGFloat(270.0) /// flag that indicates if rotation is enabled or not public var rotationEnabled = true /// Sets the minimum offset (padding) around the chart, defaults to 0.0 public var minOffset = CGFloat(0.0) /// iOS && OSX only: Enabled multi-touch rotation using two fingers. private var _rotationWithTwoFingers = false private var _tapGestureRecognizer: NSUITapGestureRecognizer! #if !os(tvOS) private var _rotationGestureRecognizer: NSUIRotationGestureRecognizer! #endif public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { stopDeceleration() } internal override func initialize() { super.initialize() _tapGestureRecognizer = NSUITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:")) self.addGestureRecognizer(_tapGestureRecognizer) #if !os(tvOS) _rotationGestureRecognizer = NSUIRotationGestureRecognizer(target: self, action: Selector("rotationGestureRecognized:")) self.addGestureRecognizer(_rotationGestureRecognizer) _rotationGestureRecognizer.enabled = rotationWithTwoFingers #endif } internal override func calcMinMax() { _deltaX = CGFloat((_data?.xVals.count ?? 0) - 1) } public override func notifyDataSetChanged() { calcMinMax() if let data = _data where _legend !== nil { _legendRenderer.computeLegend(data) } calculateOffsets() setNeedsDisplay() } internal override func calculateOffsets() { var legendLeft = CGFloat(0.0) var legendRight = CGFloat(0.0) var legendBottom = CGFloat(0.0) var legendTop = CGFloat(0.0) if (_legend != nil && _legend.enabled) { var fullLegendWidth = min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) fullLegendWidth += _legend.formSize + _legend.formToTextSpace if (_legend.position == .RightOfChartCenter) { // this is the space between the legend and the chart let spacing = CGFloat(13.0) legendRight = fullLegendWidth + spacing } else if (_legend.position == .RightOfChart) { // this is the space between the legend and the chart let spacing = CGFloat(8.0) let legendWidth = fullLegendWidth + spacing let legendHeight = _legend.neededHeight + _legend.textHeightMax let c = self.midPoint let bottomRight = CGPoint(x: self.bounds.width - legendWidth + 15.0, y: legendHeight + 15) let distLegend = distanceToCenter(x: bottomRight.x, y: bottomRight.y) let reference = getPosition(center: c, dist: self.radius, angle: angleForPoint(x: bottomRight.x, y: bottomRight.y)) let distReference = distanceToCenter(x: reference.x, y: reference.y) let minOffset = CGFloat(5.0) if (distLegend < distReference) { let diff = distReference - distLegend legendRight = minOffset + diff } if (bottomRight.y >= c.y && self.bounds.height - legendWidth > self.bounds.width) { legendRight = legendWidth } } else if (_legend.position == .LeftOfChartCenter) { // this is the space between the legend and the chart let spacing = CGFloat(13.0) legendLeft = fullLegendWidth + spacing } else if (_legend.position == .LeftOfChart) { // this is the space between the legend and the chart let spacing = CGFloat(8.0) let legendWidth = fullLegendWidth + spacing let legendHeight = _legend.neededHeight + _legend.textHeightMax let c = self.midPoint let bottomLeft = CGPoint(x: legendWidth - 15.0, y: legendHeight + 15) let distLegend = distanceToCenter(x: bottomLeft.x, y: bottomLeft.y) let reference = getPosition(center: c, dist: self.radius, angle: angleForPoint(x: bottomLeft.x, y: bottomLeft.y)) let distReference = distanceToCenter(x: reference.x, y: reference.y) let min = CGFloat(5.0) if (distLegend < distReference) { let diff = distReference - distLegend legendLeft = min + diff } if (bottomLeft.y >= c.y && self.bounds.height - legendWidth > self.bounds.width) { legendLeft = legendWidth } } else if (_legend.position == .BelowChartLeft || _legend.position == .BelowChartRight || _legend.position == .BelowChartCenter) { // It's possible that we do not need this offset anymore as it // is available through the extraOffsets, but changing it can mean // changing default visibility for existing apps. let yOffset = self.requiredLegendOffset legendBottom = min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent) } else if (_legend.position == .AboveChartLeft || _legend.position == .AboveChartRight || _legend.position == .AboveChartCenter) { // It's possible that we do not need this offset anymore as it // is available through the extraOffsets, but changing it can mean // changing default visibility for existing apps. let yOffset = self.requiredLegendOffset legendTop = min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent) } legendLeft += self.requiredBaseOffset legendRight += self.requiredBaseOffset legendTop += self.requiredBaseOffset } legendTop += self.extraTopOffset legendRight += self.extraRightOffset legendBottom += self.extraBottomOffset legendLeft += self.extraLeftOffset var minOffset = self.minOffset if (self.isKindOfClass(RadarChartView)) { let x = (self as! RadarChartView).xAxis if x.isEnabled && x.drawLabelsEnabled { minOffset = max(minOffset, x.labelRotatedWidth) } } let offsetLeft = max(minOffset, legendLeft) let offsetTop = max(minOffset, legendTop) let offsetRight = max(minOffset, legendRight) let offsetBottom = max(minOffset, max(self.requiredBaseOffset, legendBottom)) _viewPortHandler.restrainViewPort(offsetLeft: offsetLeft, offsetTop: offsetTop, offsetRight: offsetRight, offsetBottom: offsetBottom) } /// - returns: the angle relative to the chart center for the given point on the chart in degrees. /// The angle is always between 0 and 360°, 0° is NORTH, 90° is EAST, ... public func angleForPoint(x x: CGFloat, y: CGFloat) -> CGFloat { let c = centerOffsets let tx = Double(x - c.x) let ty = Double(y - c.y) let length = sqrt(tx * tx + ty * ty) let r = acos(ty / length) var angle = r * ChartUtils.Math.RAD2DEG if (x > c.x) { angle = 360.0 - angle } // add 90° because chart starts EAST angle = angle + 90.0 // neutralize overflow if (angle > 360.0) { angle = angle - 360.0 } return CGFloat(angle) } /// Calculates the position around a center point, depending on the distance /// from the center, and the angle of the position around the center. internal func getPosition(center center: CGPoint, dist: CGFloat, angle: CGFloat) -> CGPoint { return CGPoint(x: center.x + dist * cos(angle * ChartUtils.Math.FDEG2RAD), y: center.y + dist * sin(angle * ChartUtils.Math.FDEG2RAD)) } /// - returns: the distance of a certain point on the chart to the center of the chart. public func distanceToCenter(x x: CGFloat, y: CGFloat) -> CGFloat { let c = self.centerOffsets var dist = CGFloat(0.0) var xDist = CGFloat(0.0) var yDist = CGFloat(0.0) if (x > c.x) { xDist = x - c.x } else { xDist = c.x - x } if (y > c.y) { yDist = y - c.y } else { yDist = c.y - y } // pythagoras dist = sqrt(pow(xDist, 2.0) + pow(yDist, 2.0)) return dist } /// - returns: the xIndex for the given angle around the center of the chart. /// -1 if not found / outofbounds. public func indexForAngle(angle: CGFloat) -> Int { fatalError("indexForAngle() cannot be called on PieRadarChartViewBase") } /// current rotation angle of the pie chart /// /// **default**: 270 --> top (NORTH) /// - returns: will always return a normalized value, which will be between 0.0 < 360.0 public var rotationAngle: CGFloat { get { return _rotationAngle } set { _rawRotationAngle = newValue _rotationAngle = ChartUtils.normalizedAngleFromAngle(newValue) setNeedsDisplay() } } /// gets the raw version of the current rotation angle of the pie chart the returned value could be any value, negative or positive, outside of the 360 degrees. /// this is used when working with rotation direction, mainly by gestures and animations. public var rawRotationAngle: CGFloat { return _rawRotationAngle } /// - returns: the diameter of the pie- or radar-chart public var diameter: CGFloat { let content = _viewPortHandler.contentRect return min(content.width, content.height) } /// - returns: the radius of the chart in pixels. public var radius: CGFloat { fatalError("radius cannot be called on PieRadarChartViewBase") } /// - returns: the required offset for the chart legend. internal var requiredLegendOffset: CGFloat { fatalError("requiredLegendOffset cannot be called on PieRadarChartViewBase") } /// - returns: the base offset needed for the chart without calculating the /// legend size. internal var requiredBaseOffset: CGFloat { fatalError("requiredBaseOffset cannot be called on PieRadarChartViewBase") } public override var chartYMax: Double { return 0.0 } public override var chartYMin: Double { return 0.0 } /// The SelectionDetail objects give information about the value at the selected index and the DataSet it belongs to. /// - returns: an array of SelectionDetail objects for the given x-index. public func getSelectionDetailsAtIndex(xIndex: Int) -> [ChartSelectionDetail] { var vals = [ChartSelectionDetail]() guard let data = _data else { return vals } for (var i = 0; i < data.dataSetCount; i++) { guard let dataSet = data.getDataSetByIndex(i) else { continue } if !dataSet.isHighlightEnabled { continue } // extract all y-values from all DataSets at the given x-index let yVal = dataSet.yValForXIndex(xIndex) if (yVal.isNaN) { continue } vals.append(ChartSelectionDetail(value: yVal, dataSetIndex: i, dataSet: dataSet)) } return vals } public var isRotationEnabled: Bool { return rotationEnabled; } /// flag that indicates if rotation is done with two fingers or one. /// when the chart is inside a scrollview, you need a two-finger rotation because a one-finger rotation eats up all touch events. /// /// On iOS this will disable one-finger rotation. /// On OSX this will keep two-finger multitouch rotation, and one-pointer mouse rotation. /// /// **default**: false public var rotationWithTwoFingers: Bool { get { return _rotationWithTwoFingers } set { _rotationWithTwoFingers = newValue #if !os(tvOS) _rotationGestureRecognizer.enabled = _rotationWithTwoFingers #endif } } /// flag that indicates if rotation is done with two fingers or one. /// when the chart is inside a scrollview, you need a two-finger rotation because a one-finger rotation eats up all touch events. /// /// On iOS this will disable one-finger rotation. /// On OSX this will keep two-finger multitouch rotation, and one-pointer mouse rotation. /// /// **default**: false public var isRotationWithTwoFingers: Bool { return _rotationWithTwoFingers } // MARK: - Animation private var _spinAnimator: ChartAnimator! /// Applys a spin animation to the Chart. public func spin(duration duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easing: ChartEasingFunctionBlock?) { if (_spinAnimator != nil) { _spinAnimator.stop() } _spinAnimator = ChartAnimator() _spinAnimator.updateBlock = { self.rotationAngle = (toAngle - fromAngle) * self._spinAnimator.phaseX + fromAngle } _spinAnimator.stopBlock = { self._spinAnimator = nil; } _spinAnimator.animate(xAxisDuration: duration, easing: easing) } public func spin(duration duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easingOption: ChartEasingOption) { spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: easingFunctionFromOption(easingOption)) } public func spin(duration duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat) { spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: nil) } public func stopSpinAnimation() { if (_spinAnimator != nil) { _spinAnimator.stop() } } // MARK: - Gestures private var _rotationGestureStartPoint: CGPoint! private var _isRotating = false private var _startAngle = CGFloat(0.0) private struct AngularVelocitySample { var time: NSTimeInterval var angle: CGFloat } private var _velocitySamples = [AngularVelocitySample]() private var _decelerationLastTime: NSTimeInterval = 0.0 private var _decelerationDisplayLink: NSUIDisplayLink! private var _decelerationAngularVelocity: CGFloat = 0.0 internal final func processRotationGestureBegan(location location: CGPoint) { self.resetVelocity() if rotationEnabled { self.sampleVelocity(touchLocation: location) } self.setGestureStartAngle(x: location.x, y: location.y) _rotationGestureStartPoint = location } internal final func processRotationGestureMoved(location location: CGPoint) { if isDragDecelerationEnabled { sampleVelocity(touchLocation: location) } if !_isRotating && distance( eventX: location.x, startX: _rotationGestureStartPoint.x, eventY: location.y, startY: _rotationGestureStartPoint.y) > CGFloat(8.0) { _isRotating = true } else { self.updateGestureRotation(x: location.x, y: location.y) setNeedsDisplay() } } internal final func processRotationGestureEnded(location location: CGPoint) { if isDragDecelerationEnabled { stopDeceleration() sampleVelocity(touchLocation: location) _decelerationAngularVelocity = calculateVelocity() if _decelerationAngularVelocity != 0.0 { _decelerationLastTime = CACurrentMediaTime() _decelerationDisplayLink = NSUIDisplayLink(target: self, selector: Selector("decelerationLoop")) _decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) } } } internal final func processRotationGestureCancelled() { if (_isRotating) { _isRotating = false } } #if !os(OSX) public override func nsuiTouchesBegan(touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { // if rotation by touch is enabled if (rotationEnabled) { stopDeceleration() if (!rotationWithTwoFingers) { let touch = touches.first as NSUITouch! let touchLocation = touch.locationInView(self) processRotationGestureBegan(location: touchLocation) } } if (!_isRotating) { super.nsuiTouchesBegan(touches, withEvent: event) } } public override func nsuiTouchesMoved(touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { if (rotationEnabled && !rotationWithTwoFingers) { let touch = touches.first as NSUITouch! let touchLocation = touch.locationInView(self) processRotationGestureMoved(location: touchLocation) } if (!_isRotating) { super.nsuiTouchesMoved(touches, withEvent: event) } } public override func nsuiTouchesEnded(touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { if (!_isRotating) { super.nsuiTouchesEnded(touches, withEvent: event) } if (rotationEnabled && !rotationWithTwoFingers) { let touch = touches.first as NSUITouch! let touchLocation = touch.locationInView(self) processRotationGestureEnded(location: touchLocation) } if (_isRotating) { _isRotating = false } } public override func nsuiTouchesCancelled(touches: Set<NSUITouch>?, withEvent event: NSUIEvent?) { super.nsuiTouchesCancelled(touches, withEvent: event) processRotationGestureCancelled() } #endif #if os(OSX) public override func mouseDown(theEvent: NSEvent) { // if rotation by touch is enabled if rotationEnabled { stopDeceleration() let location = self.convertPoint(theEvent.locationInWindow, fromView: nil) processRotationGestureBegan(location: location) } if !_isRotating { super.mouseDown(theEvent) } } public override func mouseDragged(theEvent: NSEvent) { if rotationEnabled { let location = self.convertPoint(theEvent.locationInWindow, fromView: nil) processRotationGestureMoved(location: location) } if !_isRotating { super.mouseDragged(theEvent) } } public override func mouseUp(theEvent: NSEvent) { if !_isRotating { super.mouseUp(theEvent) } if rotationEnabled { let location = self.convertPoint(theEvent.locationInWindow, fromView: nil) processRotationGestureEnded(location: location) } if _isRotating { _isRotating = false } } #endif private func resetVelocity() { _velocitySamples.removeAll(keepCapacity: false) } private func sampleVelocity(touchLocation touchLocation: CGPoint) { let currentTime = CACurrentMediaTime() _velocitySamples.append(AngularVelocitySample(time: currentTime, angle: angleForPoint(x: touchLocation.x, y: touchLocation.y))) // Remove samples older than our sample time - 1 seconds for (var i = 0, count = _velocitySamples.count; i < count - 2; i++) { if (currentTime - _velocitySamples[i].time > 1.0) { _velocitySamples.removeAtIndex(0) i-- count-- } else { break } } } private func calculateVelocity() -> CGFloat { if (_velocitySamples.isEmpty) { return 0.0 } var firstSample = _velocitySamples[0] var lastSample = _velocitySamples[_velocitySamples.count - 1] // Look for a sample that's closest to the latest sample, but not the same, so we can deduce the direction var beforeLastSample = firstSample for (var i = _velocitySamples.count - 1; i >= 0; i--) { beforeLastSample = _velocitySamples[i] if (beforeLastSample.angle != lastSample.angle) { break } } // Calculate the sampling time var timeDelta = lastSample.time - firstSample.time if (timeDelta == 0.0) { timeDelta = 0.1 } // Calculate clockwise/ccw by choosing two values that should be closest to each other, // so if the angles are two far from each other we know they are inverted "for sure" var clockwise = lastSample.angle >= beforeLastSample.angle if (abs(lastSample.angle - beforeLastSample.angle) > 270.0) { clockwise = !clockwise } // Now if the "gesture" is over a too big of an angle - then we know the angles are inverted, and we need to move them closer to each other from both sides of the 360.0 wrapping point if (lastSample.angle - firstSample.angle > 180.0) { firstSample.angle += 360.0 } else if (firstSample.angle - lastSample.angle > 180.0) { lastSample.angle += 360.0 } // The velocity var velocity = abs((lastSample.angle - firstSample.angle) / CGFloat(timeDelta)) // Direction? if (!clockwise) { velocity = -velocity } return velocity } /// sets the starting angle of the rotation, this is only used by the touch listener, x and y is the touch position private func setGestureStartAngle(x x: CGFloat, y: CGFloat) { _startAngle = angleForPoint(x: x, y: y) // take the current angle into consideration when starting a new drag _startAngle -= _rotationAngle } /// updates the view rotation depending on the given touch position, also takes the starting angle into consideration private func updateGestureRotation(x x: CGFloat, y: CGFloat) { self.rotationAngle = angleForPoint(x: x, y: y) - _startAngle } public func stopDeceleration() { if (_decelerationDisplayLink !== nil) { _decelerationDisplayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) _decelerationDisplayLink = nil } } @objc private func decelerationLoop() { let currentTime = CACurrentMediaTime() _decelerationAngularVelocity *= self.dragDecelerationFrictionCoef let timeInterval = CGFloat(currentTime - _decelerationLastTime) self.rotationAngle += _decelerationAngularVelocity * timeInterval _decelerationLastTime = currentTime if(abs(_decelerationAngularVelocity) < 0.001) { stopDeceleration() } } /// - returns: the distance between two points private func distance(eventX eventX: CGFloat, startX: CGFloat, eventY: CGFloat, startY: CGFloat) -> CGFloat { let dx = eventX - startX let dy = eventY - startY return sqrt(dx * dx + dy * dy) } /// - returns: the distance between two points private func distance(from from: CGPoint, to: CGPoint) -> CGFloat { let dx = from.x - to.x let dy = from.y - to.y return sqrt(dx * dx + dy * dy) } /// reference to the last highlighted object private var _lastHighlight: ChartHighlight! @objc private func tapGestureRecognized(recognizer: NSUITapGestureRecognizer) { if (recognizer.state == NSUIGestureRecognizerState.Ended) { if !self.isHighLightPerTapEnabled { return } let location = recognizer.locationInView(self) let distance = distanceToCenter(x: location.x, y: location.y) // check if a slice was touched if (distance > self.radius) { // if no slice was touched, highlight nothing self.highlightValues(nil) if _lastHighlight == nil { self.highlightValues(nil) // do not call delegate } else { self.highlightValue(highlight: nil, callDelegate: true) // call delegate } _lastHighlight = nil } else { var angle = angleForPoint(x: location.x, y: location.y) if (self.isKindOfClass(PieChartView)) { angle /= _animator.phaseY } let index = indexForAngle(angle) // check if the index could be found if (index < 0) { self.highlightValues(nil) _lastHighlight = nil } else { let valsAtIndex = getSelectionDetailsAtIndex(index) var dataSetIndex = 0 // get the dataset that is closest to the selection (PieChart only has one DataSet) if (self.isKindOfClass(RadarChartView)) { dataSetIndex = ChartUtils.closestDataSetIndex(valsAtIndex, value: Double(distance / (self as! RadarChartView).factor), axis: nil) } if (dataSetIndex < 0) { self.highlightValues(nil) _lastHighlight = nil } else { let h = ChartHighlight(xIndex: index, dataSetIndex: dataSetIndex) if (_lastHighlight !== nil && h == _lastHighlight) { self.highlightValue(highlight: nil, callDelegate: true) _lastHighlight = nil } else { self.highlightValue(highlight: h, callDelegate: true) _lastHighlight = h } } } } } } #if !os(tvOS) @objc private func rotationGestureRecognized(recognizer: NSUIRotationGestureRecognizer) { if (recognizer.state == NSUIGestureRecognizerState.Began) { stopDeceleration() _startAngle = self.rawRotationAngle } if (recognizer.state == NSUIGestureRecognizerState.Began || recognizer.state == NSUIGestureRecognizerState.Changed) { let angle = ChartUtils.Math.FRAD2DEG * recognizer.nsuiRotation self.rotationAngle = _startAngle + angle setNeedsDisplay() } else if (recognizer.state == NSUIGestureRecognizerState.Ended) { let angle = ChartUtils.Math.FRAD2DEG * recognizer.nsuiRotation self.rotationAngle = _startAngle + angle setNeedsDisplay() if (isDragDecelerationEnabled) { stopDeceleration() _decelerationAngularVelocity = ChartUtils.Math.FRAD2DEG * recognizer.velocity if (_decelerationAngularVelocity != 0.0) { _decelerationLastTime = CACurrentMediaTime() _decelerationDisplayLink = NSUIDisplayLink(target: self, selector: Selector("decelerationLoop")) _decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) } } } } #endif }
apache-2.0
208310b5ce7a71d9448ebcfafa6e61bd
31.434874
191
0.559381
5.548428
false
false
false
false
Houzz/PuzzleLayout
PuzzleLayout/PuzzleLayout/Layout/Sections Layout/QuickColumnBasedPuzzlePieceSectionLayout.swift
1
58304
// // ColumnBasedPuzzlePieceSectionLayout.swift // PuzzleLayout // // Created by Yossi Avramov on 05/10/2016. // Copyright © 2016 Houzz. All rights reserved. // import UIKit public class QuickColumnBasedPuzzlePieceSectionLayout: QuickPuzzlePieceSectionLayout, PuzzlePieceSectionLayoutSeperatable { //MARK: - Public /** The margins used to lay out content in a section Section insets reflect the spacing at the outer edges of the section. The margins affect the initial position of the header view, the minimum space on either side of each line of items, and the distance from the last line to the footer view. The margin insets do not affect the size of the header and footer views in the non scrolling direction. The default edge insets are all set to 0. */ public var sectionInsets: UIEdgeInsets = .zero { didSet { if let ctx = invalidationContext(with: kInvalidateForRowInfoChange) { parentLayout!.invalidateLayout(with: ctx) } else if let _ = itemsInfo { if let type = estimatedColumnType ?? columnType { if type.hasItemSize { itemSizeBased_fixForRowInfoChange() } else { columnsNumberBased_fixForRowInfoChange() } } } } } /** The minimum spacing to use between items in the same row. This value represents the minimum spacing between items in the same row. This spacing is used to compute how many items can fit in a single line, but after the number of items is determined, the actual spacing may possibly be adjusted upward. The default value of this property is 0. */ public var minimumInteritemSpacing: CGFloat = 0 { didSet { if let ctx = invalidationContext(with: kInvalidateForRowInfoChange) { parentLayout!.invalidateLayout(with: ctx) } else if let _ = itemsInfo { if let type = estimatedColumnType ?? columnType { if type.hasItemSize { itemSizeBased_fixForRowInfoChange() } else { columnsNumberBased_fixForRowInfoChange() } } } } } /** The minimum spacing to use between lines of items in the grid. This value represents the minimum spacing between successive rows. This spacing is not applied to the space between the header and the first line or between the last line and the footer. The default value of this property is 0. */ public var minimumLineSpacing: CGFloat = 0 { didSet { if let ctx = invalidationContext(with: kInvalidateForMinimumLineSpacingChange) { parentLayout!.invalidateLayout(with: ctx) } else if let _ = itemsInfo { updateItemsOriginY(forceUpdateOrigin: true) } } } /// The column type if cells shouldn't be self-sized. Othersize, nil. public private(set) var columnType: ColumnType? = .itemSize(size: CGSize(width: 50, height: 50)) /// The column type if cells should be self-sized. Othersize, nil. public private(set) var estimatedColumnType: ColumnType? = nil /// The row alignment if 'estimatedColumnType != nil' public private(set) var rowAlignment: RowAlignmentOnItemSelfSizing = .none /// Set the column type for cells without self-sizing. When setting it, 'estimatedColumnType' will set to nil. public func setColumnType(_ type: ColumnType) { estimatedColumnType = nil rowAlignment = .none columnType = type if let ctx = self.invalidationContext(with: kInvalidateForColumnTypeChange) { parentLayout!.invalidateLayout(with: ctx) } else if let _ = itemsInfo { updateItemsList() } } /// Set the column type for cells with self-sizing. When setting it, 'columnType' will set to nil. public func setEstimatedColumnType(_ type: ColumnType, rowAlignment: RowAlignmentOnItemSelfSizing) { columnType = nil if rowAlignment == .none { #if DEBUGLog DEBUGLog("'rowAlignment' can't be none. Set to alignCenter") #endif self.rowAlignment = .alignCenter } else { self.rowAlignment = rowAlignment } estimatedColumnType = type if let ctx = self.invalidationContext(with: kInvalidateForColumnTypeChange) { parentLayout!.invalidateLayout(with: ctx) } else if let _ = itemsInfo { updateItemsList() } } /// Set the row alignment if 'estimatedColumnType != nil' public func updateRowAlignment(to rowAlignment: RowAlignmentOnItemSelfSizing) { guard estimatedColumnType != nil else { #if DEBUGLog DEBUGLog("can't update 'rowAlignment' when 'estimatedColumnType' is nil.") #endif return } if rowAlignment == .none { #if DEBUGLog DEBUGLog("'rowAlignment' can't be none. Set to alignCenter") #endif self.rowAlignment = .alignCenter } else { self.rowAlignment = rowAlignment } if let ctx = self.invalidationContext(with: kInvalidateForRowAlignmentChange) { parentLayout!.invalidateLayout(with: ctx) } } /** The default height type to use for section header. The default height is no header. Section header is positioned a section origin (0,0) in section coordinate system (Section insets top doesn't affect it). */ public var headerHeight: HeadeFooterHeightSize = .none { didSet { if let ctx = self.invalidationContext(with: kInvalidateForHeaderEstimatedHeightChange) { parentLayout!.invalidateLayout(with: ctx) } else { updateItemsOriginY(updateHeaderHeight: true) } } } /** A Boolean value indicating whether headers pin to the top of the collection view bounds during scrolling. When this property is true, section header views scroll with content until they reach the top of the screen, at which point they are pinned to the upper bounds of the collection view. Each new header view that scrolls to the top of the screen pushes the previously pinned header view offscreen. */ public var sectionHeaderPinToVisibleBounds: Bool = false { didSet { switch headerHeight { case .none: break default: if let ctx = self.invalidationContext(with: kInvalidateForHeaderEstimatedHeightChange) { parentLayout!.invalidateLayout(with: ctx) } } } } /** The default height type to use for section footer. The default height is no footer. Section footer is positioned a section origin (0,sectionHeight-footerHeight) in section coordinate system. */ public var footerHeight: HeadeFooterHeightSize = .none { didSet { if let ctx = self.invalidationContext(with: kInvalidateForFooterEstimatedHeightChange) { parentLayout!.invalidateLayout(with: ctx) } else { updateFooter() } } } /** A Boolean value indicating whether footers pin to the bottom of the collection view bounds during scrolling. When this property is true, section footer views scroll with content until they reach the bottom of the screen, at which point they are pinned to the lower bounds of the collection view. Each new footer view that scrolls to the bottom of the screen pushes the previously pinned footer view offscreen. */ public var sectionFooterPinToVisibleBounds: Bool = false { didSet { switch footerHeight { case .none: break default: if let ctx = self.invalidationContext(with: kInvalidateForFooterEstimatedHeightChange) { parentLayout!.invalidateLayout(with: ctx) } } } } /// A Boolean value indicating whether should add view on section top insets. public var showTopGutter: Bool = false { didSet { if oldValue != showTopGutter && sectionInsets.top != 0, let ctx = self.invalidationContext { ctx.invalidateSectionLayoutData = self ctx.invalidateDecorationElements(ofKind: PuzzleCollectionElementKindSectionTopGutter, at: [indexPath(forIndex: 0)!]) parentLayout!.invalidateLayout(with: ctx) } } } public var topGutterInsets: UIEdgeInsets /// A Boolean value indicating whether should add view on section bottom insets. public var showBottomGutter: Bool = false { didSet { if oldValue != showBottomGutter && sectionInsets.bottom != 0, let ctx = self.invalidationContext { ctx.invalidateSectionLayoutData = self ctx.invalidateDecorationElements(ofKind: PuzzleCollectionElementKindSectionBottomGutter, at: [indexPath(forIndex: 0)!]) parentLayout!.invalidateLayout(with: ctx) } } } public var bottomGutterInsets: UIEdgeInsets /// Reset the layout public func resetLayout() { if let ctx = self.invalidationContext(with: kInvalidateForResetLayout) { ctx.invalidateSectionLayoutData = self parentLayout!.invalidateLayout(with: ctx) } } //MARK: - Init /** Init a layout for cells without supporting self-sizing. Cell won't allow updating it size to best fit for its content views. - parameter columnType: The column type. - parameter sectionInsets: The margins used to lay out content in a section. Default, all set to 0. - parameter minimumInteritemSpacing: The minimum spacing to use between items in the same row. Default is 0. - parameter minimumLineSpacing: The minimum spacing to use between lines of items in the grid. Default is 0. - parameter headerHeight: The default height type to use for section header. The default height is no header. - parameter sectionHeaderPinToVisibleBounds: A Boolean value indicating whether headers pin to the top of the collection view bounds during scrolling. - parameter footerHeight: The default height type to use for section footer. The default height is no footer. - parameter sectionFooterPinToVisibleBounds: A Boolean value indicating whether footers pin to the bottom of the collection view bounds during scrolling. - parameter separatorLineStyle: A PuzzlePieceSeparatorLineStyle value indicating if should add to each cell a separator line in its bottom. Default, show separator line for all cells. - parameter separatorLineInsets: An insets for separator line from the cell left & right edges. Default, left & right are zero. - parameter separatorLineColor: The color for separator lines. On nil, use the default color from the 'PuzzleCollectionViewLayout'. Default is nil. - parameter showTopGutter: A Boolean value indicating whether should add view on section top insets. - parameter showBottomGutter: A Boolean value indicating whether should add view on section bottom insets. */ public init(columnType: ColumnType, sectionInsets: UIEdgeInsets = .zero, minimumInteritemSpacing: CGFloat = 0, minimumLineSpacing: CGFloat = 0, headerHeight: HeadeFooterHeightSize = .none, sectionHeaderPinToVisibleBounds: Bool = false, footerHeight: HeadeFooterHeightSize = .none, sectionFooterPinToVisibleBounds: Bool = false, separatorLineStyle: PuzzlePieceSeparatorLineStyle = .all, separatorLineInsets: UIEdgeInsets = .zero, separatorLineColor: UIColor? = nil, showTopGutter: Bool = false, topGutterInsets: UIEdgeInsets = .zero, showBottomGutter: Bool = false, bottomGutterInsets: UIEdgeInsets = .zero) { self.columnType = columnType self.sectionInsets = sectionInsets self.minimumInteritemSpacing = minimumInteritemSpacing self.minimumLineSpacing = minimumLineSpacing self.headerHeight = headerHeight self.sectionHeaderPinToVisibleBounds = sectionHeaderPinToVisibleBounds self.footerHeight = footerHeight self.sectionFooterPinToVisibleBounds = sectionFooterPinToVisibleBounds self.topGutterInsets = topGutterInsets self.showTopGutter = showTopGutter self.bottomGutterInsets = bottomGutterInsets self.showBottomGutter = showBottomGutter super.init() self.separatorLineStyle = separatorLineStyle self.separatorLineInsets = separatorLineInsets self.separatorLineColor = separatorLineColor } /** Init a layout for cells with supporting self-sizing. - parameter estimatedColumnType: The estimated column type. - parameter rowAlignment: The row alignment to align cells in same row with different heights. Default, cells in same row have same center. - parameter sectionInsets: The margins used to lay out content in a section. Default, all set to 0. - parameter minimumInteritemSpacing: The minimum spacing to use between items in the same row. Default is 0. - parameter minimumLineSpacing: The minimum spacing to use between lines of items in the grid. Default is 0. - parameter headerHeight: The default height type to use for section header. The default height is no header. - parameter sectionHeaderPinToVisibleBounds: A Boolean value indicating whether headers pin to the top of the collection view bounds during scrolling. - parameter footerHeight: The default height type to use for section footer. The default height is no footer. - parameter sectionFooterPinToVisibleBounds: A Boolean value indicating whether footers pin to the bottom of the collection view bounds during scrolling. - parameter separatorLineStyle: A PuzzlePieceSeparatorLineStyle value indicating if should add to each cell a separator line in its bottom. Default, show separator line for all cells. - parameter separatorLineInsets: An insets for separator line from the cell left & right edges. Default, left & right are zero. - parameter separatorLineColor: The color for separator lines. On nil, use the default color from the 'PuzzleCollectionViewLayout'. Default is nil. - parameter showTopGutter: A Boolean value indicating whether should add view on section top insets. - parameter showBottomGutter: A Boolean value indicating whether should add view on section bottom insets. */ public init(estimatedColumnType: ColumnType, rowAlignment: RowAlignmentOnItemSelfSizing = .alignCenter, sectionInsets: UIEdgeInsets = .zero, minimumInteritemSpacing: CGFloat = 0, minimumLineSpacing: CGFloat = 0, headerHeight: HeadeFooterHeightSize = .none, sectionHeaderPinToVisibleBounds: Bool = false, footerHeight: HeadeFooterHeightSize = .none, sectionFooterPinToVisibleBounds: Bool = false, separatorLineStyle: PuzzlePieceSeparatorLineStyle = .all, separatorLineInsets: UIEdgeInsets = .zero, separatorLineColor: UIColor? = nil, showTopGutter: Bool = false, topGutterInsets: UIEdgeInsets = .zero, showBottomGutter: Bool = false, bottomGutterInsets: UIEdgeInsets = .zero) { self.estimatedColumnType = estimatedColumnType self.rowAlignment = rowAlignment self.sectionInsets = sectionInsets self.minimumInteritemSpacing = minimumInteritemSpacing self.minimumLineSpacing = minimumLineSpacing self.headerHeight = headerHeight self.sectionHeaderPinToVisibleBounds = sectionHeaderPinToVisibleBounds self.footerHeight = footerHeight self.sectionFooterPinToVisibleBounds = sectionFooterPinToVisibleBounds self.topGutterInsets = topGutterInsets self.showTopGutter = showTopGutter self.bottomGutterInsets = bottomGutterInsets self.showBottomGutter = showBottomGutter super.init() self.separatorLineStyle = separatorLineStyle self.separatorLineInsets = separatorLineInsets self.separatorLineColor = separatorLineColor } //MARK: - PuzzlePieceSectionLayout override public var heightOfSection: CGFloat { var maxY: CGFloat = 0 if let footer = footerInfo { maxY = footer.maxOriginY } else if let lastItem = itemsInfo.last { maxY = lastItem.frame.minY + lastItem.rowHeight + sectionInsets.bottom } else if let header = headerInfo { maxY = header.maxOriginY + sectionInsets.bottom } return maxY } override public func invalidate(for reason: InvalidationReason, with info: Any?) { super.invalidate(for: reason, with: info) if reason == .resetLayout || ((info as? String) == kInvalidateForResetLayout) { itemsInfo = nil headerInfo = nil footerInfo = nil } guard let _ = itemsInfo else { return } if let invalidationStr = info as? String { switch invalidationStr { case kInvalidateForRowInfoChange: if let type = estimatedColumnType ?? columnType { if type.hasItemSize { itemSizeBased_fixForRowInfoChange() } else { columnsNumberBased_fixForRowInfoChange() } } case kInvalidateForColumnTypeChange: updateItemsList() case kInvalidateForHeaderEstimatedHeightChange: updateItemsOriginY(updateHeaderHeight: true) case kInvalidateHeaderForPreferredHeight, kInvalidateForMinimumLineSpacingChange: updateItemsOriginY(forceUpdateOrigin: true) case kInvalidateForFooterEstimatedHeightChange: updateFooter() default: break } } else if let itemIndex = info as? Int { updateItems(fromIndex: itemIndex) } } override public func invalidateItem(at index: Int) { switch itemsInfo[index].heightState { case .computed: itemsInfo[index].heightState = .estimated case .fixed: if itemsInfo[index].frame.height != itemSize.height { itemsInfo[index].frame.size.height = itemSize.height itemsInfo[index].rowHeight = itemSize.height updateItems(fromIndex: index) } default: break } } override public func invalidateSupplementaryView(ofKind elementKind: String, at index: Int) { switch elementKind { case PuzzleCollectionElementKindSectionHeader: if let _ = headerInfo { switch headerInfo!.heightState { case .computed: headerInfo!.heightState = .estimated case .fixed: switch headerHeight { case .fixed(let height): if headerInfo!.height != height { headerInfo!.height = height updateItemsOriginY(forceUpdateOrigin: true) } default: assert(false, "How it can be? 'headerInfo.heightState' is fixed but 'headerHeight' isn't") } default: break } } case PuzzleCollectionElementKindSectionFooter: if let _ = footerInfo { switch footerInfo!.heightState { case .computed: footerInfo!.heightState = .estimated case .fixed: switch footerHeight { case .fixed(let height): if footerInfo!.height != height { footerInfo!.height = height } default: assert(false, "How it can be? 'footerInfo.heightState' is fixed but 'footerHeight' isn't") } default: break } } default: break } } override public func prepare(for reason: InvalidationReason, updates: [SectionUpdate]?) { super.prepare(for: reason, updates: updates) if itemsInfo == nil { collectionViewWidth = sectionWidth prepareItemsFromScratch() } else if reason == .reloadDataForUpdateDataSourceCounts && (updates?.isEmpty ?? true) == false { let heightState: ItemHeightState = (estimatedColumnType != nil) ? .estimated : .fixed for update in updates! { switch update { case .insertItems(let itemIndexes): for itemIndex in itemIndexes.sorted(by: { $0 < $1 }) { itemsInfo.insert(ItemInfo(heightState: heightState, frame: CGRect(origin: .zero, size: itemSize)), at: itemIndex) } case .deleteItems(let itemIndexes): for itemIndex in itemIndexes.sorted(by: { $1 < $0 }) { itemsInfo.remove(at: itemIndex) } case .reloadItems(let itemIndexes): if heightState == .estimated { for itemIndex in itemIndexes { itemsInfo[itemIndex].heightState = heightState } } case .moveItem(let fromIndex, let toIndex): swap(&itemsInfo[fromIndex], &itemsInfo[toIndex]) } } collectionViewWidth = sectionWidth updateItemsList() } else if collectionViewWidth != sectionWidth || ((reason == .reloadData || reason == .changeCollectionViewLayoutOrDataSource) && fixCountOfItemsList()) { collectionViewWidth = sectionWidth updateItemsList() } } override public func layoutItems(in rect: CGRect, sectionIndex: Int) -> [ItemKey] { var itemsInRect = [ItemKey]() guard numberOfItemsInSection != 0 else { return [] } if let headerInfo = headerInfo, headerInfo.intersects(with: rect) { itemsInRect.append(ItemKey(indexPath: IndexPath(item: 0, section: sectionIndex), kind: PuzzleCollectionElementKindSectionHeader, category: .supplementaryView)) } if showTopGutter && sectionInsets.top != 0 { let originY: CGFloat = headerInfo?.maxOriginY ?? 0 let topGutterFrame = CGRect(x: topGutterInsets.left, y: originY + topGutterInsets.top, width: collectionViewWidth - topGutterInsets.right - topGutterInsets.left, height: sectionInsets.top - topGutterInsets.top - topGutterInsets.bottom) if rect.intersects(topGutterFrame) { itemsInRect.append(ItemKey(indexPath: IndexPath(item: 0, section: sectionIndex), kind: PuzzleCollectionElementKindSectionTopGutter, category: .decorationView)) } } for itemIndex in 0 ..< numberOfItemsInSection { let itemInfo = itemsInfo[itemIndex] var itemFrame = itemInfo.frame switch rowAlignment { case .equalHeight: itemFrame.size.height = itemInfo.rowHeight case .alignBottom: itemFrame.origin.y += (itemInfo.rowHeight - itemFrame.height) case .alignCenter: itemFrame.origin.y += (itemInfo.rowHeight - itemFrame.height) * 0.5 default: break } if itemFrame.intersects(rect) { itemsInRect.append(ItemKey(indexPath: IndexPath(item: itemIndex, section: sectionIndex), kind: nil, category: .cell)) } else if rect.maxY < itemInfo.frame.minY { break } } if showBottomGutter && sectionInsets.bottom != 0 { let maxY: CGFloat if let footer = footerInfo { maxY = footer.originY } else if let lastItem = itemsInfo.last { maxY = lastItem.frame.minY + lastItem.rowHeight + sectionInsets.bottom } else if let header = headerInfo { maxY = header.maxOriginY + sectionInsets.bottom } else { maxY = 0 } let bottonGutterFrame = CGRect(x: bottomGutterInsets.left, y: maxY - sectionInsets.bottom + bottomGutterInsets.top, width: collectionViewWidth - bottomGutterInsets.right - bottomGutterInsets.left, height: sectionInsets.bottom - bottomGutterInsets.top - bottomGutterInsets.bottom) if rect.intersects(bottonGutterFrame) { itemsInRect.append(ItemKey(indexPath: IndexPath(item: 0, section: sectionIndex), kind: PuzzleCollectionElementKindSectionBottomGutter, category: .decorationView)) } } if let footerInfo = footerInfo, footerInfo.intersects(with: rect) { itemsInRect.append(ItemKey(indexPath: IndexPath(item: 0, section: sectionIndex), kind: PuzzleCollectionElementKindSectionFooter, category: .supplementaryView)) } return itemsInRect } override public func layoutAttributesForItem(at indexPath: IndexPath) -> PuzzleCollectionViewLayoutAttributes? { guard indexPath.item < itemsInfo.count else { return nil } let itemInfo = itemsInfo[indexPath.item] let itemAttributes = PuzzleCollectionViewLayoutAttributes(forCellWith: indexPath) var itemFrame = itemInfo.frame switch rowAlignment { case .equalHeight: itemFrame.size.height = itemInfo.rowHeight case .alignBottom: itemFrame.origin.y += (itemInfo.rowHeight - itemFrame.height) case .alignCenter: itemFrame.origin.y += (itemInfo.rowHeight - itemFrame.height) * 0.5 default: break } itemAttributes.frame = itemFrame if itemInfo.heightState != .estimated { itemAttributes.cachedSize = itemFrame.size } return itemAttributes } override public func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> PuzzleCollectionViewLayoutAttributes? { switch elementKind { case PuzzleCollectionElementKindSectionHeader: if let headerInfo = headerInfo { let itemAttributes = PuzzleCollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, with: indexPath) let frame = CGRect(x: 0, y: headerInfo.originY, width: collectionViewWidth, height: headerInfo.height) itemAttributes.frame = frame if headerInfo.heightState != .estimated { itemAttributes.cachedSize = frame.size } return itemAttributes } else { return nil } case PuzzleCollectionElementKindSectionFooter: if let footerInfo = footerInfo { let itemAttributes = PuzzleCollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, with: indexPath) let frame = CGRect(x: 0, y: footerInfo.originY, width: collectionViewWidth, height: footerInfo.height) itemAttributes.frame = frame if footerInfo.heightState != .estimated { itemAttributes.cachedSize = frame.size } return itemAttributes } else { return nil } default: return nil } } override public func layoutAttributesForDecorationView(ofKind elementKind: String, at indexPath: IndexPath) -> PuzzleCollectionViewLayoutAttributes? { if elementKind == PuzzleCollectionElementKindSectionTopGutter { if showTopGutter && sectionInsets.top != 0 { let originY: CGFloat = headerInfo?.maxOriginY ?? 0 let gutterAttributes = PuzzleCollectionViewLayoutAttributes(forDecorationViewOfKind: elementKind, with: indexPath) gutterAttributes.frame = CGRect(x: topGutterInsets.left, y: originY + topGutterInsets.top, width: collectionViewWidth - topGutterInsets.right - topGutterInsets.left, height: sectionInsets.top - topGutterInsets.top - topGutterInsets.bottom) if let gutterColor = separatorLineColor { gutterAttributes.info = [PuzzleCollectionColoredViewColorKey : gutterColor] } else if let gutterColor = parentLayout?.separatorLineColor { gutterAttributes.info = [PuzzleCollectionColoredViewColorKey : gutterColor] } gutterAttributes.zIndex = PuzzleCollectionSeparatorsViewZIndex return gutterAttributes } } else if elementKind == PuzzleCollectionElementKindSectionBottomGutter { if showBottomGutter && sectionInsets.bottom != 0 { let maxY: CGFloat if let footer = footerInfo { maxY = footer.originY } else if let lastItem = itemsInfo.last { maxY = lastItem.frame.minY + lastItem.rowHeight + sectionInsets.bottom } else if let header = headerInfo { maxY = header.maxOriginY + sectionInsets.bottom } else { maxY = 0 } let gutterAttributes = PuzzleCollectionViewLayoutAttributes(forDecorationViewOfKind: elementKind, with: indexPath) gutterAttributes.frame = CGRect(x: bottomGutterInsets.left, y: maxY - sectionInsets.bottom + bottomGutterInsets.top, width: collectionViewWidth - bottomGutterInsets.right - bottomGutterInsets.left, height: sectionInsets.bottom - bottomGutterInsets.top - bottomGutterInsets.bottom) if let gutterColor = separatorLineColor { gutterAttributes.info = [PuzzleCollectionColoredViewColorKey : gutterColor] } else if let gutterColor = parentLayout?.separatorLineColor { gutterAttributes.info = [PuzzleCollectionColoredViewColorKey : gutterColor] } gutterAttributes.zIndex = PuzzleCollectionSeparatorsViewZIndex return gutterAttributes } } return nil } override public func shouldPinHeaderSupplementaryView() -> Bool { return sectionHeaderPinToVisibleBounds } override public func shouldPinFooterSupplementaryView() -> Bool { return sectionFooterPinToVisibleBounds } //PreferredAttributes Invalidation override public func shouldCalculatePreferredLayout(for elementCategory: InvalidationElementCategory, withOriginalSize originalSize: CGSize) -> Bool { var shouldInvalidate = false switch elementCategory { case .cell(let index): return estimatedColumnType != nil && (index < numberOfItemsInSection) && itemsInfo[index].heightState == .estimated case .supplementaryView(_, let elementKind): shouldInvalidate = ( ((elementKind == PuzzleCollectionElementKindSectionHeader && headerInfo != nil && headerInfo!.heightState == .estimated) || (elementKind == PuzzleCollectionElementKindSectionFooter && footerInfo != nil && footerInfo!.heightState == .estimated)) ) default: break } return shouldInvalidate } override public func shouldInvalidate(for elementCategory: InvalidationElementCategory, forPreferredSize preferredSize: inout CGSize, withOriginalSize originalSize: CGSize) -> Bool { var shouldInvalidate = false switch elementCategory { case .cell(let index): if (estimatedColumnType != nil && (index < numberOfItemsInSection)) && preferredSize.height != originalSize.height { shouldInvalidate = (itemsInfo[index].heightState != .computed || itemsInfo[index].rowHeight < preferredSize.height) } case .supplementaryView(_, let elementKind): shouldInvalidate = ( ((elementKind == PuzzleCollectionElementKindSectionHeader && headerInfo != nil && headerInfo!.heightState != .fixed) || (elementKind == PuzzleCollectionElementKindSectionFooter && footerInfo != nil && footerInfo!.heightState != .fixed) ) && (preferredSize.height.roundToNearestHalf != originalSize.height.roundToNearestHalf) ) default: break } if shouldInvalidate { preferredSize.width = originalSize.width preferredSize.height = ceil(preferredSize.height) return true } else { return false } } override public func invalidationInfo(for elementCategory: InvalidationElementCategory, forPreferredSize preferredSize: CGSize, withOriginalSize originalSize: CGSize) -> Any? { var info: Any? = nil switch elementCategory { case .cell(let index): itemsInfo[index].frame.size.height = preferredSize.height itemsInfo[index].heightState = .computed info = index case .supplementaryView(_, let elementKind): if elementKind == PuzzleCollectionElementKindSectionHeader { headerInfo!.height = preferredSize.height headerInfo!.heightState = .computed info = kInvalidateHeaderForPreferredHeight } else if elementKind == PuzzleCollectionElementKindSectionFooter { footerInfo!.height = preferredSize.height footerInfo!.heightState = .computed } default: break } return info } //MARK: - Private properties fileprivate var itemsInfo: [ItemInfo]! fileprivate var headerInfo: HeaderFooterInfo? fileprivate var footerInfo: HeaderFooterInfo? fileprivate var numberOfColumnsInRow: Int = 1 fileprivate var itemSize: CGSize = .zero fileprivate var actualInteritemSpacing: CGFloat = 0 fileprivate var collectionViewWidth: CGFloat = 0 //MARK: - Private fileprivate func numberOfColumns(from itemSize: CGSize) -> Int { guard itemSize.width != 0 else { return 0 } let contentWidth = collectionViewWidth - (sectionInsets.left + sectionInsets.right) return Int(floor((contentWidth + minimumInteritemSpacing) / (itemSize.width + minimumInteritemSpacing))) } fileprivate func itemWidth(from numberOfColumns: Int) -> CGFloat { guard numberOfColumnsInRow != 0 else { return 0 } let contentWidth = collectionViewWidth - (sectionInsets.left + sectionInsets.right) var itemWidth = (contentWidth - (minimumInteritemSpacing * (CGFloat(numberOfColumns - 1)))) itemWidth /= CGFloat(numberOfColumns) return floor(itemWidth * 2) * 0.5 //Floor to nearest half } private func prepareItemsFromScratch() { updateItemSizeAndNumberOfColumns() let heightState: ItemHeightState = (estimatedColumnType != nil) ? .estimated : .fixed itemsInfo = [ItemInfo](repeating: ItemInfo(heightState: heightState, frame: CGRect(origin: .zero, size: itemSize)), count: numberOfItemsInSection) guard numberOfColumnsInRow != 0 else { assert(false, "Number of columns can't be 0") return } switch headerHeight { case .fixed(let height): headerInfo = HeaderFooterInfo(heightState: .fixed, originY: 0, height: height) case .estimated(let height): headerInfo = HeaderFooterInfo(heightState: .estimated, originY: 0, height: height) default: break } var lastOriginY: CGFloat = (headerInfo?.maxOriginY ?? 0) + sectionInsets.top if numberOfItemsInSection != 0 { if numberOfColumnsInRow == 1 { let originX = (collectionViewWidth - itemSize.width) * 0.5 for index in 0..<numberOfItemsInSection { itemsInfo[index] = ItemInfo(heightState: heightState, frame: CGRect(origin: CGPoint(x: originX, y: lastOriginY), size: itemSize)) lastOriginY += itemSize.height + minimumLineSpacing } } else { var startItemIndex = 0 while startItemIndex < numberOfItemsInSection { let endItemIndex = min(startItemIndex + numberOfColumnsInRow - 1, numberOfItemsInSection - 1) var lastOriginX = sectionInsets.left for index in startItemIndex...endItemIndex { itemsInfo[index] = ItemInfo(heightState: heightState, frame: CGRect(origin: CGPoint(x: lastOriginX, y: lastOriginY), size: itemSize)) lastOriginX += itemSize.width + actualInteritemSpacing } startItemIndex = endItemIndex + 1 lastOriginY += itemSize.height + minimumLineSpacing } } lastOriginY -= minimumLineSpacing } lastOriginY += sectionInsets.bottom switch footerHeight { case .fixed(let height): footerInfo = HeaderFooterInfo(heightState: .fixed, originY: lastOriginY, height: height) case .estimated(let height): footerInfo = HeaderFooterInfo(heightState: .estimated, originY: lastOriginY, height: height) default: break } } //MARK: - Updates private func updateItemSizeAndNumberOfColumns() { assert(estimatedColumnType != nil || columnType != nil, "'estimatedColumnType' and 'columnType' can't be both nil") let type = (estimatedColumnType ?? columnType)! switch type { case .itemSize(let itemSize): self.itemSize = itemSize self.numberOfColumnsInRow = numberOfColumns(from: itemSize) case .quickDynamicItemSize(let closure): self.itemSize = closure(self, collectionViewWidth) self.numberOfColumnsInRow = numberOfColumns(from: itemSize) case .numberOfColumns(let numberOfColumns, let height): self.itemSize = CGSize(width: 0, height: height) self.numberOfColumnsInRow = Int(numberOfColumns) self.itemSize.width = itemWidth(from: self.numberOfColumnsInRow) case .quickDynamicNumberOfColumns(let closure): let res = closure(self, collectionViewWidth) self.itemSize = CGSize(width: 0, height: res.itemHeight) self.numberOfColumnsInRow = Int(res.numberOfColumns) self.itemSize.width = itemWidth(from: self.numberOfColumnsInRow) case .numberOfColumnsWithWidthDependency(let numberOfColumns, let heightWidthRatio, let heightConstant): self.numberOfColumnsInRow = Int(numberOfColumns) self.itemSize.width = itemWidth(from: self.numberOfColumnsInRow) self.itemSize.height = (self.itemSize.width * heightWidthRatio) + heightConstant case .dynamicNumberOfColumns(_): break case .dynamicItemSize(_): break } updateActualInteritemSpacing() } fileprivate func updateActualInteritemSpacing() { guard numberOfColumnsInRow != 0 else { actualInteritemSpacing = 0 return } guard itemSize.width != 0 else { actualInteritemSpacing = 0 return } let contentWidth = collectionViewWidth - (sectionInsets.left + sectionInsets.right) actualInteritemSpacing = floor((contentWidth - (CGFloat(numberOfColumnsInRow) * (itemSize.width))) / CGFloat(numberOfColumnsInRow-1) * 2) * 0.5 } fileprivate func updateItemsOriginXForMultipleColumns(updateItemWidth: Bool) { var startItemIndex = 0 var rowIndex = 0 while startItemIndex < numberOfItemsInSection { let endItemIndex = min(startItemIndex + numberOfColumnsInRow - 1, numberOfItemsInSection - 1) var lastOriginX = sectionInsets.left for index in startItemIndex...endItemIndex { itemsInfo[index].frame.origin.x = lastOriginX if updateItemWidth { itemsInfo[index].frame.size.width = itemSize.width if itemsInfo[index].heightState != .fixed { itemsInfo[index].heightState = .estimated } } lastOriginX += itemSize.width + actualInteritemSpacing } startItemIndex = endItemIndex + 1 rowIndex += 1 } } fileprivate func updateItemsWidthAndOriginXForSingleColumn() { let originX = (collectionViewWidth - itemSize.width) * 0.5 for index in 0..<numberOfItemsInSection { itemsInfo[index].frame.origin.x = originX itemsInfo[index].frame.size.width = itemSize.width if itemsInfo[index].heightState != .fixed { itemsInfo[index].heightState = .estimated } } } fileprivate func updateItemsOriginY(forceUpdateOrigin: Bool = false, updateItemHeight: Bool = false, updateHeaderHeight: Bool = false) { var didUpdateHeader = false if updateHeaderHeight { let oldHeight = (headerInfo?.maxOriginY ?? 0) updateHeader() didUpdateHeader = (headerInfo?.maxOriginY ?? 0) != oldHeight } guard forceUpdateOrigin || didUpdateHeader || updateItemHeight else { return } if numberOfColumnsInRow == 1 { updateItemsOriginYForSingleColumn(forceUpdateOrigin: forceUpdateOrigin, updateItemHeight: updateItemHeight) } else { updateItemsOriginYForMultipleColumns(forceUpdateOrigin: forceUpdateOrigin, updateItemHeight: updateItemHeight) } } private func updateItemsOriginYForMultipleColumns(forceUpdateOrigin: Bool = false, updateItemHeight: Bool = false) { guard let _ = itemsInfo else { return } var lastOriginY: CGFloat = (headerInfo?.maxOriginY ?? 0) + sectionInsets.top var startItemIndex = 0 let estiamted: Bool = (estimatedColumnType != nil) if numberOfItemsInSection != 0 { while startItemIndex < numberOfItemsInSection { let endItemIndex = min(startItemIndex + numberOfColumnsInRow - 1, numberOfItemsInSection - 1) var lastOriginX = sectionInsets.left var maxHeight: CGFloat = 0 for index in startItemIndex...endItemIndex { if updateItemHeight { if estiamted { if itemsInfo[index].heightState != .computed { itemsInfo[index].heightState = .estimated itemsInfo[index].frame.size.height = itemSize.height } } else { itemsInfo[index].frame.size.height = itemSize.height itemsInfo[index].heightState = .fixed } } maxHeight = max(maxHeight, itemsInfo[index].frame.height) } for index in startItemIndex...endItemIndex { itemsInfo[index].frame.origin = CGPoint(x: lastOriginX, y: lastOriginY) itemsInfo[index].rowHeight = maxHeight lastOriginX += itemSize.width + actualInteritemSpacing } startItemIndex = endItemIndex + 1 lastOriginY += maxHeight + minimumLineSpacing } lastOriginY -= minimumLineSpacing } lastOriginY += sectionInsets.bottom updateFooter(originY: lastOriginY) } private func updateItemsOriginYForSingleColumn(forceUpdateOrigin: Bool = false, updateItemHeight: Bool = false) { guard let _ = itemsInfo else { return } let originX = (collectionViewWidth - itemSize.width) * 0.5 var lastOriginY: CGFloat = (headerInfo?.maxOriginY ?? 0) + sectionInsets.top let estiamted: Bool = (estimatedColumnType != nil) if numberOfItemsInSection != 0 { for index in 0..<numberOfItemsInSection { itemsInfo[index].frame.origin = CGPoint(x: originX, y: lastOriginY) itemsInfo[index].rowHeight = itemsInfo[index].frame.height if updateItemHeight { if estiamted { if itemsInfo[index].heightState != .computed { itemsInfo[index].heightState = .estimated itemsInfo[index].frame.size.height = itemSize.height } } else { itemsInfo[index].frame.size.height = itemSize.height itemsInfo[index].heightState = .fixed } } lastOriginY += itemsInfo[index].frame.height + minimumLineSpacing } lastOriginY -= minimumLineSpacing } lastOriginY += sectionInsets.bottom updateFooter(originY: lastOriginY) } private func updateItems(fromIndex index: Int) { if numberOfColumnsInRow == 1 { itemsInfo[index].rowHeight = itemsInfo[index].frame.height var lastOriginY: CGFloat = itemsInfo[index].frame.maxY if index + 1 != numberOfItemsInSection { lastOriginY += minimumLineSpacing for index in index ..< numberOfItemsInSection { itemsInfo[index].frame.origin.y = lastOriginY lastOriginY += itemsInfo[index].rowHeight + minimumLineSpacing } } lastOriginY += sectionInsets.bottom updateFooter(originY: lastOriginY) } else { var startItemIndex = index - (index % numberOfColumnsInRow) var lastOriginY: CGFloat = itemsInfo[index].frame.minY if startItemIndex < numberOfItemsInSection { while startItemIndex < numberOfItemsInSection { let endItemIndex = min(startItemIndex + numberOfColumnsInRow - 1, numberOfItemsInSection - 1) var maxHeight: CGFloat = 0 for index in startItemIndex...endItemIndex { maxHeight = max(maxHeight, itemsInfo[index].frame.height) } for index in startItemIndex...endItemIndex { itemsInfo[index].frame.origin.y = lastOriginY itemsInfo[index].rowHeight = maxHeight } lastOriginY += maxHeight + minimumLineSpacing startItemIndex = endItemIndex + 1 } lastOriginY -= minimumLineSpacing } else { lastOriginY = itemsInfo[index].frame.maxY } lastOriginY += sectionInsets.bottom updateFooter(originY: lastOriginY) } } private func updateHeader() { switch headerHeight { case .none: if let _ = headerInfo { headerInfo = nil } case .fixed(let height): if let _ = headerInfo { headerInfo!.height = height headerInfo!.heightState = .fixed } else { headerInfo = HeaderFooterInfo(heightState: .fixed, originY: 0, height: height) } case .estimated(let height): if let _ = headerInfo { if headerInfo!.heightState == .estimated { headerInfo!.height = height } } else { headerInfo = HeaderFooterInfo(heightState: .estimated, originY: 0, height: height) } } } private func updateFooter(originY: CGFloat? = nil) { var lastOriginY: CGFloat! = originY if lastOriginY == nil { if let lastItem = itemsInfo.last { lastOriginY = lastItem.frame.origin.y + lastItem.rowHeight + sectionInsets.bottom } else if let header = headerInfo { lastOriginY = header.maxOriginY + sectionInsets.top + sectionInsets.bottom } else { lastOriginY = sectionInsets.top + sectionInsets.bottom } } // Update section footer if needed switch footerHeight { case .none: footerInfo = nil case .fixed(let height): if let _ = footerInfo { footerInfo!.originY = lastOriginY footerInfo!.height = height footerInfo!.heightState = .fixed } else { footerInfo = HeaderFooterInfo(heightState: .fixed, originY: lastOriginY, height: height) } case .estimated(let height): if let _ = footerInfo { footerInfo!.originY = lastOriginY if footerInfo!.heightState == .estimated { footerInfo!.height = height } } else { footerInfo = HeaderFooterInfo(heightState: .estimated, originY: lastOriginY, height: height) } } } /* 1. Section insets or minimum inter-item spacing changed & based on item size: 1.1. Compute number of column 1.2. Number of columns did change: 1.2.1. Fix origin X & origin Y 1.2.2. Fix row height 1.2.3. Fix row index 1.2.4. fix item index at row 1.3. Number of columns didn’t change: 1.3.1 Number of columns is 1: Do nothing. 1.3.2 Number of columns is bigger than 1: Update origin X */ private func itemSizeBased_fixForRowInfoChange() { let updatedNumberOfColumns = numberOfColumns(from: self.itemSize) updateActualInteritemSpacing() guard numberOfItemsInSection != 0 else { self.numberOfColumnsInRow = updatedNumberOfColumns return } if updatedNumberOfColumns != self.numberOfColumnsInRow { self.numberOfColumnsInRow = updatedNumberOfColumns updateItemsOriginY(forceUpdateOrigin: true) } else { if numberOfColumnsInRow != 1 { updateItemsOriginXForMultipleColumns(updateItemWidth: false) } } } /* 1. Section insets or minimum inter-item spacing changed & based on number of columns: 1.1. Compute item width 1.2. Compute actual interitem spacing 1.3. Update origin X and item width 1.4. If height state isn’t fixed. Set it as estimated. */ private func columnsNumberBased_fixForRowInfoChange() { self.itemSize.width = itemWidth(from: self.numberOfColumnsInRow) updateActualInteritemSpacing() if numberOfColumnsInRow == 1 { updateItemsWidthAndOriginXForSingleColumn() } else { updateItemsOriginXForMultipleColumns(updateItemWidth: true) } } private func fixCountOfItemsList() -> Bool { guard itemsInfo != nil else { prepareItemsFromScratch() return false } let heightState: ItemHeightState = (estimatedColumnType != nil) ? .estimated : .fixed let updatedItemsNumber = numberOfItemsInSection let oldItemsNumber = itemsInfo.count if oldItemsNumber > updatedItemsNumber { itemsInfo.removeSubrange(updatedItemsNumber ..< oldItemsNumber) return true } else if oldItemsNumber < updatedItemsNumber { itemsInfo! += [ItemInfo](repeating: ItemInfo(heightState: heightState, frame: CGRect(origin: .zero, size: itemSize)), count: updatedItemsNumber-oldItemsNumber) return true } else { return false } } private func updateItemsList() { let oldItemSize = itemSize updateItemSizeAndNumberOfColumns() guard numberOfColumnsInRow != 0 else { assert(false, "Number of columns can't be 0") return } let didChangeItemWidth = oldItemSize.width != itemSize.width let didChangeItemHeight = oldItemSize.height != itemSize.height updateHeader() var lastOriginY = (headerInfo?.maxOriginY ?? 0) + sectionInsets.top if numberOfItemsInSection != 0 { if numberOfColumnsInRow == 1 { let originX = (collectionViewWidth - itemSize.width) * 0.5 for index in 0..<numberOfItemsInSection { itemsInfo[index].frame.origin = CGPoint(x: originX, y: lastOriginY) itemsInfo[index].frame.size.width = itemSize.width if didChangeItemHeight && itemsInfo[index].heightState != .computed { itemsInfo[index].frame.size.height = itemSize.height } if didChangeItemWidth && itemsInfo[index].heightState == .computed { itemsInfo[index].heightState = .estimated } lastOriginY += itemsInfo[index].frame.height + minimumLineSpacing } } else { var startItemIndex = 0 while startItemIndex < numberOfItemsInSection { let endItemIndex = min(startItemIndex + numberOfColumnsInRow - 1, numberOfItemsInSection - 1) var lastOriginX = sectionInsets.left var maxHeight: CGFloat = 0 for index in startItemIndex...endItemIndex { if didChangeItemHeight && itemsInfo[index].heightState != .computed { itemsInfo[index].frame.size.height = itemSize.height } if didChangeItemWidth && itemsInfo[index].heightState == .computed { itemsInfo[index].heightState = .estimated } maxHeight = max(maxHeight, itemsInfo[index].frame.height) } for index in startItemIndex...endItemIndex { itemsInfo[index].frame.origin = CGPoint(x: lastOriginX, y: lastOriginY) itemsInfo[index].frame.size.width = itemSize.width itemsInfo[index].rowHeight = maxHeight lastOriginX += itemSize.width + actualInteritemSpacing } startItemIndex = endItemIndex + 1 lastOriginY += maxHeight + minimumLineSpacing } } lastOriginY -= minimumLineSpacing } lastOriginY += sectionInsets.bottom updateFooter(originY: lastOriginY) } } //MARK: - Utils private struct ItemInfo: CustomStringConvertible { var heightState: ItemHeightState var frame: CGRect var needInvalidation: Bool = false var rowHeight: CGFloat = 0 init(heightState: ItemHeightState, frame: CGRect) { self.heightState = heightState self.frame = frame self.rowHeight = frame.height } var description: String { return "Item Info: State:\(heightState) ; Frame: \(frame)" } } private let kInvalidateForResetLayout = "reset" private let kInvalidateForRowInfoChange = "RowInfo" private let kInvalidateForColumnTypeChange = "ColumnType" private let kInvalidateForMinimumLineSpacingChange = "MinimumLineSpacing" private let kInvalidateForHeaderEstimatedHeightChange = "HeaderEstimatedHeight" private let kInvalidateForFooterEstimatedHeightChange = "FooterEstimatedHeight" private let kInvalidateHeaderForPreferredHeight = "PreferredHeaderHeight" private let kInvalidateForRowAlignmentChange = "RowAlignment" extension CGFloat { fileprivate var roundToNearestHalf: CGFloat { return floor(self * 2) / 2 } }
mit
0d06189c80e8af802fb359cd7dcb331a
43.605203
350
0.605122
5.540677
false
false
false
false
eTilbudsavis/native-ios-eta-sdk
Sources/PagedPublication/PagedPublicationView.swift
1
27321
// // ┌────┬─┐ ┌─────┐ // │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐ // ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │ // └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘ // └─┘ // // Copyright (c) 2018 ShopGun. All rights reserved. import UIKit import Verso /// The object that does the fetching of the publication's public protocol PagedPublicationViewDataLoader { typealias PublicationLoadedHandler = ((Result<PagedPublicationView.PublicationModel, Error>) -> Void) typealias PagesLoadedHandler = ((Result<[PagedPublicationView.PageModel], Error>) -> Void) typealias HotspotsLoadedHandler = ((Result<[PagedPublicationView.HotspotModel], Error>) -> Void) func startLoading(publicationId: PagedPublicationView.PublicationId, publicationLoaded: @escaping PublicationLoadedHandler, pagesLoaded: @escaping PagesLoadedHandler, hotspotsLoaded: @escaping HotspotsLoadedHandler) func cancelLoading() } public protocol PagedPublicationViewDelegate: class { // MARK: Page Change events func pageIndexesChanged(current currentPageIndexes: IndexSet, previous oldPageIndexes: IndexSet, in pagedPublicationView: PagedPublicationView) func pageIndexesFinishedChanging(current currentPageIndexes: IndexSet, previous oldPageIndexes: IndexSet, in pagedPublicationView: PagedPublicationView) func didFinishLoadingPageImage(imageURL: URL, pageIndex: Int, in pagedPublicationView: PagedPublicationView) // MARK: Hotspot events func didTap(pageIndex: Int, locationInPage: CGPoint, hittingHotspots: [PagedPublicationView.HotspotModel], in pagedPublicationView: PagedPublicationView) func didLongPress(pageIndex: Int, locationInPage: CGPoint, hittingHotspots: [PagedPublicationView.HotspotModel], in pagedPublicationView: PagedPublicationView) func didDoubleTap(pageIndex: Int, locationInPage: CGPoint, hittingHotspots: [PagedPublicationView.HotspotModel], in pagedPublicationView: PagedPublicationView) // MARK: Outro events func outroDidAppear(_ outroView: PagedPublicationView.OutroView, in pagedPublicationView: PagedPublicationView) func outroDidDisappear(_ outroView: PagedPublicationView.OutroView, in pagedPublicationView: PagedPublicationView) // MARK: Loading events func didStartReloading(in pagedPublicationView: PagedPublicationView) func didLoad(publication publicationModel: PagedPublicationView.PublicationModel, in pagedPublicationView: PagedPublicationView) func didLoad(pages pageModels: [PagedPublicationView.PageModel], in pagedPublicationView: PagedPublicationView) func didLoad(hotspots hotspotModels: [PagedPublicationView.HotspotModel], in pagedPublicationView: PagedPublicationView) } public protocol PagedPublicationViewDataSource: class { func outroViewProperties(for pagedPublicationView: PagedPublicationView) -> PagedPublicationView.OutroViewProperties? func configure(outroView: PagedPublicationView.OutroView, for pagedPublicationView: PagedPublicationView) func textForPageNumberLabel(pageIndexes: IndexSet, pageCount: Int, for pagedPublicationView: PagedPublicationView) -> String? } // MARK: - public class PagedPublicationView: UIView { public typealias OutroView = VersoPageView public typealias OutroViewProperties = (viewClass: OutroView.Type, width: CGFloat, maxZoom: CGFloat) public typealias PublicationId = CoreAPI.PagedPublication.Identifier public typealias PublicationModel = CoreAPI.PagedPublication public typealias PageModel = CoreAPI.PagedPublication.Page public typealias HotspotModel = CoreAPI.PagedPublication.Hotspot public typealias CoreProperties = (pageCount: Int?, bgColor: UIColor, aspectRatio: Double) /** This will configure the `CoreAPI` and `EventsTracker` components using the `Settings` from the default SettingsFile. If you dont call this (or at least `CoreAPI.configure()`) before you start using the `PagedPublicationView`, there will be a `fatalError`. - parameter sendEvents: If set to `true` (the default) it will configure the `EventsTracker` to send anonymous publication opened & page-read events. You must make sure that the default Settings file has all the properties needed for tracking events. */ public static func configure(sendEvents: Bool = true) { CoreAPI.configure() if sendEvents { EventsTracker.configure() } } public weak var delegate: PagedPublicationViewDelegate? public weak var dataSource: PagedPublicationViewDataSource? fileprivate var postReloadPageIndex: Int = 0 public func reload(publicationId: PublicationId, initialPageIndex: Int = 0, initialProperties: CoreProperties = (nil, .white, 1.0)) { DispatchQueue.main.async { [weak self] in guard let s = self else { return } s.coreProperties = initialProperties s.publicationState = .loading(publicationId) s.pagesState = .loading(publicationId) s.hotspotsState = .loading(publicationId) // change what we are showing based on the states s.updateCurrentViewState(initialPageIndex: initialPageIndex) // TODO: what if reload different after starting to load? need to handle id change s.postReloadPageIndex = initialPageIndex s.delegate?.didStartReloading(in: s) // do the loading s.dataLoader.cancelLoading() s.dataLoader.startLoading(publicationId: publicationId, publicationLoaded: { [weak self] in self?.publicationDidLoad(forId: publicationId, result: $0) }, pagesLoaded: { [weak self] in self?.pagesDidLoad(forId: publicationId, result: $0) }, hotspotsLoaded: { [weak self] in self?.hotspotsDidLoad(forId: publicationId, result: $0) }) } } public func jump(toPageIndex pageIndex: Int, animated: Bool) { switch self.currentViewState { case .contents: contentsView.versoView.jump(toPageIndex: pageIndex, animated: animated) case .loading, .initial, .error: postReloadPageIndex = pageIndex } } /// Tell the page publication that it is now visible again. /// (eg. when a view that was placed over the top of this view is removed, and the content becomes visible again). /// This will restart event collection. You MUST remember to call this if you previously called `didEnterBackground`, otherwise /// the PagePublicationView will not function correctly. public func didEnterForeground() { // start listening for the app going into the background NotificationCenter.default.addObserver(self, selector: #selector(willResignActiveNotification), name: UIApplication.willResignActiveNotification, object: nil) lifecycleEventTracker?.didAppear() } /// Tell the page publication that it is no longer visible. /// (eg. a view has been placed over the top of the PagedPublicationView, so the content is no longer visible) /// This will pause event collection, until `didEnterForeground` is called again. public func didEnterBackground() { // stop listening for going into the background NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil) lifecycleEventTracker?.didDisappear() } // MARK: - UIView Lifecycle public override init(frame: CGRect) { super.init(frame: frame) addSubview(self.contentsView) self.contentsView.alpha = 0 self.contentsView.versoView.delegate = self self.contentsView.versoView.dataSource = self self.contentsView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ contentsView.leadingAnchor.constraint(equalTo: leadingAnchor), contentsView.trailingAnchor.constraint(equalTo: trailingAnchor), contentsView.topAnchor.constraint(equalTo: topAnchor), contentsView.bottomAnchor.constraint(equalTo: bottomAnchor) ]) addSubview(self.loadingView) self.loadingView.alpha = 0 loadingView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ loadingView.centerXAnchor.constraint(equalTo: layoutMarginsGuide.centerXAnchor), loadingView.centerYAnchor.constraint(equalTo: layoutMarginsGuide.centerYAnchor) ]) addSubview(self.errorView) self.errorView.alpha = 0 self.errorView.retryButton.addTarget(self, action: #selector(didTapErrorRetryButton), for: .touchUpInside) errorView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ errorView.centerXAnchor.constraint(equalTo: layoutMarginsGuide.centerXAnchor), errorView.centerYAnchor.constraint(equalTo: layoutMarginsGuide.centerYAnchor), { let con = errorView.widthAnchor.constraint(lessThanOrEqualTo: layoutMarginsGuide.widthAnchor) con.priority = .defaultHigh return con }(), { let con = errorView.heightAnchor.constraint(lessThanOrEqualTo: layoutMarginsGuide.heightAnchor) con.priority = .defaultHigh return con }() ]) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil) } override public var backgroundColor: UIColor? { set { super.backgroundColor = newValue var whiteComponent: CGFloat = 1.0 newValue?.getWhite(&whiteComponent, alpha: nil) self.isBackgroundDark = whiteComponent <= 0.6 } get { return super.backgroundColor } } var isBackgroundDark: Bool = false // MARK: - Internal enum LoadingState<Id, Model> { case unloaded case loading(Id) case loaded(Id, Model) case error(Id, Error) } enum ViewState { case initial case loading(bgColor: UIColor) case contents(coreProperties: CoreProperties, additionalLoading: Bool) case error(bgColor: UIColor, error: Error) init(coreProperties: CoreProperties, publicationState: LoadingState<PublicationId, PublicationModel>, pagesState: LoadingState<PublicationId, [PageModel]>, hotspotsState: LoadingState<PublicationId, [IndexSet: [HotspotModel]]>) { switch (publicationState, pagesState, hotspotsState) { case (.error(_, let error), _, _), (_, .error(_, let error), _): // the publication failed to load, or the pages failed. // either way, it's an error, so show an error (preferring the publication error) self = .error(bgColor: coreProperties.bgColor, error: error) case (_, _, _) where (coreProperties.pageCount ?? 0) == 0: // we dont have a pageCount, so show spinner (even if pages or hotspots have loaded) self = .loading(bgColor: coreProperties.bgColor) case (_, _, .loading), (_, .loading, _), (.loading, _, _): // we have a page count, but still loading publication or hotpots or pages, so show the contents with a spinner self = .contents(coreProperties: coreProperties, additionalLoading: true) case (.loaded, _, _): // publication is loaded (pages & hotspots loaded or error) self = .contents(coreProperties: coreProperties, additionalLoading: false) default: self = .initial } } } public internal(set) var coreProperties: CoreProperties = (nil, .white, 1.0) var publicationState: LoadingState<PublicationId, PublicationModel> = .unloaded var pagesState: LoadingState<PublicationId, [PageModel]> = .unloaded var hotspotsState: LoadingState<PublicationId, [IndexSet: [HotspotModel]]> = .unloaded var currentViewState: ViewState = .initial public var dataLoader: PagedPublicationViewDataLoader = PagedPublicationView.CoreAPILoader() public var imageLoader: PagedPublicationViewImageLoader? = KingfisherImageLoader() public var eventHandler: PagedPublicationViewEventHandler? = PagedPublicationView.EventsHandler() /// The pan gesture used to change the pages. public var panGestureRecognizer: UIPanGestureRecognizer { return contentsView.versoView.panGestureRecognizer } /// This will return the OutroView (provided by the delegate) only after it has been configured. /// It is configured once the user has scrolled within a certain distance of the outro page (currently 10 pages). public var outroView: OutroView? { guard let outroIndex = outroPageIndex else { return nil } return contentsView.versoView.getPageViewIfLoaded(outroIndex) } public var isOutroPageVisible: Bool { return isOutroPage(inPageIndexes: contentsView.versoView.visiblePageIndexes) } public var pageCount: Int { return coreProperties.pageCount ?? 0 } /// The page indexes of the spread that was centered when scrolling animations last ended public var currentPageIndexes: IndexSet { return self.contentsView.versoView.currentPageIndexes } /// The publication Id that is being loaded, has been loaded, or failed to load public var publicationId: PublicationId? { switch publicationState { case .unloaded: return nil case .loading(let id), .loaded(let id, _), .error(let id, _): return id } } /// The loaded Publication Model public var publicationModel: PublicationModel? { guard case .loaded(_, let model) = self.publicationState else { return nil } return model } public func hotspotModels(onPageIndexes pageIndexSet: IndexSet) -> [HotspotModel] { guard case .loaded(_, let hotspotModelsByPage) = self.hotspotsState else { return [] } return hotspotModelsByPage.reduce(into: [], { if $1.key.contains(where: pageIndexSet.contains) { $0 += $1.value } }) } public var pageModels: [PageModel]? { guard case .loaded(_, let models) = self.pagesState else { return nil } return models } /// Returns the pageview for the pageIndex, or nil if it hasnt been loaded yet public func pageViewIfLoaded(atPageIndex pageIndex: Int) -> UIView? { return self.contentsView.versoView.getPageViewIfLoaded(pageIndex) } let contentsView = PagedPublicationView.ContentsView() let loadingView = PagedPublicationView.LoadingView() let errorView = PagedPublicationView.ErrorView() let hotspotOverlayView = HotspotOverlayView() lazy var outroOutsideTapGesture: UITapGestureRecognizer = { [weak self] in let tap = UITapGestureRecognizer(target: self, action: #selector(didTapOutsideOutro)) tap.cancelsTouchesInView = false self?.addGestureRecognizer(tap) return tap }() var lifecycleEventTracker: PagedPublicationView.LifecycleEventTracker? // MARK: - Data Loading private func publicationDidLoad(forId publicationId: PublicationId, result: Result<PublicationModel, Error>) { switch result { case .success(let publicationModel): self.publicationState = .loaded(publicationId, publicationModel) // update coreProperties using the publication self.coreProperties = (pageCount: publicationModel.pageCount, bgColor: publicationModel.branding.color ?? self.coreProperties.bgColor, aspectRatio: publicationModel.aspectRatio) // successful reload, event handler can now call opened & didAppear (if new publication, or we havnt called it yet) if lifecycleEventTracker?.publicationId != publicationModel.id, let eventHandler = self.eventHandler { lifecycleEventTracker = PagedPublicationView.LifecycleEventTracker(publicationId: publicationModel.id, eventHandler: eventHandler) lifecycleEventTracker?.opened() lifecycleEventTracker?.didAppear() let loadedIndexes = self.currentPageIndexes.filter { (self.contentsView.versoView.getPageViewIfLoaded($0) as? PagedPublicationView.PageView)?.isViewImageLoaded ?? false } lifecycleEventTracker?.spreadDidAppear( pageIndexes: currentPageIndexes, loadedIndexes: IndexSet(loadedIndexes)) } delegate?.didLoad(publication: publicationModel, in: self) case .failure(let error): self.publicationState = .error(publicationId, error) } self.updateCurrentViewState(initialPageIndex: self.postReloadPageIndex) } private func pagesDidLoad(forId publicationId: PublicationId, result: Result<[PageModel], Error>) { switch result { case .success(let pageModels): // generate page view states based on the pageModels self.pagesState = .loaded(publicationId, pageModels) delegate?.didLoad(pages: pageModels, in: self) case .failure(let error): self.pagesState = .error(publicationId, error) } self.updateCurrentViewState(initialPageIndex: self.postReloadPageIndex) } private func hotspotsDidLoad(forId publicationId: PublicationId, result: Result<[HotspotModel], Error>) { switch result { case .success(let hotspotModels): // key hotspots by their pageLocations let hotspotsByPage: [IndexSet: [HotspotModel]] = hotspotModels.reduce(into: [:], { let pageKey = IndexSet($1.pageLocations.keys) $0[pageKey] = $0[pageKey, default: []] + [$1] }) self.hotspotsState = .loaded(publicationId, hotspotsByPage) self.delegate?.didLoad(hotspots: hotspotModels, in: self) case .failure(let error): self.hotspotsState = .error(publicationId, error) } self.updateCurrentViewState(initialPageIndex: self.postReloadPageIndex) } // MARK: View updating // given the loading states (and coreProperties, generate the correct viewState private func updateCurrentViewState(initialPageIndex: Int?) { let oldViewState = self.currentViewState // Based on the pub/pages/hotspots states, return the state of the view currentViewState = ViewState(coreProperties: self.coreProperties, publicationState: self.publicationState, pagesState: self.pagesState, hotspotsState: self.hotspotsState) // change what views are visible (and update them) based on the viewState switch self.currentViewState { case .initial: self.loadingView.alpha = 0 self.contentsView.alpha = 0 self.errorView.alpha = 0 self.backgroundColor = .white case let .loading(bgColor): self.loadingView.alpha = 1 self.contentsView.alpha = 0 self.errorView.alpha = 0 self.backgroundColor = bgColor //TODO: change loading foreground color case let .contents(coreProperties, additionalLoading): self.loadingView.alpha = 0 self.contentsView.alpha = 1 self.errorView.alpha = 0 self.backgroundColor = coreProperties.bgColor updateContentsViewLabels(pageIndexes: currentPageIndexes, additionalLoading: additionalLoading) case let .error(bgColor, error): self.loadingView.alpha = 0 self.contentsView.alpha = 0 self.errorView.alpha = 1 self.backgroundColor = bgColor self.errorView.tintColor = self.isBackgroundDark ? UIColor.white : UIColor(white: 0, alpha: 0.7) self.errorView.update(for: error) } // reload the verso based on the change to the pageCount switch (currentViewState, oldViewState) { case let (.contents(coreProperties, _), .contents(oldProperties, _)) where oldProperties.pageCount == coreProperties.pageCount: self.contentsView.versoView.reconfigureVisiblePages() self.contentsView.versoView.reconfigureSpreadOverlay() default: self.contentsView.versoView.reloadPages(targetPageIndex: initialPageIndex) } } // refresh the properties of the contentsView based on the current state func updateContentsViewLabels(pageIndexes: IndexSet, additionalLoading: Bool) { var properties = contentsView.properties if let pageCount = coreProperties.pageCount, self.isOutroPage(inPageIndexes: pageIndexes) == false, self.isOutroPageVisible == false { properties.pageLabelString = dataSourceWithDefaults.textForPageNumberLabel(pageIndexes: pageIndexes, pageCount: pageCount, for: self) } else { properties.pageLabelString = nil } properties.showAdditionalLoading = additionalLoading properties.isBackgroundBlack = self.isBackgroundDark contentsView.update(properties: properties) } // MARK: Derived Values var dataSourceWithDefaults: PagedPublicationViewDataSource { return self.dataSource ?? self } var outroViewProperties: OutroViewProperties? { return dataSourceWithDefaults.outroViewProperties(for: self) } var outroPageIndex: Int? { return outroViewProperties != nil && pageCount > 0 ? pageCount : nil } func isOutroPage(inPageIndexes pageIndexSet: IndexSet) -> Bool { guard let outroIndex = self.outroPageIndex else { return false } return pageIndexSet.contains(outroIndex) } // Get the properties for a page, based on the pages state func pageViewProperties(forPageIndex pageIndex: Int) -> PageView.Properties { guard case .loaded(_, let pageModels) = self.pagesState, pageModels.indices.contains(pageIndex) else { // return a 'loading' page view return .init(pageTitle: String(pageIndex+1), isBackgroundDark: self.isBackgroundDark, aspectRatio: CGFloat(self.coreProperties.aspectRatio), images: nil) } let pageModel = pageModels[pageIndex] return .init(pageTitle: pageModel.title ?? String(pageModel.index + 1), isBackgroundDark: self.isBackgroundDark, aspectRatio: CGFloat(pageModel.aspectRatio), images: pageModel.images) } // MARK: - @objc fileprivate func didTapOutsideOutro(_ tap: UITapGestureRecognizer) { guard self.isOutroPageVisible, let outroView = self.outroView else { return } let location = tap.location(in: outroView) if outroView.bounds.contains(location) == false { jump(toPageIndex: pageCount-1, animated: true) } } @objc fileprivate func didTapErrorRetryButton(_ btn: UIButton) { guard let pubId = self.publicationId else { return } self.reload(publicationId: pubId, initialPageIndex: self.postReloadPageIndex, initialProperties: self.coreProperties) } @objc fileprivate func willResignActiveNotification(_ notification: Notification) { // once in the background, listen for coming back to the foreground again NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActiveNotification), name: UIApplication.didBecomeActiveNotification, object: nil) didEnterBackground() } @objc fileprivate func didBecomeActiveNotification(_ notification: Notification) { // once in the foreground, stop listen for that again NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil) didEnterForeground() } } // MARK: - private typealias PageViewDelegate = PagedPublicationView extension PageViewDelegate: PagedPublicationPageViewDelegate { func didFinishLoading(viewImage imageURL: URL, fromCache: Bool, in pageView: PagedPublicationView.PageView) { let pageIndex = pageView.pageIndex // tell the spread that the image loaded. // Will be ignored if page isnt part of the spread lifecycleEventTracker?.pageDidLoad(pageIndex: pageIndex) delegate?.didFinishLoadingPageImage(imageURL: imageURL, pageIndex: pageIndex, in: self) } } // MARK: - private typealias HotspotDelegate = PagedPublicationView extension HotspotDelegate: HotspotOverlayViewDelegate { func didTapHotspot(overlay: PagedPublicationView.HotspotOverlayView, hotspots: [HotspotModel], hotspotRects: [CGRect], locationInOverlay: CGPoint, pageIndex: Int, locationInPage: CGPoint) { delegate?.didTap(pageIndex: pageIndex, locationInPage: locationInPage, hittingHotspots: hotspots, in: self) } func didLongPressHotspot(overlay: PagedPublicationView.HotspotOverlayView, hotspots: [HotspotModel], hotspotRects: [CGRect], locationInOverlay: CGPoint, pageIndex: Int, locationInPage: CGPoint) { delegate?.didLongPress(pageIndex: pageIndex, locationInPage: locationInPage, hittingHotspots: hotspots, in: self) } func didDoubleTapHotspot(overlay: PagedPublicationView.HotspotOverlayView, hotspots: [HotspotModel], hotspotRects: [CGRect], locationInOverlay: CGPoint, pageIndex: Int, locationInPage: CGPoint) { delegate?.didDoubleTap(pageIndex: pageIndex, locationInPage: locationInPage, hittingHotspots: hotspots, in: self) } }
mit
4207d4c82863e46fccd3a0b9bd2fa042
45.791379
255
0.664247
5.301621
false
false
false
false
batoulapps/QamarDeen
QamarDeen/QamarDeen/Services/Points.swift
1
3345
// // Points.swift // QamarDeen // // Created by Mazyad Alabduljaleel on 12/28/16. // Copyright © 2016 Batoul Apps. All rights reserved. // import Foundation /// Points /// class which holds the points calculation private final class Points { static func `for`(_ fast: Fast) -> Int { guard let rawValue = fast.type, let fastKind = Fast.Kind(rawValue: rawValue) else { return 0 } switch fastKind { case .none: return 0 case .forgiveness: return 100 case .vow: return 250 case .reconcile: return 400 case .voluntary: return 500 case .mandatory: return 500 } } static func `for`(_ charity: Charity) -> Int { guard let rawValue = charity.type, let charityKind = Charity.Kind(rawValue: rawValue) else { return 0 } switch charityKind { case .smile: return 25 default: return 100 } } static func `for`(_ prayer: Prayer) -> Int { guard let methodValue = prayer.method, let method = Prayer.Method(rawValue: methodValue), let kindValue = prayer.type, let kind = Prayer.Kind(rawValue: kindValue) else { return 0 } switch (method, kind) { case (.alone, .shuruq): return 200 case (.alone, .qiyam): return 300 case (.alone, _): return 100 case (.group, .qiyam): return 300 case (.group, _): return 400 case (.aloneWithVoluntary, _): return 200 case (.groupWithVoluntary, _): return 500 case (.late, _): return 25 case (.excused, _): return 300 default: return 0 } } static func `for`(_ reading: Reading) -> Int { return reading.ayahCount * 2 } } /// Extensions /// convenience access to point calculation through model classes // MARK: CountableAction extension Collection where Iterator.Element: CountableAction { var points: Int { return map { $0.points } .reduce(0, +) } } // MARK: Fasting extension Fast: CountableAction { var points: Int { return Points.for(self) } } // MARK: Charity extension Charity: CountableAction { var points: Int { return Points.for(self) } } // MARK: Prayer extension Prayer: CountableAction { var points: Int { return Points.for(self) } } /// MARK: Reading extension Reading: CountableAction { var points: Int { return Points.for(self) } } // MARK: Day extension Day: CountableAction { var charityCollection: [Charity] { return charities?.flatMap { $0 as? Charity } ?? [] } var prayerCollection: [Prayer] { return prayers?.flatMap { $0 as? Prayer } ?? [] } var readingsCollection: [Reading] { return readings?.flatMap { $0 as? Reading } ?? [] } var points: Int { return [ fast?.points ?? 0, prayerCollection.points, charityCollection.points, readingsCollection.points ].reduce(0, +) } }
mit
f8725257af08974842670c12a1f7ec3b
22.222222
100
0.53439
4.216898
false
false
false
false
digitalcatnip/Pace-SSS-iOS
SSSFreshmanApp/SSSFreshmanApp/TutorTVC.swift
1
7509
// // TutorTVC.swift // Pace SSS // // Created by James McCarthy on 8/31/16. // Copyright © 2016 Digital Catnip. All rights reserved. // import GoogleAPIClient import GTMOAuth2 import RealmSwift class TutorTVC: UITableViewController { private let kKeychainItemName = "SSS Freshman App" private let kClientID = "1071382956425-khatsf83p2hm5oihev02j2v36q5je8r8.apps.googleusercontent.com" // If modifying these scopes, delete your previously saved credentials by // resetting the iOS simulator or uninstall the app. private let scopes = ["https://www.googleapis.com/auth/spreadsheets.readonly"] private let service = GTLService() private var tutors: Results<Tutor>? var refresher = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() if let auth = GTMOAuth2ViewControllerTouch.authForGoogleFromKeychainForName( kKeychainItemName, clientID: kClientID, clientSecret: nil) { service.authorizer = auth } refresher = UIRefreshControl() refresher.tintColor = UIColor.redColor() refresher.addTarget(self, action: #selector(showTutors), forControlEvents: .ValueChanged) self.refreshControl = refresher self.navigationController?.navigationBar.tintColor = UIColor(red: 39/255, green: 85/255, blue: 235/255, alpha: 1.0) loadTutorsFromRealm(false) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let authorizer = service.authorizer, canAuth = authorizer.canAuthorize where canAuth { showTutors() } else { presentViewController( createAuthController(), animated: true, completion: nil ) } } override func viewDidAppear(animated: Bool) { registerScreen("TutorScreen") } //MARK: UITableViewDataSource functions override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tutors != nil { return tutors!.count } else { return 0; } } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 90.0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("tutorCell", forIndexPath: indexPath) as! TutorCell cell.tutorObj = tutors![indexPath.row] cell.configure() return cell } // MARK: UITableViewDelegate functions override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if tutors != nil && indexPath.row < tutors!.count { let tutor = tutors![indexPath.row] sendEmailToTutor(tutor) } tableView.deselectRowAtIndexPath(indexPath, animated: true) } //MARK: Send Email func sendEmailToTutor(tutor: Tutor) { registerButtonAction("Tutors", action: "Email Tutor", label: tutor.fullName()) EmailAction.emailSomeone( tutor.email, message: "Hello \(tutor.first_name),\nI would like help in \(tutor.subjects).", subject: "From an SSS App User", presenter: self ) } // MARK: Google Sheets API func showTutors() { NSLog("Loading from network!") refresher.beginRefreshing() let baseUrl = "https://sheets.googleapis.com/v4/spreadsheets" let spreadsheetId = "1BSCxHudMSLj1tDzdxFWYBqWtxDbj_Dz4jC2ZN4JiTtU" let courseRange = "tutor!A2:D" let url = String(format:"%@/%@/values/%@", baseUrl, spreadsheetId, courseRange) let params = ["majorDimension": "ROWS"] let fullUrl = GTLUtilities.URLWithString(url, queryParameters: params) service.fetchObjectWithURL(fullUrl, objectClass: GTLObject.self, delegate: self, didFinishSelector: #selector(TutorTVC.displayResultWithTicket(_:finishedWithObject:error:)) ) } func displayResultWithTicket(ticket: GTLServiceTicket, finishedWithObject object : GTLObject, error: NSError?) { if error != nil { showAlert("Network Issue", message: "Tutor information may be incorrect.") return } let rows = object.JSON["values"] as! [[String]] if rows.isEmpty { NSLog("No data found.") return } //Track the existing courses so we can delete removed entries let oldTutors = ModelManager.sharedInstance.query(Tutor.self, queryString: nil) var otArr = [Tutor]() for course in oldTutors { otArr.append(course) } var hashes = [Int]() var tutors = [Tutor]() for row in rows { let t = Tutor() t.initializeFromSpreadsheet(row) tutors.append(t) hashes.append(t.id) } //Sort the IDs of the new objects, then check to see if the old objects are in the new list //We'll delete any old object not in the list hashes.sortInPlace() var toDelete = [Tutor]() for tutor in otArr { if let _ = hashes.indexOf(tutor.id) { } else { toDelete.append(tutor) } } ModelManager.sharedInstance.saveModels(tutors) ModelManager.sharedInstance.deleteModels(toDelete) loadTutorsFromRealm(true) refresher.endRefreshing() } private func createAuthController() -> GTMOAuth2ViewControllerTouch { let scopeString = scopes.joinWithSeparator(" ") return GTMOAuth2ViewControllerTouch( scope: scopeString, clientID: kClientID, clientSecret: nil, keychainItemName: kKeychainItemName, delegate: self, finishedSelector: #selector(CourseVC.viewController(_:finishedWithAuth:error:)) ) } func viewController(vc : UIViewController, finishedWithAuth authResult : GTMOAuth2Authentication, error : NSError?) { if let error = error { service.authorizer = nil showAlert("Authentication Error", message: error.localizedDescription) return } service.authorizer = authResult dismissViewControllerAnimated(true, completion: nil) } func showAlert(title : String, message: String) { let alert = UIAlertController( title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert ) let ok = UIAlertAction( title: "OK", style: UIAlertActionStyle.Default, handler: nil ) alert.addAction(ok) presentViewController(alert, animated: true, completion: nil) } // MARK: Data Management func loadTutorsFromRealm(shouldReload: Bool) { tutors = ModelManager.sharedInstance.query(Tutor.self, queryString: nil).sorted("first_name") if shouldReload { tableView!.reloadData() } NSLog("Done loading from realm!") } }
mit
bf3d0f7f6f1fb3b7aed7dc3d57b92be9
34.415094
126
0.611215
4.757921
false
false
false
false
biohazardlover/ByTrain
ByTrain/AllStationsRequest.swift
1
2510
import Alamofire extension DataRequest { @discardableResult func responseStationGroups( queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<[StationGroup]>) -> Void) -> Self { let responseSerializer = DataResponseSerializer<[StationGroup]> { (request, response, data, error) -> Result<[StationGroup]> in guard error == nil else { return .failure(BackendError.network(error: error!)) } let stringResponseSerializer = DataRequest.stringResponseSerializer() let result = stringResponseSerializer.serializeResponse(request, response, data, nil) guard case let .success(string) = result else { return .failure(BackendError.stringSerialization(error: result.error!)) } guard let response = response else { return .failure(BackendError.objectSerialization(reason: "String could not be serialized: \(string)")) } let stations = Station.collection(from: response, withRepresentation: string) var stationGroups = [StationGroup]() for station in stations { if let stationNameIntials = station.stationNameIntials, let firstCharacter = stationNameIntials.characters.first { let initial = String(firstCharacter).uppercased() if var stationGroup = (stationGroups.filter() { $0.initial == initial }).first { stationGroup.stations.append(station) } else { var stationGroup = StationGroup() stationGroup.initial = initial stationGroup.stations.append(station) stationGroups.append(stationGroup) } } } stationGroups.sort(by: { $0.initial <= $1.initial }) return .success(stationGroups) } return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) } } @discardableResult public func retrieveAllStations( completionHandler: @escaping (DataResponse<[StationGroup]>) -> Void) -> DataRequest { return request("https://kyfw.12306.cn/otn/resources/js/framework/station_name.js", method: .get).responseStationGroups(completionHandler: completionHandler) }
mit
fde10544dc1ebc4a739730aa5b523717
42.275862
160
0.6
5.678733
false
false
false
false
bradhilton/TableViewSource
TableViewSource/TableViewSourcesSource/TableViewSourcesSource.swift
1
2399
// // TableViewSourcesSource.swift // TableViewSource // // Created by Bradley Hilton on 2/9/16. // Copyright © 2016 Brad Hilton. All rights reserved. // protocol TableViewSourcesSource : TableViewInterfaceSource { var sources: [TableViewSource] { get set } } extension TableViewSourcesSource { func sourceForSection(section: Int) -> TableViewSource? { return sourceForIndex(section) { $0 + $1.numberOfSections() } } func sourceForSectionTitleAtIndex(index: Int) -> TableViewSource? { return sourceForIndex(index) { $0 + ($1.sectionIndexTitles()?.count ?? 0) } } func sourceForIndex(index: Int, combine: (Int, TableViewSource) -> Int) -> TableViewSource? { for i in sources.indices { if index < sources[0...i].reduce(0, combine: combine) { return self.sources[i] } } return nil } func sectionOffsetForSource(source: TableViewSource) -> Int { if let i = sources.indexOf({ $0 === source }) { return sources[0..<i].reduce(0) { $0 + $1.numberOfSections() } } return 0 } func indexPathForSource(source: TableViewSource, indexPath: NSIndexPath) -> NSIndexPath { return NSIndexPath(forRow: indexPath.row, inSection: indexPath.section - sectionOffsetForSource(source)) } func indexPathFromSource(source: TableViewSource, indexPath: NSIndexPath) -> NSIndexPath { return NSIndexPath(forRow: indexPath.row, inSection: indexPath.section + sectionOffsetForSource(source)) } func sectionForSource(source: TableViewSource, section: Int) -> Int { return section - sectionOffsetForSource(source) } func sectionFromSource(source: TableViewSource, section: Int) -> Int { return section + sectionOffsetForSource(source) } func delegate<T>(indexPath: NSIndexPath, handler: (TableViewSource, NSIndexPath) -> T?) -> T? { guard let source = sourceForSection(indexPath.section) else { return nil } return handler(source, indexPathForSource(source, indexPath: indexPath)) } func delegate<T>(section: Int, handler: (TableViewSource, Int) -> T?) -> T? { guard let source = sourceForSection(section) else { return nil } return handler(source, sectionForSource(source, section: section)) } }
mit
81322222bc144d0f354bd874f430d0f3
34.264706
112
0.649708
4.416206
false
false
false
false
qingcai518/MyFacePlus
MyFacePlus/UIImage.swift
1
1462
// // UIImage.swift // MyFacePlus // // Created by liqc on 2017/07/12. // Copyright © 2017年 RN-079. All rights reserved. // import UIKit extension UIImage { func getImage(from rect : CGRect) -> UIImage? { if let cgImage = self.cgImage, let subImage = cgImage.cropping(to: rect) { return UIImage(cgImage: subImage) } return nil } func strechImage() -> UIImage? { guard let cgImage = self.cgImage else {return self} guard let filter = CIFilter(name: "CIStretchCrop") else {return self} let inputImage = CIImage(cgImage: cgImage) filter.setValue(inputImage, forKey: kCIInputImageKey) if let outputImage = filter.outputImage { return UIImage(ciImage: outputImage) } return self } func drawImage(in rect: CGRect, _ inputImage : UIImage) -> UIImage? { UIGraphicsBeginImageContext(self.size) draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) inputImage.draw(in: rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } func applyStrech(in rect : CGRect) -> UIImage? { if let subImage = self.getImage(from: rect), let strechZone = subImage.strechImage() { return self.drawImage(in: rect, strechZone) } return nil } }
apache-2.0
adb231838077214adb3e23a774392c8e
28.77551
94
0.607265
4.291176
false
false
false
false
6ag/AppScreenshots
AppScreenshots/Classes/Module/Home/View/JFAlbumItemCollectionViewCell.swift
1
3471
// // JFAlbumItemCollectionViewCell.swift // AppScreenshots // // Created by zhoujianfeng on 2017/2/9. // Copyright © 2017年 zhoujianfeng. All rights reserved. // import UIKit import Photos /// 自定义相册的相册cell class JFAlbumItemCollectionViewCell: UICollectionViewCell { var albumItem: JFAlbumItem? { didSet { guard let albumItem = albumItem, let asset = albumItem.fetchResult.lastObject else { return } // 加载图片 PHCachingImageManager.default().requestImage( for: asset, targetSize: CGSize(width: JFPhotoPickerViewItemWidth * 1.5, height: JFPhotoPickerViewItemWidth * 1.5), contentMode: .aspectFit, options: nil) { [weak self] (image, info) in self?.imageView.image = image } // 相册标题 titleLabel.text = albumItem.title // 是否选中 selectedButton.isHidden = !albumItem.isSelected } } override init(frame: CGRect) { super.init(frame: frame) prepareUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - 懒加载 fileprivate lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.layer.masksToBounds = true return imageView }() /// 标题 fileprivate lazy var titleLabel: UILabel = { let label = UILabel() label.textColor = UIColor.white label.font = UIFont.systemFont(ofSize: layoutFont(iPhone6: 16)) return label }() /// 选中按钮 lazy var selectedButton: UIButton = { let button = UIButton(type: .custom) button.setBackgroundImage(UIImage(named: "photo_picker_icon_selected"), for: .normal) button.isUserInteractionEnabled = false return button }() /// 选中时的遮罩 lazy var shadowView: UIView = { let view = UIView() view.alpha = 0 view.backgroundColor = UIColor(white: 1.0, alpha: 0.1) return view }() } // MARK: - 设置界面 extension JFAlbumItemCollectionViewCell { /// 准备UI fileprivate func prepareUI() { contentView.addSubview(imageView) contentView.addSubview(titleLabel) contentView.addSubview(selectedButton) contentView.addSubview(shadowView) imageView.snp.makeConstraints { (make) in make.left.equalTo(layoutHorizontal(iPhone6: 5)) make.right.equalTo(layoutHorizontal(iPhone6: -5)) make.top.equalTo(layoutVertical(iPhone6: 5)) make.bottom.equalTo(layoutVertical(iPhone6: -25)) } titleLabel.snp.makeConstraints { (make) in make.centerX.equalTo(self.contentView) make.bottom.equalTo(self.contentView) } selectedButton.snp.makeConstraints { (make) in make.top.equalTo(self.contentView) make.right.equalTo(self.contentView) make.size.equalTo(CGSize(width: layoutHorizontal(iPhone6: 22), height: layoutVertical(iPhone6: 22))) } shadowView.snp.makeConstraints { (make) in make.edges.equalTo(self.imageView) } } }
mit
e59d89e32fe95a8152a99981c537e8bf
29.232143
118
0.594507
4.762307
false
false
false
false
Awalz/ark-ios-monitor
ArkMonitor/Settings/Server Selection/Custom Server Selection/SettingsSaveTableViewCell.swift
1
2468
// Copyright (c) 2016 Ark // // 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 protocol SettingsSaveTableViewCellDelegate: class { func saveCellButtonWasTapped(_ cell: SettingsSaveTableViewCell) } class SettingsSaveTableViewCell: UITableViewCell { var saveButton: UIButton! public weak var delegate: SettingsSaveTableViewCellDelegate? init(reuseIdentifier: String) { super.init(style: .default, reuseIdentifier: "username") backgroundColor = ArkPalette.backgroundColor selectionStyle = .none saveButton = UIButton() saveButton.title("Save", color: UIColor.white) saveButton.setBackgroundColor(ArkPalette.accentColor, forState: UIControlState()) saveButton.titleLabel?.font = UIFont.systemFont(ofSize: 20.0, weight: .semibold) saveButton.addTarget(self, action: #selector(saveButtonTapped), for: .touchUpInside) saveButton.clipsToBounds = true saveButton.layer.cornerRadius = 8.0 addSubview(saveButton) saveButton.snp.makeConstraints { (make) in make.width.equalTo(250.0) make.height.equalTo(45.0) make.center.equalToSuperview() } } @objc private func saveButtonTapped() { delegate?.saveCellButtonWasTapped(self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
292c1cac71ea8fdab479f28a701e970a
42.298246
137
0.718801
4.936
false
false
false
false
anagac3/living-together-server
Sources/App/Controllers/BoardMessageController.swift
1
4568
// // BoardMessageController.swift // LivingTogetherServer // // Created by Andres Aguilar on 8/16/17. // // import Vapor import HTTP import Fluent final class BoardMessageController { /// it should return an index of all available posts func index(_ req: Request) throws -> ResponseRepresentable { return try BoardMessage.all().makeJSON() } func fetchAll(_ req: Request) throws -> ResponseRepresentable { try validateHousehold(req) let householdId = req.data[BoardMessage.householdIdKey]?.int! return try BoardMessage.makeQuery().filter(BoardMessage.householdIdKey, .equals, householdId).all().makeJSON() } /// create and save the message //residentId, householdId func create(_ req: Request) throws -> ResponseRepresentable { try validateHousehold(req) let boardMessage = try req.boardMessage() try boardMessage.save() return boardMessage } /// When the consumer calls 'GET' on a specific resource, ie: /// '/posts/13rd88' we should show that specific post func show(_ req: Request) throws -> ResponseRepresentable { let boardMessage = try fetchBoardMessage(req) return boardMessage } /// When the consumer calls 'DELETE' on a specific resource, ie: /// 'posts/l2jd9' we should remove that resource from the database func delete(_ req: Request) throws -> ResponseRepresentable { let boardMessage = try fetchBoardMessage(req) try boardMessage.delete() return Response(status: .ok) } /// When the consumer calls 'DELETE' on the entire table, ie: /// '/posts' we should remove the entire table func clear(_ req: Request) throws -> ResponseRepresentable { try BoardMessage.makeQuery().delete() return Response(status: .ok) } func addRoutes(routeBuilder: RouteBuilder) { let boardMessageBuilder = routeBuilder.grouped("boardMessage") boardMessageBuilder.post("create", handler: create) boardMessageBuilder.post("show", handler: show) boardMessageBuilder.post("showAll", handler: fetchAll) boardMessageBuilder.post("delete", handler: delete) //To keep out of production boardMessageBuilder.post("deleteAll", handler: clear) boardMessageBuilder.get(handler: index) } } extension BoardMessageController { func validateHousehold(_ req: Request) throws { guard let householdId = req.data[BoardMessage.householdIdKey]?.int, let residentId = req.data[BoardMessage.residentIdKey] else { throw Abort.badRequest } guard let household = try Household.find(householdId), let resident = try Resident.find(residentId) else { throw Abort.notFound } guard try Node(node: household.id) == resident.householdId else { throw Abort.unauthorized } } //Returns boardMessage func fetchBoardMessage(_ req: Request) throws -> BoardMessage { try validateResident(req) let boardMessage = try BoardMessage.find(req.data[BoardMessage.idKey]?.int) return boardMessage! } //Validate request parameters id and asigneeId //Validate boardMessaee and resident exist //Validate resident belongs to household func validateResident(_ req: Request) throws { guard let toDoId = req.data[BoardMessage.idKey]?.int, let residentId = req.data[BoardMessage.residentIdKey] else { throw Abort.badRequest } guard let boardMessage = try BoardMessage.find(toDoId), let resident = try Resident.find(residentId), let household = try Household.find(boardMessage.householdId) else { throw Abort.notFound } guard try Node(node: household.id) == resident.householdId else { throw Abort.unauthorized } } } extension Request { /// Create a post from the JSON body /// return BadRequest error if invalid /// or no JSON func boardMessage() throws -> BoardMessage { guard let json = json else { throw Abort.badRequest } return try BoardMessage(json: json) } } /// Since PostController doesn't require anything to /// be initialized we can conform it to EmptyInitializable. /// /// This will allow it to be passed by type. extension BoardMessageController: EmptyInitializable { }
mit
360cc735c1dc39de0f84bc608e90fd1c
31.628571
177
0.648862
4.685128
false
false
false
false
Onavoy/Torpedo
Torpedo/Classes/Date/DateExtension.swift
1
1618
import Foundation public extension Date { private static var formatsMap: [String : DateFormatter] = [:] public var milliseconds: Double { return timeIntervalSince1970 * 1000.0 } public var millisecondsString : String { return String(milliseconds) } public init(milliseconds: Double) { self.init(timeIntervalSince1970: milliseconds / 1000.0) } public init(milliseconds: Int64) { self.init(timeIntervalSince1970: Double(milliseconds) / 1000.0) } public init(milliseconds: Int32) { self.init(timeIntervalSince1970: Double(milliseconds) / 1000.0) } public init(milliseconds: UInt) { self.init(timeIntervalSince1970: Double(milliseconds) / 1000.0) } public init(milliseconds: String) { self.init(timeIntervalSince1970: Double(milliseconds)! / 1000.0) } public init?(string: String, format: String) { let date = Date.formatter(with: format).date(from: string) if date != nil { self = date! return } return nil } public func format(_ format: String) -> String { return Date.formatter(with: format).string(from: self) } public static func formatter(with format: String) -> DateFormatter { var foundFormatter = Date.formatsMap[format] if foundFormatter == nil { foundFormatter = DateFormatter() foundFormatter?.dateFormat = format Date.formatsMap[format] = foundFormatter! } return foundFormatter! } }
mit
7f5322b0f47d8b4d9f146b2ef8d3969b
26.896552
72
0.614339
4.676301
false
false
false
false
darkzero/SimplePlayer
SimplePlayer/UI/CustomController/AnnularProgress.swift
1
3559
// // AnnularProgress.swift // SimplePlayer // // Created by darkzero on 14-6-11. // Copyright (c) 2014 darkzero. All rights reserved. // import UIKit import QuartzCore import Darwin let pi:CGFloat = 3.1415926; //@IBDesignable class CustomView : UIView { // @IBInspectable var borderColor: UIColor = UIColor.clearColor() // @IBInspectable var borderWidth: CGFloat = 0 // @IBInspectable var cornerRadius: CGFloat = 0 //} @IBDesignable class AnnularProgress: UIView { @IBInspectable var outerRadius:CGFloat = 48.0; @IBInspectable var innerRadius:CGFloat = 32.0; var currentValue : CGFloat = 0; var maxValue : CGFloat = 0; //var outerRadius:CGFloat = 0; //var innerRadius:CGFloat = 0; override init(frame: CGRect) { super.init(frame: frame) // Initialization code } // init(outerRadius:CGFloat, innerRadius:CGFloat) { let frame:CGRect = CGRectMake(0, 0, outerRadius * 2.0, outerRadius * 2.0); super.init(frame: frame); self.outerRadius = outerRadius; self.innerRadius = innerRadius; self.backgroundColor = UIColor.clearColor(); //println("Search iTunes API at URL \(outerRadius)") NSLog("%f", self.outerRadius); } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code // draw annular background color var lineWidth = self.outerRadius - self.innerRadius; var processBackgroundPath:UIBezierPath = UIBezierPath(); processBackgroundPath.lineWidth = lineWidth; processBackgroundPath.lineCapStyle = kCGLineCapButt; var centerPoint:CGPoint = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2); var radius:CGFloat = (self.bounds.size.width - lineWidth)/2; var startAngle:CGFloat = ((self.currentValue/self.maxValue) * 2 * pi) - (pi / 2.0); var endAngle:CGFloat = (2 * pi) - (pi / 2);// + startAngle; processBackgroundPath.addArcWithCenter(centerPoint, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true); UIColor.whiteColor().set(); processBackgroundPath.stroke(); // draw progress var processPath:UIBezierPath = UIBezierPath(); processPath.lineCapStyle = kCGLineCapButt; processPath.lineWidth = lineWidth; startAngle = -1 * (pi / 2); endAngle = ((self.currentValue/self.maxValue) * 2 * pi) + startAngle; processPath.addArcWithCenter(centerPoint, radius:radius, startAngle:startAngle, endAngle:endAngle, clockwise:true); UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1.0).set(); processPath.stroke(); } override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafeMutablePointer<Void>) { // self.setNeedsDisplay(); } override func didMoveToSuperview() { addObserver(self, forKeyPath: "currentValue", options: NSKeyValueObservingOptions.New|NSKeyValueObservingOptions.Old , context: nil); addObserver(self, forKeyPath: "maxValue", options: NSKeyValueObservingOptions.New|NSKeyValueObservingOptions.Old, context: nil); } }
mit
3ebabd460b2d36fdc44b3c70fcff44a7
36.861702
159
0.655802
4.592258
false
false
false
false
lcepy/STNetWork
STNetWork/STNetWorkResponse.swift
2
4035
// // STNetWorkResponse.swift // STNetWork // // Created by xiangwenwen on 15/6/12. // Copyright (c) 2015年 xiangwenwen. All rights reserved. // import UIKit class STNetworkResponse: NSObject { var httpResponse:NSHTTPURLResponse? var response:NSURLResponse? var responseHeader:Dictionary<NSObject,AnyObject>? var responseCookie:Dictionary<NSObject,AnyObject>! init(response:NSURLResponse?) { self.httpResponse = response as? NSHTTPURLResponse self.response = response self.responseHeader = self.httpResponse?.allHeaderFields super.init() self.responseCookie = self.getAllResponseCookie() } /** 获取 response所有的头信息 :returns: <#return value description#> */ func getAllResponseHeader()-> Dictionary<NSObject,AnyObject>?{ if let responseHeader = self.responseHeader{ return responseHeader } return nil } /** 获取 response的响应状态 :returns: <#return value description#> */ func getStatusCode()->Int?{ return self.httpResponse?.statusCode } /** 根据key返回一个header值 :param: headerKey <#headerKey description#> :returns: <#return value description#> */ func getResponseHeader(headerKey:NSObject?)->AnyObject?{ if let key = headerKey{ return self.responseHeader![headerKey!] } return nil } /** 获取所有的 cookie (注意,这个方法获取的是全局的) :returns: <#return value description#> */ func getAllStorageCookie()->Array<AnyObject>?{ var cookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage() if let cookies:Array<AnyObject> = cookieStorage.cookies{ return cookies } return nil } /** 获取当前 response 的所有cookie :returns: <#return value description#> */ func getAllResponseCookie()->Dictionary<NSObject,AnyObject>?{ self.responseCookie = [:] if let cookiesString: NSString = self.responseHeader!["Set-Cookie" as NSObject] as? NSString{ var cookiesArray:Array<AnyObject> = cookiesString.componentsSeparatedByString(";") for cookiesOne in cookiesArray{ if let _cookiesOne = cookiesOne as? NSString{ var _cookiesArray:Array<AnyObject> = _cookiesOne.componentsSeparatedByString(",") for _cookiesString in _cookiesArray{ if var _value = _cookiesString as? NSString{ _value = _value.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) var cookie:Array<AnyObject> = _value.componentsSeparatedByString("=") var cookieKey:String = String(cookie[0] as! String) self.responseCookie[cookieKey as NSObject] = cookie[1] } } }else{ if var value = cookiesOne as? NSString{ value = value.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) var cookie:Array<AnyObject> = value.componentsSeparatedByString("=") var cookieKey:String = String(cookie[0] as! String) self.responseCookie[cookieKey as NSObject] = cookie[1] } } } return self.responseCookie } return nil } /** 根据key返回一个cookie值 :param: cookieKey <#cookieKey description#> :returns: <#return value description#> */ func getResponseCookie(cookieKey:NSObject?)->AnyObject?{ if let key:NSObject = cookieKey{ if let value:AnyObject = self.responseCookie?[key]{ return value } return nil } return nil } }
mit
cfc2fea75dcbf3152f73a21012ca2e2c
31.131148
116
0.587395
5.239305
false
false
false
false
lady12/firefox-ios
Sync/LoginPayload.swift
14
4070
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCGLogger private let log = Logger.syncLogger public class LoginPayload: CleartextPayloadJSON { private static let OptionalStringFields = [ "formSubmitURL", "httpRealm", ] private static let OptionalNumericFields = [ "timeLastUsed", "timeCreated", "timePasswordChanged", "timesUsed", ] private static let RequiredStringFields = [ "hostname", "username", "password", "usernameField", "passwordField", ] public class func fromJSON(json: JSON) -> LoginPayload? { let p = LoginPayload(json) if p.isValid() { return p } return nil } override public func isValid() -> Bool { if !super.isValid() { return false } if self["deleted"].isBool { return true } if !LoginPayload.RequiredStringFields.every({ self[$0].isString }) { return false } if !LoginPayload.OptionalStringFields.every({ field in let val = self[field] // Yup, 404 is not found, so this means "string or nothing". let valid = val.isString || val.isNull || val.asError?.code == 404 if !valid { log.debug("Field \(field) is invalid: \(val)") } return valid }) { return false } if !LoginPayload.OptionalNumericFields.every({ field in let val = self[field] // Yup, 404 is not found, so this means "number or nothing". // We only check for number because we're including timestamps as NSNumbers. let valid = val.isNumber || val.isNull || val.asError?.code == 404 if !valid { log.debug("Field \(field) is invalid: \(val)") } return valid }) { return false } return true } public var hostname: String { return self["hostname"].asString! } public var username: String { return self["username"].asString! } public var password: String { return self["password"].asString! } public var usernameField: String { return self["usernameField"].asString! } public var passwordField: String { return self["passwordField"].asString! } public var formSubmitURL: String? { return self["formSubmitURL"].asString } public var httpRealm: String? { return self["httpRealm"].asString } private func timestamp(field: String) -> Timestamp? { let json = self[field] if let i = json.asInt64 where i > 0 { return Timestamp(i) } return nil } public var timesUsed: Int? { return self["timesUsed"].asInt } public var timeCreated: Timestamp? { return self.timestamp("timeCreated") } public var timeLastUsed: Timestamp? { return self.timestamp("timeLastUsed") } public var timePasswordChanged: Timestamp? { return self.timestamp("timePasswordChanged") } override public func equalPayloads(obj: CleartextPayloadJSON) -> Bool { if let p = obj as? LoginPayload { if !super.equalPayloads(p) { return false; } if p.deleted || self.deleted { return self.deleted == p.deleted } // If either record is deleted, these other fields might be missing. // But we just checked, so we're good to roll on. return LoginPayload.RequiredStringFields.every({ field in p[field].asString == self[field].asString }) // TODO: optional fields. } return false } }
mpl-2.0
64f4de9c0228bd4458f4b3c1cb200eb4
25.601307
88
0.562408
4.921403
false
false
false
false
juliaguo/shakeWake
shakeWake/shakeWake/MovingAverage.swift
1
892
// // MovingAverage.swift // shakeWake // import Foundation class MovingAverage { var samples: Array<Double> var sampleCount = 0 var period: Int init(period: Int) { self.period = period samples = Array<Double>() } var average: Double { let sum: Double = samples.reduce(0, +) if period > samples.count { return sum / Double(samples.count) } else { return sum / Double(period) } } func addSample(value: Double) -> Double { let pos = Int(fmodf(Float(sampleCount), Float(period))) sampleCount += 1 if pos >= samples.count { samples.append(value) } else { samples[pos] = value } return average } func getAverage() -> Double { return average } }
mit
27def3f716d44bdf4593b84793282d7f
18.822222
63
0.507848
4.437811
false
false
false
false
haskellswift/swift-package-manager
Sources/TestSupport/XCTAssertHelpers.swift
2
3061
/* This source file is part of the Swift.org open source project Copyright 2015 - 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import Basic import POSIX import Utility #if os(macOS) import class Foundation.Bundle #endif public func XCTAssertBuilds(_ path: AbsolutePath, configurations: Set<Configuration> = [.Debug, .Release], file: StaticString = #file, line: UInt = #line, Xcc: [String] = [], Xld: [String] = [], Xswiftc: [String] = [], env: [String: String] = [:]) { for conf in configurations { do { print(" Building \(conf)") _ = try executeSwiftBuild(path, configuration: conf, printIfError: true, Xcc: Xcc, Xld: Xld, Xswiftc: Xswiftc, env: env) } catch { XCTFail("`swift build -c \(conf)' failed:\n\n\(error)\n", file: file, line: line) } } } public func XCTAssertSwiftTest(_ path: AbsolutePath, file: StaticString = #file, line: UInt = #line, env: [String: String] = [:]) { do { _ = try SwiftPMProduct.SwiftTest.execute([], chdir: path, env: env, printIfError: true) } catch { XCTFail("`swift test' failed:\n\n\(error)\n", file: file, line: line) } } public func XCTAssertBuildFails(_ path: AbsolutePath, file: StaticString = #file, line: UInt = #line, Xcc: [String] = [], Xld: [String] = [], Xswiftc: [String] = [], env: [String: String] = [:]) { do { _ = try executeSwiftBuild(path, Xcc: Xcc, Xld: Xld, Xswiftc: Xswiftc) XCTFail("`swift build' succeeded but should have failed", file: file, line: line) } catch POSIX.Error.exitStatus(let status, _) where status == 1{ // noop } catch { XCTFail("`swift build' failed in an unexpected manner") } } public func XCTAssertFileExists(_ path: AbsolutePath, file: StaticString = #file, line: UInt = #line) { if !isFile(path) { XCTFail("Expected file doesn’t exist: \(path.asString)", file: file, line: line) } } public func XCTAssertDirectoryExists(_ path: AbsolutePath, file: StaticString = #file, line: UInt = #line) { if !isDirectory(path) { XCTFail("Expected directory doesn’t exist: \(path.asString)", file: file, line: line) } } public func XCTAssertNoSuchPath(_ path: AbsolutePath, file: StaticString = #file, line: UInt = #line) { if exists(path) { XCTFail("path exists but should not: \(path.asString)", file: file, line: line) } } public func XCTAssertThrows<T: Swift.Error>(_ expectedError: T, file: StaticString = #file, line: UInt = #line, _ body: () throws -> ()) where T: Equatable { do { try body() XCTFail("body completed successfully", file: file, line: line) } catch let error as T { XCTAssertEqual(error, expectedError, file: file, line: line) } catch { XCTFail("unexpected error thrown", file: file, line: line) } }
apache-2.0
722833b54dba925cc63cba4b66897fa8
36.740741
249
0.642787
3.802239
false
false
false
false
ChrisAU/PapyrusCore
PapyrusCore/Array+Combinations.swift
1
1729
// // Array+Combinations.swift // PapyrusCore // // Created by Chris Nevin on 27/05/2016. // Copyright © 2016 CJNevin. All rights reserved. // import Foundation internal extension Array { /// Shuffle array in place. mutating func shuffle() { self = shuffled() } /// - returns: Shuffled array using elements in array. func shuffled() -> Array { return sorted(by: {_, _ in arc4random() % 2 == 0}) } // This thread on stack overflow was very helpful: // https://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n func combinations(_ length: Int) -> [[Element]] { if length <= 0 || length > count { return [] } var buffer = [[Element]]() var indexes = (0..<length).map{ $0 } var k = length - 1 while true { repeat { buffer.append(indexes.map{ self[$0] }) indexes[k] += 1 } while indexes[k] != count if length == 1 { return buffer } while true { let offset = k - 1 if indexes[offset] == count - (length - offset) { if offset == 0 { return buffer } k = offset continue } indexes[offset] += 1 let current = indexes[offset] var i = k, j = 1 while i != length { indexes[i] = current + j i += 1 j += 1 } k = length - 1 break } } } }
bsd-2-clause
48111a9578f04e2557678d81ab4e721e
27.8
107
0.444444
4.657682
false
false
false
false
adrfer/swift
validation-test/compiler_crashers_2_fixed/0016-rdar21437203.swift
20
470
// RUN: %target-swift-frontend %s -emit-silgen struct Curds { var whey: AnyObject? = nil } private class Butter { private func churn<T>(block: () throws -> T) throws -> T { return try block() } } struct Cow { private var b : Butter init() { self.b = Butter() } func cheese() throws { let a = Curds() let b = Curds() let c = Curds() var err = 0 var newChild = 0 defer { } try self.b.churn { return () } } }
apache-2.0
265fde6bdaae9907178181dae07bce91
14.666667
62
0.548936
3.175676
false
false
false
false
brokenhandsio/AWSwift
Sources/AWSwift/AwsRequest.swift
1
3050
import Foundation struct AwsRequest { fileprivate let awsAccessKeyId: String fileprivate let awsAccessKeySecret: String fileprivate let service: AwsService fileprivate let region: AwsRegion fileprivate let request: [String: Any] fileprivate let requestMethod: HttpMethod init(awsAccessKeyId: String, awsAccessKeySecret: String, service: AwsService, region: AwsRegion, request: [String: Any], requestMethod: HttpMethod) { self.awsAccessKeyId = awsAccessKeyId self.awsAccessKeySecret = awsAccessKeySecret self.service = service self.region = region self.request = request self.requestMethod = requestMethod } func makeRequest(onCompletion: @escaping (_ jsonResponse: String?, _ error: AwsRequestErorr?) -> Void) { let headerHost = "\(service.getServiceHostname()).\(region.rawValue).amazonaws.com" let urlString = "https://\(headerHost)" let url = URL(string: urlString)! var urlRequest = URLRequest(url: url) let requestDate = Date() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyyMMdd'T'HHmmss'Z'" let requestDateString = dateFormatter.string(from: requestDate) let jsonData = try? JSONSerialization.data(withJSONObject: request, options: .prettyPrinted) guard let json = jsonData else { onCompletion(nil, .failed(message: "Could not convert request to JSON")) return } urlRequest.httpMethod = requestMethod.rawValue urlRequest.httpBody = json urlRequest.setValue(requestDateString, forHTTPHeaderField: "X-Amz-Date") urlRequest.setValue(headerHost, forHTTPHeaderField: "Host") urlRequest.setValue(service.getAmzTarget(), forHTTPHeaderField: "X-Amz-Target") urlRequest.setValue("application/x-amz-json-1.0", forHTTPHeaderField: "Content-Type") let headerSigner = HeaderSignerGenerator(awsAccessId: awsAccessKeyId, awsAccessSecret: awsAccessKeySecret) let authHeader = headerSigner.getAuthHeader(forRequest: request, requestDate: requestDate, service: service, region: region, requestMethod: requestMethod) urlRequest.setValue(authHeader, forHTTPHeaderField: "Authorization") let session = URLSession.shared let dataTask = session.dataTask(with: urlRequest) { data, response, error in var responseString: String? if let data = data { responseString = String(data: data, encoding: .utf8) } var awsError: AwsRequestErorr? if let error = error { awsError = .failed(message: "Request failed: \(error.localizedDescription)") } onCompletion(responseString, awsError) } dataTask.resume() } } public enum AwsRequestErorr: Error { case failed(message: String) }
mit
9c366298c6583b506377b0b99a09f3d0
39.131579
162
0.648525
5.13468
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/FleetCell.swift
2
1561
// // FleetCell.swift // Neocom // // Created by Artem Shimanski on 26/12/2018. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import TreeController class FleetCell: RowCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var stackView: UIStackView! @IBOutlet weak var scrollView: UIScrollView! override func prepareForReuse() { super.prepareForReuse() scrollView.contentOffset = .zero } } extension Prototype { enum FleetCell { static let `default` = Prototype(nib: UINib(nibName: "FleetCell", bundle: nil), reuseIdentifier: "FleetCell") } } extension Tree.Item { class FleetFetchedResultsRow: FetchedResultsRow<Fleet> { override var prototype: Prototype? { return Prototype.FleetCell.default } lazy var types: [SDEInvType] = { let context = Services.sde.viewContext return (result.loadouts?.array as? [Loadout])?.compactMap{context.invType(Int($0.typeID))} ?? [] }() override func configure(cell: UITableViewCell, treeController: TreeController?) { super.configure(cell: cell, treeController: treeController) guard let cell = cell as? FleetCell else {return} cell.stackView.arrangedSubviews.forEach { cell.stackView.removeArrangedSubview($0) } types.compactMap{$0.icon?.image?.image}.forEach { let imageView = UIImageView(image: $0) imageView.widthAnchor.constraint(equalToConstant: 32).isActive = true imageView.heightAnchor.constraint(equalToConstant: 32).isActive = true cell.stackView.addArrangedSubview(imageView) } } } }
lgpl-2.1
3a8396cbd17ce1251c5854cbbca0a7f8
27.888889
111
0.733333
3.890274
false
false
false
false
Lebron1992/SlackTextViewController-Swift
SlackTextViewController-Swift/SlackTextViewController-Swift/Source/SLKTypingIndicatorView.swift
1
9282
// // SLKTypingIndicatorView.swift // SlackTextViewController-Swift // // Created by 曾文志 on 17/08/2017. // Copyright © 2017 hacknocraft. All rights reserved. // import UIKit open class SLKTypingIndicatorView: SLKBaseTypingIndicatorView { // MARK: - Public Properties /// The amount of time a name should keep visible. If is zero, the indicator will not remove nor disappear automatically. Default is 6.0 seconds open var interval: TimeInterval = 6.0 /// If YES, the user can dismiss the indicator by tapping on it. Default is NO open var canResignByTouch = false /// The color of the text. Default is grayColor open var textColor: UIColor = .gray /// The font of the text. Default is system font, 12 pts open var textFont: UIFont = .systemFont(ofSize: 12) /// The font to be used when matching a username string. Default is system bold font, 12 pts open var highlightFont: UIFont = .boldSystemFont(ofSize: 12) /// The inner padding to use when laying out content in the view. Default is {10, 40, 10, 10} open var contentInset: UIEdgeInsets { get { return _contentInset } set { if (_contentInset == newValue) || (newValue == .zero) { return } _contentInset = newValue slk_updateConstraintConstants() } } private var _contentInset = UIEdgeInsets(top: 10, left: 40, bottom: 10, right: 10) // MARK: - Private Properties private var SLKTypingIndicatorViewIdentifier: String { return "\(SLKTextViewControllerDomain).\(NSStringFromClass(type(of: self)))" } /// The text label used to display the typing indicator content private lazy var textLabel: UILabel = { let textLabel = UILabel() textLabel.translatesAutoresizingMaskIntoConstraints = false textLabel.backgroundColor = .clear textLabel.contentMode = .topLeft textLabel.isUserInteractionEnabled = false return textLabel }() private var usernames = [String]() private var timers = [Timer]() // Auto-Layout margin constraints used for updating their constants private var leftContraint: NSLayoutConstraint? private var rightContraint: NSLayoutConstraint? // MARK: - Initializers public override init(frame: CGRect) { super.init(frame: frame) slk_commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) slk_commonInit() } private func slk_commonInit() { backgroundColor = .white addSubview(textLabel) slk_setupConstraints() } // MARK: - Public API open func insertUsername(_ username: String?) { guard let username = username else { return } let isShowing = usernames.contains(username) if interval > 0.0 { if isShowing, let timer = slk_timerWithIdentifier(username) { slk_invalidateTimer(timer) } let timer = Timer(timeInterval: interval, target: self, selector: #selector(slk_shouldRemoveUsername(_:)), userInfo: [SLKTypingIndicatorViewIdentifier: username], repeats: false) RunLoop.current.add(timer, forMode: .defaultRunLoopMode) timers.append(timer) } if isShowing { return } usernames.append(username) self.textLabel.attributedText = attributedString self.isVisible = true } open func removeUsername(_ username: String?) { guard let username = username, let nameIndex = usernames.index(of: username) else { return } usernames.remove(at: nameIndex) if usernames.count > 0 { textLabel.attributedText = attributedString } else { isVisible = false } } // MARK: - SLKTypingIndicatorProtocol open override var isVisible: Bool { get { return _isVisible } set { // Skip when updating the same value, specially to avoid inovking KVO unnecessary if _isVisible == newValue { return } // Required implementation for key-value observer compliance willChangeValue(forKey: "visible") _isVisible = newValue if !_isVisible { slk_invalidateTimers() } // Required implementation for key-value observer compliance didChangeValue(forKey: "visible") } } private var _isVisible = false open override func dismissIndicator() { if isVisible { isVisible = false } } // MARK: - Getters private var attributedString: NSAttributedString? { guard usernames.count != 0, let firstObject = usernames.first, let lastObject = usernames.last else { return nil } var text = "" if self.usernames.count == 1 { text = String(format: NSLocalizedString("%@ is typing", comment: ""), firstObject) } else if self.usernames.count == 2 { text = String(format: NSLocalizedString("%@ & %@ are typing", comment: ""), firstObject, lastObject) } else if self.usernames.count > 2 { text = NSLocalizedString("Several people are typing", comment: "") } let style = NSMutableParagraphStyle() style.alignment = .left style.lineBreakMode = .byTruncatingTail style.minimumLineHeight = 10.0 let attributes: [String: Any] = [NSFontAttributeName: textFont, NSForegroundColorAttributeName: textColor, NSParagraphStyleAttributeName: style] let attributedString = NSMutableAttributedString(string: text, attributes: attributes) if self.usernames.count <= 2 { attributedString.addAttribute(NSFontAttributeName, value: highlightFont, range: text.nsRange(of: firstObject)) attributedString.addAttribute(NSFontAttributeName, value: highlightFont, range: text.nsRange(of: lastObject)) } return attributedString } open override var intrinsicContentSize: CGSize { return CGSize(width: UIViewNoIntrinsicMetric, height: height) } private var height: CGFloat { var height = textFont.lineHeight height += contentInset.top height += contentInset.bottom return height } // MARK: - Setters open override var isHidden: Bool { get { return _isHidden } set { if _isHidden == newValue { return } if newValue { slk_prepareForReuse() } _isHidden = newValue } } private var _isHidden = false // MARK: - Private Methods @objc private func slk_shouldRemoveUsername(_ timer: Timer) { guard let userInfo = timer.userInfo as? [String: String], let username = userInfo[SLKTypingIndicatorViewIdentifier] else { return } removeUsername(username) slk_invalidateTimer(timer) } private func slk_timerWithIdentifier(_ identifier: String) -> Timer? { for timer in timers { if let userInfo = timer.userInfo as? [String: String], let username = userInfo[SLKTypingIndicatorViewIdentifier], identifier == username { return timer } } return nil } private func slk_invalidateTimer(_ timer: Timer) { timer.invalidate() timers.removeObject(timer) } private func slk_invalidateTimers() { timers.forEach { $0.invalidate() } timers.removeAll() } private func slk_prepareForReuse() { slk_invalidateTimers() textLabel.text = nil usernames.removeAll() } private func slk_setupConstraints() { let views: [String: Any] = ["textLabel": textLabel] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[textLabel]|", options: [], metrics: nil, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[textLabel]-(0@750)-|", options: [], metrics: nil, views: views)) leftContraint = slk_constraintsForAttribute(.leading).first self.leftContraint = slk_constraintsForAttribute(.trailing).first slk_updateConstraintConstants() } private func slk_updateConstraintConstants() { leftContraint?.constant = contentInset.left rightContraint?.constant = contentInset.right } // MARK: - Hit Testing open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) } open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) if canResignByTouch { dismissIndicator() } } // MARK: - Lifeterm deinit { slk_invalidateTimers() } }
mit
a4c261b8fd5b0ddde9790111e7399e9d
29.813953
148
0.609272
5.118653
false
false
false
false
whitepixelstudios/Armchair
Source/Armchair.swift
1
81444
// Armchair.swift // // Copyright (c) 2014 Armchair (http://github.com/UrbanApps/Armchair) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import StoreKit import SystemConfiguration #if os(iOS) import UIKit #elseif os(OSX) import AppKit #else // Not yet supported #endif // MARK: - // MARK: PUBLIC Interface // MARK: - // MARK: Properties /* * Get/Set your Apple generated software id. * This is the only required setup value. * This call needs to be first. No default. */ public var appID: String = "" public func appID(_ appID: String) { Armchair.appID = appID Manager.defaultManager.appID = appID } /* * Get/Set the App Name to use in the prompt * Default value is your localized display name from the info.plist */ public func appName() -> String { return Manager.defaultManager.appName } public func appName(_ appName: String) { Manager.defaultManager.appName = appName } /* * Get/Set the title to use on the review prompt. * Default value is a localized "Rate <appName>" */ public func reviewTitle() -> String { return Manager.defaultManager.reviewTitle } public func reviewTitle(_ reviewTitle: String) { Manager.defaultManager.reviewTitle = reviewTitle } /* * Get/Set the message to use on the review prompt. * Default value is a localized * "If you enjoy using <appName>, would you mind taking a moment to rate it? It won't take more than a minute. Thanks for your support!" */ public func reviewMessage() -> String { return Manager.defaultManager.reviewMessage } public func reviewMessage(_ reviewMessage: String) { Manager.defaultManager.reviewMessage = reviewMessage } /* * Get/Set the cancel button title to use on the review prompt. * Default value is a localized "No, Thanks" */ public func cancelButtonTitle() -> String { return Manager.defaultManager.cancelButtonTitle } public func cancelButtonTitle(_ cancelButtonTitle: String) { Manager.defaultManager.cancelButtonTitle = cancelButtonTitle } /* * Get/Set the rate button title to use on the review prompt. * Default value is a localized "Rate <appName>" */ public func rateButtonTitle() -> String { return Manager.defaultManager.rateButtonTitle } public func rateButtonTitle(_ rateButtonTitle: String) { Manager.defaultManager.rateButtonTitle = rateButtonTitle } /* * Get/Set the remind me later button title to use on the review prompt. * It is optional, so you can set it to nil to hide the remind button from displaying * Default value is a localized "Remind me later" */ public func remindButtonTitle() -> String? { return Manager.defaultManager.remindButtonTitle } public func remindButtonTitle(_ remindButtonTitle: String?) { Manager.defaultManager.remindButtonTitle = remindButtonTitle } /* * Get/Set the NSUserDefault keys that store the usage data for Armchair * Default values are in the form of "<appID>_Armchair<Setting>" */ public func keyForArmchairKeyType(_ keyType: ArmchairKey) -> String { return Manager.defaultManager.keyForArmchairKeyType(keyType) } public func setKey(_ key: NSString, armchairKeyType: ArmchairKey) { Manager.defaultManager.setKey(key, armchairKeyType: armchairKeyType) } /* * Get/Set the prefix to the NSUserDefault keys that store the usage data for Armchair * Default value is the App ID, and it is prepended to the keys for key type, above * This prevents different apps using a shared Key/Value store from overwriting each other. */ public func keyPrefix() -> String { return Manager.defaultManager.keyPrefix } public func keyPrefix(_ keyPrefix: String) { Manager.defaultManager.keyPrefix = keyPrefix } /* * Get/Set the object that stores the usage data for Armchair * it is optional but if you pass nil, Armchair can not run. * Default value is NSUserDefaults.standardUserDefaults() */ public func userDefaultsObject() -> ArmchairDefaultsObject? { return Manager.defaultManager.userDefaultsObject } public func userDefaultsObject(_ userDefaultsObject: ArmchairDefaultsObject?) { Manager.defaultManager.userDefaultsObject = userDefaultsObject } /* * Users will need to have the same version of your app installed for this many * days before they will be prompted to rate it. * Default => 30 */ public func daysUntilPrompt() -> UInt { return Manager.defaultManager.daysUntilPrompt } public func daysUntilPrompt(_ daysUntilPrompt: UInt) { Manager.defaultManager.daysUntilPrompt = daysUntilPrompt } /* * An example of a 'use' would be if the user launched the app. Bringing the app * into the foreground (on devices that support it) would also be considered * a 'use'. * * Users need to 'use' the same version of the app this many times before * before they will be prompted to rate it. * Default => 20 */ public func usesUntilPrompt() -> UInt { return Manager.defaultManager.usesUntilPrompt } public func usesUntilPrompt(_ usesUntilPrompt: UInt) { Manager.defaultManager.usesUntilPrompt = usesUntilPrompt } /* * A significant event can be anything you want to be in your app. In a * telephone app, a significant event might be placing or receiving a call. * In a game, it might be beating a level or a boss. This is just another * layer of filtering that can be used to make sure that only the most * loyal of your users are being prompted to rate you on the app store. * If you leave this at a value of 0 (default), then this won't be a criterion * used for rating. * * To tell Armchair that the user has performed * a significant event, call the method Armchair.userDidSignificantEvent() * Default => 0 */ public func significantEventsUntilPrompt() -> UInt { return Manager.defaultManager.significantEventsUntilPrompt } public func significantEventsUntilPrompt(_ significantEventsUntilPrompt: UInt) { Manager.defaultManager.significantEventsUntilPrompt = significantEventsUntilPrompt } /* * Once the rating alert is presented to the user, they might select * 'Remind me later'. This value specifies how many days Armchair * will wait before reminding them. A value of 0 disables reminders and * removes the 'Remind me later' button. * Default => 1 */ public func daysBeforeReminding() -> UInt { return Manager.defaultManager.daysBeforeReminding } public func daysBeforeReminding(_ daysBeforeReminding: UInt) { Manager.defaultManager.daysBeforeReminding = daysBeforeReminding } /* * By default, Armchair tracks all new bundle versions. * When it detects a new version, it resets the values saved for usage, * significant events, popup shown, user action etc... * By setting this to false, Armchair will ONLY track the version it * was initialized with. If this setting is set to true, Armchair * will reset after each new version detection. * Default => true */ public func tracksNewVersions() -> Bool { return Manager.defaultManager.tracksNewVersions } public func tracksNewVersions(_ tracksNewVersions: Bool) { Manager.defaultManager.tracksNewVersions = tracksNewVersions } /* * If the user has rated the app once before, and you don't want it to show on * a new version, set this to false. This is useful if you release small bugfix * versions and don't want to pester your users with popups for every minor * version. For example, you might set this to false for every minor build, then * when you push a major version upgrade, leave it as true to ask for a rating again. * Default => true */ public func shouldPromptIfRated() -> Bool { return Manager.defaultManager.shouldPromptIfRated } public func shouldPromptIfRated(_ shouldPromptIfRated: Bool) { Manager.defaultManager.shouldPromptIfRated = shouldPromptIfRated } /* * Return whether Armchair will try and present the Storekit review prompt (useful for custom dialog modification) */ public var shouldTryStoreKitReviewPrompt : Bool { return Manager.defaultManager.shouldTryStoreKitReviewPrompt } /* * If set to true, the main bundle will always be used to load localized strings. * Set this to true if you have provided your own custom localizations in * ArmchairLocalizable.strings in your main bundle * Default => false. */ public func useMainAppBundleForLocalizations() -> Bool { return Manager.defaultManager.useMainAppBundleForLocalizations } public func useMainAppBundleForLocalizations(_ useMainAppBundleForLocalizations: Bool) { Manager.defaultManager.useMainAppBundleForLocalizations = useMainAppBundleForLocalizations } /* * If you are an Apple Affiliate, enter your code here. * If none is set, the author's code will be used as it is better to be set as something * rather than nothing. If you want to thank me for making Armchair, feel free * to leave this value at it's default. */ public func affiliateCode() -> String { return Manager.defaultManager.affiliateCode } public func affiliateCode(_ affiliateCode: String) { Manager.defaultManager.affiliateCode = affiliateCode } /* * If you are an Apple Affiliate, enter your campaign code here. * Default => "Armchair-<appID>" */ public func affiliateCampaignCode() -> String { return Manager.defaultManager.affiliateCampaignCode } public func affiliateCampaignCode(_ affiliateCampaignCode: String) { Manager.defaultManager.affiliateCampaignCode = affiliateCampaignCode } #if os(iOS) /* * If set to true, use SKStoreReviewController's requestReview() prompt instead of the default prompt. * If not on iOS 10.3+, reort to the default prompt. * Default => false. */ public func useStoreKitReviewPrompt() -> Bool { return Manager.defaultManager.useStoreKitReviewPrompt } public func useStoreKitReviewPrompt(_ useStoreKitReviewPrompt: Bool) { Manager.defaultManager.useStoreKitReviewPrompt = useStoreKitReviewPrompt } #endif /* * 'true' will show the Armchair alert everytime. Useful for testing * how your message looks and making sure the link to your app's review page works. * Calling this method in a production build (DEBUG preprocessor macro is not defined) * has no effect. In app store builds, you don't have to worry about accidentally * leaving debugEnabled to true * Default => false */ public func debugEnabled() -> Bool { return Manager.defaultManager.debugEnabled } public func debugEnabled(_ debugEnabled: Bool) { #if Debug Manager.defaultManager.debugEnabled = debugEnabled #else print("[Armchair] Debug is disabled on release builds.") print("[Armchair] If you really want to enable debug mode,") print("[Armchair] add \"-DDebug\" to your Swift Compiler - Custom Flags") print("[Armchair] section in the target's build settings for release") #endif } /** Reset all counters manually. This resets UseCount, SignificantEventCount and FirstUseDate (daysUntilPrompt) */ public func resetUsageCounters() { StandardUserDefaults().setObject(NSNumber(value: Date().timeIntervalSince1970), forKey: keyForArmchairKeyType(ArmchairKey.FirstUseDate)) StandardUserDefaults().setObject(NSNumber(value: 1), forKey: keyForArmchairKeyType(ArmchairKey.UseCount)) StandardUserDefaults().setObject(NSNumber(value: 0), forKey: keyForArmchairKeyType(ArmchairKey.SignificantEventCount)) StandardUserDefaults().synchronize() } /** Reset all values tracked by Armchair to initial state. */ public func resetAllCounters() { let currentVersionKey = keyForArmchairKeyType(ArmchairKey.CurrentVersion) let trackingVersion: String? = StandardUserDefaults().stringForKey(currentVersionKey) let bundleVersionKey = kCFBundleVersionKey as String let currentVersion = Bundle.main.object(forInfoDictionaryKey: bundleVersionKey) as? String StandardUserDefaults().setObject(trackingVersion as AnyObject?, forKey: keyForArmchairKeyType(ArmchairKey.PreviousVersion)) StandardUserDefaults().setObject(StandardUserDefaults().objectForKey(keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion)), forKey: keyForArmchairKeyType(ArmchairKey.PreviousVersionRated)) StandardUserDefaults().setObject(StandardUserDefaults().objectForKey(keyForArmchairKeyType(ArmchairKey.DeclinedToRate)), forKey: keyForArmchairKeyType(ArmchairKey.PreviousVersionDeclinedToRate)) StandardUserDefaults().setObject(currentVersion as AnyObject?, forKey: currentVersionKey) resetUsageCounters() StandardUserDefaults().setObject(NSNumber(value: false), forKey: keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion)) StandardUserDefaults().setObject(NSNumber(value: false), forKey: keyForArmchairKeyType(ArmchairKey.DeclinedToRate)) StandardUserDefaults().setObject(NSNumber(value: 0), forKey: keyForArmchairKeyType(ArmchairKey.ReminderRequestDate)) StandardUserDefaults().synchronize() } /* * * */ public func resetDefaults() { Manager.defaultManager.debugEnabled = false Manager.defaultManager.appName = Manager.defaultManager.defaultAppName() Manager.defaultManager.reviewTitle = Manager.defaultManager.defaultReviewTitle() Manager.defaultManager.reviewMessage = Manager.defaultManager.defaultReviewMessage() Manager.defaultManager.cancelButtonTitle = Manager.defaultManager.defaultCancelButtonTitle() Manager.defaultManager.rateButtonTitle = Manager.defaultManager.defaultRateButtonTitle() Manager.defaultManager.remindButtonTitle = Manager.defaultManager.defaultRemindButtonTitle() Manager.defaultManager.daysUntilPrompt = 30 Manager.defaultManager.daysBeforeReminding = 1 Manager.defaultManager.shouldPromptIfRated = true Manager.defaultManager.significantEventsUntilPrompt = 20 Manager.defaultManager.tracksNewVersions = true Manager.defaultManager.useMainAppBundleForLocalizations = false Manager.defaultManager.affiliateCode = Manager.defaultManager.defaultAffiliateCode() Manager.defaultManager.affiliateCampaignCode = Manager.defaultManager.defaultAffiliateCampaignCode() Manager.defaultManager.didDeclineToRateClosure = nil Manager.defaultManager.didDisplayAlertClosure = nil Manager.defaultManager.didOptToRateClosure = nil Manager.defaultManager.didOptToRemindLaterClosure = nil Manager.defaultManager.customAlertClosure = nil #if os(iOS) Manager.defaultManager.usesAnimation = true Manager.defaultManager.tintColor = nil Manager.defaultManager.usesAlertController = Manager.defaultManager.defaultUsesAlertController() Manager.defaultManager.opensInStoreKit = Manager.defaultManager.defaultOpensInStoreKit() Manager.defaultManager.willPresentModalViewClosure = nil Manager.defaultManager.didDismissModalViewClosure = nil #endif Manager.defaultManager.armchairKeyFirstUseDate = Manager.defaultManager.defaultArmchairKeyFirstUseDate() Manager.defaultManager.armchairKeyUseCount = Manager.defaultManager.defaultArmchairKeyUseCount() Manager.defaultManager.armchairKeySignificantEventCount = Manager.defaultManager.defaultArmchairKeySignificantEventCount() Manager.defaultManager.armchairKeyCurrentVersion = Manager.defaultManager.defaultArmchairKeyCurrentVersion() Manager.defaultManager.armchairKeyRatedCurrentVersion = Manager.defaultManager.defaultArmchairKeyRatedCurrentVersion() Manager.defaultManager.armchairKeyDeclinedToRate = Manager.defaultManager.defaultArmchairKeyDeclinedToRate() Manager.defaultManager.armchairKeyReminderRequestDate = Manager.defaultManager.defaultArmchairKeyReminderRequestDate() Manager.defaultManager.armchairKeyPreviousVersion = Manager.defaultManager.defaultArmchairKeyPreviousVersion() Manager.defaultManager.armchairKeyPreviousVersionRated = Manager.defaultManager.defaultArmchairKeyPreviousVersionRated() Manager.defaultManager.armchairKeyPreviousVersionDeclinedToRate = Manager.defaultManager.defaultArmchairKeyDeclinedToRate() Manager.defaultManager.armchairKeyRatedAnyVersion = Manager.defaultManager.defaultArmchairKeyRatedAnyVersion() Manager.defaultManager.armchairKeyAppiraterMigrationCompleted = Manager.defaultManager.defaultArmchairKeyAppiraterMigrationCompleted() Manager.defaultManager.armchairKeyUAAppReviewManagerMigrationCompleted = Manager.defaultManager.defaultArmchairKeyUAAppReviewManagerMigrationCompleted() Manager.defaultManager.keyPrefix = Manager.defaultManager.defaultKeyPrefix() } #if os(iOS) /* * Set whether or not Armchair uses animation when pushing modal StoreKit * view controllers for the app. * Default => true */ public func usesAnimation() -> Bool { return Manager.defaultManager.usesAnimation } public func usesAnimation(_ usesAnimation: Bool) { Manager.defaultManager.usesAnimation = usesAnimation } /* * Set a tint color to apply to UIAlertController * Default => nil (the default tint color is used) */ public func tintColor() -> UIColor? { return Manager.defaultManager.tintColor } public func tintColor(tintColor: UIColor?) { Manager.defaultManager.tintColor = tintColor } /* * Set whether or not Armchair uses a UIAlertController when presenting on iOS 8 * We prefer not to use it so that the Rate button can be on the bottom and the cancel button on the top, * Something not possible as of iOS 8.0 * Default => false */ public func usesAlertController() -> Bool { return Manager.defaultManager.usesAlertController } public func usesAlertController(_ usesAlertController: Bool) { Manager.defaultManager.usesAlertController = usesAlertController } /* * If set to true, Armchair will open App Store link inside the app using * SKStoreProductViewController. * - itunes affiliate codes DO NOT work on iOS 7 inside StoreKit, * - itunes affiliate codes DO work on iOS 8 inside StoreKit, * Default => false on iOS 7, true on iOS 8+ */ public func opensInStoreKit() -> Bool { return Manager.defaultManager.opensInStoreKit } public func opensInStoreKit(_ opensInStoreKit: Bool) { Manager.defaultManager.opensInStoreKit = opensInStoreKit } #endif // MARK: Events /* * Tells Armchair that the user performed a significant event. * A significant event is whatever you want it to be. If you're app is used * to make VoIP calls, then you might want to call this method whenever the * user places a call. If it's a game, you might want to call this whenever * the user beats a level boss. * * If the user has performed enough significant events and used the app enough, * you can suppress the rating alert by passing false for canPromptForRating. The * rating alert will simply be postponed until it is called again with true for * canPromptForRating. */ public func userDidSignificantEvent(_ canPromptForRating: Bool) { Manager.defaultManager.userDidSignificantEvent(canPromptForRating) } /* * Tells Armchair that the user performed a significant event. * A significant event is whatever you want it to be. If you're app is used * to make VoIP calls, then you might want to call this method whenever the * user places a call. If it's a game, you might want to call this whenever * the user beats a level boss. * * This is similar to the userDidSignificantEvent method, but allows the passing of a * ArmchairShouldPromptClosure that will be executed before prompting. * The closure passes all the keys and values that Armchair uses to * determine if it the prompt conditions have been met, and it is up to you * to use this info and return a Bool on whether or not the prompt should be shown. * The closure is run synchronous and on the main queue, so be sure to handle it appropriately. * Return true to proceed and show the prompt, return false to kill the pending presentation. */ public func userDidSignificantEvent(_ shouldPrompt: @escaping ArmchairShouldPromptClosure) { Manager.defaultManager.userDidSignificantEvent(shouldPrompt) } // MARK: Prompts /* * Tells Armchair to show the prompt (a rating alert). The prompt * will be showed if there is an internet connection available, the user hasn't * declined to rate, hasn't rated current version and you are tracking new versions. * * You could call to show the prompt regardless of Armchair settings, * for instance, in the case of some special event in your app. */ public func showPrompt() { Manager.defaultManager.showPrompt() } /* * Tells Armchair to show the review prompt alert if all restrictions have been met. * The prompt will be shown if all restrictions are met, there is an internet connection available, * the user hasn't declined to rate, hasn't rated current version, and you are tracking new versions. * * You could call to show the prompt, for instance, in the case of some special event in your app, * like a user login. */ public func showPromptIfNecessary() { Manager.defaultManager.showPrompt(ifNecessary: true) } /* * Tells Armchair to show the review prompt alert. * * This is similar to the showPromptIfNecessary method, but allows the passing of a * ArmchairShouldPromptClosure that will be executed before prompting. * The closure passes all the keys and values that Armchair uses to * determine if it the prompt conditions have been met, and it is up to you * to use this info and return a Bool on whether or not the prompt should be shown. * The closure is run synchronous and on the main queue, so be sure to handle it appropriately. * Return true to proceed and show the prompt, return false to kill the pending presentation. */ public func showPrompt(_ shouldPrompt: ArmchairShouldPromptClosure) { Manager.defaultManager.showPrompt(shouldPrompt) } /** Returns true if rating conditions have been met already and rating prompt is likely to be shown. */ public func ratingConditionsHaveBeenMet() -> Bool { return Manager.defaultManager.ratingConditionsHaveBeenMet() } // MARK: Misc /* * This is the review URL string, generated by substituting the appID, affiliate code * and affilitate campaign code into the template URL. */ public func reviewURLString() -> String { return Manager.defaultManager.reviewURLString() } /* * Tells Armchair to open the App Store page where the user can specify a * rating for the app. Also records the fact that this has happened, so the * user won't be prompted again to rate the app. * * The only case where you should call this directly is if your app has an * explicit "Rate this app" command somewhere. In all other cases, don't worry * about calling this -- instead, just call the other functions listed above, * and let Armchair handle the bookkeeping of deciding when to ask the user * whether to rate the app. */ public func rateApp() { Manager.defaultManager.rateApp() } #if os(iOS) /* * Tells Armchair to immediately close any open rating modals * for instance, a StoreKit rating View Controller. */ public func closeModalPanel() { Manager.defaultManager.closeModalPanel() } #endif // MARK: Closures /* * Armchair uses closures instead of delegate methods for callbacks. * Default is nil for all of them. */ public typealias ArmchairClosure = () -> () public typealias ArmchairClosureCustomAlert = (_ rateAppClosure: @escaping ArmchairClosure, _ remindLaterClosure: @escaping ArmchairClosure, _ noThanksClosure: @escaping ArmchairClosure) -> () public typealias ArmchairAnimateClosure = (Bool) -> () public typealias ArmchairShouldPromptClosure = (ArmchairTrackingInfo) -> Bool public typealias ArmchairShouldIncrementClosure = () -> Bool public func onDidDisplayAlert(_ didDisplayAlertClosure: ArmchairClosure?) { Manager.defaultManager.didDisplayAlertClosure = didDisplayAlertClosure } public func customAlertClosure(_ customAlertClosure: ArmchairClosureCustomAlert?) { Manager.defaultManager.customAlertClosure = customAlertClosure } public func onDidDeclineToRate(_ didDeclineToRateClosure: ArmchairClosure?) { Manager.defaultManager.didDeclineToRateClosure = didDeclineToRateClosure } public func onDidOptToRate(_ didOptToRateClosure: ArmchairClosure?) { Manager.defaultManager.didOptToRateClosure = didOptToRateClosure } public func onDidOptToRemindLater(_ didOptToRemindLaterClosure: ArmchairClosure?) { Manager.defaultManager.didOptToRemindLaterClosure = didOptToRemindLaterClosure } #if os(iOS) public func onWillPresentModalView(_ willPresentModalViewClosure: ArmchairAnimateClosure?) { Manager.defaultManager.willPresentModalViewClosure = willPresentModalViewClosure } public func onDidDismissModalView(_ didDismissModalViewClosure: ArmchairAnimateClosure?) { Manager.defaultManager.didDismissModalViewClosure = didDismissModalViewClosure } #endif /* * The setShouldPromptClosure is called just after all the rating coditions * have been met and Armchair has decided it should display a prompt, * but just before the prompt actually displays. * * The closure passes all the keys and values that Armchair used to * determine that the prompt conditions had been met, but it is up to you * to use this info and return a Bool on whether or not the prompt should be shown. * Return true to proceed and show the prompt, return false to kill the pending presentation. */ public func shouldPromptClosure(_ shouldPromptClosure: ArmchairShouldPromptClosure?) { Manager.defaultManager.shouldPromptClosure = shouldPromptClosure } /* * The setShouldIncrementUseClosure, if valid, is called before incrementing the use count. * Returning false allows you to ignore a use. This may be usefull in cases such as Facebook login * where the app is backgrounded momentarily and the resultant enter foreground event should * not be considered another use. */ public func shouldIncrementUseCountClosure(_ shouldIncrementUseCountClosure: ArmchairShouldIncrementClosure?) { Manager.defaultManager.shouldIncrementUseCountClosure = shouldIncrementUseCountClosure } // MARK: Armchair Logger Protocol public typealias ArmchairLogger = (Manager, _ log: String, _ file: StaticString, _ function: StaticString, _ line: UInt) -> Void /* * Set a closure to capture debug log and to plug in the desired logging framework. */ public func logger(_ logger: @escaping ArmchairLogger) { Manager.defaultManager.logger = logger } // MARK: - // MARK: Armchair Defaults Protocol @objc public protocol ArmchairDefaultsObject { func objectForKey(_ defaultName: String) -> AnyObject? func setObject(_ value: AnyObject?, forKey defaultName: String) func removeObjectForKey(_ defaultName: String) func stringForKey(_ defaultName: String) -> String? func integerForKey(_ defaultName: String) -> Int func doubleForKey(_ defaultName: String) -> Double func boolForKey(_ defaultName: String) -> Bool func setInteger(_ value: Int, forKey defaultName: String) func setDouble(_ value: Double, forKey defaultName: String) func setBool(_ value: Bool, forKey defaultName: String) @discardableResult func synchronize() -> Bool } open class StandardUserDefaults: ArmchairDefaultsObject { let defaults = UserDefaults.standard @objc open func objectForKey(_ defaultName: String) -> AnyObject? { return defaults.object(forKey: defaultName) as AnyObject? } @objc open func setObject(_ value: AnyObject?, forKey defaultName: String) { defaults.set(value, forKey: defaultName) } @objc open func removeObjectForKey(_ defaultName: String) { defaults.removeObject(forKey: defaultName) } @objc open func stringForKey(_ defaultName: String) -> String? { return defaults.string(forKey: defaultName) } @objc open func integerForKey(_ defaultName: String) -> Int { return defaults.integer(forKey: defaultName) } @objc open func doubleForKey(_ defaultName: String) -> Double { return defaults.double(forKey: defaultName) } @objc open func boolForKey(_ defaultName: String) -> Bool { return defaults.bool(forKey: defaultName) } @objc open func setInteger(_ value: Int, forKey defaultName: String) { defaults.set(value, forKey: defaultName) } @objc open func setDouble(_ value: Double, forKey defaultName: String) { defaults.set(value, forKey: defaultName) } @objc open func setBool(_ value: Bool, forKey defaultName: String) { defaults.set(value, forKey: defaultName) } @discardableResult @objc open func synchronize() -> Bool { return defaults.synchronize() } } public enum ArmchairKey: String, CustomStringConvertible { case FirstUseDate = "First Use Date" case UseCount = "Use Count" case SignificantEventCount = "Significant Event Count" case CurrentVersion = "Current Version" case RatedCurrentVersion = "Rated Current Version" case DeclinedToRate = "Declined To Rate" case ReminderRequestDate = "Reminder Request Date" case PreviousVersion = "Previous Version" case PreviousVersionRated = "Previous Version Rated" case PreviousVersionDeclinedToRate = "Previous Version Declined To Rate" case RatedAnyVersion = "Rated Any Version" case AppiraterMigrationCompleted = "Appirater Migration Completed" case UAAppReviewManagerMigrationCompleted = "UAAppReviewManager Migration Completed" static let allValues = [FirstUseDate, UseCount, SignificantEventCount, CurrentVersion, RatedCurrentVersion, DeclinedToRate, ReminderRequestDate, PreviousVersion, PreviousVersionRated, PreviousVersionDeclinedToRate, RatedAnyVersion, AppiraterMigrationCompleted, UAAppReviewManagerMigrationCompleted] public var description : String { get { return self.rawValue } } } open class ArmchairTrackingInfo: CustomStringConvertible { open let info: Dictionary<ArmchairKey, AnyObject> init(info: Dictionary<ArmchairKey, AnyObject>) { self.info = info } open var description: String { get { var description = "ArmchairTrackingInfo\r" for (key, val) in info { description += " - \(key): \(val)\r" } return description } } } public struct AppiraterKey { static var FirstUseDate = "kAppiraterFirstUseDate" static var UseCount = "kAppiraterUseCount" static var SignificantEventCount = "kAppiraterSignificantEventCount" static var CurrentVersion = "kAppiraterCurrentVersion" static var RatedCurrentVersion = "kAppiraterRatedCurrentVersion" static var RatedAnyVersion = "kAppiraterRatedAnyVersion" static var DeclinedToRate = "kAppiraterDeclinedToRate" static var ReminderRequestDate = "kAppiraterReminderRequestDate" } // MARK: - // MARK: PRIVATE Interface #if os(iOS) open class ArmchairManager : NSObject, SKStoreProductViewControllerDelegate { } #elseif os(OSX) open class ArmchairManager : NSObject, NSAlertDelegate { } #else // Untested, and currently unsupported #endif open class Manager : ArmchairManager { #if os(iOS) fileprivate var operatingSystemVersion = NSString(string: UIDevice.current.systemVersion).doubleValue #elseif os(OSX) private var operatingSystemVersion = Double(ProcessInfo.processInfo.operatingSystemVersion.majorVersion) #else #endif // MARK: - // MARK: Review Alert & Properties #if os(iOS) fileprivate var ratingAlert: UIAlertController? = nil fileprivate let reviewURLTemplate = "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&id=APP_ID&at=AFFILIATE_CODE&ct=AFFILIATE_CAMPAIGN_CODE&action=write-review" fileprivate let reviewURLTemplateiOS11 = "https://itunes.apple.com/us/app/idAPP_ID?ls=1&mt=8&at=AFFILIATE_CODE&ct=AFFILIATE_CAMPAIGN_CODE&action=write-review" #elseif os(OSX) private var ratingAlert: NSAlert? = nil private let reviewURLTemplate = "macappstore://itunes.apple.com/us/app/idAPP_ID?ls=1&mt=12&at=AFFILIATE_CODE&ct=AFFILIATE_CAMPAIGN_CODE" #else #endif fileprivate lazy var appName: String = self.defaultAppName() fileprivate func defaultAppName() -> String { let mainBundle = Bundle.main let displayName = mainBundle.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String let bundleNameKey = kCFBundleNameKey as String let name = mainBundle.object(forInfoDictionaryKey: bundleNameKey) as? String return displayName ?? name ?? "This App" } fileprivate lazy var reviewTitle: String = self.defaultReviewTitle() fileprivate func defaultReviewTitle() -> String { var template = "Rate %@" // Check for a localized version of the default title if let bundle = self.bundle() { template = bundle.localizedString(forKey: template, value: bundle.localizedString(forKey: template, value:"", table: nil), table: "ArmchairLocalizable") } return template.replacingOccurrences(of: "%@", with: "\(self.appName)", options: NSString.CompareOptions(rawValue: 0), range: nil) } fileprivate lazy var reviewMessage: String = self.defaultReviewMessage() fileprivate func defaultReviewMessage() -> String { var template = "If you enjoy using %@, would you mind taking a moment to rate it? It won't take more than a minute. Thanks for your support!" // Check for a localized version of the default title if let bundle = self.bundle() { template = bundle.localizedString(forKey: template, value: bundle.localizedString(forKey: template, value:"", table: nil), table: "ArmchairLocalizable") } return template.replacingOccurrences(of: "%@", with: "\(self.appName)", options: NSString.CompareOptions(rawValue: 0), range: nil) } fileprivate lazy var cancelButtonTitle: String = self.defaultCancelButtonTitle() fileprivate func defaultCancelButtonTitle() -> String { var title = "No, Thanks" // Check for a localized version of the default title if let bundle = self.bundle() { title = bundle.localizedString(forKey: title, value: bundle.localizedString(forKey: title, value:"", table: nil), table: "ArmchairLocalizable") } return title } fileprivate lazy var rateButtonTitle: String = self.defaultRateButtonTitle() fileprivate func defaultRateButtonTitle() -> String { var template = "Rate %@" // Check for a localized version of the default title if let bundle = self.bundle() { template = bundle.localizedString(forKey: template, value: bundle.localizedString(forKey: template, value:"", table: nil), table: "ArmchairLocalizable") } return template.replacingOccurrences(of: "%@", with: "\(self.appName)", options: NSString.CompareOptions(rawValue: 0), range: nil) } fileprivate lazy var remindButtonTitle: String? = self.defaultRemindButtonTitle() fileprivate func defaultRemindButtonTitle() -> String? { //if reminders are disabled, return a nil title to supress the button if self.daysBeforeReminding == 0 { return nil } var title = "Remind me later" // Check for a localized version of the default title if let bundle = self.bundle() { title = bundle.localizedString(forKey: title, value: bundle.localizedString(forKey: title, value:"", table: nil), table: "ArmchairLocalizable") } return title } // Tracking Logic / Configuration fileprivate var appID: String = "" { didSet { keyPrefix = defaultKeyPrefix() if affiliateCampaignCode == defaultAffiliateCampaignCode() { affiliateCampaignCode = affiliateCampaignCode + "-\(appID)" } } } // MARK: Properties with sensible defaults fileprivate var daysUntilPrompt: UInt = 30 fileprivate var usesUntilPrompt: UInt = 20 fileprivate var significantEventsUntilPrompt: UInt = 0 fileprivate var daysBeforeReminding: UInt = 1 fileprivate var tracksNewVersions: Bool = true fileprivate var shouldPromptIfRated: Bool = true fileprivate var useMainAppBundleForLocalizations: Bool = false fileprivate var debugEnabled: Bool = false { didSet { if self.debugEnabled { debugLog("Debug enabled for app: \(appID)") } } } // If you aren't going to set an affiliate code yourself, please leave this as is. // It is my affiliate code. It is better that somebody's code is used rather than nobody's. fileprivate var affiliateCode: String = "11l7j9" fileprivate var affiliateCampaignCode: String = "Armchair" #if os(iOS) fileprivate var usesAnimation: Bool = true fileprivate var tintColor: UIColor? = nil fileprivate lazy var usesAlertController: Bool = self.defaultUsesAlertController() fileprivate lazy var opensInStoreKit: Bool = self.defaultOpensInStoreKit() fileprivate var useStoreKitReviewPrompt: Bool = false fileprivate func defaultOpensInStoreKit() -> Bool { return operatingSystemVersion >= 8 } fileprivate func defaultUsesAlertController() -> Bool { return operatingSystemVersion >= 9 } #endif // MARK: Tracking Keys with sensible defaults fileprivate lazy var armchairKeyFirstUseDate: String = self.defaultArmchairKeyFirstUseDate() fileprivate lazy var armchairKeyUseCount: String = self.defaultArmchairKeyUseCount() fileprivate lazy var armchairKeySignificantEventCount: String = self.defaultArmchairKeySignificantEventCount() fileprivate lazy var armchairKeyCurrentVersion: String = self.defaultArmchairKeyCurrentVersion() fileprivate lazy var armchairKeyRatedCurrentVersion: String = self.defaultArmchairKeyRatedCurrentVersion() fileprivate lazy var armchairKeyDeclinedToRate: String = self.defaultArmchairKeyDeclinedToRate() fileprivate lazy var armchairKeyReminderRequestDate: String = self.defaultArmchairKeyReminderRequestDate() fileprivate lazy var armchairKeyPreviousVersion: String = self.defaultArmchairKeyPreviousVersion() fileprivate lazy var armchairKeyPreviousVersionRated: String = self.defaultArmchairKeyPreviousVersionRated() fileprivate lazy var armchairKeyPreviousVersionDeclinedToRate: String = self.defaultArmchairKeyPreviousVersionDeclinedToRate() fileprivate lazy var armchairKeyRatedAnyVersion: String = self.defaultArmchairKeyRatedAnyVersion() fileprivate lazy var armchairKeyAppiraterMigrationCompleted: String = self.defaultArmchairKeyAppiraterMigrationCompleted() fileprivate lazy var armchairKeyUAAppReviewManagerMigrationCompleted: String = self.defaultArmchairKeyUAAppReviewManagerMigrationCompleted() fileprivate func defaultArmchairKeyFirstUseDate() -> String { return "ArmchairFirstUseDate" } fileprivate func defaultArmchairKeyUseCount() -> String { return "ArmchairUseCount" } fileprivate func defaultArmchairKeySignificantEventCount() -> String { return "ArmchairSignificantEventCount" } fileprivate func defaultArmchairKeyCurrentVersion() -> String { return "ArmchairKeyCurrentVersion" } fileprivate func defaultArmchairKeyRatedCurrentVersion() -> String { return "ArmchairRatedCurrentVersion" } fileprivate func defaultArmchairKeyDeclinedToRate() -> String { return "ArmchairKeyDeclinedToRate" } fileprivate func defaultArmchairKeyReminderRequestDate() -> String { return "ArmchairReminderRequestDate" } fileprivate func defaultArmchairKeyPreviousVersion() -> String { return "ArmchairPreviousVersion" } fileprivate func defaultArmchairKeyPreviousVersionRated() -> String { return "ArmchairPreviousVersionRated" } fileprivate func defaultArmchairKeyPreviousVersionDeclinedToRate() -> String { return "ArmchairPreviousVersionDeclinedToRate" } fileprivate func defaultArmchairKeyRatedAnyVersion() -> String { return "ArmchairKeyRatedAnyVersion" } fileprivate func defaultArmchairKeyAppiraterMigrationCompleted() -> String { return "ArmchairAppiraterMigrationCompleted" } fileprivate func defaultArmchairKeyUAAppReviewManagerMigrationCompleted() -> String { return "ArmchairUAAppReviewManagerMigrationCompleted" } fileprivate lazy var keyPrefix: String = self.defaultKeyPrefix() fileprivate func defaultKeyPrefix() -> String { if !self.appID.isEmpty { return self.appID + "_" } else { return "_" } } fileprivate var userDefaultsObject:ArmchairDefaultsObject? = StandardUserDefaults() // MARK: Optional Closures var didDisplayAlertClosure: ArmchairClosure? var didDeclineToRateClosure: ArmchairClosure? var didOptToRateClosure: ArmchairClosure? var didOptToRemindLaterClosure: ArmchairClosure? var customAlertClosure: ArmchairClosureCustomAlert? #if os(iOS) var willPresentModalViewClosure: ArmchairAnimateClosure? var didDismissModalViewClosure: ArmchairAnimateClosure? #endif var shouldPromptClosure: ArmchairShouldPromptClosure? var shouldIncrementUseCountClosure: ArmchairShouldIncrementClosure? // MARK: State Vars fileprivate var modalPanelOpen: Bool = false #if os(iOS) fileprivate lazy var currentStatusBarStyle: UIStatusBarStyle = { return UIApplication.shared.statusBarStyle }() #endif // MARK: - // MARK: PRIVATE Methods fileprivate func userDidSignificantEvent(_ canPromptForRating: Bool) { DispatchQueue.global(qos: .background).async { self.incrementSignificantEventAndRate(canPromptForRating) } } fileprivate func userDidSignificantEvent(_ shouldPrompt: @escaping ArmchairShouldPromptClosure) { DispatchQueue.global(qos: .background).async { self.incrementSignificantEventAndRate(shouldPrompt) } } // MARK: - // MARK: PRIVATE Rating Helpers fileprivate func incrementAndRate(_ canPromptForRating: Bool) { migrateKeysIfNecessary() incrementUseCount() showPrompt(ifNecessary: canPromptForRating) } fileprivate func incrementAndRate(_ shouldPrompt: ArmchairShouldPromptClosure) { migrateKeysIfNecessary() incrementUseCount() showPrompt(shouldPrompt) } fileprivate func incrementSignificantEventAndRate(_ canPromptForRating: Bool) { migrateKeysIfNecessary() incrementSignificantEventCount() showPrompt(ifNecessary: canPromptForRating) } fileprivate func incrementSignificantEventAndRate(_ shouldPrompt: ArmchairShouldPromptClosure) { migrateKeysIfNecessary() incrementSignificantEventCount() showPrompt(shouldPrompt) } fileprivate func incrementUseCount() { var shouldIncrement = true if let closure = shouldIncrementUseCountClosure { shouldIncrement = closure() } if shouldIncrement { _incrementCountForKeyType(ArmchairKey.UseCount) } } fileprivate func incrementSignificantEventCount() { _incrementCountForKeyType(ArmchairKey.SignificantEventCount) } fileprivate func _incrementCountForKeyType(_ incrementKeyType: ArmchairKey) { let incrementKey = keyForArmchairKeyType(incrementKeyType) let bundleVersionKey = kCFBundleVersionKey as String // App's version. Not settable as the other ivars because that would be crazy. let currentVersion = Bundle.main.object(forInfoDictionaryKey: bundleVersionKey) as? String if currentVersion == nil { assertionFailure("Could not read kCFBundleVersionKey from InfoDictionary") return } // Get the version number that we've been tracking thus far let currentVersionKey = keyForArmchairKeyType(ArmchairKey.CurrentVersion) var trackingVersion: String? = userDefaultsObject?.stringForKey(currentVersionKey) // New install, or changed keys if trackingVersion == nil { trackingVersion = currentVersion userDefaultsObject?.setObject(currentVersion as AnyObject?, forKey: currentVersionKey) } debugLog("Tracking version: \(trackingVersion!)") if trackingVersion == currentVersion { // Check if the first use date has been set. if not, set it. let firstUseDateKey = keyForArmchairKeyType(ArmchairKey.FirstUseDate) var timeInterval: Double? = userDefaultsObject?.doubleForKey(firstUseDateKey) if 0 == timeInterval { timeInterval = Date().timeIntervalSince1970 userDefaultsObject?.setObject(NSNumber(value: timeInterval!), forKey: firstUseDateKey) } // Increment the key's count var incrementKeyCount = userDefaultsObject!.integerForKey(incrementKey) incrementKeyCount += 1 userDefaultsObject?.setInteger(incrementKeyCount, forKey:incrementKey) debugLog("Incremented \(incrementKeyType): \(incrementKeyCount)") } else if tracksNewVersions { // it's a new version of the app, so restart tracking resetAllCounters() debugLog("Reset Tracking Version to: \(trackingVersion!)") } userDefaultsObject?.synchronize() } fileprivate func showPrompt(ifNecessary canPromptForRating: Bool) { if canPromptForRating && connectedToNetwork() && ratingConditionsHaveBeenMet() { var shouldPrompt: Bool = true if let closure = shouldPromptClosure { if Thread.isMainThread { shouldPrompt = closure(trackingInfo()) } else { DispatchQueue.main.sync { shouldPrompt = closure(self.trackingInfo()) } } } if shouldPrompt { DispatchQueue.main.async { self.showRatingAlert() } } } } fileprivate func showPrompt(_ shouldPrompt: ArmchairShouldPromptClosure) { var shouldPromptVal = false if Thread.isMainThread { shouldPromptVal = shouldPrompt(trackingInfo()) } else { DispatchQueue.main.sync { shouldPromptVal = shouldPrompt(self.trackingInfo()) } } if (shouldPromptVal) { DispatchQueue.main.async { self.showRatingAlert() } } } fileprivate func showPrompt() { if !appID.isEmpty && connectedToNetwork() && !userHasDeclinedToRate() && !userHasRatedCurrentVersion() { showRatingAlert() } } fileprivate func ratingConditionsHaveBeenMet() -> Bool { if debugEnabled { return true } if appID.isEmpty { return false } // check if the app has been used long enough let timeIntervalOfFirstLaunch = userDefaultsObject?.doubleForKey(keyForArmchairKeyType(ArmchairKey.FirstUseDate)) if let timeInterval = timeIntervalOfFirstLaunch { let dateOfFirstLaunch = Date(timeIntervalSince1970: timeInterval) let timeSinceFirstLaunch = Date().timeIntervalSince(dateOfFirstLaunch) let timeUntilRate: TimeInterval = 60 * 60 * 24 * Double(daysUntilPrompt) if timeSinceFirstLaunch < timeUntilRate { return false } } else { return false } // check if the app has been used enough times let useCount = userDefaultsObject?.integerForKey(keyForArmchairKeyType(ArmchairKey.UseCount)) if let count = useCount { if UInt(count) <= usesUntilPrompt { return false } } else { return false } // check if the user has done enough significant events let significantEventCount = userDefaultsObject?.integerForKey(keyForArmchairKeyType(ArmchairKey.SignificantEventCount)) if let count = significantEventCount { if UInt(count) < significantEventsUntilPrompt { return false } } else { return false } // Check if the user previously has declined to rate this version of the app if userHasDeclinedToRate() { return false } // Check if the user has already rated the app? if userHasRatedCurrentVersion() { return false } // If the user wanted to be reminded later, has enough time passed? let timeIntervalOfReminder = userDefaultsObject?.doubleForKey(keyForArmchairKeyType(ArmchairKey.ReminderRequestDate)) if let timeInterval = timeIntervalOfReminder { let reminderRequestDate = Date(timeIntervalSince1970: timeInterval) let timeSinceReminderRequest = Date().timeIntervalSince(reminderRequestDate) let timeUntilReminder: TimeInterval = 60 * 60 * 24 * Double(daysBeforeReminding) if timeSinceReminderRequest < timeUntilReminder { return false } } else { return false } // if we have a global set to not show if the end-user has already rated once, and the developer has not opted out of displaying on minor updates let ratedAnyVersion = userDefaultsObject?.boolForKey(keyForArmchairKeyType(ArmchairKey.RatedAnyVersion)) if let ratedAlready = ratedAnyVersion { if (!shouldPromptIfRated && ratedAlready) { return false } } return true } fileprivate func userHasDeclinedToRate() -> Bool { if let declined = userDefaultsObject?.boolForKey(keyForArmchairKeyType(ArmchairKey.DeclinedToRate)) { return declined } else { return false } } fileprivate func userHasRatedCurrentVersion() -> Bool { if let ratedCurrentVersion = userDefaultsObject?.boolForKey(keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion)) { return ratedCurrentVersion } else { return false } } fileprivate func showsRemindButton() -> Bool { return (daysBeforeReminding > 0 && remindButtonTitle != nil) } public var shouldTryStoreKitReviewPrompt : Bool { if #available(iOS 10.3, *), useStoreKitReviewPrompt { return true } return false } fileprivate func requestStoreKitReviewPrompt() -> Bool { if #available(iOS 10.3, *), useStoreKitReviewPrompt { SKStoreReviewController.requestReview() // Assume this version is rated. There is no API to tell if the user actaully rated. userDefaultsObject?.setBool(true, forKey: keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion)) userDefaultsObject?.setBool(true, forKey: keyForArmchairKeyType(ArmchairKey.RatedAnyVersion)) userDefaultsObject?.synchronize() closeModalPanel() return true } return false } fileprivate func showRatingAlert() { if let customClosure = customAlertClosure { customClosure({[weak self] in if let result = self?.requestStoreKitReviewPrompt(), result { ///Showed storekit prompt, all done } else { /// Didn't show storekit prompt, present app store manually self?._rateApp() } }, {[weak self] in self?.remindMeLater()}, {[weak self] in self?.dontRate()}) if let closure = self.didDisplayAlertClosure { closure() } } else { #if os(iOS) if requestStoreKitReviewPrompt() { ///Showed storekit prompt, all done } else { /// Didn't show storekit prompt, present app store manually let alertView : UIAlertController = UIAlertController(title: reviewTitle, message: reviewMessage, preferredStyle: UIAlertControllerStyle.alert) alertView.addAction(UIAlertAction(title: cancelButtonTitle, style:UIAlertActionStyle.default, handler: { (alert: UIAlertAction!) in self.dontRate() })) if (showsRemindButton()) { alertView.addAction(UIAlertAction(title: remindButtonTitle!, style:UIAlertActionStyle.default, handler: { (alert: UIAlertAction!) in self.remindMeLater() })) } alertView.addAction(UIAlertAction(title: rateButtonTitle, style:UIAlertActionStyle.cancel, handler: { (alert: UIAlertAction!) in self._rateApp() })) ratingAlert = alertView // get the top most controller (= the StoreKit Controller) and dismiss it if let presentingController = UIApplication.shared.keyWindow?.rootViewController { if let topController = Manager.topMostViewController(presentingController) { topController.present(alertView, animated: usesAnimation) { [weak self] in if let closure = self?.didDisplayAlertClosure { closure() } print("presentViewController() completed") } } // note that tint color has to be set after the controller is presented in order to take effect (last checked in iOS 9.3) alertView.view.tintColor = tintColor } } #elseif os(OSX) let alert: NSAlert = NSAlert() alert.messageText = reviewTitle alert.informativeText = reviewMessage alert.addButton(withTitle: rateButtonTitle) if showsRemindButton() { alert.addButton(withTitle: remindButtonTitle!) } alert.addButton(withTitle: cancelButtonTitle) ratingAlert = alert if let window = NSApplication.shared.keyWindow { alert.beginSheetModal(for: window) { (response: NSApplication.ModalResponse) in self.handleNSAlertResponse(response) } } else { let response = alert.runModal() handleNSAlertResponse(response) } if let closure = self.didDisplayAlertClosure { closure() } #else #endif } } // MARK: - // MARK: PRIVATE Alert View / StoreKit Delegate Methods #if os(iOS) //Delegate call from the StoreKit view. open func productViewControllerDidFinish(_ viewController: SKStoreProductViewController!) { closeModalPanel() } //Close the in-app rating (StoreKit) view and restore the previous status bar style. fileprivate func closeModalPanel() { let usedAnimation = usesAnimation if modalPanelOpen { UIApplication.shared.setStatusBarStyle(currentStatusBarStyle, animated:usesAnimation) modalPanelOpen = false // get the top most controller (= the StoreKit Controller) and dismiss it if let presentingController = UIApplication.shared.keyWindow?.rootViewController { if let topController = Manager.topMostViewController(presentingController) { topController.dismiss(animated: usesAnimation) {} currentStatusBarStyle = UIStatusBarStyle.default } } } if let closure = self.didDismissModalViewClosure { closure(usedAnimation) } } #elseif os(OSX) private func handleNSAlertResponse(_ response: NSApplication.ModalResponse) { switch (response) { case .alertFirstButtonReturn: // they want to rate it _rateApp() case .alertSecondButtonReturn: // remind them later or cancel if showsRemindButton() { remindMeLater() } else { dontRate() } case .alertThirdButtonReturn: // they don't want to rate it dontRate() default: return } } #else #endif private func dontRate() { userDefaultsObject?.setBool(true, forKey: keyForArmchairKeyType(ArmchairKey.DeclinedToRate)) userDefaultsObject?.synchronize() if let closure = didDeclineToRateClosure { closure() } } private func remindMeLater() { userDefaultsObject?.setDouble(Date().timeIntervalSince1970, forKey: keyForArmchairKeyType(ArmchairKey.ReminderRequestDate)) userDefaultsObject?.synchronize() if let closure = didOptToRemindLaterClosure { closure() } } private func _rateApp() { rateApp() if let closure = didOptToRateClosure { closure() } } fileprivate func rateApp() { userDefaultsObject?.setBool(true, forKey: keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion)) userDefaultsObject?.setBool(true, forKey: keyForArmchairKeyType(ArmchairKey.RatedAnyVersion)) userDefaultsObject?.synchronize() #if os(iOS) // Use the in-app StoreKit view if set, available (iOS 7+) and imported. This works in the simulator. if opensInStoreKit { let storeViewController = SKStoreProductViewController() var productParameters: [String:AnyObject]! = [SKStoreProductParameterITunesItemIdentifier : appID as AnyObject] if (operatingSystemVersion >= 8) { productParameters[SKStoreProductParameterAffiliateToken] = affiliateCode as AnyObject? productParameters[SKStoreProductParameterCampaignToken] = affiliateCampaignCode as AnyObject? } storeViewController.loadProduct(withParameters: productParameters, completionBlock: nil) storeViewController.delegate = self if let closure = willPresentModalViewClosure { closure(usesAnimation) } if let rootController = Manager.getRootViewController() { rootController.present(storeViewController, animated: usesAnimation) { self.modalPanelOpen = true //Temporarily use a status bar to match the StoreKit view. self.currentStatusBarStyle = UIApplication.shared.statusBarStyle UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.default, animated: self.usesAnimation) } } //Use the standard openUrl method } else { if let url = URL(string: reviewURLString()) { UIApplication.shared.openURL(url) } } // Check for iOS simulator #if (arch(i386) || arch(x86_64)) && os(iOS) debugLog("iTunes App Store is not supported on the iOS simulator.") debugLog(" - We would have went to \(reviewURLString()).") debugLog(" - Try running on a test-device") let fakeURL = reviewURLString().replacingOccurrences(of: "itms-apps", with:"http") debugLog(" - Or try copy/pasting \(fakeURL) into a browser on your computer.") #endif #elseif os(OSX) if let url = URL(string: reviewURLString()) { let opened = NSWorkspace.shared.open(url) if !opened { debugLog("Failed to open \(url)") } } #else #endif } fileprivate func reviewURLString() -> String { #if os(iOS) let template = operatingSystemVersion >= 11 ? reviewURLTemplateiOS11 : reviewURLTemplate #elseif os(OSX) let template = reviewURLTemplate #else #endif var reviewURL = template.replacingOccurrences(of: "APP_ID", with: "\(appID)") reviewURL = reviewURL.replacingOccurrences(of: "AFFILIATE_CODE", with: "\(affiliateCode)") reviewURL = reviewURL.replacingOccurrences(of: "AFFILIATE_CAMPAIGN_CODE", with: "\(affiliateCampaignCode)") return reviewURL } // Mark: - // Mark: PRIVATE Key Helpers private func trackingInfo() -> ArmchairTrackingInfo { var trackingInfo: Dictionary<ArmchairKey, AnyObject> = [:] for keyType in ArmchairKey.allValues { let obj: AnyObject? = userDefaultsObject?.objectForKey(keyForArmchairKeyType(keyType)) if let val = obj as? NSObject { trackingInfo[keyType] = val } else { trackingInfo[keyType] = NSNull() } } return ArmchairTrackingInfo(info: trackingInfo) } fileprivate func keyForArmchairKeyType(_ keyType: ArmchairKey) -> String { switch (keyType) { case .FirstUseDate: return keyPrefix + armchairKeyFirstUseDate case .UseCount: return keyPrefix + armchairKeyUseCount case .SignificantEventCount: return keyPrefix + armchairKeySignificantEventCount case .CurrentVersion: return keyPrefix + armchairKeyCurrentVersion case .RatedCurrentVersion: return keyPrefix + armchairKeyRatedCurrentVersion case .DeclinedToRate: return keyPrefix + armchairKeyDeclinedToRate case .ReminderRequestDate: return keyPrefix + armchairKeyReminderRequestDate case .PreviousVersion: return keyPrefix + armchairKeyPreviousVersion case .PreviousVersionRated: return keyPrefix + armchairKeyPreviousVersionRated case .PreviousVersionDeclinedToRate: return keyPrefix + armchairKeyPreviousVersionDeclinedToRate case .RatedAnyVersion: return keyPrefix + armchairKeyRatedAnyVersion case .AppiraterMigrationCompleted: return keyPrefix + armchairKeyAppiraterMigrationCompleted case .UAAppReviewManagerMigrationCompleted: return keyPrefix + armchairKeyUAAppReviewManagerMigrationCompleted } } fileprivate func setKey(_ key: NSString, armchairKeyType: ArmchairKey) { switch armchairKeyType { case .FirstUseDate: armchairKeyFirstUseDate = key as String case .UseCount: armchairKeyUseCount = key as String case .SignificantEventCount: armchairKeySignificantEventCount = key as String case .CurrentVersion: armchairKeyCurrentVersion = key as String case .RatedCurrentVersion: armchairKeyRatedCurrentVersion = key as String case .DeclinedToRate: armchairKeyDeclinedToRate = key as String case .ReminderRequestDate: armchairKeyReminderRequestDate = key as String case .PreviousVersion: armchairKeyPreviousVersion = key as String case .PreviousVersionRated: armchairKeyPreviousVersionRated = key as String case .PreviousVersionDeclinedToRate: armchairKeyPreviousVersionDeclinedToRate = key as String case .RatedAnyVersion: armchairKeyRatedAnyVersion = key as String case .AppiraterMigrationCompleted: armchairKeyAppiraterMigrationCompleted = key as String case .UAAppReviewManagerMigrationCompleted: armchairKeyUAAppReviewManagerMigrationCompleted = key as String } } private func armchairKeyForAppiraterKey(_ appiraterKey: String) -> String { switch appiraterKey { case AppiraterKey.FirstUseDate: return keyForArmchairKeyType(ArmchairKey.FirstUseDate) case AppiraterKey.UseCount: return keyForArmchairKeyType(ArmchairKey.UseCount) case AppiraterKey.SignificantEventCount: return keyForArmchairKeyType(ArmchairKey.SignificantEventCount) case AppiraterKey.CurrentVersion: return keyForArmchairKeyType(ArmchairKey.CurrentVersion) case AppiraterKey.RatedCurrentVersion: return keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion) case AppiraterKey.DeclinedToRate: return keyForArmchairKeyType(ArmchairKey.DeclinedToRate) case AppiraterKey.ReminderRequestDate: return keyForArmchairKeyType(ArmchairKey.ReminderRequestDate) case AppiraterKey.RatedAnyVersion: return keyForArmchairKeyType(ArmchairKey.RatedAnyVersion) default: return "" } } private func migrateAppiraterKeysIfNecessary() { let appiraterAlreadyCompletedKey: NSString = keyForArmchairKeyType(.AppiraterMigrationCompleted) as NSString let appiraterMigrationAlreadyCompleted = userDefaultsObject?.boolForKey(appiraterAlreadyCompletedKey as String) if let completed = appiraterMigrationAlreadyCompleted { if completed { return } } let oldKeys: [String] = [AppiraterKey.FirstUseDate, AppiraterKey.UseCount, AppiraterKey.SignificantEventCount, AppiraterKey.CurrentVersion, AppiraterKey.RatedCurrentVersion, AppiraterKey.RatedAnyVersion, AppiraterKey.DeclinedToRate, AppiraterKey.ReminderRequestDate] for oldKey in oldKeys { let oldValue: NSObject? = userDefaultsObject?.objectForKey(oldKey) as? NSObject if let val = oldValue { let newKey = armchairKeyForAppiraterKey(oldKey) userDefaultsObject?.setObject(val, forKey: newKey) userDefaultsObject?.removeObjectForKey(oldKey) } } userDefaultsObject?.setObject(NSNumber(value: true), forKey: appiraterAlreadyCompletedKey as String) userDefaultsObject?.synchronize() } // This only supports the default UAAppReviewManager keys. If you customized them, you will have to manually migrate your values over. private func migrateUAAppReviewManagerKeysIfNecessary() { let appReviewManagerAlreadyCompletedKey: NSString = keyForArmchairKeyType(.UAAppReviewManagerMigrationCompleted) as NSString let appReviewManagerMigrationAlreadyCompleted = userDefaultsObject?.boolForKey(appReviewManagerAlreadyCompletedKey as String) if let completed = appReviewManagerMigrationAlreadyCompleted { if completed { return } } // By default, UAAppReviewManager keys are in the format <appID>_UAAppReviewManagerKey<keyType> let oldKeys: [String:ArmchairKey] = ["\(appID)_UAAppReviewManagerKeyFirstUseDate" : ArmchairKey.FirstUseDate, "\(appID)_UAAppReviewManagerKeyUseCount" : ArmchairKey.UseCount, "\(appID)_UAAppReviewManagerKeySignificantEventCount" : ArmchairKey.SignificantEventCount, "\(appID)_UAAppReviewManagerKeyCurrentVersion" : ArmchairKey.CurrentVersion, "\(appID)_UAAppReviewManagerKeyRatedCurrentVersion" : ArmchairKey.RatedCurrentVersion, "\(appID)_UAAppReviewManagerKeyDeclinedToRate" : ArmchairKey.DeclinedToRate, "\(appID)_UAAppReviewManagerKeyReminderRequestDate" : ArmchairKey.ReminderRequestDate, "\(appID)_UAAppReviewManagerKeyPreviousVersion" : ArmchairKey.PreviousVersion, "\(appID)_UAAppReviewManagerKeyPreviousVersionRated" : ArmchairKey.PreviousVersionRated, "\(appID)_UAAppReviewManagerKeyPreviousVersionDeclinedToRate" : ArmchairKey.PreviousVersionDeclinedToRate, "\(appID)_UAAppReviewManagerKeyRatedAnyVersion" : ArmchairKey.RatedAnyVersion] for (oldKey, newKeyType) in oldKeys { let oldValue: NSObject? = userDefaultsObject?.objectForKey(oldKey) as? NSObject if let val = oldValue { userDefaultsObject?.setObject(val, forKey: keyForArmchairKeyType(newKeyType)) userDefaultsObject?.removeObjectForKey(oldKey) } } userDefaultsObject?.setObject(NSNumber(value: true), forKey: appReviewManagerAlreadyCompletedKey as String) userDefaultsObject?.synchronize() } private func migrateKeysIfNecessary() { migrateAppiraterKeysIfNecessary() migrateUAAppReviewManagerKeysIfNecessary() } // MARK: - // MARK: Internet Connectivity private func connectedToNetwork() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { SCNetworkReachabilityCreateWithAddress(nil, $0) } }) else { return false } var flags : SCNetworkReachabilityFlags = [] if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) { return false } let isReachable = flags.contains(.reachable) let needsConnection = flags.contains(.connectionRequired) return (isReachable && !needsConnection) } // MARK: - // MARK: PRIVATE Misc Helpers private func bundle() -> Bundle? { var bundle: Bundle? = nil if useMainAppBundleForLocalizations { bundle = Bundle.main } else { let armchairBundleURL: URL? = Bundle.main.url(forResource: "Armchair", withExtension: "bundle") if let url = armchairBundleURL { bundle = Bundle(url: url) } else { bundle = Bundle(for: type(of: self)) } } return bundle } #if os(iOS) private static func topMostViewController(_ controller: UIViewController?) -> UIViewController? { var isPresenting: Bool = false var topController: UIViewController? = controller repeat { // this path is called only on iOS 6+, so -presentedViewController is fine here. if let controller = topController { if let presented = controller.presentedViewController { isPresenting = true topController = presented } else { isPresenting = false } } } while isPresenting return topController } private static func getRootViewController() -> UIViewController? { if var window = UIApplication.shared.keyWindow { if window.windowLevel != UIWindowLevelNormal { let windows: NSArray = UIApplication.shared.windows as NSArray for candidateWindow in windows { if let candidateWindow = candidateWindow as? UIWindow { if candidateWindow.windowLevel == UIWindowLevelNormal { window = candidateWindow break } } } } return iterateSubViewsForViewController(window) } return nil } private static func iterateSubViewsForViewController(_ parentView: UIView) -> UIViewController? { for subView in parentView.subviews { if let responder = subView.next { if responder.isKind(of: UIViewController.self) { return topMostViewController(responder as? UIViewController) } } if let found = iterateSubViewsForViewController(subView) { return found } } return nil } #endif private func hideRatingAlert() { if let alert = ratingAlert { debugLog("Hiding Alert") #if os(iOS) let isAlertVisible = alert.isViewLoaded && alert.view.window != nil if isAlertVisible { alert.dismiss(animated: false, completion: { self.dontRate() }) } #elseif os(OSX) if let window = NSApplication.shared.keyWindow { if let parent = window.sheetParent { parent.endSheet(window) } } #else #endif ratingAlert = nil } } fileprivate func defaultAffiliateCode() -> String { return "11l7j9" } fileprivate func defaultAffiliateCampaignCode() -> String { return "Armchair" } // MARK: - // MARK: Notification Handlers @objc public func appWillResignActive(_ notification: Notification) { debugLog("appWillResignActive:") hideRatingAlert() } @objc public func applicationDidFinishLaunching(_ notification: Notification) { DispatchQueue.global(qos: .background).async { self.debugLog("applicationDidFinishLaunching:") self.migrateKeysIfNecessary() self.incrementUseCount() } } @objc public func applicationWillEnterForeground(_ notification: Notification) { DispatchQueue.global(qos: .background).async { self.debugLog("applicationWillEnterForeground:") self.migrateKeysIfNecessary() self.incrementUseCount() } } // MARK: - // MARK: Singleton public class var defaultManager: Manager { assert(Armchair.appID != "", "Armchair.appID(appID: String) has to be the first Armchair call made.") struct Singleton { static let instance: Manager = Manager(appID: Armchair.appID) } return Singleton.instance } init(appID: String) { super.init() setupNotifications() } // MARK: Singleton Instance Setup fileprivate func setupNotifications() { #if os(iOS) NotificationCenter.default.addObserver(self, selector: #selector(Manager.appWillResignActive(_:)), name: NSNotification.Name.UIApplicationWillResignActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(Manager.applicationDidFinishLaunching(_:)), name: NSNotification.Name.UIApplicationDidFinishLaunching, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(Manager.applicationWillEnterForeground(_:)), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil) #elseif os(OSX) NotificationCenter.default.addObserver(self, selector: #selector(Manager.appWillResignActive(_:)), name: NSApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(Manager.applicationDidFinishLaunching(_:)), name: NSApplication.didFinishLaunchingNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(Manager.applicationWillEnterForeground(_:)), name: NSApplication.willBecomeActiveNotification, object: nil) #else #endif } // MARK: - // MARK: Printable override open var debugDescription: String { get { return "Armchair: appID=\(Armchair.appID)" } } // MARK: - // MARK: Debug let lockQueue = DispatchQueue(label: "com.armchair.lockqueue") public var logger: ArmchairLogger = { manager, log, file, function, line in if manager.debugEnabled { manager.lockQueue.sync(execute: { print("[Armchair] \(log)") }) } } fileprivate func debugLog(_ log: String, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) { logger(self, log, file, function, line) } }
mit
56b793ce4ba36e911c8509e1615e1896
42.622924
302
0.66108
5.20276
false
false
false
false
koehlermichael/focus
Blockzilla/WebCacheUtils.swift
1
1479
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation class WebCacheUtils { static func reset() { URLCache.shared.removeAllCachedResponses() HTTPCookieStorage.shared.removeCookies(since: Date.distantPast) guard let cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first, let cacheFiles = try? FileManager.default.contentsOfDirectory(atPath: cachesPath) else { return } for file in cacheFiles where file != "Snapshots" { let path = (cachesPath as NSString).appendingPathComponent(file) do { try FileManager.default.removeItem(atPath: path) } catch { NSLog("Found \(path) but was unable to remove it: \(error)") } } // Remove the in-memory history that WebKit maintains if let clazz = NSClassFromString("Web" + "History") as? NSObjectProtocol { if clazz.responds(to: Selector(("optional" + "Shared" + "History"))) { if let webHistory = clazz.perform(Selector(("optional" + "Shared" + "History"))) { let o = webHistory.takeUnretainedValue() _ = o.perform(Selector(("remove" + "All" + "Items"))) } } } } }
mpl-2.0
40b4c398f4c105a42d64b71e4a01df00
42.5
114
0.608519
4.755627
false
false
false
false
hengZhuo/DouYuZhiBo
swift-DYZB/swift-DYZB/Classes/Home/View/RecommendCycleView.swift
1
4241
// // RecommendCycleView.swift // swift-DYZB // // Created by chenrin on 2016/11/17. // Copyright © 2016年 zhuoheng. All rights reserved. // import UIKit private let kCollectViewCell = "cell" class RecommendCycleView: UIView { // MARK:- 控件属性 @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! var cycleTimer : Timer? var cyclesModel : [CycleModel]?{ didSet{ self.collectionView.reloadData() //设置pageControlelr个数 self.pageControl.numberOfPages = cyclesModel?.count ?? 0 //默认滚动到中间某一个位置 let indexPath = NSIndexPath(item: (cyclesModel?.count ?? 0) * 10, section: 0) collectionView.scrollToItem(at: indexPath as IndexPath, at: .left, animated: false) removeCycleTimer() //添加定时器 addCycleTimer() } } // MARK:- 系统回调 override func awakeFromNib() { super.awakeFromNib() //设置该控件不随着父控件拉伸和缩小 autoresizingMask = UIViewAutoresizing.init(rawValue: 0) //注册cell collectionView.register(UINib(nibName: "CycleCollectionCell", bundle: nil), forCellWithReuseIdentifier: kCollectViewCell) } override func layoutSubviews() { super.layoutSubviews() //设置collectionView的layout let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 collectionView.isPagingEnabled = true layout.scrollDirection = .horizontal //不显示滚动条 collectionView.showsHorizontalScrollIndicator = false } } // MARK:- 提供一个类方法快速创建View extension RecommendCycleView{ class func recomendCycleView() -> RecommendCycleView{ return Bundle.main.loadNibNamed("RecommendCycleView", owner: nil, options: nil)?.first as! RecommendCycleView } } // MARK:- UICollectionViewDataSource extension RecommendCycleView : UICollectionViewDataSource,UICollectionViewDelegate{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (cyclesModel?.count ?? 0) * 1000 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCollectViewCell, for: indexPath) as! CycleCollectionCell let cycle = cyclesModel?[indexPath.item % cyclesModel!.count] cell.cycleModel = cycle return cell } func scrollViewDidScroll(_ scrollView: UIScrollView) { //获取滚动的便宜量 let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5 //计算pageControl的currentIndex pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cyclesModel?.count ?? 1) } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { removeCycleTimer() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { addCycleTimer() } } // MARK:- 对定时器的操作 extension RecommendCycleView{ fileprivate func addCycleTimer(){ cycleTimer = Timer(timeInterval: 4.0, target: self, selector: #selector(sctollToNext), userInfo: nil, repeats: true) RunLoop.main.add(cycleTimer!, forMode: RunLoopMode.commonModes) } fileprivate func removeCycleTimer(){ //从运行循环中移除 cycleTimer?.invalidate() cycleTimer = nil } @objc fileprivate func sctollToNext() { //获取滚动的偏移量 let currentOffsetX = collectionView.contentOffset.x let offsetX = currentOffsetX + collectionView.bounds.width //滚动到该位置 collectionView.setContentOffset(CGPoint(x:offsetX,y:0), animated: true) } }
mit
f2a442b6cb2b760d8737fae4891298e8
30.193798
132
0.661531
5.31572
false
false
false
false
kimyoutora/RouterKit
RouterKit/Route.swift
1
1769
// // Route.swift // RouterKit // // Created by Kang Chen on 2/21/16. // // import Foundation /// A definable route in the format of scheme://path/to e.g. /// "app://users/A/profile". /// @see `router.addRoute` for more supported formats. public typealias Route = String extension Route { func extractSchemeAndPath() -> (scheme: String?, path: String) { let components = self.componentsSeparatedByString("://") let scheme = components.count > 1 ? components.first : nil let path = components.last! return (scheme, path) } } public typealias Path = String extension Path { func pathComponents() -> [RouteComponentType] { let components = self.tokenizePath() let pathComponents = components.map { (component) -> RouteComponentType in // TODO: handle regex components if component.hasPrefix(":") { return ParameterRouteComponent(rawComponent: component.substringWithRange(component.startIndex.advancedBy(1)..<component.endIndex)) } else { return StaticRouteComponent(rawComponent: component) } } return pathComponents } func tokenizePath() -> [String] { let withoutWhitespace = self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) let withoutBeginningTrailingDelimiters = withoutWhitespace.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "/")) let components = withoutBeginningTrailingDelimiters.componentsSeparatedByString("/") switch components.first { case .Some(""): // empty path case, just return an empty array return [] default: return components } } }
mit
ef8792527b13a3f51ed51e2176b575bd
33.019231
147
0.659695
5.039886
false
false
false
false
roshanman/FriendCircle
FriendCircle/Classes/Tools/Image+Extension.swift
1
1057
// // Image+Extension.swift // FriendCircle // // Created by zhangxiuming on 2017/09/26. // import Foundation fileprivate let bundle = Bundle(for: FCLikeView.self) fileprivate let bundleURL = bundle.url(forResource: "FriendCircle", withExtension: "bundle")! fileprivate let resourceBundle = Bundle(url: bundleURL)! extension UIImage { static let like = UIImage(named: "FCLike", in: resourceBundle, compatibleWith: nil)! static let moreOp = UIImage(named: "FCOperateMore", in: resourceBundle, compatibleWith: nil)! static let likeWhite = UIImage(named: "FCLikeWhite", in: resourceBundle, compatibleWith: nil)! static let commentWhite = UIImage(named: "FCCommentWhite", in: resourceBundle, compatibleWith: nil)! static let videoPlay = UIImage(named: "VideoPlay", in: resourceBundle, compatibleWith: nil)! static let defaultAvatar = UIImage(named: "defaultAvatar", in: resourceBundle, compatibleWith: nil)! static let imagePlaceHolder = UIImage(named: "imagePlaceHolder", in: resourceBundle, compatibleWith: nil)! }
mit
710c632f4026b85bc96580501d2c5f95
43.041667
110
0.743614
4.194444
false
false
false
false
milseman/swift
test/SILGen/multi_file.swift
13
3107
// RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/multi_file_helper.swift | %FileCheck %s func markUsed<T>(_ t: T) {} // CHECK-LABEL: sil hidden @_T010multi_file12rdar16016713{{[_0-9a-zA-Z]*}}F func rdar16016713(_ r: Range) { // CHECK: [[LIMIT:%[0-9]+]] = function_ref @_T010multi_file5RangeV5limitSifg : $@convention(method) (Range) -> Int // CHECK: {{%[0-9]+}} = apply [[LIMIT]]({{%[0-9]+}}) : $@convention(method) (Range) -> Int markUsed(r.limit) } // CHECK-LABEL: sil hidden @_T010multi_file26lazyPropertiesAreNotStored{{[_0-9a-zA-Z]*}}F func lazyPropertiesAreNotStored(_ container: LazyContainer) { var container = container // CHECK: {{%[0-9]+}} = function_ref @_T010multi_file13LazyContainerV7lazyVarSifg : $@convention(method) (@inout LazyContainer) -> Int markUsed(container.lazyVar) } // CHECK-LABEL: sil hidden @_T010multi_file29lazyRefPropertiesAreNotStored{{[_0-9a-zA-Z]*}}F func lazyRefPropertiesAreNotStored(_ container: LazyContainerClass) { // CHECK: bb0([[ARG:%.*]] : $LazyContainerClass): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: {{%[0-9]+}} = class_method [[BORROWED_ARG]] : $LazyContainerClass, #LazyContainerClass.lazyVar!getter.1 : (LazyContainerClass) -> () -> Int, $@convention(method) (@guaranteed LazyContainerClass) -> Int markUsed(container.lazyVar) } // CHECK-LABEL: sil hidden @_T010multi_file25finalVarsAreDevirtualizedyAA18FinalPropertyClassCF func finalVarsAreDevirtualized(_ obj: FinalPropertyClass) { // CHECK: bb0([[ARG:%.*]] : $FinalPropertyClass): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: ref_element_addr [[BORROWED_ARG]] : $FinalPropertyClass, #FinalPropertyClass.foo // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] markUsed(obj.foo) // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [[BORROWED_ARG]] : $FinalPropertyClass, #FinalPropertyClass.bar!getter.1 markUsed(obj.bar) } // rdar://18448869 // CHECK-LABEL: sil hidden @_T010multi_file34finalVarsDontNeedMaterializeForSetyAA27ObservingPropertyFinalClassCF func finalVarsDontNeedMaterializeForSet(_ obj: ObservingPropertyFinalClass) { obj.foo += 1 // CHECK: function_ref @_T010multi_file27ObservingPropertyFinalClassC3fooSifg // CHECK: function_ref @_T010multi_file27ObservingPropertyFinalClassC3fooSifs } // rdar://18503960 // Ensure that we type-check the materializeForSet accessor from the protocol. class HasComputedProperty: ProtocolWithProperty { var foo: Int { get { return 1 } set {} } } // CHECK-LABEL: sil hidden [transparent] @_T010multi_file19HasComputedPropertyC3fooSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasComputedProperty) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK-LABEL: sil private [transparent] [thunk] @_T010multi_file19HasComputedPropertyCAA012ProtocolWithE0A2aDP3fooSifmTW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasComputedProperty) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
apache-2.0
b3e07a67137948e6b78139280a62f4f3
54.482143
292
0.727712
3.518686
false
false
false
false
vasili-v/themis
vendor/github.com/apache/thrift/lib/swift/Sources/TFileHandleTransport.swift
21
1632
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 public class TFileHandleTransport: TTransport { var inputFileHandle: FileHandle var outputFileHandle: FileHandle public init(inputFileHandle: FileHandle, outputFileHandle: FileHandle) { self.inputFileHandle = inputFileHandle self.outputFileHandle = outputFileHandle } public convenience init(fileHandle: FileHandle) { self.init(inputFileHandle: fileHandle, outputFileHandle: fileHandle) } public func read(size: Int) throws -> Data { var data = Data() while data.count < size { let read = inputFileHandle.readData(ofLength: size - data.count) data.append(read) if read.count == 0 { break } } return data } public func write(data: Data) throws { outputFileHandle.write(data) } public func flush() throws { return } }
apache-2.0
965885e52673676bcec9e48fddaf3707
28.142857
74
0.726103
4.387097
false
false
false
false
brunophilipe/tune
tune/Player Interfaces/MediaPlayer.swift
1
2078
// // MediaPlayer.swift // tune // // Created by Bruno Philipe on 1/5/17. // Copyright © 2017 Bruno Philipe. All rights reserved. // import Foundation protocol MediaPlayer: MediaSearchable { /// Internal identification of this media player, such as "itunes" var playerId: String { get } // MARK: - Playback status information var currentTrack: MediaPlayerItem? { get } var currentPlaylist: MediaPlayerPlaylist? { get } var currentPlaybackInfo: MediaPlayerPlaybackInfo? { get } // MARK: - Playback control functions func playPause() func pause() func stop() func nextTrack() func previousTrack() // MARK: - Media control functions func play(track: MediaPlayerItem) } struct MediaPlayerPlaybackInfo { let progress: Double let status: PlayerStatus let shuffleOn: Bool let repeatOn: Bool enum PlayerStatus { case stopped case playing case paused // case fastForwarding // case rewinding } } protocol MediaPlayerItem { var kind: MediaPlayerItemKind { get } var name: String { get } var artist: String { get } var album: String { get } var year: String? { get } var time: Double? { get } var index: Int? { get } func compare(_ otherItem: MediaPlayerItem?) -> Bool } enum MediaPlayerItemKind { case track case album } protocol MediaPlayerPlaylist { var count: Int { get } var name: String? { get } var time: Double? { get } func item(at index: Int) -> MediaPlayerItem? func compare(_ otherPlaylist: MediaPlayerPlaylist?) -> Bool } // This is a bit of a hack, because we can't force the protocol to inherit from Equatable, // but the Swift compiler is smart enough to let the operators be used! Yay! func ==(_ lhi: MediaPlayerItem?, _ rhi: MediaPlayerItem?) -> Bool { return lhi?.compare(rhi) ?? false } func !=(_ lhi: MediaPlayerItem?, _ rhi: MediaPlayerItem?) -> Bool { return !(lhi == rhi) } func ==(_ lhp: MediaPlayerPlaylist?, _ rhp: MediaPlayerPlaylist?) -> Bool { return lhp?.compare(rhp) ?? false } func !=(_ lhp: MediaPlayerPlaylist?, _ rhp: MediaPlayerPlaylist?) -> Bool { return !(lhp == rhp) }
gpl-3.0
a2c14d7841a628473ebd47109e9f9e54
18.780952
90
0.698122
3.404918
false
false
false
false
ngageoint/mage-ios
MageTests/Mocks/MockGeometryEditCoordinator.swift
1
1031
// // MockGeometryEditCoordinator.swift // MAGETests // // Created by Daniel Barela on 6/10/21. // Copyright © 2021 National Geospatial Intelligence Agency. All rights reserved. // import Foundation import sf_ios class MockGeometryEditCoordinator : GeometryEditCoordinator { var _currentGeometry: SFGeometry! = SFPoint(x: 1.0, andY: 1.0); var _fieldName: String! = "Field Name" var _pinImage: UIImage! = UIImage(named: "observations") override func start() { } override func update(_ geometry: SFGeometry!) { _currentGeometry = geometry; } override var currentGeometry: SFGeometry! { get { return _currentGeometry } set { _currentGeometry = newValue } } override var pinImage: UIImage! { get { return _pinImage } set { _pinImage = newValue } } override func fieldName() -> String! { return _fieldName } }
apache-2.0
70b96ab814cbb686bcf522179b36d23d
20.914894
82
0.578641
4.618834
false
false
false
false
domenicosolazzo/practice-swift
Networking/Downloading synchronously with NSURLConnection/Downloading synchronously with NSURLConnection/ViewController.swift
1
1399
// // ViewController.swift // Downloading synchronously with NSURLConnection // // Created by Domenico Solazzo on 16/05/15. // License MIT // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() /* You can have a custom URL here */ let urlAsString = "http://www.domenicosolazzo.com" let url = URL(string: urlAsString) let urlRequest = URLRequest(url: url!) var response: URLResponse? var error: NSError? print("Firing synchronous url connection...") let dispatchQueue = DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default) dispatchQueue.async(execute: { /* Get the data for our URL, synchronously */ let data = try NSURLConnection.sendSynchronousRequest(urlRequest, returning: &response) if data != nil && error == nil{ print("\(data.count) bytes of data was returned") } else if data.count == 0 && error == nil{ print("No data was returned") } else if error != nil{ print("Error happened = \(error)"); } }) print("We are done") } }
mit
ee2ced030496bad25a026b6a7a6ae34e
27.55102
83
0.530379
5.422481
false
false
false
false
CaiMiao/CGSSGuide
DereGuide/Unit/Information/View/UnitInformationSkillListCell.swift
1
2145
// // UnitInformationSkillListCell.swift // DereGuide // // Created by zzk on 2017/5/20. // Copyright © 2017年 zzk. All rights reserved. // import UIKit import SnapKit class UnitInformationSkillListCell: UITableViewCell { var leftLabel: UILabel! var skillListGrid: GridLabel! override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) leftLabel = UILabel() leftLabel.text = NSLocalizedString("特技列表", comment: "队伍详情页面") leftLabel.font = UIFont.systemFont(ofSize: 16) leftLabel.textAlignment = .left skillListGrid = GridLabel.init(rows: 5, columns: 1, textAligment: .left) skillListGrid.distribution = .fill skillListGrid.numberOfLines = 0 contentView.addSubview(leftLabel) contentView.addSubview(skillListGrid) leftLabel.snp.makeConstraints { (make) in make.top.equalTo(10) make.left.equalTo(10) } skillListGrid.snp.makeConstraints { (make) in make.top.equalTo(leftLabel.snp.bottom).offset(5) make.left.equalTo(10) make.right.equalTo(-10) make.bottom.equalTo(-10) } selectionStyle = .none } func setup(with unit: Unit) { var skillListStrings = [[String]]() let skillListColor = [[UIColor]].init(repeating: [UIColor.darkGray], count: 5) for i in 0...4 { if let skill = unit[i].card?.skill { let str = "\(skill.skillName!): Lv.\(unit[i].skillLevel)\n\(skill.getLocalizedExplainByLevel(Int(unit[i].skillLevel)))" let arr = [str] skillListStrings.append(arr) } else { skillListStrings.append([""]) } } skillListGrid.setContents(skillListStrings) skillListGrid.setColors(skillListColor) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
2b889afc7f7427425e8d1d3b10d92bf7
29.753623
135
0.596607
4.384298
false
false
false
false
sschiau/swift
stdlib/public/Darwin/Accelerate/vDSP_SingleVectorOperations.swift
8
34786
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // // vDSP Extrema // //===----------------------------------------------------------------------===// @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension vDSP { // MARK: Elementwise minimum /// Returns an array containing the lesser of the corresponding values in `vectorA` and `vectorB`, single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` @inlinable public static func minimum<U>(_ vectorA: U, _ vectorB: U) -> [Float] where U: AccelerateBuffer, U.Element == Float { precondition(vectorA.count == vectorB.count) let result = Array<Float>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in minimum(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the lesser of the corresponding values in `vectorA` and `vectorB`, single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Parameter result: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` @inlinable public static func minimum<U, V>(_ vectorA: U, _ vectorB: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Float, V.Element == Float { let n = vDSP_Length(min(vectorA.count, vectorB.count, result.count)) result.withUnsafeMutableBufferPointer { r in vectorA.withUnsafeBufferPointer { a in vectorB.withUnsafeBufferPointer { b in vDSP_vmin(a.baseAddress!, 1, b.baseAddress!, 1, r.baseAddress!, 1, n) } } } } /// Returns an array containing the lesser of the corresponding values in `vectorA` and `vectorB`, double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` @inlinable public static func minimum<U>(_ vectorA: U, _ vectorB: U) -> [Double] where U: AccelerateBuffer, U.Element == Double { precondition(vectorA.count == vectorB.count) let result = Array<Double>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in minimum(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the lesser of the corresponding values in `vectorA` and `vectorB`, double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Parameter result: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` @inlinable public static func minimum<U, V>(_ vectorA: U, _ vectorB: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Double, V.Element == Double { let n = vDSP_Length(min(vectorA.count, vectorB.count, result.count)) result.withUnsafeMutableBufferPointer { r in vectorA.withUnsafeBufferPointer { a in vectorB.withUnsafeBufferPointer { b in vDSP_vminD(a.baseAddress!, 1, b.baseAddress!, 1, r.baseAddress!, 1, n) } } } } // MARK: Elementwise maximum /// Returns an array containing the greater of the corresponding values in `vectorA` and `vectorB`, single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] > b[i] ? a[i] : b[i]` /// - Parameter vectorB: the `b` in `c[i] = a[i] > b[i] ? a[i] : b[i]` /// - Returns: the `c` in `c[i] = a[i] > b[i] ? a[i] : b[i]` @inlinable public static func maximum<U>(_ vectorA: U, _ vectorB: U) -> [Float] where U: AccelerateBuffer, U.Element == Float { precondition(vectorA.count == vectorB.count) let result = Array<Float>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in maximum(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the greater of the corresponding values in `vectorA` and `vectorB`, single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] > b[i] ? a[i] : b[i]` /// - Parameter vectorB: the `b` in `c[i] = a[i] > b[i] ? a[i] : b[i]` /// - Parameter result: the `c` in `c[i] = a[i] > b[i] ? a[i] : b[i]` @inlinable public static func maximum<U, V>(_ vectorA: U, _ vectorB: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Float, V.Element == Float { let n = vDSP_Length(min(vectorA.count, vectorB.count, result.count)) result.withUnsafeMutableBufferPointer { r in vectorA.withUnsafeBufferPointer { a in vectorB.withUnsafeBufferPointer { b in vDSP_vmax(a.baseAddress!, 1, b.baseAddress!, 1, r.baseAddress!, 1, n) } } } } /// Returns an array containing the greater of the corresponding values in `vectorA` and `vectorB`, double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] > b[i] ? a[i] : b[i]` /// - Parameter vectorB: the `b` in `c[i] = a[i] > b[i] ? a[i] : b[i]` /// - Returns: the `c` in `c[i] = `c[i] = a[i] > b[i] ? a[i] : b[i]` @inlinable public static func maximum<U>(_ vectorA: U, _ vectorB: U) -> [Double] where U: AccelerateBuffer, U.Element == Double { precondition(vectorA.count == vectorB.count) let result = Array<Double>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in maximum(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the greater of the corresponding values in `vectorA` and `vectorB`, double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] > b[i] ? a[i] : b[i]` /// - Parameter vectorB: the `b` in `c[i] = a[i] > b[i] ? a[i] : b[i]` /// - Parameter result: the `c` in `c[i] = a[i] > b[i] ? a[i] : b[i]` @inlinable public static func maximum<U, V>(_ vectorA: U, _ vectorB: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Double, V.Element == Double { let n = vDSP_Length(min(vectorA.count, vectorB.count, result.count)) result.withUnsafeMutableBufferPointer { r in vectorA.withUnsafeBufferPointer { a in vectorB.withUnsafeBufferPointer { b in vDSP_vmaxD(a.baseAddress!, 1, b.baseAddress!, 1, r.baseAddress!, 1, n) } } } } } //===----------------------------------------------------------------------===// // // vDSP Absolute and Negation // //===----------------------------------------------------------------------===// @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension vDSP { /// Returns an array containing the absolute values of `vector`, /// single-precision. /// /// - Parameter vector: The input vector. /// - Parameter result: The output vector. @inlinable public static func absolute<U>(_ vector: U) -> [Float] where U: AccelerateBuffer, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in absolute(vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the absolute values of `vector`, /// single-precision. /// /// - Parameter vector: The input vector. /// - Parameter result: The output vector. @inlinable public static func absolute<U, V>(_ vector: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Float, V.Element == Float { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in vDSP_vabs(v.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } /// Returns an array containing the absolute values of `vector`, /// double-precision. /// /// - Parameter vector: The input vector. /// - Parameter result: The output vector. @inlinable public static func absolute<U>(_ vector: U) -> [Double] where U: AccelerateBuffer, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in absolute(vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the absolute values of `vector`, /// double-precision. /// /// - Parameter vector: The input vector. /// - Parameter result: The output vector. @inlinable public static func absolute<U, V>(_ vector: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Double, V.Element == Double { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in vDSP_vabsD(v.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } /// Returns an array containing the negative absolute values of `vector`, /// single-precision. /// /// - Parameter vector: The input vector. /// - Parameter result: The output vector. @inlinable public static func negativeAbsolute<U>(_ vector: U) -> [Float] where U: AccelerateBuffer, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in negativeAbsolute(vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the negative absolute values of `vector`, /// single-precision. /// /// - Parameter vector: The input vector. /// - Parameter result: The output vector. @inlinable public static func negativeAbsolute<U, V>(_ vector: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Float, V.Element == Float { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in vDSP_vnabs(v.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } /// Returns an array containing the negative absolute values of `vector`, /// double-precision. /// /// - Parameter vector: The input vector. /// - Parameter result: The output vector. @inlinable public static func negativeAbsolute<U>(_ vector: U) -> [Double] where U: AccelerateBuffer, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in negativeAbsolute(vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the negative absolute values of `vector`, /// double-precision. /// /// - Parameter vector: The input vector. /// - Parameter result: The output vector. @inlinable public static func negativeAbsolute<U, V>(_ vector: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Double, V.Element == Double { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in vDSP_vnabsD(v.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } /// Returns an array containing the negative values of `vector`, /// single-precision. /// /// - Parameter vector: The input vector. /// - Parameter result: The output vector. @inlinable public static func negative<U>(_ vector: U) -> [Float] where U: AccelerateBuffer, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in negative(vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the negative values of `vector`, /// single-precision. /// /// - Parameter vector: The input vector. /// - Parameter result: The output vector. @inlinable public static func negative<U, V>(_ vector: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Float, V.Element == Float { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in vDSP_vneg(v.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } /// Returns an array containing the negative values of `vector`, /// double-precision. /// /// - Parameter vector: The input vector. /// - Parameter result: The output vector. @inlinable public static func negative<U>(_ vector: U) -> [Double] where U: AccelerateBuffer, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in negative(vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the negative values of `vector`, /// double-precision. /// /// - Parameter vector: The input vector. /// - Parameter result: The output vector. @inlinable public static func negative<U, V>(_ vector: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Double, V.Element == Double { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in vDSP_vnegD(v.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } //===----------------------------------------------------------------------===// // // vDSP In-place reversing and sorting // //===----------------------------------------------------------------------===// @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension vDSP { // MARK: Reversing /// Reverses an array of single-precision values in-place. /// /// - Parameter vector: The array to reverse. @inlinable public static func reverse<V>(_ vector: inout V) where V: AccelerateMutableBuffer, V.Element == Float { let n = vDSP_Length(vector.count) vector.withUnsafeMutableBufferPointer { v in vDSP_vrvrs(v.baseAddress!, 1, n) } } /// Reverses an array of double-precision values in-place. /// /// - Parameter vector: The array to reverse. @inlinable public static func reverse<V>(_ vector: inout V) where V: AccelerateMutableBuffer, V.Element == Double { let n = vDSP_Length(vector.count) vector.withUnsafeMutableBufferPointer { v in vDSP_vrvrsD(v.baseAddress!, 1, n) } } // MARK: Sorting public enum SortOrder: Int32 { case ascending = 1 case descending = -1 } /// Sorts an array of single-precision values in-place. /// /// - Parameter vector: The array to sort. /// - Parameter sortOrder: The sort direction. @inlinable public static func sort<V>(_ vector: inout V, sortOrder: SortOrder) where V: AccelerateMutableBuffer, V.Element == Float { let n = vDSP_Length(vector.count) vector.withUnsafeMutableBufferPointer { v in vDSP_vsort(v.baseAddress!, n, sortOrder.rawValue) } } /// Sorts an array of double-precision values in-place. /// /// - Parameter vector: The array to sort. /// - Parameter sortOrder: The sort direction. @inlinable public static func sort<V>(_ vector: inout V, sortOrder: SortOrder) where V: AccelerateMutableBuffer, V.Element == Double { let n = vDSP_Length(vector.count) vector.withUnsafeMutableBufferPointer { v in vDSP_vsortD(v.baseAddress!, n, sortOrder.rawValue) } } } //===----------------------------------------------------------------------===// // // vDSP Single vector arithmetic // //===----------------------------------------------------------------------===// @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension vDSP { // MARK: Square /// Returns an array containing the square of each element in `vector`, single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` @inlinable public static func square<U>(_ vector: U) -> [Float] where U: AccelerateBuffer, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in square(vector, result: &buffer) initializedCount = vector.count } return result } /// Calculates the square of each element in `vector`, writing the result to `result`; single-precision. /// /// - Parameter _ vector: Input values. /// - Parameter result: Output values. @inlinable public static func square<U, V>(_ vector: U, result: inout V) where U : AccelerateBuffer, V : AccelerateMutableBuffer, U.Element == Float, V.Element == Float { precondition(vector.count == result.count) let n = vDSP_Length(vector.count) result.withUnsafeMutableBufferPointer { dest in vector.withUnsafeBufferPointer { src in vDSP_vsq(src.baseAddress!, 1, dest.baseAddress!, 1, n) } } } /// Returns an array containing the square of each element in `vector`, double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` @inlinable public static func square<U>(_ vector: U) -> [Double] where U: AccelerateBuffer, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in square(vector, result: &buffer) initializedCount = vector.count } return result } /// Calculates the square of each element in `vector`, writing the result to `result`; double-precision. /// /// - Parameter _ vector: Input values. /// - Parameter result: Output values. @inlinable public static func square<U, V>(_ vector: U, result: inout V) where U : AccelerateBuffer, V : AccelerateMutableBuffer, U.Element == Double, V.Element == Double { precondition(vector.count == result.count) let n = vDSP_Length(vector.count) result.withUnsafeMutableBufferPointer { dest in vector.withUnsafeBufferPointer { src in vDSP_vsqD(src.baseAddress!, 1, dest.baseAddress!, 1, n) } } } // MARK: Signed Square /// Returns an array containing the signed square of each element in `vector`, single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` @inlinable public static func signedSquare<U>(_ vector: U) -> [Float] where U: AccelerateBuffer, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in signedSquare(vector, result: &buffer) initializedCount = vector.count } return result } /// Calculates the signed square of each element in `vector`, writing the result to `result`; single-precision. /// /// - Parameter _ vector: Input values. /// - Parameter result: Output values. @inlinable public static func signedSquare<U, V>(_ vector: U, result: inout V) where U : AccelerateBuffer, V : AccelerateMutableBuffer, U.Element == Float, V.Element == Float { precondition(vector.count == result.count) let n = vDSP_Length(vector.count) result.withUnsafeMutableBufferPointer { dest in vector.withUnsafeBufferPointer { src in vDSP_vssq(src.baseAddress!, 1, dest.baseAddress!, 1, n) } } } /// Returns an array containing the signed square of each element in `vector`, double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` @inlinable public static func signedSquare<U>(_ vector: U) -> [Double] where U: AccelerateBuffer, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in signedSquare(vector, result: &buffer) initializedCount = vector.count } return result } /// Calculates the signed square of each element in `vector`, writing the result to `result`; double-precision. /// /// - Parameter _ vector: Input values. /// - Parameter result: Output values. @inlinable public static func signedSquare<U, V>(_ vector: U, result: inout V) where U : AccelerateBuffer, V : AccelerateMutableBuffer, U.Element == Double, V.Element == Double { precondition(vector.count == result.count) let n = vDSP_Length(vector.count) result.withUnsafeMutableBufferPointer { dest in vector.withUnsafeBufferPointer { src in vDSP_vssqD(src.baseAddress!, 1, dest.baseAddress!, 1, n) } } } // MARK: Truncate to Fraction /// Returns an array containing each element in `vector` truncated to fraction, single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` @inlinable public static func trunc<U>(_ vector: U) -> [Float] where U: AccelerateBuffer, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in trunc(vector, result: &buffer) initializedCount = vector.count } return result } /// Truncates to fraction each element in `vector`, writing the result to `result`; single-precision. /// /// - Parameter _ vector: Input values. /// - Parameter result: Output values. @inlinable public static func trunc<U, V>(_ vector: U, result: inout V) where U : AccelerateBuffer, V : AccelerateMutableBuffer, U.Element == Float, V.Element == Float { precondition(vector.count == result.count) let n = vDSP_Length(vector.count) result.withUnsafeMutableBufferPointer { dest in vector.withUnsafeBufferPointer { src in vDSP_vfrac(src.baseAddress!, 1, dest.baseAddress!, 1, n) } } } /// Returns an array containing each element in `vector` truncated to fraction, double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` /// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` @inlinable public static func trunc<U>(_ vector: U) -> [Double] where U: AccelerateBuffer, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in trunc(vector, result: &buffer) initializedCount = vector.count } return result } /// Truncates to fraction each element in `vector`, writing the result to `result`; double-precision. /// /// - Parameter _ vector: Input values. /// - Parameter result: Output values. @inlinable public static func trunc<U, V>(_ vector: U, result: inout V) where U : AccelerateBuffer, V : AccelerateMutableBuffer, U.Element == Double, V.Element == Double { precondition(vector.count == result.count) let n = vDSP_Length(vector.count) result.withUnsafeMutableBufferPointer { dest in vector.withUnsafeBufferPointer { src in vDSP_vfracD(src.baseAddress!, 1, dest.baseAddress!, 1, n) } } } // Zero crossing /// Returns the number of zero crossings in `vector`; single-precision. /// /// - Parameter _ vector: Input values. /// - Returns: The total number of transitions from positive to negative values and from negative to positive values. @inlinable public static func countZeroCrossings<U>(_ vector: U) -> UInt where U : AccelerateBuffer, U.Element == Float { let n = vDSP_Length(vector.count) var crossingCount: vDSP_Length = 0 var lastCrossingIndex: vDSP_Length = 0 vector.withUnsafeBufferPointer { src in vDSP_nzcros(src.baseAddress!, 1, n, &lastCrossingIndex, &crossingCount, n) } return crossingCount } /// Returns the number of zero crossings in `vector`; double-precision. /// /// - Parameter _ vector: Input values. /// - Returns: The total number of transitions from positive to negative values and from negative to positive values. @inlinable public static func countZeroCrossings<U>(_ vector: U) -> UInt where U : AccelerateBuffer, U.Element == Double { let n = vDSP_Length(vector.count) var crossingCount: vDSP_Length = 0 var lastCrossingIndex: vDSP_Length = 0 vector.withUnsafeBufferPointer { src in vDSP_nzcrosD(src.baseAddress!, 1, n, &lastCrossingIndex, &crossingCount, n) } return crossingCount } }
apache-2.0
6001698bec30e77932037d05bc9d4759
34.137374
121
0.467343
5.027605
false
false
false
false
vectorform/Texty
Source/TextyTextView.swift
1
4244
// Copyright (c) 2018 Vectorform, LLC // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. import Foundation import UIKit open class TextyTextView: UITextView, TextStyleDelegate { public var style: TextStyle { willSet { self.style.delegate = nil } didSet { self.style = TextStyle(with: self.style) self.style.delegate = self self.redrawText() } } // The purpose of this variable is to keep a reference to the original text, including all contained tags. Once a // style is applied to a string, all tags are stripped and lost forever. private var taggedText: String? open override var font: UIFont? { get { return self.style.font } set { self.style.font = newValue } } open override var text: String? { get { return self.attributedText?.string } set { self.taggedText = newValue self.redrawText() } } open override var textAlignment: NSTextAlignment { get { return self.style.paragraphStyle!.alignment } set { let paragraphStyle: NSMutableParagraphStyle = style.paragraphStyle!.mutableCopy() as! NSMutableParagraphStyle paragraphStyle.alignment = newValue style.paragraphStyle = paragraphStyle } } open override var textColor: UIColor! { get { return self.style.foregroundColor } set { self.style.foregroundColor = newValue } } public convenience init() { self.init(style: TextStyle()) } public required init(style: TextStyle, frame: CGRect = .zero) { self.style = style super.init(frame: frame, textContainer: nil) self.isEditable = false // Ensure didSet is called in self.style ({ self.style = style })() self.loadDefaults() } public required init?(coder aDecoder: NSCoder) { fatalError("Interface Builder is not supported") } internal func didUpdate(style: TextStyle) { self.redrawText() } private func loadDefaults() { if self.style.font == nil { self.style.font = super.font } if self.style.foregroundColor == nil { self.style.foregroundColor = super.textColor } if self.style.paragraphStyle == nil { let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .natural paragraphStyle.lineBreakMode = .byWordWrapping self.style.paragraphStyle = paragraphStyle } } private func redrawText() { self.attributedText = style.attributedString(with: self.taggedText) } }
bsd-3-clause
f634216424ad71eb20bca27183752e54
36.22807
121
0.667059
5.064439
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/GSR-Booking/Model/GSRRoom.swift
1
2461
// // GSRRoom.swift // PennMobile // // Created by Zhilei Zheng on 2/2/18. // Copyright © 2018 PennLabs. All rights reserved. // import Foundation struct GSRRoom: Codable { let roomName: String let id: Int var availability: [GSRTimeSlot] } extension Array where Element == GSRRoom { func getMinMaxDates() -> (Date?, Date?) { var min: Date? var max: Date? for room in self { if let firstStartTime = room.availability.first?.startTime, min == nil || (firstStartTime < min!) { min = firstStartTime } if let lastEndTime = room.availability.last?.endTime, max == nil || (lastEndTime > max!) { max = lastEndTime } } return (min, max) } } extension GSRRoom { func addMissingTimeslots(minDate: Date, maxDate: Date) -> [GSRTimeSlot] { var newTimes = [GSRTimeSlot]() // Fill in early slots if let earliestTime = availability.first { var currTime = earliestTime let minTime = minDate.add(minutes: 30) while currTime.startTime >= minTime { let newTimeSlot = GSRTimeSlot(startTime: currTime.startTime.add(minutes: -30), endTime: currTime.startTime, isAvailable: false) newTimes.insert(newTimeSlot, at: 0) currTime = newTimeSlot } } // Fill in middle slots for i in 0..<availability.count { var prevTime = availability[i] newTimes.append(prevTime) if i == availability.count - 1 { break } let nextTime = availability[i+1] while prevTime.endTime < nextTime.startTime { let newTimeSlot = GSRTimeSlot(startTime: prevTime.endTime, endTime: prevTime.endTime.add(minutes: 30), isAvailable: false) newTimes.append(newTimeSlot) prevTime = newTimeSlot } } // Fill in early slots if let latestTime = availability.last { var currTime = latestTime let maxTime = maxDate.add(minutes: -30) while currTime.endTime <= maxTime { let newTimeSlot = GSRTimeSlot(startTime: currTime.endTime, endTime: currTime.endTime.add(minutes: 30), isAvailable: false) newTimes.append(newTimeSlot) currTime = newTimeSlot } } return newTimes } }
mit
e1a873804ba9f2f6c856a768e37cfdb3
30.948052
143
0.576016
4.416517
false
false
false
false
PJayRushton/stats
Stats/ContactsHelper.swift
1
4858
// // ContactsHelper.swift // Stats // // Created by Parker Rushton on 6/3/17. // Copyright © 2017 AppsByPJ. All rights reserved. // import Foundation import ContactsUI import Contacts class ContactsHelper: NSObject { // MARK: - Types enum ContactsError: Error { case formatting } // MARK: - Init fileprivate let viewController: UIViewController init(viewController: UIViewController) { self.viewController = viewController } fileprivate let store = CNContactStore() // MARK: - Public var contactSelected: ((Result<(String, String)>) -> Void) = { _ in } func addressButtonPressed() { presentContactPicker() } func presentErrorAlert() { let alert = UIAlertController(title: "This is awkward. . . 😅", message: "Something went wrong when selecting your contact", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Its OK 😞", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Try again", style: .default, handler: { _ in self.presentContactPicker() })) viewController.present(alert, animated: true, completion: nil) } } // MARK: - Private extension ContactsHelper { fileprivate var contactKeys: [String] { return [CNContactPhoneNumbersKey] } fileprivate func presentContactPicker() { requestAccess { [unowned self] accessGranted in DispatchQueue.main.async { if accessGranted { self.presentContactPickerViewController() } else { self.presentPermissionErrorAlert() } } } } fileprivate func requestAccess(completion: ((Bool) -> Void)? = nil) { store.requestAccess(for: CNEntityType.contacts) { (granted, error) in completion?(granted) } } fileprivate func presentContactPickerViewController() { let contactPickerVC = CNContactPickerViewController() contactPickerVC.delegate = self contactPickerVC.title = "Select a phone number" contactPickerVC.navigationController?.navigationBar.tintColor = .flatSkyBlue Appearance.setUp(navTextColor: .flatSkyBlue) contactPickerVC.displayedPropertyKeys = self.contactKeys contactPickerVC.predicateForEnablingContact = NSPredicate(format: "phoneNumbers.@count > 0") contactPickerVC.predicateForSelectionOfContact = NSPredicate(format: "phoneNumbers.@count == 1") contactPickerVC.predicateForSelectionOfProperty = NSPredicate(format: "key == phoneNumber") viewController.present(contactPickerVC, animated: true, completion: nil) } fileprivate func presentPermissionErrorAlert() { let alert = UIAlertController(title: "Access Denied", message: "St@ needs access to your contacts enable this feature", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Too bad 🤐 ", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Open Sesame! 🚪", style: .default, handler: { _ in guard let settingsURL = URL(string: UIApplicationOpenSettingsURLString) else { return } UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil) })) viewController.present(alert, animated: true, completion: nil) } fileprivate func process(contact: CNContact, contactProperty: CNContactProperty? = nil) { Appearance.setUp(navTextColor: .white) let name = contact.firstLastInitial if let phone = contactProperty?.value as? CNPhoneNumber { let selectedContact = (name, phone.stringValue) contactSelected(Result.success(selectedContact)) } else if let phone = contact.phoneNumbers.first?.value { let selectedContact = (name, phone.stringValue) contactSelected(Result.success(selectedContact)) } else { contactSelected(Result.failure(ContactsError.formatting)) } } } extension ContactsHelper: CNContactPickerDelegate { func contactPicker(_ picker: CNContactPickerViewController, didSelect contactProperty: CNContactProperty) { process(contact: contactProperty.contact, contactProperty: contactProperty) } func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) { process(contact: contact) } func contactPickerDidCancel(_ picker: CNContactPickerViewController) { Appearance.setUp(navTextColor: .white) } } extension CNContact { var firstLastInitial: String { return "\(givenName) \(familyName.firstLetter)" } }
mit
12f49c73e867aaee7eda1dc3fc742b96
32.645833
155
0.654076
5.121564
false
false
false
false
zeroleaf/LeetCode
LeetCode/LeetCodeTests/303_RangeSumQuerySpec.swift
1
1071
// // RangeSumQuerySpec.swift // LeetCode // // Created by zeroleaf on 16/2/13. // Copyright © 2016年 zeroleaf. All rights reserved. // import XCTest import Quick import Nimble class RangeSumQuery { var sums: [Int] init(nums: [Int]) { sums = [Int](count: nums.count, repeatedValue: 0) if !nums.isEmpty { sums[0] = nums[0] } for var i = 1; i < nums.count; i++ { sums[i] = sums[i - 1] + nums[i] } } func sumRange(i: Int, j: Int) -> Int { if i == 0 { return sums[j] } return sums[j] - sums[i - 1] } } class RangeSumQuerySpec: QuickSpec { override func spec() { describe("Range Sum Query") { it("Test Case") { let nums = [-2, 0, 3, -5, 2, -1] let s = RangeSumQuery(nums: nums) expect(s.sumRange(0, j: 2)).to(equal(1)) expect(s.sumRange(2, j: 5)).to(equal(-1)) expect(s.sumRange(0, j: 5)).to(equal(-3)) } } } }
mit
0b38243420dca92699fe0515f8cb66bf
19.538462
57
0.476592
3.236364
false
false
false
false
blockchain/My-Wallet-V3-iOS
Blockchain/Wallet/WalletManager.swift
1
12019
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BitcoinChainKit import BitcoinKit import DIKit import FeatureAuthenticationDomain import FeatureSettingsDomain import JavaScriptCore import PlatformKit import RxCocoa import RxSwift import ToolKit import WalletPayloadKit /** Manager object for operations to the Blockchain Wallet. */ @objc class WalletManager: NSObject, JSContextProviderAPI, WalletRepositoryProvider, WalletManagerAPI { @Inject static var shared: WalletManager @LazyInject var loggedInReloadHandler: LoggedInReloadAPI @objc static var sharedInstance: WalletManager { shared } // TODO: Replace this with asset-specific wallet architecture @objc let wallet: Wallet let reactiveWallet: ReactiveWalletAPI // TODO: make this private(set) once other methods in RootService have been migrated in here @objc var latestMultiAddressResponse: MultiAddressResponse? @objc var didChangePassword: Bool = false weak var authDelegate: WalletAuthDelegate? weak var accountInfoDelegate: WalletAccountInfoDelegate? @objc weak var addressesDelegate: WalletAddressesDelegate? @objc weak var recoveryDelegate: WalletRecoveryDelegate? @objc weak var historyDelegate: WalletHistoryDelegate? @objc weak var accountInfoAndExchangeRatesDelegate: WalletAccountInfoAndExchangeRatesDelegate? @objc weak var backupDelegate: WalletBackupDelegate? weak var keyImportDelegate: WalletKeyImportDelegate? weak var secondPasswordDelegate: WalletSecondPasswordDelegate? private(set) var repository: WalletRepositoryAPI! private(set) var legacyRepository: WalletRepository! init( wallet: Wallet = Wallet()!, appSettings: AppSettingsAPI = resolve(), reactiveWallet: ReactiveWalletAPI = resolve(), featureFlagService: FeatureFlagsServiceAPI = resolve() ) { self.wallet = wallet self.reactiveWallet = reactiveWallet super.init() let repository = WalletRepository( jsContextProvider: self, appSettings: appSettings, reactiveWallet: reactiveWallet, featureFlagService: featureFlagService ) let walletConnect = WalletConnectMetadata( jsContextProvider: self ) legacyRepository = repository self.repository = repository self.wallet.repository = repository self.wallet.delegate = self self.wallet.ethereum.reactiveWallet = reactiveWallet self.wallet.bitcoin.reactiveWallet = reactiveWallet self.wallet.walletConnect = walletConnect self.wallet.handleReload = { [weak self] in self?.loggedInReloadHandler.reload() } } /// Returns the context. Should be invoked on the main queue always. /// If the context has not been generated, func fetchJSContext() -> JSContext { wallet.loadContextIfNeeded() } /// Performs closing operations on the wallet. This should be called on logout and /// when the app is backgrounded func close() { latestMultiAddressResponse = nil wallet.resetSyncStatus() wallet.loadJS() wallet.hasLoadedAccountInfo = false beginBackgroundUpdateTask() } @objc func forgetWallet() { BlockchainSettings.App.shared.clearPin() // Clear all cookies (important one is the server session id SID) HTTPCookieStorage.shared.deleteAllCookies() legacyRepository.legacySessionToken = nil legacyRepository.legacyPassword = nil BlockchainSettings.App.shared.set(guid: nil) BlockchainSettings.App.shared.set(sharedKey: nil) wallet.loadJS() latestMultiAddressResponse = nil let clearOnLogoutHandler: ClearOnLogoutAPI = DIKit.resolve() clearOnLogoutHandler.clearOnLogout() BlockchainSettings.App.shared.set(biometryEnabled: false) } private var backgroundUpdateTaskIdentifer: UIBackgroundTaskIdentifier? private func beginBackgroundUpdateTask() { // We're using a background task to ensure we get enough time to sync. The bg task has to be ended before or when the timer expires, // otherwise the app gets killed by the system. Always kill the old handler before starting a new one. In case the system starts a bg // task when the app goes into background, comes to foreground and goes to background before the first background task was ended. // In that case the first background task is never killed and the system kills the app when the maximum time is up. endBackgroundUpdateTask() backgroundUpdateTaskIdentifer = UIApplication.shared.beginBackgroundTask { [unowned self] in self.endBackgroundUpdateTask() } } private func endBackgroundUpdateTask() { guard let backgroundUpdateTaskIdentifer = backgroundUpdateTaskIdentifer else { return } UIApplication.shared.endBackgroundTask(backgroundUpdateTaskIdentifer) } fileprivate func updateFiatSymbols() { guard wallet.hasLoadedAccountInfo == true else { return } guard let fiatCode = wallet.accountInfo["currency"] as? String else { Logger.shared.warning("Could not get fiat code") return } guard let btcRates = wallet.btcRates else { Logger.shared.warning("btcRates not present") return } guard var currencySymbols = btcRates[fiatCode] as? [AnyHashable: Any] else { Logger.shared.warning("Currency symbols dictionary is nil") return } currencySymbols["code"] = fiatCode latestMultiAddressResponse?.symbol_local = CurrencySymbol(dict: currencySymbols) } } extension WalletManager { func loadWalletJS() { wallet.loadJS() } func fetch(with password: String) { wallet.fetch(with: password) } func walletIsInitialized() -> Bool { wallet.isInitialized() } func walletNeedsSecondPassword() -> Bool { wallet.needsSecondPassword() } func walletGetHistoryForAllAssets() { wallet.getHistoryForAllAssets() } func newWallet(password: String, email: String) { wallet.newAccount(password, email: email) } func load(with guid: String, sharedKey: String, password: String) { wallet.load(withGuid: guid, sharedKey: sharedKey, password: password) } func markWalletAsNew() { wallet.isNew = true } func recoverFromMetadata(seedPhrase: String) { wallet.recoverFromMetadata(withMnemonicPassphrase: seedPhrase) } func recover(email: String, password: String, seedPhrase: String) { wallet.recover( withEmail: email, password: password, mnemonicPassphrase: seedPhrase ) } } extension WalletManager: WalletDelegate { // MARK: - Auth func didCreateNewAccount(_ guid: String!, sharedKey: String!, password: String!) { // this is no-op intentionally // for context, `CreateWalletScreenInteractor` and `RecoverWalletScreenInteractor` // are stealing the `Wallet` delegate and capturing this method to do their logic // // This is added here so that the `WalletManager+Rx` and `WalletManager+Combine` // would be able to listen if the method is invoked and handle it. } func errorCreatingNewAccount(_ message: String!) { // this is no-op intentionally ^^ same as above ^^ } func walletJSReady() { // this is no-op intentionally ^^ same as above ^^ } func walletDidGetBtcExchangeRates() { updateFiatSymbols() } func walletDidLoad() { Logger.shared.info("walletDidLoad()") endBackgroundUpdateTask() } func walletDidDecrypt(withSharedKey sharedKey: String?, guid: String?) { Logger.shared.info("walletDidDecrypt()") DispatchQueue.main.async { self.authDelegate?.didDecryptWallet( guid: guid, sharedKey: sharedKey, password: self.legacyRepository.legacyPassword ) } didChangePassword = false } func walletDidFinishLoad() { Logger.shared.info("walletDidFinishLoad()") DispatchQueue.main.async { self.authDelegate?.authenticationCompleted() } } func walletFailedToDecrypt() { Logger.shared.info("walletFailedToDecrypt()") DispatchQueue.main.async { self.authDelegate?.authenticationError(error: AuthenticationError( code: .errorDecryptingWallet ) ) } } func walletFailedToLoad() { Logger.shared.info("walletFailedToLoad()") DispatchQueue.main.async { [unowned self] in self.authDelegate?.authenticationError( error: AuthenticationError( code: .failedToLoadWallet ) ) } } // MARK: - Addresses func returnToAddressesScreen() { DispatchQueue.main.async { [unowned self] in self.addressesDelegate?.returnToAddressesScreen() } } // MARK: - Account Info func walletDidGetAccountInfo(_ wallet: Wallet!) { DispatchQueue.main.async { [unowned self] in self.accountInfoDelegate?.didGetAccountInfo() } } // MARK: - BTC Multiaddress func didGet(_ response: MultiAddressResponse) { latestMultiAddressResponse = response wallet.getAccountInfoAndExchangeRates() updateFiatSymbols() } // MARK: - Backup func didBackupWallet() { DispatchQueue.main.async { [unowned self] in self.backupDelegate?.didBackupWallet() } } func didFailBackupWallet() { DispatchQueue.main.async { [unowned self] in self.backupDelegate?.didFailBackupWallet() } } // MARK: - Account Info and Exchange Rates on startup func walletDidGetAccountInfoAndExchangeRates(_ wallet: Wallet!) { DispatchQueue.main.async { [unowned self] in self.accountInfoAndExchangeRatesDelegate?.didGetAccountInfoAndExchangeRates() } } // MARK: - Recovery func didRecoverWallet() { DispatchQueue.main.async { [unowned self] in self.recoveryDelegate?.didRecoverWallet() } } func didFailRecovery() { DispatchQueue.main.async { [unowned self] in self.recoveryDelegate?.didFailRecovery() } } // MARK: - History func didFailGetHistory(_ error: String?) { DispatchQueue.main.async { [unowned self] in self.historyDelegate?.didFailGetHistory(error: error) } } func didFetchBitcoinCashHistory() { DispatchQueue.main.async { [unowned self] in self.historyDelegate?.didFetchBitcoinCashHistory() } } // MARK: - Second Password @objc func getSecondPassword(withSuccess success: WalletSuccessCallback, dismiss: WalletDismissCallback) { secondPasswordDelegate?.getSecondPassword(success: success, dismiss: dismiss) } @objc func getPrivateKeyPassword(withSuccess success: WalletSuccessCallback) { secondPasswordDelegate?.getPrivateKeyPassword(success: success) } // MARK: - Key Importing func askUserToAddWatchOnlyAddress(_ address: AssetAddress, then: @escaping () -> Void) { DispatchQueue.main.async { [unowned self] in self.keyImportDelegate?.askUserToAddWatchOnlyAddress(address, then: then) } } @objc func scanPrivateKeyForWatchOnlyAddress(_ address: String) { let address = BitcoinAssetAddress(publicKey: address) DispatchQueue.main.async { [unowned self] in self.keyImportDelegate?.scanPrivateKeyForWatchOnlyAddress(address) } } }
lgpl-3.0
4b60e58a52925bd14d0bb1bfac846b38
30.877984
141
0.666334
5.017954
false
false
false
false
Miguel-Herrero/Swift
Pro Swift/syntax/Documentation markup.playground/Contents.swift
1
2842
/** Call this function to grok some globs. - Author: Miguel Herrero - Throws: LoadError.networkFailed, LoadError.writeFailed - Precondition: inputArray.count > 0 - Complexity: O(1) - Returns: A string containing a date formatted as RFC-822 - Parameters: - album: The name of a Taylor Swift album - track: The track number to load - bar: Consectetur adipisicing elit */ func myGreatFunction(album: String, track: Int, bar: String) { // do stuff } /// 🚲 A two-wheeled, human-powered mode of transportation. class Bicycle { /** Frame and construction style. - Road: For streets or trails. - Touring: For long journeys. - Cruiser: For casual trips around town. - Hybrid: For general-purpose transportation. */ enum Style { case Road, Touring, Cruiser, Hybrid } /** Mechanism for converting pedal power into motion. - Fixed: A single, fixed gear. - Freewheel: A variable-speed, disengageable gear. */ enum Gearing { case Fixed case Freewheel(speeds: Int) } /** Hardware used for steering. - Riser: A casual handlebar. - Café: An upright handlebar. - Drop: A classic handlebar. - Bullhorn: A powerful handlebar. */ enum Handlebar { case Riser, Café, Drop, Bullhorn } /// The style of the bicycle. let style: Style /// The gearing of the bicycle. let gearing: Gearing /// The handlebar of the bicycle. let handlebar: Handlebar /// The size of the frame, in centimeters. let frameSize: Int /// The number of trips travelled by the bicycle. private(set) var numberOfTrips: Int /// The total distance travelled by the bicycle, in meters. private(set) var distanceTravelled: Double /** Initializes a new bicycle with the provided parts and specifications. - Parameters: - style: The style of the bicycle - gearing: The gearing of the bicycle - handlebar: The handlebar of the bicycle - frameSize: The frame size of the bicycle, in centimeters - Returns: A beautiful, brand-new bicycle, custom built just for you. */ init(style: Style, gearing: Gearing, handlebar: Handlebar, frameSize centimeters: Int) { self.style = style self.gearing = gearing self.handlebar = handlebar self.frameSize = centimeters self.numberOfTrips = 0 self.distanceTravelled = 0 } /** Take a bike out for a spin. - Parameter meters: The distance to travel in meters. */ func travel(distance meters: Double) { if meters > 0 { distanceTravelled += meters numberOfTrips += 1 } } }
gpl-3.0
d37861e024d409146d57ff2c7775d124
25.036697
92
0.615791
4.202963
false
false
false
false
mattermost/mattermost-mobile
ios/MattermostShare/ShareViewController.swift
1
4998
// // ShareViewController.swift // MattermostShare // // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // import Gekidou import SwiftUI import UIKit import os.log class ShareViewController: UIViewController { private var fileManager: LocalFileManager? private var dismissKeyboardObserver: NSObjectProtocol? private var closeExtensionObserver: NSObjectProtocol? private var doPostObserver: NSObjectProtocol? override func viewDidLoad() { super.viewDidLoad() self.isModalInPresentation = true self.addObservers() fileManager = LocalFileManager() if let inputItems = extensionContext?.inputItems { fileManager!.extractDataFromContext( inputItems, completionHander: {[weak self] attachments, linkPreviewUrl, message in self?.showUIView( attachments: attachments, linkPreviewUrl: linkPreviewUrl, message: message ) }) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } private func addObservers() { self.dismissKeyboardObserver = NotificationCenter.default.addObserver( forName: NSNotification.Name("dismissKeyboard"), object: nil, queue: nil) { _ in self.dismissKeyboard() } self.closeExtensionObserver = NotificationCenter.default.addObserver( forName: NSNotification.Name("close"), object: nil, queue: nil, using: close ) self.doPostObserver = NotificationCenter.default.addObserver( forName: NSNotification.Name("doPost"), object: nil, queue: nil, using: doPost ) } private func removeObservers() { fileManager = nil NotificationCenter.default.removeObserver(dismissKeyboardObserver as Any) NotificationCenter.default.removeObserver(closeExtensionObserver as Any) NotificationCenter.default.removeObserver(doPostObserver as Any) } private func close(_ notification: Notification) { self.removeObservers() if let userInfo = notification.userInfo, let attachments = userInfo["attachments"] as? [AttachmentModel] { fileManager?.clearTempDirectory(attachments.map{ $0.fileUrl.path}) } extensionContext?.completeRequest(returningItems: []) } private func dismissKeyboard() { self.view.endEditing(false) } private func doPost(_ notification: Notification) { removeObservers() if let userInfo = notification.userInfo { let serverUrl = userInfo["serverUrl"] as? String let channelId = userInfo["channelId"] as? String let text = userInfo["message"] as? String ?? "" let attachments = userInfo["attachments"] as? [AttachmentModel] ?? [] let linkPreviewUrl = userInfo["linkPreviewUrl"] as? String let fileCount = attachments.count let files: [String] = attachments.map{ $0.fileUrl.absoluteString } var message = text if linkPreviewUrl != nil && !linkPreviewUrl!.isEmpty { if text.isEmpty { message = linkPreviewUrl! } else { message = "\(text)\n\n\(linkPreviewUrl!)" } } print("Do post to \(serverUrl ?? "") in channel \(channelId ?? "") the message \(message) with preview \(linkPreviewUrl ?? "") and attaching \(fileCount) files") if let url = serverUrl, let channel = channelId { os_log( OSLogType.default, "Mattermost BackgroundSession: Sharing content to serverUrl=%{public}@ in channelId=%{public}@ with message=%{public}@ and attaching %{public}@ files", url, channel, message, "\(fileCount)" ) let shareExtension = Gekidou.ShareExtension() shareExtension.uploadFiles( serverUrl: url, channelId: channel, message: message, files: files, completionHandler: { [weak self] in self?.extensionContext!.completeRequest(returningItems: []) }) } else { extensionContext!.completeRequest(returningItems: []) } } } func showUIView(attachments: [AttachmentModel], linkPreviewUrl: String?, message: String?) { let childView = UIHostingController( rootView: ShareUIView( attachments: attachments, linkPreviewUrl: linkPreviewUrl ?? "", message: message ?? "" ) ) addChild(childView) childView.view.translatesAutoresizingMaskIntoConstraints = false view.addSubview(childView.view) childView.didMove(toParent: self) NSLayoutConstraint.activate([ childView.view.widthAnchor.constraint(equalTo: view.widthAnchor), childView.view.heightAnchor.constraint(equalTo: view.heightAnchor), childView.view.centerXAnchor.constraint(equalTo: view.centerXAnchor), childView.view.centerYAnchor.constraint(equalTo: view.centerYAnchor) ]) } }
apache-2.0
5dd2dff27ccda5d17ec0ddb3c72ecf55
31.666667
167
0.662065
5.033233
false
false
false
false
eraydiler/password-locker
PasswordLockerSwift/Classes/Controller/DynamicTVCS/CategoriesTableViewController.swift
1
6590
// // CategoriesTableViewController.swift // PasswordLockerSwift // // Created by Eray on 03/02/15. // Copyright (c) 2015 Eray. All rights reserved. // import UIKit import CoreData class CategoriesTableViewController: UITableViewController, NSFetchedResultsControllerDelegate { func configureView() { self.tableView.rowHeight = 50.0 } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() // println(managedObjectContext) configureView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Fetched results controller /* `NSFetchedResultsController` lazily initialized fetches the displayed domain model */ var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> { // return if already initialized if self._fetchedResultsController != nil { return self._fetchedResultsController! } let managedObjectContext = NSManagedObjectContext.mr_default() /* `NSFetchRequest` config fetch all `Item`s order them alphabetically by name at least one sort order _is_ required */ let entity = NSEntityDescription.entity(forEntityName: "Category", in: managedObjectContext) let sort = NSSortDescriptor(key: "name", ascending: true) let req = NSFetchRequest<NSFetchRequestResult>() req.entity = entity req.sortDescriptors = [sort] /* NSFetchedResultsController initialization a `nil` `sectionNameKeyPath` generates a single section */ let aFetchedResultsController = NSFetchedResultsController(fetchRequest: req, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) aFetchedResultsController.delegate = self self._fetchedResultsController = aFetchedResultsController // perform initial model fetch var e: NSError? do { try self._fetchedResultsController!.performFetch() } catch let error as NSError { e = error print("fetch error: \(e!.localizedDescription)") abort(); } return self._fetchedResultsController! } var _fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>? // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return self.fetchedResultsController.sections!.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return self.fetchedResultsController.sections![section].numberOfObjects } // create and configure each `UITableViewCell` override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell = UITableViewCell() cell = tableView.dequeueReusableCell(withIdentifier: "CategoryCell", for: indexPath) self.configureCell(cell, atIndexPath: indexPath) return cell } // MARK: - Table view delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let indexPath = self.tableView.indexPathForSelectedRow let category = self.fetchedResultsController.object(at: indexPath!) as! Category if category.name == "Note" { // self.performSegueWithIdentifier("toNoteTypeTVCSegue", sender: nil) self.performSegue(withIdentifier: "toValuesTVCSegue", sender: nil) } else { self.performSegue(withIdentifier: "toTypesTVCSegue", sender: nil) } } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. let indexPath = self.tableView.indexPathForSelectedRow let category = self.fetchedResultsController.object(at: indexPath!) as! Category if segue.identifier == "toTypesTVCSegue" { let targetVC = segue.destination as! TypesTableViewController // targetVC.managedObjectContext = managedObjectContext targetVC.category = category } /*else if segue.identifier == "toNoteTypeTVCSegue" { let targetVC = segue.destinationViewController as! NoteTypeTableViewController targetVC.managedObjectContext = self.managedObjectContext }*/ else if segue.identifier == "toValuesTVCSegue" { let targetVC = segue.destination as! ValuesTableViewController targetVC.category = category targetVC.delegate = self.tabBarController as! TabBarController let type = getNoteType(category.types.allObjects as! [Type]) targetVC.type = type } } /* helper method to configure a `UITableViewCell` ask `NSFetchedResultsController` for the model */ func configureCell(_ cell: UITableViewCell, atIndexPath indexPath: IndexPath) { let category = self.fetchedResultsController.object(at: indexPath) as! Category let imageView = cell.contentView.subviews[0] as! UIImageView let titleLabel = cell.contentView.subviews[1] as! UILabel imageView.image = UIImage(named: category.imageName) titleLabel.text = category.name } // MARK: - Helper Methods func getNoteType(_ types: [Type]) -> Type { for type in types { if type.name == "Note" { return type } } return types[0] } }
mit
68ba17ffd93637bad6046f67ed5f3b2b
37.764706
170
0.658118
5.837024
false
false
false
false
jekahy/Adoreavatars
AdoravatarsTests/DownloadVCTests.swift
1
1174
// // DownloadsVCTests.swift // Adoravatars // // Created by Eugene on 06.07.17. // Copyright © 2017 Eugene. All rights reserved. // import XCTest @testable import Adoravatars class DownloadsVCTests: XCTestCase { var sut:DownloadsVC! override func setUp() { super.setUp() let downloadsVM = DownloadsVM(api: APIServiceStubbed()) sut = createSut(vm: downloadsVM) } // MARK: Tests func testInitTableViewNotNil() { XCTAssertNotNil(sut.tableView) } func testInitViewModelNotNil() { XCTAssertNotNil(sut.viewModel) } func testInitAvatarDownloadTasksConnected() { let rows = sut.tableView.numberOfRows(inSection: 0) XCTAssertEqual(rows, 1) } // MARK: Helpers func createSut(vm:DownloadsVMType)->DownloadsVC { let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard .instantiateViewController(withIdentifier: "DownloadsVC") as! DownloadsVC controller.viewModel = vm _ = controller.view return controller } }
mit
0bd71315e17c04b7873143a785059de9
19.946429
69
0.614663
4.511538
false
true
false
false
zhenghuadong11/firstGitHub
旅游app_useSwift/旅游app_useSwift/MYSetUpLoginTableViewCell.swift
1
2246
// // MYSetUpLoginTableViewCell.swift // 旅游app_useSwift // // Created by zhenghuadong on 16/5/1. // Copyright © 2016年 zhenghuadong. All rights reserved. // import UIKit class MYSetUpLoginTableViewCell: UITableViewCell { @IBAction func switchClick(sender: UISwitch) { if sender.on == true { MYMineModel._shareMineModel.remenberPassWord = true if MYMineModel._shareMineModel.name != nil { let path = NSBundle.mainBundle().pathForResource("nowUser", ofType: "plist") var array = Array<[String:AnyObject]>() let dict:[String:AnyObject] = ["user":MYMineModel._shareMineModel.name!,"passWord":MYMineModel._shareMineModel.passWord!] array.append(dict) (array as NSArray).writeToFile(path!, atomically: true) } } else { MYMineModel._shareMineModel.remenberPassWord = false let path = NSBundle.mainBundle().pathForResource("nowUser", ofType: "plist") var array = Array<[String:AnyObject]>() (array as NSArray).writeToFile(path!, atomically: true) } } @IBOutlet weak var sw: UISwitch! static func setUpLoginTableViewCellWithTableView(tableView:UITableView) -> MYSetUpLoginTableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("MYSetUpLoginTableViewCell") as? MYSetUpLoginTableViewCell if cell == nil { cell = NSBundle.mainBundle().loadNibNamed("MYSetUpLoginTableViewCell", owner: nil, options: nil).first as? MYSetUpLoginTableViewCell } return cell! } override func awakeFromNib() { super.awakeFromNib() let path = NSBundle.mainBundle().pathForResource("nowUser.plist", ofType: nil) let array = NSArray.init(contentsOfFile: path!) as? Array<[String:AnyObject]> if array?.count == 0 { self.sw.on = false return } self.sw.on = true } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
apache-2.0
a8869f1e1d47a64e43d5ab667a0b4c9a
30.535211
144
0.605181
4.635611
false
false
false
false
twobitlabs/TBLCategories
Swift Extensions/UIColor+TBL.swift
1
2527
import UIKit public extension UIColor { /** Parse a string for a hex color value. Currently does not support 8-character strings with alpha components */ @objc convenience init?(fromHexString hexString: String) { let colorHexString = hexString.replacingOccurrences(of: "#", with: "", options: NSString.CompareOptions(), range: nil) let scanner = Scanner(string: colorHexString) var hexValue: UInt64 = 0 switch colorHexString.count { case 8: if scanner.scanHexInt64(&hexValue) { let r = CGFloat((hexValue & 0xff000000) >> 24) / 255 let g = CGFloat((hexValue & 0x00ff0000) >> 16) / 255 let b = CGFloat((hexValue & 0x0000ff00) >> 8) / 255 let a = CGFloat(hexValue & 0x000000ff) / 255 self.init(red: r, green: g, blue: b, alpha: a) return } case 6: if scanner.scanHexInt64(&hexValue) { let r = CGFloat((hexValue & 0x00ff0000) >> 16) / 255 let g = CGFloat((hexValue & 0x0000ff00) >> 8) / 255 let b = CGFloat(hexValue & 0x000000ff) / 255 self.init(red: r, green: g, blue: b, alpha: 1) return } default: return nil } return nil } @objc func toHexString() -> String? { guard let components = cgColor.components, components.count >= 3 else { return nil } // ignore alpha let red = components[0] let green = components[1] let blue = components[2] let red255 = Int((red * 255).rounded()) let green255 = Int((green * 255).rounded()) let blue255 = Int((blue * 255).rounded()) let redHex = String(format: "%02X", red255) let greenHex = String(format: "%02X", green255) let blueHex = String(format: "%02X", blue255) return "\(redHex)\(greenHex)\(blueHex)" } @objc func asImage(width: CGFloat = 1, height: CGFloat = 1) -> UIImage { let rect = CGRect(x: 0, y: 0, width: width, height: height) UIGraphicsBeginImageContext(rect.size) let context: CGContext = UIGraphicsGetCurrentContext()! context.setFillColor(cgColor) context.fill(rect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } }
mit
16455134c356f81285568e86d623265b
36.716418
126
0.550851
4.536804
false
false
false
false
SwiftAndroid/swift
stdlib/public/core/SwiftNativeNSArray.swift
1
9173
//===--- SwiftNativeNSArray.swift -----------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // _ContiguousArrayStorageBase supplies the implementation of the // _NSArrayCore API (and thus, NSArray the API) for our // _ContiguousArrayStorage<T>. We can't put this implementation // directly on _ContiguousArrayStorage because generic classes can't // override Objective-C selectors. // //===----------------------------------------------------------------------===// #if _runtime(_ObjC) import SwiftShims /// Returns `true` iff the given `index` is valid as a position, i.e. `0 /// ≤ index ≤ count`. @_transparent internal func _isValidArrayIndex(_ index: Int, count: Int) -> Bool { return (index >= 0) && (index <= count) } /// Returns `true` iff the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @_transparent internal func _isValidArraySubscript(_ index: Int, count: Int) -> Bool { return (index >= 0) && (index < count) } /// An `NSArray` with Swift-native reference counting and contiguous /// storage. internal class _SwiftNativeNSArrayWithContiguousStorage : _SwiftNativeNSArray { // Provides NSArray inheritance and native refcounting // Operate on our contiguous storage internal func withUnsafeBufferOfObjects<R>( @noescape _ body: UnsafeBufferPointer<AnyObject> throws -> R ) rethrows -> R { _sanityCheckFailure( "Must override withUnsafeBufferOfObjects in derived classes") } } // Implement the APIs required by NSArray extension _SwiftNativeNSArrayWithContiguousStorage : _NSArrayCore { @objc internal var count: Int { return withUnsafeBufferOfObjects { $0.count } } @objc(objectAtIndex:) internal func objectAt(_ index: Int) -> AnyObject { return withUnsafeBufferOfObjects { objects in _precondition( _isValidArraySubscript(index, count: objects.count), "Array index out of range") return objects[index] } } @objc internal func getObjects( _ aBuffer: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange ) { return withUnsafeBufferOfObjects { objects in _precondition( _isValidArrayIndex(range.location, count: objects.count), "Array index out of range") _precondition( _isValidArrayIndex( range.location + range.length, count: objects.count), "Array index out of range") if objects.isEmpty { return } // These objects are "returned" at +0, so treat them as values to // avoid retains. UnsafeMutablePointer<Int>(aBuffer).initializeFrom( UnsafeMutablePointer(objects.baseAddress! + range.location), count: range.length) } } @objc(countByEnumeratingWithState:objects:count:) internal func countByEnumerating( with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>?, count: Int ) -> Int { var enumerationState = state.pointee if enumerationState.state != 0 { return 0 } return withUnsafeBufferOfObjects { objects in enumerationState.mutationsPtr = _fastEnumerationStorageMutationsPtr enumerationState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects.baseAddress) enumerationState.state = 1 state.pointee = enumerationState return objects.count } } @objc(copyWithZone:) internal func copy(with _: _SwiftNSZone?) -> AnyObject { return self } } /// An `NSArray` whose contiguous storage is created and filled, upon /// first access, by bridging the elements of a Swift `Array`. /// /// Ideally instances of this class would be allocated in-line in the /// buffers used for Array storage. @objc internal final class _SwiftDeferredNSArray : _SwiftNativeNSArrayWithContiguousStorage { // This stored property should be stored at offset zero. We perform atomic // operations on it. // // Do not access this property directly. internal var _heapBufferBridged_DoNotUse: AnyObject? = nil // When this class is allocated inline, this property can become a // computed one. internal let _nativeStorage: _ContiguousArrayStorageBase internal var _heapBufferBridgedPtr: UnsafeMutablePointer<AnyObject?> { return UnsafeMutablePointer(_getUnsafePointerToStoredProperties(self)) } internal typealias HeapBufferStorage = _HeapBufferStorage<Int, AnyObject> internal var _heapBufferBridged: HeapBufferStorage? { if let ref = _stdlib_atomicLoadARCRef(object: _heapBufferBridgedPtr) { return unsafeBitCast(ref, to: HeapBufferStorage.self) } return nil } internal init(_nativeStorage: _ContiguousArrayStorageBase) { self._nativeStorage = _nativeStorage } internal func _destroyBridgedStorage(_ hb: HeapBufferStorage?) { if let bridgedStorage = hb { let heapBuffer = _HeapBuffer(bridgedStorage) let count = heapBuffer.value heapBuffer.baseAddress.deinitialize(count: count) } } deinit { _destroyBridgedStorage(_heapBufferBridged) } internal override func withUnsafeBufferOfObjects<R>( @noescape _ body: UnsafeBufferPointer<AnyObject> throws -> R ) rethrows -> R { repeat { var buffer: UnsafeBufferPointer<AnyObject> // If we've already got a buffer of bridged objects, just use it if let bridgedStorage = _heapBufferBridged { let heapBuffer = _HeapBuffer(bridgedStorage) buffer = UnsafeBufferPointer( start: heapBuffer.baseAddress, count: heapBuffer.value) } // If elements are bridged verbatim, the native buffer is all we // need, so return that. else if let buf = _nativeStorage._withVerbatimBridgedUnsafeBuffer( { $0 } ) { buffer = buf } else { // Create buffer of bridged objects. let objects = _nativeStorage._getNonVerbatimBridgedHeapBuffer() // Atomically store a reference to that buffer in self. if !_stdlib_atomicInitializeARCRef( object: _heapBufferBridgedPtr, desired: objects.storage!) { // Another thread won the race. Throw out our buffer. _destroyBridgedStorage( unsafeDowncast(objects.storage!, to: HeapBufferStorage.self)) } continue // Try again } defer { _fixLifetime(self) } return try body(buffer) } while true } /// Returns the number of elements in the array. /// /// This override allows the count to be read without triggering /// bridging of array elements. @objc internal override var count: Int { if let bridgedStorage = _heapBufferBridged { return _HeapBuffer(bridgedStorage).value } // Check if elements are bridged verbatim. return _nativeStorage._withVerbatimBridgedUnsafeBuffer { $0.count } ?? _nativeStorage._getNonVerbatimBridgedCount() } } #else // Empty shim version for non-objc platforms. class _SwiftNativeNSArrayWithContiguousStorage {} #endif /// Base class of the heap buffer backing arrays. internal class _ContiguousArrayStorageBase : _SwiftNativeNSArrayWithContiguousStorage { #if _runtime(_ObjC) internal override func withUnsafeBufferOfObjects<R>( @noescape _ body: UnsafeBufferPointer<AnyObject> throws -> R ) rethrows -> R { if let result = try _withVerbatimBridgedUnsafeBuffer(body) { return result } _sanityCheckFailure( "Can't use a buffer of non-verbatim-bridged elements as an NSArray") } /// If the stored type is bridged verbatim, invoke `body` on an /// `UnsafeBufferPointer` to the elements and return the result. /// Otherwise, return `nil`. internal func _withVerbatimBridgedUnsafeBuffer<R>( @noescape _ body: UnsafeBufferPointer<AnyObject> throws -> R ) rethrows -> R? { _sanityCheckFailure( "Concrete subclasses must implement _withVerbatimBridgedUnsafeBuffer") } internal func _getNonVerbatimBridgedCount(_ dummy: Void) -> Int { _sanityCheckFailure( "Concrete subclasses must implement _getNonVerbatimBridgedCount") } internal func _getNonVerbatimBridgedHeapBuffer(_ dummy: Void) -> _HeapBuffer<Int, AnyObject> { _sanityCheckFailure( "Concrete subclasses must implement _getNonVerbatimBridgedHeapBuffer") } #endif func canStoreElements(ofDynamicType _: Any.Type) -> Bool { _sanityCheckFailure( "Concrete subclasses must implement canStoreElements(ofDynamicType:)") } /// A type that every element in the array is. var staticElementType: Any.Type { _sanityCheckFailure( "Concrete subclasses must implement staticElementType") } deinit { _sanityCheck( self !== _emptyArrayStorage, "Deallocating empty array storage?!") } }
apache-2.0
b184fcca429aa273641afb183bf8de9a
31.507092
80
0.684411
5.152895
false
false
false
false
uraimo/Swift-Playgrounds
2017-05-07-ConcurrencyInSwift.playground/Pages/OperationQueue.xcplaygroundpage/Contents.swift
1
1505
/*: ## All About Concurrency in Swift - Part 1: The Present Playground Read the post at [uraimo.com](https://ww.uraimo.com/2017/05/07/all-about-concurrency-in-swift-1-the-present/) */ //: [Previous - GCD](@previous) import Foundation import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true /*: # OperationQueue */ /*: ### Operation Queue Basics */ var queue = OperationQueue() queue.name = "My Custom Queue" queue.maxConcurrentOperationCount = 2 var mainqueue = OperationQueue.main //Refers to the queue of the main thread queue.addOperation { print("Op1") } queue.addOperation { print("Op2") } //: Operations var op3 = BlockOperation(block: { print("Op3") }) op3.queuePriority = .veryHigh op3.completionBlock = { if op3.isCancelled { print("Someone cancelled me.") } print("Completed Op3") } var op4 = BlockOperation { print("Op4 always after Op3") OperationQueue.main.addOperation{ print("I'm on main queue!") } } //: Dependencies between operations op4.addDependency(op3) queue.addOperation(op4) // op3 will complete before op4, always queue.addOperation(op3) //: Operation status op3.isReady //Ready for execution? op3.isExecuting //Executing now? op3.isFinished //Finished naturally or cancelled? op3.isCancelled //Manually cancelled? //: Cancel operations queue.cancelAllOperations() op3.cancel() //: Suspend or check suspension status queue.isSuspended = true
mit
db2f7c0f82715fb2b1fe83bb0a465d0c
15.010638
110
0.698339
3.753117
false
false
false
false
kesun421/firefox-ios
Shared/UserAgent.swift
3
5570
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import AVFoundation import UIKit open class UserAgent { private static var defaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)! private static func clientUserAgent(prefix: String) -> String { return "\(prefix)/\(AppInfo.appVersion)b\(AppInfo.buildNumber) (\(DeviceInfo.deviceModel()); iPhone OS \(UIDevice.current.systemVersion)) (\(AppInfo.displayName))" } open static var syncUserAgent: String { return clientUserAgent(prefix: "Firefox-iOS-Sync") } open static var tokenServerClientUserAgent: String { return clientUserAgent(prefix: "Firefox-iOS-Token") } open static var fxaUserAgent: String { return clientUserAgent(prefix: "Firefox-iOS-FxA") } open static var defaultClientUserAgent: String { return clientUserAgent(prefix: "Firefox-iOS") } /** * Use this if you know that a value must have been computed before your * code runs, or you don't mind failure. */ open static func cachedUserAgent(checkiOSVersion: Bool = true, checkFirefoxVersion: Bool = true, checkFirefoxBuildNumber: Bool = true) -> String? { let currentiOSVersion = UIDevice.current.systemVersion let lastiOSVersion = defaults.string(forKey: "LastDeviceSystemVersionNumber") let currentFirefoxBuildNumber = AppInfo.buildNumber let currentFirefoxVersion = AppInfo.appVersion let lastFirefoxVersion = defaults.string(forKey: "LastFirefoxVersionNumber") let lastFirefoxBuildNumber = defaults.string(forKey: "LastFirefoxBuildNumber") if let firefoxUA = defaults.string(forKey: "UserAgent") { if (!checkiOSVersion || (lastiOSVersion == currentiOSVersion)) && (!checkFirefoxVersion || (lastFirefoxVersion == currentFirefoxVersion) && (!checkFirefoxBuildNumber || (lastFirefoxBuildNumber == currentFirefoxBuildNumber))) { return firefoxUA } } return nil } /** * This will typically return quickly, but can require creation of a UIWebView. * As a result, it must be called on the UI thread. */ open static func defaultUserAgent() -> String { assert(Thread.current.isMainThread, "This method must be called on the main thread.") if let firefoxUA = UserAgent.cachedUserAgent(checkiOSVersion: true) { return firefoxUA } let webView = UIWebView() let appVersion = AppInfo.appVersion let buildNumber = AppInfo.buildNumber let currentiOSVersion = UIDevice.current.systemVersion defaults.set(currentiOSVersion, forKey: "LastDeviceSystemVersionNumber") defaults.set(appVersion, forKey: "LastFirefoxVersionNumber") defaults.set(buildNumber, forKey: "LastFirefoxBuildNumber") let userAgent = webView.stringByEvaluatingJavaScript(from: "navigator.userAgent")! // Extract the WebKit version and use it as the Safari version. let webKitVersionRegex = try! NSRegularExpression(pattern: "AppleWebKit/([^ ]+) ", options: []) let match = webKitVersionRegex.firstMatch(in: userAgent, options: [], range: NSRange(location: 0, length: userAgent.characters.count)) if match == nil { print("Error: Unable to determine WebKit version in UA.") return userAgent // Fall back to Safari's. } let webKitVersion = (userAgent as NSString).substring(with: match!.rangeAt(1)) // Insert "FxiOS/<version>" before the Mobile/ section. let mobileRange = (userAgent as NSString).range(of: "Mobile/") if mobileRange.location == NSNotFound { print("Error: Unable to find Mobile section in UA.") return userAgent // Fall back to Safari's. } let mutableUA = NSMutableString(string: userAgent) mutableUA.insert("FxiOS/\(appVersion)b\(AppInfo.buildNumber) ", at: mobileRange.location) let firefoxUA = "\(mutableUA) Safari/\(webKitVersion)" defaults.set(firefoxUA, forKey: "UserAgent") return firefoxUA } open static func desktopUserAgent() -> String { let userAgent = NSMutableString(string: defaultUserAgent()) // Spoof platform section let platformRegex = try! NSRegularExpression(pattern: "\\([^\\)]+\\)", options: []) guard let platformMatch = platformRegex.firstMatch(in: userAgent as String, options: [], range: NSRange(location: 0, length: userAgent.length)) else { print("Error: Unable to determine platform in UA.") return String(userAgent) } userAgent.replaceCharacters(in: platformMatch.range, with: "(Macintosh; Intel Mac OS X 10_11_1)") // Strip mobile section let mobileRegex = try! NSRegularExpression(pattern: " FxiOS/[^ ]+ Mobile/[^ ]+", options: []) guard let mobileMatch = mobileRegex.firstMatch(in: userAgent as String, options: [], range: NSRange(location: 0, length: userAgent.length)) else { print("Error: Unable to find Mobile section in UA.") return String(userAgent) } userAgent.replaceCharacters(in: mobileMatch.range, with: "") return String(userAgent) } }
mpl-2.0
b895bb9d3610514f4aef6cca8a2756d5
41.519084
171
0.655476
4.951111
false
false
false
false
maximedegreve/Walllpaper
Sources/App/Tasks/IntercomTasks.swift
1
1323
// // Dribbble.swift // Walllpaper // // Created by Maxime De Greve on 19/02/2017. // // import Vapor import HTTP import Fluent import FluentMySQL import Foundation final class IntercomTasks { static func schedule(){ try? background { try? updateUsers() } } static func updateUsers() throws -> Void{ // Rate Limiting: 82 request per 10 seconds (100 per minute) // Also for each user update -0.1 we lose on request // So limit goes down 10 for 100 users let limitAmount = 82 - 10 let usersPerRequest = 100 let usersCount = try User.query().all().count let amountIterations = ceil(Double(usersCount)/Double(usersPerRequest)) for iterate in 0...Int(amountIterations) { let offset = iterate * usersPerRequest let limit = Limit(count: usersPerRequest, offset: offset) let userQuery = try User.query() userQuery.limit = limit let users = try userQuery.all() _ = try? Intercom.bulkUsersUpdate(users: users) let secondsSleep = UInt32(floor(Double(limitAmount/10))) sleep(secondsSleep) } } }
mit
cb1245970f9b94ac855c22ae9893d89a
24.442308
79
0.555556
4.577855
false
false
false
false
manavgabhawala/swift
test/SILGen/objc_thunks.swift
1
28381
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -emit-verbose-sil | %FileCheck %s // REQUIRES: objc_interop import gizmo import ansible class Hoozit : Gizmo { func typical(_ x: Int, y: Gizmo) -> Gizmo { return y } // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozit7typical{{.*}} : $@convention(objc_method) (Int, Gizmo, Hoozit) -> @autoreleased Gizmo { // CHECK: bb0([[X:%.*]] : $Int, [[Y:%.*]] : $Gizmo, [[THIS:%.*]] : $Hoozit): // CHECK-NEXT: [[Y_COPY:%.*]] = copy_value [[Y]] // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref objc_thunks.Hoozit.typical // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Hoozit7typical{{.*}} : $@convention(method) (Int, @owned Gizmo, @guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[X]], [[Y_COPY]], [[BORROWED_THIS_COPY]]) {{.*}} line:[[@LINE-8]]:8:auto_gen // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] : $Hoozit // CHECK-NEXT: return [[RES]] : $Gizmo{{.*}} line:[[@LINE-11]]:8:auto_gen // CHECK-NEXT: } // end sil function '_TToFC11objc_thunks6Hoozit7typical{{.*}}' // NS_CONSUMES_SELF by inheritance override func fork() { } // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozit4fork{{.*}} : $@convention(objc_method) (@owned Hoozit) -> () { // CHECK: bb0([[THIS:%.*]] : $Hoozit): // CHECK-NEXT: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Hoozit4fork{{.*}} : $@convention(method) (@guaranteed Hoozit) -> () // CHECK-NEXT: apply [[NATIVE]]([[BORROWED_THIS]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS]] from [[THIS]] // CHECK-NEXT: destroy_value [[THIS]] // CHECK-NEXT: return // CHECK-NEXT: } // NS_CONSUMED 'gizmo' argument by inheritance override class func consume(_ gizmo: Gizmo?) { } // CHECK-LABEL: sil hidden [thunk] @_TToZFC11objc_thunks6Hoozit7consume{{.*}} : $@convention(objc_method) (@owned Optional<Gizmo>, @objc_metatype Hoozit.Type) -> () { // CHECK: bb0([[GIZMO:%.*]] : $Optional<Gizmo>, [[THIS:%.*]] : $@objc_metatype Hoozit.Type): // CHECK-NEXT: [[THICK_THIS:%[0-9]+]] = objc_to_thick_metatype [[THIS]] : $@objc_metatype Hoozit.Type to $@thick Hoozit.Type // CHECK: [[NATIVE:%.*]] = function_ref @_TZFC11objc_thunks6Hoozit7consume{{.*}} : $@convention(method) (@owned Optional<Gizmo>, @thick Hoozit.Type) -> () // CHECK-NEXT: apply [[NATIVE]]([[GIZMO]], [[THICK_THIS]]) // CHECK-NEXT: return // CHECK-NEXT: } // NS_RETURNS_RETAINED by family (-copy) func copyFoo() -> Gizmo { return self } // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozit7copyFoo{{.*}} : $@convention(objc_method) (Hoozit) -> @owned Gizmo // CHECK: bb0([[THIS:%.*]] : $Hoozit): // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Hoozit7copyFoo{{.*}} : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return [[RES]] // CHECK-NEXT: } // Override the normal family conventions to make this non-consuming and // returning at +0. func initFoo() -> Gizmo { return self } // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozit7initFoo{{.*}} : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo // CHECK: bb0([[THIS:%.*]] : $Hoozit): // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Hoozit7initFoo{{.*}} : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return [[RES]] // CHECK-NEXT: } var typicalProperty: Gizmo // -- getter // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozitg15typicalPropertyCSo5Gizmo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo { // CHECK: bb0([[SELF:%.*]] : $Hoozit): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref objc_thunks.Hoozit.typicalProperty.getter // CHECK-NEXT: [[GETIMPL:%.*]] = function_ref @_TFC11objc_thunks6Hoozitg15typicalPropertyCSo5Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[GETIMPL]]([[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: return [[RES]] : $Gizmo // CHECK-NEXT: } // CHECK-LABEL: sil hidden @_TFC11objc_thunks6Hoozitg15typicalPropertyCSo5Gizmo : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK: bb0(%0 : $Hoozit): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: [[ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Hoozit.typicalProperty // CHECK-NEXT: [[RES:%.*]] = load [copy] [[ADDR]] {{.*}} // CHECK-NEXT: return [[RES]] // -- setter // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozits15typicalPropertyCSo5Gizmo : $@convention(objc_method) (Gizmo, Hoozit) -> () { // CHECK: bb0([[VALUE:%.*]] : $Gizmo, [[THIS:%.*]] : $Hoozit): // CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] : $Gizmo // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] : $Hoozit // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: // function_ref objc_thunks.Hoozit.typicalProperty.setter // CHECK: [[FR:%.*]] = function_ref @_TFC11objc_thunks6Hoozits15typicalPropertyCSo5Gizmo // CHECK: [[RES:%.*]] = apply [[FR]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]]) // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: return [[RES]] : $(), scope {{.*}} // id: {{.*}} line:[[@LINE-32]]:7:auto_gen // CHECK: } // end sil function '_TToFC11objc_thunks6Hoozits15typicalPropertyCSo5Gizmo' // CHECK-LABEL: sil hidden @_TFC11objc_thunks6Hoozits15typicalPropertyCSo5Gizmo // CHECK: bb0([[ARG0:%.*]] : $Gizmo, [[ARG1:%.*]] : $Hoozit): // CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK: [[ARG0_COPY:%.*]] = copy_value [[BORROWED_ARG0]] // CHECK: [[ADDR:%.*]] = ref_element_addr [[ARG1]] : {{.*}}, #Hoozit.typicalProperty // CHECK: assign [[ARG0_COPY]] to [[ADDR]] : $*Gizmo // CHECK: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK: destroy_value [[ARG0]] // CHECK: } // end sil function '_TFC11objc_thunks6Hoozits15typicalPropertyCSo5Gizmo' // NS_RETURNS_RETAINED getter by family (-copy) var copyProperty: Gizmo // -- getter // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozitg12copyPropertyCSo5Gizmo : $@convention(objc_method) (Hoozit) -> @owned Gizmo { // CHECK: bb0([[SELF:%.*]] : $Hoozit): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref objc_thunks.Hoozit.copyProperty.getter // CHECK-NEXT: [[FR:%.*]] = function_ref @_TFC11objc_thunks6Hoozitg12copyPropertyCSo5Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[FR]]([[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: return [[RES]] // CHECK-NEXT: } // CHECK-LABEL: sil hidden @_TFC11objc_thunks6Hoozitg12copyPropertyCSo5Gizmo // CHECK: bb0(%0 : $Hoozit): // CHECK: [[ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Hoozit.copyProperty // CHECK-NEXT: [[RES:%.*]] = load [copy] [[ADDR]] // CHECK-NEXT: return [[RES]] // -- setter is normal // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozits12copyPropertyCSo5Gizmo : $@convention(objc_method) (Gizmo, Hoozit) -> () { // CHECK: bb0([[VALUE:%.*]] : $Gizmo, [[THIS:%.*]] : $Hoozit): // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref objc_thunks.Hoozit.copyProperty.setter // CHECK-NEXT: [[FR:%.*]] = function_ref @_TFC11objc_thunks6Hoozits12copyPropertyCSo5Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[FR]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return [[RES]] // CHECK-LABEL: sil hidden @_TFC11objc_thunks6Hoozits12copyPropertyCSo5Gizmo // CHECK: bb0([[ARG1:%.*]] : $Gizmo, [[SELF:%.*]] : $Hoozit): // CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]] // CHECK: [[ARG1_COPY:%.*]] = copy_value [[BORROWED_ARG1]] // CHECK: [[ADDR:%.*]] = ref_element_addr [[SELF]] : {{.*}}, #Hoozit.copyProperty // CHECK: assign [[ARG1_COPY]] to [[ADDR]] // CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]] // CHECK: destroy_value [[ARG1]] // CHECK: } // end sil function '_TFC11objc_thunks6Hoozits12copyPropertyCSo5Gizmo' var roProperty: Gizmo { return self } // -- getter // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozitg10roPropertyCSo5Gizmo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo { // CHECK: bb0([[THIS:%.*]] : $Hoozit): // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Hoozitg10roPropertyCSo5Gizmo : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] : $Hoozit // CHECK-NEXT: return [[RES]] : $Gizmo // CHECK-NEXT: } // end sil function '_TToFC11objc_thunks6Hoozitg10roPropertyCSo5Gizmo' // -- no setter // CHECK-NOT: sil hidden [thunk] @_TToFC11objc_thunks6Hoozits10roPropertyCSo5Gizmo var rwProperty: Gizmo { get { return self } set {} } // -- getter // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozitg10rwPropertyCSo5Gizmo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo // -- setter // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozits10rwPropertyCSo5Gizmo : $@convention(objc_method) (Gizmo, Hoozit) -> () { // CHECK: bb0([[VALUE:%.*]] : $Gizmo, [[THIS:%.*]] : $Hoozit): // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Hoozits10rwPropertyCSo5Gizmo : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> () // CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return // CHECK-NEXT: } var copyRWProperty: Gizmo { get { return self } set {} } // -- getter // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozitg14copyRWPropertyCSo5Gizmo : $@convention(objc_method) (Hoozit) -> @owned Gizmo { // CHECK: bb0([[THIS:%.*]] : $Hoozit): // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Hoozitg14copyRWPropertyCSo5Gizmo : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NOT: return // CHECK-NEXT: return [[RES]] // CHECK-NEXT: } // -- setter is normal // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozits14copyRWPropertyCSo5Gizmo : $@convention(objc_method) (Gizmo, Hoozit) -> () { // CHECK: bb0([[VALUE:%.*]] : $Gizmo, [[THIS:%.*]] : $Hoozit): // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Hoozits14copyRWPropertyCSo5Gizmo : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> () // CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return // CHECK-NEXT: } var initProperty: Gizmo // -- getter // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozitg12initPropertyCSo5Gizmo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo { // CHECK: bb0([[THIS:%.*]] : $Hoozit): // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Hoozitg12initPropertyCSo5Gizmo : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return [[RES]] // CHECK-NEXT: } // -- setter // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozits12initPropertyCSo5Gizmo : $@convention(objc_method) (Gizmo, Hoozit) -> () { // CHECK: bb0([[VALUE:%.*]] : $Gizmo, [[THIS:%.*]] : $Hoozit): // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Hoozits12initPropertyCSo5Gizmo : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> () // CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return // CHECK-NEXT: } var propComputed: Gizmo { @objc(initPropComputedGetter) get { return self } @objc(initPropComputedSetter:) set {} } // -- getter // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozitg12propComputedCSo5Gizmo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo { // CHECK: bb0([[THIS:%.*]] : $Hoozit): // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Hoozitg12propComputedCSo5Gizmo : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return [[RES]] // CHECK-NEXT: } // -- setter // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozits12propComputedCSo5Gizmo : $@convention(objc_method) (Gizmo, Hoozit) -> () { // CHECK: bb0([[VALUE:%.*]] : $Gizmo, [[THIS:%.*]] : $Hoozit): // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Hoozits12propComputedCSo5Gizmo : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> () // CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return // CHECK-NEXT: } // Don't export generics to ObjC yet func generic<T>(_ x: T) {} // CHECK-NOT: sil hidden [thunk] @_TToFC11objc_thunks6Hoozit7generic{{.*}} // Constructor. // CHECK-LABEL: sil hidden @_TFC11objc_thunks6Hoozitc{{.*}} : $@convention(method) (Int, @owned Hoozit) -> @owned Hoozit { // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Hoozit } // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELFMUI:%[0-9]+]] = mark_uninitialized [derivedself] [[PB]] // CHECK: [[GIZMO:%[0-9]+]] = upcast [[SELF:%[0-9]+]] : $Hoozit to $Gizmo // CHECK: [[SUPERMETHOD:%[0-9]+]] = super_method [volatile] [[SELF]] : $Hoozit, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> (Int) -> Gizmo!, $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo> // CHECK-NEXT: [[SELF_REPLACED:%[0-9]+]] = apply [[SUPERMETHOD]](%0, [[X:%[0-9]+]]) : $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo> // CHECK-NOT: unconditional_checked_cast downcast [[SELF_REPLACED]] : $Gizmo to $Hoozit // CHECK: unchecked_ref_cast // CHECK: return override init(bellsOn x : Int) { super.init(bellsOn: x) other() } // Subscript subscript (i: Int) -> Hoozit { // Getter // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozitg9subscript{{.*}} : $@convention(objc_method) (Int, Hoozit) -> @autoreleased Hoozit // CHECK: bb0([[I:%[0-9]+]] : $Int, [[SELF:%[0-9]+]] : $Hoozit): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Hoozit // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%[0-9]+]] = function_ref @_TFC11objc_thunks6Hoozitg9subscript{{.*}} : $@convention(method) (Int, @guaranteed Hoozit) -> @owned Hoozit // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[NATIVE]]([[I]], [[BORROWED_SELF_COPY]]) : $@convention(method) (Int, @guaranteed Hoozit) -> @owned Hoozit // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: return [[RESULT]] : $Hoozit get { return self } // Setter // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozits9subscript{{.*}} : $@convention(objc_method) (Hoozit, Int, Hoozit) -> () // CHECK: bb0([[VALUE:%[0-9]+]] : $Hoozit, [[I:%[0-9]+]] : $Int, [[SELF:%[0-9]+]] : $Hoozit): // CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] : $Hoozit // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Hoozit // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NATIVE:%[0-9]+]] = function_ref @_TFC11objc_thunks6Hoozits9subscript{{.*}} : $@convention(method) (@owned Hoozit, Int, @guaranteed Hoozit) -> () // CHECK: [[RESULT:%[0-9]+]] = apply [[NATIVE]]([[VALUE_COPY]], [[I]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Hoozit, Int, @guaranteed Hoozit) -> () // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: return [[RESULT]] : $() // CHECK: } // end sil function '_TToFC11objc_thunks6Hoozits9subscript{{.*}}' set {} } } class Wotsit<T> : Gizmo { // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Wotsit5plain{{.*}} : $@convention(objc_method) <T> (Wotsit<T>) -> () { // CHECK: bb0([[SELF:%.*]] : $Wotsit<T>): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Wotsit<T> // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Wotsit5plain{{.*}} : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> () // CHECK-NEXT: [[RESULT:%.*]] = apply [[NATIVE]]<T>([[BORROWED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> () // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] : $Wotsit<T> // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } func plain() { } func generic<U>(_ x: U) {} var property : T init(t: T) { self.property = t super.init() } // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Wotsitg11descriptionSS : $@convention(objc_method) <T> (Wotsit<T>) -> @autoreleased NSString { // CHECK: bb0([[SELF:%.*]] : $Wotsit<T>): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Wotsit<T> // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Wotsitg11descriptionSS : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> @owned String // CHECK-NEXT: [[RESULT:%.*]] = apply [[NATIVE:%.*]]<T>([[BORROWED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> @owned String // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] : $Wotsit<T> // CHECK-NEXT: // function_ref // CHECK-NEXT: [[BRIDGE:%.*]] = function_ref @_TFE10FoundationSS19_bridgeToObjectiveCfT_CSo8NSString // CHECK-NEXT: [[BORROWED_RESULT:%.*]] = begin_borrow [[RESULT]] // CHECK-NEXT: [[NSRESULT:%.*]] = apply [[BRIDGE]]([[BORROWED_RESULT]]) : $@convention(method) (@guaranteed String) -> @owned NSString // CHECK-NEXT: end_borrow [[BORROWED_RESULT]] from [[RESULT]] // CHECK-NEXT: destroy_value [[RESULT]] // CHECK-NEXT: return [[NSRESULT]] : $NSString // CHECK-NEXT: } override var description : String { return "Hello, world." } // Ivar destroyer // CHECK: sil hidden @_TToF{{.*}}WotsitE // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6WotsitcfT_GSQGS0_x__ : $@convention(objc_method) <T> (@owned Wotsit<T>) -> @owned Optional<Wotsit<T>> // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6WotsitcfT7bellsOnSi_GSQGS0_x__ : $@convention(objc_method) <T> (Int, @owned Wotsit<T>) -> @owned Optional<Wotsit<T>> } // CHECK-NOT: sil hidden [thunk] @_TToF{{.*}}Wotsit{{.*}} // Extension initializers, properties and methods need thunks too. extension Hoozit { // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozitc{{.*}} : $@convention(objc_method) (Int, @owned Hoozit) -> @owned Hoozit dynamic convenience init(int i: Int) { self.init(bellsOn: i) } // CHECK-LABEL: sil hidden @_TFC11objc_thunks6Hoozitc{{.*}} : $@convention(method) (Double, @owned Hoozit) -> @owned Hoozit convenience init(double d: Double) { // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Hoozit } // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELFMUI:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] // CHECK: [[X_BOX:%[0-9]+]] = alloc_box ${ var X } var x = X() // CHECK: [[CTOR:%[0-9]+]] = class_method [volatile] [[SELF:%[0-9]+]] : $Hoozit, #Hoozit.init!initializer.1.foreign : (Hoozit.Type) -> (Int) -> Hoozit, $@convention(objc_method) (Int, @owned Hoozit) -> @owned Hoozit // CHECK: [[NEW_SELF:%[0-9]+]] = apply [[CTOR]] // CHECK: store [[NEW_SELF]] to [init] [[SELFMUI]] : $*Hoozit // CHECK: [[NONNULL:%[0-9]+]] = is_nonnull [[NEW_SELF]] : $Hoozit // CHECK-NEXT: cond_br [[NONNULL]], [[NONNULL_BB:bb[0-9]+]], [[NULL_BB:bb[0-9]+]] // CHECK: [[NULL_BB]]: // CHECK-NEXT: destroy_value [[X_BOX]] : ${ var X } // CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]] // CHECK: [[NONNULL_BB]]: // CHECK: [[OTHER_REF:%[0-9]+]] = function_ref @_TF11objc_thunks5otherFT_T_ : $@convention(thin) () -> () // CHECK-NEXT: apply [[OTHER_REF]]() : $@convention(thin) () -> () // CHECK-NEXT: destroy_value [[X_BOX]] : ${ var X } // CHECK-NEXT: br [[EPILOG_BB]] // CHECK: [[EPILOG_BB]]: // CHECK-NOT: super_method // CHECK: return self.init(int:Int(d)) other() } func foof() {} // CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozit4foof{{.*}} : $@convention(objc_method) (Hoozit) -> () { var extensionProperty: Int { return 0 } // CHECK-LABEL: sil hidden @_TFC11objc_thunks6Hoozitg17extensionPropertySi : $@convention(method) (@guaranteed Hoozit) -> Int } // Calling objc methods of subclass should go through native entry points func useHoozit(_ h: Hoozit) { // sil @_TF11objc_thunks9useHoozitFT1hC11objc_thunks6Hoozit_T_ // In the class decl, gets dynamically dispatched h.fork() // CHECK: class_method {{%.*}} : {{.*}}, #Hoozit.fork!1 : // In an extension, 'dynamic' was inferred. h.foof() // CHECK: class_method [volatile] {{%.*}} : {{.*}}, #Hoozit.foof!1.foreign } func useWotsit(_ w: Wotsit<String>) { // sil @_TF11objc_thunks9useWotsitFT1wGCSo6WotsitSS__T_ w.plain() // CHECK: class_method {{%.*}} : {{.*}}, #Wotsit.plain!1 : w.generic(2) // CHECK: class_method {{%.*}} : {{.*}}, #Wotsit.generic!1 : // Inherited methods only have objc entry points w.clone() // CHECK: class_method [volatile] {{%.*}} : {{.*}}, #Gizmo.clone!1.foreign } func other() { } class X { } // CHECK-LABEL: sil hidden @_TF11objc_thunks8property func property(_ g: Gizmo) -> Int { // CHECK: bb0([[ARG:%.*]] : $Gizmo): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $Gizmo, #Gizmo.count!getter.1.foreign return g.count } // CHECK-LABEL: sil hidden @_TF11objc_thunks13blockProperty func blockProperty(_ g: Gizmo) { // CHECK: bb0([[ARG:%.*]] : $Gizmo): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $Gizmo, #Gizmo.block!setter.1.foreign g.block = { } // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $Gizmo, #Gizmo.block!getter.1.foreign g.block() } class DesignatedStubs : Gizmo { var i: Int override init() { i = 5 } // CHECK-LABEL: sil hidden @_TFC11objc_thunks15DesignatedStubsc{{.*}} // CHECK: function_ref @_TFs25_unimplementedInitializer // CHECK: string_literal utf8 "objc_thunks.DesignatedStubs" // CHECK: string_literal utf8 "init(bellsOn:)" // CHECK: string_literal utf8 "{{.*}}objc_thunks.swift" // CHECK: return // CHECK-NOT: sil hidden @_TFCSo15DesignatedStubsc{{.*}} } class DesignatedOverrides : Gizmo { var i: Int = 5 // CHECK-LABEL: sil hidden @_TFC11objc_thunks19DesignatedOverridesc{{.*}} // CHECK-NOT: return // CHECK: function_ref @_TIvC11objc_thunks19DesignatedOverrides1iSii : $@convention(thin) () -> Int // CHECK: super_method [volatile] [[SELF:%[0-9]+]] : $DesignatedOverrides, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> () -> Gizmo!, $@convention(objc_method) (@owned Gizmo) -> @owned Optional<Gizmo> // CHECK: return // CHECK-LABEL: sil hidden @_TFC11objc_thunks19DesignatedOverridesc{{.*}} // CHECK: function_ref @_TIvC11objc_thunks19DesignatedOverrides1iSii : $@convention(thin) () -> Int // CHECK: super_method [volatile] [[SELF:%[0-9]+]] : $DesignatedOverrides, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> (Int) -> Gizmo!, $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo> // CHECK: return } // Make sure we copy blocks passed in as IUOs - <rdar://problem/22471309> func registerAnsible() { // CHECK: function_ref @_TFF11objc_thunks15registerAnsibleFT_T_U_FGSqFT_T__T_ Ansible.anseAsync({ completion in completion!() }) }
apache-2.0
84e542417dab8a76b59c16390ddfdb6a
52.83871
222
0.616466
3.321587
false
false
false
false
naeemshaikh90/Reading-List
Stanford/cs193p-2017/Calculator/Calculator/CalculatorBrain.swift
1
4591
/** * Created by Naeem Shaikh on 01/03/17. * * Copyright © 2017-present Naeem Shaikh * * 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 struct CalculatorBrain { mutating func addUnaryOperation(named symbol: String, _ operation: @escaping (Double) -> Double) { operations[symbol] = Operation.unaryOperation(operation) } private var accumulator: Double? private enum Operation { case constant(Double) case unaryOperation((Double) -> Double) case binaryOperation((Double, Double) -> Double) case equals } private var operations: Dictionary<String, Operation> = [ "π" : Operation.constant(Double.pi), "e" : Operation.constant(M_E), "√" : Operation.unaryOperation(sqrt), "cos" : Operation.unaryOperation(cos), "sin" : Operation.unaryOperation(sin), "±" : Operation.unaryOperation({ -$0 }), "%" : Operation.unaryOperation({ $0 / 100 }), "×" : Operation.binaryOperation({ $0 * $1 }), "÷" : Operation.binaryOperation({ $0 / $1 }), "+" : Operation.binaryOperation({ $0 + $1 }), "−" : Operation.binaryOperation({ $0 - $1 }), "=" : Operation.equals ] mutating func performOperation(_ symbol: String) { if let operation = operations[symbol] { switch operation { case .constant(let value): accumulator = value case .unaryOperation(let function): if accumulator != nil { accumulator = function(accumulator!) } case .binaryOperation(let function): if accumulator != nil { pendingBinaryOperation = PendingBinaryOperation(function: function, firstOperand: accumulator!) accumulator = nil } case .equals: perfomrPendingBinaryOperation() } } } private mutating func perfomrPendingBinaryOperation() { if pendingBinaryOperation != nil && accumulator != nil { accumulator = pendingBinaryOperation!.perform(with: accumulator!) pendingBinaryOperation = nil } } private var pendingBinaryOperation: PendingBinaryOperation? /** * 5. Add a Bool property to your CalculatorBrain called resultIsPending which * returns whether there is a binary operation pending. */ private var resultIsPending: Bool { get { return pendingBinaryOperation != nil } } /** * 6. Add a String property to your CalculatorBrain called description which returns a description of * the sequence of operands and operations that led to the value returned by result (or the result so * far if resultIsPending). The character = (the equals sign) should never appear in this description, * nor should ... (ellipses). */ var description: String? private struct PendingBinaryOperation { let function: (Double, Double) -> Double let firstOperand: Double func perform(with secondOperand: Double) -> Double { return function(firstOperand, secondOperand) } } mutating func setOperand(_ operand: Double) { accumulator = operand } var result: Double? { get { return accumulator } } }
mit
a6b166902a701a501ec13b292c640115
35.656
106
0.618944
5.051819
false
false
false
false
stevestreza/Relayout
Framework/Layout/ViewLayout.swift
1
3157
import Foundation #if os(OSX) import AppKit #else import UIKit #endif /// Manages a context of NSLayoutConstraint objects that will be applied to a given view. public class ViewLayout { /// The root view that will have its layout managed by the ViewLayout. public let rootView: UIView /// The LayingOut objects that will define the layout for the rootView. public let layouts: [LayingOut] /** Creates a new ViewLayout with the given rootView and LayingOut objects. - parameter rootView: The root view that will have its layout managed by the ViewLayout. - parameter layouts: The LayingOut objects that will define the layout for the rootView. - returns: A new ViewLayout for the given rootView and LayingOut objects. */ public init(rootView: UIView, layouts: [LayingOut]) { self.rootView = rootView self.layouts = layouts } /** Creates a new ViewLayout with the given rootView and a single LayingOut object. - parameter rootView: The root view that will have its layout managed by the ViewLayout. - parameter layout: The LayingOut object that will define the layout for the rootView. - returns: A new ViewLayout for the given rootView and LayingOut object. */ public convenience init(rootView: UIView, layout: LayingOut) { self.init(rootView: rootView, layouts: [layout]) } private(set) var activeConstraints: [NSLayoutConstraint] = [] private var isLayingOut = false /** Deactivates the NSLayoutConstraint objects previously on the view, generates a new Array<NSLayoutConstraint> to apply to the view, and then activates those. - note: You can call this from within a UIView animation context and your view will animate into place. If you're adding new views to the layout, consider pre-setting their `frame` property to define their starting position. - note: This method is reentrant, but will not recalculate NSLayoutConstraint objects, so you can call this from methods that may themselves trigger a layout (but nothing will happen subsequently). */ public func layout() { guard isLayingOut == false else { return } isLayingOut = true NSLayoutConstraint.deactivateConstraints(activeConstraints) activeConstraints = layouts.flatMap { $0.constraints(in: self.rootView) } NSLayoutConstraint.activateConstraints(activeConstraints) #if os(OSX) rootView.needsLayout = true rootView.updateConstraintsForSubtreeIfNeeded() rootView.layoutSubtreeIfNeeded() #else rootView.setNeedsLayout() rootView.layoutIfNeeded() #endif isLayingOut = false } } public extension LayingOut { /** Creates a new ViewLayout from the given LayingOut object and a root view. - parameter rootView: The root view that will have its layout managed by the ViewLayout. - returns: A new ViewLayout for the given rootView and LayingOut object. */ public func viewLayout(withRootView rootView: UIView) -> ViewLayout { return ViewLayout(rootView: rootView, layout: self) } }
isc
56fdbd43b8e756f34e96fd0ff9a844ba
34.875
99
0.713652
4.956044
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/Cells/HLHotelDetailsNoPriceCell.swift
1
1884
fileprivate func < <T: Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T: Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } class HLHotelDetailsNoPriceCell: HLHotelDetailsTableCell { @IBOutlet fileprivate weak var noPriceLabel: UILabel! @IBOutlet fileprivate(set) weak var changeButton: UIButton! private static let textFont = UIFont.systemFont(ofSize: 15.0) var noPriceReasonText: String = "" { didSet { noPriceLabel.text = noPriceReasonText } } var changeHandler: (() -> Void)! class func estimatedHeight(_ text: String?, width: CGFloat, canChangeSearchInfo: Bool) -> CGFloat { guard canChangeSearchInfo || !text.isNilOrEmpty() else { return 0.0 } let topMargin: CGFloat = 5.0 var textHeight: CGFloat = 0.0 if text?.count > 0 { let horizontalMargin: CGFloat = 15.0 textHeight = text!.hl_height(attributes: [NSAttributedString.Key.font: HLHotelDetailsNoPriceCell.textFont], width: width - 2 * horizontalMargin) } let spaceBetweenButtonAndText: CGFloat = 15.0 let buttonHeight: CGFloat = canChangeSearchInfo ? 40.0 : 0.0 let bottomMargin: CGFloat = 20.0 return topMargin + textHeight + spaceBetweenButtonAndText + buttonHeight + bottomMargin } @IBAction func changeButtonPressed(_ sender: AnyObject) { changeHandler() } override func awakeFromNib() { super.awakeFromNib() noPriceReasonText = "" noPriceLabel.font = HLHotelDetailsNoPriceCell.textFont changeButton.backgroundColor = JRColorScheme.actionColor() } }
mit
4505dca33ccf0ebb7373f6f58fffcb1f
28.904762
156
0.635881
4.331034
false
false
false
false
jianlong108/Swift
SwiftApp/SwiftApp/首页/HomeTableViewCell.swift
1
1743
// // HomeTableViewCell.swift // SwiftApp // // Created by Wangjianlong on 16/1/24. // Copyright © 2016年 JL. All rights reserved. // import UIKit class HomeTableViewCell: UITableViewCell { var iconView:UIImageView? var topLabel:UILabel? var acceoryLabel:UILabel? var contentLabel:UILabel? var timeLabel:UILabel? // var dataModel:HomeProtocol? var dataModel:HomeDataModel? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.iconView = UIImageView.init(frame: CGRectZero) self.topLabel = UILabel.init(frame: CGRectZero) self.acceoryLabel = UILabel.init(frame: CGRectZero) self.contentLabel = UILabel.init(frame: CGRectZero) self.timeLabel = UILabel.init(frame: CGRectZero) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setData(dataModel:HomeDataModel)->Void{ self.dataModel = dataModel self.textLabel?.text = dataModel.title } private let margin:CGFloat = 10.0 // override func layoutSubviews() { // super.layoutSubviews() // // let width = self.frame.size.width // let height = self.frame.size.height // // self.iconView?.frame = CGRectMake(margin, margin, 30, 30) // self.topLabel?.frame = CGRectMake(CGRectGetMaxX(iconView!.frame)+margin, margin, width-margin-CGRectGetMaxX(iconView!.frame)+margin, 20) // self.acceoryLabel?.frame = CGRectMake(<#T##x: CGFloat##CGFloat#>, <#T##y: CGFloat##CGFloat#>, <#T##width: CGFloat##CGFloat#>, <#T##height: CGFloat##CGFloat#>) // } }
apache-2.0
897288a9abca4326b9d68f98f6939c91
33.8
168
0.658046
4.142857
false
false
false
false
zisko/swift
test/attr/attr_autoclosure.swift
2
6348
// RUN: %target-typecheck-verify-swift // Simple case. var fn : @autoclosure () -> Int = 4 // expected-error {{@autoclosure may only be used on parameters}} expected-error {{cannot convert value of type 'Int' to specified type '() -> Int'}} @autoclosure func func1() {} // expected-error {{attribute can only be applied to types, not declarations}} func func1a(_ v1 : @autoclosure Int) {} // expected-error {{@autoclosure attribute only applies to function types}} func func2(_ fp : @autoclosure () -> Int) { func2(4)} func func3(fp fpx : @autoclosure () -> Int) {func3(fp: 0)} func func4(fp : @autoclosure () -> Int) {func4(fp: 0)} func func6(_: @autoclosure () -> Int) {func6(0)} // autoclosure + inout doesn't make sense. func func8(_ x: inout @autoclosure () -> Bool) -> Bool { // expected-error {{@autoclosure may only be used on parameters}} } func func9(_ x: @autoclosure (Int) -> Bool) {} // expected-error {{argument type of @autoclosure parameter must be '()'}} func func10(_ x: @autoclosure (Int, String, Int) -> Void) {} // expected-error {{argument type of @autoclosure parameter must be '()'}} // <rdar://problem/19707366> QoI: @autoclosure declaration change fixit let migrate4 : (@autoclosure() -> ()) -> () struct SomeStruct { @autoclosure let property : () -> Int // expected-error {{attribute can only be applied to types, not declarations}} init() { } } class BaseClass { @autoclosure var property : () -> Int // expected-error {{attribute can only be applied to types, not declarations}} init() {} } class DerivedClass { var property : () -> Int { get {} set {} } } protocol P1 { associatedtype Element } protocol P2 : P1 { associatedtype Element } func overloadedEach<O: P1>(_ source: O, _ closure: @escaping () -> ()) { } func overloadedEach<P: P2>(_ source: P, _ closure: @escaping () -> ()) { } struct S : P2 { typealias Element = Int func each(_ closure: @autoclosure () -> ()) { // expected-note@-1{{parameter 'closure' is implicitly non-escaping}} overloadedEach(self, closure) // expected-error {{passing non-escaping parameter 'closure' to function expecting an @escaping closure}} } } struct AutoclosureEscapeTest { @autoclosure let delayed: () -> Int // expected-error {{attribute can only be applied to types, not declarations}} } // @autoclosure(escaping) // expected-error @+1 {{attribute can only be applied to types, not declarations}} func func10(@autoclosure(escaping _: () -> ()) { } // expected-error{{expected parameter name followed by ':'}} func func11(_: @autoclosure(escaping) @noescape () -> ()) { } // expected-error{{@escaping conflicts with @noescape}} // expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{28-38= @escaping}} class Super { func f1(_ x: @autoclosure(escaping) () -> ()) { } // expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{28-38= @escaping}} func f2(_ x: @autoclosure(escaping) () -> ()) { } // expected-note {{potential overridden instance method 'f2' here}} // expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{28-38= @escaping}} func f3(x: @autoclosure () -> ()) { } } class Sub : Super { override func f1(_ x: @autoclosure(escaping)() -> ()) { } // expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{37-47= @escaping }} override func f2(_ x: @autoclosure () -> ()) { } // expected-error{{does not override any method}} // expected-note{{type does not match superclass instance method with type '(@autoclosure @escaping () -> ()) -> ()'}} override func f3(_ x: @autoclosure(escaping) () -> ()) { } // expected-error{{does not override any method}} // expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{37-47= @escaping}} } func func12_sink(_ x: @escaping () -> Int) { } func func12a(_ x: @autoclosure () -> Int) { // expected-note@-1{{parameter 'x' is implicitly non-escaping}} func12_sink(x) // expected-error {{passing non-escaping parameter 'x' to function expecting an @escaping closure}} } func func12b(_ x: @autoclosure(escaping) () -> Int) { // expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{31-41= @escaping}} func12_sink(x) // ok } func func12c(_ x: @autoclosure @escaping () -> Int) { func12_sink(x) // ok } func func12d(_ x: @escaping @autoclosure () -> Int) { func12_sink(x) // ok } class TestFunc12 { var x: Int = 5 func foo() -> Int { return 0 } func test() { func12a(x + foo()) // okay func12b(x + foo()) // expected-error@-1{{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{13-13=self.}} // expected-error@-2{{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{17-17=self.}} } } enum AutoclosureFailableOf<T> { case Success(@autoclosure () -> T) // expected-error {{@autoclosure may only be used on parameters}} case Failure() } let _ : (@autoclosure () -> ()) -> () let _ : (@autoclosure(escaping) () -> ()) -> () // expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{22-32= @escaping}} // escaping is the name of param type let _ : (@autoclosure(escaping) -> ()) -> () // expected-error {{use of undeclared type 'escaping'}} // expected-error@-1 {{argument type of @autoclosure parameter must be '()'}} // Migration // expected-error @+1 {{attribute can only be applied to types, not declarations}} func migrateAC(@autoclosure _: () -> ()) { } // expected-error @+1 {{attribute can only be applied to types, not declarations}} func migrateACE(@autoclosure(escaping) _: () -> ()) { } func takesAutoclosure(_ fn: @autoclosure () -> Int) {} func callAutoclosureWithNoEscape(_ fn: () -> Int) { takesAutoclosure(1+1) // ok } func callAutoclosureWithNoEscape_2(_ fn: () -> Int) { takesAutoclosure(fn()) // ok } func callAutoclosureWithNoEscape_3(_ fn: @autoclosure () -> Int) { takesAutoclosure(fn()) // ok } // expected-error @+1 {{@autoclosure must not be used on variadic parameters}} func variadicAutoclosure(_ fn: @autoclosure () -> ()...) { for _ in fn {} }
apache-2.0
20d9c86f34d254ff1d59a35c2ec738ae
38.428571
219
0.657687
3.765125
false
false
false
false
zisko/swift
test/Sema/enum_equatable_hashable.swift
1
7776
// RUN: %empty-directory(%t) // RUN: cp %s %t/main.swift // RUN: %target-swift-frontend -typecheck -verify -primary-file %t/main.swift %S/Inputs/enum_equatable_hashable_other.swift -verify-ignore-unknown enum Foo { case A, B } if Foo.A == .B { } var aHash: Int = Foo.A.hashValue Foo.A == Foo.B // expected-warning {{result of operator '==' is unused}} enum Generic<T> { case A, B static func method() -> Int { // Test synthesis of == without any member lookup being done if A == B { } return Generic.A.hashValue } } if Generic<Foo>.A == .B { } var gaHash: Int = Generic<Foo>.A.hashValue func localEnum() -> Bool { enum Local { case A, B } return Local.A == .B } enum CustomHashable { case A, B var hashValue: Int { return 0 } } func ==(x: CustomHashable, y: CustomHashable) -> Bool { // expected-note 4 {{non-matching type}} return true } if CustomHashable.A == .B { } var custHash: Int = CustomHashable.A.hashValue // We still synthesize conforming overloads of '==' and 'hashValue' if // explicit definitions don't satisfy the protocol requirements. Probably // not what we actually want. enum InvalidCustomHashable { case A, B var hashValue: String { return "" } // expected-note{{previously declared here}} } func ==(x: InvalidCustomHashable, y: InvalidCustomHashable) -> String { // expected-note 4 {{non-matching type}} return "" } if InvalidCustomHashable.A == .B { } var s: String = InvalidCustomHashable.A == .B s = InvalidCustomHashable.A.hashValue var i: Int = InvalidCustomHashable.A.hashValue // Check use of an enum's synthesized members before the enum is actually declared. struct UseEnumBeforeDeclaration { let eqValue = EnumToUseBeforeDeclaration.A == .A let hashValue = EnumToUseBeforeDeclaration.A.hashValue } enum EnumToUseBeforeDeclaration { case A } // Check enums from another file in the same module. if FromOtherFile.A == .A {} let _: Int = FromOtherFile.A.hashValue func getFromOtherFile() -> AlsoFromOtherFile { return .A } if .A == getFromOtherFile() {} func overloadFromOtherFile() -> YetAnotherFromOtherFile { return .A } func overloadFromOtherFile() -> Bool { return false } if .A == overloadFromOtherFile() {} // Complex enums are not implicitly Equatable or Hashable. enum Complex { case A(Int) case B } if Complex.A(1) == .B { } // expected-error{{binary operator '==' cannot be applied to operands of type 'Complex' and '_'}} // expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: }} // Enums with equatable payloads are equatable if they explicitly conform. enum EnumWithEquatablePayload: Equatable { case A(Int) case B(String, Int) case C } if EnumWithEquatablePayload.A(1) == .B("x", 1) { } if EnumWithEquatablePayload.A(1) == .C { } if EnumWithEquatablePayload.B("x", 1) == .C { } // Enums with hashable payloads are hashable if they explicitly conform. enum EnumWithHashablePayload: Hashable { case A(Int) case B(String, Int) case C } _ = EnumWithHashablePayload.A(1).hashValue _ = EnumWithHashablePayload.B("x", 1).hashValue _ = EnumWithHashablePayload.C.hashValue // ...and they should also inherit equatability from Hashable. if EnumWithHashablePayload.A(1) == .B("x", 1) { } if EnumWithHashablePayload.A(1) == .C { } if EnumWithHashablePayload.B("x", 1) == .C { } // Enums with non-hashable payloads don't derive conformance. struct NotHashable {} enum EnumWithNonHashablePayload: Hashable { // expected-error 2 {{does not conform}} case A(NotHashable) } // Enums should be able to derive conformances based on the conformances of // their generic arguments. enum GenericHashable<T: Hashable>: Hashable { case A(T) case B } if GenericHashable<String>.A("a") == .B { } var genericHashableHash: Int = GenericHashable<String>.A("a").hashValue // But it should be an error if the generic argument doesn't have the necessary // constraints to satisfy the conditions for derivation. enum GenericNotHashable<T: Equatable>: Hashable { // expected-error {{does not conform}} case A(T) case B } if GenericNotHashable<String>.A("a") == .B { } var genericNotHashableHash: Int = GenericNotHashable<String>.A("a").hashValue // expected-error {{value of type 'GenericNotHashable<String>' has no member 'hashValue'}} // An enum with no cases should not derive conformance. enum NoCases: Hashable {} // expected-error 2 {{does not conform}} // rdar://19773050 private enum Bar<T> { case E(Unknown<T>) // expected-error {{use of undeclared type 'Unknown'}} mutating func value() -> T { switch self { // FIXME: Should diagnose here that '.' needs to be inserted, but E has an ErrorType at this point case E(let x): return x.value } } } // Equatable extension -- rdar://20981254 enum Instrument { case Piano case Violin case Guitar } extension Instrument : Equatable {} // Explicit conformance should work too public enum Medicine { case Antibiotic case Antihistamine } extension Medicine : Equatable {} public func ==(lhs: Medicine, rhs: Medicine) -> Bool { // expected-note 3 {{non-matching type}} return true } // No explicit conformance; it could be derived, but we don't support extensions // yet. extension Complex : Hashable {} // expected-error 2 {{cannot be automatically synthesized in an extension}} // No explicit conformance and it cannot be derived. enum NotExplicitlyHashableAndCannotDerive { case A(NotHashable) } extension NotExplicitlyHashableAndCannotDerive : Hashable {} // expected-error 2 {{does not conform}} // Verify that conformance (albeit manually implemented) can still be added to // a type in a different file. extension OtherFileNonconforming: Hashable { static func ==(lhs: OtherFileNonconforming, rhs: OtherFileNonconforming) -> Bool { // expected-note 3 {{non-matching type}} return true } var hashValue: Int { return 0 } } // ...but synthesis in a type defined in another file doesn't work yet. extension YetOtherFileNonconforming: Equatable {} // expected-error {{cannot be automatically synthesized in an extension}} // Verify that an indirect enum doesn't emit any errors as long as its "leaves" // are conformant. enum StringBinaryTree: Hashable { indirect case tree(StringBinaryTree, StringBinaryTree) case leaf(String) } // Add some generics to make it more complex. enum BinaryTree<Element: Hashable>: Hashable { indirect case tree(BinaryTree, BinaryTree) case leaf(Element) } // Verify mutually indirect enums. enum MutuallyIndirectA: Hashable { indirect case b(MutuallyIndirectB) case data(Int) } enum MutuallyIndirectB: Hashable { indirect case a(MutuallyIndirectA) case data(Int) } // Verify that it works if the enum itself is indirect, rather than the cases. indirect enum TotallyIndirect: Hashable { case another(TotallyIndirect) case end(Int) } // Check the use of conditional conformances. enum ArrayOfEquatables : Equatable { case only([Int]) } struct NotEquatable { } enum ArrayOfNotEquatables : Equatable { // expected-error{{type 'ArrayOfNotEquatables' does not conform to protocol 'Equatable'}} case only([NotEquatable]) } // FIXME: Remove -verify-ignore-unknown. // <unknown>:0: error: unexpected error produced: invalid redeclaration of 'hashValue' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(Foo, Foo) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '<T> (Generic<T>, Generic<T>) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(InvalidCustomHashable, InvalidCustomHashable) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(EnumToUseBeforeDeclaration, EnumToUseBeforeDeclaration) -> Bool'
apache-2.0
66594b1c9bb62e7186b953b56495b60b
30.481781
168
0.722994
3.859057
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift
14
7012
// // ObserveOn.swift // RxSwift // // Created by Krunoslav Zaher on 7/25/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Wraps the source sequence in order to run its observer callbacks on the specified scheduler. This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription actions have side-effects that require to be run on a scheduler, use `subscribeOn`. - seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html) - parameter scheduler: Scheduler to notify observers on. - returns: The source sequence whose observations happen on the specified scheduler. */ public func observeOn(_ scheduler: ImmediateSchedulerType) -> Observable<Element> { if let scheduler = scheduler as? SerialDispatchQueueScheduler { return ObserveOnSerialDispatchQueue(source: self.asObservable(), scheduler: scheduler) } else { return ObserveOn(source: self.asObservable(), scheduler: scheduler) } } } final private class ObserveOn<Element>: Producer<Element> { let scheduler: ImmediateSchedulerType let source: Observable<Element> init(source: Observable<Element>, scheduler: ImmediateSchedulerType) { self.scheduler = scheduler self.source = source #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { let sink = ObserveOnSink(scheduler: self.scheduler, observer: observer, cancel: cancel) let subscription = self.source.subscribe(sink) return (sink: sink, subscription: subscription) } #if TRACE_RESOURCES deinit { _ = Resources.decrementTotal() } #endif } enum ObserveOnState : Int32 { // pump is not running case stopped = 0 // pump is running case running = 1 } final private class ObserveOnSink<Observer: ObserverType>: ObserverBase<Observer.Element> { typealias Element = Observer.Element let _scheduler: ImmediateSchedulerType var _lock = SpinLock() let _observer: Observer // state var _state = ObserveOnState.stopped var _queue = Queue<Event<Element>>(capacity: 10) let _scheduleDisposable = SerialDisposable() let _cancel: Cancelable init(scheduler: ImmediateSchedulerType, observer: Observer, cancel: Cancelable) { self._scheduler = scheduler self._observer = observer self._cancel = cancel } override func onCore(_ event: Event<Element>) { let shouldStart = self._lock.calculateLocked { () -> Bool in self._queue.enqueue(event) switch self._state { case .stopped: self._state = .running return true case .running: return false } } if shouldStart { self._scheduleDisposable.disposable = self._scheduler.scheduleRecursive((), action: self.run) } } func run(_ state: (), _ recurse: (()) -> Void) { let (nextEvent, observer) = self._lock.calculateLocked { () -> (Event<Element>?, Observer) in if !self._queue.isEmpty { return (self._queue.dequeue(), self._observer) } else { self._state = .stopped return (nil, self._observer) } } if let nextEvent = nextEvent, !self._cancel.isDisposed { observer.on(nextEvent) if nextEvent.isStopEvent { self.dispose() } } else { return } let shouldContinue = self._shouldContinue_synchronized() if shouldContinue { recurse(()) } } func _shouldContinue_synchronized() -> Bool { self._lock.lock(); defer { self._lock.unlock() } // { if !self._queue.isEmpty { return true } else { self._state = .stopped return false } // } } override func dispose() { super.dispose() self._cancel.dispose() self._scheduleDisposable.dispose() } } #if TRACE_RESOURCES fileprivate let _numberOfSerialDispatchQueueObservables = AtomicInt(0) extension Resources { /** Counts number of `SerialDispatchQueueObservables`. Purposed for unit tests. */ public static var numberOfSerialDispatchQueueObservables: Int32 { return load(_numberOfSerialDispatchQueueObservables) } } #endif final private class ObserveOnSerialDispatchQueueSink<Observer: ObserverType>: ObserverBase<Observer.Element> { let scheduler: SerialDispatchQueueScheduler let observer: Observer let cancel: Cancelable var cachedScheduleLambda: (((sink: ObserveOnSerialDispatchQueueSink<Observer>, event: Event<Element>)) -> Disposable)! init(scheduler: SerialDispatchQueueScheduler, observer: Observer, cancel: Cancelable) { self.scheduler = scheduler self.observer = observer self.cancel = cancel super.init() self.cachedScheduleLambda = { pair in guard !cancel.isDisposed else { return Disposables.create() } pair.sink.observer.on(pair.event) if pair.event.isStopEvent { pair.sink.dispose() } return Disposables.create() } } override func onCore(_ event: Event<Element>) { _ = self.scheduler.schedule((self, event), action: self.cachedScheduleLambda!) } override func dispose() { super.dispose() self.cancel.dispose() } } final private class ObserveOnSerialDispatchQueue<Element>: Producer<Element> { let scheduler: SerialDispatchQueueScheduler let source: Observable<Element> init(source: Observable<Element>, scheduler: SerialDispatchQueueScheduler) { self.scheduler = scheduler self.source = source #if TRACE_RESOURCES _ = Resources.incrementTotal() _ = increment(_numberOfSerialDispatchQueueObservables) #endif } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { let sink = ObserveOnSerialDispatchQueueSink(scheduler: self.scheduler, observer: observer, cancel: cancel) let subscription = self.source.subscribe(sink) return (sink: sink, subscription: subscription) } #if TRACE_RESOURCES deinit { _ = Resources.decrementTotal() _ = decrement(_numberOfSerialDispatchQueueObservables) } #endif }
mit
df7425e27625632dd894b922bbb0a282
29.350649
171
0.627585
4.990036
false
false
false
false
segmentio/analytics-swift
Sources/Segment/Plugins/DeviceToken.swift
1
1258
// // DeviceToken.swift // Segment // // Created by Brandon Sneed on 3/24/21. // import Foundation public class DeviceToken: PlatformPlugin { public let type = PluginType.before public weak var analytics: Analytics? public var token: String? = nil public required init() { } public func execute<T: RawEvent>(event: T?) -> T? { guard var workingEvent = event else { return event } if var context = workingEvent.context?.dictionaryValue, let token = token { context[keyPath: "device.token"] = token do { workingEvent.context = try JSON(context) } catch { analytics?.reportInternalError(error) } } return workingEvent } } extension Analytics { public func setDeviceToken(_ token: String) { if let tokenPlugin = self.find(pluginType: DeviceToken.self) { tokenPlugin.token = token } else { let tokenPlugin = DeviceToken() tokenPlugin.token = token add(plugin: tokenPlugin) } } } extension Data { var hexString: String { let hexString = map { String(format: "%02.2hhx", $0) }.joined() return hexString } }
mit
657e90a26258c3a9a8341f8bec33a4cf
24.673469
83
0.585056
4.429577
false
false
false
false
LeeroyDing/Bond
BondTests/UIKitBondTests.swift
14
6504
// // UIKitTests.swift // Bond // // Created by Srđan Rašić on 11/02/15. // Copyright (c) 2015 Bond. All rights reserved. // import UIKit import XCTest import Bond class UIKitTests: XCTestCase { func testUIViewHiddenBond() { var dynamicDriver = Dynamic<Bool>(false) let view = UIView() view.hidden = true XCTAssert(view.hidden == true, "Initial value") dynamicDriver ->> view.dynHidden XCTAssert(view.hidden == false, "Value after binding") dynamicDriver.value = true XCTAssert(view.hidden == true, "Value after dynamic change") } func testUIViewAlphaBond() { var dynamicDriver = Dynamic<CGFloat>(0.1) let view = UIView() view.alpha = 0.0 XCTAssert(abs(view.alpha - 0.0) < 0.0001, "Initial value") dynamicDriver ->> view.dynAlpha XCTAssert(abs(view.alpha - 0.1) < 0.0001, "Value after binding") dynamicDriver.value = 0.5 XCTAssert(abs(view.alpha - 0.5) < 0.0001, "Value after dynamic change") } func testUIViewBackgroundColorBond() { var dynamicDriver = Dynamic<UIColor>(UIColor.blackColor()) let view = UIView() view.backgroundColor = UIColor.redColor() XCTAssert(view.backgroundColor == UIColor.redColor(), "Initial value") dynamicDriver ->> view.dynBackgroundColor XCTAssert(view.backgroundColor == UIColor.blackColor(), "Value after binding") dynamicDriver.value = UIColor.blueColor() XCTAssert(view.backgroundColor == UIColor.blueColor(), "Value after dynamic change") } func testUILabelBond() { var dynamicDriver = Dynamic<String>("b") let label = UILabel() label.text = "a" XCTAssert(label.text == "a", "Initial value") dynamicDriver ->> label.designatedBond XCTAssert(label.text == "b", "Value after binding") dynamicDriver.value = "c" XCTAssert(label.text == "c", "Value after dynamic change") } func testUILabelAttributedTextBond() { var dynamicDriver = Dynamic<NSAttributedString>(NSAttributedString(string: "b")) let label = UILabel() label.text = "a" XCTAssert(label.text == "a", "Initial value") dynamicDriver ->> label.dynAttributedText XCTAssert(label.attributedText.string == "b", "Value after binding") dynamicDriver.value = NSAttributedString(string: "c") XCTAssert(label.attributedText.string == "c", "Value after dynamic change") } func testUIProgressViewBond() { var dynamicDriver = Dynamic<Float>(0) let progressView = UIProgressView() progressView.progress = 0.1 XCTAssert(progressView.progress == 0.1, "Initial value") dynamicDriver ->> progressView.designatedBond XCTAssert(progressView.progress == 0.0, "Value after binding") dynamicDriver.value = 0.5 XCTAssert(progressView.progress == 0.5, "Value after dynamic change") } func testUIImageViewBond() { let image = UIImage() var dynamicDriver = Dynamic<UIImage?>(nil) let imageView = UIImageView() imageView.image = image XCTAssert(imageView.image == image, "Initial value") dynamicDriver ->> imageView.designatedBond XCTAssert(imageView.image == nil, "Value after binding") imageView.image = image XCTAssert(imageView.image == image, "Value after dynamic change") } func testUIButtonEnabledBond() { var dynamicDriver = Dynamic<Bool>(false) let button = UIButton() button.enabled = true XCTAssert(button.enabled == true, "Initial value") dynamicDriver ->> button.designatedBond XCTAssert(button.enabled == false, "Value after binding") dynamicDriver.value = true XCTAssert(button.enabled == true, "Value after dynamic change") } func testUIButtonTitleBond() { var dynamicDriver = Dynamic<String>("b") let button = UIButton() button.titleLabel?.text = "a" XCTAssert(button.titleLabel?.text == "a", "Initial value") dynamicDriver ->> button.dynTitle XCTAssert(button.titleLabel?.text == "b", "Value after binding") dynamicDriver.value = "c" XCTAssert(button.titleLabel?.text == "c", "Value after dynamic change") } func testUIButtonImageBond() { let image1 = UIImage() let image2 = UIImage() var dynamicDriver = Dynamic<UIImage?>(nil) let button = UIButton() button.setImage(image1, forState: .Normal) XCTAssert(button.imageForState(.Normal) == image1, "Initial value") dynamicDriver ->> button.dynImageForNormalState XCTAssert(button.imageForState(.Normal) == nil, "Value after binding") dynamicDriver.value = image2 XCTAssert(button.imageForState(.Normal) == image2, "Value after dynamic change") } func testUIBarItemEnabledBond() { var dynamicDriver = Dynamic<Bool>(false) let barItem = UIBarButtonItem() barItem.enabled = true XCTAssert(barItem.enabled == true, "Initial value") dynamicDriver ->> barItem.designatedBond XCTAssert(barItem.enabled == false, "Value after binding") dynamicDriver.value = true XCTAssert(barItem.enabled == true, "Value after dynamic change") } func testUIBarItemTitleBond() { var dynamicDriver = Dynamic<String>("b") let barItem = UIBarButtonItem() barItem.title = "a" XCTAssert(barItem.title == "a", "Initial value") dynamicDriver ->> barItem.dynTitle XCTAssert(barItem.title == "b", "Value after binding") dynamicDriver.value = "c" XCTAssert(barItem.title == "c", "Value after dynamic change") } func testUIBarItemImageBond() { let image1 = UIImage() let image2 = UIImage() var dynamicDriver = Dynamic<UIImage?>(nil) let barItem = UIBarButtonItem() barItem.image = image1 XCTAssert(barItem.image == image1, "Initial value") dynamicDriver ->> barItem.dynImage XCTAssert(barItem.image == nil, "Value after binding") dynamicDriver.value = image2 XCTAssert(barItem.image == image2, "Value after dynamic change") } func testUIActivityIndicatorViewHiddenBond() { var dynamicDriver = Dynamic<Bool>(false) let view = UIActivityIndicatorView() view.startAnimating() XCTAssert(view.isAnimating() == true, "Initial value") dynamicDriver ->> view.dynIsAnimating XCTAssert(view.isAnimating() == false, "Value after binding") dynamicDriver.value = true XCTAssert(view.isAnimating() == true, "Value after dynamic change") } }
mit
670881899a3519e388cfa72299f5ad15
29.237209
88
0.66682
4.366017
false
true
false
false
RxSwiftCommunity/Action
Tests/iOS-Tests/BarButtonTests.swift
1
2799
import Quick import Nimble import RxSwift import Action class BarButtonTests: QuickSpec { override func spec() { it("is nil by default") { let subject = UIBarButtonItem(barButtonSystemItem: .save, target: nil, action: nil) expect(subject.rx.action).to( beNil() ) } it("respects setter") { var subject = UIBarButtonItem(barButtonSystemItem: .save, target: nil, action: nil) let action = emptyAction() subject.rx.action = action expect(subject.rx.action).to(beAKindOf(CocoaAction.self)) } it("disables the button while executing") { var subject = UIBarButtonItem(barButtonSystemItem: .save, target: nil, action: nil) var observer: AnyObserver<Void>! let action = CocoaAction(workFactory: { _ in return Observable.create { (obsv) -> Disposable in observer = obsv return Disposables.create() } }) subject.rx.action = action action.execute() expect(subject.isEnabled).toEventually( beFalse() ) observer.onCompleted() expect(subject.isEnabled).toEventually( beTrue() ) } it("disables the button if the Action is disabled") { var subject = UIBarButtonItem(barButtonSystemItem: .save, target: nil, action: nil) subject.rx.action = emptyAction(.just(false)) expect(subject.target).toEventuallyNot(beNil()) expect(subject.isEnabled).to(beFalse()) } it("doesn't execute a disabled action when tapped") { var subject = UIBarButtonItem(barButtonSystemItem: .save, target: nil, action: nil) var executed = false subject.rx.action = CocoaAction(enabledIf: .just(false), workFactory: { _ in executed = true return .empty() }) _ = subject.target?.perform(subject.action, with: subject) expect(executed) == false } it("executes the action when tapped") { var subject = UIBarButtonItem(barButtonSystemItem: .save, target: nil, action: nil) var executed = false let action = CocoaAction(workFactory: { _ in executed = true return .empty() }) subject.rx.action = action // Setting the action has the asynchronous effect of adding a target. expect(subject.target).toEventuallyNot(beNil()) _ = subject.target?.perform(subject.action, with: subject) expect(executed).to(beTrue()) } it("disposes of old action subscriptions when re-set") { var subject = UIBarButtonItem(barButtonSystemItem: .save, target: nil, action: nil) var disposed = false autoreleasepool { let disposeBag = DisposeBag() let action = emptyAction() subject.rx.action = action action .elements .subscribe(onNext: nil, onError: nil, onCompleted: nil, onDisposed: { disposed = true }) .disposed(by: disposeBag) } subject.rx.action = nil expect(disposed).to(beTrue()) } } }
mit
9096113cd1e48c4f55b2dce126bfe0bc
26.99
86
0.679886
3.850069
false
false
false
false
anas10/Monumap
Monumap/Network/Serialization/JSONSerializable.swift
1
784
// // JSONSerializable.swift // Monumap // // Created by Anas Ait Ali on 19/03/2017. // Copyright © 2017 Anas Ait Ali. All rights reserved. // import Foundation import SwiftyJSON protocol JSONSerializable { init(json: [String: Any]) throws } enum JSONSerializationError: Error { case missing(String) case invalid(String, JSON) case invalidJSON } extension JSONSerializationError : Equatable {} func ==(lhs: JSONSerializationError, rhs: JSONSerializationError) -> Bool { switch (lhs, rhs) { case (let .missing(s1), let .missing(s2)): return s1 == s2 case (let .invalid(s1, a1), let .invalid(s2, a2)): return s1 == s2 && a1 == a2 case (.invalidJSON, .invalidJSON): return true default: return false } }
apache-2.0
5f8932052ebfed3e81d642282ec901e3
20.75
75
0.648787
3.782609
false
false
false
false
huangboju/QMUI.swift
QMUI.swift/Demo/Modules/Demos/UIKit/QDLabelViewController.swift
1
3103
// // QDLabelViewController.swift // QMUI.swift // // Created by qd-hxt on 2018/4/10. // Copyright © 2018年 伯驹 黄. All rights reserved. // import UIKit class QDLabelViewController: QDCommonViewController { private lazy var label1: QMUILabel = { let label = QMUILabel() label.text = "可长按复制" label.font = UIFontMake(15) label.textColor = UIColorGray5 label.canPerformCopyAction = true label.sizeToFit() return label }() private lazy var label2: QMUILabel = { let label = QMUILabel() label.text = "可设置 contentInsets" label.font = UIFontMake(15) label.textColor = UIColorWhite label.backgroundColor = UIColorGray8 label.contentEdgeInsets = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16) label.sizeToFit() return label }() private lazy var label3: QMUILabel = { let label = QMUILabel() label.text = "复制上面第二个label的样式" label.qmui_setTheSameAppearance(as: label2) label.sizeToFit() return label }() private lazy var separatorLayer1: CALayer = { let separatorLayer = QDCommonUI.generateSeparatorLayer() return separatorLayer }() private lazy var separatorLayer2: CALayer = { let separatorLayer = QDCommonUI.generateSeparatorLayer() return separatorLayer }() private lazy var separatorLayer3: CALayer = { let separatorLayer = QDCommonUI.generateSeparatorLayer() return separatorLayer }() override func initSubviews() { super.initSubviews() view.addSubview(label1) view.layer.addSublayer(separatorLayer1) view.addSubview(label2) view.layer.addSublayer(separatorLayer2) view.addSubview(label3) view.layer.addSublayer(separatorLayer3) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let contentMinY = self.qmui_navigationBarMaxYInViewCoordinator let buttonSpacingHeight = QDButtonSpacingHeight label1.frame = label1.frame.setXY(view.bounds.width.center(label1.bounds.width), contentMinY + buttonSpacingHeight.center(label1.bounds.height)) separatorLayer1.frame = CGRect(x: 0, y: contentMinY + buttonSpacingHeight * 1, width: view.bounds.width, height: PixelOne) label2.frame = label2.frame.setXY(view.bounds.width.center(label2.bounds.width), separatorLayer1.frame.maxY + buttonSpacingHeight.center(label2.bounds.height)) separatorLayer2.frame = CGRect(x: 0, y: contentMinY + buttonSpacingHeight * 2, width: view.bounds.width, height: PixelOne) label3.frame = label3.frame.setXY(view.bounds.width.center(label3.bounds.width), separatorLayer2.frame.maxY + buttonSpacingHeight.center(label3.bounds.height)) separatorLayer3.frame = CGRect(x: 0, y: contentMinY + buttonSpacingHeight * 3, width: view.bounds.width, height: PixelOne) } }
mit
8553dbaaf1ef3e9e83ef258ba451e438
34.149425
167
0.660889
4.356125
false
false
false
false
edx/edx-app-ios
Source/CourseShareUtmParameters.swift
1
687
// // CourseShareUtmParameters.swift // edX // // Created by Salman on 19/05/2017. // Copyright © 2017 edX. All rights reserved. // import UIKit @objc class CourseShareUtmParameters: NSObject { let facebook: String? let twitter: String? var linkedin: String? = nil var email: String? = nil @objc init?(params: [String: Any]) { facebook = params["facebook"] as? String twitter = params["twitter"] as? String super.init() } @objc convenience init?(utmParams: [String: Any]) { self.init(params: utmParams) linkedin = utmParams["linkedin"] as? String email = utmParams["email"] as? String } }
apache-2.0
0f203bd99fd11515666db7c6f51fc788
22.655172
55
0.61516
3.811111
false
false
false
false
hackersatcambridge/hac-website
Sources/HaCWebsiteLib/Views/LandingPage/LandingPage.swift
1
9029
import HaCTML // swiftlint:disable line_length struct LandingPage: Nodeable { let updates: [PostCard] let feature: LandingFeature? let youtubeUrl = "https://www.youtube.com/hackersatcambridge" let facebookUrl = "https://www.facebook.com/hackersatcambridge" let githubUrl = "https://github.com/hackersatcambridge/" let mediumUrl = "https://medium.com/hackers-at-cambridge" let calendarUrl = "https://calendar.google.com/calendar/embed?src=10isedeg17ugvrvg73jq9p5gts%40group.calendar.google.com&ctz=Europe/London" let demonstratorsGroupUrl = "https://www.facebook.com/groups/1567785333234852/" var featureNode: Nodeable? { return feature.map{ feature in El.Section[Attr.className => "LandingFeature LandingTop__feature"].containing( El.H1[Attr.className => "LandingFeature__subtitle Text--sectionHeading"].containing("Featured"), El.Div[Attr.className => "LandingFeature__hero"].containing(feature) ) } } var node: Node { return Page( title: "Hackers at Cambridge", content: Fragment( El.Div[Attr.className => "LandingTop"].containing( El.Header[Attr.className => "LandingIntroduction LandingTop__introduction"].containing( El.Div[Attr.className => "LandingIntroduction__titleContainer"].containing( El.Img[ Attr.className => "SiteLogo", Attr.src => Assets.publicPath("/images/hac-logo-dark.svg"), Attr.alt => "Hackers at Cambridge" ], El.Div[Attr.className => "TagLine"].containing("Cambridge's student tech society") ), El.P[Attr.className => "LandingIntroduction__missionStatement"].containing("We are a community focused on learning about and building things with technology."), El.A[Attr.href => "http://eepurl.com/ckeD2b"].containing( El.Div[Attr.className => "BigButton"].containing( "Join our mailing list" ) ), El.Div[Attr.className => "LandingIntroduction__social"].containing( El.Div[Attr.className => "LandingIntroduction__socialText"].containing("And find us on"), El.Div[Attr.className => "LandingIntroduction__socialIconRow"].containing( El.A[Attr.href => githubUrl, Attr.className => "LandingIntroduction__socialLinkIcon"].containing( El.Img[ Attr.className => "LandingIntroduction__socialLinkIconImg", Attr.src => Assets.publicPath("/images/github_icon.svg"), Attr.alt => "GitHub" ] ), El.A[Attr.href => facebookUrl, Attr.className => "LandingIntroduction__socialLinkIcon"].containing( El.Img[ Attr.className => "LandingIntroduction__socialLinkIconImg", Attr.src => Assets.publicPath("/images/facebook_icon.svg"), Attr.alt => "Facebook" ] ), El.A[Attr.href => youtubeUrl, Attr.className => "LandingIntroduction__socialLinkIcon"].containing( El.Img[ Attr.className => "LandingIntroduction__socialLinkIconImg", Attr.src => Assets.publicPath("/images/youtube_icon.svg"), Attr.alt => "YouTube" ] ), El.A[Attr.href => mediumUrl, Attr.className => "LandingIntroduction__socialLinkIcon"].containing( El.Img[ Attr.className => "LandingIntroduction__socialLinkIconImg", Attr.src => Assets.publicPath("/images/medium_icon.svg"), Attr.alt => "Medium" ] ) ) ) ), featureNode ), // El.Section[Attr.className => "LandingUpdateFeed"].containing( // El.H1[Attr.className => "LandingUpdateFeed__title Text--sectionHeading"].containing("Updates"), // El.Div[Attr.className => "LandingUpdateFeed__postContainer"].containing( // updates.map { // El.Div[Attr.className => "LandingUpdateFeed__item"].containing($0) // } // ) // ), El.Article[Attr.className => "LandingAbout", Attr.id => "about"].containing( El.Div[Attr.className => "LandingAbout__section"].containing( El.Div[Attr.className => "LandingAbout__imageContainer"].containing( El.Img[ Attr.className => "LandingAbout__image", Attr.src => Assets.publicPath("/images/whoishac.jpg") ] ), El.Div[Attr.className => "LandingAbout__text"].containing( El.H1[Attr.className => "LandingAbout__subtitle Text--sectionHeading"].containing("About"), El.H2[Attr.className => "Text--headline"].containing("Who are Hackers at Cambridge?"), Markdown(""" Don't let the name scare you, we aren't the kind of hackers that try our best to get around complex security systems. We are simply an enthusiastic group of people who love technology. At HaC it’s our mission to empower everyone to build whatever technology project they want. Whether you are a complete beginner or a seasoned pro, we're here to help you develop and share your tech skills. """), El.A[ Attr.href => "/about", Attr.className => "BigButton" ].containing( "About us" ) ) ), El.Article[Attr.className => "LandingAbout__section"].containing( El.Div[Attr.className => "LandingAbout__imageContainer"].containing( El.Img[ Attr.className => "LandingAbout__image", Attr.src => Assets.publicPath("/images/hacworkshop.jpg") ] ), El.Div[Attr.className => "LandingAbout__text"].containing( El.H1[Attr.className => "Text--headline"].containing("Workshops"), Markdown(""" Run by members of the community and open to everyone, our workshops aim to inspire and to teach practical technology skills. If you've missed one of our workshops and would like to catch up, check out our [YouTube page](\(youtubeUrl)) for recordings. If you would like to help out at one of our workshops, join the [demonstrators group](\(demonstratorsGroupUrl)), we'd love to have you! """), El.A[ Attr.href => "/workshops", Attr.className => "BigButton" ].containing( "Check out our workshops" ) ) ), El.Article[Attr.className => "LandingAbout__section"].containing( El.Div[Attr.className => "LandingAbout__imageContainer"].containing( El.Img[ Attr.className => "LandingAbout__image", Attr.src => Assets.publicPath("/images/hachackathon.jpg") ] ), El.Div[Attr.className => "LandingAbout__text"].containing( El.H1[Attr.className => "Text--headline"].containing("Hackathons and Game Jams"), Markdown(""" At the end of the Michaelmas we run the annual Hackers at Cambridge Game Gig - a fun and friendly competition where 100 Cambridge students from a wide variety of courses get together to make games in 12 hours At the end of the Lent term we additionally run an annual themed hackathon. Last year we partnered with charities in order to tackle problems around the world. These competitions naturally come with lots of awesome free food. """) ) ), El.Article[Attr.className => "LandingAbout__section"].containing( El.Div[Attr.className => "LandingAbout__imageContainer"].containing( El.Img[ Attr.className => "LandingAbout__image", Attr.src => Assets.publicPath("/images/hashcode.jpg") ] ), El.Div[Attr.className => "LandingAbout__text"].containing( El.H1[Attr.className => "Text--headline"].containing("HaC Nights"), Markdown(""" HaC Nights are weekly events we run for people of all experience levels! If you have something you’re working on - be it a project, some supervision work or coursework – then a HaC night is a great social environment for getting things done. We’ll bring the food, you bring the work and if you get stuck, there’s bound to be someone in the room who can help you out! Find us on [our Facebook page](\(facebookUrl)) to stay up to date """) ) ) ) ) ).node } }
mit
8e2a2f2a99f96a6f2992859ecb557fcb
49.954802
257
0.578113
4.734383
false
false
false
false
ifabijanovic/firebase-messages-swift
Social/UI/Shared/BBSUITheme.swift
2
2093
// // BBSUITheme.swift // Social // // Created by Ivan Fabijanović on 25/11/15. // Copyright © 2015 Bellabeat. All rights reserved. // import UIKit internal let SystemTintColor = UIColor(red: 0.0, green: 122.0/255.0, blue: 1.0, alpha: 1.0) public class BBSUITheme: NSObject { public var contentFontName: String public var contentBackgroundColor: UIColor public var contentTextColor: UIColor public var contentHighlightColor: UIColor public var contentDimmedColor: UIColor public var navigationBarColor: UIColor public var navigationBarTextColor: UIColor public var navigationBarTinColor: UIColor public var statusBarStyle: UIStatusBarStyle public var activityIndicatorTintColor: UIColor public override init() { self.contentFontName = "Helvetica Neue" self.contentBackgroundColor = UIColor.whiteColor() self.contentTextColor = UIColor.blackColor() self.contentHighlightColor = SystemTintColor self.contentDimmedColor = UIColor.lightGrayColor() self.navigationBarColor = UIColor.whiteColor() self.navigationBarTextColor = UIColor.blackColor() self.navigationBarTinColor = SystemTintColor self.statusBarStyle = .Default self.activityIndicatorTintColor = UIColor.blackColor() super.init() } public func applyToViewController(viewController: UIViewController) { viewController.view.backgroundColor = self.contentBackgroundColor if let collectionViewController = viewController as? UICollectionViewController { collectionViewController.collectionView?.backgroundColor = self.contentBackgroundColor } viewController.navigationController?.navigationBar.barTintColor = self.navigationBarColor viewController.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: self.navigationBarTextColor] viewController.navigationController?.navigationBar.tintColor = self.navigationBarTinColor } }
mit
7292d91fa14a8f4d767695d137a1e28a
36.339286
142
0.730273
5.728767
false
false
false
false
ualch9/onebusaway-iphone
OneBusAway/OneBusAwayTests/OBAKitTests/services/ModelFactory_Tests.swift
3
2730
// // ModelFactory_Tests.swift // OneBusAwayTests // // Created by Aaron Brethorst on 7/24/18. // Copyright © 2018 OneBusAway. All rights reserved. // import Quick import Nimble import OBAKit // swiftlint:disable force_cast class ModelFactory_getAgenciesWithCoverageV2_Tests: QuickSpec { override func spec() { context("with good data") { let modelFactory = OBAModelFactory.init() let jsonData = OBATestHelpers.jsonDictionary(fromFile: "agencies_with_coverage.json") var listWithRange: OBAListWithRangeAndReferencesV2! var agencies: [OBAAgencyWithCoverageV2]! var error: NSError? beforeEach { // The model factory expects that only the `data` field gets passed in. let subset = jsonData["data"] as! [String: Any] listWithRange = modelFactory.getAgenciesWithCoverageV2(fromJson: subset, error: &error) agencies = (listWithRange.values as! [OBAAgencyWithCoverageV2]) } describe("list with range") { it("has the expected values") { expect(listWithRange.limitExceeded).to(beFalse()) expect(listWithRange.outOfRange).to(beFalse()) expect(listWithRange.references).toNot(beNil()) } } describe("agency data") { it("has the right number of elements") { expect(agencies.count).to(equal(12)) } it("has the correct information for Sound Transit") { let soundTransit = agencies[8] expect(soundTransit.agencyId).to(equal("40")) expect(soundTransit.agency?.name).to(equal("Sound Transit")) expect(soundTransit.lat).to(equal(47.532444)) expect(soundTransit.lon).to(equal(-122.329459)) expect(soundTransit.latSpan).to(equal(0.8850059999999971)) expect(soundTransit.lonSpan).to(equal(0.621138000000002)) let regionBounds = OBARegionBoundsV2(lat: 47.532444, latSpan: 0.8850059999999971, lon: -122.329459, lonSpan: 0.621138000000002) expect(soundTransit.regionBounds).to(equal(regionBounds)) } } describe("modelFactory.references") { it("has a list of agencies") { expect(modelFactory.references.agencies.keys.count).to(equal(12)) } } describe("error") { it("is nil") { expect(error).to(beNil()) } } } } }
apache-2.0
6fdf116e3e5f7e1ff12fa738e9d2d9d2
37.43662
147
0.559546
4.602024
false
true
false
false
zisko/swift
test/APINotes/versioned.swift
1
12805
// RUN: %empty-directory(%t) // RUN: %target-swift-ide-test -F %S/Inputs/custom-frameworks -print-module -source-filename %s -module-to-print=APINotesFrameworkTest -function-definitions=false -print-regular-comments -swift-version 4 | %FileCheck -check-prefix=CHECK-SWIFT-4 %s // RUN: %target-swift-ide-test -F %S/Inputs/custom-frameworks -print-module -source-filename %s -module-to-print=APINotesFrameworkTest -function-definitions=false -print-regular-comments -swift-version 3 | %FileCheck -check-prefix=CHECK-SWIFT-3 %s // CHECK-SWIFT-4: func jumpTo(x: Double, y: Double, z: Double) // CHECK-SWIFT-3: func jumpTo(x: Double, y: Double, z: Double) // CHECK-SWIFT-4: func accept(_ ptr: UnsafeMutablePointer<Double>) // CHECK-SWIFT-3: func acceptPointer(_ ptr: UnsafeMutablePointer<Double>?) // CHECK-SWIFT-4: func normallyUnchanged() // CHECK-SWIFT-4: @available(swift, obsoleted: 4, renamed: "normallyUnchanged()") // CHECK-SWIFT-4-NEXT: func normallyUnchangedButChangedInSwift3() // CHECK-SWIFT-3: @available(swift, obsoleted: 3, renamed: "normallyUnchangedButChangedInSwift3()") // CHECK-SWIFT-3-NEXT: func normallyUnchanged() // CHECK-SWIFT-3: func normallyUnchangedButChangedInSwift3() // CHECK-SWIFT-4: func normallyChanged() // CHECK-SWIFT-4-NEXT: @available(swift, obsoleted: 4, renamed: "normallyChanged()") // CHECK-SWIFT-4-NEXT: func normallyChangedButSpecialInSwift3() // CHECK-SWIFT-4-NEXT: @available(swift, obsoleted: 3, renamed: "normallyChanged()") // CHECK-SWIFT-4-NEXT: func normallyChangedOriginal() // CHECK-SWIFT-3: @available(swift, introduced: 4, renamed: "normallyChangedButSpecialInSwift3()") // CHECK-SWIFT-3-NEXT: func normallyChanged() // CHECK-SWIFT-3-NEXT: func normallyChangedButSpecialInSwift3() // CHECK-SWIFT-3-NEXT: @available(swift, obsoleted: 3, renamed: "normallyChangedButSpecialInSwift3()") // CHECK-SWIFT-3-NEXT: func normallyChangedOriginal() // CHECK-SWIFT-4: @available(swift, obsoleted: 4, renamed: "NormallyUnchangedWrapper") // CHECK-SWIFT-4-NEXT: typealias NormallyUnchangedButChangedInSwift3Wrapper = NormallyUnchangedWrapper // CHECK-SWIFT-4: struct NormallyUnchangedWrapper { // CHECK-SWIFT-3: typealias NormallyUnchangedButChangedInSwift3Wrapper = NormallyUnchangedWrapper // CHECK-SWIFT-3-NEXT: struct NormallyUnchangedWrapper { // CHECK-SWIFT-4: @available(swift, obsoleted: 4, renamed: "NormallyChangedWrapper") // CHECK-SWIFT-4-NEXT: typealias NormallyChangedButSpecialInSwift3Wrapper = NormallyChangedWrapper // CHECK-SWIFT-4: @available(swift, obsoleted: 3, renamed: "NormallyChangedWrapper") // CHECK-SWIFT-4-NEXT: typealias NormallyChangedOriginalWrapper = NormallyChangedWrapper // CHECK-SWIFT-4: struct NormallyChangedWrapper { // CHECK-SWIFT-3: typealias NormallyChangedButSpecialInSwift3Wrapper = NormallyChangedWrapper // CHECK-SWIFT-3-NEXT: @available(swift, obsoleted: 3, renamed: "NormallyChangedButSpecialInSwift3Wrapper") // CHECK-SWIFT-3-NEXT: typealias NormallyChangedOriginalWrapper = NormallyChangedButSpecialInSwift3Wrapper // CHECK-SWIFT-3-NEXT: struct NormallyChangedWrapper { // RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 4 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-4 %s // RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 3 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-3 %s // RUN: %target-swift-frontend -emit-silgen -F %S/Inputs/custom-frameworks -swift-version 3 %s -DSILGEN 2>&1 | %FileCheck -check-prefix=CHECK-SILGEN -check-prefix=CHECK-SILGEN-3 %s // RUN: %target-swift-frontend -emit-silgen -F %S/Inputs/custom-frameworks -swift-version 4 %s -DSILGEN 2>&1 | %FileCheck -check-prefix=CHECK-SILGEN -check-prefix=CHECK-SILGEN-4 %s import APINotesFrameworkTest #if !SILGEN func testRenamedTopLevelDiags() { var value = 0.0 // CHECK-DIAGS-4-NOT: versioned.swift:[[@LINE+1]]: accept(&value) // CHECK-DIAGS-3: versioned.swift:[[@LINE-1]]:3: error: 'accept' has been renamed to 'acceptPointer(_:)' // CHECK-DIAGS-3: note: 'accept' was introduced in Swift 4 // CHECK-DIAGS-3-NOT: versioned.swift:[[@LINE+1]]: acceptPointer(&value) // CHECK-DIAGS-4: versioned.swift:[[@LINE-1]]:3: error: 'acceptPointer' has been renamed to 'accept(_:)' // CHECK-DIAGS-4: note: 'acceptPointer' was obsoleted in Swift 4 acceptDoublePointer(&value) // CHECK-DIAGS: versioned.swift:[[@LINE-1]]:3: error: 'acceptDoublePointer' has been renamed to // CHECK-DIAGS-4-SAME: 'accept(_:)' // CHECK-DIAGS-3-SAME: 'acceptPointer(_:)' // CHECK-DIAGS: note: 'acceptDoublePointer' was obsoleted in Swift 3 oldAcceptDoublePointer(&value) // CHECK-DIAGS: versioned.swift:[[@LINE-1]]:3: error: 'oldAcceptDoublePointer' has been renamed to // CHECK-DIAGS-4-SAME: 'accept(_:)' // CHECK-DIAGS-3-SAME: 'acceptPointer(_:)' // CHECK-DIAGS: note: 'oldAcceptDoublePointer' has been explicitly marked unavailable here _ = SomeCStruct() // CHECK-DIAGS: versioned.swift:[[@LINE-1]]:7: error: 'SomeCStruct' has been renamed to // CHECK-DIAGS-4-SAME: 'VeryImportantCStruct' // CHECK-DIAGS-3-SAME: 'ImportantCStruct' // CHECK-DIAGS: note: 'SomeCStruct' was obsoleted in Swift 3 // CHECK-DIAGS-3-NOT: versioned.swift:[[@LINE+1]]: _ = ImportantCStruct() // CHECK-DIAGS-4: versioned.swift:[[@LINE-1]]:7: error: 'ImportantCStruct' has been renamed to 'VeryImportantCStruct' // CHECK-DIAGS-4: note: 'ImportantCStruct' was obsoleted in Swift 4 // CHECK-DIAGS-4-NOT: versioned.swift:[[@LINE+1]]: _ = VeryImportantCStruct() // CHECK-DIAGS-3-NOTE: versioned.swift:[[@LINE-1]]: // CHECK-DIAGS-3-NOT: versioned.swift:[[@LINE+1]]: let s = InnerInSwift4() // CHECK-DIAGS-4: versioned.swift:[[@LINE-1]]:11: error: 'InnerInSwift4' has been renamed to 'Outer.Inner' // CHECK-DIAGS-4: note: 'InnerInSwift4' was obsoleted in Swift 4 _ = s.value // CHECK-DIAGS-4-NOT: versioned.swift:[[@LINE-1]]: // CHECK-DIAGS-4-NOT: versioned.swift:[[@LINE+1]]: let t = Outer.Inner() // CHECK-DIAGS-3-NOT: versioned.swift:[[@LINE-1]]: _ = s.value // CHECK-DIAGS-3-NOT: versioned.swift:[[@LINE-1]]: } func testAKA(structValue: ImportantCStruct, aliasValue: ImportantCAlias) { let _: Int = structValue // CHECK-DIAGS-3: versioned.swift:[[@LINE-1]]:16: error: cannot convert value of type 'ImportantCStruct' to specified type 'Int' let _: Int = aliasValue // CHECK-DIAGS-3: versioned.swift:[[@LINE-1]]:16: error: cannot convert value of type 'ImportantCAlias' (aka 'Int32') to specified type 'Int' let optStructValue: Optional = structValue let _: Int = optStructValue // CHECK-DIAGS-3: versioned.swift:[[@LINE-1]]:16: error: cannot convert value of type 'Optional<ImportantCStruct>' to specified type 'Int' let optAliasValue: Optional = aliasValue let _: Int = optAliasValue // CHECK-DIAGS-3: versioned.swift:[[@LINE-1]]:16: error: cannot convert value of type 'Optional<ImportantCAlias>' (aka 'Optional<Int32>') to specified type 'Int' } func testRenamedEnumConstants() { _ = AnonymousEnumValue // okay // CHECK-DIAGS-4: [[@LINE+1]]:7: error: 'AnonymousEnumRenamed' has been renamed to 'AnonymousEnumRenamedSwiftUnversioned' _ = AnonymousEnumRenamed // CHECK-DIAGS-3: [[@LINE-1]]:7: error: 'AnonymousEnumRenamed' has been renamed to 'AnonymousEnumRenamedSwift3' // CHECK-DIAGS-4-NOT: :[[@LINE+1]]:7: _ = AnonymousEnumRenamedSwiftUnversioned // CHECK-DIAGS-3: [[@LINE-1]]:7: error: 'AnonymousEnumRenamedSwiftUnversioned' has been renamed to 'AnonymousEnumRenamedSwift3' // CHECK-DIAGS-4: [[@LINE+1]]:7: error: 'AnonymousEnumRenamedSwift3' has been renamed to 'AnonymousEnumRenamedSwiftUnversioned' _ = AnonymousEnumRenamedSwift3 // CHECK-DIAGS-3-NOT: :[[@LINE-1]]:7: } func testRenamedUnknownEnum() { _ = UnknownEnumValue // okay // CHECK-DIAGS-4: [[@LINE+1]]:7: error: 'UnknownEnumRenamed' has been renamed to 'UnknownEnumRenamedSwiftUnversioned' _ = UnknownEnumRenamed // CHECK-DIAGS-3: [[@LINE-1]]:7: error: 'UnknownEnumRenamed' has been renamed to 'UnknownEnumRenamedSwift3' // CHECK-DIAGS-4-NOT: :[[@LINE+1]]:7: _ = UnknownEnumRenamedSwiftUnversioned // CHECK-DIAGS-3: [[@LINE-1]]:7: error: 'UnknownEnumRenamedSwiftUnversioned' has been renamed to 'UnknownEnumRenamedSwift3' // CHECK-DIAGS-4: [[@LINE+1]]:7: error: 'UnknownEnumRenamedSwift3' has been renamed to 'UnknownEnumRenamedSwiftUnversioned' _ = UnknownEnumRenamedSwift3 // CHECK-DIAGS-3-NOT: :[[@LINE-1]]:7: } func testRenamedTrueEnum() { // CHECK-DIAGS: [[@LINE+1]]:7: error: use of unresolved identifier 'TrueEnumValue' _ = TrueEnumValue // CHECK-DIAGS: [[@LINE+1]]:7: error: type 'TrueEnum' has no member 'TrueEnumValue' _ = TrueEnum.TrueEnumValue // CHECK-DIAGS: [[@LINE+1]]:16: error: 'Value' has been renamed to 'value' _ = TrueEnum.Value _ = TrueEnum.value // okay // CHECK-DIAGS: [[@LINE+1]]:7: error: use of unresolved identifier 'TrueEnumRenamed' _ = TrueEnumRenamed // CHECK-DIAGS: [[@LINE+1]]:7: error: type 'TrueEnum' has no member 'TrueEnumRenamed' _ = TrueEnum.TrueEnumRenamed // CHECK-DIAGS-4: [[@LINE+1]]:16: error: 'Renamed' has been renamed to 'renamedSwiftUnversioned' _ = TrueEnum.Renamed // CHECK-DIAGS-3: [[@LINE-1]]:16: error: 'Renamed' has been renamed to 'renamedSwift3' // CHECK-DIAGS: [[@LINE+1]]:7: error: type 'TrueEnum' has no member 'renamed' _ = TrueEnum.renamed // CHECK-DIAGS-4-NOT: :[[@LINE+1]]:16: _ = TrueEnum.renamedSwiftUnversioned // CHECK-DIAGS-3: [[@LINE-1]]:16: error: 'renamedSwiftUnversioned' has been renamed to 'renamedSwift3' // CHECK-DIAGS-4: [[@LINE+1]]:16: error: 'renamedSwift3' has been renamed to 'renamedSwiftUnversioned' _ = TrueEnum.renamedSwift3 // CHECK-DIAGS-3-NOT: :[[@LINE-1]]:16: // CHECK-DIAGS: [[@LINE+1]]:7: error: use of unresolved identifier 'TrueEnumAliasRenamed' _ = TrueEnumAliasRenamed // CHECK-DIAGS: [[@LINE+1]]:7: error: type 'TrueEnum' has no member 'TrueEnumAliasRenamed' _ = TrueEnum.TrueEnumAliasRenamed // CHECK-DIAGS-4: [[@LINE+1]]:16: error: 'AliasRenamed' has been renamed to 'aliasRenamedSwiftUnversioned' _ = TrueEnum.AliasRenamed // CHECK-DIAGS-3: [[@LINE-1]]:16: error: 'AliasRenamed' has been renamed to 'aliasRenamedSwift3' // CHECK-DIAGS: [[@LINE+1]]:7: error: type 'TrueEnum' has no member 'aliasRenamed' _ = TrueEnum.aliasRenamed // CHECK-DIAGS-4-NOT: :[[@LINE+1]]:16: _ = TrueEnum.aliasRenamedSwiftUnversioned // CHECK-DIAGS-3: [[@LINE-1]]:16: error: 'aliasRenamedSwiftUnversioned' has been renamed to 'aliasRenamedSwift3' // CHECK-DIAGS-4: [[@LINE+1]]:16: error: 'aliasRenamedSwift3' has been renamed to 'aliasRenamedSwiftUnversioned' _ = TrueEnum.aliasRenamedSwift3 // CHECK-DIAGS-3-NOT: :[[@LINE-1]]:16: } func testRenamedOptionyEnum() { // CHECK-DIAGS: [[@LINE+1]]:7: error: use of unresolved identifier 'OptionyEnumValue' _ = OptionyEnumValue // CHECK-DIAGS: [[@LINE+1]]:7: error: type 'OptionyEnum' has no member 'OptionyEnumValue' _ = OptionyEnum.OptionyEnumValue // CHECK-DIAGS: [[@LINE+1]]:19: error: 'Value' has been renamed to 'value' _ = OptionyEnum.Value _ = OptionyEnum.value // okay // CHECK-DIAGS: [[@LINE+1]]:7: error: use of unresolved identifier 'OptionyEnumRenamed' _ = OptionyEnumRenamed // CHECK-DIAGS: [[@LINE+1]]:7: error: type 'OptionyEnum' has no member 'OptionyEnumRenamed' _ = OptionyEnum.OptionyEnumRenamed // CHECK-DIAGS-4: [[@LINE+1]]:19: error: 'Renamed' has been renamed to 'renamedSwiftUnversioned' _ = OptionyEnum.Renamed // CHECK-DIAGS-3: [[@LINE-1]]:19: error: 'Renamed' has been renamed to 'renamedSwift3' // CHECK-DIAGS: [[@LINE+1]]:7: error: type 'OptionyEnum' has no member 'renamed' _ = OptionyEnum.renamed // CHECK-DIAGS-4-NOT: :[[@LINE+1]]:19: _ = OptionyEnum.renamedSwiftUnversioned // CHECK-DIAGS-3: [[@LINE-1]]:19: error: 'renamedSwiftUnversioned' has been renamed to 'renamedSwift3' // CHECK-DIAGS-4: [[@LINE+1]]:19: error: 'renamedSwift3' has been renamed to 'renamedSwiftUnversioned' _ = OptionyEnum.renamedSwift3 // CHECK-DIAGS-3-NOT: :[[@LINE-1]]:19: } #endif #if !swift(>=4) func useSwift3Name(_: ImportantCStruct) {} // CHECK-SILGEN-3: sil hidden @$S9versioned13useSwift3NameyySo11SomeCStructVF func useNewlyNested(_: InnerInSwift4) {} // CHECK-SILGEN-3: sil hidden @$S9versioned14useNewlyNestedyySo13InnerInSwift4VF #endif func useSwift4Name(_: VeryImportantCStruct) {} // CHECK-SILGEN: sil hidden @$S9versioned13useSwift4NameyySo11SomeCStructVF #if swift(>=4) func testSwiftWrapperInSwift4() { _ = EnclosingStruct.Identifier.member let _: EnclosingStruct.Identifier = .member } #else func testSwiftWrapperInSwift3() { _ = EnclosingStruct.Identifier.member let _: EnclosingStruct.Identifier = .member } #endif
apache-2.0
73ee9cda2b0d1228135c44cee4ceaeb5
45.394928
248
0.720578
3.452413
false
false
false
false
benlangmuir/swift
validation-test/compiler_crashers_fixed/00185-swift-completegenerictyperesolver-resolvegenerictypeparamtype.swift
65
3809
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck protocol b { class func e() } struct c { var d: b.Type func e() { d.e() } } import Foun { func j var _ = j } } class x { s m func j(m) } struct j<u> : r { func j(j: j.n) { } } enum q<v> { let k: v let u: v.l } protocol y { o= p>(r: m<v>) } struct D : y { s p = Int func y<v k r { s m } class y<D> { w <r: func j<v x: v) { x.k() } func x(j: Int = a) { } let k = x class j { func y((Any, j))(v: (Any, AnyObject)) { y(v) } } func w(j: () -> ()) { } class v { l _ = w() { } } ({}) func v<x>() -> (x, x -> x) -> x { l y j s<q : l, y: l m y.n == q.n> { } o l { u n } y q<x> { s w(x, () -> ()) } o n { func j() p } class r { func s() -> p { t "" } } class w: r, n { k v: ))] = [] } class n<x : n> } } class b<i : b> i: g{ func c {} e g { : g { h func i() -> } func b<e>(e : e) -> c { e struct j<l : o> { k b: l } func a<l>() -> [j<l>] { return [] } f k) func f<l>() -> (l, l -> l) -> l { l j l.n = { } { l) { n } } protocol f { class func n() } class l: f{ class func n {} func a<i>() { b b { l j } } class a<f : b, l : b m f.l == l> { } protocol b { typealias l typealias k } struct j<n : b> : b { typealias l = n typealias k = a<j<n>, l> } protocol a { class func c() } class b: a { class func c() { } } (b() as a).dynamicType.c() func f(c: i, l: i) -> (((i, i) -> i) -> i) { b { (h -> i) d $k } let e: Int = 1, 1) class g<j :g func f<m>() -> (m, m -> m) -> m { e c e.i = { }} func h<d { enum h { func e var _ = e } } protocol e { e func e() } struct h { var d: e.h func e() { d.e() } } protocol f { i [] } func f<g>() -> (g, g -> g) -> g func a<T>() { enum b { case c } } ) func n<w>() -> (w, w -> w) -> w { o m o.q = { } { w) { k } } protocol n { class func q() } class o: n{ class func q {} func p(e: Int = x) { } let c = p c() func r<o: y, s q n<s> ==(r(t)) protocol p : p { } protocol p { class func c() } class e: p { class func c() { } } (e() u p).v.c() k e.w == l> { } func p(c: Any, m: Any) -> (((Any, Any) -> Any) -> Any) { func o() as o).m.k() func p(k: b) -> <i>(() -> i) -> b { n { o f "\(k): \(o())" } } struct d<d : n, o:j n { l p } protocol o : o { } func o< protocol a { typealias d typealias e = d typealias f = d } class b<h : c, i : c where h.g == i> : a { } class b<h, i> { } protocol c { typealias g } func m(c: b) -> <h>(() -> h) -> b { f) -> j) -> > j { l i !(k) } d l) func d<m>-> (m, m - w class x<u>: d { l i: u init(i: u) { o.i = j { r { w s "\(f): \(w())" } } protocol h { q k { t w } w protocol k : w { func v <h: h m h.p == k>(l: h.p) { } } protocol h { n func w(w: } class h<u : h> { func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) { return { (m: (Any, Any) -> Any) -> Any in return m(x, y) } } func b(z: (((Any, Any) -> Any) -> Any)) -> Any { return z({ (p: Any, q:Any) -> Any in return p }) } b(a(1, a(2, 3))) func n<p>() -> (p, p -> p) -> p { b, l] g(o(q)) h e { j class func r() } class k: h{ class func r {} var k = 1 var s: r -> r t -> r) -> r m u h>] { u [] } func r(e: () -> ()) { } class n { var _ = r()
apache-2.0
4194b614c280c8f422c88496892015a1
13.159851
79
0.418745
2.329664
false
false
false
false
madeatsampa/MacMagazine-iOS
MacMagazineTests/ParsedObjectTests.swift
2
2411
// // ParsedObjectTests.swift // MacMagazineTests // // Created by Cassio Rossi on 26/05/2019. // Copyright © 2019 MacMagazine. All rights reserved. // @testable import MacMagazine import XCTest // Tests to be performed: // 1) Create a mock test // 2) Test for the content of the mock data, adding to the XMLPost class class ParsedObjectTests: XCTestCase { var postExample: Data? let examplePost = ExamplePost() override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. guard let post = self.examplePost.getExamplePost() else { return } postExample = post } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testGetPost() { XCTAssertNotNil(postExample, "Example post should exist") } func testParseExample() { guard let post = postExample else { XCTFail("Example post should exist") return } let expectation = self.expectation(description: "Testing API for a valid XML...") expectation.expectedFulfillmentCount = 2 let onCompletion = { (post: XMLPost?) in guard let post = post else { expectation.fulfill() return } XCTAssertEqual(post.title, self.examplePost.getValidTitle(), "API response title must match") XCTAssertEqual(post.link, self.examplePost.getValidLink(), "API response link must match") XCTAssertEqual(post.pubDate, self.examplePost.getValidPubdate(), "API response date should must match") XCTAssertEqual(post.artworkURL, self.examplePost.getValidArtworkURL(), "API response artworkURL must match") XCTAssertEqual(post.podcastURL, "", "API response podcastURL must match") XCTAssertEqual(post.podcast, "", "API response podcast must match") XCTAssertEqual(post.duration, "", "API response duration must match") XCTAssertEqual(post.podcastFrame, "", "API response podcastFrame must match") XCTAssertEqual(post.excerpt, self.examplePost.getValidExcerpt(), "API response excerpt must match") XCTAssertEqual(post.categories, self.examplePost.getValidCategories(), "API response categories must match") expectation.fulfill() } API().parse(post, onCompletion: onCompletion, numberOfPosts: 1) waitForExpectations(timeout: 30) { error in XCTAssertNil(error, "Error occurred: \(String(describing: error))") } } }
mit
7c8875078a03d132f7842d081d791426
32.472222
111
0.732365
3.983471
false
true
false
false
ctinnell/PDFGrid
PDFGrid/ViewController.swift
1
4833
// // ViewController.swift // PDFGrid // // Created by Clay Tinnell on 2/15/15. // Copyright (c) 2015 Clay Tinnell. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(animated: Bool) { loadPDFInWebView(generatePDF()) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func testData() -> (String, [String],[[String]]) { //Attribution: Test data shamelessly scraped from here: //http://stats.nba.com/league/player/#!/?sort=PTS&dir=1&PerMode=Totals let title = "2014-2015 NBA Player Statistics" let columnTitles = ["Player", "Games", "Minutes", "FG PCT", "Rebounds", "Assists", "Points"] var detailValues = [["James Harden", "53", "1940", "45.5", "50", "360", "1451"]] detailValues.append(["Stephen Curry", "51", "1695", "48.1", "240", "402", "1203"]) detailValues.append(["LeBron James", "46", "1675", "49.1", "257", "334", "1195"]) detailValues.append(["Kyrie Irving", "53", "1992", "46.6", "175", "284", "1153"]) detailValues.append(["Blake Griffin", "51", "1800", "50.1", "385", "262", "1149"]) detailValues.append(["Anthony Davis", "47", "1683", "54.7", "486", "80", "1142"]) detailValues.append(["Damian Lillard", "53", "1925", "43.3", "243", "333", "1138"]) detailValues.append(["LaMarcus Aldridge", "47", "1693", "46.3", "486", "85", "1108"]) detailValues.append(["Klay Thompson", "50", "1623", "47.1", "171", "147", "1104"]) detailValues.append(["Monta Ellis", "56", "1884", "45.0", "132", "251", "1094"]) detailValues.append(["Gordon Hayward", "53", "1865", "46.0", "264", "227", "1024"]) detailValues.append(["Russell Westbrook", "40", "1312", "43.3", "252", "307", "1041"]) detailValues.append(["Jimmy Butler", "50", "1966", "46.2", "291", "164", "1028"]) detailValues.append(["Nikola Vucevic", "51", "1754", "53.5", "578", "95", "999"]) detailValues.append(["Kyle Lowry", "54", "1883", "42.3", "255", "391", "998"]) detailValues.append(["Chris Paul", "55", "1911", "47.0", "268", "540", "978"]) detailValues.append(["Marc Gasol", "53", "1796", "49.1", "427", "197", "968"]) detailValues.append(["Carmelo Anthony", "40", "1428", "44.4", "264", "122", "966"]) detailValues.append(["John Wall", "55", "1960", "46.1", "246", "555", "956"]) detailValues.append(["Rudy Gay", "48", "1695", "44.4", "283", "186", "955"]) detailValues.append(["Pau Gasol", "52", "1820", "49.1", "627", "153", "952"]) detailValues.append(["DeMarcus Cousins", "40", "1381", "46.5", "498", "133", "950"]) detailValues.append(["Dirk Nowitzki", "52", "1550", "46.5", "311", "101", "946"]) detailValues.append(["Chris Bosh", "44", "1556", "46.0", "310", "95", "928"]) return (title,columnTitles,detailValues) } func color(red: Float, green: Float, blue: Float) -> UIColor { return UIColor(red: CGFloat(red/255.0), green: CGFloat(green/255.0), blue: CGFloat(blue/255.0), alpha: 1.0) } func generatePDF() -> String { let (title, columnTitles, detailValues) = testData() let h1Color = color(70.0, green: 170.0, blue: 200.0) let h2Color = color(136.0, green: 136.0, blue: 136.0) let rowColor = color(239.0, green: 239.0, blue: 239.0) let document = PDFGridDocument(columnTitles: columnTitles, detailValues: detailValues, gridBackgroundColor: rowColor, fileName: "NBAStats") document.addHeader(0, title: title, height: 35.0, startingColumn: 0, endingColumn: columnTitles.count-1, backgroundColor: h1Color) document.addHeader(1, title: "Time On The Court", height: 25.0, startingColumn: 0, endingColumn: 2, backgroundColor: h2Color) document.addHeader(1, title: "Key Stats", height: 25.0, startingColumn: 3, endingColumn: 4, backgroundColor: h2Color) document.addHeader(1, title: "Scoring", height: 25.0, startingColumn: 5, endingColumn: 6, backgroundColor: h2Color) return document.generate() } func loadPDFInWebView(filePath: String) { let fileURL = NSURL(fileURLWithPath: filePath) let request = NSURLRequest(URL: fileURL, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 20.0) webView.loadRequest(request) webView.scalesPageToFit = true webView.sizeToFit() } }
gpl-2.0
066a93a6f5b6f0e054fd76be40fd5e05
48.824742
147
0.599421
3.391579
false
false
false
false
HabitRPG/habitrpg-ios
Habitica API Client/Habitica API Client/Models/Content/APISpecialItem.swift
1
1357
// // APISpecialItem.swift // Habitica API Client // // Created by Phillip Thelen on 08.06.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models class APISpecialItem: SpecialItemProtocol, Decodable { var isSubscriberItem: Bool = false var key: String? var text: String? var notes: String? var value: Float = 0 var itemType: String? var target: String? var immediateUse: Bool = false var silent: Bool = false enum CodingKeys: String, CodingKey { case key case text case notes case value case target case immediateUse case silent } public required init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) key = try? values.decode(String.self, forKey: .key) text = try? values.decode(String.self, forKey: .text) notes = try? values.decode(String.self, forKey: .notes) value = (try? values.decode(Float.self, forKey: .key)) ?? 0 target = try? values.decode(String.self, forKey: .target) immediateUse = (try? values.decode(Bool.self, forKey: .immediateUse)) ?? false silent = (try? values.decode(Bool.self, forKey: .silent)) ?? false itemType = ItemType.special.rawValue } }
gpl-3.0
fe1a2e6a3c6cca22b9def6c3fdd4bd92
29.818182
86
0.640118
4
false
false
false
false
czechboy0/Buildasaur
Buildasaur/DashboardViewController.swift
2
11069
// // DashboardViewController.swift // Buildasaur // // Created by Honza Dvorsky on 28/09/2015. // Copyright © 2015 Honza Dvorsky. All rights reserved. // import Cocoa import BuildaKit import ReactiveCocoa import Result protocol EditeeDelegate: class, EmptyXcodeServerViewControllerDelegate, XcodeServerViewControllerDelegate, EmptyProjectViewControllerDelegate, ProjectViewControllerDelegate, EmptyBuildTemplateViewControllerDelegate, BuildTemplateViewControllerDelegate, SyncerViewControllerDelegate { } class DashboardViewController: PresentableViewController { @IBOutlet weak var syncersTableView: NSTableView! @IBOutlet weak var startAllButton: NSButton! @IBOutlet weak var stopAllButton: NSButton! @IBOutlet weak var autostartButton: NSButton! @IBOutlet weak var launchOnLoginButton: NSButton! let config = MutableProperty<[String: AnyObject]>([:]) //injected before viewDidLoad var syncerManager: SyncerManager! var serviceAuthenticator: ServiceAuthenticator! private var syncerViewModels: MutableProperty<[SyncerViewModel]> = MutableProperty([]) override func viewDidLoad() { super.viewDidLoad() self.configTitle() self.configDataSource() self.configTableView() self.configHeaderView() } override func viewDidAppear() { super.viewDidAppear() if let window = self.view.window { window.minSize = CGSize(width: 700, height: 300) } } func configTitle() { let version = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String self.title = "Buildasaur \(version), at your service!" } func configHeaderView() { //setup start/stop all buttons let anySyncerStateChanged = self.syncerViewModels.producer.flatMap(.Merge) { newViewModels -> SignalProducer<SignalProducer<Bool, NoError>, NoError> in return SignalProducer { sink, _ in newViewModels.forEach { sink.sendNext($0.syncer.activeSignalProducer.producer) } sink.sendCompleted() } }.flatten(.Merge) combineLatest(anySyncerStateChanged, self.syncerViewModels.producer) .startWithNext { [weak self] (_, viewModels) -> () in guard let sself = self else { return } //startAll is enabled if >0 is NOT ACTIVE let startAllEnabled = viewModels.filter { !$0.syncer.active }.count > 0 sself.startAllButton.enabled = startAllEnabled //stopAll is enabled if >0 is ACTIVE let stopAllEnabled = viewModels.filter { $0.syncer.active }.count > 0 sself.stopAllButton.enabled = stopAllEnabled } //setup config self.config.value = self.syncerManager.storageManager.config.value self.autostartButton.on = self.config.value["autostart"] as? Bool ?? false self.config.producer.startWithNext { [weak self] config in guard let sself = self else { return } sself.syncerManager.storageManager.config.value = config } self.autostartButton.rac_on.startWithNext { [weak self] in guard let sself = self else { return } sself.config.value["autostart"] = $0 } //setup login item self.launchOnLoginButton.on = self.syncerManager.loginItem.isLaunchItem } func configTableView() { let tableView = self.syncersTableView tableView.setDataSource(self) tableView.setDelegate(self) tableView.columnAutoresizingStyle = .UniformColumnAutoresizingStyle } func configDataSource() { let present: SyncerViewModel.PresentEditViewControllerType = { self.showSyncerEditViewControllerWithTriplet($0.toEditable(), state: .Syncer) } self.syncerManager.syncersProducer.startWithNext { newSyncers in self.syncerViewModels.value = newSyncers .map { SyncerViewModel(syncer: $0, presentEditViewController: present) } .sort { $0.0.initialProjectName < $0.1.initialProjectName } self.syncersTableView.reloadData() } } //MARK: Responding to button inside of cells private func syncerViewModelFromSender(sender: BuildaNSButton) -> SyncerViewModel { let selectedRow = sender.row! let syncerViewModel = self.syncerViewModels.value[selectedRow] return syncerViewModel } @IBAction func startAllButtonClicked(sender: AnyObject) { self.syncerViewModels.value.forEach { $0.startButtonClicked() } } @IBAction func stopAllButtonClicked(sender: AnyObject) { self.syncerViewModels.value.forEach { $0.stopButtonClicked() } } @IBAction func newSyncerButtonClicked(sender: AnyObject) { self.showNewSyncerViewController() } @IBAction func editButtonClicked(sender: BuildaNSButton) { self.syncerViewModelFromSender(sender).viewButtonClicked() } @IBAction func controlButtonClicked(sender: BuildaNSButton) { self.syncerViewModelFromSender(sender).controlButtonClicked() } @IBAction func doubleClickedRow(sender: AnyObject?) { let clickedRow = self.syncersTableView.clickedRow guard clickedRow >= 0 else { return } let syncerViewModel = self.syncerViewModels.value[clickedRow] syncerViewModel.viewButtonClicked() } @IBAction func infoButtonClicked(sender: AnyObject) { openLink("https://github.com/czechboy0/Buildasaur#buildasaur") } @IBAction func launchOnLoginClicked(sender: NSButton) { let newValue = sender.on let loginItem = self.syncerManager.loginItem loginItem.isLaunchItem = newValue //to be in sync in the UI, in case setting fails self.launchOnLoginButton.on = loginItem.isLaunchItem } @IBAction func checkForUpdatesClicked(sender: NSButton) { (NSApp.delegate as! AppDelegate).checkForUpdates(sender) } } extension DashboardViewController { func showNewSyncerViewController() { //configure an editing window with a brand new syncer let triplet = self.syncerManager.factory.newEditableTriplet() // //Debugging hack - insert the first server and project we have // triplet.server = self.syncerManager.storageManager.serverConfigs.value.first!.1 // triplet.project = self.syncerManager.storageManager.projectConfigs.value["E94BAED5-7D91-426A-B6B6-5C39BF1F7032"]! // triplet.buildTemplate = self.syncerManager.storageManager.buildTemplates.value["EB0C3E74-C303-4C33-AF0E-012B650D2E9F"] self.showSyncerEditViewControllerWithTriplet(triplet, state: .NoServer) } func showSyncerEditViewControllerWithTriplet(triplet: EditableConfigTriplet, state: EditorState) { let uniqueIdentifier = triplet.syncer.id let viewController: MainEditorViewController = self.storyboardLoader.presentableViewControllerWithStoryboardIdentifier("editorViewController", uniqueIdentifier: uniqueIdentifier, delegate: self.presentingDelegate) var context = EditorContext() context.configTriplet = triplet context.syncerManager = self.syncerManager viewController.factory = EditorViewControllerFactory(storyboardLoader: self.storyboardLoader, serviceAuthenticator: self.serviceAuthenticator) context.editeeDelegate = viewController viewController.context.value = context viewController.loadInState(state) self.presentingDelegate?.presentViewControllerInUniqueWindow(viewController) } } extension DashboardViewController: NSTableViewDataSource { func numberOfRowsInTableView(tableView: NSTableView) -> Int { return self.syncerViewModels.value.count } enum Column: String { case Status = "status" case XCSHost = "xcs_host" case ProjectName = "project_name" case BuildTemplate = "build_template" case Control = "control" case Edit = "edit" } func getTypeOfReusableView<T: NSView>(column: Column) -> T { guard let view = self.syncersTableView.makeViewWithIdentifier(column.rawValue, owner: self) else { fatalError("Couldn't get a reusable view for column \(column)") } guard let typedView = view as? T else { fatalError("Couldn't type view \(view) into type \(T.className())") } return typedView } func bindTextView(view: NSTableCellView, column: Column, viewModel: SyncerViewModel) { let destination = view.textField!.rac_stringValue switch column { case .Status: destination <~ viewModel.status case .XCSHost: destination <~ viewModel.host case .ProjectName: destination <~ viewModel.projectName case .BuildTemplate: destination <~ viewModel.buildTemplateName default: break } } func bindButtonView(view: BuildaNSButton, column: Column, viewModel: SyncerViewModel) { let destinationTitle = view.rac_title let destinationEnabled = view.rac_enabled switch column { case .Edit: destinationTitle <~ viewModel.editButtonTitle destinationEnabled <~ viewModel.editButtonEnabled case .Control: destinationTitle <~ viewModel.controlButtonTitle default: break } } func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { guard let tcolumn = tableColumn else { return nil } let columnIdentifier = tcolumn.identifier guard let column = Column(rawValue: columnIdentifier) else { return nil } let syncerViewModel = self.syncerViewModels.value[row] //based on the column decide which reuse identifier we'll use switch column { case .Status, .XCSHost, .ProjectName, .BuildTemplate: //basic text view let view: NSTableCellView = self.getTypeOfReusableView(column) self.bindTextView(view, column: column, viewModel: syncerViewModel) return view case .Control, .Edit: //push button let view: BuildaNSButton = self.getTypeOfReusableView(column) self.bindButtonView(view, column: column, viewModel: syncerViewModel) view.row = row return view } } } class BuildaNSButton: NSButton { var row: Int? } extension DashboardViewController: NSTableViewDelegate { func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat { return 30 } }
mit
641791219889ea1bea459f336900a371
36.646259
285
0.661366
5.11224
false
true
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/Services/LikeUserHelpers.swift
1
3748
import Foundation /// Helper class for creating LikeUser objects. /// Used by PostService and CommentService when fetching likes for posts/comments. /// @objc class LikeUserHelper: NSObject { @objc class func createOrUpdateFrom(remoteUser: RemoteLikeUser, context: NSManagedObjectContext) -> LikeUser { let liker = likeUser(for: remoteUser, context: context) ?? LikeUser(context: context) liker.userID = remoteUser.userID.int64Value liker.username = remoteUser.username liker.displayName = remoteUser.displayName liker.primaryBlogID = remoteUser.primaryBlogID?.int64Value ?? 0 liker.avatarUrl = remoteUser.avatarURL liker.bio = remoteUser.bio ?? "" liker.dateLikedString = remoteUser.dateLiked ?? "" liker.dateLiked = DateUtils.date(fromISOString: liker.dateLikedString) liker.likedSiteID = remoteUser.likedSiteID?.int64Value ?? 0 liker.likedPostID = remoteUser.likedPostID?.int64Value ?? 0 liker.likedCommentID = remoteUser.likedCommentID?.int64Value ?? 0 liker.preferredBlog = createPreferredBlogFrom(remotePreferredBlog: remoteUser.preferredBlog, forUser: liker, context: context) liker.dateFetched = Date() return liker } class func likeUser(for remoteUser: RemoteLikeUser, context: NSManagedObjectContext) -> LikeUser? { let userID = remoteUser.userID ?? 0 let siteID = remoteUser.likedSiteID ?? 0 let postID = remoteUser.likedPostID ?? 0 let commentID = remoteUser.likedCommentID ?? 0 let request = LikeUser.fetchRequest() as NSFetchRequest<LikeUser> request.predicate = NSPredicate(format: "userID = %@ AND likedSiteID = %@ AND likedPostID = %@ AND likedCommentID = %@", userID, siteID, postID, commentID) return try? context.fetch(request).first } private class func createPreferredBlogFrom(remotePreferredBlog: RemoteLikeUserPreferredBlog?, forUser user: LikeUser, context: NSManagedObjectContext) -> LikeUserPreferredBlog? { guard let remotePreferredBlog = remotePreferredBlog, let preferredBlog = user.preferredBlog ?? NSEntityDescription.insertNewObject(forEntityName: "LikeUserPreferredBlog", into: context) as? LikeUserPreferredBlog else { return nil } preferredBlog.blogUrl = remotePreferredBlog.blogUrl preferredBlog.blogName = remotePreferredBlog.blogName preferredBlog.iconUrl = remotePreferredBlog.iconUrl preferredBlog.blogID = remotePreferredBlog.blogID?.int64Value ?? 0 preferredBlog.user = user return preferredBlog } class func purgeStaleLikes() { let derivedContext = ContextManager.shared.newDerivedContext() derivedContext.perform { purgeStaleLikes(fromContext: derivedContext) ContextManager.shared.save(derivedContext) } } // Delete all LikeUsers that were last fetched at least 7 days ago. private class func purgeStaleLikes(fromContext context: NSManagedObjectContext) { guard let staleDate = Calendar.current.date(byAdding: .day, value: -7, to: Date()) else { DDLogError("Error creating date to purge stale Likes.") return } let request = LikeUser.fetchRequest() as NSFetchRequest<LikeUser> request.predicate = NSPredicate(format: "dateFetched <= %@", staleDate as CVarArg) do { let users = try context.fetch(request) users.forEach { context.delete($0) } } catch { DDLogError("Error fetching Like Users: \(error)") } } }
gpl-2.0
37e7ccd78cc48ac3c69daf2de5345050
43.619048
179
0.673426
4.873862
false
false
false
false
daaavid/TIY-Assignments
44--Philosophone/Philosophone/Philosophone/Settings.swift
1
1188
// // Settings.swift // Philosophone // // Created by david on 12/4/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import Foundation let kHourKey = "Hour" let kCategoriesKey = "Categories" let kSoundKey = "Sound" class Settings: NSObject, NSCoding { var hour: Int var categories: [String] var sound: Bool init(hour: Int, categories: [String], sound: Bool) { self.hour = hour self.categories = categories self.sound = sound } required convenience init?(coder decoder: NSCoder) { guard let hour = decoder.decodeObjectForKey(kHourKey) as? Int, let categories = decoder.decodeObjectForKey(kCategoriesKey) as? [String], let sound = decoder.decodeObjectForKey(kSoundKey) as? Bool else { return nil } self.init(hour: hour, categories: categories, sound: sound) } func encodeWithCoder(coder: NSCoder) { coder.encodeObject(self.hour, forKey: kHourKey) coder.encodeObject(self.categories, forKey: kCategoriesKey) coder.encodeObject(self.sound, forKey: kSoundKey) } }
cc0-1.0
c6c4735eadfb016c331cb8e184ca719e
23.75
85
0.622578
4.079038
false
false
false
false
Takanu/Pelican
Sources/Pelican/API/Types/Message Content/Video.swift
1
2254
// // Video.swift // Pelican // // Created by Takanu Kyriako on 31/08/2017. // import Foundation /** Represents a video file. Go figure. */ public struct Video: TelegramType, MessageFile { // STORAGE AND IDENTIFIERS public var contentType: String = "video" public var method: String = "sendVideo" // FILE SOURCE public var fileID: String? public var url: String? // PARAMETERS /// Width of the video in pixels. public var width: Int? /// Height of the video in pixels. public var height: Int? /// Duration of the video in seconds. public var duration: Int? /// A thumbnail displayed for the video before it plays. public var thumb: Photo? /// The mime type of the video. public var mimeType: String? /// The file size of the video public var fileSize: Int? /// Coding keys to map values when Encoding and Decoding. enum CodingKeys: String, CodingKey { case fileID = "file_id" case url case width case height case duration case thumb case mimeType = "mime_type" case fileSize = "file_size" } public init(fileID: String, width: Int? = nil, height: Int? = nil, duration: Int? = nil, thumb: Photo? = nil, mimeType: String? = nil, fileSize: Int? = nil) { self.fileID = fileID self.width = width self.height = height self.duration = duration self.thumb = thumb self.mimeType = mimeType self.fileSize = fileSize } public init?(url: String, width: Int? = nil, height: Int? = nil, duration: Int? = nil, thumb: Photo? = nil, mimeType: String? = nil, fileSize: Int? = nil) { if url.checkURLValidity(acceptedExtensions: ["mp4"]) == false { return nil } self.url = url self.width = width self.height = height self.duration = duration self.thumb = thumb self.mimeType = mimeType self.fileSize = fileSize } // SendType conforming methods to send itself to Telegram under the provided method. public func getQuery() -> [String: Codable] { var keys: [String: Codable] = [ "video": fileID] if duration != 0 { keys["duration"] = duration } if width != 0 { keys["width"] = width } if height != 0 { keys["height"] = height } return keys } }
mit
a491739e13836c56fa04c0980a42a5b2
20.065421
85
0.637977
3.451761
false
false
false
false
fleurdeswift/data-structure
ExtraDataStructures/TimeRange.swift
1
2005
// // TimeRange.swift // ExtraDataStructures // // Copyright © 2015 Fleur de Swift. All rights reserved. // import Foundation public struct TimeRange { public var start: NSTimeInterval; public var length: NSTimeInterval; public init(start: NSTimeInterval, length: NSTimeInterval) { self.start = start; self.length = length; } public init(start: NSTimeInterval, end: NSTimeInterval) { self.start = start; self.length = end - start; } public init(t0: NSTimeInterval, t1: NSTimeInterval) { self.init(start: min(t0, t1), end: max(t0, t1)); } public func contains(t: NSTimeInterval) -> Bool { return (t >= start) && (t < end); } public func intersects(range2: TimeRange) -> Bool { return (self.start < range2.start + range2.length && range2.start < self.start + self.length); } public func intersection(range2: TimeRange) -> TimeRange { let max1 = self.start + self.length; let max2 = range2.start + range2.length; let minend = (max1 < max2) ? max1 : max2; if range2.start <= self.start && self.start < max2 { return TimeRange(start: self.start, length: minend - self.start); } else if self.start <= range2.start && range2.start < max1 { return TimeRange(start: range2.start, length: minend - range2.start); } return TimeRange(start: -1, length: 0); } public var isValid: Bool { get { return start >= 0 && length > 0; } } public var end: NSTimeInterval { get { return start + length; } } } public func + (range: TimeRange, delta: NSTimeInterval) -> TimeRange { return TimeRange(start: range.start + delta, length: range.length); } public func - (range: TimeRange, delta: NSTimeInterval) -> TimeRange { return TimeRange(start: range.start - delta, length: range.length); }
mit
7b64d1988124bc1e0d81a56c8559880e
27.225352
102
0.593313
3.937132
false
false
false
false
nate-parrott/aamoji
aamoji/SQLite.swift-master/SQLite Tests/FunctionsTests.swift
19
8892
import XCTest import SQLite class FunctionsTests: SQLiteTestCase { func test_createFunction_withZeroArguments() { let f1: () -> Expression<Bool> = db.create(function: "f1") { true } let f2: () -> Expression<Bool?> = db.create(function: "f2") { nil } let table = db["table"] db.create(table: table) { $0.column(Expression<Int>("id"), primaryKey: true) } table.insert().rowid! XCTAssert(table.select(f1()).first![f1()]) AssertSQL("SELECT \"f1\"() FROM \"table\" LIMIT 1") XCTAssertNil(table.select(f2()).first![f2()]) AssertSQL("SELECT \"f2\"() FROM \"table\" LIMIT 1") } func test_createFunction_withOneArgument() { let f1: Expression<String> -> Expression<Bool> = db.create(function: "f1") { _ in return true } let f2: Expression<String?> -> Expression<Bool> = db.create(function: "f2") { _ in return false } let f3: Expression<String> -> Expression<Bool?> = db.create(function: "f3") { _ in return true } let f4: Expression<String?> -> Expression<Bool?> = db.create(function: "f4") { _ in return nil } let table = db["table"] let s1 = Expression<String>("s1") let s2 = Expression<String?>("s2") db.create(table: table) { t in t.column(s1) t.column(s2) } table.insert(s1 <- "s1").rowid! let null = Expression<String?>(value: nil as String?) XCTAssert(table.select(f1(s1)).first![f1(s1)]) AssertSQL("SELECT \"f1\"(\"s1\") FROM \"table\" LIMIT 1") XCTAssert(!table.select(f2(s2)).first![f2(s2)]) AssertSQL("SELECT \"f2\"(\"s2\") FROM \"table\" LIMIT 1") XCTAssert(table.select(f3(s1)).first![f3(s1)]!) AssertSQL("SELECT \"f3\"(\"s1\") FROM \"table\" LIMIT 1") XCTAssertNil(table.select(f4(null)).first![f4(null)]) AssertSQL("SELECT \"f4\"(NULL) FROM \"table\" LIMIT 1") } func test_createFunction_withValueArgument() { let f1: Expression<Bool> -> Expression<Bool> = ( db.create(function: "f1") { (a: Bool) -> Bool in return a } ) let table = db["table"] let b = Expression<Bool>("b") db.create(table: table) { t in t.column(b) } table.insert(b <- true).rowid! XCTAssert(table.select(f1(b)).first![f1(b)]) AssertSQL("SELECT \"f1\"(\"b\") FROM \"table\" LIMIT 1") } func test_createFunction_withTwoArguments() { let table = db["table"] let b1 = Expression<Bool>("b1") let b2 = Expression<Bool?>("b2") db.create(table: table) { t in t.column(b1) t.column(b2) } table.insert(b1 <- true).rowid! let f1: (Bool, Expression<Bool>) -> Expression<Bool> = db.create(function: "f1") { $0 && $1 } let f2: (Bool?, Expression<Bool>) -> Expression<Bool> = db.create(function: "f2") { $0 ?? $1 } let f3: (Bool, Expression<Bool?>) -> Expression<Bool> = db.create(function: "f3") { $0 && $1 != nil } let f4: (Bool?, Expression<Bool?>) -> Expression<Bool> = db.create(function: "f4") { $0 ?? $1 != nil } XCTAssert(table.select(f1(true, b1)).first![f1(true, b1)]) AssertSQL("SELECT \"f1\"(1, \"b1\") FROM \"table\" LIMIT 1") XCTAssert(table.select(f2(nil, b1)).first![f2(nil, b1)]) AssertSQL("SELECT \"f2\"(NULL, \"b1\") FROM \"table\" LIMIT 1") XCTAssertFalse(table.select(f3(false, b2)).first![f3(false, b2)]) AssertSQL("SELECT \"f3\"(0, \"b2\") FROM \"table\" LIMIT 1") XCTAssertFalse(table.select(f4(nil, b2)).first![f4(nil, b2)]) AssertSQL("SELECT \"f4\"(NULL, \"b2\") FROM \"table\" LIMIT 1") let f5: (Bool, Expression<Bool>) -> Expression<Bool?> = db.create(function: "f5") { $0 && $1 } let f6: (Bool?, Expression<Bool>) -> Expression<Bool?> = db.create(function: "f6") { $0 ?? $1 } let f7: (Bool, Expression<Bool?>) -> Expression<Bool?> = db.create(function: "f7") { $0 && $1 != nil } let f8: (Bool?, Expression<Bool?>) -> Expression<Bool?> = db.create(function: "f8") { $0 ?? $1 != nil } XCTAssert(table.select(f5(true, b1)).first![f5(true, b1)]!) AssertSQL("SELECT \"f5\"(1, \"b1\") FROM \"table\" LIMIT 1") XCTAssert(table.select(f6(nil, b1)).first![f6(nil, b1)]!) AssertSQL("SELECT \"f6\"(NULL, \"b1\") FROM \"table\" LIMIT 1") XCTAssertFalse(table.select(f7(false, b2)).first![f7(false, b2)]!) AssertSQL("SELECT \"f7\"(0, \"b2\") FROM \"table\" LIMIT 1") XCTAssertFalse(table.select(f8(nil, b2)).first![f8(nil, b2)]!) AssertSQL("SELECT \"f8\"(NULL, \"b2\") FROM \"table\" LIMIT 1") let f9: (Expression<Bool>, Expression<Bool>) -> Expression<Bool> = db.create(function: "f9") { $0 && $1 } let f10: (Expression<Bool?>, Expression<Bool>) -> Expression<Bool> = db.create(function: "f10") { $0 ?? $1 } let f11: (Expression<Bool>, Expression<Bool?>) -> Expression<Bool> = db.create(function: "f11") { $0 && $1 != nil } let f12: (Expression<Bool?>, Expression<Bool?>) -> Expression<Bool> = db.create(function: "f12") { $0 ?? $1 != nil } XCTAssert(table.select(f9(b1, b1)).first![f9(b1, b1)]) AssertSQL("SELECT \"f9\"(\"b1\", \"b1\") FROM \"table\" LIMIT 1") XCTAssert(table.select(f10(b2, b1)).first![f10(b2, b1)]) AssertSQL("SELECT \"f10\"(\"b2\", \"b1\") FROM \"table\" LIMIT 1") XCTAssertFalse(table.select(f11(b1, b2)).first![f11(b1, b2)]) AssertSQL("SELECT \"f11\"(\"b1\", \"b2\") FROM \"table\" LIMIT 1") XCTAssertFalse(table.select(f12(b2, b2)).first![f12(b2, b2)]) AssertSQL("SELECT \"f12\"(\"b2\", \"b2\") FROM \"table\" LIMIT 1") let f13: (Expression<Bool>, Expression<Bool>) -> Expression<Bool?> = db.create(function: "f13") { $0 && $1 } let f14: (Expression<Bool?>, Expression<Bool>) -> Expression<Bool?> = db.create(function: "f14") { $0 ?? $1 } let f15: (Expression<Bool>, Expression<Bool?>) -> Expression<Bool?> = db.create(function: "f15") { $0 && $1 != nil } let f16: (Expression<Bool?>, Expression<Bool?>) -> Expression<Bool?> = db.create(function: "f16") { $0 ?? $1 != nil } XCTAssert(table.select(f13(b1, b1)).first![f13(b1, b1)]!) AssertSQL("SELECT \"f13\"(\"b1\", \"b1\") FROM \"table\" LIMIT 1") XCTAssert(table.select(f14(b2, b1)).first![f14(b2, b1)]!) AssertSQL("SELECT \"f14\"(\"b2\", \"b1\") FROM \"table\" LIMIT 1") XCTAssertFalse(table.select(f15(b1, b2)).first![f15(b1, b2)]!) AssertSQL("SELECT \"f15\"(\"b1\", \"b2\") FROM \"table\" LIMIT 1") XCTAssertFalse(table.select(f16(b2, b2)).first![f16(b2, b2)]!) AssertSQL("SELECT \"f16\"(\"b2\", \"b2\") FROM \"table\" LIMIT 1") let f17: (Expression<Bool>, Bool) -> Expression<Bool> = db.create(function: "f17") { $0 && $1 } let f18: (Expression<Bool?>, Bool) -> Expression<Bool> = db.create(function: "f18") { $0 ?? $1 } let f19: (Expression<Bool>, Bool?) -> Expression<Bool> = db.create(function: "f19") { $0 && $1 != nil } let f20: (Expression<Bool?>, Bool?) -> Expression<Bool> = db.create(function: "f20") { $0 ?? $1 != nil } XCTAssert(table.select(f17(b1, true)).first![f17(b1, true)]) AssertSQL("SELECT \"f17\"(\"b1\", 1) FROM \"table\" LIMIT 1") XCTAssert(table.select(f18(b2, true)).first![f18(b2, true)]) AssertSQL("SELECT \"f18\"(\"b2\", 1) FROM \"table\" LIMIT 1") XCTAssertFalse(table.select(f19(b1, nil)).first![f19(b1, nil)]) AssertSQL("SELECT \"f19\"(\"b1\", NULL) FROM \"table\" LIMIT 1") XCTAssertFalse(table.select(f20(b2, nil)).first![f20(b2, nil)]) AssertSQL("SELECT \"f20\"(\"b2\", NULL) FROM \"table\" LIMIT 1") let f21: (Expression<Bool>, Bool) -> Expression<Bool?> = db.create(function: "f21") { $0 && $1 } let f22: (Expression<Bool?>, Bool) -> Expression<Bool?> = db.create(function: "f22") { $0 ?? $1 } let f23: (Expression<Bool>, Bool?) -> Expression<Bool?> = db.create(function: "f23") { $0 && $1 != nil } let f24: (Expression<Bool?>, Bool?) -> Expression<Bool?> = db.create(function: "f24") { $0 ?? $1 != nil } XCTAssert(table.select(f21(b1, true)).first![f21(b1, true)]!) AssertSQL("SELECT \"f21\"(\"b1\", 1) FROM \"table\" LIMIT 1") XCTAssert(table.select(f22(b2, true)).first![f22(b2, true)]!) AssertSQL("SELECT \"f22\"(\"b2\", 1) FROM \"table\" LIMIT 1") XCTAssertFalse(table.select(f23(b1, nil)).first![f23(b1, nil)]!) AssertSQL("SELECT \"f23\"(\"b1\", NULL) FROM \"table\" LIMIT 1") XCTAssertFalse(table.select(f24(b2, nil)).first![f24(b2, nil)]!) AssertSQL("SELECT \"f24\"(\"b2\", NULL) FROM \"table\" LIMIT 1") } }
mit
95e67795b493309348c630c53569968f
53.219512
125
0.558142
3.149841
false
false
false
false
adriaan/DiskFiller
DiskFiller/FileHandler.swift
1
6679
import Foundation final class FileHandler { weak var delegate: FileHandlerDelegate? let fileManager = FileManager.default let fileHandlingQueue = DispatchQueue.global(qos: .userInitiated) var shouldStop = false let documentsPath: String? let sourcePath: String? = Bundle.main.path(forResource: "winking_kitten", ofType: "jpg") var numberOfFilesStored: Int? init() { let searchPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) documentsPath = searchPaths.first initialiseNumFiles() } func fillDisk() { shouldStop = false guard let documentsPath = documentsPath, let sourcePath = sourcePath else { delegate?.fileHandler(fileHander: self, didFailWithError: FileHandlingError.documentsPathNotFound) return } fileHandlingQueue.async { do { let filePaths = try self.fileManager.contentsOfDirectory(atPath: documentsPath) var i = filePaths.count self.numberOfFilesStored = i var proceed = true while proceed { let fileName = "/file\(i).jpg" let filePath = documentsPath.appending(fileName) if !self.fileManager.fileExists(atPath: filePath) { do { try self.fileManager.copyItem(atPath: sourcePath, toPath: filePath) self.delegate?.fileHandlerDidAddFile(fileHander: self) self.incrementFilesStored() } catch { proceed = false self.delegate?.fileHandlerDidFinishAddingFiles(fileHander: self) } } if self.shouldStop { self.delegate?.fileHandlerDidCancel(fileHander: self) return } i += 1 } } catch { self.delegate?.fileHandler(fileHander: self, didFailWithError: FileHandlingError.documentsPathNotFound) } } } func removeSomeFiles(numberOfFiles: Int) { shouldStop = false guard let documentsPath = documentsPath else { delegate?.fileHandler(fileHander: self, didFailWithError: FileHandlingError.documentsPathNotFound) return } fileHandlingQueue.async { do { let filePaths = try self.fileManager.contentsOfDirectory(atPath: documentsPath) let numToDelete = min(numberOfFiles, filePaths.count) guard numToDelete > 0 else { self.delegate?.fileHandlerDidFinishRemovingFiles(fileHander: self) return } for i in 0..<numToDelete { let path = "\(documentsPath)/\(filePaths[i])" self.removeFile(atPath: path) } self.delegate?.fileHandlerDidFinishRemovingFiles(fileHander: self) } catch { self.delegate?.fileHandler(fileHander: self, didFailWithError: FileHandlingError.documentsPathNotFound) } } } func removeAllFiles() { shouldStop = false guard let documentsPath = documentsPath else { delegate?.fileHandler(fileHander: self, didFailWithError: FileHandlingError.documentsPathNotFound) return } fileHandlingQueue.async { do { let filePaths = try self.fileManager.contentsOfDirectory(atPath: documentsPath) for filePath in filePaths { let path = "\(documentsPath)/\(filePath)" self.removeFile(atPath: path) if self.shouldStop { self.delegate?.fileHandlerDidCancel(fileHander: self) return } } self.delegate?.fileHandlerDidFinishRemovingFiles(fileHander: self) } catch { self.delegate?.fileHandler(fileHander: self, didFailWithError: FileHandlingError.documentsPathNotFound) } } } private func incrementFilesStored() { guard let numFiles = numberOfFilesStored else { initialiseNumFiles() return } numberOfFilesStored = numFiles + 1 } private func decrementFilesStored() { guard let numFiles = numberOfFilesStored else { initialiseNumFiles() return } numberOfFilesStored = max(numFiles - 1, 0) } private func initialiseNumFiles() { guard let documentsPath = documentsPath, let filePaths = try? self.fileManager.contentsOfDirectory(atPath: documentsPath) else { return } numberOfFilesStored = filePaths.count } private func removeFile(atPath path: String) { guard fileManager.fileExists(atPath: path) else { return } do { try fileManager.removeItem(atPath: path) decrementFilesStored() delegate?.fileHandlerDidRemoveFile(fileHander: self) } catch { delegate?.fileHandler(fileHander: self, didFailWithError: FileHandlingError.failedToDelete) } } } protocol FileHandlerDelegate: class { func fileHandlerDidAddFile(fileHander: FileHandler) func fileHandlerDidRemoveFile(fileHander: FileHandler) func fileHandlerDidFinishAddingFiles(fileHander: FileHandler) func fileHandlerDidFinishRemovingFiles(fileHander: FileHandler) func fileHandler(fileHander: FileHandler, didFailWithError error: FileHandlingError) func fileHandlerDidCancel(fileHander: FileHandler) } enum FileHandlingError: Error { case failedToDelete case failedToCopy case documentsPathNotFound var shortDescription: String { switch self { case .failedToCopy: return "Failed to save file" case .failedToDelete: return "Failed to delete file" case .documentsPathNotFound: return "Documents folder not found" } } var description: String { switch self { case .failedToCopy: return "Copying and saving a kitten failed. Please try again..." case .failedToDelete: return "Our attemts to delete a kitten from your hard drive failed. Please try again..." case .documentsPathNotFound: return "We couldn't find the folder we use for storing kittens." } } }
mit
35dc34b6cd47ac4fe2f4db205b70b326
37.165714
145
0.595898
5.693947
false
false
false
false
caronae/caronae-ios
Caronae/User/ProfileViewController.swift
1
7803
import UIKit import InputMask class ProfileViewController: UIViewController, UICollectionViewDataSource { // ID @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var courseLabel: UILabel! @IBOutlet weak var profileImage: UIImageView! @IBOutlet weak var phoneView: UIView! @IBOutlet weak var phoneButton: UIButton! // Mutual friends @IBOutlet weak var mutualFriendsView: UIView! @IBOutlet weak var mutualFriendsCollectionView: UICollectionView! @IBOutlet weak var mutualFriendsLabel: UILabel! // Numbers @IBOutlet weak var joinedDateLabel: UILabel! @IBOutlet weak var numDrivesLabel: UILabel! @IBOutlet weak var numRidesLabel: UILabel! // Car details @IBOutlet weak var carDetailsView: UIView! @IBOutlet weak var carPlateLabel: UILabel! @IBOutlet weak var carModelLabel: UILabel! @IBOutlet weak var carColorLabel: UILabel! @IBOutlet weak var editButton: UIBarButtonItem! @IBOutlet weak var signoutButton: UIButton! @IBOutlet weak var reportView: UIView! var user: User! var mutualFriends = [User]() override func viewDidLoad() { super.viewDidLoad() updateProfileFields() if UserService.instance.user == self.user { NotificationCenter.default.addObserver(self, selector: #selector(updateProfileFields), name: .CaronaeDidUpdateUser, object: nil) } // Add gesture recognizer to phoneButton for longpress let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(didLongPressPhoneButton)) phoneButton.addGestureRecognizer(longPressGesture) // Add gesture reconizer to profileImage for tap let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTapProfileImage)) profileImage.addGestureRecognizer(tapGesture) } deinit { NotificationCenter.default.removeObserver(self) } @objc func updateProfileFields() { guard let currentUser = UserService.instance.user else { return } if currentUser.id == user.id { self.title = "Meu Perfil" if user.carOwner { carPlateLabel.text = user.carPlate carModelLabel.text = user.carModel carColorLabel.text = user.carColor } else { carPlateLabel.text = "-" carModelLabel.text = "-" carColorLabel.text = "-" } DispatchQueue.main.async { self.mutualFriendsView.removeFromSuperview() self.reportView.removeFromSuperview() } } else { self.title = user.name self.navigationItem.rightBarButtonItem = nil DispatchQueue.main.async { self.carDetailsView.removeFromSuperview() self.signoutButton.removeFromSuperview() } updateMutualFriends() } if let userCreateAt = user.createdAt { let joinedDateFormatter = DateFormatter() joinedDateFormatter.dateFormat = "MM/yyyy" joinedDateLabel.text = joinedDateFormatter.string(from: userCreateAt) } if let profilePictureURL = user.profilePictureURL, !profilePictureURL.isEmpty { self.profileImage.crn_setImage(with: URL(string: profilePictureURL)) } nameLabel.text = user.name courseLabel.text = user.occupation numDrivesLabel.text = user.numDrives > -1 ? String(user.numDrives) : "-" numRidesLabel.text = user.numRides > -1 ? String(user.numRides) : "-" configurePhoneNumber() updateRidesOfferedCount() } func configurePhoneNumber() { if let phoneNumber = user.phoneNumber, !phoneNumber.isEmpty { let phoneMask = try! Mask(format: Caronae9PhoneNumberPattern) let result = phoneMask.apply(toText: CaretString(string: phoneNumber, caretPosition: phoneNumber.endIndex)) let formattedPhoneNumber = result.formattedText.string phoneButton.setTitle(formattedPhoneNumber, for: .normal) } else { DispatchQueue.main.async { self.phoneView.removeFromSuperview() } } } func updateRidesOfferedCount() { UserService.instance.ridesCountForUser(withID: user.id, success: { offeredCount, takenCount in self.numDrivesLabel.text = String(offeredCount) self.numRidesLabel.text = String(takenCount) }, error: { err in NSLog("Error reading history count for user: %@", err.localizedDescription) }) } func updateMutualFriends() { UserService.instance.mutualFriendsForUser(withFacebookID: user.facebookID, success: { mutualFriends, totalCount in self.mutualFriends = mutualFriends self.mutualFriendsCollectionView.reloadData() if totalCount > 0 { self.mutualFriendsLabel.text = String(format: "Amigos em comum: %ld no total e %ld no Caronaê", totalCount, mutualFriends.count) } else { self.mutualFriendsLabel.text = "Amigos em comum: 0" } }, error: { err in NSLog("Error loading mutual friends for user: %@", err.localizedDescription) }) } // MARK: IBActions @objc func didTapProfileImage() { guard let profilePictureURL = user.profilePictureURL, !profilePictureURL.isEmpty else { return } CaronaeImageViewer.instance.present(pictureURL: profilePictureURL, animatedFrom: profileImage) } @objc func didLongPressPhoneButton() { guard let phoneText = phoneButton.titleLabel?.text, !phoneText.isEmpty else { return } let alert = PhoneNumberAlert().actionSheet(view: self, buttonText: phoneText, user: user) self.present(alert!, animated: true, completion: nil) } @IBAction func didTapPhoneButton() { guard let phoneNumber = user.phoneNumber else { return } let phoneNumberURLString = String(format: "telprompt://%@", phoneNumber) UIApplication.shared.openURL(URL(string: phoneNumberURLString)!) } @IBAction func didTapLogoutButton() { let alert = CaronaeAlertController(title: "Você deseja mesmo sair da sua conta?", message: nil, preferredStyle: .alert) alert?.addAction(SDCAlertAction(title: "Cancelar", style: .cancel, handler: nil)) alert?.addAction(SDCAlertAction(title: "Sair", style: .destructive, handler: { _ in UserService.instance.signOut() })) alert?.present(completion: nil) } // MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ReportUser" { let falaeVC = segue.destination as! FalaeViewController falaeVC.reportedUser = user } } // MARK: Collection methods (Mutual friends) func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return mutualFriends.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Friend Cell", for: indexPath) as! RiderCell let user = mutualFriends[indexPath.row] cell.configure(with: user) return cell } }
gpl-3.0
6674543e81323c0b49e88ee55fa8f79d
36.325359
144
0.630304
5.10871
false
false
false
false
iOSDevLog/iOSDevLog
116. Dropit/Dropit/DropitViewController.swift
1
5391
// // DropitViewController.swift // Dropit // // Created by jiaxianhua on 15/10/3. // Copyright © 2015年 com.jiaxh. All rights reserved. // import UIKit class DropitViewController: UIViewController, UIDynamicAnimatorDelegate { // MARK: - Outlets @IBOutlet weak var gameView: BezierPathsView! // MARK: - Animation lazy var animator: UIDynamicAnimator = { let lazilyCreatedDynamicAnimator = UIDynamicAnimator(referenceView: self.gameView) lazilyCreatedDynamicAnimator.delegate = self return lazilyCreatedDynamicAnimator }() let dropitBehavior = DropitBehavior() var attachment: UIAttachmentBehavior? { willSet { if attachment != nil { animator.removeBehavior(attachment!) } gameView.setPath(nil, named: PathNames.Attachment) } didSet { if attachment != nil { animator.addBehavior(attachment!) attachment?.action = { [unowned self] in if let attachedView = self.attachment?.items.first as? UIView { let path = UIBezierPath() path.moveToPoint(self.attachment!.anchorPoint) path.addLineToPoint(attachedView.center) self.gameView.setPath(path, named: PathNames.Attachment) } } } } } // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() animator.addBehavior(dropitBehavior) } // MARK: - Constants struct PathNames { static let MiddleBarrier = "Middle Barrier" static let Attachment = "Attachment" } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let barrierSize = dropSize let barrierOrigin = CGPoint(x: gameView.bounds.midX-barrierSize.width/2, y: gameView.bounds.midY-barrierSize.height/2) let path = UIBezierPath(ovalInRect: CGRect(origin: barrierOrigin, size: barrierSize)) dropitBehavior.addBarrier(path, named: PathNames.MiddleBarrier) gameView.setPath(path, named: PathNames.MiddleBarrier) } func dynamicAnimatorDidPause(animator: UIDynamicAnimator) { removeCompletedRow() } var dropsPerRow = 10 var dropSize: CGSize { let size = gameView.bounds.width / CGFloat(dropsPerRow) return CGSize(width: size, height: size) } var lastDroppedView: UIView? @IBAction func grabDrop(sender: UIPanGestureRecognizer) { let gesturePoint = sender.locationInView(gameView) switch sender.state { case .Began: if let viewToAttachTo = lastDroppedView { attachment = UIAttachmentBehavior(item: viewToAttachTo, attachedToAnchor: gesturePoint) lastDroppedView = nil } case .Changed: attachment?.anchorPoint = gesturePoint case .Ended: attachment = nil default: break } } @IBAction func drop(sender: UITapGestureRecognizer) { drop() } func drop() { var frame = CGRect(origin: CGPointZero, size: dropSize) frame.origin.x = CGFloat.random(dropsPerRow) * dropSize.width let dropView = UIView(frame: frame) dropView.backgroundColor = UIColor.random lastDroppedView = dropView dropitBehavior.addDrop(dropView) } // removes a single, completed row // allows for a little "wiggle room" for mostly complete rows // in the end, does nothing more than call removeDrop() in DropitBehavior func removeCompletedRow() { var dropsToRemove = [UIView]() var dropFrame = CGRect(x: 0, y: gameView.frame.maxY, width: dropSize.width, height: dropSize.height) repeat { dropFrame.origin.y -= dropSize.height dropFrame.origin.x = 0 var dropsFound = [UIView]() var rowIsComplete = true for _ in 0 ..< dropsPerRow { if let hitView = gameView.hitTest(CGPoint(x: dropFrame.midX, y: dropFrame.midY), withEvent: nil) { if hitView.superview == gameView { dropsFound.append(hitView) } else { rowIsComplete = false } } dropFrame.origin.x += dropSize.width } if rowIsComplete { dropsToRemove += dropsFound } } while dropsToRemove.count == 0 && dropFrame.origin.y > 0 for drop in dropsToRemove { dropitBehavior.removeDrop(drop) } } } // MARK: - Extensions private extension CGFloat { static func random(max: Int) -> CGFloat { return CGFloat(arc4random() % UInt32(max)) } } private extension UIColor { class var random: UIColor { switch arc4random()%5 { case 0: return UIColor.greenColor() case 1: return UIColor.blueColor() case 2: return UIColor.orangeColor() case 3: return UIColor.redColor() case 4: return UIColor.purpleColor() default: return UIColor.blackColor() } } }
mit
d08e757096b0f604ad4e6b77c9d0f20f
31.463855
126
0.586488
4.880435
false
false
false
false
johnno1962d/swift
stdlib/public/core/Collection.swift
1
25984
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A type that provides subscript access to its elements. /// /// - Important: In most cases, it's best to ignore this protocol and use /// `CollectionType` instead, as it has a more complete interface. public protocol Indexable { // This protocol is almost an implementation detail of the standard // library; it is used to deduce things like the `SubSequence` and // `Iterator` type from a minimal collection, but it is also used in // exposed places like as a constraint on `IndexingIterator`. /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. associatedtype Index : ForwardIndex /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. /// /// - Complexity: O(1) var startIndex: Index { get } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. /// /// - Complexity: O(1) var endIndex: Index { get } // The declaration of _Element and subscript here is a trick used to // break a cyclic conformance/deduction that Swift can't handle. We // need something other than a Collection.Iterator.Element that can // be used as IndexingIterator<T>'s Element. Here we arrange for // the Collection itself to have an Element type that's deducible from // its subscript. Ideally we'd like to constrain this Element to be the same // as Collection.Iterator.Element (see below), but we have no way of // expressing it today. associatedtype _Element /// Returns the element at the given `position`. /// /// - Complexity: O(1) subscript(position: Index) -> _Element { get } } /// A type that supports subscript assignment to a mutable collection. public protocol MutableIndexable { associatedtype Index : ForwardIndex var startIndex: Index { get } var endIndex: Index { get } associatedtype _Element subscript(position: Index) -> _Element { get set } } /// The iterator used for collections that don't specify one. public struct IndexingIterator<Elements : Indexable> : IteratorProtocol, Sequence { /// Create an *iterator* over the given collection. public /// @testable init(_elements: Elements) { self._elements = _elements self._position = _elements.startIndex } /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// - Precondition: No preceding call to `self.next()` has returned `nil`. public mutating func next() -> Elements._Element? { if _position == _elements.endIndex { return nil } let element = _elements[_position] _position._successorInPlace() return element } internal let _elements: Elements internal var _position: Elements.Index } /// A multi-pass sequence with addressable positions. /// /// Positions are represented by an associated `Index` type. Whereas /// an arbitrary sequence may be consumed as it is traversed, a /// collection is multi-pass: any element may be revisited merely by /// saving its index. /// /// The sequence view of the elements is identical to the collection /// view. In other words, the following code binds the same series of /// values to `x` as does `for x in self {}`: /// /// for i in startIndex..<endIndex { /// let x = self[i] /// } public protocol Collection : Indexable, Sequence { /// A type that provides the sequence's iteration interface and /// encapsulates its iteration state. /// /// By default, a `Collection` satisfies `Sequence` by /// supplying a `IndexingIterator` as its associated `Iterator` /// type. associatedtype Iterator : IteratorProtocol = IndexingIterator<Self> // FIXME: Needed here so that the `Iterator` is properly deduced from // a custom `makeIterator()` function. Otherwise we get an // `IndexingIterator`. <rdar://problem/21539115> func makeIterator() -> Iterator // FIXME: should be constrained to Collection // (<rdar://problem/20715009> Implement recursive protocol // constraints) /// A `Sequence` that can represent a contiguous subrange of `self`'s /// elements. /// /// - Note: This associated type appears as a requirement in /// `Sequence`, but is restated here with stricter /// constraints: in a `Collection`, the `SubSequence` should /// also be a `Collection`. associatedtype SubSequence : Indexable, Sequence = Slice<Self> /// Returns the element at the given `position`. subscript(position: Index) -> Iterator.Element { get } /// Returns a collection representing a contiguous sub-range of /// `self`'s elements. /// /// - Complexity: O(1) subscript(bounds: Range<Index>) -> SubSequence { get } /// Returns `self[startIndex..<end]` /// /// - Complexity: O(1) @warn_unused_result func prefix(upTo end: Index) -> SubSequence /// Returns `self[start..<endIndex]` /// /// - Complexity: O(1) @warn_unused_result func suffix(from start: Index) -> SubSequence /// Returns `prefix(upTo: position.successor())` /// /// - Complexity: O(1) @warn_unused_result func prefix(through position: Index) -> SubSequence /// Returns `true` iff `self` is empty. var isEmpty: Bool { get } /// Returns the number of elements. /// /// - Complexity: O(1) if `Index` conforms to `RandomAccessIndex`; /// O(N) otherwise. var count: Index.Distance { get } // The following requirement enables dispatching for indexOf when // the element type is Equatable. /// Returns `Optional(Optional(index))` if an element was found; /// `nil` otherwise. /// /// - Complexity: O(N). @warn_unused_result func _customIndexOfEquatableElement(_ element: Iterator.Element) -> Index?? /// Returns the first element of `self`, or `nil` if `self` is empty. var first: Iterator.Element? { get } } /// Supply the default `makeIterator()` method for `Collection` models /// that accept the default associated `Iterator`, /// `IndexingIterator<Self>`. extension Collection where Iterator == IndexingIterator<Self> { public func makeIterator() -> IndexingIterator<Self> { return IndexingIterator(_elements: self) } } /// Supply the default "slicing" `subscript` for `Collection` models /// that accept the default associated `SubSequence`, `Slice<Self>`. extension Collection where SubSequence == Slice<Self> { public subscript(bounds: Range<Index>) -> Slice<Self> { Index._failEarlyRangeCheck2( rangeStart: bounds.startIndex, rangeEnd: bounds.endIndex, boundsStart: startIndex, boundsEnd: endIndex) return Slice(_base: self, bounds: bounds) } } extension Collection where SubSequence == Self { /// If `!self.isEmpty`, remove the first element and return it, otherwise /// return `nil`. /// /// - Complexity: O(1) @warn_unused_result public mutating func popFirst() -> Iterator.Element? { guard !isEmpty else { return nil } let element = first! self = self[startIndex.successor()..<endIndex] return element } } extension Collection where SubSequence == Self, Index : BidirectionalIndex { /// If `!self.isEmpty`, remove the last element and return it, otherwise /// return `nil`. /// /// - Complexity: O(1) @warn_unused_result public mutating func popLast() -> Iterator.Element? { guard !isEmpty else { return nil } let element = last! self = self[startIndex..<endIndex.predecessor()] return element } } /// Default implementations of core requirements extension Collection { /// Returns `true` iff `self` is empty. /// /// - Complexity: O(1) public var isEmpty: Bool { return startIndex == endIndex } /// Returns the first element of `self`, or `nil` if `self` is empty. /// /// - Complexity: O(1) public var first: Iterator.Element? { // NB: Accessing `startIndex` may not be O(1) for some lazy collections, // so instead of testing `isEmpty` and then returning the first element, // we'll just rely on the fact that the iterator always yields the // first element first. var i = makeIterator() return i.next() } /// Returns a value less than or equal to the number of elements in /// `self`, *nondestructively*. /// /// - Complexity: O(`count`). public var underestimatedCount: Int { return numericCast(count) } /// Returns the number of elements. /// /// - Complexity: O(1) if `Index` conforms to `RandomAccessIndex`; /// O(N) otherwise. public var count: Index.Distance { return startIndex.distance(to: endIndex) } /// Customization point for `Sequence.index(of:)`. /// /// Define this method if the collection can find an element in less than /// O(N) by exploiting collection-specific knowledge. /// /// - Returns: `nil` if a linear search should be attempted instead, /// `Optional(nil)` if the element was not found, or /// `Optional(Optional(index))` if an element was found. /// /// - Complexity: O(`count`). @warn_unused_result public // dispatching func _customIndexOfEquatableElement(_: Iterator.Element) -> Index?? { return nil } } //===----------------------------------------------------------------------===// // Default implementations for Collection //===----------------------------------------------------------------------===// extension Collection { /// Returns an `Array` containing the results of mapping `transform` /// over `self`. /// /// - Complexity: O(N). @warn_unused_result public func map<T>( _ transform: @noescape (Iterator.Element) throws -> T ) rethrows -> [T] { let count: Int = numericCast(self.count) if count == 0 { return [] } var result = ContiguousArray<T>() result.reserveCapacity(count) var i = self.startIndex for _ in 0..<count { result.append(try transform(self[i])) i = i.successor() } _expectEnd(i, self) return Array(result) } /// Returns a subsequence containing all but the first `n` elements. /// /// - Precondition: `n >= 0` /// - Complexity: O(`n`) @warn_unused_result public func dropFirst(_ n: Int) -> SubSequence { _precondition(n >= 0, "Can't drop a negative number of elements from a collection") let start = startIndex.advanced(by: numericCast(n), limit: endIndex) return self[start..<endIndex] } /// Returns a subsequence containing all but the last `n` elements. /// /// - Precondition: `n >= 0` /// - Complexity: O(`self.count`) @warn_unused_result public func dropLast(_ n: Int) -> SubSequence { _precondition( n >= 0, "Can't drop a negative number of elements from a collection") let amount = Swift.max(0, numericCast(count) - n) let end = startIndex.advanced(by: numericCast(amount), limit: endIndex) return self[startIndex..<end] } /// Returns a subsequence, up to `maxLength` in length, containing the /// initial elements. /// /// If `maxLength` exceeds `self.count`, the result contains all /// the elements of `self`. /// /// - Precondition: `maxLength >= 0` /// - Complexity: O(`maxLength`) @warn_unused_result public func prefix(_ maxLength: Int) -> SubSequence { _precondition( maxLength >= 0, "Can't take a prefix of negative length from a collection") let end = startIndex.advanced(by: numericCast(maxLength), limit: endIndex) return self[startIndex..<end] } /// Returns a slice, up to `maxLength` in length, containing the /// final elements of `self`. /// /// If `maxLength` exceeds `s.count`, the result contains all /// the elements of `self`. /// /// - Precondition: `maxLength >= 0` /// - Complexity: O(`self.count`) @warn_unused_result public func suffix(_ maxLength: Int) -> SubSequence { _precondition( maxLength >= 0, "Can't take a suffix of negative length from a collection") let amount = Swift.max(0, numericCast(count) - maxLength) let start = startIndex.advanced(by: numericCast(amount), limit: endIndex) return self[start..<endIndex] } /// Returns `self[startIndex..<end]` /// /// - Complexity: O(1) @warn_unused_result public func prefix(upTo end: Index) -> SubSequence { return self[startIndex..<end] } /// Returns `self[start..<endIndex]` /// /// - Complexity: O(1) @warn_unused_result public func suffix(from start: Index) -> SubSequence { return self[start..<endIndex] } /// Returns `prefix(upTo: position.successor())` /// /// - Complexity: O(1) @warn_unused_result public func prefix(through position: Index) -> SubSequence { return prefix(upTo: position.successor()) } /// Returns the maximal `SubSequence`s of `self`, in order, that /// don't contain elements satisfying the predicate `isSeparator`. /// /// - Parameter maxSplits: The maximum number of `SubSequence`s to /// return, minus 1. /// If `maxSplits + 1` `SubSequence`s are returned, the last one is /// a suffix of `self` containing *all* the elements of `self` following the /// last split point. /// The default value is `Int.max`. /// /// - Parameter omittingEmptySubsequences: If `false`, an empty `SubSequence` /// is produced in the result for each pair of consecutive elements /// satisfying `isSeparator`. /// The default value is `true`. /// /// - Precondition: `maxSplits >= 0` @warn_unused_result public func split( maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, isSeparator: @noescape (Iterator.Element) throws -> Bool ) rethrows -> [SubSequence] { _precondition(maxSplits >= 0, "Must take zero or more splits") var result: [SubSequence] = [] var subSequenceStart: Index = startIndex func appendSubsequence(end: Index) -> Bool { if subSequenceStart == end && omittingEmptySubsequences { return false } result.append(self[subSequenceStart..<end]) return true } if maxSplits == 0 || isEmpty { appendSubsequence(end: endIndex) return result } var subSequenceEnd = subSequenceStart let cachedEndIndex = endIndex while subSequenceEnd != cachedEndIndex { if try isSeparator(self[subSequenceEnd]) { let didAppend = appendSubsequence(end: subSequenceEnd) subSequenceEnd._successorInPlace() subSequenceStart = subSequenceEnd if didAppend && result.count == maxSplits { break } continue } subSequenceEnd._successorInPlace() } if subSequenceStart != cachedEndIndex || !omittingEmptySubsequences { result.append(self[subSequenceStart..<cachedEndIndex]) } return result } } extension Collection where Iterator.Element : Equatable { /// Returns the maximal `SubSequence`s of `self`, in order, around a /// `separator` element. /// /// - Parameter maxSplits: The maximum number of `SubSequence`s to /// return, minus 1. /// If `maxSplits + 1` `SubSequence`s are returned, the last one is /// a suffix of `self` containing *all* the elements of `self` following the /// last split point. /// The default value is `Int.max`. /// /// - Parameter omittingEmptySubsequences: If `false`, an empty `SubSequence` /// is produced in the result for each pair of consecutive elements /// equal to `separator`. /// The default value is `true`. /// /// - Precondition: `maxSplits >= 0` @warn_unused_result public func split( separator: Iterator.Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true ) -> [SubSequence] { return split( maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, isSeparator: { $0 == separator }) } } extension Collection where Index : BidirectionalIndex { /// Returns a subsequence containing all but the last `n` elements. /// /// - Precondition: `n >= 0` /// - Complexity: O(`n`) @warn_unused_result public func dropLast(_ n: Int) -> SubSequence { _precondition( n >= 0, "Can't drop a negative number of elements from a collection") let end = endIndex.advanced(by: numericCast(-n), limit: startIndex) return self[startIndex..<end] } /// Returns a slice, up to `maxLength` in length, containing the /// final elements of `self`. /// /// If `maxLength` exceeds `s.count`, the result contains all /// the elements of `self`. /// /// - Precondition: `maxLength >= 0` /// - Complexity: O(`maxLength`) @warn_unused_result public func suffix(_ maxLength: Int) -> SubSequence { _precondition( maxLength >= 0, "Can't take a suffix of negative length from a collection") let start = endIndex.advanced(by: numericCast(-maxLength), limit: startIndex) return self[start..<endIndex] } } extension Collection where SubSequence == Self { /// Remove the element at `startIndex` and return it. /// /// - Complexity: O(1) /// - Precondition: `!self.isEmpty`. @discardableResult public mutating func removeFirst() -> Iterator.Element { _precondition(!isEmpty, "can't remove items from an empty collection") let element = first! self = self[startIndex.successor()..<endIndex] return element } /// Remove the first `n` elements. /// /// - Complexity: /// - O(1) if `Index` conforms to `RandomAccessIndex` /// - O(n) otherwise /// - Precondition: `n >= 0 && self.count >= n`. public mutating func removeFirst(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "can't remove more items from a collection than it contains") self = self[startIndex.advanced(by: numericCast(n))..<endIndex] } } extension Collection where SubSequence == Self, Index : BidirectionalIndex { /// Remove an element from the end. /// /// - Complexity: O(1) /// - Precondition: `!self.isEmpty` @discardableResult public mutating func removeLast() -> Iterator.Element { let element = last! self = self[startIndex..<endIndex.predecessor()] return element } /// Remove the last `n` elements. /// /// - Complexity: /// - O(1) if `Index` conforms to `RandomAccessIndex` /// - O(n) otherwise /// - Precondition: `n >= 0 && self.count >= n`. public mutating func removeLast(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "can't remove more items from a collection than it contains") self = self[startIndex..<endIndex.advanced(by: numericCast(-n))] } } extension Sequence where Self : _ArrayProtocol, Self.Element == Self.Iterator.Element { // A fast implementation for when you are backed by a contiguous array. public func _copyContents( initializing ptr: UnsafeMutablePointer<Iterator.Element> ) -> UnsafeMutablePointer<Iterator.Element> { if let s = self._baseAddressIfContiguous { let count = self.count ptr.initializeFrom(s, count: count) _fixLifetime(self._owner) return ptr + count } else { var p = ptr for x in self { p.initialize(with: x) p += 1 } return p } } } extension Collection { public func _preprocessingPass<R>(_ preprocess: @noescape () -> R) -> R? { return preprocess() } } /// A *collection* that supports subscript assignment. /// /// For any instance `a` of a type conforming to /// `MutableCollection`, : /// /// a[i] = x /// let y = a[i] /// /// is equivalent to: /// /// a[i] = x /// let y = x /// public protocol MutableCollection : MutableIndexable, Collection { // FIXME: should be constrained to MutableCollection // (<rdar://problem/20715009> Implement recursive protocol // constraints) associatedtype SubSequence : Collection /*: MutableCollection*/ = MutableSlice<Self> /// Access the element at `position`. /// /// - Precondition: `position` indicates a valid position in `self` and /// `position != endIndex`. /// /// - Complexity: O(1) subscript(position: Index) -> Iterator.Element {get set} /// Returns a collection representing a contiguous sub-range of /// `self`'s elements. /// /// - Complexity: O(1) for the getter, O(`bounds.count`) for the setter. subscript(bounds: Range<Index>) -> SubSequence {get set} /// Call `body(p)`, where `p` is a pointer to the collection's /// mutable contiguous storage. If no such storage exists, it is /// first created. If the collection does not support an internal /// representation in a form of mutable contiguous storage, `body` is not /// called and `nil` is returned. /// /// Often, the optimizer can eliminate bounds- and uniqueness-checks /// within an algorithm, but when that fails, invoking the /// same algorithm on `body`\ 's argument lets you trade safety for /// speed. mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: @noescape (UnsafeMutablePointer<Iterator.Element>, Int) throws -> R ) rethrows -> R? // FIXME: the signature should use UnsafeMutableBufferPointer, but the // compiler can't handle that. // // <rdar://problem/21933004> Restore the signature of // _withUnsafeMutableBufferPointerIfSupported() that mentions // UnsafeMutableBufferPointer } extension MutableCollection { public mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: @noescape (UnsafeMutablePointer<Iterator.Element>, Int) throws -> R ) rethrows -> R? { return nil } public subscript(bounds: Range<Index>) -> MutableSlice<Self> { get { Index._failEarlyRangeCheck2( rangeStart: bounds.startIndex, rangeEnd: bounds.endIndex, boundsStart: startIndex, boundsEnd: endIndex) return MutableSlice(_base: self, bounds: bounds) } set { _writeBackMutableSlice(&self, bounds: bounds, slice: newValue) } } } internal func _writeBackMutableSlice< C : MutableCollection, Slice_ : Collection where C._Element == Slice_.Iterator.Element, C.Index == Slice_.Index >(_ self_: inout C, bounds: Range<C.Index>, slice: Slice_) { C.Index._failEarlyRangeCheck2( rangeStart: bounds.startIndex, rangeEnd: bounds.endIndex, boundsStart: self_.startIndex, boundsEnd: self_.endIndex) // FIXME(performance): can we use // _withUnsafeMutableBufferPointerIfSupported? Would that create inout // aliasing violations if the newValue points to the same buffer? var selfElementIndex = bounds.startIndex let selfElementsEndIndex = bounds.endIndex var newElementIndex = slice.startIndex let newElementsEndIndex = slice.endIndex while selfElementIndex != selfElementsEndIndex && newElementIndex != newElementsEndIndex { self_[selfElementIndex] = slice[newElementIndex] selfElementIndex._successorInPlace() newElementIndex._successorInPlace() } _precondition( selfElementIndex == selfElementsEndIndex, "Cannot replace a slice of a MutableCollection with a slice of a smaller size") _precondition( newElementIndex == newElementsEndIndex, "Cannot replace a slice of a MutableCollection with a slice of a larger size") } @available(*, unavailable, message: "Bit enum has been removed. Please use Int instead.") public enum Bit {} @available(*, unavailable, renamed: "IndexingIterator") public struct IndexingGenerator<Elements : Indexable> {} @available(*, unavailable, renamed: "Collection") public typealias CollectionType = Collection extension Collection { @available(*, unavailable, renamed: "Iterator") public typealias Generator = Iterator @available(*, unavailable, renamed: "makeIterator") public func generate() -> Iterator { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "Removed in Swift 3. Please use underestimatedCount property.") public func underestimateCount() -> Int { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "Please use split(maxSplits:omittingEmptySubsequences:isSeparator:) instead") public func split( _ maxSplit: Int = Int.max, allowEmptySlices: Bool = false, isSeparator: @noescape (Iterator.Element) throws -> Bool ) rethrows -> [SubSequence] { fatalError("unavailable function can't be called") } } extension Collection where Iterator.Element : Equatable { @available(*, unavailable, message: "Please use split(separator:maxSplits:omittingEmptySubsequences:) instead") public func split( _ separator: Iterator.Element, maxSplit: Int = Int.max, allowEmptySlices: Bool = false ) -> [SubSequence] { fatalError("unavailable function can't be called") } } @available(*, unavailable, renamed: "MutableCollection") public typealias MutableCollectionType = MutableCollection @available(*, unavailable, message: "PermutationGenerator has been removed in Swift 3") public struct PermutationGenerator<C : Collection, Indices : Sequence> {} @available(*, unavailable, message: "Please use 'Collection where SubSequence : MutableCollection'") public typealias MutableSliceable = Collection
apache-2.0
327a48e52f1cc069405a35081d893f54
32.100637
115
0.665448
4.34007
false
false
false
false
nagyistoce/SwiftHN
SwiftHN/Views/BorderedButton.swift
1
3422
// // BorderedButton.swift // SwiftHN // // Created by Thomas Ricouard on 06/06/14. // Copyright (c) 2014 Thomas Ricouard. All rights reserved. // import UIKit import SwiftHNShared @IBDesignable class BorderedButton: UIView { typealias buttonTouchInsideEvent = (sender: UIButton) -> () // MARK: Internals views var button : UIButton = UIButton(frame: CGRectZero) let animationDuration = 0.15 // MARK: Callback var onButtonTouch: buttonTouchInsideEvent! // MARK: IBSpec @IBInspectable var borderColor: UIColor = UIColor.HNColor() { didSet { self.layer.borderColor = borderColor.CGColor } } @IBInspectable var borderWidth: CGFloat = 0.5 { didSet { self.layer.borderWidth = borderWidth } } @IBInspectable var borderCornerRadius: CGFloat = 5.0 { didSet { self.layer.cornerRadius = borderCornerRadius } } @IBInspectable var labelColor: UIColor = UIColor.HNColor() { didSet { self.button.setTitleColor(labelColor, forState: .Normal) } } @IBInspectable var labelText: String = "Default" { didSet { self.button.setTitle(labelText, forState: .Normal) } } @IBInspectable var labelFontSize: CGFloat = 11.0 { didSet { self.button.titleLabel?.font = UIFont.systemFontOfSize(labelFontSize) } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } override init(frame: CGRect) { super.init(frame: frame) self.setup() } func setup() { self.userInteractionEnabled = true self.button.addTarget(self, action: "onPress:", forControlEvents: .TouchDown) self.button.addTarget(self, action: "onRealPress:", forControlEvents: .TouchUpInside) self.button.addTarget(self, action: "onReset:", forControlEvents: .TouchUpInside) self.button.addTarget(self, action: "onReset:", forControlEvents: .TouchUpOutside) self.button.addTarget(self, action: "onReset:", forControlEvents: .TouchDragExit) self.button.addTarget(self, action: "onReset:", forControlEvents: .TouchCancel) } // MARK: views setup override func layoutSubviews() { super.layoutSubviews() self.borderColor = UIColor.HNColor() self.labelColor = UIColor.HNColor() self.borderWidth = 0.5 self.borderCornerRadius = 5.0 self.labelFontSize = 11.0 self.button.frame = self.bounds self.button.titleLabel?.textAlignment = .Center self.button.backgroundColor = UIColor.clearColor() self.addSubview(self.button) } // MARK: Actions func onPress(sender: AnyObject) { UIView.animateWithDuration(self.animationDuration, animations: { self.labelColor = UIColor.whiteColor() self.backgroundColor = UIColor.HNColor() }) } func onReset(sender: AnyObject) { UIView.animateWithDuration(self.animationDuration, animations: { self.labelColor = UIColor.HNColor() self.backgroundColor = UIColor.clearColor() }) } func onRealPress(sender: AnyObject) { self.onButtonTouch(sender: sender as UIButton) } }
gpl-2.0
6b2953c77cd2fe8df449533f311ed7fe
28.5
93
0.618936
4.707015
false
false
false
false
ivanbruel/Moya-ObjectMapper
Sample/Demo/DemoViewModel.swift
1
1796
// // DemoViewModel.swift // Demo // // Created by Bruno Oliveira on 17/01/2019. // Copyright © 2019 Ash Furrow. All rights reserved. // import Foundation import Moya import Moya_ObjectMapper class DemoViewModel { let networking: MoyaProvider<GitHub> var repositoriesResponse: ((Bool, String, [Repository]?) -> Void)? = nil var zenResponse: ((Bool, String) -> Void)? = nil init(networking: MoyaProvider<GitHub>) { self.networking = networking } func downloadRepositories(_ username: String) { networking.request(.userRepositories(username), completion: { [weak self] result in var success = true var message = "Unable to fetch from GitHub" var repositores: [Repository]? = nil switch result { case let .success(response): do { let repos: [Repository]? = try response.mapArray(Repository.self) if let repos = repos { // Presumably, you'd parse the JSON into a model object. This is just a demo, so we'll keep it as-is. repositores = repos } else { success = false } } catch { success = false } case let .failure(error): guard let description = error.errorDescription else { break } message = description success = false } self?.repositoriesResponse?(success, message, repositores) }) } func downloadZen() { networking.request(.zen, completion: { [weak self] result in var success = true var message = "Couldn't access API" if case let .success(response) = result { message = (try? response.mapString()) ?? message } else { success = false } self?.zenResponse?(success, message) }) } }
mit
6c83f20696a143cdd41588ff0e4c6b10
27.046875
113
0.605571
4.388753
false
false
false
false
dduan/swift
test/SILGen/objc_dictionary_bridging.swift
1
5018
// RUN: rm -rf %t && mkdir -p %t // RUN: %build-silgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-silgen %s | FileCheck %s // REQUIRES: objc_interop import Foundation import gizmo @objc class Foo : NSObject { // Bridging dictionary parameters // CHECK-LABEL: sil hidden [thunk] @_TToFC24objc_dictionary_bridging3Foo23bridge_Dictionary_param{{.*}} : $@convention(objc_method) (NSDictionary, Foo) -> () func bridge_Dictionary_param(dict: Dictionary<Foo, Foo>) { // CHECK: bb0([[NSDICT:%[0-9]+]] : $NSDictionary, [[SELF:%[0-9]+]] : $Foo): // CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_TZFE10FoundationVs10Dictionary36_unconditionallyBridgeFromObjectiveCfGSqCSo12NSDictionary_GS0_xq__ // CHECK-NEXT: [[OPT_NSDICT:%[0-9]+]] = enum $Optional<NSDictionary>, #Optional.some!enumelt.1, [[NSDICT]] : $NSDictionary // CHECK-NEXT: [[DICT_META:%[0-9]+]] = metatype $@thin Dictionary<Foo, Foo>.Type // CHECK-NEXT: [[DICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[OPT_NSDICT]], [[DICT_META]]) // CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_TFC24objc_dictionary_bridging3Foo23bridge_Dictionary_param // CHECK: [[RESULT:%[0-9]+]] = apply [[SWIFT_FN]]([[DICT]], [[SELF]]) : $@convention(method) (@owned Dictionary<Foo, Foo>, @guaranteed Foo) -> () // CHECK: return [[RESULT]] : $() } // Bridging dictionary results // CHECK-LABEL: sil hidden [thunk] @_TToFC24objc_dictionary_bridging3Foo24bridge_Dictionary_result{{.*}} : $@convention(objc_method) (Foo) -> @autoreleased NSDictionary func bridge_Dictionary_result() -> Dictionary<Foo, Foo> { // CHECK: bb0([[SELF:%[0-9]+]] : $Foo): // CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_TFC24objc_dictionary_bridging3Foo24bridge_Dictionary_result{{.*}} : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo> // CHECK-NEXT: [[DICT:%[0-9]+]] = apply [[SWIFT_FN]]([[SELF]]) : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo> // CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_TFE10FoundationVs10Dictionary19_bridgeToObjectiveCfT_CSo12NSDictionary // CHECK-NEXT: [[NSDICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[DICT]]) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary // CHECK-NEXT: release_value [[DICT]] // CHECK-NEXT: return [[NSDICT]] : $NSDictionary } var property: Dictionary<Foo, Foo> = [:] // Property getter // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC24objc_dictionary_bridging3Foog8propertyGVs10DictionaryS0_S0__ : $@convention(objc_method) (Foo) -> @autoreleased NSDictionary // CHECK: bb0([[SELF:%[0-9]+]] : $Foo): // CHECK: [[GETTER:%[0-9]+]] = function_ref @_TFC24objc_dictionary_bridging3Foog8propertyGVs10DictionaryS0_S0__ : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo> // CHECK: [[DICT:%[0-9]+]] = apply [[GETTER]]([[SELF]]) : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo> // CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_TFE10FoundationVs10Dictionary19_bridgeToObjectiveCfT_CSo12NSDictionary // CHECK: [[NSDICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[DICT]]) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary // CHECK: release_value [[DICT]] // CHECK: return [[NSDICT]] : $NSDictionary // Property setter // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC24objc_dictionary_bridging3Foos8propertyGVs10DictionaryS0_S0__ : $@convention(objc_method) (NSDictionary, Foo) -> () // CHECK: bb0([[NSDICT:%[0-9]+]] : $NSDictionary, [[SELF:%[0-9]+]] : $Foo): // CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_TZFE10FoundationVs10Dictionary36_unconditionallyBridgeFromObjectiveCfGSqCSo12NSDictionary_GS0_xq__ // CHECK: [[OPT_NSDICT:%[0-9]+]] = enum $Optional<NSDictionary>, #Optional.some!enumelt.1, [[NSDICT]] : $NSDictionary // CHECK: [[DICT_META:%[0-9]+]] = metatype $@thin Dictionary<Foo, Foo>.Type // CHECK: [[DICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[OPT_NSDICT]], [[DICT_META]]) // CHECK: [[SETTER:%[0-9]+]] = function_ref @_TFC24objc_dictionary_bridging3Foos8propertyGVs10DictionaryS0_S0__ : $@convention(method) (@owned Dictionary<Foo, Foo>, @guaranteed Foo) -> () // CHECK: [[RESULT:%[0-9]+]] = apply [[SETTER]]([[DICT]], [[SELF]]) : $@convention(method) (@owned Dictionary<Foo, Foo>, @guaranteed Foo) -> () // CHECK: return [[RESULT]] : $() // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC24objc_dictionary_bridging3Foog19nonVerbatimProperty{{.*}} : $@convention(objc_method) (Foo) -> @autoreleased NSDictionary // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC24objc_dictionary_bridging3Foos19nonVerbatimProperty{{.*}} : $@convention(objc_method) (NSDictionary, Foo) -> () @objc var nonVerbatimProperty: Dictionary<String, Int> = [:] } func ==(x: Foo, y: Foo) -> Bool { }
apache-2.0
957d1a0225fd75e5203d994c53add639
70.542857
204
0.655551
3.441924
false
false
false
false
systers/PowerUp
Powerup/OOC-Event-Classes/PopupEventPlayer.swift
2
13646
import UIKit /** Handles the entire popup lifecycle. Owns all popup views, media, and interactions. Example retrieving a model from the Popups dataset: ``` // get the correct model let scenarioID = 5 let popupID = 1 guard let model: PopupEvent = PopupEvents().getPopup(type: .scenario, collection: String(scenarioID), popupID: popupID ) else { print("Could not retrieve outro story sequence for scenario \(scenarioID) with popupID \(popupID).") return } let event: PopupEventPlayer? = PopupEventPlayer(delegate: self, model: model) guard let popup = event else { return } popup.id = popupID self.view.addSubview(popup) ``` Or use anywhere with a locally created model: ``` func addPopup() { let model = PopupEvent(topText: "Made with ♥", botText: "by Systers Open Source", imgName: nil, slideSound: nil, badgeSound: nil) let popup: PopupEventPlayer = PopupEventPlayer(model) self.view.addSubview(popup) } ``` Delegate methods: (optional) ``` func popupDidShow(sender: PopupEventPlayer) func popupDidHide(sender: PopupEventPlayer) func popupWasTapped(sender: PopupEventPlayer) ``` - Author: Cadence Holmes 2018 */ class PopupEventPlayer: UIView { /* ******************************* MARK: Properties ******************************* */ weak var delegate: PopupEventPlayerDelegate? var id: Int? let angleSize: CGFloat = 0.1, slideAnimDuration: Double = 0.5, popupDuration: Double = 5.0, fontName: String = "Montserrat-Bold" var width: CGFloat, height: CGFloat var bgColor: UIColor // { didSet { updateContainer() } } var borderColor: UIColor // { didSet { updateContainer() } } var textColor: UIColor // { didSet { updateLabels() } } var mainText: String? // { didSet { updateMainLabel() } } var subText: String? // { didSet { updateSubLabel() } } var image: UIImage? // { didSet { updateImageView() } } var container: UIView, mainLabel: UILabel, subLabel: UILabel, imageView: UIImageView var soundPlayer: SoundPlayer? = SoundPlayer() var slideSound: String? var badgeSound: String? let defaultSounds = (slideIn: "placeholder", showImage: "placeholder2") private var tapped: Bool enum AccessibilityIdentifiers: String { case popupEventPlayer = "popup-event-player" } /* ******************************* MARK: Initializers ******************************* */ required init(coder aDecoder: NSCoder) { fatalError("This class does not support NSCoding") } override init(frame: CGRect) { // initialize non-optional properties self.width = UIScreen.main.bounds.width * 0.8 self.height = UIScreen.main.bounds.height * 0.25 self.bgColor = UIColor.init(red: 129 / 255.0, green: 236 / 255.0, blue: 236 / 255.0, alpha: 1.0) self.borderColor = UIColor.black self.textColor = UIColor.black self.container = UIView(frame: CGRect.zero) self.mainLabel = UILabel(frame: CGRect.zero) self.subLabel = UILabel(frame: CGRect.zero) self.imageView = UIImageView(frame: CGRect.zero) self.tapped = false super.init(frame: frame) self.accessibilityIdentifier = AccessibilityIdentifiers.popupEventPlayer.rawValue // setup subviews setupSubviews() updateContainer() // add a tap gesture to manually dismiss the popup let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapView(sender:))) self.container.addGestureRecognizer(tap) // add subviews container.addSubview(mainLabel) container.addSubview(subLabel) container.addSubview(imageView) self.addSubview(self.container) } convenience init(delegate: PopupEventPlayerDelegate?, model: PopupEvent?) { self.init(frame: CGRect.zero) self.delegate = delegate guard let m = model else { return } if m.topText != nil { mainText = m.topText updateMainLabel() } if m.botText != nil { subText = m.botText updateSubLabel() } if m.imgName != nil { image = UIImage(named: m.imgName!) updateImageView() } if m.slideSound != nil { slideSound = m.slideSound! } if m.badgeSound != nil { badgeSound = m.badgeSound! } } convenience init(_ model: PopupEvent) { self.init(delegate: nil, model: model) } @objc func tapView(sender: UITapGestureRecognizer) { self.delegate?.popupWasTapped(sender: self) hide() } // setup view for debugging and animate view automatically when view is added to a superview override func didMoveToSuperview() { show() } /* ******************************* MARK: Setup and Setters ******************************* */ /** Size and layout subviews. */ private func setupSubviews() { container.frame = CGRect(x: UIScreen.main.bounds.width, y: 10, width: width, height: height) // compute label frames let angleOffset = width * angleSize let constrainW = container.bounds.width - angleOffset // set label contraints let constrainH = container.bounds.height let labelWidth = constrainW * 0.9 // shared label width let labelHeight = constrainH * 0.9 // combined label height let mainLabelHeight = labelHeight * 0.65 let subLabelHeight = labelHeight - mainLabelHeight let offsetY = (constrainH - labelHeight) / 2 // set margins let offsetX = ((constrainW - labelWidth) / 2) + angleOffset mainLabel.frame = CGRect(x: offsetX, y: offsetY, width: labelWidth, height: mainLabelHeight) subLabel.frame = CGRect(x: offsetX, y: offsetY + mainLabelHeight, width: labelWidth, height: subLabelHeight) mainLabel.font = UIFont(name: fontName, size: 30) subLabel.font = UIFont(name: fontName, size: 15) mainLabel.textAlignment = .center subLabel.textAlignment = .center mainLabel.adjustsFontSizeToFitWidth = true subLabel.adjustsFontSizeToFitWidth = true mainLabel.layer.opacity = 0 subLabel.layer.opacity = 0 let size = constrainH * 0.9 let degrees = -90.0 let radians = CGFloat(degrees * Double.pi / 180) let rotateTransform = CATransform3DMakeRotation(radians, 0, 0, 1) let shrink = CGFloat(0.1) imageView.frame = CGRect(x: -(size / 5), y: size / 4, width: size, height: size) imageView.layer.transform = CATransform3DScale(rotateTransform, shrink, shrink, shrink) imageView.layer.opacity = 0 imageView.contentMode = .scaleAspectFit } /** Animate text labels upwards. - Parameter label: `UILabel` to be animated. - Remark: References `slideAnimateDuration`. - Note: See `Animate`. */ private func animateLabelText (_ label: UILabel) { Animate(label, slideAnimDuration * 2).fade(to: 1) } // setters to ensure views are updated if content changed after initialization /** Updates the main and sub labels. Calls `updateMainLabel()` and `updateSubLabel()`. */ func updateLabels() { updateMainLabel() updateSubLabel() } /** Updates the main label. References relevant class properties and updates the upper text label *with* fade-in animations. */ func updateMainLabel() { mainLabel.textColor = textColor guard let text = mainText else { return } mainLabel.text = text animateLabelText(mainLabel) } /** Updates the sub label. References relevant class properties and updates the lower text label *with* fade-in animations. */ func updateSubLabel() { subLabel.textColor = textColor guard let text = subText else { return } subLabel.text = text animateLabelText(subLabel) } /** Updates the image view. References relevant class properties and updates the image view *without* animations. Animations are handled when the class is implemented and added to a superview. */ func updateImageView() { guard let image = image else { return } imageView.image = image } /** Draws the inner container layer (angle and shadow). Also updates `self.frame` to conform to the inner containers bounds. */ func updateContainer() { let layer: CAShapeLayer = drawAngledShape() container.layer.addSublayer(layer) self.frame = container.bounds } // draw an angle on the left border, add shadow : called in updatedContainer() /** Draws the layer for the popup view, including the angled edge. - Returns: `CAShapeLayer` for the `PopupEventPlayer` view. */ private func drawAngledShape() -> CAShapeLayer { let borderWidth: CGFloat = 1.5 let bounds = container.bounds let layer = CAShapeLayer() let path = UIBezierPath() path.move(to: CGPoint(x: 0, y: 0)) path.addLine(to: CGPoint(x: bounds.width, y: 0)) path.addLine(to: CGPoint(x: bounds.width, y: bounds.height)) path.addLine(to: CGPoint(x: bounds.width * angleSize, y: bounds.height)) path.close() layer.path = path.cgPath layer.fillColor = bgColor.cgColor layer.strokeColor = borderColor.cgColor layer.lineWidth = borderWidth layer.shadowPath = layer.path layer.shadowColor = UIColor.black.cgColor layer.shadowOpacity = 1 layer.shadowOffset = CGSize.zero layer.shadowRadius = 10 return layer } /* ******************************* MARK: Public Class Methods ******************************* */ /** Animates showing the popup. Automatically called when an instance of PopupEventPlayer is added to a superview. See `didMoveToSuperview()`. Handles animations asyncronously on a background thread, checks for and plays sound, and times the popup for automatic dismissal. */ func show() { self.delegate?.popupDidShow(sender: self) let volume: Float = 0.2 let x = UIScreen.main.bounds.width - width animateSlideTo(x: x) playSound(fileName: slideSound, volume: volume) DispatchQueue.global(qos: .background).async { DispatchQueue.main.asyncAfter(deadline: .now() + self.popupDuration) { self.hide() } } } // hide() is automatically called after show() + self.popupDuration /** Animates hiding the popup. Automatically called after `show()` + `popupDuration`, or when the popup is tapped. Handles animations asyncronously on a background thread, calls delegate method `popupDidFinish(sender:)`. */ func hide() { if !tapped { tapped = true let x = UIScreen.main.bounds.width * 2 animateSlideTo(x: x) DispatchQueue.global(qos: .background).async { DispatchQueue.main.asyncAfter(deadline: .now() + self.slideAnimDuration) { self.delegate?.popupDidHide(sender: self) self.removeFromSuperview() } } } } /* ******************************* MARK: Private Class Methods ******************************* */ /** Animate sliding the popup into view. - Parameter x: The distance to slide the popup. */ private func animateSlideTo(x: CGFloat) { Animate(container, slideAnimDuration).move(to: [x, container.frame.origin.y], then: { if self.image != nil { self.animateShowImageWithSound() } }) } /** Animate showing the badge image and call `playSound()`. */ private func animateShowImageWithSound() { let duration: Double = 0.2 let volume: Float = 0.1 Animate(imageView, duration).setSpring(0.3, 12).reset().fade(to: 1) playSound(fileName: badgeSound, volume: volume) } /** Play a sound file once. - Parameter fileName: The name of the audio asset to be played. - Parameter volume: The volume at which the sound is played. */ private func playSound (fileName: String?, volume: Float?) { if fileName != nil && !tapped { guard let sound = fileName else { return } guard let player = self.soundPlayer else { return } let vol = (volume != nil) ? volume : 1 player.playSound(sound, vol!) } } } /* ******************************* MARK: Delegate Methods ******************************* */ protocol PopupEventPlayerDelegate: AnyObject { /** Called when `PopupEventPlayer` is successfully initialized and the view is added to the view hierarchy. */ func popupDidShow(sender: PopupEventPlayer) /** Called when `PopupEventPlayer` is dismissed, whether by tapping or waiting for the duration. */ func popupDidHide(sender: PopupEventPlayer) /** Called when `PopupEventPlayer` is tapped to hide. */ func popupWasTapped(sender: PopupEventPlayer) }
gpl-2.0
49323cb2abc87008f8c38240103b1ba9
31.255319
169
0.602756
4.68544
false
false
false
false
harrycheung/Mobile-App-Performance
SwiftApp/SwiftApp/SwiftyJSON.swift
2
35412
// SwiftyJSON.swift // // Copyright (c) 2014 Ruoyu Fu, Pinglin Tang // // 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 // MARK: - Error ///Error domain public let ErrorDomain: String! = "SwiftyJSONErrorDomain" ///Error code public let ErrorUnsupportedType: Int! = 999 public let ErrorIndexOutOfBounds: Int! = 900 public let ErrorWrongType: Int! = 901 public let ErrorNotExist: Int! = 500 // MARK: - JSON Type /** JSON's type definitions. See http://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Type :Int{ case Number case String case Bool case Array case Dictionary case Null case Unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. :param: data The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary :param: opt The JSON serialization reading options. `.AllowFragments` by default. :param: error error The NSErrorPointer used to return the error. `nil` by default. :returns: The created JSON */ public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) { if let object: AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: opt, error: error) { self.init(object) } else { self.init(NSNull()) } } /** Creates a JSON using the object. :param: object The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. :returns: The created JSON */ public init(_ object: AnyObject) { self.object = object } /// Private object private var _object: AnyObject = NSNull() /// Private type private var _type: Type = .Null /// prviate error private var _error: NSError? /// Object in JSON public var object: AnyObject { get { return _object } set { _object = newValue switch newValue { case let number as NSNumber: if number.isBool { _type = .Bool } else { _type = .Number } case let string as NSString: _type = .String case let null as NSNull: _type = .Null case let array as [AnyObject]: _type = .Array case let dictionary as [String : AnyObject]: _type = .Dictionary default: _type = .Unknown _object = NSNull() _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) } } } /// json type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } /// The static null json public static var nullJSON: JSON { get { return JSON(NSNull()) } } } // MARK: - SequenceType extension JSON: SequenceType{ /// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `false`. public var isEmpty: Bool { get { switch self.type { case .Array: return (self.object as! [AnyObject]).isEmpty case .Dictionary: return (self.object as! [String : AnyObject]).isEmpty default: return false } } } /// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`. public var count: Int { get { switch self.type { case .Array: return self.arrayValue.count case .Dictionary: return self.dictionaryValue.count default: return 0 } } } /** If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty. :returns: Return a *generator* over the elements of this *sequence*. */ public func generate() -> GeneratorOf <(String, JSON)> { switch self.type { case .Array: let array_ = object as! [AnyObject] var generate_ = array_.generate() var index_: Int = 0 return GeneratorOf<(String, JSON)> { if let element_: AnyObject = generate_.next() { return ("\(index_++)", JSON(element_)) } else { return nil } } case .Dictionary: let dictionary_ = object as! [String : AnyObject] var generate_ = dictionary_.generate() return GeneratorOf<(String, JSON)> { if let (key_: String, value_: AnyObject) = generate_.next() { return (key_, JSON(value_)) } else { return nil } } default: return GeneratorOf<(String, JSON)> { return nil } } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public protocol SubscriptType {} extension Int: SubscriptType {} extension String: SubscriptType {} extension JSON { /// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error. private subscript(#index: Int) -> JSON { get { if self.type != .Array { var errorResult_ = JSON.nullJSON errorResult_._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) return errorResult_ } let array_ = self.object as! [AnyObject] if index >= 0 && index < array_.count { return JSON(array_[index]) } var errorResult_ = JSON.nullJSON errorResult_._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) return errorResult_ } set { if self.type == .Array { var array_ = self.object as! [AnyObject] if array_.count > index { array_[index] = newValue.object self.object = array_ } } } } /// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error. private subscript(#key: String) -> JSON { get { var returnJSON = JSON.nullJSON if self.type == .Dictionary { if let object_: AnyObject = self.object[key] { returnJSON = JSON(object_) } else { returnJSON._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) } } else { returnJSON._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) } return returnJSON } set { if self.type == .Dictionary { var dictionary_ = self.object as! [String : AnyObject] dictionary_[key] = newValue.object self.object = dictionary_ } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. private subscript(#sub: SubscriptType) -> JSON { get { if sub is String { return self[key:sub as! String] } else { return self[index:sub as! Int] } } set { if sub is String { self[key:sub as! String] = newValue } else { self[index:sub as! Int] = newValue } } } /** Find a json in the complex data structuresby using the Int/String's array. :param: path The target json's path. Example: let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] The same as: let name = json[9]["list"]["person"]["name"] :returns: Return a json found by the path or a null json with error */ public subscript(path: [SubscriptType]) -> JSON { get { if path.count == 0 { return JSON.nullJSON } var next = self for sub in path { next = next[sub:sub] } return next } set { switch path.count { case 0: return case 1: self[sub:path[0]] = newValue default: var last = newValue var newPath = path newPath.removeLast() for sub in path.reverse() { var previousLast = self[newPath] previousLast[sub:sub] = last last = previousLast if newPath.count <= 1 { break } newPath.removeLast() } self[sub:newPath[0]] = last } } } /** Find a json in the complex data structuresby using the Int/String's array. :param: path The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] :returns: Return a json found by the path or a null json with error */ public subscript(path: SubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: StringLiteralConvertible { public init(stringLiteral value: StringLiteralType) { self.init(value) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value) } } extension JSON: IntegerLiteralConvertible { public init(integerLiteral value: IntegerLiteralType) { self.init(value) } } extension JSON: BooleanLiteralConvertible { public init(booleanLiteral value: BooleanLiteralType) { self.init(value) } } extension JSON: FloatLiteralConvertible { public init(floatLiteral value: FloatLiteralType) { self.init(value) } } extension JSON: DictionaryLiteralConvertible { public init(dictionaryLiteral elements: (String, AnyObject)...) { var dictionary_ = [String : AnyObject]() for (key_, value) in elements { dictionary_[key_] = value } self.init(dictionary_) } } extension JSON: ArrayLiteralConvertible { public init(arrayLiteral elements: AnyObject...) { self.init(elements) } } extension JSON: NilLiteralConvertible { public init(nilLiteral: ()) { self.init(NSNull()) } } // MARK: - Raw extension JSON: RawRepresentable { public init?(rawValue: AnyObject) { if JSON(rawValue).type == .Unknown { return nil } else { self.init(rawValue) } } public var rawValue: AnyObject { return self.object } public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(0), error: NSErrorPointer = nil) -> NSData? { return NSJSONSerialization.dataWithJSONObject(self.object, options: opt, error:error) } public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? { switch self.type { case .Array, .Dictionary: if let data = self.rawData(options: opt) { return (NSString(data: data, encoding: encoding) as! String) } else { return nil } case .String: return (self.object as! String) case .Number: return (self.object as! NSNumber).stringValue case .Bool: return (self.object as! Bool).description case .Null: return "null" default: return nil } } } // MARK: - Printable, DebugPrintable extension JSON: Printable, DebugPrintable { public var description: String { if let string = self.rawString(options:.PrettyPrinted) { return string } else { return "unknown" } } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { get { if self.type == .Array { return map(self.object as! [AnyObject]){ JSON($0) } } else { return nil } } } //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } //Optional [AnyObject] public var arrayObject: [AnyObject]? { get { switch self.type { case .Array: return self.object as? [AnyObject] default: return nil } } set { if newValue != nil { self.object = NSMutableArray(array: newValue!, copyItems: true) } else { self.object = NSNull() } } } } // MARK: - Dictionary extension JSON { private func _map<Key:Hashable ,Value, NewValue>(source: [Key: Value], transform: Value -> NewValue) -> [Key: NewValue] { var result = [Key: NewValue](minimumCapacity:source.count) for (key,value) in source { result[key] = transform(value) } return result } //Optional [String : JSON] public var dictionary: [String : JSON]? { get { if self.type == .Dictionary { return _map(self.object as! [String : AnyObject]){ JSON($0) } } else { return nil } } } //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { get { return self.dictionary ?? [:] } } //Optional [String : AnyObject] public var dictionaryObject: [String : AnyObject]? { get { switch self.type { case .Dictionary: return self.object as? [String : AnyObject] default: return nil } } set { if newValue != nil { self.object = NSMutableDictionary(dictionary: newValue!, copyItems: true) } else { self.object = NSNull() } } } } // MARK: - Bool extension JSON: BooleanType { //Optional bool public var bool: Bool? { get { switch self.type { case .Bool: return self.object.boolValue default: return nil } } set { if newValue != nil { self.object = NSNumber(bool: newValue!) } else { self.object = NSNull() } } } //Non-optional bool public var boolValue: Bool { get { switch self.type { case .Bool, .Number, .String: return self.object.boolValue default: return false } } set { self.object = NSNumber(bool: newValue) } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch self.type { case .String: return self.object as? String default: return nil } } set { if newValue != nil { self.object = NSString(string:newValue!) } else { self.object = NSNull() } } } //Non-optional string public var stringValue: String { get { switch self.type { case .String: return self.object as! String case .Number: return self.object.stringValue case .Bool: return (self.object as! Bool).description default: return "" } } set { self.object = NSString(string:newValue) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch self.type { case .Number, .Bool: return self.object as? NSNumber default: return nil } } set { self.object = newValue?.copy() ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .String: let scanner = NSScanner(string: self.object as! String) if scanner.scanDouble(nil){ if (scanner.atEnd) { return NSNumber(double:(self.object as! NSString).doubleValue) } } return NSNumber(double: 0.0) case .Number, .Bool: return self.object as! NSNumber default: return NSNumber(double: 0.0) } } set { self.object = newValue.copy() } } } //MARK: - Null extension JSON { public var null: NSNull? { get { switch self.type { case .Null: return NSNull() default: return nil } } set { self.object = NSNull() } } } //MARK: - URL extension JSON { //Optional URL public var URL: NSURL? { get { switch self.type { case .String: if let encodedString_ = self.object.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) { return NSURL(string: encodedString_) } else { return nil } default: return nil } } set { self.object = newValue?.absoluteString ?? NSNull() } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return self.number?.doubleValue } set { if newValue != nil { self.object = NSNumber(double: newValue!) } else { self.object = NSNull() } } } public var doubleValue: Double { get { return self.numberValue.doubleValue } set { self.object = NSNumber(double: newValue) } } public var float: Float? { get { return self.number?.floatValue } set { if newValue != nil { self.object = NSNumber(float: newValue!) } else { self.object = NSNull() } } } public var floatValue: Float { get { return self.numberValue.floatValue } set { self.object = NSNumber(float: newValue) } } public var int: Int? { get { return self.number?.longValue } set { if newValue != nil { self.object = NSNumber(integer: newValue!) } else { self.object = NSNull() } } } public var intValue: Int { get { return self.numberValue.integerValue } set { self.object = NSNumber(integer: newValue) } } public var uInt: UInt? { get { return self.number?.unsignedLongValue } set { if newValue != nil { self.object = NSNumber(unsignedLong: newValue!) } else { self.object = NSNull() } } } public var uIntValue: UInt { get { return self.numberValue.unsignedLongValue } set { self.object = NSNumber(unsignedLong: newValue) } } public var int8: Int8? { get { return self.number?.charValue } set { if newValue != nil { self.object = NSNumber(char: newValue!) } else { self.object = NSNull() } } } public var int8Value: Int8 { get { return self.numberValue.charValue } set { self.object = NSNumber(char: newValue) } } public var uInt8: UInt8? { get { return self.number?.unsignedCharValue } set { if newValue != nil { self.object = NSNumber(unsignedChar: newValue!) } else { self.object = NSNull() } } } public var uInt8Value: UInt8 { get { return self.numberValue.unsignedCharValue } set { self.object = NSNumber(unsignedChar: newValue) } } public var int16: Int16? { get { return self.number?.shortValue } set { if newValue != nil { self.object = NSNumber(short: newValue!) } else { self.object = NSNull() } } } public var int16Value: Int16 { get { return self.numberValue.shortValue } set { self.object = NSNumber(short: newValue) } } public var uInt16: UInt16? { get { return self.number?.unsignedShortValue } set { if newValue != nil { self.object = NSNumber(unsignedShort: newValue!) } else { self.object = NSNull() } } } public var uInt16Value: UInt16 { get { return self.numberValue.unsignedShortValue } set { self.object = NSNumber(unsignedShort: newValue) } } public var int32: Int32? { get { return self.number?.intValue } set { if newValue != nil { self.object = NSNumber(int: newValue!) } else { self.object = NSNull() } } } public var int32Value: Int32 { get { return self.numberValue.intValue } set { self.object = NSNumber(int: newValue) } } public var uInt32: UInt32? { get { return self.number?.unsignedIntValue } set { if newValue != nil { self.object = NSNumber(unsignedInt: newValue!) } else { self.object = NSNull() } } } public var uInt32Value: UInt32 { get { return self.numberValue.unsignedIntValue } set { self.object = NSNumber(unsignedInt: newValue) } } public var int64: Int64? { get { return self.number?.longLongValue } set { if newValue != nil { self.object = NSNumber(longLong: newValue!) } else { self.object = NSNull() } } } public var int64Value: Int64 { get { return self.numberValue.longLongValue } set { self.object = NSNumber(longLong: newValue) } } public var uInt64: UInt64? { get { return self.number?.unsignedLongLongValue } set { if newValue != nil { self.object = NSNumber(unsignedLongLong: newValue!) } else { self.object = NSNull() } } } public var uInt64Value: UInt64 { get { return self.numberValue.unsignedLongLongValue } set { self.object = NSNumber(unsignedLongLong: newValue) } } } //MARK: - Comparable extension JSON: Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) == (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) == (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func <=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) <= (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) <= (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func >=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) >= (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) >= (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func >(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) > (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) > (rhs.object as! String) default: return false } } public func <(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) < (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) < (rhs.object as! String) default: return false } } private let trueNumber = NSNumber(bool: true) private let falseNumber = NSNumber(bool: false) private let trueObjCType = String.fromCString(trueNumber.objCType) private let falseObjCType = String.fromCString(falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber: Comparable { var isBool:Bool { get { let objCType = String.fromCString(self.objCType) if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){ return true } else { return false } } } } public func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedSame } } public func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } public func <(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedAscending } } public func >(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedDescending } } public func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedDescending } } public func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedAscending } } //MARK:- Unavailable @availability(*, unavailable, renamed="JSON") public typealias JSONValue = JSON extension JSON { @availability(*, unavailable, message="use 'init(_ object:AnyObject)' instead") public init(object: AnyObject) { self = JSON(object) } @availability(*, unavailable, renamed="dictionaryObject") public var dictionaryObjects: [String : AnyObject]? { get { return self.dictionaryObject } } @availability(*, unavailable, renamed="arrayObject") public var arrayObjects: [AnyObject]? { get { return self.arrayObject } } @availability(*, unavailable, renamed="int8") public var char: Int8? { get { return self.number?.charValue } } @availability(*, unavailable, renamed="int8Value") public var charValue: Int8 { get { return self.numberValue.charValue } } @availability(*, unavailable, renamed="uInt8") public var unsignedChar: UInt8? { get{ return self.number?.unsignedCharValue } } @availability(*, unavailable, renamed="uInt8Value") public var unsignedCharValue: UInt8 { get{ return self.numberValue.unsignedCharValue } } @availability(*, unavailable, renamed="int16") public var short: Int16? { get{ return self.number?.shortValue } } @availability(*, unavailable, renamed="int16Value") public var shortValue: Int16 { get{ return self.numberValue.shortValue } } @availability(*, unavailable, renamed="uInt16") public var unsignedShort: UInt16? { get{ return self.number?.unsignedShortValue } } @availability(*, unavailable, renamed="uInt16Value") public var unsignedShortValue: UInt16 { get{ return self.numberValue.unsignedShortValue } } @availability(*, unavailable, renamed="int") public var long: Int? { get{ return self.number?.longValue } } @availability(*, unavailable, renamed="intValue") public var longValue: Int { get{ return self.numberValue.longValue } } @availability(*, unavailable, renamed="uInt") public var unsignedLong: UInt? { get{ return self.number?.unsignedLongValue } } @availability(*, unavailable, renamed="uIntValue") public var unsignedLongValue: UInt { get{ return self.numberValue.unsignedLongValue } } @availability(*, unavailable, renamed="int64") public var longLong: Int64? { get{ return self.number?.longLongValue } } @availability(*, unavailable, renamed="int64Value") public var longLongValue: Int64 { get{ return self.numberValue.longLongValue } } @availability(*, unavailable, renamed="uInt64") public var unsignedLongLong: UInt64? { get{ return self.number?.unsignedLongLongValue } } @availability(*, unavailable, renamed="uInt64Value") public var unsignedLongLongValue: UInt64 { get{ return self.numberValue.unsignedLongLongValue } } @availability(*, unavailable, renamed="int") public var integer: Int? { get { return self.number?.integerValue } } @availability(*, unavailable, renamed="intValue") public var integerValue: Int { get { return self.numberValue.integerValue } } @availability(*, unavailable, renamed="uInt") public var unsignedInteger: Int? { get { return self.number?.unsignedIntegerValue } } @availability(*, unavailable, renamed="uIntValue") public var unsignedIntegerValue: Int { get { return self.numberValue.unsignedIntegerValue } } }
gpl-3.0
fbaf1dc5d5d0c132287789c7bf93e506
25.525843
259
0.527702
4.719712
false
false
false
false
aleffert/SnapKit
Source/Debugging.swift
1
6722
// // SnapKit // // Copyright (c) 2011-2015 SnapKit Team - https://github.com/SnapKit // // 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. #if os(iOS) import UIKit #else import AppKit #endif /** Used to allow adding a snp_label to a View for debugging purposes */ public extension View { public var snp_label: String? { get { return objc_getAssociatedObject(self, &labelKey) as? String } set { objc_setAssociatedObject(self, &labelKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_COPY_NONATOMIC)) } } } /** Used to allow adding a snp_label to a LayoutConstraint for debugging purposes */ public extension LayoutConstraint { public var snp_label: String? { get { return objc_getAssociatedObject(self, &labelKey) as? String } set { objc_setAssociatedObject(self, &labelKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_COPY_NONATOMIC)) } } override public var description: String { var description = "<" description += descriptionForObject(self) description += " \(descriptionForObject(self.firstItem))" if self.firstAttribute != .NotAnAttribute { description += ".\(self.firstAttribute.snp_description)" } description += " \(self.relation.snp_description)" if let secondItem: AnyObject = self.secondItem { description += " \(descriptionForObject(secondItem))" } if self.secondAttribute != .NotAnAttribute { description += ".\(self.secondAttribute.snp_description)" } if self.multiplier != 1.0 { description += " * \(self.multiplier)" } if self.secondAttribute == .NotAnAttribute { description += " \(self.constant)" } else { if self.constant > 0.0 { description += " + \(self.constant)" } else if self.constant < 0.0 { description += " - \(CGFloat.abs(self.constant))" } } if self.priority != 1000.0 { description += " ^\(self.priority)" } description += ">" return description } } private var labelKey = "" private func descriptionForObject(object: AnyObject) -> String { let pointerDescription = NSString(format: "%p", [object]) if let object = object as? View { return "<\(object.dynamicType.description()):\(object.snp_label ?? pointerDescription)>" } else if let object = object as? LayoutConstraint { let identifierString : String if let identifier = object.identifier { identifierString = "(\(identifier))" } else { identifierString = "" } let locationString : String if let location = (object.snp_constraint as? ConcreteConstraint)?.location { locationString = "@\(location.file.lastPathComponent):\(location.line)" } else { locationString = "" } return "<\(object.dynamicType.description()):\(object.snp_label ?? pointerDescription)\(identifierString)\(locationString)>" } return "<\(object.dynamicType.description()):\(pointerDescription)>" } private extension NSLayoutRelation { private var snp_description: String { switch self { case .Equal: return "==" case .GreaterThanOrEqual: return ">=" case .LessThanOrEqual: return "<=" } } } private extension NSLayoutAttribute { private var snp_description: String { #if os(iOS) switch self { case .NotAnAttribute: return "notAnAttribute" case .Top: return "top" case .Left: return "left" case .Bottom: return "bottom" case .Right: return "right" case .Leading: return "leading" case .Trailing: return "trailing" case .Width: return "width" case .Height: return "height" case .CenterX: return "centerX" case .CenterY: return "centerY" case .Baseline: return "baseline" case .FirstBaseline: return "firstBaseline" case .TopMargin: return "topMargin" case .LeftMargin: return "leftMargin" case .BottomMargin: return "bottomMargin" case .RightMargin: return "rightMargin" case .LeadingMargin: return "leadingMargin" case .TrailingMargin: return "trailingMargin" case .CenterXWithinMargins: return "centerXWithinMargins" case .CenterYWithinMargins: return "centerYWithinMargins" } #else switch self { case .NotAnAttribute: return "notAnAttribute" case .Top: return "top" case .Left: return "left" case .Bottom: return "bottom" case .Right: return "right" case .Leading: return "leading" case .Trailing: return "trailing" case .Width: return "width" case .Height: return "height" case .CenterX: return "centerX" case .CenterY: return "centerY" case .Baseline: return "baseline" } #endif } }
mit
78b5998a76c58825b7dbaccc5ad3d0c9
34.378947
132
0.576465
5.020164
false
false
false
false
Fidetro/SwiftFFDB
Sources/Update.swift
1
825
// // Update.swift // Swift-FFDB // // Created by Fidetro on 2018/5/30. // Copyright © 2018年 Fidetro. All rights reserved. // import Foundation public struct Update:STMT { let stmt: String public init(_ table:FFObject.Type) { self.init(table.tableName()) } public init(_ stmt: String?=nil) { if let stmt = stmt { self.stmt = "update" + " " + stmt + " " }else{ self.stmt = "update" + " " } } } // MARK: - Set extension Update { public func set(_ set:String) -> Set { return Set(stmt, format: set) } public func set(_ columns:[String]?=nil) -> Set { return Set.init(stmt, columns: columns) } }
apache-2.0
1df49a8e0032503a43d8af23a1995a2d
19.55
53
0.470803
3.859155
false
false
false
false
tonystone/geofeatures2
Sources/GeoFeatures/LineString.swift
1
7191
/// /// LineString.swift /// /// Copyright (c) 2016 Tony Stone /// /// 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. /// /// Created by Tony Stone on 2/14/2016. /// /// /// NOTE: This file was auto generated by gyb from file CoordinateCollectionTypes.swift.gyb using the following command. /// /// ~/gyb --line-directive '' -DSelf=LineString -o LineString.swift CoordinateCollectionTypes.swift.gyb /// /// Do NOT edit this file directly as it will be regenerated automatically when needed. /// import Swift /// /// A LineString is a Curve with linear interpolation between Coordinates. Each consecutive pair of /// Coordinates defines a Line segment. /// public struct LineString: Geometry, Curve { /// /// The `Precision` of this LineString /// public let precision: Precision /// /// The `CoordinateSystem` of this LineString /// public let coordinateSystem: CoordinateSystem /// /// Construct an empty `LineString`. /// public init() { self.init([], precision: defaultPrecision, coordinateSystem: defaultCoordinateSystem) } /// /// Construct an empty `LineString`. /// /// - parameters: /// - precision: The `Precision` model this `LineString` should use in calculations on it's coordinates. /// - coordinateSystem: The 'CoordinateSystem` this `LineString` should use in calculations on it's coordinates. /// public init(precision: Precision = defaultPrecision, coordinateSystem: CoordinateSystem = defaultCoordinateSystem) { self.init([], precision: precision, coordinateSystem: coordinateSystem) } /// /// Construct a LineString from another LineString (copy constructor) changing the precision and coordinateSystem. /// /// - parameters: /// - other: The LineString of the same type that you want to construct a new LineString from. /// - precision: Optionally change the `Precision` model this `LineString` should use in calculations on it's coordinates. /// - coordinateSystem: Optionally change the 'CoordinateSystem` this `LineString` should use in calculations on it's coordinates. /// public init(other: LineString, precision: Precision, coordinateSystem: CoordinateSystem) { self.init(other.coordinates, precision: precision, coordinateSystem: coordinateSystem) } /// /// Construct a LineString from any `CoordinateCollectionType` changing the precision and coordinateSystem. /// /// - parameters: /// - other: The `CoordinateCollectionType` that you want to construct a new LineString from. /// - precision: Optionally change the `Precision` model this `LineString` should use in calculations on it's coordinates. /// - coordinateSystem: Optionally change the 'CoordinateSystem` this `LineString` should use in calculations on it's coordinates. /// public init<T: CoordinateCollectionType>(converting other: T, precision: Precision, coordinateSystem: CoordinateSystem) { self.precision = precision self.coordinateSystem = coordinateSystem /// Add the elements to our backing storage self.replaceSubrange(0..<0, with: other) } /// /// Construct a `LineString` from an `Array` which holds `Coordinate` objects. /// /// LineString can be constructed from any Swift.Collection type as /// long as it has an Element type equal the Coordinate type specified in Element. /// /// - parameters: /// - elements: A\n `Array` of `Coordinate` coordinates. /// - precision: The `Precision` model this `LineString` should use in calculations on it's coordinates. /// - coordinateSystem: The 'CoordinateSystem` this `LineString` should use in calculations on it's coordinates. /// public init(_ coordinates: [Coordinate], precision: Precision = defaultPrecision, coordinateSystem: CoordinateSystem = defaultCoordinateSystem) { self.precision = precision self.coordinateSystem = coordinateSystem /// Add the elements to our backing storage self.replaceSubrange(0..<0, with: coordinates) } private var coordinates: [Coordinate] = [] } // MARK: - ExpressibleByArrayLiteral conformance extension LineString: ExpressibleByArrayLiteral { /// Creates an instance initialized with the given elements. public init(arrayLiteral elements: Coordinate...) { self.init(elements) } } // MARK: `CoordinateCollectionType` and `RangeReplaceableCollection` conformance extension LineString: CoordinateCollectionType, RangeReplaceableCollection { /// /// Returns the position immediately after `i`. /// /// - Precondition: `(startIndex..<endIndex).contains(i)` /// public func index(after i: Int) -> Int { return i+1 } /// /// Always zero, which is the index of the first element when non-empty. /// public var startIndex: Int { return 0 } /// /// A "past-the-end" element index; the successor of the last valid subscript argument. /// public var endIndex: Int { return self.coordinates.count } /// /// Accesses the element at the specified position. /// public subscript(index: Int) -> Coordinate { get { return coordinates[index] } set (newElement) { self.replaceSubrange(index..<(index + 1), with: [newElement]) } } /// /// Replaces the specified subrange of elements with the given collection. /// /// This method has the effect of removing the specified range of elements /// from the collection and inserting the new elements at the same location. /// The number of new elements need not match the number of elements being /// removed. /// public mutating func replaceSubrange<C, R>(_ subrange: R, with newElements: C) where C : Collection, R : RangeExpression, Coordinate == C.Element, Int == R.Bound { self.coordinates.replaceSubrange(subrange, with: newElements.map({ self.precision.convert($0) })) } } // MARK: CustomStringConvertible & CustomDebugStringConvertible Conformance extension LineString: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return "\(type(of: self))([\(self.map { String(describing: $0) }.joined(separator: ", "))])" } public var debugDescription: String { return self.description } } // MARK: Equatable Conformance extension LineString: Equatable { static public func == (lhs: LineString, rhs: LineString) -> Bool { return lhs.equals(rhs) } }
apache-2.0
d6a7238a6a4a41f58c2677187030eb68
35.688776
167
0.678487
4.826174
false
false
false
false
phatblat/realm-cocoa
Realm/ObjectServerTests/RealmServer.swift
1
30573
//////////////////////////////////////////////////////////////////////////// // // Copyright 2020 Realm 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 "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 Realm.Private import RealmSwift import XCTest #if os(macOS) extension URLSession { fileprivate func resultDataTask(with request: URLRequest, _ completionHandler: @escaping (Result<Data, Error>) -> Void) { URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue()).dataTask(with: request) { (data, response, error) in if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode >= 200 && httpResponse.statusCode < 300, let data = data { completionHandler(.success(data)) } else { completionHandler(.failure(error ?? URLError(.badServerResponse))) } }.resume() } // Synchronously perform a data task, returning the data from it fileprivate func resultDataTask(with request: URLRequest) -> Result<Data, Error> { var result: Result<Data, Error>! let group = DispatchGroup() group.enter() resultDataTask(with: request) { result = $0 group.leave() } guard case .success = group.wait(timeout: .now() + 10) else { return .failure(URLError(.cannotFindHost)) } return result } } private func bsonType(_ type: PropertyType) -> String { switch type { case .UUID: return "uuid" case .any: return "mixed" case .bool: return "bool" case .data: return "binData" case .date: return "date" case .decimal128: return "decimal" case .double: return "double" case .float: return "float" case .int: return "long" case .object: return "object" case .objectId: return "objectId" case .string: return "string" case .linkingObjects: return "linkingObjects" } } private extension Property { func stitchRule(_ schema: Schema) -> [String: Any] { let type: String if self.type == .object { type = bsonType(schema[objectClassName!]!.primaryKeyProperty!.type) } else { type = bsonType(self.type) } if isArray { return [ "bsonType": "array", "items": [ "bsonType": type ] ] } if isSet { return [ "bsonType": "array", "uniqueItems": true, "items": [ "bsonType": type ] ] } if isMap { return [ "bsonType": "object", "properties": [:], "additionalProperties": [ "bsonType": type ] ] } return [ "bsonType": type ] } } private extension ObjectSchema { func stitchRule(_ partitionKeyType: String, _ schema: Schema, id: String? = nil) -> [String: Any] { var stitchProperties: [String: Any] = [ "realm_id": [ "bsonType": "\(partitionKeyType)" ] ] var relationships: [String: Any] = [:] // First pass we only create the primary key property as we can't add // links until the targets of the links exist if id == nil { let pk = primaryKeyProperty! stitchProperties[pk.name] = pk.stitchRule(schema) } else { for property in properties { stitchProperties[property.name] = property.stitchRule(schema) if property.type == .object { relationships[property.name] = [ "ref": "#/relationship/mongodb1/test_data/\(property.objectClassName!)", "foreign_key": "_id", "is_list": property.isArray || property.isSet || property.isMap ] } } } return [ "_id": id as Any, "database": "test_data", "collection": "\(className)", "roles": [[ "name": "default", "apply_when": [:], "insert": true, "delete": true, "additional_fields": [:] ]], "schema": [ "properties": stitchProperties, // The server currently only supports non-optional collections // but requires them to be marked as optional "required": properties.compactMap { $0.isOptional || $0.type == .any || $0.isArray || $0.isMap || $0.isSet ? nil : $0.name }, "title": "\(className)" ], "relationships": relationships ] } } // MARK: - AdminProfile struct AdminProfile: Codable { struct Role: Codable { enum CodingKeys: String, CodingKey { case groupId = "group_id" } let groupId: String } let roles: [Role] } // MARK: - Admin class Admin { // MARK: AdminSession /// An authenticated session for using the Admin API class AdminSession { /// The access token of the authenticated user var accessToken: String /// The group id associated with the authenticated user var groupId: String init(accessToken: String, groupId: String) { self.accessToken = accessToken self.groupId = groupId } // MARK: AdminEndpoint /// Representation of a given admin endpoint. /// This allows us to call a give endpoint dynamically with loose typing. @dynamicMemberLookup struct AdminEndpoint { /// The access token of the authenticated user var accessToken: String /// The group id associated with the authenticated user var groupId: String /// The endpoint url. This will be appending to dynamically by appending the dynamic member called /// as if it were a path. var url: URL /** Append the given member to the path. E.g., if the current URL is set to http://localhost:9090/api/admin/v3.0/groups/groupId/apps/appId and you currently have a: ``` var app: AdminEndpoint ``` you can fetch a list of all services by calling ``` app.services.get() ``` */ subscript(dynamicMember member: String) -> AdminEndpoint { let pattern = "([a-z0-9])([A-Z])" let regex = try? NSRegularExpression(pattern: pattern, options: []) let range = NSRange(location: 0, length: member.count) let snakeCaseMember = regex?.stringByReplacingMatches(in: member, options: [], range: range, withTemplate: "$1_$2").lowercased() return AdminEndpoint(accessToken: accessToken, groupId: groupId, url: url.appendingPathComponent(snakeCaseMember!)) } /** Append the given id to the path. E.g., if the current URL is set to http://localhost:9090/api/admin/v3.0/groups/groupId/apps/ and you currently have a: ``` var apps: AdminEndpoint var appId: String ``` you can fetch the app from its appId with ``` apps[appId].get() ``` */ subscript(_ id: String) -> AdminEndpoint { return AdminEndpoint(accessToken: accessToken, groupId: groupId, url: url.appendingPathComponent(id)) } private func request(httpMethod: String, data: Any? = nil, completionHandler: @escaping (Result<Any?, Error>) -> Void) { var components = URLComponents(url: self.url, resolvingAgainstBaseURL: false)! components.query = "bypass_service_change=SyncProtocolVersionIncrease" var request = URLRequest(url: components.url!) request.httpMethod = httpMethod request.allHTTPHeaderFields = [ "Authorization": "Bearer \(accessToken)", "Content-Type": "application/json;charset=utf-8", "Accept": "application/json" ] if let data = data { do { request.httpBody = try JSONSerialization.data(withJSONObject: data) } catch { completionHandler(.failure(error)) } } URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: OperationQueue()) .resultDataTask(with: request) { result in completionHandler(result.flatMap { data in Result { data.count > 0 ? try JSONSerialization.jsonObject(with: data) : nil } }) } } private func request(on group: DispatchGroup, httpMethod: String, data: Any? = nil, _ completionHandler: @escaping (Result<Any?, Error>) -> Void) { group.enter() request(httpMethod: httpMethod, data: data) { result in completionHandler(result) group.leave() } } private func request(httpMethod: String, data: Any? = nil) -> Result<Any?, Error> { let group = DispatchGroup() var result: Result<Any?, Error>! group.enter() request(httpMethod: httpMethod, data: data) { result = $0 group.leave() } guard case .success = group.wait(timeout: .now() + 5) else { return .failure(URLError(.badServerResponse)) } return result } func get(_ completionHandler: @escaping (Result<Any?, Error>) -> Void) { request(httpMethod: "GET", completionHandler: completionHandler) } func get(on group: DispatchGroup, _ completionHandler: @escaping (Result<Any?, Error>) -> Void) { request(on: group, httpMethod: "GET", completionHandler) } func get() -> Result<Any?, Error> { request(httpMethod: "GET") } func post(_ data: Any, _ completionHandler: @escaping (Result<Any?, Error>) -> Void) { request(httpMethod: "POST", data: data, completionHandler: completionHandler) } func post(on group: DispatchGroup, _ data: Any, _ completionHandler: @escaping (Result<Any?, Error>) -> Void) { request(on: group, httpMethod: "POST", data: data, completionHandler) } func post(_ data: Any) -> Result<Any?, Error> { request(httpMethod: "POST", data: data) } func put(_ completionHandler: @escaping (Result<Any?, Error>) -> Void) { request(httpMethod: "PUT", completionHandler: completionHandler) } func put(on group: DispatchGroup, data: Any? = nil, _ completionHandler: @escaping (Result<Any?, Error>) -> Void) { request(on: group, httpMethod: "PUT", data: data, completionHandler) } func patch(on group: DispatchGroup, _ data: Any, _ completionHandler: @escaping (Result<Any?, Error>) -> Void) { request(on: group, httpMethod: "PATCH", data: data, completionHandler) } } /// The initial endpoint to access the admin server lazy var apps = AdminEndpoint(accessToken: accessToken, groupId: groupId, url: URL(string: "http://localhost:9090/api/admin/v3.0/groups/\(groupId)/apps")!) } private func userProfile(accessToken: String) -> Result<AdminProfile, Error> { var request = URLRequest(url: URL(string: "http://localhost:9090/api/admin/v3.0/auth/profile")!) request.allHTTPHeaderFields = [ "Authorization": "Bearer \(String(describing: accessToken))" ] return URLSession.shared.resultDataTask(with: request) .flatMap { data in Result { try JSONDecoder().decode(AdminProfile.self, from: data) } } } /// Synchronously authenticate an admin session func login() throws -> AdminSession { let authUrl = URL(string: "http://localhost:9090/api/admin/v3.0/auth/providers/local-userpass/login")! var loginRequest = URLRequest(url: authUrl) loginRequest.httpMethod = "POST" loginRequest.allHTTPHeaderFields = ["Content-Type": "application/json;charset=utf-8", "Accept": "application/json"] loginRequest.httpBody = try! JSONEncoder().encode(["provider": "userpass", "username": "[email protected]", "password": "password"]) return try URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue()) .resultDataTask(with: loginRequest) .flatMap { data in return Result { if let accessToken = try JSONDecoder().decode([String: String].self, from: data)["access_token"] { return accessToken } throw URLError(.badServerResponse) } } .flatMap { (accessToken: String) -> Result<AdminSession, Error> in self.userProfile(accessToken: accessToken).map { AdminSession(accessToken: accessToken, groupId: $0.roles[0].groupId) } } .get() } } // MARK: RealmServer /** A sandboxed server. This singleton launches and maintains all server processes and allows for app creation. */ @available(OSX 10.13, *) @objc(RealmServer) public class RealmServer: NSObject { public enum LogLevel { case none, info, warn, error } /// Shared RealmServer. This class only needs to be initialized and torn down once per test suite run. @objc public static var shared = RealmServer() /// Log level for the server and mongo processes. public var logLevel = LogLevel.none /// Process that runs the local mongo server. Should be terminated on exit. private let mongoProcess = Process() /// Process that runs the local backend server. Should be terminated on exit. private let serverProcess = Process() /// The root URL of the project. private static let rootUrl = URL(string: #file)! .deletingLastPathComponent() // RealmServer.swift .deletingLastPathComponent() // ObjectServerTests .deletingLastPathComponent() // Realm private static let buildDir = rootUrl.appendingPathComponent(".baas") private static let binDir = buildDir.appendingPathComponent("bin") /// The directory where mongo stores its files. This is a unique value so that /// we have a fresh mongo each run. private lazy var tempDir = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent("realm-test-\(UUID().uuidString)") /// Whether or not this is a parent or child process. private lazy var isParentProcess = (getenv("RLMProcessIsChild") == nil) /// The current admin session private var session: Admin.AdminSession? /// Check if the BaaS files are present and we can run the server @objc public class func haveServer() -> Bool { let goDir = RealmServer.buildDir.appendingPathComponent("stitch") return FileManager.default.fileExists(atPath: goDir.path) } private override init() { super.init() if isParentProcess { atexit { _ = RealmServer.shared.tearDown } do { try launchMongoProcess() try launchServerProcess() self.session = try Admin().login() } catch { XCTFail("Could not initiate admin session: \(error.localizedDescription)") } } } /// Lazy teardown for exit only. private lazy var tearDown: () = { serverProcess.terminate() let mongo = RealmServer.binDir.appendingPathComponent("mongo").path // step down the replica set let rsStepDownProcess = Process() rsStepDownProcess.launchPath = mongo rsStepDownProcess.arguments = [ "admin", "--port", "26000", "--eval", "'db.adminCommand({replSetStepDown: 0, secondaryCatchUpPeriodSecs: 0, force: true})'"] try? rsStepDownProcess.run() rsStepDownProcess.waitUntilExit() // step down the replica set let mongoShutdownProcess = Process() mongoShutdownProcess.launchPath = mongo mongoShutdownProcess.arguments = [ "admin", "--port", "26000", "--eval", "'db.shutdownServer({force: true})'"] try? mongoShutdownProcess.run() mongoShutdownProcess.waitUntilExit() mongoProcess.terminate() try? FileManager().removeItem(at: tempDir) }() /// Launch the mongo server in the background. /// This process should run until the test suite is complete. private func launchMongoProcess() throws { try! FileManager().createDirectory(at: tempDir, withIntermediateDirectories: false, attributes: nil) mongoProcess.launchPath = RealmServer.binDir.appendingPathComponent("mongod").path mongoProcess.arguments = [ "--quiet", "--dbpath", tempDir.path, "--bind_ip", "localhost", "--port", "26000", "--replSet", "test" ] mongoProcess.standardOutput = nil try mongoProcess.run() let initProcess = Process() initProcess.launchPath = RealmServer.binDir.appendingPathComponent("mongo").path initProcess.arguments = [ "--port", "26000", "--eval", "rs.initiate()" ] initProcess.standardOutput = nil try initProcess.run() initProcess.waitUntilExit() } private func launchServerProcess() throws { let binDir = Self.buildDir.appendingPathComponent("bin").path let libDir = Self.buildDir.appendingPathComponent("lib").path let binPath = "$PATH:\(binDir)" let stitchRoot = RealmServer.buildDir.path + "/go/src/github.com/10gen/stitch" // create the admin user let userProcess = Process() userProcess.environment = [ "PATH": binPath, "LD_LIBRARY_PATH": libDir ] userProcess.launchPath = "\(binDir)/create_user" userProcess.arguments = [ "addUser", "-domainID", "000000000000000000000000", "-mongoURI", "mongodb://localhost:26000", "-salt", "DQOWene1723baqD!_@#", "-id", "[email protected]", "-password", "password" ] try userProcess.run() userProcess.waitUntilExit() serverProcess.environment = [ "PATH": binPath, "LD_LIBRARY_PATH": libDir ] // golang server needs a tmp directory try! FileManager.default.createDirectory(atPath: "\(tempDir.path)/tmp", withIntermediateDirectories: false, attributes: nil) serverProcess.launchPath = "\(binDir)/stitch_server" serverProcess.currentDirectoryPath = tempDir.path serverProcess.arguments = [ "--configFile", "\(stitchRoot)/etc/configs/test_config.json" ] let pipe = Pipe() pipe.fileHandleForReading.readabilityHandler = { file in guard file.availableData.count > 0, let available = String(data: file.availableData, encoding: .utf8)?.split(separator: "\t") else { return } // prettify server output var parts = [String]() for part in available { if part.contains("INFO") { guard self.logLevel == .info else { return } parts.append("🔵") } else if part.contains("DEBUG") { guard self.logLevel == .info || self.logLevel == .warn else { return } parts.append("🟡") } else if part.contains("ERROR") { parts.append("🔴") } else if let json = try? JSONSerialization.jsonObject(with: part.data(using: .utf8)!) { parts.append(String(data: try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted), encoding: .utf8)!) } else if !part.isEmpty { parts.append(String(part)) } } print(parts.joined(separator: "\t")) } if logLevel != .none { serverProcess.standardOutput = pipe } else { serverProcess.standardOutput = nil } try serverProcess.run() waitForServerToStart() } private func waitForServerToStart() { let group = DispatchGroup() group.enter() func pingServer(_ tries: Int = 0) { let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: OperationQueue()) session.dataTask(with: URL(string: "http://localhost:9090")!) { (_, _, error) in if error != nil { usleep(50000) pingServer(tries + 1) } else { group.leave() } }.resume() } pingServer() guard case .success = group.wait(timeout: .now() + 10) else { return XCTFail("Server did not start") } } public typealias AppId = String private func failOnError<T>(_ result: Result<T, Error>) { if case .failure(let error) = result { XCTFail(error.localizedDescription) } } /// Create a new server app @objc public func createAppForBSONType(_ bsonType: String) throws -> AppId { guard let session = session else { throw URLError(.unknown) } let info = try session.apps.post(["name": "test"]).get() guard let appInfo = info as? [String: Any], let clientAppId = appInfo["client_app_id"] as? String, let appId = appInfo["_id"] as? String else { throw URLError(.badServerResponse) } let app = session.apps[appId] let group = DispatchGroup() app.authProviders.post(on: group, ["type": "anon-user"], failOnError) app.authProviders.post(on: group, [ "type": "local-userpass", "config": [ "emailConfirmationUrl": "http://foo.com", "resetPasswordUrl": "http://foo.com", "confirmEmailSubject": "Hi", "resetPasswordSubject": "Bye", "autoConfirm": true ] ], failOnError) app.authProviders.get(on: group) { authProviders in do { guard let authProviders = try authProviders.get() as? [[String: Any]] else { return XCTFail("Bad formatting for authProviders") } guard let provider = authProviders.first(where: { $0["type"] as? String == "api-key" }) else { return XCTFail("Did not find api-key provider") } app.authProviders[provider["_id"] as! String].enable.put(on: group, self.failOnError) } catch { XCTFail(error.localizedDescription) } } _ = app.secrets.post([ "name": "BackingDB_uri", "value": "mongodb://localhost:26000" ]) let serviceResponse = app.services.post([ "name": "mongodb1", "type": "mongodb", "config": [ "uri": "mongodb://localhost:26000", "sync": [ "state": "enabled", "database_name": "test_data", "partition": [ "key": "realm_id", "type": "\(bsonType)", "required": false, "permissions": [ "read": true, "write": true ] ] ] ] ]) guard let serviceId = (try serviceResponse.get() as? [String: Any])?["_id"] as? String else { throw URLError(.badServerResponse) } let rules = app.services[serviceId].rules // Creating the rules is a two-step process where we first add all the // rules and then add properties to them so that we can add relationships let schema = ObjectiveCSupport.convert(object: RLMSchema.shared()) let syncTypes = schema.objectSchema.filter { guard let pk = $0.primaryKeyProperty else { return false } return pk.name == "_id" } var ruleCreations = [Result<Any?, Error>]() for objectSchema in syncTypes { ruleCreations.append(rules.post(objectSchema.stitchRule(bsonType, schema))) } var ruleIds: [String: String] = [:] for result in ruleCreations { guard case .success(let data) = result else { fatalError("Failed to create rule: \(result)") } let dict = (data as! [String: String]) ruleIds[dict["collection"]!] = dict["_id"]! } for objectSchema in syncTypes { let id = ruleIds[objectSchema.className]! rules[id].put(on: group, data: objectSchema.stitchRule(bsonType, schema, id: id), failOnError) } app.sync.config.put(on: group, data: [ "development_mode_enabled": true ], failOnError) app.functions.post(on: group, [ "name": "sum", "private": false, "can_evaluate": [:], "source": """ exports = function(...args) { return parseInt(args.reduce((a,b) => a + b, 0)); }; """ ], failOnError) app.functions.post(on: group, [ "name": "updateUserData", "private": false, "can_evaluate": [:], "source": """ exports = async function(data) { const user = context.user; const mongodb = context.services.get("mongodb1"); const userDataCollection = mongodb.db("test_data").collection("UserData"); await userDataCollection.updateOne( { "user_id": user.id }, { "$set": data }, { "upsert": true } ); return true; }; """ ], failOnError) let userDataRule: [String: Any] = [ "database": "test_data", "collection": "UserData", "roles": [[ "name": "default", "apply_when": [:], "insert": true, "delete": true, "additional_fields": [:] ]], "schema": [:], "relationships": [:] ] _ = rules.post(userDataRule) app.customUserData.patch(on: group, [ "mongo_service_id": serviceId, "enabled": true, "database_name": "test_data", "collection_name": "UserData", "user_id_field": "user_id" ], failOnError) _ = app.secrets.post([ "name": "gcm", "value": "gcm" ]) app.services.post(on: group, [ "name": "gcm", "type": "gcm", "config": [ "senderId": "gcm" ], "secret_config": [ "apiKey": "gcm" ], "version": 1 ], failOnError) guard case .success = group.wait(timeout: .now() + 5.0) else { throw URLError(.badServerResponse) } return clientAppId } @objc public func createApp() throws -> AppId { try createAppForBSONType("string") } } #endif
apache-2.0
0397d8488c13c2ceb41b2d3e017219dc
36.455882
159
0.515607
5.029455
false
false
false
false
LeafPlayer/Leaf
Leaf/UIComponents/Video/old/VideoLayer.swift
1
8137
import Cocoa import OpenGL.GL import OpenGL.GL3 func getProcAddress(_ ctx: UnsafeMutableRawPointer?, _ name: UnsafePointer<Int8>?) -> UnsafeMutableRawPointer? { let symbol: CFString = CFStringCreateWithCString( kCFAllocatorDefault, name, kCFStringEncodingASCII) let indentifier = CFBundleGetBundleWithIdentifier("com.apple.opengl" as CFString) let addr = CFBundleGetFunctionPointerForName(indentifier, symbol) if addr == nil { print("Cannot get OpenGL function pointer!") } return addr } func updateCallback(_ ctx: UnsafeMutableRawPointer?) { let videoLayer = unsafeBitCast(ctx, to: VideoLayer.self) videoLayer.queue.async { if !videoLayer.isAsynchronous { videoLayer.display() } } } class VideoLayer: CAOpenGLLayer { var mpv: OpaquePointer? var mpvGLCBContext: OpaquePointer? var surfaceSize: NSSize? var link: CVDisplayLink? var queue: DispatchQueue = DispatchQueue(label: "io.mpv.callbackQueue") private var _inLiveResize: Bool? var inLiveResize: Bool { set(live) { _inLiveResize = live if _inLiveResize == false { isAsynchronous = false queue.async{ self.display() } } else { isAsynchronous = true } } get { return _inLiveResize! } } override init() { super.init() autoresizingMask = [.layerWidthSizable, .layerHeightSizable] backgroundColor = NSColor.black.cgColor _inLiveResize = false } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func canDraw(inCGLContext ctx: CGLContextObj, pixelFormat pf: CGLPixelFormatObj, forLayerTime t: CFTimeInterval, displayTime ts: UnsafePointer<CVTimeStamp>?) -> Bool { return true } override func draw(inCGLContext ctx: CGLContextObj, pixelFormat pf: CGLPixelFormatObj, forLayerTime t: CFTimeInterval, displayTime ts: UnsafePointer<CVTimeStamp>?) { var i: GLint = 0 glGetIntegerv(GLenum(GL_DRAW_FRAMEBUFFER_BINDING), &i) if mpvGLCBContext != nil { if inLiveResize == false { surfaceSize = self.bounds.size } mpv_opengl_cb_draw(mpvGLCBContext, i, Int32(surfaceSize!.width), Int32(-surfaceSize!.height)) } else { glClearColor(0, 0, 0, 1) glClear(GLbitfield(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT )) } CGLFlushDrawable(ctx) } override func copyCGLPixelFormat(forDisplayMask mask: UInt32) -> CGLPixelFormatObj { let attrs: [CGLPixelFormatAttribute] = [ kCGLPFAOpenGLProfile, CGLPixelFormatAttribute(kCGLOGLPVersion_3_2_Core.rawValue), kCGLPFADoubleBuffer, kCGLPFAAllowOfflineRenderers, kCGLPFABackingStore, kCGLPFAAccelerated, kCGLPFASupportsAutomaticGraphicsSwitching, _CGLPixelFormatAttribute(rawValue: 0) ] var npix: GLint = 0 var pix: CGLPixelFormatObj? CGLChoosePixelFormat(attrs, &pix, &npix) return pix! } override func copyCGLContext(forPixelFormat pf: CGLPixelFormatObj) -> CGLContextObj { let ctx = super.copyCGLContext(forPixelFormat:pf) var i: GLint = 1 CGLSetParameter(ctx, kCGLCPSwapInterval, &i) CGLEnable(ctx, kCGLCEMPEngine) CGLSetCurrentContext(ctx) initMPV() initDisplayLink() return ctx } override func display() { super.display() CATransaction.flush() } func initMPV() { mpv = mpv_create() if mpv == nil { print("failed creating context") exit(1) } checkError(mpv_set_option_string(mpv, "terminal", "yes")) checkError(mpv_set_option_string(mpv, "input-media-keys", "yes")) checkError(mpv_set_option_string(mpv, "input-ipc-server", "/tmp/mpvsocket")) checkError(mpv_set_option_string(mpv, "input-default-bindings", "yes")) checkError(mpv_set_option_string(mpv, "config", "yes")) //checkError(mpv_set_option_string(mpv, "msg-level", "all=v")) checkError(mpv_set_option_string(mpv, "config-dir", NSHomeDirectory()+"/.config/mpv")) checkError(mpv_set_option_string(mpv, "vo", "opengl-cb")) checkError(mpv_set_option_string(mpv, "display-fps", "60")) checkError(mpv_initialize(mpv)) mpvGLCBContext = OpaquePointer(mpv_get_sub_api(mpv, MPV_SUB_API_OPENGL_CB)) if mpvGLCBContext == nil { print("libmpv does not have the opengl-cb sub-API.") exit(1) } let r = mpv_opengl_cb_init_gl(mpvGLCBContext, nil, getProcAddress, nil) if r < 0 { print("gl init has failed.") exit(1) } mpv_opengl_cb_set_update_callback(mpvGLCBContext, updateCallback, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())) mpv_set_wakeup_callback(mpv, { (ctx) in let mpvController = unsafeBitCast(ctx, to: VideoLayer.self) mpvController.readEvents() }, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())) } func loadFile(filename: String) { queue.async { let cmd = ["loadfile", filename, nil] var cargs = cmd.map { $0.flatMap { UnsafePointer<Int8>(strdup($0)) } } self.checkError(mpv_command(self.mpv, &cargs)) } } func uninitMPV() { let cmd = ["quit", nil] var args = cmd.map{$0.flatMap{UnsafePointer<Int8>(strdup($0))}} mpv_command(mpv, &args) } private func readEvents() { queue.async { while self.mpv != nil { let event = mpv_wait_event(self.mpv, 0) if event!.pointee.event_id == MPV_EVENT_NONE { break } self.handleEvent(event) } } } func handleEvent(_ event: UnsafePointer<mpv_event>!) { switch event.pointee.event_id { case MPV_EVENT_SHUTDOWN: mpv_opengl_cb_uninit_gl(mpvGLCBContext) mpvGLCBContext = nil mpv_detach_destroy(mpv) mpv = nil NSApp.terminate(self) case MPV_EVENT_LOG_MESSAGE: let logmsg = UnsafeMutablePointer<mpv_event_log_message>(OpaquePointer(event.pointee.data)) print("log:", String(cString: (logmsg!.pointee.prefix)!), String(cString: (logmsg!.pointee.level)!), String(cString: (logmsg!.pointee.text)!)) default: print("event:", String(cString: mpv_event_name(event.pointee.event_id))) } } let displayLinkCallback: CVDisplayLinkOutputCallback = { (displayLink, now, outputTime, flagsIn, flagsOut, displayLinkContext) -> CVReturn in let layer: VideoLayer = unsafeBitCast(displayLinkContext, to: VideoLayer.self) if layer.mpvGLCBContext != nil { mpv_opengl_cb_report_flip(layer.mpvGLCBContext, 0) } return kCVReturnSuccess } func initDisplayLink() { let displayId = UInt32(NSScreen.main!.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as! Int) CVDisplayLinkCreateWithCGDisplay(displayId, &link) CVDisplayLinkSetOutputCallback(link!, displayLinkCallback, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())) CVDisplayLinkStart(link!) } func uninitDisplaylink() { if CVDisplayLinkIsRunning(link!) { CVDisplayLinkStop(link!) } } func checkError(_ status: CInt) { if (status < 0) { print("mpv API error:", mpv_error_string(status)) exit(1) } } }
gpl-3.0
b654dd6445389b341898770f81e98776
32.348361
145
0.59506
4.289404
false
false
false
false
Yurssoft/QuickFile
Pods/SwiftMessages/SwiftMessages/PhysicsPanHandler.swift
2
6722
// // PhysicsPanHandler.swift // SwiftMessages // // Created by Timothy Moose on 6/25/17. // Copyright © 2017 SwiftKick Mobile. All rights reserved. // import UIKit open class PhysicsPanHandler { public final class State { weak var messageView: UIView? weak var containerView: UIView? var dynamicAnimator: UIDynamicAnimator var itemBehavior: UIDynamicItemBehavior var attachmentBehavior: UIAttachmentBehavior? { didSet { if let oldValue = oldValue { dynamicAnimator.removeBehavior(oldValue) } if let attachmentBehavior = attachmentBehavior { dynamicAnimator.addBehavior(attachmentBehavior) angle = messageView?.angle ?? angle time = CFAbsoluteTimeGetCurrent() } } } var time: CFAbsoluteTime = 0 var angle: CGFloat = 0 public init(messageView: UIView, containerView: UIView) { self.messageView = messageView self.containerView = containerView let dynamicAnimator = UIDynamicAnimator(referenceView: containerView) let itemBehavior = UIDynamicItemBehavior(items: [messageView]) itemBehavior.allowsRotation = true dynamicAnimator.addBehavior(itemBehavior) self.itemBehavior = itemBehavior self.dynamicAnimator = dynamicAnimator } func update(attachmentAnchorPoint anchorPoint: CGPoint) { angle = messageView?.angle ?? angle time = CFAbsoluteTimeGetCurrent() attachmentBehavior?.anchorPoint = anchorPoint } public func stop() { guard let messageView = messageView else { dynamicAnimator.removeAllBehaviors() return } let center = messageView.center let transform = messageView.transform dynamicAnimator.removeAllBehaviors() messageView.center = center messageView.transform = transform } } weak var animator: Animator? weak var messageView: UIView? weak var containerView: UIView? private(set) public var state: State? private(set) public var isOffScreen = false private var restingCenter: CGPoint? public init(context: AnimationContext, animator: Animator) { messageView = context.messageView containerView = context.containerView self.animator = animator let pan = UIPanGestureRecognizer() pan.addTarget(self, action: #selector(pan(_:))) if let view = messageView as? BackgroundViewable { view.backgroundView.addGestureRecognizer(pan) } else { context.messageView.addGestureRecognizer(pan) } } @objc func pan(_ pan: UIPanGestureRecognizer) { guard let messageView = messageView, let containerView = containerView, let animator = animator else { return } let anchorPoint = pan.location(in: containerView) switch pan.state { case .began: animator.delegate?.panStarted(animator: animator) let state = State(messageView: messageView, containerView: containerView) self.state = state let center = messageView.center restingCenter = center let offset = UIOffset(horizontal: anchorPoint.x - center.x, vertical: anchorPoint.y - center.y) let attachmentBehavior = UIAttachmentBehavior(item: messageView, offsetFromCenter: offset, attachedToAnchor: anchorPoint) state.attachmentBehavior = attachmentBehavior state.itemBehavior.action = { [weak self, weak messageView, weak containerView] in guard let strongSelf = self, let messageView = messageView, let containerView = containerView, let animator = strongSelf.animator else { return } let view = (messageView as? BackgroundViewable)?.backgroundView ?? messageView let frame = containerView.convert(view.bounds, from: view) if !containerView.bounds.intersects(frame) { strongSelf.isOffScreen = true DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) { animator.delegate?.hide(animator: animator) } } } case .changed: guard let state = state else { return } state.update(attachmentAnchorPoint: anchorPoint) case .ended, .cancelled: guard let state = state else { return } let velocity = pan.velocity(in: containerView) let time = CFAbsoluteTimeGetCurrent() let angle = messageView.angle let angularVelocity: CGFloat if time > state.time { angularVelocity = (angle - state.angle) / CGFloat(time - state.time) } else { angularVelocity = 0 } let speed = sqrt(pow(velocity.x, 2) + pow(velocity.y, 2)) // The multiplier on angular velocity was determined by hand-tuning let energy = sqrt(pow(speed, 2) + pow(angularVelocity * 75, 2)) if energy > 200 && speed > 600 { // Limit the speed and angular velocity to reasonable values let speedScale = speed > 0 ? min(1, 1800 / speed) : 1 let escapeVelocity = CGPoint(x: velocity.x * speedScale, y: velocity.y * speedScale) let angularSpeedScale = min(1, 10 / fabs(angularVelocity)) let escapeAngularVelocity = angularVelocity * angularSpeedScale state.itemBehavior.addLinearVelocity(escapeVelocity, for: messageView) state.itemBehavior.addAngularVelocity(escapeAngularVelocity, for: messageView) state.attachmentBehavior = nil } else { animator.delegate?.panEnded(animator: animator) state.stop() self.state = nil UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.65, initialSpringVelocity: 0, options: .beginFromCurrentState, animations: { messageView.center = self.restingCenter ?? CGPoint(x: containerView.bounds.width / 2, y: containerView.bounds.height / 2) messageView.transform = CGAffineTransform.identity }, completion: nil) } default: break } } } extension UIView { var angle: CGFloat { // http://stackoverflow.com/a/2051861/1271826 return atan2(transform.b, transform.a) } }
mit
52bc8bbcd72591b37dc642fe92333a08
42.642857
162
0.610028
5.540808
false
false
false
false