repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
mitchtreece/Bulletin | Example/Pods/Espresso/Espresso/Classes/Core/UIKit/UIViewController/UIStyledNavigationController.swift | 1 | 8662 | //
// UIStyledNavigationController.swift
// Espresso
//
// Created by Mitch Treece on 12/18/17.
//
import UIKit
/**
A `UINavigationController` subclass that implements common appearance properties.
*/
public class UIStyledNavigationController: UINavigationController, UINavigationControllerDelegate {
private var statusBarStyle: UIStatusBarStyle = .default
private var statusBarHidden: Bool = false
private var statusBarAnimation: UIStatusBarAnimation = .fade
public override var preferredStatusBarStyle: UIStatusBarStyle {
return statusBarStyle
}
public override var prefersStatusBarHidden: Bool {
return statusBarHidden
}
public override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return statusBarAnimation
}
public override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
self.delegate = self
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.delegate = self
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public override func viewDidLoad() {
super.viewDidLoad()
// Style initial view controller
if let vc = viewControllers.first, vc is UINavigationBarAppearanceProvider, viewControllers.count > 0 {
update(with: vc, sourceVC: nil, animated: false)
}
}
private func update(with vc: UIViewController, sourceVC: UIViewController?, animated: Bool) {
let sbAppearance = (vc as? UIStatusBarAppearanceProvider)?.preferredStatusBarAppearance
let lastSbAppearance = (sourceVC as? UIStatusBarAppearanceProvider)?.preferredStatusBarAppearance
let defaultSbAppearance = UIStatusBarAppearance()
statusBarStyle = sbAppearance?.style ?? lastSbAppearance?.style ?? defaultSbAppearance.style
statusBarHidden = sbAppearance?.hidden ?? lastSbAppearance?.hidden ?? defaultSbAppearance.hidden
statusBarAnimation = sbAppearance?.animation ?? lastSbAppearance?.animation ?? defaultSbAppearance.animation
setNeedsStatusBarAppearanceUpdate()
let nbAppearance = (vc as? UINavigationBarAppearanceProvider)?.preferredNavigationBarAppearance
let lastNbAppearance = (sourceVC as? UINavigationBarAppearanceProvider)?.preferredNavigationBarAppearance
let defaultNbAppearance = UINavigationBarAppearance()
navigationBar.barTintColor = nbAppearance?.barColor ?? lastNbAppearance?.barColor ?? defaultNbAppearance.barColor
navigationBar.tintColor = nbAppearance?.itemColor ?? lastNbAppearance?.itemColor ?? defaultNbAppearance.itemColor
navigationBar.titleTextAttributes = [
.font: nbAppearance?.titleFont ?? lastNbAppearance?.titleFont ?? defaultNbAppearance.titleFont,
.foregroundColor: nbAppearance?.titleColor ?? lastNbAppearance?.titleColor ?? defaultNbAppearance.titleColor
]
if #available(iOS 11, *) {
let displayMode = nbAppearance?.largeTitleDisplayMode ?? lastNbAppearance?.largeTitleDisplayMode ?? .automatic
vc.navigationItem.largeTitleDisplayMode = displayMode
navigationBar.prefersLargeTitles = (displayMode != .never)
let titleColor = nbAppearance?.largeTitleColor ??
lastNbAppearance?.largeTitleColor ??
nbAppearance?.titleColor ??
lastNbAppearance?.titleColor ??
defaultNbAppearance.largeTitleColor
navigationBar.largeTitleTextAttributes = [
.font: (nbAppearance?.largeTitleFont ?? lastNbAppearance?.largeTitleFont ?? defaultNbAppearance.largeTitleFont) as Any,
.foregroundColor: titleColor
]
}
let hidden = (nbAppearance?.hidden ?? lastNbAppearance?.hidden ?? defaultNbAppearance.hidden)
setNavigationBarHidden(hidden, animated: animated)
if nbAppearance?.transparent ?? lastNbAppearance?.transparent ?? false {
navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationBar.shadowImage = UIImage()
}
else {
navigationBar.setBackgroundImage(nil, for: .default)
navigationBar.shadowImage = nil
}
if nbAppearance?.backButtonHidden ?? defaultNbAppearance.backButtonHidden {
navigationBar.backIndicatorImage = UIImage()
navigationBar.backIndicatorTransitionMaskImage = UIImage()
let backItem = UIBarButtonItem(title: nil, style: UIBarButtonItem.Style.plain, target: nil, action: nil)
vc.navigationItem.backBarButtonItem = backItem
sourceVC?.navigationItem.backBarButtonItem = backItem
}
else {
if var image = nbAppearance?.backButtonImage ?? lastNbAppearance?.backButtonImage {
image = image.withRenderingMode(.alwaysTemplate)
navigationBar.backIndicatorImage = image
navigationBar.backIndicatorTransitionMaskImage = image
}
if let title = nbAppearance?.backButtonTitle {
let backItem = UIBarButtonItem(title: title, style: UIBarButtonItem.Style.plain, target: nil, action: nil)
vc.navigationItem.backBarButtonItem = backItem
sourceVC?.navigationItem.backBarButtonItem = backItem
}
}
}
/**
Tells the navigation controller to re-draw it's navigation bar.
*/
public func setNeedsNavigationBarAppearanceUpdate() {
guard let vc = self.topViewController else { return }
let sourceIndex = (viewControllers.count - 2)
let sourceVC = viewControllers[safe: sourceIndex]
update(with: vc, sourceVC: sourceVC, animated: true)
}
public override func setViewControllers(_ viewControllers: [UIViewController], animated: Bool) {
if let vc = viewControllers.last, viewControllers.count > 0 {
guard let _ = vc as? UINavigationBarAppearanceProvider else {
super.setViewControllers(viewControllers, animated: animated)
return
}
let sourceIndex = (viewControllers.count - 2)
let sourceVC = (sourceIndex >= 0) ? viewControllers[sourceIndex] : nil
update(with: vc, sourceVC: sourceVC, animated: false)
}
super.setViewControllers(viewControllers, animated: animated)
}
public override func pushViewController(_ viewController: UIViewController, animated: Bool) {
if viewController is UINavigationBarAppearanceProvider {
update(with: viewController, sourceVC: self.topViewController, animated: animated)
}
super.pushViewController(viewController, animated: animated)
}
public override func popViewController(animated: Bool) -> UIViewController? {
if let topVC = topViewController, let index = viewControllers.firstIndex(of: topVC) {
guard (index - 1) >= 0 else { return super.popViewController(animated: animated) }
let vc = viewControllers[index - 1]
update(with: vc, sourceVC: topVC, animated: animated)
}
return super.popViewController(animated: animated)
}
public override func popToRootViewController(animated: Bool) -> [UIViewController]? {
guard viewControllers.count > 0 else { return super.popToRootViewController(animated: animated) }
let viewController = viewControllers[0]
update(with: viewController, sourceVC: self.topViewController, animated: animated)
return super.popToRootViewController(animated: animated)
}
public override func popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? {
update(with: viewController, sourceVC: self.topViewController, animated: animated)
return super.popToViewController(viewController, animated: animated)
}
}
| mit |
perrywky/CCFlexbox | Source/AppDelegate.swift | 1 | 2504 | //
// AppDelegate.swift
// CCFlexbox
//
// Created by Perry on 15/12/28.
// Copyright © 2015年 Perry. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let storyboard = UIStoryboard(name: "Demo", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("DemoViewController") as! DemoViewController
// let nav = UINavigationController.init(rootViewController: MasterViewController.init())
window = UIWindow.init()
window!.rootViewController = vc
window!.makeKeyAndVisible()
window!.backgroundColor = UIColor.whiteColor()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
EvgenyKarkan/Feeds4U | iFeed/Sources/Data/Workers/Common/EVKParser.swift | 1 | 2253 | //
// EVKParser.swift
// iFeed
//
// Created by Evgeny Karkan on 8/16/15.
// Copyright (c) 2015 Evgeny Karkan. All rights reserved.
//
import FeedKit
// MARK: - EVKParserDelegate
protocol EVKParserDelegate: AnyObject {
func didStartParsingFeed()
func didEndParsingFeed(_ feed: Feed)
func didFailParsingFeed()
}
final class EVKParser: NSObject {
// MARK: - properties
weak var delegate: EVKParserDelegate?
private var feed : Feed!
// MARK: - public API
func beginParseURL(_ rssURL: URL) {
self.delegate?.didStartParsingFeed()
let parser = FeedParser(URL: rssURL)
parser.parseAsync { (result) in
DispatchQueue.main.async {
switch result {
case .success(let feed):
guard let rssFeed = feed.rssFeed else {
self.delegate?.didFailParsingFeed()
return
}
// Create Feed
self.feed = EVKBrain.brain.createEntity(name: kFeed) as? Feed
self.feed.title = rssFeed.title
self.feed.rssURL = rssURL.absoluteString
self.feed.summary = rssFeed.description
// Create Feeds
rssFeed.items?.forEach({ rrsFeedItem in
if let feedItem: FeedItem = EVKBrain.brain.createEntity(name: kFeedItem) as? FeedItem {
feedItem.title = rrsFeedItem.title ?? ""
feedItem.link = rrsFeedItem.link ?? ""
feedItem.publishDate = rrsFeedItem.pubDate ?? Date()
//relationship
feedItem.feed = self.feed
}
})
self.delegate?.didEndParsingFeed(self.feed)
case .failure( _):
self.delegate?.didFailParsingFeed()
}
}
}
}
}
| mit |
MakeSchool/TripPlanner | TripPlanner/ErrorHandling/DefaultErrorHandler.swift | 1 | 713 | //
// DefaultErrorHandler.swift
// TripPlanner
//
// Created by Benjamin Encz on 7/27/15.
// Copyright © 2015 Make School. All rights reserved.
//
import Foundation
class DefaultErrorHandler {
func handleError(error: ErrorType, displayToUser: Bool) {
print(error)
}
func displayErrorMessage(message: String) {
}
func wrap<ReturnType>(@noescape f: () throws -> ReturnType) -> ReturnType? {
do {
return try f()
} catch let error {
print(error)
return nil
}
}
func wrap<ReturnType>(@noescape f: () throws -> ReturnType?) -> ReturnType? {
do {
return try f()
} catch let error {
print(error)
return nil
}
}
} | mit |
Vadimkomis/Myclok | Pods/Auth0/Auth0/UserPatchAttributes.swift | 2 | 5648 | // UserPatchAttributes.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// Atributes of the user allowed to update using `patch()` method of `Users`
public class UserPatchAttributes {
private(set) var dictionary: [String: Any]
/**
Creates a new attributes
- parameter dictionary: default attribute values
- returns: new attributes
*/
public init(dictionary: [String: Any] = [:]) {
self.dictionary = dictionary
}
/**
Mark/Unmark a user as blocked
- parameter blocked: if the user is blocked
- returns: itself
*/
public func blocked(_ blocked: Bool) -> UserPatchAttributes {
dictionary["blocked"] = blocked
return self
}
/**
Changes the email of the user
- parameter email: new email for the user
- parameter verified: if the email is verified
- parameter verify: if the user should verify the email
- parameter connection: name of the connection
- parameter clientId: Auth0 clientId
- returns: itself
*/
public func email(_ email: String, verified: Bool? = nil, verify: Bool? = nil, connection: String, clientId: String) -> UserPatchAttributes {
dictionary["email"] = email
dictionary["verify_email"] = verify
dictionary["email_verified"] = verified
dictionary["connection"] = connection
dictionary["client_id"] = clientId
return self
}
/**
Sets the verified status of the email
- parameter verified: if the email is verified or not
- parameter connection: connection name
- returns: itself
*/
public func emailVerified(_ verified: Bool, connection: String) -> UserPatchAttributes {
dictionary["email_verified"] = verified
dictionary["connection"] = connection
return self
}
/**
Changes the phone number of the user (SMS connection only)
- parameter phoneNumber: new phone number for the user
- parameter verified: if the phone number is verified
- parameter verify: if the user should verify the phone number
- parameter connection: name of the connection
- parameter clientId: Auth0 clientId
- returns: itself
*/
public func phoneNumber(_ phoneNumber: String, verified: Bool? = nil, verify: Bool? = nil, connection: String, clientId: String) -> UserPatchAttributes {
dictionary["phone_number"] = phoneNumber
dictionary["verify_phone_number"] = verify
dictionary["phone_verified"] = verified
dictionary["connection"] = connection
dictionary["client_id"] = clientId
return self
}
/**
Sets the verified status of the phone number
- parameter verified: if the phone number is verified or not
- parameter connection: connection name
- returns: itself
*/
public func phoneVerified(_ verified: Bool, connection: String) -> UserPatchAttributes {
dictionary["phone_verified"] = verified
dictionary["connection"] = connection
return self
}
/**
Changes the user's password
- parameter password: new password for the user
- parameter verify: if the password should be verified by the user
- parameter connection: name of the connection
- returns: itself
*/
public func password(_ password: String, verify: Bool? = nil, connection: String) -> UserPatchAttributes {
dictionary["password"] = password
dictionary["connection"] = connection
dictionary["verify_password"] = verify
return self
}
/**
Changes the username
- parameter username: new username
- parameter connection: name of the connection
- returns: itself
*/
public func username(_ username: String, connection: String) -> UserPatchAttributes {
dictionary["username"] = username
dictionary["connection"] = connection
return self
}
/**
Updates user metadata
- parameter metadata: new user metadata values
- returns: itself
*/
public func userMetadata(_ metadata: [String: Any]) -> UserPatchAttributes {
dictionary["user_metadata"] = metadata
return self
}
/**
Updates app metadata
- parameter metadata: new app metadata values
- returns: itself
*/
public func appMetadata(_ metadata: [String: Any]) -> UserPatchAttributes {
dictionary["app_metadata"] = metadata
return self
}
}
| mit |
stripe/stripe-ios | StripePayments/StripePayments/Internal/Categories/NSDictionary+Stripe.swift | 1 | 4160 | //
// NSDictionary+Stripe.swift
// StripePayments
//
// Created by Jack Flintermann on 10/15/15.
// Copyright © 2015 Stripe, Inc. All rights reserved.
//
import Foundation
extension Dictionary where Key == AnyHashable, Value: Any {
@_spi(STP) public func stp_dictionaryByRemovingNulls() -> [AnyHashable: Any] {
var result = [AnyHashable: Any]()
(self as NSDictionary).enumerateKeysAndObjects({ key, obj, _ in
guard let key = key as? AnyHashable else {
assertionFailure()
return
}
if let obj = obj as? [Any] {
// Save array after removing any null values
let stp = obj.stp_arrayByRemovingNulls()
result[key] = stp
} else if let obj = obj as? [AnyHashable: Any] {
// Save dictionary after removing any null values
let stp = obj.stp_dictionaryByRemovingNulls()
result[key] = stp
} else if obj is NSNull {
// Skip null value
} else {
// Save other value
result[key] = obj
}
})
// Make immutable copy
return result
}
func stp_dictionaryByRemovingNonStrings() -> [String: String] {
var result: [String: String] = [:]
(self as NSDictionary).enumerateKeysAndObjects({ key, obj, _ in
if let key = key as? String, let obj = obj as? String {
// Save valid key/value pair
result[key] = obj
}
})
// Make immutable copy
return result
}
// Getters
@_spi(STP) public func stp_array(forKey key: String) -> [Any]? {
let value = self[key]
if value != nil {
return value as? [Any]
}
return nil
}
@_spi(STP) public func stp_bool(forKey key: String, or defaultValue: Bool) -> Bool {
let value = self[key]
if value != nil {
if let value = value as? NSNumber {
return value.boolValue
}
if value is NSString {
let string = (value as? String)?.lowercased()
// boolValue on NSString is true for "Y", "y", "T", "t", or 1-9
if (string == "true") || (string as NSString?)?.boolValue ?? false {
return true
} else {
return false
}
}
}
return defaultValue
}
@_spi(STP) public func stp_date(forKey key: String) -> Date? {
let value = self[key]
if let value = value as? NSNumber {
let timeInterval = value.doubleValue
return Date(timeIntervalSince1970: TimeInterval(timeInterval))
} else if let value = value as? NSString {
let timeInterval = value.doubleValue
return Date(timeIntervalSince1970: TimeInterval(timeInterval))
}
return nil
}
@_spi(STP) public func stp_dictionary(forKey key: String) -> [AnyHashable: Any]? {
let value = self[key]
if value != nil && (value is [AnyHashable: Any]) {
return value as? [AnyHashable: Any]
}
return nil
}
func stp_int(forKey key: String, or defaultValue: Int) -> Int {
let value = self[key]
if let value = value as? NSNumber {
return value.intValue
} else if let value = value as? NSString {
return Int(value.intValue)
}
return defaultValue
}
func stp_number(forKey key: String) -> NSNumber? {
return self[key] as? NSNumber
}
@_spi(STP) public func stp_string(forKey key: String) -> String? {
let value = self[key]
if value != nil && (value is NSString) {
return value as? String
}
return nil
}
func stp_url(forKey key: String) -> URL? {
let value = self[key]
if value != nil && (value is NSString) && ((value as? String)?.count ?? 0) > 0 {
return URL(string: value as? String ?? "")
}
return nil
}
}
| mit |
lojals/curiosity_reader | curiosity_reader/curiosity_reader/Charts/Classes/Charts/BarLineChartViewBase.swift | 1 | 52722 | //
// BarLineChartViewBase.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics.CGBase
import UIKit.UIGestureRecognizer
/// Base-class of LineChart, BarChart, ScatterChart and CandleStickChart.
public class BarLineChartViewBase: ChartViewBase, UIGestureRecognizerDelegate
{
/// the maximum number of entried to which values will be drawn
internal var _maxVisibleValueCount = 100
private var _pinchZoomEnabled = false
private var _doubleTapToZoomEnabled = true
private var _dragEnabled = true
private var _scaleXEnabled = true
private var _scaleYEnabled = true
/// the color for the background of the chart-drawing area (everything behind the grid lines).
public var gridBackgroundColor = UIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0)
public var borderColor = UIColor.blackColor()
public var borderLineWidth: CGFloat = 1.0
/// flag indicating if the grid background should be drawn or not
public var drawGridBackgroundEnabled = true
/// Sets drawing the borders rectangle to true. If this is enabled, there is no point drawing the axis-lines of x- and y-axis.
public var drawBordersEnabled = false
/// the object representing the labels on the y-axis, this object is prepared
/// in the pepareYLabels() method
internal var _leftAxis: ChartYAxis!
internal var _rightAxis: ChartYAxis!
/// the object representing the labels on the x-axis
internal var _xAxis: ChartXAxis!
internal var _leftYAxisRenderer: ChartYAxisRenderer!
internal var _rightYAxisRenderer: ChartYAxisRenderer!
internal var _leftAxisTransformer: ChartTransformer!
internal var _rightAxisTransformer: ChartTransformer!
internal var _xAxisRenderer: ChartXAxisRenderer!
private var _tapGestureRecognizer: UITapGestureRecognizer!
private var _doubleTapGestureRecognizer: UITapGestureRecognizer!
private var _pinchGestureRecognizer: UIPinchGestureRecognizer!
private var _panGestureRecognizer: UIPanGestureRecognizer!
/// flag that indicates if a custom viewport offset has been set
private var _customViewPortEnabled = false
public override init(frame: CGRect)
{
super.init(frame: frame);
}
public required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder);
}
deinit
{
stopDeceleration();
}
internal override func initialize()
{
super.initialize();
_leftAxis = ChartYAxis(position: .Left);
_rightAxis = ChartYAxis(position: .Right);
_xAxis = ChartXAxis();
_leftAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler);
_rightAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler);
_leftYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer);
_rightYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer);
_xAxisRenderer = ChartXAxisRenderer(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer);
_tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:"));
_doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("doubleTapGestureRecognized:"));
_doubleTapGestureRecognizer.numberOfTapsRequired = 2;
_pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: Selector("pinchGestureRecognized:"));
_panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("panGestureRecognized:"));
_pinchGestureRecognizer.delegate = self;
_panGestureRecognizer.delegate = self;
self.addGestureRecognizer(_tapGestureRecognizer);
self.addGestureRecognizer(_doubleTapGestureRecognizer);
self.addGestureRecognizer(_pinchGestureRecognizer);
self.addGestureRecognizer(_panGestureRecognizer);
_doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled;
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled;
_panGestureRecognizer.enabled = _dragEnabled;
}
public override func drawRect(rect: CGRect)
{
super.drawRect(rect);
if (_dataNotSet)
{
return;
}
let context = UIGraphicsGetCurrentContext();
calcModulus();
if (_xAxisRenderer !== nil)
{
_xAxisRenderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus);
}
if (renderer !== nil)
{
renderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus);
}
// execute all drawing commands
drawGridBackground(context: context);
if (_leftAxis.isEnabled)
{
_leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum);
}
if (_rightAxis.isEnabled)
{
_rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum);
}
_xAxisRenderer?.renderAxisLine(context: context);
_leftYAxisRenderer?.renderAxisLine(context: context);
_rightYAxisRenderer?.renderAxisLine(context: context);
// make sure the graph values and grid cannot be drawn outside the content-rect
CGContextSaveGState(context);
CGContextClipToRect(context, _viewPortHandler.contentRect);
if (_xAxis.isDrawLimitLinesBehindDataEnabled)
{
_xAxisRenderer?.renderLimitLines(context: context);
}
if (_leftAxis.isDrawLimitLinesBehindDataEnabled)
{
_leftYAxisRenderer?.renderLimitLines(context: context);
}
if (_rightAxis.isDrawLimitLinesBehindDataEnabled)
{
_rightYAxisRenderer?.renderLimitLines(context: context);
}
_xAxisRenderer?.renderGridLines(context: context);
_leftYAxisRenderer?.renderGridLines(context: context);
_rightYAxisRenderer?.renderGridLines(context: context);
renderer?.drawData(context: context);
if (!_xAxis.isDrawLimitLinesBehindDataEnabled)
{
_xAxisRenderer?.renderLimitLines(context: context);
}
if (!_leftAxis.isDrawLimitLinesBehindDataEnabled)
{
_leftYAxisRenderer?.renderLimitLines(context: context);
}
if (!_rightAxis.isDrawLimitLinesBehindDataEnabled)
{
_rightYAxisRenderer?.renderLimitLines(context: context);
}
// if highlighting is enabled
if (highlightEnabled && highlightIndicatorEnabled && valuesToHighlight())
{
renderer?.drawHighlighted(context: context, indices: _indicesToHightlight);
}
// Removes clipping rectangle
CGContextRestoreGState(context);
renderer!.drawExtras(context: context);
_xAxisRenderer.renderAxisLabels(context: context);
_leftYAxisRenderer.renderAxisLabels(context: context);
_rightYAxisRenderer.renderAxisLabels(context: context);
renderer!.drawValues(context: context);
_legendRenderer.renderLegend(context: context);
// drawLegend();
drawMarkers(context: context);
drawDescription(context: context);
}
internal func prepareValuePxMatrix()
{
_rightAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_rightAxis.axisRange), chartYMin: _rightAxis.axisMinimum);
_leftAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_leftAxis.axisRange), chartYMin: _leftAxis.axisMinimum);
}
internal func prepareOffsetMatrix()
{
_rightAxisTransformer.prepareMatrixOffset(_rightAxis.isInverted);
_leftAxisTransformer.prepareMatrixOffset(_leftAxis.isInverted);
}
public override func notifyDataSetChanged()
{
if (_dataNotSet)
{
return;
}
calcMinMax();
_leftAxis?._defaultValueFormatter = _defaultValueFormatter;
_rightAxis?._defaultValueFormatter = _defaultValueFormatter;
_leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum);
_rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum);
_xAxisRenderer?.computeAxis(xValAverageLength: _data.xValAverageLength, xValues: _data.xVals);
_legendRenderer?.computeLegend(_data);
calculateOffsets();
setNeedsDisplay();
}
internal override func calcMinMax()
{
var minLeft = _data.getYMin(.Left);
var maxLeft = _data.getYMax(.Left);
var minRight = _data.getYMin(.Right);
var maxRight = _data.getYMax(.Right);
var leftRange = abs(maxLeft - (_leftAxis.isStartAtZeroEnabled ? 0.0 : minLeft));
var rightRange = abs(maxRight - (_rightAxis.isStartAtZeroEnabled ? 0.0 : minRight));
// in case all values are equal
if (leftRange == 0.0)
{
maxLeft = maxLeft + 1.0;
if (!_leftAxis.isStartAtZeroEnabled)
{
minLeft = minLeft - 1.0;
}
}
if (rightRange == 0.0)
{
maxRight = maxRight + 1.0;
if (!_rightAxis.isStartAtZeroEnabled)
{
minRight = minRight - 1.0;
}
}
var topSpaceLeft = leftRange * Float(_leftAxis.spaceTop);
var topSpaceRight = rightRange * Float(_rightAxis.spaceTop);
var bottomSpaceLeft = leftRange * Float(_leftAxis.spaceBottom);
var bottomSpaceRight = rightRange * Float(_rightAxis.spaceBottom);
_chartXMax = Float(_data.xVals.count - 1);
_deltaX = CGFloat(abs(_chartXMax - _chartXMin));
_leftAxis.axisMaximum = !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft);
_rightAxis.axisMaximum = !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight);
_leftAxis.axisMinimum = !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft);
_rightAxis.axisMinimum = !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight);
// consider starting at zero (0)
if (_leftAxis.isStartAtZeroEnabled)
{
_leftAxis.axisMinimum = 0.0;
}
if (_rightAxis.isStartAtZeroEnabled)
{
_rightAxis.axisMinimum = 0.0;
}
_leftAxis.axisRange = abs(_leftAxis.axisMaximum - _leftAxis.axisMinimum);
_rightAxis.axisRange = abs(_rightAxis.axisMaximum - _rightAxis.axisMinimum);
}
internal override func calculateOffsets()
{
if (!_customViewPortEnabled)
{
var offsetLeft = CGFloat(0.0);
var offsetRight = CGFloat(0.0);
var offsetTop = CGFloat(0.0);
var offsetBottom = CGFloat(0.0);
// setup offsets for legend
if (_legend !== nil && _legend.isEnabled)
{
if (_legend.position == .RightOfChart
|| _legend.position == .RightOfChartCenter)
{
offsetRight += _legend.textWidthMax + _legend.xOffset * 2.0;
}
if (_legend.position == .LeftOfChart
|| _legend.position == .LeftOfChartCenter)
{
offsetLeft += _legend.textWidthMax + _legend.xOffset * 2.0;
}
else if (_legend.position == .BelowChartLeft
|| _legend.position == .BelowChartRight
|| _legend.position == .BelowChartCenter)
{
offsetBottom += _legend.textHeightMax * 3.0;
}
}
// offsets for y-labels
if (leftAxis.needsOffset)
{
offsetLeft += leftAxis.requiredSize().width;
}
if (rightAxis.needsOffset)
{
offsetRight += rightAxis.requiredSize().width;
}
var xlabelheight = xAxis.labelHeight * 2.0;
if (xAxis.isEnabled)
{
// offsets for x-labels
if (xAxis.labelPosition == .Bottom)
{
offsetBottom += xlabelheight;
}
else if (xAxis.labelPosition == .Top)
{
offsetTop += xlabelheight;
}
else if (xAxis.labelPosition == .BothSided)
{
offsetBottom += xlabelheight;
offsetTop += xlabelheight;
}
}
var min = CGFloat(10.0);
_viewPortHandler.restrainViewPort(
offsetLeft: max(min, offsetLeft),
offsetTop: max(min, offsetTop),
offsetRight: max(min, offsetRight),
offsetBottom: max(min, offsetBottom));
}
prepareOffsetMatrix();
prepareValuePxMatrix();
}
/// calculates the modulus for x-labels and grid
internal func calcModulus()
{
if (_xAxis === nil || !_xAxis.isEnabled)
{
return;
}
if (!_xAxis.isAxisModulusCustom)
{
_xAxis.axisLabelModulus = Int(ceil((CGFloat(_data.xValCount) * _xAxis.labelWidth) / (_viewPortHandler.contentWidth * _viewPortHandler.touchMatrix.a)));
}
if (_xAxis.axisLabelModulus < 1)
{
_xAxis.axisLabelModulus = 1;
}
}
public override func getMarkerPosition(#entry: ChartDataEntry, dataSetIndex: Int) -> CGPoint
{
var xPos = CGFloat(entry.xIndex);
if (self.isKindOfClass(BarChartView))
{
var bd = _data as! BarChartData;
var space = bd.groupSpace;
var j = _data.getDataSetByIndex(dataSetIndex)!.entryIndex(entry: entry, isEqual: true);
var x = CGFloat(j * (_data.dataSetCount - 1) + dataSetIndex) + space * CGFloat(j) + space / 2.0;
xPos += x;
}
// position of the marker depends on selected value index and value
var pt = CGPoint(x: xPos, y: CGFloat(entry.value) * _animator.phaseY);
getTransformer(_data.getDataSetByIndex(dataSetIndex)!.axisDependency).pointValueToPixel(&pt);
return pt;
}
/// draws the grid background
internal func drawGridBackground(#context: CGContext)
{
if (drawGridBackgroundEnabled || drawBordersEnabled)
{
CGContextSaveGState(context);
}
if (drawGridBackgroundEnabled)
{
// draw the grid background
CGContextSetFillColorWithColor(context, gridBackgroundColor.CGColor);
CGContextFillRect(context, _viewPortHandler.contentRect);
}
if (drawBordersEnabled)
{
CGContextSetLineWidth(context, borderLineWidth);
CGContextSetStrokeColorWithColor(context, borderColor.CGColor);
CGContextStrokeRect(context, _viewPortHandler.contentRect);
}
if (drawGridBackgroundEnabled || drawBordersEnabled)
{
CGContextRestoreGState(context);
}
}
/// Returns the Transformer class that contains all matrices and is
/// responsible for transforming values into pixels on the screen and
/// backwards.
public func getTransformer(which: ChartYAxis.AxisDependency) -> ChartTransformer
{
if (which == .Left)
{
return _leftAxisTransformer;
}
else
{
return _rightAxisTransformer;
}
}
// MARK: - Gestures
private enum GestureScaleAxis
{
case Both
case X
case Y
}
private var _isDragging = false;
private var _isScaling = false;
private var _gestureScaleAxis = GestureScaleAxis.Both;
private var _closestDataSetToTouch: ChartDataSet!;
private var _panGestureReachedEdge: Bool = false;
private weak var _outerScrollView: UIScrollView?;
/// the last highlighted object
private var _lastHighlighted: ChartHighlight!;
private var _lastPanPoint = CGPoint() /// This is to prevent using setTranslation which resets velocity
private var _decelerationLastTime: NSTimeInterval = 0.0
private var _decelerationDisplayLink: CADisplayLink!
private var _decelerationVelocity = CGPoint()
@objc private func tapGestureRecognized(recognizer: UITapGestureRecognizer)
{
if (_dataNotSet)
{
return;
}
if (recognizer.state == UIGestureRecognizerState.Ended)
{
var h = getHighlightByTouchPoint(recognizer.locationInView(self));
if (h === nil || h!.isEqual(_lastHighlighted))
{
self.highlightValue(highlight: nil, callDelegate: true);
_lastHighlighted = nil;
}
else
{
_lastHighlighted = h;
self.highlightValue(highlight: h, callDelegate: true);
}
}
}
@objc private func doubleTapGestureRecognized(recognizer: UITapGestureRecognizer)
{
if (_dataNotSet)
{
return;
}
if (recognizer.state == UIGestureRecognizerState.Ended)
{
if (!_dataNotSet && _doubleTapToZoomEnabled)
{
var location = recognizer.locationInView(self);
location.x = location.x - _viewPortHandler.offsetLeft;
if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
location.y = -(location.y - _viewPortHandler.offsetTop);
}
else
{
location.y = -(self.bounds.size.height - location.y - _viewPortHandler.offsetBottom);
}
self.zoom(1.4, scaleY: 1.4, x: location.x, y: location.y);
}
}
}
@objc private func pinchGestureRecognized(recognizer: UIPinchGestureRecognizer)
{
if (recognizer.state == UIGestureRecognizerState.Began)
{
stopDeceleration();
if (!_dataNotSet && (_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled))
{
_isScaling = true;
if (_pinchZoomEnabled)
{
_gestureScaleAxis = .Both;
}
else
{
var x = abs(recognizer.locationInView(self).x - recognizer.locationOfTouch(1, inView: self).x);
var y = abs(recognizer.locationInView(self).y - recognizer.locationOfTouch(1, inView: self).y);
if (x > y)
{
_gestureScaleAxis = .X;
}
else
{
_gestureScaleAxis = .Y;
}
}
}
}
else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled)
{
if (_isScaling)
{
_isScaling = false;
}
}
else if (recognizer.state == UIGestureRecognizerState.Changed)
{
if (_isScaling)
{
var location = recognizer.locationInView(self);
location.x = location.x - _viewPortHandler.offsetLeft;
if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
location.y = -(location.y - _viewPortHandler.offsetTop);
}
else
{
location.y = -(_viewPortHandler.chartHeight - location.y - _viewPortHandler.offsetBottom);
}
var scaleX = (_gestureScaleAxis == .Both || _gestureScaleAxis == .X) && _scaleXEnabled ? recognizer.scale : 1.0;
var scaleY = (_gestureScaleAxis == .Both || _gestureScaleAxis == .Y) && _scaleYEnabled ? recognizer.scale : 1.0;
var matrix = CGAffineTransformMakeTranslation(location.x, location.y);
matrix = CGAffineTransformScale(matrix, scaleX, scaleY);
matrix = CGAffineTransformTranslate(matrix,
-location.x, -location.y);
matrix = CGAffineTransformConcat(_viewPortHandler.touchMatrix, matrix);
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
recognizer.scale = 1.0;
}
}
}
@objc private func panGestureRecognized(recognizer: UIPanGestureRecognizer)
{
if (recognizer.state == UIGestureRecognizerState.Began)
{
stopDeceleration();
if ((!_dataNotSet && _dragEnabled && !self.hasNoDragOffset) || !self.isFullyZoomedOut)
{
_isDragging = true;
_closestDataSetToTouch = getDataSetByTouchPoint(recognizer.locationOfTouch(0, inView: self));
var translation = recognizer.translationInView(self);
if (!performPanChange(translation: translation))
{
if (_outerScrollView !== nil)
{
// We can stop dragging right now, and let the scroll view take control
_outerScrollView = nil;
_isDragging = false;
}
}
else
{
if (_outerScrollView !== nil)
{
// Prevent the parent scroll view from scrolling
_outerScrollView?.scrollEnabled = false;
}
}
_lastPanPoint = recognizer.translationInView(self);
}
}
else if (recognizer.state == UIGestureRecognizerState.Changed)
{
if (_isDragging)
{
var originalTranslation = recognizer.translationInView(self);
var translation = CGPoint(x: originalTranslation.x - _lastPanPoint.x, y: originalTranslation.y - _lastPanPoint.y);
performPanChange(translation: translation);
_lastPanPoint = originalTranslation;
}
else if (isHighlightPerDragEnabled)
{
var h = getHighlightByTouchPoint(recognizer.locationInView(self));
if ((h === nil && _lastHighlighted !== nil) ||
(h !== nil && _lastHighlighted === nil) ||
(h !== nil && _lastHighlighted !== nil && !h!.isEqual(_lastHighlighted)))
{
_lastHighlighted = h;
self.highlightValue(highlight: h, callDelegate: true);
}
}
}
else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled)
{
if (_isDragging)
{
if (recognizer.state == UIGestureRecognizerState.Ended && isDragDecelerationEnabled)
{
stopDeceleration();
_decelerationLastTime = CACurrentMediaTime();
_decelerationVelocity = recognizer.velocityInView(self);
_decelerationDisplayLink = CADisplayLink(target: self, selector: Selector("decelerationLoop"));
_decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes);
}
_isDragging = false;
}
if (_outerScrollView !== nil)
{
_outerScrollView?.scrollEnabled = true;
_outerScrollView = nil;
}
}
}
private func performPanChange(var #translation: CGPoint) -> Bool
{
if (isAnyAxisInverted && _closestDataSetToTouch !== nil
&& getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
if (self is HorizontalBarChartView)
{
translation.x = -translation.x;
}
else
{
translation.y = -translation.y;
}
}
var originalMatrix = _viewPortHandler.touchMatrix;
var matrix = CGAffineTransformMakeTranslation(translation.x, translation.y);
matrix = CGAffineTransformConcat(originalMatrix, matrix);
matrix = _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
// Did we managed to actually drag or did we reach the edge?
return matrix.tx != originalMatrix.tx || matrix.ty != originalMatrix.ty;
}
public func stopDeceleration()
{
if (_decelerationDisplayLink !== nil)
{
_decelerationDisplayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes);
_decelerationDisplayLink = nil;
}
}
@objc private func decelerationLoop()
{
var currentTime = CACurrentMediaTime();
_decelerationVelocity.x *= self.dragDecelerationFrictionCoef;
_decelerationVelocity.y *= self.dragDecelerationFrictionCoef;
var timeInterval = CGFloat(currentTime - _decelerationLastTime);
var distance = CGPoint(
x: _decelerationVelocity.x * timeInterval,
y: _decelerationVelocity.y * timeInterval
);
if (!performPanChange(translation: distance))
{
// We reached the edge, stop
_decelerationVelocity.x = 0.0;
_decelerationVelocity.y = 0.0;
}
_decelerationLastTime = currentTime;
if (abs(_decelerationVelocity.x) < 0.001 && abs(_decelerationVelocity.y) < 0.001)
{
stopDeceleration();
}
}
public override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool
{
if (!super.gestureRecognizerShouldBegin(gestureRecognizer))
{
return false;
}
if (gestureRecognizer == _panGestureRecognizer)
{
if (_dataNotSet || !_dragEnabled || !self.hasNoDragOffset ||
(self.isFullyZoomedOut && !self.isHighlightPerDragEnabled))
{
return false;
}
}
else if (gestureRecognizer == _pinchGestureRecognizer)
{
if (_dataNotSet || (!_pinchZoomEnabled && !_scaleXEnabled && !_scaleYEnabled))
{
return false;
}
}
return true;
}
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool
{
if ((gestureRecognizer.isKindOfClass(UIPinchGestureRecognizer) &&
otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer)) ||
(gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) &&
otherGestureRecognizer.isKindOfClass(UIPinchGestureRecognizer)))
{
return true;
}
if (gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) &&
otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && (
gestureRecognizer == _panGestureRecognizer
))
{
var scrollView = self.superview;
while (scrollView !== nil && !scrollView!.isKindOfClass(UIScrollView))
{
scrollView = scrollView?.superview;
}
var foundScrollView = scrollView as? UIScrollView;
if (foundScrollView !== nil && !foundScrollView!.scrollEnabled)
{
foundScrollView = nil;
}
var scrollViewPanGestureRecognizer: UIGestureRecognizer!;
if (foundScrollView !== nil)
{
for scrollRecognizer in foundScrollView!.gestureRecognizers as! [UIGestureRecognizer]
{
if (scrollRecognizer.isKindOfClass(UIPanGestureRecognizer))
{
scrollViewPanGestureRecognizer = scrollRecognizer as! UIPanGestureRecognizer;
break;
}
}
}
if (otherGestureRecognizer === scrollViewPanGestureRecognizer)
{
_outerScrollView = foundScrollView;
return true;
}
}
return false;
}
/// MARK: Viewport modifiers
/// Zooms in by 1.4f, into the charts center. center.
public func zoomIn()
{
var matrix = _viewPortHandler.zoomIn(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0));
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
}
/// Zooms out by 0.7f, from the charts center. center.
public func zoomOut()
{
var matrix = _viewPortHandler.zoomOut(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0));
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
}
/// Zooms in or out by the given scale factor. x and y are the coordinates
/// (in pixels) of the zoom center.
///
/// :param: scaleX if < 1f --> zoom out, if > 1f --> zoom in
/// :param: scaleY if < 1f --> zoom out, if > 1f --> zoom in
/// :param: x
/// :param: y
public func zoom(scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat)
{
var matrix = _viewPortHandler.zoom(scaleX: scaleX, scaleY: scaleY, x: x, y: -y);
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
}
/// Resets all zooming and dragging and makes the chart fit exactly it's bounds.
public func fitScreen()
{
var matrix = _viewPortHandler.fitScreen();
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
}
/// Sets the minimum scale value to which can be zoomed out. 1f = fitScreen
public func setScaleMinima(scaleX: CGFloat, scaleY: CGFloat)
{
_viewPortHandler.setMinimumScaleX(scaleX);
_viewPortHandler.setMinimumScaleY(scaleY);
}
/// Sets the size of the area (range on the x-axis) that should be maximum
/// visible at once. If this is e.g. set to 10, no more than 10 values on the
/// x-axis can be viewed at once without scrolling.
public func setVisibleXRange(xRange: CGFloat)
{
var xScale = _deltaX / (xRange);
_viewPortHandler.setMinimumScaleX(xScale);
}
/// Sets the size of the area (range on the y-axis) that should be maximum visible at once.
///
/// :param: yRange
/// :param: axis - the axis for which this limit should apply
public func setVisibleYRange(yRange: CGFloat, axis: ChartYAxis.AxisDependency)
{
var yScale = getDeltaY(axis) / yRange;
_viewPortHandler.setMinimumScaleY(yScale);
}
/// Moves the left side of the current viewport to the specified x-index.
public func moveViewToX(xIndex: Int)
{
if (_viewPortHandler.hasChartDimens)
{
var pt = CGPoint(x: CGFloat(xIndex), y: 0.0);
getTransformer(.Left).pointValueToPixel(&pt);
_viewPortHandler.centerViewPort(pt: pt, chart: self);
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewToX(xIndex); });
}
}
/// Centers the viewport to the specified y-value on the y-axis.
///
/// :param: yValue
/// :param: axis - which axis should be used as a reference for the y-axis
public func moveViewToY(yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY;
var pt = CGPoint(x: 0.0, y: yValue + valsInView / 2.0);
getTransformer(axis).pointValueToPixel(&pt);
_viewPortHandler.centerViewPort(pt: pt, chart: self);
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewToY(yValue, axis: axis); });
}
}
/// This will move the left side of the current viewport to the specified x-index on the x-axis, and center the viewport to the specified y-value on the y-axis.
///
/// :param: xIndex
/// :param: yValue
/// :param: axis - which axis should be used as a reference for the y-axis
public func moveViewTo(#xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY;
var pt = CGPoint(x: CGFloat(xIndex), y: yValue + valsInView / 2.0);
getTransformer(axis).pointValueToPixel(&pt);
_viewPortHandler.centerViewPort(pt: pt, chart: self);
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewTo(xIndex: xIndex, yValue: yValue, axis: axis); });
}
}
/// This will move the center of the current viewport to the specified x-index and y-value.
///
/// :param: xIndex
/// :param: yValue
/// :param: axis - which axis should be used as a reference for the y-axis
public func centerViewTo(#xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY;
var xsInView = CGFloat(xAxis.values.count) / _viewPortHandler.scaleX;
var pt = CGPoint(x: CGFloat(xIndex) - xsInView / 2.0, y: yValue + valsInView / 2.0);
getTransformer(axis).pointValueToPixel(&pt);
_viewPortHandler.centerViewPort(pt: pt, chart: self);
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.centerViewTo(xIndex: xIndex, yValue: yValue, axis: axis); });
}
}
/// Sets custom offsets for the current ViewPort (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use resetViewPortOffsets() to undo this.
public func setViewPortOffsets(#left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat)
{
_customViewPortEnabled = true;
if (NSThread.isMainThread())
{
self._viewPortHandler.restrainViewPort(offsetLeft: left, offsetTop: top, offsetRight: right, offsetBottom: bottom);
prepareOffsetMatrix();
prepareValuePxMatrix();
}
else
{
dispatch_async(dispatch_get_main_queue(), {
self.setViewPortOffsets(left: left, top: top, right: right, bottom: bottom);
});
}
}
/// Resets all custom offsets set via setViewPortOffsets(...) method. Allows the chart to again calculate all offsets automatically.
public func resetViewPortOffsets()
{
_customViewPortEnabled = false;
calculateOffsets();
}
// MARK: - Accessors
/// Returns the delta-y value (y-value range) of the specified axis.
public func getDeltaY(axis: ChartYAxis.AxisDependency) -> CGFloat
{
if (axis == .Left)
{
return CGFloat(leftAxis.axisRange);
}
else
{
return CGFloat(rightAxis.axisRange);
}
}
/// Returns the position (in pixels) the provided Entry has inside the chart view
public func getPosition(e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint
{
var vals = CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value));
getTransformer(axis).pointValueToPixel(&vals);
return vals;
}
/// the number of maximum visible drawn values on the chart
/// only active when setDrawValues() is enabled
public var maxVisibleValueCount: Int
{
get
{
return _maxVisibleValueCount;
}
set
{
_maxVisibleValueCount = newValue;
}
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
public var dragEnabled: Bool
{
get
{
return _dragEnabled;
}
set
{
if (_dragEnabled != newValue)
{
_dragEnabled = newValue;
}
}
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
public var isDragEnabled: Bool
{
return dragEnabled;
}
/// is scaling enabled? (zooming in and out by gesture) for the chart (this does not affect dragging).
public func setScaleEnabled(enabled: Bool)
{
if (_scaleXEnabled != enabled || _scaleYEnabled != enabled)
{
_scaleXEnabled = enabled;
_scaleYEnabled = enabled;
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled;
}
}
public var scaleXEnabled: Bool
{
get
{
return _scaleXEnabled
}
set
{
if (_scaleXEnabled != newValue)
{
_scaleXEnabled = newValue;
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled;
}
}
}
public var scaleYEnabled: Bool
{
get
{
return _scaleYEnabled
}
set
{
if (_scaleYEnabled != newValue)
{
_scaleYEnabled = newValue;
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled;
}
}
}
public var isScaleXEnabled: Bool { return scaleXEnabled; }
public var isScaleYEnabled: Bool { return scaleYEnabled; }
/// flag that indicates if double tap zoom is enabled or not
public var doubleTapToZoomEnabled: Bool
{
get
{
return _doubleTapToZoomEnabled;
}
set
{
if (_doubleTapToZoomEnabled != newValue)
{
_doubleTapToZoomEnabled = newValue;
_doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled;
}
}
}
/// :returns: true if zooming via double-tap is enabled false if not.
/// :default: true
public var isDoubleTapToZoomEnabled: Bool
{
return doubleTapToZoomEnabled;
}
/// flag that indicates if highlighting per dragging over a fully zoomed out chart is enabled
public var highlightPerDragEnabled = true
/// If set to true, highlighting per dragging over a fully zoomed out chart is enabled
/// You might want to disable this when using inside a UIScrollView
/// :default: true
public var isHighlightPerDragEnabled: Bool
{
return highlightPerDragEnabled;
}
/// if set to true, the highlight indicator (lines for linechart, dark bar for barchart) will be drawn upon selecting values.
public var highlightIndicatorEnabled = true
/// If set to true, the highlight indicator (vertical line for LineChart and
/// ScatterChart, dark bar overlay for BarChart) that gives visual indication
/// that an Entry has been selected will be drawn upon selecting values. This
/// does not depend on the MarkerView.
/// :default: true
public var isHighlightIndicatorEnabled: Bool
{
return highlightIndicatorEnabled;
}
/// :returns: true if drawing the grid background is enabled, false if not.
/// :default: true
public var isDrawGridBackgroundEnabled: Bool
{
return drawGridBackgroundEnabled;
}
/// :returns: true if drawing the borders rectangle is enabled, false if not.
/// :default: false
public var isDrawBordersEnabled: Bool
{
return drawBordersEnabled;
}
/// Returns the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the Line-, Scatter-, or CandleStick-Chart.
public func getHighlightByTouchPoint(var pt: CGPoint) -> ChartHighlight!
{
if (_dataNotSet || _data === nil)
{
println("Can't select by touch. No data set.");
return nil;
}
var valPt = CGPoint();
valPt.x = pt.x;
valPt.y = 0.0;
// take any transformer to determine the x-axis value
_leftAxisTransformer.pixelToValue(&valPt);
var xTouchVal = valPt.x;
var base = floor(xTouchVal);
var touchOffset = _deltaX * 0.025;
// touch out of chart
if (xTouchVal < -touchOffset || xTouchVal > _deltaX + touchOffset)
{
return nil;
}
if (base < 0.0)
{
base = 0.0;
}
if (base >= _deltaX)
{
base = _deltaX - 1.0;
}
var xIndex = Int(base);
// check if we are more than half of a x-value or not
if (xTouchVal - base > 0.5)
{
xIndex = Int(base + 1.0);
}
var valsAtIndex = getYValsAtIndex(xIndex);
var leftdist = ChartUtils.getMinimumDistance(valsAtIndex, val: Float(pt.y), axis: .Left);
var rightdist = ChartUtils.getMinimumDistance(valsAtIndex, val: Float(pt.y), axis: .Right);
if (_data!.getFirstRight() === nil)
{
rightdist = FLT_MAX;
}
if (_data!.getFirstLeft() === nil)
{
leftdist = FLT_MAX;
}
var axis: ChartYAxis.AxisDependency = leftdist < rightdist ? .Left : .Right;
var dataSetIndex = ChartUtils.closestDataSetIndex(valsAtIndex, value: Float(pt.y), axis: axis);
if (dataSetIndex == -1)
{
return nil;
}
return ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex);
}
/// Returns an array of SelInfo objects for the given x-index. The SelInfo
/// objects give information about the value at the selected index and the
/// DataSet it belongs to.
public func getYValsAtIndex(xIndex: Int) -> [ChartSelInfo]
{
var vals = [ChartSelInfo]();
var pt = CGPoint();
for (var i = 0, count = _data.dataSetCount; i < count; i++)
{
var dataSet = _data.getDataSetByIndex(i);
if (dataSet === nil)
{
continue;
}
// extract all y-values from all DataSets at the given x-index
var yVal = dataSet!.yValForXIndex(xIndex);
pt.y = CGFloat(yVal);
getTransformer(dataSet!.axisDependency).pointValueToPixel(&pt);
if (!isnan(pt.y))
{
vals.append(ChartSelInfo(value: Float(pt.y), dataSetIndex: i, dataSet: dataSet!));
}
}
return vals;
}
/// Returns the x and y values in the chart at the given touch point
/// (encapsulated in a PointD). This method transforms pixel coordinates to
/// coordinates / values in the chart. This is the opposite method to
/// getPixelsForValues(...).
public func getValueByTouchPoint(var #pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGPoint
{
getTransformer(axis).pixelToValue(&pt);
return pt;
}
/// Transforms the given chart values into pixels. This is the opposite
/// method to getValueByTouchPoint(...).
public func getPixelForValue(x: Float, y: Float, axis: ChartYAxis.AxisDependency) -> CGPoint
{
var pt = CGPoint(x: CGFloat(x), y: CGFloat(y));
getTransformer(axis).pointValueToPixel(&pt);
return pt;
}
/// returns the y-value at the given touch position (must not necessarily be
/// a value contained in one of the datasets)
public func getYValueByTouchPoint(#pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGFloat
{
return getValueByTouchPoint(pt: pt, axis: axis).y;
}
/// returns the Entry object displayed at the touched position of the chart
public func getEntryByTouchPoint(pt: CGPoint) -> ChartDataEntry!
{
var h = getHighlightByTouchPoint(pt);
if (h !== nil)
{
return _data!.getEntryForHighlight(h!);
}
return nil;
}
///returns the DataSet object displayed at the touched position of the chart
public func getDataSetByTouchPoint(pt: CGPoint) -> BarLineScatterCandleChartDataSet!
{
var h = getHighlightByTouchPoint(pt);
if (h !== nil)
{
return _data.getDataSetByIndex(h.dataSetIndex) as! BarLineScatterCandleChartDataSet!;
}
return nil;
}
/// Returns the lowest x-index (value on the x-axis) that is still visible on he chart.
public var lowestVisibleXIndex: Int
{
var pt = CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom);
getTransformer(.Left).pixelToValue(&pt);
return (pt.x <= 0.0) ? 0 : Int(pt.x + 1.0);
}
/// Returns the highest x-index (value on the x-axis) that is still visible on the chart.
public var highestVisibleXIndex: Int
{
var pt = CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom);
getTransformer(.Left).pixelToValue(&pt);
return (Int(pt.x) >= _data.xValCount) ? _data.xValCount - 1 : Int(pt.x);
}
/// returns the current x-scale factor
public var scaleX: CGFloat
{
if (_viewPortHandler === nil)
{
return 1.0;
}
return _viewPortHandler.scaleX;
}
/// returns the current y-scale factor
public var scaleY: CGFloat
{
if (_viewPortHandler === nil)
{
return 1.0;
}
return _viewPortHandler.scaleY;
}
/// if the chart is fully zoomed out, return true
public var isFullyZoomedOut: Bool { return _viewPortHandler.isFullyZoomedOut; }
/// Returns the left y-axis object. In the horizontal bar-chart, this is the
/// top axis.
public var leftAxis: ChartYAxis
{
return _leftAxis;
}
/// Returns the right y-axis object. In the horizontal bar-chart, this is the
/// bottom axis.
public var rightAxis: ChartYAxis { return _rightAxis; }
/// Returns the y-axis object to the corresponding AxisDependency. In the
/// horizontal bar-chart, LEFT == top, RIGHT == BOTTOM
public func getAxis(axis: ChartYAxis.AxisDependency) -> ChartYAxis
{
if (axis == .Left)
{
return _leftAxis;
}
else
{
return _rightAxis;
}
}
/// Returns the object representing all x-labels, this method can be used to
/// acquire the XAxis object and modify it (e.g. change the position of the
/// labels)
public var xAxis: ChartXAxis
{
return _xAxis;
}
/// flag that indicates if pinch-zoom is enabled. if true, both x and y axis can be scaled with 2 fingers, if false, x and y axis can be scaled separately
public var pinchZoomEnabled: Bool
{
get
{
return _pinchZoomEnabled;
}
set
{
if (_pinchZoomEnabled != newValue)
{
_pinchZoomEnabled = newValue;
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled;
}
}
}
/// returns true if pinch-zoom is enabled, false if not
/// :default: false
public var isPinchZoomEnabled: Bool { return pinchZoomEnabled; }
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the x-axis.
public func setDragOffsetX(offset: CGFloat)
{
_viewPortHandler.setDragOffsetX(offset);
}
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the y-axis.
public func setDragOffsetY(offset: CGFloat)
{
_viewPortHandler.setDragOffsetY(offset);
}
/// :returns: true if both drag offsets (x and y) are zero or smaller.
public var hasNoDragOffset: Bool { return _viewPortHandler.hasNoDragOffset; }
public var xAxisRenderer: ChartXAxisRenderer { return _xAxisRenderer; }
public var leftYAxisRenderer: ChartYAxisRenderer { return _leftYAxisRenderer; }
public var rightYAxisRenderer: ChartYAxisRenderer { return _rightYAxisRenderer; }
public override var chartYMax: Float
{
return max(leftAxis.axisMaximum, rightAxis.axisMaximum);
}
public override var chartYMin: Float
{
return min(leftAxis.axisMinimum, rightAxis.axisMinimum);
}
/// Returns true if either the left or the right or both axes are inverted.
public var isAnyAxisInverted: Bool
{
return _leftAxis.isInverted || _rightAxis.isInverted;
}
}
/// Default formatter that calculates the position of the filled line.
internal class BarLineChartFillFormatter: NSObject, ChartFillFormatter
{
private weak var _chart: BarLineChartViewBase!;
internal init(chart: BarLineChartViewBase)
{
_chart = chart;
}
internal func getFillLinePosition(#dataSet: LineChartDataSet, data: LineChartData, chartMaxY: Float, chartMinY: Float) -> CGFloat
{
var fillMin = CGFloat(0.0);
if (dataSet.yMax > 0.0 && dataSet.yMin < 0.0)
{
fillMin = 0.0;
}
else
{
if (!_chart.getAxis(dataSet.axisDependency).isStartAtZeroEnabled)
{
var max: Float, min: Float;
if (data.yMax > 0.0)
{
max = 0.0;
}
else
{
max = chartMaxY;
}
if (data.yMin < 0.0)
{
min = 0.0;
}
else
{
min = chartMinY;
}
fillMin = CGFloat(dataSet.yMin >= 0.0 ? min : max);
}
else
{
fillMin = 0.0;
}
}
return fillMin;
}
}
| gpl-2.0 |
Fenrikur/ef-app_ios | Domain Model/EurofurenceModelTests/Events/Favourites/WhenLaunchingApplicationWithPreexistingFavourites.swift | 1 | 1660 | import EurofurenceModel
import EurofurenceModelTestDoubles
import XCTest
class WhenLaunchingApplicationWithPreexistingFavourites: XCTestCase {
func testTheObserversAreToldAboutTheFavouritedEvents() {
let characteristics = ModelCharacteristics.randomWithoutDeletions
let expected = characteristics.events.changed.map({ EventIdentifier($0.identifier) })
let dataStore = InMemoryDataStore(response: characteristics)
dataStore.performTransaction { (transaction) in
expected.forEach(transaction.saveFavouriteEventIdentifier)
}
let context = EurofurenceSessionTestBuilder().with(dataStore).build()
let observer = CapturingEventsServiceObserver()
context.eventsService.add(observer)
XCTAssertTrue(expected.contains(elementsFrom: observer.capturedFavouriteEventIdentifiers))
}
func testTheFavouritesAreSortedByEventStartTime() {
let response = ModelCharacteristics.randomWithoutDeletions
let events = response.events.changed
let dataStore = InMemoryDataStore(response: response)
dataStore.performTransaction { (transaction) in
events.map({ EventIdentifier($0.identifier) }).forEach(transaction.saveFavouriteEventIdentifier)
}
let context = EurofurenceSessionTestBuilder().with(dataStore).build()
let observer = CapturingEventsServiceObserver()
context.eventsService.add(observer)
let expected = events.sorted(by: { $0.startDateTime < $1.startDateTime }).map({ EventIdentifier($0.identifier) })
XCTAssertEqual(expected, observer.capturedFavouriteEventIdentifiers)
}
}
| mit |
jai/FoundationSafety | Example/FoundationSafety/JGSwiftViewController.swift | 1 | 181 | //
// JGSwiftViewController.swift
// FoundationSafety
//
// Created by Jai Govindani on 6/14/14.
// Copyright (c) 2014 Jai Govindani. All rights reserved.
//
import Foundation
| mit |
arnoappenzeller/PiPifier | PiPifier iOS/PiPifier iOS/RoundRectButton.swift | 1 | 921 | //
// RoundRectButton.swift
// PiPifier iOS
//
// Created by Arno Appenzeller on 18.05.17.
// Copyright © 2017 APPenzeller. All rights reserved.
//
import UIKit
@IBDesignable
class RoundRectButton: UIButton {
@IBInspectable
public var cornerRadius: CGFloat = 2.0 {
didSet {
self.layer.cornerRadius = self.cornerRadius
}
}
@IBInspectable
public var borderWidth: CGFloat = 1.0 {
didSet{
self.layer.borderWidth = self.borderWidth
}
}
@IBInspectable
public var borderColor: UIColor = UIColor.blue {
didSet{
self.layer.borderColor = self.borderColor.cgColor
}
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/03713-swift-sourcemanager-getmessage.swift | 11 | 309 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct B<f : A? {
var d = compose(Any) {
class c : j { func g: a {
protocol A : S<T where g: a {
enum S<T {
class c : a {
class
case c,
var
| mit |
austinzheng/swift-compiler-crashes | fixed/01965-swift-constraints-constraintsystem-diagnosefailurefromconstraints.swift | 11 | 191 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func f<c>(f){let:c=c() | mit |
NoryCao/zhuishushenqi | zhuishushenqi/Root/Views/ZSLeftViewCell.swift | 1 | 1700 | //
// ZSLeftViewCell.swift
// zhuishushenqi
//
// Created by caony on 2018/10/22.
// Copyright © 2018 QS. All rights reserved.
//
import UIKit
class ZSLeftViewCell: UITableViewCell {
lazy var iconView:UIImageView = {
let imageView = UIImageView(frame: CGRect(x: SideVC.maximumLeftOffsetWidth/2 - 12.5, y: 10, width: 25, height: 25))
return imageView
}()
lazy var selectedView:UIView = {
let view = UIView(frame: CGRect(x: 0,y: 0,width: 5,height: 44))
view.backgroundColor = UIColor ( red: 0.7235, green: 0.0, blue: 0.1146, alpha: 1.0 )
view.isHidden = true
return view
}()
lazy var nameLabel:UILabel = {
let label = UILabel(frame: CGRect(x: SideVC.maximumLeftOffsetWidth/2 - 20,y: 35,width: 40,height: 10))
label.font = UIFont.systemFont(ofSize: 9)
label.textAlignment = .center
label.textColor = UIColor(white: 1.0, alpha: 0.5)
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(self.iconView)
contentView.addSubview(self.selectedView)
contentView.addSubview(self.nameLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/24336-no-stacktrace.swift | 9 | 255 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
a{var _={
protocol A{{{
{
{
{{
{
{{
{
{
(""[
{
{
{
="
}
}
protocol a{
class
case c,()
| mit |
open-telemetry/opentelemetry-swift | Sources/OpenTelemetrySdk/Metrics/IntObserverMetricHandleSdk.swift | 1 | 338 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
import OpenTelemetryApi
struct IntObserverMetricHandleSdk: IntObserverMetricHandle {
public private(set) var aggregator = LastValueAggregator<Int>()
func observe(value: Int) {
aggregator.update(value: value)
}
}
| apache-2.0 |
banDedo/BDModules | Harness/HarnessTests/Mocks/MockAPISessionManager.swift | 1 | 1075 | //
// MockAPISessionManager.swift
// Harness
//
// Created by Patrick Hogan on 3/14/15.
// Copyright (c) 2015 bandedo. All rights reserved.
//
import BDModules
import Foundation
class MockAPISessionManager: APISessionManager {
private(set) var parameters: NSDictionary?
var dataTask: NSURLSessionDataTask? = NSURLSessionDataTask()
var responseObject: NSDictionary? = NSDictionary()
var error: NSError?
override init() {
super.init(dynamicBaseURL: NSURL(string: "https://www.test.com")!)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func performRequest(
#method: APISessionManager.Method,
path: String,
parameters: NSDictionary?,
headers: [ String : String ]?,
files: [MultipartFile]?,
handler: URLSessionDataTaskHandler) -> NSURLSessionDataTask! {
self.parameters = parameters
handler(dataTask, responseObject, error)
return dataTask
}
}
| apache-2.0 |
manavgabhawala/swift | test/SILGen/if_while_binding.swift | 1 | 14686 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s
func foo() -> String? { return "" }
func bar() -> String? { return "" }
func a(_ x: String) {}
func b(_ x: String) {}
func c(_ x: String) {}
func marker_1() {}
func marker_2() {}
func marker_3() {}
// CHECK-LABEL: sil hidden @_T016if_while_binding0A8_no_else{{[_0-9a-zA-Z]*}}F
func if_no_else() {
// CHECK: [[FOO:%.*]] = function_ref @_T016if_while_binding3fooSSSgyF
// CHECK: [[OPT_RES:%.*]] = apply [[FOO]]()
// CHECK: switch_enum [[OPT_RES]] : $Optional<String>, case #Optional.some!enumelt.1: [[YES:bb[0-9]+]], default [[CONT:bb[0-9]+]]
if let x = foo() {
// CHECK: [[YES]]([[VAL:%[0-9]+]] : $String):
// CHECK: [[A:%.*]] = function_ref @_T016if_while_binding1a
// CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]]
// CHECK: apply [[A]]([[VAL_COPY]])
// CHECK: end_borrow [[BORROWED_VAL]] from [[VAL]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
a(x)
}
// CHECK: [[CONT]]:
// CHECK-NEXT: tuple ()
}
// CHECK: } // end sil function '_T016if_while_binding0A8_no_else{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden @_T016if_while_binding0A11_else_chainyyF : $@convention(thin) () -> () {
func if_else_chain() {
// CHECK: [[FOO:%.*]] = function_ref @_T016if_while_binding3foo{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: [[OPT_RES:%.*]] = apply [[FOO]]()
// CHECK-NEXT: switch_enum [[OPT_RES]] : $Optional<String>, case #Optional.some!enumelt.1: [[YESX:bb[0-9]+]], default [[NOX:bb[0-9]+]]
if let x = foo() {
// CHECK: [[YESX]]([[VAL:%[0-9]+]] : $String):
// CHECK: debug_value [[VAL]] : $String, let, name "x"
// CHECK: [[A:%.*]] = function_ref @_T016if_while_binding1a
// CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]]
// CHECK: apply [[A]]([[VAL_COPY]])
// CHECK: end_borrow [[BORROWED_VAL]] from [[VAL]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT_X:bb[0-9]+]]
a(x)
// CHECK: [[NOX]]:
// CHECK: alloc_box ${ var String }, var, name "y"
// CHECK: switch_enum {{.*}} : $Optional<String>, case #Optional.some!enumelt.1: [[YESY:bb[0-9]+]], default [[ELSE1:bb[0-9]+]]
// CHECK: [[ELSE1]]:
// CHECK: dealloc_box {{.*}} ${ var String }
// CHECK: br [[ELSE:bb[0-9]+]]
} else if var y = bar() {
// CHECK: [[YESY]]([[VAL:%[0-9]+]] : $String):
// CHECK: br [[CONT_Y:bb[0-9]+]]
b(y)
} else {
// CHECK: [[ELSE]]:
// CHECK: function_ref if_while_binding.c
c("")
// CHECK: br [[CONT_Y]]
}
// CHECK: [[CONT_Y]]:
// br [[CONT_X]]
// CHECK: [[CONT_X]]:
}
// CHECK-LABEL: sil hidden @_T016if_while_binding0B5_loopyyF : $@convention(thin) () -> () {
func while_loop() {
// CHECK: br [[LOOP_ENTRY:bb[0-9]+]]
// CHECK: [[LOOP_ENTRY]]:
// CHECK: switch_enum {{.*}} : $Optional<String>, case #Optional.some!enumelt.1: [[LOOP_BODY:bb[0-9]+]], default [[LOOP_EXIT:bb[0-9]+]]
while let x = foo() {
// CHECK: [[LOOP_BODY]]([[X:%[0-9]+]] : $String):
// CHECK: switch_enum {{.*}} : $Optional<String>, case #Optional.some!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
if let y = bar() {
// CHECK: [[YES]]([[Y:%[0-9]+]] : $String):
a(y)
break
// CHECK: destroy_value [[Y]]
// CHECK: destroy_value [[X]]
// CHECK: br [[LOOP_EXIT]]
}
// CHECK: [[NO]]:
// CHECK: destroy_value [[X]]
// CHECK: br [[LOOP_ENTRY]]
}
// CHECK: [[LOOP_EXIT]]:
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
// Don't leak alloc_stacks for address-only conditional bindings in 'while'.
// <rdar://problem/16202294>
// CHECK-LABEL: sil hidden @_T016if_while_binding0B13_loop_generic{{[_0-9a-zA-Z]*}}F
// CHECK: br [[COND:bb[0-9]+]]
// CHECK: [[COND]]:
// CHECK: [[X:%.*]] = alloc_stack $T, let, name "x"
// CHECK: [[OPTBUF:%[0-9]+]] = alloc_stack $Optional<T>
// CHECK: switch_enum_addr {{.*}}, case #Optional.some!enumelt.1: [[LOOPBODY:bb.*]], default [[OUT:bb[0-9]+]]
// CHECK: [[OUT]]:
// CHECK: dealloc_stack [[OPTBUF]]
// CHECK: dealloc_stack [[X]]
// CHECK: br [[DONE:bb[0-9]+]]
// CHECK: [[LOOPBODY]]:
// CHECK: [[ENUMVAL:%.*]] = unchecked_take_enum_data_addr
// CHECK: copy_addr [take] [[ENUMVAL]] to [initialization] [[X]]
// CHECK: destroy_addr [[X]]
// CHECK: dealloc_stack [[X]]
// CHECK: br [[COND]]
// CHECK: [[DONE]]:
// CHECK: destroy_value %0
func while_loop_generic<T>(_ source: () -> T?) {
while let x = source() {
}
}
// <rdar://problem/19382942> Improve 'if let' to avoid optional pyramid of doom
// CHECK-LABEL: sil hidden @_T016if_while_binding0B11_loop_multiyyF
func while_loop_multi() {
// CHECK: br [[LOOP_ENTRY:bb[0-9]+]]
// CHECK: [[LOOP_ENTRY]]:
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], default [[LOOP_EXIT0:bb[0-9]+]]
// CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : $String):
// CHECK: debug_value [[A]] : $String, let, name "a"
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[LOOP_BODY:bb.*]], default [[LOOP_EXIT2a:bb[0-9]+]]
// CHECK: [[LOOP_EXIT2a]]:
// CHECK: destroy_value [[A]]
// CHECK: br [[LOOP_EXIT0]]
// CHECK: [[LOOP_BODY]]([[B:%[0-9]+]] : $String):
while let a = foo(), let b = bar() {
// CHECK: debug_value [[B]] : $String, let, name "b"
// CHECK: [[BORROWED_A:%.*]] = begin_borrow [[A]]
// CHECK: [[A_COPY:%.*]] = copy_value [[BORROWED_A]]
// CHECK: debug_value [[A_COPY]] : $String, let, name "c"
// CHECK: end_borrow [[BORROWED_A]] from [[A]]
// CHECK: destroy_value [[A_COPY]]
// CHECK: destroy_value [[B]]
// CHECK: destroy_value [[A]]
// CHECK: br [[LOOP_ENTRY]]
let c = a
}
// CHECK: [[LOOP_EXIT0]]:
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @_T016if_while_binding0A6_multiyyF
func if_multi() {
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], default [[IF_DONE:bb[0-9]+]]
// CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : $String):
// CHECK: debug_value [[A]] : $String, let, name "a"
// CHECK: [[B:%[0-9]+]] = alloc_box ${ var String }, var, name "b"
// CHECK: [[PB:%[0-9]+]] = project_box [[B]]
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[IF_BODY:bb.*]], default [[IF_EXIT1a:bb[0-9]+]]
// CHECK: [[IF_EXIT1a]]:
// CHECK: dealloc_box {{.*}} ${ var String }
// CHECK: destroy_value [[A]]
// CHECK: br [[IF_DONE]]
// CHECK: [[IF_BODY]]([[BVAL:%[0-9]+]] : $String):
if let a = foo(), var b = bar() {
// CHECK: store [[BVAL]] to [init] [[PB]] : $*String
// CHECK: debug_value {{.*}} : $String, let, name "c"
// CHECK: destroy_value [[B]]
// CHECK: destroy_value [[A]]
// CHECK: br [[IF_DONE]]
let c = a
}
// CHECK: [[IF_DONE]]:
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @_T016if_while_binding0A11_multi_elseyyF
func if_multi_else() {
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], default [[ELSE:bb[0-9]+]]
// CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : $String):
// CHECK: debug_value [[A]] : $String, let, name "a"
// CHECK: [[B:%[0-9]+]] = alloc_box ${ var String }, var, name "b"
// CHECK: [[PB:%[0-9]+]] = project_box [[B]]
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[IF_BODY:bb.*]], default [[IF_EXIT1a:bb[0-9]+]]
// CHECK: [[IF_EXIT1a]]:
// CHECK: dealloc_box {{.*}} ${ var String }
// CHECK: destroy_value [[A]]
// CHECK: br [[ELSE]]
// CHECK: [[IF_BODY]]([[BVAL:%[0-9]+]] : $String):
if let a = foo(), var b = bar() {
// CHECK: store [[BVAL]] to [init] [[PB]] : $*String
// CHECK: debug_value {{.*}} : $String, let, name "c"
// CHECK: destroy_value [[B]]
// CHECK: destroy_value [[A]]
// CHECK: br [[IF_DONE:bb[0-9]+]]
let c = a
} else {
let d = 0
// CHECK: [[ELSE]]:
// CHECK: debug_value {{.*}} : $Int, let, name "d"
// CHECK: br [[IF_DONE]]
}
// CHECK: [[IF_DONE]]:
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @_T016if_while_binding0A12_multi_whereyyF
func if_multi_where() {
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], default [[ELSE:bb[0-9]+]]
// CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : $String):
// CHECK: debug_value [[A]] : $String, let, name "a"
// CHECK: [[BBOX:%[0-9]+]] = alloc_box ${ var String }, var, name "b"
// CHECK: [[PB:%[0-9]+]] = project_box [[BBOX]]
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECK_WHERE:bb.*]], default [[IF_EXIT1a:bb[0-9]+]]
// CHECK: [[IF_EXIT1a]]:
// CHECK: dealloc_box {{.*}} ${ var String }
// CHECK: destroy_value [[A]]
// CHECK: br [[ELSE]]
// CHECK: [[CHECK_WHERE]]([[B:%[0-9]+]] : $String):
// CHECK: function_ref Swift.Bool._getBuiltinLogicValue () -> Builtin.Int1
// CHECK: cond_br {{.*}}, [[IF_BODY:bb[0-9]+]], [[IF_EXIT3:bb[0-9]+]]
// CHECK: [[IF_EXIT3]]:
// CHECK: destroy_value [[BBOX]]
// CHECK: destroy_value [[A]]
// CHECK: br [[IF_DONE:bb[0-9]+]]
if let a = foo(), var b = bar(), a == b {
// CHECK: [[IF_BODY]]:
// CHECK: destroy_value [[BBOX]]
// CHECK: destroy_value [[A]]
// CHECK: br [[IF_DONE]]
let c = a
}
// CHECK: [[IF_DONE]]:
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
// <rdar://problem/19797158> Swift 1.2's "if" has 2 behaviors. They could be unified.
// CHECK-LABEL: sil hidden @_T016if_while_binding0A16_leading_booleanySiF
func if_leading_boolean(_ a : Int) {
// Test the boolean condition.
// CHECK: debug_value %0 : $Int, let, name "a"
// CHECK: [[EQRESULT:%[0-9]+]] = apply {{.*}}(%0, %0{{.*}}) : $@convention({{.*}}) (Int, Int{{.*}}) -> Bool
// CHECK-NEXT: [[EQRESULTI1:%[0-9]+]] = apply %2([[EQRESULT]]) : $@convention(method) (Bool) -> Builtin.Int1
// CHECK-NEXT: cond_br [[EQRESULTI1]], [[CHECKFOO:bb[0-9]+]], [[IFDONE:bb[0-9]+]]
// Call Foo and test for the optional being present.
// CHECK: [[CHECKFOO]]:
// CHECK: [[OPTRESULT:%[0-9]+]] = apply {{.*}}() : $@convention(thin) () -> @owned Optional<String>
// CHECK: switch_enum [[OPTRESULT]] : $Optional<String>, case #Optional.some!enumelt.1: [[SUCCESS:bb.*]], default [[IF_DONE:bb[0-9]+]]
// CHECK: [[SUCCESS]]([[B:%[0-9]+]] : $String):
// CHECK: debug_value [[B]] : $String, let, name "b"
// CHECK: [[BORROWED_B:%.*]] = begin_borrow [[B]]
// CHECK: [[B_COPY:%.*]] = copy_value [[BORROWED_B]]
// CHECK: debug_value [[B_COPY]] : $String, let, name "c"
// CHECK: end_borrow [[BORROWED_B]] from [[B]]
// CHECK: destroy_value [[B_COPY]]
// CHECK: destroy_value [[B]]
// CHECK: br [[IFDONE]]
if a == a, let b = foo() {
let c = b
}
// CHECK: [[IFDONE]]:
// CHECK-NEXT: tuple ()
}
/// <rdar://problem/20364869> Assertion failure when using 'as' pattern in 'if let'
class BaseClass {}
class DerivedClass : BaseClass {}
// CHECK-LABEL: sil hidden @_T016if_while_binding20testAsPatternInIfLetyAA9BaseClassCSgF
func testAsPatternInIfLet(_ a : BaseClass?) {
// CHECK: bb0([[ARG:%.*]] : $Optional<BaseClass>):
// CHECK: debug_value [[ARG]] : $Optional<BaseClass>, let, name "a"
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] : $Optional<BaseClass>
// CHECK: switch_enum [[ARG_COPY]] : $Optional<BaseClass>, case #Optional.some!enumelt.1: [[OPTPRESENTBB:bb[0-9]+]], default [[NILBB:bb[0-9]+]]
// CHECK: [[NILBB]]:
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: br [[EXITBB:bb[0-9]+]]
// CHECK: [[OPTPRESENTBB]]([[CLS:%.*]] : $BaseClass):
// CHECK: checked_cast_br [[CLS]] : $BaseClass to $DerivedClass, [[ISDERIVEDBB:bb[0-9]+]], [[ISBASEBB:bb[0-9]+]]
// CHECK: [[ISDERIVEDBB]]([[DERIVED_CLS:%.*]] : $DerivedClass):
// CHECK: [[DERIVED_CLS_SOME:%.*]] = enum $Optional<DerivedClass>, #Optional.some!enumelt.1, [[DERIVED_CLS]] : $DerivedClass
// CHECK: br [[MERGE:bb[0-9]+]]([[DERIVED_CLS_SOME]] : $Optional<DerivedClass>)
// CHECK: [[ISBASEBB]]([[BASECLASS:%.*]] : $BaseClass):
// CHECK: destroy_value [[BASECLASS]] : $BaseClass
// CHECK: = enum $Optional<DerivedClass>, #Optional.none!enumelt
// CHECK: br [[MERGE]](
// CHECK: [[MERGE]]([[OPTVAL:%[0-9]+]] : $Optional<DerivedClass>):
// CHECK: switch_enum [[OPTVAL]] : $Optional<DerivedClass>, case #Optional.some!enumelt.1: [[ISDERIVEDBB:bb[0-9]+]], default [[NILBB:bb[0-9]+]]
// CHECK: [[ISDERIVEDBB]]([[DERIVEDVAL:%[0-9]+]] : $DerivedClass):
// CHECK: debug_value [[DERIVEDVAL]] : $DerivedClass
// => SEMANTIC SIL TODO: This is benign, but scoping wise, this end borrow should be after derived val.
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[DERIVEDVAL]] : $DerivedClass
// CHECK: br [[EXITBB]]
// CHECK: [[EXITBB]]:
// CHECK: destroy_value [[ARG]] : $Optional<BaseClass>
// CHECK: tuple ()
// CHECK: return
if case let b as DerivedClass = a {
}
}
// <rdar://problem/22312114> if case crashes swift - bools not supported in let/else yet
// CHECK-LABEL: sil hidden @_T016if_while_binding12testCaseBoolySbSgF
func testCaseBool(_ value : Bool?) {
// CHECK: bb0(%0 : $Optional<Bool>):
// CHECK: switch_enum %0 : $Optional<Bool>, case #Optional.some!enumelt.1: bb1, default bb3
// CHECK: bb1(%3 : $Bool):
// CHECK: [[ISTRUE:%[0-9]+]] = struct_extract %3 : $Bool, #Bool._value
// CHECK: cond_br [[ISTRUE]], bb2, bb3
// CHECK: bb2:
// CHECK: function_ref @_T016if_while_binding8marker_1yyF
// CHECK: br bb3{{.*}} // id: %8
if case true? = value {
marker_1()
}
// CHECK: bb3: // Preds: bb2 bb1 bb0
// CHECK: switch_enum %0 : $Optional<Bool>, case #Optional.some!enumelt.1: bb4, default bb6
// CHECK: bb4(
// CHECK: [[ISTRUE:%[0-9]+]] = struct_extract %10 : $Bool, #Bool._value{{.*}}// user: %12
// CHECK: cond_br [[ISTRUE]], bb6, bb5
// CHECK: bb5:
// CHECK: function_ref @_T016if_while_binding8marker_2yyF
// CHECK: br bb6{{.*}} // id: %15
// CHECK: bb6: // Preds: bb5 bb4 bb3
if case false? = value {
marker_2()
}
}
| apache-2.0 |
ohadh123/MuscleUp- | Pods/GTProgressBar/GTProgressBar/Classes/GTProgressBar.swift | 1 | 7715 | //
// GTProgressBar.swift
// Pods
//
// Created by Grzegorz Tatarzyn on 19/09/2016.
import UIKit
@IBDesignable
public class GTProgressBar: UIView {
private let minimumProgressBarWidth: CGFloat = 20
private let minimumProgressBarFillHeight: CGFloat = 1
private let backgroundView = UIView()
private let fillView = UIView()
private let progressLabel = UILabel()
private var _progress: CGFloat = 1
public var font: UIFont = UIFont.systemFont(ofSize: 12) {
didSet {
progressLabel.font = font
self.setNeedsLayout()
}
}
public var progressLabelInsets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) {
didSet {
self.setNeedsLayout()
}
}
@IBInspectable
public var progressLabelInsetLeft: CGFloat = 0.0 {
didSet {
self.progressLabelInsets.left = max(0.0, progressLabelInsetLeft)
self.setNeedsLayout()
}
}
@IBInspectable
public var progressLabelInsetRight: CGFloat = 0.0 {
didSet {
self.progressLabelInsets.right = max(0.0, progressLabelInsetRight)
self.setNeedsLayout()
}
}
@IBInspectable
public var progressLabelInsetTop: CGFloat = 0.0 {
didSet {
self.progressLabelInsets.top = max(0.0, progressLabelInsetTop)
self.setNeedsLayout()
}
}
@IBInspectable
public var progressLabelInsetBottom: CGFloat = 0.0 {
didSet {
self.progressLabelInsets.bottom = max(0.0, progressLabelInsetBottom)
self.setNeedsLayout()
}
}
public var barMaxHeight: CGFloat? {
didSet {
self.setNeedsLayout()
}
}
@IBInspectable
public var barBorderColor: UIColor = UIColor.black {
didSet {
backgroundView.layer.borderColor = barBorderColor.cgColor
self.setNeedsLayout()
}
}
@IBInspectable
public var barBackgroundColor: UIColor = UIColor.white {
didSet {
backgroundView.backgroundColor = barBackgroundColor
self.setNeedsLayout()
}
}
@IBInspectable
public var barFillColor: UIColor = UIColor.black {
didSet {
fillView.backgroundColor = barFillColor
self.setNeedsLayout()
}
}
@IBInspectable
public var barBorderWidth: CGFloat = 2 {
didSet {
backgroundView.layer.borderWidth = barBorderWidth
self.setNeedsLayout()
}
}
@IBInspectable
public var barFillInset: CGFloat = 2 {
didSet {
self.setNeedsLayout()
}
}
@IBInspectable
public var progress: CGFloat {
get {
return self._progress
}
set {
self._progress = min(max(newValue,0), 1)
self.setNeedsLayout()
}
}
@IBInspectable
public var labelTextColor: UIColor = UIColor.black {
didSet {
progressLabel.textColor = labelTextColor
self.setNeedsLayout()
}
}
@IBInspectable
public var displayLabel: Bool = true {
didSet {
self.progressLabel.isHidden = !self.displayLabel
self.setNeedsLayout()
}
}
@IBInspectable
public var cornerRadius: CGFloat = 0.0 {
didSet {
self.layer.masksToBounds = cornerRadius != 0.0
self.layer.cornerRadius = cornerRadius
self.setNeedsLayout()
}
}
public var labelPosition: GTProgressBarLabelPosition = GTProgressBarLabelPosition.left {
didSet {
self.setNeedsLayout()
}
}
@IBInspectable
public var labelPositionInt: Int = 0 {
didSet {
let enumPosition = GTProgressBarLabelPosition(rawValue: labelPositionInt)
if let position = enumPosition {
self.labelPosition = position
}
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
prepareSubviews()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepareSubviews()
}
private func prepareSubviews() {
progressLabel.textAlignment = NSTextAlignment.center
progressLabel.font = font
progressLabel.textColor = labelTextColor
addSubview(progressLabel)
backgroundView.backgroundColor = barBackgroundColor
backgroundView.layer.borderWidth = barBorderWidth
backgroundView.layer.borderColor = barBorderColor.cgColor
addSubview(backgroundView)
fillView.backgroundColor = barFillColor
addSubview(fillView)
}
public override func layoutSubviews() {
updateProgressLabelText()
updateViewsLocation()
}
public override func sizeThatFits(_ size: CGSize) -> CGSize {
return createFrameCalculator().sizeThatFits(size)
}
private func updateViewsLocation() {
let frameCalculator: FrameCalculator = createFrameCalculator()
progressLabel.frame = frameCalculator.labelFrame()
frameCalculator.center(view: progressLabel, parent: self)
backgroundView.frame = frameCalculator.backgroundViewFrame()
backgroundView.layer.cornerRadius = cornerRadiusFor(view: backgroundView)
if (barMaxHeight != nil) {
frameCalculator.center(view: backgroundView, parent: self)
}
fillView.frame = fillViewFrameFor(progress: _progress)
fillView.layer.cornerRadius = cornerRadiusFor(view: fillView)
}
private func createFrameCalculator() -> FrameCalculator {
switch labelPosition {
case .right:
return LabelRightFrameCalculator(progressBar: self)
case .top:
return LabelTopFrameCalculator(progressBar: self)
case .bottom:
return LabelBottomFrameCalculator(progressBar: self)
default:
return LabelLeftFrameCalculator(progressBar: self)
}
}
private func updateProgressLabelText() {
progressLabel.text = "\(Int(_progress * 100))%"
}
public func animateTo(progress: CGFloat) {
let newProgress = min(max(progress,0), 1)
let fillViewFrame = fillViewFrameFor(progress: newProgress)
let frameChange: () -> () = {
self.fillView.frame.size.width = fillViewFrame.size.width
self._progress = newProgress
}
if #available(iOS 10.0, *) {
UIViewPropertyAnimator(duration: 0.8, curve: .easeInOut, animations: frameChange)
.startAnimation()
} else {
UIView.animate(withDuration: 0.8,
delay: 0,
options: [UIViewAnimationOptions.curveEaseInOut],
animations: frameChange,
completion: nil);
}
}
private func fillViewFrameFor(progress: CGFloat) -> CGRect {
let offset = barBorderWidth + barFillInset
let fillFrame = backgroundView.frame.insetBy(dx: offset, dy: offset)
let fillFrameAdjustedSize = CGSize(width: fillFrame.width * progress, height: fillFrame.height)
return CGRect(origin: fillFrame.origin, size: fillFrameAdjustedSize)
}
private func cornerRadiusFor(view: UIView) -> CGFloat {
if cornerRadius != 0.0 {
return cornerRadius
}
return view.frame.height / 2 * 0.7
}
}
| apache-2.0 |
ChristianKienle/highway | Sources/HighwayCore/Features/Swift/SwiftRunTool.swift | 1 | 1823 | import Foundation
import ZFile
import Url
import Task
import Arguments
import POSIX
public enum SwiftRun { }
public extension SwiftRun {
public final class Tool {
public let context: Context
public init(context: Context) {
self.context = context
}
public func run(with options: Options) throws -> Result {
let arguments = options.taskArguments
let task = try Task(commandName: "swift", arguments: arguments, provider: context.executableProvider)
task.currentDirectoryUrl = options.currentWorkingDirectory
task.enableReadableOutputDataCapturing()
try context.executor.execute(task: task)
try task.throwIfNotSuccess("🛣🔥 \(SwiftRun.Tool.self) failed running task\n\(task).")
let output = task.capturedOutputString
return Result(output: output ?? "")
}
}
}
public extension SwiftRun {
public struct Result {
public let output: String
}
public struct Options {
public var executable: String? = nil // swift run $executable
public var arguments: Arguments = .empty
public var packageUrl: FolderProtocol? = nil // --package-path
public var currentWorkingDirectory: FolderProtocol = FileSystem().currentFolder
public init() {}
var taskArguments: Arguments {
var result = Arguments()
result.append("run")
if let packageUrl = packageUrl {
result.append("--package-path")
result.append(packageUrl.path)
}
if let executable = executable {
result.append(executable)
}
result += arguments
return result
}
}
}
| mit |
Elm-Tree-Island/Shower | Shower/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/AppKit/NSPopUpButtonSpec.swift | 5 | 3720 | import Quick
import Nimble
import ReactiveCocoa
import ReactiveSwift
import Result
import AppKit
final class NSPopUpButtonSpec: QuickSpec {
override func spec() {
describe("NSPopUpButton") {
var button: NSPopUpButton!
var window: NSWindow!
weak var _button: NSButton?
let testTitles = (0..<100).map { $0.description }
beforeEach {
window = NSWindow()
button = NSPopUpButton(frame: .zero)
_button = button
for (i, title) in testTitles.enumerated() {
let item = NSMenuItem(title: title, action: nil, keyEquivalent: "")
item.tag = 1000 + i
button.menu?.addItem(item)
}
window.contentView?.addSubview(button)
}
afterEach {
autoreleasepool {
button.removeFromSuperview()
button = nil
}
expect(_button).to(beNil())
}
it("should emit selected index changes") {
var values = [Int]()
button.reactive.selectedIndexes.observeValues { values.append($0) }
button.menu?.performActionForItem(at: 1)
button.menu?.performActionForItem(at: 99)
expect(values) == [1, 99]
}
it("should emit selected title changes") {
var values = [String]()
button.reactive.selectedTitles.observeValues { values.append($0) }
button.menu?.performActionForItem(at: 1)
button.menu?.performActionForItem(at: 99)
expect(values) == ["1", "99"]
}
it("should accept changes from its bindings to its index values") {
let (signal, observer) = Signal<Int?, NoError>.pipe()
button.reactive.selectedIndex <~ SignalProducer(signal)
observer.send(value: 1)
expect(button.indexOfSelectedItem) == 1
observer.send(value: 99)
expect(button.indexOfSelectedItem) == 99
observer.send(value: nil)
expect(button.indexOfSelectedItem) == -1
expect(button.selectedItem?.title).to(beNil())
}
it("should accept changes from its bindings to its title values") {
let (signal, observer) = Signal<String?, NoError>.pipe()
button.reactive.selectedTitle <~ SignalProducer(signal)
observer.send(value: "1")
expect(button.selectedItem?.title) == "1"
observer.send(value: "99")
expect(button.selectedItem?.title) == "99"
observer.send(value: nil)
expect(button.selectedItem?.title).to(beNil())
expect(button.indexOfSelectedItem) == -1
}
it("should emit selected item changes") {
var values = [NSMenuItem]()
button.reactive.selectedItems.observeValues { values.append($0) }
button.menu?.performActionForItem(at: 1)
button.menu?.performActionForItem(at: 99)
let titles = values.map { $0.title }
expect(titles) == ["1", "99"]
}
it("should emit selected tag changes") {
var values = [Int]()
button.reactive.selectedTags.observeValues { values.append($0) }
button.menu?.performActionForItem(at: 1)
button.menu?.performActionForItem(at: 99)
expect(values) == [1001, 1099]
}
it("should accept changes from its bindings to its tag values") {
let (signal, observer) = Signal<Int, NoError>.pipe()
button.reactive.selectedTag <~ SignalProducer(signal)
observer.send(value: 1001)
expect(button.selectedItem?.tag) == 1001
expect(button.indexOfSelectedItem) == 1
observer.send(value: 1099)
expect(button.selectedItem?.tag) == 1099
expect(button.indexOfSelectedItem) == 99
observer.send(value: 1042)
expect(button.selectedItem?.tag) == 1042
expect(button.indexOfSelectedItem) == 42
// Sending an invalid tag number doesn't change the selection
observer.send(value: testTitles.count + 1)
expect(button.selectedItem?.tag) == 1042
expect(button.indexOfSelectedItem) == 42
}
}
}
}
| gpl-3.0 |
AxziplinLib/TabNavigations | Sources/_ScrollViewDelegates.swift | 1 | 5811 | //
// _ScrollViewDelegates.swift
// AxReminder
//
// Created by devedbox on 2017/9/19.
// Copyright © 2017年 devedbox. All rights reserved.
//
import UIKit
// MARK: - _ScrollViewDelegateQueue.
/// A type representing the managing queue of the delegates of one UIScrollView.
/// The delegates is managed with the NSHashTable as the storage.
internal class _ScrollViewDelegatesQueue: NSObject {
/// Delegates storage.
fileprivate let _hashTable = NSHashTable<UIScrollViewDelegate>.weakObjects()
/// A closure to get the view for scroll view's zooming.
var viewForZooming: ((UIScrollView) -> UIView?)? = nil
/// A closure decides whether the scroll view should scroll to top.
var scrollViewShouldScrollToTop: ((UIScrollView) -> Bool)? = nil
}
// Confirming to UIScrollViewDelegate.
extension _ScrollViewDelegatesQueue: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
_hashTable.allObjects.forEach{ $0.scrollViewDidScroll?(scrollView) }
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
_hashTable.allObjects.forEach{ $0.scrollViewDidZoom?(scrollView) }
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
_hashTable.allObjects.forEach{ $0.scrollViewWillBeginDragging?(scrollView) }
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
_hashTable.allObjects.forEach{ $0.scrollViewWillEndDragging?(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset) }
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
_hashTable.allObjects.forEach{ $0.scrollViewDidEndDragging?(scrollView, willDecelerate: decelerate) }
}
func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
_hashTable.allObjects.forEach{ $0.scrollViewWillBeginDecelerating?(scrollView) }
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
_hashTable.allObjects.forEach{ $0.scrollViewDidEndDecelerating?(scrollView) }
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
_hashTable.allObjects.forEach{ $0.scrollViewDidEndScrollingAnimation?(scrollView) }
}
func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
_hashTable.allObjects.forEach{ $0.scrollViewWillBeginZooming?(scrollView, with: view) }
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
_hashTable.allObjects.forEach{ $0.scrollViewDidEndZooming?(scrollView, with: view, atScale: scale) }
}
@available(iOS 11.0, *)
func scrollViewDidChangeAdjustedContentInset(_ scrollView: UIScrollView) {
_hashTable.allObjects.forEach{ $0.scrollViewDidChangeAdjustedContentInset?(scrollView) }
}
}
extension _ScrollViewDelegatesQueue {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return viewForZooming?(scrollView)
}
func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool {
return scrollViewShouldScrollToTop?(scrollView) ?? false
}
}
extension _ScrollViewDelegatesQueue {
/// Add a new UIScrollViewDelegate object to the managed queue.
/// - Parameter delegate: A UIScrollViewDelegate to be added and managed.
func add(_ delegate: UIScrollViewDelegate?) { _hashTable.add(delegate) }
/// Remove a existing UIScrollViewDelegate object from the managed queue.
/// - Parameter delegate: The existing delegate the be removed.
func remove(_ delegate: UIScrollViewDelegate?) { _hashTable.remove(delegate) }
/// Remove all the managed UIScrollViewDelegate objects.
func removeAll() { _hashTable.removeAllObjects() }
}
// MARK: - _ScrollViewDidEndScrollingAnimation.
/// A type reresenting the a hook of UIScrollViewDelegate to set as the temporary
/// delegate and to get the call back of the `setContentOffset(:animated:)` if the
/// transition is animated.
internal class _ScrollViewDidEndScrollingAnimation: NSObject {
fileprivate var _completion: ((UIScrollView)->Void)
/// Creates a _ScrollViewDidEndScrollingAnimation object with the call back closure.
///
/// - Parameter completion: A closure will be triggered when the `scrollViewDidEndScrollingAnimation(:)` is called.
/// - Returns: A _ScrollViewDidEndScrollingAnimation with the call back closure.
internal init(_ completion: @escaping (UIScrollView)->Void) {
_completion = completion
super.init()
}
}
// Confirming of UIScrollViewDelegate.
extension _ScrollViewDidEndScrollingAnimation: UIScrollViewDelegate {
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
_completion(scrollView)
}
}
// MARK: - _ScrollViewDidScroll.
/// A type reresenting the a hook of UIScrollViewDelegate to set as the temporary
/// delegate and to get the call back when scroll view did scroll.
internal class _ScrollViewDidScroll: NSObject {
fileprivate var _didScroll: ((UIScrollView) -> Void)
/// Creates a _ScrollViewDidScroll object with the call back closure.
///
/// - Parameter completion: A closure will be triggered when the `scrollViewDidScroll(:)` is called.
/// - Returns: A _ScrollViewDidScroll with the call back closure.
internal init(_ didScroll: @escaping ((UIScrollView) -> Void)) {
_didScroll = didScroll
}
}
// Confirming of UIScrollViewDelegate.
extension _ScrollViewDidScroll: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
_didScroll(scrollView)
}
}
| apache-2.0 |
raulriera/UpvoteControl | UpvoteControl/UpvoteControl.swift | 1 | 3990 | //
// UpvoteControl.swift
// Raúl Riera
//
// Created by Raúl Riera on 26/04/2015.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import UIKit
@IBDesignable
open class UpvoteControl: UIControl {
/**
The current count value
The default value for this property is 0. It will increment and decrement internally depending of the `selected` property
*/
@IBInspectable open var count: Int = 0 {
didSet {
updateCountLabel()
}
}
@IBInspectable open var borderRadius: CGFloat = 0 {
didSet {
updateLayer()
}
}
@IBInspectable open var shadow: Bool = false {
didSet {
updateLayer()
}
}
@IBInspectable open var vertical: Bool = true {
didSet {
updateCountLabel()
}
}
/**
The font of the text
Until Xcode supports @IBInspectable for UIFonts, this is the only way to change the font of the inner label
*/
@IBInspectable open var font: UIFont? {
didSet {
countLabel.font = font
}
}
/**
The color of text
The default value for this property is a black color (set through the blackColor class method of UIColor).
*/
@IBInspectable open var textColor: UIColor = .black {
didSet {
countLabel.textColor = textColor
}
}
private var countLabel: UILabel = UILabel()
override open var isSelected: Bool {
didSet {
if isSelected {
countLabel.textColor = tintColor
} else {
countLabel.textColor = textColor
}
}
}
// MARK: Overrides
open override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
super.endTracking(touch, with:event)
if let touch = touch , touch.tapCount > 0 {
if isSelected {
count -= 1
} else {
count += 1
}
isSelected = !isSelected
super.sendActions(for: .valueChanged)
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureView()
}
override init(frame: CGRect) {
super.init(frame: frame)
configureView()
}
// MARK: Private
private func configureView() {
// Allow this method to only run once
guard countLabel.superview == .none else { return }
updateLayer()
countLabel = UILabel(frame: bounds)
countLabel.font = UIFont(name: "AppleSDGothicNeo-Medium", size: 12)
countLabel.numberOfLines = 0
countLabel.lineBreakMode = .byWordWrapping
countLabel.textAlignment = .center
countLabel.isUserInteractionEnabled = false
countLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(countLabel)
let centerXConstraint = NSLayoutConstraint(item: countLabel, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)
let centerYConstraint = NSLayoutConstraint(item: countLabel, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)
NSLayoutConstraint.activate([centerXConstraint, centerYConstraint])
countLabel.setNeedsDisplay()
}
private func updateLayer() {
layer.cornerRadius = borderRadius
if shadow {
layer.shadowColor = UIColor.darkGray.cgColor
layer.shadowRadius = 0.5
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.shadowOpacity = 0.5
}
}
private func updateCountLabel() {
if vertical {
countLabel.text = "▲\n\(count)"
} else {
countLabel.text = "▲ \(count)"
}
}
}
| mit |
cnoon/swift-compiler-crashes | crashes-fuzzing/26099-swift-constraints-constraintsystem-getconstraintlocator.swift | 7 | 237 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a{
if true{class B<T where g:h{
class B{
class b
func P{
{b{b{
| mit |
muhlenXi/SwiftEx | projects/TodoList/TodoList/TodoModel.swift | 1 | 572 | //
// TodoModel.swift
// TodoList
//
// Created by 席银军 on 2017/8/20.
// Copyright © 2017年 muhlenXi. All rights reserved.
//
import Foundation
class TodoModel {
var id: String
var image: String
var title: String
var date: Date
// MARK: - init method
init(id: String, image: String, title: String, date: Date) {
self.id = id
self.image = image
self.title = title
self.date = date
}
init() {
id = ""
image = ""
title = ""
date = Date()
}
}
| mit |
laszlokorte/reform-swift | ReformCore/ReformCore/TranslateInstruction.swift | 1 | 1807 | //
// TranslateInstruction.swift
// ReformCore
//
// Created by Laszlo Korte on 14.08.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
public struct TranslateInstruction : Instruction {
public typealias DistanceType = RuntimeDistance & Labeled
public var target : FormIdentifier? {
return formId
}
public let formId : FormIdentifier
public let distance : DistanceType
public init(formId: FormIdentifier, distance: DistanceType) {
self.formId = formId
self.distance = distance
}
public func evaluate<T:Runtime>(_ runtime: T) {
guard let form = runtime.get(formId) as? Translatable else {
runtime.reportError(.unknownForm)
return
}
guard let delta = distance.getDeltaFor(runtime) else {
runtime.reportError(.invalidDistance)
return
}
form.translator.translate(runtime, delta: delta)
}
public func getDescription(_ stringifier: Stringifier) -> String { let formName = stringifier.labelFor(formId) ?? "???"
return "Move \(formName) \(distance.getDescription(stringifier))"
}
public func analyze<T:Analyzer>(_ analyzer: T) {
}
public var isDegenerated : Bool {
return distance.isDegenerated
}
}
extension TranslateInstruction : Mergeable {
public func mergeWith(_ other: TranslateInstruction, force: Bool) -> TranslateInstruction? {
guard formId == other.formId else {
return nil
}
guard let newDistance = merge(distance: distance, distance: other.distance, force: force) else {
return nil
}
return TranslateInstruction(formId: formId, distance: newDistance)
}
}
| mit |
iHunterX/SocketIODemo | DemoSocketIO/Utils/UIViewExtensions/UIViewBorder.swift | 1 | 6453 | //
// UIViewExtensions.swift
// DemoSocketIO
//
// Created by Loc.dx-KeizuDev on 10/28/16.
// Copyright © 2016 Loc Dinh Xuan. All rights reserved.
//
import UIKit
//class UIViewBorder: UIView {
class BorderView: UIView {
var lineColor = UIColor.clear
@IBInspectable var lineBorderColor: UIColor = .clear {
didSet{
updateColor()
}
}
func updateColor(){
lineColor = lineBorderColor
}
@IBInspectable var leftBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: 0.0, y: 0.0, width: newValue, height: bounds.height))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = lineColor
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[line(==lineWidth)]", options: [], metrics: metrics, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[line]|", options: [], metrics: nil, views: views))
}
}
@IBInspectable var topBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: 0.0, y: 0.0, width: bounds.width, height: newValue))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = lineColor
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[line]|", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[line(==lineWidth)]", options: [], metrics: metrics, views: views))
}
}
@IBInspectable var rightBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: bounds.width, y: 0.0, width: newValue, height: bounds.height))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = lineColor
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "[line(==lineWidth)]|", options: [], metrics: metrics, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[line]|", options: [], metrics: nil, views: views))
}
}
@IBInspectable var bottomBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: 0.0, y: bounds.height, width: bounds.width, height: newValue))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = lineColor
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[line]|", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[line(==lineWidth)]|", options: [], metrics: metrics, views: views))
}
}
// @IBInspectable dynamic open var borderColor: UIColor = .lightGray
// @IBInspectable dynamic open var thickness: CGFloat = 1
//
// @IBInspectable dynamic open var topBorder: Bool = false {
// didSet {
// addBorder(edge: .top)
// }
// }
// @IBInspectable dynamic open var bottomBorder: Bool = false {
// didSet {
// addBorder(edge: .bottom)
// }
// }
// @IBInspectable dynamic open var rightBorder: Bool = false {
// didSet {
// addBorder(edge: .right)
// }
// }
// @IBInspectable dynamic open var leftBorder: Bool = false {
// didSet {
// addBorder(edge: .left)
// }
// }
// enum
// //decalare a private topBorder
// func addTopBorderWithColor(color: UIColor, thickness: CGFloat) {
// let border = CALayer()
// border.backgroundColor = color.cgColor
// border.frame = CGRect(x:0,y: 0,width: self.frame.size.width,height: thickness)
// self.layer.addSublayer(border)
// }
// func addTopBorderWithColor(color: UIColor, thickness: CGFloat) {
// let border = CALayer()
// border.backgroundColor = color.cgColor
// border.frame = CGRect(x:0,y: 0,width: self.frame.size.width,height: thickness)
// self.layer.addSublayer(border)
// }
//
// func addRightBorderWithColor(color: UIColor, thickness: CGFloat) {
// let border = CALayer()
// border.backgroundColor = color.cgColor
// border.frame = CGRect(x:self.frame.size.width - thickness,y: 0,width: width,height: self.frame.size.height)
// self.layer.addSublayer(border)
// }
//
// func addBottomBorderWithColor(color: UIColor, thickness: CGFloat) {
// let border = CALayer()
// border.backgroundColor = color.cgColor
// border.frame = CGRect(x:0,y: self.frame.size.height - thickness,width: self.frame.size.width,height: thickness)
// self.layer.addSublayer(border)
// }
//
// func addLeftBorderWithColor(color: UIColor, thickness: CGFloat) {
// let border = CALayer()
// border.backgroundColor = color.cgColor
// border.frame = CGRect(x:0,y: 0,width: thickness,height: self.frame.size.height)
// self.layer.addSublayer(border)
// }
}
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
}
| gpl-3.0 |
ccrama/Slide-iOS | Slide for Reddit/Fonts/FontGenerator.swift | 1 | 5057 | //
// FontGenerator.swift
// Slide for Reddit
//
// Created by Carlos Crane on 1/28/17.
// Copyright © 2017 Haptic Apps. All rights reserved.
//
import DTCoreText
import UIKit
class FontGenerator {
public static func fontOfSize(size: CGFloat, submission: Bool) -> UIFont {
let fontName = UserDefaults.standard.string(forKey: submission ? "postfont" : "commentfont") ?? ( submission ? "AvenirNext-DemiBold" : "AvenirNext-Medium")
let adjustedSize = size + CGFloat(submission ? SettingValues.postFontOffset : SettingValues.commentFontOffset)
return FontMapping.fromStoredName(name: fontName).font(ofSize: adjustedSize) ?? UIFont.systemFont(ofSize: adjustedSize)
}
public static func boldFontOfSize(size: CGFloat, submission: Bool) -> UIFont {
let normalFont = fontOfSize(size: size, submission: submission)
if normalFont.fontName == UIFont.systemFont(ofSize: 10).fontName {
return UIFont.boldSystemFont(ofSize: size)
}
return normalFont.makeBold()
}
public static var postFont = Font.SYSTEM
public static var commentFont = Font.SYSTEM
public static func initialize() {
if let name = UserDefaults.standard.string(forKey: "postfont") {
if let t = Font(rawValue: name) {
postFont = t
}
}
if let name = UserDefaults.standard.string(forKey: "commentfont") {
if let t = Font(rawValue: name) {
commentFont = t
}
}
}
enum Font: String {
case HELVETICA = "helvetica"
case AVENIR = "avenirnext-regular"
case AVENIR_MEDIUM = "avenirnext-medium"
case ROBOTOCONDENSED_REGULAR = "rcreg"
case ROBOTOCONDENSED_BOLD = "rcbold"
case ROBOTO_LIGHT = "rlight"
case ROBOTO_BOLD = "rbold"
case ROBOTO_MEDIUM = "rmed"
case SYSTEM = "system"
case PAPYRUS = "papyrus"
case CHALKBOARD = "chalkboard"
public static var cases: [Font] {
return [.HELVETICA, .AVENIR, .AVENIR_MEDIUM, .ROBOTOCONDENSED_REGULAR, .ROBOTOCONDENSED_BOLD, .ROBOTO_LIGHT, .ROBOTO_BOLD, .ROBOTO_MEDIUM, .SYSTEM]
}
public func bold() -> UIFont {
switch self {
case .HELVETICA:
return UIFont.init(name: "HelveticaNeue-Bold", size: 16)!
case .AVENIR:
return UIFont.init(name: "AvenirNext-DemiBold", size: 16)!
case .AVENIR_MEDIUM:
return UIFont.init(name: "AvenirNext-Bold", size: 16)!
case .ROBOTOCONDENSED_REGULAR:
return UIFont.init(name: "RobotoCondensed-Bold", size: 16)!
case .ROBOTOCONDENSED_BOLD:
return UIFont.init(name: "RobotoCondensed-Bold", size: 16)!
case .ROBOTO_LIGHT:
return UIFont.init(name: "Roboto-Medium", size: 16)!
case .ROBOTO_BOLD:
return UIFont.init(name: "Roboto-Bold", size: 16)!
case .ROBOTO_MEDIUM:
return UIFont.init(name: "Roboto-Bold", size: 16)!
case .PAPYRUS:
return UIFont.init(name: "Papyrus", size: 16)!
case .CHALKBOARD:
return UIFont.init(name: "ChalkboardSE-Bold", size: 16)!
case .SYSTEM:
return UIFont.boldSystemFont(ofSize: 16)
}
}
public var font: UIFont {
switch self {
case .HELVETICA:
return UIFont.init(name: "HelveticaNeue", size: 16)!
case .AVENIR:
return UIFont.init(name: "AvenirNext-Regular", size: 16)!
case .AVENIR_MEDIUM:
return UIFont.init(name: "AvenirNext-DemiBold", size: 16)!
case .ROBOTOCONDENSED_REGULAR:
return UIFont.init(name: "RobotoCondensed-Regular", size: 16)!
case .ROBOTOCONDENSED_BOLD:
return UIFont.init(name: "RobotoCondensed-Bold", size: 16)!
case .ROBOTO_LIGHT:
return UIFont.init(name: "Roboto-Light", size: 16)!
case .ROBOTO_BOLD:
return UIFont.init(name: "Roboto-Bold", size: 16)!
case .ROBOTO_MEDIUM:
return UIFont.init(name: "Roboto-Medium", size: 16)!
case .PAPYRUS:
return UIFont.init(name: "Papyrus", size: 16)!
case .CHALKBOARD:
return UIFont.init(name: "ChalkboardSE-Regular", size: 16)!
case .SYSTEM:
return UIFont.systemFont(ofSize: 16)
}
}
}
}
extension UIFont {
func withTraits(traits: UIFontDescriptor.SymbolicTraits...) -> UIFont {
let descriptor = self.fontDescriptor
.withSymbolicTraits(UIFontDescriptor.SymbolicTraits(traits)) ?? self.fontDescriptor
return UIFont(descriptor: descriptor, size: 0)
}
func makeBold() -> UIFont {
return withTraits(traits: .traitBold)
}
}
| apache-2.0 |
qingtianbuyu/Mono | Moon/Classes/Explore/Model/MNTea.swift | 1 | 1020 | //
// MNTea.swift
// Moon
//
// Created by YKing on 16/5/25.
// Copyright © 2016年 YKing. All rights reserved.
//
import UIKit
class MNTea: NSObject {
var start: Int = 0
var entity_list: [MNExploreEntity]?
var kind: Int = 2
var share_text: String?
var push_msg: String?
var title: String?
var sub_title: String?
var bg_img_url: String?
var release_date: Date?
var intro: String?
var read_time: String?
var share_time: String?
var share_image: String?
var id: Int = 0
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forKey key: String) {
if key == "entity_list" {
guard let array = (value as?[[String : AnyObject]]) else {
return
}
var tmpArray = [MNExploreEntity]()
for dict in array {
tmpArray.append(MNExploreEntity(dict:dict))
}
entity_list = tmpArray
return
}
super.setValue(value, forKey: key)
}
}
| mit |
LondonSwift/OnTrack | OnTrack/OnTrack/AppDelegate.swift | 1 | 3392 | //
// AppDelegate.swift
// OnTrack
//
// Created by Daren David Taylor on 01/09/2015.
// Copyright (c) 2015 LondonSwift. All rights reserved.
//
import UIKit
import LSRepeater
import Fabric
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func setupDefaults() {
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.objectForKey("file") == nil {
defaults.setObject("PennineBridleway.gpx", forKey:"file");
defaults.synchronize();
}
if defaults.objectForKey("OffTrackAudioOn") == nil {
defaults.setBool(true, forKey:"OffTrackAudioOn");
defaults.synchronize();
}
if defaults.objectForKey("WeatherAudioOn") == nil {
defaults.setBool(true, forKey:"WeatherAudioOn");
defaults.synchronize();
}
if defaults.objectForKey("RSSAudioOn") == nil {
defaults.setBool(true, forKey:"RSSAudioOn");
defaults.synchronize();
}
if defaults.objectForKey("TimeAudioOn") == nil {
defaults.setBool(true, forKey:"TimeAudioOn");
defaults.synchronize();
}
if defaults.objectForKey("OffTrackDistance") == nil {
defaults.setDouble(10.0, forKey:"OffTrackDistance");
defaults.synchronize();
}
if defaults.objectForKey("hasCopiedFiles") == nil {
// add this back in when we go live
// defaults.setBool(true, forKey:"hasCopiedFiles");
// defaults.synchronize();
self.copyFiles()
}
}
func copyFiles() {
let fileManager = NSFileManager.defaultManager()
do {
for path in ["PennineBridleway"] {
if let fullSourcePath = NSBundle.mainBundle().pathForResource(path, ofType:"gpx") {
if fileManager.fileExistsAtPath(fullSourcePath) {
try fileManager.copyItemAtPath(fullSourcePath, toPath: NSURL.applicationDocumentsDirectory().URLByAppendingPathComponent(path+".gpx").path!)
}
}
}
}
catch {
print("error copying")
}
}
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
self.setupDefaults()
let data = NSData(contentsOfURL: url)
if let path = url.lastPathComponent {
data?.writeToURL(NSURL.applicationDocumentsDirectory().URLByAppendingPathComponent(path), atomically: true)
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(path, forKey:"file");
defaults.synchronize();
let vc = self.window?.rootViewController as! MapViewController
vc.loadRoute(path)
}
return true
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Fabric.with([Crashlytics.self()])
self.setupDefaults()
return true
}
}
| gpl-3.0 |
bhajian/raspi-remote | Carthage/Checkouts/ios-sdk/Source/RelationshipExtractionV1Beta/Models/Sentence.swift | 1 | 3217 | /**
* Copyright IBM Corporation 2016
*
* 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 Freddy
/** Contains the analysis of an input sentence. Produced by the Relationship Extraction service. */
public struct Sentence: JSONDecodable {
/// The numeric identifier of the sentence.
public let sentenceID: Int
/// The index of the first token in the sentence.
public let begin: Int
/// The index of the last token in the sentence.
public let end: Int
/// The complete text of the analyzed sentence.
public let text: String
/// The serialized constituent parse tree for the sentence. See the following link for more
/// information: http://en.wikipedia.org/wiki/Parse_tree
public let parse: String
/// The dependency parse tree for the sentence. See the following link for more information:
/// http://www.cis.upenn.edu/~treebank/
public let dependencyParse: String
/// The universal Stanford dependency parse tree for the sentence. See the following link for
/// more information: http://nlp.stanford.edu/software/stanford-dependencies.shtml
public let usdDependencyParse: String
/// A list of Token objects for each token in the sentence. Tokens are the individual words and
/// punctuation in the sentence.
public let tokens: [Token]
/// Used internally to initialize a `Sentence` model from JSON.
public init(json: JSON) throws {
sentenceID = try json.int("sid")
begin = try json.int("begin")
end = try json.int("end")
text = try json.string("text")
parse = try json.string("parse", "text")
dependencyParse = try json.string("dependency_parse")
usdDependencyParse = try json.string("usd_dependency_parse")
tokens = try json.arrayOf("tokens", "token", type: Token.self)
}
}
/** A Token object provides more information about a specific token (word or punctuation) in the
sentence. */
public struct Token: JSONDecodable {
/// The beginning character offset of the token among all tokens of the input text.
public let begin: Int
/// The ending character offset of the token among all tokens of the input text.
public let end: Int
/// The token to which this object pertains.
public let text: String
/// The numeric identifier of the token.
public let tokenID: Int
/// Used internally to initialize a `Token` model from JSON.
public init(json: JSON) throws {
begin = try json.int("begin")
end = try json.int("end")
text = try json.string("text")
tokenID = try json.int("tid")
}
}
| mit |
quickthyme/PUTcat | PUTcat/Application/Data/Parser/DataStore/PCParserDataStoreLocal.swift | 1 | 1800 |
import Foundation
class PCParserDataStoreLocal : PCParserDataStore {
private static let StorageFile_Pfx = "PCParserList_"
private static let StorageFile_Sfx = ".json"
private static let StorageKey = "parsers"
private static func StorageFileName(_ parentID: String) -> String {
return "\(StorageFile_Pfx)\(parentID)\(StorageFile_Sfx)"
}
static func fetch(transactionID: String, asCopy: Bool) -> Composed.Action<Any, PCList<PCParser>> {
return Composed.Action<Any, PCList<PCParser>> { _, completion in
guard
let path = DocumentsDirectory.existingFilePathWithName(StorageFileName(transactionID)),
let dict = xJSON.parse(file: path) as? [String:Any],
let items = dict[StorageKey] as? [[String:Any]]
else { return completion(.success(PCList<PCParser>())) }
let list = PCList<PCParser>(fromLocal: items)
completion(
.success(
(asCopy) ? list.copy() : list
)
)
}
}
static func store(transactionID: String) -> Composed.Action<PCList<PCParser>, PCList<PCParser>> {
return Composed.Action<PCList<PCParser>, PCList<PCParser>> { list, completion in
guard let list = list else {
return completion(.failure(PCError(code: 404, text: "No list to store \(StorageKey)")))
}
let path = DocumentsDirectory.filePathWithName(StorageFileName(transactionID))
let dict = [ StorageKey : list.toLocal() ]
if xJSON.write(dict, toFile: path) { completion(.success(list)) }
else {
completion(.failure(PCError(code: 404, text: "Error writing \(StorageKey)")))
}
}
}
}
| apache-2.0 |
ja-mes/experiments | iOS/Auto layout expiriment/Auto layout expiriment/ViewController.swift | 1 | 519 | //
// ViewController.swift
// Auto layout expiriment
//
// Created by James Brown on 8/14/16.
// Copyright © 2016 James Brown. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
luoziyong/firefox-ios | Client/Frontend/Home/HistoryPanel.swift | 1 | 25397 | /* 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 Shared
import Storage
import XCGLogger
import Deferred
private let log = Logger.browserLogger
private typealias SectionNumber = Int
private typealias CategoryNumber = Int
private typealias CategorySpec = (section: SectionNumber?, rows: Int, offset: Int)
private struct HistoryPanelUX {
static let WelcomeScreenItemTextColor = UIColor.gray
static let WelcomeScreenItemWidth = 170
static let IconSize = 23
static let IconBorderColor = UIColor(white: 0, alpha: 0.1)
static let IconBorderWidth: CGFloat = 0.5
}
private func getDate(_ dayOffset: Int) -> Date {
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
let nowComponents = (calendar as NSCalendar).components([.year, .month, .day], from: Date())
let today = calendar.date(from: nowComponents)!
return (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.day, value: dayOffset, to: today, options: [])!
}
class HistoryPanel: SiteTableViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate?
private var currentSyncedDevicesCount: Int?
var events = [NotificationFirefoxAccountChanged, NotificationPrivateDataClearedHistory, NotificationDynamicFontChanged]
var refreshControl: UIRefreshControl?
fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = {
return UILongPressGestureRecognizer(target: self, action: #selector(HistoryPanel.longPress(_:)))
}()
private lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverlayView()
private let QueryLimit = 100
private let NumSections = 5
private let Today = getDate(0)
private let Yesterday = getDate(-1)
private let ThisWeek = getDate(-7)
private var categories: [CategorySpec] = [CategorySpec]() // Category number (index) -> (UI section, row count, cursor offset).
private var sectionLookup = [SectionNumber: CategoryNumber]() // Reverse lookup from UI section to data category.
var syncDetailText = ""
var hasRecentlyClosed: Bool {
return self.profile.recentlyClosedTabs.tabs.count > 0
}
// MARK: - Lifecycle
init() {
super.init(nibName: nil, bundle: nil)
events.forEach { NotificationCenter.default.addObserver(self, selector: #selector(HistoryPanel.notificationReceived(_:)), name: $0, object: nil) }
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
events.forEach { NotificationCenter.default.removeObserver(self, name: $0, object: nil) }
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.addGestureRecognizer(longPressRecognizer)
tableView.accessibilityIdentifier = "History List"
updateSyncedDevicesCount().uponQueue(DispatchQueue.main) { result in
self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Add a refresh control if the user is logged in and the control was not added before. If the user is not
// logged in, remove any existing control but only when it is not currently refreshing. Otherwise, wait for
// the refresh to finish before removing the control.
if profile.hasSyncableAccount() && refreshControl == nil {
addRefreshControl()
} else if refreshControl?.isRefreshing == false {
removeRefreshControl()
}
updateSyncedDevicesCount().uponQueue(DispatchQueue.main) { result in
self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount)
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: { context in
self.presentedViewController?.dismiss(animated: true, completion: nil)
}, completion: nil)
}
@objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
guard longPressGestureRecognizer.state == UIGestureRecognizerState.began else { return }
let touchPoint = longPressGestureRecognizer.location(in: tableView)
guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return }
if indexPath.section != 0 {
presentContextMenu(for: indexPath)
}
}
// MARK: - History Data Store
func updateNumberOfSyncedDevices(_ count: Int?) {
if let count = count, count > 0 {
syncDetailText = String.localizedStringWithFormat(Strings.SyncedTabsTableViewCellDescription, count)
} else {
syncDetailText = ""
}
self.tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: .automatic)
}
func updateSyncedDevicesCount() -> Success {
return chainDeferred(self.profile.getCachedClientsAndTabs()) { tabsAndClients in
self.currentSyncedDevicesCount = tabsAndClients.count
return succeed()
}
}
func notificationReceived(_ notification: Notification) {
switch notification.name {
case NotificationFirefoxAccountChanged, NotificationPrivateDataClearedHistory:
if self.profile.hasSyncableAccount() {
resyncHistory()
}
break
case NotificationDynamicFontChanged:
if emptyStateOverlayView.superview != nil {
emptyStateOverlayView.removeFromSuperview()
}
emptyStateOverlayView = createEmptyStateOverlayView()
resyncHistory()
break
default:
// no need to do anything at all
log.warning("Received unexpected notification \(notification.name)")
break
}
}
private func fetchData() -> Deferred<Maybe<Cursor<Site>>> {
return profile.history.getSitesByLastVisit(QueryLimit)
}
private func setData(_ data: Cursor<Site>) {
self.data = data
self.computeSectionOffsets()
}
func resyncHistory() {
profile.syncManager.syncHistory().uponQueue(DispatchQueue.main) { result in
if result.isSuccess {
self.reloadData()
} else {
self.endRefreshing()
}
self.updateSyncedDevicesCount().uponQueue(DispatchQueue.main) { result in
self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount)
}
}
}
// MARK: - Refreshing TableView
func addRefreshControl() {
let refresh = UIRefreshControl()
refresh.addTarget(self, action: #selector(HistoryPanel.refresh), for: UIControlEvents.valueChanged)
self.refreshControl = refresh
self.tableView.addSubview(refresh)
}
func removeRefreshControl() {
self.refreshControl?.removeFromSuperview()
self.refreshControl = nil
}
func endRefreshing() {
// Always end refreshing, even if we failed!
self.refreshControl?.endRefreshing()
// Remove the refresh control if the user has logged out in the meantime
if !self.profile.hasSyncableAccount() {
self.removeRefreshControl()
}
}
@objc func refresh() {
self.refreshControl?.beginRefreshing()
resyncHistory()
}
override func reloadData() {
self.fetchData().uponQueue(DispatchQueue.main) { result in
if let data = result.successValue {
self.setData(data)
self.tableView.reloadData()
self.updateEmptyPanelState()
}
self.endRefreshing()
}
}
// MARK: - Empty State
private func updateEmptyPanelState() {
if data.count == 0 {
if self.emptyStateOverlayView.superview == nil {
self.tableView.addSubview(self.emptyStateOverlayView)
self.emptyStateOverlayView.snp.makeConstraints { make -> Void in
make.left.right.bottom.equalTo(self.view)
make.top.equalTo(self.view).offset(100)
}
}
} else {
self.tableView.alwaysBounceVertical = true
self.emptyStateOverlayView.removeFromSuperview()
}
}
private func createEmptyStateOverlayView() -> UIView {
let overlayView = UIView()
overlayView.backgroundColor = UIColor.white
let welcomeLabel = UILabel()
overlayView.addSubview(welcomeLabel)
welcomeLabel.text = Strings.HistoryPanelEmptyStateTitle
welcomeLabel.textAlignment = NSTextAlignment.center
welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontLight
welcomeLabel.textColor = HistoryPanelUX.WelcomeScreenItemTextColor
welcomeLabel.numberOfLines = 0
welcomeLabel.adjustsFontSizeToFitWidth = true
welcomeLabel.snp.makeConstraints { make in
make.centerX.equalTo(overlayView)
// Sets proper top constraint for iPhone 6 in portait and for iPad.
make.centerY.equalTo(overlayView).offset(HomePanelUX.EmptyTabContentOffset).priority(100)
// Sets proper top constraint for iPhone 4, 5 in portrait.
make.top.greaterThanOrEqualTo(overlayView).offset(50)
make.width.equalTo(HistoryPanelUX.WelcomeScreenItemWidth)
}
return overlayView
}
// MARK: - TableView Row Helpers
func computeSectionOffsets() {
var counts = [Int](repeating: 0, count: NumSections)
// Loop over all the data. Record the start of each "section" of our list.
for i in 0..<data.count {
if let site = data[i] {
counts[categoryForDate(site.latestVisit!.date) + 1] += 1
}
}
var section = 0
var offset = 0
self.categories = [CategorySpec]()
for i in 0..<NumSections {
let count = counts[i]
if i == 0 {
sectionLookup[section] = i
section += 1
}
if count > 0 {
log.debug("Category \(i) has \(count) rows, and thus is section \(section).")
self.categories.append((section: section, rows: count, offset: offset))
sectionLookup[section] = i
offset += count
section += 1
} else {
log.debug("Category \(i) has 0 rows, and thus has no section.")
self.categories.append((section: nil, rows: 0, offset: offset))
}
}
}
fileprivate func siteForIndexPath(_ indexPath: IndexPath) -> Site? {
let offset = self.categories[sectionLookup[indexPath.section]!].offset
return data[indexPath.row + offset]
}
private func categoryForDate(_ date: MicrosecondTimestamp) -> Int {
let date = Double(date)
if date > (1000000 * Today.timeIntervalSince1970) {
return 0
}
if date > (1000000 * Yesterday.timeIntervalSince1970) {
return 1
}
if date > (1000000 * ThisWeek.timeIntervalSince1970) {
return 2
}
return 3
}
private func isInCategory(_ date: MicrosecondTimestamp, category: Int) -> Bool {
return self.categoryForDate(date) == category
}
// UI sections disappear as categories empty. We need to translate back and forth.
private func uiSectionToCategory(_ section: SectionNumber) -> CategoryNumber {
for i in 0..<self.categories.count {
if let s = self.categories[i].section, s == section {
return i
}
}
return 0
}
private func categoryToUISection(_ category: CategoryNumber) -> SectionNumber? {
return self.categories[category].section
}
// MARK: - TableView Delegate / DataSource
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
cell.accessoryType = UITableViewCellAccessoryType.none
if indexPath.section == 0 {
cell.imageView!.layer.borderWidth = 0
return indexPath.row == 0 ? configureRecentlyClosed(cell, for: indexPath) : configureSyncedTabs(cell, for: indexPath)
} else {
return configureSite(cell, for: indexPath)
}
}
func configureRecentlyClosed(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell {
cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
cell.textLabel!.text = Strings.RecentlyClosedTabsButtonTitle
cell.detailTextLabel!.text = ""
cell.imageView!.image = UIImage(named: "recently_closed")
cell.imageView?.backgroundColor = UIColor.white
if !hasRecentlyClosed {
cell.textLabel?.alpha = 0.5
cell.imageView!.alpha = 0.5
cell.selectionStyle = .none
}
cell.accessibilityIdentifier = "HistoryPanel.recentlyClosedCell"
return cell
}
func configureSyncedTabs(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell {
cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
cell.textLabel!.text = Strings.SyncedTabsTableViewCellTitle
cell.detailTextLabel!.text = self.syncDetailText
cell.imageView!.image = UIImage(named: "synced_devices")
cell.imageView?.backgroundColor = UIColor.white
cell.accessibilityIdentifier = "HistoryPanel.syncedDevicesCell"
return cell
}
func configureSite(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell {
if let site = siteForIndexPath(indexPath), let cell = cell as? TwoLineTableViewCell {
cell.setLines(site.title, detailText: site.url)
cell.imageView!.layer.borderColor = HistoryPanelUX.IconBorderColor.cgColor
cell.imageView!.layer.borderWidth = HistoryPanelUX.IconBorderWidth
cell.imageView?.setIcon(site.icon, forURL: site.tileURL, completed: { (color, url) in
if site.tileURL == url {
cell.imageView?.image = cell.imageView?.image?.createScaled(CGSize(width: HistoryPanelUX.IconSize, height: HistoryPanelUX.IconSize))
cell.imageView?.backgroundColor = color
cell.imageView?.contentMode = .center
}
})
}
return cell
}
func numberOfSectionsInTableView(_ tableView: UITableView) -> Int {
var count = 1
for category in self.categories where category.rows > 0 {
count += 1
}
return count
}
func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
if indexPath.section == 0 {
self.tableView.deselectRow(at: indexPath, animated: true)
return indexPath.row == 0 ? self.showRecentlyClosed() : self.showSyncedTabs()
}
if let site = self.siteForIndexPath(indexPath), let url = URL(string: site.url) {
let visitType = VisitType.typed // Means History, too.
if let homePanelDelegate = homePanelDelegate {
homePanelDelegate.homePanel(self, didSelectURL: url, visitType: visitType)
}
return
}
log.warning("No site or no URL when selecting row.")
}
func pinTopSite(_ site: Site) {
_ = profile.history.addPinnedTopSite(site).value
}
func showSyncedTabs() {
let nextController = RemoteTabsPanel()
nextController.homePanelDelegate = self.homePanelDelegate
nextController.profile = self.profile
self.refreshControl?.endRefreshing()
self.navigationController?.pushViewController(nextController, animated: true)
}
func showRecentlyClosed() {
guard hasRecentlyClosed else {
return
}
let nextController = RecentlyClosedTabsPanel()
nextController.homePanelDelegate = self.homePanelDelegate
nextController.profile = self.profile
self.refreshControl?.endRefreshing()
self.navigationController?.pushViewController(nextController, animated: true)
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var title = String()
switch sectionLookup[section]! {
case 0: return nil
case 1: title = NSLocalizedString("Today", comment: "History tableview section header")
case 2: title = NSLocalizedString("Yesterday", comment: "History tableview section header")
case 3: title = NSLocalizedString("Last week", comment: "History tableview section header")
case 4: title = NSLocalizedString("Last month", comment: "History tableview section header")
default:
assertionFailure("Invalid history section \(section)")
}
return title
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0 {
return nil
}
return super.tableView(tableView, viewForHeaderInSection: section)
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return 0
}
return super.tableView(tableView, heightForHeaderInSection: section)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 2
}
return self.categories[uiSectionToCategory(section)].rows
}
func tableView(_ tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: IndexPath) {
// Intentionally blank. Required to use UITableViewRowActions
}
fileprivate func removeHistoryForURLAtIndexPath(indexPath: IndexPath) {
if let site = self.siteForIndexPath(indexPath) {
// Why the dispatches? Because we call success and failure on the DB
// queue, and so calling anything else that calls through to the DB will
// deadlock. This problem will go away when the history API switches to
// Deferred instead of using callbacks.
self.profile.history.removeHistoryForURL(site.url)
.upon { res in
self.fetchData().uponQueue(DispatchQueue.main) { result in
// If a section will be empty after removal, we must remove the section itself.
if let data = result.successValue {
let oldCategories = self.categories
self.data = data
self.computeSectionOffsets()
let sectionsToDelete = NSMutableIndexSet()
var rowsToDelete = [IndexPath]()
let sectionsToAdd = NSMutableIndexSet()
var rowsToAdd = [IndexPath]()
for (index, category) in self.categories.enumerated() {
let oldCategory = oldCategories[index]
// don't bother if we're not displaying this category
if oldCategory.section == nil && category.section == nil {
continue
}
// 1. add a new section if the section didn't previously exist
if oldCategory.section == nil && category.section != oldCategory.section {
log.debug("adding section \(category.section ?? 0)")
sectionsToAdd.add(category.section!)
}
// 2. add a new row if there are more rows now than there were before
if oldCategory.rows < category.rows {
log.debug("adding row to \(category.section ?? 0) at \(category.rows-1)")
rowsToAdd.append(IndexPath(row: category.rows-1, section: category.section!))
}
// if we're dealing with the section where the row was deleted:
// 1. if the category no longer has a section, then we need to delete the entire section
// 2. delete a row if the number of rows has been reduced
// 3. delete the selected row and add a new one on the bottom of the section if the number of rows has stayed the same
if oldCategory.section == indexPath.section {
if category.section == nil {
log.debug("deleting section \(indexPath.section)")
sectionsToDelete.add(indexPath.section)
} else if oldCategory.section == category.section {
if oldCategory.rows > category.rows {
log.debug("deleting row from \(category.section ?? 0) at \(indexPath.row)")
rowsToDelete.append(indexPath)
} else if category.rows == oldCategory.rows {
log.debug("in section \(category.section ?? 0), removing row at \(indexPath.row) and inserting row at \(category.rows-1)")
rowsToDelete.append(indexPath)
rowsToAdd.append(IndexPath(row: category.rows-1, section: indexPath.section))
}
}
}
}
self.tableView.beginUpdates()
if sectionsToAdd.count > 0 {
self.tableView.insertSections(sectionsToAdd as IndexSet, with: UITableViewRowAnimation.left)
}
if sectionsToDelete.count > 0 {
self.tableView.deleteSections(sectionsToDelete as IndexSet, with: UITableViewRowAnimation.right)
}
if !rowsToDelete.isEmpty {
self.tableView.deleteRows(at: rowsToDelete, with: UITableViewRowAnimation.right)
}
if !rowsToAdd.isEmpty {
self.tableView.insertRows(at: rowsToAdd, with: UITableViewRowAnimation.right)
}
self.tableView.endUpdates()
self.updateEmptyPanelState()
}
}
}
}
}
func tableView(_ tableView: UITableView, editActionsForRowAtIndexPath indexPath: IndexPath) -> [AnyObject]? {
if indexPath.section == 0 {
return []
}
let title = NSLocalizedString("Delete", tableName: "HistoryPanel", comment: "Action button for deleting history entries in the history panel.")
let delete = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: title, handler: { (action, indexPath) in
self.removeHistoryForURLAtIndexPath(indexPath: indexPath)
})
return [delete]
}
}
extension HistoryPanel: HomePanelContextMenu {
func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> ActionOverlayTableViewController?) {
guard let contextMenu = completionHandler() else { return }
self.present(contextMenu, animated: true, completion: nil)
}
func getSiteDetails(for indexPath: IndexPath) -> Site? {
return siteForIndexPath(indexPath)
}
func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [ActionOverlayTableViewAction]? {
guard var actions = getDefaultContextMenuActions(for: site, homePanelDelegate: homePanelDelegate) else { return nil }
let removeAction = ActionOverlayTableViewAction(title: Strings.DeleteFromHistoryContextMenuTitle, iconString: "action_delete", handler: { action in
self.removeHistoryForURLAtIndexPath(indexPath: indexPath)
})
let pinTopSite = ActionOverlayTableViewAction(title: Strings.PinTopsiteActionTitle, iconString: "action_pin", handler: { action in
self.pinTopSite(site)
})
if FeatureSwitches.activityStream.isMember(profile.prefs) {
actions.append(pinTopSite)
}
actions.append(removeAction)
return actions
}
}
| mpl-2.0 |
eduresende/ios-nd-swift-syntax-swift-3 | Lesson6/L6_Classes_Properties_Methods.playground/Sources/SupportCode.swift | 1 | 887 | //
// This file (and all other Swift source files in the Sources directory of this playground) will be precompiled into a framework which is automatically made available to Classes_Properties_Methods.playground.
//
import UIKit
class Movie {
let title: String
let director: String
let releaseYear: Int
init(title: String, director:String, releaseYear: Int) {
self.title = title
self.director = director
self.releaseYear = releaseYear
}
}
class MovieArchive {
var movies:[Movie]
func filterByYear(_ year:Int, movies: [Movie]) -> [Movie] {
var filteredArray = [Movie]()
for movie in movies {
if movie.releaseYear == year {
filteredArray.append(movie)
}
}
return filteredArray
}
init(movies:[Movie]) {
self.movies = movies
}
}
| mit |
yapstudios/YapAnimator | Example/YapAnimatorExample-macOS/AppDelegate.swift | 1 | 493 | //
// AppDelegate.swift
// YapAnimatorExample_Mac
//
// Created by Ollie Wagner on 7/7/17.
// Copyright © 2017 Yap Studios. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| bsd-2-clause |
niunaruto/DeDaoAppSwift | testSwift/Pods/RxSwift/RxSwift/Observables/GroupBy.swift | 20 | 4742 | //
// GroupBy.swift
// RxSwift
//
// Created by Tomi Koskinen on 01/12/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/*
Groups the elements of an observable sequence according to a specified key selector function.
- seealso: [groupBy operator on reactivex.io](http://reactivex.io/documentation/operators/groupby.html)
- parameter keySelector: A function to extract the key for each element.
- returns: A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
*/
public func groupBy<Key: Hashable>(keySelector: @escaping (Element) throws -> Key)
-> Observable<GroupedObservable<Key, Element>> {
return GroupBy(source: self.asObservable(), selector: keySelector)
}
}
final private class GroupedObservableImpl<Element>: Observable<Element> {
private var _subject: PublishSubject<Element>
private var _refCount: RefCountDisposable
init(subject: PublishSubject<Element>, refCount: RefCountDisposable) {
self._subject = subject
self._refCount = refCount
}
override public func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
let release = self._refCount.retain()
let subscription = self._subject.subscribe(observer)
return Disposables.create(release, subscription)
}
}
final private class GroupBySink<Key: Hashable, Element, Observer: ObserverType>
: Sink<Observer>
, ObserverType where Observer.Element == GroupedObservable<Key, Element> {
typealias ResultType = Observer.Element
typealias Parent = GroupBy<Key, Element>
private let _parent: Parent
private let _subscription = SingleAssignmentDisposable()
private var _refCountDisposable: RefCountDisposable!
private var _groupedSubjectTable: [Key: PublishSubject<Element>]
init(parent: Parent, observer: Observer, cancel: Cancelable) {
self._parent = parent
self._groupedSubjectTable = [Key: PublishSubject<Element>]()
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
self._refCountDisposable = RefCountDisposable(disposable: self._subscription)
self._subscription.setDisposable(self._parent._source.subscribe(self))
return self._refCountDisposable
}
private func onGroupEvent(key: Key, value: Element) {
if let writer = self._groupedSubjectTable[key] {
writer.on(.next(value))
} else {
let writer = PublishSubject<Element>()
self._groupedSubjectTable[key] = writer
let group = GroupedObservable(
key: key,
source: GroupedObservableImpl(subject: writer, refCount: _refCountDisposable)
)
self.forwardOn(.next(group))
writer.on(.next(value))
}
}
final func on(_ event: Event<Element>) {
switch event {
case let .next(value):
do {
let groupKey = try self._parent._selector(value)
self.onGroupEvent(key: groupKey, value: value)
}
catch let e {
self.error(e)
return
}
case let .error(e):
self.error(e)
case .completed:
self.forwardOnGroups(event: .completed)
self.forwardOn(.completed)
self._subscription.dispose()
self.dispose()
}
}
final func error(_ error: Swift.Error) {
self.forwardOnGroups(event: .error(error))
self.forwardOn(.error(error))
self._subscription.dispose()
self.dispose()
}
final func forwardOnGroups(event: Event<Element>) {
for writer in self._groupedSubjectTable.values {
writer.on(event)
}
}
}
final private class GroupBy<Key: Hashable, Element>: Producer<GroupedObservable<Key,Element>> {
typealias KeySelector = (Element) throws -> Key
fileprivate let _source: Observable<Element>
fileprivate let _selector: KeySelector
init(source: Observable<Element>, selector: @escaping KeySelector) {
self._source = source
self._selector = selector
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == GroupedObservable<Key,Element> {
let sink = GroupBySink(parent: self, observer: observer, cancel: cancel)
return (sink: sink, subscription: sink.run())
}
}
| mit |
mrdepth/EVEUniverse | Legacy/Neocom/Neocom/NCTableViewBackgroundLabel.swift | 2 | 940 | //
// File.swift
// Neocom
//
// Created by Artem Shimanski on 08.12.16.
// Copyright © 2016 Artem Shimanski. All rights reserved.
//
import UIKit
class NCTableViewBackgroundLabel: NCLabel {
override init(frame: CGRect) {
super.init(frame: frame)
numberOfLines = 0
pointSize = 15
font = UIFont.systemFont(ofSize: fontSize(contentSizeCategory: UIApplication.shared.preferredContentSizeCategory))
textColor = UIColor.lightText
}
convenience init(text: String) {
self.init(frame: CGRect.zero)
let paragraph = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraph.firstLineHeadIndent = 20
paragraph.headIndent = 20
paragraph.tailIndent = -20
paragraph.alignment = NSTextAlignment.center
attributedText = NSAttributedString(string: text, attributes: [NSAttributedStringKey.paragraphStyle: paragraph])
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| lgpl-2.1 |
niunaruto/DeDaoAppSwift | testSwift/Pods/RxCocoa/RxCocoa/iOS/UIScrollView+Rx.swift | 33 | 6592 | //
// UIScrollView+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 4/3/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import RxSwift
import UIKit
extension Reactive where Base: UIScrollView {
public typealias EndZoomEvent = (view: UIView?, scale: CGFloat)
public typealias WillEndDraggingEvent = (velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
/// Reactive wrapper for `delegate`.
///
/// For more information take a look at `DelegateProxyType` protocol documentation.
public var delegate: DelegateProxy<UIScrollView, UIScrollViewDelegate> {
return RxScrollViewDelegateProxy.proxy(for: base)
}
/// Reactive wrapper for `contentOffset`.
public var contentOffset: ControlProperty<CGPoint> {
let proxy = RxScrollViewDelegateProxy.proxy(for: base)
let bindingObserver = Binder(self.base) { scrollView, contentOffset in
scrollView.contentOffset = contentOffset
}
return ControlProperty(values: proxy.contentOffsetBehaviorSubject, valueSink: bindingObserver)
}
/// Bindable sink for `scrollEnabled` property.
public var isScrollEnabled: Binder<Bool> {
return Binder(self.base) { scrollView, scrollEnabled in
scrollView.isScrollEnabled = scrollEnabled
}
}
/// Reactive wrapper for delegate method `scrollViewDidScroll`
public var didScroll: ControlEvent<Void> {
let source = RxScrollViewDelegateProxy.proxy(for: base).contentOffsetPublishSubject
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewWillBeginDecelerating`
public var willBeginDecelerating: ControlEvent<Void> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillBeginDecelerating(_:))).map { _ in }
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewDidEndDecelerating`
public var didEndDecelerating: ControlEvent<Void> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndDecelerating(_:))).map { _ in }
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewWillBeginDragging`
public var willBeginDragging: ControlEvent<Void> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillBeginDragging(_:))).map { _ in }
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewWillEndDragging(_:withVelocity:targetContentOffset:)`
public var willEndDragging: ControlEvent<WillEndDraggingEvent> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillEndDragging(_:withVelocity:targetContentOffset:)))
.map { value -> WillEndDraggingEvent in
let velocity = try castOrThrow(CGPoint.self, value[1])
let targetContentOffsetValue = try castOrThrow(NSValue.self, value[2])
guard let rawPointer = targetContentOffsetValue.pointerValue else { throw RxCocoaError.unknown }
let typedPointer = rawPointer.bindMemory(to: CGPoint.self, capacity: MemoryLayout<CGPoint>.size)
return (velocity, typedPointer)
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewDidEndDragging(_:willDecelerate:)`
public var didEndDragging: ControlEvent<Bool> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndDragging(_:willDecelerate:))).map { value -> Bool in
return try castOrThrow(Bool.self, value[1])
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewDidZoom`
public var didZoom: ControlEvent<Void> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidZoom)).map { _ in }
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewDidScrollToTop`
public var didScrollToTop: ControlEvent<Void> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidScrollToTop(_:))).map { _ in }
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewDidEndScrollingAnimation`
public var didEndScrollingAnimation: ControlEvent<Void> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndScrollingAnimation(_:))).map { _ in }
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewWillBeginZooming(_:with:)`
public var willBeginZooming: ControlEvent<UIView?> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillBeginZooming(_:with:))).map { value -> UIView? in
return try castOptionalOrThrow(UIView.self, value[1] as AnyObject)
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewDidEndZooming(_:with:atScale:)`
public var didEndZooming: ControlEvent<EndZoomEvent> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndZooming(_:with:atScale:))).map { value -> EndZoomEvent in
return (try castOptionalOrThrow(UIView.self, value[1] as AnyObject), try castOrThrow(CGFloat.self, value[2]))
}
return ControlEvent(events: source)
}
/// Installs delegate as forwarding delegate on `delegate`.
/// Delegate won't be retained.
///
/// It enables using normal delegate mechanism with reactive delegate mechanism.
///
/// - parameter delegate: Delegate object.
/// - returns: Disposable object that can be used to unbind the delegate.
public func setDelegate(_ delegate: UIScrollViewDelegate)
-> Disposable {
return RxScrollViewDelegateProxy.installForwardDelegate(delegate, retainDelegate: false, onProxyForObject: self.base)
}
}
#endif
| mit |
OscarSwanros/swift | validation-test/compiler_crashers_fixed/28796-result-second.swift | 2 | 495 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// REQUIRES: asserts
// RUN: not %target-swift-frontend %s -emit-ir
class a<a{{{}}func b{extension{class a<a{{}class a:RangeReplaceableCollection
| apache-2.0 |
mozilla/focus | Shared/AppConfig.swift | 5 | 1209 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
protocol AppConfig {
var adjustFile: String { get }
var firefoxAppStoreURL: URL { get }
var productName: String { get }
var rightsFile: String { get }
var supportPath: String { get }
var appId: String { get }
var wordmark: UIImage { get }
}
struct FocusAppConfig: AppConfig {
let adjustFile = "Adjust-Focus"
let firefoxAppStoreURL = URL(string: "https://app.adjust.com/gs1ao4")!
let productName = "Focus"
let rightsFile = "rights-focus.html"
let supportPath = "kb/focus"
let appId = "1055677337"
let wordmark = #imageLiteral(resourceName: "img_focus_wordmark")
}
struct KlarAppConfig: AppConfig {
let adjustFile = "Adjust-Klar"
let firefoxAppStoreURL = URL(string: "https://app.adjust.com/c04cts")!
let productName = "Klar"
let rightsFile = "rights-klar.html"
let supportPath = "products/klar"
let appId = "1073435754"
let wordmark = #imageLiteral(resourceName: "img_klar_wordmark")
}
| mpl-2.0 |
roecrew/AudioKit | AudioKit/Common/Tests/AKMorphingOscillatorTests.swift | 2 | 1274 | //
// AKMorphingOscillatorTests.swift
// AudioKitTestSuite
//
// Created by Aurelius Prochazka on 8/8/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import XCTest
import AudioKit
class AKMorphingOscillatorTests: AKTestCase {
func testDefault() {
output = AKMorphingOscillator()
AKTestMD5("49b1b0f944c9ba307a890cb55cec75d6")
}
func testParametersSetOnInit() {
output = AKMorphingOscillator(
waveformArray: [AKTable(.Sine), AKTable(.Triangle), AKTable(.Sawtooth), AKTable(.Square)],
frequency: 1234,
amplitude: 0.5,
index: 1.234,
detuningOffset: 1.234,
detuningMultiplier: 1.234)
AKTestMD5("626954fd45dd2d60e0879d73e0c9d7dd")
}
func testParametersSetAfterInit() {
let oscillator = AKMorphingOscillator(waveformArray: [AKTable(.Sine), AKTable(.Triangle), AKTable(.Sawtooth), AKTable(.Square)])
oscillator.frequency = 1234
oscillator.amplitude = 0.5
oscillator.index = 1.234
oscillator.detuningOffset = 1.234
oscillator.detuningMultiplier = 1.234
output = oscillator
AKTestMD5("626954fd45dd2d60e0879d73e0c9d7dd")
}}
| mit |
hooman/swift | test/IRGen/unmanaged_objc_throw_func.swift | 4 | 4399 | // RUN: %target-swift-frontend -emit-ir -enable-copy-propagation %s | %FileCheck %s
// REQUIRES: objc_interop
// REQUIRES: optimized_stdlib
import Foundation
@objc protocol SR_9035_P {
func returnUnmanagedCFArray() throws -> Unmanaged<CFArray>
}
// CHECK-LABEL: define hidden swiftcc %TSo10CFArrayRefa* @"$s25unmanaged_objc_throw_func9SR_9035_CC22returnUnmanagedCFArrays0G0VySo0H3RefaGyKF"
@objc class SR_9035_C: NSObject, SR_9035_P {
func returnUnmanagedCFArray() throws -> Unmanaged<CFArray> {
// CHECK: %[[T0:.+]] = call swiftcc { %swift.bridge*, i8* } @"$ss27_allocateUninitializedArrayySayxG_BptBwlF"(i{{32|64}} 1, %swift.type* @"$sSiN")
// CHECK-NEXT: %[[T1:.+]] = extractvalue { %swift.bridge*, i8* } %[[T0]], 0
// CHECK-NEXT: %[[T2:.+]] = extractvalue { %swift.bridge*, i8* } %[[T0]], 1
// CHECK-NEXT: %[[T3:.+]] = bitcast i8* %[[T2]] to %TSi*
// CHECK-NEXT: %._value = getelementptr inbounds %TSi, %TSi* %[[T3]], i32 0, i32 0
// CHECK: %[[T7:.+]] = call swiftcc %swift.bridge* @"$ss27_finalizeUninitializedArrayySayxGABnlF"(%swift.bridge* %[[T1]], %swift.type* @"$sSiN")
// CHECK: %[[T4:.+]] = call swiftcc %TSo7NSArrayC* @"$sSa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF"(%swift.bridge* %[[T7]], %swift.type* @"$sSiN")
// CHECK-NEXT: %[[T5:.+]] = bitcast %TSo7NSArrayC* %[[T4]] to %TSo10CFArrayRefa*
// CHECK-NEXT: store %TSo10CFArrayRefa* %[[T5]]
// CHECK-NEXT: call void @swift_bridgeObjectRelease(%swift.bridge* %{{[0-9]+}}) #{{[0-9]+}}
// CHECK-NEXT: %[[T6:.+]] = bitcast %TSo10CFArrayRefa* %[[T5]] to i8*
// CHECK-NEXT: call void @llvm.objc.release(i8* %[[T6]])
// CHECK-NEXT: ret %TSo10CFArrayRefa* %[[T5]]
let arr = [1] as CFArray
return Unmanaged.passUnretained(arr)
}
}
// CHECK: %[[T0:.+]] = call swiftcc %TSo10CFArrayRefa* @"$s25unmanaged_objc_throw_func9SR_9035_CC22returnUnmanagedCFArrays0G0VySo0H3RefaGyKF"
// CHECK-NEXT: %[[T2:.+]] = load %swift.error*, %swift.error** %swifterror, align {{[0-9]+}}
// CHECK-NEXT: %[[T3:.+]] = icmp ne %swift.error* %[[T2]], null
// CHECK-NEXT: br i1 %[[T3]], label %[[L1:.+]], label %[[L2:.+]]
// CHECK: [[L2]]: ; preds = %entry
// CHECK-NEXT: %[[T4:.+]] = phi %TSo10CFArrayRefa* [ %[[T0]], %entry ]
// CHECK-NEXT: %[[T4a:.+]] = bitcast %T25unmanaged_objc_throw_func9SR_9035_CC* %{{.+}} to i8*
// CHECK-NEXT: call void @llvm.objc.release(i8* %[[T4a]])
// CHECK-NEXT: %[[T5:.+]] = ptrtoint %TSo10CFArrayRefa* %[[T4]] to i{{32|64}}
// CHECK-NEXT: br label %[[L3:.+]]
// CHECK: [[L1]]: ; preds = %entry
// CHECK-NEXT: %[[T6:.+]] = phi %swift.error* [ %[[T2]], %entry ]
// CHECK-NEXT: store %swift.error* null, %swift.error** %swifterror, align {{[0-9]+}}
// CHECK-NEXT: %[[T6a:.+]] = bitcast %T25unmanaged_objc_throw_func9SR_9035_CC* %{{.+}} to i8*
// CHECK-NEXT: call void @llvm.objc.release(i8* %[[T6a]])
// CHECK-NEXT: %[[T7:.+]] = icmp eq i{{32|64}} %{{.+}}, 0
// CHECK-NEXT: br i1 %[[T7]], label %[[L4:.+]], label %[[L5:.+]]
// CHECK: [[L5]]: ; preds = %[[L1]]
// CHECK-NEXT: %[[T8:.+]] = inttoptr i{{32|64}} %{{.+}} to i8*
// CHECK-NEXT: br label %[[L6:.+]]
// CHECK: [[L6]]: ; preds = %[[L5]]
// CHECK-NEXT: %[[T9:.+]] = phi i8* [ %[[T8]], %[[L5]] ]
// CHECK-NEXT: %[[T10:.+]] = call swiftcc %TSo7NSErrorC* @"$s10Foundation22_convertErrorToNSErrorySo0E0Cs0C0_pF"(%swift.error* %[[T6]]) #{{[0-9]+}}
// CHECK: call swiftcc void @"$sSA7pointeexvs"(%swift.opaque* noalias nocapture %{{.+}}, i8* %[[T9]], %swift.type* %{{.+}}) #{{[0-9]+}}
// CHECK-NEXT: %[[T11:.+]] = bitcast %TSo7NSErrorCSg* %{{.+}} to i8*
// CHECK: call void @swift_errorRelease(%swift.error* %[[T6]]) #{{[0-9]+}}
// CHECK-NEXT: br label %[[L7:.+]]
// CHECK: [[L4]]: ; preds = %[[L1]]
// CHECK-NEXT: call void @swift_errorRelease(%swift.error* %[[T6]]) #{{[0-9]+}}
// CHECK-NEXT: br label %[[L7]]
// CHECK: [[L7]]: ; preds = %[[L6]], %[[L4]]
// CHECK-NEXT: br label %[[L3]]
// CHECK: [[L3]]: ; preds = %[[L2]], %[[L7]]
// CHECK-NEXT: %[[T12:.+]] = phi i{{32|64}} [ 0, %[[L7]] ], [ %[[T5]], %[[L2]] ]
// CHECK-NEXT: %[[T14:.+]] = inttoptr i{{32|64}} %[[T12]] to %struct.__CFArray*
// CHECK-NEXT: ret %struct.__CFArray* %[[T14]]
| apache-2.0 |
Miridescen/M_365key | 365KEY_swift/365KEY_swift/MainController/Class/UserCenter/controller/SKMyFocusController.swift | 1 | 4764 | //
// SKMyFocusController.swift
// 365KEY_swift
//
// Created by 牟松 on 2016/12/1.
// Copyright © 2016年 DoNews. All rights reserved.
//
import UIKit
class SKMyFocusController: UIViewController {
var navBar: UINavigationBar?
var navItem: UINavigationItem?
var bgView: UIView?
var headBtnView: UIView?
var productBtn: UIButton?
var peopleBtn: UIButton?
lazy var NoInfoView = SKNoInfoView(frame: CGRect(x: 0, y: 72, width: SKScreenWidth, height: SKScreenHeight-64-72))
lazy var focusProductView = SKMyfocusProductTV(frame: CGRect(x: 0, y: 72, width: SKScreenWidth, height: SKScreenHeight-64-72), style: UITableViewStyle.init(rawValue: 0)!)
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
addSubView()
loadData()
}
func loadData() {
NSURLConnection.connection.userCenterMyFocusDataRqeuest { (bool, jsonData) in
if bool {
self.focusProductView.dataSourceArray = jsonData!
self.bgView?.addSubview(self.focusProductView)
} else {
self.bgView?.insertSubview(self.NoInfoView, at: (self.bgView?.subviews.count)!)
}
}
}
}
extension SKMyFocusController{
func addSubView() {
navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: SKScreenWidth, height: 64))
navBar?.isTranslucent = false
navBar?.barTintColor = UIColor().mainColor
navBar?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
view.addSubview(navBar!)
navItem = UINavigationItem()
navItem?.leftBarButtonItem = UIBarButtonItem(SK_barButtonItem: UIImage(named:"icon_back"), selectorImage: UIImage(named:"icon_back"), tragtic: self, action: #selector(backBtnDidClick))
navItem?.title = "我的关注"
navBar?.items = [navItem!]
bgView = UIView(frame: CGRect(x: 0, y: 64, width: SKScreenWidth, height: SKScreenHeight-64))
view.addSubview(bgView!)
headBtnView = UIView(frame: CGRect(x: 0, y: 0, width: SKScreenWidth, height: 72))
bgView?.addSubview(headBtnView!)
let topLineLayer = CALayer()
topLineLayer.frame = CGRect(x: 16, y: 12, width: SKScreenWidth-32, height: 1)
topLineLayer.backgroundColor = UIColor(white: 225/255.0, alpha: 1).cgColor
headBtnView?.layer.addSublayer(topLineLayer)
let bottemLineLayer = CALayer()
bottemLineLayer.frame = CGRect(x: 16, y: 60, width: SKScreenWidth-32, height: 1)
bottemLineLayer.backgroundColor = UIColor(white: 225/255.0, alpha: 1).cgColor
headBtnView?.layer.addSublayer(bottemLineLayer)
let verticalLineLayer = CALayer()
verticalLineLayer.frame = CGRect(x: SKScreenWidth/2, y: 27, width: 2, height: 20)
verticalLineLayer.backgroundColor = UIColor(white: 225/255.0, alpha: 1).cgColor
headBtnView?.layer.addSublayer(verticalLineLayer)
productBtn = UIButton(frame: CGRect(x: ((SKScreenWidth/2-16)-126)/2+16, y: 23, width: 126, height: 28))
productBtn?.setBackgroundImage(UIImage(named: "bg_guanzhu_nav"), for: .selected)
productBtn?.setTitle("产品", for: .normal)
productBtn?.setTitleColor(UIColor.white, for: .selected)
productBtn?.setTitleColor(UIColor.black, for: .normal)
productBtn?.isSelected = true
productBtn?.addTarget(self, action: #selector(productBtnDidClick), for: .touchUpInside)
headBtnView?.addSubview(productBtn!)
peopleBtn = UIButton(frame: CGRect(x: ((SKScreenWidth/2-16)-126)/2+SKScreenWidth/2, y: 23, width: 126, height: 28))
peopleBtn?.setBackgroundImage(UIImage(named: "bg_guanzhu_nav"), for: .selected)
peopleBtn?.setTitle("人脉", for: .normal)
peopleBtn?.setTitleColor(UIColor.white, for: .selected)
peopleBtn?.setTitleColor(UIColor.black, for: .normal)
peopleBtn?.addTarget(self, action: #selector(peopleBtnDidClick), for: .touchUpInside)
headBtnView?.addSubview(peopleBtn!)
}
@objc private func backBtnDidClick(){
_ = navigationController?.popViewController(animated: true)
}
@objc private func productBtnDidClick(btn: UIButton){
btn.isSelected = true
peopleBtn?.isSelected = false
bgView?.insertSubview(focusProductView, at: (bgView?.subviews.count)!)
}
@objc private func peopleBtnDidClick(btn: UIButton){
btn.isSelected = true
productBtn?.isSelected = false
bgView?.insertSubview(NoInfoView, at: (bgView?.subviews.count)!)
}
}
| apache-2.0 |
amcnary/cs147_instagator | instagator-prototype/instagator-prototype/PersonTableViewCell.swift | 1 | 481 | //
// PersonTableViewCell.swift
// instagator-prototype
//
// Created by Amanda McNary on 11/18/15.
// Copyright © 2015 ThePenguins. All rights reserved.
//
import Foundation
import UIKit
class PersonTableViewCell: UITableViewCell {
// MARK: - constants
static let reuseIdentifier = "PersonTableViewCell"
// MARK: - interface outlets
@IBOutlet weak var personImageView: UIImageView!
@IBOutlet weak var personNameLabel: UILabel!
} | apache-2.0 |
jeremiahyan/ResearchKit | samples/ORKCatalog/ORKCatalog/AppDelegate.swift | 2 | 1882 | /*
Copyright (c) 2015, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
return true
}
}
| bsd-3-clause |
firebase/firebase-ios-sdk | Example/tvOSSample/tvOSSample/EmailLoginViewController.swift | 2 | 3029 | // Copyright 2017 Google
//
// 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 FirebaseAuth
protocol EmailLoginDelegate {
func emailLogin(_ controller: EmailLoginViewController, signedInAs user: User)
func emailLogin(_ controller: EmailLoginViewController, failedWithError error: Error)
}
class EmailLoginViewController: UIViewController {
// MARK: - Public Properties
var delegate: EmailLoginDelegate?
// MARK: - User Interface
@IBOutlet private var emailAddress: UITextField!
@IBOutlet private var password: UITextField!
// MARK: - User Actions
@IBAction func logInButtonHit(_ sender: UIButton) {
guard let (email, password) = validatedInputs() else { return }
Auth.auth().signIn(withEmail: email, password: password) { [unowned self] result, error in
guard let result = result else {
print("Error signing in: \(error!)")
self.delegate?.emailLogin(self, failedWithError: error!)
return
}
print("Signed in as user: \(result.user.uid)")
self.delegate?.emailLogin(self, signedInAs: result.user)
}
}
@IBAction func signUpButtonHit(_ sender: UIButton) {
guard let (email, password) = validatedInputs() else { return }
Auth.auth().createUser(withEmail: email, password: password) { [unowned self] result, error in
guard let result = result else {
print("Error signing up: \(error!)")
self.delegate?.emailLogin(self, failedWithError: error!)
return
}
print("Created new user: \(result.user.uid)!")
self.delegate?.emailLogin(self, signedInAs: result.user)
}
}
// MARK: - View Controller Lifecycle
override func viewDidLoad() {}
// MARK: - Helper Methods
/// Validate the inputs for user email and password, returning the username and password if valid,
/// otherwise nil.
private func validatedInputs() -> (email: String, password: String)? {
guard let userEmail = emailAddress.text, userEmail.count >= 6 else {
presentError(with: "Email address isn't long enough.")
return nil
}
guard let userPassword = password.text, userPassword.count >= 6 else {
presentError(with: "Password is not long enough!")
return nil
}
return (userEmail, userPassword)
}
func presentError(with text: String) {
let alert = UIAlertController(title: "Error", message: text, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .default))
present(alert, animated: true)
}
}
| apache-2.0 |
mozilla-mobile/firefox-ios | CredentialProvider/Cells/NoSearchResultCell.swift | 2 | 1712 | // 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 NoSearchResultCell: UITableViewCell {
static let identifier = "noSearchResultCell"
lazy private var titleLabel: UILabel = .build { label in
label.textColor = UIColor.CredentialProvider.titleColor
label.text = .LoginsListNoMatchingResultTitle
label.font = UIFont.systemFont(ofSize: 15)
}
lazy private var descriptionLabel: UILabel = .build { label in
label.text = .LoginsListNoMatchingResultSubtitle
label.textColor = .systemGray
label.font = UIFont.systemFont(ofSize: 13)
label.textAlignment = .center
label.numberOfLines = 0
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
backgroundColor = UIColor.CredentialProvider.tableViewBackgroundColor
contentView.addSubviews(titleLabel, descriptionLabel)
NSLayoutConstraint.activate([
titleLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 55),
descriptionLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
descriptionLabel.topAnchor.constraint(equalTo: titleLabel.layoutMarginsGuide.bottomAnchor, constant: 15),
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mpl-2.0 |
klundberg/swift-corelibs-foundation | TestFoundation/TestNSURLResponse.swift | 1 | 15023 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
class TestNSURLResponse : XCTestCase {
static var allTests: [(String, (TestNSURLResponse) -> () throws -> Void)] {
return [
("test_URL", test_URL),
("test_MIMEType_1", test_MIMEType_1),
("test_MIMEType_2", test_MIMEType_2),
("test_ExpectedContentLength", test_ExpectedContentLength),
("test_TextEncodingName", test_TextEncodingName),
("test_suggestedFilename", test_suggestedFilename),
("test_suggestedFilename_2", test_suggestedFilename_2),
("test_suggestedFilename_3", test_suggestedFilename_3),
("test_copywithzone", test_copyWithZone),
]
}
func test_URL() {
let url = URL(string: "a/test/path")!
let res = URLResponse(url: url, mimeType: "txt", expectedContentLength: 0, textEncodingName: nil)
XCTAssertEqual(res.url, url, "should be the expected url")
}
func test_MIMEType_1() {
let mimetype = "text/plain"
let res = URLResponse(url: URL(string: "test")!, mimeType: mimetype, expectedContentLength: 0, textEncodingName: nil)
XCTAssertEqual(res.mimeType, mimetype, "should be the passed in mimetype")
}
func test_MIMEType_2() {
let mimetype = "APPlication/wordperFECT"
let res = URLResponse(url: URL(string: "test")!, mimeType: mimetype, expectedContentLength: 0, textEncodingName: nil)
XCTAssertEqual(res.mimeType, mimetype, "should be the other mimetype")
}
func test_ExpectedContentLength() {
let zeroContentLength = 0
let positiveContentLength = 100
let url = URL(string: "test")!
let res1 = URLResponse(url: url, mimeType: "text/plain", expectedContentLength: zeroContentLength, textEncodingName: nil)
XCTAssertEqual(res1.expectedContentLength, Int64(zeroContentLength), "should be Int65 of the zero length")
let res2 = URLResponse(url: url, mimeType: "text/plain", expectedContentLength: positiveContentLength, textEncodingName: nil)
XCTAssertEqual(res2.expectedContentLength, Int64(positiveContentLength), "should be Int64 of the positive content length")
}
func test_TextEncodingName() {
let encoding = "utf8"
let url = URL(string: "test")!
let res1 = URLResponse(url: url, mimeType: nil, expectedContentLength: 0, textEncodingName: encoding)
XCTAssertEqual(res1.textEncodingName, encoding, "should be the utf8 encoding")
let res2 = URLResponse(url: url, mimeType: nil, expectedContentLength: 0, textEncodingName: nil)
XCTAssertNil(res2.textEncodingName)
}
func test_suggestedFilename() {
let url = URL(string: "a/test/name.extension")!
let res = URLResponse(url: url, mimeType: "txt", expectedContentLength: 0, textEncodingName: nil)
XCTAssertEqual(res.suggestedFilename, "name.extension")
}
func test_suggestedFilename_2() {
let url = URL(string: "a/test/name.extension?foo=bar")!
let res = URLResponse(url: url, mimeType: "txt", expectedContentLength: 0, textEncodingName: nil)
XCTAssertEqual(res.suggestedFilename, "name.extension")
}
func test_suggestedFilename_3() {
let url = URL(string: "a://bar")!
let res = URLResponse(url: url, mimeType: "txt", expectedContentLength: 0, textEncodingName: nil)
XCTAssertEqual(res.suggestedFilename, "Unknown")
}
func test_copyWithZone() {
let url = URL(string: "a/test/path")!
let res = URLResponse(url: url, mimeType: "txt", expectedContentLength: 0, textEncodingName: nil)
XCTAssertTrue(res.isEqual(res.copy()))
}
}
class TestNSHTTPURLResponse : XCTestCase {
static var allTests: [(String, (TestNSHTTPURLResponse) -> () throws -> Void)] {
return [
("test_URL_and_status_1", test_URL_and_status_1),
("test_URL_and_status_2", test_URL_and_status_2),
("test_headerFields_1", test_headerFields_1),
("test_headerFields_2", test_headerFields_2),
("test_headerFields_3", test_headerFields_3),
("test_contentLength_available_1", test_contentLength_available_1),
("test_contentLength_available_2", test_contentLength_available_2),
("test_contentLength_available_3", test_contentLength_available_3),
("test_contentLength_available_4", test_contentLength_available_4),
("test_contentLength_notAvailable", test_contentLength_notAvailable),
("test_contentLength_withTransferEncoding", test_contentLength_withTransferEncoding),
("test_contentLength_withContentEncoding", test_contentLength_withContentEncoding),
("test_contentLength_withContentEncodingAndTransferEncoding", test_contentLength_withContentEncodingAndTransferEncoding),
("test_contentLength_withContentEncodingAndTransferEncoding_2", test_contentLength_withContentEncodingAndTransferEncoding_2),
("test_suggestedFilename_notAvailable_1", test_suggestedFilename_notAvailable_1),
("test_suggestedFilename_notAvailable_2", test_suggestedFilename_notAvailable_2),
("test_suggestedFilename_1", test_suggestedFilename_1),
("test_suggestedFilename_2", test_suggestedFilename_2),
("test_suggestedFilename_3", test_suggestedFilename_3),
("test_suggestedFilename_4", test_suggestedFilename_4),
("test_suggestedFilename_removeSlashes_1", test_suggestedFilename_removeSlashes_1),
("test_suggestedFilename_removeSlashes_2", test_suggestedFilename_removeSlashes_2),
("test_MIMETypeAndCharacterEncoding_1", test_MIMETypeAndCharacterEncoding_1),
("test_MIMETypeAndCharacterEncoding_2", test_MIMETypeAndCharacterEncoding_2),
("test_MIMETypeAndCharacterEncoding_3", test_MIMETypeAndCharacterEncoding_3),
]
}
let url = URL(string: "https://www.swift.org")!
func test_URL_and_status_1() {
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: ["Content-Length": "5299"])
XCTAssertEqual(sut?.url, url)
XCTAssertEqual(sut?.statusCode, 200)
}
func test_URL_and_status_2() {
let url = URL(string: "http://www.apple.com")!
let sut = NSHTTPURLResponse(url: url, statusCode: 302, httpVersion: "HTTP/1.1", headerFields: ["Content-Length": "5299"])
XCTAssertEqual(sut?.url, url)
XCTAssertEqual(sut?.statusCode, 302)
}
func test_headerFields_1() {
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: nil)
XCTAssertEqual(sut?.allHeaderFields.count, 0)
}
func test_headerFields_2() {
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: [:])
XCTAssertEqual(sut?.allHeaderFields.count, 0)
}
func test_headerFields_3() {
let f = ["A": "1", "B": "2"]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.allHeaderFields.count, 2)
XCTAssertEqual(sut?.allHeaderFields["A"], "1")
XCTAssertEqual(sut?.allHeaderFields["B"], "2")
}
// Note that the message content length is different from the message
// transfer length.
// The transfer length can only be derived when the Transfer-Encoding is identity (default).
// For compressed content (Content-Encoding other than identity), there is not way to derive the
// content length from the transfer length.
//
// C.f. <https://tools.ietf.org/html/rfc2616#section-4.4>
func test_contentLength_available_1() {
let f = ["Content-Length": "997"]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.expectedContentLength, 997)
}
func test_contentLength_available_2() {
let f = ["Content-Length": "997", "Transfer-Encoding": "identity"]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.expectedContentLength, 997)
}
func test_contentLength_available_3() {
let f = ["Content-Length": "997", "Content-Encoding": "identity"]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.expectedContentLength, 997)
}
func test_contentLength_available_4() {
let f = ["Content-Length": "997", "Content-Encoding": "identity", "Transfer-Encoding": "identity"]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.expectedContentLength, 997)
}
func test_contentLength_notAvailable() {
let f = ["Server": "Apache"]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.expectedContentLength, -1)
}
func test_contentLength_withTransferEncoding() {
let f = ["Content-Length": "997", "Transfer-Encoding": "chunked"]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.expectedContentLength, 997)
}
func test_contentLength_withContentEncoding() {
let f = ["Content-Length": "997", "Content-Encoding": "deflate"]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.expectedContentLength, 997)
}
func test_contentLength_withContentEncodingAndTransferEncoding() {
let f = ["Content-Length": "997", "Content-Encoding": "deflate", "Transfer-Encoding": "identity"]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.expectedContentLength, 997)
}
func test_contentLength_withContentEncodingAndTransferEncoding_2() {
let f = ["Content-Length": "997", "Content-Encoding": "identity", "Transfer-Encoding": "chunked"]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.expectedContentLength, 997)
}
// The `suggestedFilename` can be derived from the "Content-Disposition"
// header as defined in RFC 1806 and more recently RFC 2183
// https://tools.ietf.org/html/rfc1806
// https://tools.ietf.org/html/rfc2183
//
// Typical use looks like this:
// Content-Disposition: attachment; filename="fname.ext"
//
// As noted in https://tools.ietf.org/html/rfc2616#section-19.5.1 the
// receiving user agent SHOULD NOT respect any directory path information
// present in the filename-parm parameter.
//
func test_suggestedFilename_notAvailable_1() {
let f: [String: String] = [:]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.suggestedFilename, "Unknown")
}
func test_suggestedFilename_notAvailable_2() {
let f = ["Content-Disposition": "inline"]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.suggestedFilename, "Unknown")
}
func test_suggestedFilename_1() {
let f = ["Content-Disposition": "attachment; filename=\"fname.ext\""]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.suggestedFilename, "fname.ext")
}
func test_suggestedFilename_2() {
let f = ["Content-Disposition": "attachment; filename=genome.jpeg; modification-date=\"Wed, 12 Feb 1997 16:29:51 -0500\";"]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.suggestedFilename, "genome.jpeg")
}
func test_suggestedFilename_3() {
let f = ["Content-Disposition": "attachment; filename=\";.ext\""]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.suggestedFilename, ";.ext")
}
func test_suggestedFilename_4() {
let f = ["Content-Disposition": "attachment; aa=bb\\; filename=\"wrong.ext\"; filename=\"fname.ext\"; cc=dd"]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.suggestedFilename, "fname.ext")
}
func test_suggestedFilename_removeSlashes_1() {
let f = ["Content-Disposition": "attachment; filename=\"/a/b/name\""]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.suggestedFilename, "_a_b_name")
}
func test_suggestedFilename_removeSlashes_2() {
let f = ["Content-Disposition": "attachment; filename=\"a/../b/name\""]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.suggestedFilename, "a_.._b_name")
}
// The MIME type / character encoding
func test_MIMETypeAndCharacterEncoding_1() {
let f = ["Server": "Apache"]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertNil(sut?.mimeType)
XCTAssertNil(sut?.textEncodingName)
}
func test_MIMETypeAndCharacterEncoding_2() {
let f = ["Content-Type": "text/html"]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.mimeType, "text/html")
XCTAssertNil(sut?.textEncodingName)
}
func test_MIMETypeAndCharacterEncoding_3() {
let f = ["Content-Type": "text/HTML; charset=ISO-8859-4"]
let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)
XCTAssertEqual(sut?.mimeType, "text/html")
XCTAssertEqual(sut?.textEncodingName, "iso-8859-4")
}
}
| apache-2.0 |
KrishMunot/swift | stdlib/public/core/Zip.swift | 4 | 3519 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A sequence of pairs built out of two underlying sequences, where
/// the elements of the `i`th pair are the `i`th elements of each
/// underlying sequence.
public func zip<Sequence1 : Sequence, Sequence2 : Sequence>(
_ sequence1: Sequence1, _ sequence2: Sequence2
) -> Zip2Sequence<Sequence1, Sequence2> {
return Zip2Sequence(_sequence1: sequence1, _sequence2: sequence2)
}
/// An iterator for `Zip2Sequence`.
public struct Zip2Iterator<
Iterator1 : IteratorProtocol, Iterator2 : IteratorProtocol
> : IteratorProtocol {
/// The type of element returned by `next()`.
public typealias Element = (Iterator1.Element, Iterator2.Element)
/// Construct around a pair of underlying iterators.
internal init(_ iterator1: Iterator1, _ iterator2: Iterator2) {
(_baseStream1, _baseStream2) = (iterator1, iterator2)
}
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// - Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made, and no preceding call to `self.next()`
/// has returned `nil`.
public mutating func next() -> Element? {
// The next() function needs to track if it has reached the end. If we
// didn't, and the first sequence is longer than the second, then when we
// have already exhausted the second sequence, on every subsequent call to
// next() we would consume and discard one additional element from the
// first sequence, even though next() had already returned nil.
if _reachedEnd {
return nil
}
guard let element1 = _baseStream1.next(), element2 = _baseStream2.next() else {
_reachedEnd = true
return nil
}
return (element1, element2)
}
internal var _baseStream1: Iterator1
internal var _baseStream2: Iterator2
internal var _reachedEnd: Bool = false
}
/// A sequence of pairs built out of two underlying sequences, where
/// the elements of the `i`th pair are the `i`th elements of each
/// underlying sequence.
public struct Zip2Sequence<Sequence1 : Sequence, Sequence2 : Sequence>
: Sequence {
public typealias Stream1 = Sequence1.Iterator
public typealias Stream2 = Sequence2.Iterator
/// A type whose instances can produce the elements of this
/// sequence, in order.
public typealias Iterator = Zip2Iterator<Stream1, Stream2>
@available(*, unavailable, renamed: "Iterator")
public typealias Generator = Iterator
/// Construct an instance that makes pairs of elements from `sequence1` and
/// `sequence2`.
public // @testable
init(_sequence1 sequence1: Sequence1, _sequence2 sequence2: Sequence2) {
(_sequence1, _sequence2) = (sequence1, sequence2)
}
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
public func makeIterator() -> Iterator {
return Iterator(
_sequence1.makeIterator(),
_sequence2.makeIterator())
}
internal let _sequence1: Sequence1
internal let _sequence2: Sequence2
}
| apache-2.0 |
ericvergnaud/antlr4 | runtime/Swift/Sources/Antlr4/atn/LexerTypeAction.swift | 7 | 1905 | ///
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
///
///
/// Implements the `type` lexer action by calling _org.antlr.v4.runtime.Lexer#setType_
/// with the assigned type.
///
/// - Sam Harwell
/// - 4.2
///
public class LexerTypeAction: LexerAction, CustomStringConvertible {
fileprivate let type: Int
///
/// Constructs a new `type` action with the specified token type value.
/// - parameter type: The type to assign to the token using _org.antlr.v4.runtime.Lexer#setType_.
///
public init(_ type: Int) {
self.type = type
}
///
/// Gets the type to assign to a token created by the lexer.
/// - returns: The type to assign to a token created by the lexer.
///
public func getType() -> Int {
return type
}
///
///
/// - returns: This method returns _org.antlr.v4.runtime.atn.LexerActionType#TYPE_.
///
public override func getActionType() -> LexerActionType {
return LexerActionType.type
}
///
///
/// - returns: This method returns `false`.
///
override
public func isPositionDependent() -> Bool {
return false
}
///
///
///
/// This action is implemented by calling _org.antlr.v4.runtime.Lexer#setType_ with the
/// value provided by _#getType_.
///
public override func execute(_ lexer: Lexer) {
lexer.setType(type)
}
public override func hash(into hasher: inout Hasher) {
hasher.combine(type)
}
public var description: String {
return "type(\(type))"
}
}
public func ==(lhs: LexerTypeAction, rhs: LexerTypeAction) -> Bool {
if lhs === rhs {
return true
}
return lhs.type == rhs.type
}
| bsd-3-clause |
ioscreator/ioscreator | IOSScaleImageTutorial/IOSScaleImageTutorial/AppDelegate.swift | 1 | 2195 | //
// AppDelegate.swift
// IOSScaleImageTutorial
//
// Created by Arthur Knopper on 07/02/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: 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:.
}
}
| mit |
chicio/RangeUISlider | Source/UI/RangeSlider.swift | 1 | 2396 | //
// RangeSlider.swift
// RangeUISlider
//
// Created by Fabrizio Duroni on 06.01.21.
// 2021 Fabrizio Duroni.
//
#if canImport(SwiftUI)
import SwiftUI
/**
RangeUISlider SwiftUI implementation using UIViewRepresentable. It exposes all the RangeUIslider properties.
*/
@available(iOS 14.0, *)
public struct RangeSlider: UIViewRepresentable {
/// Min value selected binding value.
/// In this property the min value selected will be exposed. It will be updated during dragging.
@Binding public var minValueSelected: CGFloat
/// Max value selected binding value.
/// In this property the max value selected will be exposed. It will be updated during dragging.
@Binding public var maxValueSelected: CGFloat
let settings: RangeSliderSettings
private let rangeUISliderCreator: RangeUISliderCreator
/**
Init RangeSlider.
- parameter minValueSelected: the binding value to get the min value selected.
- parameter maxValueSelected: the binding value to get the max value selected.
*/
public init(minValueSelected: Binding<CGFloat>, maxValueSelected: Binding<CGFloat>) {
self._minValueSelected = minValueSelected
self._maxValueSelected = maxValueSelected
self.settings = RangeSliderSettings()
self.rangeUISliderCreator = RangeUISliderCreator()
}
// MARK: lifecycle
/**
Implementation of `UIViewRepresentable.makeUIView(context: Context)` method.
- parameter content: the SwiftUI context.
- returns: an instance of RangeUISlider
*/
public func makeUIView(context: Context) -> RangeUISlider {
let rangeSlider = rangeUISliderCreator.createFrom(settings: settings)
rangeSlider.delegate = context.coordinator
return rangeSlider
}
/**
Implementation of `UIViewRepresentable.updateUIView(_ uiView: RangeUISlider, context: Context)` method.
- parameter uiView: the `RangeUISlider` instance.
- parameter content: the SwiftUI context.
*/
public func updateUIView(_ uiView: RangeUISlider, context: Context) { }
/**
Implementation of `UIViewRepresentable.makeCoordinator()` method.
- returns: an instance of `RangeSliderCoordinator`
*/
public func makeCoordinator() -> RangeSliderCoordinator {
return RangeSliderCoordinator(rangeSlider: self)
}
}
#endif
| mit |
blue42u/swift-t | stc/tests/513-strings-14.swift | 4 | 1219 |
import assert;
import string;
main {
string x = "hello world\n";
string y = "banana nana\n";
trace(x);
assertEqual(x, "hello world\n","");
// Success cases
string s = replace("hello world", "world", "folks", 0);
assertEqual("hello folks", s, "s");
string s1 = replace("banana", "an", "ah", 0);
assertEqual("bahana", s1, "s1");
string s1a = replaceAll("banana", "an", "..", 0, 4);
assertEqual(s1a, "b..ana", "s1a");
string s2 = replace(y, "ana", "i", 0);
assertEqual("bina nana\n", s2, "s2");
string s3 = replaceAll("banana", "an", "ah");
assertEqual("bahaha", s3, "s3");
string s4 = replace_all(y, "ana", "i", 0);
assertEqual("bina ni\n", s4, "s4");
string s4a = replace_all(y, "ana", "i", 2);
assertEqual("bani ni\n", s4a, "s4a");
// Failure cases
string s5 = replace("hello world", "", "folks", 0);
assertEqual("hello world", s5, "s5");
string s6 = replace("banana", "an", "ah", 5);
assertEqual("banana", s6, "s6");
string s7 = replace("banana", "", "ah", 5);
assertEqual("banana", s7, "s7");
string s8 = replace_all("banana", "an", "anana", 0);
assertEqual("bananaananaa", s8, "s8");
}
| apache-2.0 |
manGoweb/S3 | Sources/S3Signer/Exports.swift | 1 | 72 | @_exported import Foundation
@_exported import enum NIOHTTP1.HTTPMethod
| mit |
sealgair/UniversalChords | UniversalChords/Finger.swift | 1 | 347 | //
// Finger.swift
// UniversalChords
//
// Created by Chase Caster on 5/24/15.
// Copyright (c) 2015 chasecaster. All rights reserved.
//
import Foundation
import MusicKit
struct Finger {
let position: Int
let string: Chroma
var note: Chroma {
return self.string + position
}
}
typealias Fingering = Array<Finger> | gpl-3.0 |
codepath-volunteer-app/VolunteerMe | VolunteerMe/Pods/DateToolsSwift/DateToolsSwift/DateTools/Enums.swift | 11 | 2271 | //
// Enums.swift
// DateToolsTests
//
// Created by Matthew York on 8/26/16.
// Copyright © 2016 Matthew York. All rights reserved.
//
// MARK: - Enums
/**
* There may come a need, say when you are making a scheduling app, when
* it might be good to know how two time periods relate to one another.
* Are they the same? Is one inside of another? All these questions may be
* asked using the relationship methods of DTTimePeriod.
*
* Further reading: [GitHub](https://github.com/MatthewYork/DateTools#relationships),
* [CodeProject](http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET)
*/
public enum Relation {
case after
case startTouching
case startInside
case insideStartTouching
case enclosingStartTouching
case enclosing
case enclosingEndTouching
case exactMatch
case inside
case insideEndTouching
case endInside
case endTouching
case before
case none // One or more of the dates does not exist
}
/**
* Whether the time period is Open or Closed
*
* Closed: The boundary moment of time is included in calculations.
*
* Open: The boundary moment of time represents a boundary value which is excluded in regard to calculations.
*/
public enum Interval {
case open
case closed
}
/**
* When a time periods is lengthened or shortened, it does so anchoring one date
* of the time period and then changing the other one. There is also an option to
* anchor the centerpoint of the time period, changing both the start and end dates.
*/
public enum Anchor {
case beginning
case center
case end
}
/**
* When a time periods is lengthened or shortened, it does so anchoring one date
* of the time period and then changing the other one. There is also an option to
* anchor the centerpoint of the time period, changing both the start and end dates.
*/
public enum Component {
case year
case month
case day
case hour
case minute
case second
}
/**
* Time units that include weeks, but not months since their exact size is dependent
* on the date. Used for TimeChunk conversions.
*/
public enum TimeUnits {
case years
case weeks
case days
case hours
case minutes
case seconds
}
| mit |
polydice/ICInputAccessory | ICInputAccessoryUITests/TokenFieldUITests.swift | 1 | 2456 | //
// TokenFieldUITests.swift
// ICInputAccessoryUITests
//
// Created by Ben on 08/03/2016.
// Copyright © 2016 Polydice, Inc.
//
// 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 XCTest
class TokenFieldUITests: XCTestCase {
private lazy var app = XCUIApplication()
override func setUp() {
super.setUp()
continueAfterFailure = false
app.launch()
}
private func typeTexts(in textField: XCUIElement) {
textField.tap()
textField.typeText("Try")
textField.typeText(" ")
textField.typeText("iCook")
textField.typeText(",")
textField.typeText("beta")
textField.typeText(" ")
let deleteKey = app.keys["delete"]
deleteKey.tap()
deleteKey.tap()
textField.typeText("TestFlight")
textField.typeText(",")
app.buttons["Search"].tap()
}
func testTokenField() {
let textField = app.tables.cells.textFields["TokenField"]
typeTexts(in: textField)
}
func testCustomizedTokenField() {
app.tables.staticTexts["CustomizedTokenField"].tap()
let tokenField = app.navigationBars["Example.CustomizedTokenView"].scrollViews.children(matching: .textField).element
typeTexts(in: tokenField)
}
func testStoryboard() {
app.tables.buttons["Storyboard"].tap()
let tokenField = app.tables.cells.textFields["Storyboard TokenField"]
typeTexts(in: tokenField)
app.tables.buttons["Back to Code"].tap()
}
}
| mit |
LamGiauKhongKhoTeam/LGKK | ModulesTests/CryptoSwiftTests/Access.swift | 1 | 7938 | //
// Access.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 06/08/16.
// Copyright © 2016 Marcin Krzyzanowski. All rights reserved.
//
import XCTest
@testable import CryptoSwift
class Access: XCTestCase {
let cipher = try! AES(key: "secret0key000000", iv: "0123456789012345")
let authenticator = HMAC(key: Array<UInt8>(hex: "b1b2b3b3b3b3b3b3b1b2b3b3b3b3b3b3"), variant: .sha1)
func testChecksum() {
let _ = Checksum.crc32([1, 2, 3])
let _ = Checksum.crc16([1, 2, 3])
}
func testRandomIV() {
let _ = AES.randomIV(AES.blockSize)
let _ = ChaCha20.randomIV(ChaCha20.blockSize)
}
func testDigest() {
let _ = Digest.md5([1, 2, 3])
let _ = Digest.sha1([1, 2, 3])
let _ = Digest.sha224([1, 2, 3])
let _ = Digest.sha256([1, 2, 3])
let _ = Digest.sha384([1, 2, 3])
let _ = Digest.sha512([1, 2, 3])
let _ = Digest.sha3([1, 2, 3], variant: .sha224)
let _ = SHA1().calculate(for: [0])
let _ = SHA2(variant: .sha224).calculate(for: [0])
let _ = SHA3(variant: .sha256).calculate(for: [0])
let _ = MD5().calculate(for: [0])
}
func testArrayExtension() {
let array = Array<UInt8>(hex: "b1b2b3b3b3b3b3b3b1b2b3b3b3b3b3b3")
let _ = array.toHexString()
let _ = array.md5()
let _ = array.sha1()
let _ = array.sha256()
let _ = array.sha384()
let _ = array.sha512()
let _ = array.sha2(.sha224)
let _ = array.sha3(.sha224)
let _ = array.crc32()
let _ = array.crc16()
do {
let _ = try array.encrypt(cipher: cipher)
let _ = try array.decrypt(cipher: cipher)
let _ = try array.authenticate(with: authenticator)
} catch {
XCTFail(error.localizedDescription)
}
}
func testCollectionExtension() {
// nothing public
}
func testStringExtension() {
let string = "foofoobarbar"
let _ = string.md5()
let _ = string.sha1()
let _ = string.sha224()
let _ = string.sha256()
let _ = string.sha384()
let _ = string.sha512()
let _ = string.sha3(.sha224)
let _ = string.crc16()
let _ = string.crc32()
do {
let _ = try string.encrypt(cipher: cipher)
let _ = try string.authenticate(with: authenticator)
} catch {
XCTFail(error.localizedDescription)
}
}
func testStringFoundationExtension() {
let string = "aPf/i9th9iX+vf49eR7PYk2q7S5xmm3jkRLejgzHNJs="
do {
let _ = try string.decryptBase64ToString(cipher: cipher)
let _ = try string.decryptBase64(cipher: cipher)
} catch {
XCTFail(error.localizedDescription)
}
}
func testIntExtension() {
// nothing public
}
func testUInt16Extension() {
// nothing public
}
func testUInt32Extension() {
// nothing public
}
func testUInt64Extension() {
// nothing public
}
func testUInt8Extension() {
// nothing public
}
func testDataExtension() {
let data = Data(bytes: [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8])
let _ = data.checksum()
let _ = data.md5()
let _ = data.sha1()
let _ = data.sha224()
let _ = data.sha256()
let _ = data.sha384()
let _ = data.sha512()
let _ = data.sha3(.sha224)
let _ = data.crc16()
let _ = data.crc32()
let _ = data.bytes
let _ = data.toHexString()
do {
let _ = try data.encrypt(cipher: cipher)
let _ = try data.decrypt(cipher: cipher)
let _ = try data.authenticate(with: authenticator)
} catch {
XCTFail(error.localizedDescription)
}
}
func testPadding() {
// PKCS7
let _ = PKCS7().add(to: [1, 2, 3], blockSize: 16)
let _ = PKCS7().remove(from: [1, 2, 3], blockSize: 16)
// NoPadding
let _ = NoPadding().add(to: [1, 2, 3], blockSize: 16)
let _ = NoPadding().remove(from: [1, 2, 3], blockSize: 16)
// ZeroPadding
let _ = ZeroPadding().add(to: [1, 2, 3], blockSize: 16)
let _ = ZeroPadding().remove(from: [1, 2, 3], blockSize: 16)
}
func testPBKDF() {
do {
let _ = PKCS5.PBKDF1.Variant.md5
let _ = try PKCS5.PBKDF1(password: [1, 2, 3, 4, 5, 6, 7], salt: [1, 2, 3, 4, 5, 6, 7, 8]).calculate()
let _ = try PKCS5.PBKDF2(password: [1, 2, 3, 4, 5, 6, 7], salt: [1, 2, 3, 4]).calculate()
} catch {
XCTFail(error.localizedDescription)
}
}
func testAuthenticators() {
do {
let _ = try HMAC(key: Array<UInt8>(hex: "b1b2b3b3b3b3b3b3b1b2b3b3b3b3b3b3"), variant: .sha1).authenticate([1, 2, 3])
let _ = try Poly1305(key: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2]).authenticate([1, 2, 3])
} catch {
XCTFail(error.localizedDescription)
}
}
func testAES() {
do {
let cipher = try AES(key: "secret0key000000", iv: "0123456789012345")
var encryptor = cipher.makeEncryptor()
let _ = try encryptor.update(withBytes: [1, 2, 3])
let _ = try encryptor.finish()
var decryptor = cipher.makeDecryptor()
let _ = try decryptor.update(withBytes: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
let _ = try decryptor.finish()
let enc = try cipher.encrypt([1, 2, 3])
let _ = try cipher.decrypt(enc)
let _ = try AES(key: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6], iv: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6], blockMode: .CBC, padding: NoPadding())
let _ = AES.Variant.aes128
let _ = AES.blockSize
} catch {
XCTFail(error.localizedDescription)
}
}
func testBlowfish() {
do {
let cipher = try Blowfish(key: "secret0key000000", iv: "01234567")
let enc = try cipher.encrypt([1, 2, 3])
let _ = try cipher.decrypt(enc)
let _ = try Blowfish(key: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6], iv: [1, 2, 3, 4, 5, 6, 7, 8], blockMode: .CBC, padding: NoPadding())
let _ = Blowfish.blockSize
} catch {
XCTFail(error.localizedDescription)
}
}
func testRabbit() {
do {
let rabbit = try Rabbit(key: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
let enc = rabbit.encrypt([1, 2, 3])
let _ = rabbit.decrypt(enc)
XCTAssertThrowsError(try Rabbit(key: "123"))
let _ = Rabbit.blockSize
let _ = Rabbit.keySize
let _ = Rabbit.ivSize
} catch {
XCTFail(error.localizedDescription)
}
}
func testChaCha20() {
let key: Array<UInt8> = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
let iv: Array<UInt8> = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
do {
let _ = ChaCha20.blockSize
let chacha20 = try ChaCha20(key: key, iv: iv)
let enc = try chacha20.encrypt([1, 3, 4])
let _ = try chacha20.decrypt(enc)
XCTAssertThrowsError(try ChaCha20(key: "123", iv: "12345678"))
let _ = chacha20.makeEncryptor()
let _ = chacha20.makeDecryptor()
} catch {
XCTFail(error.localizedDescription)
}
}
}
| mit |
playgroundscon/Playgrounds | Playgrounds/Extension/UIView+Utilities.swift | 1 | 489 | //
// UIView+Utilities.swift
// Playgrounds
//
// Created by Andyy Hope on 19/11/16.
// Copyright © 2016 Andyy Hope. All rights reserved.
//
import UIKit
extension UIView {
func circular() {
cornerRadius = bounds.height / 2
clipsToBounds = true
}
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
clipsToBounds = true
}
}
}
| gpl-3.0 |
ahoppen/swift | stdlib/public/core/Sequence.swift | 4 | 46221 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that supplies the values of a sequence one at a time.
///
/// The `IteratorProtocol` protocol is tightly linked with the `Sequence`
/// protocol. Sequences provide access to their elements by creating an
/// iterator, which keeps track of its iteration process and returns one
/// element at a time as it advances through the sequence.
///
/// Whenever you use a `for`-`in` loop with an array, set, or any other
/// collection or sequence, you're using that type's iterator. Swift uses a
/// sequence's or collection's iterator internally to enable the `for`-`in`
/// loop language construct.
///
/// Using a sequence's iterator directly gives you access to the same elements
/// in the same order as iterating over that sequence using a `for`-`in` loop.
/// For example, you might typically use a `for`-`in` loop to print each of
/// the elements in an array.
///
/// let animals = ["Antelope", "Butterfly", "Camel", "Dolphin"]
/// for animal in animals {
/// print(animal)
/// }
/// // Prints "Antelope"
/// // Prints "Butterfly"
/// // Prints "Camel"
/// // Prints "Dolphin"
///
/// Behind the scenes, Swift uses the `animals` array's iterator to loop over
/// the contents of the array.
///
/// var animalIterator = animals.makeIterator()
/// while let animal = animalIterator.next() {
/// print(animal)
/// }
/// // Prints "Antelope"
/// // Prints "Butterfly"
/// // Prints "Camel"
/// // Prints "Dolphin"
///
/// The call to `animals.makeIterator()` returns an instance of the array's
/// iterator. Next, the `while` loop calls the iterator's `next()` method
/// repeatedly, binding each element that is returned to `animal` and exiting
/// when the `next()` method returns `nil`.
///
/// Using Iterators Directly
/// ========================
///
/// You rarely need to use iterators directly, because a `for`-`in` loop is the
/// more idiomatic approach to traversing a sequence in Swift. Some
/// algorithms, however, may call for direct iterator use.
///
/// One example is the `reduce1(_:)` method. Similar to the `reduce(_:_:)`
/// method defined in the standard library, which takes an initial value and a
/// combining closure, `reduce1(_:)` uses the first element of the sequence as
/// the initial value.
///
/// Here's an implementation of the `reduce1(_:)` method. The sequence's
/// iterator is used directly to retrieve the initial value before looping
/// over the rest of the sequence.
///
/// extension Sequence {
/// func reduce1(
/// _ nextPartialResult: (Element, Element) -> Element
/// ) -> Element?
/// {
/// var i = makeIterator()
/// guard var accumulated = i.next() else {
/// return nil
/// }
///
/// while let element = i.next() {
/// accumulated = nextPartialResult(accumulated, element)
/// }
/// return accumulated
/// }
/// }
///
/// The `reduce1(_:)` method makes certain kinds of sequence operations
/// simpler. Here's how to find the longest string in a sequence, using the
/// `animals` array introduced earlier as an example:
///
/// let longestAnimal = animals.reduce1 { current, element in
/// if current.count > element.count {
/// return current
/// } else {
/// return element
/// }
/// }
/// print(longestAnimal)
/// // Prints Optional("Butterfly")
///
/// Using Multiple Iterators
/// ========================
///
/// Whenever you use multiple iterators (or `for`-`in` loops) over a single
/// sequence, be sure you know that the specific sequence supports repeated
/// iteration, either because you know its concrete type or because the
/// sequence is also constrained to the `Collection` protocol.
///
/// Obtain each separate iterator from separate calls to the sequence's
/// `makeIterator()` method rather than by copying. Copying an iterator is
/// safe, but advancing one copy of an iterator by calling its `next()` method
/// may invalidate other copies of that iterator. `for`-`in` loops are safe in
/// this regard.
///
/// Adding IteratorProtocol Conformance to Your Type
/// ================================================
///
/// Implementing an iterator that conforms to `IteratorProtocol` is simple.
/// Declare a `next()` method that advances one step in the related sequence
/// and returns the current element. When the sequence has been exhausted, the
/// `next()` method returns `nil`.
///
/// For example, consider a custom `Countdown` sequence. You can initialize the
/// `Countdown` sequence with a starting integer and then iterate over the
/// count down to zero. The `Countdown` structure's definition is short: It
/// contains only the starting count and the `makeIterator()` method required
/// by the `Sequence` protocol.
///
/// struct Countdown: Sequence {
/// let start: Int
///
/// func makeIterator() -> CountdownIterator {
/// return CountdownIterator(self)
/// }
/// }
///
/// The `makeIterator()` method returns another custom type, an iterator named
/// `CountdownIterator`. The `CountdownIterator` type keeps track of both the
/// `Countdown` sequence that it's iterating and the number of times it has
/// returned a value.
///
/// struct CountdownIterator: IteratorProtocol {
/// let countdown: Countdown
/// var times = 0
///
/// init(_ countdown: Countdown) {
/// self.countdown = countdown
/// }
///
/// mutating func next() -> Int? {
/// let nextNumber = countdown.start - times
/// guard nextNumber > 0
/// else { return nil }
///
/// times += 1
/// return nextNumber
/// }
/// }
///
/// Each time the `next()` method is called on a `CountdownIterator` instance,
/// it calculates the new next value, checks to see whether it has reached
/// zero, and then returns either the number, or `nil` if the iterator is
/// finished returning elements of the sequence.
///
/// Creating and iterating over a `Countdown` sequence uses a
/// `CountdownIterator` to handle the iteration.
///
/// let threeTwoOne = Countdown(start: 3)
/// for count in threeTwoOne {
/// print("\(count)...")
/// }
/// // Prints "3..."
/// // Prints "2..."
/// // Prints "1..."
public protocol IteratorProtocol {
/// The type of element traversed by the iterator.
associatedtype Element
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Repeatedly calling this method returns, in order, all the elements of the
/// underlying sequence. As soon as the sequence has run out of elements, all
/// subsequent calls return `nil`.
///
/// You must not call this method if any other copy of this iterator has been
/// advanced with a call to its `next()` method.
///
/// The following example shows how an iterator can be used explicitly to
/// emulate a `for`-`in` loop. First, retrieve a sequence's iterator, and
/// then call the iterator's `next()` method until it returns `nil`.
///
/// let numbers = [2, 3, 5, 7]
/// var numbersIterator = numbers.makeIterator()
///
/// while let num = numbersIterator.next() {
/// print(num)
/// }
/// // Prints "2"
/// // Prints "3"
/// // Prints "5"
/// // Prints "7"
///
/// - Returns: The next element in the underlying sequence, if a next element
/// exists; otherwise, `nil`.
mutating func next() -> Element?
}
/// A type that provides sequential, iterated access to its elements.
///
/// A sequence is a list of values that you can step through one at a time. The
/// most common way to iterate over the elements of a sequence is to use a
/// `for`-`in` loop:
///
/// let oneTwoThree = 1...3
/// for number in oneTwoThree {
/// print(number)
/// }
/// // Prints "1"
/// // Prints "2"
/// // Prints "3"
///
/// While seemingly simple, this capability gives you access to a large number
/// of operations that you can perform on any sequence. As an example, to
/// check whether a sequence includes a particular value, you can test each
/// value sequentially until you've found a match or reached the end of the
/// sequence. This example checks to see whether a particular insect is in an
/// array.
///
/// let bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
/// var hasMosquito = false
/// for bug in bugs {
/// if bug == "Mosquito" {
/// hasMosquito = true
/// break
/// }
/// }
/// print("'bugs' has a mosquito: \(hasMosquito)")
/// // Prints "'bugs' has a mosquito: false"
///
/// The `Sequence` protocol provides default implementations for many common
/// operations that depend on sequential access to a sequence's values. For
/// clearer, more concise code, the example above could use the array's
/// `contains(_:)` method, which every sequence inherits from `Sequence`,
/// instead of iterating manually:
///
/// if bugs.contains("Mosquito") {
/// print("Break out the bug spray.")
/// } else {
/// print("Whew, no mosquitos!")
/// }
/// // Prints "Whew, no mosquitos!"
///
/// Repeated Access
/// ===============
///
/// The `Sequence` protocol makes no requirement on conforming types regarding
/// whether they will be destructively consumed by iteration. As a
/// consequence, don't assume that multiple `for`-`in` loops on a sequence
/// will either resume iteration or restart from the beginning:
///
/// for element in sequence {
/// if ... some condition { break }
/// }
///
/// for element in sequence {
/// // No defined behavior
/// }
///
/// In this case, you cannot assume either that a sequence will be consumable
/// and will resume iteration, or that a sequence is a collection and will
/// restart iteration from the first element. A conforming sequence that is
/// not a collection is allowed to produce an arbitrary sequence of elements
/// in the second `for`-`in` loop.
///
/// To establish that a type you've created supports nondestructive iteration,
/// add conformance to the `Collection` protocol.
///
/// Conforming to the Sequence Protocol
/// ===================================
///
/// Making your own custom types conform to `Sequence` enables many useful
/// operations, like `for`-`in` looping and the `contains` method, without
/// much effort. To add `Sequence` conformance to your own custom type, add a
/// `makeIterator()` method that returns an iterator.
///
/// Alternatively, if your type can act as its own iterator, implementing the
/// requirements of the `IteratorProtocol` protocol and declaring conformance
/// to both `Sequence` and `IteratorProtocol` are sufficient.
///
/// Here's a definition of a `Countdown` sequence that serves as its own
/// iterator. The `makeIterator()` method is provided as a default
/// implementation.
///
/// struct Countdown: Sequence, IteratorProtocol {
/// var count: Int
///
/// mutating func next() -> Int? {
/// if count == 0 {
/// return nil
/// } else {
/// defer { count -= 1 }
/// return count
/// }
/// }
/// }
///
/// let threeToGo = Countdown(count: 3)
/// for i in threeToGo {
/// print(i)
/// }
/// // Prints "3"
/// // Prints "2"
/// // Prints "1"
///
/// Expected Performance
/// ====================
///
/// A sequence should provide its iterator in O(1). The `Sequence` protocol
/// makes no other requirements about element access, so routines that
/// traverse a sequence should be considered O(*n*) unless documented
/// otherwise.
public protocol Sequence {
/// A type representing the sequence's elements.
associatedtype Element
/// A type that provides the sequence's iteration interface and
/// encapsulates its iteration state.
associatedtype Iterator: IteratorProtocol where Iterator.Element == Element
// FIXME: <rdar://problem/34142121>
// This typealias should be removed as it predates the source compatibility
// guarantees of Swift 3, but it cannot due to a bug.
@available(*, unavailable, renamed: "Iterator")
typealias Generator = Iterator
/// A type that represents a subsequence of some of the sequence's elements.
// associatedtype SubSequence: Sequence = AnySequence<Element>
// where Element == SubSequence.Element,
// SubSequence.SubSequence == SubSequence
// typealias SubSequence = AnySequence<Element>
/// Returns an iterator over the elements of this sequence.
__consuming func makeIterator() -> Iterator
/// A value less than or equal to the number of elements in the sequence,
/// calculated nondestructively.
///
/// The default implementation returns 0. If you provide your own
/// implementation, make sure to compute the value nondestructively.
///
/// - Complexity: O(1), except if the sequence also conforms to `Collection`.
/// In this case, see the documentation of `Collection.underestimatedCount`.
var underestimatedCount: Int { get }
func _customContainsEquatableElement(
_ element: Element
) -> Bool?
/// Create a native array buffer containing the elements of `self`,
/// in the same order.
__consuming func _copyToContiguousArray() -> ContiguousArray<Element>
/// Copy `self` into an unsafe buffer, initializing its memory.
///
/// The default implementation simply iterates over the elements of the
/// sequence, initializing the buffer one item at a time.
///
/// For sequences whose elements are stored in contiguous chunks of memory,
/// it may be more efficient to copy them in bulk, using the
/// `UnsafeMutablePointer.initialize(from:count:)` method.
///
/// - Parameter ptr: An unsafe buffer addressing uninitialized memory. The
/// buffer must be of sufficient size to accommodate
/// `source.underestimatedCount` elements. (Some implementations trap
/// if given a buffer that's smaller than this.)
///
/// - Returns: `(it, c)`, where `c` is the number of elements copied into the
/// buffer, and `it` is a partially consumed iterator that can be used to
/// retrieve elements that did not fit into the buffer (if any). (This can
/// only happen if `underestimatedCount` turned out to be an actual
/// underestimate, and the buffer did not contain enough space to hold the
/// entire sequence.)
///
/// On return, the memory region in `buffer[0 ..< c]` is initialized to
/// the first `c` elements in the sequence.
__consuming func _copyContents(
initializing ptr: UnsafeMutableBufferPointer<Element>
) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index)
/// Executes a closure on the sequence’s contiguous storage.
///
/// This method calls `body(buffer)`, where `buffer` is a pointer to the
/// collection’s contiguous storage. If the contiguous storage doesn't exist,
/// the collection creates it. If the collection doesn’t support an internal
/// representation in a form of contiguous storage, the method doesn’t call
/// `body` --- it immediately returns `nil`.
///
/// The optimizer can often eliminate bounds- and uniqueness-checking
/// within an algorithm. When that fails, however, invoking the same
/// algorithm on the `buffer` argument may let you trade safety for speed.
///
/// Successive calls to this method may provide a different pointer on each
/// call. Don't store `buffer` outside of this method.
///
/// A `Collection` that provides its own implementation of this method
/// must provide contiguous storage to its elements in the same order
/// as they appear in the collection. This guarantees that it's possible to
/// generate contiguous mutable storage to any of its subsequences by slicing
/// `buffer` with a range formed from the distances to the subsequence's
/// `startIndex` and `endIndex`, respectively.
///
/// - Parameters:
/// - body: A closure that receives an `UnsafeBufferPointer` to the
/// sequence's contiguous storage.
/// - Returns: The value returned from `body`, unless the sequence doesn't
/// support contiguous storage, in which case the method ignores `body` and
/// returns `nil`.
func withContiguousStorageIfAvailable<R>(
_ body: (_ buffer: UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R?
}
// Provides a default associated type witness for Iterator when the
// Self type is both a Sequence and an Iterator.
extension Sequence where Self: IteratorProtocol {
// @_implements(Sequence, Iterator)
public typealias _Default_Iterator = Self
}
/// A default makeIterator() function for `IteratorProtocol` instances that
/// are declared to conform to `Sequence`
extension Sequence where Self.Iterator == Self {
/// Returns an iterator over the elements of this sequence.
@inlinable
public __consuming func makeIterator() -> Self {
return self
}
}
/// A sequence that lazily consumes and drops `n` elements from an underlying
/// `Base` iterator before possibly returning the first available element.
///
/// The underlying iterator's sequence may be infinite.
@frozen
public struct DropFirstSequence<Base: Sequence> {
@usableFromInline
internal let _base: Base
@usableFromInline
internal let _limit: Int
@inlinable
public init(_ base: Base, dropping limit: Int) {
_precondition(limit >= 0,
"Can't drop a negative number of elements from a sequence")
_base = base
_limit = limit
}
}
extension DropFirstSequence: Sequence {
public typealias Element = Base.Element
public typealias Iterator = Base.Iterator
public typealias SubSequence = AnySequence<Element>
@inlinable
public __consuming func makeIterator() -> Iterator {
var it = _base.makeIterator()
var dropped = 0
while dropped < _limit, it.next() != nil { dropped &+= 1 }
return it
}
@inlinable
public __consuming func dropFirst(_ k: Int) -> DropFirstSequence<Base> {
// If this is already a _DropFirstSequence, we need to fold in
// the current drop count and drop limit so no data is lost.
//
// i.e. [1,2,3,4].dropFirst(1).dropFirst(1) should be equivalent to
// [1,2,3,4].dropFirst(2).
return DropFirstSequence(_base, dropping: _limit + k)
}
}
/// A sequence that only consumes up to `n` elements from an underlying
/// `Base` iterator.
///
/// The underlying iterator's sequence may be infinite.
@frozen
public struct PrefixSequence<Base: Sequence> {
@usableFromInline
internal var _base: Base
@usableFromInline
internal let _maxLength: Int
@inlinable
public init(_ base: Base, maxLength: Int) {
_precondition(maxLength >= 0, "Can't take a prefix of negative length")
_base = base
_maxLength = maxLength
}
}
extension PrefixSequence {
@frozen
public struct Iterator {
@usableFromInline
internal var _base: Base.Iterator
@usableFromInline
internal var _remaining: Int
@inlinable
internal init(_ base: Base.Iterator, maxLength: Int) {
_base = base
_remaining = maxLength
}
}
}
extension PrefixSequence.Iterator: IteratorProtocol {
public typealias Element = Base.Element
@inlinable
public mutating func next() -> Element? {
if _remaining != 0 {
_remaining &-= 1
return _base.next()
} else {
return nil
}
}
}
extension PrefixSequence: Sequence {
@inlinable
public __consuming func makeIterator() -> Iterator {
return Iterator(_base.makeIterator(), maxLength: _maxLength)
}
@inlinable
public __consuming func prefix(_ maxLength: Int) -> PrefixSequence<Base> {
let length = Swift.min(maxLength, self._maxLength)
return PrefixSequence(_base, maxLength: length)
}
}
/// A sequence that lazily consumes and drops `n` elements from an underlying
/// `Base` iterator before possibly returning the first available element.
///
/// The underlying iterator's sequence may be infinite.
@frozen
public struct DropWhileSequence<Base: Sequence> {
public typealias Element = Base.Element
@usableFromInline
internal var _iterator: Base.Iterator
@usableFromInline
internal var _nextElement: Element?
@inlinable
internal init(iterator: Base.Iterator, predicate: (Element) throws -> Bool) rethrows {
_iterator = iterator
_nextElement = _iterator.next()
while let x = _nextElement, try predicate(x) {
_nextElement = _iterator.next()
}
}
@inlinable
internal init(_ base: Base, predicate: (Element) throws -> Bool) rethrows {
self = try DropWhileSequence(iterator: base.makeIterator(), predicate: predicate)
}
}
extension DropWhileSequence {
@frozen
public struct Iterator {
@usableFromInline
internal var _iterator: Base.Iterator
@usableFromInline
internal var _nextElement: Element?
@inlinable
internal init(_ iterator: Base.Iterator, nextElement: Element?) {
_iterator = iterator
_nextElement = nextElement
}
}
}
extension DropWhileSequence.Iterator: IteratorProtocol {
public typealias Element = Base.Element
@inlinable
public mutating func next() -> Element? {
guard let next = _nextElement else { return nil }
_nextElement = _iterator.next()
return next
}
}
extension DropWhileSequence: Sequence {
@inlinable
public func makeIterator() -> Iterator {
return Iterator(_iterator, nextElement: _nextElement)
}
@inlinable
public __consuming func drop(
while predicate: (Element) throws -> Bool
) rethrows -> DropWhileSequence<Base> {
guard let x = _nextElement, try predicate(x) else { return self }
return try DropWhileSequence(iterator: _iterator, predicate: predicate)
}
}
//===----------------------------------------------------------------------===//
// Default implementations for Sequence
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns an array containing the results of mapping the given closure
/// over the sequence's elements.
///
/// In this example, `map` is used first to convert the names in the array
/// to lowercase strings and then to count their characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let lowercaseNames = cast.map { $0.lowercased() }
/// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
/// let letterCounts = cast.map { $0.count }
/// // 'letterCounts' == [6, 6, 3, 4]
///
/// - Parameter transform: A mapping closure. `transform` accepts an
/// element of this sequence as its parameter and returns a transformed
/// value of the same or of a different type.
/// - Returns: An array containing the transformed elements of this
/// sequence.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func map<T>(
_ transform: (Element) throws -> T
) rethrows -> [T] {
let initialCapacity = underestimatedCount
var result = ContiguousArray<T>()
result.reserveCapacity(initialCapacity)
var iterator = self.makeIterator()
// Add elements up to the initial capacity without checking for regrowth.
for _ in 0..<initialCapacity {
result.append(try transform(iterator.next()!))
}
// Add remaining elements, if any.
while let element = iterator.next() {
result.append(try transform(element))
}
return Array(result)
}
/// Returns an array containing, in order, the elements of the sequence
/// that satisfy the given predicate.
///
/// In this example, `filter(_:)` is used to include only names shorter than
/// five characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let shortNames = cast.filter { $0.count < 5 }
/// print(shortNames)
/// // Prints "["Kim", "Karl"]"
///
/// - Parameter isIncluded: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element should be included in the returned array.
/// - Returns: An array of the elements that `isIncluded` allowed.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public __consuming func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {
return try _filter(isIncluded)
}
@_transparent
public func _filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {
var result = ContiguousArray<Element>()
var iterator = self.makeIterator()
while let element = iterator.next() {
if try isIncluded(element) {
result.append(element)
}
}
return Array(result)
}
/// A value less than or equal to the number of elements in the sequence,
/// calculated nondestructively.
///
/// The default implementation returns 0. If you provide your own
/// implementation, make sure to compute the value nondestructively.
///
/// - Complexity: O(1), except if the sequence also conforms to `Collection`.
/// In this case, see the documentation of `Collection.underestimatedCount`.
@inlinable
public var underestimatedCount: Int {
return 0
}
@inlinable
@inline(__always)
public func _customContainsEquatableElement(
_ element: Iterator.Element
) -> Bool? {
return nil
}
/// Calls the given closure on each element in the sequence in the same order
/// as a `for`-`in` loop.
///
/// The two loops in the following example produce the same output:
///
/// let numberWords = ["one", "two", "three"]
/// for word in numberWords {
/// print(word)
/// }
/// // Prints "one"
/// // Prints "two"
/// // Prints "three"
///
/// numberWords.forEach { word in
/// print(word)
/// }
/// // Same as above
///
/// Using the `forEach` method is distinct from a `for`-`in` loop in two
/// important ways:
///
/// 1. You cannot use a `break` or `continue` statement to exit the current
/// call of the `body` closure or skip subsequent calls.
/// 2. Using the `return` statement in the `body` closure will exit only from
/// the current call to `body`, not from any outer scope, and won't skip
/// subsequent calls.
///
/// - Parameter body: A closure that takes an element of the sequence as a
/// parameter.
@_semantics("sequence.forEach")
@inlinable
public func forEach(
_ body: (Element) throws -> Void
) rethrows {
for element in self {
try body(element)
}
}
}
extension Sequence {
/// Returns the first element of the sequence that satisfies the given
/// predicate.
///
/// The following example uses the `first(where:)` method to find the first
/// negative number in an array of integers:
///
/// let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
/// if let firstNegative = numbers.first(where: { $0 < 0 }) {
/// print("The first negative number is \(firstNegative).")
/// }
/// // Prints "The first negative number is -2."
///
/// - Parameter predicate: A closure that takes an element of the sequence as
/// its argument and returns a Boolean value indicating whether the
/// element is a match.
/// - Returns: The first element of the sequence that satisfies `predicate`,
/// or `nil` if there is no element that satisfies `predicate`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func first(
where predicate: (Element) throws -> Bool
) rethrows -> Element? {
for element in self {
if try predicate(element) {
return element
}
}
return nil
}
}
extension Sequence where Element: Equatable {
/// Returns the longest possible subsequences of the sequence, in order,
/// around elements equal to the given element.
///
/// The resulting array consists of at most `maxSplits + 1` subsequences.
/// Elements that are used to split the sequence are not returned as part of
/// any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string at each
/// space character (" "). The first use of `split` returns each word that
/// was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.split(separator: " ")
/// .map(String.init))
/// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(line.split(separator: " ", maxSplits: 1)
/// .map(String.init))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// print(line.split(separator: " ", omittingEmptySubsequences: false)
/// .map(String.init))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - separator: The element that should be split upon.
/// - 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 consecutive pair of `separator`
/// elements in the sequence and for each instance of `separator` at the
/// start or end of the sequence. If `true`, only nonempty subsequences
/// are returned. The default value is `true`.
/// - Returns: An array of subsequences, split from this sequence's elements.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public __consuming func split(
separator: Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
) -> [ArraySlice<Element>] {
return split(
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences,
whereSeparator: { $0 == separator })
}
}
extension Sequence {
/// Returns the longest possible subsequences of the sequence, in order, that
/// don't contain elements satisfying the given predicate. Elements that are
/// used to split the sequence are not returned as part of any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string using a
/// closure that matches spaces. The first use of `split` returns each word
/// that was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.split(whereSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(
/// line.split(maxSplits: 1, whereSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `true` for the `allowEmptySlices` parameter, so
/// the returned array contains empty strings where spaces were repeated.
///
/// print(
/// line.split(
/// omittingEmptySubsequences: false,
/// whereSeparator: { $0 == " " }
/// ).map(String.init))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - 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`.
/// - isSeparator: A closure that returns `true` if its argument should be
/// used to split the sequence; otherwise, `false`.
/// - Returns: An array of subsequences, split from this sequence's elements.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public __consuming func split(
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
whereSeparator isSeparator: (Element) throws -> Bool
) rethrows -> [ArraySlice<Element>] {
_precondition(maxSplits >= 0, "Must take zero or more splits")
let whole = Array(self)
return try whole.split(
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences,
whereSeparator: isSeparator)
}
/// Returns a subsequence, up to the given maximum length, containing the
/// final elements of the sequence.
///
/// The sequence must be finite. If the maximum length exceeds the number of
/// elements in the sequence, the result contains all the elements in the
/// sequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public __consuming func suffix(_ maxLength: Int) -> [Element] {
_precondition(maxLength >= 0, "Can't take a suffix of negative length from a sequence")
guard maxLength != 0 else { return [] }
// FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T>
// Put incoming elements into a ring buffer to save space. Once all
// elements are consumed, reorder the ring buffer into a copy and return it.
// This saves memory for sequences particularly longer than `maxLength`.
var ringBuffer = ContiguousArray<Element>()
ringBuffer.reserveCapacity(Swift.min(maxLength, underestimatedCount))
var i = 0
for element in self {
if ringBuffer.count < maxLength {
ringBuffer.append(element)
} else {
ringBuffer[i] = element
i = (i + 1) % maxLength
}
}
if i != ringBuffer.startIndex {
var rotated = ContiguousArray<Element>()
rotated.reserveCapacity(ringBuffer.count)
rotated += ringBuffer[i..<ringBuffer.endIndex]
rotated += ringBuffer[0..<i]
return Array(rotated)
} else {
return Array(ringBuffer)
}
}
/// Returns a sequence containing all but the given number of initial
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in
/// the sequence, the result is an empty sequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropFirst(2))
/// // Prints "[3, 4, 5]"
/// print(numbers.dropFirst(10))
/// // Prints "[]"
///
/// - Parameter k: The number of elements to drop from the beginning of
/// the sequence. `k` must be greater than or equal to zero.
/// - Returns: A sequence starting after the specified number of
/// elements.
///
/// - Complexity: O(1), with O(*k*) deferred to each iteration of the result,
/// where *k* is the number of elements to drop from the beginning of
/// the sequence.
@inlinable
public __consuming func dropFirst(_ k: Int = 1) -> DropFirstSequence<Self> {
return DropFirstSequence(self, dropping: k)
}
/// Returns a sequence containing all but the given number of final
/// elements.
///
/// The sequence must be finite. If the number of elements to drop exceeds
/// the number of elements in the sequence, the result is an empty
/// sequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// print(numbers.dropLast(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop off the end of the
/// sequence. `n` must be greater than or equal to zero.
/// - Returns: A sequence leaving off the specified number of elements.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public __consuming func dropLast(_ k: Int = 1) -> [Element] {
_precondition(k >= 0, "Can't drop a negative number of elements from a sequence")
guard k != 0 else { return Array(self) }
// FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T>
// Put incoming elements from this sequence in a holding tank, a ring buffer
// of size <= k. If more elements keep coming in, pull them out of the
// holding tank into the result, an `Array`. This saves
// `k` * sizeof(Element) of memory, because slices keep the entire
// memory of an `Array` alive.
var result = ContiguousArray<Element>()
var ringBuffer = ContiguousArray<Element>()
var i = ringBuffer.startIndex
for element in self {
if ringBuffer.count < k {
ringBuffer.append(element)
} else {
result.append(ringBuffer[i])
ringBuffer[i] = element
i = (i + 1) % k
}
}
return Array(result)
}
/// Returns a sequence by skipping the initial, consecutive elements that
/// satisfy the given predicate.
///
/// The following example uses the `drop(while:)` method to skip over the
/// positive numbers at the beginning of the `numbers` array. The result
/// begins with the first element of `numbers` that does not satisfy
/// `predicate`.
///
/// let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
/// let startingWithNegative = numbers.drop(while: { $0 > 0 })
/// // startingWithNegative == [-2, 9, -6, 10, 1]
///
/// If `predicate` matches every element in the sequence, the result is an
/// empty sequence.
///
/// - Parameter predicate: A closure that takes an element of the sequence as
/// its argument and returns a Boolean value indicating whether the
/// element should be included in the result.
/// - Returns: A sequence starting after the initial, consecutive elements
/// that satisfy `predicate`.
///
/// - Complexity: O(*k*), where *k* is the number of elements to drop from
/// the beginning of the sequence.
@inlinable
public __consuming func drop(
while predicate: (Element) throws -> Bool
) rethrows -> DropWhileSequence<Self> {
return try DropWhileSequence(self, predicate: predicate)
}
/// Returns a sequence, up to the specified maximum length, containing the
/// initial elements of the sequence.
///
/// If the maximum length exceeds the number of elements in the sequence,
/// the result contains all the elements in the sequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.prefix(2))
/// // Prints "[1, 2]"
/// print(numbers.prefix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
/// - Returns: A sequence starting at the beginning of this sequence
/// with at most `maxLength` elements.
///
/// - Complexity: O(1)
@inlinable
public __consuming func prefix(_ maxLength: Int) -> PrefixSequence<Self> {
return PrefixSequence(self, maxLength: maxLength)
}
/// Returns a sequence containing the initial, consecutive elements that
/// satisfy the given predicate.
///
/// The following example uses the `prefix(while:)` method to find the
/// positive numbers at the beginning of the `numbers` array. Every element
/// of `numbers` up to, but not including, the first negative value is
/// included in the result.
///
/// let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
/// let positivePrefix = numbers.prefix(while: { $0 > 0 })
/// // positivePrefix == [3, 7, 4]
///
/// If `predicate` matches every element in the sequence, the resulting
/// sequence contains every element of the sequence.
///
/// - Parameter predicate: A closure that takes an element of the sequence as
/// its argument and returns a Boolean value indicating whether the
/// element should be included in the result.
/// - Returns: A sequence of the initial, consecutive elements that
/// satisfy `predicate`.
///
/// - Complexity: O(*k*), where *k* is the length of the result.
@inlinable
public __consuming func prefix(
while predicate: (Element) throws -> Bool
) rethrows -> [Element] {
var result = ContiguousArray<Element>()
for element in self {
guard try predicate(element) else {
break
}
result.append(element)
}
return Array(result)
}
}
extension Sequence {
/// Copy `self` into an unsafe buffer, initializing its memory.
///
/// The default implementation simply iterates over the elements of the
/// sequence, initializing the buffer one item at a time.
///
/// For sequences whose elements are stored in contiguous chunks of memory,
/// it may be more efficient to copy them in bulk, using the
/// `UnsafeMutablePointer.initialize(from:count:)` method.
///
/// - Parameter ptr: An unsafe buffer addressing uninitialized memory. The
/// buffer must be of sufficient size to accommodate
/// `source.underestimatedCount` elements. (Some implementations trap
/// if given a buffer that's smaller than this.)
///
/// - Returns: `(it, c)`, where `c` is the number of elements copied into the
/// buffer, and `it` is a partially consumed iterator that can be used to
/// retrieve elements that did not fit into the buffer (if any). (This can
/// only happen if `underestimatedCount` turned out to be an actual
/// underestimate, and the buffer did not contain enough space to hold the
/// entire sequence.)
///
/// On return, the memory region in `buffer[0 ..< c]` is initialized to
/// the first `c` elements in the sequence.
@inlinable
public __consuming func _copyContents(
initializing buffer: UnsafeMutableBufferPointer<Element>
) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) {
return _copySequenceContents(initializing: buffer)
}
@_alwaysEmitIntoClient
internal __consuming func _copySequenceContents(
initializing buffer: UnsafeMutableBufferPointer<Element>
) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) {
var it = self.makeIterator()
guard var ptr = buffer.baseAddress else { return (it,buffer.startIndex) }
for idx in buffer.startIndex..<buffer.count {
guard let x = it.next() else {
return (it, idx)
}
ptr.initialize(to: x)
ptr += 1
}
return (it,buffer.endIndex)
}
@inlinable
public func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R? {
return nil
}
}
// FIXME(ABI)#182
// Pending <rdar://problem/14011860> and <rdar://problem/14396120>,
// pass an IteratorProtocol through IteratorSequence to give it "Sequence-ness"
/// A sequence built around an iterator of type `Base`.
///
/// Useful mostly to recover the ability to use `for`...`in`,
/// given just an iterator `i`:
///
/// for x in IteratorSequence(i) { ... }
@frozen
public struct IteratorSequence<Base: IteratorProtocol> {
@usableFromInline
internal var _base: Base
/// Creates an instance whose iterator is a copy of `base`.
@inlinable
public init(_ base: Base) {
_base = base
}
}
extension IteratorSequence: IteratorProtocol, Sequence {
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
///
/// - Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made.
@inlinable
public mutating func next() -> Base.Element? {
return _base.next()
}
}
extension IteratorSequence: Sendable where Base: Sendable { }
/* FIXME: ideally for compatibility we would declare
extension Sequence {
@available(swift, deprecated: 5, message: "")
public typealias SubSequence = AnySequence<Element>
}
*/
| apache-2.0 |
kstaring/swift | validation-test/compiler_crashers_fixed/26458-swift-constraints-constraintsystem-simplifymemberconstraint.swift | 11 | 402 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
{nil...{(
| apache-2.0 |
StanZabroda/Hydra | Hydra/AuthController.swift | 1 | 3274 |
import UIKit
class AuthController: UIViewController,VKSdkDelegate {
var motionView:UIImageView!
var authButton: UIButton!
var authLogo:UIImageView!
override func loadView() {
super.loadView()
VKSdk.initializeWithDelegate(self, andAppId: "4689635")
if VKSdk.wakeUpSession() == true {
self.startWorking()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.blackColor()
self.setNeedsStatusBarAppearanceUpdate()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.motionView = UIImageView(frame: CGRectMake(0, 0, screenSizeWidth, screenSizeHeight))
self.motionView.image = UIImage(named: "placeholderBackground")
self.view.addSubview(self.motionView)
self.motionView.frame = CGRectMake(0, 0, screenSizeWidth, screenSizeHeight)
self.authButton = UIButton(frame: CGRectMake(screenSizeWidth/2 - 100, screenSizeHeight-150, 200, 50))
self.authButton.setTitle("Авторизация", forState: UIControlState.Normal)
self.authButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
self.authButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Highlighted)
self.authButton.setBackgroundImage(UIImage(named: "authButton"), forState: UIControlState.Normal)
self.authButton.addTarget(self, action: "authButtonAction", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(self.authButton)
self.authLogo = UIImageView(frame: CGRectMake(screenSizeWidth/2 - 100, 100, 200, 200))
self.authLogo.image = UIImage(named: "authLogo")
self.view.addSubview(self.authLogo)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
func authButtonAction() {
log.debug("auth button action")
VKSdk.authorize(["audio","status"], revokeAccess: true, forceOAuth: true, inApp: true)
}
func startWorking() {
dispatch.async.main { () -> Void in
HRInterfaceManager.sharedInstance.openDrawer()
self.presentViewController(HRInterfaceManager.sharedInstance.mainNav, animated: false, completion: nil)
}
}
func vkSdkNeedCaptchaEnter(captchaError: VKError!) {
//
}
func vkSdkTokenHasExpired(expiredToken: VKAccessToken!) {
//
}
func vkSdkReceivedNewToken(newToken: VKAccessToken!) {
self.startWorking()
}
func vkSdkShouldPresentViewController(controller: UIViewController!) {
self.presentViewController(controller, animated: true, completion: nil)
}
func vkSdkAcceptedUserToken(token: VKAccessToken!) {
self.startWorking()
}
func vkSdkUserDeniedAccess(authorizationError: VKError!) {
//
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
}
| mit |
arvedviehweger/swift | test/Parse/ConditionalCompilation/identifierName.swift | 1 | 1928 | // RUN: %target-typecheck-verify-swift
// Ensure that the identifiers in compilation conditions don't reference
// any decls in the scope.
func f2(
FOO: Int,
swift: Int, _compiler_version: Int,
os: Int, arch: Int, _endian: Int, _runtime: Int,
arm: Int, i386: Int, macOS: Int, OSX: Int, Linux: Int,
big: Int, little: Int,
_ObjC: Int, _Native: Int
) {
#if FOO
_ = FOO
#elseif os(macOS) && os(OSX) && os(Linux)
_ = os + macOS + OSX + Linux
#elseif arch(i386) && arch(arm)
_ = arch + i386 + arm
#elseif _endian(big) && _endian(little)
_ = _endian + big + little
#elseif _runtime(_ObjC) && _runtime(_Native)
_ = _runtime + _ObjC + _Native
#elseif swift(>=1.0) && _compiler_version("3.*.0")
_ = swift + _compiler_version
#endif
}
func f2() {
let
FOO = 1, swift = 1, _compiler_version = 1,
os = 1, arch = 1, _endian = 1, _runtime = 1,
arm = 1, i386 = 1, macOS = 1, OSX = 1, Linux = 1,
big = 1, little = 1,
_ObjC = 1, _Native = 1
#if FOO
_ = FOO
#elseif os(macOS) && os(OSX) && os(Linux)
_ = os + macOS + OSX + Linux
#elseif arch(i386) && arch(arm)
_ = arch + i386 + arm
#elseif _endian(big) && _endian(little)
_ = _endian + big + little
#elseif _runtime(_ObjC) && _runtime(_Native)
_ = _runtime + _ObjC + _Native
#elseif swift(>=1.0) && _compiler_version("3.*.0")
_ = swift + _compiler_version
#endif
}
struct S {
let
FOO = 1, swift = 1, _compiler_version = 1,
os = 1, arch = 1, _endian = 1, _runtime = 1,
arm = 1, i386 = 1, macOS = 1, OSX = 1, Linux = 1,
big = 1, little = 1,
_ObjC = 1, _Native = 1
#if FOO
#elseif os(macOS) && os(OSX) && os(Linux)
#elseif arch(i386) && arch(arm)
#elseif _endian(big) && _endian(little)
#elseif _runtime(_ObjC) && _runtime(_Native)
#elseif swift(>=1.0) && _compiler_version("3.*.0")
#endif
}
/// Ensure 'variable used within its own initial value' not to be emitted.
let BAR = { () -> Void in
#if BAR
#endif
}
| apache-2.0 |
JonyFang/AnimatedDropdownMenu | Examples/Examples/Navigation/DropdownMenuNavigationController.swift | 1 | 1048 | //
// DropdownMenuNavigationController.swift
// AnimatedDropdownMenu
//
// Created by JonyFang on 17/3/1.
// Copyright © 2017年 JonyFang. All rights reserved.
//
import UIKit
class DropdownMenuNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
configNavigationBar()
}
private func configNavigationBar() {
navigationBar.backgroundColor = nil
navigationBar.isTranslucent = true
navigationBar.shadowImage = nil
navigationBar.barStyle = .black
navigationBar.setBackgroundImage(nil, for: .default)
let textAttributes: [String: Any] = [
NSForegroundColorAttributeName: UIColor.menuLightTextColor(),
NSFontAttributeName: UIFont.navigationBarTitleFont()
]
navigationBar.titleTextAttributes = textAttributes
navigationBar.tintColor = UIColor.menuLightTextColor()
navigationBar.barTintColor = UIColor.menuLightTextColor()
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/08393-swift-typebase-getcanonicaltype.swift | 11 | 243 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
struct d {
var b: A
protocol A : A
protocol A {
typealias e : e
| mit |
huangboju/Moots | Examples/SwiftUI/Mac/Get-It-master/Get It/GrayButton.swift | 1 | 468 | //
// GrayButton.swift
// Get It
//
// Created by Kevin De Koninck on 29/01/2017.
// Copyright © 2017 Kevin De Koninck. All rights reserved.
//
import Cocoa
class GrayButton: NSButton {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
self.layer?.backgroundColor = CGColor.init(red: 0.3, green: 0.3, blue: 0.3, alpha: 0.3)
self.layer?.cornerRadius = 15.0
self.layer?.masksToBounds = true
}
}
| mit |
iabudiab/HTMLKit | HTMLKit.playground/Pages/Parsing Fragments.xcplaygroundpage/Contents.swift | 1 | 717 | //: [Previous](@previous)
/*:
# Parsing Document Fragments
*/
import HTMLKit
/*:
Given some HTML content
*/
let htmlString = "<div><p>Hello HTMLKit</p></div><td>some table data"
/*:
You can prase it as a document fragment in a specified context element:
*/
let parser = HTMLParser(string: htmlString)
let tableContext = HTMLElement(tagName: "table")
var elements = parser.parseFragment(withContextElement: tableContext)
for element in elements {
print(element.outerHTML)
}
/*:
The same parser instance can be reusued:
*/
let bodyContext = HTMLElement(tagName: "body")
elements = parser.parseFragment(withContextElement: bodyContext)
for element in elements {
print(element.outerHTML)
}
//: [Next](@next)
| mit |
danielrcardenas/ac-course-2017 | frameworks/SwarmChemistry-Swif/Demo_ScreenSaver/Defaults.swift | 1 | 1059 | //
// Defaults.swift
// SwarmChemistry
//
// Created by mitsuyoshi.yamazaki on 2017/09/07.
// Copyright © 2017 Mitsuyoshi Yamazaki. All rights reserved.
//
import Foundation
import ScreenSaver
import SwarmChemistry
internal class Defaults {
fileprivate static var moduleName: String {
let bundle = Bundle.init(for: self)
return bundle.bundleIdentifier!
}
fileprivate static var defaults: ScreenSaverDefaults {
return ScreenSaverDefaults.init(forModuleWithName: moduleName)!
}
fileprivate static func fullKey(of key: String) -> String {
return moduleName + "." + key
}
}
extension Defaults {
static var selectedRecipe: Recipe? {
get {
guard let recipeName = defaults.object(forKey: fullKey(of: "selectedRecipeName")) as? String else {
return nil
}
return Recipe.presetRecipes.filter { $0.name == recipeName }.first
}
set {
let defaults = self.defaults
defaults.set(newValue?.name, forKey: fullKey(of: "selectedRecipeName"))
defaults.synchronize()
}
}
}
| apache-2.0 |
alokc83/rayW-SwiftSeries | RW-SwiftSeries-controlStatment-challenge6.playground/Contents.swift | 1 | 769 | //: Playground - noun: a place where people can play
import UIKit
for var i=0; i<10; i++ {
println(i)
}
for j in 1..<10{
println(j)
}
for k in 1...10{
println(k)
}
var counter = 10
while(counter > 0){
counter -= 1
}
var c = 10
do {
println(c)
c -= 1
}while (c>0)
var movieList = [1:"Jurrassic World", 2:"Spy", 3:"Terminator"]
for (_,value) in movieList{
println("\(value)")
}
// challenge 6
for i in 1...100{
let multipleOf3 = i%3 == 0
let multipleOf5 = i%5 == 0
if multipleOf3 && multipleOf5{
println("fizzBuzz")
}
else if multipleOf3{
println("Fizz")
}
else if multipleOf5{
println("Buzz")
}
else{
println("No fizz, no Buzz, no fizzBuzz")
}
}
| mit |
LyuGGang/ReapWhatYouSow-iOS | ReapWhatYouSow/ViewController.swift | 1 | 519 | //
// ViewController.swift
// ReapWhatYouSow
//
// Created by 류원경 on 2015. 1. 8..
// Copyright (c) 2015년 CodeineStudio. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
nickplee/A-E-S-T-H-E-T-I-C-A-M | Aestheticam/Sources/Controllers/BaseController.swift | 2 | 913 | //
// BaseController.swift
// A E S T H E T I C A M
//
// Created by Nick Lee on 5/23/16.
// Copyright © 2016 Nick Lee. All rights reserved.
//
import Foundation
import UIKit
import ADTransitionController
class BaseController: ADTransitioningViewController {
override var prefersStatusBarHidden : Bool {
return true
}
private let trans = ADCubeTransition(duration: 0.5, orientation: ADTransitionRightToLeft, sourceRect: UIScreen.main.bounds)
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
transition = trans
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
transition = trans
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return .portrait
}
}
| mit |
chayelheinsen/GamingStreams-tvOS-App | StreamCenter/HitboxAPI.swift | 3 | 10750 | //
// HitboxAPI.swift
// GamingStreamsTVApp
//
// Created by Brendan Kirchner on 10/12/15.
// Copyright © 2015 Rivus Media Inc. All rights reserved.
//
import UIKit
import Alamofire
class HitboxAPI {
enum HitboxError: ErrorType {
case URLError
case JSONError
case AuthError
case NoAuthTokenError
case OtherError
var errorDescription: String {
get {
switch self {
case .URLError:
return "There was an error with the request."
case .JSONError:
return "There was an error parsing the JSON."
case .AuthError:
return "The user is not authenticated."
case .NoAuthTokenError:
return "There was no auth token provided in the response data."
case .OtherError:
return "An unidentified error occured."
}
}
}
var recoverySuggestion: String {
get {
switch self {
case .URLError:
return "Please make sure that the url is formatted correctly."
case .JSONError:
return "Please check the request information and response."
case .AuthError:
return "Please make sure to authenticate with Twitch before attempting to load this data."
case .NoAuthTokenError:
return "Please check the server logs and response."
case .OtherError:
return "Sorry, there's no provided solution for this error."
}
}
}
}
///This is a method to retrieve the most popular Hitbox games and we filter it to only games that have streams with content that is live at the moment
///
/// - parameters:
/// - offset: An integer offset to load content after the primary results (useful when you reach the end of a scrolling list)
/// - limit: The number of games to return
/// - searchTerm: An optional search term
/// - completionHandler: A closure providing results and an error (both optionals) to be executed once the request completes
static func getGames(offset: Int, limit: Int, searchTerm: String? = nil, completionHandler: (games: [HitboxGame]?, error: HitboxError?) -> ()) {
let urlString = "https://api.hitbox.tv/games"
var parameters: [String : AnyObject] = ["limit" : limit, "liveonly" : "true", "offset" : offset]
if let term = searchTerm {
parameters["q"] = term
}
Alamofire.request(.GET, urlString, parameters: parameters)
.responseJSON { (response) -> Void in
//do the stuff
if(response.result.isSuccess) {
if let baseDict = response.result.value as? [String : AnyObject] {
if let gamesDict = baseDict["categories"] as? [[String : AnyObject]] {
var games = [HitboxGame]()
for gameRaw in gamesDict {
if let game = HitboxGame(dict: gameRaw) {
games.append(game)
}
}
Logger.Debug("Returned \(games.count) results")
completionHandler(games: games, error: nil)
return
}
}
Logger.Error("Could not parse the response as JSON")
completionHandler(games: nil, error: .JSONError)
return
}
else {
Logger.Error("Could not request top games")
completionHandler(games: nil, error: .URLError)
return
}
}
}
///This is a method to retrieve the Hitbox streams for a specific game
///
/// - parameters:
/// - forGame: An integer gameID for given HitboxGame. This is called the category_id in the Hitbox API
/// - offset: An integer offset to load content after the primary results (useful when you reach the end of a scrolling list)
/// - limit: The number of games to return
/// - completionHandler: A closure providing results and an error (both optionals) to be executed once the request completes
static func getLiveStreams(forGame gameid: Int, offset: Int, limit: Int, completionHandler: (streams: [HitboxMedia]?, error: HitboxError?) -> ()) {
let urlString = "https://api.hitbox.tv/media/live/list"
Alamofire.request(.GET, urlString, parameters:
[ "game" : gameid,
"limit" : limit,
"start" : offset,
"publicOnly" : true ])
.responseJSON { (response) -> Void in
//do the stuff
if(response.result.isSuccess) {
if let baseDict = response.result.value as? [String : AnyObject] {
if let streamsDicts = baseDict["livestream"] as? [[String : AnyObject]] {
var streams = [HitboxMedia]()
for streamRaw in streamsDicts {
if let stream = HitboxMedia(dict: streamRaw) {
streams.append(stream)
}
}
Logger.Debug("Returned \(streams.count) results")
completionHandler(streams: streams, error: nil)
return
}
}
Logger.Error("Could not parse the response as JSON")
completionHandler(streams: nil, error: .JSONError)
return
}
else {
Logger.Error("Could not request top streams")
completionHandler(streams: nil, error: .URLError)
return
}
}
}
///This is a method to retrieve the stream links and information for a given Hitbox Stream
///
/// - parameters:
/// - forMediaID: A media ID for a given stream. In the Hitbox API they call it the user_media_id
/// - completionHandler: A closure providing results and an error (both optionals) to be executed once the request completes
static func getStreamInfo(forMediaId mediaId: String, completionHandler: (streamVideos: [HitboxStreamVideo]?, error: HitboxError?) -> ()) {
let urlString = "http://www.hitbox.tv/api/player/config/live/\(mediaId)"
Logger.Debug("getting stream info for: \(urlString)")
Alamofire.request(.GET, urlString)
.responseJSON { (response) -> Void in
if(response.result.isSuccess) {
if let baseDict = response.result.value as? [String : AnyObject] {
if let playlist = baseDict["playlist"] as? [[String : AnyObject]], bitrates = playlist.first?["bitrates"] as? [[String : AnyObject]] {
var streamVideos = [HitboxStreamVideo]()
for bitrate in bitrates {
if let video = HitboxStreamVideo(dict: bitrate) {
streamVideos.append(video)
}
}
// //this is no longer necessary, it was to try and get a rtmp stream but AVPlayer doesn't support that
// if streamVideos.count == 0 {
// //rtmp://edge.live.hitbox.tv/live/youplay
// streamVideos += HitboxStreamVideo.alternativeCreation(playlist.first)
// }
Logger.Debug("Returned \(streamVideos.count) results")
completionHandler(streamVideos: streamVideos, error: nil)
return
}
}
Logger.Error("Could not parse the response as JSON")
completionHandler(streamVideos: nil, error: .JSONError)
return
}
else {
Logger.Error("Could not request stream info")
completionHandler(streamVideos: nil, error: .URLError)
return
}
}
}
///This is a method to authenticate with the HitboxAPI. It takes a username and password and if it's successful it will store the token in the User's Keychain
///
/// - parameters:
/// - username: A username
/// - password: A password
/// - completionHandler: A closure providing a boolean indicating if the authentication was successful and an optional error if it was not successful
static func authenticate(withUserName username: String, password: String, completionHandler: (success: Bool, error: HitboxError?) -> ()) {
let urlString = "https://www.hitbox.tv/api/auth/login"
Alamofire.request(.POST, urlString, parameters:
[ "login" : username,
"pass" : password,
"rememberme" : "" ])
.responseJSON { (response) -> Void in
if response.result.isSuccess {
if let baseDict = response.result.value as? [String : AnyObject] {
if let dataDict = baseDict["data"] as? [String : AnyObject], token = dataDict["authToken"] as? String {
if let username = dataDict["user_name"] as? String {
TokenHelper.storeHitboxUsername(username)
}
TokenHelper.storeHitboxToken(token)
Mixpanel.tracker()?.trackEvents([Event.ServiceAuthenticationEvent("Hitbox")])
Logger.Debug("Successfully authenticated")
completionHandler(success: true, error: nil)
return
}
}
Logger.Error("Could not parse the response as JSON")
completionHandler(success: false, error: .NoAuthTokenError)
}
else {
Logger.Error("Could not request for authentication")
completionHandler(success: false, error: .URLError)
}
}
}
}
| mit |
Pintumo/PNTMPhotos | Example/AppDelegate.swift | 1 | 2621 | //
// AppDelegate.swift
// PNTMPhotos
//
// Created by Evangelos Sismanidis on 07.12.16.
// Copyright © 2016 Pintumo. All rights reserved.
//
import RxSwift
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let photos = PNTMPhotos(withAlbum: "PNTMPhotos")
_ = photos.save(image: UIImage(named: "PNTMPhotosLogo")!).subscribe(onNext: { saved in
print(saved)
})
_ = photos.select(index: 0, size: CGSize(width: 100, height: 100), contentMode: .aspectFit).subscribe(onNext: { image in
print(image)
})
_ = photos.all().subscribe(onNext: { assets in
print(assets.count)
})
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
mlpqaz/V2ex | ZZV2ex/Pods/Ji/Source/JiHelper.swift | 3 | 1694 | //
// JiHelper.swift
// Ji
//
// Created by Honghao Zhang on 2015-07-21.
// Copyright (c) 2015 Honghao Zhang (张宏昊)
//
// 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
extension String {
/**
Creates a new String from a xmlChar CString, using UTF-8 encoding.
- parameter char: xmlChar CString
- returns: Returns nil if the CString is NULL or if it contains ill-formed UTF-8 code unit sequences.
*/
static func fromXmlChar(_ char: UnsafePointer<xmlChar>?) -> String? {
if let char = char {
return String(validatingUTF8: UnsafeRawPointer(char).assumingMemoryBound(to: CChar.self))
} else {
return nil
}
}
}
| apache-2.0 |
SmallElephant/FEAlgorithm-Swift | 7-String/7-String/ReverseString.swift | 1 | 1628 | //
// ReverseString.swift
// 7-String
//
// Created by keso on 2017/1/8.
// Copyright © 2017年 FlyElephant. All rights reserved.
//
import Foundation
class ReverseString {
func reversePosition(strArr:inout [Character],begin:Int,end:Int) {
var low:Int = begin
var high:Int = end
while low < high {
swap(&strArr[low], &strArr[high])
low += 1
high -= 1
}
}
func leftRoateString(str:String,len:Int) -> String {
var strArr:[Character] = [Character]()
for c in str.characters {
strArr.append(c)
}
reversePosition(strArr: &strArr, begin: 0, end: len - 1)
reversePosition(strArr: &strArr, begin: len, end: strArr.count - 1)
reversePosition(strArr: &strArr, begin: 0, end: strArr.count - 1)
return String(strArr)
}
func reverseSentence(str:String) -> String {
var strArr:[Character] = [Character]()
for c in str.characters {
strArr.append(c)
}
reversePosition(strArr: &strArr, begin: 0, end: str.characters.count - 1)
var start:Int = 0
var end:Int = 0
while end < strArr.count {
if String(strArr[start]) == " " {
start += 1
end += 1
} else if String(strArr[end]) == " " {
reversePosition(strArr: &strArr, begin: start, end: end-1)
start = end
} else {
end += 1
}
}
return String(strArr)
}
}
| mit |
peaks-cc/iOS11_samplecode | chapter_12/HomeKitSample/App/Code/Protocol/TriggerSelector.swift | 1 | 163 | //
// TriggerSelector.swift
//
// Created by ToKoRo on 2017-09-03.
//
import HomeKit
protocol TriggerSelector {
func selectTrigger(_ trigger: HMTrigger)
}
| mit |
DonMag/ScratchPad | Swift3/scratchy/fbb/FBEdgeCrossing.swift | 3 | 5001 | //
// FBEdgeCrossing.swift
// Swift VectorBoolean for iOS
//
// Based on FBEdgeCrossing - Created by Andrew Finnell on 6/15/11.
// Copyright 2011 Fortunate Bear, LLC. All rights reserved.
//
// Created by Leslie Titze on 2015-07-02.
// Copyright (c) 2015 Leslie Titze. All rights reserved.
//
import UIKit
/// FBEdgeCrossing is used by the boolean operations code to hold data about
/// where two edges actually cross (as opposed to just intersect).
///
/// The main piece of data is the intersection, but it also holds a pointer to the
/// crossing's counterpart in the other FBBezierGraph
class FBEdgeCrossing {
fileprivate var _intersection: FBBezierIntersection
var edge: FBBezierCurve?
var counterpart: FBEdgeCrossing?
var fromCrossingOverlap = false
var entry = false
var processed = false
var selfCrossing = false
var index: Int = 0
//+ (id) crossingWithIntersection:(FBBezierIntersection *)intersection
init(intersection: FBBezierIntersection) {
_intersection = intersection
}
var isProcessed : Bool {
return processed
}
var isSelfCrossing : Bool {
return selfCrossing
}
var isEntry : Bool {
return entry
}
//@synthesize edge=_edge;
//@synthesize counterpart=_counterpart;
//@synthesize entry=_entry;
//@synthesize processed=_processed;
//@synthesize selfCrossing=_selfCrossing;
//@synthesize index=_index;
//@synthesize fromCrossingOverlap=_fromCrossingOverlap;
//@property (assign) FBBezierCurve *edge;
//@property (assign) FBEdgeCrossing *counterpart;
//@property (readonly) CGFloat order;
//@property (getter = isEntry) BOOL entry;
//@property (getter = isProcessed) BOOL processed;
//@property (getter = isSelfCrossing) BOOL selfCrossing;
//@property BOOL fromCrossingOverlap;
//@property NSUInteger index;
// An easy way to iterate crossings. It doesn't wrap when it reaches the end.
//@property (readonly) FBEdgeCrossing *next;
//@property (readonly) FBEdgeCrossing *previous;
//@property (readonly) FBEdgeCrossing *nextNonself;
//@property (readonly) FBEdgeCrossing *previousNonself;
// These properties pass through to the underlying intersection
//@property (readonly) CGFloat parameter;
///@property (readonly) FBBezierCurve *curve;
//@property (readonly) FBBezierCurve *leftCurve;
//@property (readonly) FBBezierCurve *rightCurve;
//@property (readonly, getter = isAtStart) BOOL atStart;
//@property (readonly, getter = isAtEnd) BOOL atEnd;
//@property (readonly) NSPoint location;
//- (void) removeFromEdge
func removeFromEdge() {
if let edge = edge {
edge.removeCrossing(self)
}
}
//- (CGFloat) order
var order : Double {
return parameter
}
//- (FBEdgeCrossing *) next
var next : FBEdgeCrossing? {
if let edge = edge {
return edge.nextCrossing(self)
} else {
return nil
}
}
//- (FBEdgeCrossing *) previous
var previous : FBEdgeCrossing? {
if let edge = edge {
return edge.previousCrossing(self)
} else {
return nil
}
}
//- (FBEdgeCrossing *) nextNonself
var nextNonself : FBEdgeCrossing? {
var nextNon : FBEdgeCrossing? = next
while nextNon != nil && nextNon!.isSelfCrossing {
nextNon = nextNon!.next
}
return nextNon
}
//- (FBEdgeCrossing *) previousNonself
var previousNonself : FBEdgeCrossing? {
var prevNon : FBEdgeCrossing? = previous
while prevNon != nil && prevNon!.isSelfCrossing {
prevNon = prevNon!.previous
}
return prevNon
}
// MARK: Underlying Intersection Access
// These properties pass through to the underlying intersection
//- (CGFloat) parameter
var parameter : Double {
// TODO: Is this actually working? Check equality operator here!
if edge == _intersection.curve1 {
return _intersection.parameter1
} else {
return _intersection.parameter2
}
}
//- (NSPoint) location
var location : CGPoint {
return _intersection.location
}
//- (FBBezierCurve *) curve
var curve : FBBezierCurve? {
return edge
}
//- (FBBezierCurve *) leftCurve
var leftCurve : FBBezierCurve? {
if isAtStart {
return nil
}
if edge == _intersection.curve1 {
return _intersection.curve1LeftBezier
} else {
return _intersection.curve2LeftBezier
}
}
//- (FBBezierCurve *) rightCurve
var rightCurve : FBBezierCurve? {
if isAtEnd {
return nil
}
if edge == _intersection.curve1 {
return _intersection.curve1RightBezier
} else {
return _intersection.curve2RightBezier
}
}
//- (BOOL) isAtStart
var isAtStart : Bool {
if edge == _intersection.curve1 {
return _intersection.isAtStartOfCurve1
} else {
return _intersection.isAtStartOfCurve2
}
}
//- (BOOL) isAtEnd
var isAtEnd : Bool {
if edge == _intersection.curve1 {
return _intersection.isAtStopOfCurve1
} else {
return _intersection.isAtStopOfCurve2
}
}
}
| mit |
ysnrkdm/Graphene | Package.swift | 1 | 159 | import PackageDescription
let package = Package(
name: "Graphene",
targets: [
Target(name: "Graphene", dependencies: ["Intrinsics"]),
]
)
| mit |
material-motion/motion-animator-objc | tests/unit/UIKitBehavioralTests.swift | 2 | 14413 | /*
Copyright 2017-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
#if IS_BAZEL_BUILD
import MotionAnimator
#else
import MotionAnimator
#endif
class ShapeLayerBackedView: UIView {
override static var layerClass: AnyClass { return CAShapeLayer.self }
override init(frame: CGRect) {
super.init(frame: frame)
let shapeLayer = self.layer as! CAShapeLayer
shapeLayer.path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 100, height: 100)).cgPath
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class UIKitBehavioralTests: XCTestCase {
var view: UIView!
var window: UIWindow!
override func setUp() {
super.setUp()
window = getTestHarnessKeyWindow()
rebuildView()
}
override func tearDown() {
view = nil
window = nil
super.tearDown()
}
private func rebuildView() {
window.subviews.forEach { $0.removeFromSuperview() }
view = ShapeLayerBackedView() // Need to animate a view's layer to get implicit animations.
view.layer.anchorPoint = .zero
window.addSubview(view)
// Connect our layers to the render server.
CATransaction.flush()
}
// MARK: Each animatable property needs to be added to exactly one of the following three tests
func testSomePropertiesImplicitlyAnimateAdditively() {
let baselineProperties: [AnimatableKeyPath: Any] = [
.bounds: CGRect(x: 0, y: 0, width: 123, height: 456),
.height: 100,
.position: CGPoint(x: 50, y: 20),
.rotation: 42,
.scale: 2.5,
// Note: prior to iOS 14 this used to work as a CGAffineTransform. iOS 14 now only accepts
// CATransform3D instances when using KVO.
.transform: CATransform3DMakeScale(1.5, 1.5, 1.5),
.width: 25,
.x: 12,
.y: 23,
]
let properties: [AnimatableKeyPath: Any]
if #available(iOS 11.0, *) {
// Corner radius became implicitly animatable in iOS 11.
var baselineWithCornerRadiusProperties = baselineProperties
baselineWithCornerRadiusProperties[.cornerRadius] = 3
properties = baselineWithCornerRadiusProperties
} else {
properties = baselineProperties
}
for (keyPath, value) in properties {
rebuildView()
UIView.animate(withDuration: 0.01) {
self.view.layer.setValue(value, forKeyPath: keyPath.rawValue)
}
XCTAssertNotNil(view.layer.animationKeys(),
"Expected \(keyPath.rawValue) to generate at least one animation.")
if let animationKeys = view.layer.animationKeys() {
for key in animationKeys {
let animation = view.layer.animation(forKey: key) as! CABasicAnimation
XCTAssertTrue(animation.isAdditive,
"Expected \(key) to be additive as a result of animating "
+ "\(keyPath.rawValue), but it was not: \(animation.debugDescription).")
}
}
}
}
func testSomePropertiesImplicitlyAnimateButNotAdditively() {
let baselineProperties: [AnimatableKeyPath: Any] = [
.backgroundColor: UIColor.blue,
.opacity: 0.5,
]
let properties: [AnimatableKeyPath: Any]
if #available(iOS 11.0, *) {
// Anchor point became implicitly animatable in iOS 11.
var baselineWithCornerRadiusProperties = baselineProperties
baselineWithCornerRadiusProperties[.anchorPoint] = CGPoint(x: 0.2, y: 0.4)
properties = baselineWithCornerRadiusProperties
} else {
properties = baselineProperties
}
for (keyPath, value) in properties {
rebuildView()
UIView.animate(withDuration: 0.01) {
self.view.layer.setValue(value, forKeyPath: keyPath.rawValue)
}
XCTAssertNotNil(view.layer.animationKeys(),
"Expected \(keyPath.rawValue) to generate at least one animation.")
if let animationKeys = view.layer.animationKeys() {
for key in animationKeys {
let animation = view.layer.animation(forKey: key) as! CABasicAnimation
XCTAssertFalse(animation.isAdditive,
"Expected \(key) not to be additive as a result of animating "
+ "\(keyPath.rawValue), but it was: \(animation.debugDescription).")
}
}
}
}
func testSomePropertiesDoNotImplicitlyAnimate() {
let baselineProperties: [AnimatableKeyPath: Any] = [
.anchorPoint: CGPoint(x: 0.2, y: 0.4),
.borderWidth: 5,
.borderColor: UIColor.red,
.cornerRadius: 3,
.shadowColor: UIColor.blue,
.shadowOffset: CGSize(width: 1, height: 1),
.shadowOpacity: 0.3,
.shadowRadius: 5,
.strokeStart: 0.2,
.strokeEnd: 0.5,
.z: 3,
]
let properties: [AnimatableKeyPath: Any]
if #available(iOS 13, *) {
// Shadow opacity became implicitly animatable in iOS 13.
var baselineWithModernSupport = baselineProperties
baselineWithModernSupport.removeValue(forKey: .shadowOpacity)
baselineWithModernSupport.removeValue(forKey: .anchorPoint)
baselineWithModernSupport.removeValue(forKey: .cornerRadius)
properties = baselineWithModernSupport
} else if #available(iOS 11.0, *) {
// Corner radius became implicitly animatable in iOS 11.
var baselineWithModernSupport = baselineProperties
baselineWithModernSupport.removeValue(forKey: .anchorPoint)
baselineWithModernSupport.removeValue(forKey: .cornerRadius)
properties = baselineWithModernSupport
} else {
properties = baselineProperties
}
for (keyPath, value) in properties {
rebuildView()
UIView.animate(withDuration: 0.01) {
self.view.layer.setValue(value, forKeyPath: keyPath.rawValue)
}
XCTAssertNil(view.layer.animationKeys(),
"Expected \(keyPath.rawValue) not to generate any animations.")
}
}
// MARK: Every animatable layer property must be added to the following test
func testNoPropertiesImplicitlyAnimateOutsideOfAnAnimationBlock() {
let properties: [AnimatableKeyPath: Any] = [
.backgroundColor: UIColor.blue,
.bounds: CGRect(x: 0, y: 0, width: 123, height: 456),
.cornerRadius: 3,
.height: 100,
.opacity: 0.5,
.position: CGPoint(x: 50, y: 20),
.rotation: 42,
.scale: 2.5,
.shadowColor: UIColor.blue,
.shadowOffset: CGSize(width: 1, height: 1),
.shadowOpacity: 0.3,
.shadowRadius: 5,
.strokeStart: 0.2,
.strokeEnd: 0.5,
.transform: CGAffineTransform(scaleX: 1.5, y: 1.5),
.width: 25,
.x: 12,
.y: 23,
]
for (keyPath, value) in properties {
rebuildView()
self.view.layer.setValue(value, forKeyPath: keyPath.rawValue)
XCTAssertNil(view.layer.animationKeys(),
"Expected \(keyPath.rawValue) not to generate any animations.")
}
}
// MARK: .beginFromCurrentState option behavior
//
// The following tests indicate that UIKit treats .beginFromCurrentState differently depending
// on the key path being animated. This difference is in line with whether or not a key path is
// animated additively or not.
//
// > See testSomePropertiesImplicitlyAnimateAdditively and
// > testSomePropertiesImplicitlyAnimateButNotAdditively for a list of which key paths are
// > animated which way.
//
// Notably, ONLY non-additive key paths are affected by the beginFromCurrentState option. This
// likely became the case starting in iOS 8 when additive animations were enabled by default.
// Additive animations will always animate additively regardless of whether or not you provide
// this flag.
func testDefaultsAnimatesOpacityNonAdditivelyFromItsModelLayerState() {
UIView.animate(withDuration: 0.1) {
self.view.alpha = 0.5
}
RunLoop.main.run(until: .init(timeIntervalSinceNow: 0.01))
let initialValue = self.view.layer.opacity
UIView.animate(withDuration: 0.1) {
self.view.alpha = 0.2
}
XCTAssertNotNil(view.layer.animationKeys(),
"Expected an animation to be added, but none were found.")
guard let animationKeys = view.layer.animationKeys() else {
return
}
XCTAssertEqual(animationKeys.count, 1,
"Expected only one animation to be added, but the following were found: "
+ "\(animationKeys).")
guard let key = animationKeys.first,
let animation = view.layer.animation(forKey: key) as? CABasicAnimation else {
return
}
XCTAssertFalse(animation.isAdditive, "Expected the animation not to be additive, but it was.")
XCTAssertTrue(animation.fromValue is Float,
"The animation's from value was not a number type: "
+ String(describing: animation.fromValue))
guard let fromValue = animation.fromValue as? Float else {
return
}
XCTAssertEqual(fromValue, initialValue, accuracy: 0.0001,
"Expected the animation to start from \(initialValue), but it did not.")
}
func testBeginFromCurrentStateAnimatesOpacityNonAdditivelyFromItsPresentationLayerState() {
UIView.animate(withDuration: 0.1) {
self.view.alpha = 0.5
}
RunLoop.main.run(until: .init(timeIntervalSinceNow: 0.01))
let initialValue = self.view.layer.presentation()!.opacity
UIView.animate(withDuration: 0.1, delay: 0, options: .beginFromCurrentState, animations: {
self.view.alpha = 0.2
}, completion: nil)
XCTAssertNotNil(view.layer.animationKeys(),
"Expected an animation to be added, but none were found.")
guard let animationKeys = view.layer.animationKeys() else {
return
}
XCTAssertEqual(animationKeys.count, 1,
"Expected only one animation to be added, but the following were found: "
+ "\(animationKeys).")
guard let key = animationKeys.first,
let animation = view.layer.animation(forKey: key) as? CABasicAnimation else {
return
}
XCTAssertFalse(animation.isAdditive, "Expected the animation not to be additive, but it was.")
XCTAssertTrue(animation.fromValue is Float,
"The animation's from value was not a number type: "
+ String(describing: animation.fromValue))
guard let fromValue = animation.fromValue as? Float else {
return
}
XCTAssertEqual(fromValue, initialValue, accuracy: 0.0001,
"Expected the animation to start from \(initialValue), but it did not.")
}
func testDefaultsAnimatesPositionAdditivelyFromItsModelLayerState() {
UIView.animate(withDuration: 0.1) {
self.view.layer.position = CGPoint(x: 100, y: self.view.layer.position.y)
}
RunLoop.main.run(until: .init(timeIntervalSinceNow: 0.01))
let initialValue = self.view.layer.position
UIView.animate(withDuration: 0.1) {
self.view.layer.position = CGPoint(x: 20, y: self.view.layer.position.y)
}
let displacement = initialValue.x - self.view.layer.position.x
XCTAssertNotNil(view.layer.animationKeys(),
"Expected an animation to be added, but none were found.")
guard let animationKeys = view.layer.animationKeys() else {
return
}
XCTAssertEqual(animationKeys.count, 2,
"Expected two animations to be added, but the following were found: "
+ "\(animationKeys).")
guard let key = animationKeys.first(where: { $0 != "position" }),
let animation = view.layer.animation(forKey: key) as? CABasicAnimation else {
return
}
XCTAssertTrue(animation.isAdditive, "Expected the animation to be additive, but it wasn't.")
XCTAssertTrue(animation.fromValue is CGPoint,
"The animation's from value was not a point type: "
+ String(describing: animation.fromValue))
guard let fromValue = animation.fromValue as? CGPoint else {
return
}
XCTAssertEqual(fromValue.x, displacement, accuracy: 0.0001,
"Expected the animation to have a delta of \(displacement), but it did not.")
}
func testBeginFromCurrentStateAnimatesPositionAdditivelyFromItsModelLayerState() {
UIView.animate(withDuration: 0.1) {
self.view.layer.position = CGPoint(x: 100, y: self.view.layer.position.y)
}
RunLoop.main.run(until: .init(timeIntervalSinceNow: 0.01))
let initialValue = self.view.layer.position
UIView.animate(withDuration: 0.1, delay: 0, options: .beginFromCurrentState, animations: {
self.view.layer.position = CGPoint(x: 20, y: self.view.layer.position.y)
}, completion: nil)
let displacement = initialValue.x - self.view.layer.position.x
XCTAssertNotNil(view.layer.animationKeys(),
"Expected an animation to be added, but none were found.")
guard let animationKeys = view.layer.animationKeys() else {
return
}
XCTAssertEqual(animationKeys.count, 2,
"Expected two animations to be added, but the following were found: "
+ "\(animationKeys).")
guard let key = animationKeys.first(where: { $0 != "position" }),
let animation = view.layer.animation(forKey: key) as? CABasicAnimation else {
return
}
XCTAssertTrue(animation.isAdditive, "Expected the animation to be additive, but it wasn't.")
XCTAssertTrue(animation.fromValue is CGPoint,
"The animation's from value was not a point type: "
+ String(describing: animation.fromValue))
guard let fromValue = animation.fromValue as? CGPoint else {
return
}
XCTAssertEqual(fromValue.x, displacement, accuracy: 0.0001,
"Expected the animation to have a delta of \(displacement), but it did not.")
}
}
| apache-2.0 |
eduresende/ios-nd-swift-syntax-swift-3 | Lesson8/L8_CalmTheCompiler.playground/Contents.swift | 1 | 887 | //: ### Calm the compiler
// Problem 1
protocol DirtyDeeds {
func cheat()
func steal()
}
class Minion: DirtyDeeds {
var name: String
init(name:String) {
self.name = name
}
}
// Problem 2
class DinnerCrew {
var members: [Souschef]
init(members: [Souschef]) {
self.members = members
}
}
protocol Souschef {
func chop(_ vegetable: String) -> String
func rinse(_ vegetable:String) -> String
}
var deviousDinnerCrew = DinnerCrew(members: [Minion]())
// Problem 3
protocol DogWalker {
func throwBall(_ numberOfTimes:Int) -> Int
func rubBelly()
}
class Neighbor: DogWalker {
func throwBall(_ numberOfTimes:Int) {
var count = 0
while count < numberOfTimes {
print("Go get it!")
count += 1
}
}
func rubBelly() {
print("Rub rub")
}
}
| mit |
iOSTestApps/firefox-ios | Utils/FaviconFetcher.swift | 1 | 6014 | import Storage
import Shared
import Alamofire
import XCGLogger
private let log = XCGLogger.defaultInstance()
private let queue = dispatch_queue_create("FaviconFetcher", DISPATCH_QUEUE_CONCURRENT)
class FaviconFetcherErrorType: ErrorType {
let description: String
init(description: String) {
self.description = description
}
}
/* A helper class to find the favicon associated with a url. This will load the page and parse any icons it finds out of it
* If that fails, it will attempt to find a favicon.ico in the root host domain
*/
public class FaviconFetcher : NSObject, NSXMLParserDelegate {
public static var userAgent: String = ""
static let ExpirationTime = NSTimeInterval(60*60*24*7) // Only check for icons once a week
class func getForUrl(url: NSURL, profile: Profile) -> Deferred<Result<[Favicon]>> {
let f = FaviconFetcher()
return f.loadFavicons(url, profile: profile)
}
private func loadFavicons(url: NSURL, profile: Profile, var oldIcons: [Favicon] = [Favicon]()) -> Deferred<Result<[Favicon]>> {
let deferred = Deferred<Result<[Favicon]>>()
dispatch_async(queue) { _ in
self.parseHTMLForFavicons(url).bind({ (result: Result<[Favicon]>) -> Deferred<[Result<Favicon>]> in
var deferreds = [Deferred<Result<Favicon>>]()
if let icons = result.successValue {
deferreds = map(icons) { self.getFavicon(url, icon: $0, profile: profile) }
}
return all(deferreds)
}).bind({ (results: [Result<Favicon>]) -> Deferred<Result<[Favicon]>> in
for result in results {
if let icon = result.successValue {
oldIcons.append(icon)
}
}
oldIcons.sort({ (a, b) -> Bool in
return a.width > b.width
})
return deferResult(oldIcons)
}).upon({ (result: Result<[Favicon]>) in
deferred.fill(result)
return
})
}
return deferred
}
lazy private var alamofire: Alamofire.Manager = {
var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
defaultHeaders["User-Agent"] = userAgent
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.timeoutIntervalForRequest = 5
configuration.HTTPAdditionalHeaders = defaultHeaders
return Alamofire.Manager(configuration: configuration)
}()
private func fetchDataForUrl(url: NSURL) -> Deferred<Result<NSData>> {
let deferred = Deferred<Result<NSData>>()
alamofire.request(.GET, url).response { (request, response, data, error) in
if let error = error {
deferred.fill(Result(failure: FaviconFetcherErrorType(description: error.description)))
} else {
let loc = response?.URL
deferred.fill(Result(success: data as! NSData))
}
}
return deferred
}
// Loads and parses an html document and tries to find any known favicon-type tags for the page
private func parseHTMLForFavicons(url: NSURL) -> Deferred<Result<[Favicon]>> {
var err: NSError?
return fetchDataForUrl(url).bind({ result -> Deferred<Result<[Favicon]>> in
var icons = [Favicon]()
if let data = result.successValue,
let element = RXMLElement(fromHTMLData: data) {
var reloadUrl: NSURL? = nil
element.iterate("head.meta") { meta in
if let refresh = meta.attribute("http-equiv") where refresh == "Refresh",
let content = meta.attribute("content"),
let index = content.rangeOfString("URL="),
let url = NSURL(string: content.substringFromIndex(advance(index.startIndex,4))) {
reloadUrl = url
}
}
if let url = reloadUrl {
return self.parseHTMLForFavicons(url)
}
element.iterate("head.link") { link in
if let rel = link.attribute("rel") where (rel == "shortcut icon" || rel == "icon" || rel == "apple-touch-icon"),
let href = link.attribute("href"),
let url = NSURL(string: href, relativeToURL: url) {
let icon = Favicon(url: url.absoluteString!, date: NSDate(), type: IconType.Icon)
icons.append(icon)
}
}
}
return deferResult(icons)
})
}
private func getFavicon(siteUrl: NSURL, icon: Favicon, profile: Profile) -> Deferred<Result<Favicon>> {
let deferred = Deferred<Result<Favicon>>()
let url = icon.url
let manager = SDWebImageManager.sharedManager()
let site = Site(url: siteUrl.absoluteString!, title: "")
var fav = Favicon(url: url, type: icon.type)
if let url = url.asURL {
manager.downloadImageWithURL(url, options: SDWebImageOptions.LowPriority, progress: nil, completed: { (img, err, cacheType, success, url) -> Void in
fav = Favicon(url: url.absoluteString!,
type: icon.type)
if let img = img {
fav.width = Int(img.size.width)
fav.height = Int(img.size.height)
profile.favicons.addFavicon(fav, forSite: site)
} else {
fav.width = 0
fav.height = 0
}
deferred.fill(Result(success: fav))
})
} else {
return deferResult(FaviconFetcherErrorType(description: "Invalid url \(url)"))
}
return deferred
}
}
| mpl-2.0 |
i-miss-you/Nuke | Pod/Classes/Core/ImageManagerLoader.swift | 1 | 10794 | // The MIT License (MIT)
//
// Copyright (c) 2015 Alexander Grebenyuk (github.com/kean).
import UIKit
internal protocol ImageManagerLoaderDelegate: class {
func imageLoader(imageLoader: ImageManagerLoader, imageTask: ImageTask, didUpdateProgressWithCompletedUnitCount completedUnitCount: Int64, totalUnitCount: Int64)
func imageLoader(imageLoader: ImageManagerLoader, imageTask: ImageTask, didCompleteWithImage image: UIImage?, error: ErrorType?)
}
internal class ImageManagerLoader {
internal weak var delegate: ImageManagerLoaderDelegate?
private let conf: ImageManagerConfiguration
private var executingTasks = [ImageTask : ImageLoaderTask]()
private var sessionTasks = [ImageRequestKey : ImageLoaderSessionTask]()
private let queue = dispatch_queue_create("ImageManagerLoader-InternalSerialQueue", DISPATCH_QUEUE_SERIAL)
private let decodingQueue: NSOperationQueue = {
let queue = NSOperationQueue()
queue.maxConcurrentOperationCount = 1
return queue
}()
private let processingQueue: NSOperationQueue = {
let queue = NSOperationQueue()
queue.maxConcurrentOperationCount = 2
return queue
}()
internal init(configuration: ImageManagerConfiguration) {
self.conf = configuration
}
internal func startLoadingForTask(task: ImageTask) {
dispatch_async(self.queue) {
let loaderTask = ImageLoaderTask(imageTask: task)
self.executingTasks[task] = loaderTask
self.startSessionTaskForTask(loaderTask)
}
}
private func startSessionTaskForTask(task: ImageLoaderTask) {
let key = ImageRequestKey(task.request, type: .Load, owner: self)
var sessionTask: ImageLoaderSessionTask! = self.sessionTasks[key]
if sessionTask == nil {
sessionTask = ImageLoaderSessionTask(key: key)
let dataTask = self.conf.dataLoader.imageDataTaskWithURL(task.request.URL, progressHandler: { [weak self] completedUnits, totalUnits in
self?.sessionTask(sessionTask, didUpdateProgressWithCompletedUnitCount: completedUnits, totalUnitCount: totalUnits)
}, completionHandler: { [weak self] data, _, error in
self?.sessionTask(sessionTask, didCompleteWithData: data, error: error)
})
dataTask.resume()
sessionTask.dataTask = dataTask
self.sessionTasks[key] = sessionTask
} else {
self.delegate?.imageLoader(self, imageTask: task.imageTask, didUpdateProgressWithCompletedUnitCount: sessionTask.completedUnitCount, totalUnitCount: sessionTask.completedUnitCount)
}
task.sessionTask = sessionTask
sessionTask.tasks.append(task)
}
private func sessionTask(sessionTask: ImageLoaderSessionTask, didUpdateProgressWithCompletedUnitCount completedUnitCount: Int64, totalUnitCount: Int64) {
dispatch_async(self.queue) {
sessionTask.totalUnitCount = totalUnitCount
sessionTask.completedUnitCount = completedUnitCount
for loaderTask in sessionTask.tasks {
self.delegate?.imageLoader(self, imageTask: loaderTask.imageTask, didUpdateProgressWithCompletedUnitCount: completedUnitCount, totalUnitCount: totalUnitCount)
}
}
}
private func sessionTask(sessionTask: ImageLoaderSessionTask, didCompleteWithData data: NSData?, error: ErrorType?) {
if let unwrappedData = data {
self.decodingQueue.addOperationWithBlock {
[weak self] in
let image = self?.conf.decoder.imageWithData(unwrappedData)
self?.sessionTask(sessionTask, didCompleteWithImage: image, error: error)
}
} else {
self.sessionTask(sessionTask, didCompleteWithImage: nil, error: error)
}
}
private func sessionTask(sessionTask: ImageLoaderSessionTask, didCompleteWithImage image: UIImage?, error: ErrorType?) {
dispatch_async(self.queue) {
for loaderTask in sessionTask.tasks {
self.processImage(image, error: error, forLoaderTask: loaderTask)
}
sessionTask.tasks.removeAll()
sessionTask.dataTask = nil
self.removeSessionTask(sessionTask)
}
}
private func processImage(image: UIImage?, error: ErrorType?, forLoaderTask task: ImageLoaderTask) {
if let unwrappedImage = image, processor = self.processorForRequest(task.request) {
let operation = NSBlockOperation { [weak self] in
let processedImage = processor.processImage(unwrappedImage)
self?.storeImage(processedImage, forRequest: task.request)
self?.loaderTask(task, didCompleteWithImage: processedImage, error: error)
}
self.processingQueue.addOperation(operation)
task.processingOperation = operation
} else {
self.storeImage(image, forRequest: task.request)
self.loaderTask(task, didCompleteWithImage: image, error: error)
}
}
private func processorForRequest(request: ImageRequest) -> ImageProcessing? {
var processors = [ImageProcessing]()
if request.shouldDecompressImage {
processors.append(ImageDecompressor(targetSize: request.targetSize, contentMode: request.contentMode))
}
if let processor = request.processor {
processors.append(processor)
}
return processors.isEmpty ? nil : ImageProcessorComposition(processors: processors)
}
private func loaderTask(task: ImageLoaderTask, didCompleteWithImage image: UIImage?, error: ErrorType?) {
dispatch_async(self.queue) {
self.delegate?.imageLoader(self, imageTask: task.imageTask, didCompleteWithImage: image, error: error)
self.executingTasks[task.imageTask] = nil
}
}
internal func stopLoadingForTask(imageTask: ImageTask) {
dispatch_async(self.queue) {
if let loaderTask = self.executingTasks[imageTask], sessionTask = loaderTask.sessionTask {
if let index = (sessionTask.tasks.indexOf { $0 === loaderTask }) {
sessionTask.tasks.removeAtIndex(index)
}
if sessionTask.tasks.isEmpty {
sessionTask.dataTask?.cancel()
sessionTask.dataTask = nil
self.removeSessionTask(sessionTask)
}
loaderTask.processingOperation?.cancel()
self.executingTasks[imageTask] = nil
}
}
}
// MARK: Misc
internal func cachedResponseForRequest(request: ImageRequest) -> ImageCachedResponse? {
return self.conf.cache?.cachedResponseForKey(ImageRequestKey(request, type: .Cache, owner: self))
}
private func storeImage(image: UIImage?, forRequest request: ImageRequest) {
if image != nil {
let cachedResponse = ImageCachedResponse(image: image!, userInfo: nil)
self.conf.cache?.storeResponse(cachedResponse, forKey: ImageRequestKey(request, type: .Cache, owner: self))
}
}
internal func preheatingKeyForRequest(request: ImageRequest) -> ImageRequestKey {
return ImageRequestKey(request, type: .Cache, owner: self)
}
private func removeSessionTask(task: ImageLoaderSessionTask) {
if self.sessionTasks[task.key] === task {
self.sessionTasks[task.key] = nil
}
}
}
// MARK: ImageManagerLoader: ImageRequestKeyOwner
extension ImageManagerLoader: ImageRequestKeyOwner {
internal func isImageRequestKey(lhs: ImageRequestKey, equalToKey rhs: ImageRequestKey) -> Bool {
switch lhs.type {
case .Cache:
if !(self.conf.dataLoader.isRequestCacheEquivalent(lhs.request, toRequest: rhs.request)) {
return false
}
let lhsProcessor: ImageProcessing! = self.processorForRequest(lhs.request)
let rhsProcessor: ImageProcessing! = self.processorForRequest(rhs.request)
if lhsProcessor != nil && rhsProcessor != nil {
return lhsProcessor.isEquivalentToProcessor(rhsProcessor)
} else if lhsProcessor != nil || rhsProcessor != nil {
return false
}
return true
case .Load:
return self.conf.dataLoader.isRequestLoadEquivalent(lhs.request, toRequest: rhs.request)
}
}
}
// MARK: - ImageLoaderTask
private class ImageLoaderTask {
let imageTask: ImageTask
var request: ImageRequest {
get {
return self.imageTask.request
}
}
var sessionTask: ImageLoaderSessionTask?
var processingOperation: NSOperation?
private init(imageTask: ImageTask) {
self.imageTask = imageTask
}
}
// MARK: - ImageLoaderSessionTask
private class ImageLoaderSessionTask {
let key: ImageRequestKey
var dataTask: NSURLSessionTask?
var tasks = [ImageLoaderTask]()
var totalUnitCount: Int64 = 0
var completedUnitCount: Int64 = 0
init(key: ImageRequestKey) {
self.key = key
}
}
// MARK: - ImageRequestKey
internal protocol ImageRequestKeyOwner: class {
func isImageRequestKey(key: ImageRequestKey, equalToKey: ImageRequestKey) -> Bool
}
internal enum ImageRequestKeyType {
case Load
case Cache
}
/** Makes it possible to use ImageRequest as a key in dictionaries (and dictionary-like structures). This should be a nested class inside ImageManager but it's impossible because of the Equatable protocol.
*/
internal class ImageRequestKey: NSObject {
let request: ImageRequest
let type: ImageRequestKeyType
weak var owner: ImageRequestKeyOwner?
override var hashValue: Int {
return self.request.URL.hashValue
}
init(_ request: ImageRequest, type: ImageRequestKeyType, owner: ImageRequestKeyOwner) {
self.request = request
self.type = type
self.owner = owner
}
// Make it possible to use ImageRequesKey as key in NSCache
override var hash: Int {
return self.hashValue
}
override func isEqual(object: AnyObject?) -> Bool {
if object === self {
return true
}
if let object = object as? ImageRequestKey {
return self == object
}
return false
}
}
private func ==(lhs: ImageRequestKey, rhs: ImageRequestKey) -> Bool {
if let owner = lhs.owner where lhs.owner === rhs.owner && lhs.type == rhs.type {
return owner.isImageRequestKey(lhs, equalToKey: rhs)
}
return false
}
| mit |
eCrowdMedia/MooApi | Tests/BookShelvesTests.swift | 1 | 1501 | import XCTest
@testable import MooApi
import Argo
import Foundation
final internal class BookShelvesTests: XCTestCase {
func testDatas() {
let testBundle = Bundle(for: type(of: self))
let path = testBundle.path(forResource: "BookshelvesInfo", ofType: "json")
let data = try! Data(contentsOf: URL(fileURLWithPath: path!))
let json = JSON(try! JSONSerialization.jsonObject(with: data, options: []))
let result = ApiDocument<Bookshelf>.decode(json)
// Test data
if result.value?.data == nil {
XCTFail("\(result.error.debugDescription)")
return
}
}
func testBookShelves() {
let testBundle = Bundle(for: type(of: self))
let path = testBundle.path(forResource: "BookshelvesData", ofType: "json")
let data = try! Data(contentsOf: URL(fileURLWithPath: path!))
let json = JSON(try! JSONSerialization.jsonObject(with: data, options: []))
let result = ApiDocumentEnvelope<Bookshelf>.decode(json)
// Test data
guard let dataList = result.value?.data else {
XCTFail("\(result.error.debugDescription)")
return
}
guard let included = result.value?.included else {
XCTFail("\(result.error.debugDescription)")
return
}
if included.books.count != dataList.count {
XCTFail("\(result.error.debugDescription)")
return
}
if included.readings.count != dataList.count {
XCTFail("\(result.error.debugDescription)")
return
}
}
}
| mit |
jmgc/swift | test/DebugInfo/async-args.swift | 1 | 2064 | // RUN: %target-swift-frontend %s -emit-ir -g -o - \
// RUN: -module-name M -enable-experimental-concurrency | %FileCheck %s
// REQUIRES: concurrency
func use<T>(_ t: T) {}
func forceSplit() async {
}
func withGenericArg<T>(_ msg: T) async {
// This odd debug info is part of a contract with CoroSplit/CoroFrame to fix
// this up after coroutine splitting.
// CHECK-LABEL: {{^define .*}} @"$s1M14withGenericArgyyxYlF"(%swift.task* %0, %swift.executor* %1, %swift.context* %2)
// CHECK: call void @llvm.dbg.declare(metadata %swift.context** %[[ALLOCA:[^,]*]],
// CHECK-SAME: metadata ![[MSG:[0-9]+]], metadata !DIExpression(
// CHECK-SAME: DW_OP_deref, DW_OP_plus_uconst, {{[0-9]+}}, DW_OP_deref))
// CHECK: call void @llvm.dbg.declare(metadata %swift.context** %[[ALLOCA]],
// CHECK-SAME: metadata ![[TAU:[0-9]+]], metadata !DIExpression(
// CHECK-SAME: DW_OP_deref, DW_OP_plus_uconst, {{[0-9]+}}))
// CHECK: store %swift.context* %2, %swift.context** %[[ALLOCA]], align
await forceSplit()
// CHECK-LABEL: {{^define .*}} @"$s1M14withGenericArgyyxYlF.resume.0"(i8* %0, i8* %1, i8* %2)
// CHECK: store i8* %2, i8** %[[ALLOCA:.*]], align
// CHECK: call void @llvm.dbg.declare(metadata i8** %[[ALLOCA]],
// CHECK-SAME: metadata ![[TAU_R:[0-9]+]], metadata !DIExpression(
// CHECK-SAME: DW_OP_deref, DW_OP_plus_uconst, [[OFFSET:[0-9]+]],
// CHECK-SAME: DW_OP_plus_uconst, {{[0-9]+}}))
// CHECK: call void @llvm.dbg.declare(metadata i8** %[[ALLOCA]],
// CHECK-SAME: metadata ![[MSG_R:[0-9]+]], metadata !DIExpression(
// CHECK-SAME: DW_OP_deref, DW_OP_plus_uconst, [[OFFSET]],
// CHECK-SAME: DW_OP_plus_uconst, {{[0-9]+}}, DW_OP_deref))
use(msg)
}
// CHECK-LABEL: {{^define }}
runAsyncAndBlock {
await withGenericArg("hello (asynchronously)")
}
// CHECK: ![[MSG]] = !DILocalVariable(name: "msg", arg: 1,
// CHECK: ![[TAU]] = !DILocalVariable(name: "$\CF\84_0_0",
// CHECK: ![[TAU_R]] = !DILocalVariable(name: "$\CF\84_0_0",
// CHECK: ![[MSG_R]] = !DILocalVariable(name: "msg", arg: 1,
| apache-2.0 |
sora0077/MaterialKit | MaterialKitTests/MaterialKitTests.swift | 1 | 916 | //
// MaterialKitTests.swift
// MaterialKitTests
//
// Created by 林達也 on 2015/06/14.
// Copyright (c) 2015年 MaterialKit. All rights reserved.
//
import UIKit
import XCTest
class MaterialKitTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
ApterKing/SwiftyJSONMappable | Pod/Classes/Observable+JSONMappable.swift | 2 | 1015 | //
// Observable+JSONMappable.swift
// SwiftyJSONMappable
//
// Created by wangcong on 15/06/2017.
// Copyright © 2017 ApterKing. All rights reserved.
//
import Foundation
import Moya
import RxSwift
import SwiftyJSON
public extension ObservableType where E == Response {
/// Transfrom received data to JSONMappable, fail on error
public func mapJSONMappable<T: JSONMappable>(_ type: T.Type, failsOnEmptyData: Bool = true) -> Observable<T> {
return flatMap({ (response) -> Observable<T> in
return Observable<T>.just(try response.mapJSONMappable(type, failsOnEmptyData: failsOnEmptyData))
})
}
/// Transfrom received data to [JSONMappable], fail on error
public func mapJSONMappable<T: JSONMappable>(_ type: [T.Type], failsOnEmptyData: Bool = true) -> Observable<[T]> {
return flatMap({ (response) -> Observable<[T]> in
return Observable<[T]>.just(try response.mapJSONMappable(type, failsOnEmptyData: failsOnEmptyData))
})
}
}
| mit |
rexpie/catchup-gui | chatTime/chatTime/MyViewController.swift | 1 | 872 | //
// MyViewController.swift
// chatTime
//
// Created by 陈静 on 14-9-21.
// Copyright (c) 2014年 Team chatTime. All rights reserved.
//
import UIKit
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Gutenberg/Layout Picker/FilterableCategoriesViewController.swift | 1 | 10620 | import UIKit
import Gridicons
import Gutenberg
class FilterableCategoriesViewController: CollapsableHeaderViewController {
private enum CategoryFilterAnalyticsKeys {
static let modifiedFilter = "filter"
static let selectedFilters = "selected_filters"
static let location = "location"
}
typealias PreviewDevice = PreviewDeviceSelectionViewController.PreviewDevice
let tableView: UITableView
private lazy var debounceSelectionChange: Debouncer = {
Debouncer(delay: 0.1) { [weak self] in
guard let `self` = self else { return }
self.itemSelectionChanged(self.selectedItem != nil)
}
}()
internal var selectedItem: IndexPath? = nil {
didSet {
debounceSelectionChange.call()
}
}
private let filterBar: CollapsableHeaderFilterBar
internal var categorySections: [CategorySection] { get {
fatalError("This should be overridden by the subclass to provide a conforming collection of categories")
} }
private var filteredSections: [CategorySection]?
private var visibleSections: [CategorySection] { filteredSections ?? categorySections }
internal var isLoading: Bool = true {
didSet {
if isLoading {
tableView.startGhostAnimation(style: GhostCellStyle.muriel)
} else {
tableView.stopGhostAnimation()
}
loadingStateChanged(isLoading)
tableView.reloadData()
}
}
var selectedPreviewDevice = PreviewDevice.default {
didSet {
tableView.reloadData()
}
}
let analyticsLocation: String
init(
analyticsLocation: String,
mainTitle: String,
prompt: String,
primaryActionTitle: String,
secondaryActionTitle: String? = nil,
defaultActionTitle: String? = nil
) {
self.analyticsLocation = analyticsLocation
tableView = UITableView(frame: .zero, style: .plain)
tableView.separatorStyle = .singleLine
tableView.separatorInset = .zero
tableView.showsVerticalScrollIndicator = false
filterBar = CollapsableHeaderFilterBar()
super.init(scrollableView: tableView,
mainTitle: mainTitle,
prompt: prompt,
primaryActionTitle: primaryActionTitle,
secondaryActionTitle: secondaryActionTitle,
defaultActionTitle: defaultActionTitle,
accessoryView: filterBar)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(CategorySectionTableViewCell.nib, forCellReuseIdentifier: CategorySectionTableViewCell.cellReuseIdentifier)
filterBar.filterDelegate = self
tableView.dataSource = self
configureCloseButton()
}
private func configureCloseButton() {
navigationItem.rightBarButtonItem = CollapsableHeaderViewController.closeButton(target: self, action: #selector(closeButtonTapped))
}
@objc func closeButtonTapped(_ sender: Any) {
dismiss(animated: true)
}
override func estimatedContentSize() -> CGSize {
let rowCount = CGFloat(max(visibleSections.count, 1))
let estimatedRowHeight: CGFloat = CategorySectionTableViewCell.estimatedCellHeight
let estimatedHeight = (estimatedRowHeight * rowCount)
return CGSize(width: tableView.contentSize.width, height: estimatedHeight)
}
public func loadingStateChanged(_ isLoading: Bool) {
filterBar.shouldShowGhostContent = isLoading
filterBar.allowsMultipleSelection = !isLoading
filterBar.reloadData()
}
}
extension FilterableCategoriesViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return CategorySectionTableViewCell.estimatedCellHeight
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return isLoading ? 1 : (visibleSections.count)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellReuseIdentifier = CategorySectionTableViewCell.cellReuseIdentifier
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as? CategorySectionTableViewCell else {
fatalError("Expected the cell with identifier \"\(cellReuseIdentifier)\" to be a \(CategorySectionTableViewCell.self). Please make sure the table view is registering the correct nib before loading the data")
}
cell.delegate = self
cell.selectionStyle = UITableViewCell.SelectionStyle.none
cell.section = isLoading ? nil : visibleSections[indexPath.row]
cell.isGhostCell = isLoading
cell.layer.masksToBounds = false
cell.clipsToBounds = false
cell.collectionView.allowsSelection = !isLoading
if let selectedItem = selectedItem, containsSelectedItem(selectedItem, atIndexPath: indexPath) {
cell.selectItemAt(selectedItem.item)
}
return cell
}
private func containsSelectedItem(_ selectedIndexPath: IndexPath, atIndexPath indexPath: IndexPath) -> Bool {
let rowSection = visibleSections[indexPath.row]
let sectionSlug = categorySections[selectedIndexPath.section].categorySlug
return (sectionSlug == rowSection.categorySlug)
}
}
extension FilterableCategoriesViewController: CategorySectionTableViewCellDelegate {
func didSelectItemAt(_ position: Int, forCell cell: CategorySectionTableViewCell, slug: String) {
guard let cellIndexPath = tableView.indexPath(for: cell),
let sectionIndex = categorySections.firstIndex(where: { $0.categorySlug == slug })
else { return }
tableView.selectRow(at: cellIndexPath, animated: false, scrollPosition: .none)
deselectCurrentLayout()
selectedItem = IndexPath(item: position, section: sectionIndex)
}
func didDeselectItem(forCell cell: CategorySectionTableViewCell) {
selectedItem = nil
}
func accessibilityElementDidBecomeFocused(forCell cell: CategorySectionTableViewCell) {
guard UIAccessibility.isVoiceOverRunning, let cellIndexPath = tableView.indexPath(for: cell) else { return }
tableView.scrollToRow(at: cellIndexPath, at: .middle, animated: true)
}
private func deselectCurrentLayout() {
guard let previousSelection = selectedItem else { return }
tableView.indexPathsForVisibleRows?.forEach { (indexPath) in
if containsSelectedItem(previousSelection, atIndexPath: indexPath) {
(tableView.cellForRow(at: indexPath) as? CategorySectionTableViewCell)?.deselectItems()
}
}
}
}
extension FilterableCategoriesViewController: CollapsableHeaderFilterBarDelegate {
func numberOfFilters() -> Int {
return categorySections.count
}
func filter(forIndex index: Int) -> CategorySection {
return categorySections[index]
}
func didSelectFilter(withIndex selectedIndex: IndexPath, withSelectedIndexes selectedIndexes: [IndexPath]) {
trackFiltersChangedEvent(isSelectionEvent: true, changedIndex: selectedIndex, selectedIndexes: selectedIndexes)
guard filteredSections == nil else {
insertFilterRow(withIndex: selectedIndex, withSelectedIndexes: selectedIndexes)
return
}
let rowsToRemove = (0..<categorySections.count).compactMap { ($0 == selectedIndex.item) ? nil : IndexPath(row: $0, section: 0) }
filteredSections = [categorySections[selectedIndex.item]]
tableView.performBatchUpdates({
contentSizeWillChange()
tableView.deleteRows(at: rowsToRemove, with: .fade)
})
}
func insertFilterRow(withIndex selectedIndex: IndexPath, withSelectedIndexes selectedIndexes: [IndexPath]) {
let sortedIndexes = selectedIndexes.sorted(by: { $0.item < $1.item })
for i in 0..<sortedIndexes.count {
if sortedIndexes[i].item == selectedIndex.item {
filteredSections?.insert(categorySections[selectedIndex.item], at: i)
break
}
}
tableView.performBatchUpdates({
if selectedIndexes.count == 2 {
contentSizeWillChange()
}
tableView.reloadSections([0], with: .automatic)
})
}
func didDeselectFilter(withIndex index: IndexPath, withSelectedIndexes selectedIndexes: [IndexPath]) {
trackFiltersChangedEvent(isSelectionEvent: false, changedIndex: index, selectedIndexes: selectedIndexes)
guard selectedIndexes.count == 0 else {
removeFilterRow(withIndex: index)
return
}
filteredSections = nil
tableView.performBatchUpdates({
contentSizeWillChange()
tableView.reloadSections([0], with: .fade)
})
}
func trackFiltersChangedEvent(isSelectionEvent: Bool, changedIndex: IndexPath, selectedIndexes: [IndexPath]) {
let event: WPAnalyticsEvent = isSelectionEvent ? .categoryFilterSelected : .categoryFilterDeselected
let filter = categorySections[changedIndex.item].categorySlug
let selectedFilters = selectedIndexes.map({ categorySections[$0.item].categorySlug }).joined(separator: ", ")
WPAnalytics.track(event, properties: [
CategoryFilterAnalyticsKeys.location: analyticsLocation,
CategoryFilterAnalyticsKeys.modifiedFilter: filter,
CategoryFilterAnalyticsKeys.selectedFilters: selectedFilters
])
}
func removeFilterRow(withIndex index: IndexPath) {
guard let filteredSections = filteredSections else { return }
var row: IndexPath? = nil
let rowSlug = categorySections[index.item].categorySlug
for i in 0..<filteredSections.count {
if filteredSections[i].categorySlug == rowSlug {
let indexPath = IndexPath(row: i, section: 0)
self.filteredSections?.remove(at: i)
row = indexPath
break
}
}
guard let rowToRemove = row else { return }
tableView.performBatchUpdates({
contentSizeWillChange()
tableView.deleteRows(at: [rowToRemove], with: .fade)
})
}
}
| gpl-2.0 |
Smartvoxx/ios | Step07/Start/SmartvoxxOnWrist Extension/ManagedObjects/Speaker.swift | 4 | 215 | //
// Speaker.swift
// Smartvoxx
//
// Created by Sebastien Arbogast on 04/10/2015.
// Copyright © 2015 Epseelon. All rights reserved.
//
import Foundation
import CoreData
class Speaker: NSManagedObject {
}
| gpl-2.0 |
tiagomartinho/calculator | CalculatorTests/CalculatorConstantsTests.swift | 1 | 2336 | import XCTest
class CalculatorConstantsTests: XCTestCase {
var calculatorBrain:CalculatorBrain?
override func setUp() {
super.setUp()
calculatorBrain = CalculatorBrain()
}
func testOneConstant(){
calculatorBrain?.pushOperation("π")
calculatorBrain?.assertItEvaluatesTo(M_PI)
}
func testOneConstantWithUnaryOperation(){
calculatorBrain?.pushOperation("π")
calculatorBrain?.pushOperation("^2")
calculatorBrain?.assertItEvaluatesTo(M_PI*M_PI)
}
func testTwoConstant(){
calculatorBrain?.pushOperation("e")
calculatorBrain?.pushOperation("π")
calculatorBrain?.assertItEvaluatesTo(M_E*M_PI)
}
func testOneConstantWithPreOperand(){
calculatorBrain?.pushOperand(3)
calculatorBrain?.pushOperation("π")
calculatorBrain?.assertItEvaluatesTo(3*M_PI)
}
func testOneConstantWithPosOperand(){
calculatorBrain?.pushOperation("e")
calculatorBrain?.pushOperand(5)
calculatorBrain?.assertItEvaluatesTo(M_E*5)
}
func testOneConstantWithOneOperandAddConstant(){
calculatorBrain?.pushOperand(3)
calculatorBrain?.pushOperation("π")
calculatorBrain?.pushOperation("+")
calculatorBrain?.pushOperation("e")
calculatorBrain?.assertItEvaluatesTo(3*M_PI+M_E)
}
func testOneOperandAddConstantWithOneOperand(){
calculatorBrain?.pushOperand(3)
calculatorBrain?.pushOperation("+")
calculatorBrain?.pushOperand(5)
calculatorBrain?.pushOperation("e")
calculatorBrain?.assertItEvaluatesTo(3+5*M_E)
}
func testOneConstantWithOneOperandAddOneOperandAndOneConstant(){
calculatorBrain?.pushOperand(3)
calculatorBrain?.pushOperation("π")
calculatorBrain?.pushOperation("+")
calculatorBrain?.pushOperand(5)
calculatorBrain?.pushOperation("e")
calculatorBrain?.assertItEvaluatesTo(3*M_PI+5*M_E)
}
func testOneConstantWithOneOperandMultipliedByNumber(){
calculatorBrain?.pushOperand(3)
calculatorBrain?.pushOperation("π")
calculatorBrain?.pushOperation("*")
calculatorBrain?.pushOperand(5)
calculatorBrain?.assertItEvaluatesTo(3*M_PI*5)
}
}
| mit |
tjw/swift | test/multifile/require-layout3/main.swift | 4 | 310 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %S/../require-layout-generic-arg-subscript.swift %S/../Inputs/require-layout-generic-class.swift %s -o %t/test
// RUN: %target-run %t/test | %FileCheck %s
// REQUIRES: executable_test
func test() {
_ = AccessorTest()[Sub(1)]
}
// CHECK: Int
test()
| apache-2.0 |
leoMehlig/Charts | Charts/Classes/Data/Implementations/Standard/LineChartDataSet.swift | 2 | 5184 | //
// LineChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
public class LineChartDataSet: LineRadarChartDataSet, ILineChartDataSet
{
private func initialize()
{
// default color
circleColors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
}
public required init()
{
super.init()
initialize()
}
public override init(yVals: [ChartDataEntry]?, label: String?)
{
super.init(yVals: yVals, label: label)
initialize()
}
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
private var _cubicIntensity = CGFloat(0.2)
/// Intensity for cubic lines (min = 0.05, max = 1)
///
/// **default**: 0.2
public var cubicIntensity: CGFloat
{
get
{
return _cubicIntensity
}
set
{
_cubicIntensity = newValue
if (_cubicIntensity > 1.0)
{
_cubicIntensity = 1.0
}
if (_cubicIntensity < 0.05)
{
_cubicIntensity = 0.05
}
}
}
/// If true, cubic lines are drawn instead of linear
public var drawCubicEnabled = false
/// - returns: true if drawing cubic lines is enabled, false if not.
public var isDrawCubicEnabled: Bool { return drawCubicEnabled }
/// If true, stepped lines are drawn instead of linear
public var drawSteppedEnabled = false
/// - returns: true if drawing stepped lines is enabled, false if not.
public var isDrawSteppedEnabled: Bool { return drawSteppedEnabled }
/// The radius of the drawn circles.
public var circleRadius = CGFloat(8.0)
public var circleColors = [NSUIColor]()
/// - returns: the color at the given index of the DataSet's circle-color array.
/// Performs a IndexOutOfBounds check by modulus.
public func getCircleColor(var index: Int) -> NSUIColor?
{
let size = circleColors.count
index = index % size
if (index >= size)
{
return nil
}
return circleColors[index]
}
/// Sets the one and ONLY color that should be used for this DataSet.
/// Internally, this recreates the colors array and adds the specified color.
public func setCircleColor(color: NSUIColor)
{
circleColors.removeAll(keepCapacity: false)
circleColors.append(color)
}
/// Resets the circle-colors array and creates a new one
public func resetCircleColors(index: Int)
{
circleColors.removeAll(keepCapacity: false)
}
/// If true, drawing circles is enabled
public var drawCirclesEnabled = true
/// - returns: true if drawing circles for this DataSet is enabled, false if not
public var isDrawCirclesEnabled: Bool { return drawCirclesEnabled }
/// The color of the inner circle (the circle-hole).
public var circleHoleColor = NSUIColor.whiteColor()
/// True if drawing circles for this DataSet is enabled, false if not
public var drawCircleHoleEnabled = true
/// - returns: true if drawing the circle-holes is enabled, false if not.
public var isDrawCircleHoleEnabled: Bool { return drawCircleHoleEnabled }
/// This is how much (in pixels) into the dash pattern are we starting from.
public var lineDashPhase = CGFloat(0.0)
/// This is the actual dash pattern.
/// I.e. [2, 3] will paint [-- -- ]
/// [1, 3, 4, 2] will paint [- ---- - ---- ]
public var lineDashLengths: [CGFloat]?
/// formatter for customizing the position of the fill-line
private var _fillFormatter: ChartFillFormatter = ChartDefaultFillFormatter()
/// Sets a custom FillFormatter to the chart that handles the position of the filled-line for each DataSet. Set this to null to use the default logic.
public var fillFormatter: ChartFillFormatter?
{
get
{
return _fillFormatter
}
set
{
if newValue == nil
{
_fillFormatter = ChartDefaultFillFormatter()
}
else
{
_fillFormatter = newValue!
}
}
}
// MARK: NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = super.copyWithZone(zone) as! LineChartDataSet
copy.circleColors = circleColors
copy.circleRadius = circleRadius
copy.cubicIntensity = cubicIntensity
copy.lineDashPhase = lineDashPhase
copy.lineDashLengths = lineDashLengths
copy.drawCirclesEnabled = drawCirclesEnabled
copy.drawCubicEnabled = drawCubicEnabled
copy.drawSteppedEnabled = drawSteppedEnabled
return copy
}
}
| apache-2.0 |
rice-apps/wellbeing-app | app/Wellbeing/LaunchScreenViewController.swift | 1 | 527 | //
// LaunchScreenViewController.swift
// Wellbeing
//
// Copyright © 2017 Rice Apps. All rights reserved.
//
import Foundation
import UIKit
class LaunchScreenViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
toohotz/IQKeyboardManager | Demo/Swift_Demo/ViewController/SettingsViewController.swift | 1 | 25121 | //
// SettingsViewController.swift
// Demo
//
// Created by Iftekhar on 26/08/15.
// Copyright (c) 2015 Iftekhar. All rights reserved.
//
class SettingsViewController: UITableViewController, OptionsViewControllerDelegate, ColorPickerTextFieldDelegate {
let sectionTitles = ["UIKeyboard handling",
"IQToolbar handling",
"UIKeyboard appearance overriding",
"Resign first responder handling",
"UISound handling",
"IQKeyboardManager Debug"]
let keyboardManagerProperties = [["Enable", "Keyboard Distance From TextField", "Prevent Showing Bottom Blank Space"],
["Enable AutoToolbar","Toolbar Manage Behaviour","Should Toolbar Uses TextField TintColor","Should Show TextField Placeholder","Placeholder Font","Toolbar Tint Color","Toolbar Done BarButtonItem Image","Toolbar Done Button Text"],
["Override Keyboard Appearance","UIKeyboard Appearance"],
["Should Resign On Touch Outside"],
["Should Play Input Clicks"],
["Debugging logs in Console"]]
let keyboardManagerPropertyDetails = [["Enable/Disable IQKeyboardManager","Set keyboard distance from textField","Prevent to show blank space between UIKeyboard and View"],
["Automatic add the IQToolbar on UIKeyboard","AutoToolbar previous/next button managing behaviour","Uses textField's tintColor property for IQToolbar","Add the textField's placeholder text on IQToolbar","UIFont for IQToolbar placeholder text","Override toolbar tintColor property","Replace toolbar done button text with provided image","Override toolbar done button text"],
["Override the keyboardAppearance for all UITextField/UITextView","All the UITextField keyboardAppearance is set using this property"],
["Resigns Keyboard on touching outside of UITextField/View"],
["Plays inputClick sound on next/previous/done click"],
["Setting enableDebugging to YES/No to turn on/off debugging mode"]]
var selectedIndexPathForOptions : NSIndexPath?
@IBAction func doneAction (sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true, completion: nil)
}
/** UIKeyboard Handling */
func enableAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().enable = sender.on
self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Fade)
}
func keyboardDistanceFromTextFieldAction (sender: UIStepper) {
IQKeyboardManager.sharedManager().keyboardDistanceFromTextField = CGFloat(sender.value)
self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 1, inSection: 0)], withRowAnimation: UITableViewRowAnimation.None)
}
func preventShowingBottomBlankSpaceAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().preventShowingBottomBlankSpace = sender.on
self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Fade)
}
/** IQToolbar handling */
func enableAutoToolbarAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().enableAutoToolbar = sender.on
self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: UITableViewRowAnimation.Fade)
}
func shouldToolbarUsesTextFieldTintColorAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldToolbarUsesTextFieldTintColor = sender.on
}
func shouldShowTextFieldPlaceholder (sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder = sender.on
self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: UITableViewRowAnimation.Fade)
}
func toolbarDoneBarButtonItemImage (sender: UISwitch) {
if sender.on {
IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemImage = UIImage(named:"IQButtonBarArrowDown")
} else {
IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemImage = nil
}
self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: UITableViewRowAnimation.Fade)
}
/** "Keyboard appearance overriding */
func overrideKeyboardAppearanceAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().overrideKeyboardAppearance = sender.on
self.tableView.reloadSections(NSIndexSet(index: 2), withRowAnimation: UITableViewRowAnimation.Fade)
}
/** Resign first responder handling */
func shouldResignOnTouchOutsideAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = sender.on
}
/** Sound handling */
func shouldPlayInputClicksAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldPlayInputClicks = sender.on
}
/** Debugging */
func enableDebugging (sender: UISwitch) {
IQKeyboardManager.sharedManager().enableDebugging = sender.on
}
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sectionTitles.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch (section)
{
case 0:
if IQKeyboardManager.sharedManager().enable == true {
let properties = keyboardManagerProperties[section]
return properties.count
} else {
return 1
}
case 1:
if IQKeyboardManager.sharedManager().enableAutoToolbar == false {
return 1
} else if IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder == false {
return 4
} else {
let properties = keyboardManagerProperties[section]
return properties.count
}
case 2:
if IQKeyboardManager.sharedManager().overrideKeyboardAppearance == true {
let properties = keyboardManagerProperties[section]
return properties.count
} else {
return 1
}
case 3,4,5:
let properties = keyboardManagerProperties[section]
return properties.count
default:
return 0
}
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionTitles[section]
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch (indexPath.section) {
case 0:
switch (indexPath.row) {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().enable
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.enableAction(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCellWithIdentifier("StepperTableViewCell") as! StepperTableViewCell
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.stepper.value = Double(IQKeyboardManager.sharedManager().keyboardDistanceFromTextField)
cell.labelStepperValue.text = NSString(format: "%.0f", IQKeyboardManager.sharedManager().keyboardDistanceFromTextField) as String
cell.stepper.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.stepper.addTarget(self, action: #selector(self.keyboardDistanceFromTextFieldAction(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 2:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().preventShowingBottomBlankSpace
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.preventShowingBottomBlankSpaceAction(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
default:
break
}
case 1:
switch (indexPath.row) {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().enableAutoToolbar
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.enableAutoToolbarAction(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCellWithIdentifier("NavigationTableViewCell") as! NavigationTableViewCell
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
return cell
case 2:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldToolbarUsesTextFieldTintColor
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldToolbarUsesTextFieldTintColorAction(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 3:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldShowTextFieldPlaceholder(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 4:
let cell = tableView.dequeueReusableCellWithIdentifier("NavigationTableViewCell") as! NavigationTableViewCell
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
return cell
case 5:
let cell = tableView.dequeueReusableCellWithIdentifier("ColorTableViewCell") as! ColorTableViewCell
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.colorPickerTextField.selectedColor = IQKeyboardManager.sharedManager().toolbarTintColor
cell.colorPickerTextField.tag = 15
cell.colorPickerTextField.delegate = self
return cell
case 6:
let cell = tableView.dequeueReusableCellWithIdentifier("ImageSwitchTableViewCell") as! ImageSwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.arrowImageView.image = IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemImage
cell.switchEnable.on = IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemImage != nil
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.toolbarDoneBarButtonItemImage(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 7:
let cell = tableView.dequeueReusableCellWithIdentifier("TextFieldTableViewCell") as! TextFieldTableViewCell
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.textField.text = IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemText
cell.textField.tag = 17
cell.textField.delegate = self
return cell
default:
break
}
case 2:
switch (indexPath.row) {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().overrideKeyboardAppearance
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.overrideKeyboardAppearanceAction(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCellWithIdentifier("NavigationTableViewCell") as! NavigationTableViewCell
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
return cell
default:
break
}
case 3:
switch (indexPath.row) {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldResignOnTouchOutside
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldResignOnTouchOutsideAction(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
default:
break
}
case 4:
switch (indexPath.row) {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldPlayInputClicks
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldPlayInputClicksAction(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
default:
break
}
case 5:
switch (indexPath.row) {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().enableDebugging
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.enableDebugging(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
default:
break
}
default:
break
}
return UITableViewCell()
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
func colorPickerTextField(textField: ColorPickerTextField, selectedColorAttributes colorAttributes: [String : AnyObject]) {
if textField.tag == 15 {
let color = colorAttributes["color"] as! UIColor
if color.isEqual(UIColor.clearColor() == true) {
IQKeyboardManager.sharedManager().toolbarTintColor = nil
} else {
IQKeyboardManager.sharedManager().toolbarTintColor = color
}
}
}
func textFieldDidEndEditing(textField: UITextField) {
if textField.tag == 17 {
IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemText = textField.text?.characters.count != 0 ? textField.text : nil
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
if identifier == "OptionsViewController" {
let controller = segue.destinationViewController as! OptionsViewController
controller.delegate = self
let cell = sender as! UITableViewCell
selectedIndexPathForOptions = self.tableView.indexPathForCell(cell)
if let selectedIndexPath = selectedIndexPathForOptions {
if selectedIndexPath.section == 1 && selectedIndexPath.row == 1 {
controller.title = "Toolbar Manage Behaviour"
controller.options = ["IQAutoToolbar By Subviews","IQAutoToolbar By Tag","IQAutoToolbar By Position"]
controller.selectedIndex = IQKeyboardManager.sharedManager().toolbarManageBehaviour.hashValue
} else if selectedIndexPath.section == 1 && selectedIndexPath.row == 4 {
controller.title = "Fonts"
controller.options = ["Bold System Font","Italic system font","Regular"]
controller.selectedIndex = IQKeyboardManager.sharedManager().toolbarManageBehaviour.hashValue
let fonts = [UIFont.boldSystemFontOfSize(12),UIFont.italicSystemFontOfSize(12),UIFont.systemFontOfSize(12)]
if let placeholderFont = IQKeyboardManager.sharedManager().placeholderFont {
if let index = fonts.indexOf(placeholderFont) {
controller.selectedIndex = index
}
}
} else if selectedIndexPath.section == 2 && selectedIndexPath.row == 1 {
controller.title = "Keyboard Appearance"
controller.options = ["UIKeyboardAppearance Default","UIKeyboardAppearance Dark","UIKeyboardAppearance Light"]
controller.selectedIndex = IQKeyboardManager.sharedManager().keyboardAppearance.hashValue
}
}
}
}
}
func optionsViewController(controller: OptionsViewController, index: NSInteger) {
if let selectedIndexPath = selectedIndexPathForOptions {
if selectedIndexPath.section == 1 && selectedIndexPath.row == 1 {
IQKeyboardManager.sharedManager().toolbarManageBehaviour = IQAutoToolbarManageBehaviour(rawValue: index)!
} else if selectedIndexPath.section == 1 && selectedIndexPath.row == 4 {
let fonts = [UIFont.boldSystemFontOfSize(12),UIFont.italicSystemFontOfSize(12),UIFont.systemFontOfSize(12)]
IQKeyboardManager.sharedManager().placeholderFont = fonts[index]
} else if selectedIndexPath.section == 2 && selectedIndexPath.row == 1 {
IQKeyboardManager.sharedManager().keyboardAppearance = UIKeyboardAppearance(rawValue: index)!
}
}
}
}
| mit |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/1223-swift-lexer-leximpl.swift | 13 | 614 | // 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
var f = 1
private class B<C> {
let enum S<T> : P {
func f<T>() -> T -> T {
return { x in x 1 {
b[c][c] = 1
}
}
class A {
class func a() -> String {
let d: String = {
return self.a()
}()
func b(c) -> <d>(() -> d) {g: e where g.h == f.h> { Int = 0) {
}
let ceturn { e
p o p.s = {
}
{
u) {
o }
}
s m {
}
struct e<j : k> {n: j
}
func p(k: b) -> <i>(() -> i) -> b {
func j(d: h) -> <k>(() -> k) -> h {
| apache-2.0 |
Lomotif/lomotif-ios-httprequest | HttpRequestExample/HttpRequestExample/AppDelegate.swift | 1 | 2197 | //
// AppDelegate.swift
// HttpRequestExample
//
// Created by Kok Chung Law on 23/4/16.
// Copyright © 2016 Lomotif Private Limited. All rights reserved.
//
import UIKit
@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 throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
sora0077/NicoKit | Playground.playground/Contents.swift | 1 | 409 | //: Playground - noun: a place where people can play
import UIKit
import XCPlayground
import NicoKit
import LoggingKit
LOGGING_VERBOSE()
var str = "Hello, playgrouna"
let api = API()
let query = Search.Query(type: .Tag("Sims4"))
let search = Search(query: query)
api.request(search).onSuccess { response in
Logging.d(response.0.first)
}
let aaa = [17]
XCPSetExecutionShouldContinueIndefinitely()
| mit |
FsThatOne/OneSunChat | OneSunChat/OneSunChat/BasicClass/TableView/BasicTableViewItem.swift | 1 | 286 | //
// BasicTableViewItem.swift
// OneSunChat
//
// Created by 刘ToTo on 16/2/23.
// Copyright © 2016年 刘ToTo. All rights reserved.
//
import UIKit
class BasicTableViewItem: BasicDataModel {
var cellClass: String?
var cellStyle: UITableViewCellStyle = .default
}
| mit |
byu-oit/ios-byuSuite | byuSuite/Classes/Reusable/UI/ByuSearchViewController.swift | 2 | 4499 | //
// ByuSearchViewController.swift
// byuSuite
//
// Created by Erik Brady on 5/8/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
import UIKit
/*!
* @class ByuSearchViewController
* @brief A ByuViewController that helps with searching a table view
* @discussion This class was created in response to how the search display controller displays itself in the BYU app. With the structure of the BYU app and its features, every search bar is in a view controller that is part of a UINavigationController's stack. The transitions to display and hide the UISearchDisplayController aren't perfectly smooth due to the UINavigationController. This class contains the functionality of UISearchDisplayController without the extra controller and glitchy UI. The search bar remains in its location instead of moving up to replace the navigation bar.
HOW TO USE:
If your class uses a UISearchBar to search a table view, extend this class.
The implementation of this class conforms to the UISearchBarDelegate protocol; therefore, your class's implementation does not need to conform to it.
You must implement -searchBar:textDidChange:. This class only calls -searchBar:textDidChange: to invoke reloading the table view's data, but the logic needs to be located in your implementation. -searchBar:textDidChange: itself doesn't reload the table view data; therefore, your class's implementation must call the table view's -reloadData (e.g., [self.tableView reloadData];) at the end of the callback in order to work properly. Since UISearchDisplayController is not being used, the search results will not be loaded in a new table view; your table view needs to display the search results. The search results will change as the user types, which requires reloading the table view's data each time the text changes.
Any callbacks that you do not implement or override will use this class's implementation or UISearchBarDelegate's default implementation if this class has not implemented them.
*/
class ByuSearchViewController: ByuViewController2, UISearchBarDelegate {
/*
Since this class is an alternative to UISearchDisplayController, there needs to be some way
to indicate that the search bar is actively being edited. With a search display controller,
there is a property 'active' (e.g., self.searchDisplayController.active). searchIsActive's
purpose is to mimick self.searchDisplayController.active. Use it in the same
way self.searchDisplayController.active would be used.
*/
var searchIsActive = false
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchIsActive = false
/*
The following line is needed just in case -searchBarShouldEndEditing: never gets called.
(e.g., user clicks cancel after clicking the search button on their keyboard)
*/
searchBar.showsCancelButton = false
searchBar.resignFirstResponder()
searchBar.text = ""
//See explanation for this function in the documentation comment in ByuSearchableViewController.h
self.searchBar(searchBar, textDidChange: searchBar.text ?? "")
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
searchIsActive = true
searchBar.tintColor = UIColor.byuTint
searchBar.showsCancelButton = true
//See explanation for this function in the documentation comment in ByuSearchableViewController.h
self.searchBar(searchBar, textDidChange: searchBar.text ?? "")
return true
}
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.showsCancelButton = false
if searchBar.text == "" {
/*
This scenario is triggered when a user gives focus to the search bar text field, doesn't enter any search text, and
begins scrolling through the table view. Since the user didn't enter any specific search text, this just shows them
the original table view data.
*/
searchBarCancelButtonClicked(searchBar)
}
return true
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
//Implement this in your own view controller
}
}
| apache-2.0 |
lorentey/swift | test/multifile/protocol-conformance-objc.swift | 28 | 264 | // RUN: %target-swift-frontend -sdk %sdk -emit-ir -primary-file %s %S/Inputs/protocol-conformance-objc-other.swift -module-name test
// REQUIRES: objc_interop
import Foundation
@objc protocol Horse {
var hindEnd: Int { get set }
}
extension Pony : Horse {}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.