repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Jnosh/swift | test/IRGen/objc_super.swift | 2 | 5262 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import gizmo
// CHECK: [[CLASS:%objc_class]] = type
// CHECK: [[TYPE:%swift.type]] = type
// CHECK: [[HOOZIT:%T10objc_super6HoozitC]] = type
// CHECK: [[PARTIAL_APPLY_CLASS:%T10objc_super12PartialApplyC]] = type
// CHECK: [[SUPER:%objc_super]] = type
// CHECK: [[OBJC:%objc_object]] = type
// CHECK: [[GIZMO:%TSo5GizmoC]] = type
// CHECK: [[NSRECT:%TSC6NSRectV]] = type
class Hoozit : Gizmo {
// CHECK: define hidden swiftcc void @_T010objc_super6HoozitC4frobyyF([[HOOZIT]]* swiftself) {{.*}} {
override func frob() {
// CHECK: [[T0:%.*]] = call [[TYPE]]* @_T010objc_super6HoozitCMa()
// CHECK: [[T1:%.*]] = bitcast [[TYPE]]* [[T0]] to [[CLASS]]*
// CHECK: store [[CLASS]]* [[T1]], [[CLASS]]** {{.*}}, align 8
// CHECK: load i8*, i8** @"\01L_selector(frob)"
// CHECK: call void bitcast (void ()* @objc_msgSendSuper2 to void ([[SUPER]]*, i8*)*)([[SUPER]]* {{.*}}, i8* {{.*}})
super.frob()
}
// CHECK: }
// CHECK: define hidden swiftcc void @_T010objc_super6HoozitC5runceyyFZ([[TYPE]]* swiftself) {{.*}} {
override class func runce() {
// CHECK: store [[CLASS]]* @"OBJC_METACLASS_$__TtC10objc_super6Hoozit", [[CLASS]]** {{.*}}, align 8
// CHECK: load i8*, i8** @"\01L_selector(runce)"
// CHECK: call void bitcast (void ()* @objc_msgSendSuper2 to void ([[SUPER]]*, i8*)*)([[SUPER]]* {{.*}}, i8* {{.*}})
super.runce()
}
// CHECK: }
// CHECK: define hidden swiftcc { double, double, double, double } @_T010objc_super6HoozitC5frameSC6NSRectVyF(%T10objc_super6HoozitC* swiftself) {{.*}} {
override func frame() -> NSRect {
// CHECK: [[T0:%.*]] = call [[TYPE]]* @_T010objc_super6HoozitCMa()
// CHECK: [[T1:%.*]] = bitcast [[TYPE]]* [[T0]] to [[CLASS]]*
// CHECK: store [[CLASS]]* [[T1]], [[CLASS]]** {{.*}}, align 8
// CHECK: load i8*, i8** @"\01L_selector(frame)"
// CHECK: call void bitcast (void ()* @objc_msgSendSuper2_stret to void ([[NSRECT]]*, [[SUPER]]*, i8*)*)([[NSRECT]]* noalias nocapture sret {{.*}}, [[SUPER]]* {{.*}}, i8* {{.*}})
return NSInsetRect(super.frame(), 2.0, 2.0)
}
// CHECK: }
// CHECK: define hidden swiftcc [[HOOZIT]]* @_T010objc_super6HoozitCACSi1x_tcfc(i64, %T10objc_super6HoozitC* swiftself) {{.*}} {
init(x:Int) {
// CHECK: load i8*, i8** @"\01L_selector(init)"
// CHECK: call [[OPAQUE:.*]]* bitcast (void ()* @objc_msgSendSuper2 to [[OPAQUE:.*]]* (%objc_super*, i8*)*)([[SUPER]]* {{.*}}, i8* {{.*}})
// CHECK-NOT: @swift_dynamicCastClassUnconditional
// CHECK: ret
super.init()
}
// CHECK: }
// CHECK: define hidden swiftcc [[HOOZIT]]* @_T010objc_super6HoozitCACSi1y_tcfc(i64, %T10objc_super6HoozitC* swiftself) {{.*}} {
init(y:Int) {
// CHECK: load i8*, i8** @"\01L_selector(initWithBellsOn:)"
// CHECK: call [[OPAQUE:.*]]* bitcast (void ()* @objc_msgSendSuper2 to [[OPAQUE:.*]]* (%objc_super*, i8*, i64)*)([[SUPER]]* {{.*}}, i8* {{.*}}, i64 {{.*}})
// CHECK-NOT: swift_dynamicCastClassUnconditional
// CHECK: ret
super.init(bellsOn:y)
}
// CHECK: }
}
func acceptFn(_ fn: () -> Void) { }
class PartialApply : Gizmo {
// CHECK: define hidden swiftcc void @_T010objc_super12PartialApplyC4frobyyF([[PARTIAL_APPLY_CLASS]]* swiftself) {{.*}} {
override func frob() {
// CHECK: call swiftcc void @_T010objc_super8acceptFnyyycF(i8* bitcast (void (%swift.refcounted*)* [[PARTIAL_FORWARDING_THUNK:@[A-Za-z0-9_]+]] to i8*), %swift.refcounted* %3)
acceptFn(super.frob)
}
// CHECK: }
}
class GenericRuncer<T> : Gizmo {
// CHECK: define hidden swiftcc void @_T010objc_super13GenericRuncerC5runceyyFZ(%swift.type* swiftself) {{.*}} {
override class func runce() {
// CHECK: [[CLASS:%.*]] = call %swift.type* @_T010objc_super13GenericRuncerCMa(%swift.type* %T)
// CHECK-NEXT: [[CLASS1:%.*]] = bitcast %swift.type* [[CLASS]] to %objc_class*
// CHECK-NEXT: [[CLASS2:%.*]] = bitcast %objc_class* [[CLASS1]] to i64*
// CHECK-NEXT: [[ISA:%.*]] = load i64, i64* [[CLASS2]], align 8
// CHECK-NEXT: [[ISA_MASK:%.*]] = load i64, i64* @swift_isaMask, align 8
// CHECK-NEXT: [[ISA_MASKED:%.*]] = and i64 [[ISA]], [[ISA_MASK]]
// CHECK-NEXT: [[ISA_PTR:%.*]] = inttoptr i64 [[ISA_MASKED]] to %swift.type*
// CHECK-NEXT: [[METACLASS:%.*]] = bitcast %swift.type* [[ISA_PTR]] to %objc_class*
// CHECK: [[METACLASS_ADDR:%.*]] = getelementptr %objc_super, %objc_super* %objc_super, i32 0, i32 1
// CHECK-NEXT: store %objc_class* [[METACLASS]], %objc_class** [[METACLASS_ADDR]], align 8
// CHECK-NEXT: [[SELECTOR:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8
// CHECK-NEXT: call void bitcast (void ()* @objc_msgSendSuper2 to void (%objc_super*, i8*)*)(%objc_super* %objc_super, i8* [[SELECTOR]])
// CHECK-NEXT: ret void
super.runce()
}
}
// CHECK: define internal swiftcc void [[PARTIAL_FORWARDING_THUNK]](%swift.refcounted* swiftself) #0 {
// CHECK: call %swift.type* @_T010objc_super12PartialApplyCMa()
// CHECK: @"\01L_selector(frob)"
// CHECK: call void bitcast (void ()* @objc_msgSendSuper2
// CHECK: }
| apache-2.0 | 336287243a9d29f0245b392528f31c78 | 48.17757 | 182 | 0.596731 | 3.290807 | false | false | false | false |
billyto/JSONSchemaValidatorKit | JSONScheme.playground/Contents.swift | 1 | 903 | //: JSONSchema : Playground to explore how to use JSONSchemaValidatorKit
import Foundation
//import JSONSchemaValidatorKit
//
////Grab JSONDocument
//let jsonPath = NSBundle.mainBundle().pathForResource("person", ofType: "json")
//let jsonData = NSData(contentsOfFile: jsonPath!)
//let jsonDocument = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: .AllowFragments) as? [String: AnyObject]
//
////Grab JSONSchema
//let jsonXPath = NSBundle.mainBundle().pathForResource("basic-schema", ofType: "json")
//let jsonXData = NSData(contentsOfFile: jsonXPath!)
//let jsonSchema = try NSJSONSerialization.JSONObjectWithData(jsonXData!, options: .AllowFragments) as? [String: AnyObject]
//
//
//
//let validator : SchemaValidator? = try SchemaValidator(withSchema: jsonSchema!)
//let result = validator!.validateJSON(jsonDocument!)
//print("do we have a valid json? \(result)")
| mit | 67eb88e9b8d9ea26da6b241160eba15f | 30.137931 | 124 | 0.748616 | 4.279621 | false | false | false | false |
tellowkrinkle/Sword | Sources/Sword/Types/DM.swift | 1 | 1025 | //
// DMChannel.swift
// Sword
//
// Created by Alejandro Alonso
// Copyright © 2017 Alejandro Alonso. All rights reserved.
//
/// DM Type
public struct DM: TextChannel {
// MARK: Properties
/// Parent class
public internal(set) weak var sword: Sword?
/// ID of DM
public let id: ChannelID
/// The recipient of this DM
public internal(set) var recipient: User
/// The last message's ID
public let lastMessageId: MessageID?
/// Indicates what kind of channel this is
public let type: ChannelType
// MARK: Initializer
/**
Creates a DMChannel struct
- parameter sword: Parent class
- parameter json: JSON representable as a dictionary
*/
init(_ sword: Sword, _ json: [String: Any]) {
self.sword = sword
self.id = ChannelID(json["id"] as! String)!
let recipients = json["recipients"] as! [[String: Any]]
self.recipient = User(sword, recipients[0])
self.lastMessageId = MessageID(json["last_message_id"] as? String)
self.type = .dm
}
}
| mit | 2fc0d28369a9bdc6227a5e981d2542a2 | 19.48 | 70 | 0.65332 | 3.968992 | false | false | false | false |
cbpowell/MarqueeLabel-Swift | Classes/MarqueeLabel.swift | 1 | 66948 | //
// MarqueeLabel.swift
//
// Created by Charles Powell on 8/6/14.
// Copyright (c) 2015 Charles Powell. All rights reserved.
//
import UIKit
import QuartzCore
public class MarqueeLabel: UILabel {
/**
An enum that defines the types of `MarqueeLabel` scrolling
- LeftRight: Scrolls left first, then back right to the original position.
- RightLeft: Scrolls right first, then back left to the original position.
- Continuous: Continuously scrolls left (with a pause at the original position if animationDelay is set).
- ContinuousReverse: Continuously scrolls right (with a pause at the original position if animationDelay is set).
*/
public enum Type {
case LeftRight
case RightLeft
case Continuous
case ContinuousReverse
}
//
// MARK: - Public properties
//
/**
Defines the direction and method in which the `MarqueeLabel` instance scrolls.
`MarqueeLabel` supports four types of scrolling: `MLLeftRight`, `MLRightLeft`, `MLContinuous`, and `MLContinuousReverse`.
Given the nature of how text direction works, the options for the `marqueeType` property require specific text alignments
and will set the textAlignment property accordingly.
- `MLLeftRight` type is ONLY compatible with a label text alignment of `NSTextAlignmentLeft`.
- `MLRightLeft` type is ONLY compatible with a label text alignment of `NSTextAlignmentRight`.
- `MLContinuous` does not require a text alignment (it is effectively centered).
- `MLContinuousReverse` does not require a text alignment (it is effectively centered).
Defaults to `MLContinuous`.
- SeeAlso: Type
- SeeAlso: textAlignment
*/
public var type: Type = .Continuous {
didSet {
if type == oldValue {
return
}
updateAndScroll()
}
}
/**
Specifies the animation curve used in the scrolling motion of the labels.
Allowable options:
- `UIViewAnimationOptionCurveEaseInOut`
- `UIViewAnimationOptionCurveEaseIn`
- `UIViewAnimationOptionCurveEaseOut`
- `UIViewAnimationOptionCurveLinear`
Defaults to `UIViewAnimationOptionCurveEaseInOut`.
*/
public var animationCurve: UIViewAnimationCurve = .Linear
/**
A boolean property that sets whether the `MarqueeLabel` should behave like a normal `UILabel`.
When set to `true` the `MarqueeLabel` will behave and look like a normal `UILabel`, and will not begin any scrolling animations.
Changes to this property take effect immediately, removing any in-flight animation as well as any edge fade. Note that `MarqueeLabel`
will respect the current values of the `lineBreakMode` and `textAlignment`properties while labelized.
To simply prevent automatic scrolling, use the `holdScrolling` property.
Defaults to `false`.
- SeeAlso: holdScrolling
- SeeAlso: lineBreakMode
@warning The label will not automatically scroll when this property is set to `YES`.
@warning The UILabel default setting for the `lineBreakMode` property is `NSLineBreakByTruncatingTail`, which truncates
the text adds an ellipsis glyph (...). Set the `lineBreakMode` property to `NSLineBreakByClipping` in order to avoid the
ellipsis, especially if using an edge transparency fade.
*/
@IBInspectable public var labelize: Bool = false {
didSet {
if labelize != oldValue {
updateAndScroll()
}
}
}
/**
A boolean property that sets whether the `MarqueeLabel` should hold (prevent) automatic label scrolling.
When set to `true`, `MarqueeLabel` will not automatically scroll even its text is larger than the specified frame,
although the specified edge fades will remain.
To set `MarqueeLabel` to act like a normal UILabel, use the `labelize` property.
Defaults to `false`.
- SeeAlso: labelize
@warning The label will not automatically scroll when this property is set to `YES`.
*/
@IBInspectable public var holdScrolling: Bool = false {
didSet {
if holdScrolling != oldValue {
if oldValue == true && !(awayFromHome || labelize || tapToScroll ) && labelShouldScroll() {
beginScroll()
}
}
}
}
/**
A boolean property that sets whether the `MarqueeLabel` should only begin a scroll when tapped.
If this property is set to `true`, the `MarqueeLabel` will only begin a scroll animation cycle when tapped. The label will
not automatically being a scroll. This setting overrides the setting of the `holdScrolling` property.
Defaults to `false`.
@warning The label will not automatically scroll when this property is set to `false`.
- SeeAlso: holdScrolling
*/
@IBInspectable public var tapToScroll: Bool = false {
didSet {
if tapToScroll != oldValue {
if tapToScroll {
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(MarqueeLabel.labelWasTapped(_:)))
self.addGestureRecognizer(tapRecognizer)
userInteractionEnabled = true
} else {
if let recognizer = self.gestureRecognizers!.first as UIGestureRecognizer? {
self.removeGestureRecognizer(recognizer)
}
userInteractionEnabled = false
}
}
}
}
/**
A read-only boolean property that indicates if the label's scroll animation has been paused.
- SeeAlso: pauseLabel
- SeeAlso: unpauseLabel
*/
public var isPaused: Bool {
return (sublabel.layer.speed == 0.0)
}
/**
A boolean property that indicates if the label is currently away from the home location.
The "home" location is the traditional location of `UILabel` text. This property essentially reflects if a scroll animation is underway.
*/
public var awayFromHome: Bool {
if let presentationLayer = sublabel.layer.presentationLayer() as? CALayer {
return !(presentationLayer.position.x == homeLabelFrame.origin.x)
}
return false
}
/**
The `MarqueeLabel` scrolling speed may be defined by one of two ways:
- Rate(CGFloat): The speed is defined by a rate of motion, in units of points per second.
- Duration(CGFloat): The speed is defined by the time to complete a scrolling animation cycle, in units of seconds.
Each case takes an associated `CGFloat` value, which is the rate/duration desired.
*/
public enum SpeedLimit {
case Rate(CGFloat)
case Duration(CGFloat)
var value: CGFloat {
switch self {
case .Rate(let rate):
return rate
case .Duration(let duration):
return duration
}
}
}
/**
Defines the speed of the `MarqueeLabel` scrolling animation.
The speed is set by specifying a case of the `SpeedLimit` enum along with an associated value.
- SeeAlso: SpeedLimit
*/
public var speed: SpeedLimit = .Duration(7.0) {
didSet {
switch (speed, oldValue) {
case (.Rate(let a), .Rate(let b)) where a == b:
return
case (.Duration(let a), .Duration(let b)) where a == b:
return
default:
updateAndScroll()
}
}
}
// @available attribute seems to cause SourceKit to crash right now
// @available(*, deprecated = 2.6, message = "Use speed property instead")
@IBInspectable public var scrollDuration: CGFloat? {
get {
switch speed {
case .Duration(let duration): return duration
case .Rate(_): return nil
}
}
set {
if let duration = newValue {
speed = .Duration(duration)
}
}
}
// @available attribute seems to cause SourceKit to crash right now
// @available(*, deprecated = 2.6, message = "Use speed property instead")
@IBInspectable public var scrollRate: CGFloat? {
get {
switch speed {
case .Duration(_): return nil
case .Rate(let rate): return rate
}
}
set {
if let rate = newValue {
speed = .Rate(rate)
}
}
}
/**
A buffer (offset) between the leading edge of the label text and the label frame.
This property adds additional space between the leading edge of the label text and the label frame. The
leading edge is the edge of the label text facing the direction of scroll (i.e. the edge that animates
offscreen first during scrolling).
Defaults to `0`.
- Note: The value set to this property affects label positioning at all times (including when `labelize` is set to `true`),
including when the text string length is short enough that the label does not need to scroll.
- Note: For Continuous-type labels, the smallest value of `leadingBuffer`, `trailingBuffer`, and `fadeLength`
is used as spacing between the two label instances. Zero is an allowable value for all three properties.
- SeeAlso: trailingBuffer
*/
@IBInspectable public var leadingBuffer: CGFloat = 0.0 {
didSet {
if leadingBuffer != oldValue {
updateAndScroll()
}
}
}
/**
A buffer (offset) between the trailing edge of the label text and the label frame.
This property adds additional space (buffer) between the trailing edge of the label text and the label frame. The
trailing edge is the edge of the label text facing away from the direction of scroll (i.e. the edge that animates
offscreen last during scrolling).
Defaults to `0`.
- Note: The value set to this property has no effect when the `labelize` property is set to `true`.
- Note: For Continuous-type labels, the smallest value of `leadingBuffer`, `trailingBuffer`, and `fadeLength`
is used as spacing between the two label instances. Zero is an allowable value for all three properties.
- SeeAlso: leadingBuffer
*/
@IBInspectable public var trailingBuffer: CGFloat = 0.0 {
didSet {
if trailingBuffer != oldValue {
updateAndScroll()
}
}
}
/**
The length of transparency fade at the left and right edges of the frame.
This propery sets the size (in points) of the view edge transparency fades on the left and right edges of a `MarqueeLabel`. The
transparency fades from an alpha of 1.0 (fully visible) to 0.0 (fully transparent) over this distance. Values set to this property
will be sanitized to prevent a fade length greater than 1/2 of the frame width.
Defaults to `0`.
*/
@IBInspectable public var fadeLength: CGFloat = 0.0 {
didSet {
if fadeLength != oldValue {
applyGradientMask(fadeLength, animated: true)
updateAndScroll()
}
}
}
/**
The length of delay in seconds that the label pauses at the completion of a scroll.
*/
@IBInspectable public var animationDelay: CGFloat = 1.0
//
// MARK: - Class Functions and Helpers
//
/**
Convenience method to restart all `MarqueeLabel` instances that have the specified view controller in their next responder chain.
- Parameter controller: The view controller for which to restart all `MarqueeLabel` instances.
- Warning: View controllers that appear with animation (such as from underneath a modal-style controller) can cause some `MarqueeLabel` text
position "jumping" when this method is used in `viewDidAppear` if scroll animations are already underway. Use this method inside `viewWillAppear:`
instead to avoid this problem.
- Warning: This method may not function properly if passed the parent view controller when using view controller containment.
- SeeAlso: restartLabel
- SeeAlso: controllerViewDidAppear:
- SeeAlso: controllerViewWillAppear:
*/
class func restartLabelsOfController(controller: UIViewController) {
MarqueeLabel.notifyController(controller, message: .Restart)
}
/**
Convenience method to restart all `MarqueeLabel` instances that have the specified view controller in their next responder chain.
Alternative to `restartLabelsOfController`. This method is retained for backwards compatibility and future enhancements.
- Parameter controller: The view controller that will appear.
- SeeAlso: restartLabel
- SeeAlso: controllerViewDidAppear
*/
class func controllerViewWillAppear(controller: UIViewController) {
MarqueeLabel.restartLabelsOfController(controller)
}
/**
Convenience method to restart all `MarqueeLabel` instances that have the specified view controller in their next responder chain.
Alternative to `restartLabelsOfController`. This method is retained for backwards compatibility and future enhancements.
- Parameter controller: The view controller that did appear.
- SeeAlso: restartLabel
- SeeAlso: controllerViewWillAppear
*/
class func controllerViewDidAppear(controller: UIViewController) {
MarqueeLabel.restartLabelsOfController(controller)
}
/**
Labelizes all `MarqueeLabel` instances that have the specified view controller in their next responder chain.
The `labelize` property of all recognized `MarqueeLabel` instances will be set to `true`.
- Parameter controller: The view controller for which all `MarqueeLabel` instances should be labelized.
- SeeAlso: labelize
*/
class func controllerLabelsLabelize(controller: UIViewController) {
MarqueeLabel.notifyController(controller, message: .Labelize)
}
/**
De-labelizes all `MarqueeLabel` instances that have the specified view controller in their next responder chain.
The `labelize` property of all recognized `MarqueeLabel` instances will be set to `false`.
- Parameter controller: The view controller for which all `MarqueeLabel` instances should be de-labelized.
- SeeAlso: labelize
*/
class func controllerLabelsAnimate(controller: UIViewController) {
MarqueeLabel.notifyController(controller, message: .Animate)
}
//
// MARK: - Initialization
//
/**
Returns a newly initialized `MarqueeLabel` instance with the specified scroll rate and edge transparency fade length.
- Parameter frame: A rectangle specifying the initial location and size of the view in its superview's coordinates. Text (for the given font, font size, etc.) that does not fit in this frame will automatically scroll.
- Parameter pixelsPerSec: A rate of scroll for the label scroll animation. Must be non-zero. Note that this will be the peak (mid-transition) rate for ease-type animation.
- Parameter fadeLength: A length of transparency fade at the left and right edges of the `MarqueeLabel` instance's frame.
- Returns: An initialized `MarqueeLabel` object or nil if the object couldn't be created.
- SeeAlso: fadeLength
*/
init(frame: CGRect, rate: CGFloat, fadeLength fade: CGFloat) {
speed = .Rate(rate)
fadeLength = CGFloat(min(fade, frame.size.width/2.0))
super.init(frame: frame)
setup()
}
/**
Returns a newly initialized `MarqueeLabel` instance with the specified scroll rate and edge transparency fade length.
- Parameter frame: A rectangle specifying the initial location and size of the view in its superview's coordinates. Text (for the given font, font size, etc.) that does not fit in this frame will automatically scroll.
- Parameter scrollDuration: A scroll duration the label scroll animation. Must be non-zero. This will be the duration that the animation takes for one-half of the scroll cycle in the case of left-right and right-left marquee types, and for one loop of a continuous marquee type.
- Parameter fadeLength: A length of transparency fade at the left and right edges of the `MarqueeLabel` instance's frame.
- Returns: An initialized `MarqueeLabel` object or nil if the object couldn't be created.
- SeeAlso: fadeLength
*/
init(frame: CGRect, duration: CGFloat, fadeLength fade: CGFloat) {
speed = .Duration(duration)
fadeLength = CGFloat(min(fade, frame.size.width/2.0))
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
/**
Returns a newly initialized `MarqueeLabel` instance.
The default scroll duration of 7.0 seconds and fade length of 0.0 are used.
- Parameter frame: A rectangle specifying the initial location and size of the view in its superview's coordinates. Text (for the given font, font size, etc.) that does not fit in this frame will automatically scroll.
- Returns: An initialized `MarqueeLabel` object or nil if the object couldn't be created.
*/
convenience public override init(frame: CGRect) {
self.init(frame: frame, duration:7.0, fadeLength:0.0)
}
private func setup() {
// Create sublabel
sublabel = UILabel(frame: self.bounds)
sublabel.tag = 700
sublabel.layer.anchorPoint = CGPoint.zero
// Add sublabel
addSubview(sublabel)
// Configure self
super.clipsToBounds = true
super.numberOfLines = 1
// Add notification observers
// Custom class notifications
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MarqueeLabel.restartForViewController(_:)), name: MarqueeKeys.Restart.rawValue, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MarqueeLabel.labelizeForController(_:)), name: MarqueeKeys.Labelize.rawValue, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MarqueeLabel.animateForController(_:)), name: MarqueeKeys.Animate.rawValue, object: nil)
// UIApplication state notifications
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MarqueeLabel.restartLabel), name: UIApplicationDidBecomeActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MarqueeLabel.shutdownLabel), name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
override public func awakeFromNib() {
super.awakeFromNib()
forwardPropertiesToSublabel()
}
private func forwardPropertiesToSublabel() {
/*
Note that this method is currently ONLY called from awakeFromNib, i.e. when
text properties are set via a Storyboard. As the Storyboard/IB doesn't currently
support attributed strings, there's no need to "forward" the super attributedString value.
*/
// Since we're a UILabel, we actually do implement all of UILabel's properties.
// We don't care about these values, we just want to forward them on to our sublabel.
let properties = ["baselineAdjustment", "enabled", "highlighted", "highlightedTextColor",
"minimumFontSize", "shadowOffset", "textAlignment",
"userInteractionEnabled", "adjustsFontSizeToFitWidth",
"lineBreakMode", "numberOfLines"]
// Iterate through properties
sublabel.text = super.text
sublabel.font = super.font
sublabel.textColor = super.textColor
sublabel.backgroundColor = super.backgroundColor ?? UIColor.clearColor()
sublabel.shadowColor = super.shadowColor
sublabel.shadowOffset = super.shadowOffset
for prop in properties {
let value: AnyObject! = super.valueForKey(prop)
sublabel.setValue(value, forKeyPath: prop)
}
}
//
// MARK: - MarqueeLabel Heavy Lifting
//
override public func layoutSubviews() {
super.layoutSubviews()
updateAndScroll(true)
}
override public func willMoveToWindow(newWindow: UIWindow?) {
if newWindow == nil {
shutdownLabel()
}
}
override public func didMoveToWindow() {
if self.window == nil {
shutdownLabel()
} else {
updateAndScroll()
}
}
private func updateAndScroll() {
updateAndScroll(true)
}
private func updateAndScroll(shouldBeginScroll: Bool) {
// Check if scrolling can occur
if !labelReadyForScroll() {
return
}
// Calculate expected size
let expectedLabelSize = sublabelSize()
// Invalidate intrinsic size
invalidateIntrinsicContentSize()
// Move label to home
returnLabelToHome()
// Check if label should scroll
// Note that the holdScrolling propery does not affect this
if !labelShouldScroll() {
// Set text alignment and break mode to act like a normal label
sublabel.textAlignment = super.textAlignment
sublabel.lineBreakMode = super.lineBreakMode
var unusedFrame = CGRect.zero
var labelFrame = CGRect.zero
switch type {
case .ContinuousReverse, .RightLeft:
CGRectDivide(bounds, &unusedFrame, &labelFrame, leadingBuffer, CGRectEdge.MaxXEdge)
labelFrame = CGRectIntegral(labelFrame)
default:
labelFrame = CGRectIntegral(CGRectMake(leadingBuffer, 0.0, bounds.size.width - leadingBuffer, bounds.size.height))
}
homeLabelFrame = labelFrame
awayOffset = 0.0
// Remove an additional sublabels (for continuous types)
repliLayer.instanceCount = 1;
// Set the sublabel frame to calculated labelFrame
sublabel.frame = labelFrame
// Configure fade
applyGradientMask(fadeLength, animated: !labelize)
return
}
// Label DOES need to scroll
// Spacing between primary and second sublabel must be at least equal to leadingBuffer, and at least equal to the fadeLength
let minTrailing = max(max(leadingBuffer, trailingBuffer), fadeLength)
switch type {
case .Continuous, .ContinuousReverse:
if (type == .Continuous) {
homeLabelFrame = CGRectIntegral(CGRectMake(leadingBuffer, 0.0, expectedLabelSize.width, bounds.size.height))
awayOffset = -(homeLabelFrame.size.width + minTrailing)
} else { // .ContinuousReverse
homeLabelFrame = CGRectIntegral(CGRectMake(bounds.size.width - (expectedLabelSize.width + leadingBuffer), 0.0, expectedLabelSize.width, bounds.size.height))
awayOffset = (homeLabelFrame.size.width + minTrailing)
}
// Set frame and text
sublabel.frame = homeLabelFrame
// Configure replication
repliLayer.instanceCount = 2
repliLayer.instanceTransform = CATransform3DMakeTranslation(-awayOffset, 0.0, 0.0)
case .RightLeft:
homeLabelFrame = CGRectIntegral(CGRectMake(bounds.size.width - (expectedLabelSize.width + leadingBuffer), 0.0, expectedLabelSize.width, bounds.size.height))
awayOffset = (expectedLabelSize.width + trailingBuffer + leadingBuffer) - bounds.size.width
// Set frame and text
sublabel.frame = homeLabelFrame
// Remove any replication
repliLayer.instanceCount = 1
// Enforce text alignment for this type
sublabel.textAlignment = NSTextAlignment.Right
case .LeftRight:
homeLabelFrame = CGRectIntegral(CGRectMake(leadingBuffer, 0.0, expectedLabelSize.width, expectedLabelSize.height))
awayOffset = bounds.size.width - (expectedLabelSize.width + leadingBuffer + trailingBuffer)
// Set frame and text
sublabel.frame = homeLabelFrame
// Remove any replication
self.repliLayer.instanceCount = 1
// Enforce text alignment for this type
sublabel.textAlignment = NSTextAlignment.Left
// Default case not required
}
// Recompute the animation duration
animationDuration = {
switch self.speed {
case .Rate(let rate):
return CGFloat(fabs(self.awayOffset) / rate)
case .Duration(let duration):
return duration
}
}()
// Configure gradient for current condition
applyGradientMask(fadeLength, animated: !self.labelize)
if !tapToScroll && !holdScrolling && shouldBeginScroll {
beginScroll()
}
}
func sublabelSize() -> CGSize {
// Bound the expected size
let maximumLabelSize = CGSizeMake(CGFloat.max, CGFloat.max)
// Calculate the expected size
var expectedLabelSize = sublabel.sizeThatFits(maximumLabelSize)
// Sanitize width to 5461.0 (largest width a UILabel will draw on an iPhone 6S Plus)
expectedLabelSize.width = min(expectedLabelSize.width, 5461.0)
// Adjust to own height (make text baseline match normal label)
expectedLabelSize.height = bounds.size.height
return expectedLabelSize
}
override public func sizeThatFits(size: CGSize) -> CGSize {
var fitSize = sublabel.sizeThatFits(size)
fitSize.width += leadingBuffer
return fitSize
}
//
// MARK: - Animation Handling
//
private func labelShouldScroll() -> Bool {
// Check for nil string
if sublabel.text == nil {
return false
}
// Check for empty string
if sublabel.text!.isEmpty {
return false
}
// Check if the label string fits
let labelTooLarge = (sublabelSize().width + leadingBuffer) > self.bounds.size.width
let animationHasDuration = speed.value > 0.0
return (!labelize && labelTooLarge && animationHasDuration)
}
private func labelReadyForScroll() -> Bool {
// Check if we have a superview
if superview == nil {
return false
}
// Check if we are attached to a window
if window == nil {
return false
}
// Check if our view controller is ready
let viewController = firstAvailableViewController()
if viewController != nil {
if !viewController!.isViewLoaded() {
return false
}
}
return true
}
private func beginScroll() {
beginScroll(true)
}
private func beginScroll(delay: Bool) {
switch self.type {
case .LeftRight, .RightLeft:
scrollAway(animationDuration, delay: animationDelay)
default:
scrollContinuous(animationDuration, delay: animationDelay)
}
}
private func returnLabelToHome() {
// Remove any gradient animation
maskLayer?.removeAllAnimations()
// Remove all sublabel position animations
sublabel.layer.removeAllAnimations()
}
// Define animation completion closure type
private typealias MLAnimationCompletion = (finished: Bool) -> ()
private func scroll(interval: CGFloat, delay: CGFloat = 0.0, scroller: Scroller, fader: CAKeyframeAnimation?) {
var scroller = scroller
// Check for conditions which would prevent scrolling
if !labelReadyForScroll() {
return
}
// Call pre-animation hook
labelWillBeginScroll()
// Start animation transactions
CATransaction.begin()
let transDuration = transactionDurationType(type, interval: interval, delay: delay)
CATransaction.setAnimationDuration(transDuration)
// Create gradient animation, if needed
let gradientAnimation: CAKeyframeAnimation?
if fadeLength > 0.0 {
// Remove any setup animation, but apply final values
if let setupAnim = maskLayer?.animationForKey("setupFade") as? CABasicAnimation, finalColors = setupAnim.toValue as? [CGColorRef] {
maskLayer?.colors = finalColors
}
maskLayer?.removeAnimationForKey("setupFade")
// Generate animation if needed
if let previousAnimation = fader {
gradientAnimation = previousAnimation
} else {
gradientAnimation = keyFrameAnimationForGradient(fadeLength, interval: interval, delay: delay)
}
// Apply scrolling animation
maskLayer?.addAnimation(gradientAnimation!, forKey: "gradient")
} else {
// No animation needed
gradientAnimation = nil
}
let completion = CompletionBlock<MLAnimationCompletion>({ (finished: Bool) -> () in
guard finished else {
// Do not continue into the next loop
return
}
// Call returned home function
self.labelReturnedToHome(true)
// Check to ensure that:
// 1) We don't double fire if an animation already exists
// 2) The instance is still attached to a window - this completion block is called for
// many reasons, including if the animation is removed due to the view being removed
// from the UIWindow (typically when the view controller is no longer the "top" view)
guard self.window != nil else {
return
}
guard self.sublabel.layer.animationForKey("position") == nil else {
return
}
// Begin again, if conditions met
if (self.labelShouldScroll() && !self.tapToScroll && !self.holdScrolling) {
// Perform completion callback
self.scroll(interval, delay: delay, scroller: scroller, fader: gradientAnimation)
}
})
// Call scroller
let scrolls = scroller.generate(interval, delay: delay)
// Perform all animations in scrolls
for (index, scroll) in scrolls.enumerate() {
let layer = scroll.layer
let anim = scroll.anim
// Add callback to single animation
if index == 0 {
anim.setValue(completion as AnyObject, forKey: MarqueeKeys.CompletionClosure.rawValue)
anim.delegate = self
}
// Add animation
layer.addAnimation(anim, forKey: "position")
}
CATransaction.commit()
}
private func scrollAway(interval: CGFloat, delay: CGFloat = 0.0) {
// Create scroller, which defines the animation to perform
let homeOrigin = homeLabelFrame.origin
let awayOrigin = offsetCGPoint(homeLabelFrame.origin, offset: awayOffset)
let scroller = Scroller(generator: {(interval: CGFloat, delay: CGFloat) -> [(layer: CALayer, anim: CAKeyframeAnimation)] in
// Create animation for position
let values: [NSValue] = [
NSValue(CGPoint: homeOrigin), // Start at home
NSValue(CGPoint: homeOrigin), // Stay at home for delay
NSValue(CGPoint: awayOrigin), // Move to away
NSValue(CGPoint: awayOrigin), // Stay at away for delay
NSValue(CGPoint: homeOrigin) // Move back to home
]
let layer = self.sublabel.layer
let anim = self.keyFrameAnimationForProperty("position", values: values, interval: interval, delay: delay)
return [(layer: layer, anim: anim)]
})
// Scroll
scroll(interval, delay: delay, scroller: scroller, fader: nil)
}
private func scrollContinuous(interval: CGFloat, delay: CGFloat) {
// Create scroller, which defines the animation to perform
let homeOrigin = homeLabelFrame.origin
let awayOrigin = offsetCGPoint(homeLabelFrame.origin, offset: awayOffset)
let scroller = Scroller(generator: { (interval: CGFloat, delay: CGFloat) -> [(layer: CALayer, anim: CAKeyframeAnimation)] in
// Create animation for position
let values: [NSValue] = [
NSValue(CGPoint: homeOrigin), // Start at home
NSValue(CGPoint: homeOrigin), // Stay at home for delay
NSValue(CGPoint: awayOrigin) // Move to away
]
// Generate animation
let layer = self.sublabel.layer
let anim = self.keyFrameAnimationForProperty("position", values: values, interval: interval, delay: delay)
return [(layer: layer, anim: anim)]
})
// Scroll
scroll(interval, delay: delay, scroller: scroller, fader: nil)
}
private func applyGradientMask(fadeLength: CGFloat, animated: Bool) {
// Remove any in-flight animations
maskLayer?.removeAllAnimations()
// Check for zero-length fade
if (fadeLength <= 0.0) {
removeGradientMask()
return
}
// Configure gradient mask without implicit animations
CATransaction.begin()
CATransaction.setDisableActions(true)
// Determine if gradient mask needs to be created
let gradientMask: CAGradientLayer
if let currentMask = self.maskLayer {
// Mask layer already configured
gradientMask = currentMask
} else {
// No mask exists, create new mask
gradientMask = CAGradientLayer()
gradientMask.shouldRasterize = true
gradientMask.rasterizationScale = UIScreen.mainScreen().scale
gradientMask.startPoint = CGPointMake(0.0, 0.5)
gradientMask.endPoint = CGPointMake(1.0, 0.5)
// Adjust stops based on fade length
let leftFadeStop = fadeLength/self.bounds.size.width
let rightFadeStop = fadeLength/self.bounds.size.width
gradientMask.locations = [0.0, leftFadeStop, (1.0 - rightFadeStop), 1.0]
}
// Set up colors
let transparent = UIColor.clearColor().CGColor
let opaque = UIColor.blackColor().CGColor
// Set mask
self.layer.mask = gradientMask
gradientMask.bounds = self.layer.bounds
gradientMask.position = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds))
// Determine colors for non-scrolling label (i.e. at home)
let adjustedColors: [CGColorRef]
let trailingFadeNeeded = self.labelShouldScroll()
switch (type) {
case .ContinuousReverse, .RightLeft:
adjustedColors = [(trailingFadeNeeded ? transparent : opaque), opaque, opaque, opaque]
// .MLContinuous, .MLLeftRight
default:
adjustedColors = [opaque, opaque, opaque, (trailingFadeNeeded ? transparent : opaque)]
break
}
if (animated) {
// Finish transaction
CATransaction.commit()
// Create animation for color change
let colorAnimation = GradientAnimation(keyPath: "colors")
colorAnimation.fromValue = gradientMask.colors
colorAnimation.toValue = adjustedColors
colorAnimation.fillMode = kCAFillModeForwards
colorAnimation.removedOnCompletion = false
colorAnimation.delegate = self
gradientMask.addAnimation(colorAnimation, forKey: "setupFade")
} else {
gradientMask.colors = adjustedColors
CATransaction.commit()
}
}
private func removeGradientMask() {
self.layer.mask = nil
}
private func keyFrameAnimationForGradient(fadeLength: CGFloat, interval: CGFloat, delay: CGFloat) -> CAKeyframeAnimation {
// Setup
let values: [[CGColorRef]]
let keyTimes: [CGFloat]
let transp = UIColor.clearColor().CGColor
let opaque = UIColor.blackColor().CGColor
// Create new animation
let animation = CAKeyframeAnimation(keyPath: "colors")
// Get timing function
let timingFunction = timingFunctionForAnimationCurve(animationCurve)
// Define keyTimes
switch (type) {
case .LeftRight, .RightLeft:
// Calculate total animation duration
let totalDuration = 2.0 * (delay + interval)
keyTimes =
[
0.0, // 1) Initial gradient
delay/totalDuration, // 2) Begin of LE fade-in, just as scroll away starts
(delay + 0.4)/totalDuration, // 3) End of LE fade in [LE fully faded]
(delay + interval - 0.4)/totalDuration, // 4) Begin of TE fade out, just before scroll away finishes
(delay + interval)/totalDuration, // 5) End of TE fade out [TE fade removed]
(delay + interval + delay)/totalDuration, // 6) Begin of TE fade back in, just as scroll home starts
(delay + interval + delay + 0.4)/totalDuration, // 7) End of TE fade back in [TE fully faded]
(totalDuration - 0.4)/totalDuration, // 8) Begin of LE fade out, just before scroll home finishes
1.0 // 9) End of LE fade out, just as scroll home finishes
]
// .MLContinuous, .MLContinuousReverse
default:
// Calculate total animation duration
let totalDuration = delay + interval
// Find when the lead label will be totally offscreen
let offsetDistance = awayOffset
let startFadeFraction = fabs((sublabel.bounds.size.width + leadingBuffer) / offsetDistance)
// Find when the animation will hit that point
let startFadeTimeFraction = timingFunction.durationPercentageForPositionPercentage(startFadeFraction, duration: totalDuration)
let startFadeTime = delay + CGFloat(startFadeTimeFraction) * interval
keyTimes = [
0.0, // Initial gradient
delay/totalDuration, // Begin of fade in
(delay + 0.2)/totalDuration, // End of fade in, just as scroll away starts
startFadeTime/totalDuration, // Begin of fade out, just before scroll home completes
(startFadeTime + 0.1)/totalDuration, // End of fade out, as scroll home completes
1.0 // Buffer final value (used on continuous types)
]
break
}
// Define values
// Get current layer values
let mask = maskLayer?.presentationLayer() as? CAGradientLayer
let currentValues = mask?.colors as? [CGColorRef]
switch (type) {
case .ContinuousReverse:
values = [
currentValues ?? [transp, opaque, opaque, opaque], // Initial gradient
[transp, opaque, opaque, opaque], // Begin of fade in
[transp, opaque, opaque, transp], // End of fade in, just as scroll away starts
[transp, opaque, opaque, transp], // Begin of fade out, just before scroll home completes
[transp, opaque, opaque, opaque], // End of fade out, as scroll home completes
[transp, opaque, opaque, opaque] // Final "home" value
]
break
case .RightLeft:
values = [
currentValues ?? [transp, opaque, opaque, opaque], // 1)
[transp, opaque, opaque, opaque], // 2)
[transp, opaque, opaque, transp], // 3)
[transp, opaque, opaque, transp], // 4)
[opaque, opaque, opaque, transp], // 5)
[opaque, opaque, opaque, transp], // 6)
[transp, opaque, opaque, transp], // 7)
[transp, opaque, opaque, transp], // 8)
[transp, opaque, opaque, opaque] // 9)
]
break
case .Continuous:
values = [
currentValues ?? [opaque, opaque, opaque, transp], // Initial gradient
[opaque, opaque, opaque, transp], // Begin of fade in
[transp, opaque, opaque, transp], // End of fade in, just as scroll away starts
[transp, opaque, opaque, transp], // Begin of fade out, just before scroll home completes
[opaque, opaque, opaque, transp], // End of fade out, as scroll home completes
[opaque, opaque, opaque, transp] // Final "home" value
]
break
case .LeftRight:
values = [
currentValues ?? [opaque, opaque, opaque, transp], // 1)
[opaque, opaque, opaque, transp], // 2)
[transp, opaque, opaque, transp], // 3)
[transp, opaque, opaque, transp], // 4)
[transp, opaque, opaque, opaque], // 5)
[transp, opaque, opaque, opaque], // 6)
[transp, opaque, opaque, transp], // 7)
[transp, opaque, opaque, transp], // 8)
[opaque, opaque, opaque, transp] // 9)
]
break
}
animation.values = values
animation.keyTimes = keyTimes
animation.timingFunctions = [timingFunction, timingFunction, timingFunction, timingFunction]
return animation
}
private func keyFrameAnimationForProperty(property: String, values: [NSValue], interval: CGFloat, delay: CGFloat) -> CAKeyframeAnimation {
// Create new animation
let animation = CAKeyframeAnimation(keyPath: property)
// Get timing function
let timingFunction = timingFunctionForAnimationCurve(animationCurve)
// Calculate times based on marqueeType
let totalDuration: CGFloat
switch (type) {
case .LeftRight, .RightLeft:
//NSAssert(values.count == 5, @"Incorrect number of values passed for MLLeftRight-type animation")
totalDuration = 2.0 * (delay + interval)
// Set up keyTimes
animation.keyTimes = [
0.0, // Initial location, home
delay/totalDuration, // Initial delay, at home
(delay + interval)/totalDuration, // Animation to away
(delay + interval + delay)/totalDuration, // Delay at away
1.0 // Animation to home
]
animation.timingFunctions = [
timingFunction,
timingFunction,
timingFunction,
timingFunction
]
// .Continuous
// .ContinuousReverse
default:
//NSAssert(values.count == 3, @"Incorrect number of values passed for MLContinous-type animation")
totalDuration = delay + interval
// Set up keyTimes
animation.keyTimes = [
0.0, // Initial location, home
delay/totalDuration, // Initial delay, at home
1.0 // Animation to away
]
animation.timingFunctions = [
timingFunction,
timingFunction
]
}
// Set values
animation.values = values
return animation
}
private func timingFunctionForAnimationCurve(curve: UIViewAnimationCurve) -> CAMediaTimingFunction {
let timingFunction: String?
switch curve {
case .EaseIn:
timingFunction = kCAMediaTimingFunctionEaseIn
case .EaseInOut:
timingFunction = kCAMediaTimingFunctionEaseInEaseOut
case .EaseOut:
timingFunction = kCAMediaTimingFunctionEaseOut
default:
timingFunction = kCAMediaTimingFunctionLinear
}
return CAMediaTimingFunction(name: timingFunction!)
}
private func transactionDurationType(labelType: Type, interval: CGFloat, delay: CGFloat) -> NSTimeInterval {
switch (labelType) {
case .LeftRight, .RightLeft:
return NSTimeInterval(2.0 * (delay + interval))
default:
return NSTimeInterval(delay + interval)
}
}
override public func animationDidStop(anim: CAAnimation, finished flag: Bool) {
if anim is GradientAnimation {
if let setupAnim = maskLayer?.animationForKey("setupFade") as? CABasicAnimation, finalColors = setupAnim.toValue as? [CGColorRef] {
maskLayer?.colors = finalColors
}
// Remove regardless, since we set removeOnCompletion = false
maskLayer?.removeAnimationForKey("setupFade")
} else {
let completion = anim.valueForKey(MarqueeKeys.CompletionClosure.rawValue) as? CompletionBlock<MLAnimationCompletion>
completion?.f(finished: flag)
}
}
//
// MARK: - Private details
//
private var sublabel = UILabel()
private var animationDuration: CGFloat = 0.0
private var homeLabelFrame = CGRect.zero
private var awayOffset: CGFloat = 0.0
override public class func layerClass() -> AnyClass {
return CAReplicatorLayer.self
}
private var repliLayer: CAReplicatorLayer {
return self.layer as! CAReplicatorLayer
}
private var maskLayer: CAGradientLayer? {
return self.layer.mask as! CAGradientLayer?
}
override public func drawLayer(layer: CALayer, inContext ctx: CGContext) {
// Do NOT call super, to prevent UILabel superclass from drawing into context
// Label drawing is handled by sublabel and CAReplicatorLayer layer class
// Draw only background color
if let bgColor = backgroundColor {
CGContextSetFillColorWithColor(ctx, bgColor.CGColor);
CGContextFillRect(ctx, layer.bounds);
}
}
private enum MarqueeKeys: String {
case Restart = "MLViewControllerRestart"
case Labelize = "MLShouldLabelize"
case Animate = "MLShouldAnimate"
case CompletionClosure = "MLAnimationCompletion"
}
class private func notifyController(controller: UIViewController, message: MarqueeKeys) {
NSNotificationCenter.defaultCenter().postNotificationName(message.rawValue, object: nil, userInfo: ["controller" : controller])
}
public func restartForViewController(notification: NSNotification) {
if let controller = notification.userInfo?["controller"] as? UIViewController {
if controller === self.firstAvailableViewController() {
self.restartLabel()
}
}
}
public func labelizeForController(notification: NSNotification) {
if let controller = notification.userInfo?["controller"] as? UIViewController {
if controller === self.firstAvailableViewController() {
self.labelize = true
}
}
}
public func animateForController(notification: NSNotification) {
if let controller = notification.userInfo?["controller"] as? UIViewController {
if controller === self.firstAvailableViewController() {
self.labelize = false
}
}
}
//
// MARK: - Label Control
//
/**
Overrides any non-size condition which is preventing the receiver from automatically scrolling, and begins a scroll animation.
Currently the only non-size conditions which can prevent a label from scrolling are the `tapToScroll` and `holdScrolling` properties. This
method will not force a label with a string that fits inside the label bounds (i.e. that would not automatically scroll) to begin a scroll
animation.
Upon the completion of the first forced scroll animation, the receiver will not automatically continue to scroll unless the conditions
preventing scrolling have been removed.
- Note: This method has no effect if called during an already in-flight scroll animation.
- SeeAlso: restartLabel
*/
public func triggerScrollStart() {
if labelShouldScroll() && !awayFromHome {
beginScroll()
}
}
/**
Immediately resets the label to the home position, cancelling any in-flight scroll animation, and restarts the scroll animation if the appropriate conditions are met.
- SeeAlso: resetLabel
- SeeAlso: triggerScrollStart
*/
public func restartLabel() {
// Shutdown the label
shutdownLabel()
// Restart scrolling if appropriate
if labelShouldScroll() && !tapToScroll && !holdScrolling {
beginScroll()
}
}
/**
Resets the label text, recalculating the scroll animation.
The text is immediately returned to the home position, and the scroll animation positions are cleared. Scrolling will not resume automatically after
a call to this method. To re-initiate scrolling, use either a call to `restartLabel` or make a change to a UILabel property such as text, bounds/frame,
font, font size, etc.
- SeeAlso: restartLabel
*/
public func resetLabel() {
returnLabelToHome()
homeLabelFrame = CGRect.null
awayOffset = 0.0
}
/**
Immediately resets the label to the home position, cancelling any in-flight scroll animation.
The text is immediately returned to the home position. Scrolling will not resume automatically after a call to this method.
To re-initiate scrolling use a call to `restartLabel` or `triggerScrollStart`, or make a change to a UILabel property such as text, bounds/frame,
font, font size, etc.
- SeeAlso: restartLabel
- SeeAlso: triggerScrollStart
*/
public func shutdownLabel() {
// Bring label to home location
returnLabelToHome()
// Apply gradient mask for home location
applyGradientMask(fadeLength, animated: false)
}
/**
Pauses the text scrolling animation, at any point during an in-progress animation.
- Note: This method has no effect if a scroll animation is NOT already in progress. To prevent automatic scrolling on a newly-initialized label prior to its presentation onscreen, see the `holdScrolling` property.
- SeeAlso: holdScrolling
- SeeAlso: unpauseLabel
*/
public func pauseLabel() {
// Prevent pausing label while not in scrolling animation, or when already paused
guard (!isPaused && awayFromHome) else {
return
}
// Pause sublabel position animations
let labelPauseTime = sublabel.layer.convertTime(CACurrentMediaTime(), fromLayer: nil)
sublabel.layer.speed = 0.0
sublabel.layer.timeOffset = labelPauseTime
// Pause gradient fade animation
let gradientPauseTime = maskLayer?.convertTime(CACurrentMediaTime(), fromLayer:nil)
maskLayer?.speed = 0.0
maskLayer?.timeOffset = gradientPauseTime!
}
/**
Un-pauses a previously paused text scrolling animation. This method has no effect if the label was not previously paused using `pauseLabel`.
- SeeAlso: pauseLabel
*/
public func unpauseLabel() {
// Only unpause if label was previously paused
guard (isPaused) else {
return
}
// Unpause sublabel position animations
let labelPausedTime = sublabel.layer.timeOffset
sublabel.layer.speed = 1.0
sublabel.layer.timeOffset = 0.0
sublabel.layer.beginTime = 0.0
sublabel.layer.beginTime = sublabel.layer.convertTime(CACurrentMediaTime(), fromLayer:nil) - labelPausedTime
// Unpause gradient fade animation
let gradientPauseTime = maskLayer?.timeOffset
maskLayer?.speed = 1.0
maskLayer?.timeOffset = 0.0
maskLayer?.beginTime = 0.0
maskLayer?.beginTime = maskLayer!.convertTime(CACurrentMediaTime(), fromLayer:nil) - gradientPauseTime!
}
public func labelWasTapped(recognizer: UIGestureRecognizer) {
if labelShouldScroll() && !awayFromHome {
beginScroll(true)
}
}
/**
Called when the label animation is about to begin.
The default implementation of this method does nothing. Subclasses may override this method in order to perform any custom actions just as
the label animation begins. This is only called in the event that the conditions for scrolling to begin are met.
*/
public func labelWillBeginScroll() {
// Default implementation does nothing - override to customize
return
}
/**
Called when the label animation has finished, and the label is at the home position.
The default implementation of this method does nothing. Subclasses may override this method in order to perform any custom actions jas as
the label animation completes, and before the next animation would begin (assuming the scroll conditions are met).
- Parameter finished: A Boolean that indicates whether or not the scroll animation actually finished before the completion handler was called.
- Warning: This method will be called, and the `finished` parameter will be `NO`, when any property changes are made that would cause the label
scrolling to be automatically reset. This includes changes to label text and font/font size changes.
*/
public func labelReturnedToHome(finished: Bool) {
// Default implementation does nothing - override to customize
return
}
//
// MARK: - Modified UILabel Functions/Getters/Setters
//
#if os(iOS)
override public func viewForBaselineLayout() -> UIView {
// Use subLabel view for handling baseline layouts
return sublabel
}
public override var viewForLastBaselineLayout: UIView {
// Use subLabel view for handling baseline layouts
return sublabel
}
#endif
public override var text: String? {
get {
return sublabel.text
}
set {
if sublabel.text == newValue {
return
}
sublabel.text = newValue
updateAndScroll()
super.text = text
}
}
public override var attributedText: NSAttributedString? {
get {
return sublabel.attributedText
}
set {
if sublabel.attributedText == newValue {
return
}
sublabel.attributedText = newValue
updateAndScroll()
super.attributedText = attributedText
}
}
public override var font: UIFont! {
get {
return sublabel.font
}
set {
if sublabel.font == newValue {
return
}
sublabel.font = newValue
super.font = newValue
updateAndScroll()
}
}
public override var textColor: UIColor! {
get {
return sublabel.textColor
}
set {
sublabel.textColor = newValue
super.textColor = newValue
}
}
public override var backgroundColor: UIColor? {
get {
return sublabel.backgroundColor
}
set {
sublabel.backgroundColor = newValue
super.backgroundColor = newValue
}
}
public override var shadowColor: UIColor? {
get {
return sublabel.shadowColor
}
set {
sublabel.shadowColor = newValue
super.shadowColor = newValue
}
}
public override var shadowOffset: CGSize {
get {
return sublabel.shadowOffset
}
set {
sublabel.shadowOffset = newValue
super.shadowOffset = newValue
}
}
public override var highlightedTextColor: UIColor? {
get {
return sublabel.highlightedTextColor
}
set {
sublabel.highlightedTextColor = newValue
super.highlightedTextColor = newValue
}
}
public override var highlighted: Bool {
get {
return sublabel.highlighted
}
set {
sublabel.highlighted = newValue
super.highlighted = newValue
}
}
public override var enabled: Bool {
get {
return sublabel.enabled
}
set {
sublabel.enabled = newValue
super.enabled = newValue
}
}
public override var numberOfLines: Int {
get {
return super.numberOfLines
}
set {
// By the nature of MarqueeLabel, this is 1
super.numberOfLines = 1
}
}
public override var adjustsFontSizeToFitWidth: Bool {
get {
return super.adjustsFontSizeToFitWidth
}
set {
// By the nature of MarqueeLabel, this is false
super.adjustsFontSizeToFitWidth = false
}
}
public override var minimumScaleFactor: CGFloat {
get {
return super.minimumScaleFactor
}
set {
super.minimumScaleFactor = 0.0
}
}
public override var baselineAdjustment: UIBaselineAdjustment {
get {
return sublabel.baselineAdjustment
}
set {
sublabel.baselineAdjustment = newValue
super.baselineAdjustment = newValue
}
}
public override func intrinsicContentSize() -> CGSize {
var content = sublabel.intrinsicContentSize()
content.width += leadingBuffer
return content
}
//
// MARK: - Support
//
private func offsetCGPoint(point: CGPoint, offset: CGFloat) -> CGPoint {
return CGPointMake(point.x + offset, point.y)
}
//
// MARK: - Deinit
//
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
//
// MARK: - Support
//
// Solution from: http://stackoverflow.com/a/24760061/580913
private class CompletionBlock<T> {
let f : T
init (_ f: T) { self.f = f }
}
private class GradientAnimation: CABasicAnimation {
}
private struct Scroller {
typealias Scroll = (layer: CALayer, anim: CAKeyframeAnimation)
init(generator gen: (interval: CGFloat, delay: CGFloat) -> [Scroll]) {
self.generator = gen
}
let generator: (interval: CGFloat, delay: CGFloat) -> [Scroll]
var scrolls: [Scroll]? = nil
mutating func generate(interval: CGFloat, delay: CGFloat) -> [Scroll] {
if let existing = scrolls {
return existing
} else {
scrolls = generator(interval: interval, delay: delay)
return scrolls!
}
}
}
private extension UIResponder {
// Thanks to Phil M
// http://stackoverflow.com/questions/1340434/get-to-uiviewcontroller-from-uiview-on-iphone
func firstAvailableViewController() -> UIViewController? {
// convenience function for casting and to "mask" the recursive function
return self.traverseResponderChainForFirstViewController()
}
func traverseResponderChainForFirstViewController() -> UIViewController? {
if let nextResponder = self.nextResponder() {
if nextResponder.isKindOfClass(UIViewController) {
return nextResponder as? UIViewController
} else if (nextResponder.isKindOfClass(UIView)) {
return nextResponder.traverseResponderChainForFirstViewController()
} else {
return nil
}
}
return nil
}
}
private extension CAMediaTimingFunction {
func durationPercentageForPositionPercentage(positionPercentage: CGFloat, duration: CGFloat) -> CGFloat {
// Finds the animation duration percentage that corresponds with the given animation "position" percentage.
// Utilizes Newton's Method to solve for the parametric Bezier curve that is used by CAMediaAnimation.
let controlPoints = self.controlPoints()
let epsilon: CGFloat = 1.0 / (100.0 * CGFloat(duration))
// Find the t value that gives the position percentage we want
let t_found = solveTforY(positionPercentage, epsilon: epsilon, controlPoints: controlPoints)
// With that t, find the corresponding animation percentage
let durationPercentage = XforCurveAt(t_found, controlPoints: controlPoints)
return durationPercentage
}
func solveTforY(y_0: CGFloat, epsilon: CGFloat, controlPoints: [CGPoint]) -> CGFloat {
// Use Newton's Method: http://en.wikipedia.org/wiki/Newton's_method
// For first guess, use t = y (i.e. if curve were linear)
var t0 = y_0
var t1 = y_0
var f0, df0: CGFloat
for _ in 0..<15 {
// Base this iteration of t1 calculated from last iteration
t0 = t1
// Calculate f(t0)
f0 = YforCurveAt(t0, controlPoints:controlPoints) - y_0
// Check if this is close (enough)
if (fabs(f0) < epsilon) {
// Done!
return t0
}
// Else continue Newton's Method
df0 = derivativeCurveYValueAt(t0, controlPoints:controlPoints)
// Check if derivative is small or zero ( http://en.wikipedia.org/wiki/Newton's_method#Failure_analysis )
if (fabs(df0) < 1e-6) {
break
}
// Else recalculate t1
t1 = t0 - f0/df0
}
// Give up - shouldn't ever get here...I hope
print("MarqueeLabel: Failed to find t for Y input!")
return t0
}
func YforCurveAt(t: CGFloat, controlPoints:[CGPoint]) -> CGFloat {
let P0 = controlPoints[0]
let P1 = controlPoints[1]
let P2 = controlPoints[2]
let P3 = controlPoints[3]
// Per http://en.wikipedia.org/wiki/Bezier_curve#Cubic_B.C3.A9zier_curves
let y0 = (pow((1.0 - t),3.0) * P0.y)
let y1 = (3.0 * pow(1.0 - t, 2.0) * t * P1.y)
let y2 = (3.0 * (1.0 - t) * pow(t, 2.0) * P2.y)
let y3 = (pow(t, 3.0) * P3.y)
return y0 + y1 + y2 + y3
}
func XforCurveAt(t: CGFloat, controlPoints: [CGPoint]) -> CGFloat {
let P0 = controlPoints[0]
let P1 = controlPoints[1]
let P2 = controlPoints[2]
let P3 = controlPoints[3]
// Per http://en.wikipedia.org/wiki/Bezier_curve#Cubic_B.C3.A9zier_curves
let x0 = (pow((1.0 - t),3.0) * P0.x)
let x1 = (3.0 * pow(1.0 - t, 2.0) * t * P1.x)
let x2 = (3.0 * (1.0 - t) * pow(t, 2.0) * P2.x)
let x3 = (pow(t, 3.0) * P3.x)
return x0 + x1 + x2 + x3
}
func derivativeCurveYValueAt(t: CGFloat, controlPoints: [CGPoint]) -> CGFloat {
let P0 = controlPoints[0]
let P1 = controlPoints[1]
let P2 = controlPoints[2]
let P3 = controlPoints[3]
let dy0 = (P0.y + 3.0 * P1.y + 3.0 * P2.y - P3.y) * -3.0
let dy1 = t * (6.0 * P0.y + 6.0 * P2.y)
let dy2 = (-3.0 * P0.y + 3.0 * P1.y)
return dy0 * pow(t, 2.0) + dy1 + dy2
}
func controlPoints() -> [CGPoint] {
// Create point array to point to
var point: [Float] = [0.0, 0.0]
var pointArray = [CGPoint]()
for i in 0...3 {
self.getControlPointAtIndex(i, values: &point)
pointArray.append(CGPoint(x: CGFloat(point[0]), y: CGFloat(point[1])))
}
return pointArray
}
}
| mit | 572155b4938ce8077a040dcbb4ffe27f | 37.256 | 283 | 0.599749 | 5.225414 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothGATT/GATTLocalEastCoordinate.swift | 1 | 1768 | //
// GATTLocalEastCoordinate.swift
// Bluetooth
//
// Created by Carlos Duclos on 7/3/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/**
Local East Coordinate
The Local East characteristic describes the East coordinate of the device using local coordinate system.
- SeeAlso: [Local East Coordinate](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.local_east_coordinate.xml)
*/
@frozen
public struct GATTLocalEastCoordinate: RawRepresentable, GATTCharacteristic {
internal static let length = MemoryLayout<Int16>.size
public static var uuid: BluetoothUUID { return .localEastCoordinate }
public let rawValue: Int16
public init(rawValue: Int16) {
self.rawValue = rawValue
}
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
self.init(rawValue: Int16(bitPattern: UInt16(littleEndian: UInt16(bytes: (data[0], data[1])))))
}
public var data: Data {
let bytes = UInt16(bitPattern: rawValue).littleEndian.bytes
return Data([bytes.0, bytes.1])
}
}
extension GATTLocalEastCoordinate: Equatable {
public static func == (lhs: GATTLocalEastCoordinate, rhs: GATTLocalEastCoordinate) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension GATTLocalEastCoordinate: CustomStringConvertible {
public var description: String {
return rawValue.description
}
}
extension GATTLocalEastCoordinate: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int16) {
self.init(rawValue: value)
}
}
| mit | 3adce24371533ea9863ba6d58eeefd13 | 24.608696 | 161 | 0.66893 | 4.554124 | false | false | false | false |
eeschimosu/SwiftLint | Source/SwiftLintFramework/String+SwiftLint.swift | 2 | 1764 | //
// String+SwiftLint.swift
// SwiftLint
//
// Created by JP Simard on 2015-05-16.
// Copyright (c) 2015 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
import SwiftXPC
extension String {
func hasTrailingWhitespace() -> Bool {
if isEmpty {
return false
}
if let character = utf16.suffix(1).first {
return NSCharacterSet.whitespaceCharacterSet().characterIsMember(character)
}
return false
}
func isUppercase() -> Bool {
return self == uppercaseString
}
public var chomped: String {
return stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())
}
public func nameStrippingLeadingUnderscoreIfPrivate(dict: XPCDictionary) -> String {
let privateACL = "source.lang.swift.accessibility.private"
if dict["key.accessibility"] as? String == privateACL && characters.first == "_" {
return self[startIndex.successor()..<endIndex]
}
return self
}
}
extension NSString {
public func lineAndCharacterForByteOffset(offset: Int) -> (line: Int, character: Int)? {
return byteRangeToNSRange(start: offset, length: 0).flatMap { range in
var numberOfLines = 0, index = 0, lineRangeStart = 0, previousIndex = 0
while index < length {
numberOfLines++
if index > range.location {
break
}
lineRangeStart = numberOfLines
previousIndex = index
index = NSMaxRange(lineRangeForRange(NSRange(location: index, length: 1)))
}
return (lineRangeStart, range.location - previousIndex + 1)
}
}
}
| mit | 42ca024ee02f53bbc9d3276e07ab6634 | 28.898305 | 92 | 0.611111 | 5.068966 | false | false | false | false |
alessioros/mobilecodegenerator3 | examples/ParkTraining/completed/ios/ParkTraining/ParkTraining/ExercisesViewController.swift | 2 | 3834 |
import UIKit
import CoreData
class ExercisesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{
@IBOutlet weak var newExerciseButton: UIButton!
@IBOutlet weak var exercisesList: UITableView!
var exercises = [NSManagedObject]()
override func viewDidLoad() {
super.viewDidLoad()
newExerciseButton.layer.cornerRadius = 36
self.exercisesList.delegate = self
self.exercisesList.dataSource = self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
}
@IBAction func newExerciseButtonTouchDown(sender: UIButton) {
// Changes background color of button when clicked
sender.backgroundColor = UIColor(red: 0.20392157, green: 0.2627451, blue: 0.6, alpha: 1)
//TODO Implement the action
}
@IBAction func newExerciseButtonTouchUpInside(sender: UIButton) {
// Restore original background color of button after click
sender.backgroundColor = UIColor(red: 0.24705882, green: 0.31764707, blue: 0.70980394, alpha: 1)
//TODO Implement the action
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.exercises.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Configure the cell...
if tableView == self.exercisesList {
let exercisesListCell = tableView.dequeueReusableCellWithIdentifier("exercisesListTableViewCell", forIndexPath: indexPath) as! DetailedTableViewCell
let exercise = exercises[indexPath.row]
exercisesListCell.img.image = UIImage(named: "list_image")
exercisesListCell.label.text = exercise.valueForKey("name") as? String
exercisesListCell.content.text = "\(exercise.valueForKey("sets")!) X \(exercise.valueForKey("reps")!)"
exercisesListCell.icon.image = UIImage(named: "list_icon")
return exercisesListCell
}
return UITableViewCell()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if tableView == self.exercisesList {}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//Legge tutti gli esercizi e li assegna a exercises
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Exercise")
do {
let results = try managedContext.executeFetchRequest(fetchRequest)
self.exercises = results as! [NSManagedObject]
} catch {
print("Error")
}
self.exercisesList.reloadData()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
//You can reference to the next ViewController and the selected UITableViewRow
if segue.identifier == "SegueIdentifierFromexercisesListToExerciseEditViewControllerID" {
let index = self.exercisesList.indexPathForSelectedRow!
let destination = segue.destinationViewController as! ExerciseEditViewController
// Pass the selected cell content to destination ...
destination.exerciseIndex = index.row
}
}
}
| gpl-3.0 | ab233b3f0367cb258b6cbf8a0cdf5779 | 31.218487 | 154 | 0.707355 | 4.865482 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceKit/Sources/EurofurenceKit/Entities/Tag.swift | 1 | 1406 | import CoreData
@objc(Tag)
public class Tag: NSManagedObject {
@nonobjc class func fetchRequest() -> NSFetchRequest<Tag> {
return NSFetchRequest<Tag>(entityName: "Tag")
}
@NSManaged public var name: String
@NSManaged public var events: Set<Event>
}
// MARK: - CanonicalTag Adaptation
extension Tag {
var canonicalTag: CanonicalTag? {
CanonicalTag.wellKnownTag(named: name)
}
}
// MARK: - Fetching
extension Tag {
static func named(name: String, in managedObjectContext: NSManagedObjectContext) -> Tag {
let fetchRequest = Self.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "name == %@", name)
let results = try? managedObjectContext.fetch(fetchRequest)
if let existingPanelHost = results?.first {
return existingPanelHost
} else {
let panelHost = Tag(context: managedObjectContext)
panelHost.name = name
return panelHost
}
}
}
// MARK: Generated accessors for events
extension Tag {
@objc(addEventsObject:)
@NSManaged func addToEvents(_ value: Event)
@objc(removeEventsObject:)
@NSManaged func removeFromEvents(_ value: Event)
@objc(addEvents:)
@NSManaged func addToEvents(_ values: Set<Event>)
@objc(removeEvents:)
@NSManaged func removeFromEvents(_ values: Set<Event>)
}
| mit | 4d5cfc8c49c220d35d982e6ef8d98b05 | 22.433333 | 93 | 0.650071 | 4.50641 | false | false | false | false |
mozilla-mobile/focus-ios | BlockzillaPackage/Sources/Onboarding/Handler/OnboardingEventsHandlerV1.swift | 1 | 1711 | /* 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 Combine
public class OnboardingEventsHandlerV1: OnboardingEventsHandling {
private let setShownTips: (Set<ToolTipRoute>) -> Void
@Published public var route: ToolTipRoute?
public var routePublisher: Published<ToolTipRoute?>.Publisher { $route }
private var visitedURLcounter = 0
private var shownTips = Set<ToolTipRoute>() {
didSet {
setShownTips(shownTips)
}
}
public init(
visitedURLcounter: Int = 0,
getShownTips: () -> Set<ToolTipRoute>,
setShownTips: @escaping (Set<ToolTipRoute>) -> Void
) {
self.visitedURLcounter = visitedURLcounter
self.setShownTips = setShownTips
self.shownTips = getShownTips()
}
public func send(_ action: Action) {
switch action {
case .applicationDidLaunch:
show(route: .onboarding(.v1))
case .enterHome:
show(route: .menu)
case .startBrowsing:
visitedURLcounter += 1
if visitedURLcounter == 3 {
show(route: .trash(.v1))
}
case .showTrackingProtection:
show(route: .trackingProtection)
case .trackerBlocked:
show(route: .trackingProtectionShield(.v1))
default:
break
}
}
private func show(route: ToolTipRoute) {
if !shownTips.contains(route) {
self.route = route
shownTips.insert(route)
}
}
}
| mpl-2.0 | 945f15e8e45c462f88c7bcf32941815d | 26.15873 | 76 | 0.603741 | 4.309824 | false | false | false | false |
kousun12/RxSwift | RxExample/RxExample/Examples/AutoLoading/GitHubSearchRepositoriesAPI.swift | 4 | 9539 | //
// GitHubSearchRepositoriesAPI.swift
// RxExample
//
// Created by Krunoslav Zaher on 10/18/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
/**
Parsed GitHub respository.
*/
struct Repository: CustomStringConvertible {
var name: String
var url: String
init(name: String, url: String) {
self.name = name
self.url = url
}
var description: String {
return "\(name) | \(url)"
}
}
/**
ServiceState state.
*/
enum ServiceState {
case Online
case Offline
}
/**
Raw response from GitHub API
*/
enum SearchRepositoryResponse {
/**
New repositories just fetched
*/
case Repositories(repositories: [Repository], nextURL: NSURL?)
/**
In case there was some problem fetching data from service, this will be returned.
It really doesn't matter if that is a failure in network layer, parsing error or something else.
In case data can't be read and parsed properly, something is wrong with server response.
*/
case ServiceOffline
/**
This example uses unauthenticated GitHub API. That API does have throttling policy and you won't
be able to make more then 10 requests per minute.
That is actually an awesome scenario to demonstrate complex retries using alert views and combination of timers.
Just search like mad, and everything will be handled right.
*/
case LimitExceeded
}
/**
This is the final result of loading. Crème de la crème.
*/
struct RepositoriesState {
/**
List of parsed repositories ready to be shown in the UI.
*/
let repositories: [Repository]
/**
Current network state.
*/
let serviceState: ServiceState?
/**
Limit exceeded
*/
let limitExceeded: Bool
static let empty = RepositoriesState(repositories: [], serviceState: nil, limitExceeded: false)
}
class GitHubSearchRepositoriesAPI {
static let sharedAPI = GitHubSearchRepositoriesAPI(wireframe: DefaultWireframe())
let activityIndicator = ActivityIndicator()
// Why would network service have wireframe service? It's here to abstract promting user
// Do we really want to make this example project factory/fascade/service competition? :)
private let _wireframe: Wireframe
private init(wireframe: Wireframe) {
_wireframe = wireframe
}
private static let parseLinksPattern = "\\s*,?\\s*<([^\\>]*)>\\s*;\\s*rel=\"([^\"]*)\""
private static let linksRegex = try! NSRegularExpression(pattern: parseLinksPattern, options: [.AllowCommentsAndWhitespace])
private static func parseLinks(links: String) throws -> [String: String] {
let length = (links as NSString).length
let matches = GitHubSearchRepositoriesAPI.linksRegex.matchesInString(links, options: NSMatchingOptions(), range: NSRange(location: 0, length: length))
var result: [String: String] = [:]
for m in matches {
let matches = (1 ..< m.numberOfRanges).map { rangeIndex -> String in
let range = m.rangeAtIndex(rangeIndex)
let startIndex = links.startIndex.advancedBy(range.location)
let endIndex = startIndex.advancedBy(range.length)
let stringRange = Range(start: startIndex, end: endIndex)
return links.substringWithRange(stringRange)
}
if matches.count != 2 {
throw exampleError("Error parsing links")
}
result[matches[1]] = matches[0]
}
return result
}
private static func parseNextURL(httpResponse: NSHTTPURLResponse) throws -> NSURL? {
guard let serializedLinks = httpResponse.allHeaderFields["Link"] as? String else {
return nil
}
let links = try GitHubSearchRepositoriesAPI.parseLinks(serializedLinks)
guard let nextPageURL = links["next"] else {
return nil
}
guard let nextUrl = NSURL(string: nextPageURL) else {
throw exampleError("Error parsing next url `\(nextPageURL)`")
}
return nextUrl
}
/**
Public fascade for search.
*/
func search(query: String, loadNextPageTrigger: Observable<Void>) -> Observable<RepositoriesState> {
let escapedQuery = URLEscape(query)
let url = NSURL(string: "https://api.github.com/search/repositories?q=\(escapedQuery)")!
return recursivelySearch([], loadNextURL: url, loadNextPageTrigger: loadNextPageTrigger)
// Here we go again
.startWith(RepositoriesState.empty)
}
private func recursivelySearch(loadedSoFar: [Repository], loadNextURL: NSURL, loadNextPageTrigger: Observable<Void>) -> Observable<RepositoriesState> {
return loadSearchURL(loadNextURL).flatMap { searchResponse -> Observable<RepositoriesState> in
switch searchResponse {
/**
If service is offline, that's ok, that means that this isn't the last thing we've heard from that API.
It will retry until either battery drains, you become angry and close the app or evil machine comes back
from the future, steals your device and Googles Sarah Connor's address.
*/
case .ServiceOffline:
return just(RepositoriesState(repositories: loadedSoFar, serviceState: .Offline, limitExceeded: false))
case .LimitExceeded:
return just(RepositoriesState(repositories: loadedSoFar, serviceState: .Online, limitExceeded: true))
case .Repositories:
break
}
// Repositories without next url? The party is done.
guard case .Repositories(let newPageRepositories, let maybeNextURL) = searchResponse else {
fatalError("Some fourth case?")
}
var loadedRepositories = loadedSoFar
loadedRepositories.appendContentsOf(newPageRepositories)
let appenedRepositories = RepositoriesState(repositories: loadedRepositories, serviceState: .Online, limitExceeded: false)
// if next page can't be loaded, just return what was loaded, and stop
guard let nextURL = maybeNextURL else {
return just(appenedRepositories)
}
return [
// return loaded immediately
just(appenedRepositories),
// wait until next page can be loaded
never().takeUntil(loadNextPageTrigger),
// load next page
self.recursivelySearch(loadedRepositories, loadNextURL: nextURL, loadNextPageTrigger: loadNextPageTrigger)
].concat()
}
}
/**
Displays UI that prompts the user when to retry.
*/
private func buildRetryPrompt() -> Observable<Void> {
return _wireframe.promptFor(
"Exceeded limit of 10 non authenticated requests per minute for GitHub API. Please wait a minute. :(\nhttps://developer.github.com/v3/#rate-limiting",
cancelAction: RetryResult.Cancel,
actions: [RetryResult.Retry]
)
.filter { (x: RetryResult) in x == .Retry }
.map { _ in () }
}
private func loadSearchURL(searchURL: NSURL) -> Observable<SearchRepositoryResponse> {
return NSURLSession.sharedSession()
.rx_response(NSURLRequest(URL: searchURL))
.retry(3)
.trackActivity(self.activityIndicator)
.observeOn(Dependencies.sharedDependencies.backgroundWorkScheduler)
.map { data, response -> SearchRepositoryResponse in
guard let httpResponse = response as? NSHTTPURLResponse else {
throw exampleError("not getting http response")
}
if httpResponse.statusCode == 403 {
return .LimitExceeded
}
let jsonRoot = try GitHubSearchRepositoriesAPI.parseJSON(httpResponse, data: data)
guard let json = jsonRoot as? [String: AnyObject] else {
throw exampleError("Casting to dictionary failed")
}
let repositories = try GitHubSearchRepositoriesAPI.parseRepositories(json)
let nextURL = try GitHubSearchRepositoriesAPI.parseNextURL(httpResponse)
return .Repositories(repositories: repositories, nextURL: nextURL)
}
.retryOnBecomesReachable(.ServiceOffline, reachabilityService: ReachabilityService.sharedReachabilityService)
}
private static func parseJSON(httpResponse: NSHTTPURLResponse, data: NSData) throws -> AnyObject {
if !(200 ..< 300 ~= httpResponse.statusCode) {
throw exampleError("Call failed")
}
return try NSJSONSerialization.JSONObjectWithData(data ?? NSData(), options: [])
}
private static func parseRepositories(json: [String: AnyObject]) throws -> [Repository] {
guard let items = json["items"] as? [[String: AnyObject]] else {
throw exampleError("Can't find items")
}
return try items.map { item in
guard let name = item["name"] as? String,
url = item["url"] as? String else {
throw exampleError("Can't parse repository")
}
return Repository(name: name, url: url)
}
}
}
| mit | 6abf8942c1a924bbcfe762fcea026945 | 34.849624 | 166 | 0.633494 | 5.126882 | false | false | false | false |
00buggy00/SwiftOpenGLTutorials | SwiftOpenGLRefactor/GraphicView.swift | 1 | 3489 | //
// GraphicView.swift
// SwiftOpenGLRefactor
//
// Created by Myles Schultz on 1/17/18.
// Copyright © 2018 MyKo. All rights reserved.
//
import Cocoa
import OpenGL.GL3
protocol RenderDelegate {
typealias SceneName = String
func loadScene()
func prepareToRender(_ scene: SceneName, for time: Double)
func render(_ scene: SceneName, with renderer: Renderer)
}
enum RenderElementType: UInt32 {
case points = 0
case lines = 1
case triangles = 4
}
protocol Renderer {
func render(_ elementCount: Int32, as elementType: RenderElementType)
}
extension NSOpenGLContext: Renderer {
func render(_ elementCount: Int32, as elementType: RenderElementType) {
glCall(glDrawArrays(elementType.rawValue, 0, elementCount))
}
}
extension _CGLContextObject: Renderer {
func render(_ elementCount: Int32, as elementType: RenderElementType) {
glCall(glDrawArrays(elementType.rawValue, 0, elementCount))
}
}
final class GraphicView: NSOpenGLView {
typealias SceneName = String
var scene: SceneName?
var displayLink: DisplayLink?
var renderDelegate: RenderDelegate?
required init?(coder: NSCoder) {
super.init(coder: coder)
let attributes: [NSOpenGLPixelFormatAttribute] = [
NSOpenGLPixelFormatAttribute(NSOpenGLPFAAllRenderers),
NSOpenGLPixelFormatAttribute(NSOpenGLPFADoubleBuffer),
NSOpenGLPixelFormatAttribute(NSOpenGLPFAColorSize), 32,
NSOpenGLPixelFormatAttribute(NSOpenGLPFAOpenGLProfile), NSOpenGLPixelFormatAttribute(NSOpenGLProfileVersion3_2Core),
0
]
guard let pixelFormat = NSOpenGLPixelFormat(attributes: attributes) else {
Swift.print("pixelFormat could not be constructed")
return
}
self.pixelFormat = pixelFormat
guard let context = NSOpenGLContext(format: pixelFormat, share: nil) else {
Swift.print("context could not be constructed")
return
}
self.openGLContext = context
// Set the context's swap interval parameter to 60Hz (i.e. 1 frame per swamp)
self.openGLContext?.setValues([1], for: .swapInterval)
displayLink = DisplayLink(forView: self)
}
override func prepareOpenGL() {
super.prepareOpenGL()
glClearColor(0.5, 0.5, 0.5, 1.0)
renderDelegate?.loadScene()
displayLink?.start()
}
override func draw(_ dirtyRect: NSRect) {
_ = drawView()
}
func drawView() -> CVReturn {
guard let context = self.openGLContext?.cglContextObj else {
print("Could not acquire an OpenGL context")
return kCVReturnError
}
CGLSetCurrentContext(context)
CGLLockContext(context)
if let time = displayLink?.currentTime {
glCall(glClear(GLbitfield(GL_COLOR_BUFFER_BIT)))
glCall(glCullFace(GLenum(GL_BACK)))
glCall(glEnable(GLenum(GL_CULL_FACE)))
if let scene = scene {
renderDelegate?.prepareToRender(scene, for: time)
renderDelegate?.render(scene, with: context.pointee)
}
}
CGLFlushDrawable(context)
CGLUnlockContext(context)
return kCVReturnSuccess
}
deinit {
displayLink?.stop()
}
}
| mit | 5ffde1c60903fcba67b7df9764dfc641 | 28.559322 | 128 | 0.626433 | 4.694482 | false | false | false | false |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Utility/OverlayScrollView.swift | 1 | 2875 | //
// OverlayScrollView.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Cocoa
class OverlayScrollView: NSScrollView {
// MARK: -
// MARK: Variables
lazy var headerOffset: CGFloat = {
self.tableHeaderOffsetFromSuperview()
}()
// MARK: -
// MARK: Initialization
required init?(coder: NSCoder) {
super.init(coder: coder)
self.initialize()
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.initialize()
}
override func awakeFromNib() {
super.awakeFromNib()
self.initialize()
}
func initialize() {
self.wantsLayer = true
}
// MARK: -
// MARK: Custom Methods
func tableHeaderOffsetFromSuperview() -> CGFloat {
for subview in self.subviews where subview is NSClipView {
for clipViewSubview in subview.subviews {
if
let tableView = clipViewSubview as? NSTableView,
let headerView = tableView.headerView {
return headerView.frame.size.height
}
}
}
return 0.0
}
// MARK: -
// MARK: NSScrollView Method Overrides
override func tile() {
guard let methodScrollerWidth = class_getClassMethod(OverlayScroller.self, #selector(OverlayScroller.scrollerWidth(for:scrollerStyle:))) else { return }
guard let methodZeroWidth = class_getClassMethod(OverlayScroller.self, #selector(OverlayScroller.zeroWidth)) else { return }
// Fake zero scroller width so the contentView gets drawn to the edge
method_exchangeImplementations(methodScrollerWidth, methodZeroWidth)
super.tile()
// Restore original scroller width
method_exchangeImplementations(methodZeroWidth, methodScrollerWidth)
// Resize vertical scroller
if let verticalScroller = self.verticalScroller {
let width = OverlayScroller.scrollerWidth(for: verticalScroller.controlSize,
scrollerStyle: verticalScroller.scrollerStyle)
verticalScroller.frame = NSRect(x: self.bounds.size.width - width,
y: self.headerOffset,
width: width,
height: self.bounds.size.height - self.headerOffset)
}
// Move scroller to front
self.sortSubviews({ view1, view2, _ -> ComparisonResult in
if view1 is OverlayScroller {
return .orderedDescending
} else if view2 is OverlayScroller {
return .orderedAscending
}
return .orderedSame
}, context: nil)
}
}
| mit | c63b4f4ad5a0531c936ae987763cd4e9 | 29.903226 | 160 | 0.588727 | 5.273394 | false | false | false | false |
RyanCodes/HanekeSwift | HanekeTests/DiskTestCase.swift | 4 | 1459 | //
// DiskTestCase.swift
// Haneke
//
// Created by Hermes Pique on 8/26/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import XCTest
class DiskTestCase : XCTestCase {
lazy var directoryPath : String = {
let documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as! String
let directoryPath = documentsPath.stringByAppendingPathComponent(self.name)
return directoryPath
}()
override func setUp() {
super.setUp()
do {
try NSFileManager.defaultManager().createDirectoryAtPath(directoryPath, withIntermediateDirectories: true, attributes: nil)
} catch _ {
}
}
override func tearDown() {
do {
try NSFileManager.defaultManager().removeItemAtPath(directoryPath)
} catch _ {
}
super.tearDown()
}
var dataIndex = 0
func writeDataWithLength(length : Int) -> String {
let data = NSData.dataWithLength(length)
return self.writeData(data)
}
func writeData(data : NSData) -> String {
let path = self.uniquePath()
data.writeToFile(path, atomically: true)
return path
}
func uniquePath() -> String {
let path = self.directoryPath.stringByAppendingPathComponent("\(dataIndex)")
dataIndex++
return path
}
}
| apache-2.0 | 6d0fb36f53a188cf4ca9bf5d5f6a08dd | 26.018519 | 163 | 0.629883 | 5.173759 | false | true | false | false |
Chaosspeeder/YourGoals | Pods/Eureka/Source/Rows/Common/FieldRow.swift | 1 | 22373 | // FieldRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
public protocol InputTypeInitiable {
init?(string stringValue: String)
}
public protocol FieldRowConformance : FormatterConformance {
var titlePercentage : CGFloat? { get set }
var placeholder : String? { get set }
var placeholderColor : UIColor? { get set }
}
extension Int: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue, radix: 10)
}
}
extension Float: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue)
}
}
extension String: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue)
}
}
extension URL: InputTypeInitiable {}
extension Double: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue)
}
}
open class FormatteableRow<Cell: CellType>: Row<Cell>, FormatterConformance where Cell: BaseCell, Cell: TextInputCell {
/// A formatter to be used to format the user's input
open var formatter: Formatter?
/// If the formatter should be used while the user is editing the text.
open var useFormatterDuringInput = false
open var useFormatterOnDidBeginEditing: Bool?
public required init(tag: String?) {
super.init(tag: tag)
displayValueFor = { [unowned self] value in
guard let v = value else { return nil }
guard let formatter = self.formatter else { return String(describing: v) }
if (self.cell.textInput as? UIView)?.isFirstResponder == true {
return self.useFormatterDuringInput ? formatter.editingString(for: v) : String(describing: v)
}
return formatter.string(for: v)
}
}
}
open class FieldRow<Cell: CellType>: FormatteableRow<Cell>, FieldRowConformance, KeyboardReturnHandler where Cell: BaseCell, Cell: TextFieldCell {
/// Configuration for the keyboardReturnType of this row
open var keyboardReturnType: KeyboardReturnTypeConfiguration?
/// The percentage of the cell that should be occupied by the textField
@available (*, deprecated, message: "Use titleLabelPercentage instead")
open var textFieldPercentage : CGFloat? {
get {
return titlePercentage.map { 1 - $0 }
}
set {
titlePercentage = newValue.map { 1 - $0 }
}
}
/// The percentage of the cell that should be occupied by the title (i.e. the titleLabel and optional imageView combined)
open var titlePercentage: CGFloat?
/// The placeholder for the textField
open var placeholder: String?
/// The textColor for the textField's placeholder
open var placeholderColor: UIColor?
public required init(tag: String?) {
super.init(tag: tag)
}
}
/**
* Protocol for cells that contain a UITextField
*/
public protocol TextInputCell {
var textInput: UITextInput { get }
}
public protocol TextFieldCell: TextInputCell {
var textField: UITextField! { get }
}
extension TextFieldCell {
public var textInput: UITextInput {
return textField
}
}
open class _FieldCell<T> : Cell<T>, UITextFieldDelegate, TextFieldCell where T: Equatable, T: InputTypeInitiable {
@IBOutlet public weak var textField: UITextField!
@IBOutlet public weak var titleLabel: UILabel?
fileprivate var observingTitleText = false
private var awakeFromNibCalled = false
open var dynamicConstraints = [NSLayoutConstraint]()
private var calculatedTitlePercentage: CGFloat = 0.7
public required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
let textField = UITextField()
self.textField = textField
textField.translatesAutoresizingMaskIntoConstraints = false
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupTitleLabel()
contentView.addSubview(titleLabel!)
contentView.addSubview(textField)
NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: nil) { [weak self] _ in
guard let me = self else { return }
guard me.observingTitleText else { return }
me.titleLabel?.removeObserver(me, forKeyPath: "text")
me.observingTitleText = false
}
NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: nil) { [weak self] _ in
guard let me = self else { return }
guard !me.observingTitleText else { return }
me.titleLabel?.addObserver(me, forKeyPath: "text", options: [.new, .old], context: nil)
me.observingTitleText = true
}
NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: nil) { [weak self] _ in
self?.setupTitleLabel()
self?.setNeedsUpdateConstraints()
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func awakeFromNib() {
super.awakeFromNib()
awakeFromNibCalled = true
}
deinit {
textField?.delegate = nil
textField?.removeTarget(self, action: nil, for: .allEvents)
guard !awakeFromNibCalled else { return }
if observingTitleText {
titleLabel?.removeObserver(self, forKeyPath: "text")
}
imageView?.removeObserver(self, forKeyPath: "image")
NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIContentSizeCategory.didChangeNotification, object: nil)
}
open override func setup() {
super.setup()
selectionStyle = .none
if !awakeFromNibCalled {
titleLabel?.addObserver(self, forKeyPath: "text", options: [.new, .old], context: nil)
observingTitleText = true
imageView?.addObserver(self, forKeyPath: "image", options: [.new, .old], context: nil)
}
textField.addTarget(self, action: #selector(_FieldCell.textFieldDidChange(_:)), for: .editingChanged)
}
open override func update() {
super.update()
detailTextLabel?.text = nil
if !awakeFromNibCalled {
if let title = row.title {
switch row.cellStyle {
case .subtitle:
textField.textAlignment = .left
textField.clearButtonMode = .whileEditing
default:
textField.textAlignment = title.isEmpty ? .left : .right
textField.clearButtonMode = title.isEmpty ? .whileEditing : .never
}
} else {
textField.textAlignment = .left
textField.clearButtonMode = .whileEditing
}
} else {
textLabel?.text = nil
titleLabel?.text = row.title
titleLabel?.textColor = row.isDisabled ? .gray : .black
}
textField.delegate = self
textField.text = row.displayValueFor?(row.value)
textField.isEnabled = !row.isDisabled
textField.textColor = row.isDisabled ? .gray : .black
textField.font = .preferredFont(forTextStyle: .body)
if let placeholder = (row as? FieldRowConformance)?.placeholder {
if let color = (row as? FieldRowConformance)?.placeholderColor {
textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [.foregroundColor: color])
} else {
textField.placeholder = (row as? FieldRowConformance)?.placeholder
}
}
if row.isHighlighted {
titleLabel?.textColor = tintColor
}
}
open override func cellCanBecomeFirstResponder() -> Bool {
return !row.isDisabled && textField?.canBecomeFirstResponder == true
}
open override func cellBecomeFirstResponder(withDirection: Direction) -> Bool {
return textField?.becomeFirstResponder() ?? false
}
open override func cellResignFirstResponder() -> Bool {
return textField?.resignFirstResponder() ?? true
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let obj = object as AnyObject?
if let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKey.kindKey],
((obj === titleLabel && keyPathValue == "text") || (obj === imageView && keyPathValue == "image")) &&
(changeType as? NSNumber)?.uintValue == NSKeyValueChange.setting.rawValue {
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
}
}
// MARK: Helpers
open func customConstraints() {
guard !awakeFromNibCalled else { return }
contentView.removeConstraints(dynamicConstraints)
dynamicConstraints = []
switch row.cellStyle {
case .subtitle:
var views: [String: AnyObject] = ["textField": textField]
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
views["titleLabel"] = titleLabel
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:[titleLabel]-3-[textField]", options: .alignAllLeading, metrics: nil, views: views)
// Here we are centering the textField with an offset of -4. This replicates the exact behavior of the default UITableViewCell with .subtitle style
dynamicConstraints.append(NSLayoutConstraint(item: textField!, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: -4))
dynamicConstraints.append(NSLayoutConstraint(item: titleLabel, attribute: .centerX, relatedBy: .equal, toItem: textField, attribute: .centerX, multiplier: 1, constant: 0))
} else {
dynamicConstraints.append(NSLayoutConstraint(item: textField!, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0))
}
if let imageView = imageView, let _ = imageView.image {
views["imageView"] = imageView
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[titleLabel]-|", options: [], metrics: nil, views: views)
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[textField]-|", options: [], metrics: nil, views: views)
} else {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[textField]-|", options: [], metrics: nil, views: views)
}
} else {
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[titleLabel]-|", options: [], metrics: nil, views: views)
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[textField]-|", options: [], metrics: nil, views: views)
} else {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[textField]-|", options: .alignAllLeft, metrics: nil, views: views)
}
}
default:
var views: [String: AnyObject] = ["textField": textField]
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-11-[textField]-11-|", options: .alignAllLastBaseline, metrics: nil, views: views)
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
views["titleLabel"] = titleLabel
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-11-[titleLabel]-11-|", options: .alignAllLastBaseline, metrics: nil, views: views)
dynamicConstraints.append(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: textField, attribute: .centerY, multiplier: 1, constant: 0))
}
if let imageView = imageView, let _ = imageView.image {
views["imageView"] = imageView
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[titleLabel]-[textField]-|", options: [], metrics: nil, views: views)
dynamicConstraints.append(NSLayoutConstraint(item: titleLabel,
attribute: .width,
relatedBy: (row as? FieldRowConformance)?.titlePercentage != nil ? .equal : .lessThanOrEqual,
toItem: contentView,
attribute: .width,
multiplier: calculatedTitlePercentage,
constant: 0.0))
} else {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[textField]-|", options: [], metrics: nil, views: views)
}
} else {
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[titleLabel]-[textField]-|", options: [], metrics: nil, views: views)
dynamicConstraints.append(NSLayoutConstraint(item: titleLabel,
attribute: .width,
relatedBy: (row as? FieldRowConformance)?.titlePercentage != nil ? .equal : .lessThanOrEqual,
toItem: contentView,
attribute: .width,
multiplier: calculatedTitlePercentage,
constant: 0.0))
} else {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[textField]-|", options: .alignAllLeft, metrics: nil, views: views)
}
}
}
contentView.addConstraints(dynamicConstraints)
}
open override func updateConstraints() {
customConstraints()
super.updateConstraints()
}
@objc open func textFieldDidChange(_ textField: UITextField) {
guard let textValue = textField.text else {
row.value = nil
return
}
guard let fieldRow = row as? FieldRowConformance, let formatter = fieldRow.formatter else {
row.value = textValue.isEmpty ? nil : (T.init(string: textValue) ?? row.value)
return
}
if fieldRow.useFormatterDuringInput {
let unsafePointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
defer {
unsafePointer.deallocate()
}
let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(unsafePointer)
let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil
if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) {
row.value = value.pointee as? T
guard var selStartPos = textField.selectedTextRange?.start else { return }
let oldVal = textField.text
textField.text = row.displayValueFor?(row.value)
selStartPos = (formatter as? FormatterProtocol)?.getNewPosition(forPosition: selStartPos, inTextInput: textField, oldValue: oldVal, newValue: textField.text) ?? selStartPos
textField.selectedTextRange = textField.textRange(from: selStartPos, to: selStartPos)
return
}
} else {
let unsafePointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
defer {
unsafePointer.deallocate()
}
let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(unsafePointer)
let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil
if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) {
row.value = value.pointee as? T
} else {
row.value = textValue.isEmpty ? nil : (T.init(string: textValue) ?? row.value)
}
}
}
// MARK: Helpers
private func setupTitleLabel() {
titleLabel = self.textLabel
titleLabel?.translatesAutoresizingMaskIntoConstraints = false
titleLabel?.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal)
titleLabel?.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal)
}
private func displayValue(useFormatter: Bool) -> String? {
guard let v = row.value else { return nil }
if let formatter = (row as? FormatterConformance)?.formatter, useFormatter {
return textField?.isFirstResponder == true ? formatter.editingString(for: v) : formatter.string(for: v)
}
return String(describing: v)
}
// MARK: TextFieldDelegate
open func textFieldDidBeginEditing(_ textField: UITextField) {
formViewController()?.beginEditing(of: self)
formViewController()?.textInputDidBeginEditing(textField, cell: self)
if let fieldRowConformance = row as? FormatterConformance, let _ = fieldRowConformance.formatter, fieldRowConformance.useFormatterOnDidBeginEditing ?? fieldRowConformance.useFormatterDuringInput {
textField.text = displayValue(useFormatter: true)
} else {
textField.text = displayValue(useFormatter: false)
}
}
open func textFieldDidEndEditing(_ textField: UITextField) {
formViewController()?.endEditing(of: self)
formViewController()?.textInputDidEndEditing(textField, cell: self)
textFieldDidChange(textField)
textField.text = displayValue(useFormatter: (row as? FormatterConformance)?.formatter != nil)
}
open func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldReturn(textField, cell: self) ?? true
}
open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return formViewController()?.textInput(textField, shouldChangeCharactersInRange:range, replacementString:string, cell: self) ?? true
}
open func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldBeginEditing(textField, cell: self) ?? true
}
open func textFieldShouldClear(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldClear(textField, cell: self) ?? true
}
open func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldEndEditing(textField, cell: self) ?? true
}
open override func layoutSubviews() {
super.layoutSubviews()
guard let row = (row as? FieldRowConformance) else { return }
defer {
// As titleLabel is the textLabel, iOS may re-layout without updating constraints, for example:
// swiping, showing alert or actionsheet from the same section.
// thus we need forcing update to use customConstraints()
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
}
guard let titlePercentage = row.titlePercentage else { return }
var targetTitleWidth = bounds.size.width * titlePercentage
if let imageView = imageView, let _ = imageView.image, let titleLabel = titleLabel {
var extraWidthToSubtract = titleLabel.frame.minX - imageView.frame.minX // Left-to-right interface layout
if UIView.userInterfaceLayoutDirection(for: self.semanticContentAttribute) == .rightToLeft {
extraWidthToSubtract = imageView.frame.maxX - titleLabel.frame.maxX
}
targetTitleWidth -= extraWidthToSubtract
}
calculatedTitlePercentage = targetTitleWidth / contentView.bounds.size.width
}
}
| lgpl-3.0 | e042e91aaa72dd4557e9de6571ae07b0 | 45.805439 | 204 | 0.642024 | 5.451511 | false | false | false | false |
edwinbosire/YAWA | YAWA-Weather/Model/Forecast.swift | 1 | 3444 | //
// Forecast.swift
// YAWA-Weather
//
// Created by edwin bosire on 15/06/2015.
// Copyright (c) 2015 Edwin Bosire. All rights reserved.
//
import Foundation
import CoreData
import UIKit
@objc(Forecast)
class Forecast: NSManagedObject {
@NSManaged var time: String
@NSManaged var temperature: NSNumber
@NSManaged var humidity: NSNumber
@NSManaged var precipitationProbability: NSNumber
@NSManaged var windSpeed: NSNumber
@NSManaged var windDirection: String
@NSManaged var summary: String
@NSManaged var icon: String
@NSManaged var weeklyForecast: NSSet
@NSManaged var city: City
class func createNewForecast() -> Forecast {
let forecast = NSEntityDescription.insertNewObjectForEntityForName("Forecast", inManagedObjectContext: StoreManager.sharedInstance.managedObjectContext!) as! Forecast
return forecast
}
class func forecastWithDictionary(weatherDictionary: NSDictionary) -> Forecast {
let forecast = Forecast.createNewForecast()
let currentWeather = weatherDictionary["currently"] as! NSDictionary
forecast.temperature = currentWeather["temperature"] as! Int
forecast.humidity = currentWeather["humidity"] as! Double
forecast.precipitationProbability = currentWeather["precipProbability"] as! Double
forecast.windSpeed = currentWeather["windSpeed"] as! Int
forecast.summary = currentWeather["summary"] as! String
forecast.icon = currentWeather["icon"] as! String
let myWeeklyForecast = Forecast.weeklyForecastFromDictionary(weatherDictionary)
let set = NSSet(array: myWeeklyForecast)
forecast.weeklyForecast = set
let windDirectionDegrees = currentWeather["windBearing"] as! Int
forecast.windDirection = forecast.windDirectionFromDegress(windDirectionDegrees)
let currentTimeIntVale = currentWeather["time"] as! Int
forecast.time = forecast.dateStringFromUnixTime(currentTimeIntVale)
return forecast
}
func image() -> UIImage {
return weatherIconFromString(icon)
}
class func weeklyForecastFromDictionary(weatherDictionary: NSDictionary) ->[Daily]{
var weeklyForcasts = [Daily]()
let weeklyWeather = weatherDictionary["daily"] as! NSDictionary
let weeklyForcast = weeklyWeather["data"] as! NSArray
for dailyDict in weeklyForcast {
let dailyForecast = Daily.dailyWithDictionary(dailyDict as! NSDictionary)
weeklyForcasts.append(dailyForecast)
}
return weeklyForcasts
}
func windDirectionFromDegress(degrees: Int) -> String {
switch degrees {
case (0...45):
return "North"
case (315...360):
return "North"
case (45...135):
return "East"
case (135...225):
return "South"
case (225...315):
return "West"
default:
return "Unknown"
}
}
func dateStringFromUnixTime(unixTime: Int) -> String {
let timeInSeconds = NSTimeInterval(unixTime)
let weatherDate = NSDate(timeIntervalSince1970: timeInSeconds)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE, MMM d"
return dateFormatter.stringFromDate(weatherDate)
}
func dayOne() -> Daily {
return weeklyForecast.allObjects[0] as! Daily
}
func dayTwo() -> Daily {
return weeklyForecast.allObjects[1] as! Daily
}
func dayThree() -> Daily {
return weeklyForecast.allObjects[2] as! Daily
}
func dayFour() -> Daily {
return weeklyForecast.allObjects[3] as! Daily
}
func dayFive() -> Daily {
return weeklyForecast.allObjects[4] as! Daily
}
}
| gpl-2.0 | 32d6114d9c0f5d87c451f4bc5ad49946 | 26.333333 | 168 | 0.738966 | 4.095125 | false | false | false | false |
swift-tweets/tweetup-kit | Sources/TweetupKit/Image.swift | 1 | 1277 | public struct Image {
public var alternativeText: String
public var source: Source
public enum Source {
case local(String)
case twitter(String)
case gist(String)
}
}
extension Image: CustomStringConvertible {
public var description: String {
return ")"
}
}
extension Image: Equatable {
public static func ==(lhs: Image, rhs: Image) -> Bool {
return lhs.alternativeText == rhs.alternativeText && lhs.source == rhs.source
}
}
extension Image.Source: CustomStringConvertible {
public var description: String {
switch self {
case let .local(path):
return path
case let .twitter(id):
return "twitter:\(id)"
case let .gist(id):
return "gist:\(id)"
}
}
}
extension Image.Source: Equatable {
public static func ==(lhs: Image.Source, rhs: Image.Source) -> Bool {
switch (lhs, rhs) {
case let (.local(path1), .local(path2)):
return path1 == path2
case let (.twitter(id1), .twitter(id2)):
return id1 == id2
case let (.gist(id1), .gist(id2)):
return id1 == id2
case (_, _):
return false
}
}
}
| mit | be1c8dc52cd38781d65dd8cd4ed019cc | 24.54 | 85 | 0.563038 | 4.228477 | false | false | false | false |
hollisliu/Spacetime-Rhapsody | Spacetime Rhapsody.playgroundbook/Contents/Sources/AudioControl.swift | 1 | 840 | //
// AudioControl.swift
// Fabric
//
// Created by Hanjie Liu on 4/1/17.
// Copyright © 2017 Hanjie Liu. All rights reserved.
//
import Foundation
import SceneKit
extension UniverseViewController {
func setupBackgroundAudio() {
let source = SCNAudioSource(fileNamed: "peace.mp3")
source?.loops = true
source?.isPositional = false
source?.volume = 0.25
player = SCNAudioPlayer(source: source!)
root?.addAudioPlayer(player!)
}
func playFabricSound(node n: SCNNode) {
let source = SCNAudioSource(fileNamed: "stretch.mp3")
source?.loops = false
source?.isPositional = true
source?.volume = 0.1
player = SCNAudioPlayer(source: source!)
n.addAudioPlayer(player!)
}
}
| mit | 3408c50e67fa9c477df0ce5040aa8913 | 22.305556 | 61 | 0.593564 | 4.302564 | false | false | false | false |
AlexRamey/mbird-iOS | Pods/CVCalendar/CVCalendar/CVCalendarMonthContentViewController.swift | 1 | 20572 | //
// CVCalendarMonthContentViewController.swift
// CVCalendar Demo
//
// Created by Eugene Mozharovsky on 12/04/15.
// Copyright (c) 2015 GameApp. All rights reserved.
//
import UIKit
public final class CVCalendarMonthContentViewController: CVCalendarContentViewController, CVCalendarContentPresentationCoordinator {
fileprivate var monthViews: [Identifier : MonthView]
public override init(calendarView: CalendarView, frame: CGRect) {
monthViews = [Identifier : MonthView]()
super.init(calendarView: calendarView, frame: frame)
initialLoad(presentedMonthView.date)
}
public init(calendarView: CalendarView, frame: CGRect, presentedDate: Foundation.Date) {
monthViews = [Identifier : MonthView]()
super.init(calendarView: calendarView, frame: frame)
presentedMonthView = MonthView(calendarView: calendarView, date: presentedDate)
presentedMonthView.updateAppearance(scrollView.bounds)
initialLoad(presentedDate)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Load & Reload
public func initialLoad(_ date: Foundation.Date) {
insertMonthView(getPreviousMonth(date), withIdentifier: previous)
insertMonthView(presentedMonthView, withIdentifier: presented)
insertMonthView(getFollowingMonth(date), withIdentifier: following)
let calendar = self.calendarView.delegate?.calendar?() ?? Calendar.current
presentedMonthView.mapDayViews { dayView in
if self.calendarView.shouldAutoSelectDayOnMonthChange &&
self.matchedDays(dayView.date, CVDate(date: date, calendar: calendar)) {
self.calendarView.coordinator.flush()
self.calendarView.touchController.receiveTouchOnDayView(dayView)
dayView.selectionView?.removeFromSuperview()
}
}
checkScrollToPreviousDisabled()
checkScrollToBeyondDisabled()
calendarView.presentedDate = CVDate(date: presentedMonthView.date, calendar: calendar)
}
public func reloadMonthViews() {
for (identifier, monthView) in monthViews {
monthView.frame.origin.x =
CGFloat(indexOfIdentifier(identifier)) * scrollView.frame.width
monthView.removeFromSuperview()
scrollView.addSubview(monthView)
}
}
// MARK: - Insertion
public func insertMonthView(_ monthView: MonthView, withIdentifier identifier: Identifier) {
let index = CGFloat(indexOfIdentifier(identifier))
monthView.frame.origin = CGPoint(x: scrollView.bounds.width * index, y: 0)
monthViews[identifier] = monthView
scrollView.addSubview(monthView)
checkScrollToPreviousDisabled()
checkScrollToBeyondDisabled()
calendarView.coordinator?.disableDays(in: presentedMonthView)
}
public func replaceMonthView(_ monthView: MonthView,
withIdentifier identifier: Identifier, animatable: Bool) {
var monthViewFrame = monthView.frame
monthViewFrame.origin.x = monthViewFrame.width * CGFloat(indexOfIdentifier(identifier))
monthView.frame = monthViewFrame
monthViews[identifier] = monthView
if animatable {
scrollView.scrollRectToVisible(monthViewFrame, animated: false)
}
}
// MARK: - Load management
public func scrolledLeft() {
if let presented = monthViews[presented], let following = monthViews[following] {
if pageLoadingEnabled {
pageLoadingEnabled = false
monthViews[previous]?.removeFromSuperview()
replaceMonthView(presented, withIdentifier: previous, animatable: false)
replaceMonthView(following, withIdentifier: self.presented, animatable: true)
insertMonthView(getFollowingMonth(following.date), withIdentifier: self.following)
self.calendarView.delegate?.didShowNextMonthView?(following.date)
}
}
}
public func scrolledRight() {
if let previous = monthViews[previous], let presented = monthViews[presented] {
if pageLoadingEnabled {
pageLoadingEnabled = false
monthViews[following]?.removeFromSuperview()
replaceMonthView(previous, withIdentifier: self.presented, animatable: true)
replaceMonthView(presented, withIdentifier: following, animatable: false)
insertMonthView(getPreviousMonth(previous.date), withIdentifier: self.previous)
self.calendarView.delegate?.didShowPreviousMonthView?(previous.date)
}
}
}
// MARK: - Override methods
public override func updateFrames(_ rect: CGRect) {
super.updateFrames(rect)
for monthView in monthViews.values {
monthView.reloadViewsWithRect(rect != CGRect.zero ? rect : scrollView.bounds)
}
reloadMonthViews()
if let presented = monthViews[presented] {
if scrollView.frame.height != presented.potentialSize.height {
updateHeight(presented.potentialSize.height, animated: false)
}
scrollView.scrollRectToVisible(presented.frame, animated: false)
}
}
public override func performedDayViewSelection(_ dayView: DayView) {
if dayView.isOut && calendarView.shouldScrollOnOutDayViewSelection {
let calendar = self.calendarView.delegate?.calendar?() ?? Calendar.current
if dayView.date.day > 20 {
let presentedDate = dayView.monthView.date
calendarView.presentedDate = CVDate(date: self.dateBeforeDate(presentedDate!), calendar: calendar)
presentPreviousView(dayView)
} else {
let presentedDate = dayView.monthView.date
calendarView.presentedDate = CVDate(date: self.dateAfterDate(presentedDate!), calendar: calendar)
presentNextView(dayView)
}
}
}
public override func presentPreviousView(_ view: UIView?) {
if presentationEnabled {
presentationEnabled = false
guard let extra = monthViews[following],
let presented = monthViews[presented],
let previous = monthViews[previous] else {
return
}
UIView.animate(withDuration: 0.5, delay: 0,
options: UIViewAnimationOptions(),
animations: { [weak self] in
guard let strongSelf = self else {
return
}
strongSelf.prepareTopMarkersOnMonthView(presented, hidden: true)
extra.frame.origin.x += strongSelf.scrollView.frame.width
presented.frame.origin.x += strongSelf.scrollView.frame.width
previous.frame.origin.x += strongSelf.scrollView.frame.width
strongSelf.replaceMonthView(presented, withIdentifier: strongSelf.following, animatable: false)
strongSelf.replaceMonthView(previous, withIdentifier: strongSelf.presented, animatable: false)
strongSelf.presentedMonthView = previous
strongSelf.updateLayoutIfNeeded()
}) { [weak self] _ in
guard let strongSelf = self else {
return
}
extra.removeFromSuperview()
strongSelf.insertMonthView(strongSelf.getPreviousMonth(previous.date),
withIdentifier: strongSelf.previous)
strongSelf.updateSelection()
strongSelf.presentationEnabled = true
for monthView in strongSelf.monthViews.values {
strongSelf.prepareTopMarkersOnMonthView(monthView, hidden: false)
}
}
self.calendarView.delegate?.didShowPreviousMonthView?(previous.date)
}
}
public override func presentNextView(_ view: UIView?) {
if presentationEnabled {
presentationEnabled = false
guard let extra = monthViews[previous],
let presented = monthViews[presented],
let following = monthViews[following] else {
return
}
UIView.animate(withDuration: 0.5, delay: 0,
options: UIViewAnimationOptions(),
animations: { [weak self] in
guard let strongSelf = self else {
return
}
strongSelf.prepareTopMarkersOnMonthView(presented, hidden: true)
extra.frame.origin.x -= strongSelf.scrollView.frame.width
presented.frame.origin.x -= strongSelf.scrollView.frame.width
following.frame.origin.x -= strongSelf.scrollView.frame.width
strongSelf.replaceMonthView(presented, withIdentifier: strongSelf.previous, animatable: false)
strongSelf.replaceMonthView(following, withIdentifier: strongSelf.presented, animatable: false)
strongSelf.presentedMonthView = following
strongSelf.updateLayoutIfNeeded()
}) { [weak self] _ in
guard let strongSelf = self else {
return
}
extra.removeFromSuperview()
strongSelf.insertMonthView(strongSelf.getFollowingMonth(following.date), withIdentifier: strongSelf.following)
strongSelf.updateSelection()
strongSelf.presentationEnabled = true
for monthView in strongSelf.monthViews.values {
strongSelf.prepareTopMarkersOnMonthView(monthView, hidden: false)
}
}
self.calendarView.delegate?.didShowNextMonthView?(following.date)
}
}
public override func updateDayViews(shouldShow: Bool) {
setDayOutViewsVisible(monthViews: monthViews, visible: shouldShow)
}
fileprivate var togglingBlocked = false
public override func togglePresentedDate(_ date: Foundation.Date) {
let calendar = self.calendarView.delegate?.calendar?() ?? Calendar.current
let presentedDate = CVDate(date: date, calendar: calendar)
guard let presentedMonth = monthViews[presented] else {
return
}
var isMatchedDays = false
var isMatchedMonths = false
// selectedDayView would be nil if shouldAutoSelectDayOnMonthChange returns false
// we want to still allow the user to toggle to a date even if there is nothing selected
if let selectedDate = calendarView.coordinator.selectedDayView?.date {
isMatchedDays = matchedDays(selectedDate, presentedDate)
isMatchedMonths = matchedMonths(presentedDate, selectedDate)
}
if !isMatchedDays && !togglingBlocked {
if !isMatchedMonths {
togglingBlocked = true
monthViews[previous]?.removeFromSuperview()
monthViews[following]?.removeFromSuperview()
insertMonthView(getPreviousMonth(date), withIdentifier: previous)
insertMonthView(getFollowingMonth(date), withIdentifier: following)
let currentMonthView = MonthView(calendarView: calendarView, date: date)
currentMonthView.updateAppearance(scrollView.bounds)
currentMonthView.alpha = 0
insertMonthView(currentMonthView, withIdentifier: presented)
presentedMonthView = currentMonthView
calendarView.presentedDate = CVDate(date: date, calendar: calendar)
UIView.animate(withDuration: toggleDateAnimationDuration, delay: 0,
options: UIViewAnimationOptions(),
animations: {
presentedMonth.alpha = 0
currentMonthView.alpha = 1
}) { [weak self] _ in
presentedMonth.removeFromSuperview()
self?.selectDayViewWithDay(presentedDate.day, inMonthView: currentMonthView)
self?.togglingBlocked = false
self?.updateLayoutIfNeeded()
}
} else {
if let currentMonthView = monthViews[presented] {
selectDayViewWithDay(presentedDate.day, inMonthView: currentMonthView)
}
}
}
}
}
// MARK: - Month management
extension CVCalendarMonthContentViewController {
public func getFollowingMonth(_ date: Foundation.Date) -> MonthView {
let calendar = self.calendarView.delegate?.calendar?() ?? Calendar.current
let firstDate = calendarView.manager.monthDateRange(date).monthStartDate
var components = Manager.componentsForDate(firstDate, calendar: calendar)
components.month! += 1
let newDate = calendar.date(from: components)!
let frame = scrollView.bounds
let monthView = MonthView(calendarView: calendarView, date: newDate)
monthView.updateAppearance(frame)
return monthView
}
public func getPreviousMonth(_ date: Foundation.Date) -> MonthView {
let calendar = self.calendarView.delegate?.calendar?() ?? Calendar.current
let firstDate = calendarView.manager.monthDateRange(date).monthStartDate
var components = Manager.componentsForDate(firstDate, calendar: calendar)
components.month! -= 1
let newDate = calendar.date(from: components)!
let frame = scrollView.bounds
let monthView = MonthView(calendarView: calendarView, date: newDate)
monthView.updateAppearance(frame)
return monthView
}
func checkScrollToPreviousDisabled() {
let calendar = self.calendarView.delegate?.calendar?() ?? Calendar.current
guard let presentedMonth = monthViews[presented],
let disableScrollingBeforeDate = calendarView.disableScrollingBeforeDate else {
return
}
let convertedDate = CVDate(date: disableScrollingBeforeDate, calendar: calendar)
presentedMonth.mapDayViews({ dayView in
if matchedDays(convertedDate, dayView.date) {
presentedMonth.allowScrollToPreviousMonth = false
}
})
}
func checkScrollToBeyondDisabled() {
let calendar = self.calendarView.delegate?.calendar?() ?? Calendar.current
guard let presentedMonth = monthViews[presented],
let disableScrollingBeyondDate = calendarView.disableScrollingBeyondDate else {
return
}
let convertedDate = CVDate(date: disableScrollingBeyondDate, calendar: calendar)
presentedMonth.mapDayViews({ dayView in
if matchedDays(convertedDate, dayView.date) {
presentedMonth.allowScrollToNextMonth = false
}
})
}
}
// MARK: - Visual preparation
extension CVCalendarMonthContentViewController {
public func prepareTopMarkersOnMonthView(_ monthView: MonthView, hidden: Bool) {
monthView.mapDayViews { dayView in
dayView.topMarker?.isHidden = hidden
}
}
public func updateSelection() {
let coordinator = calendarView.coordinator
if let selected = coordinator?.selectedDayView {
for (index, monthView) in monthViews {
if indexOfIdentifier(index) != 1 {
monthView.mapDayViews {
dayView in
if dayView == selected {
dayView.setDeselectedWithClearing(true)
coordinator?.dequeueDayView(dayView)
}
}
}
}
}
let calendar = self.calendarView.delegate?.calendar?() ?? Calendar.current
if let presentedMonthView = monthViews[presented] {
self.presentedMonthView = presentedMonthView
calendarView.presentedDate = CVDate(date: presentedMonthView.date, calendar: calendar)
if let selected = coordinator?.selectedDayView,
let selectedMonthView = selected.monthView ,
!matchedMonths(CVDate(date: selectedMonthView.date, calendar: calendar),
CVDate(date: presentedMonthView.date, calendar: calendar)) &&
calendarView.shouldAutoSelectDayOnMonthChange {
let current = CVDate(date: Date(), calendar: calendar)
let presented = CVDate(date: presentedMonthView.date, calendar: calendar)
if matchedMonths(current, presented) {
selectDayViewWithDay(current.day, inMonthView: presentedMonthView)
} else {
selectDayViewWithDay(CVDate(date: calendarView.manager
.monthDateRange(presentedMonthView.date).monthStartDate, calendar: calendar).day,
inMonthView: presentedMonthView)
}
}
if coordinator?.selectedStartDayView != nil || coordinator?.selectedEndDayView != nil {
coordinator?.highlightSelectedDays(in: presentedMonthView)
}
coordinator?.disableDays(in: presentedMonthView)
}
}
public func selectDayViewWithDay(_ day: Int, inMonthView monthView: CVCalendarMonthView) {
let coordinator = calendarView.coordinator
monthView.mapDayViews { dayView in
if dayView.date.day == day && !dayView.isOut {
if let selected = coordinator?.selectedDayView , selected != dayView {
self.calendarView.didSelectDayView(dayView)
}
coordinator?.performDayViewSingleSelection(dayView)
}
}
}
}
// MARK: - UIScrollViewDelegate
extension CVCalendarMonthContentViewController {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y != 0 {
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: 0)
}
//restricts scrolling to previous months
if monthViews[presented]?.allowScrollToPreviousMonth == false,
scrollView.contentOffset.x < scrollView.frame.width {
scrollView.setContentOffset(CGPoint(x: scrollView.frame.width, y: 0), animated: false)
return
}
//restricts scrolling to next months
if monthViews[presented]?.allowScrollToNextMonth == false,
scrollView.contentOffset.x > scrollView.frame.width {
scrollView.setContentOffset(CGPoint(x: scrollView.frame.width, y: 0), animated: false)
return
}
let page = Int(floor((scrollView.contentOffset.x - scrollView.frame.width / 2) / scrollView.frame.width) + 1)
if currentPage != page {
currentPage = page
}
lastContentOffset = scrollView.contentOffset.x
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if let presented = monthViews[presented] {
prepareTopMarkersOnMonthView(presented, hidden: true)
}
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if pageChanged {
switch direction {
case .left: scrolledLeft()
case .right: scrolledRight()
default: break
}
}
updateSelection()
updateLayoutIfNeeded()
pageLoadingEnabled = true
direction = .none
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView,
willDecelerate decelerate: Bool) {
if decelerate {
let rightBorder = scrollView.frame.width
if scrollView.contentOffset.x <= rightBorder {
direction = .right
} else {
direction = .left
}
}
for monthView in monthViews.values {
prepareTopMarkersOnMonthView(monthView, hidden: false)
}
}
}
| mit | a4ea87d9cd998ab78bdad67d42560ada | 38.714286 | 132 | 0.619629 | 6.124442 | false | false | false | false |
primetimer/PrimeFactors | PrimeFactors/Classes/PhiTable.swift | 1 | 5976 | //
// PhiTable.swift
// PrimeBase
//
// Created by Stephan Jancar on 29.11.16.
// Copyright © 2016 esjot. All rights reserved.
//
import Foundation
public class PhiTable {
var usebackward = true //Use backward calculation via known pi
var usecache = true
var pcalc : PrimeCalculator!
var pitable : PiTable!
var maxpintable : UInt64 = 0
var primorial : [UInt64] = []
var primorial1 : [UInt64] = []
var phi : [[UInt64]] = []
var phitablesize = 7
var phicache = NSCache<NSString, NSNumber>()
func ReleaseCache() {
phicache = NSCache<NSString, NSNumber>()
}
var first : [UInt64] = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,71,73,79,83,89,97]
private func CalcPrimorial(maxp: UInt64 = 23) { //23 because 2*3*...*23 < UInt32.max
var prod : UInt64 = 1
var prod1 : UInt64 = 1
for p in self.first {
if p > maxp {
break
}
prod = prod * p
prod1 = prod1 * (p-1)
primorial.append(prod)
primorial1.append(prod1)
}
}
init(pcalc : PrimeCalculator, pitable: PiTable, phitablesize : Int = 7) {
//verbose = piverbose
self.pcalc = pcalc
self.pitable = pitable
self.phitablesize = phitablesize
self.maxpintable = pitable.Pin(m: pitable.ValidUpto())
CalcPrimorial()
Initphitable()
}
private func Initphitable()
{
phi = [[UInt64]] (repeating: [], count: phitablesize)
for l in 0..<phitablesize
{
phi[l] = [UInt64] (repeating : 0, count : Int(primorial[l]))
var count : UInt64 = 0
for k in 0..<primorial[l]
{
var relativeprime = true
for pindex in 0...l
{
let p = pitable.NthPrime(n: pindex+1)
if k % p == 0 {
relativeprime = false
break
}
}
if relativeprime {
count = count + 1
}
phi[l][Int(k)] = count
}
}
}
//The Number of integers of the for form n = pi * pj
//with pj >= pi > a-tth Prime
func P2(x: UInt64, a: UInt64) -> UInt64 {
#if true
let starttime = CFAbsoluteTimeGetCurrent()
#endif
let r2 = x.squareRoot()
let pib = pitable.Pin(m: r2)
if a >= pib { return 0 }
var p2 : UInt64 = 0
for i in a+1...pib {
let p = pitable.NthPrime(n: Int(i))
let xp = x / p
let pi = pitable.Pin(m: xp)
p2 = p2 + pi - (i - 1)
}
#if false
phideltap2time = phideltap2time + CFAbsoluteTimeGetCurrent() - starttime
#endif
return p2
}
var rekurs = 0
//The Number of integers of the for form n = pi * pj * pk
//with k >= pj >= pi > a-tth Prime
func P3(x: UInt64, a: UInt64) -> UInt64 {
let r3 = x.iroot3()
let pi3 = pitable.Pin(m: r3)
if a >= pi3 { return 0 }
var p3 : UInt64 = 0
for i in a+1...pi3 {
let p = pitable.NthPrime(n: Int(i))
let xp = x / p
let rxp = xp.squareRoot()
let bi = pitable.Pin(m: rxp)
for j in i...bi {
let q = pitable.NthPrime(n: (Int(j)))
let xpq = x / (p*q)
let pixpq = pitable.Pin(m: xpq)
p3 = p3 + pixpq - (j-1)
}
}
return p3
}
//Calculates Phi aka Legendre sum
func Phi(x: UInt64, nr: Int) -> UInt64 {
if x == 0 { return 0 }
assert (UInt64(nr) <= pitable.ValidUpto())
// phi(x) = primorial1 * (x / primorial) + phitable
if nr == 0 { return x }
if nr == 1 { return x - x/2 }
if nr == 2 { return x - x/2 - x/3 + x/6 }
if nr == 3 { return x - x/2 - x/3 + x/6 - x/5 + x/10 + x/15 - x/30 }
if x < pitable.NthPrime(n: nr+1) { return 1 }
if nr < phitablesize {
let t = x / primorial[nr-1]
let r = x - primorial[nr-1] * t
let q = primorial1[nr-1]
let y = q * t + phi[nr-1][Int(r)]
return y
}
//Look in Cache
var nskey : NSString = ""
if usecache && nr < 500 {
let key = String(x) + ":" + String(nr)
nskey = NSString(string: key)
if let cachedVersion = phicache.object(forKey: nskey) {
return cachedVersion.uint64Value
}
}
rekurs = rekurs + 1
let value = PhiCalc(x: x, nr: nr)
if usecache && nr < 500 {
let cachevalue = NSNumber(value: value)
phicache.setObject(cachevalue, forKey: nskey)
}
//print("time: ",rekurs, x,nr,phideltafwdtime,phideltap2time)
rekurs = rekurs - 1
return value
}
var phideltafwdtime = 0.0
var phideltap2time = 0.0
private func IsPhiByPix(x: UInt64, a: Int) -> Bool
{
if x>maxpintable {
return false
}
let pa = pitable.NthPrime(n: a)
if x < pa*pa {
return true
}
return false
}
private func PhiCalc(x: UInt64, nr : Int) -> UInt64
{
#if false
if IsPhiByPix(x: x,a: nr) {
let pix = pitable.Pin(m: x)
let phi = pix - UInt64(nr) + 1
return phi
}
#endif
if usebackward && x < maxpintable {
// Use backward Formula
// phi = 1 + pi(x) - nr + P2(x,nr) + P3(x,nr)
// for x in p(nr) ... p(nr+1)^4
let pa = pitable.NthPrime(n: nr)
//let pa1 = pitable.NthPrime(n: nr+1)
if x <= pa {
return 1
}
let papow2 = pa * pa
let papow4 = papow2 * papow2
#if false
if pa1pow >= UInt64(UInt32.max / 2) { pa1pow = x+1 } // to avoid overflow
else { pa1pow = pa1pow * pa1pow }
#endif
if x < papow4 {
let pix = pitable.Pin(m: x)
var p2 : UInt64 = 0
if x >= papow2 {
p2 = P2(x: x, a : UInt64(nr))
}
var p3 : UInt64 = 0
if x >= pa * pa * pa {
p3 = P3(x: x, a: UInt64(nr))
}
let phi = 1 + pix + p2 + p3 - UInt64(nr)
return phi
}
}
//Use forward Recursion
#if true
let starttime = CFAbsoluteTimeGetCurrent()
#endif
var result = Phi(x: x, nr: phitablesize - 1)
#if false
phideltafwdtime = phideltafwdtime + CFAbsoluteTimeGetCurrent() - starttime
#endif
var i = phitablesize
while i <= nr {
let p = self.pitable.NthPrime(n: i)
let n2 = x / p
if n2 < p { break }
let dif = Phi(x: n2,nr: i-1)
result = result - dif
i = i + 1
}
var k = nr
while x < self.pitable.NthPrime(n: k+1) {
k = k - 1
}
let delta = (Int(i)-Int(k)-1)
result = UInt64(Int(result) + delta)
return result
}
}
| mit | 71aca7725075b27619976174c64c08ff | 19.67474 | 97 | 0.570879 | 2.490621 | false | false | false | false |
JTWang4778/JTLive | MuXueLive/LiveListCell.swift | 1 | 2213 | //
// LiveListCell.swift
// MuXueLive
//
// Created by 王锦涛 on 2016/12/17.
// Copyright © 2016年 JTWang. All rights reserved.
//
import UIKit
import Kingfisher
class LiveListCell: UITableViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var cityLabel: UILabel!
@IBOutlet weak var onlineLabel: UILabel!
@IBOutlet weak var liveImageView: UIImageView!
var clickBlock:((_ liverModel: LiveModel) -> ())?
var liveModel: LiveModel! {
didSet{
self.nameLabel.text = liveModel.liver.nick!
self.cityLabel.text = liveModel.city!
let online = liveModel.online_users!
self.onlineLabel.text = "\(online)人在看"
var iconImageUrlStr = liveModel.liver.portrait!
if iconImageUrlStr.hasPrefix("http://img2.inke.cn/") == false {
iconImageUrlStr = "http://img2.inke.cn/" + iconImageUrlStr
}
let iconUrl = URL.init(string: iconImageUrlStr)!
self.liveImageView.kf.setImage(with: iconUrl, placeholder: UIImage.init(named: "avatar_default"), options: nil, progressBlock: nil, completionHandler: nil)
self.iconImageView.kf.setImage(with: iconUrl, placeholder: UIImage.init(named: "avatar_default"), options: nil, progressBlock: nil, completionHandler: nil)
}
}
override func awakeFromNib() {
super.awakeFromNib()
self.iconImageView.layer.cornerRadius = 25
self.iconImageView.layer.masksToBounds = true
self.iconImageView.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(self.didClickIconimageView))
self.iconImageView.addGestureRecognizer(tap)
}
func didClickIconimageView() {
// 拿到用户模型 展示上去
self.clickBlock!(self.liveModel)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 976b09b03c549ed3d1680f78d5ac4964 | 30.114286 | 167 | 0.631313 | 4.546973 | false | false | false | false |
Hypercoin/Hypercoin-mac | Hypercoin/Services/CoinMarketCapService.swift | 1 | 1631 | //
// CoinMarketCap.swift
// Hypercoin
//
// Created by Axel Etcheverry on 18/10/2017.
// Copyright © 2017 Hypercoin. All rights reserved.
//
import Foundation
import Alamofire
import RxSwift
import RxAlamofire
import Marshal
class CoinMarketCapService {
fileprivate var url = "https://api.coinmarketcap.com/v1/ticker/"
func getStubMarketCap() -> Observable<[MarketCap]> {
return Observable.create { observer in
let jsonData = JsonHelper.readJsonFile(fileName: "sample")
guard let json = try? JSONParser.JSONArrayWithData(jsonData) else {
observer.onCompleted()
return Disposables.create()
}
let coins = json.flatMap { item in
return try? MarketCap(object: item)
}
observer.on(.next(coins))
observer.onCompleted()
return Disposables.create()
}
}
func getMarketCap() -> Observable<[MarketCap]> {
return RxAlamofire.request(.get, self.url)
.debug()
.flatMap { request in
return Observable.create { observer in
_ = request.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.rx.data().subscribe { data in
do {
guard let jsonData = data.element else {
// @TODO: Create custom error
observer.on(.completed)
return
}
let json = try JSONParser.JSONArrayWithData(jsonData)
let coins = json.flatMap { item in
return try? MarketCap(object: item)
}
observer.on(.next(coins))
observer.on(.completed)
} catch let error {
observer.on(.error(error))
}
}
return Disposables.create()
}
}
}
}
| mit | 615a672b40e9e5d5f2aff0a1679a771e | 21.638889 | 70 | 0.646626 | 3.638393 | false | false | false | false |
LYM-mg/DemoTest | 其他功能/SwiftyDemo/SwiftyDemo/TbaleViewContainTBController.swift | 1 | 9758 | //
// TbaleViewContainTBController.swift
// SwiftyDemo
//
// Created by newunion on 2019/4/8.
// Copyright © 2019年 firestonetmt. All rights reserved.
//
import UIKit
class TbaleViewContainTBController: UIViewController {
fileprivate lazy var tableView: UITableView = { [unowned self] in
let tb = UITableView(frame: .zero, style: .plain)
tb.backgroundColor = UIColor.white
tb.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tb.dataSource = self
tb.delegate = self
tb.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 64, right: 0)
tb.estimatedRowHeight = 44 // 设置估算高度
tb.rowHeight = UITableView.automaticDimension // 告诉tableView我们cell的高度是自动的
tb.register(MGTBCell.self, forCellReuseIdentifier: "CellID")
if #available(iOS 11.0, *){
tb.contentInsetAdjustmentBehavior = .never
}else {
self.automaticallyAdjustsScrollViewInsets = false
}
return tb
}()
var headerView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.randomColor()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: #selector(self.rightClick))
self.view.addSubview(self.tableView)
tableView.snp.makeConstraints { (make) in
make.left.right.bottom.equalTo(self.view)
make.top.equalTo(self.view).offset(64)
}
let headerView = UIView()
headerView.backgroundColor = UIColor.red
tableView.tableHeaderView = headerView
self.headerView = headerView
headerView.snp.makeConstraints { (make) in
make.left.right.equalTo(self.view)
make.width.equalTo(self.view.mg_width)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let btn = UIButton()
let lb = UILabel()
btn.backgroundColor = UIColor.randomColor()
btn.setTitle("傻瓜", for: .normal)
btn.addTarget(self, action: #selector(changeClick), for: .touchUpInside)
lb.backgroundColor = UIColor.randomColor()
lb.text = "你就是一个笨蛋,是吗?"
lb.numberOfLines = 0;
lb.tag = 100;
headerView.addSubview(btn)
headerView.addSubview(lb)
lb.snp.makeConstraints { (make) in
make.left.right.equalTo(headerView)
make.top.equalTo(headerView).offset(10)
make.bottom.equalTo(btn.snp.top).offset(-10)
}
btn.snp.makeConstraints { (make) in
make.left.right.equalTo(headerView)
make.bottom.equalTo(headerView).offset(-10)
}
tableView.reloadData()
}
deinit {
print("\(self) deinit")
}
@objc func changeClick() {
var str = "你就是一个笨蛋,是吗?不🙅♂️,我不是,你才是笨蛋!那你是一个傻瓜,笨笨哒,哈哈哈哈哈。不🙅♀️,我也不是一个傻瓜,我是一个可爱的人。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。"
/// 随机数
let count = str.count
let randonNumber = Int(arc4random_uniform(UInt32(count-11))+11)
str = String(str.prefix(randonNumber))
print(str)
let lb: UILabel = self.tableView.tableHeaderView?.viewWithTag(100) as! UILabel
lb.text = str
UIView.animate(withDuration: 0.5) {
self.tableView.layoutIfNeeded()
self.tableView.tableHeaderView = self.headerView;
}
}
@objc func rightClick() {
// self.navigationController?.pushViewController(TbaleViewContainTBController(), animated: true)
}
}
extension TbaleViewContainTBController:UITableViewDataSource,UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 15
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath) as! MGTBCell
cell.index = indexPath.row;
cell.backgroundColor = UIColor.randomColor()
return cell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 35
}
// func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// return 44
// }
}
class MGTBCell: UITableViewCell {
var index: NSInteger? {
didSet {
let height = self.tableView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
print("contentSize.height=\(self.tableView.contentSize.height) -- \(height)")
// self.tableView.mg_height = self.tableView.contentSize.height
self.tableView.reloadData()
self.mg_height = self.tableView.contentSize.height;
DispatchQueue.main.asyncAfter(deadline: .now()+0.001) {
self.tableView.snp.makeConstraints { (make) in
make.height.equalTo(self.tableView.contentSize.height)
}
self.superview?.layoutIfNeeded()
self.contentView.layoutIfNeeded()
}
}
}
fileprivate lazy var tableView: UITableView = { [unowned self] in
let tb = UITableView(frame: .zero, style: .plain)
tb.backgroundColor = UIColor.white
tb.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tb.dataSource = self
tb.delegate = self
tb.isScrollEnabled = false
if #available(iOS 11.0, *) {
tb.contentInsetAdjustmentBehavior = .never
}else {
}
// tb.estimatedRowHeight = 44 // 设置估算高度
// tb.rowHeight = UITableView.automaticDimension // 告诉tableView我们cell的高度是自动的
tb.rowHeight = 44
tb.register(UITableViewCell.self, forCellReuseIdentifier: "CellID111")
return tb
}()
var block:((_ btn: UIButton, _ cell:MGTBCell) -> ())?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.contentView.addSubview(self.tableView)
tableView.snp.makeConstraints { (make) in
make.edges.equalTo(self.contentView)
make.width.equalTo(MGScreenW)
make.height.equalTo(self.contentView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func btnClick(_ btn: UIButton) {
if (block != nil) {
self.block!(btn,self)
}
}
}
extension MGTBCell:UITableViewDataSource,UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch index {
case 0,2,5,8,12:
return 3
case 1,4,9:
return 1
default:
return 2
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellID111", for: indexPath)
switch index {
case 0,2,5,8,12:
cell.backgroundColor = UIColor.red
case 1,4,9:
cell.backgroundColor = UIColor.green
default:
cell.backgroundColor = UIColor.blue
}
cell.textLabel?.text = "MGindex=\(String(describing: index!)) -- \(indexPath.row)"
return cell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 35
}
}
| mit | f64dcc34b0a91ded340de4528e35aa81 | 37.087963 | 733 | 0.649568 | 3.672768 | false | false | false | false |
YoungFuRui/douyu | douyuTV/douyuTV/Classes/Home/Controller/RecommendViewController.swift | 1 | 4011 | //
// RecommendViewController.swift
// douyuTV
//
// Created by free on 17/2/20.
// Copyright © 2017年 free. All rights reserved.
//
import UIKit
private let kItemMargin : CGFloat = 10
private let kItemW = (kScreenW - 3 * kItemMargin) / 2
private let kNormalItemH = kItemW * 3 / 4
private let kPrettyItemH = kItemW * 4 / 3
private let kHeaderViewH : CGFloat = 50
private let kNormalCellID = "kNormalCellID"
private let kHeaderViewID = "kHeaderViewID"
private let kPrettyCellID = "kPrettyCellID"
class RecommendViewController: UIViewController {
// MARK:- 懒加载属性
lazy var collectionView : UICollectionView = {[unowned self] in
// 1.创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin)
// 2.创建UICollectionView
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.backgroundColor = UIColor.white
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
// MARK:- 系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
// 设置UI界面
setupUI()
}
}
// MARK:- 设置UI界面内容
extension RecommendViewController {
func setupUI() {
// 1.将UICollectionView添加到控制器的View中
view.addSubview(collectionView)
}
}
// MARK:- 遵守UICollectionView的数据源协议
extension RecommendViewController : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 12
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return 8
}
return 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 1.定义cell
let cell : UICollectionViewCell!
// 2.取出cell
if indexPath.section == 1 {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath)
} else {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
// 1.取出section的HeaderView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind:kind, withReuseIdentifier: kHeaderViewID, for: indexPath)
return headerView
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
if indexPath.section == 1 {
return CGSize(width: kItemW, height: kPrettyItemH)
}
return CGSize(width: kItemW, height: kNormalItemH)
}
}
| mit | 36f8a2a9af5d2317b39e9e0eb7720c93 | 35.849057 | 186 | 0.693036 | 5.838565 | false | false | false | false |
konanxu/WeiBoWithSwift | WeiBo/WeiBo/Classes/Home/HomeTableViewController.swift | 1 | 5932 | //
// HomeTableViewController.swift
// WeiBo
//
// Created by Konan on 16/3/8.
// Copyright © 2016年 Konan. All rights reserved.
//
import UIKit
let kTableViewCellIndentifier = "kTableViewCellIndentifier"
class HomeTableViewController: BaseTableViewController {
var statuses:[Status]?
{
didSet{
tableView.reloadData()
}
}
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()
if !userLogin{
vistorView!.setUpInfo(true, imageName: "visitordiscover_feed_image_house", message: "关注一些人,回这里看看有什么惊喜")
return
}
tableView.delegate = self
setupNav()
if userLogin{
loadData()
}
tableView.registerClass(StatusTableViewCell.self, forCellReuseIdentifier: kTableViewCellIndentifier)
// tableView.estimatedRowHeight = 200
// tableView.rowHeight = UITableViewAutomaticDimension
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
}
private func loadData(){
Status.loadStatus { (models, error) -> () in
if error != nil{
return
}
self.statuses = models
}
}
let titleBtn = TitleButton()
private func setupNav(){
//初始化左右按钮
navigationItem.leftBarButtonItem = UIBarButtonItem.createBarButton("navigationbar_friendattention", target: self, action: "friendClick")
navigationItem.rightBarButtonItem = UIBarButtonItem.createBarButton("navigationbar_pop", target: self, action: "qCodeClick")
let spaRight = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
spaRight.width = -10
navigationItem.setRightBarButtonItems([spaRight,navigationItem.rightBarButtonItem!], animated: true)
let spaLeft = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
spaLeft.width = -5
navigationItem.setLeftBarButtonItems([spaLeft,navigationItem.leftBarButtonItem!], animated: true)
//初始化标题按钮
titleBtn.setTitle("Konan_Xu ", forState: UIControlState.Normal)
titleBtn.addTarget(self, action: "titleClick:", forControlEvents: UIControlEvents.TouchUpInside)
navigationItem.titleView = titleBtn
popoverAnimation.addObserver(self, forKeyPath: "isPresent", options: NSKeyValueObservingOptions.New, context: nil)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if(keyPath == "isPresent"){
titleBtn.selected = !titleBtn.selected
}
}
func titleClick(btn:TitleButton){
print(__FUNCTION__)
//弹出菜单,取出vc 设置转场自定义
let sb = UIStoryboard(name: "PopoverViewController", bundle: nil)
let vc = sb.instantiateInitialViewController()
vc?.transitioningDelegate = popoverAnimation
vc?.modalPresentationStyle = UIModalPresentationStyle.Custom
presentViewController(vc!, animated: true, completion: nil)
}
func friendClick(){
print(__FUNCTION__)
}
func qCodeClick(){
let sb = UIStoryboard(name: "QRCodeViewController", bundle: nil)
let vc = sb.instantiateInitialViewController()
presentViewController(vc!, animated: true, completion: nil)
}
deinit{
super.viewDidLoad()
popoverAnimation.removeObserver(self, forKeyPath: "isPresent")
}
override func viewWillAppear(animated: Bool) {
if !userLogin{
vistorView!.centerViewUpdateConstraints()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
rowCache.removeAll()
}
private lazy var popoverAnimation:PopoverAnimation = {
let pop = PopoverAnimation()
pop.popFrame = CGRect(x: 80, y: 56, width: 150, height: 300)
return pop
}()
var rowCache: [Int: CGFloat] = [Int: CGFloat]()
}
extension HomeTableViewController{
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(kTableViewCellIndentifier, forIndexPath: indexPath) as! StatusTableViewCell
cell.status = statuses![indexPath.row]
// cell.textLabel?.text = statuses![indexPath.row].text
// cell.detailTextLabel?.text = statuses![indexPath.row].user?.name
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let status = statuses![indexPath.row]
if let height = rowCache[status.id]
{
print("从缓存中获取")
return height
}
let cell = tableView.dequeueReusableCellWithIdentifier(kTableViewCellIndentifier) as! StatusTableViewCell
let height = cell.rowHeight(status)
rowCache[status.id] = height
print("新的计算")
return height
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return statuses?.count ?? 0
}
}
| mit | 71f1ddf6934ef8c503ce9c2ba0afc0b3 | 33.252941 | 157 | 0.651211 | 5.457357 | false | false | false | false |
Shjv4/VntripFramework | VntripFramework/Classes/VNTTextField.swift | 1 | 3476 | //
// VNTTextField.swift
// VntripFramework
//
// Created by Hoang NA on 2/23/17.
// Copyright © 2017 VNTrip OTA. All rights reserved.
//
import UIKit
@IBDesignable
class VNTTextField: UITextField {
/// The color of left view, if not set the default color of left view will be set to Blue
@IBInspectable var leftImageBackgroundColor:UIColor? {
didSet {
if let imageView = self.viewWithTag(100) {
imageView.tintColor = leftImageBackgroundColor
}
}
}
/// The frame of left image view
@IBInspectable var leftImageRect:CGRect? = nil {
didSet {
if let imageView = self.viewWithTag(100) {
imageView.frame = leftImageRect!
imageView.setNeedsDisplay()
}
}
}
/// The image of left view
@IBInspectable var leftImage:UIImage? = nil {
didSet {
let imageView = UIImageView(frame: CGRect(x: 10, y: 10, width: 16, height: 16))
imageView.contentMode = .center
imageView.image = leftImage?.withRenderingMode(.alwaysTemplate)
imageView.tag = 100
self.addSubview(imageView)
}
}
/// The color of right view, if not set the default color of right view will be set to Blue
@IBInspectable var rightImageBackgroundColor:UIColor? {
didSet {
self.rightView?.tintColor = rightImageBackgroundColor
}
}
/// The image of right view
@IBInspectable var rightImage:UIImage? = nil {
didSet {
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 22, height: 14))
imageView.image = rightImage?.withRenderingMode(.alwaysTemplate)
imageView.contentMode = .center
self.rightView = imageView
self.rightViewMode = .always
}
}
/// Set down icon for right view
@IBInspectable var downIconOnRightView: Bool = false {
didSet {
if downIconOnRightView == true {
let bundle = Bundle(for: self.classForCoder)
let downIcon = UIImage(named: "DownArrowIcon", in: bundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate)
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 22, height: 14))
imageView.image = downIcon
imageView.contentMode = .left
self.rightView = imageView
self.rightViewMode = .always
}
}
}
/// Inset for left indent
@IBInspectable var insetX: CGFloat = 0
/// Inset for top indent
@IBInspectable var insetY: CGFloat = 0
/// The corner radius of VNTTextField
@IBInspectable var cornerRadius:CGFloat = 0 {
didSet {
self.layer.cornerRadius = cornerRadius
self.layer.masksToBounds = cornerRadius > 0
}
}
/** Indent for text
*/
override func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: insetX, dy: insetY)
}
/** Indent for editing state text
*/
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: insetX, dy: insetY)
}
/** Indent for placeholder text
*/
override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: insetX, dy: insetY)
}
}
| mit | c7f4705fa1dee7332fd841e7bfbd0281 | 30.026786 | 131 | 0.589928 | 4.866947 | false | false | false | false |
natecook1000/swift | test/SILGen/conditional_conformance.swift | 3 | 3515 | // RUN: %target-swift-emit-silgen -enable-sil-ownership %s | %FileCheck %s
protocol P1 {
func normal()
func generic<T: P3>(_: T)
}
protocol P2 {}
protocol P3 {}
protocol P4 {
associatedtype AT
}
struct Conformance<A> {}
extension Conformance: P1 where A: P2 {
func normal() {}
func generic<T: P3>(_: T) {}
}
// CHECK-LABEL: sil_witness_table hidden <A where A : P2> Conformance<A>: P1 module conditional_conformance {
// CHECK-NEXT: method #P1.normal!1: <Self where Self : P1> (Self) -> () -> () : @$S23conditional_conformance11ConformanceVyxGAA2P1A2A2P2RzlAaEP6normalyyFTW // protocol witness for P1.normal() in conformance <A> Conformance<A>
// CHECK-NEXT: method #P1.generic!1: <Self where Self : P1><T where T : P3> (Self) -> (T) -> () : @$S23conditional_conformance11ConformanceVyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW // protocol witness for P1.generic<A>(_:) in conformance <A> Conformance<A>
// CHECK-NEXT: conditional_conformance (A: P2): dependent
// CHECK-NEXT: }
struct ConformanceAssoc<A> {}
extension ConformanceAssoc: P1 where A: P4, A.AT: P2 {
func normal() {}
func generic<T: P3>(_: T) {}
}
// CHECK-LABEL: sil_witness_table hidden <A where A : P4, A.AT : P2> ConformanceAssoc<A>: P1 module conditional_conformance {
// CHECK-NEXT: method #P1.normal!1: <Self where Self : P1> (Self) -> () -> () : @$S23conditional_conformance16ConformanceAssocVyxGAA2P1A2A2P4RzAA2P22ATRpzlAaEP6normalyyFTW // protocol witness for P1.normal() in conformance <A> ConformanceAssoc<A>
// CHECK-NEXT: method #P1.generic!1: <Self where Self : P1><T where T : P3> (Self) -> (T) -> () : @$S23conditional_conformance16ConformanceAssocVyxGAA2P1A2A2P4RzAA2P22ATRpzlAaEP7genericyyqd__AA2P3Rd__lFTW // protocol witness for P1.generic<A>(_:) in conformance <A> ConformanceAssoc<A>
// CHECK-NEXT: conditional_conformance (A: P4): dependent
// CHECK-NEXT: conditional_conformance (A.AT: P2): dependent
// CHECK-NEXT: }
/*
FIXME: same type constraints are modelled incorrectly.
struct SameTypeConcrete<B> {}
extension SameTypeConcrete: P1 where B == Int {
func normal() {}
func generic<T: P3>(_: T) {}
}
struct SameTypeGeneric<C, D> {}
extension SameTypeGeneric: P1 where C == D {
func normal() {}
func generic<T: P3>(_: T) {}
}
struct SameTypeGenericConcrete<E, F> {}
extension SameTypeGenericConcrete: P1 where E == [F] {
func normal() {}
func generic<T: P3>(_: T) {}
}
struct Everything<G, H, I, J, K, L> {}
extension Everything: P1 where G: P2, H == Int, I == J, K == [L] {
func normal() {}
func generic<T: P3>(_: T) {}
}
*/
struct IsP2: P2 {}
struct IsNotP2 {}
class Base<A> {}
extension Base: P1 where A: P2 {
func normal() {}
func generic<T: P3>(_: T) {}
}
// CHECK-LABEL: sil_witness_table hidden <A where A : P2> Base<A>: P1 module conditional_conformance {
// CHECK-NEXT: method #P1.normal!1: <Self where Self : P1> (Self) -> () -> () : @$S23conditional_conformance4BaseCyxGAA2P1A2A2P2RzlAaEP6normalyyFTW // protocol witness for P1.normal() in conformance <A> Base<A>
// CHECK-NEXT: method #P1.generic!1: <Self where Self : P1><T where T : P3> (Self) -> (T) -> () : @$S23conditional_conformance4BaseCyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW // protocol witness for P1.generic<A>(_:) in conformance <A> Base<A>
// CHECK-NEXT: conditional_conformance (A: P2): dependent
// CHECK-NEXT: }
// These don't get separate witness tables, but shouldn't crash anything.
class SubclassGood: Base<IsP2> {}
class SubclassBad: Base<IsNotP2> {}
| apache-2.0 | c8fa7530896a4869eda63c04bee6fd6b | 42.9375 | 288 | 0.687055 | 3.011997 | false | false | false | false |
oskarpearson/rileylink_ios | RileyLink/KeychainManager.swift | 2 | 8325 | //
// KeychainManager.swift
// Loop
//
// Created by Nate Racklyeft on 6/26/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
import Security
enum KeychainManagerError: Error {
case add(OSStatus)
case copy(OSStatus)
case delete(OSStatus)
case unknownResult
}
/**
Influenced by https://github.com/marketplacer/keychain-swift
*/
struct KeychainManager {
typealias Query = [String: NSObject]
var accessibility: CFString = kSecAttrAccessibleAfterFirstUnlock
var accessGroup: String?
struct InternetCredentials {
let username: String
let password: String
let url: URL
}
// MARK: - Convenience methods
private func query(by class: CFString) -> Query {
var query: Query = [kSecClass as String: `class`]
if let accessGroup = accessGroup {
query[kSecAttrAccessGroup as String] = accessGroup as NSObject?
}
return query
}
private func queryForGenericPassword(by service: String) -> Query {
var query = self.query(by: kSecClassGenericPassword)
query[kSecAttrService as String] = service as NSObject?
return query
}
private func queryForInternetPassword(account: String? = nil, url: URL? = nil) -> Query {
var query = self.query(by: kSecClassInternetPassword)
if let account = account {
query[kSecAttrAccount as String] = account as NSObject?
}
if let url = url, let components = URLComponents(url: url, resolvingAgainstBaseURL: true) {
for (key, value) in components.keychainAttributes {
query[key] = value
}
}
return query
}
private func updatedQuery(_ query: Query, withPassword password: String) throws -> Query {
var query = query
guard let value = password.data(using: String.Encoding.utf8) else {
throw KeychainManagerError.add(errSecDecode)
}
query[kSecValueData as String] = value as NSObject?
query[kSecAttrAccessible as String] = accessibility
return query
}
func delete(_ query: Query) throws {
let statusCode = SecItemDelete(query as CFDictionary)
guard statusCode == errSecSuccess || statusCode == errSecItemNotFound else {
throw KeychainManagerError.delete(statusCode)
}
}
// MARK: – Generic Passwords
func replaceGenericPassword(_ password: String?, forService service: String) throws {
var query = queryForGenericPassword(by: service)
try delete(query)
guard let password = password else {
return
}
query = try updatedQuery(query, withPassword: password)
let statusCode = SecItemAdd(query as CFDictionary, nil)
guard statusCode == errSecSuccess else {
throw KeychainManagerError.add(statusCode)
}
}
func getGenericPasswordForService(_ service: String) throws -> String {
var query = queryForGenericPassword(by: service)
query[kSecReturnData as String] = kCFBooleanTrue
query[kSecMatchLimit as String] = kSecMatchLimitOne
var result: AnyObject?
let statusCode = SecItemCopyMatching(query as CFDictionary, &result)
guard statusCode == errSecSuccess else {
throw KeychainManagerError.copy(statusCode)
}
guard let passwordData = result as? Data, let password = String(data: passwordData, encoding: String.Encoding.utf8) else {
throw KeychainManagerError.unknownResult
}
return password
}
// MARK – Internet Passwords
func setInternetPassword(_ password: String, forAccount account: String, atURL url: URL) throws {
var query = try updatedQuery(queryForInternetPassword(account: account, url: url), withPassword: password)
query[kSecAttrAccount as String] = account as NSObject?
if let components = URLComponents(url: url, resolvingAgainstBaseURL: true) {
for (key, value) in components.keychainAttributes {
query[key] = value
}
}
let statusCode = SecItemAdd(query as CFDictionary, nil)
guard statusCode == errSecSuccess else {
throw KeychainManagerError.add(statusCode)
}
}
func replaceInternetCredentials(_ credentials: InternetCredentials?, forAccount account: String) throws {
let query = queryForInternetPassword(account: account)
try delete(query)
if let credentials = credentials {
try setInternetPassword(credentials.password, forAccount: credentials.username, atURL: credentials.url)
}
}
func replaceInternetCredentials(_ credentials: InternetCredentials?, forURL url: URL) throws {
let query = queryForInternetPassword(url: url)
try delete(query)
if let credentials = credentials {
try setInternetPassword(credentials.password, forAccount: credentials.username, atURL: credentials.url)
}
}
func getInternetCredentials(account: String? = nil, url: URL? = nil) throws -> InternetCredentials {
var query = queryForInternetPassword(account: account, url: url)
query[kSecReturnData as String] = kCFBooleanTrue
query[kSecReturnAttributes as String] = kCFBooleanTrue
query[kSecMatchLimit as String] = kSecMatchLimitOne
var result: AnyObject?
let statusCode: OSStatus = SecItemCopyMatching(query as CFDictionary, &result)
guard statusCode == errSecSuccess else {
throw KeychainManagerError.copy(statusCode)
}
if let result = result as? [AnyHashable: Any], let passwordData = result[kSecValueData as String] as? Data,
let password = String(data: passwordData, encoding: String.Encoding.utf8),
let url = URLComponents(keychainAttributes: result)?.url,
let username = result[kSecAttrAccount as String] as? String
{
return InternetCredentials(username: username, password: password, url: url)
}
throw KeychainManagerError.unknownResult
}
}
private enum SecurityProtocol {
case http
case https
init?(scheme: String?) {
switch scheme?.lowercased() {
case "http"?:
self = .http
case "https"?:
self = .https
default:
return nil
}
}
init?(secAttrProtocol: CFString) {
if secAttrProtocol == kSecAttrProtocolHTTP {
self = .http
} else if secAttrProtocol == kSecAttrProtocolHTTPS {
self = .https
} else {
return nil
}
}
var scheme: String {
switch self {
case .http:
return "http"
case .https:
return "https"
}
}
var secAttrProtocol: CFString {
switch self {
case .http:
return kSecAttrProtocolHTTP
case .https:
return kSecAttrProtocolHTTPS
}
}
}
private extension URLComponents {
init?(keychainAttributes: [AnyHashable: Any]) {
self.init()
if let secAttProtocol = keychainAttributes[kSecAttrProtocol as String] {
scheme = SecurityProtocol(secAttrProtocol: secAttProtocol as! CFString)?.scheme
}
host = keychainAttributes[kSecAttrServer as String] as? String
if let port = keychainAttributes[kSecAttrPort as String] as? NSNumber, port.intValue > 0 {
self.port = port as Int?
}
if let path = keychainAttributes[kSecAttrPath as String] as? String {
self.path = path
}
}
var keychainAttributes: [String: NSObject] {
var query: [String: NSObject] = [:]
if let `protocol` = SecurityProtocol(scheme: scheme) {
query[kSecAttrProtocol as String] = `protocol`.secAttrProtocol
}
if let host = host {
query[kSecAttrServer as String] = host as NSObject
}
if let port = port {
query[kSecAttrPort as String] = port as NSObject
}
if !path.isEmpty {
query[kSecAttrPath as String] = path as NSObject
}
return query
}
}
| mit | 3efc4509dff988a59c20be95465c444e | 27.686207 | 130 | 0.631326 | 5.205882 | false | false | false | false |
huonw/swift | test/TBD/struct.swift | 1 | 7071 | // RUN: %target-swift-frontend -emit-ir -o- -parse-as-library -module-name test -validate-tbd-against-ir=missing %s
// RUN: %target-swift-frontend -emit-ir -o- -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -enable-resilience
// RUN: %target-swift-frontend -emit-ir -o- -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -enable-testing
// RUN: %target-swift-frontend -emit-ir -o- -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -enable-resilience -enable-testing
public struct PublicNothing {}
public struct PublicInit {
public init() {}
public init(public_: Int) {}
internal init(internal_: Int) {}
private init(private_: Int) {}
}
public struct PublicMethods {
public init() {}
public func publicMethod() {}
internal func internalMethod() {}
private func privateMethod() {}
}
public struct PublicProperties {
public let publicLet: Int = 0
internal let internalLet: Int = 0
private let privateLet: Int = 0
public var publicVar: Int = 0
internal var internalVar: Int = 0
private var privateVar: Int = 0
public var publicVarGet: Int { return 0 }
internal var internalVarGet: Int { return 0 }
private var privateVarGet: Int { return 0 }
public var publicVarGetSet: Int {
get { return 0 }
set {}
}
internal var internalVarGetSet: Int {
get { return 0 }
set {}
}
private var privateVarGetSet: Int {
get { return 0 }
set {}
}
}
public struct PublicSubscripts {
public subscript(publicGet _: Int) -> Int { return 0 }
internal subscript(internalGet _: Int) -> Int { return 0 }
private subscript(privateGet _: Int) -> Int { return 0 }
public subscript(publicGetSet _: Int) -> Int {
get {return 0 }
set {}
}
internal subscript(internalGetSet _: Int) -> Int {
get {return 0 }
set {}
}
private subscript(privateGetSet _: Int) -> Int {
get {return 0 }
set {}
}
}
public struct PublicStatics {
public static func publicStaticFunc() {}
internal static func internalStaticFunc() {}
private static func privateStaticFunc() {}
public static let publicLet: Int = 0
internal static let internalLet: Int = 0
private static let privateLet: Int = 0
public static var publicVar: Int = 0
internal static var internalVar: Int = 0
private static var privateVar: Int = 0
public static var publicVarGet: Int { return 0 }
internal static var internalVarGet: Int { return 0 }
private static var privateVarGet: Int { return 0 }
public static var publicVarGetSet: Int {
get { return 0 }
set {}
}
internal static var internalVarGetSet: Int {
get { return 0 }
set {}
}
private static var privateVarGetSet: Int {
get { return 0 }
set {}
}
}
public struct PublicGeneric<T, U, V> {
public var publicVar: T
internal var internalVar: U
private var privateVar: V
public var publicVarConcrete: Int = 0
internal var internalVarConcrete: Int = 0
private var privateVarConcrete: Int = 0
public init<S>(t: T, u: U, v: V, _: S) {
publicVar = t
internalVar = u
privateVar = v
}
public func publicGeneric<A>(_: A) {}
internal func internalGeneric<A>(_: A) {}
private func privateGeneric<A>(_: A) {}
public static func publicStaticGeneric<A>(_: A) {}
internal static func internalStaticGeneric<A>(_: A) {}
private static func privateStaticGeneric<A>(_: A) {}
}
internal struct InternalNothing {}
internal struct InternalInit {
internal init() {}
internal init(internal_: Int) {}
private init(private_: Int) {}
}
internal struct InternalMethods {
internal init() {}
internal func internalMethod() {}
private func privateMethod() {}
}
internal struct InternalProperties {
internal let internalLet: Int = 0
private let privateLet: Int = 0
internal var internalVar: Int = 0
private var privateVar: Int = 0
internal var internalVarGet: Int { return 0 }
private var privateVarGet: Int { return 0 }
internal var internalVarGetSet: Int {
get { return 0 }
set {}
}
private var privateVarGetSet: Int {
get { return 0 }
set {}
}
}
internal struct InternalSubscripts {
internal subscript(internalGet _: Int) -> Int { return 0 }
private subscript(privateGet _: Int) -> Int { return 0 }
internal subscript(internalGetSet _: Int) -> Int {
get {return 0 }
set {}
}
private subscript(privateGetSet _: Int) -> Int {
get {return 0 }
set {}
}
}
internal struct InternalStatics {
internal static func internalStaticFunc() {}
private static func privateStaticFunc() {}
internal static let internalLet: Int = 0
private static let privateLet: Int = 0
internal static var internalVar: Int = 0
private static var privateVar: Int = 0
internal static var internalVarGet: Int { return 0 }
private static var privateVarGet: Int { return 0 }
internal static var internalVarGetSet: Int {
get { return 0 }
set {}
}
private static var privateVarGetSet: Int {
get { return 0 }
set {}
}
}
internal struct InternalGeneric<T, U, V> {
internal var internalVar: U
private var privateVar: V
internal var internalVarConcrete: Int = 0
private var privateVarConcrete: Int = 0
internal init<S>(t: T, u: U, v: V, _: S) {
internalVar = u
privateVar = v
}
internal func internalGeneric<A>(_: A) {}
private func privateGeneric<A>(_: A) {}
internal static func internalStaticGeneric<A>(_: A) {}
private static func privateStaticGeneric<A>(_: A) {}
}
private struct PrivateNothing {}
private struct PrivateInit {
private init() {}
private init(private_: Int) {}
}
private struct PrivateMethods {
private init() {}
private func privateMethod() {}
}
private struct PrivateProperties {
private let privateLet: Int = 0
private var privateVar: Int = 0
private var privateVarGet: Int { return 0 }
private var privateVarGetSet: Int {
get { return 0 }
set {}
}
}
private struct PrivateSubscripts {
private subscript(privateGet _: Int) -> Int { return 0 }
private subscript(privateGetSet _: Int) -> Int {
get {return 0 }
set {}
}
}
private struct PrivateStatics {
private static func privateStaticFunc() {}
private static let privateLet: Int = 0
private static var privateVar: Int = 0
private static var privateVarGet: Int { return 0 }
private static var privateVarGetSet: Int {
get { return 0 }
set {}
}
}
private struct PrivateGeneric<T, U, V> {
private var privateVar: V
private var privateVarConcrete: Int = 0
private init<S>(t: T, u: U, v: V, _: S) {
privateVar = v
}
private func privateGeneric<A>(_: A) {}
private static func privateStaticGeneric<A>(_: A) {}
}
| apache-2.0 | af3ad309e025cb723060ec536f4868c7 | 24.435252 | 150 | 0.641635 | 4.290655 | false | false | false | false |
xu6148152/binea_project_for_ios | Bouncer Settings/Bouncer/BouncerBehavior.swift | 1 | 1967 | //
// BouncerBehavior.swift
// Bouncer
//
// Created by CS193p Instructor.
// Copyright (c) 2015 Stanford University. All rights reserved.
//
import UIKit
// mostly stolen from Dropit
// since Bouncer's behavior is very similar to Dropit's
// but changed "drop" terminology to "block"
class BouncerBehavior: UIDynamicBehavior
{
let gravity = UIGravityBehavior()
lazy var collider: UICollisionBehavior = {
let lazilyCreatedCollider = UICollisionBehavior()
lazilyCreatedCollider.translatesReferenceBoundsIntoBoundary = true
return lazilyCreatedCollider
}()
lazy var blockBehavior: UIDynamicItemBehavior = {
let lazilyCreatedBlockBehavior = UIDynamicItemBehavior()
lazilyCreatedBlockBehavior.allowsRotation = true
lazilyCreatedBlockBehavior.elasticity = CGFloat(NSUserDefaults.standardUserDefaults().doubleForKey("BouncerBehavior.Elasticity"))
lazilyCreatedBlockBehavior.friction = 0
lazilyCreatedBlockBehavior.resistance = 0
NSNotificationCenter.defaultCenter().addObserverForName(NSUserDefaultsDidChangeNotification,
object: nil,
queue: nil) { (notification) -> Void in
lazilyCreatedBlockBehavior.elasticity = CGFloat(NSUserDefaults.standardUserDefaults().doubleForKey("BouncerBehavior.Elasticity"))
}
return lazilyCreatedBlockBehavior
}()
override init() {
super.init()
addChildBehavior(gravity)
addChildBehavior(collider)
addChildBehavior(blockBehavior)
}
func addBlock(block: UIView) {
dynamicAnimator?.referenceView?.addSubview(block)
gravity.addItem(block)
collider.addItem(block)
blockBehavior.addItem(block)
}
func removeBlock(block: UIView) {
gravity.removeItem(block)
collider.removeItem(block)
blockBehavior.removeItem(block)
block.removeFromSuperview()
}
}
| mit | c1ed596b56b9934f898c18933388bc99 | 32.338983 | 145 | 0.700051 | 5.176316 | false | false | false | false |
RevenueCat/purchases-ios | Tests/UnitTests/Misc/XCTestCase+Extensions.swift | 1 | 2717 | //
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// XCTestCase+Extensions.swift
//
// Created by Andrés Boedo on 9/16/21.
import Foundation
@testable import RevenueCat
import XCTest
extension XCTestCase {
func expectFatalError(
expectedMessage: String,
testcase: @escaping () -> Void,
file: StaticString = #filePath,
line: UInt = #line
) {
let expectation = self.expectation(description: "expectingFatalError")
var fatalErrorReceived = false
var assertionMessage: String?
FatalErrorUtil.replaceFatalError { message, _, _ in
fatalErrorReceived = true
assertionMessage = message
expectation.fulfill()
self.unreachable()
}
DispatchQueue.global(qos: .userInitiated).async(execute: testcase)
waitForExpectations(timeout: 2) { _ in
XCTAssert(fatalErrorReceived, "fatalError wasn't received", file: file, line: line)
XCTAssertEqual(assertionMessage, expectedMessage, file: file, line: line)
FatalErrorUtil.restoreFatalError()
}
}
func expectNoFatalError(
testcase: @escaping () -> Void,
file: StaticString = #filePath,
line: UInt = #line
) {
let expectation = self.expectation(description: "expectingNoFatalError")
var fatalErrorReceived = false
FatalErrorUtil.replaceFatalError { _, _, _ in
fatalErrorReceived = true
self.unreachable()
}
DispatchQueue.global(qos: .userInitiated).async {
testcase()
expectation.fulfill()
}
waitForExpectations(timeout: 2) { _ in
XCTAssert(!fatalErrorReceived, "fatalError was received", file: file, line: line)
FatalErrorUtil.restoreFatalError()
}
}
}
/// Similar to `XCTUnrap` but it allows an `async` closure.
@MainActor
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *)
func XCTAsyncUnwrap<T>(
_ expression: @autoclosure () async throws -> T?,
_ message: @autoclosure () -> String = "",
file: StaticString = #filePath,
line: UInt = #line
) async throws -> T {
let value = try await expression()
return try XCTUnwrap(
value,
message(),
file: file,
line: line
)
}
private extension XCTestCase {
func unreachable() -> Never {
repeat {
RunLoop.current.run()
} while (true)
}
}
| mit | 113f64af0b4a349ce579f56b7a5a4c8b | 26.16 | 95 | 0.61377 | 4.595601 | false | true | false | false |
milseman/swift | test/SILOptimizer/devirt_covariant_return.swift | 4 | 7900 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -O -Xllvm -disable-sil-cm-rr-cm=0 -Xllvm -sil-inline-generics=false -primary-file %s -emit-sil -sil-inline-threshold 1000 -sil-verify-all | %FileCheck %s
// Make sure that we can dig all the way through the class hierarchy and
// protocol conformances with covariant return types correctly. The verifier
// should trip if we do not handle things correctly.
//
// TODO: this is not working right now: rdar://problem/33461095
// As a side-test it also checks if all allocs can be promoted to the stack.
// CHECK-LABEL: sil hidden @_T023devirt_covariant_return6driveryyF : $@convention(thin) () -> () {
// CHECK: bb0
// CHECK: alloc_ref
// CHECK: alloc_ref
// CHECK: alloc_ref
// CHECK: function_ref @unknown1a : $@convention(thin) () -> ()
// CHECK: apply
// CHECK: function_ref @defenestrate : $@convention(thin) () -> ()
// CHECK: apply
// CHECK: function_ref @unknown2a : $@convention(thin) () -> ()
// CHECK: apply
// CHECK: apply
// CHECK: function_ref @unknown3a : $@convention(thin) () -> ()
// CHECK: apply
// CHECK: apply
// CHECK: tuple
// CHECK: return
@_silgen_name("unknown1a")
func unknown1a() -> ()
@_silgen_name("unknown1b")
func unknown1b() -> ()
@_silgen_name("unknown2a")
func unknown2a() -> ()
@_silgen_name("unknown2b")
func unknown2b() -> ()
@_silgen_name("unknown3a")
func unknown3a() -> ()
@_silgen_name("unknown3b")
func unknown3b() -> ()
@_silgen_name("defenestrate")
func defenestrate() -> ()
class B<T> {
// We do not specialize typealias's correctly now.
//typealias X = B
func doSomething() -> B<T> {
unknown1a()
return self
}
// See comment in protocol P
//class func doSomethingMeta() {
// unknown1b()
//}
func doSomethingElse() {
defenestrate()
}
}
class B2<T> : B<T> {
// When we have covariance in protocols, change this to B2.
// We do not specialize typealias correctly now.
//typealias X = B
override func doSomething() -> B2<T> {
unknown2a()
return self
}
// See comment in protocol P
//override class func doSomethingMeta() {
// unknown2b()
//}
}
class B3<T> : B2<T> {
override func doSomething() -> B3<T> {
unknown3a()
return self
}
}
func WhatShouldIDo<T>(_ b : B<T>) -> B<T> {
b.doSomething().doSomethingElse()
return b
}
func doSomethingWithB<T>(_ b : B<T>) {
}
struct S {}
func driver() -> () {
let b = B<S>()
let b2 = B2<S>()
let b3 = B3<S>()
WhatShouldIDo(b)
WhatShouldIDo(b2)
WhatShouldIDo(b3)
}
driver()
public class Bear {
public init?(fail: Bool) {
if fail { return nil }
}
// Check that devirtualizer can handle convenience initializers, which have covariant optional
// return types.
// CHECK-LABEL: sil @_T023devirt_covariant_return4BearC{{[_0-9a-zA-Z]*}}fc
// CHECK: checked_cast_br [exact] %{{.*}} : $Bear to $PolarBear
// CHECK: upcast %{{.*}} : $Optional<PolarBear> to $Optional<Bear>
// CHECK: }
public convenience init?(delegateFailure: Bool, failAfter: Bool) {
self.init(fail: delegateFailure)
if failAfter { return nil }
}
}
final class PolarBear: Bear {
override init?(fail: Bool) {
super.init(fail: fail)
}
init?(chainFailure: Bool, failAfter: Bool) {
super.init(fail: chainFailure)
if failAfter { return nil }
}
}
class Payload {
let value: Int32
init(_ n: Int32) {
value = n
}
func getValue() -> Int32 {
return value
}
}
final class Payload1: Payload {
override init(_ n: Int32) {
super.init(n)
}
}
class C {
func doSomething() -> Payload? {
return Payload(1)
}
}
final class C1:C {
// Override base method, but return a non-optional result
override func doSomething() -> Payload {
return Payload(2)
}
}
final class C2:C {
// Override base method, but return a non-optional result of a type,
// which is derived from the expected type.
override func doSomething() -> Payload1 {
return Payload1(2)
}
}
// Check that the Optional return value from doSomething
// gets properly unwrapped into a Payload object and then further
// devirtualized.
// CHECK-LABEL: sil shared [noinline] @_T023devirt_covariant_return7driver1s5Int32VAA2C1CFTf4d_n
// CHECK: integer_literal $Builtin.Int32, 2
// CHECK: struct $Int32 (%{{.*}} : $Builtin.Int32)
// CHECK-NOT: class_method
// CHECK-NOT: function_ref
// CHECK: return
@inline(never)
func driver1(_ c: C1) -> Int32 {
return c.doSomething().getValue()
}
// Check that the Optional return value from doSomething
// gets properly unwrapped into a Payload object and then further
// devirtualized.
// CHECK-LABEL: sil shared [noinline] @_T023devirt_covariant_return7driver3s5Int32VAA1CCFTf4g_n
// CHECK: bb{{[0-9]+}}(%{{[0-9]+}} : $C2):
// CHECK-NOT: bb{{.*}}:
// check that for C2, we convert the non-optional result into an optional and then cast.
// CHECK: enum $Optional
// CHECK-NEXT: upcast
// CHECK: return
@inline(never)
func driver3(_ c: C) -> Int32 {
return c.doSomething()!.getValue()
}
public class D {
let v: Int32
init(_ n: Int32) {
v = n
}
}
public class D1 : D {
public func foo() -> D? {
return nil
}
public func boo() -> Int32 {
return foo()!.v
}
}
let sD = D(0)
public class D2: D1 {
// Override base method, but return a non-optional result
override public func foo() -> D {
return sD
}
}
// Check that the boo call gets properly devirtualized and that
// that D2.foo() is inlined thanks to this.
// CHECK-LABEL: sil shared [noinline] @_T023devirt_covariant_return7driver2s5Int32VAA2D2CFTf4g_n
// CHECK-NOT: class_method
// CHECK: checked_cast_br [exact] %{{.*}} : $D1 to $D2
// CHECK: bb2
// CHECK: global_addr
// CHECK: load
// CHECK: ref_element_addr
// CHECK: bb3
// CHECK: class_method
// CHECK: }
@inline(never)
func driver2(_ d: D2) -> Int32 {
return d.boo()
}
class AA {
}
class BB : AA {
}
class CCC {
@inline(never)
func foo(_ b: BB) -> (AA, AA) {
return (b, b)
}
}
class DDD : CCC {
@inline(never)
override func foo(_ b: BB) -> (BB, BB) {
return (b, b)
}
}
class EEE : CCC {
@inline(never)
override func foo(_ b: BB) -> (AA, AA) {
return (b, b)
}
}
// Check that c.foo() is devirtualized, because the optimizer can handle the casting the return type
// correctly, i.e. it can cast (BBB, BBB) into (AAA, AAA)
// CHECK-LABEL: sil shared [noinline] @_T023devirt_covariant_return37testDevirtOfMethodReturningTupleTypesAA2AAC_ADtAA3CCCC_AA2BBC1btFTf4gg_n
// CHECK: checked_cast_br [exact] %{{.*}} : $CCC to $CCC
// CHECK: checked_cast_br [exact] %{{.*}} : $CCC to $DDD
// CHECK: checked_cast_br [exact] %{{.*}} : $CCC to $EEE
// CHECK: class_method
// CHECK: }
@inline(never)
func testDevirtOfMethodReturningTupleTypes(_ c: CCC, b: BB) -> (AA, AA) {
return c.foo(b)
}
class AAAA {
}
class BBBB : AAAA {
}
class CCCC {
let a: BBBB
var foo : (AAAA, AAAA) {
@inline(never)
get {
return (a, a)
}
}
init(x: BBBB) { a = x }
}
class DDDD : CCCC {
override var foo : (BBBB, BBBB) {
@inline(never)
get {
return (a, a)
}
}
}
// Check devirtualization of methods with optional results, where
// optional results need to be casted.
// CHECK-LABEL: sil shared [noinline] @{{.*}}testOverridingMethodWithOptionalResult
// CHECK: checked_cast_br [exact] %{{.*}} : $F to $F
// CHECK: checked_cast_br [exact] %{{.*}} : $F to $G
// CHECK: switch_enum
// CHECK: checked_cast_br [exact] %{{.*}} : $F to $H
// CHECK: switch_enum
@inline(never)
public func testOverridingMethodWithOptionalResult(_ f: F) -> (F?, Int)? {
return f.foo()
}
public class F {
@inline(never)
public func foo() -> (F?, Int)? {
return (F(), 1)
}
}
public class G: F {
@inline(never)
override public func foo() -> (G?, Int)? {
return (G(), 2)
}
}
public class H: F {
@inline(never)
override public func foo() -> (H?, Int)? {
return nil
}
}
| apache-2.0 | 775f3243a0bfbc5f4bebaee3c0135939 | 21.507123 | 212 | 0.636835 | 3.16 | false | false | false | false |
adamnemecek/AudioKit | Sources/AudioKit/Nodes/Playback/AudioPlayer/AudioPlayer+Playback.swift | 1 | 3649 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
extension AudioPlayer {
// MARK: - Playback
/// Play now or at a future time
/// - Parameters:
/// - when: What time to schedule for. A value of nil means now or will
/// use a pre-existing scheduled time.
/// - completionCallbackType: Constants that specify when the completion handler must be invoked.
public func play(from startTime: TimeInterval? = nil,
to endTime: TimeInterval? = nil,
at when: AVAudioTime? = nil,
completionCallbackType: AVAudioPlayerNodeCompletionCallbackType = .dataPlayedBack) {
if isPaused {
resume()
return
}
if isPlaying {
stop()
}
guard let engine = playerNode.engine else {
Log("🛑 Error: AudioPlayer must be attached before playback.", type: .error)
return
}
guard engine.isRunning else {
Log("🛑 Error: AudioPlayer's engine must be running before playback.", type: .error)
return
}
if when != nil {
scheduleTime = nil
playerNode.stop()
}
editStartTime = startTime ?? editStartTime
editEndTime = endTime ?? editEndTime
if !isScheduled || isSeeking {
schedule(at: when,
completionCallbackType: completionCallbackType)
}
playerNode.play()
isPlaying = true
}
/// Pauses audio player. Calling play() will resume from the paused time.
public func pause() {
guard isPlaying, !isPaused else { return }
pausedTime = getCurrentTime()
playerNode.pause()
isPaused = true
}
/// Resumes audio player from paused time
public func resume() {
isPaused = false
if !isBuffered {
seek(time: pausedTime)
}
playerNode.play()
}
/// Gets the accurate playhead time regardless of seeking and pausing
/// Can't be relied on if playerNode has its playstate modified directly
public func getCurrentTime() -> TimeInterval {
if let nodeTime = playerNode.lastRenderTime,
nodeTime.isSampleTimeValid,
let playerTime = playerNode.playerTime(forNodeTime: nodeTime) {
return (Double(playerTime.sampleTime) / playerTime.sampleRate) + editStartTime
} else if isPaused {
return pausedTime
}
return editStartTime
}
/// Sets the player's audio file to a certain time in the track (in seconds)
/// and respects the players current play state
/// - Parameters:
/// - time seconds into the audio file to set playhead
public func seek(time: TimeInterval) {
let wasPlaying = isPlaying
let time = time.clamped(to: 0...duration)
isSeeking = true
if wasPlaying {
play(from: time, to: duration)
} else {
editStartTime = time
editEndTime = duration
}
isSeeking = false
}
}
extension AudioPlayer {
/// Synonym for isPlaying
public var isStarted: Bool { isPlaying }
/// Synonym for play()
public func start() {
play()
}
/// Stop audio player. This won't generate a callback event
public func stop() {
guard isPlaying else { return }
pausedTime = getCurrentTime()
isPlaying = false
isSeeking = false
playerNode.stop()
scheduleTime = nil
}
}
| mit | 8d65f5c02965e149d15cccbd206226d8 | 28.379032 | 105 | 0.587702 | 5.038728 | false | false | false | false |
nathantannar4/Parse-Dashboard-for-iOS-Pro | Pods/Former/Former/Cells/FormStepperCell.swift | 3 | 2093 | //
// FormStepperCell.swift
// Former-Demo
//
// Created by Ryo Aoyama on 7/30/15.
// Copyright © 2015 Ryo Aoyama. All rights reserved.
//
import UIKit
open class FormStepperCell: FormCell, StepperFormableRow {
// MARK: Public
public private(set) weak var titleLabel: UILabel!
public private(set) weak var displayLabel: UILabel!
public private(set) weak var stepper: UIStepper!
public func formTitleLabel() -> UILabel? {
return titleLabel
}
public func formDisplayLabel() -> UILabel? {
return displayLabel
}
public func formStepper() -> UIStepper {
return stepper
}
open override func setup() {
super.setup()
let titleLabel = UILabel()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.insertSubview(titleLabel, at: 0)
self.titleLabel = titleLabel
let displayLabel = UILabel()
displayLabel.textColor = .lightGray
displayLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.insertSubview(displayLabel, at: 0)
self.displayLabel = displayLabel
let stepper = UIStepper()
accessoryView = stepper
self.stepper = stepper
let constraints = [
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[title]-0-|",
options: [],
metrics: nil,
views: ["title": titleLabel]
),
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[display]-0-|",
options: [],
metrics: nil,
views: ["display": displayLabel]
),
NSLayoutConstraint.constraints(
withVisualFormat: "H:|-15-[title]-(>=0)-[display]-5-|",
options: [],
metrics: nil,
views: ["title": titleLabel, "display": displayLabel]
)
].flatMap { $0 }
contentView.addConstraints(constraints)
}
}
| mit | c470cce818ec37a8031b3661829c894e | 28.464789 | 70 | 0.569312 | 5.490814 | false | false | false | false |
slavapestov/swift | stdlib/public/core/StringCore.swift | 1 | 22942 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// The core implementation of a highly-optimizable String that
/// can store both ASCII and UTF-16, and can wrap native Swift
/// _StringBuffer or NSString instances.
///
/// Usage note: when elements are 8 bits wide, this code may
/// dereference one past the end of the byte array that it owns, so
/// make sure that storage is allocated! You want a null terminator
/// anyway, so it shouldn't be a burden.
//
// Implementation note: We try hard to avoid branches in this code, so
// for example we use integer math to avoid switching on the element
// size with the ternary operator. This is also the cause of the
// extra element requirement for 8 bit elements. See the
// implementation of subscript(Int) -> UTF16.CodeUnit below for details.
public struct _StringCore {
//===--------------------------------------------------------------------===//
// Internals
public var _baseAddress: COpaquePointer
var _countAndFlags: UInt
public var _owner: AnyObject?
/// (private) create the implementation of a string from its component parts.
init(
baseAddress: COpaquePointer,
_countAndFlags: UInt,
owner: AnyObject?
) {
self._baseAddress = baseAddress
self._countAndFlags = _countAndFlags
self._owner = owner
_invariantCheck()
}
func _invariantCheck() {
// Note: this code is intentionally #if'ed out. It unconditionally
// accesses lazily initialized globals, and thus it is a performance burden
// in non-checked builds.
#if INTERNAL_CHECKS_ENABLED
_sanityCheck(count >= 0)
if _baseAddress == nil {
#if _runtime(_ObjC)
_sanityCheck(hasCocoaBuffer,
"Only opaque cocoa strings may have a null base pointer")
#endif
_sanityCheck(elementWidth == 2,
"Opaque cocoa strings should have an elementWidth of 2")
}
else if _baseAddress == _emptyStringBase {
_sanityCheck(!hasCocoaBuffer)
_sanityCheck(count == 0, "Empty string storage with non-zero length")
_sanityCheck(_owner == nil, "String pointing at empty storage has owner")
}
else if let buffer = nativeBuffer {
_sanityCheck(!hasCocoaBuffer)
_sanityCheck(elementWidth == buffer.elementWidth,
"_StringCore elementWidth doesn't match its buffer's")
_sanityCheck(UnsafeMutablePointer(_baseAddress) >= buffer.start)
_sanityCheck(UnsafeMutablePointer(_baseAddress) <= buffer.usedEnd)
_sanityCheck(UnsafeMutablePointer(_pointerToNth(count)) <= buffer.usedEnd)
}
#endif
}
/// Bitmask for the count part of `_countAndFlags`.
var _countMask: UInt {
return UInt.max >> 2
}
/// Bitmask for the flags part of `_countAndFlags`.
var _flagMask: UInt {
return ~_countMask
}
/// Value by which to multiply a 2nd byte fetched in order to
/// assemble a UTF-16 code unit from our contiguous storage. If we
/// store ASCII, this will be zero. Otherwise, it will be 0x100.
var _highByteMultiplier: UTF16.CodeUnit {
return UTF16.CodeUnit(elementShift) << 8
}
/// Return a pointer to the Nth element of contiguous
/// storage. Caveats: The string must have contiguous storage; the
/// element may be 1 or 2 bytes wide, depending on elementWidth; the
/// result may be null if the string is empty.
@warn_unused_result
func _pointerToNth(n: Int) -> COpaquePointer {
_sanityCheck(hasContiguousStorage && n >= 0 && n <= count)
return COpaquePointer(
UnsafeMutablePointer<RawByte>(_baseAddress) + (n << elementShift))
}
static func _copyElements(
srcStart: COpaquePointer, srcElementWidth: Int,
dstStart: COpaquePointer, dstElementWidth: Int,
count: Int
) {
// Copy the old stuff into the new storage
if _fastPath(srcElementWidth == dstElementWidth) {
// No change in storage width; we can use memcpy
_memcpy(
dest: UnsafeMutablePointer(dstStart),
src: UnsafeMutablePointer(srcStart),
size: UInt(count << (srcElementWidth - 1)))
}
else if (srcElementWidth < dstElementWidth) {
// Widening ASCII to UTF-16; we need to copy the bytes manually
var dest = UnsafeMutablePointer<UTF16.CodeUnit>(dstStart)
var src = UnsafeMutablePointer<UTF8.CodeUnit>(srcStart)
let srcEnd = src + count
while (src != srcEnd) {
dest.memory = UTF16.CodeUnit(src.memory)
dest += 1
src += 1
}
}
else {
// Narrowing UTF-16 to ASCII; we need to copy the bytes manually
var dest = UnsafeMutablePointer<UTF8.CodeUnit>(dstStart)
var src = UnsafeMutablePointer<UTF16.CodeUnit>(srcStart)
let srcEnd = src + count
while (src != srcEnd) {
dest.memory = UTF8.CodeUnit(src.memory)
dest += 1
src += 1
}
}
}
//===--------------------------------------------------------------------===//
// Initialization
public init(
baseAddress: COpaquePointer,
count: Int,
elementShift: Int,
hasCocoaBuffer: Bool,
owner: AnyObject?
) {
_sanityCheck(elementShift == 0 || elementShift == 1)
self._baseAddress = baseAddress
self._countAndFlags
= (UInt(elementShift) << (UInt._sizeInBits - 1))
| ((hasCocoaBuffer ? 1 : 0) << (UInt._sizeInBits - 2))
| UInt(count)
self._owner = owner
_sanityCheck(UInt(count) & _flagMask == 0, "String too long to represent")
_invariantCheck()
}
/// Create a _StringCore that covers the entire length of the _StringBuffer.
init(_ buffer: _StringBuffer) {
self = _StringCore(
baseAddress: COpaquePointer(buffer.start),
count: buffer.usedCount,
elementShift: buffer.elementShift,
hasCocoaBuffer: false,
owner: buffer._anyObject
)
}
/// Create the implementation of an empty string.
///
/// - Note: There is no null terminator in an empty string.
public init() {
self._baseAddress = _emptyStringBase
self._countAndFlags = 0
self._owner = nil
_invariantCheck()
}
//===--------------------------------------------------------------------===//
// Properties
/// The number of elements stored
/// - Complexity: O(1).
public var count: Int {
get {
return Int(_countAndFlags & _countMask)
}
set(newValue) {
_sanityCheck(UInt(newValue) & _flagMask == 0)
_countAndFlags = (_countAndFlags & _flagMask) | UInt(newValue)
}
}
/// Left shift amount to apply to an offset N so that when
/// added to a UnsafeMutablePointer<RawByte>, it traverses N elements.
var elementShift: Int {
return Int(_countAndFlags >> (UInt._sizeInBits - 1))
}
/// The number of bytes per element.
///
/// If the string does not have an ASCII buffer available (including the case
/// when we don't have a utf16 buffer) then it equals 2.
public var elementWidth: Int {
return elementShift &+ 1
}
public var hasContiguousStorage: Bool {
#if _runtime(_ObjC)
return _fastPath(_baseAddress != nil)
#else
return true
#endif
}
/// Are we using an `NSString` for storage?
public var hasCocoaBuffer: Bool {
return Int((_countAndFlags << 1)._value) < 0
}
public var startASCII: UnsafeMutablePointer<UTF8.CodeUnit> {
_sanityCheck(elementWidth == 1, "String does not contain contiguous ASCII")
return UnsafeMutablePointer(_baseAddress)
}
/// True iff a contiguous ASCII buffer available.
public var isASCII: Bool {
return elementWidth == 1
}
public var startUTF16: UnsafeMutablePointer<UTF16.CodeUnit> {
_sanityCheck(
count == 0 || elementWidth == 2,
"String does not contain contiguous UTF-16")
return UnsafeMutablePointer(_baseAddress)
}
/// the native _StringBuffer, if any, or `nil`.
public var nativeBuffer: _StringBuffer? {
if !hasCocoaBuffer {
return _owner.map {
unsafeBitCast($0, _StringBuffer.self)
}
}
return nil
}
#if _runtime(_ObjC)
/// the Cocoa String buffer, if any, or `nil`.
public var cocoaBuffer: _CocoaStringType? {
if hasCocoaBuffer {
return _owner.map {
unsafeBitCast($0, _CocoaStringType.self)
}
}
return nil
}
#endif
//===--------------------------------------------------------------------===//
// slicing
/// Returns the given sub-`_StringCore`.
public subscript(subRange: Range<Int>) -> _StringCore {
_precondition(
subRange.startIndex >= 0,
"subscript: subRange start precedes String start")
_precondition(
subRange.endIndex <= count,
"subscript: subRange extends past String end")
let newCount = subRange.endIndex - subRange.startIndex
_sanityCheck(UInt(newCount) & _flagMask == 0)
if hasContiguousStorage {
return _StringCore(
baseAddress: _pointerToNth(subRange.startIndex),
_countAndFlags: (_countAndFlags & _flagMask) | UInt(newCount),
owner: _owner)
}
#if _runtime(_ObjC)
return _cocoaStringSlice(self, subRange)
#else
_sanityCheckFailure("subscript: non-native string without objc runtime")
#endif
}
/// Get the Nth UTF-16 Code Unit stored.
@warn_unused_result
func _nthContiguous(position: Int) -> UTF16.CodeUnit {
let p = UnsafeMutablePointer<UInt8>(_pointerToNth(position)._rawValue)
// Always dereference two bytes, but when elements are 8 bits we
// multiply the high byte by 0.
// FIXME(performance): use masking instead of multiplication.
return UTF16.CodeUnit(p.memory)
+ UTF16.CodeUnit((p + 1).memory) * _highByteMultiplier
}
/// Get the Nth UTF-16 Code Unit stored.
public subscript(position: Int) -> UTF16.CodeUnit {
_precondition(
position >= 0,
"subscript: index precedes String start")
_precondition(
position <= count,
"subscript: index points past String end")
if _fastPath(_baseAddress != nil) {
return _nthContiguous(position)
}
#if _runtime(_ObjC)
return _cocoaStringSubscript(self, position)
#else
_sanityCheckFailure("subscript: non-native string without objc runtime")
#endif
}
/// Write the string, in the given encoding, to output.
func encode<
Encoding: UnicodeCodecType
>(encoding: Encoding.Type, output: (Encoding.CodeUnit) -> Void)
{
if _fastPath(_baseAddress != nil) {
if _fastPath(elementWidth == 1) {
for x in UnsafeBufferPointer(
start: UnsafeMutablePointer<UTF8.CodeUnit>(_baseAddress),
count: count
) {
Encoding.encode(UnicodeScalar(UInt32(x)), output: output)
}
}
else {
let hadError = transcode(UTF16.self, encoding,
UnsafeBufferPointer(
start: UnsafeMutablePointer<UTF16.CodeUnit>(_baseAddress),
count: count
).generate(),
output,
stopOnError: true
)
_sanityCheck(!hadError, "Swift.String with native storage should not have unpaired surrogates")
}
}
else if (hasCocoaBuffer) {
#if _runtime(_ObjC)
_StringCore(
_cocoaStringToContiguous(cocoaBuffer!, 0..<count, minimumCapacity: 0)
).encode(encoding, output: output)
#else
_sanityCheckFailure("encode: non-native string without objc runtime")
#endif
}
}
/// Attempt to claim unused capacity in the String's existing
/// native buffer, if any. Return zero and a pointer to the claimed
/// storage if successful. Otherwise, returns a suggested new
/// capacity and a null pointer.
///
/// - Note: If successful, effectively appends garbage to the String
/// until it has newSize UTF-16 code units; you must immediately copy
/// valid UTF-16 into that storage.
///
/// - Note: If unsuccessful because of insufficient space in an
/// existing buffer, the suggested new capacity will at least double
/// the existing buffer's storage.
@warn_unused_result
mutating func _claimCapacity(
newSize: Int, minElementWidth: Int) -> (Int, COpaquePointer) {
if _fastPath((nativeBuffer != nil) && elementWidth >= minElementWidth) {
var buffer = nativeBuffer!
// In order to grow the substring in place, this _StringCore should point
// at the substring at the end of a _StringBuffer. Otherwise, some other
// String is using parts of the buffer beyond our last byte.
let usedStart = _pointerToNth(0)
let usedEnd = _pointerToNth(count)
// Attempt to claim unused capacity in the buffer
if _fastPath(
buffer.grow(
UnsafePointer(usedStart)..<UnsafePointer(usedEnd),
newUsedCount: newSize)
) {
count = newSize
return (0, usedEnd)
}
else if newSize > buffer.capacity {
// Growth failed because of insufficient storage; double the size
return (max(_growArrayCapacity(buffer.capacity), newSize), nil)
}
}
return (newSize, nil)
}
/// Ensure that this String references a _StringBuffer having
/// a capacity of at least newSize elements of at least the given width.
/// Effectively appends garbage to the String until it has newSize
/// UTF-16 code units. Returns a pointer to the garbage code units;
/// you must immediately copy valid data into that storage.
@warn_unused_result
mutating func _growBuffer(
newSize: Int, minElementWidth: Int
) -> COpaquePointer {
let (newCapacity, existingStorage)
= _claimCapacity(newSize, minElementWidth: minElementWidth)
if _fastPath(existingStorage != nil) {
return existingStorage
}
let oldCount = count
_copyInPlace(
newSize: newSize,
newCapacity: newCapacity,
minElementWidth: minElementWidth)
return _pointerToNth(oldCount)
}
/// Replace the storage of self with a native _StringBuffer having a
/// capacity of at least newCapacity elements of at least the given
/// width. Effectively appends garbage to the String until it has
/// newSize UTF-16 code units.
mutating func _copyInPlace(
newSize newSize: Int, newCapacity: Int, minElementWidth: Int
) {
_sanityCheck(newCapacity >= newSize)
let oldCount = count
// Allocate storage.
let newElementWidth =
minElementWidth >= elementWidth
? minElementWidth
: representableAsASCII() ? 1 : 2
let newStorage = _StringBuffer(capacity: newCapacity, initialSize: newSize,
elementWidth: newElementWidth)
if hasContiguousStorage {
_StringCore._copyElements(
_baseAddress, srcElementWidth: elementWidth,
dstStart: COpaquePointer(newStorage.start),
dstElementWidth: newElementWidth, count: oldCount)
}
else {
#if _runtime(_ObjC)
// Opaque cocoa buffers might not store ASCII, so assert that
// we've allocated for 2-byte elements.
// FIXME: can we get Cocoa to tell us quickly that an opaque
// string is ASCII? Do we care much about that edge case?
_sanityCheck(newStorage.elementShift == 1)
_cocoaStringReadAll(cocoaBuffer!, UnsafeMutablePointer(newStorage.start))
#else
_sanityCheckFailure("_copyInPlace: non-native string without objc runtime")
#endif
}
self = _StringCore(newStorage)
}
/// Append `c` to `self`.
///
/// - Complexity: O(1) when amortized over repeated appends of equal
/// character values.
mutating func append(c: UnicodeScalar) {
let width = UTF16.width(c)
append(
width == 2 ? UTF16.leadSurrogate(c) : UTF16.CodeUnit(c.value),
width == 2 ? UTF16.trailSurrogate(c) : nil
)
}
/// Append `u` to `self`.
///
/// - Complexity: Amortized O(1).
public mutating func append(u: UTF16.CodeUnit) {
append(u, nil)
}
mutating func append(u0: UTF16.CodeUnit, _ u1: UTF16.CodeUnit?) {
_invariantCheck()
let minBytesPerCodeUnit = u0 <= 0x7f ? 1 : 2
let utf16Width = u1 == nil ? 1 : 2
let destination = _growBuffer(
count + utf16Width, minElementWidth: minBytesPerCodeUnit)
if _fastPath(elementWidth == 1) {
_sanityCheck(
_pointerToNth(count)
== COpaquePointer(UnsafeMutablePointer<RawByte>(destination) + 1))
UnsafeMutablePointer<UTF8.CodeUnit>(destination)[0] = UTF8.CodeUnit(u0)
}
else {
let destination16
= UnsafeMutablePointer<UTF16.CodeUnit>(destination._rawValue)
destination16[0] = u0
if u1 != nil {
destination16[1] = u1!
}
}
_invariantCheck()
}
mutating func append(rhs: _StringCore) {
_invariantCheck()
let minElementWidth
= elementWidth >= rhs.elementWidth
? elementWidth
: rhs.representableAsASCII() ? 1 : 2
let destination = _growBuffer(
count + rhs.count, minElementWidth: minElementWidth)
if _fastPath(rhs.hasContiguousStorage) {
_StringCore._copyElements(
rhs._baseAddress, srcElementWidth: rhs.elementWidth,
dstStart: destination, dstElementWidth:elementWidth, count: rhs.count)
}
else {
#if _runtime(_ObjC)
_sanityCheck(elementWidth == 2)
_cocoaStringReadAll(rhs.cocoaBuffer!, UnsafeMutablePointer(destination))
#else
_sanityCheckFailure("subscript: non-native string without objc runtime")
#endif
}
_invariantCheck()
}
/// Return true iff the contents of this string can be
/// represented as pure ASCII.
///
/// - Complexity: O(N) in the worst case.
@warn_unused_result
func representableAsASCII() -> Bool {
if _slowPath(!hasContiguousStorage) {
return false
}
if _fastPath(elementWidth == 1) {
return true
}
let unsafeBuffer =
UnsafeBufferPointer(
start: UnsafeMutablePointer<UTF16.CodeUnit>(_baseAddress),
count: count)
return !unsafeBuffer.contains { $0 > 0x7f }
}
}
extension _StringCore : CollectionType {
public // @testable
var startIndex: Int {
return 0
}
public // @testable
var endIndex: Int {
return count
}
}
extension _StringCore : RangeReplaceableCollectionType {
/// Replace the given `subRange` of elements with `newElements`.
///
/// - Complexity: O(`subRange.count`) if `subRange.endIndex
/// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise.
public mutating func replaceRange<
C: CollectionType where C.Generator.Element == UTF16.CodeUnit
>(
subRange: Range<Int>, with newElements: C
) {
_precondition(
subRange.startIndex >= 0,
"replaceRange: subRange start precedes String start")
_precondition(
subRange.endIndex <= count,
"replaceRange: subRange extends past String end")
let width = elementWidth == 2 || newElements.contains { $0 > 0x7f } ? 2 : 1
let replacementCount = numericCast(newElements.count) as Int
let replacedCount = subRange.count
let tailCount = count - subRange.endIndex
let growth = replacementCount - replacedCount
let newCount = count + growth
// Successfully claiming capacity only ensures that we can modify
// the newly-claimed storage without observably mutating other
// strings, i.e., when we're appending. Already-used characters
// can only be mutated when we have a unique reference to the
// buffer.
let appending = subRange.startIndex == endIndex
let existingStorage = !hasCocoaBuffer && (
appending || isUniquelyReferencedNonObjC(&_owner)
) ? _claimCapacity(newCount, minElementWidth: width).1 : nil
if _fastPath(existingStorage != nil) {
let rangeStart = UnsafeMutablePointer<UInt8>(
_pointerToNth(subRange.startIndex))
let tailStart = rangeStart + (replacedCount << elementShift)
if growth > 0 {
(tailStart + (growth << elementShift)).assignBackwardFrom(
tailStart, count: tailCount << elementShift)
}
if _fastPath(elementWidth == 1) {
var dst = rangeStart
for u in newElements {
dst.memory = UInt8(u & 0xFF)
dst += 1
}
}
else {
var dst = UnsafeMutablePointer<UTF16.CodeUnit>(rangeStart)
for u in newElements {
dst.memory = u
dst += 1
}
}
if growth < 0 {
(tailStart + (growth << elementShift)).assignFrom(
tailStart, count: tailCount << elementShift)
}
}
else {
var r = _StringCore(
_StringBuffer(
capacity: newCount,
initialSize: 0,
elementWidth:
width == 1 ? 1
: representableAsASCII() && !newElements.contains { $0 > 0x7f } ? 1
: 2
))
r.appendContentsOf(self[0..<subRange.startIndex])
r.appendContentsOf(newElements)
r.appendContentsOf(self[subRange.endIndex..<count])
self = r
}
}
public mutating func reserveCapacity(n: Int) {
if _fastPath(!hasCocoaBuffer) {
if _fastPath(isUniquelyReferencedNonObjC(&_owner)) {
let subRange: Range<UnsafePointer<RawByte>>
= UnsafePointer(_pointerToNth(0))..<UnsafePointer(_pointerToNth(count))
if _fastPath(nativeBuffer!.hasCapacity(n, forSubRange: subRange)) {
return
}
}
}
_copyInPlace(newSize: count, newCapacity: max(count, n), minElementWidth: 1)
}
public mutating func appendContentsOf<
S : SequenceType
where S.Generator.Element == UTF16.CodeUnit
>(s: S) {
var width = elementWidth
if width == 1 {
if let hasNonAscii = s._preprocessingPass({
s.contains { $0 > 0x7f }
}) {
width = hasNonAscii ? 2 : 1
}
}
let growth = s.underestimateCount()
var g = s.generate()
if _fastPath(growth > 0) {
let newSize = count + growth
let destination = _growBuffer(newSize, minElementWidth: width)
if elementWidth == 1 {
let destination8 = UnsafeMutablePointer<UTF8.CodeUnit>(destination)
for i in 0..<growth {
destination8[i] = UTF8.CodeUnit(g.next()!)
}
}
else {
let destination16 = UnsafeMutablePointer<UTF16.CodeUnit>(destination)
for i in 0..<growth {
destination16[i] = g.next()!
}
}
}
// Append any remaining elements
for u in GeneratorSequence(g) {
self.append(u)
}
}
}
// Used to support a tighter invariant: all strings with contiguous
// storage have a non-NULL base address.
var _emptyStringStorage: UInt32 = 0
var _emptyStringBase: COpaquePointer {
return COpaquePointer(
UnsafeMutablePointer<UInt16>(Builtin.addressof(&_emptyStringStorage)))
}
| apache-2.0 | faf82a7649808b03b042fc0ba9957647 | 30.863889 | 103 | 0.641792 | 4.595753 | false | false | false | false |
3sidedcube/CubeGeoJSON | GeoJSON/Feature.swift | 1 | 1401 | //
// Feature.swift
// GeoJSON
//
// Created by Simon Mitchell on 02/10/2016.
// Copyright © 2016 threesidedcube. All rights reserved.
//
import Foundation
/// A feature represents a `Geometry` object and a JSON structure of associated data [spec](http://geojson.org/geojson-spec.html#feature-objects)
open class Feature: NSObject {
/// The geometry object that this feature represents
open var geometry: Geometry
/// A JSON payload of properties on the feature object
open var properties: [AnyHashable : Any]
public init?(dictionary: [AnyHashable : Any]) {
guard let geometryDict = dictionary["geometry"] as? [AnyHashable : Any], let properties = dictionary["properties"] as? [AnyHashable : Any] else { return nil }
geometry = Geometry(dictionary: geometryDict)
self.properties = properties
}
}
/// A feature collection represents a set of `Feature` objects [spec](http://geojson.org/geojson-spec.html#feature-collection-objects)
open class FeatureCollection: NSObject {
/// An array of features that the collection represents
open var features: [Feature]
public init?(dictionary: [AnyHashable : Any]) {
guard let featuresArray = dictionary["features"] as? [[AnyHashable : Any]] else { return nil }
features = featuresArray.compactMap({ Feature(dictionary: $0) })
}
}
| apache-2.0 | dc11dfc609f65e341b66d1bfa1ef334c | 34 | 166 | 0.681429 | 4.444444 | false | false | false | false |
denizsokmen/Raid | Raid/SingleBugViewController.swift | 1 | 2142 | //
// SingleBugViewController.swift
// Raid
//
// Created by deniz sokmen on 1/1/15.
// Copyright (c) 2015 student7. All rights reserved.
//
import UIKit
class SingleBugViewController: UIViewController {
var bug: BugReport!
@IBOutlet weak var descriptionText: UITextView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var progressBar: UIProgressView!
@IBOutlet weak var priorityLabel: UILabel!
@IBOutlet weak var resolveButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let color: CGFloat = CGFloat(bug.priority) / 5.0
progressBar.progress = Float(color)
progressBar.progressTintColor = UIColor(red: color, green: 1-color, blue: 0.0, alpha: 1.0)
priorityLabel.textColor = UIColor(red: color, green: 1-color, blue: 0.0, alpha: 1.0)
if color > 0.7 {
priorityLabel.text = "HIGH"
}
else if color > 0.4 {
priorityLabel.text = "NORMAL"
}
else {
priorityLabel.text = "LOW"
}
titleLabel.text = "#" + String(bug.id) + " - " + bug.title
descriptionText.text = bug.description
}
override func viewWillAppear(animated: Bool) {
if bug.solved == true {
priorityLabel.text = "Resolved"
priorityLabel.textColor = UIColor(red: 0.2, green: 0.8, blue: 0.0, alpha: 1.0)
progressBar.progress = 1.0
progressBar.progressTintColor = UIColor(red: 0.2, green: 0.8, blue: 0.0, alpha: 1.0)
resolveButton.hidden = true
}
else {
resolveButton.hidden = false
}
Database.sharedInstance.save()
}
@IBAction func resolve(sender: AnyObject) {
bug.solved = true
self.navigationController?.popToRootViewControllerAnimated(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-2.0 | 20be5ca7fde4d9ee8ffc345ccd5e1df1 | 30.043478 | 98 | 0.602708 | 4.318548 | false | false | false | false |
tjw/swift | benchmark/single-source/NibbleSort.swift | 3 | 1330 | // NibbleSort benchmark
//
// Source: https://gist.github.com/airspeedswift/f4daff4ea5c6de9e1fdf
import TestsUtils
public var NibbleSort = BenchmarkInfo(
name: "NibbleSort",
runFunction: run_NibbleSort,
tags: [.validation]
)
@inline(never)
public func run_NibbleSort(_ N: Int) {
let vRef: UInt64 = 0xfeedbba000000000
let v: UInt64 = 0xbadbeef
var c = NibbleCollection(v)
for _ in 1...10000*N {
c.val = v
c.sort()
if c.val != vRef {
break
}
}
CheckResults(c.val == vRef)
}
struct NibbleCollection: RandomAccessCollection, MutableCollection {
var val: UInt64
init(_ val: UInt64) { self.val = val }
typealias Index = UInt64
let startIndex: UInt64 = 0
let endIndex: UInt64 = 16
subscript(bounds: Range<Index>) -> Slice<NibbleCollection> {
get {
fatalError("Should not be called. Added here to please the type checker")
}
set {
fatalError("Should not be called. Added here to please the type checker")
}
}
subscript(idx: UInt64) -> UInt64 {
get {
return (val >> (idx*4)) & 0xf
}
set(n) {
let mask = (0xf as UInt64) << (idx * 4)
val &= ~mask
val |= n << (idx * 4)
}
}
typealias Iterator = IndexingIterator<NibbleCollection>
func makeIterator() -> Iterator { return Iterator(_elements: self) }
}
| apache-2.0 | 3d800dbc51fca7dd9c0b0f99e6806812 | 20.803279 | 79 | 0.637594 | 3.392857 | false | false | false | false |
grpc/grpc-swift | Tests/GRPCTests/ImmediateServerFailureTests.swift | 1 | 3420 | /*
* Copyright 2019, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import EchoModel
import Foundation
import GRPC
import NIOCore
import XCTest
class ImmediatelyFailingEchoProvider: Echo_EchoProvider {
let interceptors: Echo_EchoServerInterceptorFactoryProtocol? = nil
static let status: GRPCStatus = .init(code: .unavailable, message: nil)
func get(
request: Echo_EchoRequest,
context: StatusOnlyCallContext
) -> EventLoopFuture<Echo_EchoResponse> {
return context.eventLoop.makeFailedFuture(ImmediatelyFailingEchoProvider.status)
}
func expand(
request: Echo_EchoRequest,
context: StreamingResponseCallContext<Echo_EchoResponse>
) -> EventLoopFuture<GRPCStatus> {
return context.eventLoop.makeFailedFuture(ImmediatelyFailingEchoProvider.status)
}
func collect(
context: UnaryResponseCallContext<Echo_EchoResponse>
) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
context.responsePromise.fail(ImmediatelyFailingEchoProvider.status)
return context.eventLoop.makeSucceededFuture({ _ in
// no-op
})
}
func update(
context: StreamingResponseCallContext<Echo_EchoResponse>
) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
context.statusPromise.fail(ImmediatelyFailingEchoProvider.status)
return context.eventLoop.makeSucceededFuture({ _ in
// no-op
})
}
}
class ImmediatelyFailingProviderTests: EchoTestCaseBase {
override func makeEchoProvider() -> Echo_EchoProvider {
return ImmediatelyFailingEchoProvider()
}
func testUnary() throws {
let expcectation = self.makeStatusExpectation()
let call = self.client.get(Echo_EchoRequest(text: "foo"))
call.status.map { $0.code }.assertEqual(.unavailable, fulfill: expcectation)
self.wait(for: [expcectation], timeout: self.defaultTestTimeout)
}
func testServerStreaming() throws {
let expcectation = self.makeStatusExpectation()
let call = self.client.expand(Echo_EchoRequest(text: "foo")) { response in
XCTFail("unexpected response: \(response)")
}
call.status.map { $0.code }.assertEqual(.unavailable, fulfill: expcectation)
self.wait(for: [expcectation], timeout: self.defaultTestTimeout)
}
func testClientStreaming() throws {
let expcectation = self.makeStatusExpectation()
let call = self.client.collect()
call.status.map { $0.code }.assertEqual(.unavailable, fulfill: expcectation)
self.wait(for: [expcectation], timeout: self.defaultTestTimeout)
}
func testBidirectionalStreaming() throws {
let expcectation = self.makeStatusExpectation()
let call = self.client.update { response in
XCTFail("unexpected response: \(response)")
}
call.status.map { $0.code }.assertEqual(.unavailable, fulfill: expcectation)
self.wait(for: [expcectation], timeout: self.defaultTestTimeout)
}
}
| apache-2.0 | 0169d09e89aa0da7e6f8ecc4a1c185da | 33.2 | 84 | 0.738012 | 4.175824 | false | true | false | false |
warren-gavin/OBehave | OBehave/Classes/ViewController/Layout/OBFullScreenDisplayBehavior.swift | 1 | 2709 | //
// OBFullScreenDisplayBehavior.swift
// OBehave
//
// Created by Warren Gavin on 24/04/2018.
// Copyright © 2018 Apokrupto. All rights reserved.
//
import UIKit
/// Make a UIStackView always expand to full screen, if the content is
/// too small, or scrollable when it's too large.
///
/// This is sometimes preferable to a typical table view when you
/// would prefer the simple layout of a stack view, plus no scrolling
/// if the content isn't too large.
///
/// With this approach a smaller font size may show as laid out in a
/// normal stack view, while another instance running with a larger font
/// size for accessibility purposes will result in a view that is still
/// laid out the same, but now scrolls to show all the content
///
/// To use in a storyboard:
///
/// - Add a scroll view to a view controller, anchored to the
/// top and bottom layout guides. The width can be whatever you like.
/// - Add a vertical stack view as a subview of the scroll view, with layout
/// constraints equal to the top, bottom, leading and trailing space, plus
/// equal widths
/// - The stack view's alignment should be fill, the distribution equal spacing
/// - Start adding elements.
///
/// To make the stack view full screen, for example to push buttons to the
/// bottom of the screen:
///
/// - Add a small UIView with a fixed height to the stack view between the
/// elements you want at the top of the screen and those at the bottom.
/// - Hook up the view's height constraint to the constraint outlet collection
/// - Hooking up multiple such padding views will separate the elements further into
/// evenly spaced groups that fill the screen if the content isn't too large.
/// - If the content is too large, there is no change
///
class OBFullScreenDisplayBehavior: OBBehavior {
@IBOutlet var paddingCellHeights: [NSLayoutConstraint]!
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var stackView: UIStackView! {
didSet {
boundsChangeObserver = stackView.observe(\.bounds, options: .new) { [weak self] stackView, _ in
guard let self = self else {
return
}
let heightDifference = self.scrollView.bounds.height - stackView.bounds.height
if heightDifference > 0 {
self.paddingCellHeights.forEach {
$0.constant += heightDifference / CGFloat(self.paddingCellHeights.count)
}
}
else {
self.boundsChangeObserver = nil
}
}
}
}
private var boundsChangeObserver: NSKeyValueObservation?
}
| mit | d148a9bce4645cc680899b2b3100ea43 | 38.823529 | 107 | 0.657312 | 4.636986 | false | false | false | false |
apple/swift-nio-http2 | Sources/NIOHTTP2/ConnectionStateMachine/ConnectionStateMachine.swift | 1 | 84297 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
import NIOHPACK
/// A state machine that governs the connection-level state of a HTTP/2 connection.
///
/// ### Overview
///
/// A HTTP/2 protocol implementation is fundamentally built on a pair of interlocking state machines:
/// one for the connection as a whole, and then one for each stream on the connection. All frames sent
/// and received on a HTTP/2 connection cause state transitions in either or both of these state
/// machines, and the set of valid state transitions in these state machines forms the complete set of
/// valid frame sequences in HTTP/2.
///
/// Not all frames need to pass through both state machines. As a general heuristic, if a frame carries a
/// stream ID field, it must pass through both the connection state machine and the stream state machine for
/// the associated stream. If it does not, then it must only pass through the connection state machine. This
/// is not a *complete* description of the way the connection behaves (see the note about PRIORITY frames
/// below), but it's a good enough operating heuristic to get through the rest of the code.
///
/// The stream state machine is handled by `HTTP2StreamStateMachine`.
///
/// ### Function
///
/// The responsibilities of this state machine are as follows:
///
/// 1) Manage the connection setup process, ensuring that the approriate client/server preamble is sent and
/// received.
/// 2) Manage the inbound and outbound connection flow control windows.
/// 3) Keep track of the bi-directional values of HTTP/2 settings.
/// 4) Manage connection cleanup, shutdown, and quiescing.
///
/// ### Implementation
///
/// All state associated with a HTTP/2 connection lives inside a single Swift enum. This enum constrains when
/// state is available, ensuring that it is not possible to query data that is not meaningful in the given state.
/// Operations on this state machine occur by calling specific functions on the structure, which will spin the
/// enum as needed and perform whatever state transitions are required.
///
/// #### PRIORITY frames
///
/// A brief digression is required on HTTP/2 PRIORITY frames. These frames appear to be sent "on" a specific
/// stream, as they carry a stream ID like all other stream-specific frames. However, unlike all other stream
/// specific frames they can be sent for streams in *any* state (including idle and fullyQuiesced, meaning they can
/// be sent for streams that have never existed or that passed away long ago), and have no effect on the stream
/// state (causing no state transitions). They only ever affect the priority tree, which neither this object nor
/// any of the streams actually maintains.
///
/// For this reason, PRIORITY frames do not actually participate in the stream state machine: only the
/// connection one. This is unlike all other frames that carry stream IDs. Essentially, they are connection-scoped
/// frames that just incidentally have a stream ID on them, rather than stream-scoped frames like all the others.
struct HTTP2ConnectionStateMachine {
/// The state required for a connection that is currently idle.
fileprivate struct IdleConnectionState: ConnectionStateWithRole, ConnectionStateWithConfiguration {
let role: ConnectionRole
var headerBlockValidation: ValidationState
var contentLengthValidation: ValidationState
}
/// The state required for a connection that has sent a connection preface.
fileprivate struct PrefaceSentState: ConnectionStateWithRole, ConnectionStateWithConfiguration, MaySendFrames, HasLocalSettings, HasFlowControlWindows {
let role: ConnectionRole
var headerBlockValidation: ValidationState
var contentLengthValidation: ValidationState
var localSettings: HTTP2SettingsState
var streamState: ConnectionStreamState
var inboundFlowControlWindow: HTTP2FlowControlWindow
var outboundFlowControlWindow: HTTP2FlowControlWindow
var localInitialWindowSize: UInt32 {
return HTTP2SettingsState.defaultInitialWindowSize
}
var remoteInitialWindowSize: UInt32 {
return self.localSettings.initialWindowSize
}
init(fromIdle idleState: IdleConnectionState, localSettings settings: HTTP2SettingsState) {
self.role = idleState.role
self.headerBlockValidation = idleState.headerBlockValidation
self.contentLengthValidation = idleState.contentLengthValidation
self.localSettings = settings
self.streamState = ConnectionStreamState()
self.inboundFlowControlWindow = HTTP2FlowControlWindow(initialValue: settings.initialWindowSize)
self.outboundFlowControlWindow = HTTP2FlowControlWindow(initialValue: HTTP2SettingsState.defaultInitialWindowSize)
}
}
/// The state required for a connection that has received a connection preface.
fileprivate struct PrefaceReceivedState: ConnectionStateWithRole, ConnectionStateWithConfiguration, MayReceiveFrames, HasRemoteSettings, HasFlowControlWindows {
let role: ConnectionRole
var headerBlockValidation: ValidationState
var contentLengthValidation: ValidationState
var remoteSettings: HTTP2SettingsState
var streamState: ConnectionStreamState
var inboundFlowControlWindow: HTTP2FlowControlWindow
var outboundFlowControlWindow: HTTP2FlowControlWindow
var localInitialWindowSize: UInt32 {
return self.remoteSettings.initialWindowSize
}
var remoteInitialWindowSize: UInt32 {
return HTTP2SettingsState.defaultInitialWindowSize
}
init(fromIdle idleState: IdleConnectionState, remoteSettings settings: HTTP2SettingsState) {
self.role = idleState.role
self.headerBlockValidation = idleState.headerBlockValidation
self.contentLengthValidation = idleState.contentLengthValidation
self.remoteSettings = settings
self.streamState = ConnectionStreamState()
self.inboundFlowControlWindow = HTTP2FlowControlWindow(initialValue: HTTP2SettingsState.defaultInitialWindowSize)
self.outboundFlowControlWindow = HTTP2FlowControlWindow(initialValue: settings.initialWindowSize)
}
}
/// The state required for a connection that is active.
fileprivate struct ActiveConnectionState: ConnectionStateWithRole, ConnectionStateWithConfiguration, MaySendFrames, MayReceiveFrames, HasLocalSettings, HasRemoteSettings, HasFlowControlWindows {
let role: ConnectionRole
var headerBlockValidation: ValidationState
var contentLengthValidation: ValidationState
var localSettings: HTTP2SettingsState
var remoteSettings: HTTP2SettingsState
var streamState: ConnectionStreamState
var inboundFlowControlWindow: HTTP2FlowControlWindow
var outboundFlowControlWindow: HTTP2FlowControlWindow
var localInitialWindowSize: UInt32 {
return self.remoteSettings.initialWindowSize
}
var remoteInitialWindowSize: UInt32 {
return self.localSettings.initialWindowSize
}
init(fromPrefaceReceived state: PrefaceReceivedState, localSettings settings: HTTP2SettingsState) {
self.role = state.role
self.headerBlockValidation = state.headerBlockValidation
self.contentLengthValidation = state.contentLengthValidation
self.remoteSettings = state.remoteSettings
self.streamState = state.streamState
self.localSettings = settings
self.outboundFlowControlWindow = state.outboundFlowControlWindow
self.inboundFlowControlWindow = state.inboundFlowControlWindow
}
init(fromPrefaceSent state: PrefaceSentState, remoteSettings settings: HTTP2SettingsState) {
self.role = state.role
self.headerBlockValidation = state.headerBlockValidation
self.contentLengthValidation = state.contentLengthValidation
self.localSettings = state.localSettings
self.streamState = state.streamState
self.remoteSettings = settings
self.outboundFlowControlWindow = state.outboundFlowControlWindow
self.inboundFlowControlWindow = state.inboundFlowControlWindow
}
}
/// The state required for a connection that is quiescing, but where the local peer has not yet sent its
/// preface.
fileprivate struct QuiescingPrefaceReceivedState: ConnectionStateWithRole, ConnectionStateWithConfiguration, RemotelyQuiescingState, MayReceiveFrames, HasRemoteSettings, QuiescingState, HasFlowControlWindows {
let role: ConnectionRole
var headerBlockValidation: ValidationState
var contentLengthValidation: ValidationState
var remoteSettings: HTTP2SettingsState
var streamState: ConnectionStreamState
var inboundFlowControlWindow: HTTP2FlowControlWindow
var outboundFlowControlWindow: HTTP2FlowControlWindow
var lastLocalStreamID: HTTP2StreamID
var localInitialWindowSize: UInt32 {
return self.remoteSettings.initialWindowSize
}
var remoteInitialWindowSize: UInt32 {
return HTTP2SettingsState.defaultInitialWindowSize
}
var quiescedByServer: Bool {
return self.role == .client
}
init(fromPrefaceReceived state: PrefaceReceivedState, lastStreamID: HTTP2StreamID) {
self.role = state.role
self.headerBlockValidation = state.headerBlockValidation
self.contentLengthValidation = state.contentLengthValidation
self.remoteSettings = state.remoteSettings
self.streamState = state.streamState
self.inboundFlowControlWindow = state.inboundFlowControlWindow
self.outboundFlowControlWindow = state.outboundFlowControlWindow
self.lastLocalStreamID = lastStreamID
}
}
/// The state required for a connection that is quiescing, but where the remote peer has not yet sent its
/// preface.
fileprivate struct QuiescingPrefaceSentState: ConnectionStateWithRole, ConnectionStateWithConfiguration, LocallyQuiescingState, MaySendFrames, HasLocalSettings, QuiescingState, HasFlowControlWindows {
let role: ConnectionRole
var headerBlockValidation: ValidationState
var contentLengthValidation: ValidationState
var localSettings: HTTP2SettingsState
var streamState: ConnectionStreamState
var inboundFlowControlWindow: HTTP2FlowControlWindow
var outboundFlowControlWindow: HTTP2FlowControlWindow
var lastRemoteStreamID: HTTP2StreamID
var localInitialWindowSize: UInt32 {
return HTTP2SettingsState.defaultInitialWindowSize
}
var remoteInitialWindowSize: UInt32 {
return self.localSettings.initialWindowSize
}
var quiescedByServer: Bool {
return self.role == .server
}
init(fromPrefaceSent state: PrefaceSentState, lastStreamID: HTTP2StreamID) {
self.role = state.role
self.headerBlockValidation = state.headerBlockValidation
self.contentLengthValidation = state.contentLengthValidation
self.localSettings = state.localSettings
self.streamState = state.streamState
self.inboundFlowControlWindow = state.inboundFlowControlWindow
self.outboundFlowControlWindow = state.outboundFlowControlWindow
self.lastRemoteStreamID = lastStreamID
}
}
/// The state required for a connection that is quiescing due to the remote peer quiescing the connection.
fileprivate struct RemotelyQuiescedState: ConnectionStateWithRole, ConnectionStateWithConfiguration, RemotelyQuiescingState, MayReceiveFrames, MaySendFrames, HasLocalSettings, HasRemoteSettings, QuiescingState, HasFlowControlWindows {
let role: ConnectionRole
var headerBlockValidation: ValidationState
var contentLengthValidation: ValidationState
var localSettings: HTTP2SettingsState
var remoteSettings: HTTP2SettingsState
var streamState: ConnectionStreamState
var inboundFlowControlWindow: HTTP2FlowControlWindow
var outboundFlowControlWindow: HTTP2FlowControlWindow
var lastLocalStreamID: HTTP2StreamID
var localInitialWindowSize: UInt32 {
return self.remoteSettings.initialWindowSize
}
var remoteInitialWindowSize: UInt32 {
return self.localSettings.initialWindowSize
}
var quiescedByServer: Bool {
return self.role == .client
}
init(fromActive state: ActiveConnectionState, lastLocalStreamID streamID: HTTP2StreamID) {
self.role = state.role
self.headerBlockValidation = state.headerBlockValidation
self.contentLengthValidation = state.contentLengthValidation
self.localSettings = state.localSettings
self.remoteSettings = state.remoteSettings
self.streamState = state.streamState
self.inboundFlowControlWindow = state.inboundFlowControlWindow
self.outboundFlowControlWindow = state.outboundFlowControlWindow
self.lastLocalStreamID = streamID
}
init(fromQuiescingPrefaceReceived state: QuiescingPrefaceReceivedState, localSettings settings: HTTP2SettingsState) {
self.role = state.role
self.headerBlockValidation = state.headerBlockValidation
self.contentLengthValidation = state.contentLengthValidation
self.remoteSettings = state.remoteSettings
self.localSettings = settings
self.streamState = state.streamState
self.inboundFlowControlWindow = state.inboundFlowControlWindow
self.outboundFlowControlWindow = state.outboundFlowControlWindow
self.lastLocalStreamID = state.lastLocalStreamID
}
}
/// The state required for a connection that is quiescing due to the local user quiescing the connection.
fileprivate struct LocallyQuiescedState: ConnectionStateWithRole, ConnectionStateWithConfiguration, LocallyQuiescingState, MaySendFrames, MayReceiveFrames, HasLocalSettings, HasRemoteSettings, QuiescingState, HasFlowControlWindows {
let role: ConnectionRole
var headerBlockValidation: ValidationState
var contentLengthValidation: ValidationState
var localSettings: HTTP2SettingsState
var remoteSettings: HTTP2SettingsState
var streamState: ConnectionStreamState
var inboundFlowControlWindow: HTTP2FlowControlWindow
var outboundFlowControlWindow: HTTP2FlowControlWindow
var lastRemoteStreamID: HTTP2StreamID
var localInitialWindowSize: UInt32 {
return self.remoteSettings.initialWindowSize
}
var remoteInitialWindowSize: UInt32 {
return self.localSettings.initialWindowSize
}
var quiescedByServer: Bool {
return self.role == .server
}
init(fromActive state: ActiveConnectionState, lastRemoteStreamID streamID: HTTP2StreamID) {
self.role = state.role
self.headerBlockValidation = state.headerBlockValidation
self.contentLengthValidation = state.contentLengthValidation
self.localSettings = state.localSettings
self.remoteSettings = state.remoteSettings
self.streamState = state.streamState
self.inboundFlowControlWindow = state.inboundFlowControlWindow
self.outboundFlowControlWindow = state.outboundFlowControlWindow
self.lastRemoteStreamID = streamID
}
init(fromQuiescingPrefaceSent state: QuiescingPrefaceSentState, remoteSettings settings: HTTP2SettingsState) {
self.role = state.role
self.headerBlockValidation = state.headerBlockValidation
self.contentLengthValidation = state.contentLengthValidation
self.localSettings = state.localSettings
self.remoteSettings = settings
self.streamState = state.streamState
self.inboundFlowControlWindow = state.inboundFlowControlWindow
self.outboundFlowControlWindow = state.outboundFlowControlWindow
self.lastRemoteStreamID = state.lastRemoteStreamID
}
}
/// The state required for a connection that is quiescing due to both peers sending GOAWAY.
fileprivate struct BothQuiescingState: ConnectionStateWithRole, ConnectionStateWithConfiguration, LocallyQuiescingState, RemotelyQuiescingState, MaySendFrames, MayReceiveFrames, HasLocalSettings, HasRemoteSettings, QuiescingState, HasFlowControlWindows {
let role: ConnectionRole
var headerBlockValidation: ValidationState
var contentLengthValidation: ValidationState
var localSettings: HTTP2SettingsState
var remoteSettings: HTTP2SettingsState
var streamState: ConnectionStreamState
var inboundFlowControlWindow: HTTP2FlowControlWindow
var outboundFlowControlWindow: HTTP2FlowControlWindow
var lastLocalStreamID: HTTP2StreamID
var lastRemoteStreamID: HTTP2StreamID
var localInitialWindowSize: UInt32 {
return self.remoteSettings.initialWindowSize
}
var remoteInitialWindowSize: UInt32 {
return self.localSettings.initialWindowSize
}
var quiescedByServer: Bool {
return true
}
init(fromRemotelyQuiesced state: RemotelyQuiescedState, lastRemoteStreamID streamID: HTTP2StreamID) {
self.role = state.role
self.headerBlockValidation = state.headerBlockValidation
self.contentLengthValidation = state.contentLengthValidation
self.localSettings = state.localSettings
self.remoteSettings = state.remoteSettings
self.streamState = state.streamState
self.inboundFlowControlWindow = state.inboundFlowControlWindow
self.outboundFlowControlWindow = state.outboundFlowControlWindow
self.lastLocalStreamID = state.lastLocalStreamID
self.lastRemoteStreamID = streamID
}
init(fromLocallyQuiesced state: LocallyQuiescedState, lastLocalStreamID streamID: HTTP2StreamID) {
self.role = state.role
self.headerBlockValidation = state.headerBlockValidation
self.contentLengthValidation = state.contentLengthValidation
self.localSettings = state.localSettings
self.remoteSettings = state.remoteSettings
self.streamState = state.streamState
self.inboundFlowControlWindow = state.inboundFlowControlWindow
self.outboundFlowControlWindow = state.outboundFlowControlWindow
self.lastRemoteStreamID = state.lastRemoteStreamID
self.lastLocalStreamID = streamID
}
}
/// The state required for a connection that has completely quiesced.
fileprivate struct FullyQuiescedState: ConnectionStateWithRole, ConnectionStateWithConfiguration, LocallyQuiescingState, RemotelyQuiescingState, SendAndReceiveGoawayState {
let role: ConnectionRole
var headerBlockValidation: ValidationState
var contentLengthValidation: ValidationState
var streamState: ConnectionStreamState
var lastLocalStreamID: HTTP2StreamID
var lastRemoteStreamID: HTTP2StreamID
init<PreviousState: LocallyQuiescingState & RemotelyQuiescingState & SendAndReceiveGoawayState & ConnectionStateWithRole & ConnectionStateWithConfiguration>(previousState: PreviousState) {
self.role = previousState.role
self.headerBlockValidation = previousState.headerBlockValidation
self.contentLengthValidation = previousState.contentLengthValidation
self.streamState = previousState.streamState
self.lastLocalStreamID = previousState.lastLocalStreamID
self.lastRemoteStreamID = previousState.lastRemoteStreamID
}
init<PreviousState: LocallyQuiescingState & SendAndReceiveGoawayState & ConnectionStateWithRole & ConnectionStateWithConfiguration>(previousState: PreviousState) {
self.role = previousState.role
self.headerBlockValidation = previousState.headerBlockValidation
self.contentLengthValidation = previousState.contentLengthValidation
self.streamState = previousState.streamState
self.lastLocalStreamID = .maxID
self.lastRemoteStreamID = previousState.lastRemoteStreamID
}
init<PreviousState: RemotelyQuiescingState & SendAndReceiveGoawayState & ConnectionStateWithRole & ConnectionStateWithConfiguration>(previousState: PreviousState) {
self.role = previousState.role
self.headerBlockValidation = previousState.headerBlockValidation
self.contentLengthValidation = previousState.contentLengthValidation
self.streamState = previousState.streamState
self.lastLocalStreamID = previousState.lastLocalStreamID
self.lastRemoteStreamID = .maxID
}
}
fileprivate enum State {
/// The connection has not begun yet. This state is usually used while the underlying transport connection
/// is being established. No data can be sent or received at this time.
case idle(IdleConnectionState)
/// Our preface has been sent, and we are awaiting the preface from the remote peer. In general we're more
/// likely to enter this state as a client than a server, but users may choose to reduce latency by
/// aggressively emitting the server preface before the client preface has been received. In either case,
/// in this state we are waiting for the remote peer to send its preface.
case prefaceSent(PrefaceSentState)
/// We have received a preface from the remote peer, and we are waiting to send our own preface. In general
/// we're more likely to enter this state as a server than as a client, but remote peers may be attempting
/// to reduce latency by aggressively emitting the server preface before they have received our preface.
/// In either case, in this state we are waiting for the local user to emit the preface.
case prefaceReceived(PrefaceReceivedState)
/// Both peers have exchanged their preface and the connection is fully active. In this state new streams
/// may be created, potentially by either peer, and the connection is fully useable.
case active(ActiveConnectionState)
/// The remote peer has sent a GOAWAY frame that quiesces the connection, preventing the creation of new
/// streams. However, there are still active streams that have been allowed to complete, so the connection
/// is not entirely inactive.
case remotelyQuiesced(RemotelyQuiescedState)
/// The local user has sent a GOAWAY frame that quiesces the connection, preventing the creation of new
/// streams. However, there are still active streams that have been allowed to complete, so the connection
/// is not entirely inactive.
case locallyQuiesced(LocallyQuiescedState)
/// Both peers have emitted a GOAWAY frame that quiesces the connection, preventing the creation of new
/// streams. However, there are still active streams that have been allowed to complete, so the connection
/// is not entirely inactive.
case bothQuiescing(BothQuiescingState)
/// We have sent our preface, and sent a GOAWAY, but we haven't received the remote preface yet.
/// This is a weird state, unlikely to be encountered in most programs, but it's technically possible.
case quiescingPrefaceSent(QuiescingPrefaceSentState)
/// We have received a preface, and received a GOAWAY, but we haven't sent our preface yet.
/// This is a weird state, unlikely to be encountered in most programs, but it's technically possible.
case quiescingPrefaceReceived(QuiescingPrefaceReceivedState)
/// The connection has completed, either cleanly or with an error. In this state, no further activity may
/// occur on the connection.
case fullyQuiesced(FullyQuiescedState)
/// This is not a real state: it's used when we are in the middle of a function invocation, to avoid CoWs
/// when modifying the associated data.
case modifying
}
/// The possible roles an endpoint may play in a connection.
enum ConnectionRole {
case server
case client
}
/// The state of a specific validation option.
enum ValidationState {
case enabled
case disabled
}
private var state: State
init(role: ConnectionRole, headerBlockValidation: ValidationState = .enabled, contentLengthValidation: ValidationState = .enabled) {
self.state = .idle(.init(role: role, headerBlockValidation: headerBlockValidation, contentLengthValidation: contentLengthValidation))
}
/// Whether this connection is closed.
var fullyQuiesced: Bool {
switch self.state {
case .fullyQuiesced:
return true
default:
return false
}
}
/// Whether the preamble can be sent.
var mustSendPreamble: Bool {
switch self.state {
case .idle, .prefaceReceived, .quiescingPrefaceReceived:
return true
default:
return false
}
}
}
// MARK:- State modifying methods
//
// These methods form the implementation of the public API of the HTTP2ConnectionStateMachine. Each of these methods
// performs a state transition, and can be used to validate that a specific action is acceptable on a connection in this state.
extension HTTP2ConnectionStateMachine {
/// Called when a SETTINGS frame has been received from the remote peer
mutating func receiveSettings(_ payload: HTTP2Frame.FramePayload.Settings, frameEncoder: inout HTTP2FrameEncoder, frameDecoder: inout HTTP2FrameDecoder) -> (StateMachineResultWithEffect, PostFrameOperation) {
switch payload {
case .ack:
// No action is ever required after receiving a settings ACK
return (self.receiveSettingsAck(frameEncoder: &frameEncoder), .nothing)
case .settings(let settings):
return self.receiveSettingsChange(settings, frameDecoder: &frameDecoder)
}
}
/// Called when the user has sent a settings update.
///
/// Note that this function assumes that this is not a settings ACK, as settings ACK frames are not
/// allowed to be sent by the user. They are always emitted by the implementation.
mutating func sendSettings(_ settings: HTTP2Settings) -> StateMachineResultWithEffect {
let validationResult = self.validateSettings(settings)
guard case .succeed = validationResult else {
return .init(result: validationResult, effect: nil)
}
switch self.state {
case .idle(let state):
self.avoidingStateMachineCoW { newState in
var settingsState = HTTP2SettingsState(localState: true)
settingsState.emitSettings(settings)
newState = .prefaceSent(.init(fromIdle: state, localSettings: settingsState))
}
case .prefaceReceived(let state):
self.avoidingStateMachineCoW { newState in
var settingsState = HTTP2SettingsState(localState: true)
settingsState.emitSettings(settings)
newState = .active(.init(fromPrefaceReceived: state, localSettings: settingsState))
}
case .prefaceSent(var state):
self.avoidingStateMachineCoW { newState in
state.localSettings.emitSettings(settings)
newState = .prefaceSent(state)
}
case .active(var state):
self.avoidingStateMachineCoW { newState in
state.localSettings.emitSettings(settings)
newState = .active(state)
}
case .quiescingPrefaceSent(var state):
self.avoidingStateMachineCoW { newState in
state.localSettings.emitSettings(settings)
newState = .quiescingPrefaceSent(state)
}
case .quiescingPrefaceReceived(let state):
self.avoidingStateMachineCoW { newState in
var settingsState = HTTP2SettingsState(localState: true)
settingsState.emitSettings(settings)
newState = .remotelyQuiesced(.init(fromQuiescingPrefaceReceived: state, localSettings: settingsState))
}
case .remotelyQuiesced(var state):
self.avoidingStateMachineCoW { newState in
state.localSettings.emitSettings(settings)
newState = .remotelyQuiesced(state)
}
case .locallyQuiesced(var state):
self.avoidingStateMachineCoW { newState in
state.localSettings.emitSettings(settings)
newState = .locallyQuiesced(state)
}
case .bothQuiescing(var state):
self.avoidingStateMachineCoW { newState in
state.localSettings.emitSettings(settings)
newState = .bothQuiescing(state)
}
case .fullyQuiesced:
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil)
case .modifying:
preconditionFailure("Must not be left in modifying state")
}
return .init(result: .succeed, effect: nil)
}
/// Called when a HEADERS frame has been received from the remote peer.
mutating func receiveHeaders(streamID: HTTP2StreamID, headers: HPACKHeaders, isEndStreamSet endStream: Bool) -> StateMachineResultWithEffect {
switch self.state {
case .prefaceReceived(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveHeaders(streamID: streamID, headers: headers, isEndStreamSet: endStream)
newState = .prefaceReceived(state)
return result
}
case .active(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveHeaders(streamID: streamID, headers: headers, isEndStreamSet: endStream)
newState = .active(state)
return result
}
case .locallyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveHeaders(streamID: streamID, headers: headers, isEndStreamSet: endStream)
newState = .locallyQuiesced(state)
newState.closeIfNeeded(state)
return result
}
case .remotelyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveHeaders(streamID: streamID, headers: headers, isEndStreamSet: endStream)
newState = .remotelyQuiesced(state)
newState.closeIfNeeded(state)
return result
}
case .bothQuiescing(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveHeaders(streamID: streamID, headers: headers, isEndStreamSet: endStream)
newState = .bothQuiescing(state)
newState.closeIfNeeded(state)
return result
}
case .quiescingPrefaceReceived(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveHeaders(streamID: streamID, headers: headers, isEndStreamSet: endStream)
newState = .quiescingPrefaceReceived(state)
return result
}
case .idle, .prefaceSent, .quiescingPrefaceSent:
// If we're still waiting for the remote preface, they are not allowed to send us a HEADERS frame yet!
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil)
case .fullyQuiesced:
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil)
case .modifying:
preconditionFailure("Must not be left in modifying state")
}
}
// Called when a HEADERS frame has been sent by the local user.
mutating func sendHeaders(streamID: HTTP2StreamID, headers: HPACKHeaders, isEndStreamSet endStream: Bool) -> StateMachineResultWithEffect {
switch self.state {
case .prefaceSent(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendHeaders(streamID: streamID, headers: headers, isEndStreamSet: endStream)
newState = .prefaceSent(state)
return result
}
case .active(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendHeaders(streamID: streamID, headers: headers, isEndStreamSet: endStream)
newState = .active(state)
return result
}
case .locallyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendHeaders(streamID: streamID, headers: headers, isEndStreamSet: endStream)
newState = .locallyQuiesced(state)
newState.closeIfNeeded(state)
return result
}
case .remotelyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendHeaders(streamID: streamID, headers: headers, isEndStreamSet: endStream)
newState = .remotelyQuiesced(state)
newState.closeIfNeeded(state)
return result
}
case .bothQuiescing(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendHeaders(streamID: streamID, headers: headers, isEndStreamSet: endStream)
newState = .bothQuiescing(state)
newState.closeIfNeeded(state)
return result
}
case .quiescingPrefaceSent(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendHeaders(streamID: streamID, headers: headers, isEndStreamSet: endStream)
newState = .quiescingPrefaceSent(state)
return result
}
case .idle, .prefaceReceived, .quiescingPrefaceReceived:
// If we're still waiting for the local preface, we are not allowed to send a HEADERS frame yet!
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil)
case .fullyQuiesced:
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil)
case .modifying:
preconditionFailure("Must not be left in modifying state")
}
}
/// Called when a DATA frame has been received.
mutating func receiveData(streamID: HTTP2StreamID, contentLength: Int, flowControlledBytes: Int, isEndStreamSet endStream: Bool) -> StateMachineResultWithEffect {
switch self.state {
case .prefaceReceived(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream)
newState = .prefaceReceived(state)
return result
}
case .active(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream)
newState = .active(state)
return result
}
case .locallyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream)
newState = .locallyQuiesced(state)
newState.closeIfNeeded(state)
return result
}
case .remotelyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream)
newState = .remotelyQuiesced(state)
newState.closeIfNeeded(state)
return result
}
case .bothQuiescing(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream)
newState = .bothQuiescing(state)
newState.closeIfNeeded(state)
return result
}
case .quiescingPrefaceReceived(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream)
newState = .quiescingPrefaceReceived(state)
return result
}
case .idle, .prefaceSent, .quiescingPrefaceSent:
// If we're still waiting for the remote preface, we are not allowed to receive a DATA frame yet!
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil)
case .fullyQuiesced:
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil)
case .modifying:
preconditionFailure("Must not be left in modifying state")
}
}
/// Called when a user is trying to send a DATA frame.
mutating func sendData(streamID: HTTP2StreamID, contentLength: Int, flowControlledBytes: Int, isEndStreamSet endStream: Bool) -> StateMachineResultWithEffect {
switch self.state {
case .prefaceSent(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream)
newState = .prefaceSent(state)
return result
}
case .active(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream)
newState = .active(state)
return result
}
case .locallyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream)
newState = .locallyQuiesced(state)
newState.closeIfNeeded(state)
return result
}
case .remotelyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream)
newState = .remotelyQuiesced(state)
newState.closeIfNeeded(state)
return result
}
case .bothQuiescing(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream)
newState = .bothQuiescing(state)
newState.closeIfNeeded(state)
return result
}
case .quiescingPrefaceSent(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream)
newState = .quiescingPrefaceSent(state)
return result
}
case .idle, .prefaceReceived, .quiescingPrefaceReceived:
// If we're still waiting for the local preface, we are not allowed to send a DATA frame yet!
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil)
case .fullyQuiesced:
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil)
case .modifying:
preconditionFailure("Must not be left in modifying state")
}
}
func receivePriority() -> StateMachineResultWithEffect {
// So long as we've received the preamble and haven't fullyQuiesced, a PRIORITY frame is basically always
// an acceptable thing to receive. The only rule is that it mustn't form a cycle in the priority
// tree, but we don't maintain enough state in this object to enforce that.
switch self.state {
case .prefaceReceived, .active, .locallyQuiesced, .remotelyQuiesced, .bothQuiescing, .quiescingPrefaceReceived:
return StateMachineResultWithEffect(result: .succeed, effect: nil)
case .idle, .prefaceSent, .quiescingPrefaceSent:
return StateMachineResultWithEffect(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil)
case .fullyQuiesced:
return StateMachineResultWithEffect(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil)
case .modifying:
preconditionFailure("Must not be left in modifying state")
}
}
func sendPriority() -> StateMachineResultWithEffect {
// So long as we've sent the preamble and haven't fullyQuiesced, a PRIORITY frame is basically always
// an acceptable thing to send. The only rule is that it mustn't form a cycle in the priority
// tree, but we don't maintain enough state in this object to enforce that.
switch self.state {
case .prefaceSent, .active, .locallyQuiesced, .remotelyQuiesced, .bothQuiescing, .quiescingPrefaceSent:
return .init(result: .succeed, effect: nil)
case .idle, .prefaceReceived, .quiescingPrefaceReceived:
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil)
case .fullyQuiesced:
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil)
case .modifying:
preconditionFailure("Must not be left in modifying state")
}
}
/// Called when a RST_STREAM frame has been received.
mutating func receiveRstStream(streamID: HTTP2StreamID, reason: HTTP2ErrorCode) -> StateMachineResultWithEffect {
switch self.state {
case .prefaceReceived(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveRstStream(streamID: streamID, reason: reason)
newState = .prefaceReceived(state)
return result
}
case .active(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveRstStream(streamID: streamID, reason: reason)
newState = .active(state)
return result
}
case .locallyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveRstStream(streamID: streamID, reason: reason)
newState = .locallyQuiesced(state)
newState.closeIfNeeded(state)
return result
}
case .remotelyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveRstStream(streamID: streamID, reason: reason)
newState = .remotelyQuiesced(state)
newState.closeIfNeeded(state)
return result
}
case .bothQuiescing(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveRstStream(streamID: streamID, reason: reason)
newState = .bothQuiescing(state)
newState.closeIfNeeded(state)
return result
}
case .quiescingPrefaceReceived(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveRstStream(streamID: streamID, reason: reason)
newState = .quiescingPrefaceReceived(state)
return result
}
case .idle, .prefaceSent, .quiescingPrefaceSent:
// We're waiting for the remote preface.
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil)
case .fullyQuiesced:
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil)
case .modifying:
preconditionFailure("Must not be left in modifying state")
}
}
/// Called when sending a RST_STREAM frame.
mutating func sendRstStream(streamID: HTTP2StreamID, reason: HTTP2ErrorCode) -> StateMachineResultWithEffect {
switch self.state {
case .prefaceSent(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendRstStream(streamID: streamID, reason: reason)
newState = .prefaceSent(state)
return result
}
case .active(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendRstStream(streamID: streamID, reason: reason)
newState = .active(state)
return result
}
case .locallyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendRstStream(streamID: streamID, reason: reason)
newState = .locallyQuiesced(state)
newState.closeIfNeeded(state)
return result
}
case .remotelyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendRstStream(streamID: streamID, reason: reason)
newState = .remotelyQuiesced(state)
newState.closeIfNeeded(state)
return result
}
case .bothQuiescing(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendRstStream(streamID: streamID, reason: reason)
newState = .bothQuiescing(state)
newState.closeIfNeeded(state)
return result
}
case .quiescingPrefaceSent(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendRstStream(streamID: streamID, reason: reason)
newState = .quiescingPrefaceSent(state)
return result
}
case .idle, .prefaceReceived, .quiescingPrefaceReceived:
// We're waiting for the local preface.
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil)
case .fullyQuiesced:
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil)
case .modifying:
preconditionFailure("Must not be left in modifying state")
}
}
/// Called when a PUSH_PROMISE frame has been initiated on a given stream.
///
/// If this method returns a stream error, the stream error should be assumed to apply to both the original
/// and child stream.
mutating func receivePushPromise(originalStreamID: HTTP2StreamID, childStreamID: HTTP2StreamID, headers: HPACKHeaders) -> StateMachineResultWithEffect {
// In states that support a push promise we have two steps. Firstly, we want to create the child stream; then we want to
// pass the PUSH_PROMISE frame through the stream state machine for the parent stream.
//
// The reason we do things in this order is that if for any reason the PUSH_PROMISE frame is invalid on the parent stream,
// we want to take out both the child stream and the parent stream. We can only do that if we have a child stream state to
// modify. For this reason, we unconditionally allow the remote peer to consume the stream. The only case where this is *not*
// true is when the child stream itself cannot be validly created, because the stream ID used by the remote peer is invalid.
// In this case this is a connection error, anyway, so we don't worry too much about it.
switch self.state {
case .prefaceReceived(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receivePushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers)
newState = .prefaceReceived(state)
return result
}
case .active(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receivePushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers)
newState = .active(state)
return result
}
case .locallyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receivePushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers)
newState = .locallyQuiesced(state)
return result
}
case .remotelyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receivePushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers)
newState = .remotelyQuiesced(state)
return result
}
case .bothQuiescing(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receivePushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers)
newState = .bothQuiescing(state)
return result
}
case .quiescingPrefaceReceived(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receivePushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers)
newState = .quiescingPrefaceReceived(state)
return result
}
case .idle, .prefaceSent, .quiescingPrefaceSent:
// We're waiting for the remote preface.
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil)
case .fullyQuiesced:
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil)
case .modifying:
preconditionFailure("Must not be left in modifying state")
}
}
mutating func sendPushPromise(originalStreamID: HTTP2StreamID, childStreamID: HTTP2StreamID, headers: HPACKHeaders) -> StateMachineResultWithEffect {
switch self.state {
case .prefaceSent(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendPushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers)
newState = .prefaceSent(state)
return result
}
case .active(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendPushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers)
newState = .active(state)
return result
}
case .locallyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendPushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers)
newState = .locallyQuiesced(state)
return result
}
case .remotelyQuiesced, .bothQuiescing:
// We have been quiesced, and may not create new streams.
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.createdStreamAfterGoaway(), type: .protocolError), effect: nil)
case .quiescingPrefaceSent(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendPushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers)
newState = .quiescingPrefaceSent(state)
return result
}
case .idle, .prefaceReceived, .quiescingPrefaceReceived:
// We're waiting for the local preface.
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil)
case .fullyQuiesced:
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil)
case .modifying:
preconditionFailure("Must not be left in modifying state")
}
}
/// Called when a PING frame has been received from the network.
mutating func receivePing(ackFlagSet: Bool) -> (StateMachineResultWithEffect, PostFrameOperation) {
// Pings are pretty straightforward: they're basically always allowed. This is a bit weird, but I can find no text in
// RFC 7540 that says that receiving PINGs with ACK flags set when no PING ACKs are expected is forbidden. This is
// very strange, but we allow it.
switch self.state {
case .prefaceReceived, .active, .locallyQuiesced, .remotelyQuiesced, .bothQuiescing, .quiescingPrefaceReceived:
return (.init(result: .succeed, effect: nil), ackFlagSet ? .nothing : .sendAck)
case .idle, .prefaceSent, .quiescingPrefaceSent:
// We're waiting for the remote preface.
return (.init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil), .nothing)
case .fullyQuiesced:
return (.init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil), .nothing)
case .modifying:
preconditionFailure("Must not be left in modifying state")
}
}
/// Called when a PING frame is about to be sent.
mutating func sendPing() -> StateMachineResultWithEffect {
// Pings are pretty straightforward: they're basically always allowed. This is a bit weird, but I can find no text in
// RFC 7540 that says that sending PINGs with ACK flags set when no PING ACKs are expected is forbidden. This is
// very strange, but we allow it.
switch self.state {
case .prefaceSent, .active, .locallyQuiesced, .remotelyQuiesced, .bothQuiescing, .quiescingPrefaceSent:
return .init(result: .succeed, effect: nil)
case .idle, .prefaceReceived, .quiescingPrefaceReceived:
// We're waiting for the local preface.
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil)
case .fullyQuiesced:
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil)
case .modifying:
preconditionFailure("Must not be left in modifying state")
}
}
/// Called when we receive a GOAWAY frame.
mutating func receiveGoaway(lastStreamID: HTTP2StreamID) -> StateMachineResultWithEffect {
// GOAWAY frames are some of the most subtle frames in HTTP/2, they cause a number of state transitions all at once.
// In particular, the value of lastStreamID heavily affects the state transitions we perform here.
// In this case, all streams initiated by us that have stream IDs higher than lastStreamID will be closed, effective
// immediately. If this leaves us with zero streams, the connection is fullyQuiesced. Otherwise, we are quiescing.
switch self.state {
case .prefaceReceived(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveGoAwayFrame(lastStreamID: lastStreamID)
let newStateData = QuiescingPrefaceReceivedState(fromPrefaceReceived: state, lastStreamID: lastStreamID)
newState = .quiescingPrefaceReceived(newStateData)
return result
}
case .active(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveGoAwayFrame(lastStreamID: lastStreamID)
let newStateData = RemotelyQuiescedState(fromActive: state, lastLocalStreamID: lastStreamID)
newState = .remotelyQuiesced(newStateData)
newState.closeIfNeeded(newStateData)
return result
}
case .locallyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveGoAwayFrame(lastStreamID: lastStreamID)
let newStateData = BothQuiescingState(fromLocallyQuiesced: state, lastLocalStreamID: lastStreamID)
newState = .bothQuiescing(newStateData)
newState.closeIfNeeded(newStateData)
return result
}
case .remotelyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveGoAwayFrame(lastStreamID: lastStreamID)
newState = .remotelyQuiesced(state)
newState.closeIfNeeded(state)
return result
}
case .bothQuiescing(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveGoAwayFrame(lastStreamID: lastStreamID)
newState = .bothQuiescing(state)
newState.closeIfNeeded(state)
return result
}
case .quiescingPrefaceReceived(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveGoAwayFrame(lastStreamID: lastStreamID)
newState = .quiescingPrefaceReceived(state)
return result
}
case .idle, .prefaceSent, .quiescingPrefaceSent:
// We're waiting for the preface.
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil)
case .fullyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
// We allow duplicate GOAWAY here, so long as it ratchets correctly.
let result = state.receiveGoAwayFrame(lastStreamID: lastStreamID)
newState = .fullyQuiesced(state)
return result
}
case .modifying:
preconditionFailure("Must not be left in modifying state")
}
}
/// Called when the user attempts to send a GOAWAY frame.
mutating func sendGoaway(lastStreamID: HTTP2StreamID) -> StateMachineResultWithEffect {
// GOAWAY frames are some of the most subtle frames in HTTP/2, they cause a number of state transitions all at once.
// In particular, the value of lastStreamID heavily affects the state transitions we perform here.
// In this case, all streams initiated by us that have stream IDs higher than lastStreamID will be closed, effective
// immediately. If this leaves us with zero streams, the connection is fullyQuiesced. Otherwise, we are quiescing.
switch self.state {
case .prefaceSent(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendGoAwayFrame(lastStreamID: lastStreamID)
let newStateData = QuiescingPrefaceSentState(fromPrefaceSent: state, lastStreamID: lastStreamID)
newState = .quiescingPrefaceSent(newStateData)
return result
}
case .active(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendGoAwayFrame(lastStreamID: lastStreamID)
let newStateData = LocallyQuiescedState(fromActive: state, lastRemoteStreamID: lastStreamID)
newState = .locallyQuiesced(newStateData)
newState.closeIfNeeded(newStateData)
return result
}
case .locallyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendGoAwayFrame(lastStreamID: lastStreamID)
newState = .locallyQuiesced(state)
newState.closeIfNeeded(state)
return result
}
case .remotelyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendGoAwayFrame(lastStreamID: lastStreamID)
let newStateData = BothQuiescingState(fromRemotelyQuiesced: state, lastRemoteStreamID: lastStreamID)
newState = .bothQuiescing(newStateData)
newState.closeIfNeeded(newStateData)
return result
}
case .bothQuiescing(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendGoAwayFrame(lastStreamID: lastStreamID)
newState = .bothQuiescing(state)
newState.closeIfNeeded(state)
return result
}
case .quiescingPrefaceSent(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendGoAwayFrame(lastStreamID: lastStreamID)
newState = .quiescingPrefaceSent(state)
return result
}
case .idle, .prefaceReceived, .quiescingPrefaceReceived:
// We're waiting for the preface.
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil)
case .fullyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
// We allow duplicate GOAWAY here, so long as it ratchets downwards.
let result = state.sendGoAwayFrame(lastStreamID: lastStreamID)
newState = .fullyQuiesced(state)
return result
}
case .modifying:
preconditionFailure("Must not be left in modifying state")
}
}
/// Called when a WINDOW_UPDATE frame has been received.
mutating func receiveWindowUpdate(streamID: HTTP2StreamID, windowIncrement: UInt32) -> StateMachineResultWithEffect {
switch self.state {
case .prefaceReceived(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveWindowUpdate(streamID: streamID, increment: windowIncrement)
newState = .prefaceReceived(state)
return result
}
case .active(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveWindowUpdate(streamID: streamID, increment: windowIncrement)
newState = .active(state)
return result
}
case .quiescingPrefaceReceived(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveWindowUpdate(streamID: streamID, increment: windowIncrement)
newState = .quiescingPrefaceReceived(state)
return result
}
case .locallyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveWindowUpdate(streamID: streamID, increment: windowIncrement)
newState = .locallyQuiesced(state)
return result
}
case .remotelyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveWindowUpdate(streamID: streamID, increment: windowIncrement)
newState = .remotelyQuiesced(state)
return result
}
case .bothQuiescing(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveWindowUpdate(streamID: streamID, increment: windowIncrement)
newState = .bothQuiescing(state)
return result
}
case .idle, .prefaceSent, .quiescingPrefaceSent:
// We're waiting for the preface.
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil)
case .fullyQuiesced:
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil)
case .modifying:
preconditionFailure("Must not be left in modifying state")
}
}
/// Called when a WINDOW_UPDATE frame is sent.
mutating func sendWindowUpdate(streamID: HTTP2StreamID, windowIncrement: UInt32) -> StateMachineResultWithEffect {
switch self.state {
case .prefaceSent(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendWindowUpdate(streamID: streamID, increment: windowIncrement)
newState = .prefaceSent(state)
return result
}
case .active(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendWindowUpdate(streamID: streamID, increment: windowIncrement)
newState = .active(state)
return result
}
case .quiescingPrefaceSent(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendWindowUpdate(streamID: streamID, increment: windowIncrement)
newState = .quiescingPrefaceSent(state)
return result
}
case .locallyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendWindowUpdate(streamID: streamID, increment: windowIncrement)
newState = .locallyQuiesced(state)
return result
}
case .remotelyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendWindowUpdate(streamID: streamID, increment: windowIncrement)
newState = .remotelyQuiesced(state)
return result
}
case .bothQuiescing(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.sendWindowUpdate(streamID: streamID, increment: windowIncrement)
newState = .bothQuiescing(state)
return result
}
case .idle, .prefaceReceived, .quiescingPrefaceReceived:
// We're waiting for the preface.
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil)
case .fullyQuiesced:
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil)
case .modifying:
preconditionFailure("Must not be left in modifying state")
}
}
/// Called when an ALTSVC frame has been received.
///
/// At present the frame is unconditionally ignored.
mutating func receiveAlternativeService(origin: String?, field: ByteBuffer?) -> StateMachineResultWithEffect {
// We don't support ALTSVC frames right now so we just ignore them.
//
// From RFC 7838 § 4:
// > The ALTSVC frame is a non-critical extension to HTTP/2. Endpoints
// > that do not support this frame will ignore it (as per the
// > extensibility rules defined in Section 4.1 of RFC7540).
return .init(result: .ignoreFrame, effect: .none)
}
/// Called when an ALTSVC frame is sent.
///
/// At present the frame is not handled, calling this function will trap.
mutating func sendAlternativeService(origin: String?, field: ByteBuffer?) -> Never {
fatalError("Currently ALTSVC frames are unhandled.")
}
/// Called when an ORIGIN frame has been received.
///
/// At present the frame is unconditionally ignored.
mutating func receiveOrigin(origins: [String]) -> StateMachineResultWithEffect {
// We don't support ORIGIN frames right now so we just ignore them.
//
// From RFC 8336 § 2.1:
// > The ORIGIN frame is a non-critical extension to HTTP/2. Endpoints
// > that do not support this frame can safely ignore it upon receipt.
return .init(result: .ignoreFrame, effect: .none)
}
/// Called when an ORIGIN frame is sent.
///
/// At present the frame is not handled, calling this function will trap.
mutating func sendOrigin(origins: [String]) -> Never {
fatalError("Currently ORIGIN frames are unhandled.")
}
}
// Mark:- Private helper methods
extension HTTP2ConnectionStateMachine {
/// Called when we have received a SETTINGS frame from the remote peer. Applies the changes immediately.
private mutating func receiveSettingsChange(_ settings: HTTP2Settings, frameDecoder: inout HTTP2FrameDecoder) -> (StateMachineResultWithEffect, PostFrameOperation) {
let validationResult = self.validateSettings(settings)
guard case .succeed = validationResult else {
return (.init(result: validationResult, effect: nil), .nothing)
}
switch self.state {
case .idle(let state):
return self.avoidingStateMachineCoW { newState in
var newStateData = PrefaceReceivedState(fromIdle: state, remoteSettings: HTTP2SettingsState(localState: false))
let result = newStateData.receiveSettingsChange(settings, frameDecoder: &frameDecoder)
newState = .prefaceReceived(newStateData)
return result
}
case .prefaceSent(let state):
return self.avoidingStateMachineCoW { newState in
var newStateData = ActiveConnectionState(fromPrefaceSent: state, remoteSettings: HTTP2SettingsState(localState: false))
let result = newStateData.receiveSettingsChange(settings, frameDecoder: &frameDecoder)
newState = .active(newStateData)
return result
}
case .prefaceReceived(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveSettingsChange(settings, frameDecoder: &frameDecoder)
newState = .prefaceReceived(state)
return result
}
case .active(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveSettingsChange(settings, frameDecoder: &frameDecoder)
newState = .active(state)
return result
}
case .remotelyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveSettingsChange(settings, frameDecoder: &frameDecoder)
newState = .remotelyQuiesced(state)
return result
}
case .locallyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveSettingsChange(settings, frameDecoder: &frameDecoder)
newState = .locallyQuiesced(state)
return result
}
case .bothQuiescing(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveSettingsChange(settings, frameDecoder: &frameDecoder)
newState = .bothQuiescing(state)
return result
}
case .quiescingPrefaceSent(let state):
return self.avoidingStateMachineCoW { newState in
var newStateData = LocallyQuiescedState(fromQuiescingPrefaceSent: state, remoteSettings: HTTP2SettingsState(localState: false))
let result = newStateData.receiveSettingsChange(settings, frameDecoder: &frameDecoder)
newState = .locallyQuiesced(newStateData)
return result
}
case .quiescingPrefaceReceived(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveSettingsChange(settings, frameDecoder: &frameDecoder)
newState = .quiescingPrefaceReceived(state)
return result
}
case .fullyQuiesced:
return (.init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil), .nothing)
case .modifying:
preconditionFailure("Must not be left in modifying state")
}
}
private mutating func receiveSettingsAck(frameEncoder: inout HTTP2FrameEncoder) -> StateMachineResultWithEffect {
// We can only receive a SETTINGS ACK after we've sent our own preface *and* the remote peer has
// sent its own. That means we have to be active or quiescing.
switch self.state {
case .active(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveSettingsAck(frameEncoder: &frameEncoder)
newState = .active(state)
return result
}
case .locallyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveSettingsAck(frameEncoder: &frameEncoder)
newState = .locallyQuiesced(state)
return result
}
case .remotelyQuiesced(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveSettingsAck(frameEncoder: &frameEncoder)
newState = .remotelyQuiesced(state)
return result
}
case .bothQuiescing(var state):
return self.avoidingStateMachineCoW { newState in
let result = state.receiveSettingsAck(frameEncoder: &frameEncoder)
newState = .bothQuiescing(state)
return result
}
case .idle, .prefaceSent, .prefaceReceived, .quiescingPrefaceReceived, .quiescingPrefaceSent:
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.receivedBadSettings(), type: .protocolError), effect: nil)
case .fullyQuiesced:
return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil)
case .modifying:
preconditionFailure("Must not be left in modifying state")
}
}
/// Validates a single HTTP/2 settings block.
///
/// - parameters:
/// - settings: The HTTP/2 settings block to validate.
/// - returns: The result of the validation.
private func validateSettings(_ settings: HTTP2Settings) -> StateMachineResult {
for setting in settings {
switch setting.parameter {
case .enablePush:
guard setting._value == 0 || setting._value == 1 else {
return .connectionError(underlyingError: NIOHTTP2Errors.invalidSetting(setting: setting), type: .protocolError)
}
case .initialWindowSize:
guard setting._value <= HTTP2FlowControlWindow.maxSize else {
return .connectionError(underlyingError: NIOHTTP2Errors.invalidSetting(setting: setting), type: .flowControlError)
}
case .maxFrameSize:
guard setting._value >= (1 << 14) && setting._value <= ((1 << 24) - 1) else {
return .connectionError(underlyingError: NIOHTTP2Errors.invalidSetting(setting: setting), type: .protocolError)
}
default:
// All other settings have unrestricted ranges.
break
}
}
return .succeed
}
}
extension HTTP2ConnectionStateMachine.State {
// Sets the connection state to fullyQuiesced if necessary.
//
// We should only call this when a server has quiesced the connection. As long as only the client has quiesced the
// connection more work can always be done.
mutating func closeIfNeeded<CurrentState: QuiescingState & LocallyQuiescingState & RemotelyQuiescingState & SendAndReceiveGoawayState & ConnectionStateWithRole & ConnectionStateWithConfiguration>(_ state: CurrentState) {
if state.quiescedByServer && state.streamState.openStreams == 0 {
self = .fullyQuiesced(.init(previousState: state))
}
}
// Sets the connection state to fullyQuiesced if necessary.
//
// We should only call this when a server has quiesced the connection. As long as only the client has quiesced the
// connection more work can always be done.
mutating func closeIfNeeded<CurrentState: QuiescingState & LocallyQuiescingState & SendAndReceiveGoawayState & ConnectionStateWithRole & ConnectionStateWithConfiguration>(_ state: CurrentState) {
if state.quiescedByServer && state.streamState.openStreams == 0 {
self = .fullyQuiesced(.init(previousState: state))
}
}
// Sets the connection state to fullyQuiesced if necessary.
//
// We should only call this when a server has quiesced the connection. As long as only the client has quiesced the
// connection more work can always be done.
mutating func closeIfNeeded<CurrentState: QuiescingState & RemotelyQuiescingState & SendAndReceiveGoawayState & ConnectionStateWithRole & ConnectionStateWithConfiguration>(_ state: CurrentState) {
if state.quiescedByServer && state.streamState.openStreams == 0 {
self = .fullyQuiesced(.init(previousState: state))
}
}
}
// MARK: CoW helpers
extension HTTP2ConnectionStateMachine {
/// So, uh...this function needs some explaining.
///
/// While the state machine logic above is great, there is a downside to having all of the state machine data in
/// associated data on enumerations: any modification of that data will trigger copy on write for heap-allocated
/// data. That means that for _every operation on the state machine_ we will CoW our underlying state, which is
/// not good.
///
/// The way we can avoid this is by using this helper function. It will temporarily set state to a value with no
/// associated data, before attempting the body of the function. It will also verify that the state machine never
/// remains in this bad state.
///
/// A key note here is that all callers must ensure that they return to a good state before they exit.
///
/// Sadly, because it's generic and has a closure, we need to force it to be inlined at all call sites, which is
/// not ideal.
@inline(__always)
private mutating func avoidingStateMachineCoW<ReturnType>(_ body: (inout State) -> ReturnType) -> ReturnType {
self.state = .modifying
defer {
assert(!self.isModifying)
}
return body(&self.state)
}
private var isModifying: Bool {
if case .modifying = self.state {
return true
} else {
return false
}
}
}
extension HTTP2StreamID {
/// Confirms that this kind of stream ID may be initiated by a peer in the specific role.
///
/// RFC 7540 limits odd stream IDs to being initiated by clients, and even stream IDs to
/// being initiated by servers. This method confirms this.
func mayBeInitiatedBy(_ role: HTTP2ConnectionStateMachine.ConnectionRole) -> Bool {
switch role {
case .client:
return self.isClientInitiated
case .server:
return self.isServerInitiated
}
}
}
/// A simple protocol that provides helpers that apply to all connection states that keep track of a role.
private protocol ConnectionStateWithRole {
var role: HTTP2ConnectionStateMachine.ConnectionRole { get }
}
extension ConnectionStateWithRole {
var peerRole: HTTP2ConnectionStateMachine.ConnectionRole {
switch self.role {
case .client:
return .server
case .server:
return .client
}
}
}
/// A simple protocol that provides helpers that apply to all connection states that have configuration.
private protocol ConnectionStateWithConfiguration {
var headerBlockValidation: HTTP2ConnectionStateMachine.ValidationState { get }
var contentLengthValidation: HTTP2ConnectionStateMachine.ValidationState { get}
}
| apache-2.0 | 60555fe3d74ea081e802955742dd8209 | 47.196112 | 258 | 0.669565 | 5.05396 | false | false | false | false |
wyp767363905/GiftSay | GiftSay/GiftSay/classes/giftSay/recommend/view/GSRecommendView.swift | 1 | 4299 | //
// GSRecommendView.swift
// GiftSay
//
// Created by qianfeng on 16/8/18.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
class GSRecommendView: UIView {
var clickClosure: ADCellClosure?
var tbView: UITableView?
var dataArray = Array<GSSelectItemsModel>()
var number: Int?
var model: GSRecommendModel?{
didSet {
tbView?.reloadData()
}
}
var secondaryBannersModel: GSSecondaryBannersModel?{
didSet {
tbView?.reloadData()
}
}
var selectModel: GSSelectModel? {
didSet {
if number == 0 {
dataArray.removeAll()
}
if selectModel?.data?.items?.count > 0 {
for item in (selectModel?.data?.items)! {
dataArray.append(item)
}
tbView?.reloadData()
}
}
}
init(){
super.init(frame: CGRectZero)
tbView = UITableView(frame: CGRectZero, style: .Plain)
tbView?.delegate = self
tbView?.dataSource = self
//分界线
tbView?.separatorStyle = .None
addSubview(tbView!)
tbView?.snp_makeConstraints(closure: {
[weak self]
(make) in
make.edges.equalTo(self!)
})
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension GSRecommendView : UITableViewDelegate,UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
var sectionNum = 0
if model?.data?.banners?.count > 0 {
sectionNum += 1
}
if secondaryBannersModel?.data?.secondary_banners?.count > 0 {
sectionNum += 1
}
if dataArray.count > 0 {
sectionNum += 1
}
return sectionNum
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rowNum = 0
if section == 0 {
if model?.data?.banners?.count > 0 {
rowNum = 1
}
}else if section == 1 {
if secondaryBannersModel?.data?.secondary_banners?.count > 0 {
rowNum = 1
}
}else if section == 2 {
if dataArray.count > 0 {
rowNum += dataArray.count
}
}
return rowNum
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var heigeht: CGFloat = 0
if indexPath.section == 0 {
if model?.data?.banners?.count > 0 {
heigeht = 160
}
}else if indexPath.section == 1 {
if secondaryBannersModel?.data?.secondary_banners?.count > 0 {
heigeht = 100
}
}else if indexPath.section == 2 {
if dataArray.count > 0 {
heigeht = 230
}
}
return heigeht
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
if indexPath.section == 0 {
if model?.data?.banners?.count > 0 {
cell = GSRecommendADCell.createADCellFor(tableView, atIndexPath: indexPath, withModel: model!, clickClosure: clickClosure)
}
}else if (secondaryBannersModel?.data?.secondary_banners?.count > 0) && (indexPath.section == 1) {
cell = GSSecondaryBannersCell.createADCellFor(tableView, atIndexPath: indexPath, withModel: secondaryBannersModel!)
}else if (dataArray.count > 0) && (indexPath.section == 2) {
cell = GSSelectCell.createSelectCellFor(tableView, atIndexPath: indexPath, withItemsModel: dataArray, clickClosure: clickClosure)
}
return cell
}
}
| mit | 321aba4671de2b0dc6614cd0ef111c77 | 23.655172 | 141 | 0.509091 | 5.231707 | false | false | false | false |
maxadamski/SwiftyHTTP | SwiftyHTTP/Foundation/RawByteBuffer.swift | 1 | 2515 | //
// RawByteBuffer.swift
// TestSwiftyCocoa
//
// Created by Helge Hess on 6/20/14.
// Copyright (c) 2014 Always Right Institute. All rights reserved.
//
import Darwin
public class RawByteBuffer {
public var buffer : UnsafeMutablePointer<RawByte>
public var capacity : Int
public var count : Int
let extra = 2
public init(capacity: Int) {
count = 0
self.capacity = capacity
if (self.capacity > 0) {
buffer = UnsafeMutablePointer<RawByte>.alloc(self.capacity + extra)
}
else {
buffer = nil
}
}
deinit {
if capacity > 0 {
buffer.dealloc(capacity + extra)
}
}
public func asByteArray() -> [UInt8] {
guard count > 0 else { return [] }
// having to assign a value is slow
var a = [UInt8](count: count, repeatedValue: 0)
memcpy(&a, self.buffer, self.count)
// Note: In the Darwin pkg there is also:
// memcpy(UnsafePointer<Void>(a), buffer, UInt(self.count))
// func memcpy(_: UnsafePointer<()>, _: ConstUnsafePointer<()>, _: UInt) -> UnsafePointer<()>
return a
}
public func ensureCapacity(newCapacity: Int) {
guard newCapacity > capacity else { return }
let newsize = newCapacity + 1024
let newbuf = UnsafeMutablePointer<RawByte>.alloc(newsize + extra)
if (count > 0) {
memcpy(newbuf, buffer, count)
}
buffer.dealloc(capacity + extra)
buffer = newbuf
capacity = newsize
}
public func reset() {
count = 0
}
public func addBytes(src: UnsafePointer<Void>, length: Int) {
// debugPrint("add \(length) count: \(count) capacity: \(capacity)")
guard length > 0 else {
// This is fine, happens for empty bodies (like in OPTION requests)
// debugPrint("NO LENGTH?")
return
}
ensureCapacity(count + length)
let dest = buffer + count
memcpy(UnsafeMutablePointer<Void>(dest), src, length)
count += length
// debugPrint("--- \(length) count: \(count) capacity: \(capacity)")
}
public func add(cs: UnsafePointer<CChar>, length: Int? = nil) {
if let len = length {
addBytes(cs, length: len)
}
else {
addBytes(cs, length: Int(strlen(cs)))
}
}
public func asString() -> String? {
guard buffer != nil else { return nil }
let cptr = UnsafeMutablePointer<CChar>(buffer)
cptr[count] = 0 // null terminate, buffer is always bigger than it claims
return String.fromCString(cptr)
}
}
| mit | b1ea87a784cd9047807bfdc3387ac9bd | 24.40404 | 99 | 0.609145 | 4.030449 | false | false | false | false |
LeeMZC/MZCWB | MZCWB/MZCWB/Classes/Other/AppDelegate.swift | 1 | 3680 | //
// AppDelegate.swift
// MZCWB
//
// Created by 马纵驰 on 16/7/19.
// Copyright © 2016年 马纵驰. All rights reserved.
//
import UIKit
import QorumLogs
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
//MARK:- 属性
var window: UIWindow?
var baseTabBarController : MZCBaseTabBarViewController?
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
setupNotf()
QorumLogs.enabled = true;
// 1.创建window
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.backgroundColor = UIColor.whiteColor()
// 2.设置根控制器
uiwindowRootVC()
// testMessageViewController()
// 3.显示window
window?.makeKeyAndVisible()
return true
}
//MARK:- private函数
private func setupNotf(){
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.uiWindowOfNewVersion), name: IsNewVersionCollectionViewControllerWillChange, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.welcomeViewControllerWillChange), name: MZCWelcomeViewControllerWillChange, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.mainUIWindowWillChange), name: MZCMainViewControllerWillChange, object: nil)
}
//MARK:根据逻辑切换UIWindow
@objc private func uiwindowRootVC(){
if isLogin() {
uiWindowOfNewVersion()
}else {
window?.rootViewController = MZCLoginTabBarViewController()
}
}
private func isLogin() -> Bool{
if MZCAccountTokenMode.accountToKen() != nil {
return true
}
return false
}
//MARK: 判断是否新颁布
private lazy var isNewVersion : Bool = {
// 1.加载info.plist
// 2.获取当前软件的版本号
let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
// 3.获取以前的软件版本号?
let defaults = NSUserDefaults.standardUserDefaults()
let sanboxVersion = (defaults.objectForKey("xxoo") as? String) ?? "0.0"
// 4.用当前的版本号和以前的版本号进行比较
// 1.0 0.0
if currentVersion.compare(sanboxVersion) == NSComparisonResult.OrderedDescending
{
// 如果当前的大于以前的, 有新版本
QL1("有新版本")
// 如果有新版本, 就利用新版本的版本号更新本地的版本号
defaults.setObject(currentVersion, forKey: "xxoo")
defaults.synchronize() // iOS7以前需要写, iOS7以后不用写
return true
}
QL1("没有新版本")
return false
}()
@objc private func uiWindowOfNewVersion(){
if isNewVersion {
window?.rootViewController = MZCNewVersionCollectionViewController()
}else {
window?.rootViewController = MZCWelcomeViewController()
}
}
@objc private func mainUIWindowWillChange(){
window?.rootViewController = MZCTabBarController()
}
@objc private func welcomeViewControllerWillChange(){
window?.rootViewController = MZCWelcomeViewController()
}
}
| artistic-2.0 | b8910234f5bdb717a46b2d3f0f21a1bc | 28.205128 | 184 | 0.623646 | 4.988321 | false | false | false | false |
yankodimitrov/Meerkat-Swift-Signals | MeerkatTests/ObserversDispatcherTests.swift | 1 | 2655 | //
// ObserversDispatcherTests.swift
// Meerkat
//
// Created by Yanko Dimitrov on 12/30/14.
// Copyright (c) 2014 Yanko Dimitrov. All rights reserved.
//
import UIKit
import XCTest
class ObserversDispatcherTests: XCTestCase {
class Subject {
let valueDidChange = ObserversDispatcher<Subject>()
}
var subject = Subject()
override func setUp() {
super.setUp()
subject = Subject()
}
func testThatWeCanAddNewObserver() {
subject.valueDidChange.addObserver(self, withCallback: { sender in })
XCTAssertTrue(subject.valueDidChange.hasObserver(self), "We should be able to add a new observer")
}
func testThatWeAreUnableToAddTheSameObserverWithDifferentCallback() {
var isSecondCallbackCalled = false
subject.valueDidChange.addObserver(self, withCallback: { sender in })
subject.valueDidChange.addObserver(self, withCallback: {
sender in
isSecondCallbackCalled = true
})
subject.valueDidChange.dispatchWithSender(subject)
XCTAssertFalse(isSecondCallbackCalled, "We should be unable to add the same observer with different callback")
}
func testThatWeCanRemoveObserver() {
subject.valueDidChange.addObserver(self, withCallback: { sender in })
subject.valueDidChange.removeObserver(self)
XCTAssertFalse(subject.valueDidChange.hasObserver(self), "We should be able to remove an observer")
}
func testThatWeCanRemoveAllObservers() {
class SecondObserver {}
let secondObserver = SecondObserver()
subject.valueDidChange.addObserver(self, withCallback: { sender in })
subject.valueDidChange.addObserver(secondObserver, withCallback: { sender in })
subject.valueDidChange.removeAllObservers()
XCTAssertFalse(subject.valueDidChange.hasObserver(self), "We should be able to remove all observers")
XCTAssertFalse(subject.valueDidChange.hasObserver(secondObserver), "We should be able to remove all observers")
}
func testThatWeCanNotifyObservers() {
var isCallbackCalled = false
subject.valueDidChange.addObserver(self, withCallback: {
sender in
isCallbackCalled = true
})
subject.valueDidChange.dispatchWithSender(subject)
XCTAssertTrue(isCallbackCalled, "We should be able to notify the observers")
}
}
| mit | f3753d6ad6dc34ef678eb88d462e2ce1 | 29.170455 | 119 | 0.638795 | 5.474227 | false | true | false | false |
lukaszwas/mcommerce-api | Sources/App/Models/Stripe/API/Routes/BalanceRoutes.swift | 1 | 2079 | //
// BalanceRoutes.swift
// Stripe
//
// Created by Anthony Castelli on 4/13/17.
//
//
import Foundation
import Node
public final class BalanceRoutes {
let client: StripeClient
init(client: StripeClient) {
self.client = client
}
/**
Retrieve balance
Retrieves the current account balance, based on the authentication that was used to make the request.
- returns: A StripeRequest<> item which you can then use to convert to the corresponding node
*/
public func retrieveBalance() throws -> StripeRequest<Balance> {
return try StripeRequest(client: self.client, method: .get, route: .balance, query: [:], body: nil, headers: nil)
}
/**
Retrieve a balance transaction
Retrieves the balance transaction with the given ID.
- returns: A StripeRequest<> item which you can then use to convert to the corresponding node
*/
public func retrieveBalance(forTransaction transactionId: String) throws -> StripeRequest<BalanceTransactionItem> {
return try StripeRequest(client: self.client, method: .get, route: .balanceHistoryTransaction(transactionId), query: [:], body: nil, headers: nil)
}
/**
List all balance history
Returns a list of transactions that have contributed to the Stripe account balance (e.g., charges, transfers, and so forth).
The transactions are returned in sorted order, with the most recent transactions appearing first.
- parameter filter: A Filter item to ass query parameters when fetching results
- returns: A StripeRequest<> item which you can then use to convert to the corresponding node
*/
public func history(forFilter filter: Filter?=nil) throws -> StripeRequest<BalanceHistoryList> {
var query = [String : NodeRepresentable]()
if let data = try filter?.createQuery() {
query = data
}
return try StripeRequest(client: self.client, method: .get, route: .balanceHistory, query: query, body: nil, headers: nil)
}
}
| mit | ec0830300f563a09e068b43ce7f2e3b6 | 35.473684 | 154 | 0.678211 | 4.67191 | false | false | false | false |
MLSDev/TRON | Source/Tests/TronTestCase.swift | 1 | 688 | //
// TronTestCase.swift
// TRON
//
// Created by Denys Telezhkin on 28.01.16.
// Copyright © 2016 Denys Telezhkin. All rights reserved.
//
import XCTest
import TRON
class TronTestCase: XCTestCase {
var tron: TRON!
override func setUp() {
super.setUp()
tron = TRON(baseURL: "https://github.com")
}
override func tearDown() {
super.tearDown()
tron = nil
}
func testTronRequestBuildables() {
let request: APIRequest<Int, APIError> = tron.swiftyJSON.request("/foo")
let tronBuilder = tron.urlBuilder
let requestBuilder = request.urlBuilder
XCTAssert(requestBuilder === tronBuilder)
}
}
| mit | f91e603d9517ae5d27bae04def8a5116 | 19.205882 | 80 | 0.628821 | 4.089286 | false | true | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/UINavigationBarAppearance+Extensions.swift | 1 | 904 | import Foundation
import UIKit
@objc extension UINavigationBarAppearance {
@objc static func appearanceForTheme(_ theme: Theme, style: WMFThemeableNavigationControllerStyle) -> UINavigationBarAppearance {
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
appearance.backgroundColor = theme.colors.chromeBackground
appearance.titleTextAttributes = theme.navigationBarTitleTextAttributes
switch style {
case .editor:
appearance.backgroundImage = theme.editorNavigationBarBackgroundImage
case .sheet:
appearance.backgroundImage = theme.sheetNavigationBarBackgroundImage
case .gallery:
appearance.backgroundImage = nil
default:
appearance.backgroundImage = theme.navigationBarBackgroundImage
}
return appearance
}
}
| mit | e4400a515d80ef04fd54d64087ac25be | 38.304348 | 133 | 0.714602 | 7.007752 | false | false | false | false |
Parallaxer/PhotoBook | Sources/View Controllers/PhotoBookViewController.swift | 1 | 4889 | import Parallaxer
import UIKit
import RxSwift
import RxCocoa
private let kPhotoBookCellID = "PhotoBookCell"
final class PhotoBookViewController: UIViewController, UICollectionViewDelegate {
@IBOutlet fileprivate var collectionView: UICollectionView!
@IBOutlet fileprivate var infinitePageView: InfinitePageView!
@IBOutlet fileprivate var photoInfoView: PhotoInfoView!
@IBOutlet fileprivate var photoInfoHeightConstraint: NSLayoutConstraint!
private lazy var photoBookAnimation: PhotoBookAnimation = {
return PhotoBookAnimation(
photoBookLayout: collectionView.collectionViewLayout as! PhotoBookCollectionViewLayout,
photoBookCollectionView: collectionView)
}()
private lazy var verticalInteractionView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.frame.size.height = view.bounds.height
scrollView.contentSize = CGSize(width: view.bounds.width, height: view.bounds.height * 2)
scrollView.isPagingEnabled = true
scrollView.alwaysBounceHorizontal = false
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
return scrollView
}()
fileprivate let photos = PhotoInfo.defaultPhotos
private var disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
infinitePageView.numberOfPages = photos.count
collectionView.reloadData()
// We need to make sure that the views have dimensionality so that our parallax intervals don't throw
// an error. In a production app, you'll need to handle the cases where your view's size is zero, but
// for the sake of this example, lets force the collection view to layout and show the content we just
// loaded.
collectionView.layoutIfNeeded()
setUpPhotoBookInteraction()
setUpPhotoInfoInteraction()
}
override var prefersStatusBarHidden: Bool {
return true
}
}
extension PhotoBookViewController {
private func setUpPhotoBookInteraction () {
photoBookAnimation
.visiblePhotoIndex
.drive(onNext: { [weak self] index in
guard let self = self else {
return
}
self.photoInfoView.populate(withPhotoInfo: self.photos[index])
})
.disposed(by: disposeBag)
infinitePageView
.bindScrollingTransform(photoBookAnimation.photoBookScrollingTransform)
.disposed(by: disposeBag)
}
private func setUpPhotoInfoInteraction() {
view.addGestureRecognizer(verticalInteractionView.panGestureRecognizer)
view.addSubview(verticalInteractionView)
let interactionTransform = verticalInteractionView.rx.contentOffset
.map { return $0.y }
// Create a transform which follows the content offset over the interval of interaction.
.parallax(over: .interval(from: 0, to: verticalInteractionView.bounds.height))
let photoInfoAnimation = PhotoInfoAnimation(maxDrawerLength: 128)
photoInfoAnimation
.photoBookInteractionEnabled
.asObservable()
.bind(to: collectionView.rx.isUserInteractionEnabled)
.disposed(by: disposeBag)
photoInfoAnimation
.photoBookAlpha
.asObservable()
.bind(to: collectionView.rx.alpha)
.disposed(by: disposeBag)
photoInfoAnimation
.photoBookScale
.emit(onNext: { [weak self] scale in
self?.collectionView.transform = CGAffineTransform(scaleX: scale, y: scale)
})
.disposed(by: disposeBag)
photoInfoAnimation
.photoInfoDrawerLength
.asObservable()
.bind(to: photoInfoHeightConstraint.rx.constant)
.disposed(by: disposeBag)
photoInfoAnimation
.bindDrawerInteraction(interactionTransform)
.disposed(by: disposeBag)
}
}
extension PhotoBookViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photos.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)
-> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPhotoBookCellID, for: indexPath)
as! PhotoBookCollectionViewCell
cell.image = photos[indexPath.row].image
photoBookAnimation
.bindPagingParallax(to: cell, at: indexPath)
.disposed(by: cell.disposeBag)
return cell
}
}
| mit | 1dac4ef3f6ffe1b149e9472c29a71709 | 34.686131 | 110 | 0.662917 | 5.731536 | false | false | false | false |
JGiola/swift-package-manager | Sources/PackageModel/Platform.swift | 1 | 4172 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2018 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
*/
/// A registry for available platforms.
public final class PlatformRegistry {
/// The current registery is hardcoded and static so we can just use
/// a singleton for now.
public static let `default`: PlatformRegistry = .init()
/// The list of known platforms.
public let knownPlatforms: [Platform]
/// The mapping of platforms to their name.
public let platformByName: [String: Platform]
/// Create a registry with the given list of platforms.
init(platforms: [Platform] = PlatformRegistry._knownPlatforms) {
self.knownPlatforms = platforms
self.platformByName = Dictionary(uniqueKeysWithValues: knownPlatforms.map({ ($0.name, $0) }))
}
/// The static list of known platforms.
private static var _knownPlatforms: [Platform] {
return [.macOS, .iOS, .tvOS, .watchOS, .linux]
}
}
/// Represents a platform.
public struct Platform: Equatable, Hashable {
/// The name of the platform.
public let name: String
/// The oldest supported deployment version by this platform.
///
/// We currently hardcode this value but we should load it from the
/// SDK's plist file. This value is always present for Apple platforms.
public let oldestSupportedVersion: PlatformVersion
/// Create a platform.
private init(name: String, oldestSupportedVersion: PlatformVersion) {
self.name = name
self.oldestSupportedVersion = oldestSupportedVersion
}
public static let macOS: Platform = Platform(name: "macos", oldestSupportedVersion: "10.10")
public static let iOS: Platform = Platform(name: "ios", oldestSupportedVersion: "8.0")
public static let tvOS: Platform = Platform(name: "tvos", oldestSupportedVersion: "9.0")
public static let watchOS: Platform = Platform(name: "watchos", oldestSupportedVersion: "2.0")
public static let linux: Platform = Platform(name: "linux", oldestSupportedVersion: .unknown)
}
/// Represents a platform version.
public struct PlatformVersion: ExpressibleByStringLiteral, Comparable, Hashable {
/// The unknown platform version.
public static let unknown: PlatformVersion = .init("0.0.0")
/// The underlying version storage.
private let version: Version
/// The string representation of the version.
public var versionString: String {
var str = "\(version.major).\(version.minor)"
if version.patch != 0 {
str += ".\(version.patch)"
}
return str
}
/// Create a platform version given a string.
///
/// The platform version is expected to be in format: X.X.X
public init(_ version: String) {
let components = version.split(separator: ".").compactMap({ Int($0) })
assert(!components.isEmpty && components.count <= 3, version)
switch components.count {
case 1:
self.version = Version(components[0], 0, 0)
case 2:
self.version = Version(components[0], components[1], 0)
case 3:
self.version = Version(components[0], components[1], components[2])
default:
fatalError("Unexpected number of components \(components)")
}
}
// MARK:- ExpressibleByStringLiteral
public init(stringLiteral value: String) {
self.init(value)
}
// MARK:- Comparable
public static func < (lhs: PlatformVersion, rhs: PlatformVersion) -> Bool {
return lhs.version < rhs.version
}
}
/// Represents a platform supported by a target.
public struct SupportedPlatform {
/// The platform.
public let platform: Platform
/// The minimum required version for this platform.
public let version: PlatformVersion
public init(platform: Platform, version: PlatformVersion) {
self.platform = platform
self.version = version
}
}
| apache-2.0 | 53475c73637fb1ec2adfd3d73d0ede12 | 33.479339 | 101 | 0.67186 | 4.620155 | false | false | false | false |
m-alani/contests | leetcode/longestSubstringWithoutRepeatingCharacters.swift | 1 | 958 | //
// longestSubstringWithoutRepeatingCharacters.swift
//
// Practice solution - Marwan Alani - 2017
//
// Check the problem (and run the code) on leetCode @ https://leetcode.com/problems/longest-substring-without-repeating-characters/
// Note: make sure that you select "Swift" from the top-left language menu of the code editor when testing this code
//
class Solution {
func lengthOfLongestSubstring(_ s: String) -> Int {
// In Swift 4, String is a collection type, so we can do "s.makeIterator()" without creating a Character View first
var itr = s.characters.makeIterator()
var longest = 0, begin = 0, end = 0
var letters = [Character: Int]()
while let key = itr.next() {
if let prev = letters[key] {
if begin <= prev {
begin = prev + 1
}
}
letters[key] = end
if longest <= end - begin {
longest = end - begin + 1
}
end += 1
}
return longest
}
}
| mit | 8bfe71d3107fb84d504eb37781303e82 | 30.933333 | 132 | 0.629436 | 3.942387 | false | false | false | false |
GraphQLSwift/GraphQL | Sources/GraphQL/Map/MapSerialization.swift | 1 | 3727 | import Foundation
import OrderedCollections
public struct MapSerialization {
static func map(with object: NSObject) throws -> Map {
switch object {
case is NSNull:
return .null
case let number as NSNumber:
return .number(Number(number))
case let string as NSString:
return .string(string as String)
case let array as NSArray:
let array: [Map] = try array.map { value in
guard let value = value as? NSObject else {
throw EncodingError.invalidValue(
array,
EncodingError.Context(
codingPath: [],
debugDescription: "Array value was not an object: \(value) in \(array)"
)
)
}
return try self.map(with: value)
}
return .array(array)
case let dictionary as NSDictionary:
// Extract from an unordered dictionary, using NSDictionary extraction order
let orderedDictionary: OrderedDictionary<String, Map> = try dictionary
.reduce(into: [:]) { dictionary, pair in
guard let key = pair.key as? String else {
throw EncodingError.invalidValue(
dictionary,
EncodingError.Context(
codingPath: [],
debugDescription: "Dictionary key was not string: \(pair.key) in \(dictionary)"
)
)
}
guard let value = pair.value as? NSObject else {
throw EncodingError.invalidValue(
dictionary,
EncodingError.Context(
codingPath: [],
debugDescription: "Dictionary value was not an object: \(key) in \(dictionary)"
)
)
}
dictionary[key] = try self.map(with: value)
}
return .dictionary(orderedDictionary)
default:
throw EncodingError.invalidValue(
object,
EncodingError.Context(
codingPath: [],
debugDescription: "Unable to encode the given top-level value to Map."
)
)
}
}
static func object(with map: Map) throws -> NSObject {
switch map {
case .undefined:
throw EncodingError.invalidValue(
self,
EncodingError.Context(
codingPath: [],
debugDescription: "undefined values should have been excluded from serialization"
)
)
case .null:
return NSNull()
case let .bool(value):
return value as NSObject
case var .number(number):
return number.number
case let .string(string):
return string as NSString
case let .array(array):
return try array.map { try object(with: $0) } as NSArray
case let .dictionary(dictionary):
// Coerce to an unordered dictionary
var unorderedDictionary: [String: NSObject] = [:]
for (key, value) in dictionary {
if !value.isUndefined {
try unorderedDictionary[key] = object(with: value)
}
}
return unorderedDictionary as NSDictionary
}
}
}
| mit | 6d332fd114f761c8072b059eea10ce54 | 38.648936 | 111 | 0.477059 | 6.211667 | false | false | false | false |
ilyahal/VKMusic | VkPlaylist/Reachability.swift | 1 | 2217 | //
// Reachability.swift
// VkPlaylist
//
// MIT License
//
// Copyright (c) 2016 Ilya Khalyapin
//
// 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 SystemConfiguration
/// Проверка на доступность сервисов
public class Reachability {
/// Активно ли подключение устройства к интернету
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
} | mit | 0685458c34b6cefd12724daef548be8d | 38.796296 | 95 | 0.707169 | 4.639309 | false | false | false | false |
benlangmuir/swift | test/attr/Inputs/BackDeployHelper.swift | 5 | 4944 | import Foundation
/// Returns the dsohandle for the dynamic library.
public func libraryHandle() -> UnsafeRawPointer {
return #dsohandle
}
/// Prepends "client:" or "library:" to the given string (depending on whether
/// the dsohandle belongs to the library or not) and then prints it.
public func testPrint(handle: UnsafeRawPointer, _ string: String) {
let libraryHandle = #dsohandle
let prefix = (handle == libraryHandle) ? "library" : "client"
print("\(prefix): \(string)")
}
/// Returns true if the host OS version is BackDeploy 2.0 or later, indicating
/// that APIs back deployed before 2.0 should run in the library.
public func isV2OrLater() -> Bool {
if #available(BackDeploy 2.0, *) {
return true
} else {
return false
}
}
/// Returns true if BackDeploy 2.0 APIs have been stripped from the binary.
public func v2APIsAreStripped() -> Bool {
#if STRIP_V2_APIS
return true
#else
return false
#endif // STRIP_V2_APIS
}
/// Describes types that can be appended to.
public protocol Appendable {
associatedtype Element
mutating func append(_ x: Element)
}
/// Describes types that can be counted.
public protocol Countable {
var count: Int { get }
}
public enum BadError: Error, Equatable {
/// Indicates badness
case bad
}
/// A totally unnecessary array type for `Int` elements.
public struct IntArray {
@usableFromInline
internal var _values: [Int]
public init(_ values: [Int]) { _values = values }
}
extension IntArray: Appendable {
public mutating func append(_ x: Int) {
_values.append(x)
}
}
extension IntArray: Countable {
public var count: Int { _values.count }
}
/// A totally unnecessary array type for `Int` elements with reference semantics.
public class ReferenceIntArray {
@usableFromInline
internal var _values: [Int]
public init(_ values: [Int]) { _values = values }
}
extension ReferenceIntArray: Appendable {
public func append(_ x: Int) {
_values.append(x)
}
}
extension ReferenceIntArray: Countable {
public var count: Int { _values.count }
}
// MARK: - Back deployed APIs
#if !STRIP_V2_APIS
@available(BackDeploy 1.0, *)
@_backDeploy(before: BackDeploy 2.0)
public func trivial() {
testPrint(handle: #dsohandle, "trivial")
}
@available(BackDeploy 1.0, *)
@_backDeploy(before: BackDeploy 2.0)
public func pleaseThrow(_ shouldThrow: Bool) throws -> Bool {
if shouldThrow { throw BadError.bad }
return !shouldThrow
}
@available(BackDeploy 1.0, *)
@_backDeploy(before: BackDeploy 2.0)
public func genericAppend<T: Appendable>(
_ a: inout T,
_ x: T.Element
) {
return a.append(x)
}
@available(BackDeploy 1.0, *)
@_backDeploy(before: BackDeploy 2.0)
public func existentialCount(_ c: any Countable) -> Int {
c.count
}
extension IntArray {
@available(BackDeploy 1.0, *)
@_backDeploy(before: BackDeploy 2.0)
public var values: [Int] { _values }
@available(BackDeploy 1.0, *)
@_backDeploy(before: BackDeploy 2.0)
public func print() {
// Tests recursive @_backDeploy since `Array.print()` is also @_backDeploy
_values.print()
}
@available(BackDeploy 1.0, *)
@_backDeploy(before: BackDeploy 2.0)
public static var empty: Self { IntArray([]) }
@available(BackDeploy 1.0, *)
@_backDeploy(before: BackDeploy 2.0)
public func toCountable() -> any Countable { self }
@available(BackDeploy 1.0, *)
@_backDeploy(before: BackDeploy 2.0)
public subscript(_ i: Int) -> Int {
get { _values[i] }
_modify { yield &_values[i] }
}
@available(BackDeploy 1.0, *)
@_backDeploy(before: BackDeploy 2.0)
public var rawValues: [Int] {
_read { yield _values }
}
}
extension ReferenceIntArray {
@available(BackDeploy 1.0, *)
@_backDeploy(before: BackDeploy 2.0)
public final var values: [Int] { _values }
@available(BackDeploy 1.0, *)
@_backDeploy(before: BackDeploy 2.0)
public final func print() {
// Tests recursive @_backDeploy since `Array.print()` is also @_backDeploy
_values.print()
}
@available(BackDeploy 1.0, *)
@_backDeploy(before: BackDeploy 2.0)
public final func copy() -> ReferenceIntArray {
return ReferenceIntArray(values)
}
@available(BackDeploy 1.0, *)
@_backDeploy(before: BackDeploy 2.0)
public final class var empty: ReferenceIntArray { ReferenceIntArray([]) }
@available(BackDeploy 1.0, *)
@_backDeploy(before: BackDeploy 2.0)
public final func toCountable() -> any Countable { self }
@available(BackDeploy 1.0, *)
@_backDeploy(before: BackDeploy 2.0)
public final subscript(_ i: Int) -> Int {
get { _values[i] }
_modify { yield &_values[i] }
}
@available(BackDeploy 1.0, *)
@_backDeploy(before: BackDeploy 2.0)
public final var rawValues: [Int] {
_read { yield _values }
}
}
extension Array {
@available(BackDeploy 1.0, *)
@_backDeploy(before: BackDeploy 2.0)
public func print() {
testPrint(handle: #dsohandle, description)
}
}
#endif // !STRIP_V2_APIS
| apache-2.0 | d5da532f03ac0a7eab24e59d518dcf70 | 23.35468 | 81 | 0.682039 | 3.603499 | false | false | false | false |
mbeloded/beaconDemo | PassKitApp/PassKitApp/Classes/UI/Widgets/BannerView/BannerView.swift | 1 | 3633 | //
// BannerView.swift
// PassKitApp
//
// Created by Alexandr Chernyy on 10/3/14.
// Copyright (c) 2014 Alexandr Chernyy. All rights reserved.
//
import UIKit
class BannerView: UIView {
@IBOutlet var bannerImage:PFImageView?
@IBOutlet var pageControl:UIPageControl?
var mall_banner_items:Array<AnyObject>!
var banner_items:Array<AnyObject> = []
var index:Int = 0
@IBOutlet weak var guest:UISwipeGestureRecognizer!
@IBOutlet weak var guest1:UISwipeGestureRecognizer!
func setupView(mall_id:String)
{
if guest != nil {
self.addGestureRecognizer(guest)
}
if guest1 != nil {
self.addGestureRecognizer(guest1)
}
mall_banner_items = CoreDataManager.sharedManager.loadData(RequestType.MALL_BANNER, key:mall_id)
for object in mall_banner_items {
var banners:Array<AnyObject> = CoreDataManager.sharedManager.loadData(RequestType.BANNER, key:(object as MallBannerModel).banner_id)
for items in banners {
banner_items.append(items)
}
}
pageControl?.numberOfPages = banner_items.count
pageControl?.pageIndicatorTintColor = UIColor.blackColor()
pageControl?.currentPageIndicatorTintColor = UIColor.lightGrayColor()
pageControl?.currentPage = index
if(banner_items.count > 0)
{
var url:NSString = (banner_items[index] as BannerModel).image!
var pngPath:NSString = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(url.lastPathComponent)");
bannerImage?.image = UIImage(named: pngPath)
}
var timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}
func update() {
index++
if(index >= banner_items.count)
{
index = 0
}
pageControl?.currentPage = index
if(banner_items.count > 0)
{
//println((banner_items[0] as MallBannerModel).id)
var url:NSString = (banner_items[index] as BannerModel).image!
var pngPath:NSString = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(url.lastPathComponent)");
bannerImage?.image = UIImage(named: pngPath)
}
}
func updateMinus() {
index--
if(index < 0)
{
index = 0
}
pageControl?.currentPage = index
if(banner_items.count > 0)
{
//println((banner_items[0] as MallBannerModel).id)
var url:NSString = (banner_items[index] as BannerModel).image!
var pngPath:NSString = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(url.lastPathComponent)");
bannerImage?.image = UIImage(named: pngPath)
}
}
@IBAction func rightSwipeAction(sender: AnyObject) {
self.updateMinus()
}
@IBAction func leftSwipeAction(sender: AnyObject) {
self.update()
}
@IBAction func pageAction(sender:AnyObject) {
index = (sender as UIPageControl).currentPage
pageControl?.currentPage = index
if(banner_items.count > 0)
{
//println((banner_items[0] as MallBannerModel).id)
var url:NSString = (banner_items[index] as BannerModel).image!
var pngPath:NSString = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(url.lastPathComponent)");
bannerImage?.image = UIImage(named: pngPath)
}
}
}
| gpl-2.0 | a61da4465081d6cdbf333d53ba531b81 | 33.273585 | 145 | 0.615745 | 4.761468 | false | false | false | false |
brittlewis12/vim-config | bundle/vim-swift/test/numeric_literals.swift | 1 | 448 | let decimalInteger = 17
let binaryInteger = 0b10001 // 17 in binary notation
let octalInteger = 0o21 // 17 in octal notation
let hexadecimalInteger = 0x11 // 17 in hexadecimal notation
let decimalInteger = 123_456_789
let separatedBinaryInteger = 0b10_001
let separatedOctalInteger = 0o21_17
let separatedHexadecimalInteger = 0x1a_f1
let pi = 3.141592
let exponential = 1.21875e1
let exponential2 = 1.21875e+1
| mit | 1a6429ecad0bbf1682589945b95ed743 | 39.727273 | 69 | 0.725446 | 3.672131 | false | false | false | false |
appsquickly/backdrop | source/CommandLine/StringExtensions.swift | 3 | 4559 | /*
* StringExtensions.swift
* Copyright (c) 2014 Ben Gollmer.
*
* 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.
*/
/* Required for localeconv(3) */
import Darwin
internal extension String {
/* Retrieves locale-specified decimal separator from the environment
* using localeconv(3).
*/
private func _localDecimalPoint() -> Character {
let locale = localeconv()
if locale != nil {
let decimalPoint = locale.memory.decimal_point
if decimalPoint != nil {
return Character(UnicodeScalar(UInt32(decimalPoint.memory)))
}
}
return "."
}
/**
* Attempts to parse the string value into a Double.
*
* - returns: A Double if the string can be parsed, nil otherwise.
*/
func toDouble() -> Double? {
var characteristic: String = "0"
var mantissa: String = "0"
var inMantissa: Bool = false
var isNegative: Bool = false
let decimalPoint = self._localDecimalPoint()
for (i, c) in self.characters.enumerate() {
if i == 0 && c == "-" {
isNegative = true
continue
}
if c == decimalPoint {
inMantissa = true
continue
}
if Int(String(c)) != nil {
if !inMantissa {
characteristic.append(c)
} else {
mantissa.append(c)
}
} else {
/* Non-numeric character found, bail */
return nil
}
}
return (Double(Int(characteristic)!) +
Double(Int(mantissa)!) / pow(Double(10), Double(mantissa.characters.count - 1))) *
(isNegative ? -1 : 1)
}
/**
* Splits a string into an array of string components.
*
* - parameter splitBy: The character to split on.
* - parameter maxSplit: The maximum number of splits to perform. If 0, all possible splits are made.
*
* - returns: An array of string components.
*/
func splitByCharacter(splitBy: Character, maxSplits: Int = 0) -> [String] {
var s = [String]()
var numSplits = 0
var curIdx = self.startIndex
for(var i = self.startIndex; i != self.endIndex; i = i.successor()) {
let c = self[i]
if c == splitBy && (maxSplits == 0 || numSplits < maxSplits) {
s.append(self[Range(start: curIdx, end: i)])
curIdx = i.successor()
numSplits++
}
}
if curIdx != self.endIndex {
s.append(self[Range(start: curIdx, end: self.endIndex)])
}
return s
}
/**
* Pads a string to the specified width.
*
* - parameter width: The width to pad the string to.
* - parameter padBy: The character to use for padding.
*
* - returns: A new string, padded to the given width.
*/
func paddedToWidth(width: Int, padBy: Character = " ") -> String {
var s = self
var currentLength = self.characters.count
while currentLength++ < width {
s.append(padBy)
}
return s
}
/**
* Wraps a string to the specified width.
*
* This just does simple greedy word-packing, it doesn't go full Knuth-Plass.
* If a single word is longer than the line width, it will be placed (unsplit)
* on a line by itself.
*
* - parameter width: The maximum length of a line.
* - parameter wrapBy: The line break character to use.
* - parameter splitBy: The character to use when splitting the string into words.
*
* - returns: A new string, wrapped at the given width.
*/
func wrappedAtWidth(width: Int, wrapBy: Character = "\n", splitBy: Character = " ") -> String {
var s = ""
var currentLineWidth = 0
for word in self.splitByCharacter(splitBy) {
let wordLength = word.characters.count
if currentLineWidth + wordLength + 1 > width {
/* Word length is greater than line length, can't wrap */
if wordLength >= width {
s += word
}
s.append(wrapBy)
currentLineWidth = 0
}
currentLineWidth += wordLength + 1
s += word
s.append(splitBy)
}
return s
}
}
| apache-2.0 | 58ae88b5fa9ba74b22a0573d834c0c12 | 27.141975 | 103 | 0.606493 | 4.140781 | false | false | false | false |
mkoehnke/WKZombie | Sources/WKZombie/HTMLFrame.swift | 1 | 2021 | //
// HTMLFrame.swift
//
// Copyright (c) 2016 Mathias Koehnke (http://www.mathiaskoehnke.de)
//
// 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
/// HTML iframe Class, which represents the <iframe> element in the DOM.
public class HTMLFrame : HTMLRedirectable {
/// Returns the value of the src attribute of the iframe.
public var source : String? {
return objectForKey("src")
}
//========================================
// MARK: Redirect Script
//========================================
internal override func actionScript() -> String? {
if let source = source {
return "window.top.location.href='\(source)';"
}
return nil
}
//========================================
// MARK: Overrides
//========================================
internal override class func createXPathQuery(_ parameters: String) -> String {
return "//iframe\(parameters)"
}
}
| mit | df0c0c083e28af5a9d80bb50c0837d7c | 37.865385 | 83 | 0.640772 | 4.90534 | false | false | false | false |
bsantanas/Twitternator2 | Twitternator2/Swifter/SwifterTrends.swift | 11 | 3169 | //
// SwifterTrends.swift
// Swifter
//
// Created by Matt Donnelly on 21/06/2014.
// Copyright (c) 2014 Matt Donnelly. All rights reserved.
//
import Foundation
public extension Swifter {
/*
GET trends/place
Returns the top 10 trending topics for a specific WOEID, if trending information is available for it.
The response is an array of "trend" objects that encode the name of the trending topic, the query parameter that can be used to search for the topic on Twitter Search, and the Twitter Search URL.
This information is cached for 5 minutes. Requesting more frequently than that will not return any more data, and will count against your rate limit usage.
*/
public func getTrendsPlaceWithWOEID(id: Int, excludeHashtags: Bool? = nil, success: ((trends: [JSONValue]?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "trends/place.json"
var parameters = Dictionary<String, Any>()
parameters["id"] = id
if excludeHashtags != nil {
if excludeHashtags! {
parameters["exclude"] = "hashtags"
}
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(trends: json.array)
return
}, failure: failure)
}
/*
GET trends/available
Returns the locations that Twitter has trending topic information for.
The response is an array of "locations" that encode the location's WOEID and some other human-readable information such as a canonical name and country the location belongs in.
A WOEID is a Yahoo! Where On Earth ID.
*/
public func getTrendsAvailableWithSuccess(success: ((trends: [JSONValue]?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "trends/available.json"
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(trends: json.array)
return
}, failure: failure)
}
/*
GET trends/closest
Returns the locations that Twitter has trending topic information for, closest to a specified location.
The response is an array of "locations" that encode the location's WOEID and some other human-readable information such as a canonical name and country the location belongs in.
A WOEID is a Yahoo! Where On Earth ID.
*/
public func getTrendsClosestWithLat(lat: Double, long: Double, success: ((trends: [JSONValue]?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "trends/closest.json"
var parameters = Dictionary<String, Any>()
parameters["lat"] = lat
parameters["long"] = long
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(trends: json.array)
return
}, failure: failure)
}
}
| mit | 6f4d92da30b0fd07a4a1c8cb3644de98 | 34.606742 | 199 | 0.65131 | 4.527143 | false | false | false | false |
GetZero/Give-Me-One | MyOne/个人/PersonalViewController.swift | 1 | 1634 | //
// PersonalViewController.swift
// MyOne
//
// Created by 韦曲凌 on 16/8/29.
// Copyright © 2016年 Wake GetZero. All rights reserved.
//
import UIKit
class PersonalViewController: UITableViewController {
var titles: [String] = ["设置", "关于"]
var images: [String] = ["setting", "copyright"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15)
tableView.rowHeight = 80
tableView.registerNib(UINib(nibName: "PersonalCell", bundle: nil), forCellReuseIdentifier: "PersonalCell")
tableView.separatorStyle = .None
tableView.bounces = false
tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth - 30, height: 1))
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return min(titles.count, images.count)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: PersonalCell = tableView.dequeueReusableCellWithIdentifier("PersonalCell", forIndexPath: indexPath) as! PersonalCell
cell.cellImage.image = UIImage(named: images[indexPath.row])
cell.titleLabel.text = titles[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 0 {
navigationController?.pushViewController(SettingViewController(), animated: true)
}
}
}
| apache-2.0 | f6a14fd0841aa4573d69e2a945d66d3d | 33.404255 | 134 | 0.685838 | 4.714286 | false | false | false | false |
zhihuitang/Apollo | Apollo/MyProfile/MyProfileViewController.swift | 1 | 5724 | //
// MyProfileViewController.swift
// Apollo
//
// Created by Zhihui Tang on 2017-01-23.
// Copyright © 2017 Zhihui Tang. All rights reserved.
//
import UIKit
// MARK:- 列表标题
let kMeSubScribe = "我的订阅"
let kMePlayHistory = "播放历史"
let kMeHasBuy = "我的已购"
let kMeWallet = "我的钱包"
let kMeLXFStore = "喜马拉雅商城"
let kMeStoreOrder = "我的商城订单"
let kMeCoupon = "我的优惠券"
let kMeGameenter = "游戏中心"
let kMeSmartDevice = "智能硬件设备"
let kMeFreeTrafic = "免流量服务"
let kMeFeedBack = "意见反馈"
let kMeSetting = "设置"
// 免流量服务 链接
let kFreeTraficURL = "http://hybrid.ximalaya.com/api/telecom/index?app=iting&device=iPhone&impl=com.gemd.iting&telephone=%28null%29&version=5.4.27"
let headerViewH: CGFloat = 288
class MyProfileViewController: BaseViewController {
override var name: String {
return "My profile"
}
// MARK:- 普通属性
var lightFlag: Bool = true
// MARK:- 懒加载属性
/// tableView
lazy var tableView: UITableView = { [unowned self] in
let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: self.view.height - 49), style: .grouped)
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = UIColor.hexInt(0xf3f3f3)
self.view.addSubview(tableView)
return tableView
}()
/// 列表标题数组
lazy var titleArray:[[String]] = {
return [[kMeSubScribe, kMePlayHistory],
[kMeHasBuy, kMeWallet],
[kMeLXFStore, kMeStoreOrder, kMeCoupon, kMeGameenter, kMeSmartDevice],
[kMeFreeTrafic, kMeFeedBack, kMeSetting]]
}()
/// 列表图标数组
lazy var imageArray:[[String]] = {
return [["me_setting_favAlbum", "me_setting_playhis"],
["me_setting_boughttracks", "me_setting_account"],
["me_setting_store", "me_setting_myorder", "me_setting_coupon", "me_setting_game", "me_setting_device"],
["me_setting_union", "me_setting_feedback", "me_setting_setting"]]
}()
/// 头部视图
lazy var headerView: MyProfileHeaderView = {
let view = MyProfileHeaderView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: headerViewH))
return view
}()
/// 状态栏
lazy var statusBackView: UIView = { [unowned self] in
let view = UIView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: 20))
view.backgroundColor = UIColor.white.withAlphaComponent(0.95)
self.view.addSubview(view)
self.view.bringSubview(toFront: view)
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.hexInt(0xf3f3f3)
automaticallyAdjustsScrollViewInsets = false
/// 初始化
setupView()
}
private func setupView() {
tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: headerViewH))
tableView.addSubview(headerView)
}
}
extension MyProfileViewController: UITableViewDelegate, UITableViewDataSource {
// MARK: 数据源
func numberOfSections(in tableView: UITableView) -> Int {
return titleArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let subTitleArr = titleArray[section]
return subTitleArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let subTextArr = titleArray[indexPath.section]
let imgArr = imageArray[indexPath.section]
let cellID = "cellId"
var cell = tableView.dequeueReusableCell(withIdentifier: cellID)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: cellID)
}
cell?.textLabel?.text = subTextArr[indexPath.row]
cell?.textLabel?.font = UIFont.systemFont(ofSize: 15)
cell?.textLabel?.textColor = RGBA(r: 0.0, g: 0.0, b: 0.0, a: 1.0)
cell?.accessoryType = .disclosureIndicator
cell?.selectionStyle = .none
cell?.imageView?.image = UIImage(named: imgArr[indexPath.row])
return cell!
}
// MARK: 代理
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
guard let title = cell?.textLabel?.text else {return}
if title == kMeFreeTrafic { // 免流量服务
jump2FreeTraficService()
} else if title == kMeSetting { // 设置
jump2Setting()
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44.0
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 10.0
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.01
}
private func jump2FreeTraficService() {
/*
guard let webVc = SVWebViewController(address: kFreeTraficURL) else {return}
webVc.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(webVc, animated: true)
*/
}
// MARK: 设置
private func jump2Setting() {
/*
let settingVc = LXFSettingViewController()
settingVc.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(settingVc, animated: true)
*/
}
}
| apache-2.0 | df89ce26fa7f264a7034d441399662b4 | 31.755952 | 147 | 0.629838 | 4.070266 | false | false | false | false |
Sillyplus/swifter | Sources/Swifter/HttpRequest.swift | 1 | 4634 | //
// HttpRequest.swift
// Swifter
// Copyright (c) 2015 Damian Kołakowski. All rights reserved.
//
import Foundation
public struct HttpRequest {
public let url: String
public let urlParams: [(String, String)]
public let method: String
public let headers: [String: String]
public let body: [UInt8]?
public var address: String?
public var params: [String: String]
public func parseUrlencodedForm() -> [(String, String)] {
guard let body = body, let contentTypeHeader = headers["content-type"] else {
return []
}
let contentTypeHeaderTokens = contentTypeHeader.split(";").map { $0.trim() }
guard let contentType = contentTypeHeaderTokens.first where contentType == "application/x-www-form-urlencoded" else {
return []
}
return UInt8ArrayToUTF8String(body).split("&").map { (param: String) -> (String, String) in
let tokens = param.split("=")
if let name = tokens.first, value = tokens.last where tokens.count == 2 {
return (name.replace("+", new: " ").removePercentEncoding(),
value.replace("+", new: " ").removePercentEncoding())
}
return ("","")
}
}
public struct MultiPart {
public let headers: [String: String]
public let body: [UInt8]
}
public func parseMultiPartFormData() -> [MultiPart] {
guard let body = body, let contentTypeHeader = headers["content-type"] else {
return []
}
let contentTypeHeaderTokens = contentTypeHeader.split(";").map { $0.trim() }
guard let contentType = contentTypeHeaderTokens.first where contentType == "multipart/form-data" else {
return []
}
var boundary: String? = nil
contentTypeHeaderTokens.forEach({
let tokens = $0.split("=")
if let key = tokens.first where key == "boundary" && tokens.count == 2 {
boundary = tokens.last
}
})
if let boundary = boundary where boundary.utf8.count > 0 {
return parseMultiPartFormData(body, boundary: "--\(boundary)")
}
return []
}
private func parseMultiPartFormData(data: [UInt8], boundary: String) -> [MultiPart] {
var generator = data.generate()
var result = [MultiPart]()
while let part = nextMultiPart(&generator, boundary: boundary, isFirst: result.isEmpty) {
result.append(part)
}
return result
}
private func nextMultiPart(inout generator: IndexingGenerator<[UInt8]>, boundary: String, isFirst: Bool) -> MultiPart? {
if isFirst {
guard nextMultiPartLine(&generator) == boundary else {
return nil
}
} else {
nextMultiPartLine(&generator)
}
var headers = [String: String]()
while let line = nextMultiPartLine(&generator) where !line.isEmpty {
let tokens = line.split(":")
if let name = tokens.first, value = tokens.last where tokens.count == 2 {
headers[name.lowercaseString] = value.trim()
}
}
guard let body = nextMultiPartBody(&generator, boundary: boundary) else {
return nil
}
return MultiPart(headers: headers, body: body)
}
private func nextMultiPartLine(inout generator: IndexingGenerator<[UInt8]>) -> String? {
var result = String()
while let value = generator.next() {
if value > Constants.CR {
result.append(Character(UnicodeScalar(value)))
}
if value == Constants.NL {
break
}
}
return result
}
private func nextMultiPartBody(inout generator: IndexingGenerator<[UInt8]>, boundary: String) -> [UInt8]? {
var body = [UInt8]()
let boundaryArray = [UInt8](boundary.utf8)
var matchOffset = 0;
while let x = generator.next() {
matchOffset = ( x == boundaryArray[matchOffset] ? matchOffset + 1 : 0 )
body.append(x)
if matchOffset == boundaryArray.count {
body.removeRange(Range<Int>(start: body.count-matchOffset, end: body.count))
if body.last == Constants.NL {
body.removeLast()
if body.last == Constants.CR {
body.removeLast()
}
}
return body
}
}
return nil
}
}
| bsd-3-clause | f02601711618d056ffceb1c39961af99 | 35.769841 | 125 | 0.557738 | 4.77137 | false | false | false | false |
planetexpress69/Rangliste-A-Swift | Rang/AppDelegate.swift | 1 | 2524 | //
// AppDelegate.swift
// Rang
//
// Created by Martin Kautz on 19.05.15.
// Copyright (c) 2015 JAKOTA Design Group. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
// ---------------------------------------------------------------------------------------------
func application(
application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UIApplication.sharedApplication().statusBarStyle = .LightContent
let navigationBarAppearace = UINavigationBar.appearance()
navigationBarAppearace.tintColor = .whiteColor()
navigationBarAppearace.barTintColor = Constants.Colors.textColor
navigationBarAppearace.translucent = false
navigationBarAppearace.titleTextAttributes = [
NSFontAttributeName : UIFont.systemFontOfSize(22),
NSForegroundColorAttributeName : UIColor.whiteColor()
]
self.window?.tintColor = Constants.Colors.textColor
self.window?.backgroundColor = UIColor.blueColor()
if let tabBarController = self.window?.rootViewController as? UITabBarController {
tabBarController.tabBar.tintColor = .whiteColor()
tabBarController.tabBar.barTintColor = Constants.Colors.textColor
tabBarController.tabBar.translucent = false
tabBarController.view.backgroundColor = .orangeColor();
if let controllersArray = tabBarController.viewControllers as?
Array<UINavigationController> {
controllersArray[0].tabBarItem.image = .fontAwesomeIconWithName(
.User, size: CGSizeMake(30.0, 30.0), textColor: .blackColor())
controllersArray[1].tabBarItem.image = .fontAwesomeIconWithName(
.Trophy, size: CGSizeMake(30.0, 30.0), textColor: .blackColor())
controllersArray[2].tabBarItem.image = .fontAwesomeIconWithName(
.InfoCircle, size: CGSizeMake(30.0, 30.0), textColor: .blackColor())
}
}
return true
}
// ---------------------------------------------------------------------------------------------
func applicationDidEnterBackground(application: UIApplication) {
NSUserDefaults.standardUserDefaults().synchronize()
}
}
| mit | ee36c38c6c5eb6f5df47f94f3e963b18 | 41.779661 | 100 | 0.59271 | 6.373737 | false | false | false | false |
trumanliu/swift-programming-languague | the swift programing language.playground/Contents.swift | 1 | 5229 | //: Playground - noun: a place where people can play
import UIKit
//变量
var str = "Hello, playground"
var myVariable = 42
myVariable = 50
//常量
let myConstant = 42
let price:Float = 2.01
let label = "my MacBook Air"
let width = 94
//类型转换
let widthLabel = label + String(width)
let apples = 3
let oranges = 5
//在string中进行拼接
let appleSummary = "I have \(apples) apples"
let fruitSummary = "I hava \(apples + oranges) pices of fruit"
//数组
var shoppingList = ["catfish","water","tulips" ,"blue paint"]
shoppingList[1] = "bottle of water"
//字典
var occupations = ["Malcolm" : "captain" ,"Kaylee" : "Mechanic"]
occupations["foo"] = "bar"
occupations
//空数组与字典
let emptyArray = [String] ()
let emptyDictionary = [String:Float]()
//for循环
let individualScores = [75,43,103,87,12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
}else{
teamScore += 1
}
}
teamScore
var optionalString : String? = "Hello"
optionalString == nil
var OptionalName : String? = "truman Liu"
var greeting = "Hello"
if let name = OptionalName {
greeting = "Hello,\(name)"
}
//switch case语句 不需要在子句中写break
let vegetable = "red pepper"
switch vegetable {
case "celery":
let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber","watercress":
let vegetableComment = "That would make a good tea sandwich"
case let x where x.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy \(x)?"
default:
let VegetableComment = "Everything tastes good in soup"
}
//for in 可以遍历字典
let interstingNumbers = [
"Prime" : [2,3,5,7,11,13],
"Fibonacci" : [1,1,2,3,5,8],
"Square":[1,4,9,16,25,36]
]
var largest = 0
var largestKind = ""
for(kind,numbers) in interstingNumbers{
for number in numbers {
if number > largest {
largest = number
largestKind = kind
}
}
}
print(largest)
print(largestKind) //练习题要求输出最大的kind
//while 语句 while在前或后
var n = 2
while n < 100{
n = n * 2
}
print(n)
var m = 2
repeat{
m = m*2
}while m < 100
print(m)
//for循环中使用..<表示范围
var total = 0
for i in 0..<10{
total += 1
}
total
// 0..<10 ➡️ [0-10)
// 0...10 ➡️ [0-10]
var total2 = 0
for i in 0...10{
total2 += 1
}
total2
//函数与闭包
func greet(person: String,day:String) -> String{
return "Hello \(person), today is \(day)."
}
greet(person:"truman",day:"Tuesday")
//greet(day:"DiDi",person:"Monday") error: argument 'person' must precede argument 'day'
//函数的参数名称作为参数的标签,参数名称钱可以自定义参数标签,“_”表示不使用参数标签
func greet2(_ person: String,_ day:String) -> String{
return "Hello \(person), today is \(day)."
}
greet2("Didi","Sunday")
func greet3(who person: String,_ day:String) -> String{
return "Hello \(person), today is \(day)."
}
greet3(who:"Didi","Sunday")
// 使用元组返回多个值
func calculateStatistics(scores:[Int]) -> (
min:Int,max:Int,sum:Int){
var min = scores[0]
var max = scores[0]
var sum = 0
for score in scores{
if score > max {
max = score
}else if score < min{
min = score
}
sum += score
}
return(min,max,sum)
}
let statics = calculateStatistics(scores: [5,3,100,3,9])
statics.0
statics.max
//可变个数参数
func sumOf(numbers:Int...) -> Int {
var sum = 0
for number in numbers{
sum += number
}
return sum
}
sumOf()
sumOf(numbers: 1,2,3)
func sumOfPara(numbers:Int...,kind:String) -> Int {
var sum = 0
for number in numbers{
sum += number
}
print(kind)
return sum
}
sumOfPara(numbers: 1,2,3,4 , kind: "wow")
//由于在调用方法时会显式指明参数名称,所以可变个参数的位置可以不是最后一个
//练习题:均值
func meanOf(numbers:Int...) -> Int {
var sum = 0
for number in numbers{
sum += number
}
return sum/numbers.count
}
meanOf(numbers: 1,2,3,4,5,6,7)
//函数可以嵌套
func returnFifteen() -> Int {
var y = 10
func minus(){
y = 25 - y
}
minus()
return y
}
returnFifteen()
//函数时一级类型,可以作为返回值
func makeIncrementer() -> ( (Int) -> Int){
func addOne(number:Int) -> Int{
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(1)
//函数可以当作参数传入另一个函数
func hasAnyMatches(list:[Int],condition:(Int) -> Bool) -> Bool{
for item in list{
if condition(item){
return true
}
}
return false
}
func lessThanTen(number:Int) -> Bool{
return number < 10
}
var numbers = [72,39,27,11]
hasAnyMatches(list: numbers, condition: lessThanTen)
//使用{} 来创建一个匿名闭包。使用in将参数根返回值类型与声明与闭包函数体进行分离
numbers.map({
(number : Int) -> Int in
let result = 3 * number
return result
})
let mappedNumbers = numbers.map({number in 3 * number})
print(mappedNumbers)
| apache-2.0 | 345aac6ee512ab7cc0b051083ac2b7a4 | 17.948 | 88 | 0.617902 | 3.066019 | false | false | false | false |
wltrup/Swift-WTUniquePrimitiveType | Example/Tests/UniqueStringTypeTests.swift | 1 | 2379 | //
// UniqueStringTypeTests.swift
// WTUniquePrimitiveTypes
//
// Created by Wagner Truppel on 31/05/2017.
// Copyright © 2017 wtruppel. All rights reserved.
//
// swiftlint:disable vertical_whitespace
// swiftlint:disable trailing_newline
// swiftlint:disable file_length
// swiftlint:disable type_body_length
import XCTest
import WTUniquePrimitiveType
class UniqueStringTypeTests: XCTestCase {
func testThatItCreatesTheCorrectInstance() {
let value: String = "John Doe"
let stringQ = StringQ(value)
XCTAssertEqual(stringQ.value, value)
}
func testExpressibleByStringLiteral() {
let stringQ = StringQ(stringLiteral: "John Doe")
XCTAssertEqual(stringQ.value, "John Doe")
}
func testExpressibleByExtendedGraphemeClusterLiteral() {
let stringQ = StringQ(extendedGraphemeClusterLiteral: "John Doe")
XCTAssertEqual(stringQ.value, "John Doe")
}
func testExpressibleByUnicodeScalarLiteral() {
let stringQ = StringQ(unicodeScalarLiteral: "John Doe")
XCTAssertEqual(stringQ.value, "John Doe")
}
func testDescription() {
let value: String = "John Doe"
let stringQ = StringQ(value)
XCTAssertEqual(stringQ.description, value.description)
}
func testEquatable() {
let value1: String = "John Doe"
let value2 = value1
let stringQ1 = StringQ(value1)
let stringQ2 = StringQ(value2)
XCTAssertTrue(stringQ1 == stringQ2)
}
func testNotEquatable() {
let value1: String = "Jane Doe"
let value2: String = "John Doe"
let stringQ1 = StringQ(value1)
let stringQ2 = StringQ(value2)
XCTAssertFalse(stringQ1 == stringQ2)
}
func testComparable() {
let value1: String = "Jane Doe"
let value2: String = "John Doe"
let stringQ1 = StringQ(value1)
let stringQ2 = StringQ(value2)
XCTAssertTrue(stringQ1 < stringQ2)
}
func testNotComparable() {
let value1: String = "John Doe"
let value2 = value1
let stringQ1 = StringQ(value1)
let stringQ2 = StringQ(value2)
XCTAssertFalse(stringQ1 < stringQ2)
}
func testHashable() {
let value: String = "John Doe"
let stringQ = StringQ(value)
XCTAssertEqual(stringQ.hashValue, value.hashValue)
}
}
| mit | 3417a4f0066618aa647bda87299aada4 | 26.651163 | 73 | 0.650967 | 4.128472 | false | true | false | false |
yonaskolb/SwagGen | Templates/Swift/Sources/API.swift | 1 | 2148 | {% include "Includes/Header.stencil" %}
import Foundation
{% if info.description %}
/** {{ info.description }} */
{% endif %}
public struct {{ options.name }} {
/// Whether to discard any errors when decoding optional properties
public static var safeOptionalDecoding = {% if options.safeOptionalDecoding %}true{% else %}false{% endif %}
/// Whether to remove invalid elements instead of throwing when decoding arrays
public static var safeArrayDecoding = {% if options.safeArrayDecoding %}true{% else %}false{% endif %}
/// Used to encode Dates when uses as string params
public static var dateEncodingFormatter = DateFormatter(formatString: "yyyy-MM-dd'T'HH:mm:ssZZZZZ",
locale: Locale(identifier: "en_US_POSIX"),
calendar: Calendar(identifier: .gregorian))
{% if info.version %}
public static let version = "{{ info.version }}"
{% endif %}
{% if tags.count >= 0 %}
{% for tag in tags %}
public enum {{ options.tagPrefix }}{{ tag|upperCamelCase }}{{ options.tagSuffix }} {}
{% endfor %}
{% endif %}
{% if servers %}
public enum Server {
{% for server in servers %}
{% if server.description %}
/** {{ server.description }} **/
{% endif %}
{% if server.variables %}
public static func {{ server.name }}({% for variable in server.variables %}{{ variable.name }}: String = "{{ variable.defaultValue }}"{% ifnot forloop.last %}, {% endif %}{% endfor %}) -> String {
var url = "{{ server.url }}"
{% for variable in server.variables %}
url = url.replacingOccurrences(of: {{'"{'}}{{variable.name}}{{'}"'}}, with: {{variable.name}})
{% endfor %}
return url
}
{% else %}
public static let {{ server.name }} = "{{ server.url }}"
{% endif %}
{% endfor %}
}
{% else %}
// No servers defined in swagger. Documentation for adding them: https://swagger.io/specification/#schema
{% endif %}
}
| mit | 2d8ac8c2bae1653a4dd7cee227f7d63b | 38.054545 | 204 | 0.556331 | 4.762749 | false | false | false | false |
penniooi/TestKichen | TestKitchen/TestKitchen/classes/common/UIButton+Util.swift | 1 | 1079 | //
// BaseViewController.swift
// TestKitchen
//
// Created by aloha on 16/8/15.
// Copyright © 2016年 胡颉禹. All rights reserved.
//
import UIKit
extension UIButton {
class func createBtn(title: String?,bgImageName: String?,selectBgImageName: String?,target:AnyObject?,action: Selector) -> UIButton {
let btn = UIButton(type: .Custom)
if let btnTitle = title {
btn.setTitle(btnTitle, forState: .Normal)
btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
}
if let btnBgImageName = bgImageName {
btn.setBackgroundImage(UIImage(named: btnBgImageName), forState: .Normal)
}
if let btnSelectBgImageName = selectBgImageName {
btn.setBackgroundImage(UIImage(named: btnSelectBgImageName), forState: .Selected)
}
if let btnTarget = target {
btn.addTarget(btnTarget, action: action, forControlEvents: .TouchUpInside)
}
return btn
}
}
| mit | 774a953fd13c0f6edbb200805b438819 | 24.47619 | 137 | 0.596262 | 4.692982 | false | false | false | false |
Zewo/Epoch | Sources/Media/Media/MediaDecoder/MediaUnkeyedDecodingContainer.swift | 2 | 13577 | struct MediaUnkeyedDecodingContainer<Map : DecodingMedia> : UnkeyedDecodingContainer {
let decoder: MediaDecoder<Map>
let map: DecodingMedia
var codingPath: [CodingKey]
var currentIndex: Int
init(referencing decoder: MediaDecoder<Map>, wrapping map: DecodingMedia) {
self.decoder = decoder
self.map = map
self.codingPath = decoder.codingPath
self.currentIndex = 0
}
var count: Int? {
return map.keyCount()
}
var isAtEnd: Bool {
guard let count = map.keyCount() else {
return true
}
return currentIndex >= count
}
func throwIfAtEnd() throws {
// TODO: throw a relevant error
}
mutating func decodeNil() throws -> Bool {
try throwIfAtEnd()
return decoder.with(pushedKey: currentIndex) {
let decoded = map.decodeNil()
currentIndex += 1
return decoded
}
}
mutating func decode(_ type: Bool.Type) throws -> Bool {
try throwIfAtEnd()
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decode(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decode(_ type: Int.Type) throws -> Int {
try throwIfAtEnd()
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decode(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decode(_ type: Int8.Type) throws -> Int8 {
try throwIfAtEnd()
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decode(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decode(_ type: Int16.Type) throws -> Int16 {
try throwIfAtEnd()
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decode(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decode(_ type: Int32.Type) throws -> Int32 {
try throwIfAtEnd()
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decode(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decode(_ type: Int64.Type) throws -> Int64 {
try throwIfAtEnd()
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decode(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decode(_ type: UInt.Type) throws -> UInt {
try throwIfAtEnd()
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decode(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decode(_ type: UInt8.Type) throws -> UInt8 {
try throwIfAtEnd()
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decode(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decode(_ type: UInt16.Type) throws -> UInt16 {
try throwIfAtEnd()
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decode(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decode(_ type: UInt32.Type) throws -> UInt32 {
try throwIfAtEnd()
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decode(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decode(_ type: UInt64.Type) throws -> UInt64 {
try throwIfAtEnd()
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decode(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decode(_ type: Float.Type) throws -> Float {
try throwIfAtEnd()
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decode(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decode(_ type: Double.Type) throws -> Double {
try throwIfAtEnd()
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decode(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decode(_ type: String.Type) throws -> String {
try throwIfAtEnd()
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decode(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
try throwIfAtEnd()
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decode(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decodeIfPresent(_ type: Bool.Type) throws -> Bool? {
guard !isAtEnd else { return nil }
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decodeIfPresent(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decodeIfPresent(_ type: Int.Type) throws -> Int? {
guard !isAtEnd else { return nil }
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decodeIfPresent(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decodeIfPresent(_ type: Int8.Type) throws -> Int8? {
guard !isAtEnd else { return nil }
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decodeIfPresent(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decodeIfPresent(_ type: Int16.Type) throws -> Int16? {
guard !isAtEnd else { return nil }
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decodeIfPresent(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decodeIfPresent(_ type: Int32.Type) throws -> Int32? {
guard !isAtEnd else { return nil }
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decodeIfPresent(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decodeIfPresent(_ type: Int64.Type) throws -> Int64? {
guard !isAtEnd else { return nil }
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decodeIfPresent(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decodeIfPresent(_ type: UInt.Type) throws -> UInt? {
guard !isAtEnd else { return nil }
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decodeIfPresent(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decodeIfPresent(_ type: UInt8.Type) throws -> UInt8? {
guard !isAtEnd else { return nil }
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decodeIfPresent(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decodeIfPresent(_ type: UInt16.Type) throws -> UInt16? {
guard !isAtEnd else { return nil }
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decodeIfPresent(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decodeIfPresent(_ type: UInt32.Type) throws -> UInt32? {
guard !isAtEnd else { return nil }
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decodeIfPresent(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decodeIfPresent(_ type: UInt64.Type) throws -> UInt64? {
guard !isAtEnd else { return nil }
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decodeIfPresent(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decodeIfPresent(_ type: Float.Type) throws -> Float? {
guard !isAtEnd else { return nil }
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decodeIfPresent(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decodeIfPresent(_ type: Double.Type) throws -> Double? {
guard !isAtEnd else { return nil }
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decodeIfPresent(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decodeIfPresent(_ type: String.Type) throws -> String? {
guard !isAtEnd else { return nil }
return try decoder.with(pushedKey: currentIndex) {
let decoded = try map.decodeIfPresent(type, forKey: currentIndex)
currentIndex += 1
return decoded
}
}
mutating func decodeIfPresent<T : Decodable>(_ type: T.Type) throws -> T? {
guard !isAtEnd else { return nil }
return try decoder.with(pushedKey: currentIndex) {
guard let value = try map.decodeIfPresent(Map.self, forKey: currentIndex) else {
return nil
}
decoder.stack.push(value)
let decoded: T = try T(from: decoder)
decoder.stack.pop()
currentIndex += 1
return decoded
}
}
mutating func nestedContainer<NestedKey>(
keyedBy type: NestedKey.Type
) throws -> KeyedDecodingContainer<NestedKey> {
return try decoder.with(pushedKey: currentIndex) {
try self.assertNotAtEnd(
forType: KeyedDecodingContainer<NestedKey>.self,
message: "Cannot get nested keyed container -- unkeyed container is at end."
)
let container = MediaKeyedDecodingContainer<NestedKey, Map>(
referencing: decoder,
wrapping: try map.keyedContainer(forKey: currentIndex)
)
currentIndex += 1
return KeyedDecodingContainer(container)
}
}
mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
return try decoder.with(pushedKey: currentIndex) {
try self.assertNotAtEnd(
forType: UnkeyedDecodingContainer.self,
message: "Cannot get nested unkeyed container -- unkeyed container is at end."
)
let container = MediaUnkeyedDecodingContainer(
referencing: decoder,
wrapping: try map.unkeyedContainer(forKey: currentIndex)
)
currentIndex += 1
return container
}
}
mutating func superDecoder() throws -> Decoder {
return try decoder.with(pushedKey: currentIndex) {
try self.assertNotAtEnd(
forType: Decoder.self,
message: "Cannot get superDecoder() -- unkeyed container is at end."
)
guard let value = try map.decodeIfPresent(Map.self, forKey: currentIndex) else {
let context = DecodingError.Context(
codingPath: codingPath,
debugDescription: "Cannot get superDecoder() -- value not found for key \(currentIndex)."
)
throw DecodingError.keyNotFound(currentIndex, context)
}
currentIndex += 1
return MediaDecoder<Map>(
referencing: value,
at: decoder.codingPath,
userInfo: decoder.userInfo
)
}
}
func assertNotAtEnd(forType type: Any.Type, message: String) throws {
guard !isAtEnd else {
let context = DecodingError.Context(
codingPath: codingPath,
debugDescription: message
)
throw DecodingError.valueNotFound(type, context)
}
}
}
| mit | a8d950d1fb068e4927c2d51e51e7b405 | 31.32619 | 109 | 0.558592 | 5.37916 | false | false | false | false |
eoger/firefox-ios | Client/Frontend/Widgets/HistoryBackButton.swift | 12 | 2492 | /* 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 SnapKit
import Shared
private struct HistoryBackButtonUX {
static let HistoryHistoryBackButtonHeaderChevronInset: CGFloat = 10
static let HistoryHistoryBackButtonHeaderChevronSize: CGFloat = 20
static let HistoryHistoryBackButtonHeaderChevronLineWidth: CGFloat = 3.0
}
class HistoryBackButton: UIButton, Themeable {
lazy var title: UILabel = {
let label = UILabel()
label.text = Strings.HistoryBackButtonTitle
return label
}()
lazy var chevron: ChevronView = {
let chevron = ChevronView(direction: .left)
chevron.lineWidth = HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronLineWidth
return chevron
}()
let topBorder = UIView()
let bottomBorder = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
isUserInteractionEnabled = true
addSubview(topBorder)
addSubview(chevron)
addSubview(title)
chevron.snp.makeConstraints { make in
make.leading.equalTo(self.safeArea.leading).offset(HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronInset)
make.centerY.equalTo(self)
make.size.equalTo(HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronSize)
}
title.snp.makeConstraints { make in
make.leading.equalTo(chevron.snp.trailing).offset(HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronInset)
make.trailing.greaterThanOrEqualTo(self).offset(-HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronInset)
make.centerY.equalTo(self)
}
topBorder.snp.makeConstraints { make in
make.leading.trailing.equalTo(self)
make.top.equalTo(self).offset(-0.5)
make.height.equalTo(0.5)
}
applyTheme()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func applyTheme() {
title.textColor = UIColor.theme.general.highlightBlue
chevron.tintColor = UIColor.theme.general.highlightBlue
backgroundColor = UIColor.theme.tableView.headerBackground
[topBorder, bottomBorder].forEach { $0.backgroundColor = UIColor.theme.homePanel.siteTableHeaderBorder }
}
}
| mpl-2.0 | d2695b22750432eb2148a91611a3cb00 | 35.115942 | 126 | 0.700241 | 5.085714 | false | false | false | false |
Ricky-Choi/AppUIKit | AppUIKit/Navigation/AUINavigationItem.swift | 1 | 3514 | //
// AUINavigationItem.swift
// AppUIKit
//
// Created by ricky on 2016. 12. 5..
// Copyright © 2016년 appcid. All rights reserved.
//
import Cocoa
open class AUINavigationItem: NSObject {
// Initializing an Item
public init(title: String) {
self.title = title
super.init()
}
// Getting and Setting Properties
public var title: String? {
didSet {
titleLabel.stringValue = title ?? ""
}
}
public var prompt: String?
public var backBarButtonItem: AUIBarButtonItem?
public var hidesBackButton: Bool {
get {
return _hidesBackButton
}
set {
setHidesBackButton(newValue, animated: false)
}
}
public func setHidesBackButton(_ hidesBackButton: Bool, animated: Bool) {
_hidesBackButton = hidesBackButton
}
public var leftItemsSupplementBackButton: Bool = false
// Customizing Views
private var _titleView: NSView?
public var titleView: NSView? {
get {
if _titleView != nil {
return _titleView
}
if title != nil {
titleLabel.stringValue = title!
return titleLabel
}
return nil
}
set {
_titleView = newValue
}
}
lazy private var titleLabel: AUILabel = {
let label = AUILabel()
label.font = NSFont.systemFont(ofSize: 16, weight: NSFont.Weight.semibold)
return label
}()
public var leftBarButtonItems: [AUIBarButtonItem]? {
get {
return _leftBarButtonItems
}
set {
setLeftBarButtonItems(newValue, animated: false)
}
}
public var leftBarButtonItem: AUIBarButtonItem? {
get {
return leftBarButtonItems?.first
}
set {
if newValue != nil {
leftBarButtonItems = [newValue!]
} else {
leftBarButtonItems = nil
}
}
}
public var rightBarButtonItems: [AUIBarButtonItem]? {
get {
return _rightBarButtonItems
}
set {
setRightBarButtonItems(newValue, animated: false)
}
}
public var rightBarButtonItem: AUIBarButtonItem? {
get {
return rightBarButtonItems?.first
}
set {
if newValue != nil {
rightBarButtonItems = [newValue!]
} else {
rightBarButtonItems = nil
}
}
}
public func setLeftBarButtonItems(_ items: [AUIBarButtonItem]?, animated: Bool) {
_leftBarButtonItems = items
}
public func setLeftBarButton(_ item: AUIBarButtonItem?, animated: Bool) {
setLeftBarButtonItems((item != nil) ? [item!] : nil, animated: animated)
}
public func setRightBarButtonItems(_ items: [AUIBarButtonItem]?, animated: Bool) {
_rightBarButtonItems = items
}
public func setRightBarButton(_ item: AUIBarButtonItem?, animated: Bool) {
setRightBarButtonItems((item != nil) ? [item!] : nil, animated: animated)
}
// private
internal weak var navigationBar: AUINavigationBar?
private var _hidesBackButton: Bool = false
private var _leftBarButtonItems: [AUIBarButtonItem]?
private var _rightBarButtonItems: [AUIBarButtonItem]?
}
| mit | 58b66910de2b22b0db96f43287b43f59 | 24.816176 | 86 | 0.556537 | 5.368502 | false | false | false | false |
nicksnyder/iOS-UIWebView-vs-UITableView | Tab/Tab/TableViewController.swift | 1 | 3455 | //
// Created by Nick Snyder on 4/28/15.
// Copyright (c) 2015 Example. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
private let cellId = "TableViewCell"
convenience override init() {
self.init(nibName: nil, bundle: nil)
self.tabBarItem = UITabBarItem(title: "UITableView", image: nil, selectedImage: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = 80
tableView.registerNib(UINib(nibName: cellId, bundle: nil), forCellReuseIdentifier: cellId)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
var urls: [AnyObject] = []
for var i=0; i<100; i++ {
urls.append(self.urlForIndexPath(NSIndexPath(forItem: i, inSection: 0))!)
urls.append(self.urlForIndexPath(NSIndexPath(forItem: i, inSection: 1))!)
urls.append(self.urlForIndexPath(NSIndexPath(forItem: i, inSection: 2))!)
urls.append(self.urlForIndexPath(NSIndexPath(forItem: i, inSection: 3))!)
urls.append(self.urlForIndexPath(NSIndexPath(forItem: i, inSection: 4))!)
urls.append(self.urlForIndexPath(NSIndexPath(forItem: i, inSection: 5))!)
urls.append(self.urlForIndexPath(NSIndexPath(forItem: i, inSection: 6))!)
urls.append(self.urlForIndexPath(NSIndexPath(forItem: i, inSection: 7))!)
}
// BUG: Set maxConcurrentDownloads to 1024 to induce deadlock in SDWebImage
SDWebImagePrefetcher.sharedImagePrefetcher().maxConcurrentDownloads = 32
SDWebImagePrefetcher.sharedImagePrefetcher().prefetchURLs(urls)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
AppDelegate.sharedInstance.clearImageCache()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
view = nil
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellId, forIndexPath: indexPath) as TableViewCell
cell.titleLabel.text = "Here are 8 random imgs"
setRandomImage(cell.imageView1, indexPath: NSIndexPath(forItem: indexPath.item, inSection: 0))
setRandomImage(cell.imageView2, indexPath: NSIndexPath(forItem: indexPath.item, inSection: 1))
setRandomImage(cell.imageView3, indexPath: NSIndexPath(forItem: indexPath.item, inSection: 2))
setRandomImage(cell.imageView4, indexPath: NSIndexPath(forItem: indexPath.item, inSection: 3))
setRandomImage(cell.imageView5, indexPath: NSIndexPath(forItem: indexPath.item, inSection: 4))
setRandomImage(cell.imageView6, indexPath: NSIndexPath(forItem: indexPath.item, inSection: 5))
setRandomImage(cell.imageView7, indexPath: NSIndexPath(forItem: indexPath.item, inSection: 6))
setRandomImage(cell.imageView8, indexPath: NSIndexPath(forItem: indexPath.item, inSection: 7))
return cell
}
private func setRandomImage(imageView: UIImageView, indexPath: NSIndexPath) {
imageView.sd_setImageWithURL(self.urlForIndexPath(indexPath), placeholderImage: nil, options: SDWebImageOptions.HighPriority)
}
private func urlForIndexPath(indexPath: NSIndexPath) -> NSURL? {
return NSURL(string: "http://lorempixel.com/100/100/?item=\(indexPath.item)§ion=\(indexPath.section)")
}
}
| mit | 33fbc4d13e82be7546e9503000ef8d4c | 44.460526 | 129 | 0.745297 | 4.423816 | false | false | false | false |
storehouse/Advance | Samples/SampleApp-iOS/Sources/ActivityView.swift | 1 | 9515 | import UIKit
import Advance
public final class ActivityView: UIView {
fileprivate static let points: [CGPoint] = {
var points: [CGPoint] = Array(repeating: CGPoint.zero, count: 10)
points[0] = CGPoint(x: 0.5, y: 0.0)
points[1] = CGPoint(x: 0.20928571428571, y: 0.16642857142857)
points[2] = CGPoint(x: 0.79071428571429, y: 0.16642857142857)
points[3] = CGPoint(x: 0.5, y: 0.3325)
points[4] = CGPoint(x: 0.20928571428571, y: 0.49964285714286)
points[5] = CGPoint(x: 0.79071428571429, y: 0.49964285714286)
points[6] = CGPoint(x: 0.5, y: 0.66607142857143)
points[7] = CGPoint(x: 0.20928571428571, y: 0.83357142857143)
points[8] = CGPoint(x: 0.79071428571429, y: 0.83357142857143)
points[9] = CGPoint(x: 0.5, y: 1.0)
return points
}()
fileprivate let segments: [ActivitySegment] = {
var segments: [ActivitySegment] = []
segments.append(ActivitySegment(firstPoint: points[1], secondPoint: points[0]))
segments.append(ActivitySegment(firstPoint: points[0], secondPoint: points[2]))
segments.append(ActivitySegment(firstPoint: points[1], secondPoint: points[3]))
segments.append(ActivitySegment(firstPoint: points[2], secondPoint: points[3]))
segments.append(ActivitySegment(firstPoint: points[1], secondPoint: points[4]))
segments.append(ActivitySegment(firstPoint: points[4], secondPoint: points[3]))
segments.append(ActivitySegment(firstPoint: points[3], secondPoint: points[5]))
segments.append(ActivitySegment(firstPoint: points[4], secondPoint: points[6]))
segments.append(ActivitySegment(firstPoint: points[6], secondPoint: points[5]))
segments.append(ActivitySegment(firstPoint: points[5], secondPoint: points[8]))
segments.append(ActivitySegment(firstPoint: points[6], secondPoint: points[7]))
segments.append(ActivitySegment(firstPoint: points[6], secondPoint: points[8]))
segments.append(ActivitySegment(firstPoint: points[7], secondPoint: points[9]))
segments.append(ActivitySegment(firstPoint: points[8], secondPoint: points[9]))
return segments
}()
fileprivate let visibilitySprings: [Spring<CGFloat>] = {
return (0...13).map {_ in
let s = Spring(initialValue: CGFloat(1.0))
s.threshold = 0.001
s.tension = 220.0 + Double(arc4random() % 200);
s.damping = 30.0 + Double(arc4random() % 10);
return s
}
}()
fileprivate var segmentLayers: [CAShapeLayer] = {
return (0...13).map {_ in
let sl = CAShapeLayer()
var actions: [String: AnyObject] = [:]
actions["position"] = NSNull()
actions["bounds"] = NSNull()
actions["lineWidth"] = NSNull()
actions["strokeColor"] = NSNull()
actions["path"] = NSNull()
return sl
}
}()
fileprivate var strokeColor: UIColor {
return color.withAlphaComponent(0.6)
}
fileprivate var flashStrokeColor: UIColor {
return color
}
fileprivate let lineWidth = CGFloat(1.0)
fileprivate let flashLineWidth = CGFloat(2.0)
fileprivate var flashTimer: Timer? = nil
public var color = UIColor(red: 0.0, green: 196.0/255.0, blue: 1.0, alpha: 1.0) {
didSet {
for sl in segmentLayers {
sl.strokeColor = strokeColor.cgColor
}
}
}
public var assembledAmount: CGFloat = 1.0 {
didSet {
updateSegmentVisibility(true)
}
}
public var flashing: Bool = false {
didSet {
guard flashing != oldValue else { return }
if flashing {
let t = Timer(timeInterval: 1.0, target: self, selector: #selector(flash), userInfo: nil, repeats: true)
RunLoop.main.add(t, forMode: RunLoop.Mode.common)
flashTimer = t
flash()
} else {
flashTimer?.invalidate()
flashTimer = nil
}
}
}
required override public init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
layer.allowsGroupOpacity = false
for vs in visibilitySprings {
vs.onChange = { [weak self] (vis) in
self?.setNeedsLayout()
}
}
for sl in segmentLayers {
sl.strokeColor = strokeColor.cgColor
sl.lineWidth = lineWidth
layer.addSublayer(sl)
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func layoutSubviews() {
super.layoutSubviews()
for i in 0..<segments.count {
let s = segments[i]
let sl = segmentLayers[i]
let visibility = visibilitySprings[i].value
sl.frame = bounds
sl.path = s.path(bounds.size, visibility: visibility).cgPath
sl.opacity = Float(visibility)
}
}
override public func sizeThatFits(_ size: CGSize) -> CGSize {
return CGSize(width: 40.0, height: 40.0)
}
public func resetAssembledAmount(_ assembledAmount: CGFloat) {
self.assembledAmount = assembledAmount
updateSegmentVisibility(false)
}
func updateSegmentVisibility(_ animated: Bool) {
for i in 0..<segments.count {
let positionInArray = CGFloat(i) / CGFloat(segments.count-1)
let minVis = (1.0-positionInArray) * 0.4
let maxVis = minVis + 0.6
var mappedVis = (assembledAmount - minVis) / (maxVis - minVis)
mappedVis = min(mappedVis, 1.0)
mappedVis = max(mappedVis, 0.0)
mappedVis = quadEaseInOut(mappedVis)
if animated {
visibilitySprings[i].target = mappedVis
} else {
visibilitySprings[i].reset(to: mappedVis)
}
}
}
@objc fileprivate dynamic func flash() {
for i in 0..<segmentLayers.count {
let t = DispatchTime.now() + Double(Int64(Double(NSEC_PER_SEC) * 0.04 * Double(i))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: t, execute: {
self.flashSegment(i)
})
}
}
fileprivate func flashSegment(_ index: Int) {
let sl = segmentLayers[index]
CATransaction.begin()
let c = CAKeyframeAnimation(keyPath: "strokeColor")
c.values = [strokeColor.cgColor, flashStrokeColor.cgColor, strokeColor.cgColor]
c.keyTimes = [0.0, 0.3, 1.0]
c.calculationMode = CAAnimationCalculationMode.cubic
c.duration = 0.5
sl.add(c, forKey: "flashStrokeColor")
let s = CAKeyframeAnimation(keyPath: "lineWidth")
s.values = [lineWidth, flashLineWidth, lineWidth]
s.keyTimes = [0.0, 0.3, 1.0]
s.calculationMode = CAAnimationCalculationMode.cubic
s.duration = 0.5
sl.add(s, forKey: "flashLineWidth")
CATransaction.commit()
}
}
private func quadEaseInOut(_ t: CGFloat) -> CGFloat {
var result = t / 0.5
if (result < 1.0) {
return 0.5*result*result
} else {
result -= 1.0
return -0.5 * (result * (result - 2.0) - 1.0)
}
}
private struct ActivitySegment {
let firstPoint: CGPoint
let secondPoint: CGPoint
let initialPosition: CGPoint = {
var p = CGPoint.zero
p.x = (CGFloat(arc4random() % 100) / 100.0)
p.y = (CGFloat(arc4random() % 100) / 100.0)
p.x = ((p.x - 0.5) * 2.0) + 0.5
p.y -= 0.6;
return p
}()
let initialRotation = ((CGFloat(arc4random() % 100) / 100.0) * CGFloat.pi)
func path(_ size: CGSize, visibility: CGFloat) -> UIBezierPath {
var p1 = initialPosition
var p2 = initialPosition
p1 = interpolate(from: p1, to: firstPoint, alpha: visibility)
p2 = interpolate(from: p2, to: secondPoint, alpha: visibility)
let rotation = initialRotation * (1.0 - visibility)
let midX = p1.x + (p2.x - p1.x) * 0.5
let midY = p1.y + (p2.y - p1.y) * 0.5
p1.x -= midX
p2.x -= midX
p1.y -= midY
p2.y -= midY
p1 = p1.applying(CGAffineTransform(rotationAngle: rotation))
p2 = p2.applying(CGAffineTransform(rotationAngle: rotation))
p1.x += midX
p2.x += midX
p1.y += midY
p2.y += midY
// we store layout info in relative coords
p1.x *= size.width
p1.y *= size.height
p2.x *= size.width
p2.y *= size.height
let p = UIBezierPath()
p.move(to: p1)
p.addLine(to: p2)
return p
}
init(firstPoint: CGPoint, secondPoint: CGPoint) {
self.firstPoint = firstPoint
self.secondPoint = secondPoint
}
}
fileprivate func interpolate(from fromPoint: CGPoint, to toPoint: CGPoint, alpha: CGFloat) -> CGPoint {
return CGPoint(
x: fromPoint.x + ((toPoint.x - fromPoint.x) * alpha),
y: fromPoint.y + ((toPoint.y - fromPoint.y) * alpha))
}
| bsd-2-clause | 52281bacc2604bd5a4b7eeeb9d1bacd2 | 33.226619 | 120 | 0.569101 | 4.035199 | false | false | false | false |
idapgroup/IDPDesign | Tests/iOS/iOSTests/Specs/Lens+UINavigationItemSpec.swift | 1 | 6310 | //
// Lens+UINavigationItemSpec.swift
// iOSTests
//
// Created by Oleksa 'trimm' Korin on 9/2/17.
// Copyright © 2017 Oleksa 'trimm' Korin. All rights reserved.
//
import Quick
import Nimble
import UIKit
@testable import IDPDesign
extension UINavigationItem: UINavigationItemProtocol { }
class LensUINavigationItemSpec: QuickSpec {
override func spec() {
describe("Lens+UINavigationItemSpec") {
context("title") {
it("should get and set") {
let lens: Lens<UINavigationItem, String?> = title()
let object = UINavigationItem()
let value: String = "mama"
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.title).to(equal(value))
}
}
context("titleView") {
it("should get and set") {
let lens: Lens<UINavigationItem, UIView?> = titleView()
let object = UINavigationItem()
let value: UIView = UIView()
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.titleView).to(equal(value))
}
}
context("prompt") {
it("should get and set") {
let lens: Lens<UINavigationItem, String?> = prompt()
let object = UINavigationItem()
let value: String = "mama"
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.prompt).to(equal(value))
}
}
context("backBarButtonItem") {
it("should get and set") {
let lens: Lens<UINavigationItem, UIBarButtonItem?> = backBarButtonItem()
let object = UINavigationItem()
let value: UIBarButtonItem = UIBarButtonItem()
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.backBarButtonItem).to(equal(value))
}
}
context("hidesBackButton") {
it("should get and set") {
let lens: Lens<UINavigationItem, Bool> = hidesBackButton()
let object = UINavigationItem()
let value: Bool = !object.hidesBackButton
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.hidesBackButton).to(equal(value))
}
}
context("leftBarButtonItems") {
it("should get and set") {
let lens: Lens<UINavigationItem, [UIBarButtonItem]?> = leftBarButtonItems()
let object = UINavigationItem()
let value: [UIBarButtonItem] = [UIBarButtonItem(barButtonSystemItem: .cancel, target: nil, action: nil)]
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.leftBarButtonItems).to(equal(value))
}
}
context("rightBarButtonItems") {
it("should get and set") {
let lens: Lens<UINavigationItem, [UIBarButtonItem]?> = rightBarButtonItems()
let object = UINavigationItem()
let value: [UIBarButtonItem] = [UIBarButtonItem(barButtonSystemItem: .cancel, target: nil, action: nil)]
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.rightBarButtonItems).to(equal(value))
}
}
context("leftItemsSupplementBackButton") {
it("should get and set") {
let lens: Lens<UINavigationItem, Bool> = leftItemsSupplementBackButton()
let object = UINavigationItem()
let value: Bool = !object.leftItemsSupplementBackButton
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.leftItemsSupplementBackButton).to(equal(value))
}
}
context("leftBarButtonItem") {
it("should get and set") {
let lens: Lens<UINavigationItem, UIBarButtonItem?> = leftBarButtonItem()
let object = UINavigationItem()
let value: UIBarButtonItem = UIBarButtonItem()
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.leftBarButtonItem).to(equal(value))
}
}
context("rightBarButtonItem") {
it("should get and set") {
let lens: Lens<UINavigationItem, UIBarButtonItem?> = rightBarButtonItem()
let object = UINavigationItem()
let value: UIBarButtonItem = UIBarButtonItem()
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.rightBarButtonItem).to(equal(value))
}
}
}
}
}
| bsd-3-clause | e99a8d65e47863d4476112ad407c45a0 | 35.468208 | 124 | 0.52116 | 5.868837 | false | false | false | false |
davidbjames/Unilib | Unilib/Sources/Strings.swift | 1 | 3262 | //
// Strings.swift
// Unilib
//
// Created by David James on 9/28/16.
// Copyright © 2016-2021 David B James. All rights reserved.
//
import Foundation
public extension String {
/// Return nil if string is empty
var value:String? {
return isEmpty ? nil : self
}
/// Return prefix of dot separated string
var dotPrefix:String? {
return components(separatedBy: ".").first
}
/// Return prefix segments of dot separate string
func dotPrefix(segments:Int = 1) -> String? {
return components(separatedBy: ".")
.prefix(segments).nonEmpty?
.joined(separator: ".")
}
/// Return suffix of dot separate string
var dotSuffix:String? {
return components(separatedBy: ".").last
}
/// Return suffix segments of dot separate string
func dotSuffix(segments:Int = 1) -> String? {
return components(separatedBy: ".")
.suffix(segments).nonEmpty?
.joined(separator: ".")
}
/// Does the string have length (!empty)
var hasText:Bool {
// This method name uses the word "text" for callsite
// clarity. If using strings for things other than
// text, make separate methods with appropriate names.
return !isEmpty
}
// TODO ✅ Other similar trim() functions
// trim(to:), trim(_:) (trims string from both sides)
// leftTrim/rightTrim, etc
func trim(from:String) -> String {
if let lowerBound = self.range(of: from)?.lowerBound {
return String(self[..<lowerBound])
} else {
return self
}
}
/// Get the index of a character in a string.
func indexDistance(of character: Character) -> Int? {
guard let index = firstIndex(of: character) else { return nil }
return distance(from: startIndex, to: index)
}
/// The "incorrect" way of getting a character
/// out of a string by integer index.
/// The Swift team's reasoning for not supporting
/// this relates to localizable content and
/// the diversity of how strings can be iterated.
/// However, there are strict cases where it makes
/// sense to have a quick and easy accessor by Int
/// so here it is.
/// e.g. Quadrant columnLetters "abcd..."
func character(at _index:Int) -> Character? {
let i = index(startIndex, offsetBy:_index)
return self[safe:i]
}
}
public extension Collection where Element == String {
/// Return all strings with dot prefix segments
var dotPrefixAll:String {
return "[" + compactMap { $0.dotPrefix }.joined(separator:",") + "]"
}
/// Return all strings with dot prefix segments
func dotPrefixAll(segments:Int = 1) -> String {
return "[" + compactMap { $0.dotPrefix(segments:segments) }.joined(separator:",") + "]"
}
/// Return all strings with dot suffix segments
var dotSuffixAll:String {
return "[" + compactMap { $0.dotSuffix }.joined(separator:",") + "]"
}
/// Return all strings with dot suffix segments
func dotSuffixAll(segments:Int = 1) -> String {
return "[" + compactMap { $0.dotSuffix(segments:segments) }.joined(separator:",") + "]"
}
}
| mit | 7f0fe64c2725d945b2d6d30ebcb50da5 | 32.597938 | 95 | 0.61031 | 4.392183 | false | false | false | false |
dmitrykurochka/CLTokenInputView-Swift | CLTokenInputView-Swift/Classes/CLTokenInputView.swift | 1 | 13528 | //
// CLTokenInputView.swift
// CLTokenInputView
//
// Created by Dmitry Kurochka on 23.08.17.
// Copyright © 2017 Prezentor. All rights reserved.
//
import UIKit
class CLTokenInputView: UIView {
weak var delegate: CLTokenInputViewDelegate?
var fieldLabel: UILabel!
var fieldView: UIView? {
willSet {
if fieldView != newValue {
fieldView?.removeFromSuperview()
}
}
didSet {
if oldValue != fieldView {
if fieldView != nil {
addSubview(fieldView!)
}
repositionViews()
}
}
}
var fieldName: String? {
didSet {
if oldValue != fieldName {
fieldLabel.text = fieldName
fieldLabel.sizeToFit()
let showField: Bool = fieldName!.characters.count > 0
fieldLabel.isHidden = !showField
if showField && fieldLabel.superview == nil {
addSubview(fieldLabel)
} else if !showField && fieldLabel.superview != nil {
fieldLabel.removeFromSuperview()
}
if oldValue == nil || oldValue != fieldName {
repositionViews()
}
}
}
}
var fieldColor: UIColor? {
didSet {
fieldLabel.textColor = fieldColor
}
}
var placeholderText: String? {
didSet {
if oldValue != placeholderText {
updatePlaceholderTextVisibility()
}
}
}
var accessoryView: UIView? {
willSet {
if accessoryView != newValue {
accessoryView?.removeFromSuperview()
}
}
didSet {
if oldValue != accessoryView {
if accessoryView != nil {
addSubview(accessoryView!)
}
repositionViews()
}
}
}
var keyboardType: UIKeyboardType! {
didSet {
textField.keyboardType = keyboardType
}
}
var autocapitalizationType: UITextAutocapitalizationType! {
didSet {
textField.autocapitalizationType = autocapitalizationType
}
}
var autocorrectionType: UITextAutocorrectionType! {
didSet {
textField.autocorrectionType = autocorrectionType
}
}
var tokenizationCharacters = Set<String>()
var drawBottomBorder: Bool = false {
didSet {
if oldValue != drawBottomBorder {
setNeedsDisplay()
}
}
}
var paddingLeft: CGFloat = 0 {
didSet {
repositionViews()
}
}
var inputTextFieldTint: UIColor! {
didSet {
textField.tintColor = inputTextFieldTint
}
}
var tokens: [CLToken] = []
var tokenViews: [CLTokenView] = []
var textField: CLBackspaceDetectingTextField!
var intrinsicContentHeight: CGFloat!
var additionalTextFieldYOffset: CGFloat!
var additionalTokenViewYOffset: CGFloat!
let hSpace: CGFloat = 0.0
let textFieldHSpace: CGFloat = 4.0 // Note: Same as CLTokenView.PADDING_X
let vSpace: CGFloat = 4.0
let minimumTextFieldWidth: CGFloat = 56.0
let paddingTop: CGFloat = 10.0
let paddingBottom: CGFloat = 10.0
let paddingRight: CGFloat = 16.0
let standardRowHeight: CGFloat = 24.0
let fieldMarginX: CGFloat = 4.0
private func commonInit() {
textField = CLBackspaceDetectingTextField(frame: bounds)
textField.translatesAutoresizingMaskIntoConstraints = false
textField.backgroundColor = .clear
textField.keyboardType = .emailAddress
textField.autocorrectionType = .no
textField.autocapitalizationType = .none
textField.delegate = self
//additionalTextFieldYOffset = 0.0
additionalTextFieldYOffset = -2
additionalTokenViewYOffset = -2
textField.addTarget(self, action: #selector(CLTokenInputView.onTextFieldDidChange(_:)), for: .editingChanged)
addSubview(textField)
fieldLabel = UILabel(frame: CGRect.zero)
fieldLabel.translatesAutoresizingMaskIntoConstraints = false
fieldLabel.font = textField.font
fieldLabel.textColor = fieldColor
addSubview(fieldLabel)
fieldLabel.isHidden = true
fieldColor = .lightGray
intrinsicContentHeight = standardRowHeight
repositionViews()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override var intrinsicContentSize: CGSize {
return CGSize(width: UIViewNoIntrinsicMetric, height: max(45, intrinsicContentHeight))
}
override func tintColorDidChange() {
tokenViews.forEach { $0.tintColor = tintColor }
}
func addToken(_ token: CLToken) {
guard !tokens.contains(token) else { return }
tokens.append(token)
let tokenView: CLTokenView = CLTokenView(token: token, font: textField.font)
tokenView.translatesAutoresizingMaskIntoConstraints = false
tokenView.tintColor = tintColor
tokenView.delegate = self
let intrinsicSize: CGSize = tokenView.intrinsicContentSize
tokenView.frame = CGRect(x: 0.0, y: 0.0, width: intrinsicSize.width, height: intrinsicSize.height)
tokenViews.append(tokenView)
addSubview(tokenView)
textField.text = ""
delegate?.tokenInputView(self, didAddToken: token)
onTextFieldDidChange(textField)
updatePlaceholderTextVisibility()
repositionViews()
}
func removeTokenAtIndex(_ index: Int) {
guard index != -1 else { return }
let tokenView = tokenViews[index]
tokenView.removeFromSuperview()
tokenViews.remove(at: index)
let removedToken = tokens[index]
tokens.remove(at: index)
delegate?.tokenInputView(self, didRemoveToken: removedToken)
updatePlaceholderTextVisibility()
repositionViews()
}
func removeToken(_ token: CLToken) {
if let index = tokens.index(of: token) {
removeTokenAtIndex(index)
}
}
var allTokens: [CLToken] {
return Array(tokens)
}
func tokenizeTextfieldText() -> CLToken? {
//print("tokenizeTextfieldText()")
var token: CLToken? = nil
if let text = textField.text, !text.isEmpty {
token = delegate?.tokenInputView(self, tokenForText: text)
if token != nil {
addToken(token!)
textField.text = ""
onTextFieldDidChange(textField)
}
}
return token
}
fileprivate func repositionViews() {
let bounds: CGRect = self.bounds
let rightBoundary: CGFloat = bounds.width - paddingRight
var firstLineRightBoundary: CGFloat = rightBoundary
var curX: CGFloat = paddingLeft//PADDING_LEFT
var curY: CGFloat = paddingTop
var totalHeight: CGFloat = standardRowHeight
var isOnFirstLine: Bool = true
// print("repositionViews curX=\(curX) curY=\(curY)")
//print("frame=\(frame)")
// Position field view (if set)
if fieldView != nil {
var fieldViewRect: CGRect = fieldView!.frame
fieldViewRect.origin.x = curX + fieldMarginX
fieldViewRect.origin.y = curY + ((standardRowHeight - fieldViewRect.height / 2.0)) - paddingTop
fieldView?.frame = fieldViewRect
curX = fieldViewRect.maxX + fieldMarginX
// print("fieldViewRect=\(fieldViewRect)")
}
// Position field label (if field name is set)
if !(fieldLabel.isHidden) {
var fieldLabelRect: CGRect = fieldLabel.frame
fieldLabelRect.origin.x = curX + fieldMarginX
//+ ((standardRowHeight - CGRectGetHeight(fieldLabelRect) / 2.0)) - paddingTop
fieldLabelRect.origin.y = curY
fieldLabel.frame = fieldLabelRect
curX = fieldLabelRect.maxX + fieldMarginX
//print("fieldLabelRect=\(fieldLabelRect)")
}
// Position accessory view (if set)
if accessoryView != nil {
var accessoryRect: CGRect = accessoryView!.frame
accessoryRect.origin.x = bounds.width - paddingRight - accessoryRect.width
accessoryRect.origin.y = curY
accessoryView!.frame = accessoryRect
firstLineRightBoundary = accessoryRect.minX - hSpace
}
// Position token views
var tokenRect: CGRect = CGRect.null
for tokenView: CLTokenView in tokenViews {
tokenRect = tokenView.frame
let tokenBoundary: CGFloat = isOnFirstLine ? firstLineRightBoundary : rightBoundary
if curX + tokenRect.width > tokenBoundary {
// Need a new line
curX = paddingLeft
curY += standardRowHeight + vSpace
totalHeight += standardRowHeight
isOnFirstLine = false
}
tokenRect.origin.x = curX
// Center our tokenView vertically within standardRowHeight
// + ((standardRowHeight - CGRectGetHeight(tokenRect)) / 2.0) + additionalTokenViewYOffset
tokenRect.origin.y = curY + additionalTokenViewYOffset
tokenView.frame = tokenRect
curX = tokenRect.maxX + hSpace
}
// Always indent textfield by a little bit
curX += textFieldHSpace
let textBoundary: CGFloat = isOnFirstLine ? firstLineRightBoundary : rightBoundary
var availableWidthForTextField: CGFloat = textBoundary - curX
if availableWidthForTextField < minimumTextFieldWidth ||
availableWidthForTextField < textField.intrinsicContentSize.width + 5 {
isOnFirstLine = false
curX = paddingLeft + textFieldHSpace
curY += standardRowHeight + vSpace
totalHeight += standardRowHeight
// Adjust the width
availableWidthForTextField = rightBoundary - curX
}
var textFieldRect: CGRect = textField.frame
textFieldRect.origin.x = curX
textFieldRect.origin.y = curY + additionalTextFieldYOffset
textFieldRect.size.width = availableWidthForTextField
textFieldRect.size.height = standardRowHeight
textField.frame = textFieldRect
let oldContentHeight: CGFloat = intrinsicContentHeight
intrinsicContentHeight = textFieldRect.maxY+paddingBottom
invalidateIntrinsicContentSize()
if oldContentHeight != intrinsicContentHeight {
delegate?.tokenInputView(self, didChangeHeightTo: intrinsicContentSize.height)
}
setNeedsDisplay()
}
func updatePlaceholderTextVisibility() {
textField.placeholder = tokens.count > 0 ? nil : placeholderText
}
override func layoutSubviews() {
super.layoutSubviews()
repositionViews()
}
var textFieldDisplayOffset: CGFloat {
return textField.frame.minY - paddingTop
}
var text: String? {
return textField.text
}
func selectTokenView(_ tokenView: CLTokenView, animated aBool: Bool) {
tokenView.setSelected(true, animated: aBool)
for otherTokenView: CLTokenView in tokenViews where otherTokenView != tokenView {
otherTokenView.setSelected(false, animated: aBool)
}
}
func unselectAllTokenViewsAnimated(_ animated: Bool) {
for tokenView: CLTokenView in tokenViews {
tokenView.setSelected(false, animated: animated)
}
}
var isEditing: Bool {
return textField.isEditing
}
func beginEditing() {
textField.becomeFirstResponder()
unselectAllTokenViewsAnimated(false)
}
func endEditing() {
textField.resignFirstResponder()
}
override func draw(_ rect: CGRect) {
super.draw(rect)
if drawBottomBorder {
let context: CGContext? = UIGraphicsGetCurrentContext()
context?.setStrokeColor(UIColor.lightGray.cgColor)
context?.setLineWidth(0.5)
context?.move(to: CGPoint(x: bounds.width, y: bounds.size.height))
context?.addLine(to: CGPoint(x: bounds.width, y: bounds.size.height))
context?.strokePath()
}
}
}
// MARK: CLBackspaceDetectingTextFieldDelegate
extension CLTokenInputView: CLBackspaceDetectingTextFieldDelegate {
func textFieldDidDeleteBackwards(_ textField: UITextField) {
DispatchQueue.main.async { [weak self] in
if textField.text?.isEmpty == true, let tokenView = self?.tokenViews.last {
self?.selectTokenView(tokenView, animated: true)
self?.textField.resignFirstResponder()
}
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
delegate?.tokenInputViewDidBeginEditing(self)
tokenViews.last?.hideUnselectedComma = false
unselectAllTokenViewsAnimated(true)
}
func textFieldDidEndEditing(_ textField: UITextField) {
delegate?.tokenInputViewDidEndEditing(self)
tokenViews.last?.hideUnselectedComma = true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
_ = tokenizeTextfieldText()
return false
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
if !string.isEmpty, tokenizationCharacters.contains(string) {
_ = tokenizeTextfieldText()
return false
}
repositionViews()
return true
}
func onTextFieldDidChange(_ sender: UITextField) {
delegate?.tokenInputView(self, didChangeText: textField.text!)
}
}
extension CLTokenInputView: CLTokenViewDelegate {
func tokenViewDidHandeLongPressure(_ tokenView: CLTokenView) {
if let index = tokenViews.index(of: tokenView), index < tokens.count {
delegate?.tokenInputView(self, didHandleLongPressureForToken: tokens[index], tokenView: tokenView)
}
}
func tokenViewDidRequestDelete(_ tokenView: CLTokenView, replaceWithText replacementText: String?) {
textField.becomeFirstResponder()
if replacementText?.isEmpty == false {
textField.text = replacementText
}
if let index = tokenViews.index(of: tokenView) {
removeTokenAtIndex(index)
}
}
func tokenViewDidRequestSelection(_ tokenView: CLTokenView) {
if tokenView.selected == true,
let index = tokenViews.index(of: tokenView),
index < tokens.count {
delegate?.tokenInputView(self, didSelectToken: tokens[index])
}
selectTokenView(tokenView, animated:true)
}
}
| mit | 25813b49510ced9f8e35f9da12adf1b4 | 28.279221 | 113 | 0.691949 | 4.599456 | false | false | false | false |
wemap/Fusuma | Sources/FSCameraView.swift | 1 | 14724 | //
// FSCameraView.swift
// Fusuma
//
// Created by Yuta Akizuki on 2015/11/14.
// Copyright © 2015年 ytakzk. All rights reserved.
//
import UIKit
import AVFoundation
import CoreMotion
@objc protocol FSCameraViewDelegate: class {
func cameraShotFinished(_ image: UIImage)
}
final class FSCameraView: UIView, UIGestureRecognizerDelegate {
@IBOutlet weak var previewViewContainer: UIView!
@IBOutlet weak var shotButton: UIButton!
@IBOutlet weak var flashButton: UIButton!
@IBOutlet weak var flipButton: UIButton!
@IBOutlet weak var fullAspectRatioConstraint: NSLayoutConstraint!
var croppedAspectRatioConstraint: NSLayoutConstraint?
@IBOutlet weak var circleCropView: FSAlbumCircleCropView!
weak var delegate: FSCameraViewDelegate? = nil
fileprivate var session: AVCaptureSession?
fileprivate var device: AVCaptureDevice?
fileprivate var videoInput: AVCaptureDeviceInput?
fileprivate var imageOutput: AVCaptureStillImageOutput?
fileprivate var videoLayer: AVCaptureVideoPreviewLayer?
fileprivate var focusView: UIView?
fileprivate var flashOffImage: UIImage?
fileprivate var flashOnImage: UIImage?
fileprivate var motionManager: CMMotionManager?
fileprivate var currentDeviceOrientation: UIDeviceOrientation?
static func instance() -> FSCameraView {
return UINib(nibName: "FSCameraView", bundle: Bundle(for: self.classForCoder())).instantiate(withOwner: self, options: nil)[0] as! FSCameraView
}
func initialize() {
if session != nil { return }
circleCropView.isHidden = fusumaCropMode == .rectangle
let bundle = Bundle(for: self.classForCoder)
flashOnImage = fusumaFlashOnImage != nil ? fusumaFlashOnImage : UIImage(named: "ic_flash_on_white_48pt", in: bundle, compatibleWith: nil)
flashOffImage = fusumaFlashOffImage != nil ? fusumaFlashOffImage : UIImage(named: "ic_flash_off_white_48pt", in: bundle, compatibleWith: nil)
let flipImage = fusumaFlipImage != nil ? fusumaFlipImage : UIImage(named: "ic_loop_white_48pt", in: bundle, compatibleWith: nil)
let shotImage = fusumaShotImage != nil ? fusumaShotImage : UIImage(named: "ic_radio_button_checked_white_24px", in: bundle, compatibleWith: nil)
if(fusumaTintIcons) {
flashButton.tintColor = fusumaBaseTintColor
flipButton.tintColor = fusumaBaseTintColor
shotButton.tintColor = fusumaBaseTintColor
flashButton.setImage(flashOffImage?.withRenderingMode(.alwaysTemplate), for: UIControlState())
flipButton.setImage(flipImage?.withRenderingMode(.alwaysTemplate), for: UIControlState())
shotButton.setImage(shotImage?.withRenderingMode(.alwaysTemplate), for: UIControlState())
} else {
flashButton.setImage(flashOffImage, for: UIControlState())
flipButton.setImage(flipImage, for: UIControlState())
shotButton.setImage(shotImage, for: UIControlState())
}
self.isHidden = false
// AVCapture
session = AVCaptureSession()
AVCaptureDevice.devices()
.filter { $0.position == AVCaptureDevice.Position.back }
.forEach {
self.device = $0
if !$0.hasFlash {
flashButton.isHidden = true
}
}
guard let device = device else { return }
do {
if let session = session {
videoInput = try AVCaptureDeviceInput(device: device)
session.addInput(videoInput!)
imageOutput = AVCaptureStillImageOutput()
session.addOutput(imageOutput!)
videoLayer = AVCaptureVideoPreviewLayer(session: session)
videoLayer?.frame = self.previewViewContainer.bounds
videoLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
self.previewViewContainer.layer.addSublayer(videoLayer!)
session.sessionPreset = AVCaptureSession.Preset.photo
session.startRunning()
}
// Focus View
self.focusView = UIView(frame: CGRect(x: 0, y: 0, width: 90, height: 90))
let tapRecognizer = UITapGestureRecognizer(target: self, action:#selector(FSCameraView.focus(_:)))
tapRecognizer.delegate = self
self.previewViewContainer.addGestureRecognizer(tapRecognizer)
} catch {
}
flashConfiguration()
self.startCamera()
NotificationCenter.default.addObserver(self,
selector: #selector(FSCameraView.willEnterForegroundNotification(_:)),
name: NSNotification.Name.UIApplicationWillEnterForeground,
object: nil)
}
@objc func willEnterForegroundNotification(_ notification: Notification) {
startCamera()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func startCamera() {
let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
if status == AVAuthorizationStatus.authorized {
session?.startRunning()
motionManager = CMMotionManager()
motionManager!.accelerometerUpdateInterval = 0.2
motionManager!.startAccelerometerUpdates(to: OperationQueue()) { [unowned self] (data, _) in
if let data = data {
if abs( data.acceleration.y ) < abs( data.acceleration.x ) {
if data.acceleration.x > 0 {
self.currentDeviceOrientation = .landscapeRight
} else {
self.currentDeviceOrientation = .landscapeLeft
}
} else {
if data.acceleration.y > 0 {
self.currentDeviceOrientation = .portraitUpsideDown
} else {
self.currentDeviceOrientation = .portrait
}
}
}
}
} else if status == AVAuthorizationStatus.denied || status == AVAuthorizationStatus.restricted {
stopCamera()
}
}
func stopCamera() {
session?.stopRunning()
motionManager?.stopAccelerometerUpdates()
currentDeviceOrientation = nil
}
@IBAction func shotButtonPressed(_ sender: UIButton) {
guard let imageOutput = imageOutput else {
return
}
DispatchQueue.global(qos: .default).async(execute: { () -> Void in
guard let videoConnection = imageOutput.connection(with: AVMediaType.video) else { return }
let orientation: UIDeviceOrientation = self.currentDeviceOrientation ?? UIDevice.current.orientation
switch (orientation) {
case .portrait:
videoConnection.videoOrientation = .portrait
case .portraitUpsideDown:
videoConnection.videoOrientation = .portraitUpsideDown
case .landscapeRight:
videoConnection.videoOrientation = .landscapeLeft
case .landscapeLeft:
videoConnection.videoOrientation = .landscapeRight
default:
videoConnection.videoOrientation = .portrait
}
imageOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler: { buffer, error -> Void in
guard let buffer = buffer else { return }
self.stopCamera()
let data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
if let image = UIImage(data: data!), let delegate = self.delegate {
// Image size
var iw: CGFloat
var ih: CGFloat
switch (orientation) {
case .landscapeLeft, .landscapeRight:
// Swap width and height if orientation is landscape
iw = image.size.height
ih = image.size.width
default:
iw = image.size.width
ih = image.size.height
}
// The center coordinate along Y axis
let rcy = ih * 0.5
let imageRef = image.cgImage?.cropping(to: CGRect(x: rcy-iw*0.5, y: 0 , width: iw, height: iw))
DispatchQueue.main.async(execute: { () -> Void in
if fusumaCropImage {
delegate.cameraShotFinished(UIImage(cgImage: imageRef!, scale: 1.0, orientation: image.imageOrientation))
} else {
delegate.cameraShotFinished(image)
}
self.session = nil
self.device = nil
self.imageOutput = nil
self.motionManager = nil
})
}
})
})
}
@IBAction func flipButtonPressed(_ sender: UIButton) {
if !cameraIsAvailable() {
return
}
session?.stopRunning()
session?.beginConfiguration()
if let session = session {
session.inputs.forEach { session.removeInput($0) }
let position = (videoInput?.device.position == AVCaptureDevice.Position.front) ? AVCaptureDevice.Position.back : AVCaptureDevice.Position.front
AVCaptureDevice.devices(for: AVMediaType.video)
.filter { $0.position == position }
.forEach {
videoInput = try? AVCaptureDeviceInput(device: $0)
if let input = videoInput {
session.addInput(input)
}
}
}
session?.commitConfiguration()
session?.startRunning()
}
@IBAction func flashButtonPressed(_ sender: UIButton) {
if !cameraIsAvailable() {
return
}
do {
if let device = device {
guard device.hasFlash else { return }
try device.lockForConfiguration()
let mode = device.flashMode
if mode == .off {
if device.isFlashModeSupported(.on) {
device.flashMode = .on
flashButton.setImage(flashOnImage, for: UIControlState())
}
} else
if mode == .on {
if device.isFlashModeSupported(.off) {
device.flashMode = .off
flashButton.setImage(flashOffImage, for: UIControlState())
}
}
device.unlockForConfiguration()
}
} catch _ {
flashButton.setImage(flashOffImage, for: UIControlState())
return
}
}
}
extension FSCameraView {
@objc func focus(_ recognizer: UITapGestureRecognizer) {
let point = recognizer.location(in: self)
let viewsize = self.bounds.size
let newPoint = CGPoint(x: point.y/viewsize.height, y: 1.0-point.x/viewsize.width)
let device = AVCaptureDevice.default(for: AVMediaType.video)
do {
try device?.lockForConfiguration()
} catch _ {
return
}
if device?.isFocusModeSupported(AVCaptureDevice.FocusMode.autoFocus) == true {
device?.focusMode = AVCaptureDevice.FocusMode.autoFocus
device?.focusPointOfInterest = newPoint
}
if device?.isExposureModeSupported(AVCaptureDevice.ExposureMode.continuousAutoExposure) == true {
device?.exposureMode = AVCaptureDevice.ExposureMode.continuousAutoExposure
device?.exposurePointOfInterest = newPoint
}
device?.unlockForConfiguration()
self.focusView?.alpha = 0.0
self.focusView?.center = point
self.focusView?.backgroundColor = UIColor.clear
self.focusView?.layer.borderColor = fusumaBaseTintColor.cgColor
self.focusView?.layer.borderWidth = 1.0
self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.addSubview(self.focusView!)
UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.8,
initialSpringVelocity: 3.0, options: UIViewAnimationOptions.curveEaseIn, // UIViewAnimationOptions.BeginFromCurrentState
animations: {
self.focusView!.alpha = 1.0
self.focusView!.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
}, completion: {(finished) in
self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.focusView!.removeFromSuperview()
})
}
func flashConfiguration() {
do {
if let device = device {
guard device.hasFlash else { return }
try device.lockForConfiguration()
if device.isFlashModeSupported(.off) {
device.flashMode = .off
flashButton.setImage(flashOffImage, for: UIControlState())
}
device.unlockForConfiguration()
}
} catch _ {
return
}
}
func cameraIsAvailable() -> Bool {
let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
if status == AVAuthorizationStatus.authorized {
return true
}
return false
}
}
| mit | e2631e5816f6b1c99cb322908ab46f61 | 34.730583 | 155 | 0.546294 | 6.328891 | false | false | false | false |
iOS-mamu/SS | P/Potatso/Core/CloudSetManager.swift | 1 | 1286 | //
// CloudSetManager.swift
// Potatso
//
// Created by LEI on 8/13/16.
// Copyright © 2016 TouchingApp. All rights reserved.
//
import Foundation
import Async
import RealmSwift
class CloudSetManager {
static let shared = CloudSetManager()
fileprivate init() {
}
func update() {
Async.background(after: 1.5) {
let realm = try! Realm()
let uuids = realm.objects(RuleSet.self).filter("isSubscribe = true").map({$0.uuid})
var uuidsArray: [String] = []
var iterator: LazyMapIterator<RLMIterator<RuleSet>, String>? = nil
iterator = uuids.makeIterator()
iterator?.forEach({ (tObj) in
uuidsArray.append(tObj as String)
})
API.updateRuleSetListDetail(uuidsArray) { (response) in
if let sets = response.result.value {
do {
try RuleSet.addRemoteArray(sets)
}catch {
error.log("Unable to save updated rulesets")
return
}
}else {
response.result.error?.log("Fail to update ruleset details")
}
}
}
}
}
| mit | 229731c7d5a5f7e0cf88af254293091b | 26.340426 | 95 | 0.506615 | 4.672727 | false | false | false | false |
darofar/lswc | p7-actor/Actor/AddActorTableViewController.swift | 1 | 966 | //
// AddActorTableViewController.swift
// Actor
//
// Created by Javier De La Rubia on 26/5/15.
// Copyright (c) 2015 Javier De La Rubia. All rights reserved.
//
import UIKit
class AddActorTableViewController: UITableViewController {
var name : String!
@IBOutlet var nameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
nameTextField.text = name
nameTextField.becomeFirstResponder()
}
// MARK: - Navigation
@IBAction func savePressed(sender: UITextField) {
performSegueWithIdentifier("Save Search Item", sender: nameTextField)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Save Search Item" {
self.name = nameTextField.text
}
/**
* if segue.identifier == "Cancel Edition" {
* //no hacer nada
* }
*/
}
}
| apache-2.0 | 9da5faa6d87830484cb8a012ef3a5315 | 23.15 | 81 | 0.613872 | 4.758621 | false | false | false | false |
mrdepth/Neocom | Neocom/Neocom/Misc/Settings.swift | 2 | 5662 | //
// Settings.swift
// Neocom
//
// Created by Artem Shimanski on 5/8/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
struct Settings: View {
@EnvironmentObject private var storage: Storage
@State private var isClearCacheActionSheetPresented = false
@ObservedObject private var notificationsEnabled = UserDefault(wrappedValue: true, key: .notificationsEnabled)
@ObservedObject private var skillQueueNotificationOptions = UserDefault(wrappedValue: NotificationsManager.SkillQueueNotificationOptions.default.rawValue, key: .notificationSettigs)
@ObservedObject private var colorScheme = UserDefault(wrappedValue: -1, key: .colorScheme)
private func skillQueueNotificationCell(option: NotificationsManager.SkillQueueNotificationOptions, title: String) -> some View {
Toggle(title, isOn: Binding(get: {
NotificationsManager.SkillQueueNotificationOptions(rawValue: self.skillQueueNotificationOptions.wrappedValue).contains(option)
}, set: { newValue in
var options = NotificationsManager.SkillQueueNotificationOptions(rawValue: self.skillQueueNotificationOptions.wrappedValue)
if newValue {
options.insert(option)
}
else {
options.remove(option)
}
self.skillQueueNotificationOptions.wrappedValue = options.rawValue
}))
}
var body: some View {
List {
Section(footer: Text("Data will be restored from iCloud.")) {
MigrateLegacyDataButton()
}
Section(header: Text("APPEARANCE")) {
Toggle(isOn: Binding(get: {
self.colorScheme.wrappedValue <= 0
}, set: { (newValue) in
self.colorScheme.wrappedValue = newValue ? -1 : 2
})) {
Text("Automatic")
}
if colorScheme.wrappedValue > 0 {
Picker(selection: $colorScheme.wrappedValue, label: Text("Appearance")) {
Text("Light Theme").tag(1)
Text("Dark Theme").tag(2)
}.pickerStyle(SegmentedPickerStyle())
}
}
LanguagePack.packs[storage.sde.tag].map { pack in
Section(header: Text("DATABASE LANGUAGE")) {
NavigationLink(destination: LanguagePacks()) {
VStack(alignment: .leading) {
Text(pack.name).foregroundColor(.primary)
pack.localizedName.modifier(SecondaryLabelModifier())
}
}
}
}
Section {
Toggle(NSLocalizedString("Notifications Enabled", comment: ""), isOn: $notificationsEnabled.wrappedValue)
}
if notificationsEnabled.wrappedValue {
Section(header: Text("SKILL QUEUE NOTIFICATIONS")) {
skillQueueNotificationCell(option: .inactive, title: NSLocalizedString("Inactive Skill Queue", comment: "Skill queue notifications"))
skillQueueNotificationCell(option: .oneHour, title: NSLocalizedString("1 Hour Left", comment: "Skill queue notifications"))
skillQueueNotificationCell(option: .fourHours, title: NSLocalizedString("4 Hours Left", comment: "Skill queue notifications"))
skillQueueNotificationCell(option: .oneDay, title: NSLocalizedString("24 Hours Left", comment: "Skill queue notifications"))
skillQueueNotificationCell(option: .skillTrainingComplete, title: NSLocalizedString("Skill Training Complete", comment: "Skill queue notifications"))
}
}
Section(header: Text("CACHE"), footer: Text("Some application features may be temporarily unavailable")) {
Button(NSLocalizedString("Clear Cache", comment: "")) {
self.isClearCacheActionSheetPresented = true
}
.frame(maxWidth: .infinity)
.accentColor(.red)
.actionSheet(isPresented: $isClearCacheActionSheetPresented) {
ActionSheet(title: Text("Are you sure?"), buttons: [
.destructive(Text("Clear Cache"), action: {
URLCache.shared.removeAllCachedResponses()
}),
.cancel()
])
}
}
}
.listStyle(GroupedListStyle())
.navigationBarTitle(Text("Settings"))
}
}
struct MigrateLegacyDataButton: View {
@State private var token = FileManager.default.ubiquityIdentityToken
var body: some View {
Group {
if token == nil {
VStack(alignment: .leading) {
Text("Migrate legacy data")
Text("Please, log in to iCloud Account").modifier(SecondaryLabelModifier())
}
}
else {
NavigationLink(NSLocalizedString("Migrate legacy data", comment: ""), destination: Migration())
}
}.onReceive(NotificationCenter.default.publisher(for: Notification.Name.NSUbiquityIdentityDidChange)) { (_) in
self.token = FileManager.default.ubiquityIdentityToken
}
}
}
struct Settings_Previews: PreviewProvider {
static var previews: some View {
Settings()
}
}
| lgpl-2.1 | fd1809d6a7806ec84d9ac3625808c4d8 | 42.883721 | 185 | 0.575693 | 5.782431 | false | false | false | false |
michaelarmstrong/Brisk | Brisk/Brisk/JSONExtension.swift | 1 | 7906 | //
// JSONExtension.swift
// Brisk
//
// Created by Michael Armstrong on 08/06/2014.
// Copyright (c) 2014 Michael Armstrong. All rights reserved.
//
import Foundation
import UIKit
let kKeyContent = "content"
extension BriskClient {
typealias dictionaryForURLCompletionClosure = ((NSURLResponse!, NSDictionary?, NSError?) -> Void)!
func dictionaryForURL(url : NSURL, completionHandler handler: dictionaryForURLCompletionClosure) {
dataForURL(url, completionHandler: {(response : NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if error != nil {
handler(response,nil,error)
return
}
var resultDictionary = NSMutableDictionary()
var deserializationError : NSError?
var obj : AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &deserializationError)
if let jsonObject: AnyObject = obj {
switch jsonObject {
case is NSArray:
resultDictionary[kKeyContent] = jsonObject
case is NSDictionary:
resultDictionary = NSMutableDictionary(dictionary: jsonObject as! NSDictionary)
default:
resultDictionary[kKeyContent] = ""
}
}
handler(response,resultDictionary.copy() as? NSDictionary,error)
})
}
func dictionaryForRequest(request : NSURLRequest, postParams : NSDictionary?, completionHandler handler: dictionaryForURLCompletionClosure) {
var urlRequest = request
if let postParams = postParams {
var serializationError : NSError?
let jsonData = NSJSONSerialization.dataWithJSONObject(postParams, options: NSJSONWritingOptions.PrettyPrinted, error: &serializationError)
if(serializationError != nil){
handler(nil,nil,serializationError)
}
let mutableRequest = urlRequest.mutableCopy() as! NSMutableURLRequest
if mutableRequest.HTTPMethod == "GET" {
mutableRequest.HTTPMethod = "POST"
}
if let jsonData = jsonData {
mutableRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableRequest.HTTPBody = jsonData
}
urlRequest = mutableRequest.copy() as! NSURLRequest
}
dataForRequest(urlRequest, completionHandler: {(response : NSURLResponse!, data: NSData!, error: NSError!) -> Void in
// TODO: Remove this MASSIVE amount of code duplication I just added and tidy up the almightly unneccesaryness of it.
if error != nil {
handler(response,nil,error)
return
}
let resultString = NSString(data: data, encoding: NSUTF8StringEncoding)
//println("Result String : \(resultString)")
var deserializationError : NSError?
var dataObj : AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &deserializationError)
if let resultObj = dataObj as? NSDictionary {
if let resultDictionary = resultObj["Content"] as? NSDictionary {
handler(response,resultDictionary,error)
} else {
if let resultArray = resultObj["Content"] as? NSArray {
let resultDictionary = [kKeyContent:resultArray]
handler(response,resultDictionary,error)
return
}
var resultDictionary = NSMutableDictionary()
switch dataObj {
case is NSArray:
resultDictionary[kKeyContent] = dataObj
case is NSDictionary:
resultDictionary = NSMutableDictionary(dictionary: dataObj as! NSDictionary)
default:
resultDictionary[kKeyContent] = ""
}
handler(response,resultDictionary,error)
return
// handler(response,nil,error)
}
return
} else {
var resultDictionary = NSMutableDictionary()
switch dataObj {
case is NSArray:
resultDictionary[kKeyContent] = dataObj
case is NSDictionary:
resultDictionary = dataObj as! NSMutableDictionary
default:
resultDictionary[kKeyContent] = ""
}
handler(response,resultDictionary,error)
return
}
})
}
func dictionaryForURL(url : NSURL, postParams : NSDictionary, completionHandler handler: dictionaryForURLCompletionClosure) {
var serializationError : NSError?
let jsonData = NSJSONSerialization.dataWithJSONObject(postParams, options: NSJSONWritingOptions.PrettyPrinted, error: &serializationError)
println("Post Params \(postParams)")
if(serializationError != nil){
handler(nil,nil,serializationError)
}
dataForURL(url, postData: jsonData!, completionHandler: {(response : NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if error != nil {
handler(response,nil,error)
return
}
let resultString = NSString(data: data, encoding: NSUTF8StringEncoding)
//println("Result String : \(resultString)")
var deserializationError : NSError?
var dataObj : AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &deserializationError)
if let resultObj = dataObj as? NSDictionary {
if let resultDictionary = resultObj["Content"] as? NSDictionary {
handler(response,resultDictionary,error)
} else {
if let resultArray = resultObj["Content"] as? NSArray {
let resultDictionary = [kKeyContent:resultArray]
handler(response,resultDictionary,error)
return
}
var resultDictionary = NSMutableDictionary()
switch dataObj {
case is NSArray:
resultDictionary[kKeyContent] = dataObj
case is NSDictionary:
resultDictionary = NSMutableDictionary(dictionary: dataObj as! NSDictionary)
default:
resultDictionary[kKeyContent] = ""
}
handler(response,resultDictionary,error)
return
// handler(response,nil,error)
}
return
} else {
var resultDictionary = NSMutableDictionary()
switch dataObj {
case is NSArray:
resultDictionary[kKeyContent] = dataObj
case is NSDictionary:
resultDictionary = dataObj as! NSMutableDictionary
default:
resultDictionary[kKeyContent] = ""
}
handler(response,resultDictionary,error)
return
}
})
}
} | mit | 7ed8baa735d435cf9e6c3fe2d7283991 | 40.182292 | 159 | 0.543511 | 6.67173 | false | false | false | false |
shepting/AutoLayout | AutoLayoutDemo/AutoLayoutDemo/User.swift | 1 | 1098 | //
// User.swift
// AutoLayoutDemo
//
// Created by Steven Hepting on 8/28/14.
// Copyright (c) 2014 Protospec. All rights reserved.
//
import UIKit
class User: NSObject {
var name: String
let profileURL: NSURL
override init() {
let names = ["Lori Rainey",
"Fannie McCallister",
"Eva Johnson",
"Danny Kip",
"John McKenzie",
"Lawrence Crimmins",
"Sumit Kumar"];
let index = Int(arc4random_uniform(UInt32(names.count)))
name = names[index]
let profileURLs = ["http://api.randomuser.me/portraits/women/9.jpg",
"http://api.randomuser.me/portraits/women/5.jpg",
"http://api.randomuser.me/portraits/women/2.jpg",
"http://api.randomuser.me/portraits/men/5.jpg",
"http://api.randomuser.me/portraits/men/2.jpg",
"http://api.randomuser.me/portraits/men/7.jpg",
"http://api.randomuser.me/portraits/men/6.jpg"]
let url = NSURL(string: profileURLs[index])
profileURL = url!
}
}
| mit | 8cdc1d6731cdff8cd738b67558aa410a | 28.675676 | 76 | 0.567395 | 3.327273 | false | false | false | false |
nucauthu/MusicPlayerDemo | MusicPlayerDemo/Models/Playlist.swift | 1 | 1435 | //
// Playlist.swift
// MusicPlayerDemo
//
// Created by Ngo Thieu Kieu Chinh on 7/10/16.
// Copyright © 2016 Ngo Thieu Kieu Chinh. All rights reserved.
//
import Foundation
class Playlist {
let name: String
var list: [Song]
var imageUrl: String?
init(name: String, list: [Song], imageUrl: String? = nil) {
self.name = name
self.list = list
self.imageUrl = imageUrl
}
//Default Contruction for Demo
init() {
self.name = "Demo Playlist"
self.list = [Song]()
let song1 = Song(title: "Bong bong bang bang", singer: "365", url: "http://data.chiasenhac.com/downloads/1675/1/1674259-822b43a8/128/Bong%20Bong%20Bang%20Bang%20-%20365daband%20[MP3%20128kbps].mp3", playlist: self)
self.list.append(song1)
let song2 = Song(title: "Song 2", singer: "Singer", url: "http://data.chiasenhac.com/downloads/1675/1/1674259-822b43a8/128/Bong%20Bong%20Bang%20Bang%20-%20365daband%20[MP3%20128kbps].mp3", playlist: self)
self.list.append(song2)
let song3 = Song(title: "Song 3", singer: "Singer", url: "http://data.chiasenhac.com/downloads/1675/1/1674259-822b43a8/128/Bong%20Bong%20Bang%20Bang%20-%20365daband%20[MP3%20128kbps].mp3", playlist: self)
self.list.append(song3)
self.imageUrl = "http://az616578.vo.msecnd.net/files/2016/04/23/635969800309510397-600135549_Album-1.jpg"
}
} | mit | 1e448e9e8e3a7fe55e60754fdd3d3b35 | 37.783784 | 222 | 0.650628 | 2.885312 | false | false | false | false |
nanthi1990/SwiftCharts | Examples/Examples/CandleStickExample.swift | 2 | 7511 | //
// CandleStickExample.swift
// SwiftCharts
//
// Created by ischuetz on 04/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
import SwiftCharts
class CandleStickExample: UIViewController {
private var chart: Chart? // arc
override func viewDidLoad() {
super.viewDidLoad()
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont)
var readFormatter = NSDateFormatter()
readFormatter.dateFormat = "dd.MM.yyyy"
var displayFormatter = NSDateFormatter()
displayFormatter.dateFormat = "MMM dd"
let date = {(str: String) -> NSDate in
return readFormatter.dateFromString(str)!
}
let calendar = NSCalendar.currentCalendar()
let dateWithComponents = {(day: Int, month: Int, year: Int) -> NSDate in
let components = NSDateComponents()
components.day = day
components.month = month
components.year = year
return calendar.dateFromComponents(components)!
}
func filler(date: NSDate) -> ChartAxisValueDate {
let filler = ChartAxisValueDate(date: date, formatter: displayFormatter)
filler.hidden = true
return filler
}
let chartPoints = [
ChartPointCandleStick(date: date("01.10.2015"), formatter: displayFormatter, high: 40, low: 37, open: 39.5, close: 39),
ChartPointCandleStick(date: date("02.10.2015"), formatter: displayFormatter, high: 39.8, low: 38, open: 39.5, close: 38.4),
ChartPointCandleStick(date: date("03.10.2015"), formatter: displayFormatter, high: 43, low: 39, open: 41.5, close: 42.5),
ChartPointCandleStick(date: date("04.10.2015"), formatter: displayFormatter, high: 48, low: 42, open: 44.6, close: 44.5),
ChartPointCandleStick(date: date("05.10.2015"), formatter: displayFormatter, high: 45, low: 41.6, open: 43, close: 44),
ChartPointCandleStick(date: date("06.10.2015"), formatter: displayFormatter, high: 46, low: 42.6, open: 44, close: 46),
ChartPointCandleStick(date: date("07.10.2015"), formatter: displayFormatter, high: 47.5, low: 41, open: 42, close: 45.5),
ChartPointCandleStick(date: date("08.10.2015"), formatter: displayFormatter, high: 50, low: 46, open: 46, close: 49),
ChartPointCandleStick(date: date("09.10.2015"), formatter: displayFormatter, high: 45, low: 41, open: 44, close: 43.5),
ChartPointCandleStick(date: date("11.10.2015"), formatter: displayFormatter, high: 47, low: 35, open: 45, close: 39),
ChartPointCandleStick(date: date("12.10.2015"), formatter: displayFormatter, high: 45, low: 33, open: 44, close: 40),
ChartPointCandleStick(date: date("13.10.2015"), formatter: displayFormatter, high: 43, low: 36, open: 41, close: 38),
ChartPointCandleStick(date: date("14.10.2015"), formatter: displayFormatter, high: 42, low: 31, open: 38, close: 39),
ChartPointCandleStick(date: date("15.10.2015"), formatter: displayFormatter, high: 39, low: 34, open: 37, close: 36),
ChartPointCandleStick(date: date("16.10.2015"), formatter: displayFormatter, high: 35, low: 32, open: 34, close: 33.5),
ChartPointCandleStick(date: date("17.10.2015"), formatter: displayFormatter, high: 32, low: 29, open: 31.5, close: 31),
ChartPointCandleStick(date: date("18.10.2015"), formatter: displayFormatter, high: 31, low: 29.5, open: 29.5, close: 30),
ChartPointCandleStick(date: date("19.10.2015"), formatter: displayFormatter, high: 29, low: 25, open: 25.5, close: 25),
ChartPointCandleStick(date: date("20.10.2015"), formatter: displayFormatter, high: 28, low: 24, open: 26.7, close: 27.5),
ChartPointCandleStick(date: date("21.10.2015"), formatter: displayFormatter, high: 28.5, low: 25.3, open: 26, close: 27),
ChartPointCandleStick(date: date("22.10.2015"), formatter: displayFormatter, high: 30, low: 28, open: 28, close: 30),
ChartPointCandleStick(date: date("25.10.2015"), formatter: displayFormatter, high: 31, low: 29, open: 31, close: 31),
ChartPointCandleStick(date: date("26.10.2015"), formatter: displayFormatter, high: 31.5, low: 29.2, open: 29.6, close: 29.6),
ChartPointCandleStick(date: date("27.10.2015"), formatter: displayFormatter, high: 30, low: 27, open: 29, close: 28.5),
ChartPointCandleStick(date: date("28.10.2015"), formatter: displayFormatter, high: 32, low: 30, open: 31, close: 30.6),
ChartPointCandleStick(date: date("29.10.2015"), formatter: displayFormatter, high: 35, low: 31, open: 31, close: 33)
]
let yValues = Array(stride(from: 20, through: 55, by: 5)).map {ChartAxisValueDouble($0, labelSettings: labelSettings)}
func generateDateAxisValues(month: Int, year: Int) -> [ChartAxisValueDate] {
let date = dateWithComponents(1, month, year)
let calendar = NSCalendar.currentCalendar()
let monthDays = calendar.rangeOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitMonth, forDate: date)
return Array(monthDays.toRange()!).map {day in
let date = dateWithComponents(day, month, year)
let axisValue = ChartAxisValueDate(date: date, formatter: displayFormatter, labelSettings: labelSettings)
axisValue.hidden = !(day % 5 == 0)
return axisValue
}
}
let xValues = generateDateAxisValues(10, 2015)
let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings))
let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical()))
let chartFrame = ExamplesDefaults.chartFrame(self.view.bounds)
let coordsSpace = ChartCoordsSpaceRightBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame)
let chartPointsLineLayer = ChartCandleStickLayer<ChartPointCandleStick>(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, itemWidth: Env.iPad ? 10 : 5, strokeWidth: Env.iPad ? 1 : 0.6)
let settings = ChartGuideLinesLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth)
let guidelinesLayer = ChartGuideLinesLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings, onlyVisibleX: true)
let dividersSettings = ChartDividersLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth, start: Env.iPad ? 7 : 3, end: 0, onlyVisibleValues: true)
let dividersLayer = ChartDividersLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: dividersSettings)
let chart = Chart(
frame: chartFrame,
layers: [
xAxis,
yAxis,
guidelinesLayer,
dividersLayer,
chartPointsLineLayer
]
)
self.view.addSubview(chart.view)
self.chart = chart
}
}
| apache-2.0 | a047ff763c04b53bc9d7ed7f109ea21f | 62.117647 | 220 | 0.650379 | 4.326613 | false | false | false | false |
Alberto-Vega/SwiftCodeChallenges | BinaryTrees.playground/Pages/Heaps.xcplaygroundpage/Contents.swift | 1 | 1557 | //: [Previous](@previous)
import Foundation
func heapifyBinaryTree(root: Node<Int>) -> Node<Int>? {
var nodeArray: [Node<Int>?]?
let size = traverse(node: root, count: 0, array: &nodeArray)
nodeArray = [Node<Int>?](repeating: nil, count: size)
traverse(node: root, count: 0, array: &nodeArray)
nodeArray?.sort(by: { (a: Node<Int>?, b: Node<Int>?) -> Bool in
guard let aValue = a?.value, let bValue = b?.value else { return false }
return aValue < bValue
})
buildTreeFromArray(array: &nodeArray)
return nodeArray?[0]
}
func traverse(node: Node<Int>?, count: Int, array: inout [Node<Int>?]?) -> Int {
guard let node = node else { return count }
array?[count] = node
var count = count
count += 1
count = traverse(node: node.left, count: count, array: &array)
count = traverse(node: node.right, count: count, array: &array)
return count
}
func buildTreeFromArray(array: inout [Node<Int>?]?) {
guard let size = array?.count else { return }
for i in 0..<size {
let left = 2*i + 1
let right = left + 1
array?[i]?.left = left >= size ? nil : array?[left]
array?[i]?.right = right >= size ? nil : array?[right]
}
}
//: ### Traversals tests.
let inputBST = Node<Int>(value: 3)
inputBST.left = Node<Int>(value: 2)
inputBST.right = Node<Int>(value: 4)
inputBST.left?.left = Node<Int>(value: 1)
/*:
This binary search tree looks like:
3
/ \
2 4
/
1
*/
heapifyBinaryTree(root: inputBST)
//: [Next](@next)
| mit | 1a7fcf62d4410bdadef91f15d4376bdc | 23.328125 | 81 | 0.599229 | 3.334047 | false | false | false | false |
khizkhiz/swift | validation-test/compiler_crashers_fixed/00202-swift-parser-parseexprpostfix.swift | 1 | 2378 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func c<b:c
func d<b: Sequence, e where Optional<e> == b.Iterator.Element>(c : b) -> e? {
for (mx : e?) in c {
}
}
protocol A {
typealias B
func b(B)
}
struct X<Y> : A {
func b(b: X.Type) {
}
}
struct c<e> {
let d: i h
}
func f(h: b) -> <e>(()-> e
func c<g>() -> (g, g -> g) -> g {
d b d.f = {
}
{
g) {
i }
}
i c {
class func f()
}
class d: c{ class func f {}
struct d<c : f,f where g.i == c.i>
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 class func g() { }
}
(h() as p).dynamicType.g()
protocol p {
}
protocol h : p {
}
protocol g : p {
}
protocol n {
o t = p
}
struct h : n {
t : n q m.t == m> (h: m) {
}
func q<t : n q t.t == g> (h: t) {
}
q(h())
func r(g: m) -> <s>(() -> s) -> n
import Foundation
class Foo<T>: NSObject {
var foo: T
init(foo: T) {
B>(t: T) {
t.c()
} x
x) {
}
class a {
var _ = i() {
}
}
a=1 as a=1
class c {
func b((Any, c))(a: (Any, AnyObject)) {
b(a)
}
}
func i(f: g) -> <j>(() -> j) -> g { func g
k, l {
typealias l = m<k<m>, f>
}
func i(c: () -> ()) {
}
class a {
var _ = i() {
}
}
protocol A {
func c() -> String
}
class B {
func d() -> String {
return ""
}
}
class C: B, A {
override func d() -> String {
return ""
}
func c() -> String {
return ""
}
}
func e<T where T: A, T: B>(t: T) {
t.c()
}
}
}
class b<i : b> i: g{ func c {}
e g {
: g {
h func i() -> }
func h<j>() -> (j, j -> j) -> j {
var f: ({ (c: e, f: e -> e) -> return f(c)
}(k, i)
let o: e = { c, g
return f(c)
}(l) -> m) -> p>, e>
}
class n<j : n>
b
prot q g: n
}
func p<n>() -> [q<n>] {
o : g.l) {
}
}
class p {
typealias g = g
class a {
typealias b = b
}
import Foundation
class m<j>k i<g : g, e : f k(f: l) {
}
i(())
class h {
typealias g = g
protocol A {
typealias B
}
class C<D> {
init <A: A where A.B == D>(e: A.B) {
}
}
| apache-2.0 | 4444c8e9aefb9ff3303efebc3e04c053 | 14.542484 | 87 | 0.445753 | 2.404449 | false | false | false | false |
LarsStegman/helios-for-reddit | Sources/Model/Subreddit/Header.swift | 1 | 609 | //
// Header.swift
// Helios
//
// Created by Lars Stegman on 02-01-17.
// Copyright © 2017 Stegman. All rights reserved.
//
import Foundation
public struct Header: Decodable, Equatable {
public let imageUrl: URL
public let size: CGSize
public let title: String
public static func ==(lhs: Header, rhs: Header) -> Bool {
return lhs.imageUrl == rhs.imageUrl && lhs.size == rhs.size && lhs.title == rhs.title
}
private enum CodingKeys: String, CodingKey {
case imageUrl = "header_img"
case size = "header_size"
case title = "header_title"
}
}
| mit | cf6f78a0eb07f32f9e4b53be3bf1476f | 23.32 | 93 | 0.631579 | 3.848101 | false | false | false | false |
ifabijanovic/swtor-holonet | ios/HoloNet/Module/Settings/UI/TextSizeSettingsTableViewController.swift | 1 | 2385 | //
// TextSizeSettingsTableViewController.swift
// SWTOR HoloNet
//
// Created by Ivan Fabijanovic on 14/07/15.
// Copyright (c) 2015 Ivan Fabijanović. All rights reserved.
//
import UIKit
class TextSizeSettingsTableViewController: BaseTableViewController {
private let themeManager: ThemeManager
private let pickerDelegate: SettingPickerDelegate<TextSize>
init(themeManager: ThemeManager, toolbox: Toolbox) {
self.themeManager = themeManager
let options: [SettingPickerOption<TextSize>] = [
SettingPickerOption(index: 0, value: .small),
SettingPickerOption(index: 1, value: .medium),
SettingPickerOption(index: 2, value: .large)
]
self.pickerDelegate = SettingPickerDelegate(options: options)
super.init(toolbox: toolbox, style: .plain)
}
// MARK: -
override func viewDidLoad() {
super.viewDidLoad()
self.title = NSLocalizedString("settings_text_size_label", comment: "")
}
// MARK: -
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return self.pickerDelegate.tableView(tableView, cellForRowAt: indexPath)
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let theme = self.theme else { return }
cell.apply(theme: theme)
cell.textLabel?.textColor = theme.contentText
cell.tintColor = theme.contentTitle
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.pickerDelegate.tableView(tableView, didSelectRowAtIndexPath: indexPath)
self.themeManager.set(textSize: self.pickerDelegate.currentValue, bundle: Bundle.main)
}
// MARK: -
override func apply(theme: Theme) {
super.apply(theme: theme)
self.tableView.separatorStyle = .none
self.tableView.backgroundColor = theme.contentBackground
self.pickerDelegate.select(item: theme.textSize, in: self.tableView)
}
}
| gpl-3.0 | 3f623af6eac136a64d8b1b2cd04a71cd | 32.577465 | 121 | 0.671141 | 4.935818 | false | false | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Characteristics/Characteristic.LockCurrentState.swift | 1 | 2133 | import Foundation
public extension AnyCharacteristic {
static func lockCurrentState(
_ value: Enums.LockCurrentState = .unsecured,
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Lock Current State",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 3,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.lockCurrentState(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func lockCurrentState(
_ value: Enums.LockCurrentState = .unsecured,
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Lock Current State",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 3,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<Enums.LockCurrentState> {
GenericCharacteristic<Enums.LockCurrentState>(
type: .lockCurrentState,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| mit | 7797a167300daf602bb93f84391f552a | 33.967213 | 67 | 0.591655 | 5.30597 | false | false | false | false |
hengZhuo/DouYuZhiBo | swift-DYZB/swift-DYZB/Classes/Home/Controller/FunnyController.swift | 1 | 4014 | //
// FunnyController.swift
// swift-DYZB
//
// Created by chenrin on 2016/11/22.
// Copyright © 2016年 zhuoheng. All rights reserved.
//
import UIKit
private let kItemMargin : CGFloat = 10
private let kItemW = (kScreenW - 3 * kItemMargin) / 2
private let kItemH = kItemW * 3 / 4
private let kBeautifulItemH = kItemW * 4 / 3
private let kCollectionCell = "kCollectionCell"
private let kBeautifulCell = "kBeautifulCell"
private let kHeaderViewH : CGFloat = 50
private let kHeaderViewID = "kHeaderViewID"
private let kCycleViewH = kScreenW * 3 / 8
class FunnyController: BaseController {
fileprivate lazy var funnyViewModel:FunnyViewModel = FunnyViewModel()
fileprivate lazy var collectionView: UICollectionView = {
//1.创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
//设置组的内边距
layout.sectionInset = UIEdgeInsetsMake(0, kItemMargin, 0, 10)
layout.headerReferenceSize = .zero
//2.创建UICollectionView
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.showsHorizontalScrollIndicator = true
collectionView.showsVerticalScrollIndicator = true
collectionView.register((UINib(nibName: "CollectionHeaderView", bundle: nil)),forSupplementaryViewOfKind:UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil),forCellWithReuseIdentifier:kCollectionCell)
collectionView.register(UINib(nibName: "CollectionBeautifulCell", bundle: nil),forCellWithReuseIdentifier:kBeautifulCell)
//大小随着父控件拉伸而拉伸
collectionView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
// MARK:- 设置UI
extension FunnyController{
fileprivate func setupUI(){
view.backgroundColor = UIColor.white
view.addSubview(collectionView)
collectionView.contentInset = UIEdgeInsetsMake(8, 0, 0, 0)
collectionView.isHidden = true
}
}
extension FunnyController{
fileprivate func loadData(){
funnyViewModel.loadFunnyData {
self.collectionView.reloadData()
self.collectionView.isHidden = false
self.stopAnimImageView()
}
}
}
// MARK:- UICollectionViewDelegate协议
extension FunnyController:UICollectionViewDelegate,UICollectionViewDataSource{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return funnyViewModel.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return funnyViewModel.anchorGroups[section].anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCollectionCell, for: indexPath) as! CollectionNormalCell
cell.anchor = funnyViewModel.anchorGroups[indexPath.section].anchors[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//1.取出headerveiw
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView
return headerView
}
}
| mit | e2128c6d95c7ddba4daa73853aa7aa3e | 37.339806 | 186 | 0.717397 | 5.649499 | false | false | false | false |
dvor/Antidote | Antidote/FriendListCellModel.swift | 2 | 533 | // 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 FriendListCellModel: BaseCellModel {
var avatar: UIImage?
var topText: String = ""
var bottomText: String = ""
var multilineBottomtext: Bool = false
var accessibilityLabel = ""
var accessibilityValue = ""
var status: UserStatus = .offline
var hideStatus: Bool = false
}
| mit | 18bcfb9f2a3500b1eab6c38984ebd53b | 27.052632 | 70 | 0.694184 | 4.164063 | false | false | false | false |
emaloney/CleanroomText | Sources/StringTrimExtension.swift | 1 | 1565 | //
// StringTrimExtension.swift
// Cleanroom Project
//
// Created by Evan Maloney on 2/19/15.
// Copyright © 2015 Gilt Groupe. All rights reserved.
//
import Foundation
/**
A `String` extension that adds a `trim()` function for removing leading and
trailing whitespace.
*/
public extension String
{
/**
Returns a version of the receiver with whitespace and newline characters
removed from the beginning and end of the string.
- returns: A trimmed version of the receiver.
*/
public func trim()
-> String
{
return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
/**
A `NSAttributedString` extension that adds a `trim()` function for removing
leading and trailing whitespace.
*/
public extension NSAttributedString
{
/**
Returns a version of the receiver with whitespace and newline characters
removed from the beginning and end of the string.
- returns: A trimmed version of the receiver.
*/
public func trim()
-> NSAttributedString
{
let doNotTrim = CharacterSet.whitespacesAndNewlines.inverted
let operateOn = string as NSString
let startRange = operateOn.rangeOfCharacter(from: doNotTrim)
let endRange = operateOn.rangeOfCharacter(from: doNotTrim, options: .backwards)
let start = (startRange.length > 0) ? startRange.location : 0
let end = (endRange.length > 0) ? NSMaxRange(endRange) : operateOn.length
return attributedSubstring(from: NSMakeRange(start, end - start))
}
}
| mit | beabaaea6bcc9e658bb4acc7ec6696c0 | 26.928571 | 87 | 0.68798 | 4.696697 | false | false | false | false |
hsuanan/Mr-Ride-iOS | Mr-Ride/Controller/NewRecordNavigationController.swift | 1 | 1351 | //
// NewRecordNavigationController.swift
// Mr-Ride
//
// Created by Hsin An Hsu on 5/23/16.
// Copyright © 2016 AppWorks School HsinAn Hsu. All rights reserved.
//
import UIKit
class NewRecordNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
setupNewRecordNavigationBar()
}
func setupNewRecordNavigationBar(){
navigationBar.translucent = false
//change status bar color to white
navigationBar.barStyle = UIBarStyle.Black
//setup Date
let todayDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd"
let dateString = dateFormatter.stringFromDate(todayDate)
navigationBar.topItem?.title = "\(dateString)"
navigationBar.barTintColor = UIColor.mrLightblueColor()
navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
navigationBar.topItem?.leftBarButtonItem?.title = "Cancel"
navigationBar.topItem?.leftBarButtonItem?.tintColor = UIColor.whiteColor()
navigationBar.topItem?.rightBarButtonItem?.title = "Finish"
navigationBar.topItem?.rightBarButtonItem?.tintColor = UIColor.whiteColor()
}
}
| mit | 03cb493f2c24cd261ecfcb0945da2cf1 | 28.347826 | 98 | 0.665185 | 5.60166 | false | false | false | false |
vakoc/particle-swift-cli | Sources/Device Commands.swift | 1 | 13538 | // This source file is part of the vakoc.com open source project(s)
//
// Copyright © 2016 Mark Vakoc. All rights reserved.
// Licensed under Apache License v2.0
//
// See http://www.vakoc.com/LICENSE.txt for license information
import Foundation
import ParticleSwift
import Dispatch
let optionalDevicesIDSArgument = Argument(name: .deviceids, helpText: "Device IDs (comma separated)", options: [.hasValue])
let optionalVariableNamesArgument = Argument(name: .variables, helpText: "Variable(s) (comma separated)", options: [.hasValue])
let optionalDetailArgument = Argument(name: .detail, helpText: "Include detailed results", options: [])
let deviceIDArgument = Argument(name: .deviceid, helpText: "Device ID", options: [.required, .hasValue])
let optionalIMEIArgument = Argument(name: .imei, helpText: "IMEI number of the Electron you are generating a claim for. This will be used as the claim code if iccid is not specified.", options: [.hasValue])
let optionalICCIDArgument = Argument(name: .iccid, helpText: "ICCID number (SIM card ID number) of the SIM you are generating a claim for. This will be used as the claim code.", options: [.hasValue])
let functionNameArgument = Argument(name: .functionName, helpText: "Function Name", options: [.required, .hasValue])
let optionalParamArgument = Argument(name: .param, helpText: "Function Parameter", options: [.hasValue])
let devicesCommand = Command(name: .devices, summary: "Print a summary of each device", arguments: [], subHelp: nil) {(arguments, extras, callback) in
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
particleCloud.devices() { (result) in
switch (result) {
case .success(let devices):
let stringValue = "\(devices)"
callback( .success(string: stringValue, json: devices.map { $0.dictionary} ))
case .failure(let err):
callback( .failure(Errors.devicesFailed(err)))
}
}
}
let deviceDetail = Command(name: .deviceDetail, summary: "Print a detail information for a device", arguments: [deviceIDArgument], subHelp: nil) {(arguments, extras, callback) in
guard let deviceID = arguments[deviceIDArgument] else {
callback( .failure(Errors.invalidDeviceID))
return
}
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
particleCloud.deviceDetailInformation(deviceID) { (result) in
switch (result) {
case .success(let deviceDetail):
let stringValue = "\(deviceDetail)"
callback( .success(string: stringValue, json: deviceDetail.dictionary ))
case .failure(let err):
callback( .failure(Errors.devicesFailed(err)))
}
}
}
private let variablesCommandSubHelp = "Retrieves the value of the requested variable(s) from the requested device(s). If the list of variables isn't provided, all variables will be returned for each device. If the device(s) aren't provided all available devices will be queried.\n\nThis results in multiple web service invocations unless both the device ids and variable names are provided. Devices need not have the same exposed variables.\n\n"
let variablesCommand = Command(name: .variables, summary: "Retrieve variable value(s) from device(s)", arguments: [optionalDevicesIDSArgument, optionalVariableNamesArgument, optionalDetailArgument], subHelp: variablesCommandSubHelp) {(arguments, extras, callback) in
let group = DispatchGroup()
var results = [String : [String : Any]]()
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
let variables = arguments[optionalVariableNamesArgument]?.components(separatedBy: ",") ?? []
let devices = arguments[optionalDevicesIDSArgument]?.components(separatedBy: ",") ?? []
let getVariableNames = { (deviceID: String) in
group.enter()
particleCloud.deviceDetailInformation(deviceID) { (result) in
switch (result) {
case .success(let deviceDetailInfo):
for variable in deviceDetailInfo.variables.keys {
group.enter()
particleCloud.variableValue(variable, deviceID: deviceID) { (result) in
switch (result) {
case .success(let variableDict):
var dict = results[deviceID] ?? [:]
if arguments[optionalDetailArgument] != nil {
dict[variable] = variableDict
} else {
dict[variable] = variableDict["result"]
}
results[deviceID] = dict
case .failure(let error):
warn("Failed to obtain variable \(variable) for device \(deviceID)")
}
group.leave()
}
}
trace("\(deviceDetailInfo)")
case .failure(let error):
warn("\(error)")
}
group.leave()
}
}
let deviceInfos = { (devices: [String]) in
for device in devices {
results[device] = [String : AnyObject]()
if variables.isEmpty {
getVariableNames(device)
} else {
for variable in variables {
group.enter()
particleCloud.variableValue(variable, deviceID: device) { (result) in
switch (result) {
case .success(let variableDict):
var dict = results[device] ?? [:]
if arguments[optionalDetailArgument] != nil {
dict[variable] = variableDict
} else {
dict[variable] = variableDict["result"]
}
results[device] = dict
case .failure(let error):
warn("Failed to obtain variable \(variable) for device \(device)")
}
group.leave()
}
}
}
}
}
group.enter()
group.notify(queue: DispatchQueue.main) {
callback( .success(string: "\(results)", json: results))
}
if devices.isEmpty {
particleCloud.devices() { (result) in
switch (result) {
case .success(let devices):
if devices.isEmpty {
callback( .success(string: "No devices found", json: []))
} else {
deviceInfos(devices.map { $0.deviceID } )
}
case .failure(let err):
callback( .failure(Errors.devicesFailed(err)))
}
group.leave()
}
} else {
deviceInfos(devices)
group.leave()
}
}
let claimDeviceCommand = Command(name: .claimDevice, summary: "Claim a new or unclaimed device to your account", arguments: [deviceIDArgument], subHelp: nil) {(arguments, extras, callback) in
guard let deviceID = arguments[deviceIDArgument] else {
return callback( .failure(Errors.invalidDeviceID))
}
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
particleCloud.claim(deviceID) { (result) in
switch (result) {
case .failure(let err):
error("Failed to claim device \(deviceID) with error \(err)")
callback( .failure(err))
case .success(let result):
callback( .success(string: "Claimed device \(deviceID)", json: ["result" : "success"]))
}
}
}
let unclaimDeviceCommand = Command(name: .unclaimDevice, summary: "Remove ownership of a device. This will unclaim regardless if the device is owned by a user or a customer.", arguments: [deviceIDArgument], subHelp: nil){ (arguments, extras, callback) in
guard let deviceID = arguments[deviceIDArgument] else {
return callback( .failure(Errors.invalidDeviceID))
}
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
particleCloud.unclaim(deviceID) { (result) in
switch (result) {
case .failure(let err):
error("Failed to claim device \(deviceID) with error \(err)")
callback( .failure(err))
case .success(let result):
callback( .success(string: "Unclaimed device \(deviceID)", json: result))
}
}
}
let transferDeviceCommand = Command(name: .transferDevice, summary: "Request device transfer from another user", arguments: [deviceIDArgument], subHelp: nil) {(arguments, extras, callback) in
guard let deviceID = arguments[deviceIDArgument] else {
return callback( .failure(Errors.invalidDeviceID))
}
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
particleCloud.transfer(deviceID) { (result) in
switch (result) {
case .failure(let err):
error("Failed to transfer device \(deviceID) with error \(err)")
callback( .failure(err))
case .success(let result):
callback( .success(string: "Transfer device \(deviceID)", json: ["result" : "success"]))
}
}
}
let createClaimCodeCommand = Command(name: .createClaimCode, summary: "Generate a device claim code", arguments: [optionalIMEIArgument, optionalICCIDArgument], subHelp: "Generate a device claim code that allows the device to be successfully claimed to a user's account during the SoftAP setup process") {(arguments, extras, callback) in
let imei = arguments[optionalIMEIArgument]
let iccid = arguments[optionalICCIDArgument]
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
particleCloud.createClaimCode(imei, iccid: iccid) { (result) in
switch (result) {
case .failure(let err):
error("Failed to create claim code with error \(err)")
callback( .failure(err))
case .success(let result):
callback( .success(string: "Created claim code \(result.claimCode) with devices \(result.deviceIDs)", json: result.dictionary))
}
}
}
private let callFunctionSubHelpText = "Invokes the specified function with the optional argument. Device(s) may be specified as comma separated device ids. If device ids are not specified all devices associated with the account that contain that function will be invoked. In this case multiple network requests are madea and will take longer to process."
let callFunctionCommand = Command(name: .callFunction, summary: "Call a function on device(s)", arguments: [functionNameArgument, optionalParamArgument], subHelp: callFunctionSubHelpText) { (arguments, extras, callback) in
let group = DispatchGroup()
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
var results = [String : [String : Any]]()
guard let function = arguments[functionNameArgument] else {
// todo
return
}
let param = arguments[optionalParamArgument]
let devices = arguments[optionalDevicesIDSArgument]?.components(separatedBy: ",") ?? []
let getFunctionNames = { (deviceID: String) in
group.enter()
particleCloud.deviceDetailInformation(deviceID) { (result) in
switch (result) {
case .success(let deviceDetailInfo):
if deviceDetailInfo.functions.contains(function) {
group.enter()
particleCloud.callFunction(function, deviceID: deviceID, argument: param) { (result) in
switch result {
case .success(let dict):
results[deviceID] = dict
case .failure(let error):
warn("Failed to call function \(function) on device \(deviceID) with error \(error)")
}
group.leave()
}
} else {
trace("Skipping device \(deviceID) as it does not support function \(function)")
}
case .failure(let error):
warn("\(error)")
}
group.leave()
}
}
let deviceInfos = { (devices: [String]) in
for device in devices {
results[device] = [String : AnyObject]()
getFunctionNames(device)
}
}
group.enter()
group.notify(queue: DispatchQueue.main) {
callback( .success(string: "\(results)", json: results))
}
if devices.isEmpty {
particleCloud.devices() { (result) in
switch (result) {
case .success(let devices):
if devices.isEmpty {
callback( .success(string: "No devices found", json: []))
} else {
deviceInfos(devices.map { $0.deviceID } )
}
case .failure(let err):
callback( .failure(Errors.devicesFailed(err)))
}
group.leave()
}
} else {
deviceInfos(devices)
group.leave()
}
}
| apache-2.0 | d4cdc8360123d8621125bc2ab61e4ff6 | 41.974603 | 448 | 0.594371 | 4.834643 | false | false | false | false |
rnine/AMCoreAudio | Tests/SimplyCoreAudioTests/AudioDeviceTests.swift | 1 | 21494 | import XCTest
@testable import SimplyCoreAudio
final class AudioDeviceTests: XCTestCase {
let defaultOutputDevice = AudioDevice.defaultOutputDevice()
let defaultInputDevice = AudioDevice.defaultInputDevice()
let defaultSystemOutputDevice = AudioDevice.defaultSystemOutputDevice()
override func setUp() {
super.setUp()
ResetDefaultDevices()
try? ResetDeviceState()
}
override func tearDown() {
super.tearDown()
ResetDefaultDevices()
try? ResetDeviceState()
}
func testDeviceLookUp() throws {
let device = try GetDevice()
let deviceUID = try XCTUnwrap(device.uid)
XCTAssertEqual(AudioDevice.lookup(by: device.id), device)
XCTAssertEqual(AudioDevice.lookup(by: deviceUID), device)
}
func testDeviceEnumeration() throws {
let device = try GetDevice()
XCTAssertTrue(AudioDevice.allDevices().contains(device))
XCTAssertTrue(AudioDevice.allDeviceIDs().contains(device.id))
XCTAssertTrue(AudioDevice.allInputDevices().contains(device))
XCTAssertTrue(AudioDevice.allOutputDevices().contains(device))
}
func testSettingDefaultDevice() throws {
let device = try GetDevice()
XCTAssertTrue(device.setAsDefaultSystemDevice())
XCTAssertEqual(AudioDevice.defaultSystemOutputDevice(), device)
XCTAssertTrue(device.setAsDefaultOutputDevice())
XCTAssertEqual(AudioDevice.defaultOutputDevice(), device)
XCTAssertTrue(device.setAsDefaultInputDevice())
XCTAssertEqual(AudioDevice.defaultInputDevice(), device)
}
func testGeneralDeviceInformation() throws {
let device = try GetDevice()
XCTAssertEqual(device.name, "Null Audio Device")
XCTAssertEqual(device.manufacturer, "Apple Inc.")
XCTAssertEqual(device.uid, "NullAudioDevice_UID")
XCTAssertEqual(device.modelUID, "NullAudioDevice_ModelUID")
XCTAssertEqual(device.configurationApplication, "com.apple.audio.AudioMIDISetup")
XCTAssertEqual(device.transportType, TransportType.virtual)
XCTAssertFalse(device.isInputOnlyDevice())
XCTAssertFalse(device.isOutputOnlyDevice())
XCTAssertFalse(device.isHidden())
XCTAssertNil(device.isJackConnected(direction: .playback))
XCTAssertNil(device.isJackConnected(direction: .recording))
XCTAssertTrue(device.isAlive())
XCTAssertFalse(device.isRunning())
XCTAssertFalse(device.isRunningSomewhere())
XCTAssertNil(device.name(channel: 0, direction: .playback))
XCTAssertNil(device.name(channel: 1, direction: .playback))
XCTAssertNil(device.name(channel: 2, direction: .playback))
XCTAssertNil(device.name(channel: 0, direction: .recording))
XCTAssertNil(device.name(channel: 1, direction: .recording))
XCTAssertNil(device.name(channel: 2, direction: .recording))
XCTAssertNotNil(device.ownedObjectIDs())
XCTAssertNotNil(device.controlList())
XCTAssertNotNil(device.relatedDevices())
}
func testLFE() throws {
let device = try GetDevice()
XCTAssertNil(device.shouldOwniSub)
device.shouldOwniSub = true
XCTAssertNil(device.shouldOwniSub)
XCTAssertNil(device.lfeMute)
device.lfeMute = true
XCTAssertNil(device.lfeMute)
XCTAssertNil(device.lfeVolume)
device.lfeVolume = 1.0
XCTAssertNil(device.lfeVolume)
XCTAssertNil(device.lfeVolumeDecibels)
device.lfeVolumeDecibels = 6.0
XCTAssertNil(device.lfeVolumeDecibels)
}
func testInputOutputLayout() throws {
let device = try GetDevice()
XCTAssertEqual(device.layoutChannels(direction: .playback), 2)
XCTAssertEqual(device.layoutChannels(direction: .recording), 2)
XCTAssertEqual(device.channels(direction: .playback), 2)
XCTAssertEqual(device.channels(direction: .recording), 2)
XCTAssertFalse(device.isInputOnlyDevice())
XCTAssertFalse(device.isOutputOnlyDevice())
}
func testVolumeInfo() throws {
let device = try GetDevice()
var volumeInfo: VolumeInfo!
XCTAssertTrue(device.setMute(false, channel: 0, direction: .playback))
volumeInfo = try XCTUnwrap(device.volumeInfo(channel: 0, direction: .playback))
XCTAssertEqual(volumeInfo.hasVolume, true)
XCTAssertEqual(volumeInfo.canSetVolume, true)
XCTAssertEqual(volumeInfo.canMute, true)
XCTAssertEqual(volumeInfo.isMuted, false)
XCTAssertEqual(volumeInfo.canPlayThru, false)
XCTAssertEqual(volumeInfo.isPlayThruSet, false)
XCTAssertTrue(device.setVolume(0, channel: 0, direction: .playback))
volumeInfo = try XCTUnwrap(device.volumeInfo(channel: 0, direction: .playback))
XCTAssertEqual(volumeInfo.volume, 0)
XCTAssertTrue(device.setVolume(0.5, channel: 0, direction: .playback))
volumeInfo = try XCTUnwrap(device.volumeInfo(channel: 0, direction: .playback))
XCTAssertEqual(volumeInfo.volume, 0.5)
XCTAssertNil(device.volumeInfo(channel: 1, direction: .playback))
XCTAssertNil(device.volumeInfo(channel: 2, direction: .playback))
XCTAssertNil(device.volumeInfo(channel: 3, direction: .playback))
XCTAssertNil(device.volumeInfo(channel: 4, direction: .playback))
XCTAssertNotNil(device.volumeInfo(channel: 0, direction: .recording))
XCTAssertNil(device.volumeInfo(channel: 1, direction: .recording))
XCTAssertNil(device.volumeInfo(channel: 2, direction: .recording))
XCTAssertNil(device.volumeInfo(channel: 3, direction: .recording))
XCTAssertNil(device.volumeInfo(channel: 4, direction: .recording))
}
func testVolume() throws {
let device = try GetDevice()
// Playback direction
XCTAssertTrue(device.setVolume(0, channel: 0, direction: .playback))
XCTAssertEqual(device.volume(channel: 0, direction: .playback), 0)
XCTAssertTrue(device.setVolume(0.5, channel: 0, direction: .playback))
XCTAssertEqual(device.volume(channel: 0, direction: .playback), 0.5)
XCTAssertFalse(device.setVolume(0.5, channel: 1, direction: .playback))
XCTAssertNil(device.volume(channel: 1, direction: .playback))
XCTAssertFalse(device.setVolume(0.5, channel: 2, direction: .playback))
XCTAssertNil(device.volume(channel: 2, direction: .playback))
// Recording direction
XCTAssertTrue(device.setVolume(0, channel: 0, direction: .recording))
XCTAssertEqual(device.volume(channel: 0, direction: .recording), 0)
XCTAssertTrue(device.setVolume(0.5, channel: 0, direction: .recording))
XCTAssertEqual(device.volume(channel: 0, direction: .recording), 0.5)
XCTAssertFalse(device.setVolume(0.5, channel: 1, direction: .recording))
XCTAssertNil(device.volume(channel: 1, direction: .recording))
XCTAssertFalse(device.setVolume(0.5, channel: 2, direction: .recording))
XCTAssertNil(device.volume(channel: 2, direction: .recording))
}
func testVolumeInDecibels() throws {
let device = try GetDevice()
// Playback direction
XCTAssertTrue(device.canSetVolume(channel: 0, direction: .playback))
XCTAssertTrue(device.setVolume(0, channel: 0, direction: .playback))
XCTAssertEqual(device.volumeInDecibels(channel: 0, direction: .playback), -96)
XCTAssertTrue(device.setVolume(0.5, channel: 0, direction: .playback))
XCTAssertEqual(device.volumeInDecibels(channel: 0, direction: .playback), -70.5)
XCTAssertFalse(device.canSetVolume(channel: 1, direction: .playback))
XCTAssertFalse(device.setVolume(0.5, channel: 1, direction: .playback))
XCTAssertNil(device.volumeInDecibels(channel: 1, direction: .playback))
XCTAssertFalse(device.canSetVolume(channel: 2, direction: .playback))
XCTAssertFalse(device.setVolume(0.5, channel: 2, direction: .playback))
XCTAssertNil(device.volumeInDecibels(channel: 2, direction: .playback))
// Recording direction
XCTAssertTrue(device.canSetVolume(channel: 0, direction: .recording))
XCTAssertTrue(device.setVolume(0, channel: 0, direction: .recording))
XCTAssertEqual(device.volumeInDecibels(channel: 0, direction: .recording), -96)
XCTAssertTrue(device.setVolume(0.5, channel: 0, direction: .recording))
XCTAssertEqual(device.volumeInDecibels(channel: 0, direction: .recording), -70.5)
XCTAssertFalse(device.canSetVolume(channel: 1, direction: .recording))
XCTAssertFalse(device.setVolume(0.5, channel: 1, direction: .recording))
XCTAssertNil(device.volumeInDecibels(channel: 1, direction: .recording))
XCTAssertFalse(device.canSetVolume(channel: 2, direction: .recording))
XCTAssertFalse(device.setVolume(0.5, channel: 2, direction: .recording))
XCTAssertNil(device.volumeInDecibels(channel: 2, direction: .recording))
}
func testMute() throws {
let device = try GetDevice()
// Playback direction
XCTAssertTrue(device.canMute(channel: 0, direction: .playback))
XCTAssertTrue(device.setMute(true, channel: 0, direction: .playback))
XCTAssertEqual(device.isMuted(channel: 0, direction: .playback), true)
XCTAssertTrue(device.setMute(false, channel: 0, direction: .playback))
XCTAssertEqual(device.isMuted(channel: 0, direction: .playback), false)
XCTAssertFalse(device.canMute(channel: 1, direction: .playback))
XCTAssertFalse(device.setMute(true, channel: 1, direction: .playback))
XCTAssertNil(device.isMuted(channel: 1, direction: .playback))
XCTAssertFalse(device.canMute(channel: 2, direction: .playback))
XCTAssertFalse(device.setMute(true, channel: 2, direction: .playback))
XCTAssertNil(device.isMuted(channel: 2, direction: .playback))
// Recording direction
XCTAssertTrue(device.canMute(channel: 0, direction: .recording))
XCTAssertTrue(device.setMute(true, channel: 0, direction: .recording))
XCTAssertEqual(device.isMuted(channel: 0, direction: .recording), true)
XCTAssertTrue(device.setMute(false, channel: 0, direction: .recording))
XCTAssertEqual(device.isMuted(channel: 0, direction: .recording), false)
XCTAssertFalse(device.canMute(channel: 1, direction: .recording))
XCTAssertFalse(device.setMute(true, channel: 1, direction: .recording))
XCTAssertNil(device.isMuted(channel: 1, direction: .recording))
XCTAssertFalse(device.canMute(channel: 2, direction: .recording))
XCTAssertFalse(device.setMute(true, channel: 2, direction: .recording))
XCTAssertNil(device.isMuted(channel: 2, direction: .recording))
}
func testMasterChannelMute() throws {
let device = try GetDevice()
XCTAssertEqual(device.canMuteMasterChannel(direction: .playback), true)
XCTAssertTrue(device.setMute(false, channel: 0, direction: .playback))
XCTAssertEqual(device.isMasterChannelMuted(direction: .playback), false)
XCTAssertTrue(device.setMute(true, channel: 0, direction: .playback))
XCTAssertEqual(device.isMasterChannelMuted(direction: .playback), true)
XCTAssertEqual(device.canMuteMasterChannel(direction: .recording), true)
XCTAssertTrue(device.setMute(false, channel: 0, direction: .recording))
XCTAssertEqual(device.isMasterChannelMuted(direction: .recording), false)
XCTAssertTrue(device.setMute(true, channel: 0, direction: .recording))
XCTAssertEqual(device.isMasterChannelMuted(direction: .recording), true)
}
func testPreferredChannelsForStereo() throws {
let device = try GetDevice()
var preferredChannels = try XCTUnwrap(device.preferredChannelsForStereo(direction: .playback))
XCTAssertEqual(preferredChannels.left, 1)
XCTAssertEqual(preferredChannels.right, 2)
XCTAssertTrue(device.setPreferredChannelsForStereo(channels: StereoPair(left: 1, right: 1), direction: .playback))
preferredChannels = try XCTUnwrap(device.preferredChannelsForStereo(direction: .playback))
XCTAssertEqual(preferredChannels.left, 1)
XCTAssertEqual(preferredChannels.right, 1)
XCTAssertTrue(device.setPreferredChannelsForStereo(channels: StereoPair(left: 2, right: 2), direction: .playback))
preferredChannels = try XCTUnwrap(device.preferredChannelsForStereo(direction: .playback))
XCTAssertEqual(preferredChannels.left, 2)
XCTAssertEqual(preferredChannels.right, 2)
XCTAssertTrue(device.setPreferredChannelsForStereo(channels: StereoPair(left: 1, right: 2), direction: .playback))
preferredChannels = try XCTUnwrap(device.preferredChannelsForStereo(direction: .playback))
XCTAssertEqual(preferredChannels.left, 1)
XCTAssertEqual(preferredChannels.right, 2)
}
func testVirtualMasterChannels() throws {
let device = try GetDevice()
XCTAssertTrue(device.canSetVirtualMasterVolume(direction: .playback))
XCTAssertTrue(device.canSetVirtualMasterVolume(direction: .recording))
XCTAssertTrue(device.setVirtualMasterVolume(0.0, direction: .playback))
XCTAssertEqual(device.virtualMasterVolume(direction: .playback), 0.0)
XCTAssertEqual(device.virtualMasterVolumeInDecibels(direction: .playback), -96.0)
XCTAssertTrue(device.setVirtualMasterVolume(0.5, direction: .playback))
XCTAssertEqual(device.virtualMasterVolume(direction: .playback), 0.5)
XCTAssertEqual(device.virtualMasterVolumeInDecibels(direction: .playback), -70.5)
XCTAssertTrue(device.setVirtualMasterVolume(0.0, direction: .recording))
XCTAssertEqual(device.virtualMasterVolume(direction: .recording), 0.0)
XCTAssertEqual(device.virtualMasterVolumeInDecibels(direction: .recording), -96.0)
XCTAssertTrue(device.setVirtualMasterVolume(0.5, direction: .recording))
XCTAssertEqual(device.virtualMasterVolume(direction: .recording), 0.5)
XCTAssertEqual(device.virtualMasterVolumeInDecibels(direction: .recording), -70.5)
}
func testVirtualMasterBalance() throws {
let device = try GetDevice()
XCTAssertFalse(device.setVirtualMasterBalance(0.0, direction: .playback))
XCTAssertNil(device.virtualMasterBalance(direction: .playback))
XCTAssertFalse(device.setVirtualMasterBalance(0.0, direction: .recording))
XCTAssertNil(device.virtualMasterBalance(direction: .recording))
}
func testSampleRate() throws {
let device = try GetDevice()
XCTAssertEqual(device.nominalSampleRates(), [44100, 48000])
XCTAssertTrue(device.setNominalSampleRate(44100))
sleep(1)
XCTAssertEqual(device.nominalSampleRate(), 44100)
XCTAssertEqual(device.actualSampleRate(), 44100)
XCTAssertTrue(device.setNominalSampleRate(48000))
sleep(1)
XCTAssertEqual(device.nominalSampleRate(), 48000)
XCTAssertEqual(device.actualSampleRate(), 48000)
}
func testDataSource() throws {
let device = try GetDevice()
XCTAssertNotNil(device.dataSource(direction: .playback))
XCTAssertNotNil(device.dataSource(direction: .recording))
}
func testDataSources() throws {
let device = try GetDevice()
XCTAssertNotNil(device.dataSources(direction: .playback))
XCTAssertNotNil(device.dataSources(direction: .recording))
}
func testDataSourceName() throws {
let device = try GetDevice()
XCTAssertEqual(device.dataSourceName(dataSourceID: 0, direction: .playback), "Data Source Item 0")
XCTAssertEqual(device.dataSourceName(dataSourceID: 1, direction: .playback), "Data Source Item 1")
XCTAssertEqual(device.dataSourceName(dataSourceID: 2, direction: .playback), "Data Source Item 2")
XCTAssertEqual(device.dataSourceName(dataSourceID: 3, direction: .playback), "Data Source Item 3")
XCTAssertNil(device.dataSourceName(dataSourceID: 4, direction: .playback))
XCTAssertEqual(device.dataSourceName(dataSourceID: 0, direction: .recording), "Data Source Item 0")
XCTAssertEqual(device.dataSourceName(dataSourceID: 1, direction: .recording), "Data Source Item 1")
XCTAssertEqual(device.dataSourceName(dataSourceID: 2, direction: .recording), "Data Source Item 2")
XCTAssertEqual(device.dataSourceName(dataSourceID: 3, direction: .recording), "Data Source Item 3")
XCTAssertNil(device.dataSourceName(dataSourceID: 4, direction: .recording))
}
func testClockSource() throws {
let device = try GetDevice()
XCTAssertNil(device.clockSourceID())
XCTAssertNil(device.clockSourceIDs())
XCTAssertNil(device.clockSourceName())
XCTAssertNil(device.clockSourceNames())
XCTAssertNil(device.clockSourceName(clockSourceID: 0))
XCTAssertFalse(device.setClockSourceID(0))
}
func testLatency() throws {
let device = try GetDevice()
XCTAssertEqual(device.latency(direction: .playback), 0)
XCTAssertEqual(device.latency(direction: .recording), 0)
}
func testSafetyOffset() throws {
let device = try GetDevice()
XCTAssertEqual(device.safetyOffset(direction: .playback), 0)
XCTAssertEqual(device.safetyOffset(direction: .recording), 0)
}
func testHogMode() throws {
let device = try GetDevice()
XCTAssertEqual(device.hogModePID(), -1)
XCTAssertTrue(device.setHogMode())
XCTAssertEqual(device.hogModePID(), pid_t(ProcessInfo.processInfo.processIdentifier))
XCTAssertTrue(device.unsetHogMode())
XCTAssertEqual(device.hogModePID(), -1)
}
func testVolumeConversion() throws {
let device = try GetDevice()
XCTAssertEqual(device.scalarToDecibels(volume: 0, channel: 0, direction: .playback), -96.0)
XCTAssertEqual(device.scalarToDecibels(volume: 1, channel: 0, direction: .playback), 6.0)
XCTAssertEqual(device.decibelsToScalar(volume: -96.0, channel: 0, direction: .playback), 0)
XCTAssertEqual(device.decibelsToScalar(volume: 6.0, channel: 0, direction: .playback), 1)
}
func testStreams() throws {
let device = try GetDevice()
XCTAssertNotNil(device.streams(direction: .playback))
XCTAssertNotNil(device.streams(direction: .recording))
}
func testCreateAndDestroyAggregateDevice() {
let inputs = AudioDevice.allNonAggregateDevices().filter {
$0.channels(direction: .recording) > 0
}
let outputs = AudioDevice.allNonAggregateDevices().filter {
$0.channels(direction: .playback) > 0
}
guard let input = inputs.first?.uid,
let output = outputs.first?.uid
else {
XCTFail("Failed to find an input and output to use")
return
}
guard let device = AudioDevice.createAggregateDevice(masterDeviceUID: output,
secondDeviceUID: input,
named: "testCreateAggregateAudioDevice",
uid: "testCreateAggregateAudioDevice-12345")
else {
XCTFail("Failed creating device")
return
}
XCTAssertTrue(device.isAggregateDevice())
XCTAssertTrue(device.ownedAggregateDevices()?.count == 2)
wait(for: 2)
let error = AudioDevice.removeAggregateDevice(id: device.id)
XCTAssertTrue(error == noErr, "Failed removing device")
wait(for: 2)
}
// MARK: - Private Functions
private func GetDevice(file: StaticString = #file, line: UInt = #line) throws -> AudioDevice {
return try XCTUnwrap(AudioDevice.lookup(by: "NullAudioDevice_UID"), "NullAudio driver is missing.", file: file, line: line)
}
private func ResetDefaultDevices() {
defaultOutputDevice?.setAsDefaultOutputDevice()
defaultInputDevice?.setAsDefaultInputDevice()
defaultSystemOutputDevice?.setAsDefaultSystemDevice()
}
private func ResetDeviceState() throws {
let device = try GetDevice()
device.unsetHogMode()
if device.nominalSampleRate() != 44100 {
device.setNominalSampleRate(44100)
sleep(1)
}
device.setPreferredChannelsForStereo(channels: StereoPair(left: 1, right: 2), direction: .playback)
device.setMute(false, channel: 0, direction: .playback)
device.setMute(false, channel: 0, direction: .recording)
device.setVolume(0.5, channel: 0, direction: .playback)
device.setVolume(0.5, channel: 0, direction: .recording)
device.setVirtualMasterVolume(0.5, direction: .playback)
device.setVirtualMasterVolume(0.5, direction: .recording)
}
private func wait(for interval: TimeInterval) {
let delayExpectation = XCTestExpectation(description: "delayExpectation")
DispatchQueue.main.asyncAfter(deadline: .now() + interval) {
delayExpectation.fulfill()
}
wait(for: [delayExpectation], timeout: interval + 1)
}
}
| mit | 52e7d5255401de923b93a721f1582378 | 42.510121 | 131 | 0.692379 | 4.56639 | false | true | false | false |
VladimirDinic/WDSideMenu | WDSideMenu/WDSideMenu/ViewControllers/SampleViewController.swift | 1 | 2255 | //
// SampleViewController.swift
// WDSideMenu
//
// Created by Vladimir Dinic on 2/19/17.
// Copyright © 2017 Vladimir Dinic. All rights reserved.
//
import UIKit
class SampleViewController: UIViewController {
@IBInspectable var headerTitle:String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.setupNavigation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupNavigation()
{
self.navigationItem.title = headerTitle
self.navigationItem.hidesBackButton = true
var barButton:UIBarButtonItem? = nil
if (self.navigationController?.viewControllers.count)! > 1
{
barButton = UIBarButtonItem(image: #imageLiteral(resourceName: "backArrow"), style: .plain, target: self, action: #selector(showMenuOrGoBack))
}
else
{
barButton = UIBarButtonItem(image: #imageLiteral(resourceName: "menuIcon"), style: .plain, target: self, action: #selector(showMenuOrGoBack))
}
barButton?.tintColor = UIColor(red: 0.0, green: 105.0/255.0, blue: 105.0/255.0, alpha: 1.0)
switch menuTypeConfig
{
case .LeftMenuAboveMainView, .LeftMenuBelowMainView, .LeftMenuStickedToMainView:
self.navigationItem.leftBarButtonItem = barButton
case .RightMenuAboveMainView, .RightMenuBelowMainView, .RightMenuStickedToMainView:
self.navigationItem.rightBarButtonItem = barButton
}
}
@objc func showMenuOrGoBack()
{
if let navigationController = self.navigationController as? MyNavigationController
{
navigationController.showMenuOrGoBack()
}
}
/*
// 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.
}
*/
}
| mit | 78a48b3bb155822d1d277ec7498e2fa0 | 31.2 | 154 | 0.658829 | 4.921397 | false | false | false | false |
mohamede1945/quran-ios | Quran/QariTableViewControllerCreator.swift | 2 | 2168 | //
// QariTableViewControllerCreator.swift
// Quran
//
// Created by Mohamed Afifi on 3/19/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import UIKit
class QariTableViewControllerCreator: NSObject, Creator, UIPopoverPresentationControllerDelegate {
private let qarisControllerCreator: AnyCreator<([Qari], Int), QariTableViewController>
init(qarisControllerCreator: AnyCreator<([Qari], Int), QariTableViewController>) {
self.qarisControllerCreator = qarisControllerCreator
}
func create(_ parameters: ([Qari], Int, UIView?)) -> QariTableViewController {
let controller = qarisControllerCreator.create(parameters.0, parameters.1)
controller.preferredContentSize = CGSize(width: 400, height: 500)
controller.modalPresentationStyle = .popover
controller.popoverPresentationController?.delegate = self
controller.popoverPresentationController?.sourceView = parameters.2
controller.popoverPresentationController?.sourceRect = parameters.2?.bounds ?? CGRect.zero
controller.popoverPresentationController?.permittedArrowDirections = .down
return controller
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .fullScreen
}
func presentationController(_ controller: UIPresentationController,
viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? {
return QariNavigationController(rootViewController: controller.presentedViewController)
}
}
| gpl-3.0 | 9ac06f3b51a8872a83c722669aa2b2dd | 42.36 | 130 | 0.745849 | 5.326781 | false | false | false | false |
coderMONSTER/ioscelebrity | YStar/YStar/Scenes/view/BenifityDetailCell.swift | 1 | 1700 | //
// BenifityDetailCell.swift
// YStar
//
// Created by MONSTER on 2017/7/13.
// Copyright © 2017年 com.yundian. All rights reserved.
//
import UIKit
class BenifityDetailCell: UITableViewCell {
@IBOutlet weak var timeImageVIew: UIImageView!
@IBOutlet weak var orderPriceImageView: UIImageView!
@IBOutlet weak var dealImageView: UIImageView!
@IBOutlet weak var dealLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var orderPriceLabel: UILabel!
// 设置BenifityDetailCell
func setBenifityDetail(model : EarningInfoModel) {
self.dealLabel.text = String.init(format: "%d", model.order_count)
self.timeLabel.text = String.init(format: "%d", model.order_num)
self.orderPriceLabel.text = String.init(format: "%.2f", model.price)
}
override func awakeFromNib() {
super.awakeFromNib()
self.dealImageView.image = UIImage.imageWith(AppConst.iconFontName.dealTotalIcon.rawValue, fontSize: dealImageView.frame.size, fontColor: UIColor.init(rgbHex: 0xFB9938))
self.timeImageVIew.image = UIImage.imageWith(AppConst.iconFontName.timeTotalIcon.rawValue, fontSize: timeImageVIew.frame.size, fontColor: UIColor.init(rgbHex: 0xFB9938))
self.orderPriceImageView.image = UIImage.imageWith(AppConst.iconFontName.priceTotalIcon.rawValue, fontSize: orderPriceImageView.frame.size, fontColor: UIColor.init(rgbHex: 0xFB9938))
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 3640febf5d7d76e5d880b7c0b4edcf9e | 32.196078 | 190 | 0.696397 | 4.211443 | false | false | false | false |
venticake/RetricaImglyKit-iOS | RetricaImglyKit/Classes/Frontend/Editor/Frame.swift | 1 | 7712 | // This file is part of the PhotoEditor Software Development Kit.
// Copyright (C) 2016 9elements GmbH <[email protected]>
// All rights reserved.
// Redistribution and use in source and binary forms, without
// modification, are permitted provided that the following license agreement
// is approved and a legal/financial contract was signed by the user.
// The license agreement can be found under the following link:
// https://www.photoeditorsdk.com/LICENSE.txt
import UIKit
/**
* The `Frame` class holds all informations needed to be managed and rendered.
*/
@available(iOS 8, *)
@objc(IMGLYFrame) public class Frame: NSObject {
/// The label of the frame. This is used for accessibility.
public var accessibilityText: String {
get {
return self.info.accessibilityText
}
}
private var ratioToImageMap = [Float : FrameContainer]()
private var ratioToThumbnailMap = [Float : FrameContainer]()
private var info = FrameInfoRecord()
/**
Returns a newly allocated instance of `Frame` using the given accessibility text.
- parameter accessibilityText: The accessibility text that describes this frame.
- returns: An instance of a `Frame`.
*/
public init(info: FrameInfoRecord) {
self.info = info
super.init()
buildURIMaps()
}
private func buildURIMaps() {
for imageInfo in info.imageInfos {
if let imageURL = NSURL(string: imageInfo.urlAtlas["mediaBase"]!) {
ratioToImageMap[imageInfo.ratio] = FrameContainer(url: imageURL)
}
if let thumbnailURL = NSURL(string: imageInfo.urlAtlas["mediaThumb"]!) {
ratioToThumbnailMap[imageInfo.ratio] = FrameContainer(url: thumbnailURL)
}
}
}
/**
Get a frame image matching the aspect ratio.
- parameter ratio: The desired ratio.
- parameter completionBlock: A completion block.
*/
public func imageForRatio(ratio: Float, completionBlock: (Image?, NSError?) -> ()) {
guard ratioToImageMap.count > 0 else {
return
}
var minDistance: Float = 99999.0
var nearestRatio: Float = 0.0
// if we dont have a nine patch image, seek for the closest possible
if ratioToImageMap[0.0] == nil {
for keyRatio in ratioToImageMap.keys {
let distance = abs(keyRatio - ratio)
if distance < minDistance {
minDistance = distance
nearestRatio = keyRatio
}
}
}
if let frameContainer = ratioToImageMap[nearestRatio] {
if let image = frameContainer.image {
completionBlock(image, nil)
} else if let url = frameContainer.url {
ImageStore.sharedStore.showSpinner = true
ImageStore.sharedStore.get(url) { (image, error) -> Void in
completionBlock(image, error)
}
}
}
}
/**
Get a frame thumbnail matching the aspect ratio.
- parameter ratio: The desired ratio.
- parameter completionBlock: A completion block.
*/
public func thumbnailForRatio(ratio: Float, completionBlock: (Image?, NSError?) -> ()) {
guard ratioToThumbnailMap.count > 0 else {
return
}
var minDistance: Float = 99999.0
var nearestRatio: Float = 0.0
for keyRatio in ratioToThumbnailMap.keys {
let distance = abs(keyRatio - ratio)
if distance < minDistance {
minDistance = distance
nearestRatio = keyRatio
}
}
if let frameContainer = ratioToThumbnailMap[nearestRatio] {
if let image = frameContainer.image {
completionBlock(image, nil)
} else if let url = frameContainer.url {
ImageStore.sharedStore.showSpinner = false
ImageStore.sharedStore.get(url) { (image, error) -> Void in
completionBlock(image, error)
}
}
}
}
/**
Add an image that is used as a frame for a ratio.
- parameter imageURL: The url of an image. This can either be in your bundle or remote.
- parameter ratio: An aspect ratio.
This method adds an url to an image to the frame which then loads its image and its thumbnail image from
an `NSURL` when needed. That image is then placed in a cache, that is purged when a memory warning is
received.
*/
public func addImageURL(imageURL: NSURL, ratio: Float) {
ratioToImageMap[ratio] = FrameContainer(url: imageURL)
}
/**
Add an thumbnail that is used as a frame for a ratio.
- parameter imageURL: The url of an image. This can either be in your bundle or remote.
- parameter ratio: An aspect ratio.
This method adds an url to an image to the frame which then loads its image and its thumbnail image from
an `NSURL` when needed. That image is then placed in a cache, that is purged when a memory warning is
received.
*/
public func addThumbnailURL(imageURL: NSURL, ratio: Float) {
ratioToThumbnailMap[ratio] = FrameContainer(url: imageURL)
}
/**
Add an image that is used as a frame for a ratio.
- parameter image: The image to use for this frame.
- parameter ratio: An aspect ratio.
This method adds an `UIImage` to a frame. This image is **not** placed in a cache by this SDK. If you choose to use this initializer,
then you should create the `UIImage`s that you pass with `init(named:)` or `init(named:inBundle:compatibleWithTraitCollection:)`,
so that they are added to the system cache and automatically purged when memory is low.
*/
public func addImage(image: UIImage, ratio: Float) {
ratioToImageMap[ratio] = FrameContainer(image: image)
}
/**
Add an thumbnail that is used as a frame for a ratio.
- parameter image: The image to use for this frame.
- parameter ratio: An aspect ratio.
This method adds an `UIImage` to a frame. This image is **not** placed in a cache by this SDK. If you choose to use this initializer,
then you should create the `UIImage`s that you pass with `init(named:)` or `init(named:inBundle:compatibleWithTraitCollection:)`,
so that they are added to the system cache and automatically purged when memory is low.
*/
public func addThumbnail(image: UIImage, ratio: Float) {
ratioToThumbnailMap[ratio] = FrameContainer(image: image)
}
// MARK: - NSObject
/**
:nodoc:
*/
public override func isEqual(object: AnyObject?) -> Bool {
guard let rhs = object as? Frame else {
return false
}
if accessibilityText != rhs.accessibilityText {
return false
}
if ratioToImageMap != rhs.ratioToImageMap {
return false
}
if ratioToThumbnailMap != rhs.ratioToThumbnailMap {
return false
}
if info != rhs.info {
return false
}
return true
}
}
private struct FrameContainer: Equatable {
let url: NSURL?
let image: UIImage?
init(url: NSURL) {
self.url = url
self.image = nil
}
init(image: UIImage) {
self.image = image
self.url = nil
}
}
private func == (lhs: FrameContainer, rhs: FrameContainer) -> Bool {
if lhs.url != rhs.url {
return false
}
if lhs.image != rhs.image {
return false
}
return true
}
| mit | bbf92cad3823ba0962081079a45bc8d0 | 31.677966 | 138 | 0.61735 | 4.601432 | false | false | false | false |
SpriteKitAlliance/SKATiledMap | SKATiledMapExample/SKATestPlayer.swift | 1 | 3088 | //
// SKATestPlayer.swift
// SKATiledMapExample
//
// Created by Skyler Lauren on 10/11/15.
// Copyright © 2015 Sprite Kit Alliance. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import Foundation
import SpriteKit
enum SKAPlayerState {
case Idel
case Left
case Right
}
class SKATestPlayer : SKSpriteNode {
var wantsToJump = false
var playerState : SKAPlayerState = .Idel
override init(texture: SKTexture?, color: UIColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
loadAssets()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func update(){
switch playerState{
case .Right :
runRight()
break
case .Left :
runLeft()
break
case .Idel :
break
}
if (wantsToJump && physicsBody?.velocity.dy == 0){
jump()
}
}
func runRight(){
physicsBody?.velocity = CGVectorMake(170, (physicsBody?.velocity.dy)!);
}
func runLeft(){
physicsBody?.velocity = CGVectorMake(-170, (physicsBody?.velocity.dy)!);
}
func jump(){
wantsToJump = false
physicsBody?.velocity = CGVectorMake((physicsBody?.velocity.dx)!, 800);
}
func loadAssets(){
position = CGPointMake(300, 500)
physicsBody = SKPhysicsBody(circleOfRadius: 15, center: CGPointMake(0, -40))
physicsBody?.allowsRotation = false
physicsBody?.restitution = 0
physicsBody?.friction = 0.2
physicsBody?.mass = 10
physicsBody?.affectedByGravity = true
physicsBody!.categoryBitMask = SKAColliderType.Player.rawValue
physicsBody!.collisionBitMask = SKAColliderType.Floor.rawValue | SKAColliderType.Wall.rawValue
physicsBody!.contactTestBitMask = SKAColliderType.Floor.rawValue | SKAColliderType.Wall.rawValue
}
} | mit | 54d8529c45fbc01008c0b24a2a666076 | 32.204301 | 104 | 0.661484 | 4.539706 | false | false | false | false |
Fri3ndlyGerman/SimpleStore | HPStore/HPStore.swift | 1 | 6411 | //
// SimpleStore.swift
// SimpleStore
//
// Created by Henrik Panhans on 06.03.17.
// Copyright © 2017 Henrik Panhans. All rights reserved.
//
import StoreKit
import SwiftyReceiptValidator
public class HPStore: NSObject, SKPaymentTransactionObserver, SKProductsRequestDelegate {
public var identifiers = [String]()
public var products = [String:SKProduct]()
public var delegate: HPStoreDelegate?
public var sharedSecret: String?
public var validator = SwiftyReceiptValidator()
public init(with identifiers: [String], secret sharedSecret: String? = nil) {
super.init()
SKPaymentQueue.default().add(self)
self.identifiers = identifiers
self.sharedSecret = sharedSecret
print("Init HPStore")
self.requestProductInfo(with: identifiers)
}
public func canMakePayments() -> Bool{
return SKPaymentQueue.canMakePayments()
}
public func restoreTransactions() {
SKPaymentQueue.default().restoreCompletedTransactions()
}
public func buyProduct(with id: String) {
if products[id] != nil && SKPaymentQueue.canMakePayments() {
let payment = SKPayment(product: products[id]! as SKProduct)
SKPaymentQueue.default().add(payment)
} else {
print("HPStore: No products found or device can't make in-app purchases")
}
}
public func requestProductInfo(with ids: [String]) {
print("HPStore: Requesting Product Info")
if self.canMakePayments() {
let productIdentifiers = NSSet(array: ids)
let productRequest = SKProductsRequest(productIdentifiers: productIdentifiers as! Set<String>)
productRequest.delegate = self
productRequest.start()
} else {
print("HPStore: Cannot perform In App Purchases")
}
}
public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
let response = HPProductResponse(response)
self.delegate?.productsRequest(didReceive: response)
if response.products.count != 0 {
self.products.removeAll()
for product in response.products {
products[product.productIdentifier] = product
}
print("HPStore: Loaded \(products.count) products")
} else {
print("HPStore: No products found")
}
}
public func request(_ request: SKRequest, didFailWithError error: Error) {
self.delegate?.productsRequest(didFailWithError: error)
}
public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
switch transaction.transactionState {
case .purchased:
let productIdentifier = transaction.payment.productIdentifier
self.validator.validate(productIdentifier, sharedSecret: sharedSecret) { result in
switch result {
case .success(let data):
print("HPStore: Receipt validation was successfull with data \(data)")
self.delegate?.transactionFinished(for: productIdentifier)
case .failure(let code, let error):
print("HPStore: Receipt validation failed with code: \(String(describing: code)), error: \(error.localizedDescription)")
self.delegate?.transactionFailed(for: productIdentifier, with: error)
}
queue.finishTransaction(transaction) // make sure this is in the validation closure
}
case .restored:
if let productIdentifier = transaction.original?.payment.productIdentifier {
self.validator.validate(productIdentifier, sharedSecret: sharedSecret) { result in
switch result {
case .success(let data):
print("HPStore: Receipt validation was successfull with data \(data)")
self.delegate?.transactionRestored(for: productIdentifier)
case .failure(let code, let error):
print("HPStore: Receipt validation failed with code: \(String(describing: code)), error: \(error.localizedDescription)")
self.delegate?.transactionFailed(for: productIdentifier, with: error)
}
queue.finishTransaction(transaction) // make sure this is in the validation closure
}
}
case .failed:
let productIdentifier = transaction.payment.productIdentifier
self.delegate?.transactionFailed(for: productIdentifier, with: transaction.error)
default:
break
}
}
}
public func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
self.delegate?.purchaseRestoringFinished()
}
public func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
self.delegate?.purchaseRestoringFailed(with: error)
}
}
public protocol HPStoreDelegate: class {
func transactionFinished(for identifier: String)
func transactionFailed(for identifier: String, with error: Error?)
func transactionRestored(for identifier: String)
func purchaseRestoringFinished()
func purchaseRestoringFailed(with error: Error)
func productsRequest(didReceive response: HPProductResponse)
func productsRequest(didFailWithError error: Error)
}
extension HPStore {
func priceStringForProduct(item: SKProduct) -> String? {
let price = item.price
if price == NSDecimalNumber(decimal: 0.00) {
return "Free"
} else {
let numberFormatter = NumberFormatter()
let locale = item.priceLocale
numberFormatter.numberStyle = .currency
numberFormatter.locale = locale
return numberFormatter.string(from: price)
}
}
}
| mit | 93c1943e97080d1250dfae7939d51be8 | 37.614458 | 148 | 0.609672 | 5.816697 | false | false | false | false |
pman215/ToastNotifications | ToastNotifications/Notification.swift | 1 | 1360 | //
// Notification.swift
// ToastNotifications
//
// Created by pman215 on 6/7/16.
// Copyright © 2016 pman215. All rights reserved.
//
import Foundation
/**
A `Notification` encapsulates the following points
- Content: Notification body composed by attributed text or images
- Appearance: Notification look and feel, size and position
- Animation: How a notification will show and hide
*/
class Notification {
let content: Content
let appearance: Appearance
let animation: Animation
weak var queue: NotificationQueue?
fileprivate weak var presenter: NotificationPresenter?
convenience init(text: String) {
let content = Content(text: text)
self.init(content: content,
appearance: Appearance(),
animation: Animation())
}
init(content: Content,
appearance: Appearance,
animation: Animation) {
self.content = content
self.appearance = appearance
self.animation = animation
}
func show(in presenter: NotificationPresenter) {
self.presenter = presenter
presenter.show(notification: self)
}
func didShow() {
// Override to add more functionality
}
func hide() {
presenter?.hideNotifications()
}
func didHide() {
queue?.dequeue(self)
}
}
| mit | 7d9c20fcc94009b22b054c02fade968f | 20.919355 | 67 | 0.64312 | 4.819149 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.