repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
steven7/ParkingApp
MapboxNavigation/UIView.swift
2
826
import UIKit extension UIView { class func defaultAnimation(_ duration: TimeInterval, animations: @escaping () -> Void, completion: ((_ completed: Bool) -> Void)?) { UIView.animate(withDuration: duration, delay: 0, options: .curveEaseInOut, animations: animations, completion: completion) } func applyDefaultCornerRadiusShadow(cornerRadius: CGFloat? = 4, shadowOpacity: CGFloat? = 0.1) { layer.cornerRadius = cornerRadius! layer.shadowOffset = CGSize(width: 0, height: 0) layer.shadowRadius = 4 layer.shadowOpacity = Float(shadowOpacity!) } func applyDefaultShadow(shadowOpacity: CGFloat? = 0.1) { layer.shadowOffset = CGSize(width: 0, height: 0) layer.shadowRadius = 4 layer.shadowOpacity = Float(shadowOpacity!) } }
isc
76b0f9b6bbed709fa914da44d9d76ca3
38.333333
137
0.664649
4.666667
false
false
false
false
ludoded/ReceiptBot
Pods/Material/Sources/iOS/TextField.swift
2
20341
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit @objc(TextFieldPlaceholderAnimation) public enum TextFieldPlaceholderAnimation: Int { case `default` case hidden } @objc(TextFieldDelegate) public protocol TextFieldDelegate: UITextFieldDelegate { /** A delegation method that is executed when the textField changed. - Parameter textField: A UITextField. - Parameter didChange text: An optional String. */ @objc optional func textField(textField: UITextField, didChange text: String?) /** A delegation method that is executed when the textField will clear. - Parameter textField: A UITextField. - Parameter willClear text: An optional String. */ @objc optional func textField(textField: UITextField, willClear text: String?) /** A delegation method that is executed when the textField is cleared. - Parameter textField: A UITextField. - Parameter didClear text: An optional String. */ @objc optional func textField(textField: UITextField, didClear text: String?) } open class TextField: UITextField { /// Default size when using AutoLayout. open override var intrinsicContentSize: CGSize { return CGSize(width: width, height: 32) } /// A Boolean that indicates if the placeholder label is animated. @IBInspectable open var isPlaceholderAnimated = true /// Set the placeholder animation value. open var placeholderAnimation = TextFieldPlaceholderAnimation.default { didSet { placeholderLabel.isHidden = .hidden == placeholderAnimation && !isEmpty } } /// A boolean indicating whether the text is empty. open var isEmpty: Bool { return 0 == text?.utf16.count } open override var leftView: UIView? { didSet { prepareLeftView() layoutSubviews() } } /// The leftView width value. open var leftViewWidth: CGFloat { guard nil != leftView else { return 0 } return leftViewOffset + height } /// The leftView offset value. open var leftViewOffset: CGFloat = 16 /// Placeholder normal text @IBInspectable open var leftViewNormalColor = Color.darkText.others { didSet { updateLeftViewColor() } } /// Placeholder active text @IBInspectable open var leftViewActiveColor = Color.blue.base { didSet { updateLeftViewColor() } } /// Divider normal height. @IBInspectable open var dividerNormalHeight: CGFloat = 1 { didSet { guard !isEditing else { return } dividerThickness = dividerNormalHeight } } /// Divider active height. @IBInspectable open var dividerActiveHeight: CGFloat = 2 { didSet { guard isEditing else { return } dividerThickness = dividerActiveHeight } } /// Divider normal color. @IBInspectable open var dividerNormalColor = Color.darkText.dividers { didSet { guard !isEditing else { return } dividerColor = dividerNormalColor } } /// Divider active color. @IBInspectable open var dividerActiveColor = Color.blue.base { didSet { guard isEditing else { return } dividerColor = dividerActiveColor } } /// The placeholderLabel font value. @IBInspectable open override var font: UIFont? { didSet { placeholderLabel.font = font } } /// The placeholderLabel text value. @IBInspectable open override var placeholder: String? { get { return placeholderLabel.text } set(value) { placeholderLabel.text = value layoutSubviews() } } /// The placeholder UILabel. @IBInspectable open let placeholderLabel = UILabel() /// Placeholder normal text @IBInspectable open var placeholderNormalColor = Color.darkText.others { didSet { updatePlaceholderLabelColor() } } /// Placeholder active text @IBInspectable open var placeholderActiveColor = Color.blue.base { didSet { updatePlaceholderLabelColor() } } /// This property adds a padding to placeholder y position animation @IBInspectable open var placeholderVerticalOffset: CGFloat = 0 /// The detailLabel UILabel that is displayed. @IBInspectable open let detailLabel = UILabel() /// The detailLabel text value. @IBInspectable open var detail: String? { get { return detailLabel.text } set(value) { detailLabel.text = value layoutSubviews() } } /// Detail text @IBInspectable open var detailColor = Color.darkText.others { didSet { updateDetailLabelColor() } } /// Vertical distance for the detailLabel from the divider. @IBInspectable open var detailVerticalOffset: CGFloat = 8 { didSet { layoutDetailLabel() } } /// Handles the textAlignment of the placeholderLabel. open override var textAlignment: NSTextAlignment { get { return super.textAlignment } set(value) { super.textAlignment = value placeholderLabel.textAlignment = value detailLabel.textAlignment = value } } /// A reference to the clearIconButton. open fileprivate(set) var clearIconButton: IconButton? /// Enables the clearIconButton. @IBInspectable open var isClearIconButtonEnabled: Bool { get { return nil != clearIconButton } set(value) { guard value else { clearIconButton?.removeTarget(self, action: #selector(handleClearIconButton), for: .touchUpInside) clearIconButton = nil return } guard nil == clearIconButton else { return } clearIconButton = IconButton(image: Icon.cm.clear, tintColor: placeholderNormalColor) clearIconButton!.contentEdgeInsetsPreset = .none clearIconButton!.pulseAnimation = .none clearButtonMode = .never rightViewMode = .whileEditing rightView = clearIconButton isClearIconButtonAutoHandled = isClearIconButtonAutoHandled ? true : false layoutSubviews() } } /// Enables the automatic handling of the clearIconButton. @IBInspectable open var isClearIconButtonAutoHandled = true { didSet { clearIconButton?.removeTarget(self, action: #selector(handleClearIconButton), for: .touchUpInside) guard isClearIconButtonAutoHandled else { return } clearIconButton?.addTarget(self, action: #selector(handleClearIconButton), for: .touchUpInside) } } /// A reference to the visibilityIconButton. open fileprivate(set) var visibilityIconButton: IconButton? /// Enables the visibilityIconButton. @IBInspectable open var isVisibilityIconButtonEnabled: Bool { get { return nil != visibilityIconButton } set(value) { guard value else { visibilityIconButton?.removeTarget(self, action: #selector(handleVisibilityIconButton), for: .touchUpInside) visibilityIconButton = nil return } guard nil == visibilityIconButton else { return } visibilityIconButton = IconButton(image: Icon.visibility, tintColor: placeholderNormalColor.withAlphaComponent(isSecureTextEntry ? 0.38 : 0.54)) visibilityIconButton!.contentEdgeInsetsPreset = .none visibilityIconButton!.pulseAnimation = .none isSecureTextEntry = true clearButtonMode = .never rightViewMode = .whileEditing rightView = visibilityIconButton isVisibilityIconButtonAutoHandled = isVisibilityIconButtonAutoHandled ? true : false layoutSubviews() } } /// Enables the automatic handling of the visibilityIconButton. @IBInspectable open var isVisibilityIconButtonAutoHandled: Bool = true { didSet { visibilityIconButton?.removeTarget(self, action: #selector(handleVisibilityIconButton), for: .touchUpInside) guard isVisibilityIconButtonAutoHandled else { return } visibilityIconButton?.addTarget(self, action: #selector(handleVisibilityIconButton), for: .touchUpInside) } } /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepare() } /** An initializer that initializes the object with a CGRect object. If AutoLayout is used, it is better to initilize the instance using the init() initializer. - Parameter frame: A CGRect instance. */ public override init(frame: CGRect) { super.init(frame: frame) prepare() } /// A convenience initializer. public convenience init() { self.init(frame: .zero) } open override func layoutSubviews() { super.layoutSubviews() layoutShape() reload() } open override func becomeFirstResponder() -> Bool { setNeedsLayout() layoutIfNeeded() return super.becomeFirstResponder() } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepare method to initialize property values and other setup operations. The super.prepare method should always be called immediately when subclassing. */ open func prepare() { clipsToBounds = false borderStyle = .none backgroundColor = nil contentScaleFactor = Screen.scale font = RobotoFont.regular(with: 16) textColor = Color.darkText.primary prepareDivider() preparePlaceholderLabel() prepareDetailLabel() prepareTargetHandlers() prepareTextAlignment() } /// Ensures that the components are sized correctly. open func reload() { layoutPlaceholderLabel() layoutDetailLabel() layoutButton(button: clearIconButton) layoutButton(button: visibilityIconButton) layoutDivider() layoutLeftView() } } extension TextField { /// Prepares the divider. fileprivate func prepareDivider() { dividerColor = dividerNormalColor } /// Prepares the placeholderLabel. fileprivate func preparePlaceholderLabel() { placeholderNormalColor = Color.darkText.others placeholderLabel.backgroundColor = .clear addSubview(placeholderLabel) } /// Prepares the detailLabel. fileprivate func prepareDetailLabel() { detailLabel.font = RobotoFont.regular(with: 12) detailLabel.numberOfLines = 0 detailColor = Color.darkText.others addSubview(detailLabel) } /// Prepares the leftView. fileprivate func prepareLeftView() { leftView?.contentMode = .left leftViewMode = .always updateLeftViewColor() } /// Prepares the target handlers. fileprivate func prepareTargetHandlers() { addTarget(self, action: #selector(handleEditingDidBegin), for: .editingDidBegin) addTarget(self, action: #selector(handleEditingChanged), for: .editingChanged) addTarget(self, action: #selector(handleEditingDidEnd), for: .editingDidEnd) } /// Prepares the textAlignment. fileprivate func prepareTextAlignment() { textAlignment = .rightToLeft == Application.userInterfaceLayoutDirection ? .right : .left } } extension TextField { /// Updates the leftView tint color. fileprivate func updateLeftViewColor() { leftView?.tintColor = isEditing ? leftViewActiveColor : leftViewNormalColor } /// Updates the placeholderLabel text color. fileprivate func updatePlaceholderLabelColor() { tintColor = placeholderActiveColor placeholderLabel.textColor = isEditing ? placeholderActiveColor : placeholderNormalColor } /// Updates the detailLabel text color. fileprivate func updateDetailLabelColor() { detailLabel.textColor = detailColor } } extension TextField { /// Layout the placeholderLabel. fileprivate func layoutPlaceholderLabel() { let w = leftViewWidth let h = 0 == height ? intrinsicContentSize.height : height placeholderLabel.transform = CGAffineTransform.identity guard isEditing || !isEmpty || !isPlaceholderAnimated else { placeholderLabel.frame = CGRect(x: w, y: 0, width: width - w, height: h) return } placeholderLabel.frame = CGRect(x: w, y: 0, width: width - w, height: h) placeholderLabel.transform = CGAffineTransform(scaleX: 0.75, y: 0.75) switch textAlignment { case .left, .natural: placeholderLabel.x = w case .right: placeholderLabel.x = width - placeholderLabel.width default:break } placeholderLabel.y = -placeholderLabel.height + placeholderVerticalOffset } /// Layout the detailLabel. fileprivate func layoutDetailLabel() { let c = dividerContentEdgeInsets detailLabel.height = detailLabel.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)).height detailLabel.x = c.left detailLabel.y = height + detailVerticalOffset detailLabel.width = width - c.left - c.right } /// Layout the a button. fileprivate func layoutButton(button: UIButton?) { button?.frame = CGRect(x: width - height, y: 0, width: height, height: height) } /// Layout the divider. fileprivate func layoutDivider() { divider.reload() } /// Layout the leftView. fileprivate func layoutLeftView() { guard let v = leftView else { return } let w = leftViewWidth v.frame = CGRect(x: 0, y: 0, width: w, height: height) dividerContentEdgeInsets.left = w } } extension TextField { /// Handles the text editing did begin state. @objc fileprivate func handleEditingDidBegin() { leftViewEditingBeginAnimation() placeholderEditingDidBeginAnimation() dividerEditingDidBeginAnimation() } // Live updates the textField text. @objc fileprivate func handleEditingChanged(textField: UITextField) { (delegate as? TextFieldDelegate)?.textField?(textField: self, didChange: textField.text) } /// Handles the text editing did end state. @objc fileprivate func handleEditingDidEnd() { leftViewEditingEndAnimation() placeholderEditingDidEndAnimation() dividerEditingDidEndAnimation() } /// Handles the clearIconButton TouchUpInside event. @objc fileprivate func handleClearIconButton() { guard nil == delegate?.textFieldShouldClear || true == delegate?.textFieldShouldClear?(self) else { return } let t = text (delegate as? TextFieldDelegate)?.textField?(textField: self, willClear: t) text = nil (delegate as? TextFieldDelegate)?.textField?(textField: self, didClear: t) } /// Handles the visibilityIconButton TouchUpInside event. @objc fileprivate func handleVisibilityIconButton() { isSecureTextEntry = !isSecureTextEntry if !isSecureTextEntry { super.font = nil font = placeholderLabel.font } visibilityIconButton?.tintColor = visibilityIconButton?.tintColor.withAlphaComponent(isSecureTextEntry ? 0.38 : 0.54) } } extension TextField { /// The animation for leftView when editing begins. fileprivate func leftViewEditingBeginAnimation() { updateLeftViewColor() } /// The animation for leftView when editing ends. fileprivate func leftViewEditingEndAnimation() { updateLeftViewColor() } /// The animation for the divider when editing begins. fileprivate func dividerEditingDidBeginAnimation() { dividerThickness = dividerActiveHeight dividerColor = dividerActiveColor } /// The animation for the divider when editing ends. fileprivate func dividerEditingDidEndAnimation() { dividerThickness = dividerNormalHeight dividerColor = dividerNormalColor } /// The animation for the placeholder when editing begins. fileprivate func placeholderEditingDidBeginAnimation() { guard .default == placeholderAnimation else { placeholderLabel.isHidden = true return } updatePlaceholderLabelColor() guard isPlaceholderAnimated else { return } guard isEmpty else { return } UIView.animate(withDuration: 0.15, animations: { [weak self] in guard let s = self else { return } s.placeholderLabel.transform = CGAffineTransform(scaleX: 0.75, y: 0.75) switch s.textAlignment { case .left, .natural: s.placeholderLabel.x = s.leftViewWidth case .right: s.placeholderLabel.x = s.width - s.placeholderLabel.width default:break } s.placeholderLabel.y = -s.placeholderLabel.height + s.placeholderVerticalOffset }) } /// The animation for the placeholder when editing ends. fileprivate func placeholderEditingDidEndAnimation() { guard .default == placeholderAnimation else { placeholderLabel.isHidden = !isEmpty return } updatePlaceholderLabelColor() guard isPlaceholderAnimated else { return } guard isEmpty else { return } UIView.animate(withDuration: 0.15, animations: { [weak self] in guard let s = self else { return } s.placeholderLabel.transform = CGAffineTransform.identity s.placeholderLabel.x = s.leftViewWidth s.placeholderLabel.y = 0 }) } }
lgpl-3.0
ef77bcfcb1d521568c96dcdcc025ee6d
28.913235
156
0.641414
5.247936
false
false
false
false
guilhermearaujo/Bumbo
Example/ViewController.swift
1
1187
// // ViewController.swift // Example // // Created by Guilherme Araújo on 17/03/17. // Copyright © 2017 Guilherme Araújo. All rights reserved. // import UIKit import Bumbo class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() Bumbo.configure(host: "http://192.168.10.24:8888/", secretKey: "my_secret_key") let width = Int((0.5 + Float(arc4random_uniform(2))) * 400) let height = Int((0.5 + Float(arc4random_uniform(2))) * 400) let url = Bumbo.load("lorempixel.com/\(width)/\(height)") .trim() .crop(leftTop: (x: 0, y: 0), rightBottom: (x: 200, y: 200)) .fitIn() .resize(width: 320, height: 320) .align(horizontal: .left, vertical: .bottom) .useSmartDetectors() .filter(.grayScale) .filter(.stripICC) .filter(.rotate(90)) .filter(.quality(50)) .filter(.noise(50)) .toURL() print(url.absoluteString) let imageView = UIImageView(frame: view.frame) imageView.contentMode = UIViewContentMode.center view.addSubview(imageView) if let data = try? Data(contentsOf: url) { imageView.image = UIImage(data: data) } } }
mit
d035e6891c5507d5aa9fc6d0f0da6a99
25.311111
83
0.631757
3.451895
false
false
false
false
coach-plus/ios
Pods/MarqueeLabel/Sources/MarqueeLabel.swift
1
73872
// // MarqueeLabel.swift // // Created by Charles Powell on 8/6/14. // Copyright (c) 2015 Charles Powell. All rights reserved. // import UIKit import QuartzCore @IBDesignable open class MarqueeLabel: UILabel, CAAnimationDelegate { /** An enum that defines the types of `MarqueeLabel` scrolling - Left: Scrolls left after the specified delay, and does not return to the original position. - LeftRight: Scrolls left first, then back right to the original position. - Right: Scrolls right after the specified delay, and does not return 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 MarqueeType { case left case leftRight case right case rightLeft case continuous case continuousReverse } // // MARK: - Public properties // /** Defines the direction and method in which the `MarqueeLabel` instance scrolls. `MarqueeLabel` supports six default types of scrolling: `Left`, `LeftRight`, `Right`, `RightLeft`, `Continuous`, and `ContinuousReverse`. Given the nature of how text direction works, the options for the `type` property require specific text alignments and will set the textAlignment property accordingly. - `LeftRight` and `Left` types are ONLY compatible with a label text alignment of `NSTextAlignment.left`. - `RightLeft` and `Right` types are ONLY compatible with a label text alignment of `NSTextAlignment.right`. - `Continuous` and `ContinuousReverse` allow the use of `NSTextAlignment.left`, `.right`, or `.center` alignments, however the text alignment only has an effect when label text is short enough that scrolling is not required. When scrolling, the labels are effectively center-aligned. Defaults to `Continuous`. - Note: Note that any `leadingBuffer` value will affect the text alignment location relative to the frame position, including with `.center` alignment, where the center alignment location will be shifted left (for `.continuous`) or right (for `.continuousReverse`) by one-half (1/2) the `.leadingBuffer` amount. Use the `.trailingBuffer` property to add a buffer between text "loops" without affecting alignment location. - SeeAlso: textAlignment - SeeAlso: leadingBuffer */ open var type: MarqueeType = .continuous { didSet { if type == oldValue { return } updateAndScroll() } } /** An optional custom scroll "sequence", defined by an array of `ScrollStep` or `FadeStep` instances. A sequence defines a single scroll/animation loop, which will continue to be automatically repeated like the default types. A `type` value is still required when using a custom sequence. The `type` value defines the `home` and `away` values used in the `ScrollStep` instances, and the `type` value determines which way the label will scroll. When a custom sequence is not supplied, the default sequences are used per the defined `type`. `ScrollStep` steps are the primary step types, and define the position of the label at a given time in the sequence. `FadeStep` steps are secondary steps that define the edge fade state (leading, trailing, or both) around the `ScrollStep` steps. Defaults to nil. - Attention: Use of the `scrollSequence` property requires understanding of how MarqueeLabel works for effective use. As a reference, it is suggested to review the methodology used to build the sequences for the default types. - SeeAlso: type - SeeAlso: ScrollStep - SeeAlso: FadeStep */ open var scrollSequence: Array<MarqueeStep>? /** Specifies the animation curve used in the scrolling motion of the labels. Allowable options: - `UIViewAnimationOptionCurveEaseInOut` - `UIViewAnimationOptionCurveEaseIn` - `UIViewAnimationOptionCurveEaseOut` - `UIViewAnimationOptionCurveLinear` Defaults to `UIViewAnimationOptionCurveEaseInOut`. */ open var animationCurve: UIView.AnimationCurve = .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 - Note: The label will not automatically scroll when this property is set to `true`. - 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 open 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`. - Note: The label will not automatically scroll when this property is set to `true`. - SeeAlso: labelize */ @IBInspectable open var holdScrolling: Bool = false { didSet { if holdScrolling != oldValue { if oldValue == true && !(awayFromHome || labelize ) && labelShouldScroll() { updateAndScroll() } } } } /** 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`. - Note: The label will not automatically scroll when this property is set to `false`. - SeeAlso: holdScrolling */ @IBInspectable open var tapToScroll: Bool = false { didSet { if tapToScroll != oldValue { if tapToScroll { let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(MarqueeLabel.labelWasTapped(_:))) self.addGestureRecognizer(tapRecognizer) isUserInteractionEnabled = true } else { if let recognizer = self.gestureRecognizers!.first as UIGestureRecognizer? { self.removeGestureRecognizer(recognizer) } isUserInteractionEnabled = false } } } } /** A read-only boolean property that indicates if the label's scroll animation has been paused. - SeeAlso: pauseLabel - SeeAlso: unpauseLabel */ open 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. */ open var awayFromHome: Bool { if let presentationLayer = sublabel.layer.presentation() { 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 */ open 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(*, deprecated, message: "Use speed property instead") @IBInspectable open var scrollDuration: CGFloat { get { switch speed { case .duration(let duration): return duration case .rate(_): return 0.0 } } set { speed = .duration(newValue) } } @available(*, deprecated, message : "Use speed property instead") @IBInspectable open var scrollRate: CGFloat { get { switch speed { case .duration(_): return 0.0 case .rate(let rate): return rate } } set { speed = .rate(newValue) } } /** 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 open 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 open 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 open 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 open var animationDelay: CGFloat = 1.0 /** The read-only/computed duration of the scroll animation (not including delay). The value of this property is calculated from the value set to the `speed` property. If a duration-type speed is used to set the label animation speed, `animationDuration` will be equivalent to that value. */ public var animationDuration: CGFloat { switch self.speed { case .rate(let rate): return CGFloat(abs(self.awayOffset) / rate) case .duration(let duration): return duration } } // // 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: */ open 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 */ open 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 */ open 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 */ open 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 */ open 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 */ public 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 */ public 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 NotificationCenter.default.addObserver(self, selector: #selector(MarqueeLabel.restartForViewController(_:)), name: NSNotification.Name(rawValue: MarqueeKeys.Restart.rawValue), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(MarqueeLabel.labelizeForController(_:)), name: NSNotification.Name(rawValue: MarqueeKeys.Labelize.rawValue), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(MarqueeLabel.animateForController(_:)), name: NSNotification.Name(rawValue: MarqueeKeys.Animate.rawValue), object: nil) // UIApplication state notifications NotificationCenter.default.addObserver(self, selector: #selector(MarqueeLabel.restartLabel), name: UIApplication.didBecomeActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(MarqueeLabel.shutdownLabel), name: UIApplication.didEnterBackgroundNotification, object: nil) } override open func awakeFromNib() { super.awakeFromNib() forwardPropertiesToSublabel() } @available(iOS 8.0, *) override open func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() 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", "contentMode"] // Iterate through properties sublabel.text = super.text sublabel.font = super.font sublabel.textColor = super.textColor sublabel.backgroundColor = super.backgroundColor ?? UIColor.clear sublabel.shadowColor = super.shadowColor sublabel.shadowOffset = super.shadowOffset for prop in properties { let value = super.value(forKey: prop) sublabel.setValue(value, forKeyPath: prop) } } // // MARK: - MarqueeLabel Heavy Lifting // override open func layoutSubviews() { super.layoutSubviews() updateAndScroll() } override open func willMove(toWindow newWindow: UIWindow?) { if newWindow == nil { shutdownLabel() } } override open func didMoveToWindow() { if self.window == nil { shutdownLabel() } else { updateAndScroll() } } private func updateAndScroll() { // Do not automatically begin scroll if tapToScroll is true updateAndScroll(overrideHold: false) } private func updateAndScroll(overrideHold: 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 let labelFrame: CGRect switch type { case .continuousReverse, .rightLeft: labelFrame = bounds.divided(atDistance: leadingBuffer, from: CGRectEdge.maxXEdge).remainder.integral default: labelFrame = CGRect(x: leadingBuffer, y: 0.0, width: bounds.size.width - leadingBuffer, height: bounds.size.height).integral } 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 // Remove fade, as by definition none is needed in this case removeGradientMask() 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) // Determine positions and generate scroll steps let sequence: [MarqueeStep] switch type { case .continuous, .continuousReverse: if (type == .continuous) { homeLabelFrame = CGRect(x: leadingBuffer, y: 0.0, width: expectedLabelSize.width, height: bounds.size.height).integral awayOffset = -(homeLabelFrame.size.width + minTrailing) } else { // .ContinuousReverse homeLabelFrame = CGRect(x: bounds.size.width - (expectedLabelSize.width + leadingBuffer), y: 0.0, width: expectedLabelSize.width, height: bounds.size.height).integral awayOffset = (homeLabelFrame.size.width + minTrailing) } // Find when the lead label will be totally offscreen let offsetDistance = awayOffset let offscreenAmount = homeLabelFrame.size.width let startFadeFraction = abs(offscreenAmount / offsetDistance) // Find when the animation will hit that point let startFadeTimeFraction = timingFunctionForAnimationCurve(animationCurve).durationPercentageForPositionPercentage(startFadeFraction, duration: (animationDelay + animationDuration)) let startFadeTime = startFadeTimeFraction * animationDuration sequence = scrollSequence ?? [ ScrollStep(timeStep: 0.0, position: .home, edgeFades: .trailing), // Starting point, at home, with trailing fade ScrollStep(timeStep: animationDelay, position: .home, edgeFades: .trailing), // Delay at home, maintaining fade state FadeStep(timeStep: 0.2, edgeFades: [.leading, .trailing]), // 0.2 sec after scroll start, fade leading edge in as well FadeStep(timeStep: (startFadeTime - animationDuration), // Maintain fade state until just before reaching end of scroll animation edgeFades: [.leading, .trailing]), ScrollStep(timeStep: animationDuration, timingFunction: animationCurve, // Ending point (back at home), with animationCurve transition, with trailing fade position: .away, edgeFades: .trailing) ] // Set frame and text sublabel.frame = homeLabelFrame // Configure replication repliLayer?.instanceCount = 2 repliLayer?.instanceTransform = CATransform3DMakeTranslation(-awayOffset, 0.0, 0.0) case .leftRight, .left, .rightLeft, .right: if (type == .leftRight || type == .left) { homeLabelFrame = CGRect(x: leadingBuffer, y: 0.0, width: expectedLabelSize.width, height: bounds.size.height).integral awayOffset = bounds.size.width - (expectedLabelSize.width + leadingBuffer + trailingBuffer) // Enforce text alignment for this type sublabel.textAlignment = NSTextAlignment.left } else { homeLabelFrame = CGRect(x: bounds.size.width - (expectedLabelSize.width + leadingBuffer), y: 0.0, width: expectedLabelSize.width, height: bounds.size.height).integral awayOffset = (expectedLabelSize.width + trailingBuffer + leadingBuffer) - bounds.size.width // Enforce text alignment for this type sublabel.textAlignment = NSTextAlignment.right } // Set frame and text sublabel.frame = homeLabelFrame // Remove any replication repliLayer?.instanceCount = 1 if (type == .leftRight || type == .rightLeft) { sequence = scrollSequence ?? [ ScrollStep(timeStep: 0.0, position: .home, edgeFades: .trailing), // Starting point, at home, with trailing fade ScrollStep(timeStep: animationDelay, position: .home, edgeFades: .trailing), // Delay at home, maintaining fade state FadeStep(timeStep: 0.2, edgeFades: [.leading, .trailing]), // 0.2 sec after delay ends, fade leading edge in as well FadeStep(timeStep: -0.2, edgeFades: [.leading, .trailing]), // Maintain fade state until 0.2 sec before reaching away position ScrollStep(timeStep: animationDuration, timingFunction: animationCurve, // Away position, using animationCurve transition, with only leading edge faded in position: .away, edgeFades: .leading), ScrollStep(timeStep: animationDelay, position: .away, edgeFades: .leading), // Delay at away, maintaining fade state (leading only) FadeStep(timeStep: 0.2, edgeFades: [.leading, .trailing]), // 0.2 sec after delay ends, fade trailing edge back in as well FadeStep(timeStep: -0.2, edgeFades: [.leading, .trailing]), // Maintain fade state until 0.2 sec before reaching home position ScrollStep(timeStep: animationDuration, timingFunction: animationCurve, // Ending point, back at home, with only trailing fade position: .home, edgeFades: .trailing) ] } else { // .left or .right sequence = scrollSequence ?? [ ScrollStep(timeStep: 0.0, position: .home, edgeFades: .trailing), // Starting point, at home, with trailing fade ScrollStep(timeStep: animationDelay, position: .home, edgeFades: .trailing), // Delay at home, maintaining fade state FadeStep(timeStep: 0.2, edgeFades: [.leading, .trailing]), // 0.2 sec after delay ends, fade leading edge in as well FadeStep(timeStep: -0.2, edgeFades: [.leading, .trailing]), // Maintain fade state until 0.2 sec before reaching away position ScrollStep(timeStep: animationDuration, timingFunction: animationCurve, // Away position, using animationCurve transition, with only leading edge faded in position: .away, edgeFades: .leading), ScrollStep(timeStep: animationDelay, position: .away, edgeFades: .leading), // "Delay" at away, maintaining fade state ] } } // Configure gradient for current condition applyGradientMask(fadeLength, animated: !self.labelize) if overrideHold || (!holdScrolling && !overrideHold) { beginScroll(sequence) } } private func sublabelSize() -> CGSize { // Bound the expected size let maximumLabelSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) // Calculate the expected size var expectedLabelSize = sublabel.sizeThatFits(maximumLabelSize) #if os(tvOS) // Sanitize width to 16384.0 (largest width a UILabel will draw on tvOS) expectedLabelSize.width = min(expectedLabelSize.width, 16384.0) #else // Sanitize width to 5461.0 (largest width a UILabel will draw on an iPhone 6S Plus) expectedLabelSize.width = min(expectedLabelSize.width, 5461.0) #endif // Adjust to own height (make text baseline match normal label) expectedLabelSize.height = bounds.size.height return expectedLabelSize } override open func sizeThatFits(_ size: CGSize) -> CGSize { var fitSize = sublabel.sizeThatFits(size) fitSize.width += leadingBuffer return fitSize } // // MARK: - Animation Handling // open 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 + CGFloat.ulpOfOne 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 returnLabelToHome() { // Remove any gradient animation maskLayer?.removeAllAnimations() // Remove all sublabel position animations sublabel.layer.removeAllAnimations() // Remove completion block scrollCompletionBlock = nil } private func beginScroll(_ sequence: [MarqueeStep]) { let scroller = generateScrollAnimation(sequence) let fader = generateGradientAnimation(sequence, totalDuration: scroller.duration) scroll(scroller, fader: fader) } private func scroll(_ scroller: MLAnimation, fader: MLAnimation?) { // Check for conditions which would prevent scrolling if !labelReadyForScroll() { return } // Convert fader to var var fader = fader // Call pre-animation hook labelWillBeginScroll() // Start animation transactions CATransaction.begin() CATransaction.setAnimationDuration(TimeInterval(scroller.duration)) // Create gradient animation, if needed let gradientAnimation: CAKeyframeAnimation? // Check for IBDesignable #if !TARGET_INTERFACE_BUILDER if fadeLength > 0.0 { // Remove any setup animation, but apply final values if let setupAnim = maskLayer?.animation(forKey: "setupFade") as? CABasicAnimation, let finalColors = setupAnim.toValue as? [CGColor] { maskLayer?.colors = finalColors } maskLayer?.removeAnimation(forKey: "setupFade") // Generate animation if needed if let previousAnimation = fader?.anim { gradientAnimation = previousAnimation } else { gradientAnimation = nil } // Apply fade animation maskLayer?.add(gradientAnimation!, forKey: "gradient") } else { // No animation needed fader = nil } #else fader = nil; #endif scrollCompletionBlock = { [weak self] (finished: Bool) -> () in guard (self != nil) else { return } // Call returned home function self!.labelReturnedToHome(finished) // Check to ensure that: // 1) 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 } // 2) We don't double fire if an animation already exists guard self!.sublabel.layer.animation(forKey: "position") == nil else { return } // 3) We don't not start automatically if the animation was unexpectedly interrupted guard finished else { // Do not continue into the next loop return } // 4) A completion block still exists for the NEXT loop. A notable case here is if // returnLabelToHome() was called during a subclass's labelReturnToHome() function guard (self!.scrollCompletionBlock != nil) else { return } // Begin again, if conditions met if (self!.labelShouldScroll() && !self!.tapToScroll && !self!.holdScrolling) { // Perform completion callback self!.scroll(scroller, fader: fader) } } // Perform scroll animation scroller.anim.setValue(true, forKey: MarqueeKeys.CompletionClosure.rawValue) scroller.anim.delegate = self if type == .left || type == .right { // Make it stay at away permanently scroller.anim.isRemovedOnCompletion = false scroller.anim.fillMode = .forwards } sublabel.layer.add(scroller.anim, forKey: "position") CATransaction.commit() } private func generateScrollAnimation(_ sequence: [MarqueeStep]) -> MLAnimation { // Create scroller, which defines the animation to perform let homeOrigin = homeLabelFrame.origin let awayOrigin = offsetCGPoint(homeLabelFrame.origin, offset: awayOffset) let scrollSteps = sequence.filter({ $0 is ScrollStep }) as! [ScrollStep] let totalDuration = scrollSteps.reduce(0.0) { $0 + $1.timeStep } // Build scroll data var totalTime: CGFloat = 0.0 var scrollKeyTimes = [NSNumber]() var scrollKeyValues = [NSValue]() var scrollTimingFunctions = [CAMediaTimingFunction]() for (offset, step) in scrollSteps.enumerated() { // Scroll Times totalTime += step.timeStep scrollKeyTimes.append(NSNumber(value:Float(totalTime/totalDuration))) // Scroll Values let scrollPosition: CGPoint switch step.position { case .home: scrollPosition = homeOrigin case .away: scrollPosition = awayOrigin case .partial(let frac): scrollPosition = offsetCGPoint(homeOrigin, offset: awayOffset*frac) } scrollKeyValues.append(NSValue(cgPoint:scrollPosition)) // Scroll Timing Functions // Only need n-1 timing functions, so discard the first value as it's unused if offset == 0 { continue } scrollTimingFunctions.append(timingFunctionForAnimationCurve(step.timingFunction)) } // Create animation let animation = CAKeyframeAnimation(keyPath: "position") // Set values animation.keyTimes = scrollKeyTimes animation.values = scrollKeyValues animation.timingFunctions = scrollTimingFunctions return (anim: animation, duration: totalDuration) } private func generateGradientAnimation(_ sequence: [MarqueeStep], totalDuration: CGFloat) -> MLAnimation { // Setup var totalTime: CGFloat = 0.0 var stepTime: CGFloat = 0.0 var fadeKeyValues = [[CGColor]]() var fadeKeyTimes = [NSNumber]() var fadeTimingFunctions = [CAMediaTimingFunction]() let transp = UIColor.clear.cgColor let opaque = UIColor.black.cgColor // Filter to get only scroll steps and valid precedent/subsequent fade steps let fadeSteps = sequence.enumerated().filter { (arg: (offset: Int, element: MarqueeStep)) -> Bool in let (offset, element) = arg // Include all Scroll Steps if element is ScrollStep { return true } // Include all Fade Steps that have a directly preceding or subsequent Scroll Step // Exception: Fade Step cannot be first step if offset == 0 { return false } // Subsequent step if 1) positive/zero time step and 2) follows a Scroll Step let subsequent = element.timeStep >= 0 && (sequence[max(0, offset - 1)] is ScrollStep) // Precedent step if 1) negative time step and 2) precedes a Scroll Step let precedent = element.timeStep < 0 && (sequence[min(sequence.count - 1, offset + 1)] is ScrollStep) return (precedent || subsequent) } for (offset, step) in fadeSteps { // Fade times if (step is ScrollStep) { totalTime += step.timeStep stepTime = totalTime } else { if step.timeStep >= 0 { // Is a Subsequent stepTime = totalTime + step.timeStep } else { // Is a Precedent, grab next step stepTime = totalTime + fadeSteps[offset + 1].element.timeStep + step.timeStep } } fadeKeyTimes.append(NSNumber(value:Float(stepTime/totalDuration))) // Fade Values let values: [CGColor] let leading = step.edgeFades.contains(.leading) ? transp : opaque let trailing = step.edgeFades.contains(.trailing) ? transp : opaque switch type { case .leftRight, .left, .continuous: values = [leading, opaque, opaque, trailing] case .rightLeft, .right, .continuousReverse: values = [trailing, opaque, opaque, leading] } fadeKeyValues.append(values) // Fade Timing Function // Only need n-1 timing functions, so discard the first value as it's unused if offset == 0 { continue } fadeTimingFunctions.append(timingFunctionForAnimationCurve(step.timingFunction)) } // Create new animation let animation = CAKeyframeAnimation(keyPath: "colors") animation.values = fadeKeyValues animation.keyTimes = fadeKeyTimes animation.timingFunctions = fadeTimingFunctions return (anim: animation, duration: max(totalTime,totalDuration)) } private func applyGradientMask(_ fadeLength: CGFloat, animated: Bool, firstStep: MarqueeStep? = nil) { // 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.main.scale gradientMask.startPoint = CGPoint(x:0.0, y:0.5) gradientMask.endPoint = CGPoint(x:1.0, y:0.5) } // Check if there is a mask to layer size mismatch if gradientMask.bounds != self.layer.bounds { // Adjust stops based on fade length let leftFadeStop = fadeLength/self.bounds.size.width let rightFadeStop = 1.0 - fadeLength/self.bounds.size.width gradientMask.locations = [0.0, leftFadeStop, rightFadeStop, 1.0].map { NSNumber(value: Float($0)) } } gradientMask.bounds = self.layer.bounds gradientMask.position = CGPoint(x:self.bounds.midX, y:self.bounds.midY) // Set up colors let transparent = UIColor.clear.cgColor let opaque = UIColor.black.cgColor // Set mask self.layer.mask = gradientMask // Determine colors for non-scrolling label (i.e. at home) let adjustedColors: [CGColor] let trailingFadeNeeded = self.labelShouldScroll() switch (type) { case .continuousReverse, .rightLeft: adjustedColors = [(trailingFadeNeeded ? transparent : opaque), opaque, opaque, opaque] // .Continuous, .LeftRight default: adjustedColors = [opaque, opaque, opaque, (trailingFadeNeeded ? transparent : opaque)] } // Check for IBDesignable #if TARGET_INTERFACE_BUILDER gradientMask.colors = adjustedColors CATransaction.commit() #else if (animated) { // Finish transaction CATransaction.commit() // Create animation for color change let colorAnimation = GradientSetupAnimation(keyPath: "colors") colorAnimation.fromValue = gradientMask.colors colorAnimation.toValue = adjustedColors colorAnimation.fillMode = .forwards colorAnimation.isRemovedOnCompletion = false colorAnimation.delegate = self gradientMask.add(colorAnimation, forKey: "setupFade") } else { gradientMask.colors = adjustedColors CATransaction.commit() } #endif } private func removeGradientMask() { self.layer.mask = nil } private func timingFunctionForAnimationCurve(_ curve: UIView.AnimationCurve) -> CAMediaTimingFunction { let timingFunction: CAMediaTimingFunctionName? switch curve { case .easeIn: timingFunction = .easeIn case .easeInOut: timingFunction = .easeInEaseOut case .easeOut: timingFunction = .easeOut default: timingFunction = .linear } return CAMediaTimingFunction(name: timingFunction!) } private func transactionDurationType(_ labelType: MarqueeType, interval: CGFloat, delay: CGFloat) -> TimeInterval { switch (labelType) { case .leftRight, .rightLeft: return TimeInterval(2.0 * (delay + interval)) default: return TimeInterval(delay + interval) } } public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if let setupAnim = anim as? GradientSetupAnimation { if let finalColors = setupAnim.toValue as? [CGColor] { maskLayer?.colors = finalColors } // Remove regardless, since we set removeOnCompletion = false maskLayer?.removeAnimation(forKey: "setupFade") } else { scrollCompletionBlock?(flag) } } // // MARK: - Private details // private var sublabel = UILabel() fileprivate var homeLabelFrame = CGRect.zero fileprivate var awayOffset: CGFloat = 0.0 override open class var layerClass: AnyClass { return CAReplicatorLayer.self } fileprivate weak var repliLayer: CAReplicatorLayer? { return self.layer as? CAReplicatorLayer } fileprivate weak var maskLayer: CAGradientLayer? { return self.layer.mask as! CAGradientLayer? } fileprivate var scrollCompletionBlock: MLAnimationCompletionBlock? override open func draw(_ layer: CALayer, in 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 { ctx.setFillColor(bgColor.cgColor); ctx.fill(layer.bounds); } } fileprivate enum MarqueeKeys: String { case Restart = "MLViewControllerRestart" case Labelize = "MLShouldLabelize" case Animate = "MLShouldAnimate" case CompletionClosure = "MLAnimationCompletion" } class fileprivate func notifyController(_ controller: UIViewController, message: MarqueeKeys) { NotificationCenter.default.post(name: Notification.Name(rawValue: message.rawValue), object: nil, userInfo: ["controller" : controller]) } @objc public func restartForViewController(_ notification: Notification) { if let controller = (notification as NSNotification).userInfo?["controller"] as? UIViewController { if controller === self.firstAvailableViewController() { self.restartLabel() } } } @objc public func labelizeForController(_ notification: Notification) { if let controller = (notification as NSNotification).userInfo?["controller"] as? UIViewController { if controller === self.firstAvailableViewController() { self.labelize = true } } } @objc public func animateForController(_ notification: Notification) { if let controller = (notification as NSNotification).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 { updateAndScroll() } } /** 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 */ @objc public func restartLabel() { // Shutdown the label shutdownLabel() // Restart scrolling if appropriate if labelShouldScroll() && !tapToScroll && !holdScrolling { updateAndScroll() } } /** 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 */ @available(*, deprecated, message : "Use the shutdownLabel function instead") 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 */ @objc 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(), from: nil) sublabel.layer.speed = 0.0 sublabel.layer.timeOffset = labelPauseTime // Pause gradient fade animation let gradientPauseTime = maskLayer?.convertTime(CACurrentMediaTime(), from: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(), from: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(), from:nil) - gradientPauseTime! } @objc public func labelWasTapped(_ recognizer: UIGestureRecognizer) { if labelShouldScroll() && !awayFromHome { // Set shouldBeginScroll to true to begin single scroll due to tap updateAndScroll(overrideHold: 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. */ open 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. */ open func labelReturnedToHome(_ finished: Bool) { // Default implementation does nothing - override to customize return } // // MARK: - Modified UILabel Functions/Getters/Setters // #if os(iOS) override open func forBaselineLayout() -> UIView { // Use subLabel view for handling baseline layouts return sublabel } override open var forLastBaselineLayout: UIView { // Use subLabel view for handling baseline layouts return sublabel } #endif override open var text: String? { get { return sublabel.text } set { if sublabel.text == newValue { return } sublabel.text = newValue updateAndScroll() super.text = text } } override open var attributedText: NSAttributedString? { get { return sublabel.attributedText } set { if sublabel.attributedText == newValue { return } sublabel.attributedText = newValue updateAndScroll() super.attributedText = attributedText } } override open var font: UIFont! { get { return sublabel.font } set { if sublabel.font == newValue { return } sublabel.font = newValue super.font = newValue updateAndScroll() } } override open var textColor: UIColor! { get { return sublabel.textColor } set { sublabel.textColor = newValue super.textColor = newValue } } override open var backgroundColor: UIColor? { get { return sublabel.backgroundColor } set { sublabel.backgroundColor = newValue super.backgroundColor = newValue } } override open var shadowColor: UIColor? { get { return sublabel.shadowColor } set { sublabel.shadowColor = newValue super.shadowColor = newValue } } override open var shadowOffset: CGSize { get { return sublabel.shadowOffset } set { sublabel.shadowOffset = newValue super.shadowOffset = newValue } } override open var highlightedTextColor: UIColor? { get { return sublabel.highlightedTextColor } set { sublabel.highlightedTextColor = newValue super.highlightedTextColor = newValue } } override open var isHighlighted: Bool { get { return sublabel.isHighlighted } set { sublabel.isHighlighted = newValue super.isHighlighted = newValue } } override open var isEnabled: Bool { get { return sublabel.isEnabled } set { sublabel.isEnabled = newValue super.isEnabled = newValue } } override open var numberOfLines: Int { get { return super.numberOfLines } set { // By the nature of MarqueeLabel, this is 1 super.numberOfLines = 1 } } override open var adjustsFontSizeToFitWidth: Bool { get { return super.adjustsFontSizeToFitWidth } set { // By the nature of MarqueeLabel, this is false super.adjustsFontSizeToFitWidth = false } } override open var minimumScaleFactor: CGFloat { get { return super.minimumScaleFactor } set { super.minimumScaleFactor = 0.0 } } override open var baselineAdjustment: UIBaselineAdjustment { get { return sublabel.baselineAdjustment } set { sublabel.baselineAdjustment = newValue super.baselineAdjustment = newValue } } override open var intrinsicContentSize: CGSize { var content = sublabel.intrinsicContentSize content.width += leadingBuffer return content } override open var tintColor: UIColor! { get { return sublabel.tintColor } set { sublabel.tintColor = newValue super.tintColor = newValue } } override open func tintColorDidChange() { super.tintColorDidChange() sublabel.tintColorDidChange() } override open var contentMode: UIView.ContentMode { get { return sublabel.contentMode } set { super.contentMode = contentMode sublabel.contentMode = newValue } } open override var isAccessibilityElement: Bool { didSet { sublabel.isAccessibilityElement = self.isAccessibilityElement } } // // MARK: - Support // fileprivate func offsetCGPoint(_ point: CGPoint, offset: CGFloat) -> CGPoint { return CGPoint(x: point.x + offset, y: point.y) } // // MARK: - Deinit // deinit { NotificationCenter.default.removeObserver(self) } } // // MARK: - Support // public protocol MarqueeStep { var timeStep: CGFloat { get } var timingFunction: UIView.AnimationCurve { get } var edgeFades: EdgeFade { get } } /** `ScrollStep` types define the label position at a specified time delta since the last `ScrollStep` step, as well as the animation curve to that position and edge fade state at the position */ public struct ScrollStep: MarqueeStep { /** An enum that provides the possible positions defined by a ScrollStep - `home`: The starting, default position of the label - `away`: The calculated position that results in the entirety of the label scrolling past. - `partial(CGFloat)`: A fractional value, specified by the associated CGFloat value, between the `home` and `away` positions (must be between 0.0 and 1.0). The `away` position depends on the MarqueeLabel `type` value. - For `left`, `leftRight`, `right`, and `rightLeft` types, the `away` position means the trailing edge of the label is visible. For `leftRight` and `rightLeft` default types, the scroll animation reverses direction after reaching this point and returns to the `home` position. - For `continuous` and `continuousReverse` types, the `away` position is the location such that if the scroll is completed at this point (i.e. the animation is removed), there will be no visible change in the label appearance. */ public enum Position { case home case away case partial(CGFloat) } /** The desired time between this step and the previous `ScrollStep` in a sequence. */ public let timeStep: CGFloat /** The animation curve to utilize between the previous `ScrollStep` in a sequence and this step. - Note: The animation curve value for the first `ScrollStep` in a sequence has no effect. */ public let timingFunction: UIView.AnimationCurve /** The position of the label for this scroll step. - SeeAlso: Position */ public let position: Position /** The option set defining the edge fade state for this scroll step. Possible options include `.leading` and `.trailing`, corresponding to the leading edge of the label scrolling (i.e. the direction of scroll) and trailing edge of the label. */ public let edgeFades: EdgeFade public init(timeStep: CGFloat, timingFunction: UIView.AnimationCurve = .linear, position: Position, edgeFades: EdgeFade) { self.timeStep = timeStep self.position = position self.edgeFades = edgeFades self.timingFunction = timingFunction } } /** `FadeStep` types allow additional edge fade state definitions, around the states defined by the `ScrollStep` steps of a sequence. `FadeStep` steps are defined by the time delta to the preceding or subsequent `ScrollStep` step and the timing function to their edge fade state. - Note: A `FadeStep` cannot be the first step in a sequence. A `FadeStep` defined as such will be ignored. */ public struct FadeStep: MarqueeStep { /** The desired time between this `FadeStep` and the preceding or subsequent `ScrollStep` in a sequence. `FadeSteps` with a negative `timeStep` value will be associated _only_ with an immediately-subsequent `ScrollStep` step in the sequence. `FadeSteps` with a positive `timeStep` value will be associated _only_ with an immediately-prior `ScrollStep` step in the sequence. - Note: A `FadeStep` with a `timeStep` value of 0.0 will have no effect, and is the same as defining the fade state with a `ScrollStep`. */ public let timeStep: CGFloat /** The animation curve to utilize between the previous fade state in a sequence and this step. */ public let timingFunction: UIView.AnimationCurve /** The option set defining the edge fade state for this fade step. Possible options include `.leading` and `.trailing`, corresponding to the leading edge of the label scrolling (i.e. the direction of scroll) and trailing edge of the label. As an Option Set type, both edge fade states may be defined using an array literal: `[.leading, .trailing]`. */ public let edgeFades: EdgeFade public init(timeStep: CGFloat, timingFunction: UIView.AnimationCurve = .linear, edgeFades: EdgeFade) { self.timeStep = timeStep self.timingFunction = timingFunction self.edgeFades = edgeFades } } public struct EdgeFade : OptionSet { public let rawValue: Int public static let leading = EdgeFade(rawValue: 1 << 0) public static let trailing = EdgeFade(rawValue: 1 << 1) public init(rawValue: Int) { self.rawValue = rawValue; } } // Define helpful typealiases fileprivate typealias MLAnimationCompletionBlock = (_ finished: Bool) -> () fileprivate typealias MLAnimation = (anim: CAKeyframeAnimation, duration: CGFloat) fileprivate class GradientSetupAnimation: CABasicAnimation { } fileprivate 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.next { if nextResponder is UIViewController { return nextResponder as? UIViewController } else if nextResponder is UIView { return nextResponder.traverseResponderChainForFirstViewController() } else { return nil } } return nil } } fileprivate 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 (abs(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 (abs(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.getControlPoint(at: i, values: &point) pointArray.append(CGPoint(x: CGFloat(point[0]), y: CGFloat(point[1]))) } return pointArray } }
mit
d69d701669c3bbd360382867a3d8a5c5
38.419424
283
0.618083
5.093216
false
false
false
false
monisun/warble
Warble/TwitterClient.swift
1
9966
// // TwitterClient.swift // Warble // // Created by Monica Sun on 5/20/15. // Copyright (c) 2015 Monica Sun. All rights reserved. // import UIKit // TODO store in plist let twitterConsumerKey = "EprTm2EfvGFT21BnsUNZyOd0r" let twitterConsumerSecret = "syq358u0WF9HCeeGKLuvqTwf6gwihrNLkrLQebmwam6TyGxDar" let twitterBaseURL = NSURL(string: "https://api.twitter.com") class TwitterClient: BDBOAuth1RequestOperationManager { var loginCompletion: ((user: User?, error: NSError?) -> ())? class var sharedInstance: TwitterClient { struct Static { static let instance = TwitterClient(baseURL: twitterBaseURL, consumerKey: twitterConsumerKey, consumerSecret: twitterConsumerSecret) } return Static.instance } func loginWithCompletion(completion: (user: User?, error: NSError?) -> ()) { loginCompletion = completion // fetch request token & redirect to authorization page TwitterClient.sharedInstance.requestSerializer.removeAccessToken() TwitterClient.sharedInstance.fetchRequestTokenWithPath("oauth/request_token", method: "GET", callbackURL: NSURL(string: "warble://oauth"), scope: nil, success: { (requestToken: BDBOAuth1Credential!) -> Void in NSLog("Successfully got the request token.") var authURL = NSURL(string: "https://api.twitter.com/oauth/authorize?oauth_token=\(requestToken.token)") UIApplication.sharedApplication().openURL(authURL!) }) { (error: NSError!) -> Void in NSLog("Error getting request token.") self.loginCompletion?(user: nil, error: error) } } func openURL(url: NSURL) { fetchAccessTokenWithPath("oauth/access_token", method: "POST", requestToken: BDBOAuth1Credential(queryString: url.query), success: { (accessToken: BDBOAuth1Credential!) -> Void in NSLog("Successfully got the access token.") TwitterClient.sharedInstance.requestSerializer.saveAccessToken(accessToken) // verify credentials and get current user TwitterClient.sharedInstance.GET("1.1/account/verify_credentials.json", parameters: nil, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in // var dict = NSJSONSerialization.JSONObjectWithData(response! as! NSData, options: nil, error: nil) as! NSDictionary var user = User(dict: response as! NSDictionary) User.currentUser = user NSLog("Successfully serialized user: \(user) with username: \(user.name)") self.loginCompletion?(user: user, error: nil)}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in NSLog("Error getting current user.") self.loginCompletion?(user: nil, error: error) }) }) { (error: NSError!) -> Void in NSLog("Failed to retrieve access token/") self.loginCompletion?(user: nil, error: error!) } } func homeTimelineWithParams(params: NSDictionary?, maxId: Int?, completion: (tweets: [Tweet]?, minId: Int?, error: NSError?) -> ()) { // get home timeline var homeTimelineUrl = "1.1/statuses/home_timeline.json?count=200" if let maxId = maxId as Int! { homeTimelineUrl += "&max_id=\(maxId)" } homeTimelineUrl = homeTimelineUrl.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! GET(homeTimelineUrl, parameters: nil, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in // var homeTimelineAsJson = NSJSONSerialization.JSONObjectWithData(response! as? NSArray, options: nil, error: nil) as! [NSDictionary] NSLog("Successfully got home timeline.") var tweetsData = Tweet.tweetsWithArray(response as! [NSDictionary]) as ([Tweet], Int) var tweets = tweetsData.0 var minId = tweetsData.1 completion(tweets: tweets, minId: minId, error: nil)}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in NSLog("Error getting home timeline: \(error.description)") completion(tweets: nil, minId: nil, error: error) }) } func tweetWithStatus(status: String, replyToTweetId: Int?, completion: (result: NSDictionary?, error: NSError?) -> ()) { var tweetJSONUrl = "1.1/statuses/update.json?status=" + status if let replyToId = replyToTweetId as Int? { tweetJSONUrl = tweetJSONUrl + "&in_reply_to_status_id=\(replyToId)" } tweetJSONUrl = tweetJSONUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! POST(tweetJSONUrl, parameters: nil, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in NSLog("Successfully tweeted with status.") completion(result: response as? NSDictionary, error: nil)}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in NSLog("Error posting new tweet: \(error.description)") completion(result: nil, error: error) }) } func retweet(id: Int, completion: (result: NSDictionary?, error: NSError?) -> ()) { var retweetJSONUrl = "1.1/statuses/retweet/\(id).json" retweetJSONUrl = retweetJSONUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! POST(retweetJSONUrl, parameters: nil, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in NSLog("Successfully retweeted a tweet.") completion(result: response as? NSDictionary, error: nil)}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in NSLog("Error retweeting: \(error.description)") completion(result: nil, error: error) }) } func destroy(id: Int, completion: (result: NSDictionary?, error: NSError?) -> ()) { var retweetJSONUrl = "1.1/statuses/destroy/\(id).json" retweetJSONUrl = retweetJSONUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! POST(retweetJSONUrl, parameters: nil, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in NSLog("Successfully destroyed a tweet.") completion(result: response as? NSDictionary, error: nil)}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in NSLog("Error destroying tweet: \(error.description)") completion(result: nil, error: error) }) } func createFavorite(id: Int, completion: (result: NSDictionary?, error: NSError?) -> ()) { var createFavoriteJSONUrl = "1.1/favorites/create.json?id=\(id)" createFavoriteJSONUrl = createFavoriteJSONUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! POST(createFavoriteJSONUrl, parameters: nil, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in NSLog("SUCCESS: Request create favorite.") completion(result: response as? NSDictionary, error: nil)}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in NSLog("Error in create favorite: \(error.description)") completion(result: nil, error: error) }) } func destroyFavorite(id: Int, completion: (result: NSDictionary?, error: NSError?) -> ()) { var destroyFavoriteJSONUrl = "1.1/favorites/destroy.json?id=\(id)" destroyFavoriteJSONUrl = destroyFavoriteJSONUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! POST(destroyFavoriteJSONUrl, parameters: nil, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in NSLog("SUCCESS: Request destroy favorite.") completion(result: response as? NSDictionary, error: nil)}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in NSLog("Error in destroy favorite: \(error.description)") completion(result: nil, error: error) }) } func searchTweets(q: String, completion: (tweets: [Tweet]?, minId: Int?, error: NSError?) -> ()) { // search for top 20 tweets var trimmedQ = q.stringByReplacingOccurrencesOfString(" ", withString: "") var searchUrl = "1.1/search/tweets.json?q=\(trimmedQ)&count=20" searchUrl = searchUrl.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! GET(searchUrl, parameters: nil, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in NSLog("Successfully got search results home timeline.") var tweetsData = Tweet.tweetsWithArray(response["statuses"] as! [NSDictionary]) as ([Tweet], Int) var tweets = tweetsData.0 var minId = tweetsData.1 completion(tweets: tweets, minId: minId, error: nil)}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in NSLog("Error getting home timeline: \(error.description)") completion(tweets: nil, minId: nil, error: error) }) } }
mit
172f109a63def733f22ef0e0b3517b5b
50.90625
159
0.61459
5.040971
false
false
false
false
SwiftAndroid/swift
test/Constraints/bridging.swift
2
15600
// RUN: %target-parse-verify-swift // REQUIRES: objc_interop import Foundation // FIXME: Should go into the standard library. public extension _ObjectiveCBridgeable { static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?) -> Self { var result: Self? = nil _forceBridgeFromObjectiveC(source!, result: &result) return result! } } public class BridgedClass : NSObject, NSCopying { @objc(copyWithZone:) public func copy(with zone: NSZone?) -> AnyObject { return self } } public class BridgedClassSub : BridgedClass { } // Attempt to bridge to a non-whitelisted type from another module. extension LazyFilterIterator : _ObjectiveCBridgeable { // expected-error{{conformance of 'LazyFilterIterator' to '_ObjectiveCBridgeable' can only be written in module 'Swift'}} public typealias _ObjectiveCType = BridgedClassSub public static func _isBridgedToObjectiveC() -> Bool { return true } public func _bridgeToObjectiveC() -> _ObjectiveCType { return BridgedClassSub() } public static func _forceBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout LazyFilterIterator? ) { } public static func _conditionallyBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout LazyFilterIterator? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?) -> LazyFilterIterator { let result: LazyFilterIterator? return result! } } struct BridgedStruct : Hashable, _ObjectiveCBridgeable { var hashValue: Int { return 0 } static func _isBridgedToObjectiveC() -> Bool { return true } func _bridgeToObjectiveC() -> BridgedClass { return BridgedClass() } static func _forceBridgeFromObjectiveC( _ x: BridgedClass, result: inout BridgedStruct?) { } static func _conditionallyBridgeFromObjectiveC( _ x: BridgedClass, result: inout BridgedStruct? ) -> Bool { return true } } func ==(x: BridgedStruct, y: BridgedStruct) -> Bool { return true } struct NotBridgedStruct : Hashable { var hashValue: Int { return 0 } } func ==(x: NotBridgedStruct, y: NotBridgedStruct) -> Bool { return true } class OtherClass : Hashable { var hashValue: Int { return 0 } } func ==(x: OtherClass, y: OtherClass) -> Bool { return true } // Basic bridging func bridgeToObjC(_ s: BridgedStruct) -> BridgedClass { return s return s as BridgedClass } func bridgeToAnyObject(_ s: BridgedStruct) -> AnyObject { return s return s as AnyObject } func bridgeFromObjC(_ c: BridgedClass) -> BridgedStruct { return c // expected-error{{'BridgedClass' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} return c as BridgedStruct } func bridgeFromObjCDerived(_ s: BridgedClassSub) -> BridgedStruct { return s // expected-error{{'BridgedClassSub' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} return s as BridgedStruct } // Array -> NSArray func arrayToNSArray() { var nsa: NSArray nsa = [AnyObject]() nsa = [BridgedClass]() nsa = [OtherClass]() nsa = [BridgedStruct]() nsa = [NotBridgedStruct]() // expected-error{{cannot assign value of type '[NotBridgedStruct]' to type 'NSArray'}} nsa = [AnyObject]() as NSArray nsa = [BridgedClass]() as NSArray nsa = [OtherClass]() as NSArray nsa = [BridgedStruct]() as NSArray nsa = [NotBridgedStruct]() as NSArray // expected-error{{cannot convert value of type '[NotBridgedStruct]' to type 'NSArray' in coercion}} _ = nsa } // NSArray -> Array func nsArrayToArray(_ nsa: NSArray) { var arr1: [AnyObject] = nsa // expected-error{{'NSArray' is not implicitly convertible to '[AnyObject]'; did you mean to use 'as' to explicitly convert?}} {{30-30= as [AnyObject]}} var _: [BridgedClass] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedClass]'}} {{30-30= as! [BridgedClass]}} var _: [OtherClass] = nsa // expected-error{{'NSArray' is not convertible to '[OtherClass]'}} {{28-28= as! [OtherClass]}} var _: [BridgedStruct] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'}} {{31-31= as! [BridgedStruct]}} var _: [NotBridgedStruct] = nsa // expected-error{{cannot convert value of type 'NSArray' to specified type '[NotBridgedStruct]'}} var _: [AnyObject] = nsa as [AnyObject] var _: [BridgedClass] = nsa as [BridgedClass] // expected-error{{'NSArray' is not convertible to '[BridgedClass]'; did you mean to use 'as!' to force downcast?}} {{31-33=as!}} var _: [OtherClass] = nsa as [OtherClass] // expected-error{{'NSArray' is not convertible to '[OtherClass]'; did you mean to use 'as!' to force downcast?}} {{29-31=as!}} var _: [BridgedStruct] = nsa as [BridgedStruct] // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'; did you mean to use 'as!' to force downcast?}} {{32-34=as!}} var _: [NotBridgedStruct] = nsa as [NotBridgedStruct] // expected-error{{cannot convert value of type 'NSArray' to type '[NotBridgedStruct]' in coercion}} var arr6: Array = nsa as Array arr6 = arr1 arr1 = arr6 } func dictionaryToNSDictionary() { // FIXME: These diagnostics are awful. var nsd: NSDictionary nsd = [NSObject : AnyObject]() nsd = [NSObject : AnyObject]() as NSDictionary nsd = [NSObject : BridgedClass]() nsd = [NSObject : BridgedClass]() as NSDictionary nsd = [NSObject : OtherClass]() nsd = [NSObject : OtherClass]() as NSDictionary nsd = [NSObject : BridgedStruct]() nsd = [NSObject : BridgedStruct]() as NSDictionary nsd = [NSObject : NotBridgedStruct]() // expected-error{{cannot assign value of type '[NSObject : NotBridgedStruct]' to type 'NSDictionary'}} nsd = [NSObject : NotBridgedStruct]() as NSDictionary // expected-error{{cannot convert value of type '[NSObject : NotBridgedStruct]' to type 'NSDictionary' in coercion}} nsd = [NSObject : BridgedClass?]() // expected-error{{cannot assign value of type '[NSObject : BridgedClass?]' to type 'NSDictionary'}} nsd = [NSObject : BridgedClass?]() as NSDictionary // expected-error{{cannot convert value of type '[NSObject : BridgedClass?]' to type 'NSDictionary' in coercion}} nsd = [NSObject : BridgedStruct?]() // expected-error{{cannot assign value of type '[NSObject : BridgedStruct?]' to type 'NSDictionary'}} nsd = [NSObject : BridgedStruct?]() as NSDictionary //expected-error{{cannot convert value of type '[NSObject : BridgedStruct?]' to type 'NSDictionary' in coercion}} nsd = [BridgedClass : AnyObject]() nsd = [BridgedClass : AnyObject]() as NSDictionary nsd = [OtherClass : AnyObject]() nsd = [OtherClass : AnyObject]() as NSDictionary nsd = [BridgedStruct : AnyObject]() nsd = [BridgedStruct : AnyObject]() as NSDictionary nsd = [NotBridgedStruct : AnyObject]() // expected-error{{cannot assign value of type '[NotBridgedStruct : AnyObject]' to type 'NSDictionary'}} nsd = [NotBridgedStruct : AnyObject]() as NSDictionary // expected-error{{cannot convert value of type '[NotBridgedStruct : AnyObject]' to type 'NSDictionary' in coercion}} // <rdar://problem/17134986> var bcOpt: BridgedClass? nsd = [BridgedStruct() : bcOpt] // expected-error{{value of optional type 'BridgedClass?' not unwrapped; did you mean to use '!' or '?'?}} bcOpt = nil _ = nsd } // In this case, we should not implicitly convert Dictionary to NSDictionary. struct NotEquatable {} func notEquatableError(_ d: Dictionary<Int, NotEquatable>) -> Bool { // FIXME: Another awful diagnostic. return d == d // expected-error{{binary operator '==' cannot be applied to two 'Dictionary<Int, NotEquatable>' operands}} // expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: }} } // NSString -> String var nss1 = "Some great text" as NSString var nss2: NSString = ((nss1 as String) + ", Some more text") as NSString // <rdar://problem/17943223> var inferDouble = 1.0/10 let d: Double = 3.14159 inferDouble = d // rdar://problem/17962491 var inferDouble2 = 1 % 3 / 3.0 let d2: Double = 3.14159 inferDouble2 = d2 // rdar://problem/18269449 var i1: Int = 1.5 * 3.5 // expected-error{{cannot convert value of type 'Double' to expected argument type 'Int'}} // rdar://problem/18330319 func rdar18330319(_ s: String, d: [String : AnyObject]) { _ = d[s] as! String? } // rdar://problem/19551164 func rdar19551164a(_ s: String, _ a: [String]) {} func rdar19551164b(_ s: NSString, _ a: NSArray) { rdar19551164a(s, a) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{18-18= as String}} // expected-error@-1{{'NSArray' is not convertible to '[String]'; did you mean to use 'as!' to force downcast?}}{{21-21= as! [String]}} } // rdar://problem/19695671 func takesSet<T: Hashable>(_ p: Set<T>) {} // expected-note {{in call to function 'takesSet'}} func takesDictionary<K: Hashable, V>(_ p: Dictionary<K, V>) {} // expected-note {{in call to function 'takesDictionary'}} func takesArray<T>(_ t: Array<T>) {} // expected-note {{in call to function 'takesArray'}} func rdar19695671() { takesSet(NSSet() as! Set) // expected-error{{generic parameter 'T' could not be inferred}} takesDictionary(NSDictionary() as! Dictionary) // expected-error{{generic parameter 'K' could not be inferred}} takesArray(NSArray() as! Array) // expected-error{{generic parameter 'T' could not be inferred}} } // This failed at one point while fixing rdar://problem/19600325. func getArrayOfAnyObject(_: AnyObject) -> [AnyObject] { return [] } func testCallback(_ f: (AnyObject) -> AnyObject?) {} testCallback { return getArrayOfAnyObject($0) } // <rdar://problem/19724719> Type checker thinks "(optionalNSString ?? nonoptionalNSString) as String" is a forced cast func rdar19724719(_ f: (String) -> (), s1: NSString?, s2: NSString) { f((s1 ?? s2) as String) } // <rdar://problem/19770981> func rdar19770981(_ s: String, ns: NSString) { func f(_ s: String) {} f(ns) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7= as String}} f(ns as String) // 'as' has higher precedence than '>' so no parens are necessary with the fixit: s > ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{9-9= as String}} _ = s > ns as String ns > s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{5-5= as String}} _ = ns as String > s // 'as' has lower precedence than '+' so add parens with the fixit: s + ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7=(}}{{9-9= as String)}} _ = s + (ns as String) ns + s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{3-3=(}}{{5-5= as String)}} _ = (ns as String) + s } // <rdar://problem/19831919> Fixit offers as! conversions that are known to always fail func rdar19831919() { var s1 = 1 + "str"; // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note{{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} } // <rdar://problem/19831698> Incorrect 'as' fixits offered for invalid literal expressions func rdar19831698() { var v70 = true + 1 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Int'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}} var v71 = true + 1.0 // expected-error{{cannot convert value of type 'Bool' to expected argument type 'Double'}} var v72 = true + true // expected-error{{binary operator '+' cannot be applied to two 'Bool' operands}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}} var v73 = true + [] // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and '[_]'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}} var v75 = true + "str" // expected-error{{cannot convert value of type 'Bool' to expected argument type 'String'}} } // <rdar://problem/19836341> Incorrect fixit for NSString? to String? conversions func rdar19836341(_ ns: NSString?, vns: NSString?) { var vns = vns let _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} var _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} // FIXME: there should be a fixit appending "as String?" to the line; for now // it's sufficient that it doesn't suggest appending "as String" // Important part about below diagnostic is that from-type is described as // 'NSString?' and not '@lvalue NSString?': let _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} var _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} vns = ns } // <rdar://problem/20029786> Swift compiler sometimes suggests changing "as!" to "as?!" func rdar20029786(_ ns: NSString?) { var s: String = ns ?? "str" as String as String // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{19-19=(}} {{50-50=) as String}} var s2 = ns ?? "str" as String as String let s3: NSString? = "str" as String? var s4: String = ns ?? "str" // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{20-20=(}}{{31-31=) as String}} var s5: String = (ns ?? "str") as String // fixed version } // <rdar://problem/19813772> QoI: Using as! instead of as in this case produces really bad diagnostic func rdar19813772(_ nsma: NSMutableArray) { var a1 = nsma as! Array // expected-error{{generic parameter 'Element' could not be inferred in cast to 'Array<_>'}} // FIXME: The following diagnostic is misleading and should not happen: expected-warning@-1{{cast from 'NSMutableArray' to unrelated type 'Array<_>' always fails}} var a2 = nsma as! Array<AnyObject> // expected-warning{{forced cast from 'NSMutableArray' to 'Array<AnyObject>' always succeeds; did you mean to use 'as'?}} {{17-20=as}} var a3 = nsma as Array<AnyObject> } // <rdar://problem/20336036> QoI: Add cast-removing fixit for "Forced cast from 'T' to 'T' always succeeds" func force_cast_fixit(_ a : [NSString]) -> [NSString] { return a as! [NSString] // expected-warning {{forced cast of '[NSString]' to same type has no effect}} {{12-27=}} } // <rdar://problem/21244068> QoI: IUO prevents specific diagnostic + fixit about non-implicitly converted bridge types func rdar21244068(_ n: NSString!) -> String { return n // expected-error {{'NSString!' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{11-11= as String}} } func forceBridgeDiag(_ obj: BridgedClass!) -> BridgedStruct { return obj // expected-error{{'BridgedClass!' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}}{{13-13= as BridgedStruct}} }
apache-2.0
171c9d277467fbf7426bd46c6a4371f6
46.272727
305
0.696603
4.112839
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothGATT/GATTPnPID.swift
1
3810
// // GATTPnPID.swift // Bluetooth // // Created by Carlos Duclos on 6/21/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /** PnP ID [PnP ID](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.pnp_id.xml) The PnP_ID characteristic returns its value when read using the GATT Characteristic Value Read procedure. The PnP_ID characteristic is a set of values that used to create a device ID value that is unique for this device. Included in the characteristic is a Vendor ID Source field, a Vendor ID field, a Product ID field and a Product Version field. These values are used to identify all devices of a given type/model/version using numbers. - Note: The fields in the above table are in the order of LSO to MSO. Where LSO = Least Significant Octet and MSO = Most Significant Octet */ @frozen public struct GATTPnPID: GATTCharacteristic { public static var uuid: BluetoothUUID { return .pnpId } internal static let length = 7 public let vendorIdSource: VendorIDSource public let vendorId: UInt16 public let productId: UInt16 public let productVersion: UInt16 public init(vendorIdSource: VendorIDSource, vendorId: UInt16, productId: UInt16, productVersion: UInt16) { self.vendorIdSource = vendorIdSource self.vendorId = vendorId self.productId = productId self.productVersion = productVersion } public init?(data: Data) { guard data.count == type(of: self).length else { return nil } guard let vendorIdSource = VendorIDSource(rawValue: data[0]) else { return nil } let vendorId = UInt16(littleEndian: UInt16(bytes: (data[1], data[2]))) let productId = UInt16(littleEndian: UInt16(bytes: (data[3], data[4]))) let productVersion = UInt16(littleEndian: UInt16(bytes: (data[5], data[6]))) self.init(vendorIdSource: vendorIdSource, vendorId: vendorId, productId: productId, productVersion: productVersion) } public var data: Data { let vendorIdBytes = vendorId.littleEndian.bytes let productIdBytes = productId.littleEndian.bytes let productVersionBytes = productVersion.littleEndian.bytes return Data([vendorIdSource.rawValue, vendorIdBytes.0, vendorIdBytes.1, productIdBytes.0, productIdBytes.1, productVersionBytes.0, productVersionBytes.1]) } } extension GATTPnPID { public enum VendorIDSource: UInt8 { /// Bluetooth SIG assigned Company Identifier value from the Assigned Numbers document case fromAssignedNumbersDocument = 0x01 /// USB Implementer’s Forum assigned Vendor ID value case fromVendorIDValue = 0x02 } } extension GATTPnPID: Equatable { public static func == (lhs: GATTPnPID, rhs: GATTPnPID) -> Bool { return lhs.vendorIdSource == rhs.vendorIdSource && lhs.vendorId == rhs.vendorId && lhs.productId == rhs.productId && lhs.productVersion == rhs.productVersion } } extension GATTPnPID: CustomStringConvertible { public var description: String { return "\(vendorIdSource) \(vendorId) \(productId) \(productVersion)" } } extension GATTPnPID.VendorIDSource: Equatable { public static func == (lhs: GATTPnPID.VendorIDSource, rhs: GATTPnPID.VendorIDSource) -> Bool { return lhs.rawValue == rhs.rawValue } } extension GATTPnPID.VendorIDSource: CustomStringConvertible { public var description: String { return rawValue.description } }
mit
891356a15c1a41535492dad4a9f05699
30.46281
333
0.663777
4.331058
false
false
false
false
kesun421/firefox-ios
Client/Frontend/Browser/TabTrayButtonExtensions.swift
3
1854
/* 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 UIKit class PrivateModeButton: ToggleButton { var light: Bool = false override init(frame: CGRect) { super.init(frame: frame) self.accessibilityLabel = PrivateModeStrings.toggleAccessibilityLabel self.accessibilityHint = PrivateModeStrings.toggleAccessibilityHint let maskImage = UIImage(named: "smallPrivateMask")?.withRenderingMode(.alwaysTemplate) self.setImage(maskImage, for: UIControlState()) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func styleForMode(privateMode isPrivate: Bool) { self.tintColor = isPrivate ? UIColor(rgb: 0xf9f9fa) : UIColor(rgb: 0x272727) self.imageView?.tintColor = self.tintColor self.isSelected = isPrivate self.accessibilityValue = isPrivate ? PrivateModeStrings.toggleAccessibilityValueOn : PrivateModeStrings.toggleAccessibilityValueOff } } extension UIButton { static func newTabButton() -> UIButton { let newTab = UIButton() newTab.setImage(UIImage.templateImageNamed("quick_action_new_tab"), for: .normal) newTab.accessibilityLabel = NSLocalizedString("New Tab", comment: "Accessibility label for the New Tab button in the tab toolbar.") return newTab } } extension TabsButton { static func tabTrayButton() -> TabsButton { let tabsButton = TabsButton() tabsButton.countLabel.text = "0" tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility Label for the tabs button in the tab toolbar") return tabsButton } }
mpl-2.0
eb0d46b8ac2f933cbb5652ce087958f4
39.304348
141
0.702805
4.957219
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/FacebookCore/Sources/Core/AppEvents/AppEvent.Builtin.swift
16
14738
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright 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 FBSDKCoreKit.FBSDKAppEvents //-------------------------------------- // MARK: - General //-------------------------------------- extension AppEvent { /** Create an event that indicates that the user has completed registration. - parameter registrationMethod: Optional registration method used. - parameter valueToSum: Optional value to sum. - parameter extraParameters: Optional dictionary of extra parameters. - returns: An app event that can be logged via `AppEventsLogger`. */ public static func completedRegistration(registrationMethod: String? = nil, valueToSum: Double? = nil, extraParameters: ParametersDictionary = [:]) -> AppEvent { var parameters = extraParameters registrationMethod.onSome({ parameters[.registrationMethod] = $0 }) return AppEvent(name: .completedRegistration, parameters: parameters, valueToSum: valueToSum) } /** Create an event that indicates that the user has completed tutorial. - parameter successful: Optional boolean value that indicates whether operation was succesful. - parameter valueToSum: Optional value to sum. - parameter extraParameters: Optional dictionary of extra parameters. - returns: An app event that can be logged via `AppEventsLogger`. */ public static func completedTutorial(successful: Bool? = nil, valueToSum: Double? = nil, extraParameters: ParametersDictionary = [:]) -> AppEvent { var parameters = extraParameters successful.onSome({ parameters[.successful] = $0 ? FBSDKAppEventParameterValueYes : FBSDKAppEventParameterValueNo }) return AppEvent(name: .completedTutorial, parameters: parameters, valueToSum: valueToSum) } /** Create an event that indicates that the user viewed specific content. - parameter contentType: Optional content type. - parameter contentId: Optional content identifier. - parameter currency: Optional string representation of currency. - parameter valueToSum: Optional value to sum. - parameter extraParameters: Optional dictionary of extra parameters. - returns: An app event that can be logged via `AppEventsLogger`. */ public static func viewedContent(contentType: String? = nil, contentId: String? = nil, currency: String? = nil, valueToSum: Double? = nil, extraParameters: ParametersDictionary = [:]) -> AppEvent { var parameters = extraParameters contentType.onSome({ parameters[.contentType] = $0 }) contentId.onSome({ parameters[.contentId] = $0 }) currency.onSome({ parameters[.currency] = $0 }) return AppEvent(name: .viewedContent, parameters: parameters, valueToSum: valueToSum) } /** Create an event that indicatest that the user has performed a search within the app. - parameter contentId: Optional content identifer. - parameter searchedString: Optional searched string. - parameter successful: Optional boolean value that indicatest whether the operation was succesful. - parameter valueToSum: Optional value to sum. - parameter extraParameters: Optional dictionary of extra parameters. - returns: An app event that can be logged via `AppEventsLogger`. */ public static func searched(contentId: String? = nil, searchedString: String? = nil, successful: Bool? = nil, valueToSum: Double? = nil, extraParameters: ParametersDictionary = [:]) -> AppEvent { var parameters = extraParameters contentId.onSome({ parameters[.contentId] = $0 }) searchedString.onSome({ parameters[.searchedString] = $0 }) successful.onSome({ parameters[.successful] = $0 ? FBSDKAppEventParameterValueYes : FBSDKAppEventParameterValueNo }) return AppEvent(name: .searched, parameters: parameters, valueToSum: valueToSum) } /** Create an event that indicatest the user has rated an item in the app. - parameter contentType: Optional type of the content. - parameter contentId: Optional content identifier. - parameter maxRatingValue: Optional max rating value. - parameter valueToSum: Optional value to sum. - parameter extraParameters: Optional dictionary of extra parameters. - returns: An app event that can be logged via `AppEventsLogger`. */ public static func rated<T: UnsignedInteger>(contentType: String? = nil, contentId: String? = nil, maxRatingValue: T? = nil, valueToSum: Double? = nil, extraParameters: ParametersDictionary = [:]) -> AppEvent { var parameters = extraParameters contentType.onSome({ parameters[.contentType] = $0 }) contentId.onSome({ parameters[.contentId] = $0 }) maxRatingValue.onSome({ parameters[.maxRatingValue] = NSNumber(value: $0.toUIntMax() as UInt64) }) return AppEvent(name: .rated, parameters: parameters, valueToSum: valueToSum) } } //-------------------------------------- // MARK: - Commerce //-------------------------------------- extension AppEvent { /** Create an app event that a user has purchased something in the application. - parameter amount: An amount of purchase. - parameter currency: Optional string representation of currency. - parameter extraParameters: Optional dictionary of extra parameters. - returns: An app event that can be logged via `AppEventsLogger`. */ public static func purchased(amount: Double, currency: String? = nil, extraParameters: ParametersDictionary = [:]) -> AppEvent { var parameters = extraParameters currency.onSome({ parameters[.currency] = $0 }) return AppEvent(name: .purchased, parameters: parameters, valueToSum: amount) } /** Create an app event that indicatest that user has added an item to the cart. - parameter contentType: Optional content type. - parameter contentId: Optional content identifier. - parameter currency: Optional string representation of currency. - parameter valueToSum: Optional value to sum. - parameter extraParameters: Optional dictionary of extra parameters. - returns: An app event that can be logged via `AppEventsLogger`. */ public static func addedToCart(contentType: String? = nil, contentId: String? = nil, currency: String? = nil, valueToSum: Double? = nil, extraParameters: ParametersDictionary = [:]) -> AppEvent { var parameters = extraParameters contentType.onSome({ parameters[.contentType] = $0 }) contentId.onSome({ parameters[.contentId] = $0 }) currency.onSome({ parameters[.currency] = $0 }) return AppEvent(name: .addedToCart, parameters: parameters, valueToSum: valueToSum) } /** Create an app event that indicates that user added an item to the wishlist. - parameter contentType: Optional content type. - parameter contentId: Optional content identifier. - parameter currency: Optional string representation of currency. - parameter valueToSum: Optional value to sum. - parameter extraParameters: Optional dictionary of extra parameters. - returns: An app event that can be logged via `AppEventsLogger`. */ public static func addedToWishlist(contentType: String? = nil, contentId: String? = nil, currency: String? = nil, valueToSum: Double? = nil, extraParameters: ParametersDictionary = [:]) -> AppEvent { var parameters = extraParameters contentType.onSome({ parameters[.contentType] = $0 }) contentId.onSome({ parameters[.contentId] = $0 }) currency.onSome({ parameters[.currency] = $0 }) return AppEvent(name: .addedToWishlist, parameters: parameters, valueToSum: valueToSum) } /** Create an event that indicatest that a user added payment information. - parameter successful: Optional boolean value that indicates whether operation was succesful. - parameter valueToSum: Optional value to sum. - parameter extraParameters: Optional dictionary of extra parameters. - returns: An app event that can be logged via `AppEventsLogger`. */ public static func addedPaymentInfo(successful: Bool? = nil, valueToSum: Double? = nil, extraParameters: ParametersDictionary = [:]) -> AppEvent { var parameters = extraParameters successful.onSome({ parameters[.successful] = $0 ? FBSDKAppEventParameterValueYes : FBSDKAppEventParameterValueNo }) return AppEvent(name: .addedPaymentInfo, parameters: parameters, valueToSum: valueToSum) } /** Create an event that indicatest that a user has initiated a checkout. - parameter contentType: Optional content type. - parameter contentId: Optional content identifier. - parameter itemCount: Optional count of items. - parameter paymentInfoAvailable: Optional boolean value that indicatest whether payment info is available. - parameter currency: Optional string representation of currency. - parameter valueToSum: Optional value to sum. - parameter extraParameters: Optional dictionary of extra parameters. - returns: An app event that can be logged via `AppEventsLogger`. */ public static func initiatedCheckout<T: UnsignedInteger>(contentType: String? = nil, contentId: String? = nil, itemCount: T? = nil, paymentInfoAvailable: Bool? = nil, currency: String? = nil, valueToSum: Double? = nil, extraParameters: ParametersDictionary = [:]) -> AppEvent { var parameters = extraParameters contentType.onSome({ parameters[.contentType] = $0 }) contentId.onSome({ parameters[.contentId] = $0 }) itemCount.onSome({ parameters[.itemCount] = NSNumber(value: $0.toUIntMax() as UInt64) }) paymentInfoAvailable.onSome({ parameters[.paymentInfoAvailable] = $0 ? FBSDKAppEventParameterValueYes : FBSDKAppEventParameterValueNo }) currency.onSome({ parameters[.currency] = $0 }) return AppEvent(name: .initiatedCheckout, parameters: parameters, valueToSum: valueToSum) } } //-------------------------------------- // MARK: - Gaming //-------------------------------------- extension AppEvent { /** Create an app event that indicates that a user has achieved a level in the application. - parameter level: Optional level achieved. Can be either a `String` or `NSNumber`. - parameter valueToSum: Optional value to sum. - parameter extraParameters: Optional dictionary of extra parameters. - returns: An app event that can be logged via `AppEventsLogger`. */ public static func achievedLevel(level: AppEventParameterValueType? = nil, valueToSum: Double? = nil, extraParameters: ParametersDictionary = [:]) -> AppEvent { var parameters = extraParameters level.onSome({ parameters[.level] = $0 }) return AppEvent(name: .achievedLevel, parameters: parameters, valueToSum: valueToSum) } /** Create an app event that indicatest that a user has unlocked an achievement. - parameter description: Optional achievement description. - parameter valueToSum: Optional value to sum. - parameter extraParameters: Optional dictionary of extra parameters. - returns: An app event that can be logged via `AppEventsLogger`. */ public static func unlockedAchievement(description: String? = nil, valueToSum: Double? = nil, extraParameters: ParametersDictionary = [:]) -> AppEvent { var parameters = extraParameters description.onSome({ parameters[.Description] = $0 }) return AppEvent(name: .unlockedAchievement, parameters: parameters, valueToSum: valueToSum) } /** Create an event that indicatest that a user spent in-app credits. - parameter contentType: Optional content type. - parameter contentId: Optional content identifier. - parameter valueToSum: Optional value to sum. - parameter extraParameters: Optional dictionary of extra parameters. - returns: An app event that can be logged via `AppEventsLogger`. */ public static func spentCredits(contentType: String? = nil, contentId: String? = nil, valueToSum: Double? = nil, extraParameters: ParametersDictionary = [:]) -> AppEvent { var parameters = extraParameters contentType.onSome({ parameters[.contentType] = $0 }) contentId.onSome({ parameters[.contentId] = $0 }) return AppEvent(name: .spentCredits, parameters: parameters, valueToSum: valueToSum) } }
mit
74aff37189be772b8500d98fe00767c7
47.006515
120
0.643846
5.149546
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Model/RealmModel/ClothingSizeConvert/BabyWearSizeConvertInfo.swift
1
956
// // BabyWearSizeConvertInfo.swift // selluv-ios // // Created by 조백근 on 2016. 12. 8.. // Copyright © 2016년 BitBoy Labs. All rights reserved. // import RealmSwift class BabyWearSizeConvertInfo: Object { dynamic var std = "" dynamic var age = "" public func setupIndexes() { self.std.indexTag = 0 self.age.indexTag = 1 } public static func displayNamesByTag() -> [String] { return [SIZE_AGE] } public static func propertyName(displayName: String) -> String { if displayName == SIZE_AGE { return "age"} return "" } public static func propertyIndex(displayName: String) -> String { if displayName == SIZE_AGE { return "0"} return "99" } public func sizeValues() -> [String] { return [(self.age.copy() as! String)] } override static func primaryKey() -> String? { return "std" } }
mit
73bb7e1740b0ff9a885f7e4b9901546f
21.547619
69
0.578669
4.117391
false
false
false
false
Donny8028/Swift-TinyFeatures
SpotlightSearch/SpotlightSearch/MovieDetailsViewController.swift
1
1517
// // MovieDetailsViewController.swift // SpotIt // // Created by Gabriel Theodoropoulos on 11/11/15. // Copyright © 2015 Appcoda. All rights reserved. // import UIKit class MovieDetailsViewController: UIViewController { @IBOutlet weak var imgMovieImage: UIImageView! @IBOutlet weak var lblTitle: UILabel! @IBOutlet weak var lblCategory: UILabel! @IBOutlet weak var lblDescription: UILabel! @IBOutlet weak var lblDirector: UILabel! @IBOutlet weak var lblStars: UILabel! @IBOutlet weak var lblRating: UILabel! var movie: [String:String]? override func viewDidLoad() { super.viewDidLoad() setView() // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) lblRating.layer.cornerRadius = lblRating.frame.size.width/2 lblRating.layer.masksToBounds = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setView() { imgMovieImage?.image = UIImage(named: movie!["Image"]!) lblTitle?.text = movie!["Title"] lblCategory?.text = movie!["Category"] lblDescription?.text = movie!["Description"] lblDirector?.text = movie!["Director"] lblStars?.text = movie!["Stars"] lblRating?.text = movie!["Rating"] } }
mit
bd658ba4958cdae771abc9fd96ae5f01
25.137931
67
0.635884
4.797468
false
false
false
false
danielmartin/swift
stdlib/public/core/StringStorage.swift
1
23887
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims // Having @objc stuff in an extension creates an ObjC category, which we don't // want. #if _runtime(_ObjC) internal protocol _AbstractStringStorage : _NSCopying { var asString: String { get } var count: Int { get } var isASCII: Bool { get } var start: UnsafePointer<UInt8> { get } var length: Int { get } // In UTF16 code units. } internal let _cocoaASCIIEncoding:UInt = 1 /* NSASCIIStringEncoding */ internal let _cocoaUTF8Encoding:UInt = 4 /* NSUTF8StringEncoding */ @_effects(readonly) private func _isNSString(_ str:AnyObject) -> UInt8 { return _swift_stdlib_isNSString(str) } #else internal protocol _AbstractStringStorage { var asString: String { get } var count: Int { get } var isASCII: Bool { get } var start: UnsafePointer<UInt8> { get } } #endif extension _AbstractStringStorage { // ObjC interfaces. #if _runtime(_ObjC) @inline(__always) @_effects(releasenone) internal func _getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, _ aRange: _SwiftNSRange ) { _precondition(aRange.location >= 0 && aRange.length >= 0, "Range out of bounds") _precondition(aRange.location + aRange.length <= Int(count), "Range out of bounds") let range = Range( uncheckedBounds: (aRange.location, aRange.location+aRange.length)) let str = asString str._copyUTF16CodeUnits( into: UnsafeMutableBufferPointer(start: buffer, count: range.count), range: range) } @inline(__always) @_effects(releasenone) internal func _getCString( _ outputPtr: UnsafeMutablePointer<UInt8>, _ maxLength: Int, _ encoding: UInt ) -> Int8 { switch (encoding, isASCII) { case (_cocoaASCIIEncoding, true): fallthrough case (_cocoaUTF8Encoding, _): guard maxLength >= count + 1 else { return 0 } let buffer = UnsafeMutableBufferPointer(start: outputPtr, count: maxLength) buffer.initialize(from: UnsafeBufferPointer(start: start, count: count)) buffer[count] = 0 return 1 default: return _cocoaGetCStringTrampoline(self, outputPtr, maxLength, encoding) } } @inline(__always) @_effects(readonly) internal func _cString(encoding: UInt) -> UnsafePointer<UInt8>? { switch (encoding, isASCII) { case (_cocoaASCIIEncoding, true): fallthrough case (_cocoaUTF8Encoding, _): return start default: return _cocoaCStringUsingEncodingTrampoline(self, encoding) } } @_effects(readonly) internal func _nativeIsEqual<T:_AbstractStringStorage>( _ nativeOther: T ) -> Int8 { if count != nativeOther.count { return 0 } return (start == nativeOther.start || (memcmp(start, nativeOther.start, count) == 0)) ? 1 : 0 } @inline(__always) @_effects(readonly) internal func _isEqual(_ other: AnyObject?) -> Int8 { guard let other = other else { return 0 } if self === other { return 1 } // Handle the case where both strings were bridged from Swift. // We can't use String.== because it doesn't match NSString semantics. let knownOther = _KnownCocoaString(other) switch knownOther { case .storage: return _nativeIsEqual( _unsafeUncheckedDowncast(other, to: _StringStorage.self)) case .shared: return _nativeIsEqual( _unsafeUncheckedDowncast(other, to: _SharedStringStorage.self)) #if !(arch(i386) || arch(arm)) case .tagged: fallthrough #endif case .cocoa: // We're allowed to crash, but for compatibility reasons NSCFString allows // non-strings here. if _isNSString(other) != 1 { return 0 } // At this point we've proven that it is an NSString of some sort, but not // one of ours. if length != _stdlib_binary_CFStringGetLength(other) { return 0 } defer { _fixLifetime(other) } // CFString will only give us ASCII bytes here, but that's fine. // We already handled non-ASCII UTF8 strings earlier since they're Swift. if let otherStart = _cocoaUTF8Pointer(other) { return (start == otherStart || (memcmp(start, otherStart, count) == 0)) ? 1 : 0 } /* The abstract implementation of -isEqualToString: falls back to -compare: immediately, so when we run out of fast options to try, do the same. We can likely be more clever here if need be */ return _cocoaStringCompare(self, other) == 0 ? 1 : 0 } } #endif //_runtime(_ObjC) } private typealias CountAndFlags = _StringObject.CountAndFlags // // TODO(String docs): Documentation about the runtime layout of these instances, // which is a little complex. The second trailing allocation holds an // Optional<_StringBreadcrumbs>. // final internal class _StringStorage : __SwiftNativeNSString, _AbstractStringStorage { #if arch(i386) || arch(arm) // The total allocated storage capacity. Note that this includes the required // nul-terminator. internal var _realCapacity: Int internal var _count: Int internal var _flags: UInt16 internal var _reserved: UInt16 @inline(__always) internal var count: Int { return _count } @inline(__always) internal var _countAndFlags: _StringObject.CountAndFlags { return CountAndFlags(count: _count, flags: _flags) } #else // The capacity of our allocation. Note that this includes the nul-terminator, // which is not available for overriding. internal var _realCapacityAndFlags: UInt64 internal var _countAndFlags: _StringObject.CountAndFlags @inline(__always) internal var count: Int { return _countAndFlags.count } // The total allocated storage capacity. Note that this includes the required // nul-terminator. @inline(__always) internal var _realCapacity: Int { return Int(truncatingIfNeeded: _realCapacityAndFlags & CountAndFlags.countMask) } #endif @inline(__always) final internal var isASCII: Bool { return _countAndFlags.isASCII } final internal var asString: String { @_effects(readonly) @inline(__always) get { return String(_StringGuts(self)) } } #if _runtime(_ObjC) @objc(length) final internal var length: Int { @_effects(readonly) @inline(__always) get { return asString.utf16.count // UTF16View special-cases ASCII for us. } } @objc final internal var hash: UInt { @_effects(readonly) get { if isASCII { return _cocoaHashASCIIBytes(start, length: count) } return _cocoaHashString(self) } } @objc(characterAtIndex:) @_effects(readonly) final internal func character(at offset: Int) -> UInt16 { let str = asString return str.utf16[str._toUTF16Index(offset)] } @objc(getCharacters:range:) @_effects(releasenone) final internal func getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange ) { _getCharacters(buffer, aRange) } @objc(_fastCStringContents:) @_effects(readonly) final internal func _fastCStringContents( _ requiresNulTermination: Int8 ) -> UnsafePointer<CChar>? { if isASCII { return start._asCChar } return nil } @objc(UTF8String) @_effects(readonly) final internal func _utf8String() -> UnsafePointer<UInt8>? { return start } @objc(cStringUsingEncoding:) @_effects(readonly) final internal func cString(encoding: UInt) -> UnsafePointer<UInt8>? { return _cString(encoding: encoding) } @objc(getCString:maxLength:encoding:) @_effects(releasenone) final internal func getCString( _ outputPtr: UnsafeMutablePointer<UInt8>, maxLength: Int, encoding: UInt ) -> Int8 { return _getCString(outputPtr, maxLength, encoding) } @objc final internal var fastestEncoding: UInt { @_effects(readonly) get { if isASCII { return _cocoaASCIIEncoding } return _cocoaUTF8Encoding } } @objc(isEqualToString:) @_effects(readonly) final internal func isEqual(to other: AnyObject?) -> Int8 { return _isEqual(other) } @objc(copyWithZone:) final internal func copy(with zone: _SwiftNSZone?) -> AnyObject { // While _StringStorage instances aren't immutable in general, // mutations may only occur when instances are uniquely referenced. // Therefore, it is safe to return self here; any outstanding Objective-C // reference will make the instance non-unique. return self } #endif // _runtime(_ObjC) private init(_doNotCallMe: ()) { _internalInvariantFailure("Use the create method") } deinit { _breadcrumbsAddress.deinitialize(count: 1) } } // Determine the actual number of code unit capacity to request from malloc. We // round up the nearest multiple of 8 that isn't a mulitple of 16, to fully // utilize malloc's small buckets while accounting for the trailing // _StringBreadCrumbs. // // NOTE: We may still under-utilize the spare bytes from the actual allocation // for Strings ~1KB or larger, though at this point we're well into our growth // curve. private func determineCodeUnitCapacity(_ desiredCapacity: Int) -> Int { #if arch(i386) || arch(arm) // FIXME: Adapt to actual 32-bit allocator. For now, let's arrange things so // that the instance size will be a multiple of 4. let bias = Int(bitPattern: _StringObject.nativeBias) let minimum = bias + desiredCapacity + 1 let size = (minimum + 3) & ~3 _internalInvariant(size % 4 == 0) let capacity = size - bias _internalInvariant(capacity > desiredCapacity) return capacity #else // Bigger than _SmallString, and we need 1 extra for nul-terminator. let minCap = 1 + Swift.max(desiredCapacity, _SmallString.capacity) _internalInvariant(minCap < 0x1_0000_0000_0000, "max 48-bit length") // Round up to the nearest multiple of 8 that isn't also a multiple of 16. let capacity = ((minCap + 7) & -16) + 8 _internalInvariant( capacity > desiredCapacity && capacity % 8 == 0 && capacity % 16 != 0) return capacity #endif } // Creation extension _StringStorage { @_effects(releasenone) private static func create( realCodeUnitCapacity: Int, countAndFlags: CountAndFlags ) -> _StringStorage { let storage = Builtin.allocWithTailElems_2( _StringStorage.self, realCodeUnitCapacity._builtinWordValue, UInt8.self, 1._builtinWordValue, Optional<_StringBreadcrumbs>.self) #if arch(i386) || arch(arm) storage._realCapacity = realCodeUnitCapacity storage._count = countAndFlags.count storage._flags = countAndFlags.flags #else storage._realCapacityAndFlags = UInt64(truncatingIfNeeded: realCodeUnitCapacity) storage._countAndFlags = countAndFlags #endif storage._breadcrumbsAddress.initialize(to: nil) storage.terminator.pointee = 0 // nul-terminated // NOTE: We can't _invariantCheck() now, because code units have not been // initialized. But, _StringGuts's initializer will. return storage } @_effects(releasenone) private static func create( capacity: Int, countAndFlags: CountAndFlags ) -> _StringStorage { _internalInvariant(capacity >= countAndFlags.count) let realCapacity = determineCodeUnitCapacity(capacity) _internalInvariant(realCapacity > capacity) return _StringStorage.create( realCodeUnitCapacity: realCapacity, countAndFlags: countAndFlags) } @_effects(releasenone) internal static func create( initializingFrom bufPtr: UnsafeBufferPointer<UInt8>, capacity: Int, isASCII: Bool ) -> _StringStorage { let countAndFlags = CountAndFlags( mortalCount: bufPtr.count, isASCII: isASCII) _internalInvariant(capacity >= bufPtr.count) let storage = _StringStorage.create( capacity: capacity, countAndFlags: countAndFlags) let addr = bufPtr.baseAddress._unsafelyUnwrappedUnchecked storage.mutableStart.initialize(from: addr, count: bufPtr.count) storage._invariantCheck() return storage } @_effects(releasenone) internal static func create( initializingFrom bufPtr: UnsafeBufferPointer<UInt8>, isASCII: Bool ) -> _StringStorage { return _StringStorage.create( initializingFrom: bufPtr, capacity: bufPtr.count, isASCII: isASCII) } } // Usage extension _StringStorage { @inline(__always) private var mutableStart: UnsafeMutablePointer<UInt8> { return UnsafeMutablePointer(Builtin.projectTailElems(self, UInt8.self)) } private var mutableEnd: UnsafeMutablePointer<UInt8> { @inline(__always) get { return mutableStart + count } } @inline(__always) internal var start: UnsafePointer<UInt8> { return UnsafePointer(mutableStart) } private final var end: UnsafePointer<UInt8> { @inline(__always) get { return UnsafePointer(mutableEnd) } } // Point to the nul-terminator. private final var terminator: UnsafeMutablePointer<UInt8> { @inline(__always) get { return mutableEnd } } private var codeUnits: UnsafeBufferPointer<UInt8> { @inline(__always) get { return UnsafeBufferPointer(start: start, count: count) } } // @opaque internal var _breadcrumbsAddress: UnsafeMutablePointer<_StringBreadcrumbs?> { let raw = Builtin.getTailAddr_Word( start._rawValue, _realCapacity._builtinWordValue, UInt8.self, Optional<_StringBreadcrumbs>.self) return UnsafeMutablePointer(raw) } // The total capacity available for code units. Note that this excludes the // required nul-terminator. internal var capacity: Int { return _realCapacity &- 1 } // The unused capacity available for appending. Note that this excludes the // required nul-terminator. // // NOTE: Callers who wish to mutate this storage should enfore nul-termination private var unusedStorage: UnsafeMutableBufferPointer<UInt8> { @inline(__always) get { return UnsafeMutableBufferPointer( start: mutableEnd, count: unusedCapacity) } } // The capacity available for appending. Note that this excludes the required // nul-terminator. internal var unusedCapacity: Int { get { return _realCapacity &- count &- 1 } } #if !INTERNAL_CHECKS_ENABLED @inline(__always) internal func _invariantCheck() {} #else internal func _invariantCheck() { let rawSelf = UnsafeRawPointer(Builtin.bridgeToRawPointer(self)) let rawStart = UnsafeRawPointer(start) _internalInvariant(unusedCapacity >= 0) _internalInvariant(count <= capacity) _internalInvariant(rawSelf + Int(_StringObject.nativeBias) == rawStart) _internalInvariant(self._realCapacity > self.count, "no room for nul-terminator") _internalInvariant(self.terminator.pointee == 0, "not nul terminated") _countAndFlags._invariantCheck() if isASCII { _internalInvariant(_allASCII(self.codeUnits)) } if let crumbs = _breadcrumbsAddress.pointee { crumbs._invariantCheck(for: self.asString) } _internalInvariant(_countAndFlags.isNativelyStored) _internalInvariant(_countAndFlags.isTailAllocated) } #endif // INTERNAL_CHECKS_ENABLED } // Appending extension _StringStorage { // Perform common post-RRC adjustments and invariant enforcement. @_effects(releasenone) private func _postRRCAdjust(newCount: Int, newIsASCII: Bool) { let countAndFlags = CountAndFlags( mortalCount: newCount, isASCII: newIsASCII) #if arch(i386) || arch(arm) self._count = countAndFlags.count self._flags = countAndFlags.flags #else self._countAndFlags = countAndFlags #endif self.terminator.pointee = 0 // TODO(String performance): Consider updating breadcrumbs when feasible. self._breadcrumbsAddress.pointee = nil _invariantCheck() } // Perform common post-append adjustments and invariant enforcement. @_effects(releasenone) private func _postAppendAdjust( appendedCount: Int, appendedIsASCII isASCII: Bool ) { let oldTerminator = self.terminator _postRRCAdjust( newCount: self.count + appendedCount, newIsASCII: self.isASCII && isASCII) _internalInvariant(oldTerminator + appendedCount == self.terminator) } @_effects(releasenone) internal func appendInPlace( _ other: UnsafeBufferPointer<UInt8>, isASCII: Bool ) { _internalInvariant(self.capacity >= other.count) let srcAddr = other.baseAddress._unsafelyUnwrappedUnchecked let srcCount = other.count self.mutableEnd.initialize(from: srcAddr, count: srcCount) _postAppendAdjust(appendedCount: srcCount, appendedIsASCII: isASCII) } @_effects(releasenone) internal func appendInPlace<Iter: IteratorProtocol>( _ other: inout Iter, isASCII: Bool ) where Iter.Element == UInt8 { var srcCount = 0 while let cu = other.next() { _internalInvariant(self.unusedCapacity >= 1) unusedStorage[srcCount] = cu srcCount += 1 } _postAppendAdjust(appendedCount: srcCount, appendedIsASCII: isASCII) } internal func clear() { _postRRCAdjust(newCount: 0, newIsASCII: true) } } // Removing extension _StringStorage { @_effects(releasenone) internal func remove(from lower: Int, to upper: Int) { _internalInvariant(lower <= upper) let lowerPtr = mutableStart + lower let upperPtr = mutableStart + upper let tailCount = mutableEnd - upperPtr lowerPtr.moveInitialize(from: upperPtr, count: tailCount) _postRRCAdjust( newCount: self.count &- (upper &- lower), newIsASCII: self.isASCII) } // Reposition a tail of this storage from src to dst. Returns the length of // the tail. @_effects(releasenone) internal func _slideTail( src: UnsafeMutablePointer<UInt8>, dst: UnsafeMutablePointer<UInt8> ) -> Int { _internalInvariant(dst >= mutableStart && src <= mutableEnd) let tailCount = mutableEnd - src dst.moveInitialize(from: src, count: tailCount) return tailCount } @_effects(releasenone) internal func replace( from lower: Int, to upper: Int, with replacement: UnsafeBufferPointer<UInt8> ) { _internalInvariant(lower <= upper) let replCount = replacement.count _internalInvariant(replCount - (upper - lower) <= unusedCapacity) // Position the tail. let lowerPtr = mutableStart + lower let tailCount = _slideTail( src: mutableStart + upper, dst: lowerPtr + replCount) // Copy in the contents. lowerPtr.moveInitialize( from: UnsafeMutablePointer( mutating: replacement.baseAddress._unsafelyUnwrappedUnchecked), count: replCount) let isASCII = self.isASCII && _allASCII(replacement) _postRRCAdjust(newCount: lower + replCount + tailCount, newIsASCII: isASCII) } @_effects(releasenone) internal func replace<C: Collection>( from lower: Int, to upper: Int, with replacement: C, replacementCount replCount: Int ) where C.Element == UInt8 { _internalInvariant(lower <= upper) _internalInvariant(replCount - (upper - lower) <= unusedCapacity) // Position the tail. let lowerPtr = mutableStart + lower let tailCount = _slideTail( src: mutableStart + upper, dst: lowerPtr + replCount) // Copy in the contents. var isASCII = self.isASCII var srcCount = 0 for cu in replacement { if cu >= 0x80 { isASCII = false } lowerPtr[srcCount] = cu srcCount += 1 } _internalInvariant(srcCount == replCount) _postRRCAdjust( newCount: lower + replCount + tailCount, newIsASCII: isASCII) } } // For shared storage and bridging literals final internal class _SharedStringStorage : __SwiftNativeNSString, _AbstractStringStorage { internal var _owner: AnyObject? internal var start: UnsafePointer<UInt8> #if arch(i386) || arch(arm) internal var _count: Int internal var _flags: UInt16 @inline(__always) internal var _countAndFlags: _StringObject.CountAndFlags { return CountAndFlags(count: _count, flags: _flags) } #else internal var _countAndFlags: _StringObject.CountAndFlags #endif internal var _breadcrumbs: _StringBreadcrumbs? = nil internal var count: Int { return _countAndFlags.count } internal init( immortal ptr: UnsafePointer<UInt8>, countAndFlags: _StringObject.CountAndFlags ) { self._owner = nil self.start = ptr #if arch(i386) || arch(arm) self._count = countAndFlags.count self._flags = countAndFlags.flags #else self._countAndFlags = countAndFlags #endif super.init() self._invariantCheck() } @inline(__always) final internal var isASCII: Bool { return _countAndFlags.isASCII } final internal var asString: String { @_effects(readonly) @inline(__always) get { return String(_StringGuts(self)) } } #if _runtime(_ObjC) @objc(length) final internal var length: Int { @_effects(readonly) get { return asString.utf16.count // UTF16View special-cases ASCII for us. } } @objc final internal var hash: UInt { @_effects(readonly) get { if isASCII { return _cocoaHashASCIIBytes(start, length: count) } return _cocoaHashString(self) } } @objc(characterAtIndex:) @_effects(readonly) final internal func character(at offset: Int) -> UInt16 { let str = asString return str.utf16[str._toUTF16Index(offset)] } @objc(getCharacters:range:) @_effects(releasenone) final internal func getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange ) { _getCharacters(buffer, aRange) } @objc final internal var fastestEncoding: UInt { @_effects(readonly) get { if isASCII { return _cocoaASCIIEncoding } return _cocoaUTF8Encoding } } @objc(_fastCStringContents:) @_effects(readonly) final internal func _fastCStringContents( _ requiresNulTermination: Int8 ) -> UnsafePointer<CChar>? { if isASCII { return start._asCChar } return nil } @objc(UTF8String) @_effects(readonly) final internal func _utf8String() -> UnsafePointer<UInt8>? { return start } @objc(cStringUsingEncoding:) @_effects(readonly) final internal func cString(encoding: UInt) -> UnsafePointer<UInt8>? { return _cString(encoding: encoding) } @objc(getCString:maxLength:encoding:) @_effects(releasenone) final internal func getCString( _ outputPtr: UnsafeMutablePointer<UInt8>, maxLength: Int, encoding: UInt ) -> Int8 { return _getCString(outputPtr, maxLength, encoding) } @objc(isEqualToString:) @_effects(readonly) final internal func isEqual(to other:AnyObject?) -> Int8 { return _isEqual(other) } @objc(copyWithZone:) final internal func copy(with zone: _SwiftNSZone?) -> AnyObject { // While _StringStorage instances aren't immutable in general, // mutations may only occur when instances are uniquely referenced. // Therefore, it is safe to return self here; any outstanding Objective-C // reference will make the instance non-unique. return self } #endif // _runtime(_ObjC) } extension _SharedStringStorage { #if !INTERNAL_CHECKS_ENABLED @inline(__always) internal func _invariantCheck() {} #else internal func _invariantCheck() { if let crumbs = _breadcrumbs { crumbs._invariantCheck(for: self.asString) } _countAndFlags._invariantCheck() _internalInvariant(!_countAndFlags.isNativelyStored) _internalInvariant(!_countAndFlags.isTailAllocated) } #endif // INTERNAL_CHECKS_ENABLED }
apache-2.0
e92ded292c279e62f9f9336128777085
28.710199
85
0.68891
4.256415
false
false
false
false
idomizrachi/Regen
regen/Dependencies/Stencil/Loader.swift
1
3358
import Foundation public protocol Loader { func loadTemplate(name: String, environment: Environment) throws -> Template func loadTemplate(names: [String], environment: Environment) throws -> Template } extension Loader { public func loadTemplate(names: [String], environment: Environment) throws -> Template { for name in names { do { return try loadTemplate(name: name, environment: environment) } catch is TemplateDoesNotExist { continue } catch { throw error } } throw TemplateDoesNotExist(templateNames: names, loader: self) } } // A class for loading a template from disk public class FileSystemLoader: Loader, CustomStringConvertible { public let paths: [Path] public init(paths: [Path]) { self.paths = paths } public init(bundle: [Bundle]) { self.paths = bundle.map { Path($0.bundlePath) } } public var description: String { return "FileSystemLoader(\(paths))" } public func loadTemplate(name: String, environment: Environment) throws -> Template { for path in paths { let templatePath = try path.safeJoin(path: Path(name)) if !templatePath.exists { continue } let content: String = try templatePath.read() return environment.templateClass.init(templateString: content, environment: environment, name: name) } throw TemplateDoesNotExist(templateNames: [name], loader: self) } public func loadTemplate(names: [String], environment: Environment) throws -> Template { for path in paths { for templateName in names { let templatePath = try path.safeJoin(path: Path(templateName)) if templatePath.exists { let content: String = try templatePath.read() return environment.templateClass.init(templateString: content, environment: environment, name: templateName) } } } throw TemplateDoesNotExist(templateNames: names, loader: self) } } public class DictionaryLoader: Loader { public let templates: [String: String] public init(templates: [String: String]) { self.templates = templates } public func loadTemplate(name: String, environment: Environment) throws -> Template { if let content = templates[name] { return environment.templateClass.init(templateString: content, environment: environment, name: name) } throw TemplateDoesNotExist(templateNames: [name], loader: self) } public func loadTemplate(names: [String], environment: Environment) throws -> Template { for name in names { if let content = templates[name] { return environment.templateClass.init(templateString: content, environment: environment, name: name) } } throw TemplateDoesNotExist(templateNames: names, loader: self) } } extension Path { func safeJoin(path: Path) throws -> Path { let newPath = self + path if !newPath.absolute().description.hasPrefix(absolute().description) { throw SuspiciousFileOperation(basePath: self, path: newPath) } return newPath } } class SuspiciousFileOperation: Error { let basePath: Path let path: Path init(basePath: Path, path: Path) { self.basePath = basePath self.path = path } var description: String { return "Path `\(path)` is located outside of base path `\(basePath)`" } }
mit
190273d205b28668e56dc66c0ec312aa
26.300813
118
0.684634
4.418421
false
false
false
false
nfls/nflsers
app/v2/Essential/AbstractMessage.swift
1
658
// // AbstractMessage.swift // NFLSers-iOS // // Created by Qingyang Hu on 01/04/2018. // Copyright © 2018 胡清阳. All rights reserved. // import Foundation import ObjectMapper typealias AbstractError = AbstractMessage struct AbstractMessage: ImmutableMappable,Error { let status: Int let message: String var localizedDescription: String { get { return self.message } } init(status: Int, message: String) { self.status = status self.message = message } init(map: Map) throws { self.status = try map.value("code") self.message = try map.value("data") } }
apache-2.0
1e86603f75d1e501dc8176962f457c7d
20
49
0.6298
4.018519
false
false
false
false
qvacua/vimr
Commons/Sources/Commons/OSLogCommons.swift
1
2237
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Foundation import os public extension OSLog { func trace<T>( file: String = #file, function: String = #function, line: Int = #line, _ msg: T ) { #if TRACE self.log( type: .debug, msg: "%{public}@", "[\((file as NSString).lastPathComponent) - \(function):\(line)] [TRACE] \(msg)" ) #endif } func debug( file: String = #file, function: String = #function, line: Int = #line ) { #if DEBUG self.log( type: .debug, msg: "%{public}@", "[\((file as NSString).lastPathComponent) - \(function):\(line)]" ) #endif } func debug<T>( file: String = #file, function: String = #function, line: Int = #line, _ msg: T ) { #if DEBUG self.log( type: .debug, msg: "%{public}@", "[\((file as NSString).lastPathComponent) - \(function):\(line)] \(msg)" ) #endif } func info<T>( file: String = #file, function: String = #function, line: Int = #line, _ msg: T ) { self.log( type: .info, msg: "%{public}@", "[\((file as NSString).lastPathComponent) - \(function):\(line)] \(msg)" ) } func `default`<T>( file: String = #file, function: String = #function, line: Int = #line, _ msg: T ) { self.log( type: .default, msg: "%{public}@", "[\((file as NSString).lastPathComponent) - \(function):\(line)] \(msg)" ) } func error<T>( file: String = #file, function: String = #function, line: Int = #line, _ msg: T ) { self.log( type: .error, msg: "%{public}@", "[\((file as NSString).lastPathComponent) - \(function):\(line)] \(msg)" ) } func fault<T>( file: String = #file, function: String = #function, line: Int = #line, _ msg: T ) { self.log( type: .fault, msg: "%{public}@", "[\((file as NSString).lastPathComponent) - \(function):\(line)] \(msg)" ) } private func log( type: OSLogType, msg: StaticString, _ object: CVarArg ) { os_log(msg, log: self, type: type, object) } }
mit
d2a4f31201a4709cc72f99e33ad38f4b
18.79646
88
0.502906
3.539557
false
false
false
false
handstandsam/ShoppingApp
iosApp/iosApp/ContentView.swift
1
737
import SwiftUI import multiplatform struct ContentView: View { func something() { let graph = IosMultiplatformApi().networkGraph.categoryRepo.getCategories { data, error in if let people = data { print(people) } if let errorReal = error { print(errorReal) } } } init(){ something() } let greet = Greeting().greeting() let user = ModelsUser(firstname: "handstands", lastname: "sam") var body: some View { Text(user.description()) Text(greet) Text(greet) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
apache-2.0
1a205237a667a55c9c323cd7f3def733
19.472222
83
0.559023
4.360947
false
false
false
false
jamalping/XPUtil
XPUtil/UIKit/UIColor+Extension.swift
1
5670
// // UIColor+Extension.swift // XPUtil // // Created by xyj on 2017/9/28. // Copyright © 2017年 xyj. All rights reserved. // import UIKit // MARK: - 渐变色 public extension UIColor { /// 渐变色方向 enum Directions: Int { case right = 0 case left case bottom case top case topLeftToBottomRight case topRightToBottomLeft case bottomLeftToTopRight case bottomRightToTopLeft } /// 生产渐变颜色 /// /// - Parameters: /// - from: 开始的颜色 /// - toColor: 结束的颜色 /// - size: 渐变颜色的范围 /// - direction: 渐变方向 /// - Returns: 渐变颜色 class func gradientColor(_ fromColor: UIColor, toColor: UIColor, size: CGSize, direction: Directions = UIColor.Directions.bottom) -> UIColor? { UIGraphicsBeginImageContextWithOptions(size, false, 0) let context = UIGraphicsGetCurrentContext() let colorSpace = CGColorSpaceCreateDeviceRGB() let colors = [fromColor.cgColor, toColor.cgColor] guard let gradient: CGGradient = CGGradient.init(colorsSpace: colorSpace, colors: colors as CFArray, locations: nil) else { return nil } var startPoint: CGPoint var endPoint: CGPoint switch direction { case .left: startPoint = CGPoint.init(x: size.width, y: 0.0) endPoint = CGPoint.init(x: 0.0, y: 0.0) case .right: startPoint = CGPoint.init(x: 0.0, y: 0.0) endPoint = CGPoint.init(x: size.width, y: 0.0) case .bottom: startPoint = CGPoint.init(x: 0.0, y: 0.0) endPoint = CGPoint.init(x: 0.0, y: size.height) case .top: startPoint = CGPoint.init(x: 0.0, y: size.height) endPoint = CGPoint.init(x: 0.0, y: 0.0) case .topLeftToBottomRight: startPoint = CGPoint.init(x: 0.0, y: 0.0) endPoint = CGPoint.init(x: size.width, y: size.height) case .topRightToBottomLeft: startPoint = CGPoint.init(x: size.width, y: 0.0) endPoint = CGPoint.init(x: 0.0, y: size.height) case .bottomLeftToTopRight: startPoint = CGPoint.init(x: 0.0, y: size.height) endPoint = CGPoint.init(x: size.width, y: 0.0) case .bottomRightToTopLeft: startPoint = CGPoint.init(x: size.width, y: size.height) endPoint = CGPoint.init(x: 0.0, y: 0.0) } context?.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: .drawsBeforeStartLocation) guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return nil } UIGraphicsEndImageContext() return UIColor.init(patternImage: image) } } public extension UIColor { // user:UIColor.init(hexString: "#ff5a10") ||UIColor.init(hexString: "ff5a10") convenience init(hexString: String, alpha: CGFloat = 1) { var r, g, b, a: CGFloat a = alpha var hexColor: String = hexString.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() // 存在#,则将#去掉 if (hexColor.hasPrefix("#")) { let splitIndex = hexColor.index(after: hexColor.startIndex) hexColor = String(hexColor[splitIndex...]) } if hexColor.count == 8 { let scanner = Scanner(string: hexColor) var hexNumber: UInt64 = 0 if scanner.scanHexInt64(&hexNumber) { r = CGFloat((hexNumber & 0xff000000) >> 24) / 255 g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255 b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255 a = CGFloat(hexNumber & 0x000000ff) / 255 self.init(red: r, green: g, blue: b, alpha: a) return } } else if hexColor.count == 6 { let scanner = Scanner(string: hexColor) var hexNumber: UInt64 = 0 if scanner.scanHexInt64(&hexNumber) { r = CGFloat((hexNumber & 0xff0000) >> 16) / 255 g = CGFloat((hexNumber & 0x00ff00) >> 8) / 255 b = CGFloat(hexNumber & 0x0000ff) / 255 self.init(red: r, green: g, blue: b, alpha: a) return } } // 设置默认值 self.init(white: 0.0, alpha: 1) } //用数值初始化颜色,便于生成设计图上标明的十六进制颜色 //user: UIColor.init(valueHex: 0xff5a10) convenience init(valueHex: UInt, alpha: CGFloat = 1.0) { self.init( red: CGFloat((valueHex & 0xFF0000) >> 16) / 255.0, green: CGFloat((valueHex & 0x00FF00) >> 8) / 255.0, blue: CGFloat(valueHex & 0x0000FF) / 255.0, alpha: alpha ) } /// 获取随机颜色 /// - Returns: 随机颜色 class func randamColor() -> UIColor{ let R = CGFloat(arc4random_uniform(255))/255.0 let G = CGFloat(arc4random_uniform(255))/255.0 let B = CGFloat(arc4random_uniform(255))/255.0 return UIColor.init(red: R, green: G, blue: B, alpha: 1) } /// 获取对应的rgba值 var component: (CGFloat,CGFloat,CGFloat,CGFloat) { get { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) return (r * 255,g * 255,b * 255,a) } } }
mit
486e1083611c6670c50e521f56e0d8bb
33.471698
147
0.548258
3.917798
false
false
false
false
akshayg13/Game
Games/FavouriteVC.swift
1
2616
// // FavouriteVC.swift // Games // // Created by Appinventiv on 23/02/17. // Copyright © 2017 Appinventiv. All rights reserved. // import UIKit import AlamofireImage class FavouriteVC: UIViewController { var favList : [ImageModel] = [] @IBOutlet weak var favCollectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() let cellNib = UINib(nibName: "GameCollectionViewCell", bundle: nil) favCollectionView.register(cellNib, forCellWithReuseIdentifier: "GameCollectionViewCellID") favCollectionView.dataSource = self favCollectionView.delegate = self // Do any additional setup after loading the view. } } extension FavouriteVC : UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return favList.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ guard let collectionCell = favCollectionView.dequeueReusableCell(withReuseIdentifier: "GameCollectionViewCellID", for: indexPath) as? GameCollectionViewCell else {fatalError("Cell not Found") } let url = URL(string: favList[indexPath.row].previewURL)! collectionCell.gameImage.af_setImage(withURL: url) collectionCell.backgroundColor = .blue collectionCell.layer.borderWidth = 2 collectionCell.layer.borderColor = UIColor.black.cgColor collectionCell.gameName.text = favList[indexPath.row].id collectionCell.favButton.isEnabled = false collectionCell.favButton.isHidden = true return collectionCell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 90, height: 120) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let imageViewVC = self.navigationController?.storyboard?.instantiateViewController(withIdentifier: "ImageViewVCID") as! ImageViewVC imageViewVC.imageToShow = favList[indexPath.row] UIView.animate(withDuration: 0.33, delay: 0, options: .curveEaseInOut, animations: { self.navigationController?.pushViewController(imageViewVC, animated: true)}, completion: nil) } }
mit
d47105523b28c4b34396f23c845c1b64
34.337838
201
0.70325
5.611588
false
false
false
false
ProjectTorch/iOS
Torch-iOS/SupportFiles/AppDelegate.swift
1
4476
import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Torch-iOS") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
51e3262174b85c6fc7d6d660791a1cc4
49.292135
285
0.682976
6.048649
false
false
false
false
makhiye/flagMatching
flag Matching/Game.swift
1
4523
// // Game.swift // flag Matching // // Created by ishmael on 7/19/17. // Copyright © 2017 ishmael.mthombeni. All rights reserved. // import Foundation import AVFoundation protocol MatchingGameDelegate { func game(_ game: Game, hideCards cards: [Int]) } struct Game { var deckOfCards = DeckOfCards() let synthesizer = AVSpeechSynthesizer() var gameDelegate: MatchingGameDelegate? var unmatchedCardsRevealed: [Int] = [] // card index numbers that have been revealed var sound = AVAudioPlayer() // add sound player var waitingForHidingCards = false //When start game we not waiting var unMatchedCards: [Int] = [] // card index numbers that matches init(){ newGame() } mutating func flipCard(atIndexNumber index: Int) -> Bool { if waitingForHidingCards {return false} if !unmatchedCardsRevealed.isEmpty && unmatchedCardsRevealed[0] == index {return false} //this is not the first tap ()its the second if !unMatchedCards.contains(index) {return false} // Card has already been matched if unmatchedCardsRevealed.count < 2 { unmatchedCardsRevealed.append(index) playFlipSound() if unmatchedCardsRevealed.count == 2 { let card1Name = deckOfCards.dealtCards[unmatchedCardsRevealed[0]] let card2Name = deckOfCards.dealtCards[unmatchedCardsRevealed[1]] if card1Name == card2Name{ // second card is a match for (indexCounter, cardIndexValue) in unMatchedCards.enumerated().reversed(){ if cardIndexValue == unmatchedCardsRevealed[0] || cardIndexValue == unmatchedCardsRevealed[1]{ unMatchedCards.remove(at: indexCounter) } } speakCard(number: index) unmatchedCardsRevealed.removeAll() if unMatchedCards.isEmpty { playGameOverSound() } }else { // second card is NOT a match resetUnmatchedcards() } } return true }else{ print("ERROR: This should be here") return false } } mutating func newGame(){ playFlipSound() deckOfCards.drawCards() for (index, _) in deckOfCards.dealtCards.enumerated() { unMatchedCards.append(index) } } mutating func playGameOverSound() { let path = Bundle.main.path(forResource: "gameOver", ofType: "mp3") playSound(withPath: path!) } mutating func playFlipSound() { let path = Bundle.main.path(forResource: "card-flip", ofType: "mp3") playSound(withPath: path!) } mutating func playShuffleSound() { let path = Bundle.main.path(forResource: "shuffle", ofType: "wav") playSound(withPath: path!) } //Plays any sound that you pass a path to mutating func playSound(withPath path: String) { let soundURL = URL(fileURLWithPath: path) do { try sound = AVAudioPlayer(contentsOf: soundURL) sound.prepareToPlay() } catch { print("ERROR! Couldn’t load sound file") } sound.play() } mutating func resetUnmatchedcards() { waitingForHidingCards = true // Tobe reset in the hideCards methods self.gameDelegate?.game(self, hideCards: unmatchedCardsRevealed) unmatchedCardsRevealed.removeAll() } func speakCard(number cardTag: Int){ synthesizer.stopSpeaking(at: .immediate) let utterance = AVSpeechUtterance(string: deckOfCards.dealtCards[cardTag]) synthesizer.speak(utterance) } }
mit
9520a384b645277888c23a9d4bf0faee
26.730061
140
0.508407
5.492102
false
false
false
false
hollanderbart/NPOStream
NPOStream/ChannelProvider.swift
1
2449
// // ChannelProvider.swift // NPOStream // // Created by Bart den Hollander on 23/07/16. // Copyright © 2016 Bart den Hollander. All rights reserved. // import Foundation public enum ChannelStreamTitle: String, CaseIterable { case NPO1 = "LI_NL1_4188102" case NPO2 = "LI_NL2_4188105" case NPO3 = "LI_NL3_4188107" case NPONieuws = "LI_NEDERLAND1_221673" case NPOPolitiek = "LI_NEDERLAND1_221675" case NPO101 = "LI_NEDERLAND3_221683" case NPOCultura = "LI_NEDERLAND2_221679" case NPOZappXtra = "LI_NEDERLAND3_221687" case NPORadio1 = "LI_RADIO1_300877" case NPORadio2 = "LI_RADIO2_300879" case NPO3FM = "LI_3FM_300881" case NPORadio4 = "LI_RA4_698901" case NPOFunX = "LI_3FM_603983" } public struct ChannelProvider { public static let streams = [ Channel( title: "NPO 1", streamTitle: ChannelStreamTitle.NPO1, url: nil), Channel( title: "NPO 2", streamTitle: ChannelStreamTitle.NPO2, url: nil), Channel( title: "NPO 3", streamTitle: ChannelStreamTitle.NPO3, url: nil), Channel( title: "NPO Nieuws", streamTitle: ChannelStreamTitle.NPONieuws, url: nil), Channel( title: "NPO Politiek", streamTitle: ChannelStreamTitle.NPOPolitiek, url: nil), Channel( title: "NPO 101", streamTitle: ChannelStreamTitle.NPO101, url: nil), Channel( title: "NPO Cultura", streamTitle: ChannelStreamTitle.NPOCultura, url: nil), Channel( title: "NPO Zapp", streamTitle: ChannelStreamTitle.NPOZappXtra, url: nil), Channel( title: "NPO Radio 1", streamTitle: ChannelStreamTitle.NPORadio1, url: nil), Channel( title: "NPO Radio 2", streamTitle: ChannelStreamTitle.NPORadio2, url: nil), Channel( title: "NPO 3FM", streamTitle: ChannelStreamTitle.NPO3FM, url: nil), Channel( title: "NPO Radio 4", streamTitle: ChannelStreamTitle.NPORadio4, url: nil), Channel( title: "NPO FunX", streamTitle: ChannelStreamTitle.NPOFunX, url: nil) ] }
mit
cdf4b891d427ef76b445f2ca49b42108
28.493976
61
0.556373
3.477273
false
false
false
false
GitHubOfJW/JavenKit
JavenKit/JWAlertViewController/Action/JWAlertAction.swift
1
972
// // JWAlertAction.swift // CarServer // // Created by 朱建伟 on 2016/11/6. // Copyright © 2016年 zhujianwei. All rights reserved. // import UIKit public enum JWAlertActionStyle:Int{ case `default` case cancel case destructive } public class JWAlertAction: NSObject { public typealias JWActionClosure = (JWAlertAction)->Void //初始化 public convenience init(title:String,style:JWAlertActionStyle,handler:@escaping JWActionClosure) { self.init() //设置标题 self.title = title //回掉 self.handler = handler //样式 self.actionStyle = style } //类型 var actionStyle:JWAlertActionStyle = JWAlertActionStyle.default //回调 var handler:JWActionClosure? //title var title:String? private override init() { super.init() } }
mit
4ee2b13ce66711d302da852d65d21734
15.368421
102
0.573419
4.400943
false
false
false
false
jverkoey/FigmaKit
Sources/FigmaKit/Node/BooleanOperationNode.swift
1
899
extension Node { public final class BooleanOperationNode: VectorNode { let booleanOperation: Operation enum Operation: String, Decodable { case union = "UNION" case intersect = "INTERSECT" case subtract = "SUBTRACT" case exclude = "EXCLUDE" } private enum CodingKeys: String, CodingKey { case booleanOperation } public required init(from decoder: Decoder) throws { let keyedDecoder = try decoder.container(keyedBy: Self.CodingKeys) self.booleanOperation = try keyedDecoder.decode(Operation.self, forKey: .booleanOperation) try super.init(from: decoder) } public override func encode(to encoder: Encoder) throws { fatalError("Not yet implemented") } override var contentDescription: String { return """ - booleanOperation: \(booleanOperation) """ } } }
apache-2.0
db3b7f390e3dc865fa5bc69b93a59681
25.441176
96
0.652948
4.756614
false
false
false
false
jessesquires/swift-proposal-analyzer
swift-proposal-analyzer.playground/Pages/SE-0021.xcplaygroundpage/Contents.swift
1
6779
/*: # Naming Functions with Argument Labels * Proposal: [SE-0021](0021-generalized-naming.md) * Author: [Doug Gregor](https://github.com/DougGregor) * Review Manager: [Joe Groff](https://github.com/jckarter) * Status: **Implemented (Swift 2.2)** * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2016-January/000021.html) * Implementation: [apple/swift@ecfde0e](https://github.com/apple/swift/commit/ecfde0e71c61184989fde0f93f8d6b7f5375b99a) ## Introduction Swift includes support for first-class functions, such that any function (or method) can be placed into a value of function type. However, when specifying the name of a function, one can only provide the base name, (e.g., `insertSubview`) without the argument labels. For overloaded functions, this means that one must disambiguate based on type information, which is awkward and verbose. This proposal allows one to provide argument labels when referencing a function, eliminating the need to provide type context in most cases. Swift-evolution thread: The first draft of this proposal was discussed [here](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151221/004555.html). It included support for naming getters/setters (separately brought up by Michael Henson [here](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/002168.html), continued [here](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151214/002203.html)). Joe Groff [convinced](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151221/004579.html) me that lenses are a better approach for working with getters/setters, so I've dropped them from this version of the proposal. ## Motivation It's fairly common in Swift for multiple functions or methods to have the same "base name", but be distinguished by parameter labels. For example, `UIView` has three methods with the same base name `insertSubview`: ```swift extension UIView { func insertSubview(view: UIView, at index: Int) func insertSubview(view: UIView, aboveSubview siblingSubview: UIView) func insertSubview(view: UIView, belowSubview siblingSubview: UIView) } ``` When calling these methods, the argument labels distinguish the different methods, e.g., ```swift someView.insertSubview(view, at: 3) someView.insertSubview(view, aboveSubview: otherView) someView.insertSubview(view, belowSubview: otherView) ``` However, when referencing the function to create a function value, one cannot provide the labels: ```swift let fn = someView.insertSubview // ambiguous: could be any of the three methods ``` In some cases, it is possible to use type annotations to disambiguate: ```swift let fn: (UIView, Int) = someView.insertSubview // ok: uses insertSubview(_:at:) let fn: (UIView, UIView) = someView.insertSubview // error: still ambiguous! ``` To resolve the latter case, one must fall back to creating a closure: ```swift let fn: (UIView, UIView) = { view, otherView in button.insertSubview(view, aboveSubview: otherView) } ``` which is painfully tedious. One additional bit of motivation: Swift should probably get some way to ask for the Objective-C selector for a given method (rather than writing a string literal). The argument to such an operation would likely be a reference to a method, which would benefit from being able to name any method, including getters and setters. ## Proposed solution I propose to extend function naming to allow compound Swift names (e.g., `insertSubview(_:aboveSubview:)`) anywhere a name can occur. Specifically, ```swift let fn = someView.insertSubview(_:at:) let fn1 = someView.insertSubview(_:aboveSubview:) ``` The same syntax can also refer to initializers, e.g., ```swift let buttonFactory = UIButton.init(type:) ``` The "produce the Objective-C selector for the given method" operation will be the subject of a separate proposal. However, here is one possibility that illustrations how it uses the proposed syntax here: ```swift let getter = Selector(NSDictionary.insertSubview(_:aboveSubview:)) // produces insertSubview:aboveSubview:. ``` ## Detailed Design Grammatically, the *primary-expression* grammar will change from: primary-expression -> identifier generic-argument-clause[opt] to: primary-expression -> unqualified-name generic-argument-clause[opt] unqualified-name -> identifier | identifier '(' ((identifier | '_') ':')+ ')' Within the parentheses, the use of "+" is important, because it disambiguates: ```swift f() ``` as a call to `f` rather than a reference to an `f` with no arguments. Zero-argument function references will still require disambiguation via contextual type information. Note that the reference to the name must include all of the arguments present in the declaration; arguments for defaulted or variadic parameters cannot be skipped. For example: ```swift func foo(x x: Int, y: Int = 7, strings: String...) { ... } let fn1 = foo(x:y:strings:) // okay let fn2 = foo(x:) // error: no function named 'foo(x:)' ``` ## Impact on existing code This is a purely additive feature that has no impact on existing code. ## Alternatives considered * Joe Groff [notes](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151214/003008.html) that *lenses* are a better solution than manually retrieving getter/setter functions when the intent is to actually operate on the properties. * Bartlomiej Cichosz [suggests](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151228/004739.html) a general partial application syntax using `_` as a placeholder, e.g., ```swift aGameView.insertSubview(_, aboveSubview: playingSurfaceView) ``` When all arguments are `_`, this provides the ability to name any method: ```swift aGameView.insertSubview(_, aboveSubview: _) ``` I decided not to go with this because I don't believe we need such a general partial application syntax in Swift. Closures using the $ names are nearly as concise, and eliminate any questions about how the `_` placeholder maps to an argument of the partially-applied function: ```swift { aGameView.insertSubview($0, aboveSubview: playingSurfaceView) } ``` * We could elide the underscores in the names, e.g., ```swift let fn1 = someView.insertSubview(:aboveSubview:) ``` However, this makes it much harder to visually distinguish methods with no first argument label from methods with a first argument label, e.g., `f(x:)` vs. `f(:x:)`. Additionally, empty argument labels in function names are written using the underscores everywhere else in the system (e.g., the Clang `swift_name` attribute), and we should maintain consistency. ---------- [Previous](@previous) | [Next](@next) */
mit
0bc5c1b68d5a42ac835a3dc40cac8953
35.643243
405
0.754389
3.943572
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/RxCocoa/RxCocoa/Common/Observable+Bind.swift
19
3426
// // Observable+Bind.swift // RxCocoa // // Created by Krunoslav Zaher on 8/29/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift extension ObservableType { /** Creates new subscription and sends elements to observer(s). In this form, it's equivalent to the `subscribe` method, but it better conveys intent, and enables writing more consistent binding code. - parameter to: Observers to receives events. - returns: Disposable object that can be used to unsubscribe the observers. */ public func bind<Observer: ObserverType>(to observers: Observer...) -> Disposable where Observer.Element == Element { return self.bind(to: observers) } /** Creates new subscription and sends elements to observer(s). In this form, it's equivalent to the `subscribe` method, but it better conveys intent, and enables writing more consistent binding code. - parameter to: Observers to receives events. - returns: Disposable object that can be used to unsubscribe the observers. */ public func bind<Observer: ObserverType>(to observers: Observer...) -> Disposable where Observer.Element == Element? { return self.map { $0 as Element? }.bind(to: observers) } /** Creates new subscription and sends elements to observer(s). In this form, it's equivalent to the `subscribe` method, but it better conveys intent, and enables writing more consistent binding code. - parameter to: Observers to receives events. - returns: Disposable object that can be used to unsubscribe the observers. */ private func bind<Observer: ObserverType>(to observers: [Observer]) -> Disposable where Observer.Element == Element { return self.subscribe { event in observers.forEach { $0.on(event) } } } /** Subscribes to observable sequence using custom binder function. - parameter to: Function used to bind elements from `self`. - returns: Object representing subscription. */ public func bind<Result>(to binder: (Self) -> Result) -> Result { return binder(self) } /** Subscribes to observable sequence using custom binder function and final parameter passed to binder function after `self` is passed. public func bind<R1, R2>(to binder: Self -> R1 -> R2, curriedArgument: R1) -> R2 { return binder(self)(curriedArgument) } - parameter to: Function used to bind elements from `self`. - parameter curriedArgument: Final argument passed to `binder` to finish binding process. - returns: Object representing subscription. */ public func bind<R1, R2>(to binder: (Self) -> (R1) -> R2, curriedArgument: R1) -> R2 { return binder(self)(curriedArgument) } /** Subscribes an element handler to an observable sequence. In case error occurs in debug mode, `fatalError` will be raised. In case error occurs in release mode, `error` will be logged. - parameter onNext: Action to invoke for each element in the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ public func bind(onNext: @escaping (Element) -> Void) -> Disposable { return self.subscribe(onNext: onNext, onError: { error in rxFatalErrorInDebug("Binding error: \(error)") }) } }
mit
99beb2f6832393a37085d184029e438c
38.367816
122
0.67854
4.653533
false
false
false
false
Ashok28/Kingfisher
Sources/Image/ImageProcessor.swift
1
38820
// // ImageProcessor.swift // Kingfisher // // Created by Wei Wang on 2016/08/26. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import CoreGraphics #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit #endif /// Represents an item which could be processed by an `ImageProcessor`. /// /// - image: Input image. The processor should provide a way to apply /// processing on this `image` and return the result image. /// - data: Input data. The processor should provide a way to apply /// processing on this `data` and return the result image. public enum ImageProcessItem { /// Input image. The processor should provide a way to apply /// processing on this `image` and return the result image. case image(KFCrossPlatformImage) /// Input data. The processor should provide a way to apply /// processing on this `data` and return the result image. case data(Data) } /// An `ImageProcessor` would be used to convert some downloaded data to an image. public protocol ImageProcessor { /// Identifier of the processor. It will be used to identify the processor when /// caching and retrieving an image. You might want to make sure that processors with /// same properties/functionality have the same identifiers, so correct processed images /// could be retrieved with proper key. /// /// - Note: Do not supply an empty string for a customized processor, which is already reserved by /// the `DefaultImageProcessor`. It is recommended to use a reverse domain name notation string of /// your own for the identifier. var identifier: String { get } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: The parsed options when processing the item. /// - Returns: The processed image. /// /// - Note: The return value should be `nil` if processing failed while converting an input item to image. /// If `nil` received by the processing caller, an error will be reported and the process flow stops. /// If the processing flow is not critical for your flow, then when the input item is already an image /// (`.image` case) and there is any errors in the processing, you could return the input image itself /// to keep the processing pipeline continuing. /// - Note: Most processor only supports CG-based images. watchOS is not supported for processors containing /// a filter, the input image will be returned directly on watchOS. func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? } extension ImageProcessor { /// Appends an `ImageProcessor` to another. The identifier of the new `ImageProcessor` /// will be "\(self.identifier)|>\(another.identifier)". /// /// - Parameter another: An `ImageProcessor` you want to append to `self`. /// - Returns: The new `ImageProcessor` will process the image in the order /// of the two processors concatenated. public func append(another: ImageProcessor) -> ImageProcessor { let newIdentifier = identifier.appending("|>\(another.identifier)") return GeneralProcessor(identifier: newIdentifier) { item, options in if let image = self.process(item: item, options: options) { return another.process(item: .image(image), options: options) } else { return nil } } } } func ==(left: ImageProcessor, right: ImageProcessor) -> Bool { return left.identifier == right.identifier } func !=(left: ImageProcessor, right: ImageProcessor) -> Bool { return !(left == right) } typealias ProcessorImp = ((ImageProcessItem, KingfisherParsedOptionsInfo) -> KFCrossPlatformImage?) struct GeneralProcessor: ImageProcessor { let identifier: String let p: ProcessorImp func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { return p(item, options) } } /// The default processor. It converts the input data to a valid image. /// Images of .PNG, .JPEG and .GIF format are supported. /// If an image item is given as `.image` case, `DefaultImageProcessor` will /// do nothing on it and return the associated image. public struct DefaultImageProcessor: ImageProcessor { /// A default `DefaultImageProcessor` could be used across. public static let `default` = DefaultImageProcessor() /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier = "" /// Creates a `DefaultImageProcessor`. Use `DefaultImageProcessor.default` to get an instance, /// if you do not have a good reason to create your own `DefaultImageProcessor`. public init() {} /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) case .data(let data): return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions) } } } /// Represents the rect corner setting when processing a round corner image. public struct RectCorner: OptionSet { /// Raw value of the rect corner. public let rawValue: Int /// Represents the top left corner. public static let topLeft = RectCorner(rawValue: 1 << 0) /// Represents the top right corner. public static let topRight = RectCorner(rawValue: 1 << 1) /// Represents the bottom left corner. public static let bottomLeft = RectCorner(rawValue: 1 << 2) /// Represents the bottom right corner. public static let bottomRight = RectCorner(rawValue: 1 << 3) /// Represents all corners. public static let all: RectCorner = [.topLeft, .topRight, .bottomLeft, .bottomRight] /// Creates a `RectCorner` option set with a given value. /// /// - Parameter rawValue: The value represents a certain corner option. public init(rawValue: Int) { self.rawValue = rawValue } var cornerIdentifier: String { if self == .all { return "" } return "_corner(\(rawValue))" } } #if !os(macOS) /// Processor for adding an blend mode to images. Only CG-based images are supported. public struct BlendImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Blend Mode will be used to blend the input image. public let blendMode: CGBlendMode /// Alpha will be used when blend image. public let alpha: CGFloat /// Background color of the output image. If `nil`, it will stay transparent. public let backgroundColor: KFCrossPlatformColor? /// Creates a `BlendImageProcessor`. /// /// - Parameters: /// - blendMode: Blend Mode will be used to blend the input image. /// - alpha: Alpha will be used when blend image. From 0.0 to 1.0. 1.0 means solid image, /// 0.0 means transparent image (not visible at all). Default is 1.0. /// - backgroundColor: Background color to apply for the output image. Default is `nil`. public init(blendMode: CGBlendMode, alpha: CGFloat = 1.0, backgroundColor: KFCrossPlatformColor? = nil) { self.blendMode = blendMode self.alpha = alpha self.backgroundColor = backgroundColor var identifier = "com.onevcat.Kingfisher.BlendImageProcessor(\(blendMode.rawValue),\(alpha))" if let color = backgroundColor { identifier.append("_\(color.hex)") } self.identifier = identifier } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.image(withBlendMode: blendMode, alpha: alpha, backgroundColor: backgroundColor) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } #endif #if os(macOS) /// Processor for adding an compositing operation to images. Only CG-based images are supported in macOS. public struct CompositingImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Compositing operation will be used to the input image. public let compositingOperation: NSCompositingOperation /// Alpha will be used when compositing image. public let alpha: CGFloat /// Background color of the output image. If `nil`, it will stay transparent. public let backgroundColor: KFCrossPlatformColor? /// Creates a `CompositingImageProcessor` /// /// - Parameters: /// - compositingOperation: Compositing operation will be used to the input image. /// - alpha: Alpha will be used when compositing image. /// From 0.0 to 1.0. 1.0 means solid image, 0.0 means transparent image. /// Default is 1.0. /// - backgroundColor: Background color to apply for the output image. Default is `nil`. public init(compositingOperation: NSCompositingOperation, alpha: CGFloat = 1.0, backgroundColor: KFCrossPlatformColor? = nil) { self.compositingOperation = compositingOperation self.alpha = alpha self.backgroundColor = backgroundColor var identifier = "com.onevcat.Kingfisher.CompositingImageProcessor(\(compositingOperation.rawValue),\(alpha))" if let color = backgroundColor { identifier.append("_\(color.hex)") } self.identifier = identifier } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.image( withCompositingOperation: compositingOperation, alpha: alpha, backgroundColor: backgroundColor) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } #endif /// Represents a radius specified in a `RoundCornerImageProcessor`. public enum Radius { /// The radius should be calculated as a fraction of the image width. Typically the associated value should be /// between 0 and 0.5, where 0 represents no radius and 0.5 represents using half of the image width. case widthFraction(CGFloat) /// The radius should be calculated as a fraction of the image height. Typically the associated value should be /// between 0 and 0.5, where 0 represents no radius and 0.5 represents using half of the image height. case heightFraction(CGFloat) /// Use a fixed point value as the round corner radius. case point(CGFloat) var radiusIdentifier: String { switch self { case .widthFraction(let f): return "w_frac_\(f)" case .heightFraction(let f): return "h_frac_\(f)" case .point(let p): return p.description } } public func compute(with size: CGSize) -> CGFloat { let cornerRadius: CGFloat switch self { case .point(let point): cornerRadius = point case .widthFraction(let widthFraction): cornerRadius = size.width * widthFraction case .heightFraction(let heightFraction): cornerRadius = size.height * heightFraction } return cornerRadius } } /// Processor for making round corner images. Only CG-based images are supported in macOS, /// if a non-CG image passed in, the processor will do nothing. /// /// - Note: The input image will be rendered with round corner pixels removed. If the image itself does not contain /// alpha channel (for example, a JPEG image), the processed image will contain an alpha channel in memory in order /// to show correctly. However, when cached to disk, Kingfisher respects the original image format by default. That /// means the alpha channel will be removed for these images. When you load the processed image from cache again, you /// will lose transparent corner. /// /// You could use `FormatIndicatedCacheSerializer.png` to force Kingfisher to serialize the image to PNG format in this /// case. /// public struct RoundCornerImageProcessor: ImageProcessor { /// Represents a radius specified in a `RoundCornerImageProcessor`. public typealias Radius = Kingfisher.Radius /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction of the /// target image with `.widthFraction`. or `.heightFraction`. For example, given a square image with width and /// height equals, `.widthFraction(0.5)` means use half of the length of size and makes the final image a round one. public let radius: Radius /// The target corners which will be applied rounding. public let roundingCorners: RectCorner /// Target size of output image should be. If `nil`, the image will keep its original size after processing. public let targetSize: CGSize? /// Background color of the output image. If `nil`, it will use a transparent background. public let backgroundColor: KFCrossPlatformColor? /// Creates a `RoundCornerImageProcessor`. /// /// - Parameters: /// - cornerRadius: Corner radius in point will be applied in processing. /// - targetSize: Target size of output image should be. If `nil`, /// the image will keep its original size after processing. /// Default is `nil`. /// - corners: The target corners which will be applied rounding. Default is `.all`. /// - backgroundColor: Background color to apply for the output image. Default is `nil`. /// /// - Note: /// /// This initializer accepts a concrete point value for `cornerRadius`. If you do not know the image size, but still /// want to apply a full round-corner (making the final image a round one), or specify the corner radius as a /// fraction of one dimension of the target image, use the `Radius` version instead. /// public init( cornerRadius: CGFloat, targetSize: CGSize? = nil, roundingCorners corners: RectCorner = .all, backgroundColor: KFCrossPlatformColor? = nil ) { let radius = Radius.point(cornerRadius) self.init(radius: radius, targetSize: targetSize, roundingCorners: corners, backgroundColor: backgroundColor) } /// Creates a `RoundCornerImageProcessor`. /// /// - Parameters: /// - radius: The radius will be applied in processing. /// - targetSize: Target size of output image should be. If `nil`, /// the image will keep its original size after processing. /// Default is `nil`. /// - corners: The target corners which will be applied rounding. Default is `.all`. /// - backgroundColor: Background color to apply for the output image. Default is `nil`. public init( radius: Radius, targetSize: CGSize? = nil, roundingCorners corners: RectCorner = .all, backgroundColor: KFCrossPlatformColor? = nil ) { self.radius = radius self.targetSize = targetSize self.roundingCorners = corners self.backgroundColor = backgroundColor self.identifier = { var identifier = "" if let size = targetSize { identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" + "(\(radius.radiusIdentifier)_\(size)\(corners.cornerIdentifier))" } else { identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" + "(\(radius.radiusIdentifier)\(corners.cornerIdentifier))" } if let backgroundColor = backgroundColor { identifier += "_\(backgroundColor)" } return identifier }() } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): let size = targetSize ?? image.kf.size return image.kf.scaled(to: options.scaleFactor) .kf.image( withRadius: radius, fit: size, roundingCorners: roundingCorners, backgroundColor: backgroundColor) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } public struct Border { public var color: KFCrossPlatformColor public var lineWidth: CGFloat /// The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction of the /// target image with `.widthFraction`. or `.heightFraction`. For example, given a square image with width and /// height equals, `.widthFraction(0.5)` means use half of the length of size and makes the final image a round one. public var radius: Radius /// The target corners which will be applied rounding. public var roundingCorners: RectCorner public init( color: KFCrossPlatformColor = .black, lineWidth: CGFloat = 4, radius: Radius = .point(0), roundingCorners: RectCorner = .all ) { self.color = color self.lineWidth = lineWidth self.radius = radius self.roundingCorners = roundingCorners } var identifier: String { "\(color.hex)_\(lineWidth)_\(radius.radiusIdentifier)_\(roundingCorners.cornerIdentifier)" } } public struct BorderImageProcessor: ImageProcessor { public var identifier: String { "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(border)" } public let border: Border public init(border: Border) { self.border = border } public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.addingBorder(border) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Represents how a size adjusts itself to fit a target size. /// /// - none: Not scale the content. /// - aspectFit: Scales the content to fit the size of the view by maintaining the aspect ratio. /// - aspectFill: Scales the content to fill the size of the view. public enum ContentMode { /// Not scale the content. case none /// Scales the content to fit the size of the view by maintaining the aspect ratio. case aspectFit /// Scales the content to fill the size of the view. case aspectFill } /// Processor for resizing images. /// If you need to resize a data represented image to a smaller size, use `DownsamplingImageProcessor` /// instead, which is more efficient and uses less memory. public struct ResizingImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// The reference size for resizing operation in point. public let referenceSize: CGSize /// Target content mode of output image should be. /// Default is `.none`. public let targetContentMode: ContentMode /// Creates a `ResizingImageProcessor`. /// /// - Parameters: /// - referenceSize: The reference size for resizing operation in point. /// - mode: Target content mode of output image should be. /// /// - Note: /// The instance of `ResizingImageProcessor` will follow its `mode` property /// and try to resizing the input images to fit or fill the `referenceSize`. /// That means if you are using a `mode` besides of `.none`, you may get an /// image with its size not be the same as the `referenceSize`. /// /// **Example**: With input image size: {100, 200}, /// `referenceSize`: {100, 100}, `mode`: `.aspectFit`, /// you will get an output image with size of {50, 100}, which "fit"s /// the `referenceSize`. /// /// If you need an output image exactly to be a specified size, append or use /// a `CroppingImageProcessor`. public init(referenceSize: CGSize, mode: ContentMode = .none) { self.referenceSize = referenceSize self.targetContentMode = mode if mode == .none { self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize))" } else { self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize), \(mode))" } } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.resize(to: referenceSize, for: targetContentMode) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for /// a better performance. A simulated Gaussian blur with specified blur radius will be applied. public struct BlurImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Blur radius for the simulated Gaussian blur. public let blurRadius: CGFloat /// Creates a `BlurImageProcessor` /// /// - parameter blurRadius: Blur radius for the simulated Gaussian blur. public init(blurRadius: CGFloat) { self.blurRadius = blurRadius self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))" } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): let radius = blurRadius * options.scaleFactor return image.kf.scaled(to: options.scaleFactor) .kf.blurred(withRadius: radius) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Processor for adding an overlay to images. Only CG-based images are supported in macOS. public struct OverlayImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Overlay color will be used to overlay the input image. public let overlay: KFCrossPlatformColor /// Fraction will be used when overlay the color to image. public let fraction: CGFloat /// Creates an `OverlayImageProcessor` /// /// - parameter overlay: Overlay color will be used to overlay the input image. /// - parameter fraction: Fraction will be used when overlay the color to image. /// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. public init(overlay: KFCrossPlatformColor, fraction: CGFloat = 0.5) { self.overlay = overlay self.fraction = fraction self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.hex)_\(fraction))" } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.overlaying(with: overlay, fraction: fraction) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Processor for tint images with color. Only CG-based images are supported. public struct TintImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Tint color will be used to tint the input image. public let tint: KFCrossPlatformColor /// Creates a `TintImageProcessor` /// /// - parameter tint: Tint color will be used to tint the input image. public init(tint: KFCrossPlatformColor) { self.tint = tint self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.hex))" } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.tinted(with: tint) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Processor for applying some color control to images. Only CG-based images are supported. /// watchOS is not supported. public struct ColorControlsProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Brightness changing to image. public let brightness: CGFloat /// Contrast changing to image. public let contrast: CGFloat /// Saturation changing to image. public let saturation: CGFloat /// InputEV changing to image. public let inputEV: CGFloat /// Creates a `ColorControlsProcessor` /// /// - Parameters: /// - brightness: Brightness changing to image. /// - contrast: Contrast changing to image. /// - saturation: Saturation changing to image. /// - inputEV: InputEV changing to image. public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) { self.brightness = brightness self.contrast = contrast self.saturation = saturation self.inputEV = inputEV self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))" } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Processor for applying black and white effect to images. Only CG-based images are supported. /// watchOS is not supported. public struct BlackWhiteProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor" /// Creates a `BlackWhiteProcessor` public init() {} /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7) .process(item: item, options: options) } } /// Processor for cropping an image. Only CG-based images are supported. /// watchOS is not supported. public struct CroppingImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Target size of output image should be. public let size: CGSize /// Anchor point from which the output size should be calculate. /// The anchor point is consisted by two values between 0.0 and 1.0. /// It indicates a related point in current image. /// See `CroppingImageProcessor.init(size:anchor:)` for more. public let anchor: CGPoint /// Creates a `CroppingImageProcessor`. /// /// - Parameters: /// - size: Target size of output image should be. /// - anchor: The anchor point from which the size should be calculated. /// Default is `CGPoint(x: 0.5, y: 0.5)`, which means the center of input image. /// - Note: /// The anchor point is consisted by two values between 0.0 and 1.0. /// It indicates a related point in current image, eg: (0.0, 0.0) for top-left /// corner, (0.5, 0.5) for center and (1.0, 1.0) for bottom-right corner. /// The `size` property of `CroppingImageProcessor` will be used along with /// `anchor` to calculate a target rectangle in the size of image. /// /// The target size will be automatically calculated with a reasonable behavior. /// For example, when you have an image size of `CGSize(width: 100, height: 100)`, /// and a target size of `CGSize(width: 20, height: 20)`: /// - with a (0.0, 0.0) anchor (top-left), the crop rect will be `{0, 0, 20, 20}`; /// - with a (0.5, 0.5) anchor (center), it will be `{40, 40, 20, 20}` /// - while with a (1.0, 1.0) anchor (bottom-right), it will be `{80, 80, 20, 20}` public init(size: CGSize, anchor: CGPoint = CGPoint(x: 0.5, y: 0.5)) { self.size = size self.anchor = anchor self.identifier = "com.onevcat.Kingfisher.CroppingImageProcessor(\(size)_\(anchor))" } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.crop(to: size, anchorOn: anchor) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Processor for downsampling an image. Compared to `ResizingImageProcessor`, this processor /// does not render the images to resize. Instead, it downsamples the input data directly to an /// image. It is a more efficient than `ResizingImageProcessor`. Prefer to use `DownsamplingImageProcessor` as possible /// as you can than the `ResizingImageProcessor`. /// /// Only CG-based images are supported. Animated images (like GIF) is not supported. public struct DownsamplingImageProcessor: ImageProcessor { /// Target size of output image should be. It should be smaller than the size of /// input image. If it is larger, the result image will be the same size of input /// data without downsampling. public let size: CGSize /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Creates a `DownsamplingImageProcessor`. /// /// - Parameter size: The target size of the downsample operation. public init(size: CGSize) { self.size = size self.identifier = "com.onevcat.Kingfisher.DownsamplingImageProcessor(\(size))" } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): guard let data = image.kf.data(format: .unknown) else { return nil } return KingfisherWrapper.downsampledImage(data: data, to: size, scale: options.scaleFactor) case .data(let data): return KingfisherWrapper.downsampledImage(data: data, to: size, scale: options.scaleFactor) } } } infix operator |>: AdditionPrecedence public func |>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor { return left.append(another: right) } extension KFCrossPlatformColor { var rgba: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 #if os(macOS) (usingColorSpace(.sRGB) ?? self).getRed(&r, green: &g, blue: &b, alpha: &a) #else getRed(&r, green: &g, blue: &b, alpha: &a) #endif return (r, g, b, a) } var hex: String { let (r, g, b, a) = rgba let rInt = Int(r * 255) << 24 let gInt = Int(g * 255) << 16 let bInt = Int(b * 255) << 8 let aInt = Int(a * 255) let rgba = rInt | gInt | bInt | aInt return String(format:"#%08x", rgba) } }
mit
e396741da9d8fb64d16997375a491241
40.652361
125
0.65219
4.803861
false
false
false
false
Headmast/openfights
MoneyHelperTests/Tests/Screens/Infromation/View/InfromationViewTests.swift
1
1007
// // InfromationViewTests.swift // MoneyHelper // // Created by Kirill Klebanov on 16/09/2017. // Copyright © 2017 Surf. All rights reserved. // import XCTest @testable import MoneyHelper final class InfromationViewTests: XCTestCase { private var view: InfromationViewController? private var output: InfromationViewOutputMock? override func setUp() { super.setUp() view = InfromationViewController() output = InfromationViewOutputMock() view?.output = output } override func tearDown() { super.tearDown() view = nil output = nil } func testThatViewNotifiesPresenterOnDidLoad() { // when self.view?.viewDidLoad() // then XCTAssert(self.output?.viewLoadedWasCalled == true) } final class InfromationViewOutputMock: InfromationViewOutput { var viewLoadedWasCalled: Bool = false func viewLoaded() { viewLoadedWasCalled = true } } }
apache-2.0
78163bd728ea7f4d34abda847c78c9eb
21.355556
66
0.643141
4.572727
false
true
false
false
kentaiwami/FiNote
ios/FiNote/FiNote/Extensions.swift
1
2468
// // Extensions.swift // FiNote // // Created by 岩見建汰 on 2018/01/21. // Copyright © 2018年 Kenta. All rights reserved. // import UIKit extension UIColor { class func hex ( _ hexStr : String, alpha : CGFloat) -> UIColor { var hexString = hexStr as NSString hexString = hexString.replacingOccurrences(of: "#", with: "") as NSString let scanner = Scanner(string: hexString as String) var color: UInt32 = 0 if scanner.scanHexInt32(&color) { let r = CGFloat((color & 0xFF0000) >> 16) / 255.0 let g = CGFloat((color & 0x00FF00) >> 8) / 255.0 let b = CGFloat(color & 0x0000FF) / 255.0 return UIColor(red:r,green:g,blue:b,alpha:alpha) } else { print("invalid hex string") return UIColor.white; } } } extension UIScrollView { public enum ScrollDirection { case top } public func scroll(to direction: ScrollDirection, animated: Bool) { let offset: CGPoint switch direction { case .top: offset = CGPoint(x: contentOffset.x, y: -adjustedContentInset.top) } setContentOffset(offset, animated: animated) } } extension String { func pregMatche(pattern: String, options: NSRegularExpression.Options = [], matches: inout [String]) -> Bool { guard let regex = try? NSRegularExpression(pattern: pattern, options: options) else { return false } let targetStringRange = NSRange(location: 0, length: self.count) let results = regex.matches(in: self, options: [], range: targetStringRange) for i in 0 ..< results.count { for j in 0 ..< results[i].numberOfRanges { let range = results[i].range(at: j) matches.append((self as NSString).substring(with: range)) } } return results.count > 0 } } extension Date { static func stringFromString(string: String, formatIn: String, formatOut: String) -> String { let formatterIn: DateFormatter = DateFormatter() formatterIn.dateFormat = formatIn let formatterOut: DateFormatter = DateFormatter() formatterOut.dateFormat = formatOut return formatterOut.string(from: formatterIn.date(from: string)!) } } extension UIViewController { func GetClassName() -> String { return String(describing: type(of: self)) } }
mit
079f0224815eedffdafec2d144d8f1e0
31.328947
114
0.608059
4.265625
false
false
false
false
Kyoooooo/DouYuZhiBo
DYZB/DYZB/Classes/Home/View/AmuseMenuViewCell.swift
1
1669
// // AmuseMenuViewCell.swift // DYZB // // Created by 张起哲 on 2017/9/9. // Copyright © 2017年 张起哲. All rights reserved. // import UIKit private let kGameCellID = "kGameCellID" class AmuseMenuViewCell: UICollectionViewCell { // MARK: 数组模型 var groups : [AnchorGroup]? { didSet { collectionView.reloadData() } } @IBOutlet weak var collectionView: UICollectionView! // MARK: 从Xib中加载 override func awakeFromNib() { super.awakeFromNib() collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) } override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout let itemW = collectionView.bounds.width / 4 let itemH = collectionView.bounds.height / 2 layout.itemSize = CGSize(width: itemW, height: itemH) } } extension AmuseMenuViewCell : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return groups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.求出Cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell // 2.给Cell设置数据 cell.baseGame = groups![indexPath.item] cell.clipsToBounds = true return cell } }
mit
b894b905747c69f9a9e3c3d501998ef1
27.491228
126
0.663177
5.139241
false
false
false
false
ziogaschr/SwiftPasscodeLock
PasscodeLock/PasscodeLock/ConfirmPasscodeState.swift
1
1496
// // ConfirmPasscodeState.swift // PasscodeLock // // Created by Yanko Dimitrov on 8/28/15. // Copyright © 2015 Yanko Dimitrov. All rights reserved. // import Foundation struct ConfirmPasscodeState: PasscodeLockStateType { let title: String let description: String let isCancellableAction = true var isTouchIDAllowed = false fileprivate var passcodeToConfirm: [String] init(passcode: [String]) { passcodeToConfirm = passcode title = localizedStringFor("PasscodeLockConfirmTitle", comment: "Confirm passcode title") description = localizedStringFor("PasscodeLockConfirmDescription", comment: "Confirm passcode description") } func acceptPasscode(_ passcode: [String], fromLock lock: PasscodeLockType) { if passcode == passcodeToConfirm { lock.repository.savePasscode(passcode) lock.delegate?.passcodeLockDidSucceed(lock) } else { let mismatchTitle = localizedStringFor("PasscodeLockMismatchTitle", comment: "Passcode mismatch title") let mismatchDescription = localizedStringFor("PasscodeLockMismatchDescription", comment: "Passcode mismatch description") let nextState = SetPasscodeState(title: mismatchTitle, description: mismatchDescription) lock.changeStateTo(nextState) lock.delegate?.passcodeLockDidFail(lock) } } }
mit
414839e907ca4b4254f67d1dabfe3f8b
32.222222
133
0.664883
5.599251
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Library/ReaderPanel.swift
2
22224
// 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 UIKit import Storage import Shared private let log = Logger.browserLogger private struct ReadingListTableViewCellUX { static let RowHeight: CGFloat = 86 static let ReadIndicatorWidth: CGFloat = 12 // image width static let ReadIndicatorHeight: CGFloat = 12 // image height static let ReadIndicatorLeftOffset: CGFloat = 18 static let ReadAccessibilitySpeechPitch: Float = 0.7 // 1.0 default, 0.0 lowest, 2.0 highest static let TitleLabelTopOffset: CGFloat = 14 - 4 static let TitleLabelLeftOffset: CGFloat = 16 + 16 + 16 static let TitleLabelRightOffset: CGFloat = -40 static let HostnameLabelBottomOffset: CGFloat = 11 static let DeleteButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) static let MarkAsReadButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) } private struct ReadingListPanelUX { // Welcome Screen static let WelcomeScreenPadding: CGFloat = 15 static let WelcomeScreenHorizontalMinPadding: CGFloat = 40 static let WelcomeScreenMaxWidth: CGFloat = 400 static let WelcomeScreenItemImageWidth: CGFloat = 20 static let WelcomeScreenTopPadding: CGFloat = 120 } class ReadingListTableViewCell: UITableViewCell, ThemeApplicable { var title: String = "Example" { didSet { titleLabel.text = title updateAccessibilityLabel() } } var url = URL(string: "http://www.example.com")! { didSet { hostnameLabel.text = simplifiedHostnameFromURL(url) updateAccessibilityLabel() } } var unread: Bool = true { didSet { readStatusImageView.image = UIImage(named: unread ? "MarkAsRead" : "MarkAsUnread")?.withRenderingMode(.alwaysTemplate) updateAccessibilityLabel() } } let readStatusImageView: UIImageView = .build { imageView in imageView.contentMode = .scaleAspectFit } let titleLabel: UILabel = .build { label in label.numberOfLines = 2 label.font = DynamicFontHelper.defaultHelper.DeviceFont } let hostnameLabel: UILabel = .build { label in label.numberOfLines = 1 label.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupLayout() } private func setupLayout() { backgroundColor = UIColor.clear separatorInset = UIEdgeInsets(top: 0, left: 48, bottom: 0, right: 0) layoutMargins = .zero preservesSuperviewLayoutMargins = false contentView.addSubviews(readStatusImageView, titleLabel, hostnameLabel) NSLayoutConstraint.activate([ readStatusImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: CGFloat(ReadingListTableViewCellUX.ReadIndicatorLeftOffset)), readStatusImageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), readStatusImageView.widthAnchor.constraint(equalToConstant: CGFloat(ReadingListTableViewCellUX.ReadIndicatorWidth)), readStatusImageView.heightAnchor.constraint(equalToConstant: CGFloat(ReadingListTableViewCellUX.ReadIndicatorHeight)), titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: CGFloat(ReadingListTableViewCellUX.TitleLabelTopOffset)), titleLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: CGFloat(ReadingListTableViewCellUX.TitleLabelLeftOffset)), titleLabel.bottomAnchor.constraint(equalTo: hostnameLabel.topAnchor), titleLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: CGFloat(ReadingListTableViewCellUX.TitleLabelRightOffset)), hostnameLabel.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor), hostnameLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: CGFloat(-ReadingListTableViewCellUX.HostnameLabelBottomOffset)), hostnameLabel.trailingAnchor.constraint(equalTo: titleLabel.trailingAnchor) ]) } func applyTheme(theme: Theme) { backgroundColor = theme.colors.layer5 selectedBackgroundView?.backgroundColor = theme.colors.layer5Hover titleLabel.textColor = unread ? theme.colors.textPrimary : theme.colors.textDisabled hostnameLabel.textColor = unread ? theme.colors.textPrimary : theme.colors.textDisabled readStatusImageView.tintColor = theme.colors.iconAction } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let prefixesToSimplify = ["www.", "mobile.", "m.", "blog."] fileprivate func simplifiedHostnameFromURL(_ url: URL) -> String { let hostname = url.host ?? "" for prefix in prefixesToSimplify { if hostname.hasPrefix(prefix) { return String(hostname[hostname.index(hostname.startIndex, offsetBy: prefix.count)...]) } } return hostname } fileprivate func updateAccessibilityLabel() { if let hostname = hostnameLabel.text, let title = titleLabel.text { let unreadStatus: String = unread ? .ReaderPanelUnreadAccessibilityLabel : .ReaderPanelReadAccessibilityLabel let string = "\(title), \(unreadStatus), \(hostname)" var label: AnyObject if !unread { // mimic light gray visual dimming by "dimming" the speech by reducing pitch let lowerPitchString = NSMutableAttributedString(string: string as String) lowerPitchString.addAttribute( NSAttributedString.Key.accessibilitySpeechPitch, value: NSNumber(value: ReadingListTableViewCellUX.ReadAccessibilitySpeechPitch as Float), range: NSRange(location: 0, length: lowerPitchString.length)) label = NSAttributedString(attributedString: lowerPitchString) } else { label = string as AnyObject } // need to use KVC as accessibilityLabel is of type String! and cannot be set to NSAttributedString other way than this // see bottom of page 121 of the PDF slides of WWDC 2012 "Accessibility for iOS" session for indication that this is OK by Apple // also this combined with Swift's strictness is why we cannot simply override accessibilityLabel and return the label directly... setValue(label, forKey: "accessibilityLabel") } } } class ReadingListPanel: UITableViewController, LibraryPanel, Themeable { weak var libraryPanelDelegate: LibraryPanelDelegate? let profile: Profile var state: LibraryPanelMainState var bottomToolbarItems: [UIBarButtonItem] = [UIBarButtonItem]() var themeManager: ThemeManager var themeObserver: NSObjectProtocol? var notificationCenter: NotificationProtocol private lazy var longPressRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(longPress)) }() private var records: [ReadingListItem]? init(profile: Profile, themeManager: ThemeManager = AppContainer.shared.resolve(), notificationCenter: NotificationProtocol = NotificationCenter.default) { self.profile = profile self.themeManager = themeManager self.notificationCenter = notificationCenter self.state = .readingList super.init(nibName: nil, bundle: nil) [ Notification.Name.FirefoxAccountChanged, Notification.Name.DynamicFontChanged, Notification.Name.DatabaseWasReopened ].forEach { NotificationCenter.default.addObserver(self, selector: #selector(notificationReceived), name: $0, object: nil) } } required init!(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) refreshReadingList() // Note this will then call applyTheme() on this class, which reloads the tableview. (navigationController as? ThemedNavigationController)?.applyTheme() tableView.accessibilityIdentifier = "ReadingTable" } override func viewDidLoad() { super.viewDidLoad() tableView.addGestureRecognizer(longPressRecognizer) tableView.estimatedRowHeight = ReadingListTableViewCellUX.RowHeight tableView.rowHeight = UITableView.automaticDimension tableView.cellLayoutMarginsFollowReadableWidth = false tableView.separatorInset = .zero tableView.layoutMargins = .zero tableView.register(ReadingListTableViewCell.self, forCellReuseIdentifier: "ReadingListTableViewCell") // Set an empty footer to prevent empty cells from appearing in the list. tableView.tableFooterView = UIView() tableView.dragDelegate = self applyTheme() listenForThemeChange() } @objc func notificationReceived(_ notification: Notification) { switch notification.name { case .FirefoxAccountChanged, .DynamicFontChanged: refreshReadingList() case .DatabaseWasReopened: if let dbName = notification.object as? String, dbName == "ReadingList.db" { refreshReadingList() } default: // no need to do anything at all log.warning("Received unexpected notification \(notification.name)") break } } func refreshReadingList() { let prevNumberOfRecords = records?.count tableView.tableHeaderView = nil if let newRecords = profile.readingList.getAvailableRecords().value.successValue { records = newRecords if let records = records, records.isEmpty { tableView.isScrollEnabled = false DispatchQueue.main.async { self.tableView.backgroundView = self.emptyStateView } } else { if prevNumberOfRecords == 0 { tableView.isScrollEnabled = true DispatchQueue.main.async { self.tableView.backgroundView = nil } } } self.tableView.reloadData() } } private lazy var emptyStateView: UIView = { let view = UIView() let welcomeLabel: UILabel = .build { label in label.text = .ReaderPanelWelcome label.textAlignment = .center label.font = DynamicFontHelper.defaultHelper.DeviceFontSmallBold label.adjustsFontSizeToFitWidth = true label.textColor = self.themeManager.currentTheme.colors.textSecondary } let readerModeLabel: UILabel = .build { label in label.text = .ReaderPanelReadingModeDescription label.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight label.numberOfLines = 0 label.textColor = self.themeManager.currentTheme.colors.textSecondary } let readerModeImageView: UIImageView = .build { imageView in imageView.contentMode = .scaleAspectFit imageView.image = UIImage(named: "ReaderModeCircle")?.withRenderingMode(.alwaysTemplate) imageView.tintColor = self.themeManager.currentTheme.colors.textSecondary } let readingListLabel: UILabel = .build { label in label.text = .ReaderPanelReadingListDescription label.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight label.numberOfLines = 0 label.textColor = self.themeManager.currentTheme.colors.textSecondary } let readingListImageView: UIImageView = .build { imageView in imageView.contentMode = .scaleAspectFit imageView.image = UIImage(named: "AddToReadingListCircle")?.withRenderingMode(.alwaysTemplate) imageView.tintColor = self.themeManager.currentTheme.colors.textSecondary } let emptyStateViewWrapper: UIView = .build { view in view.addSubviews(welcomeLabel, readerModeLabel, readerModeImageView, readingListLabel, readingListImageView) } view.addSubview(emptyStateViewWrapper) NSLayoutConstraint.activate([ // title welcomeLabel.topAnchor.constraint(equalTo: emptyStateViewWrapper.topAnchor), welcomeLabel.leadingAnchor.constraint(equalTo: emptyStateViewWrapper.leadingAnchor), welcomeLabel.trailingAnchor.constraint(equalTo: emptyStateViewWrapper.trailingAnchor), // first row readerModeLabel.topAnchor.constraint(equalTo: welcomeLabel.bottomAnchor, constant: ReadingListPanelUX.WelcomeScreenPadding), readerModeLabel.leadingAnchor.constraint(equalTo: welcomeLabel.leadingAnchor), readerModeLabel.trailingAnchor.constraint(equalTo: readerModeImageView.leadingAnchor, constant: -ReadingListPanelUX.WelcomeScreenPadding), readerModeImageView.centerYAnchor.constraint(equalTo: readerModeLabel.centerYAnchor), readerModeImageView.trailingAnchor.constraint(equalTo: welcomeLabel.trailingAnchor), readerModeImageView.widthAnchor.constraint(equalToConstant: ReadingListPanelUX.WelcomeScreenItemImageWidth), // second row readingListLabel.topAnchor.constraint(equalTo: readerModeLabel.bottomAnchor, constant: ReadingListPanelUX.WelcomeScreenPadding), readingListLabel.leadingAnchor.constraint(equalTo: welcomeLabel.leadingAnchor), readingListLabel.trailingAnchor.constraint(equalTo: readingListImageView.leadingAnchor, constant: -ReadingListPanelUX.WelcomeScreenPadding), readingListImageView.centerYAnchor.constraint(equalTo: readingListLabel.centerYAnchor), readingListImageView.trailingAnchor.constraint(equalTo: welcomeLabel.trailingAnchor), readingListImageView.widthAnchor.constraint(equalToConstant: ReadingListPanelUX.WelcomeScreenItemImageWidth), readingListLabel.bottomAnchor.constraint(equalTo: emptyStateViewWrapper.bottomAnchor), // overall positioning of emptyStateViewWrapper emptyStateViewWrapper.leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: ReadingListPanelUX.WelcomeScreenHorizontalMinPadding), emptyStateViewWrapper.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -ReadingListPanelUX.WelcomeScreenHorizontalMinPadding), emptyStateViewWrapper.widthAnchor.constraint(lessThanOrEqualToConstant: ReadingListPanelUX.WelcomeScreenMaxWidth), emptyStateViewWrapper.centerXAnchor.constraint(equalTo: view.centerXAnchor), emptyStateViewWrapper.topAnchor.constraint(equalTo: view.topAnchor, constant: ReadingListPanelUX.WelcomeScreenTopPadding) ]) return view }() @objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) { guard longPressGestureRecognizer.state == .began else { return } let touchPoint = longPressGestureRecognizer.location(in: tableView) guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return } presentContextMenu(for: indexPath) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return records?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ReadingListTableViewCell", for: indexPath) as! ReadingListTableViewCell if let record = records?[indexPath.row] { cell.title = record.title cell.url = URL(string: record.url)! cell.unread = record.unread cell.applyTheme(theme: themeManager.currentTheme) } return cell } override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { guard let record = records?[safe: indexPath.row] else { return nil } let deleteAction = UIContextualAction(style: .destructive, title: .ReaderPanelRemove) { [weak self] (_, _, completion) in guard let strongSelf = self else { completion(false); return } strongSelf.deleteItem(atIndex: indexPath) completion(true) } let toggleText: String = record.unread ? .ReaderPanelMarkAsRead : .ReaderModeBarMarkAsUnread let unreadToggleAction = UIContextualAction(style: .normal, title: toggleText.stringSplitWithNewline()) { [weak self] (_, view, completion) in guard let strongSelf = self else { completion(false); return } strongSelf.toggleItem(atIndex: indexPath) completion(true) } return UISwipeActionsConfiguration(actions: [unreadToggleAction, deleteAction]) } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // the cells you would like the actions to appear needs to be editable return true } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) if let record = records?[indexPath.row], let url = URL(string: record.url), let encodedURL = url.encodeReaderModeURL(WebServer.sharedInstance.baseReaderModeURL()) { // Mark the item as read profile.readingList.updateRecord(record, unread: false) // Reading list items are closest in concept to bookmarks. let visitType = VisitType.bookmark libraryPanelDelegate?.libraryPanel(didSelectURL: encodedURL, visitType: visitType) TelemetryWrapper.recordEvent(category: .action, method: .open, object: .readingListItem) } } fileprivate func deleteItem(atIndex indexPath: IndexPath) { if let record = records?[indexPath.row] { TelemetryWrapper.recordEvent(category: .action, method: .delete, object: .readingListItem, value: .readingListPanel) profile.readingList.deleteRecord(record, completion: { success in guard success else { return } self.records?.remove(at: indexPath.row) DispatchQueue.main.async { self.tableView.deleteRows(at: [indexPath], with: .automatic) // reshow empty state if no records left if let records = self.records, records.isEmpty { self.refreshReadingList() } } }) } } fileprivate func toggleItem(atIndex indexPath: IndexPath) { if let record = records?[indexPath.row] { TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .readingListItem, value: !record.unread ? .markAsUnread : .markAsRead, extras: [ "from": "reading-list-panel" ]) if let updatedRecord = profile.readingList.updateRecord(record, unread: !record.unread).value.successValue { records?[indexPath.row] = updatedRecord tableView.reloadRows(at: [indexPath], with: .automatic) } } } func applyTheme() { tableView.separatorColor = themeManager.currentTheme.colors.borderPrimary view.backgroundColor = themeManager.currentTheme.colors.layer6 tableView.backgroundColor = themeManager.currentTheme.colors.layer6 refreshReadingList() } } extension ReadingListPanel: LibraryPanelContextMenu { func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) { guard let contextMenu = completionHandler() else { return } self.present(contextMenu, animated: true, completion: nil) } func getSiteDetails(for indexPath: IndexPath) -> Site? { guard let record = records?[indexPath.row] else { return nil } return Site(url: record.url, title: record.title) } func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonRowActions]? { guard var actions = getDefaultContextMenuActions(for: site, libraryPanelDelegate: libraryPanelDelegate) else { return nil } let removeAction = SingleActionViewModel(title: .RemoveContextMenuTitle, iconString: ImageIdentifiers.actionRemove, tapHandler: { _ in self.deleteItem(atIndex: indexPath) }).items actions.append(removeAction) return actions } } extension ReadingListPanel: UITableViewDragDelegate { func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] { guard let site = getSiteDetails(for: indexPath), let url = URL(string: site.url), let itemProvider = NSItemProvider(contentsOf: url) else { return [] } TelemetryWrapper.recordEvent(category: .action, method: .drag, object: .url, value: .readingListPanel) let dragItem = UIDragItem(itemProvider: itemProvider) dragItem.localObject = site return [dragItem] } func tableView(_ tableView: UITableView, dragSessionWillBegin session: UIDragSession) { presentedViewController?.dismiss(animated: true) } }
mpl-2.0
40d3996acacc849eb8c12a063fd27c4d
46.184713
194
0.68678
5.876256
false
false
false
false
google/iosched-ios
Source/IOsched/Screens/Explore/ExploreViewController.swift
1
12871
// // Copyright (c) 2019 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import ArWebView // swiftlint:disable identifier_name public func IsExploreModeSupported() -> Bool { if #available(iOS 11, *) { #if targetEnvironment(simulator) return true #else return GARArStatus.sharedInstance.arKitReady #endif } else { return false } } // swiftlint:enable identifier_name class ExploreViewController: UIViewController, WKNavigationDelegate, UIScrollViewDelegate { @available(iOS 11, *) private lazy var arWebView: GARArWebView! = initializeWebView() private lazy var notSupportedView = ExploreNotSupportedView(frame: view.frame) private lazy var offlineView = ExploreOfflineView(frame: view.frame) private let reservationDataSource: RemoteReservationDataSource private let bookmarkDataSource: RemoteBookmarkDataSource private let sessionsDataSource: LazyReadonlySessionsDataSource private let debugStatusFetcher = DebugModeStatusFetcher() private static let dateFormatter: DateFormatter = { let formatter = TimeZoneAwareDateFormatter() formatter.setLocalizedDateFormatFromTemplate("MMMdd") formatter.timeZone = TimeZone.userTimeZone() return formatter }() private static let timeFormatter: DateFormatter = { let formatter = TimeZoneAwareDateFormatter() formatter.timeStyle = .short formatter.timeZone = TimeZone.userTimeZone() return formatter }() public init(reservations: RemoteReservationDataSource, bookmarks: RemoteBookmarkDataSource, sessions: LazyReadonlySessionsDataSource) { reservationDataSource = reservations bookmarkDataSource = bookmarks sessionsDataSource = sessions super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func jsonForReservedAndBookmarkedSessions() -> String { sessionsDataSource.update() var userAgenda: [Session] = [] for reservedSession in reservationDataSource.reservedSessions where reservedSession.status != .none { if let session = sessionsDataSource[reservedSession.id] { userAgenda.append(session) } } for bookmarkedSessionID in bookmarkDataSource.bookmarks.keys { // Don't duplicate reserved/waitlisted and bookmarked sessions here. if reservationDataSource.reservationStatus(for: bookmarkedSessionID) == .none, let session = sessionsDataSource[bookmarkedSessionID] { userAgenda.append(session) } } var list: [[String: Any]] = [] for session in userAgenda { let dateString = ExploreViewController.dateFormatter.string(from: session.startTimestamp) let timeString = ExploreViewController.timeFormatter.string(from: session.startTimestamp) let startTimestamp = Int(session.startTimestamp.timeIntervalSince1970.rounded()) list.append([ "name": session.title, "location": session.roomName, "day": dateString, "time": timeString, "timestamp": startTimestamp, "description": session.detail ]) } let object = ["schedule": list] let json = try? JSONSerialization.data(withJSONObject: object, options: []) let jsonString = json.flatMap { String(data: $0, encoding: .unicode) } return jsonString ?? "{\"schedule\":[]}" } override func viewDidLoad() { super.viewDidLoad() if #available(iOS 11, *) { if IsExploreModeSupported() { setupWebView() } else { setupNotSupportedView() } } else { setupNotSupportedView() } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if #available(iOS 11, *) { UIApplication.shared.isIdleTimerDisabled = true } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) UIApplication.shared.isIdleTimerDisabled = false if #available(iOS 11, *) { showOverlay() } } @available(iOS 11, *) private func initializeWebView() -> GARArWebView { let configuration = WKWebViewConfiguration() configuration.allowsInlineMediaPlayback = true configuration.mediaTypesRequiringUserActionForPlayback = [] configuration.websiteDataStore = WKWebsiteDataStore.default() let webView = WKWebView(frame: view.bounds, configuration: configuration) let arWebView = GARArWebView(frame: view.bounds, webView: webView) arWebView.translatesAutoresizingMaskIntoConstraints = false arWebView.webView.navigationDelegate = self arWebView.webView.scrollView.isScrollEnabled = false arWebView.webView.scrollView.minimumZoomScale = 1 arWebView.webView.scrollView.maximumZoomScale = 1 arWebView.webView.scrollView.pinchGestureRecognizer?.isEnabled = false arWebView.webView.scrollView.delegate = self return arWebView } @available(iOS 11, *) private func setupWebView() { view.addSubview(arWebView) removeScrollGestureRecognizers() setupWebViewConstraints() registerForTimeZoneChanges() NotificationCenter.default.addObserver(self, selector: #selector(refresh(_:)), name: UIApplication.willEnterForegroundNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(didEnterBackgroundNotification(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil) } private func setupNotSupportedView() { notSupportedView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(notSupportedView) let constraints = [ NSLayoutConstraint(item: notSupportedView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0), NSLayoutConstraint(item: notSupportedView, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: 0), NSLayoutConstraint(item: notSupportedView, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: 0), NSLayoutConstraint(item: notSupportedView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0) ] view.addConstraints(constraints) } private func setupOfflineView() { offlineView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(offlineView) let constraints = [ NSLayoutConstraint(item: offlineView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0), NSLayoutConstraint(item: offlineView, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: 0), NSLayoutConstraint(item: offlineView, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: 0), NSLayoutConstraint(item: offlineView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0) ] view.addConstraints(constraints) } @available(iOS 11, *) private func reloadWebView() { let url = URL(string: "https://sp-io2019.appspot.com/")! let request = URLRequest(url: url, cachePolicy: .reloadRevalidatingCacheData, timeoutInterval: 100) arWebView?.load(request) } @available(iOS 11, *) @objc private func refresh(_ sender: Any) { reloadWebView() } @available(iOS 11, *) @objc private func didEnterBackgroundNotification(_ sender: Any) { showOverlay() } @available(iOS 11, *) private func showOverlay() { let script = "window.app && window.app.addIntroOverlay && window.app.addIntroOverlay();" arWebView.webView.evaluateJavaScript(script) { (result, error) in guard error == nil else { print(error!) return } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if #available(iOS 11, *), IsExploreModeSupported() { offlineView.removeFromSuperview() reloadWebView() } } deinit { NotificationCenter.default.removeObserver(self) } @available(iOS 11, *) private func setupWebViewConstraints() { let constraints = [ NSLayoutConstraint(item: arWebView, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: 0), NSLayoutConstraint(item: arWebView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0), NSLayoutConstraint(item: arWebView, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: 0), NSLayoutConstraint(item: arWebView, attribute: .bottom, relatedBy: .equal, toItem: bottomLayoutGuide, attribute: .top, multiplier: 1, constant: 0) ] view.addConstraints(constraints) } // MARK: - WKNavigationDelegate func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { let agendaJSON = jsonForReservedAndBookmarkedSessions() let javascript = "var object = \(agendaJSON); window.app.sendIOAppUserAgenda(object);" webView.evaluateJavaScript(javascript) { (result, error) in if let error = error { print("evaluateJavascript error: \(error)") } if let result = result { print(result) } } debugStatusFetcher.fetchDebugModeEnabled { status in if status { webView.evaluateJavaScript("window.app.setDebugUser();") { (_, error) in if let error = error { print("Error enabling debug mode: \(error)") } } } } } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { setupOfflineView() } func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { if #available(iOS 11, *) { arWebView.webView(webView, didCommit: navigation) } } @available(iOS 11, *) func removeScrollGestureRecognizers() { // hack for recognizer in arWebView.webView.scrollView.gestureRecognizers ?? [] { recognizer.isEnabled = false arWebView.webView.scrollView.removeGestureRecognizer(recognizer) } } // MARK: - UIScrollViewDelegate func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { if #available(iOS 11, *), IsExploreModeSupported() { removeScrollGestureRecognizers() } } func registerForTimeZoneChanges() { NotificationCenter.default.addObserver(self, selector: #selector(timeZoneDidChange(_:)), name: .timezoneUpdate, object: nil) } @objc private func timeZoneDidChange(_ notification: Any) { if #available(iOS 11, *) { reloadWebView() } } }
apache-2.0
0740d6295ebffe8009514a963a1e1e96
33.231383
99
0.620542
5.206715
false
false
false
false
DoubleSha/BitcoinSwift
BitcoinSwift/Models/NotFoundMessage.swift
1
2181
// // NotFoundMessage.swift // BitcoinSwift // // Created by James MacWhyte on 9/27/14. // Copyright (c) 2014 DoubleSha. All rights reserved. // import Foundation public func ==(left: NotFoundMessage, right: NotFoundMessage) -> Bool { return left.inventoryVectors == right.inventoryVectors } /// Message payload object corresponding to the Message.Command.NotFound command. Is a response to /// getdata, sent if any requested data items could not be relayed. For example, the requested /// transaction may not be in the memory pool or relay set. /// https://en.bitcoin.it/wiki/Protocol_specification#notfound public struct NotFoundMessage: Equatable { public let inventoryVectors: [InventoryVector] public init(inventoryVectors: [InventoryVector]) { precondition(inventoryVectors.count > 0 && inventoryVectors.count <= 50000) self.inventoryVectors = inventoryVectors } } extension NotFoundMessage: MessagePayload { public var command: Message.Command { return Message.Command.NotFound } public var bitcoinData: NSData { let data = NSMutableData() data.appendVarInt(inventoryVectors.count) for inventoryVector in inventoryVectors { data.appendData(inventoryVector.bitcoinData) } return data } public static func fromBitcoinStream(stream: NSInputStream) -> NotFoundMessage? { let inventoryCount = stream.readVarInt() if inventoryCount == nil { Logger.warn("Failed to parse count from NotFoundMessage") return nil } if inventoryCount! == 0 { Logger.warn("Failed to parse NotFoundMessage. Count is zero") return nil } if inventoryCount! > 50000 { Logger.warn("Failed to parse NotFoundMessage. Count is greater than 50000") return nil } var inventoryVectors: [InventoryVector] = [] for _ in 0..<inventoryCount! { let inventoryVector = InventoryVector.fromBitcoinStream(stream) if inventoryVector == nil { Logger.warn("Failed to parse inventory vector from NotFoundMessage") return nil } inventoryVectors.append(inventoryVector!) } return NotFoundMessage(inventoryVectors: inventoryVectors) } }
apache-2.0
13b1058a434bdb3d87a8c05a097963a0
30.608696
99
0.718936
4.45102
false
false
false
false
NeluDob/GifCameraController
Example/GifCameraController/PreviewViewController.swift
1
3302
// // PreviewViewController.swift // GifCameraController // // Created by lola on 4/8/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import ImageIO import MobileCoreServices import AssetsLibrary class PreviewViewController: UIViewController { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! var bitmaps: [CGImage]! var duration: Double! var closeButton: UIButton! var saveButton: UIButton! var gifView: UIImageView! override func viewDidLoad() { super.viewDidLoad() setupGif() self.view.backgroundColor = UIColor.white } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.activityIndicator.hidesWhenStopped = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } fileprivate func setupGif(){ var frames = [UIImage]() for bitmap in bitmaps { let image = UIImage(cgImage: bitmap) frames.append(image) } let gif = UIImage.animatedImage(with: frames, duration: self.duration) self.gifView = UIImageView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width / 2.0, height: UIScreen.main.bounds.height / 2.0)) self.gifView.center = self.view.center self.gifView.image = gif self.view.insertSubview(self.gifView, belowSubview: self.activityIndicator) } @IBAction func saveButtonPressed(_ sender: AnyObject) { self.activityIndicator.startAnimating() UIApplication.shared.beginIgnoringInteractionEvents() let temporaryFile = (NSTemporaryDirectory() as NSString).appendingPathComponent("temp") let fileOutputURL = URL(fileURLWithPath: temporaryFile) let destination = CGImageDestinationCreateWithURL(fileOutputURL as CFURL, kUTTypeGIF, self.bitmaps.count, nil) let fileProperties = [kCGImagePropertyGIFDictionary as String:[kCGImagePropertyGIFLoopCount as String: 0]] let frameProperties = [kCGImagePropertyGIFDictionary as String:[kCGImagePropertyGIFDelayTime as String: self.duration / Double(self.bitmaps.count)]] CGImageDestinationSetProperties(destination!, fileProperties as CFDictionary) for bitmap in self.bitmaps! { CGImageDestinationAddImage(destination!, bitmap, frameProperties as CFDictionary) } CGImageDestinationSetProperties(destination!, fileProperties as CFDictionary) if CGImageDestinationFinalize(destination!) { let library = ALAssetsLibrary() let gifData = try! Data(contentsOf: fileOutputURL) library.writeImageData(toSavedPhotosAlbum: gifData, metadata: nil) { ( url, error) -> Void in DispatchQueue.main.async { self.activityIndicator.stopAnimating() UIApplication.shared.endIgnoringInteractionEvents() self.dismiss(animated: true) { () -> Void in } } } } } @IBAction func closeButtonPressed(_ sender: AnyObject) { dismiss(animated: true) { () -> Void in } } }
mit
b9d03f966fecc9d89ebf0ad9954980be
36.089888
156
0.653135
5.402619
false
false
false
false
schrockblock/gtfs-stations
Example/GTFS StationsTests/PredictionSpec.swift
1
948
// // PredictionSpec.swift // GTFS Stations // // Created by Elliot Schrock on 7/30/15. // Copyright (c) 2015 Elliot Schrock. All rights reserved. // import GTFSStations import Quick import Nimble import SubwayStations class PredictionSpec: QuickSpec { override func spec() { describe("Prediction", { () -> Void in it("is equal when everything matches") { let route = NYCRoute(objectId: "1") let time = NSDate() let first = Prediction(time: time as Date) let second = Prediction(time: time as Date) first.route = route first.direction = .downtown second.route = route second.direction = .downtown expect([first].contains(where: {second == $0})).to(beTruthy()) } }) } }
mit
1f95cf6de3a2ddf408b8c674d11bb3ad
26.085714
78
0.509494
4.787879
false
false
false
false
mightydeveloper/swift
test/SILGen/errors.swift
7
41467
// RUN: %target-swift-frontend -parse-stdlib -emit-silgen -verify %s | FileCheck %s import Swift class Cat {} enum HomeworkError : ErrorType { case TooHard case TooMuch case CatAteIt(Cat) } // CHECK: sil hidden @_TF6errors10make_a_cat{{.*}} : $@convention(thin) () -> (@owned Cat, @error ErrorType) { // CHECK: [[T0:%.*]] = function_ref @_TFC6errors3CatC{{.*}} : $@convention(thin) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[T1:%.*]] = metatype $@thick Cat.Type // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: return [[T2]] : $Cat func make_a_cat() throws -> Cat { return Cat() } // CHECK: sil hidden @_TF6errors15dont_make_a_cat{{.*}} : $@convention(thin) () -> (@owned Cat, @error ErrorType) { // CHECK: [[BOX:%.*]] = alloc_existential_box $ErrorType, $HomeworkError // CHECK: [[T0:%.*]] = function_ref @_TFO6errors13HomeworkError7TooHardFMS0_S0_ : $@convention(thin) (@thin HomeworkError.Type) -> @owned HomeworkError // CHECK-NEXT: [[T1:%.*]] = metatype $@thin HomeworkError.Type // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: store [[T2]] to [[BOX]]#1 // CHECK-NEXT: builtin "willThrow" // CHECK-NEXT: throw [[BOX]]#0 func dont_make_a_cat() throws -> Cat { throw HomeworkError.TooHard } // CHECK: sil hidden @_TF6errors11dont_return{{.*}} : $@convention(thin) <T> (@out T, @in T) -> @error ErrorType { // CHECK: [[BOX:%.*]] = alloc_existential_box $ErrorType, $HomeworkError // CHECK: [[T0:%.*]] = function_ref @_TFO6errors13HomeworkError7TooMuchFMS0_S0_ : $@convention(thin) (@thin HomeworkError.Type) -> @owned HomeworkError // CHECK-NEXT: [[T1:%.*]] = metatype $@thin HomeworkError.Type // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: store [[T2]] to [[BOX]]#1 // CHECK-NEXT: builtin "willThrow" // CHECK-NEXT: destroy_addr %1 : $*T // CHECK-NEXT: throw [[BOX]]#0 func dont_return<T>(argument: T) throws -> T { throw HomeworkError.TooMuch } // CHECK: sil hidden @_TF6errors16all_together_nowFSbCS_3Cat : $@convention(thin) (Bool) -> @owned Cat { // CHECK: bb0(%0 : $Bool): // CHECK: [[DR_FN:%.*]] = function_ref @_TF6errors11dont_returnur{{.*}} : // Branch on the flag. // CHECK: cond_br {{%.*}}, [[FLAG_TRUE:bb[0-9]+]], [[FLAG_FALSE:bb[0-9]+]] // In the true case, call make_a_cat(). // CHECK: [[FLAG_TRUE]]: // CHECK: [[MAC_FN:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error ErrorType) // CHECK-NEXT: try_apply [[MAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[MAC_NORMAL:bb[0-9]+]], error [[MAC_ERROR:bb[0-9]+]] // CHECK: [[MAC_NORMAL]]([[T0:%.*]] : $Cat): // CHECK-NEXT: br [[TERNARY_CONT:bb[0-9]+]]([[T0]] : $Cat) // In the false case, call dont_make_a_cat(). // CHECK: [[FLAG_FALSE]]: // CHECK: [[DMAC_FN:%.*]] = function_ref @_TF6errors15dont_make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error ErrorType) // CHECK-NEXT: try_apply [[DMAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[DMAC_NORMAL:bb[0-9]+]], error [[DMAC_ERROR:bb[0-9]+]] // CHECK: [[DMAC_NORMAL]]([[T0:%.*]] : $Cat): // CHECK-NEXT: br [[TERNARY_CONT]]([[T0]] : $Cat) // Merge point for the ternary operator. Call dont_return with the result. // CHECK: [[TERNARY_CONT]]([[T0:%.*]] : $Cat): // CHECK-NEXT: [[ARG_TEMP:%.*]] = alloc_stack $Cat // CHECK-NEXT: store [[T0]] to [[ARG_TEMP]]#1 // CHECK-NEXT: [[RET_TEMP:%.*]] = alloc_stack $Cat // CHECK-NEXT: try_apply [[DR_FN]]<Cat>([[RET_TEMP]]#1, [[ARG_TEMP]]#1) : $@convention(thin) <τ_0_0> (@out τ_0_0, @in τ_0_0) -> @error ErrorType, normal [[DR_NORMAL:bb[0-9]+]], error [[DR_ERROR:bb[0-9]+]] // CHECK: [[DR_NORMAL]]({{%.*}} : $()): // CHECK-NEXT: [[T0:%.*]] = load [[RET_TEMP]]#1 : $*Cat // CHECK-NEXT: dealloc_stack [[RET_TEMP]]#0 // CHECK-NEXT: dealloc_stack [[ARG_TEMP]]#0 // CHECK-NEXT: br [[RETURN:bb[0-9]+]]([[T0]] : $Cat) // Return block. // CHECK: [[RETURN]]([[T0:%.*]] : $Cat): // CHECK-NEXT: return [[T0]] : $Cat // Catch dispatch block. // CHECK: [[CATCH:bb[0-9]+]]([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: [[SRC_TEMP:%.*]] = alloc_stack $ErrorType // CHECK-NEXT: store [[ERROR]] to [[SRC_TEMP]]#1 // CHECK-NEXT: [[DEST_TEMP:%.*]] = alloc_stack $HomeworkError // CHECK-NEXT: checked_cast_addr_br copy_on_success ErrorType in [[SRC_TEMP]]#1 : $*ErrorType to HomeworkError in [[DEST_TEMP]]#1 : $*HomeworkError, [[IS_HWE:bb[0-9]+]], [[NOT_HWE:bb[0-9]+]] // Catch HomeworkError. // CHECK: [[IS_HWE]]: // CHECK-NEXT: [[T0:%.*]] = load [[DEST_TEMP]]#1 : $*HomeworkError // CHECK-NEXT: switch_enum [[T0]] : $HomeworkError, case #HomeworkError.CatAteIt!enumelt.1: [[MATCH:bb[0-9]+]], default [[NO_MATCH:bb[0-9]+]] // Catch HomeworkError.CatAteIt. // CHECK: [[MATCH]]([[T0:%.*]] : $Cat): // CHECK-NEXT: debug_value // CHECK-NEXT: dealloc_stack [[DEST_TEMP]]#0 // CHECK-NEXT: destroy_addr [[SRC_TEMP]]#1 // CHECK-NEXT: dealloc_stack [[SRC_TEMP]]#0 // CHECK-NEXT: br [[RETURN]]([[T0]] : $Cat) // Catch other HomeworkErrors. // CHECK: [[NO_MATCH]]: // CHECK-NEXT: dealloc_stack [[DEST_TEMP]]#0 // CHECK-NEXT: dealloc_stack [[SRC_TEMP]]#0 // CHECK-NEXT: br [[CATCHALL:bb[0-9]+]] // Catch other types. // CHECK: [[NOT_HWE]]: // CHECK-NEXT: dealloc_stack [[DEST_TEMP]]#0 // CHECK-NEXT: dealloc_stack [[SRC_TEMP]]#0 // CHECK-NEXT: br [[CATCHALL:bb[0-9]+]] // Catch all. // CHECK: [[CATCHALL]]: // CHECK: [[T0:%.*]] = function_ref @_TFC6errors3CatC{{.*}} : $@convention(thin) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[T1:%.*]] = metatype $@thick Cat.Type // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: strong_release [[ERROR]] : $ErrorType // CHECK-NEXT: br [[RETURN]]([[T2]] : $Cat) // Landing pad. // CHECK: [[MAC_ERROR]]([[T0:%.*]] : $ErrorType): // CHECK-NEXT: br [[CATCH]]([[T0]] : $ErrorType) // CHECK: [[DMAC_ERROR]]([[T0:%.*]] : $ErrorType): // CHECK-NEXT: br [[CATCH]]([[T0]] : $ErrorType) // CHECK: [[DR_ERROR]]([[T0:%.*]] : $ErrorType): // CHECK-NEXT: dealloc_stack // CHECK-NEXT: dealloc_stack // CHECK-NEXT: br [[CATCH]]([[T0]] : $ErrorType) func all_together_now(flag: Bool) -> Cat { do { return try dont_return(flag ? make_a_cat() : dont_make_a_cat()) } catch HomeworkError.CatAteIt(let cat) { return cat } catch _ { return Cat() } } // Catch in non-throwing context. // CHECK-LABEL: sil hidden @_TF6errors11catch_a_catFT_CS_3Cat : $@convention(thin) () -> @owned Cat // CHECK-NEXT: bb0: // CHECK: [[F:%.*]] = function_ref @_TFC6errors3CatC{{.*}} : $@convention(thin) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[M:%.*]] = metatype $@thick Cat.Type // CHECK-NEXT: [[V:%.*]] = apply [[F]]([[M]]) // CHECK-NEXT: return [[V]] : $Cat func catch_a_cat() -> Cat { do { return Cat() } catch _ as HomeworkError {} // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}} } // Initializers. class HasThrowingInit { var field: Int init(value: Int) throws { field = value } } // CHECK-LABEL: sil hidden @_TFC6errors15HasThrowingInitc{{.*}} : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error ErrorType) { // CHECK: [[T0:%.*]] = mark_uninitialized [rootself] %1 : $HasThrowingInit // CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[T0]] : $HasThrowingInit // CHECK-NEXT: assign %0 to [[T1]] : $*Int // CHECK-NEXT: return [[T0]] : $HasThrowingInit // CHECK-LABEL: sil hidden @_TFC6errors15HasThrowingInitC{{.*}} : $@convention(thin) (Int, @thick HasThrowingInit.Type) -> (@owned HasThrowingInit, @error ErrorType) // CHECK: [[SELF:%.*]] = alloc_ref $HasThrowingInit // CHECK: [[T0:%.*]] = function_ref @_TFC6errors15HasThrowingInitc{{.*}} : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error ErrorType) // CHECK-NEXT: try_apply [[T0]](%0, [[SELF]]) : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error ErrorType), normal bb1, error bb2 // CHECK: bb1([[SELF:%.*]] : $HasThrowingInit): // CHECK-NEXT: return [[SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: builtin "willThrow" // CHECK-NEXT: throw [[ERROR]] enum ColorError : ErrorType { case Red, Green, Blue } //CHECK-LABEL: sil hidden @_TF6errors6IThrowFzT_Vs5Int32 //CHECK: builtin "willThrow" //CHECK-NEXT: throw func IThrow() throws -> Int32 { throw ColorError.Red return 0 // expected-warning {{will never be executed}} } // Make sure that we are not emitting calls to 'willThrow' on rethrow sites. //CHECK-LABEL: sil hidden @_TF6errors12DoesNotThrowFzT_Vs5Int32 //CHECK-NOT: builtin "willThrow" //CHECK: return func DoesNotThrow() throws -> Int32 { try IThrow() return 2 } // rdar://20782111 protocol Doomed { func check() throws } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV6errors12DoomedStructS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed DoomedStruct) -> @error ErrorType // CHECK: [[TEMP:%.*]] = alloc_stack $DoomedStruct // CHECK: copy_addr %0 to [initialization] [[TEMP]]#1 // CHECK: [[SELF:%.*]] = load [[TEMP]]#1 : $*DoomedStruct // CHECK: [[T0:%.*]] = function_ref @_TFV6errors12DoomedStruct5check{{.*}} : $@convention(method) (DoomedStruct) -> @error ErrorType // CHECK-NEXT: try_apply [[T0]]([[SELF]]) // CHECK: bb1([[T0:%.*]] : $()): // CHECK: dealloc_stack [[TEMP]]#0 // CHECK: return [[T0]] : $() // CHECK: bb2([[T0:%.*]] : $ErrorType): // CHECK: builtin "willThrow"([[T0]] : $ErrorType) // CHECK: dealloc_stack [[TEMP]]#0 // CHECK: throw [[T0]] : $ErrorType struct DoomedStruct : Doomed { func check() throws {} } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC6errors11DoomedClassS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed DoomedClass) -> @error ErrorType { // CHECK: [[TEMP:%.*]] = alloc_stack $DoomedClass // CHECK: copy_addr %0 to [initialization] [[TEMP]]#1 // CHECK: [[SELF:%.*]] = load [[TEMP]]#1 : $*DoomedClass // CHECK: [[T0:%.*]] = class_method [[SELF]] : $DoomedClass, #DoomedClass.check!1 : DoomedClass -> () throws -> () , $@convention(method) (@guaranteed DoomedClass) -> @error ErrorType // CHECK-NEXT: try_apply [[T0]]([[SELF]]) // CHECK: bb1([[T0:%.*]] : $()): // CHECK: strong_release [[SELF]] : $DoomedClass // CHECK: dealloc_stack [[TEMP]]#0 // CHECK: return [[T0]] : $() // CHECK: bb2([[T0:%.*]] : $ErrorType): // CHECK: builtin "willThrow"([[T0]] : $ErrorType) // CHECK: strong_release [[SELF]] : $DoomedClass // CHECK: dealloc_stack [[TEMP]]#0 // CHECK: throw [[T0]] : $ErrorType class DoomedClass : Doomed { func check() throws {} } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV6errors11HappyStructS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed HappyStruct) -> @error ErrorType // CHECK: [[TEMP:%.*]] = alloc_stack $HappyStruct // CHECK: copy_addr %0 to [initialization] [[TEMP]]#1 // CHECK: [[SELF:%.*]] = load [[TEMP]]#1 : $*HappyStruct // CHECK: [[T0:%.*]] = function_ref @_TFV6errors11HappyStruct5check{{.*}} : $@convention(method) (HappyStruct) -> () // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: dealloc_stack [[TEMP]]#0 // CHECK: return [[T1]] : $() struct HappyStruct : Doomed { func check() {} } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC6errors10HappyClassS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed HappyClass) -> @error ErrorType // CHECK: [[TEMP:%.*]] = alloc_stack $HappyClass // CHECK: copy_addr %0 to [initialization] [[TEMP]]#1 // CHECK: [[SELF:%.*]] = load [[TEMP]]#1 : $*HappyClass // CHECK: [[T0:%.*]] = class_method [[SELF]] : $HappyClass, #HappyClass.check!1 : HappyClass -> () -> () , $@convention(method) (@guaranteed HappyClass) -> () // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: strong_release [[SELF]] : $HappyClass // CHECK: dealloc_stack [[TEMP]]#0 // CHECK: return [[T1]] : $() class HappyClass : Doomed { func check() {} } func create<T>(fn: () throws -> T) throws -> T { return try fn() } func testThunk(fn: () throws -> Int) throws -> Int { return try create(fn) } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__dSizoPs9ErrorType__XFo__iSizoPS___ : $@convention(thin) (@out Int, @owned @callee_owned () -> (Int, @error ErrorType)) -> @error ErrorType // CHECK: bb0(%0 : $*Int, %1 : $@callee_owned () -> (Int, @error ErrorType)): // CHECK: try_apply %1() // CHECK: bb1([[T0:%.*]] : $Int): // CHECK: store [[T0]] to %0 : $*Int // CHECK: [[T0:%.*]] = tuple () // CHECK: return [[T0]] // CHECK: bb2([[T0:%.*]] : $ErrorType): // CHECK: builtin "willThrow"([[T0]] : $ErrorType) // CHECK: throw [[T0]] : $ErrorType func createInt(fn: () -> Int) throws {} func testForceTry(fn: () -> Int) { try! createInt(fn) } // CHECK-LABEL: sil hidden @_TF6errors12testForceTryFFT_SiT_ : $@convention(thin) (@owned @callee_owned () -> Int) -> () // CHECK: [[T0:%.*]] = function_ref @_TF6errors9createIntFzFT_SiT_ : $@convention(thin) (@owned @callee_owned () -> Int) -> @error ErrorType // CHECK: try_apply [[T0]](%0) // CHECK: strong_release // CHECK: return // CHECK: builtin "unexpectedError" // CHECK: unreachable func testForceTryMultiple() { _ = try! (make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden @_TF6errors20testForceTryMultipleFT_T_ // CHECK-NEXT: bb0: // CHECK: [[FN_1:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]] // CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : $Cat) // CHECK: [[FN_2:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]] // CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : $Cat) // CHECK-NEXT: strong_release [[VALUE_2]] : $Cat // CHECK-NEXT: strong_release [[VALUE_1]] : $Cat // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.+]] : $ErrorType): // CHECK-NEXT: = builtin "unexpectedError"([[ERROR]] : $ErrorType) // CHECK-NEXT: unreachable // CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : $ErrorType): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $ErrorType) // CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : $ErrorType): // CHECK-NEXT: strong_release [[VALUE_1]] : $Cat // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $ErrorType) // CHECK: {{^}$}} // Make sure we balance scopes correctly inside a switch. // <rdar://problem/20923654> enum CatFood { case Canned case Dry } // Something we can switch on that throws. func preferredFood() throws -> CatFood { return CatFood.Canned } func feedCat() throws -> Int { switch try preferredFood() { case .Canned: return 0 case .Dry: return 1 } } // CHECK-LABEL: sil hidden @_TF6errors7feedCatFzT_Si : $@convention(thin) () -> (Int, @error ErrorType) // CHECK: %0 = function_ref @_TF6errors13preferredFoodFzT_OS_7CatFood : $@convention(thin) () -> (CatFood, @error ErrorType) // CHECK: try_apply %0() : $@convention(thin) () -> (CatFood, @error ErrorType), normal bb1, error bb5 // CHECK: bb1([[VAL:%.*]] : $CatFood): // CHECK: switch_enum [[VAL]] : $CatFood, case #CatFood.Canned!enumelt: bb2, case #CatFood.Dry!enumelt: bb3 // CHECK: bb5([[ERROR:%.*]] : $ErrorType) // CHECK: throw [[ERROR]] : $ErrorType // Throwing statements inside cases. func getHungryCat(food: CatFood) throws -> Cat { switch food { case .Canned: return try make_a_cat() case .Dry: return try dont_make_a_cat() } } // errors.getHungryCat throws (errors.CatFood) -> errors.Cat // CHECK-LABEL: sil hidden @_TF6errors12getHungryCatFzOS_7CatFoodCS_3Cat : $@convention(thin) (CatFood) -> (@owned Cat, @error ErrorType) // CHECK: bb0(%0 : $CatFood): // CHECK: switch_enum %0 : $CatFood, case #CatFood.Canned!enumelt: bb1, case #CatFood.Dry!enumelt: bb3 // CHECK: bb1: // CHECK: [[FN:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error ErrorType) // CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal bb2, error bb6 // CHECK: bb3: // CHECK: [[FN:%.*]] = function_ref @_TF6errors15dont_make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error ErrorType) // CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal bb4, error bb7 // CHECK: bb6([[ERROR:%.*]] : $ErrorType): // CHECK: br bb8([[ERROR:%.*]] : $ErrorType) // CHECK: bb7([[ERROR:%.*]] : $ErrorType): // CHECK: br bb8([[ERROR]] : $ErrorType) // CHECK: bb8([[ERROR:%.*]] : $ErrorType): // CHECK: throw [[ERROR]] : $ErrorType func take_many_cats(cats: Cat...) throws {} func test_variadic(cat: Cat) throws { try take_many_cats(make_a_cat(), cat, make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden @_TF6errors13test_variadicFzCS_3CatT_ // CHECK: [[TAKE_FN:%.*]] = function_ref @_TF6errors14take_many_catsFztGSaCS_3Cat__T_ : $@convention(thin) (@owned Array<Cat>) -> @error ErrorType // CHECK: [[N:%.*]] = integer_literal $Builtin.Word, 4 // CHECK: [[T0:%.*]] = function_ref @_TFs27_allocateUninitializedArray // CHECK: [[T1:%.*]] = apply [[T0]]<Cat>([[N]]) // CHECK: [[ARRAY:%.*]] = tuple_extract [[T1]] : $(Array<Cat>, Builtin.RawPointer), 0 // CHECK: [[T2:%.*]] = tuple_extract [[T1]] : $(Array<Cat>, Builtin.RawPointer), 1 // CHECK: [[ELT0:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to $*Cat // Element 0. // CHECK: [[T0:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error ErrorType) // CHECK: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[NORM_0:bb[0-9]+]], error [[ERR_0:bb[0-9]+]] // CHECK: [[NORM_0]]([[CAT0:%.*]] : $Cat): // CHECK-NEXT: store [[CAT0]] to [[ELT0]] // Element 1. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 1 // CHECK-NEXT: [[ELT1:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: strong_retain %0 // CHECK-NEXT: store %0 to [[ELT1]] // Element 2. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 2 // CHECK-NEXT: [[ELT2:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error ErrorType) // CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[NORM_2:bb[0-9]+]], error [[ERR_2:bb[0-9]+]] // CHECK: [[NORM_2]]([[CAT2:%.*]] : $Cat): // CHECK-NEXT: store [[CAT2]] to [[ELT2]] // Element 3. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 3 // CHECK-NEXT: [[ELT3:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error ErrorType) // CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[NORM_3:bb[0-9]+]], error [[ERR_3:bb[0-9]+]] // CHECK: [[NORM_3]]([[CAT3:%.*]] : $Cat): // CHECK-NEXT: store [[CAT3]] to [[ELT3]] // Complete the call and return. // CHECK-NEXT: try_apply [[TAKE_FN]]([[ARRAY]]) : $@convention(thin) (@owned Array<Cat>) -> @error ErrorType, normal [[NORM_CALL:bb[0-9]+]], error [[ERR_CALL:bb[0-9]+]] // CHECK: [[NORM_CALL]]([[T0:%.*]] : $()): // CHECK-NEXT: strong_release %0 : $Cat // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return // Failure from element 0. // CHECK: [[ERR_0]]([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TFs29_deallocateUninitializedArray // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW:.*]]([[ERROR]] : $ErrorType) // Failure from element 2. // CHECK: [[ERR_2]]([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: destroy_addr [[ELT1]] // CHECK-NEXT: destroy_addr [[ELT0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TFs29_deallocateUninitializedArray // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $ErrorType) // Failure from element 3. // CHECK: [[ERR_3]]([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: destroy_addr [[ELT2]] // CHECK-NEXT: destroy_addr [[ELT1]] // CHECK-NEXT: destroy_addr [[ELT0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TFs29_deallocateUninitializedArray // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $ErrorType) // Failure from call. // CHECK: [[ERR_CALL]]([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $ErrorType) // Rethrow. // CHECK: [[RETHROW]]([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: strong_release %0 : $Cat // CHECK-NEXT: throw [[ERROR]] // rdar://20861374 // Clear out the self box before delegating. class BaseThrowingInit : HasThrowingInit { var subField: Int init(value: Int, subField: Int) throws { self.subField = subField try super.init(value: value) } } // CHECK: sil hidden @_TFC6errors16BaseThrowingInitc{{.*}} : $@convention(method) (Int, Int, @owned BaseThrowingInit) -> (@owned BaseThrowingInit, @error ErrorType) // CHECK: [[BOX:%.*]] = alloc_box $BaseThrowingInit // CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [derivedself] [[BOX]]#1 // Initialize subField. // CHECK: [[T0:%.*]] = load [[MARKED_BOX]] // CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[T0]] : $BaseThrowingInit, #BaseThrowingInit.subField // CHECK-NEXT: assign %1 to [[T1]] // Super delegation. // CHECK-NEXT: [[T0:%.*]] = load [[MARKED_BOX]] // CHECK-NEXT: [[T2:%.*]] = upcast [[T0]] : $BaseThrowingInit to $HasThrowingInit // CHECK-NEXT: function_ref // CHECK-NEXT: [[T3:%.*]] = function_ref @_TFC6errors15HasThrowingInitc // CHECK-NEXT: apply [[T3]](%0, [[T2]]) // Cleanups for writebacks. protocol Supportable { mutating func support() throws } protocol Buildable { typealias Structure : Supportable var firstStructure: Structure { get set } subscript(name: String) -> Structure { get set } } func supportFirstStructure<B: Buildable>(inout b: B) throws { try b.firstStructure.support() } // CHECK-LABEL: sil hidden @_TF6errors21supportFirstStructure{{.*}} : $@convention(thin) <B where B : Buildable, B.Structure : Supportable> (@inout B) -> @error ErrorType { // CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 : // CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure // CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]]#1 : $*B.Structure to $Builtin.RawPointer // CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.firstStructure!materializeForSet.1 : // CHECK: [[T1:%.*]] = apply [[MAT]]<B, B.Structure>([[BUFFER_CAST]], [[MATBUFFER]]#1, [[BASE:%.*#1]]) // CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0 // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to $*B.Structure // CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1 // CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B // CHECK: try_apply [[SUPPORT]]<B.Structure>([[T4]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $ErrorType): // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: throw [[ERROR]] func supportStructure<B: Buildable>(inout b: B, name: String) throws { try b[name].support() } // CHECK-LABEL: sil hidden @_TF6errors16supportStructure // CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 : // CHECK: retain_value [[INDEX:%1]] : $String // CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure // CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]]#1 : $*B.Structure to $Builtin.RawPointer // CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.subscript!materializeForSet.1 : // CHECK: [[T1:%.*]] = apply [[MAT]]<B, B.Structure>([[BUFFER_CAST]], [[MATBUFFER]]#1, [[INDEX]], [[BASE:%.*#1]]) // CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0 // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to $*B.Structure // CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1 // CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B // CHECK: try_apply [[SUPPORT]]<B.Structure>([[T4]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: release_value [[INDEX]] : $String // CHECK: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $ErrorType): // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: release_value [[INDEX]] : $String // CHECK: throw [[ERROR]] struct Pylon { var name: String mutating func support() throws {} } struct Bridge { var mainPylon : Pylon subscript(name: String) -> Pylon { get { return mainPylon } set {} } } func supportStructure(inout b: Bridge, name: String) throws { try b[name].support() } // CHECK: sil hidden @_TF6errors16supportStructureFzTRVS_6Bridge4nameSS_T_ : // CHECK: [[SUPPORT:%.*]] = function_ref @_TFV6errors5Pylon7support // CHECK: retain_value [[INDEX:%1]] : $String // CHECK-NEXT: retain_value [[INDEX]] : $String // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Pylon // CHECK-NEXT: [[BASE:%.*]] = load [[B:%2#1]] : $*Bridge // CHECK-NEXT: retain_value [[BASE]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[GETTER:%.*]] = function_ref @_TFV6errors6Bridgeg9subscriptFSSVS_5Pylon : // CHECK-NEXT: [[T0:%.*]] = apply [[GETTER]]([[INDEX]], [[BASE]]) // CHECK-NEXT: release_value [[BASE]] // CHECK-NEXT: store [[T0]] to [[TEMP]]#1 // CHECK-NEXT: try_apply [[SUPPORT]]([[TEMP]]#1) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK-NEXT: [[T0:%.*]] = load [[TEMP]]#1 // CHECK-NEXT: function_ref // CHECK-NEXT: [[SETTER:%.*]] = function_ref @_TFV6errors6Bridges9subscriptFSSVS_5Pylon : // CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX]], [[B]]) // CHECK-NEXT: dealloc_stack [[TEMP]]#0 // CHECK-NEXT: release_value [[INDEX]] : $String // CHECK-NEXT: copy_addr // CHECK-NEXT: strong_release // CHECK-NEXT: tuple () // CHECK-NEXT: return // We end up with ugly redundancy here because we don't want to // consume things during cleanup emission. It's questionable. // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: [[T0:%.*]] = load [[TEMP]]#1 // CHECK-NEXT: retain_value [[T0]] // CHECK-NEXT: retain_value [[INDEX]] : $String // CHECK-NEXT: function_ref // CHECK-NEXT: [[SETTER:%.*]] = function_ref @_TFV6errors6Bridges9subscriptFSSVS_5Pylon : // CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX]], [[B]]) // CHECK-NEXT: destroy_addr [[TEMP]]#1 // CHECK-NEXT: dealloc_stack [[TEMP]]#0 // CHECK-NEXT: release_value [[INDEX]] : $String // CHECK-NEXT: release_value [[INDEX]] : $String // CHECK-NEXT: copy_addr // CHECK-NEXT: strong_release // CHECK-NEXT: throw [[ERROR]] struct OwnedBridge { var owner : Builtin.UnknownObject subscript(name: String) -> Pylon { addressWithOwner { return (nil, owner) } mutableAddressWithOwner { return (nil, owner) } } } func supportStructure(inout b: OwnedBridge, name: String) throws { try b[name].support() } // CHECK: sil hidden @_TF6errors16supportStructureFzTRVS_11OwnedBridge4nameSS_T_ : // CHECK: [[SUPPORT:%.*]] = function_ref @_TFV6errors5Pylon7support // CHECK: retain_value [[INDEX:%1]] : $String // CHECK-NEXT: function_ref // CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @_TFV6errors11OwnedBridgeaO9subscriptFSSVS_5Pylon : // CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[INDEX]], [[BASE:%2#1]]) // CHECK-NEXT: [[T1:%.*]] = tuple_extract [[T0]] : {{.*}}, 0 // CHECK-NEXT: [[OWNER:%.*]] = tuple_extract [[T0]] : {{.*}}, 1 // CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]] // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]] // CHECK-NEXT: try_apply [[SUPPORT]]([[T5]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK-NEXT: strong_release [[OWNER]] : $Builtin.UnknownObject // CHECK-NEXT: release_value [[INDEX]] : $String // CHECK-NEXT: copy_addr // CHECK-NEXT: strong_release // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: strong_release [[OWNER]] : $Builtin.UnknownObject // CHECK-NEXT: release_value [[INDEX]] : $String // CHECK-NEXT: copy_addr // CHECK-NEXT: strong_release // CHECK-NEXT: throw [[ERROR]] struct PinnedBridge { var owner : Builtin.NativeObject subscript(name: String) -> Pylon { addressWithPinnedNativeOwner { return (nil, owner) } mutableAddressWithPinnedNativeOwner { return (nil, owner) } } } func supportStructure(inout b: PinnedBridge, name: String) throws { try b[name].support() } // CHECK: sil hidden @_TF6errors16supportStructureFzTRVS_12PinnedBridge4nameSS_T_ : // CHECK: [[SUPPORT:%.*]] = function_ref @_TFV6errors5Pylon7support // CHECK: retain_value [[INDEX:%1]] : $String // CHECK-NEXT: function_ref // CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @_TFV6errors12PinnedBridgeap9subscriptFSSVS_5Pylon : // CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[INDEX]], [[BASE:%2#1]]) // CHECK-NEXT: [[T1:%.*]] = tuple_extract [[T0]] : {{.*}}, 0 // CHECK-NEXT: [[OWNER:%.*]] = tuple_extract [[T0]] : {{.*}}, 1 // CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]] // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]] // CHECK-NEXT: try_apply [[SUPPORT]]([[T5]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK-NEXT: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: release_value [[INDEX]] : $String // CHECK-NEXT: copy_addr // CHECK-NEXT: strong_release // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $ErrorType): // CHECK-NEXT: retain_value [[OWNER]] // CHECK-NEXT: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: release_value [[OWNER]] // CHECK-NEXT: release_value [[INDEX]] : $String // CHECK-NEXT: copy_addr // CHECK-NEXT: strong_release // CHECK-NEXT: throw [[ERROR]] // ! peepholes its argument with getSemanticsProvidingExpr(). // Test that that doesn't look through try!. // rdar://21515402 func testForcePeephole(f: () throws -> Int?) -> Int { let x = (try! f())! return x } // CHECK-LABEL: sil hidden @_TF6errors15testOptionalTryFT_T_ // CHECK-NEXT: bb0: // CHECK: [[FN:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]] // CHECK: [[SUCCESS]]([[VALUE:%.+]] : $Cat) // CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<Cat>, #Optional.Some!enumelt.1, [[VALUE]] // CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<Cat>) // CHECK: [[DONE]]([[RESULT:%.+]] : $Optional<Cat>): // CHECK-NEXT: release_value [[RESULT]] : $Optional<Cat> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]({{%.+}} : $ErrorType): // CHECK-NEXT: [[NONE:%.+]] = enum $Optional<Cat>, #Optional.None!enumelt // CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<Cat>) // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $ErrorType): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $ErrorType) // CHECK: {{^}$}} func testOptionalTry() { _ = try? make_a_cat() } // CHECK-LABEL: sil hidden @_TF6errors18testOptionalTryVarFT_T_ // CHECK-NEXT: bb0: // CHECK-NEXT: [[BOX:%.+]] = alloc_box $Optional<Cat> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]]#1 : $*Optional<Cat>, #Optional.Some!enumelt.1 // CHECK: [[FN:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]] // CHECK: [[SUCCESS]]([[VALUE:%.+]] : $Cat) // CHECK-NEXT: store [[VALUE]] to [[BOX_DATA]] : $*Cat // CHECK-NEXT: inject_enum_addr [[BOX]]#1 : $*Optional<Cat>, #Optional.Some!enumelt.1 // CHECK-NEXT: br [[DONE:[^ ]+]] // CHECK: [[DONE]]: // CHECK-NEXT: strong_release [[BOX]]#0 : $@box Optional<Cat> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]({{%.+}} : $ErrorType): // CHECK-NEXT: inject_enum_addr [[BOX]]#1 : $*Optional<Cat>, #Optional.None!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $ErrorType): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $ErrorType) // CHECK: {{^}$}} func testOptionalTryVar() { var cat = try? make_a_cat() // expected-warning {{initialization of variable 'cat' was never used; consider replacing with assignment to '_' or removing it}} } // CHECK-LABEL: sil hidden @_TF6errors26testOptionalTryAddressOnly // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_stack $Optional<T> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]]#1 : $*Optional<T>, #Optional.Some!enumelt.1 // CHECK: [[FN:%.+]] = function_ref @_TF6errors11dont_return // CHECK-NEXT: [[ARG_BOX:%.+]] = alloc_stack $T // CHECK-NEXT: copy_addr %0 to [initialization] [[ARG_BOX]]#1 : $*T // CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], [[ARG_BOX]]#1) : $@convention(thin) <τ_0_0> (@out τ_0_0, @in τ_0_0) -> @error ErrorType, normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]] // CHECK: [[SUCCESS]]({{%.+}} : $()): // CHECK-NEXT: inject_enum_addr [[BOX]]#1 : $*Optional<T>, #Optional.Some!enumelt.1 // CHECK-NEXT: dealloc_stack [[ARG_BOX]]#0 : $*@local_storage T // CHECK-NEXT: br [[DONE:[^ ]+]] // CHECK: [[DONE]]: // CHECK-NEXT: destroy_addr [[BOX]]#1 : $*Optional<T> // CHECK-NEXT: dealloc_stack [[BOX]]#0 : $*@local_storage Optional<T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]({{%.+}} : $ErrorType): // CHECK-NEXT: inject_enum_addr [[BOX]]#1 : $*Optional<T>, #Optional.None!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $ErrorType): // CHECK-NEXT: dealloc_stack [[ARG_BOX]]#0 : $*@local_storage T // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $ErrorType) // CHECK: {{^}$}} func testOptionalTryAddressOnly<T>(obj: T) { _ = try? dont_return(obj) } // CHECK-LABEL: sil hidden @_TF6errors29testOptionalTryAddressOnlyVar // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_box $Optional<T> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]]#1 : $*Optional<T>, #Optional.Some!enumelt.1 // CHECK: [[FN:%.+]] = function_ref @_TF6errors11dont_return // CHECK-NEXT: [[ARG_BOX:%.+]] = alloc_stack $T // CHECK-NEXT: copy_addr %0 to [initialization] [[ARG_BOX]]#1 : $*T // CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], [[ARG_BOX]]#1) : $@convention(thin) <τ_0_0> (@out τ_0_0, @in τ_0_0) -> @error ErrorType, normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]] // CHECK: [[SUCCESS]]({{%.+}} : $()): // CHECK-NEXT: inject_enum_addr [[BOX]]#1 : $*Optional<T>, #Optional.Some!enumelt.1 // CHECK-NEXT: dealloc_stack [[ARG_BOX]]#0 : $*@local_storage T // CHECK-NEXT: br [[DONE:[^ ]+]] // CHECK: [[DONE]]: // CHECK-NEXT: strong_release [[BOX]]#0 : $@box Optional<T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]({{%.+}} : $ErrorType): // CHECK-NEXT: inject_enum_addr [[BOX]]#1 : $*Optional<T>, #Optional.None!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $ErrorType): // CHECK-NEXT: dealloc_stack [[ARG_BOX]]#0 : $*@local_storage T // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $ErrorType) // CHECK: {{^}$}} func testOptionalTryAddressOnlyVar<T>(obj: T) { var copy = try? dont_return(obj) // expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}} } // CHECK-LABEL: sil hidden @_TF6errors23testOptionalTryMultipleFT_T_ // CHECK: bb0: // CHECK: [[FN_1:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]] // CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : $Cat) // CHECK: [[FN_2:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error ErrorType), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]] // CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : $Cat) // CHECK-NEXT: [[TUPLE:%.+]] = tuple ([[VALUE_1]] : $Cat, [[VALUE_2]] : $Cat) // CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.Some!enumelt.1, [[TUPLE]] // CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<(Cat, Cat)>) // CHECK: [[DONE]]([[RESULT:%.+]] : $Optional<(Cat, Cat)>): // CHECK-NEXT: release_value [[RESULT]] : $Optional<(Cat, Cat)> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]({{%.+}} : $ErrorType): // CHECK-NEXT: [[NONE:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.None!enumelt // CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<(Cat, Cat)>) // CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : $ErrorType): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $ErrorType) // CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : $ErrorType): // CHECK-NEXT: strong_release [[VALUE_1]] : $Cat // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $ErrorType) // CHECK: {{^}$}} func testOptionalTryMultiple() { _ = try? (make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden @_TF6errors25testOptionalTryNeverFailsFT_T_ // CHECK: bb0: // CHECK-NEXT: [[VALUE:%.+]] = tuple () // CHECK-NEXT: = enum $Optional<()>, #Optional.Some!enumelt.1, [[VALUE]] // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: {{^}$}} func testOptionalTryNeverFails() { _ = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}} } // CHECK-LABEL: sil hidden @_TF6errors28testOptionalTryNeverFailsVarFT_T_ // CHECK: bb0: // CHECK-NEXT: [[BOX:%.+]] = alloc_box $Optional<()> // CHECK-NEXT: = init_enum_data_addr [[BOX]]#1 : $*Optional<()>, #Optional.Some!enumelt.1 // CHECK-NEXT: inject_enum_addr [[BOX]]#1 : $*Optional<()>, #Optional.Some!enumelt.1 // CHECK-NEXT: strong_release [[BOX]]#0 : $@box Optional<()> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK-NEXT: {{^}$}} func testOptionalTryNeverFailsVar() { var unit: ()? = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{initialization of variable 'unit' was never used; consider replacing with assignment to '_' or removing it}} } // CHECK-LABEL: sil hidden @_TF6errors36testOptionalTryNeverFailsAddressOnly // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_stack $Optional<T> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]]#1 : $*Optional<T>, #Optional.Some!enumelt.1 // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T // CHECK-NEXT: inject_enum_addr [[BOX]]#1 : $*Optional<T>, #Optional.Some!enumelt.1 // CHECK-NEXT: destroy_addr [[BOX]]#1 : $*Optional<T> // CHECK-NEXT: dealloc_stack [[BOX]]#0 : $*@local_storage Optional<T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK-NEXT: {{^}$}} func testOptionalTryNeverFailsAddressOnly<T>(obj: T) { _ = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}} } // CHECK-LABEL: sil hidden @_TF6errors39testOptionalTryNeverFailsAddressOnlyVar // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_box $Optional<T> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]]#1 : $*Optional<T>, #Optional.Some!enumelt.1 // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T // CHECK-NEXT: inject_enum_addr [[BOX]]#1 : $*Optional<T>, #Optional.Some!enumelt.1 // CHECK-NEXT: strong_release [[BOX]]#0 : $@box Optional<T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK-NEXT: {{^}$}} func testOptionalTryNeverFailsAddressOnlyVar<T>(obj: T) { var copy = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}} }
apache-2.0
97aa917acaf09bafbd473eb0f89e52d3
46.598163
238
0.606566
3.198179
false
false
false
false
mightydeveloper/swift
validation-test/compiler_crashers_fixed/0097-swift-clangmoduleunit-getimportedmodules.swift
13
2120
// 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 import Foundation class gfe<u>: hg { ji nm: u ba(nm: u) { wv.nm = nm t.ba() } } func ts<u : on>(ml: u) { } ts(v w on) ({}) lk fed<xw : ihg> { ji ml: xw } func ay<xw>() -> [fed<xw>] { kj [] } protocol ay { class func fed() } class ml: ay { class func fed() { } } (ml() w ay).ay.fed() protocol ml { class func sr() } lk fed { ji xw: ml.ut func sr() { xw.sr() } } ji ts = cb ji dcb: o -> o = { kj $dc } edc fed: o = { (ml: o, ts: o -> o) -> o yx kj ts(ml) }(ts, dcb) edc cb: o = { ml, ts yx kj ts(ml) }(ts, dcb) ts sr) func ts<fed>() -> (fed, fed -> fed) -> fed { xw ml xw.v = { } { fed) { sr } } protocol ts { class func v() } class xw: ts{ class func v {} protocol ay { } protocol ml : ay { } protocol fed : ay { } protocol xw { r ts = ay } lk sr : xw { r ts = ml } func v<ml : ml, wv : xw qp wv.ts == ml> (ih: wv) { } func v<ml : xw qp ml.ts == fed> (ih: ml) { } v(sr()) func fed<xw { enum fed { func sr ji _ = sr } } class fed { func ml((x, fed))(ay: (x, ed)) { ml(ay) } } func ay(ml: x, rq: x) -> (((x, x) -> x) -> x) { kj { (edc: (x, x) -> x) -> x yx kj edc(ml, rq) } } func ml(p: (((x, x) -> x) -> x)) -> x { kj p({ (ih: x, kj:x) -> x yx kj ih }) } ml(ay(cb, ay(s, rq))) protocol xw { r B func ml(B) } lk fe<po> : xw { func ml(ml: fe.ut) { } } class xw<u : xw> { } protocol xw { } lk B : xw { } lk sr<gf, ml: xw qp gf.sr == ml> { } protocol xw { r ml } lk B<u : xw> { edc sr: u edc v: u.ml } protocol sr { r vu func fed<u qp u.ml == vu>(ts: B<u>) } lk gf : sr { r vu = o func fed<u qp u.ml == vu>(ts: B<u>) { } } class ay<ts : ml, fed : ml qp ts.xw == fed> { } protocol ml { r xw r sr } lk fed<sr : ml> : ml { hgf r ts = xw } class ml<sr : fed, v
apache-2.0
a86297ca8570675530bb17e132bf63fb
13.421769
87
0.464623
2.392777
false
false
false
false
AquaGeek/DataStructures
DataStructuresTests/StackTests.swift
1
1514
// // StackTests.swift // DataStructuresTests // // Created by Tyler Stromberg on 4/26/15. // Copyright (c) 2015 Tyler Stromberg. All rights reserved. // import Foundation import XCTest import DataStructures class StackTests: XCTestCase { func testIsEmpty() { var stack = Stack<Int>() XCTAssertTrue(stack.isEmpty, "Stack should be empty when initialized") } func testPush() { var stack = Stack<Int>() XCTAssertEqual(stack.count, 0, "Stack should be empty") stack.push(1) XCTAssertEqual(stack.count, 1, "Stack should have 1 item") } func testPop() { var stack = Stack<Int>() stack.push(1) XCTAssertEqual(stack.count, 1, "Stack should have 1 item") var top = stack.pop() XCTAssertEqual(top!, 1, "Wrong value returned") XCTAssertEqual(stack.count, 0, "Stack should now be empty") } func testPopWhenEmpty() { var stack = Stack<Int>() XCTAssertEqual(stack.count, 0, "Stack should be empty") XCTAssertNil(stack.pop()) } func testLIFO() { var stack = Stack<Int>() stack.push(1) stack.push(2) stack.push(3) XCTAssertEqual(stack.count, 3, "Stack should have 3 items") XCTAssertEqual(stack.pop()!, 3, "Wrong value returned") XCTAssertEqual(stack.pop()!, 2, "Wrong value returned") XCTAssertEqual(stack.pop()!, 1, "Wrong value returned") } }
mit
5fad9bf2d16f75726eaebe8017954005
26.035714
78
0.595112
4.193906
false
true
false
false
onevcat/RandomColorSwift
RandomColor/RandomColor.swift
1
8072
// // RandomColor.swift // RandomColorSwift // // Copyright (c) 2020 Wei Wang (http://onevcat.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. #if canImport(UIKit) import UIKit public typealias Color = UIColor #else import Cocoa public typealias Color = NSColor #endif private var colorDictionary: [Hue: ColorDefinition] = [ .monochrome: ColorDefinition(hueRange: nil, lowerBounds: [(0,0), (100,0)]), .red: ColorDefinition(hueRange: (-26,18), lowerBounds: [(20,100), (30,92), (40,89), (50,85), (60,78), (70,70), (80,60), (90,55), (100,50)]), .orange: ColorDefinition(hueRange: (19,46), lowerBounds: [(20,100), (30,93), (40,88), (50,86), (60,85), (70,70), (100,70)]), .yellow: ColorDefinition(hueRange: (47,62), lowerBounds: [(25,100), (40,94), (50,89), (60,86), (70,84), (80,82), (90,80), (100,75)]), .green: ColorDefinition(hueRange: (63,178), lowerBounds: [(30,100), (40,90), (50,85), (60,81), (70,74), (80,64), (90,50), (100,40)]), .blue: ColorDefinition(hueRange: (179,257), lowerBounds: [(20,100), (30,86), (40,80), (50,74), (60,60), (70,52), (80,44), (90,39), (100,35)]), .purple: ColorDefinition(hueRange: (258, 282), lowerBounds: [(20,100), (30,87), (40,79), (50,70), (60,65), (70,59), (80,52), (90,45), (100,42)]), .pink: ColorDefinition(hueRange: (283, 334), lowerBounds: [(20,100), (30,90), (40,86), (60,84), (80,80), (90,75), (100,73)]) ] extension Hue { var range: Range { switch self { case .value(let value): return (value, value) case .random: return (0, 360) default: if let colorDefinition = colorDictionary[self] { return colorDefinition.hueRange ?? (0, 360) } else { assert(false, "Unrecgonized Hue enum: \(self).") return (0, 360) } } } } /** Generate a single random color with some conditions. - parameter hue: Hue of target color. It will be the main property of the generated color. Default is .Random. - parameter luminosity: Luminosity of target color. It will decide the brightness of generated color. Default is .Random. - returns: A random color following input conditions. It will be a `UIColor` object for iOS target, and an `NSColor` object for OSX target. */ public func randomColor(hue: Hue = .random, luminosity: Luminosity = .random) -> Color { func random(in range: Range) -> Int { assert(range.max >= range.min, "Max in range should be greater than min") return Int(arc4random_uniform(UInt32(range.max - range.min))) + range.min } func getColorDefinition(hueValue: Int) -> ColorDefinition { var hueValue = hueValue if hueValue >= 334 && hueValue <= 360 { hueValue -= 360 } let color = colorDictionary.values.filter({ (definition: ColorDefinition) -> Bool in if let hueRange = definition.hueRange { return hueValue >= hueRange.min && hueValue <= hueRange.max } else { return false } }) assert(color.count == 1, "There should one and only one color satisfied the filter") return color.first! } func pickHue(_ hue: Hue) -> Int { var hueValue = random(in: hue.range) // Instead of storing red as two seperate ranges, // we group them, using negative numbers if hueValue < 0 { hueValue = hueValue + 360 } return hueValue } func pickSaturation(color: ColorDefinition, hue: Hue, luminosity: Luminosity) -> Int { var color = color if luminosity == .random { return random(in: (0, 100)) } if hue == .monochrome { return 0 } let saturationRange = color.saturationRange var sMin = saturationRange.min var sMax = saturationRange.max switch luminosity { case .bright: sMin = 55 case .dark: sMin = sMax - 10 case .light: sMax = 55 default: () } return random(in: (sMin, sMax)) } func pickBrightness(color: ColorDefinition, saturationValue: Int, luminosity: Luminosity) -> Int { var color = color func getMinimumBrightness(saturationValue: Int) -> Int { let lowerBounds = color.lowerBounds; for i in 0 ..< lowerBounds.count - 1 { let s1 = Float(lowerBounds[i].0) let v1 = Float(lowerBounds[i].1) let s2 = Float(lowerBounds[i+1].0) let v2 = Float(lowerBounds[i+1].1) if Float(saturationValue) >= s1 && Float(saturationValue) <= s2 { let m = (v2 - v1) / (s2 - s1) let b = v1 - m * s1 return lroundf(m * Float(saturationValue) + b) } } return 0 } var bMin = getMinimumBrightness(saturationValue: saturationValue) var bMax = 100 switch luminosity { case .dark: bMax = bMin + 20 case .light: bMin = (bMax + bMin) / 2 case .random: bMin = 0 bMax = 100 default: () } return random(in: (bMin, bMax)) } let hueValue = pickHue(hue) let color = getColorDefinition(hueValue: hueValue) let saturationValue = pickSaturation(color: color, hue: hue, luminosity: luminosity) let brightnessValue = pickBrightness(color: color, saturationValue: saturationValue, luminosity: luminosity) #if canImport(UIKit) return Color(hue: CGFloat(hueValue) / 360.0, saturation: CGFloat(saturationValue) / 100.0, brightness: CGFloat(brightnessValue) / 100.0, alpha: 1.0) #else return Color(deviceHue: CGFloat(hueValue) / 360.0, saturation: CGFloat(saturationValue) / 100.0, brightness: CGFloat(brightnessValue) / 100.0, alpha: 1.0) #endif } /** Generate a set of random colors with some conditions. - parameter count: The count of how many colors will be generated. - parameter hue: Hue of target color. It will be the main property of the generated color. Default is .Random. - parameter luminosity: Luminosity of target color. It will decide the brightness of generated color. Default is .Random. - returns: An array of random colors following input conditions. The elements will be `UIColor` objects for iOS target, and `NSColor` objects for OSX target. */ public func randomColors(count: Int, hue: Hue = .random, luminosity: Luminosity = .random) -> [Color] { var colors: [Color] = [] while (colors.count < count) { colors.append(randomColor(hue: hue, luminosity: luminosity)) } return colors }
mit
67973903dc9a48486b1cfce7b235e30f
37.62201
157
0.597498
3.901402
false
false
false
false
austinzheng/swift
test/Prototypes/IntroSort.swift
35
13103
//===--- IntroSort.swift --------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // RUN: %empty-directory(%t) // RUN: %target-build-swift -g -Onone -DUSE_STDLIBUNITTEST %s -o %t/a.out // RUN: %target-codesign %t/a.out // RUN: %target-run %t/a.out // REQUIRES: executable_test // Note: This introsort was the standard library's sort algorithm until Swift 5. import Swift import StdlibUnittest extension MutableCollection { /// Sorts the elements at `elements[a]`, `elements[b]`, and `elements[c]`. /// Stable. /// /// The indices passed as `a`, `b`, and `c` do not need to be consecutive, but /// must be in strict increasing order. /// /// - Precondition: `a < b && b < c` /// - Postcondition: `self[a] <= self[b] && self[b] <= self[c]` @inlinable public // @testable mutating func _sort3( _ a: Index, _ b: Index, _ c: Index, by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows { // There are thirteen possible permutations for the original ordering of // the elements at indices `a`, `b`, and `c`. The comments in the code below // show the relative ordering of the three elements using a three-digit // number as shorthand for the position and comparative relationship of // each element. For example, "312" indicates that the element at `a` is the // largest of the three, the element at `b` is the smallest, and the element // at `c` is the median. This hypothetical input array has a 312 ordering for // `a`, `b`, and `c`: // // [ 7, 4, 3, 9, 2, 0, 3, 7, 6, 5 ] // ^ ^ ^ // a b c // // - If each of the three elements is distinct, they could be ordered as any // of the permutations of 1, 2, and 3: 123, 132, 213, 231, 312, or 321. // - If two elements are equivalent and one is distinct, they could be // ordered as any permutation of 1, 1, and 2 or 1, 2, and 2: 112, 121, 211, // 122, 212, or 221. // - If all three elements are equivalent, they are already in order: 111. switch try (areInIncreasingOrder(self[b], self[a]), areInIncreasingOrder(self[c], self[b])) { case (false, false): // 0 swaps: 123, 112, 122, 111 break case (true, true): // 1 swap: 321 // swap(a, c): 312->123 swapAt(a, c) case (true, false): // 1 swap: 213, 212 --- 2 swaps: 312, 211 // swap(a, b): 213->123, 212->122, 312->132, 211->121 swapAt(a, b) if try areInIncreasingOrder(self[c], self[b]) { // 132 (started as 312), 121 (started as 211) // swap(b, c): 132->123, 121->112 swapAt(b, c) } case (false, true): // 1 swap: 132, 121 --- 2 swaps: 231, 221 // swap(b, c): 132->123, 121->112, 231->213, 221->212 swapAt(b, c) if try areInIncreasingOrder(self[b], self[a]) { // 213 (started as 231), 212 (started as 221) // swap(a, b): 213->123, 212->122 swapAt(a, b) } } } } extension MutableCollection where Self: RandomAccessCollection { /// Reorders the collection and returns an index `p` such that every element /// in `range.lowerBound..<p` is less than every element in /// `p..<range.upperBound`. /// /// - Precondition: The count of `range` must be >= 3 i.e. /// `distance(from: range.lowerBound, to: range.upperBound) >= 3` @inlinable internal mutating func _partition( within range: Range<Index>, by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> Index { var lo = range.lowerBound var hi = index(before: range.upperBound) // Sort the first, middle, and last elements, then use the middle value // as the pivot for the partition. let half = distance(from: lo, to: hi) / 2 let mid = index(lo, offsetBy: half) try _sort3(lo, mid, hi, by: areInIncreasingOrder) // FIXME: Stashing the pivot element instead of using the index won't work // for move-only types. let pivot = self[mid] // Loop invariants: // * lo < hi // * self[i] < pivot, for i in range.lowerBound..<lo // * pivot <= self[i] for i in hi..<range.upperBound Loop: while true { FindLo: do { formIndex(after: &lo) while lo != hi { if try !areInIncreasingOrder(self[lo], pivot) { break FindLo } formIndex(after: &lo) } break Loop } FindHi: do { formIndex(before: &hi) while hi != lo { if try areInIncreasingOrder(self[hi], pivot) { break FindHi } formIndex(before: &hi) } break Loop } swapAt(lo, hi) } return lo } @inlinable public // @testable mutating func _introSort( within range: Range<Index>, by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows { let n = distance(from: range.lowerBound, to: range.upperBound) guard n > 1 else { return } // Set max recursion depth to 2*floor(log(N)), as suggested in the introsort // paper: http://www.cs.rpi.edu/~musser/gp/introsort.ps let depthLimit = 2 * n._binaryLogarithm() try _introSortImpl( within: range, by: areInIncreasingOrder, depthLimit: depthLimit) } @inlinable internal mutating func _introSortImpl( within range: Range<Index>, by areInIncreasingOrder: (Element, Element) throws -> Bool, depthLimit: Int ) rethrows { // Insertion sort is better at handling smaller regions. if distance(from: range.lowerBound, to: range.upperBound) < 20 { try _insertionSort(within: range, by: areInIncreasingOrder) } else if depthLimit == 0 { try _heapSort(within: range, by: areInIncreasingOrder) } else { // Partition and sort. // We don't check the depthLimit variable for underflow because this // variable is always greater than zero (see check above). let partIdx = try _partition(within: range, by: areInIncreasingOrder) try _introSortImpl( within: range.lowerBound..<partIdx, by: areInIncreasingOrder, depthLimit: depthLimit &- 1) try _introSortImpl( within: partIdx..<range.upperBound, by: areInIncreasingOrder, depthLimit: depthLimit &- 1) } } @inlinable internal mutating func _siftDown( _ idx: Index, within range: Range<Index>, by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows { var idx = idx var countToIndex = distance(from: range.lowerBound, to: idx) var countFromIndex = distance(from: idx, to: range.upperBound) // Check if left child is within bounds. If not, stop iterating, because // there are no children of the given node in the heap. while countToIndex + 1 < countFromIndex { let left = index(idx, offsetBy: countToIndex + 1) var largest = idx if try areInIncreasingOrder(self[largest], self[left]) { largest = left } // Check if right child is also within bounds before trying to examine it. if countToIndex + 2 < countFromIndex { let right = index(after: left) if try areInIncreasingOrder(self[largest], self[right]) { largest = right } } // If a child is bigger than the current node, swap them and continue // sifting down. if largest != idx { swapAt(idx, largest) idx = largest countToIndex = distance(from: range.lowerBound, to: idx) countFromIndex = distance(from: idx, to: range.upperBound) } else { break } } } @inlinable internal mutating func _heapify( within range: Range<Index>, by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows { // Here we build a heap starting from the lowest nodes and moving to the // root. On every step we sift down the current node to obey the max-heap // property: // parent >= max(leftChild, rightChild) // // We skip the rightmost half of the array, because these nodes don't have // any children. let root = range.lowerBound let half = distance(from: range.lowerBound, to: range.upperBound) / 2 var node = index(root, offsetBy: half) while node != root { formIndex(before: &node) try _siftDown(node, within: range, by: areInIncreasingOrder) } } @inlinable public // @testable mutating func _heapSort( within range: Range<Index>, by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows { var hi = range.upperBound let lo = range.lowerBound try _heapify(within: range, by: areInIncreasingOrder) formIndex(before: &hi) while hi != lo { swapAt(lo, hi) try _siftDown(lo, within: lo..<hi, by: areInIncreasingOrder) formIndex(before: &hi) } } } //===--- Tests ------------------------------------------------------------===// //===----------------------------------------------------------------------===// var suite = TestSuite("IntroSort") // The routine is based on http://www.cs.dartmouth.edu/~doug/mdmspe.pdf func makeQSortKiller(_ len: Int) -> [Int] { var candidate: Int = 0 var keys = [Int: Int]() func Compare(_ x: Int, y : Int) -> Bool { if keys[x] == nil && keys[y] == nil { if (x == candidate) { keys[x] = keys.count } else { keys[y] = keys.count } } if keys[x] == nil { candidate = x return true } if keys[y] == nil { candidate = y return false } return keys[x]! > keys[y]! } var ary = [Int](repeating: 0, count: len) var ret = [Int](repeating: 0, count: len) for i in 0..<len { ary[i] = i } ary = ary.sorted(by: Compare) for i in 0..<len { ret[ary[i]] = i } return ret } suite.test("sorted/complexity") { var ary: [Int] = [] // Check performance of sorting an array of repeating values. var comparisons_100 = 0 ary = Array(repeating: 0, count: 100) ary._introSort(within: 0..<ary.count) { comparisons_100 += 1; return $0 < $1 } var comparisons_1000 = 0 ary = Array(repeating: 0, count: 1000) ary._introSort(within: 0..<ary.count) { comparisons_1000 += 1; return $0 < $1 } expectTrue(comparisons_1000/comparisons_100 < 20) // Try to construct 'bad' case for quicksort, on which the algorithm // goes quadratic. comparisons_100 = 0 ary = makeQSortKiller(100) ary._introSort(within: 0..<ary.count) { comparisons_100 += 1; return $0 < $1 } comparisons_1000 = 0 ary = makeQSortKiller(1000) ary._introSort(within: 0..<ary.count) { comparisons_1000 += 1; return $0 < $1 } expectTrue(comparisons_1000/comparisons_100 < 20) } suite.test("sort3/simple") .forEach(in: [ [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1] ]) { var input = $0 input._sort3(0, 1, 2, by: <) expectEqual([1, 2, 3], input) } func isSorted<T>(_ a: [T], by areInIncreasingOrder: (T, T) -> Bool) -> Bool { return !zip(a.dropFirst(), a).contains(where: areInIncreasingOrder) } suite.test("sort3/stable") .forEach(in: [ [1, 1, 2], [1, 2, 1], [2, 1, 1], [1, 2, 2], [2, 1, 2], [2, 2, 1], [1, 1, 1] ]) { // decorate with offset, but sort by value var input = Array($0.enumerated()) input._sort3(0, 1, 2) { $0.element < $1.element } // offsets should still be ordered for equal values expectTrue(isSorted(input) { if $0.element == $1.element { return $0.offset < $1.offset } return $0.element < $1.element }) } suite.test("heapSort") { // Generates the next permutation of `num` as a binary integer, using long // arithmetics approach. // // - Precondition: All values in `num` are either 0 or 1. func addOne(to num: [Int]) -> [Int] { // `num` represents a binary integer. To add one, we toggle any bits until // we've set a clear bit. var num = num for i in num.indices { if num[i] == 1 { num[i] = 0 } else { num[i] = 1 break } } return num } // Test binary number size. let numberLength = 11 var binaryNumber = Array(repeating: 0, count: numberLength) // We are testing sort on all permutations off 0-1s of size `numberLength` // except the all 1's case (its equals to all 0's case). while !binaryNumber.allSatisfy({ $0 == 1 }) { var buffer = binaryNumber buffer._heapSort(within: buffer.startIndex..<buffer.endIndex, by: <) expectTrue(isSorted(buffer, by: <)) binaryNumber = addOne(to: binaryNumber) } } runAllTests()
apache-2.0
880ed97e71ad371124f9ffeb8d833a8f
32.005038
81
0.594215
3.744784
false
false
false
false
anisimovsergey/lumino-ios
Lumino/SettingsViewController.swift
1
1929
// // SettingsViewController.swift // Lumino // // Created by Sergey Anisimov on 07/05/2017. // Copyright © 2017 Sergey Anisimov. All rights reserved. // import Foundation import UIKit import CoreData import MulticastDelegateSwift class SettingsViewController: UIViewController, WebSocketConnectionDelegate { @IBOutlet var name: UITextField! @IBOutlet var save: UIBarButtonItem! var device: DeviceListItem! @IBAction func cancelEdit(sender: AnyObject) { if !self.device.client.isConnected { self.presentedViewController?.performSegue(withIdentifier: "unwindToDetails", sender: self) } else { dismiss(animated: true, completion: nil) } } @IBAction func save(sender: AnyObject) { let settings = Settings(isOn: self.device.isOn!, deviceName: name.text!) _ = device.client.updateSettings(settings) dismiss(animated: true, completion: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) name.text = self.device.name self.device.client.connectionDelegate += self if !self.device.client.isConnected { showDisconnected() } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.device.client.connectionDelegate -= self } func websocketDidConnect(client: WebSocketClient) { self.presentedViewController?.performSegue(withIdentifier: "unwindToSettings", sender: self) self.save.isEnabled = true } func websocketDidDisconnect(client: WebSocketClient) { showDisconnected() } @IBAction func unwindToSettings(_ segue:UIStoryboardSegue) { print("unwind to settings") } func showDisconnected() { self.performSegue(withIdentifier: "disconnected", sender:self) self.save.isEnabled = false } }
mit
3aee38a4c5992c5db91e813f4df9908e
28.212121
103
0.679979
4.83208
false
false
false
false
lerigos/music-service
iOS_9/Pods/SwiftyVK/Source/API/Notes.swift
2
2981
extension _VKAPI { ///Methods for working with notes. More - https://vk.com/dev/notes public struct Notes { ///Returns a list of notes created by a user. More - https://vk.com/dev/notes.get public static func get(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "notes.get", parameters: parameters) } ///Returns a note by its ID. More - https://vk.com/dev/notes.getById public static func getById(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "notes.getById", parameters: parameters) } ///Returns a list of a user's friends' notes. More - https://vk.com/dev/notes.getFriendsNotes public static func getFriendsNotes(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "notes.getFriendsNotes", parameters: parameters) } ///Creates a new note for the current user. More - https://vk.com/dev/notes.add public static func add(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "notes.add", parameters: parameters) } ///Edits a note of the current user. More - https://vk.com/dev/notes.edit public static func edit(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "notes.edit", parameters: parameters) } ///Deletes a note of the current user. More - https://vk.com/dev/notes.delete public static func delete(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "notes.delete", parameters: parameters) } ///Returns a list of comments on a note. More - https://vk.com/dev/notes.getComments public static func getComments(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "notes.getComments", parameters: parameters) } ///Adds a new comment on a note. More - https://vk.com/dev/notes.createComment public static func createComment(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "notes.createComment", parameters: parameters) } ///Edits a comment on a note. More - https://vk.com/dev/notes.editComment public static func editComment(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "notes.editComment", parameters: parameters) } ///Deletes a comment on a note. More - https://vk.com/dev/notes.deleteComment public static func deleteComment(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "notes.deleteComment", parameters: parameters) } ///Restores a deleted comment on a note. More - https://vk.com/dev/notes.restoreComment public static func restoreComment(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "notes.restoreComment", parameters: parameters) } } }
apache-2.0
dbd1f5434e54e7ba8dd039910e8fe3cf
35.353659
97
0.631332
4.169231
false
false
false
false
billdonner/sheetcheats9
sc9/ModalMenuViewController.swift
1
4485
// // ModalMenuViewController.swift // // Created by william donner on 9/25/15. // import UIKit // presents a bunch of choices as a transparent modal overlay controller var modalMenuViewController:ModalMenuViewController! //MARK:- a view embedding a stackview final class ModalStackView: UIView { var itemViews: [UIView] = [] // the items in the stackview var stackView: UIStackView! @objc func tapped(sender:UITapGestureRecognizer) { if let label = sender.view as? UILabel { let idx = label.tag - 1000 let item = menuitems[idx] //print("segue via \(item)") modalMenuViewController.performSegue(withIdentifier: item.segueid, sender: self) } } func refresh() { //// adjust color of background here in the case of settings changes var idx = 0 for itemv in itemViews { if performanceMode { itemv.backgroundColor = Col.r(.modalmenuBackground) } else { itemv.backgroundColor = menuitems[idx].color } idx += 1 } stackView.setNeedsLayout() } private func iav( ) { self.backgroundColor = Col.r(.modalmenuBackground) // dont forget self let makeView = { (color: UIColor,text:String,idx:Int) -> UIView in let lab = UILabel(frame: .zero) lab.translatesAutoresizingMaskIntoConstraints = false lab.numberOfLines = 0 lab.backgroundColor = color lab.text = text lab.font = UIFont.systemFont(ofSize: 24) lab.textColor = .white lab.textAlignment = .center lab.isUserInteractionEnabled = true // important ! lab.tag = idx + 1000 let tgr = UITapGestureRecognizer(target: self, action: #selector(ModalStackView.tapped(sender:))) lab.addGestureRecognizer(tgr) return lab } for item in menuitems { let thisview = makeView(item.color,item.title,itemViews.count) itemViews.append(thisview) } stackView = UIStackView(arrangedSubviews:itemViews) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.distribution = .fillEqually stackView.axis = UILayoutConstraintAxis.vertical stackView.backgroundColor = Col.r(.modalmenuBackground) addSubview(stackView) stackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true stackView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true stackView.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true stackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -10).isActive = true // } required init(coder aDecoder: NSCoder) { super.init(coder:aDecoder)! iav() } } final class ModalMenuViewController: UIViewController,ModelData { deinit { self.cleanupFontSizeAware(self) } override var prefersStatusBarHidden: Bool { get { return true } } @IBOutlet weak var mystackView: ModalStackView! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) mystackView.refresh() } override func viewDidLoad() { modalMenuViewController = self // stash this for use in view super.viewDidLoad() self.setupFontSizeAware(self) self.view.backgroundColor = Col.r(.modalmenuBackground) self.mystackView.backgroundColor = Col.r(.modalmenuBackground) } override func viewDidLayoutSubviews() { // mystackView.stackView.axis = UILayoutConstraintAxis.vertical //traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.regular ? UILayoutConstraintAxis.horizontal : UILayoutConstraintAxis.vertical // print(traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.regular) } } extension ModalMenuViewController :SegueHelpers { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { self.prepForSegue(segue , sender: sender) } } extension ModalMenuViewController : FontSizeAware { func refreshFontSizeAware(_ vc:ModalMenuViewController) { vc.view.setNeedsDisplay() } }
apache-2.0
8993d5e245d74b194eb14778a5d92d0f
32.721805
143
0.639688
5.050676
false
false
false
false
lerigos/music-service
iOS_9/Pods/SwiftyVK/Source/API/User.swift
2
2135
extension _VKAPI { ///Methods for working with users. More - https://vk.com/dev/users public struct Users { ///Returns detailed information on users. More - https://vk.com/dev/users.get public static func get(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "users.get", parameters: parameters) } ///Returns a list of users matching the search criteria. More - https://vk.com/dev/users.search public static func search(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "users.search", parameters: parameters) } ///Returns information whether a user installed the application. More - https://vk.com/dev/users.isAppUser public static func isAppUser(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "users.isAppUser", parameters: parameters) } ///Returns a list of IDs of users and communities followed by the user. More - https://vk.com/dev/users.getSubscriptions public static func getSubscriptions(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "users.getSubscriptions", parameters: parameters) } ///Returns a list of IDs of followers of the user in question, sorted by date added, most recent first. More - https://vk.com/dev/users.getFollowers public static func getFollowers(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "users.getFollowers", parameters: parameters) } ///Reports (submits a complain about) a user. More - https://vk.com/dev/users.report public static func report(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "users.report", parameters: parameters) } ///Indexes user's current location and returns a list of users who are in the vicinity. More - https://vk.com/dev/users.getNearby public static func getNearby(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "users.getNearby", parameters: parameters) } } }
apache-2.0
504daa6595a3dde5e6fb2553211074d5
39.283019
152
0.654333
4.27
false
false
false
false
PJayRushton/stats
Stats/MainMiddleware.swift
1
1177
// // MainMiddleware.swift // Stats // // Created by Parker Rushton on 8/31/17. // Copyright © 2017 AppsByPJ. All rights reserved. // import UIKit struct MainMiddleware: Middleware { func process(event: Event, state: AppState) { switch event { case let event as ICloudUserLoaded: guard let id = event.id else { return } App.core.fire(command: GetCurrentUser(iCloudId: id)) case let event as Updated<Team>: if event.payload.id == state.teamState.currentTeamId { App.core.fire(event: Selected<Team>(event.payload)) } case let event as TeamObjectAdded<GameStats>: guard event.object.isSeason && event.object.gameId == state.seasonState.currentSeasonId else { return } App.core.fire(command: UpdateTrophies()) case let event as TeamObjectChanged<GameStats>: guard event.object.isSeason && event.object.gameId == state.seasonState.currentSeasonId else { return } App.core.fire(command: UpdateTrophies()) default: break } } }
mit
4b36e39728541d18034f32ee479c2a8c
30.783784
115
0.596939
4.404494
false
false
false
false
gouyz/GYZBaking
baking/Classes/Home/Controller/GYZReportVC.swift
1
4430
// // GYZReportVC.swift // baking // 举报商家 // Created by gouyz on 2017/4/27. // Copyright © 2017年 gouyz. All rights reserved. // import UIKit import MBProgressHUD class GYZReportVC: GYZBaseVC,UITextViewDelegate { var placeHolder = "请输入您的举报原因..." var seggestTxt: String = "" var shopId: String = "" override func viewDidLoad() { super.viewDidLoad() self.title = "举报商家" setupUI() } func setupUI(){ let noteView: UIView = UIView() noteView.backgroundColor = kWhiteColor view.addSubview(noteView) noteView.addSubview(noteTxtView) noteTxtView.delegate = self noteTxtView.text = placeHolder noteView.addSubview(desLab) desLab.text = "0/100" view.addSubview(sendBtn) noteView.snp.makeConstraints { (make) in make.left.right.equalTo(view) make.top.equalTo(kMargin) make.height.equalTo(150) } noteTxtView.snp.makeConstraints { (make) in make.left.equalTo(noteView).offset(kMargin) make.right.equalTo(noteView).offset(-kMargin) make.top.equalTo(noteView) make.bottom.equalTo(desLab.snp.top) } desLab.snp.makeConstraints { (make) in make.bottom.equalTo(noteView) make.left.right.equalTo(noteTxtView) make.height.equalTo(30) } sendBtn.snp.makeConstraints { (make) in make.left.equalTo(kStateHeight) make.right.equalTo(-kStateHeight) make.top.equalTo(noteView.snp.bottom).offset(30) make.height.equalTo(kBottomTabbarHeight) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } lazy var noteTxtView : UITextView = { let txtView = UITextView() txtView.textColor = kGaryFontColor txtView.font = k15Font return txtView }() lazy var desLab: UILabel = { let lab = UILabel() lab.font = k15Font lab.textColor = kGaryFontColor lab.textAlignment = .right return lab }() /// 举 报按钮 fileprivate lazy var sendBtn : UIButton = { let btn = UIButton.init(type: .custom) btn.backgroundColor = kBtnClickBGColor btn.setTitle("举 报", for: .normal) btn.setTitleColor(kWhiteColor, for: .normal) btn.titleLabel?.font = k15Font btn.addTarget(self, action: #selector(clickedSendBtn(btn:)), for: .touchUpInside) btn.cornerRadius = kCornerRadius return btn }() /// 举 报 func clickedSendBtn(btn: UIButton){ requestSubmit() } /// 提交举报 func requestSubmit(){ weak var weakSelf = self createHUD(message: "加载中...") GYZNetWork.requestNetwork("Member/addReport", parameters: ["user_id":userDefaults.string(forKey: "userId") ?? "","content": seggestTxt,"member_id": shopId], success: { (response) in weakSelf?.hud?.hide(animated: true) // GYZLog(response) if response["status"].intValue == kQuestSuccessTag{//请求成功 } MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue) }, failture: { (error) in weakSelf?.hud?.hide(animated: true) GYZLog(error) }) } ///MARK UITextViewDelegate func textViewDidBeginEditing(_ textView: UITextView) { let text = textView.text if text == placeHolder { textView.text = "" } } func textViewDidChange(_ textView: UITextView) { let text : String = textView.text if text.isEmpty { textView.text = placeHolder }else{ seggestTxt = text } } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if range.length == 0 && range.location > 99 {//最多输入100位 return false } desLab.text = "\(range.location)/100" return true } }
mit
94f9a0281b3fafa1b0d925cef59fba57
27.585526
190
0.567089
4.479381
false
false
false
false
merlos/iOS-Open-GPX-Tracker
OpenGpxTracker/DefaultNameSetupViewController.swift
1
15655
// // DefaultNameSetupViewController.swift // OpenGpxTracker // // Created by Vincent on 3/3/20. // import UIKit /// It is an editor for the default file name. class DefaultNameSetupViewController: UITableViewController, UITextFieldDelegate { /// text field for user to key in file name format. var cellTextField = UITextField() /// sample text to depict possible date time format. var cellSampleLabel = UILabel() /// proccessed date format text, such as 'TIME' HH:MM:ss, instead of TIME {HH}:{MM}:{ss} /// /// also used for final date formatting for use in default name callup when saving. var processedDateFormat = String() /// A value denoting the validity of the processed date format. var dateFormatIsInvalid = false /// let defaultDateFormat = DefaultDateFormat() /// to use UTC time instead of local. var useUTC = false /// to use en_US_POSIX instead of usual locale. (Force English name scheme) var useEN = false /// Global Preferences var preferences: Preferences = Preferences.shared /// Built in presets. Should be made addable customs next time. let presets = [("Defaults", "dd-MMM-yyyy-HHmm", "{dd}-{MMM}-{yyyy}-{HH}{mm}"), ("ISO8601 (UTC)", "yyyy-MM-dd'T'HH:mm:ss'Z'", "{yyyy}-{MM}-{dd}T{HH}:{mm}:{ss}Z"), ("ISO8601 (UTC offset)", "yyyy-MM-dd'T'HH:mm:ssZ", "{yyyy}-{MM}-{dd}T{HH}:{mm}:{ss}{Z}"), ("Day, Date at time (12 hr)", "EEEE, MMM d, yyyy 'at' h:mm a", "{EEEE}, {MMM} {d}, {yyyy} at {h}:{mm} {a}"), ("Day, Date at time (24 hr)", "EEEE, MMM d, yyyy 'at' HH:mm", "{EEEE}, {MMM} {d}, {yyyy} at {HH}:{mm}")] /// Sections of table view private enum Sections: Int, CaseIterable { case input, settings, presets } override func viewDidLoad() { super.viewDidLoad() useUTC = preferences.dateFormatUseUTC useEN = preferences.dateFormatUseEN addNotificationObservers() } func addNotificationObservers() { let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(dateButtonTapped(_:)), name: .dateFieldTapped, object: nil) } // MARK: Text Field Related @objc func dateButtonTapped(_ sender: Notification) { if cellTextField.text != nil { guard let notificationValues = sender.userInfo else { return } // swiftlint:disable force_cast let patternDict = notificationValues as! [String: String] guard let pattern = patternDict["sender"] else { return } cellTextField.insertText("{\(pattern)}") } } /// Legacy date selection toolbar for iOS 8 use, as it lacks new API for the new toolbar layout. func createSimpleDateSelectionBar() -> UIToolbar { let bar = UIToolbar() let bracket = UIBarButtonItem(title: "{ ... }", style: .plain, target: self, action: #selector(buttonTapped(_:for:))) bracket.tag = 6 let day = UIBarButtonItem(title: "Day", style: .plain, target: self, action: #selector(buttonTapped(_:for:))) day.tag = 0 let month = UIBarButtonItem(title: "Month", style: .plain, target: self, action: #selector(buttonTapped(_:for:))) month.tag = 1 let year = UIBarButtonItem(title: "Year", style: .plain, target: self, action: #selector(buttonTapped(_:for:))) year.tag = 2 let hour = UIBarButtonItem(title: "Hr", style: .plain, target: self, action: #selector(buttonTapped(_:for:))) hour.tag = 3 let min = UIBarButtonItem(title: "Min", style: .plain, target: self, action: #selector(buttonTapped(_:for:))) min.tag = 4 let sec = UIBarButtonItem(title: "Sec", style: .plain, target: self, action: #selector(buttonTapped(_:for:))) sec.tag = 5 bar.items = [bracket, day, month, year, hour, min, sec] bar.sizeToFit() return bar } /// Handles text insertion as per keyboard bar button pressed. @objc func buttonTapped(_ sender: UIBarButtonItem, for event: UIEvent) { if cellTextField.text != nil { switch sender.tag { case 0: cellTextField.insertText("{dd}") case 1: cellTextField.insertText("{MM}") case 2: cellTextField.insertText("{yyyy}") case 3: cellTextField.insertText("{HH}") case 4: cellTextField.insertText("{mm}") case 5: cellTextField.insertText("{ss}") case 6: cellTextField.insertText("{}") guard let currRange = cellTextField.selectedTextRange, let wantedRange = cellTextField.position(from: currRange.start, offset: -1) else { return } cellTextField.selectedTextRange = cellTextField.textRange(from: wantedRange, to: wantedRange) default: return } updateSampleTextField() } } /// Call when text field is currently editing, and an update to sample label is required. @objc func updateSampleTextField() { let processed = defaultDateFormat.getDateFormat(unprocessed: self.cellTextField.text!) processedDateFormat = processed.0 dateFormatIsInvalid = processed.1 //dateFormatter.dateFormat = processedDateFormat cellSampleLabel.text = defaultDateFormat.getDate(processedFormat: processedDateFormat, useUTC: useUTC, useENLocale: useEN) } // MARK: UITextField Delegate /// Enables keyboard 'done' action to resign text field func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } /// handling of textfield when editing commence. func textFieldDidBeginEditing(_ textField: UITextField) { //remove checkmark from selected date format preset, as textfield edited == not preset anymore let selectedIndexPath = IndexPath(row: preferences.dateFormatPreset, section: Sections.presets.rawValue) tableView.cellForRow(at: selectedIndexPath)?.accessoryType = .none useUTC = false // clear UTC value, unlock UTC cell, as format may now be custom. lockUTCCell(useUTC) } /// handling of textfield when editing is done. func textFieldDidEndEditing(_ textField: UITextField) { if cellTextField.text != preferences.dateFormatInput { saveDateFormat(processedDateFormat, input: cellTextField.text) // save if user input is custom / derivative of preset. } else { // to get back preset set, and its rules (such as UTC for ISO8601 preset) let selectedIndexPath = IndexPath(row: preferences.dateFormatPreset, section: Sections.presets.rawValue) tableView.cellForRow(at: selectedIndexPath)?.accessoryType = .checkmark if preferences.dateFormatPreset == 1 { useUTC = true lockUTCCell(useUTC) } } } /// allows clear button to operate. func textFieldShouldClear(_ textField: UITextField) -> Bool { return true } // MARK: Preference Setting /// Saves date format to Preferences/UserDefaults func saveDateFormat(_ dateFormat: String, input: String?, index: Int = -1) { guard let input = input else { return } print(dateFormat) if dateFormatIsInvalid || input.isEmpty || dateFormat.isEmpty { return } // ensures no invalid date format (revert) preferences.dateFormat = dateFormat preferences.dateFormatInput = input preferences.dateFormatPreset = index preferences.dateFormatUseUTC = useUTC } // MARK: Table View /// Locks UTC cell such that it cannot be unchecked, for preset that require it. func lockUTCCell(_ state: Bool) { let indexPath = IndexPath(row: 0, section: Sections.settings.rawValue) useUTC = state tableView.cellForRow(at: indexPath)?.accessoryType = state ? .checkmark : .none tableView.cellForRow(at: indexPath)?.isUserInteractionEnabled = !state tableView.cellForRow(at: indexPath)?.textLabel?.isEnabled = !state updateSampleTextField() } /// return number of sections based on `Sections` override func numberOfSections(in tableView: UITableView) -> Int { return Sections.allCases.count } /// implement title of each section override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case Sections.input.rawValue: return NSLocalizedString("DEFAULT_NAME_DATE_FORMAT", comment: "no comment") case Sections.settings.rawValue: return NSLocalizedString("DEFAULT_NAME_SETTINGS", comment: "no comment") case Sections.presets.rawValue: return NSLocalizedString("DEFAULT_NAME_PRESET", comment: "no comment") default: fatalError("Section out of range") } } /// implement footer for input section only override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { if section == Sections.input.rawValue { return NSLocalizedString("DEFAULT_NAME_INPUT_FOOTER", comment: "no comment") } else { return nil } } /// return number of rows in each section override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case Sections.input.rawValue: return 2 case Sections.settings.rawValue: if Locale.current.languageCode == "en" { return 1 // force locale to EN should only be shown if Locale is not EN. } else { return 2 } case Sections.presets.rawValue: return presets.count default: fatalError("Row out of range") } } /// setup each cell, according its requirements. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = UITableViewCell(style: .default, reuseIdentifier: "inputCell") if indexPath.section == Sections.input.rawValue { if indexPath.row == 0 { cellSampleLabel = UILabel(frame: CGRect(x: 87, y: 0, width: view.frame.width - 99, height: cell.frame.height)) cellSampleLabel.font = .boldSystemFont(ofSize: 17) cell.addSubview(cellSampleLabel) cellSampleLabel.text = "" updateSampleTextField() cellSampleLabel.adjustsFontSizeToFitWidth = true cell.textLabel!.text = NSLocalizedString("DEFAULT_NAME_SAMPLE_OUTPUT_TITLE", comment: "no comment") cell.textLabel?.font = .systemFont(ofSize: 17) } else if indexPath.row == 1 { cellTextField = UITextField(frame: CGRect(x: 22, y: 0, width: view.frame.width - 48, height: cell.frame.height)) cellTextField.text = preferences.dateFormatInput updateSampleTextField() cellTextField.clearButtonMode = .whileEditing cellTextField.delegate = self cellTextField.returnKeyType = .done if #available(iOS 9, *) { let dateFieldSelector = DateFieldTypeView(frame: CGRect(x: 0, y: 0, width: cellTextField.frame.width, height: 75)) cellTextField.inputAccessoryView = dateFieldSelector } else { cellTextField.inputAccessoryView = createSimpleDateSelectionBar() } cellTextField.addTarget(self, action: #selector(updateSampleTextField), for: UIControl.Event.editingChanged) cell.contentView.addSubview(cellTextField) } cell.selectionStyle = .none cellTextField.autocorrectionType = .no } else if indexPath.section == Sections.settings.rawValue { if indexPath.row == 0 { cell.textLabel!.text = NSLocalizedString("DEFAULT_NAME_USE_UTC", comment: "no comment")//"Use UTC?" cell.accessoryType = preferences.dateFormatUseUTC ? .checkmark : .none if preferences.dateFormatPreset == 1 { cell.isUserInteractionEnabled = !useUTC cell.textLabel?.isEnabled = !useUTC } } else if indexPath.row == 1 { cell.textLabel!.text = NSLocalizedString("DEFAULT_NAME_ENGLISH_LOCALE", comment: "no comment")//"Force English Locale?" cell.accessoryType = preferences.dateFormatUseEN ? .checkmark : .none } updateSampleTextField() } else if indexPath.section == Sections.presets.rawValue { cell = UITableViewCell(style: .subtitle, reuseIdentifier: "presetCell") cell.textLabel?.text = presets[indexPath.row].0 cell.detailTextLabel?.text = defaultDateFormat.getDate(processedFormat: presets[indexPath.row].1, useUTC: useUTC, useENLocale: useEN) if preferences.dateFormatPreset != -1 { // if not custom cell.accessoryType = preferences.dateFormatPreset == indexPath.row ? .checkmark : .none } } return cell } /// handling of cell selection. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == Sections.settings.rawValue { if indexPath.row == 0 { //remove checkmark from selected utc setting let newUseUTC = !preferences.dateFormatUseUTC preferences.dateFormatUseUTC = newUseUTC useUTC = newUseUTC tableView.cellForRow(at: indexPath)?.accessoryType = newUseUTC ? .checkmark : .none } else if indexPath.row == 1 { //remove checkmark from selected en locale setting let newUseEN = !preferences.dateFormatUseEN preferences.dateFormatUseEN = newUseEN useEN = newUseEN tableView.cellForRow(at: indexPath)?.accessoryType = newUseEN ? .checkmark : .none } updateSampleTextField() } if indexPath.section == Sections.presets.rawValue { //cellSampleLabel.text = "{\(presets[indexPath.row].1)}" cellTextField.text = presets[indexPath.row].2 //update cell UI //remove checkmark from selected date format preset let selectedIndexPath = IndexPath(row: preferences.dateFormatPreset, section: indexPath.section) tableView.cellForRow(at: selectedIndexPath)?.accessoryType = .none //add checkmark to new selected date format preset tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark preferences.dateFormatPreset = indexPath.row preferences.dateFormatInput = presets[indexPath.row].2 updateSampleTextField() preferences.dateFormat = processedDateFormat if preferences.dateFormatPreset == 1 { lockUTCCell(true) } else { lockUTCCell(false) } preferences.dateFormatUseUTC = useUTC } tableView.deselectRow(at: indexPath, animated: true) } }
gpl-3.0
dddf5fa19cfa1b44b7e507c405df52bc
44.909091
145
0.620824
4.936928
false
false
false
false
WalletOne/P2P
P2PExample/Controllers/Freelancer/FreelancerViewController.swift
1
1884
// // FreelancerViewController.swift // P2P_iOS // // Created by Vitaliy Kuzmenko on 02/08/2017. // Copyright © 2017 Wallet One. All rights reserved. // import UIKit import P2PCore import P2PUI class FreelancerViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let freelancer = Freelancer() freelancer.id = "alinakuzmenko" // NSUUID().uuidString freelancer.title = "Alina Kuzmenko" freelancer.phoneNumber = "79286635566" DataStorage.default.freelancer = freelancer P2PCore.setBenificiary(id: freelancer.id, title: freelancer.title, phoneNumber: freelancer.phoneNumber) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) switch segue.identifier! { case "DealsViewController": let vc = segue.destination as! DealsViewController vc.userTypeId = .freelancer default:break } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let paymentToolsIndexPath = IndexPath(row: 0, section: 1) let payoutsIndexPath = IndexPath(row: 1, section: 1) switch indexPath { case paymentToolsIndexPath: presentPaymentTools() case payoutsIndexPath: presentPayouts() default: break } } func presentPaymentTools() { let vc = PaymentToolsViewController(owner: .benificiary, delegate: nil) navigationController?.pushViewController(vc, animated: true) } func presentPayouts() { let vc = PayoutsViewController(dealId: nil) navigationController?.pushViewController(vc, animated: true) } }
mit
6f94138d8691c335307125e536b1ed60
29.370968
111
0.651089
4.548309
false
false
false
false
sahandnayebaziz/Dana-Hills
Dana Hills/BellSchedulesViewController.swift
1
6636
// // BellSchedulesViewController.swift // Dana Hills // // Created by Nayebaziz, Sahand on 9/23/16. // Copyright © 2016 Nayebaziz, Sahand. All rights reserved. // import UIKit import AFDateHelper struct ClassPeriod { var name: String var startTime: Date var endTime: Date } struct Schedule { var name: String var periods: [ClassPeriod] } class BellSchedulesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { let tableView = UITableView(frame: CGRect.zero, style: .grouped) var schedules: [Schedule] = [] override func viewDidLoad() { super.viewDidLoad() title = "Bell Schedules" automaticallyAdjustsScrollViewInsets = false navigationController?.navigationBar.barTintColor = Colors.blue navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white] navigationController?.navigationBar.tintColor = UIColor.white let blockSchedule = Schedule(name: "Block Schedule", periods: [ ClassPeriod(name: "Period 0", startTime: date(atHour: 6, withMinutes: 42), endTime: date(atHour: 7, withMinutes: 47)), ClassPeriod(name: "Period 1/2", startTime: date(atHour: 7, withMinutes: 56), endTime: date(atHour: 9, withMinutes: 41)), ClassPeriod(name: "Tutorial", startTime: date(atHour: 9, withMinutes: 51), endTime: date(atHour: 10, withMinutes: 19)), ClassPeriod(name: "Break", startTime: date(atHour: 10, withMinutes: 19), endTime: date(atHour: 10, withMinutes: 24)), ClassPeriod(name: "Period 3/4", startTime: date(atHour: 10, withMinutes: 33), endTime: date(atHour: 12, withMinutes: 19)), ClassPeriod(name: "Lunch", startTime: date(atHour: 12, withMinutes: 19), endTime: date(atHour: 12, withMinutes: 49)), ClassPeriod(name: "Period 5/6", startTime: date(atHour: 12, withMinutes: 58), endTime: date(atHour: 14, withMinutes: 44)) ]) let lateStart = Schedule(name: "Late Start", periods: [ ClassPeriod(name: "Period 1", startTime: date(atHour: 8, withMinutes: 40), endTime: date(atHour: 9, withMinutes: 28)), ClassPeriod(name: "Period 3", startTime: date(atHour: 9, withMinutes: 37), endTime: date(atHour: 10, withMinutes: 24)), ClassPeriod(name: "Break", startTime: date(atHour: 10, withMinutes: 24), endTime: date(atHour: 10, withMinutes: 30)), ClassPeriod(name: "Period 2", startTime: date(atHour: 10, withMinutes: 39), endTime: date(atHour: 11, withMinutes: 26)), ClassPeriod(name: "Period 4", startTime: date(atHour: 11, withMinutes: 35), endTime: date(atHour: 12, withMinutes: 22)), ClassPeriod(name: "Lunch", startTime: date(atHour: 12, withMinutes: 22), endTime: date(atHour: 12, withMinutes: 52)), ClassPeriod(name: "Period 5", startTime: date(atHour: 13, withMinutes: 1), endTime: date(atHour: 13, withMinutes: 48)), ClassPeriod(name: "Period 6", startTime: date(atHour: 13, withMinutes: 57), endTime: date(atHour: 14, withMinutes: 44)) ]) let traditionalSchedule = Schedule(name: "Traditional Schedule", periods: [ ClassPeriod(name: "Period 0", startTime: date(atHour: 6, withMinutes: 42), endTime: date(atHour: 7, withMinutes: 47)), ClassPeriod(name: "Period 1", startTime: date(atHour: 7, withMinutes: 56), endTime: date(atHour: 8, withMinutes: 53)), ClassPeriod(name: "Period 3", startTime: date(atHour: 9, withMinutes: 02), endTime: date(atHour: 9, withMinutes: 56)), ClassPeriod(name: "Break", startTime: date(atHour: 9, withMinutes: 56), endTime: date(atHour: 10, withMinutes: 2)), ClassPeriod(name: "Period 2", startTime: date(atHour: 10, withMinutes: 11), endTime: date(atHour: 11, withMinutes: 5)), ClassPeriod(name: "Period 4", startTime: date(atHour: 11, withMinutes: 14), endTime: date(atHour: 12, withMinutes: 8)), ClassPeriod(name: "Lunch", startTime: date(atHour: 12, withMinutes: 08), endTime: date(atHour: 12, withMinutes: 38)), ClassPeriod(name: "Period 5", startTime: date(atHour: 12, withMinutes: 47), endTime: date(atHour: 13, withMinutes: 41)), ClassPeriod(name: "Period 6", startTime: date(atHour: 13, withMinutes: 50), endTime: date(atHour: 14, withMinutes: 44)) ]) schedules.append(blockSchedule) schedules.append(lateStart) schedules.append(traditionalSchedule) view.addSubview(tableView) tableView.snp.makeConstraints { make in make.top.equalTo(topLayoutGuide.snp.bottom) make.bottom.equalTo(bottomLayoutGuide.snp.top) make.width.equalTo(view) make.centerX.equalTo(view) } tableView.delegate = self tableView.dataSource = self tableView.reloadData() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(tappedDone)) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } func numberOfSections(in tableView: UITableView) -> Int { return schedules.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return schedules[section].periods.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cell") if cell == nil { cell = UITableViewCell(style: .value1, reuseIdentifier: "cell") } let period = schedules[indexPath.section].periods[indexPath.row] cell!.textLabel?.text = period.name cell!.detailTextLabel?.text = "\(period.startTime.toString(format: .custom("h:mm a"))) - \(period.endTime.toString(format: .custom("h:mm a")))" return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } private func date(atHour hour: Int, withMinutes minutes: Int) -> Date { return Date().dateFor(.startOfDay).adjust(.hour, offset: hour).adjust(.minute, offset: minutes) } @objc func tappedDone() { dismiss(animated: true, completion: nil) } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return schedules[section].name } }
mit
01f0d472c3ac250bf62405fb22689563
51.244094
151
0.658628
4.090629
false
false
false
false
apple/swift
test/IRGen/prespecialized-metadata/struct-inmodule-1argument-2distinct_use.swift
14
3392
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main5ValueVySdGMf" = linkonce_odr hidden constant <{ // CHECk-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32{{(, \[4 x i8\])?}}, // CHECk-SAME: i64 // CHECK-SAME: }> <{ // i8** @"$sBi64_WV", // i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVySdGWV", i32 0, i32 0), // CHECk-SAME: [[INT]] 512, // CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), // CHECK-SAME: %swift.type* @"$sSdN", // CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}}, // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] // CHECK: @"$s4main5ValueVySiGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32{{(, \[4 x i8\])?}}, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** @"$sB[[INT]]_WV", // i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVySiGWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 512, // CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}}, // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] struct Value<First> { let first: First } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySiGMf" to %swift.full_type*), i32 0, i32 1)) // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySdGMf" to %swift.full_type*), i32 0, i32 1)) // CHECK: } func doit() { consume( Value(first: 13) ) consume( Value(first: 13.0) ) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE]], i8* undef, i8* undef, %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), [[INT]]* @"$s4main5ValueVMz") #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
apache-2.0
8bd2ec0ac969211c2184ce6c09981c66
48.882353
332
0.60908
3.05036
false
false
false
false
LawrenceHan/iOS-project-playground
Puzzle/Puzzle/MyPlayground.playground/Contents.swift
1
317
//: Playground - noun: a place where people can play import Cocoa var str = "Hello, playground" let availableCPUCount: Int = 8; let routesCount = 34; var groupCount = routesCount / availableCPUCount + 1 var indexOffset = groupCount * 0 var beginIndex = 0 + indexOffset var endIndex = (groupCount - 1) + indexOffset
mit
c96cb73c2c0e3d690f84878295ab89e2
27.818182
52
0.741325
3.77381
false
false
false
false
con-beo-vang/Spendy
Spendy/Helpers/SPNotification.swift
1
850
// // SPNotification.swift // Spendy // // Created by Harley Trung on 10/5/15. // Copyright © 2015 Cheetah. All rights reserved. // import Foundation class SPNotification { static let transactionsLoadedForAccount = "TransactionsLoadedForAccount" static let transactionAddedOrUpdated = "TransactionAddedOrUpdated" static let accountAddedOrUpdated = "AccountAddedOrUpdated" static let allCategoriesLoaded = "AllCategoriesLoaded" static let allAccountsLoadedLocally = "AllAccountsLoadedLocally" static let allAccountsLoadedRemotely = "AllAccountsLoadedRemotely" static let recomputedBalanceForOneAccount = "RecomputedBalanceForOneAccount" static let balanceStatsUpdated = "balanceStatsUpdated" static let finishedBootstrapingCategories = "FinishedBootstrapCategories" }
mit
29a207a24c52a367681271a417d1c89a
39.428571
79
0.758539
4.690608
false
false
false
false
X140Yu/Lemon
Lemon/Features/OAuth/OAuthHelper.swift
1
651
import Foundation class OAuthHelper { /// decode targetKey from a URLStirng with query /// /// - Parameters: /// - targetKey: "code" /// - queryURLStirng: "lemon://oauth/github?code=123123" /// - Returns: "123123" class func decode(_ targetKey: String, _ queryURLStirng: String) -> String? { if let tokenURL = URL(string: queryURLStirng) { if let components = tokenURL.query?.components(separatedBy: "&") { for comp in components { if (comp.range(of: "\(targetKey)" + "=") != nil) { return comp.components(separatedBy: "=").last } } } } return nil } }
gpl-3.0
16c325b53eb341ff75824ae5c5937118
27.304348
79
0.576037
3.969512
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Trivial - 不需要看的题目/标准库实现题/707_Design Linked List.swift
1
3799
// 707_Design Linked List // https://leetcode.com/problems/design-linked-list/ // // Created by Honghao Zhang on 10/5/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // Design your implementation of the linked list. You can choose to use the singly linked list or the doubly linked list. A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node. If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed. // //Implement these functions in your linked list class: // //get(index) : Get the value of the index-th node in the linked list. If the index is invalid, return -1. //addAtHead(val) : Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. //addAtTail(val) : Append a node of value val to the last element of the linked list. //addAtIndex(index, val) : Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. If index is negative, the node will be inserted at the head of the list. //deleteAtIndex(index) : Delete the index-th node in the linked list, if the index is valid. //Example: // //MyLinkedList linkedList = new MyLinkedList(); //linkedList.addAtHead(1); //linkedList.addAtTail(3); //linkedList.addAtIndex(1, 2); // linked list becomes 1->2->3 //linkedList.get(1); // returns 2 //linkedList.deleteAtIndex(1); // now the linked list is 1->3 //linkedList.get(1); // returns 3 //Note: // //All values will be in the range of [1, 1000]. //The number of operations will be in the range of [1, 1000]. //Please do not use the built-in LinkedList library. // import Foundation class Num707 { class MyLinkedList { var nums: [Int] = [] /** Initialize your data structure here. */ init() { } /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ func get(_ index: Int) -> Int { guard index < nums.count, index >= 0 else { return -1 } return nums[index] } /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ func addAtHead(_ val: Int) { nums.insert(val, at: 0) } /** Append a node of value val to the last element of the linked list. */ func addAtTail(_ val: Int) { nums.append(val) } /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ func addAtIndex(_ index: Int, _ val: Int) { guard index <= nums.count else { return } if index < 0 { nums.insert(val, at: 0) } else { nums.insert(val, at: index) } } /** Delete the index-th node in the linked list, if the index is valid. */ func deleteAtIndex(_ index: Int) { guard index < nums.count, index >= 0 else { return } nums.remove(at: index) } } /** * Your MyLinkedList object will be instantiated and called as such: * let obj = MyLinkedList() * let ret_1: Int = obj.get(index) * obj.addAtHead(val) * obj.addAtTail(val) * obj.addAtIndex(index, val) * obj.deleteAtIndex(index) */ }
mit
be5c43ccc5fce17742084dec50460fa7
38.978947
464
0.662191
3.805611
false
false
false
false
AcroMace/receptionkit
ReceptionKit/View Controllers/Received Messages/SmoochConversationDelegate.swift
1
4924
// // SmoochConversationDelegate.swift // ReceptionKit // // Created by Andy Cho on 2015-04-24. // Copyright (c) 2015 Andy Cho. All rights reserved. // import Foundation import UIKit class ConversationDelegate: NSObject, SKTConversationDelegate { var isPresentingMessage = false // Display the message modal when a message arrives // Only displays the last message func conversation(_ conversation: SKTConversation, didReceiveMessages messages: [Any]) { display(messages: messages) } func conversation(_ conversation: SKTConversation, didReceivePreviousMessages messages: [Any]) { display(messages: messages) } // Don't show the default Smooch conversation func conversation(_ conversation: SKTConversation, shouldShowFor action: SKTAction, withInfo info: [AnyHashable : Any]?) -> Bool { return false } // Don't show the default Smooch notification func conversation(_ conversation: SKTConversation, shouldShowInAppNotificationFor message: SKTMessage) -> Bool { return false } // Don't do anything when reading messages func conversation(_ conversation: SKTConversation, unreadCountDidChange unreadCount: UInt) { // Do nothing } // Don't let the user tap on the message (which should not be visible) func conversation(_ conversation: SKTConversation, shouldHandle action: SKTMessageAction) -> Bool { return false } // MARK: - Private methods private func display(messages: [Any]) { // May be a bug here where messages are ignored if the messages are batched // and multiple messages are sent at once guard let lastMessage = messages.last as? SKTMessage, !lastMessage.isFromCurrentUser else { return } guard let text = lastMessage.text else { Logger.error("Received an empty message from Smooch") return } if Config.Photos.EnableCommand && containsImageCommand(text), let photo = camera.takePhoto() { messageSender.send(image: photo) } else { showReceivedMessage(lastMessage) } } private func containsImageCommand(_ text: String) -> Bool { return text.contains(Config.Photos.ImageCaptureCommand) } private func showReceivedMessage(_ message: SKTMessage) { let topVC = getTopViewController() guard let receivedMessageView = createReceivedMessageView(message) else { Logger.error("Could not create ReceivedMessageView to display the received message") return } // Check that there is no presentation already before presenting if isPresentingMessage { topVC.dismiss(animated: true) { () -> Void in self.isPresentingMessage = false self.presentMessageView(receivedMessageView) } } else { self.presentMessageView(receivedMessageView) } // Dismiss the message after 10 seconds Timer.scheduledTimer( timeInterval: 10.0, target: self, selector: #selector(dismissMessageView(_:)), userInfo: nil, repeats: false) } // Present the message private func presentMessageView(_ viewController: UIViewController) { getTopViewController().present(viewController, animated: true) { () -> Void in self.isPresentingMessage = true } } // Dismiss the message @objc private func dismissMessageView(_ timer: Timer!) { guard isPresentingMessage else { return } getTopViewController().dismiss(animated: true) { [weak self] in self?.isPresentingMessage = false } } /** Get the view controller that's currently being presented This is where the notification will show - returns: The top view controller */ private func getTopViewController() -> UIViewController { return UIApplication.shared.keyWindow!.rootViewController! } /** Create a received message view - parameter lastMessage: Last message in the conversation - returns: The view created */ private func createReceivedMessageView(_ lastMessage: SKTMessage) -> ReceivedMessageViewController? { guard let name = lastMessage.name, let text = lastMessage.text, let picture = lastMessage.avatarUrl else { Logger.error("Message received was missing information") return nil } let receivedMessageView = ReceivedMessageViewController(nibName: ReceivedMessageViewController.nibName, bundle: nil) let receivedMessageViewModel = ReceivedMessageViewModel( name: name, message: text, picture: picture) receivedMessageView.configure(receivedMessageViewModel) return receivedMessageView } }
mit
0894cd681d94dd35afb06dd94403283c
33.676056
134
0.660642
5.346363
false
false
false
false
dclelland/AudioKit
AudioKit/Common/Nodes/Effects/Reverb/Comb Filter Reverb/AKCombFilterReverb.swift
1
4768
// // AKCombFilterReverb.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// This filter reiterates input with an echo density determined by /// loopDuration. The attenuation rate is independent and is determined by /// reverbDuration, the reverberation duration (defined as the time in seconds /// for a signal to decay to 1/1000, or 60dB down from its original amplitude). /// Output from a comb filter will appear only after loopDuration seconds. /// /// - parameter input: Input node to process /// - parameter reverbDuration: The time in seconds for a signal to decay to 1/1000, or 60dB from its original amplitude. (aka RT-60). /// - parameter loopDuration: The loop time of the filter, in seconds. This can also be thought of as the delay time. Determines frequency response curve, loopDuration * sr/2 peaks spaced evenly between 0 and sr/2. /// public class AKCombFilterReverb: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKCombFilterReverbAudioUnit? internal var token: AUParameterObserverToken? private var reverbDurationParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// The time in seconds for a signal to decay to 1/1000, or 60dB from its original amplitude. (aka RT-60). public var reverbDuration: Double = 1.0 { willSet { if reverbDuration != newValue { if internalAU!.isSetUp() { reverbDurationParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.reverbDuration = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this filter node /// /// - parameter input: Input node to process /// - parameter reverbDuration: The time in seconds for a signal to decay to 1/1000, or 60dB from its original amplitude. (aka RT-60). /// - parameter loopDuration: The loop time of the filter, in seconds. This can also be thought of as the delay time. Determines frequency response curve, loopDuration * sr/2 peaks spaced evenly between 0 and sr/2. /// public init( _ input: AKNode, reverbDuration: Double = 1.0, loopDuration: Double = 0.1) { self.reverbDuration = reverbDuration var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = 0x636f6d62 /*'comb'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKCombFilterReverbAudioUnit.self, asComponentDescription: description, name: "Local AKCombFilterReverb", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKCombFilterReverbAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) self.internalAU!.setLoopDuration(Float(loopDuration)) } guard let tree = internalAU?.parameterTree else { return } reverbDurationParameter = tree.valueForKey("reverbDuration") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.reverbDurationParameter!.address { self.reverbDuration = Double(value) } } } internalAU?.reverbDuration = Float(reverbDuration) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
mit
3a45a4a157351b032b41fce9f1a4563a
36.543307
218
0.651426
5.280177
false
false
false
false
LaszloPinter/CircleColorPicker
CircleColorPicker/ColorPicker/Views/LinearPickers/SaturationPickerView.swift
1
2076
// // SaturationPickerView.swift // CircleColorPicker // // Created by Laszlo Pinter on 11/17/17. // Copyright © 2017 Laszlo Pinter. All rights reserved. // import UIKit open class SaturationPickerView: LinearPickerView { open override func handleOrientationChange() { (frontLayerView as! SaturationMask).isVertical = isVertical } open override func createFrontLayerView() -> UIView{ let frontLayer = SaturationMask(frame: CGRect.init(origin: CGPoint.zero, size: self.bounds.size)) frontLayer.isVertical = isVertical return frontLayer } class SaturationMask: UIView { public var isVertical = false func drawScale(context: CGContext){ let startColor = UIColor.init(hue: 1, saturation: 0, brightness: 1, alpha: 1).cgColor let endColor = UIColor.init(hue: 1, saturation: 0, brightness: 1, alpha: 0).cgColor let colorSpace = CGColorSpaceCreateDeviceRGB() let colors = [startColor, endColor] as CFArray if let gradient = CGGradient.init(colorsSpace: colorSpace, colors: colors, locations: nil) { var startPoint: CGPoint! var endPoint: CGPoint! if isVertical { startPoint = CGPoint(x: self.bounds.width, y: self.bounds.height) endPoint = CGPoint(x: self.bounds.width, y: 0) }else { startPoint = CGPoint(x: 0, y: self.bounds.height) endPoint = CGPoint(x: self.bounds.width, y: self.bounds.height) } context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: .drawsBeforeStartLocation) } } override func draw(_ rect: CGRect) { super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } drawScale(context: context) } } }
mit
5de8e8a29931d39dd4303506bff55a7d
34.775862
122
0.577349
5
false
false
false
false
erik/sketches
projects/jot/Jot/ContentView.swift
1
10009
import Combine import SwiftUI // Apparently not possible to modify this with SwiftUI yet. // https://stackoverflow.com/questions/59813943/ extension NSTextField { override open var focusRingType: NSFocusRingType { get { .none } set {} } } struct PlanItemView: View { @Environment(\.managedObjectContext) var moc @ObservedObject var item: TodoItem @State var isEditing = false func commitChange() { isEditing = false item.objectWillChange.send() moc.perform { try? moc.save() } } var body: some View { HStack(alignment: .firstTextBaseline) { Image(systemName: isEditing ? "pencil.circle" : (item.isCompleted ? "circle.fill" : "circle")) .foregroundColor(.gray) .frame(width: 14, height: 14) .onTapGesture(count: 1) { item.isCompleted = !item.isCompleted; commitChange() } ZStack(alignment: .leading) { TextField( item.task ?? "", text: Binding($item.task)!, onEditingChanged: { hasFocus in if !hasFocus { self.isEditing = false } }, onCommit: { commitChange() } ) .padding(2) .background(Color(NSColor.textBackgroundColor)) .cornerRadius(6.0) .opacity(isEditing ? 1 : 0) .onExitCommand { isEditing = false } .onReceive(NotificationCenter.default.publisher(for: NSTextField.textDidEndEditingNotification)) { _ in commitChange() } Text(item.task!) .strikethrough(item.isCompleted, color: .secondary) .foregroundColor(item.isCompleted ? .secondary : .primary) .opacity(isEditing ? 0 : 1) .onTapGesture { isEditing = true } } .textFieldStyle(.plain) .foregroundColor(.secondary) } .contentShape(Rectangle()) // In order to make the whole thing clickable .contextMenu { Button("Edit", action: { self.isEditing = true }) // TODO: This doesn't work. Button("Remove", action: { item.isRemoved = true; commitChange() }) } } } extension NSTextView { override open var frame: CGRect { didSet { backgroundColor = .clear drawsBackground = true } } } struct DateHeader: View { let weekday: String! let monthday: String! let year: String! init(date: Date) { let fmt = DateFormatter() fmt.dateFormat = "EEEE" weekday = fmt.string(from: date) fmt.dateFormat = "MMMM dd" monthday = fmt.string(from: date) fmt.dateFormat = "yyyy" year = fmt.string(from: date) } var body: some View { HStack { Text(weekday) .font(.body.bold()) + Text(" ") + Text(monthday) .font(.body.bold()) .foregroundColor(.gray) Spacer() } } } class DebouncingExecutor: ObservableObject { private var timer: Timer? func afterDelay(of: TimeInterval, perform block: @escaping () -> Void) { timer?.invalidate() timer = Timer.scheduledTimer( withTimeInterval: of, repeats: false, block: { _ in block() } ) } } struct JournalView: View { @Environment(\.managedObjectContext) var managedObjectContext private let debouncedSaveExecutor = DebouncingExecutor() private let placeholderText: String = "What's on your mind?" @ObservedObject var journal: JournalEntry let isEditable: Bool @Namespace var planListBottomId @State var newPlanItem: String = "" func createNewTodo() { if !newPlanItem.isEmpty { journal.addTodo( of: newPlanItem, using: managedObjectContext ) } newPlanItem = "" } var body: some View { DateHeader(date: journal.date!) .padding(.bottom, 5) ScrollViewReader { scrollViewReader in VStack(alignment: .leading, spacing: 5) { ForEach(journal.todoItemsArray, id: \.self) { item in if !item.isRemoved { PlanItemView(item: item) } } if isEditable { HStack(alignment: .firstTextBaseline) { Image(systemName: "plus.circle") .foregroundColor(.gray) .frame(width: 14, height: 14) .onTapGesture { createNewTodo() withAnimation { scrollViewReader.scrollTo(planListBottomId) } } TextField( journal.todoItemsArray.isEmpty ? "Add plan..." : "Add another...", text: $newPlanItem, onCommit: { createNewTodo() withAnimation { scrollViewReader.scrollTo(planListBottomId) } } ) .padding(2.0) .textFieldStyle(.plain) .id(planListBottomId) } } } } Spacer() .frame(minHeight: 15) if isEditable || !(journal.note ?? "").isEmpty { ZStack(alignment: .topLeading) { TextEditor(text: $journal.noteOrEmpty) .disableAutocorrection(false) .onChange(of: journal.noteOrEmpty, perform: { _ in debouncedSaveExecutor.afterDelay(of: 2.0, perform: { managedObjectContext.perform { try? managedObjectContext.save() } }) }) .disabled(!isEditable) .foregroundColor(!isEditable ? .secondary : .primary) .multilineTextAlignment(.leading) .frame(height: 90) Text(placeholderText) .foregroundColor(.secondary) .disabled(!isEditable) .allowsHitTesting(false) .padding(.leading, 5) .opacity(journal.noteOrEmpty == "" ? 1 : 0) } .padding() .background(Color(NSColor.textBackgroundColor).opacity(0.5)) .cornerRadius(10) .font(.body) } } } struct JournalListView: View { @ObservedObject var currentJournal: JournalEntry @FetchRequest var previousJournals: FetchedResults<JournalEntry> // TODO: Would this break when the day rolls over? init(_ currentDate: Date, _ managedObjectContext: NSManagedObjectContext) { currentJournal = JournalEntry.getOrCreateFor( date: currentDate, using: managedObjectContext ) _previousJournals = FetchRequest<JournalEntry>( sortDescriptors: [NSSortDescriptor(keyPath: \JournalEntry.date, ascending: false)], predicate: NSPredicate(format: "%K != %@", #keyPath(JournalEntry.date), currentDate as NSDate) ) } var body: some View { VStack(alignment: .leading) { JournalView( journal: currentJournal, isEditable: true ) ForEach(previousJournals, id: \.self) { journal in JournalView( journal: journal, isEditable: false ) } VStack(alignment: .center) { Text("That's all!") .font(.body) .foregroundColor(.secondary) .padding() .frame(maxWidth: .infinity) } } } } class ContentViewModel: ObservableObject { @Published var currentDate: Date = Calendar.current.startOfDay(for: Date()) init() { NotificationCenter.default.addObserver( self, selector: #selector(dateChanged), name: .NSCalendarDayChanged, object: nil ) } @objc func dateChanged() { DispatchQueue.main.sync { currentDate = Calendar.current.startOfDay(for: Date()) } } } struct ContentView: View { @ObservedObject var viewModel = ContentViewModel() @EnvironmentObject var statusBar: StatusBarController @Environment(\.managedObjectContext) var managedObjectContext var body: some View { // TODO: Kind of wacky nesting going on here. GeometryReader { _ in ScrollView(showsIndicators: true) { JournalListView(viewModel.currentDate, managedObjectContext) .padding() } .background(Color(NSColor.windowBackgroundColor)) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { Group { ContentView() .environment(\.colorScheme, .dark) .environment(\.managedObjectContext, PersistenceController.preview.container.viewContext) ContentView() .environment(\.colorScheme, .light) .environment(\.managedObjectContext, PersistenceController.preview.container.viewContext) } } }
agpl-3.0
0efe81b7fb13448d1a811b2685b5a9a8
30.875796
119
0.506544
5.421993
false
false
false
false
jtbandes/swift
test/Interpreter/objc_class_properties.swift
5
5812
// RUN: rm -rf %t && mkdir -p %t // RUN: %clang %target-cc-options -isysroot %sdk -fobjc-arc %S/Inputs/ObjCClasses/ObjCClasses.m -c -o %t/ObjCClasses.o // RUN: %target-build-swift -I %S/Inputs/ObjCClasses/ %t/ObjCClasses.o %s -o %t/a.out // RUN: %target-run %t/a.out // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation import StdlibUnittest import ObjCClasses class SwiftClass : ProtoWithClassProperty { static var getCount = 0 static var setCount = 0 private static var _value: CInt = 0 @objc class func reset() { getCount = 0 setCount = 0 _value = 0 } @objc class var value: CInt { get { getCount += 1 return _value } set { setCount += 1 _value = newValue } } @objc class var optionalClassProp: Bool { return true } } class Subclass : ClassWithClassProperty { static var getCount = 0 static var setCount = 0 override class func reset() { getCount = 0 setCount = 0 super.reset() } override class var value: CInt { get { getCount += 1 return super.value } set { setCount += 1 super.value = newValue } } override class var optionalClassProp: Bool { return true } } var ClassProperties = TestSuite("ClassProperties") ClassProperties.test("direct") { ClassWithClassProperty.reset() expectEqual(0, ClassWithClassProperty.value) ClassWithClassProperty.value = 4 expectEqual(4, ClassWithClassProperty.value) Subclass.reset() expectEqual(0, Subclass.value) Subclass.value = 4 expectEqual(4, Subclass.value) expectEqual(2, Subclass.getCount) expectEqual(1, Subclass.setCount) } func testExistential(_ e: ProtoWithClassProperty.Type) { e.reset() expectEqual(0, e.value) e.value = 4 expectEqual(4, e.value) } ClassProperties.test("existentials") { testExistential(ClassWithClassProperty.self) testExistential(ObjCSubclassWithClassProperty.self) testExistential(SwiftClass.self) expectEqual(2, SwiftClass.getCount) expectEqual(1, SwiftClass.setCount) testExistential(Subclass.self) expectEqual(2, Subclass.getCount) expectEqual(1, Subclass.setCount) } func testGeneric<T: ProtoWithClassProperty>(_ e: T.Type) { e.reset() expectEqual(0, e.value) e.value = 4 expectEqual(4, e.value) } ClassProperties.test("generics") { testGeneric(ClassWithClassProperty.self) testGeneric(ObjCSubclassWithClassProperty.self) testGeneric(SwiftClass.self) expectEqual(2, SwiftClass.getCount) expectEqual(1, SwiftClass.setCount) testGeneric(Subclass.self) expectEqual(2, Subclass.getCount) expectEqual(1, Subclass.setCount) } func testInheritance(_ e: ClassWithClassProperty.Type) { e.reset() expectEqual(0, e.value) e.value = 4 expectEqual(4, e.value) } ClassProperties.test("inheritance") { testInheritance(ClassWithClassProperty.self) testInheritance(ObjCSubclassWithClassProperty.self) testInheritance(Subclass.self) expectEqual(2, Subclass.getCount) expectEqual(1, Subclass.setCount) } func testInheritanceGeneric<T: ClassWithClassProperty>(_ e: T.Type) { e.reset() expectEqual(0, e.value) e.value = 4 expectEqual(4, e.value) } ClassProperties.test("inheritance/generic") { testInheritanceGeneric(ClassWithClassProperty.self) testInheritanceGeneric(ObjCSubclassWithClassProperty.self) testInheritanceGeneric(Subclass.self) expectEqual(2, Subclass.getCount) expectEqual(1, Subclass.setCount) } ClassProperties.test("optionalProp") { let noProp: ProtoWithClassProperty.Type = ClassWithClassProperty.self expectNil(noProp.optionalClassProp) let hasProp: ProtoWithClassProperty.Type = Subclass.self expectNotNil(hasProp.optionalClassProp) expectEqual(true, hasProp.optionalClassProp!) let hasOwnProp: ProtoWithClassProperty.Type = SwiftClass.self expectNotNil(hasOwnProp.optionalClassProp) expectEqual(true, hasOwnProp.optionalClassProp!) let hasPropObjC: ProtoWithClassProperty.Type = ObjCSubclassWithClassProperty.self expectNotNil(hasPropObjC.optionalClassProp) expectEqual(true, hasPropObjC.optionalClassProp!) } class NamingConflictSubclass : PropertyNamingConflict { override var prop: Any? { return nil } override class var prop: Any? { return NamingConflictSubclass() } } ClassProperties.test("namingConflict") { let obj = PropertyNamingConflict() expectTrue(obj === obj.prop.map { $0 as AnyObject }) expectNil(type(of: obj).prop) expectNil(PropertyNamingConflict.prop) let sub = NamingConflictSubclass() expectNil(sub.prop) expectNotNil(type(of: sub).prop) expectNotNil(NamingConflictSubclass.prop) } extension NamingConflictSubclass : PropertyNamingConflictProto { var protoProp: Any? { get { return self } set {} } class var protoProp: Any? { get { return nil } set {} } } ClassProperties.test("namingConflict/protocol") { let obj: PropertyNamingConflictProto = NamingConflictSubclass() expectTrue(obj === obj.protoProp.map { $0 as AnyObject }) expectNil(type(of: obj).protoProp) let type: PropertyNamingConflictProto.Type = NamingConflictSubclass.self expectNil(type.protoProp) } var global1: Int = 0 var global2: Int = 0 class Steak : NSObject { @objc override var thickness: Int { get { return global1 } set { global1 = newValue } } } extension NSObject : HasThickness { @objc var thickness: Int { get { return global2 } set { global2 = newValue } } } protocol HasThickness : class { var thickness: Int { get set } } ClassProperties.test("dynamicOverride") { // Calls NSObject.thickness NSObject().thickness += 1 // Calls Steak.thickness (Steak() as NSObject).thickness += 1 Steak().thickness += 1 (Steak() as HasThickness).thickness += 1 expectEqual(3, global1) expectEqual(1, global2) } runAllTests()
apache-2.0
914aab959cab82db34910d9ab2026495
23.016529
118
0.728493
3.890228
false
true
false
false
mownier/photostream
Photostream/Modules/Post Discovery/Interactor/PostDiscoveryInteractor.swift
1
4527
// // PostDiscoveryInteractor.swift // Photostream // // Created by Mounir Ybanez on 20/12/2016. // Copyright © 2016 Mounir Ybanez. All rights reserved. // protocol PostDiscoveryInteractorInput: BaseModuleInteractorInput { func fetchNew(with limit: UInt) func fetchNext(with limit: UInt) func like(post id: String) func unlike(post id: String) } protocol PostDiscoveryInteractorOutput: BaseModuleInteractorOutput { func postDiscoveryDidRefresh(with data: [PostDiscoveryData]) func postDiscoveryDidLoadMore(with data: [PostDiscoveryData]) func postDiscoveryDidRefresh(with error: PostServiceError) func postDiscoveryDidLoadMore(with error: PostServiceError) func postDiscoveryDidLike(with postId: String, and error: PostServiceError?) func postDiscoveryDidUnlike(with postId: String, and error: PostServiceError?) } protocol PostDiscoveryInteractorInterface: BaseModuleInteractor { var service: PostService! { set get } var offset: String? { set get } var isFetching: Bool { set get } init(service: PostService) func fetchDiscoveryPosts(with limit: UInt) } class PostDiscoveryInteractor: PostDiscoveryInteractorInterface { typealias Output = PostDiscoveryInteractorOutput weak var output: Output? var service: PostService! var offset: String? var isFetching: Bool = false required init(service: PostService) { self.service = service } func fetchDiscoveryPosts(with limit: UInt) { guard !isFetching, offset != nil, output != nil else { return } service.fetchDiscoveryPosts(offset: offset!, limit: limit) { [weak self] result in guard result.error == nil else { self?.didFetch(with: result.error!) return } guard let list = result.posts, list.count > 0 else { self?.didFetch(with: [PostDiscoveryData]()) return } var posts = [PostDiscoveryData]() for post in list.posts { guard let user = list.users[post.userId] else { continue } var item = PostDiscoveryDataItem() item.id = post.id item.message = post.message item.timestamp = post.timestamp item.photoUrl = post.photo.url item.photoWidth = post.photo.width item.photoHeight = post.photo.height item.likes = post.likesCount item.comments = post.commentsCount item.isLiked = post.isLiked item.userId = user.id item.avatarUrl = user.avatarUrl item.displayName = user.displayName posts.append(item) } self?.didFetch(with: posts) self?.offset = result.nextOffset } } private func didFetch(with error: PostServiceError) { if offset != nil, offset!.isEmpty { output?.postDiscoveryDidRefresh(with: error) } else { output?.postDiscoveryDidLoadMore(with: error) } isFetching = false } private func didFetch(with data: [PostDiscoveryData]) { if offset != nil, offset!.isEmpty { output?.postDiscoveryDidRefresh(with: data) } else { output?.postDiscoveryDidLoadMore(with: data) } isFetching = false } } extension PostDiscoveryInteractor: PostDiscoveryInteractorInput { func fetchNew(with limit: UInt) { offset = "" fetchDiscoveryPosts(with: limit) } func fetchNext(with limit: UInt) { fetchDiscoveryPosts(with: limit) } func like(post id: String) { guard output != nil else { return } service.like(id: id) { [unowned self] error in self.output?.postDiscoveryDidLike(with: id, and: error) } } func unlike(post id: String) { guard output != nil else { return } service.unlike(id: id) { [unowned self] error in self.output?.postDiscoveryDidUnlike(with: id, and: error) } } }
mit
c1978c0147ff20c7b321fff0108219a5
27.828025
90
0.568493
5.108352
false
false
false
false
EvsenevDev/SmartReceiptsiOS
SmartReceiptsTests/Modules Tests/OCRConfigurationModuleTest.swift
2
1912
// // OCRConfigurationModuleTest.swift // SmartReceiptsTests // // Created by Bogdan Evsenev on 28/10/2017. // Copyright © 2017 Will Baumann. All rights reserved. // @testable import Cuckoo @testable import SmartReceipts import Viperit import RxSwift import RxTest import XCTest import SwiftyStoreKit import StoreKit class OCRConfigurationModuleTest: XCTestCase { var presenter: MockOCRConfigurationPresenter! var interactor: MockOCRConfigurationInteractor! var router: MockOCRConfigurationRouter! let purchaseService = MockPurchaseService().withEnabledSuperclassSpy() let bag = DisposeBag() override func setUp() { super.setUp() var module = AppModules.OCRConfiguration.build() module.injectMock(presenter: MockOCRConfigurationPresenter().withEnabledSuperclassSpy()) module.injectMock(interactor: MockOCRConfigurationInteractor(purchaseService: purchaseService).withEnabledSuperclassSpy()) module.injectMock(router: MockOCRConfigurationRouter().withEnabledSuperclassSpy()) presenter = module.presenter as? MockOCRConfigurationPresenter interactor = module.interactor as? MockOCRConfigurationInteractor router = module.router as? MockOCRConfigurationRouter configureStubs() } override func tearDown() { super.tearDown() } private func configureStubs() { stub(purchaseService) { mock in mock.requestProducts().thenReturn(Observable<SKProduct>.never()) mock.purchase(prodcutID: "").thenReturn(Observable<PurchaseDetails>.never()) } } func testInteractor() { _ = interactor.requestProducts() verify(purchaseService).requestProducts() _ = interactor.purchase(product: "") verify(purchaseService).purchase(prodcutID: "") } }
agpl-3.0
c41352d594719912b4253db9a0a2f431
29.333333
130
0.695447
5.137097
false
true
false
false
Constructor-io/constructorio-client-swift
AutocompleteClient/FW/Logic/Highlighting/CIOHighlighter.swift
1
2918
// // CIOHighlighter.swift // Constructor.io // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import UIKit /** Class responsible for result highlighting. It uses attributesProvider to get the string styling attributes. */ public class CIOHighlighter { /** Provides higlighting attributes. */ public var attributesProvider: CIOHighlightingAttributesProvider public init(attributesProvider: CIOHighlightingAttributesProvider) { self.attributesProvider = attributesProvider } /** Highlights the parts of the string matched in the search term. - parameter searchTerm: Search term used to query for results. - parameter itemTitle: Result item title which contains the search term, or parts of it. - returns: NSAttributeString with highlighted parts of the string. Styling is provided by the attributesProvider. */ public func highlight(searchTerm: String, itemTitle: String) -> NSAttributedString { // Tokenize search term let searchTokens = searchTerm.components(separatedBy: CharacterSet.alphanumerics.inverted) let finalString = NSMutableAttributedString() // Match on tokenized results var iterator = itemTitle.makeIterator(characterSet: .alphanumerics) while let (matches, result) = iterator.next() { guard matches else { // Not-matched, add specified font for default finalString.append(NSAttributedString.build(string: result, attributes: self.attributesProvider.defaultSubstringAttributes())) continue } // An alphanumeric match // Check prefix match let (prefix, suffix) = getBestPrefixBetween(prefixers: searchTokens, prefixee: result) // Add specified font for highlighted finalString.append(NSAttributedString.build(string: prefix, attributes: self.attributesProvider.highlightedSubstringAttributes())) // Add specified font for non-highlighted finalString.append(NSAttributedString.build(string: suffix, attributes: self.attributesProvider.defaultSubstringAttributes())) } return finalString } // Identify the best possible prefix match by any of the prefixers onto the given prefixee. private func getBestPrefixBetween(prefixers: [String], prefixee: String) -> (String, String) { var bestMatch = 0 for prefixer in prefixers { if prefixer.count > prefixee.count { continue } guard prefixee.lowercased().hasPrefix(prefixer.lowercased()), prefixer.count > bestMatch else { continue } bestMatch = prefixer.count } let index = prefixee.index(prefixee.startIndex, offsetBy: bestMatch) return (String(prefixee[..<index]), String(prefixee[index...])) } }
mit
03e8272bde5543e14270a255416602f8
38.418919
142
0.682208
5.144621
false
false
false
false
supertommy/swift-status-bar-app-osx
SwiftStatusBarApplication/IconView.swift
1
1548
// // IconView.swift // SwiftStatusBarApplication // // Created by Tommy Leung on 6/7/14. // Copyright (c) 2014 Tommy Leung. All rights reserved. // import Foundation import Cocoa class IconView : NSView { private(set) var image: NSImage private let item: NSStatusItem var onMouseDown: () -> () var isSelected: Bool { didSet { //redraw if isSelected changes for bg highlight if (isSelected != oldValue) { self.needsDisplay = true } } } init(imageName: String, item: NSStatusItem) { self.image = NSImage(named: imageName)! self.item = item self.isSelected = false self.onMouseDown = {} let thickness = NSStatusBar.systemStatusBar().thickness let rect = CGRectMake(0, 0, thickness, thickness) super.init(frame: rect) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(dirtyRect: NSRect) { self.item.drawStatusBarBackgroundInRect(dirtyRect, withHighlight: self.isSelected) let size = self.image.size let rect = CGRectMake(2, 2, size.width, size.height) self.image.drawInRect(rect) } override func mouseDown(theEvent: NSEvent) { self.isSelected = !self.isSelected; self.onMouseDown(); } override func mouseUp(theEvent: NSEvent) { } }
mit
b00d9d58061220e5bfc1a2ecec1d1b4d
21.779412
90
0.578811
4.566372
false
false
false
false
6ag/AppScreenshots
AppScreenshots/Classes/Module/Home/View/JFPasterGroupCollectionViewCell.swift
1
1993
// // JFPasterGroupCollectionViewCell.swift // AppScreenshots // // Created by zhoujianfeng on 2017/2/12. // Copyright © 2017年 zhoujianfeng. All rights reserved. // import UIKit class JFPasterGroupCollectionViewCell: UICollectionViewCell { /// 贴纸组模型 var pasterGroup: JFPasterGroup? { didSet { imageView.image = UIImage(contentsOfFile: Bundle.main.path(forResource: pasterGroup?.iconName ?? "", ofType: nil) ?? "") } } override init(frame: CGRect) { super.init(frame: frame) prepareUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - 懒加载 /// 贴纸 lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit return imageView }() /// 圆角背景 lazy var bgView: UIView = { let view = UIView() view.layer.cornerRadius = 10 view.backgroundColor = UIColor.colorWithHexString("#333333", alpha: 0.3) return view }() } // MARK: - 设置界面 extension JFPasterGroupCollectionViewCell { /// 准备UI fileprivate func prepareUI() { contentView.addSubview(bgView) contentView.addSubview(imageView) bgView.snp.makeConstraints { (make) in make.left.equalTo(layoutHorizontal(iPhone6: 8)) make.right.equalTo(layoutHorizontal(iPhone6: -8)) make.top.equalTo(layoutVertical(iPhone6: 8)) make.bottom.equalTo(layoutVertical(iPhone6: -8)) } imageView.snp.makeConstraints { (make) in make.left.equalTo(layoutHorizontal(iPhone6: 12)) make.right.equalTo(layoutHorizontal(iPhone6: -12)) make.top.equalTo(layoutVertical(iPhone6: 12)) make.bottom.equalTo(layoutVertical(iPhone6: -12)) } } }
mit
02dbe535d3ae67612790ab6989180068
26.464789
132
0.605641
4.513889
false
false
false
false
PerfectlySoft/Perfect-HTTP
Sources/PerfectHTTP/HTTPRequest.swift
1
5377
// // HTTPRequest.swift // PerfectLib // // Created by Kyle Jessup on 2016-06-20. // Copyright (C) 2016 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // // import PerfectNet /// An HTTP based request object. /// Contains all HTTP header and content data submitted by the client. public protocol HTTPRequest: class { /// The HTTP request method. var method: HTTPMethod { get set } /// The request path. var path: String { get set } /// Path components which may have been parsed during request reading. /// Paths which end in a slash should have an empty component at the end of the array. /// Since all paths are assumed to start with a slash, no empty leading component is included. var pathComponents: [String] { get } /// The parsed and decoded query/search arguments. var queryParams: [(String, String)] { get } /// The HTTP protocol version. For example (1, 0), (1, 1), (2, 0) var protocolVersion: (Int, Int) { get } /// The IP address and connecting port of the client. var remoteAddress: (host: String, port: UInt16) { get } /// The IP address and listening port for the server. var serverAddress: (host: String, port: UInt16) { get } /// The canonical name for the server. var serverName: String { get } /// The server's document root from which static file content will generally be served. var documentRoot: String { get } /// The TCP connection for this request. var connection: NetTCP { get } /// Any URL variables acquired during routing the path to the request handler. var urlVariables: [String:String] { get set } /// This dictionary is available for general use. /// It permits components which might be loosely coupled and called at differing times /// in the request execution process (eg. request/response filters) to pass messages or store /// data for later use. var scratchPad: [String:Any] { get set } /// Returns the requested incoming header value. func header(_ named: HTTPRequestHeader.Name) -> String? /// Add a header to the response. /// No check for duplicate or repeated headers will be made. func addHeader(_ named: HTTPRequestHeader.Name, value: String) /// Set the indicated header value. /// If the header already exists then the existing value will be replaced. func setHeader(_ named: HTTPRequestHeader.Name, value: String) /// Provide access to all current header values. var headers: AnyIterator<(HTTPRequestHeader.Name, String)> { get } // impl note: these xParams vars could be implimented as a protocol extension parsing the raw // query/post string // but they are likely to be called several times and the required parsing would // incur unwanted overhead /// Any parsed and decoded POST body parameters. /// If the POST content type is multipart/form-data then these will contain only the /// non-file upload parameters. var postParams: [(String, String)] { get } /// POST body data as raw bytes. /// If the POST content type is multipart/form-data then this will be nil. var postBodyBytes: [UInt8]? { get set } /// POST body data treated as UTF-8 bytes and decoded into a String, if possible. /// If the POST content type is multipart/form-data then this will be nil. var postBodyString: String? { get } /// If the POST content type is multipart/form-data then this will contain the decoded form /// parameters and file upload data. /// This value will be nil if the request is not POST or did not have a multipart/form-data /// content type. var postFileUploads: [MimeReader.BodySpec]? { get } } public extension HTTPRequest { /// Returns the first GET or POST parameter with the given name. /// Returns the supplied default value if the parameter was not found. func param(name: String, defaultValue: String? = nil) -> String? { for p in self.queryParams where p.0 == name { return p.1 } for p in self.postParams where p.0 == name { return p.1 } return defaultValue } /// Returns all GET or POST parameters with the given name. func params(named: String) -> [String] { let a = self.params().filter { $0.0 == named }.map { $0.1 } return a } /// Returns all GET or POST parameters. func params() -> [(String, String)] { let a = self.queryParams + self.postParams return a } } public extension HTTPRequest { /// Returns the full request URI. var uri: String { if self.queryParams.count == 0 { return self.path } return "\(self.path)?\(self.queryParams.map { return "\($0.0.stringByEncodingURL)=\($0.1.stringByEncodingURL)" }.joined(separator: "&"))" } /// Returns all the cookie name/value pairs parsed from the request. var cookies: [(String, String)] { guard let cookie = self.header(.cookie) else { return [(String, String)]() } return cookie.split(separator: ";").compactMap { let d = $0.split(separator: "=") guard d.count == 2 else { return nil } let d2 = d.map { String($0.filter { $0 != Character(" ") }).stringByDecodingURL ?? "" } return (d2[0], d2[1]) } } }
apache-2.0
a7d9b2ad6a730387b0e8e5b1463c11eb
38.248175
139
0.680863
3.832502
false
false
false
false
emilstahl/swift
stdlib/public/core/OptionSet.swift
10
6400
//===--- OptionSet.swift --------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 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 // //===----------------------------------------------------------------------===// /// Supplies convenient conformance to `SetAlgebraType` for any type /// whose `RawValue` is a `BitwiseOperationsType`. For example: /// /// struct PackagingOptions : OptionSetType { /// let rawValue: Int /// init(rawValue: Int) { self.rawValue = rawValue } /// /// static let Box = PackagingOptions(rawValue: 1) /// static let Carton = PackagingOptions(rawValue: 2) /// static let Bag = PackagingOptions(rawValue: 4) /// static let Satchel = PackagingOptions(rawValue: 8) /// static let BoxOrBag: PackagingOptions = [Box, Bag] /// static let BoxOrCartonOrBag: PackagingOptions = [Box, Carton, Bag] /// } /// /// In the example above, `PackagingOptions.Element` is the same type /// as `PackagingOptions`, and instance `a` subsumes instance `b` if /// and only if `a.rawValue & b.rawValue == b.rawValue`. public protocol OptionSetType : SetAlgebraType, RawRepresentable { // We can't constrain the associated Element type to be the same as // Self, but we can do almost as well with a default and a // constrained extension /// An `OptionSet`'s `Element` type is normally `Self`. typealias Element = Self // FIXME: This initializer should just be the failable init from // RawRepresentable. Unfortunately, current language limitations // that prevent non-failable initializers from forwarding to // failable ones would prevent us from generating the non-failing // default (zero-argument) initializer. Since OptionSetType's main // purpose is to create convenient conformances to SetAlgebraType, // we opt for a non-failable initializer. /// Convert from a value of `RawValue`, succeeding unconditionally. init(rawValue: RawValue) } /// `OptionSetType` requirements for which default implementations /// are supplied. /// /// - Note: A type conforming to `OptionSetType` can implement any of /// these initializers or methods, and those implementations will be /// used in lieu of these defaults. extension OptionSetType { /// Returns the set of elements contained in `self`, in `other`, or in /// both `self` and `other`. @warn_unused_result public func union(other: Self) -> Self { var r: Self = Self(rawValue: self.rawValue) r.unionInPlace(other) return r } /// Returns the set of elements contained in both `self` and `other`. @warn_unused_result public func intersect(other: Self) -> Self { var r = Self(rawValue: self.rawValue) r.intersectInPlace(other) return r } /// Returns the set of elements contained in `self` or in `other`, /// but not in both `self` and `other`. @warn_unused_result public func exclusiveOr(other: Self) -> Self { var r = Self(rawValue: self.rawValue) r.exclusiveOrInPlace(other) return r } } /// `OptionSetType` requirements for which default implementations are /// supplied when `Element == Self`, which is the default. /// /// - Note: A type conforming to `OptionSetType` can implement any of /// these initializers or methods, and those implementations will be /// used in lieu of these defaults. extension OptionSetType where Element == Self { /// Returns `true` if `self` contains `member`. /// /// - Equivalent to `self.intersect([member]) == [member]` @warn_unused_result public func contains(member: Self) -> Bool { return self.isSupersetOf(member) } /// If `member` is not already contained in `self`, insert it. /// /// - Equivalent to `self.unionInPlace([member])` /// - Postcondition: `self.contains(member)` public mutating func insert(member: Element) { self.unionInPlace(member) } /// If `member` is contained in `self`, remove and return it. /// Otherwise, return `nil`. /// /// - Postcondition: `self.intersect([member]).isEmpty` public mutating func remove(member: Element) -> Element? { let r = isSupersetOf(member) ? Optional(member) : nil self.subtractInPlace(member) return r } } /// `OptionSetType` requirements for which default implementations are /// supplied when `RawValue` conforms to `BitwiseOperationsType`, /// which is the usual case. Each distinct bit of an option set's /// `.rawValue` corresponds to a disjoint element of the option set. /// /// - `union` is implemented as a bitwise "or" (`|`) of `rawValue`s /// - `intersection` is implemented as a bitwise "and" (`|`) of `rawValue`s /// - `exclusiveOr` is implemented as a bitwise "exclusive or" (`^`) of `rawValue`s /// /// - Note: A type conforming to `OptionSetType` can implement any of /// these initializers or methods, and those implementations will be /// used in lieu of these defaults. extension OptionSetType where RawValue : BitwiseOperationsType { /// Create an empty instance. /// /// - Equivalent to `[] as Self` public init() { self.init(rawValue: .allZeros) } /// Insert all elements of `other` into `self`. /// /// - Equivalent to replacing `self` with `self.union(other)`. /// - Postcondition: `self.isSupersetOf(other)` public mutating func unionInPlace(other: Self) { self = Self(rawValue: self.rawValue | other.rawValue) } /// Remove all elements of `self` that are not also present in /// `other`. /// /// - Equivalent to replacing `self` with `self.intersect(other)` /// - Postcondition: `self.isSubsetOf(other)` public mutating func intersectInPlace(other: Self) { self = Self(rawValue: self.rawValue & other.rawValue) } /// Replace `self` with a set containing all elements contained in /// either `self` or `other`, but not both. /// /// - Equivalent to replacing `self` with `self.exclusiveOr(other)` public mutating func exclusiveOrInPlace(other: Self) { self = Self(rawValue: self.rawValue ^ other.rawValue) } } @available(*, unavailable, renamed="OptionSetType") public typealias RawOptionSetType = OptionSetType
apache-2.0
c0494f8e21b9eb7a6557c4b6f2641c3a
37.554217
83
0.675469
4.196721
false
false
false
false
DianQK/RxExample
RxZhihuDaily/AppDelegate.swift
1
2078
// // AppDelegate.swift // RxZhihuDaily // // Created by 宋宋 on 16/2/11. // Copyright © 2016年 DianQK. All rights reserved. // import UIKit import RxSwift import RxCocoa import SWRevealViewController @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let disposeBag = DisposeBag() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { ZhihuDailyProvider.request(.StartImage) .mapObject(LaunchImageModel) .subscribeNext { NSUserDefaults.standardUserDefaults().setURL(NSURL(string: $0.img), forKey: Config.Launch.launchImageKey) } .addDisposableTo(disposeBag) window = UIWindow(frame: UIScreen.mainScreen().bounds) let mainViewController = UIStoryboard(name: .Main).instantiateViewControllerWithClass(MainTableViewController) let sideViewController = UIStoryboard(name: .Side).instantiateViewControllerWithClass(SideViewController) let navgationController = UINavigationController(rootViewController: mainViewController) let revealController = SWRevealViewController(rearViewController: sideViewController, frontViewController: navgationController) revealController.toggleAnimationType = .EaseOut revealController.frontViewShadowOffset = CGSizeZero revealController.frontViewShadowOpacity = 0 revealController.frontViewShadowRadius = 0 revealController.rearViewRevealWidth = 225 window?.rootViewController = revealController window?.makeKeyAndVisible() let navigationBarAppearance = UINavigationBar.appearance() let textAttributes = [NSForegroundColorAttributeName: Config.Color.white] navigationBarAppearance.barTintColor = Config.Color.white navigationBarAppearance.tintColor = Config.Color.white navigationBarAppearance.titleTextAttributes = textAttributes return true } }
mit
b2111a0d3870ae3701017a70b25a7af7
38.075472
135
0.731531
5.900285
false
true
false
false
ivlasov/EvoShare
EvoShareSwift/MyBalanceController.swift
2
2424
// // MyBalanceController.swift // EvoShareSwift // // Created by Ilya Vlasov on 1/23/15. // Copyright (c) 2015 mtu. All rights reserved. // import Foundation import UIKit class MyBalanceController : UIViewController, ConnectionManagerDelegate { @IBOutlet weak var fullBalance: UILabel! @IBOutlet weak var fullBalanceCurrency: UILabel! @IBOutlet weak var verifiedBalance: UILabel! @IBOutlet weak var verifiedBalanceCurrency: UILabel! override func viewDidLoad() { super.viewDidLoad() ConnectionManager.sharedInstance.delegate = self requestData() let iconImg = UIImage(named: "menu") let menuBtn = UIBarButtonItem(image: iconImg, style: UIBarButtonItemStyle.Plain, target: self, action: "toogle:") self.parentViewController?.navigationItem.setRightBarButtonItem(menuBtn, animated: true) } override func didReceiveMemoryWarning() { // } func toogle(sender: UIBarButtonItem) { toggleSideMenuView() } func requestData() { let locale = NSLocale.currentLocale() let countryCode = locale.objectForKey(NSLocaleCountryCode) as! String let promoListRequest = ["UID":EVOUidSingleton.sharedInstance.userID(),"LOC":countryCode, "DBG":true] as Dictionary<String,AnyObject> let params = ["RQS":promoListRequest, "M": 216] as Dictionary<String,AnyObject> var err: NSError? let finalJSONData = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: &err) let stringJSON : String = NSString(data: finalJSONData!, encoding: NSUTF8StringEncoding)! ConnectionManager.sharedInstance.socket.writeString(stringJSON) } } extension MyBalanceController : ConnectionManagerDelegate { func connectionManagerDidRecieveObject(responseObject: AnyObject) { let responseDict : [String:AnyObject] = responseObject as! [String:AnyObject] var fullBalanceText : String = String(format: "%.2f",responseDict["FBL"] as! Double) var verBalanceText : String = String(format: "%.2f",responseDict["VBL"] as! Double) var curr = responseDict["CYR"] as! String self.fullBalance.text = fullBalanceText self.verifiedBalance.text = verBalanceText self.fullBalanceCurrency.text = curr self.verifiedBalanceCurrency.text = curr } }
unlicense
51b675c0c2e3d974e0eba886ff2b99f1
38.112903
140
0.697195
4.715953
false
false
false
false
100mango/SwiftCssParser
SwiftCssParser/SwiftCssTheme.swift
1
2479
// // SwiftCssTheme.swift // SwiftCssParser // // Created by Mango on 2017/6/3. // Copyright © 2017年 Mango. All rights reserved. // import UIKit public class SwiftCssTheme { public static let updateThemeNotification = Notification.Name("SwiftCSSThemeUpdate") public enum Theme { case day case night } public static var theme: Theme = .day { didSet { switch theme { case .day: self.themeCSS = SwiftCSS(CssFileURL: URL.CssURL(name: "day")) case .night: self.themeCSS = SwiftCSS(CssFileURL: URL.CssURL(name: "night")) } NotificationCenter.default.post(name: updateThemeNotification, object: nil) } } public static var themeCSS = SwiftCSS(CssFileURL: URL.CssURL(name: "day")) } private extension URL { static func CssURL(name:String) -> URL { return Bundle.main.url(forResource: name, withExtension: "css")! } } extension UIView { private struct AssociatedKeys { static var selector = "themeColorSelector" static var key = "themeColorKey" } var backgroundColorCSS: (selector: String,key: String) { get { guard let selector = objc_getAssociatedObject(self, &AssociatedKeys.selector) as? String else { return ("","") } guard let key = objc_getAssociatedObject(self, &AssociatedKeys.key) as? String else { return ("","") } return (selector,key) } set { let selector = newValue.selector let key = newValue.key objc_setAssociatedObject(self, &AssociatedKeys.selector, selector, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) objc_setAssociatedObject(self, &AssociatedKeys.key, key, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) NotificationCenter.default.addObserver(self, selector: #selector(_cssUpdateBackgroundColor), name: SwiftCssTheme.updateThemeNotification, object: nil) //set css and update backgroundColor _cssUpdateBackgroundColor() } } @objc private dynamic func _cssUpdateBackgroundColor() { self.backgroundColor = SwiftCssTheme.themeCSS.color(selector: self.backgroundColorCSS.selector, key: self.backgroundColorCSS.key) } }
mit
cc9fe173b2c7b7f2b32ec46462991f80
28.47619
162
0.596527
4.752399
false
false
false
false
RobinFalko/Ubergang
Ubergang/Tween/CGPointTween.swift
2
601
// // CGPointTween.swift // Ubergang // // Created by Robin Frielingsdorf on 14/01/16. // Copyright © 2016 Robin Falko. All rights reserved. // import Foundation open class CGPointTween: UTween<CGPoint> { var currentValue = CGPoint() override func compute(_ value: Double) -> CGPoint { _ = super.compute(value) let from = self.fromC() let to = self.toC() currentValue.x = from.x + (to.x - from.x) * CGFloat(value) currentValue.y = from.y + (to.y - from.y) * CGFloat(value) return currentValue } }
apache-2.0
05ab4ad06ef7bc9cf76c4c8b959c166b
22.076923
66
0.58
3.680982
false
false
false
false
indexsky/ShiftPoint
ShiftPoint/ShiftPoint/Enemy.swift
2
2110
// // Enemy.swift // ShiftPoint // // Created by Ashton Wai on 5/7/16. // Copyright © 2016 Ashton Wai & Zachary Bebel. All rights reserved. // import SpriteKit class Enemy : SKShapeNode { var size: CGSize var scorePoints: Int var hitPoints: Int var typeColor: SKColor var forward: CGPoint = CGPoint(x: 0.0, y: 1.0) var gameScene: GameScene let scoreSound: SKAction = SKAction.playSoundFileNamed("Score.mp3", waitForCompletion: false) // MARK: - Initialization - init(size: CGSize, scorePoints: Int, hitPoints: Int, typeColor: SKColor, gameScene: GameScene) { self.size = size self.scorePoints = scorePoints self.hitPoints = hitPoints self.typeColor = typeColor self.gameScene = gameScene super.init() gameScene.numOfEnemies += 1 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Particles - func explosion() -> SKEmitterNode { let emitter = SKEmitterNode(fileNamed: "Explosion")! emitter.particleColorSequence = nil emitter.particleColorBlendFactor = 1.0 emitter.particleColor = typeColor emitter.position = self.position emitter.zPosition = Config.GameLayer.Animation return emitter } func scoreMarker() -> SKLabelNode { let scoreMarker = SKLabelNode(fontNamed: Config.Font.MainFont) scoreMarker.fontColor = UIColor.cyan scoreMarker.fontSize = 30 scoreMarker.text = "\(scorePoints)" scoreMarker.position = self.position scoreMarker.zPosition = Config.GameLayer.Sprite return scoreMarker } // MARK: - Event Handlers - func move() { fatalError("Must Override") } func onHit(_ damage: Int) -> Int { hitPoints -= damage if hitPoints <= 0 { onDestroy() } return hitPoints } func onDestroy() { gameScene.numOfEnemies -= 1 self.removeFromParent() } }
mit
4ce84e53fdf382f0c2b537869e3f7a21
26.38961
100
0.613561
4.487234
false
false
false
false
Mashape/httpsnippet
test/fixtures/output/swift/nsurlsession/custom-method.swift
2
578
import Foundation let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) request.httpMethod = "PROPFIND" let session = URLSession.shared let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) dataTask.resume()
mit
6de3a73223408642550f30dee0251ed5
31.111111
116
0.634948
4.624
false
false
false
false
khizkhiz/swift
test/SILGen/optional.swift
2
3507
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s func testCall(f: (() -> ())?) { f?() } // CHECK: sil hidden @{{.*}}testCall{{.*}} // CHECK: bb0([[T0:%.*]] : $Optional<() -> ()>): // CHECK: [[T1:%.*]] = select_enum %0 // CHECK-NEXT: cond_br [[T1]], bb1, bb3 // If it does, project and load the value out of the implicitly unwrapped // optional... // CHECK: bb1: // CHECK-NEXT: [[FN0:%.*]] = unchecked_enum_data %0 : $Optional<() -> ()>, #Optional.some!enumelt.1 // ...unnecessarily reabstract back to () -> ()... // CHECK: [[T0:%.*]] = function_ref @_TTRXFo_iT__iT__XFo___ : $@convention(thin) (@owned @callee_owned (@in ()) -> @out ()) -> () // CHECK-NEXT: [[FN1:%.*]] = partial_apply [[T0]]([[FN0]]) // .... then call it // CHECK-NEXT: apply [[FN1]]() // CHECK: br bb2( // (first nothing block) // CHECK: bb3: // CHECK-NEXT: enum $Optional<()>, #Optional.none!enumelt // CHECK-NEXT: br bb2 func testAddrOnlyCallResult<T>(f: (()->T)?) { var f = f var x = f?() } // CHECK-LABEL: sil hidden @{{.*}}testAddrOnlyCallResult{{.*}} : $@convention(thin) <T> (@owned Optional<() -> T>) -> () // CHECK: bb0([[T0:%.*]] : $Optional<() -> T>): // CHECK: [[F:%.*]] = alloc_box $Optional<() -> T>, var, name "f" // CHECK-NEXT: [[PBF:%.*]] = project_box [[F]] // CHECK: store [[T0]] to [[PBF]] // CHECK-NEXT: [[X:%.*]] = alloc_box $Optional<T>, var, name "x" // CHECK-NEXT: [[PBX:%.*]] = project_box [[X]] // CHECK-NEXT: [[TEMP:%.*]] = init_enum_data_addr [[PBX]] // Check whether 'f' holds a value. // CHECK: [[T1:%.*]] = select_enum_addr [[PBF]] // CHECK-NEXT: cond_br [[T1]], bb1, bb3 // If so, pull out the value... // CHECK: bb1: // CHECK-NEXT: [[T1:%.*]] = unchecked_take_enum_data_addr [[PBF]] // CHECK-NEXT: [[T0:%.*]] = load [[T1]] // CHECK-NEXT: strong_retain // ...evaluate the rest of the suffix... // CHECK-NEXT: function_ref // CHECK-NEXT: [[THUNK:%.*]] = function_ref @{{.*}} : $@convention(thin) <τ_0_0> (@owned @callee_owned (@in ()) -> @out τ_0_0) -> @out τ_0_0 // CHECK-NEXT: [[T1:%.*]] = partial_apply [[THUNK]]<T>([[T0]]) // CHECK-NEXT: apply [[T1]]([[TEMP]]) // ...and coerce to T? // CHECK-NEXT: inject_enum_addr [[PBX]] {{.*}}some // CHECK-NEXT: br bb2 // Continuation block. // CHECK: bb2 // CHECK-NEXT: strong_release [[X]] // CHECK-NEXT: strong_release [[F]] // CHECK-NEXT: release_value %0 // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return [[T0]] : $() // Nothing block. // CHECK: bb3: // CHECK-NEXT: inject_enum_addr [[PBX]] {{.*}}none // CHECK-NEXT: br bb2 // <rdar://problem/15180622> func wrap<T>(x: T) -> T? { return x } // CHECK-LABEL: sil hidden @_TF8optional16wrap_then_unwrap func wrap_then_unwrap<T>(x: T) -> T { // CHECK: [[FORCE:%.*]] = function_ref @_TFs26_stdlib_Optional_unwrappedurFGSqx_x // CHECK: apply [[FORCE]]<{{.*}}>(%0, {{%.*}}) return wrap(x)! } // CHECK-LABEL: sil hidden @_TF8optional10tuple_bind func tuple_bind(x: (Int, String)?) -> String? { return x?.1 // CHECK: cond_br {{%.*}}, [[NONNULL:bb[0-9]+]], [[NULL:bb[0-9]+]] // CHECK: [[NONNULL]]: // CHECK: [[STRING:%.*]] = tuple_extract {{%.*}} : $(Int, String), 1 // CHECK-NOT: release_value [[STRING]] } // rdar://21883752 - We were crashing on this function because the deallocation happened // out of scope. // CHECK-LABEL: sil hidden @_TF8optional16crash_on_deallocFTGVs10DictionarySiGSaSi___T_ func crash_on_dealloc(dict : [Int : [Int]] = [:]) { var dict = dict dict[1]?.append(2) }
apache-2.0
9af21a2701a0ddfc7fff7b191189dfdd
36.276596
140
0.559075
2.97201
false
false
false
false
ivanbruel/MarkdownKit
MarkdownKit/Sources/Common/Elements/Header/MarkdownHeader.swift
1
1278
// // MarkdownHeader.swift // Pods // // Created by Ivan Bruel on 18/07/16. // // import Foundation open class MarkdownHeader: MarkdownLevelElement { fileprivate static let regex = "^(#{1,%@})\\s*(.+)$" open var maxLevel: Int open var font: MarkdownFont? open var color: MarkdownColor? open var fontIncrease: Int open var regex: String { let level: String = maxLevel > 0 ? "\(maxLevel)" : "" return String(format: MarkdownHeader.regex, level) } public init(font: MarkdownFont? = MarkdownHeader.defaultFont, maxLevel: Int = 0, fontIncrease: Int = 2, color: MarkdownColor? = nil) { self.maxLevel = maxLevel self.font = font self.color = color self.fontIncrease = fontIncrease } open func formatText(_ attributedString: NSMutableAttributedString, range: NSRange, level: Int) { attributedString.deleteCharacters(in: range) } open func attributesForLevel(_ level: Int) -> [NSAttributedString.Key: AnyObject] { var attributes = self.attributes if let font = font { let headerFontSize: CGFloat = font.pointSize + 4 + (-1 * CGFloat(level) * CGFloat(fontIncrease)) attributes[NSAttributedString.Key.font] = font.withSize(headerFontSize).bold() } return attributes } }
mit
23359083caeb366d40d67e01e93e33dc
27.4
104
0.673709
4.057143
false
false
false
false
gyro-n/PaymentsIos
GyronPayments/Classes/Resources/LedgerResource.swift
1
2833
// // LedgerResource.swift // GyronPayments // // Created by Ye David on 11/18/16. // Copyright © 2016 gyron. All rights reserved. // import Foundation import PromiseKit /** LedgerListRequestData is a class that defines the request pararmeters that is used to get a list of ledger objects. */ open class LedgerListRequestData: ExtendedAnyObject, RequestDataDelegate, SortRequestDelegate, PaginationRequestDelegate { /** The sort order for the list (ASC or DESC) */ public var sortOrder: String? /** The property name to sort by */ public var sortBy: String? /** The desired page no */ public var page: Int? /** The desired page size of the returning data set */ public var pageSize: Int? /** Get all of the ledgers */ public var all: Bool? public var from: String? public var to: String? public var min: Int? public var max: Int? /** The currency of the ledger */ public var currency: String? public init(all: Bool? = nil, from: String? = nil, to: String? = nil, min: Int? = nil, max: Int? = nil, currency: String? = nil, sortOrder: String? = nil, sortBy: String? = "created_on", page: Int? = nil, pageSize: Int? = nil) { self.all = all self.from = from self.to = to self.min = min self.max = max self.currency = currency self.sortOrder = sortOrder self.sortBy = sortBy self.page = page self.pageSize = pageSize } public func convertToMap() -> RequestData { return convertToRequestData() } } /** The LedgerResource class is used to perform operations related to the management of transfer ledgers. */ open class LedgerResource: BaseResource { /** The base root path for the request url */ let basePath: String = "/transfers/:transferId/ledgers" ///--------------------------- /// @name Routes ///--------------------------- /** Lists the ledgers available based on the transfer id. @param transferId the transfer id @param data the parameters to be passed to the request @param callback the callback function to be called when the request is completed @return A promise object with the Ledgers list */ public func list(transferId: String, data: LedgerListRequestData?, callback: ResponseCallback<Ledgers>?) -> Promise<Ledgers> { let routePath: String = self.getRoutePath(id: nil, basePath: basePath, pathParams: [(":transferId", transferId)]) return self.runRoute(requiredParams: [], method: HttpProtocol.HTTPMethod.GET, path: routePath, pathParams: nil, data: data, callback: callback) } }
mit
4ad5651d33368e25acd315bf25cd5605
27.897959
151
0.610523
4.363636
false
false
false
false
jspahrsummers/RxSwift
RxSwift/Observable.swift
1
12139
// // Observable.swift // RxSwift // // Created by Justin Spahr-Summers on 2014-06-25. // Copyright (c) 2014 GitHub. All rights reserved. // import Foundation /// A push-driven stream that sends the same values to all observers. class Observable<T> { @final let _queue = dispatch_queue_create("com.github.ReactiveCocoa.Observable", DISPATCH_QUEUE_CONCURRENT) @final var _current: Box<T>? = nil @final var _observers: Box<SinkOf<T>>[] = [] /// The current (most recent) value of the Observable. var current: T { get { var value: T? = nil dispatch_sync(_queue) { value = self._current } return value! } } /// Initializes an Observable that will run the given action immediately, to /// observe all changes. /// /// `generator` _must_ yield at least one value synchronously, as /// Observables can never have a null current value. init(generator: SinkOf<T> -> ()) { generator(SinkOf { value in dispatch_barrier_sync(self._queue) { self._current = Box(value) for sinkBox in self._observers { sinkBox.value.put(value) } } }) assert(_current != nil) } /// Initializes an Observable with the given default value, and an action to /// perform to begin observing future changes. convenience init(initialValue: T, generator: SinkOf<T> -> ()) { self.init(generator: { sink in sink.put(initialValue) return generator(sink) }) } /// Creates a repeating timer of the given interval, sending updates on the /// given scheduler. @final class func interval(interval: NSTimeInterval, onScheduler scheduler: RepeatableScheduler, withLeeway leeway: NSTimeInterval = 0) -> Observable<NSDate> { let startDate = NSDate() return Observable<NSDate>(initialValue: startDate) { sink in scheduler.scheduleAfter(startDate.dateByAddingTimeInterval(interval), repeatingEvery: interval, withLeeway: leeway) { sink.put(NSDate()) } return () } } /// Notifies `observer` about all changes to the receiver's value. /// /// Returns a Disposable which can be disposed of to stop notifying /// `observer` of future changes. @final func observe<S: Sink where S.Element == T>(observer: S) -> Disposable { let box = Box(SinkOf<T>(observer)) dispatch_barrier_sync(_queue) { self._observers.append(box) box.value.put(self._current!) } return ActionDisposable { dispatch_barrier_async(self._queue) { self._observers = removeObjectIdenticalTo(box, fromArray: self._observers) } } } /// Convenience function to invoke observe() with a Sink that will pass /// values to the given closure. @final func observe(observer: T -> ()) -> Disposable { return observe(SinkOf(observer)) } /// Creates an Observable that will always have the same value. @final class func constant(value: T) -> Observable<T> { return Observable { sink in sink.put(value) } } /// Resolves all Optional values in the stream, ignoring any that are `nil`. /// /// evidence - Used to prove to the typechecker that the receiver is /// a stream of optionals. Simply pass in the `identity` /// function. /// initialValue - A default value for the returned stream, in case the /// receiver's current value is `nil`, which would otherwise /// result in a null value for the returned stream. @final func ignoreNil<U>(evidence: Observable<T> -> Observable<U?>, initialValue: U) -> Observable<U> { return Observable<U>(initialValue: initialValue) { sink in evidence(self).observe { maybeValue in if let value = maybeValue { sink.put(value) } } return () } } /// Merges an Observable of Observables into a single stream, biased toward /// the Observables added earlier. /// /// evidence - Used to prove to the typechecker that the receiver is /// a stream-of-streams. Simply pass in the `identity` function. /// /// Returns an Observable that will forward changes from the original streams /// as they arrive, starting with earlier ones. @final func merge<U>(evidence: Observable<T> -> Observable<Observable<U>>) -> Observable<U> { return Observable<U> { sink in let streams = Atomic<Observable<U>[]>([]) evidence(self).observe { stream in streams.modify { (var arr) in arr.append(stream) return arr } stream.observe(sink) } } } /// Switches on an Observable of Observables, forwarding values from the /// latest inner stream. /// /// evidence - Used to prove to the typechecker that the receiver is /// a stream-of-streams. Simply pass in the `identity` function. /// /// Returns an Observable that will forward changes only from the latest /// Observable sent upon the receiver. @final func switchToLatest<U>(evidence: Observable<T> -> Observable<Observable<U>>) -> Observable<U> { return Observable<U> { sink in let latestDisposable = SerialDisposable() evidence(self).observe { stream in latestDisposable.innerDisposable = nil latestDisposable.innerDisposable = stream.observe(sink) } } } /// Maps each value in the stream to a new value. @final func map<U>(f: T -> U) -> Observable<U> { return Observable<U> { sink in self.observe { value in sink.put(f(value)) } return () } } /// Combines all the values in the stream, forwarding the result of each /// intermediate combination step. @final func scan<U>(initialValue: U, _ f: (U, T) -> U) -> Observable<U> { let previous = Atomic(initialValue) return Observable<U> { sink in self.observe { value in let newValue = f(previous.value, value) sink.put(newValue) previous.value = newValue } return () } } /// Returns a stream that will yield the first `count` values from the /// receiver, where `count` is greater than zero. @final func take(count: Int) -> Observable<T> { assert(count > 0) let soFar = Atomic(0) return Observable { sink in let selfDisposable = SerialDisposable() selfDisposable.innerDisposable = self.observe { value in let orig = soFar.modify { $0 + 1 } if orig < count { sink.put(value) } else { selfDisposable.dispose() } } } } /// Returns a stream that will yield values from the receiver while `pred` /// remains `true`, starting with `initialValue` (in case the predicate /// fails on the receiver's current value). @final func takeWhile(initialValue: T, _ pred: T -> Bool) -> Observable<T> { return Observable(initialValue: initialValue) { sink in let selfDisposable = SerialDisposable() selfDisposable.innerDisposable = self.observe { value in if pred(value) { sink.put(value) } else { selfDisposable.dispose() } } } } /// Combines each value in the stream with its preceding value, starting /// with `initialValue`. @final func combinePrevious(initialValue: T) -> Observable<(T, T)> { let previous = Atomic(initialValue) return Observable<(T, T)> { sink in self.observe { value in let orig = previous.swap(value) sink.put((orig, value)) } return () } } /// Returns a stream that will replace the first `count` values from the /// receiver with `nil`, then forward everything afterward. @final func skip(count: Int) -> Observable<T?> { let soFar = Atomic(0) return skipWhile { _ in let orig = soFar.modify { $0 + 1 } return orig < count } } /// Returns a stream that will replace values from the receiver with `nil` /// while `pred` remains `true`, then forward everything afterward. @final func skipWhile(pred: T -> Bool) -> Observable<T?> { return Observable<T?>(initialValue: nil) { sink in let skipping = Atomic(true) self.observe { value in if skipping.value && pred(value) { sink.put(nil) } else { skipping.value = false sink.put(value) } } return () } } /// Buffers values yielded by the receiver, preserving them for future /// enumeration. /// /// capacity - If not nil, the maximum number of values to buffer. If more /// are received, the earliest values are dropped and won't be /// enumerated over in the future. /// /// Returns an Enumerable over the buffered values, and a Disposable which /// can be used to cancel all further buffering. @final func buffer(capacity: Int? = nil) -> (Enumerable<T>, Disposable) { let buffer = EnumerableBuffer<T>(capacity: capacity) let observationDisposable = self.observe { value in buffer.put(.Next(Box(value))) } let bufferDisposable = ActionDisposable { observationDisposable.dispose() // FIXME: This violates the buffer size, since it will now only // contain N - 1 values. buffer.put(.Completed) } return (buffer, bufferDisposable) } /// Preserves only the values of the stream that pass the given predicate, /// starting with `initialValue` (in case the predicate fails on the /// receiver's current value). @final func filter(initialValue: T, pred: T -> Bool) -> Observable<T> { return Observable(initialValue: initialValue) { sink in self.observe { value in if pred(value) { sink.put(value) } } return () } } /// Skips all consecutive, repeating values in the stream, forwarding only /// the first occurrence. /// /// evidence - Used to prove to the typechecker that the receiver contains /// values which are `Equatable`. Simply pass in the `identity` /// function. @final func skipRepeats<U: Equatable>(evidence: Observable<T> -> Observable<U>) -> Observable<U> { return Observable<U> { sink in let maybePrevious = Atomic<U?>(nil) evidence(self).observe { current in if let previous = maybePrevious.swap(current) { if current == previous { return } } sink.put(current) } return () } } /// Combines the receiver with the given stream, forwarding the latest /// updates to either. /// /// Returns an Observable which will send a new value whenever the receiver /// or `stream` changes. @final func combineLatestWith<U>(stream: Observable<U>) -> Observable<(T, U)> { return Observable<(T, U)> { sink in // FIXME: This implementation is probably racey. self.observe { value in sink.put(value, stream.current) } stream.observe { value in sink.put(self.current, value) } } } /// Forwards the current value from the receiver whenever `sampler` sends /// a value. @final func sampleOn<U>(sampler: Observable<U>) -> Observable<T> { return Observable { sink in sampler.observe { _ in sink.put(self.current) } return () } } /// Delays values by the given interval, forwarding them on the given /// scheduler. /// /// Returns an Observable that will default to `nil`, then send the /// receiver's values after injecting the specified delay. @final func delay(interval: NSTimeInterval, onScheduler scheduler: Scheduler) -> Observable<T?> { return Observable<T?>(initialValue: nil) { sink in self.observe { value in scheduler.scheduleAfter(NSDate(timeIntervalSinceNow: interval)) { sink.put(value) } return () } return () } } /// Yields all values on the given scheduler, instead of whichever /// scheduler they originally changed upon. /// /// Returns an Observable that will default to `nil`, then send the /// receiver's values after being scheduled. @final func deliverOn(scheduler: Scheduler) -> Observable<T?> { return Observable<T?>(initialValue: nil) { sink in self.observe { value in scheduler.schedule { sink.put(value) } return () } return () } } /// Blocks indefinitely, waiting for the given predicate to be true. /// /// Returns the first value that passes. @final func firstPassingTest(pred: T -> Bool) -> T { let cond = NSCondition() cond.name = "com.github.ReactiveCocoa.Observable.firstPassingTest" var matchingValue: T? = nil observe { value in if !pred(value) { return } withLock(cond) { () -> () in matchingValue = value cond.signal() } } return withLock(cond) { while matchingValue == nil { cond.wait() } return matchingValue! } } }
mit
9bd2bac4667293ec6c283e97147be54d
27.833729
160
0.669248
3.63552
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Characteristics/Characteristic.TargetVerticalTiltAngle.swift
1
2121
import Foundation public extension AnyCharacteristic { static func targetVerticalTiltAngle( _ value: Int = -90, permissions: [CharacteristicPermission] = [.read, .write, .events], description: String? = "Target Vertical Tilt Angle", format: CharacteristicFormat? = .int, unit: CharacteristicUnit? = .arcdegrees, maxLength: Int? = nil, maxValue: Double? = 90, minValue: Double? = -90, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.targetVerticalTiltAngle( 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 targetVerticalTiltAngle( _ value: Int = -90, permissions: [CharacteristicPermission] = [.read, .write, .events], description: String? = "Target Vertical Tilt Angle", format: CharacteristicFormat? = .int, unit: CharacteristicUnit? = .arcdegrees, maxLength: Int? = nil, maxValue: Double? = 90, minValue: Double? = -90, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<Int> { GenericCharacteristic<Int>( type: .targetVerticalTiltAngle, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
mit
e969b21499f52dbf7bc757e65bd68eae
33.770492
75
0.585573
5.276119
false
false
false
false
asbhat/stanford-ios10-apps
Calculator/Calculator/CalculatorViewController.swift
1
7010
// // CalculatorViewController.swift // Calculator // // Created by Aditya Bhat on 6/5/17. // Copyright © 2017 Aditya Bhat. 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 UIKit class CalculatorViewController: UIViewController { @IBOutlet weak var display: UILabel! @IBOutlet weak var history: UILabel! @IBOutlet weak var mValue: UILabel! @IBOutlet weak var undoBackspace: UIButton! @IBOutlet weak var graph: UIButton! override var prefersStatusBarHidden: Bool { return false } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: animated) } override func viewDidDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: animated) } private let displayFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.minimumIntegerDigits = 1 return formatter }() private struct DisplayFormat { static let maximumDecimalPlaces = 6 } private var brain = CalculatorBrain() private var userIsInTheMiddleOfTyping = false { willSet { if newValue { UIView.performWithoutAnimation { undoBackspace.setTitle("⌫", for: .normal) undoBackspace.layoutIfNeeded() } } else { UIView.performWithoutAnimation { undoBackspace.setTitle("Undo", for: .normal) undoBackspace.layoutIfNeeded() } } } } private var variables = [String : Double]() @IBAction func touchDigit(_ sender: UIButton) { let digit = sender.currentTitle! if userIsInTheMiddleOfTyping { let textCurrentlyInDisplay = display.text! if !(digit == "." && textCurrentlyInDisplay.contains(".")) { display.text = textCurrentlyInDisplay + digit } } else { display.text = digit == "." ? "0." : digit userIsInTheMiddleOfTyping = true } } private var displayValue: Double { get { return Double(display.text!)! } set { displayFormatter.maximumFractionDigits = newValue.remainder(dividingBy: 1) == 0 ? 0 : DisplayFormat.maximumDecimalPlaces display.text = displayFormatter.string(from: NSNumber(value: newValue)) } } @IBAction func performOperation(_ sender: UIButton) { if userIsInTheMiddleOfTyping { brain.setOperand(displayValue) userIsInTheMiddleOfTyping = false } if let mathematicalSymbol = sender.currentTitle { brain.performOperation(mathematicalSymbol) } evaluateAndUpdate() } @IBAction func clear() { brain.clear() variables.removeAll() evaluateAndUpdate() userIsInTheMiddleOfTyping = false } private func backspace() { if display.text!.count > 1 { display.text = String(display.text!.dropLast()) } else { display.text = "0" userIsInTheMiddleOfTyping = false } } @IBAction func undo() { if userIsInTheMiddleOfTyping { backspace() } else { brain.undo() evaluateAndUpdate() } } @IBAction func setM(_ sender: UIButton) { variables["M"] = displayValue evaluateAndUpdate() userIsInTheMiddleOfTyping = false } @IBAction func useVariable(_ sender: UIButton) { brain.setOperand(variable: sender.currentTitle!) evaluateAndUpdate() } private func evaluateAndUpdate() { let evaluation = brain.evaluate(using: variables) history.text = evaluation.description.isEmpty ? " " : evaluation.description + (evaluation.isPending ? " ..." : " =") if evaluation.result != nil { displayValue = evaluation.result! } else if evaluation.description.isEmpty { displayValue = 0 } if evaluation.errorMessage != nil { display.text = evaluation.errorMessage } updateMValue() updateGraphAbility() } private func updateMValue() { if let m = variables["M"] { displayFormatter.maximumFractionDigits = m.remainder(dividingBy: 1) == 0 ? 0 : DisplayFormat.maximumDecimalPlaces mValue.text = "M=" + displayFormatter.string(from: NSNumber(value: m))! } else { mValue.text = "" } } private var canGraph = false { willSet { UIView.performWithoutAnimation { graph.alpha = newValue ? 1.0 : 0.5 graph.layoutIfNeeded() } } } private func updateGraphAbility() { let evaluation = brain.evaluate(using: ["M": 1]) canGraph = !evaluation.isPending && !evaluation.description.isEmpty && evaluation.errorMessage == nil } override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { if identifier == "graph" { return canGraph } return false } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { var destinationVC = segue.destination if let navigationVC = destinationVC as? UINavigationController { destinationVC = navigationVC.visibleViewController ?? destinationVC } if let graphingVC = destinationVC as? GraphingViewController { let brainCopy = brain // copied so additional changes don't affect the graph let description = brainCopy.evaluate(using: ["M": 1]).description graphingVC.setEquation(description: description) { brainCopy.evaluate(using: ["M": $0] ).result ?? 0 } graphingVC.navigationItem.title = description } } } @IBDesignable extension UIButton { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set (newRadius) { layer.cornerRadius = newRadius layer.masksToBounds = newRadius > 0 } } }
apache-2.0
12bc4ceb1a844097d955f91bdd1325a2
30.995434
132
0.608962
5.194218
false
false
false
false
Raizlabs/ios-template
PRODUCTNAME/app/Pods/Swiftilities/Pod/Classes/Keyboard/Keyboard.swift
1
4237
// // Keyboard.swift // Swiftilities // // Created by Rob Visentin on 2/5/16. // Copyright © 2016 Raizlabs. All rights reserved. // import UIKit /** * A set of abstractions around the keyboard. */ public class Keyboard { public typealias FrameChangeHandler = (CGRect) -> Void fileprivate(set) static var frame: CGRect = .zero fileprivate static var notificationObserver: NSObjectProtocol? fileprivate static let frameObservers = NSMapTable<AnyObject, AnyObject>.weakToStrongObjects() /** Add a keyboard frame observer with associated handler. Perform view changes in the handler to have them tied to the animation characteristics of the keyboard frame changes. - parameter observer: The object that will act as the observer for keyboard frame changes. NOTE: this object is not strongly held, therefore a corresponding call to remove is not required. - parameter animated: Whether or not to animate changes in the handler block alongside the keyboard frame changes. - parameter handler: A block in which to perform view changes. */ public static func addFrameObserver(_ observer: AnyObject, withAnimations animated: Bool = true, handler: @escaping FrameChangeHandler) { frameObservers.setObject(KeyboardHandler(handler: handler, animated: animated), forKey: observer) if notificationObserver == nil { setupObservers() } } /** Remove the object as a keyboard frame observer. NOTE: observer is not strongly held, therefore this method is purely optional. - parameter observer: The object being observed to remove. */ public static func removeFrameObserver(_ observer: AnyObject) { frameObservers.removeObject(forKey: observer) if frameObservers.count == 0 { teardownObservers() } } } extension UIView.AnimationCurve { func animationOptions() -> UIView.AnimationOptions { switch self { case .easeInOut: return .curveEaseInOut case .easeIn: return .curveEaseIn case .easeOut: return .curveEaseOut case .linear: return .curveLinear default: // Some private UIViewAnimationCurve values unknown to the compiler can leak through notifications. return UIView.AnimationOptions(rawValue: UInt(rawValue << 16)) } } } // MARK: - Private private extension Keyboard { static func setupObservers() { notificationObserver = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillChangeFrameNotification, object: nil, queue: .main) { notification -> Void in guard let frameValue: NSValue = (notification as NSNotification).userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return } frame = frameValue.cgRectValue let handlers = frameObservers.objectEnumerator() while let handler = handlers?.nextObject() as? KeyboardHandler<FrameChangeHandler> { if let durationValue = (notification as NSNotification).userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber, handler.animated { let curveValue = ((notification as NSNotification).userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber)?.intValue let curve = curveValue.flatMap(UIView.AnimationCurve.init) ?? .easeInOut UIView.animate(withDuration: durationValue.doubleValue, delay: 0.0, options: curve.animationOptions(), animations: { handler.handler(frame) }, completion: nil) } else { handler.handler(frame) } } } } static func teardownObservers() { if let notificationObserver = notificationObserver { NotificationCenter.default.removeObserver(notificationObserver) self.notificationObserver = nil } } } private final class KeyboardHandler<T> { let handler: T let animated: Bool init(handler: T, animated: Bool) { self.handler = handler self.animated = animated } }
mit
58f3975cb3700fd64c1bc11cc312897b
35.517241
193
0.671152
5.368821
false
false
false
false
mityung/XERUNG
IOS/Xerung/Xerung/CreateDirectoryViewController.swift
1
20797
// // CreateDirectoryViewController.swift // Xerung // // Created by mityung on 23/02/17. // Copyright © 2017 mityung. All rights reserved. // import UIKit class CreateDirectoryViewController: UIViewController, UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate ,UINavigationControllerDelegate, UIImagePickerControllerDelegate , DropDownViewControllerDelegate , UIPopoverPresentationControllerDelegate , UITextViewDelegate { @IBOutlet weak var userImage: UIImageView! @IBOutlet weak var aboutDirectory: UITextView! @IBOutlet weak var privateDirectory: UITextField! @IBOutlet weak var directoryName: UITextField! @IBOutlet weak var tableView: UITableView! @IBOutlet var view3: UIView! @IBOutlet var view2: UIView! @IBOutlet var view1: UIView! var photo = "0" var imagePicker = UIImagePickerController() var playerIndex = [Int]() var countryName = [String]() var countryCode = [String]() var countryPhoneCode = [String]() var tmpTextField:UITextField! override func viewDidLoad() { super.viewDidLoad() self.title = "Create Directory" aboutDirectory.delegate = self privateDirectory.delegate = self directoryName.delegate = self directoryName.autocapitalizationType = .sentences privateDirectory.autocapitalizationType = .sentences aboutDirectory.text = "About Directory" aboutDirectory.textColor = UIColor.lightGray privateDirectory.tag = -2 directoryName.tag = -3 getOffLineData() getContactDetails { (response) in DispatchQueue.main.async(execute: { self.tableView.reloadData() }) } userImage.layer.cornerRadius = userImage.frame.width/2 userImage.layer.masksToBounds = true userImage.layer.borderWidth = 1 userImage.layer.borderColor = themeColor.cgColor userImage.image = UIImage(named: "defaultDirectory") self.tabBarController?.tabBar.isHidden = true // tableView.backgroundView = UIImageView(image: UIImage(named: "backScreen.png")) tableView.separatorStyle = .none self.tableView.estimatedRowHeight = 170; self.tableView.rowHeight = UITableViewAutomaticDimension; /*let backgroundImage = UIImageView(frame: self.view.bounds) backgroundImage.image = UIImage(named: "backScreen.png") self.view.insertSubview(backgroundImage, at: 0)*/ // let image = UIImage(named: "backScreen.png")! //self.view1.backgroundColor = UIColor(patternImage: image ) let btn1 = UIButton(type: .custom) btn1.setImage(UIImage(named: "bar"), for: .normal) btn1.frame = CGRect(x: 0, y: 0, width: 30, height: 30) btn1.addTarget(self, action: #selector(self.sideMenu(_:)), for: .touchUpInside) let item1 = UIBarButtonItem(customView: btn1) self.navigationItem.setLeftBarButton(item1, animated: true) } @IBAction func sideMenu(_ sender: Any) { self.menuContainerViewController.toggleLeftSideMenuCompletion { () -> Void in } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return phoneBook.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "AddMemberCell2", for: indexPath) as! AddMemberCell2 cell.nameLabel.text = phoneBook[indexPath.row].name cell.numberLabel.text = phoneBook[indexPath.row].phone cell.countryText.text = phoneBook[indexPath.row].country cell.countryText.delegate = self cell.countryText.tag = indexPath.row cell.backgroundColor = UIColor.clear cell.selectionStyle = .none if playerIndex.contains(indexPath.row) == true { cell.tickImage.image = UIImage(named: "checked") }else{ cell.tickImage.image = UIImage(named: "uncheck") } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if checkNumber(phoneBook[indexPath.row].phone) == true { if playerIndex.contains(indexPath.row) == true { playerIndex = playerIndex.filter{$0 != indexPath.row} tableView.reloadRows(at: [indexPath], with: .fade) }else{ playerIndex.append(indexPath.row) tableView.reloadRows(at: [indexPath], with: .fade) } }else{ self.showAlert("Alert", message: "Please select valid contact number.") } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } func checkNumber(_ number:String) -> Bool { let num = number.removingWhitespaces() if num.characters.count > 9 && num.characters.count < 14 { return true }else { return false } } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let allowedCharacter = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz?.,/ " let aSet = CharacterSet(charactersIn:allowedCharacter).inverted let compSepByCharInSet = string.components(separatedBy: aSet) let numberFiltered = compSepByCharInSet.joined(separator: "") if string == numberFiltered{ let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string) let numberOfChars = newText.characters.count if textField.tag == -3 { return numberOfChars < 21 }else if textField.tag == -2 { return numberOfChars < 26 }else if textField.tag == -1 { return numberOfChars < 101 }else { return numberOfChars < 51 } }else{ return string == numberFiltered } } func textFieldDidBeginEditing(_ textField: UITextField) { if textField.tag == -3 { view1.backgroundColor = themeColor }else if textField.tag == -2 { view2.backgroundColor = themeColor } } @available(iOS 10.0, *) func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) { if textField.tag == -3 { view1.backgroundColor = UIColor.lightGray if (textField.text?.characters.count)! < 4 { self.showAlert("Alert", message: "Please enter minimum four characters.") } }else if textField.tag == -2 { view2.backgroundColor = UIColor.lightGray } } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" // Recognizes enter key in keyboard { textView.resignFirstResponder() return false } let allowedCharacter = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz?.,/ " let aSet = CharacterSet(charactersIn:allowedCharacter).inverted let compSepByCharInSet = text.components(separatedBy: aSet) let numberFiltered = compSepByCharInSet.joined(separator: "") if text == numberFiltered{ let newText = (textView.text! as NSString).replacingCharacters(in: range, with: text) let numberOfChars = newText.characters.count return numberOfChars < 101 }else{ return text == numberFiltered } } func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { if textView.text == "About Directory" { textView.text = "" textView.textColor = UIColor.black } view3.backgroundColor = themeColor return true } func textViewDidEndEditing(_ textView: UITextView) { if textView.text == "" { textView.text = "About Directory" textView.textColor = UIColor.lightGray } view3.backgroundColor = UIColor.lightGray } @IBAction func createDirectory(_ sender: UIBarButtonItem) { self.view.endEditing(true) if directoryName.text == "" { self.showAlert("Alert", message: "Please enter values in all fields.") return } if privateDirectory.text == "" { self.showAlert("Alert", message: "Please enter values in all fields.") return } if (directoryName.text?.characters.count)! < 4 { self.showAlert("Alert", message: "Please enter minimum four characters.") } if aboutDirectory.text == "About Directory" { aboutDirectory.text = "" } if aboutDirectory.text == "" { self.showAlert("Alert", message: "Please fill all data.") aboutDirectory.text = "About Directory" aboutDirectory.textColor = UIColor.lightGray return } var str = "" for i in 0 ..< playerIndex.count { str = str + phoneBook[playerIndex[i]].name + ":" + self.getNumber(phoneBook[playerIndex[i]].phone.trim() , country:phoneBook[playerIndex[i]].country) + ":" } let count = playerIndex.count * 2 + 3 str = String(count) + ":" + str + name + ":" + mobileNo let sendJson: [String: String] = [ "PGROUPID":"0", "PUID": userID, "PGROUPNAME": directoryName.text! , "PMADEBY":mobileNo , "PDESC": aboutDirectory.text!, "PSTATEID":"0", "PGROUPTYPEVAR":"", "PTAGNAME":privateDirectory.text!, "PGROUPPHOTO":photo, "PCHANGEBYPHONENO":"0", "AFLAG":"0", "AGROUPMEMBERLIST":str ] print(sendJson) if Reachability.isConnectedToNetwork() { startLoader(view: self.view) DataProvider.sharedInstance.getServerData(sendJson, path: "GroupService", successBlock: { (response) in print(response) if response["STATUS"].stringValue == "SUCCESS" { self.sendNotification() self.showAlert("Confirmation", message: "Directory created successfully.") }else if response["STATUS"].stringValue == "Already exist" { self.showAlert("Alert", message: "Directory already exist.") } stopLoader() }) { (error) in print(error) stopLoader() } }else{ showAlert("Alert", message: "No internet connectivity.") } } func sendNotification() { let sendJson: [String: String] = [ "PPHONENUMBER": mobileNo, "PFLAG": "1", "PPHONETYPE": "0" , ] if Reachability.isConnectedToNetwork() { startLoader(view: self.view) DataProvider.sharedInstance.getServerData(sendJson, path: "sendNotiMSG", successBlock: { (response) in print(response) stopLoader() }) { (error) in print(error) stopLoader() } }else{ showAlert("Alert", message: "No internet connectivity.") } } func getNumber(_ str:String ,country:String ) -> String { let str1 = str.removingWhitespaces() let temp = countryName.index(of: country) if countryPhoneCode[temp!] == "91" { return "+91" + String(str1.characters.suffix(10)) }else{ return countryPhoneCode[temp!] + String(str1.characters.suffix(10)) } } @IBAction func UploadPhoto(_ sender: AnyObject) { let refreshAlert = UIAlertController(title: "Picture", message: title, preferredStyle: UIAlertControllerStyle.alert) refreshAlert.addAction(UIAlertAction(title: "Library", style: .default, handler: { (action: UIAlertAction!) in self.openLibrary() })) refreshAlert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action: UIAlertAction!) in self.openCamera() })) refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action: UIAlertAction!) in })) present(refreshAlert, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController!, didFinishPickingImage image1: UIImage!, editingInfo: NSDictionary!){ self.dismiss(animated: true, completion: { () -> Void in }) let image2 = self.resizeImage(image1, targetSize: CGSize(width: 300.0, height: 300.0)) let imageData = UIImageJPEGRepresentation(image2, 0.5) photo = imageData!.base64EncodedString(options: []) userImage.image = image1 } // take phota using camera func openCamera() { if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.camera; imagePicker.allowsEditing = false self.present(imagePicker, animated: true, completion: nil) } } // take photo from library func openLibrary() { if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.savedPhotosAlbum){ print("Button capture") imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum; imagePicker.allowsEditing = false self.present(imagePicker, animated: true, completion: nil) } } // this method is used to resize the image func resizeImage(_ image: UIImage, targetSize: CGSize) -> UIImage { let size = image.size let widthRatio = targetSize.width / image.size.width let heightRatio = targetSize.height / image.size.height // Figure out what our orientation is, and use that to form the rectangle var newSize: CGSize if(widthRatio > heightRatio) { newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio) } else { newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio) } // This is the rect that we've calculated out and this is what is actually used below let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height) // Actually do the resizing to the rect using the ImageContext stuff UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) image.draw(in: rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } func showAlert(_ title:String,message:String){ let refreshAlert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) refreshAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction!) in if title == "Confirmation" { let storyBoard = UIStoryboard(name: "Main", bundle: nil) as UIStoryboard let mfSideMenuContainer = storyBoard.instantiateViewController(withIdentifier: "MFSideMenuContainerViewController") as! MFSideMenuContainerViewController let dashboard = storyBoard.instantiateViewController(withIdentifier: "Directory_ViewController") as! UITabBarController let leftSideMenuController = storyBoard.instantiateViewController(withIdentifier: "SideMenuViewController") as! SideMenuViewController mfSideMenuContainer.leftMenuViewController = leftSideMenuController mfSideMenuContainer.centerViewController = dashboard let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.window?.rootViewController = mfSideMenuContainer } })) present(refreshAlert, animated: true, completion: nil) } // when click on textfield show the popup for select the subject func dropDown(_ textField:UITextField ) { let selector = countryName let popoverContent = (self.storyboard?.instantiateViewController(withIdentifier: "DropDownViewController"))! as! DropDownViewController popoverContent.delegate = self popoverContent.data = selector let nav = UINavigationController(rootViewController: popoverContent) nav.modalPresentationStyle = UIModalPresentationStyle.popover let popover = nav.popoverPresentationController popoverContent.preferredContentSize = CGSize(width: 300,height: 265) popover!.permittedArrowDirections = .any popover!.delegate = self popover!.sourceView = textField popover!.sourceRect = CGRect(x: textField.frame.width/3, y: 20, width: 0, height: 0) self.present(nav, animated: true, completion: nil) tmpTextField = textField } func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle{ return UIModalPresentationStyle.none } func saveString(_ strText: NSString) { tmpTextField.text = strText as String phoneBook[tmpTextField.tag].country = strText as String } func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { if textField.tag == -1 || textField.tag == -2 || textField.tag == -3 { return true }else{ self.dropDown(textField) return false } } func textFieldDidEndEditing(_ textField: UITextField) { if textField.tag == -3 { if (textField.text?.characters.count)! < 4 { self.showAlert("Alert", message: "Please enter minimum four characters.") } } } func getOffLineData(){ let databasePath = UserDefaults.standard.url(forKey: "DataBasePath")! let contactDB = FMDatabase(path: String(describing: databasePath)) if (contactDB?.open())! { let querySQL = "SELECT * FROM Country " let results:FMResultSet? = contactDB?.executeQuery(querySQL,withArgumentsIn: nil) self.countryName = [] self.countryCode = [] self.countryPhoneCode = [] while((results?.next()) == true){ self.countryName.append(results!.string(forColumn: "countryName")!) self.countryCode.append(results!.string(forColumn: "countryCodeId")!) self.countryPhoneCode.append(results!.string(forColumn: "phoneCountryCode")!) } contactDB?.close() } else { print("Error: \(contactDB?.lastErrorMessage())") } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
a1fe5065e014e8baf2fbf7de02f7ed0e
36.135714
280
0.604684
5.358413
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Transport/URLSession/URLRequest+Convenience.swift
1
3542
// // URLRequest+Convenience.swift // // // Created by Vladislav Fitc on 02/03/2020. // import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif extension URLRequest: Builder {} extension CharacterSet { // Allowed characters taken from [RFC 3986](https://tools.ietf.org/html/rfc3986) (cf. §2 "Characters"): // - unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" // - gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" // - sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" // // ... with these further restrictions: // - ampersand ('&') and equal sign ('=') removed because they are used as delimiters for the parameters; // - question mark ('?') and hash ('#') removed because they mark the beginning and the end of the query string. // - plus ('+') is removed because it is interpreted as a space by Algolia's servers. // static let urlParameterAllowed: CharacterSet = .alphanumerics.union(.init(charactersIn: "-._~:/[]@!$'()*,;")) static let urlPathComponentAllowed: CharacterSet = { var characterSet = CharacterSet() characterSet.formUnion(CharacterSet.urlPathAllowed) characterSet.remove(charactersIn: "/") return characterSet }() } extension URLRequest { subscript(header key: HTTPHeaderKey) -> String? { get { return allHTTPHeaderFields?[key.rawValue] } set(newValue) { setValue(newValue, forHTTPHeaderField: key.rawValue) } } init(command: AlgoliaCommand) { var urlComponents = URLComponents() urlComponents.scheme = "https" urlComponents.percentEncodedPath = command.path.path if let urlParameters = command.requestOptions?.urlParameters { urlComponents.queryItems = urlParameters.map { (key, value) in .init(name: key.rawValue, value: value) } } var request = URLRequest(url: urlComponents.url!) request.httpMethod = command.method.rawValue request.httpBody = command.body if let requestOptions = command.requestOptions { requestOptions.headers.forEach { header in let (value, field) = (header.value, header.key.rawValue) request.setValue(value, forHTTPHeaderField: field) } // If body is set in query parameters, it will override the body passed as parameter to this function if let body = requestOptions.body, !body.isEmpty { let jsonEncodedBody = try? JSONSerialization.data(withJSONObject: body, options: []) request.httpBody = jsonEncodedBody } } request.httpBody = command.body self = request } } extension URLRequest { var credentials: Credentials? { get { guard let appID = applicationID, let apiKey = apiKey else { return nil } return AlgoliaCredentials(applicationID: appID, apiKey: apiKey) } set { guard let newValue = newValue else { applicationID = nil apiKey = nil return } applicationID = newValue.applicationID apiKey = newValue.apiKey } } var applicationID: ApplicationID? { get { return self[header: .applicationID].flatMap(ApplicationID.init) } set { self[header: .applicationID] = newValue?.rawValue } } var apiKey: APIKey? { get { return self[header: .apiKey].flatMap(APIKey.init) } set { do { try setAPIKey(newValue) } catch let error { Logger.error("Couldn't set API key in the request body due to error: \(error)") } } } }
mit
88d7a1992b027429566478eecdaf5444
24.65942
114
0.634284
4.313033
false
false
false
false
narner/AudioKit
Playgrounds/AudioKitPlaygrounds/Playgrounds/Effects.playground/Pages/Auto Wah Wah.xcplaygroundpage/Contents.swift
1
954
//: ## Auto Wah Wah //: One of the most iconic guitar effects is the wah-pedal. //: This playground runs an audio loop of a guitar through an AKAutoWah node. import AudioKitPlaygrounds import AudioKit let file = try AKAudioFile(readFileName: playgroundAudioFiles[0]) let player = try AKAudioPlayer(file: file) player.looping = true var wah = AKAutoWah(player) wah.wah = 1 wah.amplitude = 1 AudioKit.output = wah AudioKit.start() player.play() //: User Interface Set up import AudioKitUI class LiveView: AKLiveViewController { override func viewDidLoad() { addTitle("Auto Wah Wah") addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles)) addView(AKSlider(property: "Wah", value: wah.wah) { sliderValue in wah.wah = sliderValue }) } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
mit
f5173cc476e6da0205e5cc9d1d2e1b13
23.461538
96
0.733753
3.893878
false
false
false
false
clowwindy/firefox-ios
Storage/Storage/SQL/SQLiteReadingList.swift
2
2124
/* 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 /** * The SQLite-backed implementation of the ReadingList protocol. */ public class SQLiteReadingList: ReadingList { let files: FileAccessor let db: BrowserDB let table = ReadingListTable<ReadingListItem>() required public init(files: FileAccessor) { self.files = files self.db = BrowserDB(files: files)! db.createOrUpdate(table) } public func clear(complete: (success: Bool) -> Void) { var err: NSError? = nil db.delete(&err) { (connection, inout err: NSError?) -> Int in return self.table.delete(connection, item: nil, err: &err) } dispatch_async(dispatch_get_main_queue()) { if err != nil { self.debug("Clear failed: \(err!.localizedDescription)") complete(success: false) } else { complete(success: true) } } } public func get(complete: (data: Cursor) -> Void) { var err: NSError? = nil let res = db.query(&err) { connection, err in return self.table.query(connection, options: nil) } dispatch_async(dispatch_get_main_queue()) { complete(data: res) } } public func add(#item: ReadingListItem, complete: (success: Bool) -> Void) { var err: NSError? = nil let inserted = db.insert(&err) { (connection, inout err: NSError?) -> Int in return self.table.insert(connection, item: item, err: &err) } dispatch_async(dispatch_get_main_queue()) { if err != nil { self.debug("Add failed: \(err!.localizedDescription)") } complete(success: err == nil) } } private let debug_enabled = false private func debug(msg: String) { if debug_enabled { println("SQLiteReadingList: " + msg) } } }
mpl-2.0
025d0b3d52913a0e9e910d3495f367f7
30.701493
84
0.574859
4.222664
false
false
false
false
NicolasRenaud/SwiftyPresentation
SwiftyPresentation/Classes/AlertPresentationController.swift
1
1677
// // AlertPresentationController.swift // Presentation // // Created by Nicolas Renaud on 18/05/2017. // Copyright © 2017 NRC. All rights reserved. // import UIKit class AlertPresentationController: SwiftyPresentationController { // MARK: - Properties private var presentationDirection: AnimationDirection private var dismissDirection: AnimationDirection // MARK: - Constructor init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?, presentationDirection: AnimationDirection, dismissDirection: AnimationDirection) { self.presentationDirection = presentationDirection self.dismissDirection = dismissDirection super.init(presentedViewController: presentedViewController, presenting: presentingViewController) } override var frameOfPresentedViewInContainerView : CGRect { var frame: CGRect = .zero if let containerView = containerView { let width = min(containerView.bounds.size.width, self.width) let height = min(containerView.bounds.size.height, self.height) let originX = (containerView.bounds.size.width / 2) - (width / 2) let originY = (containerView.bounds.size.height / 2) - (height / 2) frame = CGRect(x: originX, y: originY, width: width, height: height) let dx = (frame.width == containerView.bounds.size.width) ? 16.0 : 0.0 let dy = (frame.height == containerView.bounds.size.height) ? 16.0 : 0.0 frame = frame.insetBy(dx: CGFloat(dx), dy: CGFloat(dy)) } return frame } }
mit
b23a3afc5ee8b2543fa0b4fb079c3bac
37.976744
190
0.673031
5.017964
false
false
false
false
jackwilsdon/GTFSKit
GTFSKit/CSVParser.swift
1
2012
// // CSVParser.swift // GTFSKit // import Foundation public protocol CSVParsable { static func parse(data: CSVData) -> Self? } public protocol CSVEnumeration: RawRepresentable { static func fromString(value: String) -> Self? static func fromString(defaultValue: Self)(value: String) -> Self? } public extension CSVEnumeration where Self: RawRepresentable, Self.RawValue == Int { public static func fromString(value: String) -> Self? { if let intValue = Int(value) { return Self(rawValue: intValue) } return nil } public static func fromString(defaultValue: Self)(value: String) -> Self? { if let actualValue = fromString(value) { return actualValue } return defaultValue } } public class CSVParser { private let lines: [String] public init(lines: [String]) { self.lines = lines } private func stripWhitespace(value: String) -> String { return value.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } private func getRowValues(line: String) -> [String] { return line.characters.split(",").map(String.init).map(stripWhitespace) } public func parse<T: CSVParsable>(parsable: T.Type) -> [T]? { var instances = [T]() var headings = [String]() for (lineIndex, line) in lines.enumerate() { let values = getRowValues(line) if lineIndex == 0 { headings = values continue } let minLength = min(headings.count, values.count) var lineData = [String: String]() for valueIndex in 0..<minLength { lineData[headings[valueIndex]] = values[valueIndex] } if let instance = parsable.parse(CSVData(data: lineData)) { instances.append(instance) } else { return nil } } return instances } }
gpl-3.0
9b8f778d983dcfd87945137bb00c21f2
25.12987
93
0.591451
4.593607
false
false
false
false
keshavvishwkarma/KVConstraintKit
KVConstraintKit/UIViewControllerExtension.swift
1
7293
// // UIViewControllerExtension.swift // https://github.com/keshavvishwkarma/KVConstraintKit.git // // Distributed under the MIT License. // // Copyright © 2016-2017 Keshav Vishwkarma <[email protected]>. 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. // // #if os(iOS) || os(tvOS) import UIKit @available(iOS 7.0, *) public enum LayoutGuideType { case top, bottom } //********* Define LayoutGuidable protocol *********// @available(iOS 7.0, *) public protocol LayoutGuidable: class { /// TO ADD SINGLE CONSTRAINT static func +(lhs: Self, rhs: (View, LayoutGuideType)) -> NSLayoutConstraint /// TO REMOVE SINGLE CONSTRAINT static func -(lhs: Self, rhs: (View, LayoutGuideType)) -> NSLayoutConstraint? /// TO ACCESS CONSTRAINT BASED ON LAYOUT GUIDE TYPE static func <-(lhs: Self, rhs: (View, LayoutGuideType)) -> NSLayoutConstraint? } // MARK: LayoutGuidable @available(iOS 7.0, *) extension LayoutGuidable where Self: UIViewController { @discardableResult public static func +(lhs: Self, rhs: (View, LayoutGuideType)) -> NSLayoutConstraint { return lhs.applyLayoutGuideConstraint(rhs.0, type: rhs.1) } @discardableResult public static func -(lhs: Self, rhs: (View, LayoutGuideType)) -> NSLayoutConstraint? { guard let appliedConstraint = lhs.accessLayoutGuideConstraint(rhs.0, type: rhs.1) else { return nil } return lhs.view - appliedConstraint } @discardableResult public static func <-(lhs: Self, rhs: (View, LayoutGuideType)) -> NSLayoutConstraint? { return lhs.accessLayoutGuideConstraint(rhs.0, type: rhs.1) } } @available(iOS 7.0, *) extension UIViewController: LayoutGuidable { /// This method is used to access applied Top Layout Guide constraint if layout guide constraint is exist in self.view for v. @discardableResult public final func accessAppliedTopLayoutGuideConstraint(_ fromView: View) -> NSLayoutConstraint? { return accessLayoutGuideConstraint(fromView, type: .top) } /// This method is used to access applied Bottom Layout Guide constraint if layout guide constraint is exist in self.view for v. @discardableResult public final func accessAppliedBottomLayoutGuideConstraint(_ fromView: View) -> NSLayoutConstraint? { return accessLayoutGuideConstraint(fromView, type: .bottom) } /// To add Top layout guide constaint. public final func applyTopLayoutGuideConstraint(_ toView: View, padding p: CGFloat) { applyLayoutGuideConstraint(toView, type: .top).constant = p } /// To add Bottom layout guide constaint. public final func applyBottomLayoutGuideConstraint(_ toView: View, padding p: CGFloat) { applyLayoutGuideConstraint(toView, type: .bottom).constant = p } /// These method is used to remove the Top Layout Guide constraint. But you cann't remove default TopLayoutGuide constraint. public final func removeAppliedTopLayoutGuideConstraint(_ fromView: View) { guard let appliedConstraint = accessLayoutGuideConstraint(fromView, type: .top) else { return } view.removeConstraint(appliedConstraint) } /// These method is used to remove the Bottom Layout Guide constraint. But you cann't remove default BottomLayoutGuide constraint. public final func removeAppliedBottomLayoutGuideConstraint(_ fromView: View) { guard let appliedConstraint = accessLayoutGuideConstraint(fromView, type: .bottom) else { return } view.removeConstraint(appliedConstraint) } } @available(iOS 7.0, *) private extension UIViewController { /// These method is used to generate Top/Bottom Layout Guide constraint final func prepareLayoutGuideConstraint(_ view: View, type t: LayoutGuideType) -> NSLayoutConstraint { switch t { case .top: return NSLayoutConstraint.prepareConstraint(view, attribute: .top, toItem: topLayoutGuide, attribute: .bottom) case .bottom: return NSLayoutConstraint.prepareConstraint(bottomLayoutGuide, attribute: .top, toItem: view, attribute: .bottom) } } /// To add Top/Bottom layout guide constaints final func applyLayoutGuideConstraint(_ view: View, type t: LayoutGuideType)->NSLayoutConstraint { if let appliedConstraint = accessLayoutGuideConstraint(view, type: t) { return appliedConstraint } else { let prepareConstraint = prepareLayoutGuideConstraint(view, type: t) self.view.addConstraint(prepareConstraint) return prepareConstraint } } /// These method is used to access applied LayoutGuide constraint from view of ViewController(self.view) to a specific view(toView). final func accessLayoutGuideConstraint(_ fromView: View, type: LayoutGuideType) -> NSLayoutConstraint? { let layoutGuide : UILayoutSupport = (type == .top) ? topLayoutGuide : bottomLayoutGuide let viewAttribute : LayoutAttribute = (type == .top) ? .top : .bottom; let layoutGuideAttribute : LayoutAttribute = (type == .top) ? .bottom : .top; // Exclude the default constraints and other constraint those can not be layout guide constraints let layoutGuideConstraints = self.view.constraints.filter { return ( ( $0.firstItem === layoutGuide && $0.secondItem === fromView ) || ( $0.firstItem === fromView && $0.secondItem === layoutGuide ) ) }.filter { return !( $0.firstAttribute == $0.secondAttribute ) } for constraint in layoutGuideConstraints { if constraint.firstItem === layoutGuide && constraint.firstAttribute == layoutGuideAttribute && constraint.secondItem === fromView && constraint.secondAttribute == viewAttribute { return constraint } else if constraint.secondItem === layoutGuide && constraint.secondAttribute == layoutGuideAttribute && constraint.firstItem === fromView && constraint.firstAttribute == viewAttribute { return constraint } else { } } return nil } } #endif
mit
d90ebf42781f10e9c1838bfe0809be0f
44.861635
151
0.694323
4.864576
false
false
false
false
opencv/opencv
modules/core/misc/objc/common/FloatVectorExt.swift
2
1235
// // FloatVectorExt.swift // // Created by Giles Payne on 2020/01/04. // import Foundation public extension FloatVector { convenience init(_ array:[Float]) { let data = array.withUnsafeBufferPointer { Data(buffer: $0) } self.init(data:data); } subscript(index: Int) -> Float { get { return self.get(index) } } var array: [Float] { get { var ret = Array<Float>(repeating: 0, count: data.count/MemoryLayout<Float>.stride) _ = ret.withUnsafeMutableBytes { data.copyBytes(to: $0) } return ret } } } extension FloatVector : Sequence { public typealias Iterator = FloatVectorIterator public func makeIterator() -> FloatVectorIterator { return FloatVectorIterator(self) } } public struct FloatVectorIterator: IteratorProtocol { public typealias Element = Float let floatVector: FloatVector var pos = 0 init(_ floatVector: FloatVector) { self.floatVector = floatVector } mutating public func next() -> Float? { guard pos >= 0 && pos < floatVector.length else { return nil } pos += 1 return floatVector.get(pos - 1) } }
apache-2.0
ea3e922ad1670eb6b1d36432d27d5c63
22.301887
94
0.602429
4.273356
false
false
false
false
lokinfey/MyPerfectframework
Examples/Authenticator/Authenticator Client/URLSessionDelegate.swift
1
2125
// // URLSessionDelegate.swift // Authenticator // // Created by Kyle Jessup on 2015-11-12. // Copyright © 2015 PerfectlySoft. All rights reserved. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import Foundation class URLSessionDelegate: NSObject, NSURLSessionDataDelegate { let username: String let password: String let completionHandler:(d:NSData?, res:NSURLResponse?, e:NSError?)->() var data: NSData? var response: NSURLResponse? var suppliedCreds = false init(username: String, password: String, completionHandler: (d:NSData?, res:NSURLResponse?, e:NSError?)->()) { self.username = username self.password = password self.completionHandler = completionHandler } func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { if self.suppliedCreds { completionHandler(.PerformDefaultHandling, nil) } else { self.suppliedCreds = true let cred = NSURLCredential(user: username, password: password, persistence: .ForSession) completionHandler(.UseCredential, cred) } } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { self.data = data } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) { self.response = response completionHandler(NSURLSessionResponseDisposition.Allow) } func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { self.completionHandler(d: self.data, res: self.response, e: error) } }
apache-2.0
4564da77d4203777dd16ede957f3de8e
35
211
0.707627
4.80543
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieCore/Swift/CollectionExtension.swift
1
11441
// // CollectionExtension.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. 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. // extension Sequence { @inlinable public func reduce(_ nextPartialResult: (Element, Element) throws -> Element) rethrows -> Element? { return try self.reduce(nil) { partial, current in try partial.map { try nextPartialResult($0, current) } ?? current } } } extension Sequence { @inlinable public func count(where predicate: (Element) throws -> Bool) rethrows -> Int { return try self.reduce(0) { try predicate($1) ? $0 + 1 : $0 } } } extension MutableCollection { @inlinable public var mutableFirst: Element { get { return self[self.startIndex] } set { self[self.startIndex] = newValue } } } extension MutableCollection where Self: BidirectionalCollection { @inlinable public var mutableLast: Element { get { return self[self.index(before: self.endIndex)] } set { self[self.index(before: self.endIndex)] = newValue } } } extension Collection where SubSequence == Self { @inlinable public mutating func popFirst(_ n: Int) -> SubSequence { precondition(n >= 0, "Can't drop a negative number of elements from a collection") let result = self.prefix(n) self.removeFirst(Swift.min(self.count, n)) return result } } extension BidirectionalCollection where SubSequence == Self { @inlinable public mutating func popLast(_ n: Int) -> SubSequence { precondition(n >= 0, "Can't drop a negative number of elements from a collection") let result = self.suffix(n) self.removeLast(Swift.min(self.count, n)) return result } } extension RandomAccessCollection { /// Returns first range of `pattern` appear in `self`, or `nil` if not match. /// /// - complexity: Amortized O(`self.count`) @inlinable public func range<C: RandomAccessCollection>(of pattern: C, where isEquivalent: (Element, Element) throws -> Bool) rethrows -> Range<Index>? where C.Element == Element { let pattern_count = pattern.count if count < pattern_count { return nil } let reverse_pattern = pattern.reversed() var cursor = self.index(startIndex, offsetBy: pattern_count - 1, limitedBy: endIndex) ?? endIndex while cursor < endIndex { guard let not_match = try zip(self.indices.prefix(through: cursor).reversed(), reverse_pattern).first(where: { try !isEquivalent(self[$0], $1) }) else { let start = self.index(cursor, offsetBy: 1 - pattern_count) let end = self.index(cursor, offsetBy: 1) return start..<end } let notMatchValue = self[not_match.0] if let pos = try reverse_pattern.dropFirst().firstIndex(where: { try isEquivalent(notMatchValue, $0) }) { cursor = self.index(not_match.0, offsetBy: reverse_pattern.distance(from: reverse_pattern.startIndex, to: pos), limitedBy: endIndex) ?? endIndex } else { cursor = self.index(not_match.0, offsetBy: pattern_count, limitedBy: endIndex) ?? endIndex } } if try self.reversed().starts(with: reverse_pattern, by: isEquivalent) { let start = self.index(endIndex, offsetBy: -pattern_count) return start..<endIndex } return nil } } extension RandomAccessCollection where Element: Equatable { /// Returns first range of `pattern` appear in `self`, or `nil` if not match. /// /// - complexity: Amortized O(`self.count`) @inlinable public func range<C: RandomAccessCollection>(of pattern: C) -> Range<Index>? where C.Element == Element { return self.range(of: pattern, where: ==) } } extension MutableCollection { @inlinable public mutating func mutateEach(body: (inout Element) throws -> Void) rethrows { var idx = self.startIndex while idx != self.endIndex { try body(&self[idx]) idx = self.index(after: idx) } } } extension Sequence { @inlinable public func appended(_ newElement: Element) -> Chain2Sequence<Self, CollectionOfOne<Element>> { return chain(self, CollectionOfOne(newElement)) } } extension Collection { @inlinable public func rotated(at index: Index) -> Chain2Sequence<SubSequence, SubSequence> { return chain(self.suffix(from: index), self.prefix(upTo: index)) } } extension Collection { @inlinable public func rotated(_ n: Int) -> Chain2Sequence<SubSequence, SubSequence> { let count = self.count if count == 0 { return chain(self[...], self[...]) } if n < 0 { let _n = -n % count return chain(self.suffix(_n), self.dropLast(_n)) } let _n = n % count return chain(self.dropFirst(_n), self.prefix(_n)) } } extension Collection where Element: Comparable { /// Returns the maximal `SubSequence`s of `self`, in order, around elements /// match in `separator`. /// /// - parameters: /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each pair of consecutive elements /// satisfying the `isSeparator` predicate and for each element at the /// start or end of the sequence satisfying the `isSeparator` predicate. /// If `true`, only nonempty subsequences are returned. The default /// value is `true`. /// - Returns: An array of subsequences, split from this sequence's elements. @inlinable public func split<S: Sequence>(separator: S, maxSplit: Int = Int.max, omittingEmptySubsequences: Bool = true) -> [SubSequence] where S.Element == Element { return self.split(maxSplits: maxSplit, omittingEmptySubsequences: omittingEmptySubsequences) { separator.contains($0) } } } extension LazySequenceProtocol { /// Return a `Sequence` containing tuples satisfies `predicate` with each elements of two `sources`. @inlinable public func merge<S>(with: S, where predicate: @escaping (Elements.Element, S.Element) -> Bool) -> LazySequence<FlattenSequence<LazyMapSequence<Elements, LazyMapSequence<LazyFilterSequence<S>, (Elements.Element, S.Element)>>>> { return self.flatMap { lhs in with.lazy.filter { rhs in predicate(lhs, rhs) }.map { (lhs, $0) } } } } extension LazyCollectionProtocol { /// Return a `Collection` containing tuples satisfies `predicate` with each elements of two `sources`. @inlinable public func merge<C>(with: C, where predicate: @escaping (Elements.Element, C.Element) -> Bool) -> LazyCollection<FlattenCollection<LazyMapCollection<Elements, LazyMapCollection<LazyFilterCollection<C>, (Elements.Element, C.Element)>>>> { return self.flatMap { lhs in with.lazy.filter { rhs in predicate(lhs, rhs) }.map { (lhs, $0) } } } } extension Sequence { /// Return an `Array` containing tuples satisfies `predicate` with each elements of two `sources`. @inlinable public func merge<S: Sequence>(with: S, where predicate: (Element, S.Element) throws -> Bool) rethrows -> [(Element, S.Element)] { var result = ContiguousArray<(Element, S.Element)>() for lhs in self { for rhs in with where try predicate(lhs, rhs) { result.append((lhs, rhs)) } } return Array(result) } } extension Sequence { /// Returns the minimum element in `self` or `nil` if the sequence is empty. /// /// - complexity: O(`elements.count`). @inlinable public func min<R: Comparable>(by: (Element) throws -> R) rethrows -> Element? { return try self.min { try by($0) < by($1) } } /// Returns the maximum element in `self` or `nil` if the sequence is empty. /// /// - complexity: O(`elements.count`). @inlinable public func max<R: Comparable>(by: (Element) throws -> R) rethrows -> Element? { return try self.max { try by($0) < by($1) } } } extension MutableCollection where Self: RandomAccessCollection { @inlinable public mutating func sort<R: Comparable>(by: (Element) -> R) { self.sort { by($0) < by($1) } } } extension Sequence { @inlinable public func sorted<R: Comparable>(by: (Element) -> R) -> [Element] { return self.sorted { by($0) < by($1) } } } extension Comparable { @inlinable public func clamped(to range: ClosedRange<Self>) -> Self { return min(max(self, range.lowerBound), range.upperBound) } } extension Strideable where Stride: SignedInteger { @inlinable public func clamped(to range: Range<Self>) -> Self { return self.clamped(to: ClosedRange(range)) } } extension RangeReplaceableCollection { @inlinable public mutating func replace<C: Collection>(with newElements: C) where Element == C.Element { self.replaceSubrange(startIndex..<endIndex, with: newElements) } } extension BidirectionalCollection where Self: MutableCollection { @inlinable public mutating func reverseSubrange(_ range: Indices.SubSequence) { for (lhs, rhs) in zip(range, range.reversed()) { if lhs < rhs { swapAt(lhs, rhs) } else { break } } } } extension Sequence { @inlinable @inline(__always) public func isStorageEqual<S: Sequence>(_ other: S) -> Bool where Element == S.Element { return self.withContiguousStorageIfAvailable { lhs in other.withContiguousStorageIfAvailable { rhs in lhs.count == rhs.count && lhs.baseAddress == rhs.baseAddress } ?? false } ?? false } }
mit
f1671f117650b32212f0009666c2fe6d
35.320635
242
0.63893
4.361799
false
false
false
false
coderMONSTER/ioscelebrity
YStar/YStar/AppAPI/SocketAPI/SocketReqeust/APISocketHelper.swift
1
4115
// // APISocketHelper.swift // viossvc // // Created by yaowang on 2016/11/21. // Copyright © 2016年 ywwlcom.yundian. All rights reserved. // import UIKit import CocoaAsyncSocket //import XCGLogger import SVProgressHUD class APISocketHelper:NSObject, GCDAsyncSocketDelegate,SocketHelper { var socket: GCDAsyncSocket?; var dispatch_queue: DispatchQueue!; var mutableData: NSMutableData = NSMutableData(); var packetHead:SocketPacketHead = SocketPacketHead(); var isConnected : Bool { return socket!.isConnected } override init() { super.init() dispatch_queue = DispatchQueue(label: "APISocket_Queue", attributes: DispatchQueue.Attributes.concurrent) socket = GCDAsyncSocket.init(delegate: self, delegateQueue: dispatch_queue); connect() } func connect() { mutableData = NSMutableData() do { if !socket!.isConnected { let host = AppConst.Network.TcpServerIP let port: UInt16 = AppConst.Network.TcpServerPort try socket?.connect(toHost: host, onPort: port, withTimeout: 5) } } catch GCDAsyncSocketError.closedError { print("¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯") } catch GCDAsyncSocketError.connectTimeoutError { print("<<<<<<<<<<<<<<<<<<<<<<<<") } catch { print(">>>>>>>>>>>>>>>>>>>>>>>") } } func disconnect() { socket?.delegate = nil; socket?.disconnect() } func sendData(_ data: Data) { objc_sync_enter(self) socket?.write(data, withTimeout: -1, tag: 0) objc_sync_exit(self) } func onPacketData(_ data: Data) { memset(&packetHead,0, MemoryLayout<SocketPacketHead>.size) (data as NSData).getBytes(&packetHead, length: MemoryLayout<SocketPacketHead>.size) if( Int(packetHead.packet_length) - MemoryLayout<SocketPacketHead>.size == Int(packetHead.data_length) ) { let packet: SocketDataPacket = SocketDataPacket(socketData: data as NSData) SocketRequestManage.shared.notifyResponsePacket(packet) } else { // debugPrint("onPacketData error packet_length:\(packetHead.packet_length) packet_length:\(packetHead.data_length) data:\(data.count)"); } } //MARK: GCDAsyncSocketDelegate @objc func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) { debugPrint("didConnectToHost host:\(host) port:\(port)") sock.perform({ () -> Void in sock.enableBackgroundingOnSocket() }); socket?.readData(withTimeout: -1, tag: 0) } @objc func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: CLong) { // XCGLogger.debug("socket:\(data)") mutableData.append(data) while mutableData.length >= 26 { var packetLen: Int16 = 0; mutableData.getBytes(&packetLen, length: MemoryLayout<Int16>.size) if mutableData.length >= Int(packetLen) { var range: NSRange = NSMakeRange(0, Int(packetLen)) onPacketData(mutableData.subdata(with: range)) range.location = range.length; range.length = mutableData.length - range.location; mutableData = (mutableData.subdata(with: range) as NSData).mutableCopy() as! NSMutableData; } else { break } } socket?.readData(withTimeout: -1, tag: 0) } @objc func socket(_ sock: GCDAsyncSocket, shouldTimeoutReadWithTag tag: CLong, elapsed: TimeInterval, bytesDone length: UInt) -> TimeInterval { return 0 } @objc func socket(_ sock: GCDAsyncSocket, shouldTimeoutWriteWithTag tag: CLong, elapsed: TimeInterval, bytesDone length: UInt) -> TimeInterval { return 0 } @objc func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) { SocketRequestManage.shared.start() } deinit { socket?.disconnect() } }
mit
7d3161e32355e22b3a09df7c09e6444e
34.573913
148
0.610364
4.581187
false
false
false
false
justindarc/firefox-ios
Shared/UserAgent.swift
2
5766
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import AVFoundation import UIKit open class UserAgent { private static var defaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)! private static func clientUserAgent(prefix: String) -> String { return "\(prefix)/\(AppInfo.appVersion)b\(AppInfo.buildNumber) (\(DeviceInfo.deviceModel()); iPhone OS \(UIDevice.current.systemVersion)) (\(AppInfo.displayName))" } public static var syncUserAgent: String { return clientUserAgent(prefix: "Firefox-iOS-Sync") } public static var tokenServerClientUserAgent: String { return clientUserAgent(prefix: "Firefox-iOS-Token") } public static var fxaUserAgent: String { return clientUserAgent(prefix: "Firefox-iOS-FxA") } public static var defaultClientUserAgent: String { return clientUserAgent(prefix: "Firefox-iOS") } /** * Use this if you know that a value must have been computed before your * code runs, or you don't mind failure. */ public static func cachedUserAgent(checkiOSVersion: Bool = true, checkFirefoxVersion: Bool = true, checkFirefoxBuildNumber: Bool = true) -> String? { let currentiOSVersion = UIDevice.current.systemVersion let lastiOSVersion = defaults.string(forKey: "LastDeviceSystemVersionNumber") let currentFirefoxBuildNumber = AppInfo.buildNumber let currentFirefoxVersion = AppInfo.appVersion let lastFirefoxVersion = defaults.string(forKey: "LastFirefoxVersionNumber") let lastFirefoxBuildNumber = defaults.string(forKey: "LastFirefoxBuildNumber") if let firefoxUA = defaults.string(forKey: "UserAgent") { if (!checkiOSVersion || (lastiOSVersion == currentiOSVersion)) && (!checkFirefoxVersion || (lastFirefoxVersion == currentFirefoxVersion) && (!checkFirefoxBuildNumber || (lastFirefoxBuildNumber == currentFirefoxBuildNumber))) { return firefoxUA } } return nil } /** * This will typically return quickly, but can require creation of a UIWebView. * As a result, it must be called on the UI thread. */ public static func defaultUserAgent() -> String { assert(Thread.current.isMainThread, "This method must be called on the main thread.") if let firefoxUA = UserAgent.cachedUserAgent(checkiOSVersion: true) { return firefoxUA } let webView = UIWebView() let appVersion = AppInfo.appVersion let buildNumber = AppInfo.buildNumber let currentiOSVersion = UIDevice.current.systemVersion defaults.set(currentiOSVersion, forKey: "LastDeviceSystemVersionNumber") defaults.set(appVersion, forKey: "LastFirefoxVersionNumber") defaults.set(buildNumber, forKey: "LastFirefoxBuildNumber") let userAgent = webView.stringByEvaluatingJavaScript(from: "navigator.userAgent")! // Extract the WebKit version and use it as the Safari version. let webKitVersionRegex = try! NSRegularExpression(pattern: "AppleWebKit/([^ ]+) ", options: []) let match = webKitVersionRegex.firstMatch(in: userAgent, options: [], range: NSRange(location: 0, length: userAgent.count)) if match == nil { print("Error: Unable to determine WebKit version in UA.") return userAgent // Fall back to Safari's. } let webKitVersion = (userAgent as NSString).substring(with: match!.range(at: 1)) // Insert "FxiOS/<version>" before the Mobile/ section. let mobileRange = (userAgent as NSString).range(of: "Mobile/") if mobileRange.location == NSNotFound { print("Error: Unable to find Mobile section in UA.") return userAgent // Fall back to Safari's. } let mutableUA = NSMutableString(string: userAgent) mutableUA.insert("FxiOS/\(appVersion)b\(AppInfo.buildNumber) ", at: mobileRange.location) let firefoxUA = "\(mutableUA) Safari/\(webKitVersion)" defaults.set(firefoxUA, forKey: "UserAgent") return firefoxUA } public static func desktopUserAgent() -> String { let userAgent = NSMutableString(string: defaultUserAgent()) // Spoof platform section let platformRegex = try! NSRegularExpression(pattern: "\\([^\\)]+\\)", options: []) guard let platformMatch = platformRegex.firstMatch(in: userAgent as String, options: [], range: NSRange(location: 0, length: userAgent.length)) else { print("Error: Unable to determine platform in UA.") return String(userAgent) } userAgent.replaceCharacters(in: platformMatch.range, with: "(Macintosh; Intel Mac OS X 10_11_1)") // Strip mobile section let mobileRegex = try! NSRegularExpression(pattern: " FxiOS/[^ ]+ Mobile/[^ ]+", options: []) guard let mobileMatch = mobileRegex.firstMatch(in: userAgent as String, options: [], range: NSRange(location: 0, length: userAgent.length)) else { print("Error: Unable to find Mobile section in UA.") return String(userAgent) } // The iOS major version is equal to the Safari major version let majoriOSVersion = (UIDevice.current.systemVersion as NSString).components(separatedBy: ".")[0] userAgent.replaceCharacters(in: mobileMatch.range, with: " Version/\(majoriOSVersion).0") return String(userAgent) } }
mpl-2.0
ab4ac278da23d2154c842d6ad296843b
42.029851
171
0.659729
4.940874
false
false
false
false
noppoMan/Prorsum
Tests/ProrsumTests/SelectTests.swift
1
1976
// // SelectTests.swift // Prorsum // // Created by Yuki Takei on 2016/11/24. // // #if os(Linux) import Glibc #else import Darwin.C #endif import XCTest import Foundation @testable import Prorsum class SelectTests: XCTestCase { static var allTests : [(String, (SelectTests) -> () throws -> Void)] { return [ ("testSelect", testSelect), ("testSelectOtherwise", testSelectOtherwise), ("testForSelect", testForSelect), ("testForSelectOtherwise", testForSelectOtherwise), ] } func testSelect() { let ch = Channel<Int>.make(capacity: 1) go { try! ch.send(1) } select { when(ch) { XCTAssertEqual($0, 1) } } } func testSelectOtherwise() { let ch = Channel<Int>.make(capacity: 1) select { otherwise { sleep(1) try! ch.send(1000) } } XCTAssertEqual(try! ch.receive(), 1000) } func testForSelect() { let ch = Channel<Int>.make(capacity: 1) let doneCh = Channel<String>.make(capacity: 1) go { try! ch.send(1) try! ch.send(2) try! ch.send(3) try! doneCh.send("done") } var i = 0 forSelect { done in when(ch) { i+=1 XCTAssertEqual($0, i) } when(doneCh) { XCTAssertEqual($0, "done") done() } } } func testForSelectOtherwise() { let ch = Channel<Int>.make(capacity: 1) go { try! ch.send(1) } forSelect { done in when(ch) { XCTAssertEqual($0, 1) } otherwise { done() } } } }
mit
225b063dc3cf5e989e9250a436536667
19.163265
74
0.437753
4.381375
false
true
false
false
vvw/XWebView
XWebView/XWVChannel.swift
1
4830
/* Copyright 2015 XWebView Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import WebKit public class XWVChannel : NSObject, WKScriptMessageHandler { public let name: String public let thread: NSThread! public let queue: dispatch_queue_t! private(set) public weak var webView: WKWebView? var typeInfo: XWVReflection! private var instances = [Int: XWVScriptPlugin]() private var userScript: WKUserScript? private class var sequenceNumber: UInt { struct sequence{ static var number: UInt = 0 } return ++sequence.number } public convenience init(name: String?, webView: WKWebView) { let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL) self.init(name: name, webView:webView, queue: queue) } public init(name: String?, webView: WKWebView, queue: dispatch_queue_t) { self.name = name ?? "\(XWVChannel.sequenceNumber)" self.webView = webView self.queue = queue thread = nil webView.prepareForPlugin() } public init(name: String?, webView: WKWebView, thread: NSThread) { self.name = name ?? "\(XWVChannel.sequenceNumber)" self.webView = webView self.thread = thread queue = nil webView.prepareForPlugin() } public func bindPlugin(object: AnyObject, toNamespace namespace: String) -> XWVScriptObject? { assert(typeInfo == nil) webView?.configuration.userContentController.addScriptMessageHandler(self, name: name) typeInfo = XWVReflection(plugin: object.dynamicType) let plugin = XWVScriptPlugin(namespace: namespace, channel: self, object: object) let stub = XWVStubGenerator(channel: self).generateForNamespace(namespace, object: plugin) userScript = webView?.injectScript((object as? XWVScripting)?.javascriptStub?(stub) ?? stub) instances[0] = plugin return plugin as XWVScriptObject } public func unbind() { assert(typeInfo != nil) if webView?.URL != nil { webView!.evaluateJavaScript("delete \(instances[0]!.namespace);", completionHandler:nil) } if userScript != nil { webView?.configuration.userContentController.removeUserScript(userScript!) } instances.removeAll(keepCapacity: false) webView?.configuration.userContentController.removeScriptMessageHandlerForName(name) } public func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if let body = message.body as? [String: AnyObject], let opcode = body["$opcode"] as? String { let target = (body["$target"] as? NSNumber)?.integerValue ?? 0 if let object = instances[target] { if opcode == "-" { if target == 0 { // Destroy plugin unbind() } else { // Destroy instance let object = instances.removeValueForKey(target) assert(object != nil) } } else if typeInfo.hasProperty(opcode) { // Update property object.updateNativeProperty(opcode, withValue: body["$operand"]) } else if typeInfo.hasMethod(opcode) { // Invoke method let args = body["$operand"] as? [AnyObject] object.invokeNativeMethod(opcode, withArguments: args) } // else Unknown opcode } else if opcode == "+" { // Create instance let args = body["$operand"] as? [AnyObject] let namespace = "\(instances[0]!.namespace)[\(target)]" instances[target] = XWVScriptPlugin(namespace: namespace, channel: self, arguments: args) } // else Unknown opcode } else if let obj = instances[0]!.object as? WKScriptMessageHandler { // Plugin claims for raw messages obj.userContentController(userContentController, didReceiveScriptMessage: message) } else { // discard unknown message println("WARNING: Unknown message: \(message.body)") } } }
apache-2.0
9047d71db28fd3cb16983bb0107b3276
41.368421
137
0.625466
5.193548
false
false
false
false
kildevaeld/DataBinding
Pod/Classes/UIWebViewHandler.swift
1
932
// // UIWebViewHandler.swift // Pods // // Created by Rasmus Kildevæld on 21/06/15. // // import Foundation class UIWebViewHandler : NSObject, HandlerProtocol { var type: AnyObject.Type? = nil func setValue(value: AnyObject?, onView: UIView) { let webView = onView as! UIWebView; var url: NSURL? var html: String? if let _url = value as? NSURL { url = _url } else if let str = value as? String { if str.hasPrefix("http://") || str.hasPrefix("https://") { url = NSURL(string: str as String) } else { html = str } } if url != nil { let request = NSURLRequest(URL: url!) webView.loadRequest(request) } else if html != nil { webView.loadHTMLString(html!, baseURL: NSURL()) } } }
mit
125818093dc1d3cd9700345b2d6ba54e
22.897436
70
0.496241
4.433333
false
false
false
false
valitovaza/IntervalReminder
IntervalReminder/IntervalsViewController.swift
1
3111
import Cocoa protocol MainWindowContainer { var mainWindow: NSWindow? { get } } extension NSApplication: MainWindowContainer {} class IntervalsViewController: NSViewController, IntervalsViewProtocol { @IBOutlet weak var tableView: NSTableView! @IBOutlet weak var intervalButton: NSButton! @IBOutlet weak var stopButton: NSButton! @IBOutlet weak var createButton: NSButton! @IBOutlet weak var checkButton: NSButton! var presenter: IntervalPresenterProtocol? var interactor: IntervalInteractorProtocol? var mainWindowContainer: MainWindowContainer = NSApp required init?(coder: NSCoder) { super.init(coder: coder) configureInteractorAndPresenter() } private func configureInteractorAndPresenter() { let intervalPresenter = IntervalPresenter(self) let intervalInteractor = IntervalInteractor(intervalPresenter) intervalPresenter.dataProvider = intervalInteractor set(interactor: intervalInteractor, andPresenter: intervalPresenter) } private func set(interactor intervalInteractor: IntervalInteractorProtocol, andPresenter intervalPresenter: IntervalPresenterProtocol) { presenter = intervalPresenter interactor = intervalInteractor } // MARK: - Lyfecycle override func viewDidLoad() { interactor?.fetch() } // MARK: - Actions private(set) var createController: ModalController? @IBAction func create(_ sender: NSButton) { if let modalWindow = modalController() { mainWindowContainer.mainWindow?.beginSheet(modalWindow, completionHandler: sheetHandler(_:)) } } func sheetHandler(_ code: NSModalResponse) { createController = nil } private func modalController() -> NSWindow? { createController = ModalController.fromNib() createController?.intervalInteractor = self.interactor return createController?.window } @IBAction func intervalAction(_ sender: NSButton) { interactor?.intervalAction() } @IBAction func stop(_ sender: NSButton) { interactor?.stop() } @IBAction func changeRepeat(_ sender: NSButton) { interactor?.changeRepeat() } // MARK: - IntervalsViewProtocol func addRow(at index: Int) { tableView.reloadData() } func removeRow(at index: Int) { tableView.reloadData() } func updateRow(at index: Int) { tableView.reloadData() } func reload() { tableView.reloadData() } } extension IntervalsViewController: NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { return presenter?.count() ?? 0 } } extension IntervalsViewController: NSTableViewDelegate { func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let cell = tableView.makeCell() as NSTableCellView presenter?.present(cell: cell, at: row) return cell } }
mit
78586c6a1b0a07c44c5088a299be45da
33.186813
91
0.667631
5.382353
false
false
false
false
CaiMiao/CGSSGuide
DereGuide/Card/View/CGSSIconView.swift
1
1334
// // CGSSIconView.swift // DereGuide // // Created by zzk on 16/8/14. // Copyright © 2016年 zzk. All rights reserved. // import UIKit import ZKCornerRadiusView protocol CGSSIconViewDelegate: class { func iconClick(_ iv: CGSSIconView) } class CGSSIconView: UIImageView { var tap: UITapGestureRecognizer? var action: Selector? weak var target: AnyObject? weak var delegate: CGSSIconViewDelegate? convenience init() { self.init(frame: CGRect.init(x: 0, y: 0, width: 48, height: 48)) } override init(frame: CGRect) { super.init(frame: frame) prepare() } func prepare() { isUserInteractionEnabled = true tap = UITapGestureRecognizer(target: self, action: #selector(onClick)) addGestureRecognizer(tap!) } func setAction(_ target: AnyObject, action: Selector) { self.action = action self.target = target } @objc func onClick() { delegate?.iconClick(self) if action != nil { _ = self.target?.perform(action!, with: self) } } override var intrinsicContentSize: CGSize { return CGSize(width: 48, height: 48) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepare() } }
mit
6efa487b7a542576a9cc4a8ee99e05d6
21.948276
78
0.604808
4.252396
false
false
false
false
mtigas/iObfs
example/ExampleObfs/AppDelegate.swift
1
6697
// // AppDelegate.swift // ExampleObfs // // Created by Mike Tigas on 4/10/16. // Copyright © 2016 Mike Tigas. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { NSURLProtocol.registerClass(TorProxyURLProtocol) let conf:TORConfiguration = TORConfiguration() conf.cookieAuthentication = NSNumber(booleanLiteral: true) conf.dataDirectory = NSURL(fileURLWithPath: NSTemporaryDirectory()) var args = [ "--socksport", "39050", "--UseBridges", "1", // Our hard-coded ports for pluggable transports "--ClientTransportPlugin", "obfs4 socks5 127.0.0.1:47351", "--ClientTransportPlugin", "meek_lite socks5 127.0.0.1:47352", "--ClientTransportPlugin", "obfs2 socks5 127.0.0.1:47353", "--ClientTransportPlugin", "obfs3 socks5 127.0.0.1:47354", "--ClientTransportPlugin", "scramblesuit socks5 127.0.0.1:47355", // Tor Browser Bundle's default obfs4 bridges "--Bridge", "obfs4 154.35.22.10:41835 8FB9F4319E89E5C6223052AA525A192AFBC85D55 cert=GGGS1TX4R81m3r0HBl79wKy1OtPPNR2CZUIrHjkRg65Vc2VR8fOyo64f9kmT1UAFG7j0HQ iat-mode=0", "--Bridge", "obfs4 198.245.60.50:443 752CF7825B3B9EA6A98C83AC41F7099D67007EA5 cert=xpmQtKUqQ/6v5X7ijgYE/f03+l2/EuQ1dexjyUhh16wQlu/cpXUGalmhDIlhuiQPNEKmKw iat-mode=0", "--Bridge", "obfs4 192.99.11.54:443 7B126FAB960E5AC6A629C729434FF84FB5074EC2 cert=VW5f8+IBUWpPFxF+rsiVy2wXkyTQG7vEd+rHeN2jV5LIDNu8wMNEOqZXPwHdwMVEBdqXEw iat-mode=0", "--Bridge", "obfs4 109.105.109.165:10527 8DFCD8FB3285E855F5A55EDDA35696C743ABFC4E cert=Bvg/itxeL4TWKLP6N1MaQzSOC6tcRIBv6q57DYAZc3b2AzuM+/TfB7mqTFEfXILCjEwzVA iat-mode=0", "--Bridge", "obfs4 83.212.101.3:41213 A09D536DD1752D542E1FBB3C9CE4449D51298239 cert=lPRQ/MXdD1t5SRZ9MquYQNT9m5DV757jtdXdlePmRCudUU9CFUOX1Tm7/meFSyPOsud7Cw iat-mode=0", "--Bridge", "obfs4 104.131.108.182:56880 EF577C30B9F788B0E1801CF7E433B3B77792B77A cert=0SFhfDQrKjUJP8Qq6wrwSICEPf3Vl/nJRsYxWbg3QRoSqhl2EB78MPS2lQxbXY4EW1wwXA iat-mode=0", "--Bridge", "obfs4 109.105.109.147:13764 BBB28DF0F201E706BE564EFE690FE9577DD8386D cert=KfMQN/tNMFdda61hMgpiMI7pbwU1T+wxjTulYnfw+4sgvG0zSH7N7fwT10BI8MUdAD7iJA iat-mode=0", "--Bridge", "obfs4 154.35.22.11:49868 A832D176ECD5C7C6B58825AE22FC4C90FA249637 cert=YPbQqXPiqTUBfjGFLpm9JYEFTBvnzEJDKJxXG5Sxzrr/v2qrhGU4Jls9lHjLAhqpXaEfZw iat-mode=0", "--Bridge", "obfs4 154.35.22.12:80 00DC6C4FA49A65BD1472993CF6730D54F11E0DBB cert=N86E9hKXXXVz6G7w2z8wFfhIDztDAzZ/3poxVePHEYjbKDWzjkRDccFMAnhK75fc65pYSg iat-mode=0", "--Bridge", "obfs4 154.35.22.13:443 FE7840FE1E21FE0A0639ED176EDA00A3ECA1E34D cert=fKnzxr+m+jWXXQGCaXe4f2gGoPXMzbL+bTBbXMYXuK0tMotd+nXyS33y2mONZWU29l81CA iat-mode=0", "--Bridge", "obfs4 154.35.22.10:80 8FB9F4319E89E5C6223052AA525A192AFBC85D55 cert=GGGS1TX4R81m3r0HBl79wKy1OtPPNR2CZUIrHjkRg65Vc2VR8fOyo64f9kmT1UAFG7j0HQ iat-mode=0", "--Bridge", "obfs4 154.35.22.10:443 8FB9F4319E89E5C6223052AA525A192AFBC85D55 cert=GGGS1TX4R81m3r0HBl79wKy1OtPPNR2CZUIrHjkRg65Vc2VR8fOyo64f9kmT1UAFG7j0HQ iat-mode=0", "--Bridge", "obfs4 154.35.22.11:443 A832D176ECD5C7C6B58825AE22FC4C90FA249637 cert=YPbQqXPiqTUBfjGFLpm9JYEFTBvnzEJDKJxXG5Sxzrr/v2qrhGU4Jls9lHjLAhqpXaEfZw iat-mode=0", "--Bridge", "obfs4 154.35.22.11:80 A832D176ECD5C7C6B58825AE22FC4C90FA249637 cert=YPbQqXPiqTUBfjGFLpm9JYEFTBvnzEJDKJxXG5Sxzrr/v2qrhGU4Jls9lHjLAhqpXaEfZw iat-mode=0", "--ignore-missing-torrc" ] // controlsocket path length is often too long #if (arch(i386) || arch(x86_64)) && (os(iOS) || os(watchOS) || os(tvOS)) args += [ "--controlport", "127.0.0.1:39060" ] #else conf.controlSocket = conf.dataDirectory?.URLByAppendingPathComponent("control_port") #endif conf.arguments = args; let torThread:TORThread = TORThread(configuration: conf) torThread.start() let obfsThread:ObfsThread = ObfsThread() obfsThread.start() /* let cookiePath:NSURL? = conf.dataDirectory?.URLByAppendingPathComponent("control_auth_cookie") // wait one second for tor to start up and actually // write the cookie file. let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 2 * Int64(NSEC_PER_SEC)) dispatch_after(time, dispatch_get_main_queue()) { let cookie:NSData = NSData(contentsOfURL: cookiePath!)! #if (arch(i386) || arch(x86_64)) && (os(iOS) || os(watchOS) || os(tvOS)) let controller:TORController = TORController(socketHost: "127.0.0.1", port: 39060) #else let controller:TORController = TORController(socketURL: conf.controlSocket!) #endif controller.authenticateWithData(cookie) { (success, error) in print("we're in!") if !success { print("err: %@", error) } } } */ // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
bsd-2-clause
51fcbc66436dbaa40100d0374ad02cc1
52.568
281
0.751045
2.849362
false
false
false
false
practicalswift/swift
test/SILOptimizer/existential_transform_soletype.swift
3
1803
// RUN: %target-swift-frontend -O -wmo -sil-existential-specializer -Xllvm -sil-disable-pass=GenericSpecializer -Xllvm -sil-disable-pass=FunctionSignatureOpts -Xllvm -sil-disable-pass=SILCombine -emit-sil -sil-verify-all %s | %FileCheck %s internal protocol SPP { func bar() -> Int32 } internal class SCC: SPP { @inline(never) func bar() -> Int32 { return 5 } } @inline(never) internal func opt2(b:SPP) -> Int32{ return b.bar() } @inline(never) internal func opt1(b:SPP) -> Int32{ return opt2(b:b) } // CHECK-LABEL: sil hidden [noinline] @$s30existential_transform_soletype4opt11bs5Int32VAA3SPP_p_tF : $@convention(thin) (@in_guaranteed SPP) -> Int32 { // CHECK: bb0(%0 : $*SPP): // CHECK: debug_value_addr // CHECK: function_ref @$s30existential_transform_soletype4opt21bs5Int32VAA3SPP_p_tFTf4e_n : $@convention(thin) <τ_0_0 where τ_0_0 : SPP> (@in_guaranteed τ_0_0) -> Int32 // user: %4 // CHECK: open_existential_addr // CHECK: apply // CHECK: return // CHECK-LABEL: } // end sil function '$s30existential_transform_soletype4opt11bs5Int32VAA3SPP_p_tF' // CHECK-LABEL: sil shared [noinline] @$s30existential_transform_soletype4opt21bs5Int32VAA3SPP_p_tFTf4e_n : $@convention(thin) <τ_0_0 where τ_0_0 : SPP> (@in_guaranteed τ_0_0) -> Int32 { // CHECK: bb0(%0 : $*τ_0_0): // CHECK: alloc_stack // CHECK: init_existential_addr // CHECK: copy_addr // CHECK: debug_value_addr // CHECK: open_existential_addr // CHECK: witness_method // CHECK: apply // CHECK: dealloc_stack // CHECK: return // CHECK-LABEL: } // end sil function '$s30existential_transform_soletype4opt21bs5Int32VAA3SPP_p_tFTf4e_n' @_optimize(none) func foo(number:Int32)->Int32 { var b:SPP if number < 5 { b = SCC() } else { b = SCC() } let x = opt1(b:b) return x }
apache-2.0
121adde899cb6783a50416fc9684100c
33.538462
239
0.680958
2.692654
false
false
false
false
darkzero/DZPopupMessageView
DZPopupMessageView/Classes/DZPopupMessageView.swift
1
7910
// // DZPopupMessageView.swift // Pods // // Created by darkzero on 16/5/15. // // import UIKit public class DZPopupMessageView: UIView { private var parentView: UIView? private var messageLabel: UILabel = UILabel(frame: CGRect(x: 10, y: 5, width: 220, height: 22)) private var iconImageView: UIImageView = UIImageView(frame: CGRect(x: 4, y: 4, width: 24, height: 24)) private var callback:(()->Void)? private var message: Message // MARK: - init required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } internal init(message: Message, in view: UIView? = nil, callback: (()->Void)? = nil) { self.message = message self.callback = callback if ( view != nil ) { self.parentView = view } else { self.parentView = UIApplication.shared.keyWindow } // calc the frame let rect = (message.text as NSString).boundingRect(with: CGSize(width: 220, height: 0), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 14.0)], context: nil) let labelRect = CGRect(x: 40, y: 8, width: min(rect.width, 220), height: rect.height) let viewRect = CGRect(x: 0, y: 0, width: min(rect.width, 220) + 60, height: max(rect.height+16, 32.0)) let radius: CGFloat = 16.0 //viewRect.height/2 super.init(frame: viewRect) self.addSubview(self.messageLabel) self.addSubview(self.iconImageView) self.messageLabel.frame = labelRect self.messageLabel.textAlignment = NSTextAlignment.left self.messageLabel.font = UIFont.systemFont(ofSize: 14.0) self.messageLabel.numberOfLines = 0 self.messageLabel.lineBreakMode = NSLineBreakMode.byWordWrapping self.messageLabel.text = message.text self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOpacity = 0.5 switch message.theme { case .dark: self.messageLabel.textColor = .white self.backgroundColor = UIColor(white: 0.5, alpha: 0.7) self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOpacity = 0.5 self.layer.borderColor = UIColor.white.cgColor self.iconImageView.tintColor = .white case .light: self.messageLabel.textColor = .darkGray self.backgroundColor = UIColor(white: 1.0, alpha: 0.9) self.layer.shadowColor = UIColor.gray.cgColor self.layer.shadowOpacity = 0.3 self.layer.borderColor = UIColor.gray.cgColor self.iconImageView.tintColor = .gray } self.layer.borderWidth = 1 var imageStr = "" switch message.type { case .info: imageStr = "dz_icon_info" break case .warning: self.layer.borderColor = UIColor.orange.cgColor if message.theme == .dark { self.backgroundColor = UIColor(white: 0.7, alpha: 0.9) } self.messageLabel.textColor = .orange imageStr = "dz_icon_warning" self.iconImageView.tintColor = .orange break case .error: self.layer.borderColor = UIColor.red.cgColor if message.theme == .dark { self.backgroundColor = UIColor(white: 0.7, alpha: 0.9) } self.messageLabel.textColor = .red //self.messageLabel.font = UIFont.boldSystemFont(ofSize: 14.0) imageStr = "dz_icon_error" self.iconImageView.tintColor = .red break } let image = UIImage(named: imageStr, in: Bundle(for: DZPopupMessageView.self), compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) self.iconImageView.image = image self.iconImageView.contentMode = .scaleAspectFill self.addSubview(iconImageView) self.layer.masksToBounds = false self.layer.shadowOffset = CGSize(width: 0, height: 0) self.layer.shadowRadius = 2 self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: radius).cgPath self.layer.shouldRasterize = true self.layer.rasterizationScale = UIScreen.main.scale self.layer.cornerRadius = radius } } extension DZPopupMessageView { // MARK: - Animations internal func showWithAnimation(_ animation: Bool, in: UIView? = nil, callback: (()->Void)? = nil) { // self.parentView?.addSubview(self) let inset = DZPopupMessageView.safeAreaInsetsOf(self.parentView!) //print(inset) switch self.message.display { case .rise, .bubbleBottom: self.center = CGPoint(x: UIScreen.main.bounds.width/2, y: UIScreen.main.bounds.height) case .drop, .bubbleTop: self.center = CGPoint(x: UIScreen.main.bounds.width/2, y: -self.bounds.height) } self.alpha = 0.0 UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseOut, animations: { self.alpha = 1.0 switch self.message.display { case .rise: self.center = CGPoint(x: UIScreen.main.bounds.width/2, y: UIScreen.main.bounds.height/2) break case .drop: self.center = CGPoint(x: UIScreen.main.bounds.width/2, y: UIScreen.main.bounds.height/2) break case .bubbleTop: self.center = CGPoint(x: UIScreen.main.bounds.width/2, y: self.bounds.height/2+inset.top+16) break case .bubbleBottom: self.center = CGPoint(x: UIScreen.main.bounds.width/2, y: UIScreen.main.bounds.height-inset.bottom-self.bounds.height/2-16) break } }) { (finished) in self.hideWithAnimation(animation) } } internal func hideWithAnimation(_ animation: Bool) { UIView.animate(withDuration: 0.5, delay: self.message.disappearDelay, options: .curveLinear, animations: { self.alpha = 0.5 //self.center = CGPoint(x: UIScreen.main.bounds.width/2, y: UIScreen.main.bounds.height/4) }) { (finished) in DZPopupMessageQueue.shared.messageList.removeLast() DZPopupMessageQueueManager.shared.next() UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveLinear, animations: { self.alpha = 0.0 switch self.message.display { case .rise: self.center = CGPoint(x: UIScreen.main.bounds.width/2, y: 0) break case .drop: self.center = CGPoint(x: UIScreen.main.bounds.width/2, y: UIScreen.main.bounds.height) break case .bubbleTop: self.center = CGPoint(x: UIScreen.main.bounds.width/2, y: -self.bounds.height) break case .bubbleBottom: self.center = CGPoint(x: UIScreen.main.bounds.width/2, y: UIScreen.main.bounds.height) break } }, completion: { (finished) in self.removeFromSuperview() self.callback?() }) } } } extension DZPopupMessageView { class func safeAreaInsetsOf(_ view: UIView) -> UIEdgeInsets { if #available(iOS 11.0, *) { return view.safeAreaInsets } else { // Fallback on earlier versions return UIEdgeInsets.zero; } } }
mit
c9692d5c34b526a733e0eaebf5389460
40.631579
143
0.576359
4.456338
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/CryptoAssets/Sources/EthereumKit/Models/TransactionTarget/EthereumSendTransactionTarget.swift
1
1445
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Foundation import MoneyKit import PlatformKit public struct EthereumSendTransactionTarget: WalletConnectTarget { public enum Method { case sign case send } // MARK: - Public Properties public let onTxCompleted: TxCompleted public let onTransactionRejected: () -> AnyPublisher<Void, Never> public var currencyType: CurrencyType { network.cryptoCurrency.currencyType } public var label: String { dAppName } // MARK: - Properties let dAppAddress: String let dAppLogoURL: String let dAppName: String let method: Method let network: EVMNetwork let transaction: EthereumJsonRpcTransaction // MARK: - Init public init( dAppAddress: String, dAppLogoURL: String, dAppName: String, method: Method, network: EVMNetwork, onTransactionRejected: @escaping () -> AnyPublisher<Void, Never>, onTxCompleted: @escaping TxCompleted, transaction: EthereumJsonRpcTransaction ) { self.dAppAddress = dAppAddress self.dAppLogoURL = dAppLogoURL self.dAppName = dAppName self.method = method self.network = network self.onTransactionRejected = onTransactionRejected self.onTxCompleted = onTxCompleted self.transaction = transaction } }
lgpl-3.0
f3c7f3673dc17590af192e89abcd5475
24.333333
73
0.668975
4.797342
false
false
false
false