repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
esttorhe/RxSwift | RxSwift/RxSwift/Observables/Implementations/Map.swift | 1 | 3343 | //
// Map.swift
// Rx
//
// Created by Krunoslav Zaher on 3/15/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class MapSink<SourceType, O : ObserverType> : Sink<O>, ObserverType {
typealias ResultType = O.Element
typealias Element = SourceType
typealias Parent = Map<SourceType, ResultType>
let parent: Parent
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func select(element: SourceType) -> RxResult<ResultType> {
return abstractMethod()
}
func on(event: Event<SourceType>) {
let observer = super.observer
switch event {
case .Next(let element):
select(element).flatMap { value in
trySendNext(observer, value)
return SuccessResult
}.recoverWith { e -> RxResult<Void> in
trySendError(observer, e)
self.dispose()
return SuccessResult
}
case .Error(let error):
trySendError(observer, error)
self.dispose()
case .Completed:
trySendCompleted(observer)
self.dispose()
}
}
}
class MapSink1<SourceType, O: ObserverType> : MapSink<SourceType, O> {
typealias ResultType = O.Element
override init(parent: Map<SourceType, ResultType>, observer: O, cancel: Disposable) {
super.init(parent: parent, observer: observer, cancel: cancel)
}
override func select(element: SourceType) -> RxResult<ResultType> {
return (self.parent.selector1!)(element)
}
}
class MapSink2<SourceType, O: ObserverType> : MapSink<SourceType, O> {
typealias ResultType = O.Element
var index = 0
override init(parent: Map<SourceType, ResultType>, observer: O, cancel: Disposable) {
super.init(parent: parent, observer: observer, cancel: cancel)
}
override func select(element: SourceType) -> RxResult<ResultType> {
return (self.parent.selector2!)(element, index++)
}
}
class Map<SourceType, ResultType>: Producer<ResultType> {
typealias Selector1 = (SourceType) -> RxResult<ResultType>
typealias Selector2 = (SourceType, Int) -> RxResult<ResultType>
let source: Observable<SourceType>
let selector1: Selector1?
let selector2: Selector2?
init(source: Observable<SourceType>, selector: Selector1) {
self.source = source
self.selector1 = selector
self.selector2 = nil
}
init(source: Observable<SourceType>, selector: Selector2) {
self.source = source
self.selector2 = selector
self.selector1 = nil
}
override func run<O: ObserverType where O.Element == ResultType>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
if let _ = self.selector1 {
let sink = MapSink1(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return self.source.subscribeSafe(sink)
}
else {
let sink = MapSink2(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return self.source.subscribeSafe(sink)
}
}
} | mit | 3f4bf6b62e5c304176224beb652691cc | 29.678899 | 148 | 0.615016 | 4.475234 | false | false | false | false |
mkrisztian95/iOS | Pods/SideMenu/Pod/Classes/SideMenuTransition.swift | 2 | 23294 | //
// SideMenuTransition.swift
// Pods
//
// Created by Jon Kent on 1/14/16.
//
//
import UIKit
internal class SideMenuTransition: UIPercentDrivenInteractiveTransition, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
private var presenting = false
private var interactive = false
private static weak var originalSuperview: UIView?
private static var switchMenus = false
internal static let singleton = SideMenuTransition()
internal static var presentDirection: UIRectEdge = .Left;
internal static weak var tapView: UIView!
internal static weak var statusBarView: UIView?
// prevent instantiation
private override init() {}
private class var viewControllerForPresentedMenu: UIViewController? {
get {
return SideMenuManager.menuLeftNavigationController?.presentingViewController != nil ? SideMenuManager.menuLeftNavigationController?.presentingViewController : SideMenuManager.menuRightNavigationController?.presentingViewController
}
}
private class var visibleViewController: UIViewController? {
get {
return getVisibleViewControllerFromViewController(UIApplication.sharedApplication().keyWindow?.rootViewController)
}
}
private class func getVisibleViewControllerFromViewController(viewController: UIViewController?) -> UIViewController? {
if let navigationController = viewController as? UINavigationController {
return getVisibleViewControllerFromViewController(navigationController.visibleViewController)
} else if let tabBarController = viewController as? UITabBarController {
return getVisibleViewControllerFromViewController(tabBarController.selectedViewController)
} else if let presentedViewController = viewController?.presentedViewController {
return getVisibleViewControllerFromViewController(presentedViewController)
}
return viewController
}
class func handlePresentMenuLeftScreenEdge(edge: UIScreenEdgePanGestureRecognizer) {
SideMenuTransition.presentDirection = .Left
handlePresentMenuPan(edge)
}
class func handlePresentMenuRightScreenEdge(edge: UIScreenEdgePanGestureRecognizer) {
SideMenuTransition.presentDirection = .Right
handlePresentMenuPan(edge)
}
class func handlePresentMenuPan(pan: UIPanGestureRecognizer) {
// how much distance have we panned in reference to the parent view?
guard let view = viewControllerForPresentedMenu != nil ? viewControllerForPresentedMenu?.view : pan.view else {
return
}
let transform = view.transform
view.transform = CGAffineTransformIdentity
let translation = pan.translationInView(pan.view!)
view.transform = transform
// do some math to translate this to a percentage based value
if !singleton.interactive {
if translation.x == 0 {
return // not sure which way the user is swiping yet, so do nothing
}
if !(pan is UIScreenEdgePanGestureRecognizer) {
SideMenuTransition.presentDirection = translation.x > 0 ? .Left : .Right
}
if let menuViewController = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController : SideMenuManager.menuRightNavigationController,
visibleViewController = visibleViewController {
singleton.interactive = true
visibleViewController.presentViewController(menuViewController, animated: true, completion: nil)
}
}
let direction: CGFloat = SideMenuTransition.presentDirection == .Left ? 1 : -1
let distance = translation.x / SideMenuManager.menuWidth
// now lets deal with different states that the gesture recognizer sends
switch (pan.state) {
case .Began, .Changed:
if pan is UIScreenEdgePanGestureRecognizer {
singleton.updateInteractiveTransition(min(distance * direction, 1))
} else if distance > 0 && SideMenuTransition.presentDirection == .Right && SideMenuManager.menuLeftNavigationController != nil {
SideMenuTransition.presentDirection = .Left
switchMenus = true
singleton.cancelInteractiveTransition()
} else if distance < 0 && SideMenuTransition.presentDirection == .Left && SideMenuManager.menuRightNavigationController != nil {
SideMenuTransition.presentDirection = .Right
switchMenus = true
singleton.cancelInteractiveTransition()
} else {
singleton.updateInteractiveTransition(min(distance * direction, 1))
}
default:
singleton.interactive = false
view.transform = CGAffineTransformIdentity
let velocity = pan.velocityInView(pan.view!).x * direction
view.transform = transform
if velocity >= 100 || velocity >= -50 && abs(distance) >= 0.5 {
// bug workaround: animation briefly resets after call to finishInteractiveTransition() but before animateTransition completion is called.
if NSProcessInfo().operatingSystemVersion.majorVersion == 8 && singleton.percentComplete > 1 - CGFloat(FLT_EPSILON) {
singleton.updateInteractiveTransition(0.9999)
}
singleton.finishInteractiveTransition()
} else {
singleton.cancelInteractiveTransition()
}
}
}
class func handleHideMenuPan(pan: UIPanGestureRecognizer) {
let translation = pan.translationInView(pan.view!)
let direction:CGFloat = SideMenuTransition.presentDirection == .Left ? -1 : 1
let distance = translation.x / SideMenuManager.menuWidth * direction
switch (pan.state) {
case .Began:
singleton.interactive = true
viewControllerForPresentedMenu?.dismissViewControllerAnimated(true, completion: nil)
case .Changed:
singleton.updateInteractiveTransition(max(min(distance, 1), 0))
default:
singleton.interactive = false
let velocity = pan.velocityInView(pan.view!).x * direction
if velocity >= 100 || velocity >= -50 && distance >= 0.5 {
// bug workaround: animation briefly resets after call to finishInteractiveTransition() but before animateTransition completion is called.
if NSProcessInfo().operatingSystemVersion.majorVersion == 8 && singleton.percentComplete > 1 - CGFloat(FLT_EPSILON) {
singleton.updateInteractiveTransition(0.9999)
}
singleton.finishInteractiveTransition()
} else {
singleton.cancelInteractiveTransition()
}
}
}
class func handleHideMenuTap(tap: UITapGestureRecognizer) {
viewControllerForPresentedMenu?.dismissViewControllerAnimated(true, completion: nil)
}
internal class func hideMenuStart() {
NSNotificationCenter.defaultCenter().removeObserver(SideMenuTransition.singleton)
let mainViewController = SideMenuTransition.viewControllerForPresentedMenu!
let menuView = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController!.view : SideMenuManager.menuRightNavigationController!.view
menuView.transform = CGAffineTransformIdentity
mainViewController.view.transform = CGAffineTransformIdentity
mainViewController.view.alpha = 1
SideMenuTransition.tapView.frame = CGRectMake(0, 0, mainViewController.view.frame.width, mainViewController.view.frame.height)
menuView.frame.origin.y = 0
menuView.frame.size.width = SideMenuManager.menuWidth
menuView.frame.size.height = mainViewController.view.frame.height
SideMenuTransition.statusBarView?.frame = UIApplication.sharedApplication().statusBarFrame
SideMenuTransition.statusBarView?.alpha = 0
switch SideMenuManager.menuPresentMode {
case .ViewSlideOut:
menuView.alpha = 1 - SideMenuManager.menuAnimationFadeStrength
menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? 0 : mainViewController.view.frame.width - SideMenuManager.menuWidth
mainViewController.view.frame.origin.x = 0
menuView.transform = CGAffineTransformMakeScale(SideMenuManager.menuAnimationTransformScaleFactor, SideMenuManager.menuAnimationTransformScaleFactor)
case .ViewSlideInOut:
menuView.alpha = 1
menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? -menuView.frame.width : mainViewController.view.frame.width
mainViewController.view.frame.origin.x = 0
case .MenuSlideIn:
menuView.alpha = 1
menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? -menuView.frame.width : mainViewController.view.frame.width
case .MenuDissolveIn:
menuView.alpha = 0
menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? 0 : mainViewController.view.frame.width - SideMenuManager.menuWidth
mainViewController.view.frame.origin.x = 0
}
}
internal class func hideMenuComplete() {
let mainViewController = SideMenuTransition.viewControllerForPresentedMenu!
let menuView = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController!.view : SideMenuManager.menuRightNavigationController!.view
SideMenuTransition.tapView.removeFromSuperview()
SideMenuTransition.statusBarView?.removeFromSuperview()
mainViewController.view.motionEffects.removeAll()
mainViewController.view.layer.shadowOpacity = 0
menuView.layer.shadowOpacity = 0
if let topNavigationController = mainViewController as? UINavigationController {
topNavigationController.interactivePopGestureRecognizer!.enabled = true
}
originalSuperview?.addSubview(mainViewController.view)
}
internal class func presentMenuStart(forSize size: CGSize = SideMenuManager.appScreenRect.size) {
guard let menuView = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController?.view : SideMenuManager.menuRightNavigationController?.view else {
return
}
let mainViewController = SideMenuTransition.viewControllerForPresentedMenu!
menuView.transform = CGAffineTransformIdentity
mainViewController.view.transform = CGAffineTransformIdentity
menuView.frame.size.width = SideMenuManager.menuWidth
menuView.frame.size.height = size.height
menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? 0 : size.width - SideMenuManager.menuWidth
SideMenuTransition.statusBarView?.frame = UIApplication.sharedApplication().statusBarFrame
SideMenuTransition.statusBarView?.alpha = 1
switch SideMenuManager.menuPresentMode {
case .ViewSlideOut:
menuView.alpha = 1
let direction:CGFloat = SideMenuTransition.presentDirection == .Left ? 1 : -1
mainViewController.view.frame.origin.x = direction * (menuView.frame.width)
mainViewController.view.layer.shadowColor = SideMenuManager.menuShadowColor.CGColor
mainViewController.view.layer.shadowRadius = SideMenuManager.menuShadowRadius
mainViewController.view.layer.shadowOpacity = SideMenuManager.menuShadowOpacity
mainViewController.view.layer.shadowOffset = CGSizeMake(0, 0)
case .ViewSlideInOut:
menuView.alpha = 1
menuView.layer.shadowColor = SideMenuManager.menuShadowColor.CGColor
menuView.layer.shadowRadius = SideMenuManager.menuShadowRadius
menuView.layer.shadowOpacity = SideMenuManager.menuShadowOpacity
menuView.layer.shadowOffset = CGSizeMake(0, 0)
let direction:CGFloat = SideMenuTransition.presentDirection == .Left ? 1 : -1
mainViewController.view.frame.origin.x = direction * (menuView.frame.width)
mainViewController.view.transform = CGAffineTransformMakeScale(SideMenuManager.menuAnimationTransformScaleFactor, SideMenuManager.menuAnimationTransformScaleFactor)
mainViewController.view.alpha = 1 - SideMenuManager.menuAnimationFadeStrength
case .MenuSlideIn, .MenuDissolveIn:
menuView.alpha = 1
menuView.layer.shadowColor = SideMenuManager.menuShadowColor.CGColor
menuView.layer.shadowRadius = SideMenuManager.menuShadowRadius
menuView.layer.shadowOpacity = SideMenuManager.menuShadowOpacity
menuView.layer.shadowOffset = CGSizeMake(0, 0)
mainViewController.view.frame = CGRectMake(0, 0, size.width, size.height)
mainViewController.view.transform = CGAffineTransformMakeScale(SideMenuManager.menuAnimationTransformScaleFactor, SideMenuManager.menuAnimationTransformScaleFactor)
mainViewController.view.alpha = 1 - SideMenuManager.menuAnimationFadeStrength
}
}
internal class func presentMenuComplete() {
NSNotificationCenter.defaultCenter().addObserver(SideMenuTransition.singleton, selector:#selector(SideMenuTransition.applicationDidEnterBackgroundNotification), name: UIApplicationDidEnterBackgroundNotification, object: nil)
let mainViewController = SideMenuTransition.viewControllerForPresentedMenu!
switch SideMenuManager.menuPresentMode {
case .MenuSlideIn, .MenuDissolveIn, .ViewSlideInOut:
if SideMenuManager.menuParallaxStrength != 0 {
let horizontal = UIInterpolatingMotionEffect(keyPath: "center.x", type: .TiltAlongHorizontalAxis)
horizontal.minimumRelativeValue = -SideMenuManager.menuParallaxStrength
horizontal.maximumRelativeValue = SideMenuManager.menuParallaxStrength
let vertical = UIInterpolatingMotionEffect(keyPath: "center.y", type: .TiltAlongVerticalAxis)
vertical.minimumRelativeValue = -SideMenuManager.menuParallaxStrength
vertical.maximumRelativeValue = SideMenuManager.menuParallaxStrength
let group = UIMotionEffectGroup()
group.motionEffects = [horizontal, vertical]
mainViewController.view.addMotionEffect(group)
}
case .ViewSlideOut: break;
}
if let topNavigationController = mainViewController as? UINavigationController {
topNavigationController.interactivePopGestureRecognizer!.enabled = false
}
}
// MARK: UIViewControllerAnimatedTransitioning protocol methods
// animate a change from one viewcontroller to another
internal func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
// get reference to our fromView, toView and the container view that we should perform the transition in
let container = transitionContext.containerView()!
if let menuBackgroundColor = SideMenuManager.menuAnimationBackgroundColor {
container.backgroundColor = menuBackgroundColor
}
// create a tuple of our screens
let screens : (from:UIViewController, to:UIViewController) = (transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!, transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!)
// assign references to our menu view controller and the 'bottom' view controller from the tuple
// remember that our menuViewController will alternate between the from and to view controller depending if we're presenting or dismissing
let menuViewController = (!presenting ? screens.from : screens.to)
let topViewController = !presenting ? screens.to : screens.from
let menuView = menuViewController.view
let topView = topViewController.view
// prepare menu items to slide in
if presenting {
let tapView = UIView()
tapView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
let exitPanGesture = UIPanGestureRecognizer()
exitPanGesture.addTarget(SideMenuTransition.self, action:#selector(SideMenuTransition.handleHideMenuPan(_:)))
let exitTapGesture = UITapGestureRecognizer()
exitTapGesture.addTarget(SideMenuTransition.self, action: #selector(SideMenuTransition.handleHideMenuTap(_:)))
tapView.addGestureRecognizer(exitPanGesture)
tapView.addGestureRecognizer(exitTapGesture)
SideMenuTransition.tapView = tapView
SideMenuTransition.originalSuperview = topView.superview
// add the both views to our view controller
switch SideMenuManager.menuPresentMode {
case .ViewSlideOut:
container.addSubview(menuView)
container.addSubview(topView)
topView.addSubview(tapView)
case .MenuSlideIn, .MenuDissolveIn, .ViewSlideInOut:
container.addSubview(topView)
container.addSubview(tapView)
container.addSubview(menuView)
}
if SideMenuManager.menuFadeStatusBar {
let blackBar = UIView()
if let menuShrinkBackgroundColor = SideMenuManager.menuAnimationBackgroundColor {
blackBar.backgroundColor = menuShrinkBackgroundColor
} else {
blackBar.backgroundColor = UIColor.blackColor()
}
blackBar.userInteractionEnabled = false
container.addSubview(blackBar)
SideMenuTransition.statusBarView = blackBar
}
SideMenuTransition.hideMenuStart() // offstage for interactive
}
// perform the animation!
let duration = transitionDuration(transitionContext)
let options: UIViewAnimationOptions = interactive ? .CurveLinear : .CurveEaseInOut
UIView.animateWithDuration(duration, delay: 0, options: options, animations: { () -> Void in
if self.presenting {
SideMenuTransition.presentMenuStart() // onstage items: slide in
}
else {
SideMenuTransition.hideMenuStart()
}
}) { (finished) -> Void in
// tell our transitionContext object that we've finished animating
if transitionContext.transitionWasCancelled() {
let viewControllerForPresentedMenu = SideMenuTransition.viewControllerForPresentedMenu
if self.presenting {
SideMenuTransition.hideMenuComplete()
} else {
SideMenuTransition.presentMenuComplete()
}
transitionContext.completeTransition(false)
if SideMenuTransition.switchMenus {
SideMenuTransition.switchMenus = false
viewControllerForPresentedMenu?.presentViewController(SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController! : SideMenuManager.menuRightNavigationController!, animated: true, completion: nil)
}
return
}
if self.presenting {
SideMenuTransition.presentMenuComplete()
transitionContext.completeTransition(true)
switch SideMenuManager.menuPresentMode {
case .ViewSlideOut:
container.addSubview(topView)
case .MenuSlideIn, .MenuDissolveIn, .ViewSlideInOut:
container.insertSubview(topView, atIndex: 0)
}
if let statusBarView = SideMenuTransition.statusBarView {
container.bringSubviewToFront(statusBarView)
}
return
}
SideMenuTransition.hideMenuComplete()
transitionContext.completeTransition(true)
menuView.removeFromSuperview()
}
}
// return how many seconds the transiton animation will take
internal func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return presenting ? SideMenuManager.menuAnimationPresentDuration : SideMenuManager.menuAnimationDismissDuration
}
// MARK: UIViewControllerTransitioningDelegate protocol methods
// return the animator when presenting a viewcontroller
// rememeber that an animator (or animation controller) is any object that aheres to the UIViewControllerAnimatedTransitioning protocol
internal func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = true
SideMenuTransition.presentDirection = presented == SideMenuManager.menuLeftNavigationController ? .Left : .Right
return self
}
// return the animator used when dismissing from a viewcontroller
internal func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
presenting = false
return self
}
internal func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
// if our interactive flag is true, return the transition manager object
// otherwise return nil
return interactive ? SideMenuTransition.singleton : nil
}
internal func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactive ? SideMenuTransition.singleton : nil
}
internal func applicationDidEnterBackgroundNotification() {
if let menuViewController: UINavigationController = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController : SideMenuManager.menuRightNavigationController {
SideMenuTransition.hideMenuStart()
SideMenuTransition.hideMenuComplete()
menuViewController.dismissViewControllerAnimated(false, completion: nil)
}
}
}
| apache-2.0 | a4527111e2779859108e587e3f468f8b | 52.549425 | 253 | 0.679875 | 6.914218 | false | false | false | false |
TENDIGI/Obsidian-iOS-SDK | Obsidian-iOS-SDK/Logger.swift | 1 | 962 | //
// Logger.swift
// ObsidianSDK
//
// Created by Nick Lee on 8/3/15.
// Copyright (c) 2015 TENDIGI, LLC. All rights reserved.
//
import Foundation
internal struct Logger {
private static let dateFormatter: NSDateFormatter = {
let defaultDateFormatter = NSDateFormatter()
defaultDateFormatter.locale = NSLocale.currentLocale()
defaultDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
return defaultDateFormatter
}()
private static func log(level: String, source: String, message: String) {
let dateString = dateFormatter.stringFromDate(NSDate())
print("\(dateString) [\(level)] [\(source)] : \(message)")
}
internal static func info(source: String, _ message: String) {
log("Info", source: source, message: message)
}
internal static func http(source: String, _ message: String) {
log("HTTP", source: source, message: message)
}
}
| mit | b13809f3543e0bfe2835e76617b10fff | 28.151515 | 77 | 0.642412 | 4.313901 | false | true | false | false |
manavgabhawala/swift | test/SILGen/cf.swift | 1 | 5015 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -import-cf-types -sdk %S/Inputs %s -emit-silgen -o - | %FileCheck %s
// REQUIRES: objc_interop
import CoreCooling
// CHECK: sil hidden @_T02cf8useEmAllySo16CCMagnetismModelCF :
// CHECK: bb0([[ARG:%.*]] : $CCMagnetismModel):
func useEmAll(_ model: CCMagnetismModel) {
// CHECK: function_ref @CCPowerSupplyGetDefault : $@convention(c) () -> @autoreleased Optional<CCPowerSupply>
let power = CCPowerSupplyGetDefault()
// CHECK: function_ref @CCRefrigeratorCreate : $@convention(c) (Optional<CCPowerSupply>) -> Optional<Unmanaged<CCRefrigerator>>
let unmanagedFridge = CCRefrigeratorCreate(power)
// CHECK: function_ref @CCRefrigeratorSpawn : $@convention(c) (Optional<CCPowerSupply>) -> @owned Optional<CCRefrigerator>
let managedFridge = CCRefrigeratorSpawn(power)
// CHECK: function_ref @CCRefrigeratorOpen : $@convention(c) (Optional<CCRefrigerator>) -> ()
CCRefrigeratorOpen(managedFridge)
// CHECK: function_ref @CCRefrigeratorCopy : $@convention(c) (Optional<CCRefrigerator>) -> @owned Optional<CCRefrigerator>
let copy = CCRefrigeratorCopy(managedFridge)
// CHECK: function_ref @CCRefrigeratorClone : $@convention(c) (Optional<CCRefrigerator>) -> @autoreleased Optional<CCRefrigerator>
let clone = CCRefrigeratorClone(managedFridge)
// CHECK: function_ref @CCRefrigeratorDestroy : $@convention(c) (@owned Optional<CCRefrigerator>) -> ()
CCRefrigeratorDestroy(clone)
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.refrigerator!1.foreign : (CCMagnetismModel) -> () -> Unmanaged<CCRefrigerator>!, $@convention(objc_method) (CCMagnetismModel) -> Optional<Unmanaged<CCRefrigerator>>
let f0 = model.refrigerator()
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.getRefrigerator!1.foreign : (CCMagnetismModel) -> () -> CCRefrigerator!, $@convention(objc_method) (CCMagnetismModel) -> @autoreleased Optional<CCRefrigerator>
let f1 = model.getRefrigerator()
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.takeRefrigerator!1.foreign : (CCMagnetismModel) -> () -> CCRefrigerator!, $@convention(objc_method) (CCMagnetismModel) -> @owned Optional<CCRefrigerator>
let f2 = model.takeRefrigerator()
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.borrowRefrigerator!1.foreign : (CCMagnetismModel) -> () -> CCRefrigerator!, $@convention(objc_method) (CCMagnetismModel) -> @autoreleased Optional<CCRefrigerator>
let f3 = model.borrowRefrigerator()
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.setRefrigerator!1.foreign : (CCMagnetismModel) -> (CCRefrigerator!) -> (), $@convention(objc_method) (Optional<CCRefrigerator>, CCMagnetismModel) -> ()
model.setRefrigerator(copy)
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.giveRefrigerator!1.foreign : (CCMagnetismModel) -> (CCRefrigerator!) -> (), $@convention(objc_method) (@owned Optional<CCRefrigerator>, CCMagnetismModel) -> ()
model.giveRefrigerator(copy)
// rdar://16846555
let prop: CCRefrigerator = model.fridgeProp
}
// Ensure that accessors are emitted for fields used as protocol witnesses.
protocol Impedance {
associatedtype Component
var real: Component { get }
var imag: Component { get }
}
extension CCImpedance: Impedance {}
// CHECK-LABEL: sil hidden [transparent] [fragile] [thunk] @_T0SC11CCImpedanceV2cf9ImpedanceA2cDP4real9ComponentQzfgTW
// CHECK-LABEL: sil shared [transparent] [fragile] @_T0SC11CCImpedanceV4realSdfg
// CHECK-LABEL: sil hidden [transparent] [fragile] [thunk] @_T0SC11CCImpedanceV2cf9ImpedanceA2cDP4imag9ComponentQzfgTW
// CHECK-LABEL: sil shared [transparent] [fragile] @_T0SC11CCImpedanceV4imagSdfg
class MyMagnetism : CCMagnetismModel {
// CHECK-LABEL: sil hidden [thunk] @_T02cf11MyMagnetismC15getRefrigerator{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (MyMagnetism) -> @autoreleased CCRefrigerator
override func getRefrigerator() -> CCRefrigerator {
return super.getRefrigerator()
}
// CHECK-LABEL: sil hidden [thunk] @_T02cf11MyMagnetismC16takeRefrigerator{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (MyMagnetism) -> @owned CCRefrigerator
override func takeRefrigerator() -> CCRefrigerator {
return super.takeRefrigerator()
}
// CHECK-LABEL: sil hidden [thunk] @_T02cf11MyMagnetismC18borrowRefrigerator{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (MyMagnetism) -> @autoreleased CCRefrigerator
override func borrowRefrigerator() -> CCRefrigerator {
return super.borrowRefrigerator()
}
}
| apache-2.0 | 16196727f1c46ce5c3c0c8ee49493a73 | 55.988636 | 254 | 0.73998 | 4.008793 | false | false | false | false |
exsortis/PnutKit | Sources/PnutKit/Models/Explore.swift | 1 | 1041 | //
// Explore.swift
// Yawp
//
// Created by Paul Schifferer on 19/5/17.
// Copyright © 2017 Pilgrimage Software. All rights reserved.
//
import Foundation
public struct Explore {
public var desc : String
public var link : URL
public var slug : String
public var title : String
}
extension Explore : Serializable {
public init?(from dict : JSONDictionary) {
guard let desc = dict["description"] as? String,
let l = dict["link"] as? String,
let link = URL(string: l),
let slug = dict["slug"] as? String,
let title = dict["title"] as? String
else { return nil }
self.desc = desc
self.link = link
self.slug = slug
self.title = title
}
public func toDictionary() -> JSONDictionary {
let dict : JSONDictionary = [
"description" : desc,
"link" : link.absoluteString,
"slug" : slug,
"title" : title,
]
return dict
}
}
| mit | 7f151eb37a409412ad37b0794291073f | 21.608696 | 62 | 0.546154 | 4.193548 | false | false | false | false |
rsmoz/swift-corelibs-foundation | Foundation/NSNull.swift | 1 | 1175 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
public class NSNull : NSObject, NSCopying, NSSecureCoding {
public override func copy() -> AnyObject {
return copyWithZone(nil)
}
public func copyWithZone(zone: NSZone) -> AnyObject {
return self
}
public override init() {
// Nothing to do here
}
public required init?(coder aDecoder: NSCoder) {
// Nothing to do here
}
public func encodeWithCoder(aCoder: NSCoder) {
// Nothing to do here
}
public static func supportsSecureCoding() -> Bool {
return true
}
public override func isEqual(object: AnyObject?) -> Bool {
return object is NSNull
}
}
public func ===(lhs: NSNull?, rhs: NSNull?) -> Bool {
guard let _ = lhs, let _ = rhs else { return false }
return true
}
| apache-2.0 | 1bb4fa7c1e1ce3846c0ebe5b80f03176 | 25.111111 | 78 | 0.631489 | 4.571984 | false | false | false | false |
codestergit/swift | test/SILGen/implicitly_unwrapped_optional.swift | 3 | 3382 | // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
func foo(f f: (() -> ())!) {
var f: (() -> ())! = f
f?()
}
// CHECK: sil hidden @{{.*}}foo{{.*}} : $@convention(thin) (@owned Optional<@callee_owned () -> ()>) -> () {
// CHECK: bb0([[T0:%.*]] : $Optional<@callee_owned () -> ()>):
// CHECK: [[F:%.*]] = alloc_box ${ var Optional<@callee_owned () -> ()> }
// CHECK: [[PF:%.*]] = project_box [[F]]
// CHECK: [[BORROWED_T0:%.*]] = begin_borrow [[T0]]
// CHECK: [[T0_COPY:%.*]] = copy_value [[BORROWED_T0]]
// CHECK: store [[T0_COPY]] to [init] [[PF]]
// CHECK: end_borrow [[BORROWED_T0]] from [[T0]]
// CHECK: [[T1:%.*]] = select_enum_addr [[PF]]
// CHECK: cond_br [[T1]], bb1, bb3
// If it does, project and load the value out of the implicitly unwrapped
// optional...
// CHECK: bb1:
// CHECK-NEXT: [[FN0_ADDR:%.*]] = unchecked_take_enum_data_addr [[PF]]
// CHECK-NEXT: [[FN0:%.*]] = load [copy] [[FN0_ADDR]]
// .... then call it
// CHECK: apply [[FN0]]() : $@callee_owned () -> ()
// CHECK: br bb2
// CHECK: bb2(
// CHECK: destroy_value [[F]]
// CHECK: destroy_value [[T0]]
// CHECK: return
// CHECK: bb3:
// CHECK: enum $Optional<()>, #Optional.none!enumelt
// CHECK: br bb2
// The rest of this is tested in optional.swift
// } // end sil function '{{.*}}foo{{.*}}'
func wrap<T>(x x: T) -> T! { return x }
// CHECK-LABEL: sil hidden @_T029implicitly_unwrapped_optional16wrap_then_unwrap{{[_0-9a-zA-Z]*}}F
func wrap_then_unwrap<T>(x x: T) -> T {
// CHECK: switch_enum_addr {{%.*}}, case #Optional.some!enumelt.1: [[OK:bb[0-9]+]], case #Optional.none!enumelt: [[FAIL:bb[0-9]+]]
// CHECK: [[FAIL]]:
// CHECK: unreachable
// CHECK: [[OK]]:
return wrap(x: x)!
}
// CHECK-LABEL: sil hidden @_T029implicitly_unwrapped_optional10tuple_bindSSSgSQySi_SStG1x_tF : $@convention(thin) (@owned Optional<(Int, String)>) -> @owned Optional<String> {
func tuple_bind(x x: (Int, String)!) -> String? {
return x?.1
// CHECK: cond_br {{%.*}}, [[NONNULL:bb[0-9]+]], [[NULL:bb[0-9]+]]
// CHECK: [[NONNULL]]:
// CHECK: [[STRING:%.*]] = tuple_extract {{%.*}} : $(Int, String), 1
// CHECK-NOT: destroy_value [[STRING]]
}
// CHECK-LABEL: sil hidden @_T029implicitly_unwrapped_optional011tuple_bind_a1_B0SSSQySi_SStG1x_tF
func tuple_bind_implicitly_unwrapped(x x: (Int, String)!) -> String {
return x.1
}
func return_any() -> AnyObject! { return nil }
func bind_any() {
let object : AnyObject? = return_any()
}
// CHECK-LABEL: sil hidden @_T029implicitly_unwrapped_optional6sr3758yyF
func sr3758() {
// Verify that there are no additional reabstractions introduced.
// CHECK: [[CLOSURE:%.+]] = function_ref @_T029implicitly_unwrapped_optional6sr3758yyFySQyypGcfU_ : $@convention(thin) (@in Optional<Any>) -> ()
// CHECK: [[F:%.+]] = thin_to_thick_function [[CLOSURE]] : $@convention(thin) (@in Optional<Any>) -> () to $@callee_owned (@in Optional<Any>) -> ()
// CHECK: [[BORROWED_F:%.*]] = begin_borrow [[F]]
// CHECK: [[CALLEE:%.+]] = copy_value [[BORROWED_F]] : $@callee_owned (@in Optional<Any>) -> ()
// CHECK: = apply [[CALLEE]]({{%.+}}) : $@callee_owned (@in Optional<Any>) -> ()
// CHECK: end_borrow [[BORROWED_F]] from [[F]]
// CHECK: destroy_value [[F]]
let f: ((Any?) -> Void) = { (arg: Any!) in }
f(nil)
} // CHECK: end sil function '_T029implicitly_unwrapped_optional6sr3758yyF'
| apache-2.0 | 9cb7c2bf35e771a922a67c4f95f580a5 | 42.922078 | 176 | 0.584565 | 3.046847 | false | false | false | false |
GitHubCha2016/ZLSwiftFM | ZLSwiftFM/ZLSwiftFM/Classes/Main/Const.swift | 1 | 2012 | //
// Const.swift
// ZLSwiftFM
//
// Created by ZXL on 2017/5/15.
// Copyright © 2017年 zl. All rights reserved.
//
import Foundation
import UIKit
import SnapKit
// 当前系统版本
let kVersion = (UIDevice.current.systemVersion as NSString).floatValue
// 屏幕宽度
let kScreenHeight = UIScreen.main.bounds.height
// 屏幕高度
let kScreenWidth = UIScreen.main.bounds.width
/// iPhone 5
let isIPhone5 = kScreenHeight == 568 ? true : false
/// iPhone 6
let isIPhone6 = kScreenHeight == 667 ? true : false
/// iPhone 6P
let isIPhone6P = kScreenHeight == 736 ? true : false
// MARK:- 颜色方法
func RGBAColor (_ r:CGFloat, _ g:CGFloat, _ b:CGFloat, a:CGFloat) -> UIColor {
return UIColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a)
}
// MARK:- 随机颜色
func randomColor() -> UIColor {
let red = CGFloat(arc4random_uniform(255))/CGFloat(255.0)
let green = CGFloat( arc4random_uniform(255))/CGFloat(255.0)
let blue = CGFloat(arc4random_uniform(255))/CGFloat(255.0)
return UIColor.init(red:red, green:green, blue:blue , alpha: 1)
}
// MARK:- 全局颜色
func kGlobalColor() -> UIColor {
return RGBAColor(255, 255, 255, a: 1)
}
func WIDTH(_ size:Float) -> CGFloat
{
return CGFloat(size / 375.0 * Float(UIScreen.main.bounds.size.width))
}
func HEIGHT(_ size:Float) -> CGFloat
{
return CGFloat(size / 667.0 * Float(UIScreen.main.bounds.size.height))
}
/// 自定义Log
func ZXLLog(file: String = #file, line: Int = #line, function: String = #function, _ items: Any) {
#if DEBUG
print("文件: \((file as NSString).lastPathComponent), 行数: \(line), 函数: \(function): => \(items) \n")
#endif
}
func customLog<T>(_ message: T, fileName: String = #file, methodName: String = #function, lineNumber: Int = #line)
{
#if DEBUG
let str : String = (fileName as NSString).pathComponents.last!.replacingOccurrences(of: "swift", with: "")
print("\(str)\(methodName)[\(lineNumber)]:\(message)")
#endif
}
| mit | 3bacb2c52ea0d3d2a9dd6454ef477824 | 27.514706 | 115 | 0.66065 | 3.297619 | false | false | false | false |
RnDity/NavigationFlowCoordinator | NavigationFlowCoordinatorExample/NavigationFlowCoordinatorExample/MovieDetailsCoordinator.swift | 1 | 1452 | //
// MovieDetailsCoordinator.swift
// NavigationFlowCoordinatorExample
//
// Created and developed by RnDity sp. z o.o. in 2018.
// Copyright © 2018 RnDity sp. z o.o. All rights reserved.
//
import Foundation
import NavigationFlowCoordinator
class MovieDetailsCoordinator: NavigationFlowCoordinator {
var connection: Connection
var movieId: String
var movieDetailsViewController: MovieDetailsViewController!
init(connection: Connection, movieId: String) {
self.connection = connection
self.movieId = movieId
super.init()
}
override func createMainViewController() -> UIViewController? {
movieDetailsViewController = MovieDetailsViewController(connection: connection, movieId: movieId)
movieDetailsViewController.flowDelegate = self
return movieDetailsViewController
}
override func handle(flowEvent: FlowEvent) -> Bool {
if let movieUpdatedFlowEvent = flowEvent as? MovieUpdatedFlowEvent, movieUpdatedFlowEvent.movieId == movieId {
movieDetailsViewController.invalidateMovieData()
}
return false
}
}
extension MovieDetailsCoordinator: MovieDetailsFlowDelegate {
func editMovie() {
start(childCoordinator: MovieCreateOrUpdateCoordinator(connection: connection, movieId: movieId))
}
func onMovieUpdated() {
send(flowEvent: MovieUpdatedFlowEvent(movieId: movieId))
}
}
| mit | a09203dbce497dfaf30e418859381189 | 30.543478 | 118 | 0.718125 | 5.14539 | false | false | false | false |
ccrama/Slide-iOS | Slide for Reddit/SFSymbolsEnum.swift | 1 | 100081 |
// Note: Cases that are commented out are symbols defined in the SFSymbols app
// that nonetheless aren't available on-device (Apple bug)
public enum SFSymbol: String {
///
case _00Circle = "00.circle"
///
case _00CircleFill = "00.circle.fill"
///
case _00Square = "00.square"
///
case _00SquareFill = "00.square.fill"
///
case _01Circle = "01.circle"
///
case _01CircleFill = "01.circle.fill"
///
case _01Square = "01.square"
///
case _01SquareFill = "01.square.fill"
///
case _02Circle = "02.circle"
///
case _02CircleFill = "02.circle.fill"
///
case _02Square = "02.square"
///
case _02SquareFill = "02.square.fill"
///
case _03Circle = "03.circle"
///
case _03CircleFill = "03.circle.fill"
///
case _03Square = "03.square"
///
case _03SquareFill = "03.square.fill"
///
case _04Circle = "04.circle"
///
case _04CircleFill = "04.circle.fill"
///
case _04Square = "04.square"
///
case _04SquareFill = "04.square.fill"
///
case _05Circle = "05.circle"
///
case _05CircleFill = "05.circle.fill"
///
case _05Square = "05.square"
///
case _05SquareFill = "05.square.fill"
///
case _06Circle = "06.circle"
///
case _06CircleFill = "06.circle.fill"
///
case _06Square = "06.square"
///
case _06SquareFill = "06.square.fill"
///
case _07Circle = "07.circle"
///
case _07CircleFill = "07.circle.fill"
///
case _07Square = "07.square"
///
case _07SquareFill = "07.square.fill"
///
case _08Circle = "08.circle"
///
case _08CircleFill = "08.circle.fill"
///
case _08Square = "08.square"
///
case _08SquareFill = "08.square.fill"
///
case _09Circle = "09.circle"
///
case _09CircleFill = "09.circle.fill"
///
case _09Square = "09.square"
///
case _09SquareFill = "09.square.fill"
///
case _0Circle = "0.circle"
///
case _0CircleFill = "0.circle.fill"
///
case _0Square = "0.square"
///
case _0SquareFill = "0.square.fill"
///
case _10Circle = "10.circle"
///
case _10CircleFill = "10.circle.fill"
///
case _10Square = "10.square"
///
case _10SquareFill = "10.square.fill"
///
case _11Circle = "11.circle"
///
case _11CircleFill = "11.circle.fill"
///
case _11Square = "11.square"
///
case _11SquareFill = "11.square.fill"
///
case _12Circle = "12.circle"
///
case _12CircleFill = "12.circle.fill"
///
case _12Square = "12.square"
///
case _12SquareFill = "12.square.fill"
///
case _13Circle = "13.circle"
///
case _13CircleFill = "13.circle.fill"
///
case _13Square = "13.square"
///
case _13SquareFill = "13.square.fill"
///
case _14Circle = "14.circle"
///
case _14CircleFill = "14.circle.fill"
///
case _14Square = "14.square"
///
case _14SquareFill = "14.square.fill"
///
case _15Circle = "15.circle"
///
case _15CircleFill = "15.circle.fill"
///
case _15Square = "15.square"
///
case _15SquareFill = "15.square.fill"
///
case _16Circle = "16.circle"
///
case _16CircleFill = "16.circle.fill"
///
case _16Square = "16.square"
///
case _16SquareFill = "16.square.fill"
///
case _17Circle = "17.circle"
///
case _17CircleFill = "17.circle.fill"
///
case _17Square = "17.square"
///
case _17SquareFill = "17.square.fill"
///
case _18Circle = "18.circle"
///
case _18CircleFill = "18.circle.fill"
///
case _18Square = "18.square"
///
case _18SquareFill = "18.square.fill"
///
case _19Circle = "19.circle"
///
case _19CircleFill = "19.circle.fill"
///
case _19Square = "19.square"
///
case _19SquareFill = "19.square.fill"
///
case _1Circle = "1.circle"
///
case _1CircleFill = "1.circle.fill"
///
case _1Magnifyingglass = "1.magnifyingglass"
///
case _1Square = "1.square"
///
case _1SquareFill = "1.square.fill"
///
case _20Circle = "20.circle"
///
case _20CircleFill = "20.circle.fill"
///
case _20Square = "20.square"
///
case _20SquareFill = "20.square.fill"
///
case _21Circle = "21.circle"
///
case _21CircleFill = "21.circle.fill"
///
case _21Square = "21.square"
///
case _21SquareFill = "21.square.fill"
///
case _22Circle = "22.circle"
///
case _22CircleFill = "22.circle.fill"
///
case _22Square = "22.square"
///
case _22SquareFill = "22.square.fill"
///
case _23Circle = "23.circle"
///
case _23CircleFill = "23.circle.fill"
///
case _23Square = "23.square"
///
case _23SquareFill = "23.square.fill"
///
case _24Circle = "24.circle"
///
case _24CircleFill = "24.circle.fill"
///
case _24Square = "24.square"
///
case _24SquareFill = "24.square.fill"
///
case _25Circle = "25.circle"
///
case _25CircleFill = "25.circle.fill"
///
case _25Square = "25.square"
///
case _25SquareFill = "25.square.fill"
///
case _26Circle = "26.circle"
///
case _26CircleFill = "26.circle.fill"
///
case _26Square = "26.square"
///
case _26SquareFill = "26.square.fill"
///
case _27Circle = "27.circle"
///
case _27CircleFill = "27.circle.fill"
///
case _27Square = "27.square"
///
case _27SquareFill = "27.square.fill"
///
case _28Circle = "28.circle"
///
case _28CircleFill = "28.circle.fill"
///
case _28Square = "28.square"
///
case _28SquareFill = "28.square.fill"
///
case _29Circle = "29.circle"
///
case _29CircleFill = "29.circle.fill"
///
case _29Square = "29.square"
///
case _29SquareFill = "29.square.fill"
///
case _2Circle = "2.circle"
///
case _2CircleFill = "2.circle.fill"
///
case _2Square = "2.square"
///
case _2SquareFill = "2.square.fill"
///
case _30Circle = "30.circle"
///
case _30CircleFill = "30.circle.fill"
///
case _30Square = "30.square"
///
case _30SquareFill = "30.square.fill"
///
case _31Circle = "31.circle"
///
case _31CircleFill = "31.circle.fill"
///
case _31Square = "31.square"
///
case _31SquareFill = "31.square.fill"
///
case _32Circle = "32.circle"
///
case _32CircleFill = "32.circle.fill"
///
case _32Square = "32.square"
///
case _32SquareFill = "32.square.fill"
///
case _33Circle = "33.circle"
///
case _33CircleFill = "33.circle.fill"
///
case _33Square = "33.square"
///
case _33SquareFill = "33.square.fill"
///
case _34Circle = "34.circle"
///
case _34CircleFill = "34.circle.fill"
///
case _34Square = "34.square"
///
case _34SquareFill = "34.square.fill"
///
case _35Circle = "35.circle"
///
case _35CircleFill = "35.circle.fill"
///
case _35Square = "35.square"
///
case _35SquareFill = "35.square.fill"
///
case _36Circle = "36.circle"
///
case _36CircleFill = "36.circle.fill"
///
case _36Square = "36.square"
///
case _36SquareFill = "36.square.fill"
///
case _37Circle = "37.circle"
///
case _37CircleFill = "37.circle.fill"
///
case _37Square = "37.square"
///
case _37SquareFill = "37.square.fill"
///
case _38Circle = "38.circle"
///
case _38CircleFill = "38.circle.fill"
///
case _38Square = "38.square"
///
case _38SquareFill = "38.square.fill"
///
case _39Circle = "39.circle"
///
case _39CircleFill = "39.circle.fill"
///
case _39Square = "39.square"
///
case _39SquareFill = "39.square.fill"
///
case _3Circle = "3.circle"
///
case _3CircleFill = "3.circle.fill"
///
case _3Square = "3.square"
///
case _3SquareFill = "3.square.fill"
///
case _40Circle = "40.circle"
///
case _40CircleFill = "40.circle.fill"
///
case _40Square = "40.square"
///
case _40SquareFill = "40.square.fill"
///
case _41Circle = "41.circle"
///
case _41CircleFill = "41.circle.fill"
///
case _41Square = "41.square"
///
case _41SquareFill = "41.square.fill"
///
case _42Circle = "42.circle"
///
case _42CircleFill = "42.circle.fill"
///
case _42Square = "42.square"
///
case _42SquareFill = "42.square.fill"
///
case _43Circle = "43.circle"
///
case _43CircleFill = "43.circle.fill"
///
case _43Square = "43.square"
///
case _43SquareFill = "43.square.fill"
///
case _44Circle = "44.circle"
///
case _44CircleFill = "44.circle.fill"
///
case _44Square = "44.square"
///
case _44SquareFill = "44.square.fill"
///
case _45Circle = "45.circle"
///
case _45CircleFill = "45.circle.fill"
///
case _45Square = "45.square"
///
case _45SquareFill = "45.square.fill"
///
case _46Circle = "46.circle"
///
case _46CircleFill = "46.circle.fill"
///
case _46Square = "46.square"
///
case _46SquareFill = "46.square.fill"
///
case _47Circle = "47.circle"
///
case _47CircleFill = "47.circle.fill"
///
case _47Square = "47.square"
///
case _47SquareFill = "47.square.fill"
///
case _48Circle = "48.circle"
///
case _48CircleFill = "48.circle.fill"
///
case _48Square = "48.square"
///
case _48SquareFill = "48.square.fill"
///
case _49Circle = "49.circle"
///
case _49CircleFill = "49.circle.fill"
///
case _49Square = "49.square"
///
case _49SquareFill = "49.square.fill"
///
case _4AltCircle = "4.alt.circle"
///
case _4AltCircleFill = "4.alt.circle.fill"
///
case _4AltSquare = "4.alt.square"
///
case _4AltSquareFill = "4.alt.square.fill"
///
case _4Circle = "4.circle"
///
case _4CircleFill = "4.circle.fill"
///
case _4Square = "4.square"
///
case _4SquareFill = "4.square.fill"
///
case _50Circle = "50.circle"
///
case _50CircleFill = "50.circle.fill"
///
case _50Square = "50.square"
///
case _50SquareFill = "50.square.fill"
///
case _5Circle = "5.circle"
///
case _5CircleFill = "5.circle.fill"
///
case _5Square = "5.square"
///
case _5SquareFill = "5.square.fill"
///
case _6AltCircle = "6.alt.circle"
///
case _6AltCircleFill = "6.alt.circle.fill"
///
case _6AltSquare = "6.alt.square"
///
case _6AltSquareFill = "6.alt.square.fill"
///
case _6Circle = "6.circle"
///
case _6CircleFill = "6.circle.fill"
///
case _6Square = "6.square"
///
case _6SquareFill = "6.square.fill"
///
case _7Circle = "7.circle"
///
case _7CircleFill = "7.circle.fill"
///
case _7Square = "7.square"
///
case _7SquareFill = "7.square.fill"
///
case _8Circle = "8.circle"
///
case _8CircleFill = "8.circle.fill"
///
case _8Square = "8.square"
///
case _8SquareFill = "8.square.fill"
///
case _9AltCircle = "9.alt.circle"
///
case _9AltCircleFill = "9.alt.circle.fill"
///
case _9AltSquare = "9.alt.square"
///
case _9AltSquareFill = "9.alt.square.fill"
///
case _9Circle = "9.circle"
///
case _9CircleFill = "9.circle.fill"
///
case _9Square = "9.square"
///
case _9SquareFill = "9.square.fill"
///
case `repeat` = "repeat"
///
case `return` = "return"
///
case a = "a"
///
case aCircle = "a.circle"
///
case aCircleFill = "a.circle.fill"
///
case aSquare = "a.square"
///
case aSquareFill = "a.square.fill"
///
case airplane = "airplane"
///
/// (Can only refer to Apple's AirPlay)
case airplayaudio = "airplayaudio"
///
/// (Can only refer to Apple's AirPlay)
case airplayvideo = "airplayvideo"
///
case alarm = "alarm"
///
case alarmFill = "alarm.fill"
///
case alt = "alt"
///
case ant = "ant"
///
case antCircle = "ant.circle"
///
case antCircleFill = "ant.circle.fill"
///
case antFill = "ant.fill"
///
case antennaRadiowavesLeftAndRight = "antenna.radiowaves.left.and.right"
///
case app = "app"
///
case appBadge = "app.badge"
///
case appBadgeFill = "app.badge.fill"
///
case appFill = "app.fill"
///
case appGift = "app.gift"
///
case appGiftFill = "app.gift.fill"
///
case archivebox = "archivebox"
///
case archiveboxFill = "archivebox.fill"
///
/// (Can only refer to Apple's ARKit)
case arkit = "arkit"
///
case arrow2Circlepath = "arrow.2.circlepath"
///
case arrow2CirclepathCircle = "arrow.2.circlepath.circle"
///
case arrow2CirclepathCircleFill = "arrow.2.circlepath.circle.fill"
///
case arrow2Squarepath = "arrow.2.squarepath"
///
case arrow3Trianglepath = "arrow.3.trianglepath"
///
case arrowBranch = "arrow.branch"
///
case arrowClockwise = "arrow.clockwise"
///
case arrowClockwiseCircle = "arrow.clockwise.circle"
///
case arrowClockwiseCircleFill = "arrow.clockwise.circle.fill"
///
/// (Can only refer to Apple's iCloud service)
case arrowClockwiseIcloud = "arrow.clockwise.icloud"
///
case arrowClockwiseIcloudFill = "arrow.clockwise.icloud.fill"
///
case arrowCounterclockwise = "arrow.counterclockwise"
///
case arrowCounterclockwiseCircle = "arrow.counterclockwise.circle"
///
case arrowCounterclockwiseCircleFill = "arrow.counterclockwise.circle.fill"
///
/// (Can only refer to Apple's iCloud service)
case arrowCounterclockwiseIcloud = "arrow.counterclockwise.icloud"
///
/// (Can only refer to Apple's iCloud service)
case arrowCounterclockwiseIcloudFill = "arrow.counterclockwise.icloud.fill"
///
case arrowDown = "arrow.down"
///
case arrowDownCircle = "arrow.down.circle"
///
case arrowDownCircleFill = "arrow.down.circle.fill"
///
case arrowDownDoc = "arrow.down.doc"
///
case arrowDownDocFill = "arrow.down.doc.fill"
///
case arrowDownLeft = "arrow.down.left"
///
case arrowDownLeftCircle = "arrow.down.left.circle"
///
case arrowDownLeftCircleFill = "arrow.down.left.circle.fill"
///
case arrowDownLeftSquare = "arrow.down.left.square"
///
case arrowDownLeftSquareFill = "arrow.down.left.square.fill"
///
/// (Can only refer to Apple's FaceTime app)
case arrowDownLeftVideo = "arrow.down.left.video"
///
/// (Can only refer to Apple's FaceTime app)
case arrowDownLeftVideoFill = "arrow.down.left.video.fill"
///
case arrowDownRight = "arrow.down.right"
///
case arrowDownRightAndArrowUpLeft = "arrow.down.right.and.arrow.up.left"
///
case arrowDownRightCircle = "arrow.down.right.circle"
///
case arrowDownRightCircleFill = "arrow.down.right.circle.fill"
///
case arrowDownRightSquare = "arrow.down.right.square"
///
case arrowDownRightSquareFill = "arrow.down.right.square.fill"
///
case arrowDownSquare = "arrow.down.square"
///
case arrowDownSquareFill = "arrow.down.square.fill"
///
case arrowDownToLine = "arrow.down.to.line"
///
case arrowDownToLineAlt = "arrow.down.to.line.alt"
///
case arrowLeft = "arrow.left"
///
case arrowLeftAndRight = "arrow.left.and.right"
///
case arrowLeftAndRightCircle = "arrow.left.and.right.circle"
///
case arrowLeftAndRightCircleFill = "arrow.left.and.right.circle.fill"
///
case arrowLeftAndRightSquare = "arrow.left.and.right.square"
///
case arrowLeftAndRightSquareFill = "arrow.left.and.right.square.fill"
///
case arrowLeftCircle = "arrow.left.circle"
///
case arrowLeftCircleFill = "arrow.left.circle.fill"
///
case arrowLeftSquare = "arrow.left.square"
///
case arrowLeftSquareFill = "arrow.left.square.fill"
///
case arrowLeftToLine = "arrow.left.to.line"
///
case arrowLeftToLineAlt = "arrow.left.to.line.alt"
///
case arrowMerge = "arrow.merge"
///
case arrowRight = "arrow.right"
///
case arrowRightArrowLeft = "arrow.right.arrow.left"
///
case arrowRightArrowLeftCircle = "arrow.right.arrow.left.circle"
///
case arrowRightArrowLeftCircleFill = "arrow.right.arrow.left.circle.fill"
///
case arrowRightArrowLeftSquare = "arrow.right.arrow.left.square"
///
case arrowRightArrowLeftSquareFill = "arrow.right.arrow.left.square.fill"
///
case arrowRightCircle = "arrow.right.circle"
///
case arrowRightCircleFill = "arrow.right.circle.fill"
///
case arrowRightSquare = "arrow.right.square"
///
case arrowRightSquareFill = "arrow.right.square.fill"
///
case arrowRightToLine = "arrow.right.to.line"
///
case arrowRightToLineAlt = "arrow.right.to.line.alt"
///
case arrowSwap = "arrow.swap"
///
case arrowTurnDownLeft = "arrow.turn.down.left"
///
case arrowTurnDownRight = "arrow.turn.down.right"
///
case arrowTurnLeftDown = "arrow.turn.left.down"
///
case arrowTurnLeftUp = "arrow.turn.left.up"
///
case arrowTurnRightDown = "arrow.turn.right.down"
///
case arrowTurnRightUp = "arrow.turn.right.up"
///
case arrowTurnUpLeft = "arrow.turn.up.left"
///
case arrowTurnUpRight = "arrow.turn.up.right"
///
case arrowUp = "arrow.up"
///
case arrowUpAndDown = "arrow.up.and.down"
///
case arrowUpAndDownCircle = "arrow.up.and.down.circle"
///
case arrowUpAndDownCircleFill = "arrow.up.and.down.circle.fill"
///
case arrowUpAndDownSquare = "arrow.up.and.down.square"
///
case arrowUpAndDownSquareFill = "arrow.up.and.down.square.fill"
///
case arrowUpArrowDown = "arrow.up.arrow.down"
///
case arrowUpArrowDownCircle = "arrow.up.arrow.down.circle"
///
case arrowUpArrowDownCircleFill = "arrow.up.arrow.down.circle.fill"
///
case arrowUpArrowDownSquare = "arrow.up.arrow.down.square"
///
case arrowUpArrowDownSquareFill = "arrow.up.arrow.down.square.fill"
///
case arrowUpBin = "arrow.up.bin"
///
case arrowUpBinFill = "arrow.up.bin.fill"
///
case arrowUpCircle = "arrow.up.circle"
///
case arrowUpCircleFill = "arrow.up.circle.fill"
///
case arrowUpDoc = "arrow.up.doc"
///
case arrowUpDocFill = "arrow.up.doc.fill"
///
case arrowUpLeft = "arrow.up.left"
///
case arrowUpLeftAndArrowDownRight = "arrow.up.left.and.arrow.down.right"
///
case arrowUpLeftCircle = "arrow.up.left.circle"
///
case arrowUpLeftCircleFill = "arrow.up.left.circle.fill"
///
case arrowUpLeftSquare = "arrow.up.left.square"
///
case arrowUpLeftSquareFill = "arrow.up.left.square.fill"
///
case arrowUpRight = "arrow.up.right"
///
case arrowUpRightCircle = "arrow.up.right.circle"
///
case arrowUpRightCircleFill = "arrow.up.right.circle.fill"
///
case arrowUpRightDiamond = "arrow.up.right.diamond"
///
case arrowUpRightDiamondFill = "arrow.up.right.diamond.fill"
///
case arrowUpRightSquare = "arrow.up.right.square"
///
case arrowUpRightSquareFill = "arrow.up.right.square.fill"
///
/// (Can only refer to Apple's FaceTime app)
case arrowUpRightVideo = "arrow.up.right.video"
///
/// (Can only refer to Apple's FaceTime app)
case arrowUpRightVideoFill = "arrow.up.right.video.fill"
///
case arrowUpSquare = "arrow.up.square"
///
case arrowUpSquareFill = "arrow.up.square.fill"
///
case arrowUpToLine = "arrow.up.to.line"
///
case arrowUpToLineAlt = "arrow.up.to.line.alt"
///
case arrowUturnDown = "arrow.uturn.down"
///
case arrowUturnDownCircle = "arrow.uturn.down.circle"
///
case arrowUturnDownCircleFill = "arrow.uturn.down.circle.fill"
///
case arrowUturnDownSquare = "arrow.uturn.down.square"
///
case arrowUturnDownSquareFill = "arrow.uturn.down.square.fill"
///
case arrowUturnLeft = "arrow.uturn.left"
///
case arrowUturnLeftCircle = "arrow.uturn.left.circle"
///
case arrowUturnLeftCircleBadgeEllipsis = "arrow.uturn.left.circle.badge.ellipsis"
///
case arrowUturnLeftCircleFill = "arrow.uturn.left.circle.fill"
///
case arrowUturnLeftSquare = "arrow.uturn.left.square"
///
case arrowUturnLeftSquareFill = "arrow.uturn.left.square.fill"
///
case arrowUturnRight = "arrow.uturn.right"
///
case arrowUturnRightCircle = "arrow.uturn.right.circle"
///
case arrowUturnRightCircleFill = "arrow.uturn.right.circle.fill"
///
case arrowUturnRightSquare = "arrow.uturn.right.square"
///
case arrowUturnRightSquareFill = "arrow.uturn.right.square.fill"
///
case arrowUturnUp = "arrow.uturn.up"
///
case arrowUturnUpCircle = "arrow.uturn.up.circle"
///
case arrowUturnUpCircleFill = "arrow.uturn.up.circle.fill"
///
case arrowUturnUpSquare = "arrow.uturn.up.square"
///
case arrowUturnUpSquareFill = "arrow.uturn.up.square.fill"
///
case arrowshapeTurnUpLeft = "arrowshape.turn.up.left"
///
case arrowshapeTurnUpLeft2 = "arrowshape.turn.up.left.2"
///
case arrowshapeTurnUpLeft2Fill = "arrowshape.turn.up.left.2.fill"
///
case arrowshapeTurnUpLeftCircle = "arrowshape.turn.up.left.circle"
///
case arrowshapeTurnUpLeftCircleFill = "arrowshape.turn.up.left.circle.fill"
///
case arrowshapeTurnUpLeftFill = "arrowshape.turn.up.left.fill"
///
case arrowshapeTurnUpRight = "arrowshape.turn.up.right"
///
case arrowshapeTurnUpRightCircle = "arrowshape.turn.up.right.circle"
///
case arrowshapeTurnUpRightCircleFill = "arrowshape.turn.up.right.circle.fill"
///
case arrowshapeTurnUpRightFill = "arrowshape.turn.up.right.fill"
///
case arrowtriangleDown = "arrowtriangle.down"
///
case arrowtriangleDownCircle = "arrowtriangle.down.circle"
///
case arrowtriangleDownCircleFill = "arrowtriangle.down.circle.fill"
///
case arrowtriangleDownFill = "arrowtriangle.down.fill"
///
case arrowtriangleDownSquare = "arrowtriangle.down.square"
///
case arrowtriangleDownSquareFill = "arrowtriangle.down.square.fill"
///
case arrowtriangleLeft = "arrowtriangle.left"
///
case arrowtriangleLeftCircle = "arrowtriangle.left.circle"
///
case arrowtriangleLeftCircleFill = "arrowtriangle.left.circle.fill"
///
case arrowtriangleLeftFill = "arrowtriangle.left.fill"
///
case arrowtriangleLeftSquare = "arrowtriangle.left.square"
///
case arrowtriangleLeftSquareFill = "arrowtriangle.left.square.fill"
///
case arrowtriangleRight = "arrowtriangle.right"
///
case arrowtriangleRightCircle = "arrowtriangle.right.circle"
///
case arrowtriangleRightCircleFill = "arrowtriangle.right.circle.fill"
///
case arrowtriangleRightFill = "arrowtriangle.right.fill"
///
case arrowtriangleRightSquare = "arrowtriangle.right.square"
///
case arrowtriangleRightSquareFill = "arrowtriangle.right.square.fill"
///
case arrowtriangleUp = "arrowtriangle.up"
///
case arrowtriangleUpCircle = "arrowtriangle.up.circle"
///
case arrowtriangleUpCircleFill = "arrowtriangle.up.circle.fill"
///
case arrowtriangleUpFill = "arrowtriangle.up.fill"
///
case arrowtriangleUpSquare = "arrowtriangle.up.square"
///
case arrowtriangleUpSquareFill = "arrowtriangle.up.square.fill"
///
case aspectratio = "aspectratio"
///
case aspectratioFill = "aspectratio.fill"
///
case asteriskCircle = "asterisk.circle"
///
case asteriskCircleFill = "asterisk.circle.fill"
///
case at = "at"
///
case atBadgeMinus = "at.badge.minus"
///
case atBadgePlus = "at.badge.plus"
///
case australsignCircle = "australsign.circle"
///
case australsignCircleFill = "australsign.circle.fill"
///
case australsignSquare = "australsign.square"
///
case australsignSquareFill = "australsign.square.fill"
///
case bCircle = "b.circle"
///
case bCircleFill = "b.circle.fill"
///
case bSquare = "b.square"
///
case bSquareFill = "b.square.fill"
///
case backward = "backward"
///
case backwardEnd = "backward.end"
///
case backwardEndAlt = "backward.end.alt"
///
case backwardEndAltFill = "backward.end.alt.fill"
///
case backwardEndFill = "backward.end.fill"
///
case backwardFill = "backward.fill"
///
case badgePlusRadiowavesRight = "badge.plus.radiowaves.right"
///
case bag = "bag"
///
case bagBadgeMinus = "bag.badge.minus"
///
case bagBadgePlus = "bag.badge.plus"
///
case bagFill = "bag.fill"
///
case bagFillBadgeMinus = "bag.fill.badge.minus"
///
case bagFillBadgePlus = "bag.fill.badge.plus"
///
case bahtsignCircle = "bahtsign.circle"
///
case bahtsignCircleFill = "bahtsign.circle.fill"
///
case bahtsignSquare = "bahtsign.square"
///
case bahtsignSquareFill = "bahtsign.square.fill"
///
case bandage = "bandage"
///
case bandageFill = "bandage.fill"
///
case barcode = "barcode"
///
case barcodeViewfinder = "barcode.viewfinder"
///
case battery0 = "battery.0"
///
case battery100 = "battery.100"
///
case battery25 = "battery.25"
///
case bedDouble = "bed.double"
///
case bedDoubleFill = "bed.double.fill"
///
case bell = "bell"
///
case bellCircle = "bell.circle"
///
case bellCircleFill = "bell.circle.fill"
///
case bellFill = "bell.fill"
///
case bellSlash = "bell.slash"
///
case bellSlashFill = "bell.slash.fill"
///
case binXmark = "bin.xmark"
///
case binXmarkFill = "bin.xmark.fill"
///
case bitcoinsignCircle = "bitcoinsign.circle"
///
case bitcoinsignCircleFill = "bitcoinsign.circle.fill"
///
case bitcoinsignSquare = "bitcoinsign.square"
///
case bitcoinsignSquareFill = "bitcoinsign.square.fill"
///
case bold = "bold"
///
case boldItalicUnderline = "bold.italic.underline"
///
case boldUnderline = "bold.underline"
///
case bolt = "bolt"
///
case boltBadgeA = "bolt.badge.a"
///
case boltBadgeAFill = "bolt.badge.a.fill"
///
case boltCircle = "bolt.circle"
///
case boltCircleFill = "bolt.circle.fill"
///
case boltFill = "bolt.fill"
///
case boltHorizontal = "bolt.horizontal"
///
case boltHorizontalCircle = "bolt.horizontal.circle"
///
case boltHorizontalCircleFill = "bolt.horizontal.circle.fill"
///
case boltHorizontalFill = "bolt.horizontal.fill"
///
/// (Can only refer to Apple's iCloud service)
case boltHorizontalIcloud = "bolt.horizontal.icloud"
///
/// (Can only refer to Apple's iCloud service)
case boltHorizontalIcloudFill = "bolt.horizontal.icloud.fill"
///
case boltSlash = "bolt.slash"
///
case boltSlashFill = "bolt.slash.fill"
///
case book = "book"
///
case bookCircle = "book.circle"
///
case bookCircleFill = "book.circle.fill"
///
case bookFill = "book.fill"
///
case bookmark = "bookmark"
///
case bookmarkFill = "bookmark.fill"
///
case briefcase = "briefcase"
///
case briefcaseFill = "briefcase.fill"
///
case bubbleLeft = "bubble.left"
///
case bubbleLeftAndBubbleRight = "bubble.left.and.bubble.right"
///
case bubbleLeftAndBubbleRightFill = "bubble.left.and.bubble.right.fill"
///
case bubbleLeftFill = "bubble.left.fill"
///
case bubbleMiddleBottom = "bubble.middle.bottom"
///
case bubbleMiddleBottomFill = "bubble.middle.bottom.fill"
///
case bubbleMiddleTop = "bubble.middle.top"
///
case bubbleMiddleTopFill = "bubble.middle.top.fill"
///
case bubbleRight = "bubble.right"
///
case bubbleRightFill = "bubble.right.fill"
///
case burn = "burn"
///
case burst = "burst"
///
case burstFill = "burst.fill"
///
case cCircle = "c.circle"
///
case cCircleFill = "c.circle.fill"
///
case cSquare = "c.square"
///
case cSquareFill = "c.square.fill"
///
case calendar = "calendar"
///
case calendarBadgeMinus = "calendar.badge.minus"
///
case calendarBadgePlus = "calendar.badge.plus"
///
case calendarCircle = "calendar.circle"
///
case calendarCircleFill = "calendar.circle.fill"
///
case camera = "camera"
///
case cameraCircle = "camera.circle"
///
case cameraCircleFill = "camera.circle.fill"
///
case cameraFill = "camera.fill"
///
case cameraOnRectangle = "camera.on.rectangle"
///
case cameraOnRectangleFill = "camera.on.rectangle.fill"
///
case cameraRotate = "camera.rotate"
///
case cameraRotateFill = "camera.rotate.fill"
///
case cameraViewfinder = "camera.viewfinder"
///
case capslock = "capslock"
///
case capslockFill = "capslock.fill"
///
case capsule = "capsule"
///
case capsuleFill = "capsule.fill"
///
case captionsBubble = "captions.bubble"
///
case captionsBubbleFill = "captions.bubble.fill"
///
case car = "car"
///
case carFill = "car.fill"
///
case cart = "cart"
///
case cartBadgeMinus = "cart.badge.minus"
///
case cartBadgePlus = "cart.badge.plus"
///
case cartFill = "cart.fill"
///
case cartFillBadgeMinus = "cart.fill.badge.minus"
///
case cartFillBadgePlus = "cart.fill.badge.plus"
///
case cedisignCircle = "cedisign.circle"
///
case cedisignCircleFill = "cedisign.circle.fill"
///
case cedisignSquare = "cedisign.square"
///
case cedisignSquareFill = "cedisign.square.fill"
///
case centsignCircle = "centsign.circle"
///
case centsignCircleFill = "centsign.circle.fill"
///
case centsignSquare = "centsign.square"
///
case centsignSquareFill = "centsign.square.fill"
///
case chartBar = "chart.bar"
///
case chartBarFill = "chart.bar.fill"
///
case chartPie = "chart.pie"
///
case chartPieFill = "chart.pie.fill"
///
case checkmark = "checkmark"
///
case checkmarkCircle = "checkmark.circle"
///
case checkmarkCircleFill = "checkmark.circle.fill"
///
case checkmarkRectangle = "checkmark.rectangle"
///
case checkmarkRectangleFill = "checkmark.rectangle.fill"
///
case checkmarkSeal = "checkmark.seal"
///
case checkmarkSealFill = "checkmark.seal.fill"
///
case checkmarkShield = "checkmark.shield"
///
case checkmarkShieldFill = "checkmark.shield.fill"
///
case checkmarkSquare = "checkmark.square"
///
case checkmarkSquareFill = "checkmark.square.fill"
///
case chevronCompactDown = "chevron.compact.down"
///
case chevronCompactLeft = "chevron.compact.left"
///
case chevronCompactRight = "chevron.compact.right"
///
case chevronCompactUp = "chevron.compact.up"
///
case chevronDown = "chevron.down"
///
case chevronDownCircle = "chevron.down.circle"
///
case chevronDownCircleFill = "chevron.down.circle.fill"
///
case chevronDownSquare = "chevron.down.square"
///
case chevronDownSquareFill = "chevron.down.square.fill"
///
case chevronLeft = "chevron.left"
///
case chevronLeft2 = "chevron.left.2"
///
case chevronLeftCircle = "chevron.left.circle"
///
case chevronLeftCircleFill = "chevron.left.circle.fill"
///
case chevronLeftSlashChevronRight = "chevron.left.slash.chevron.right"
///
case chevronLeftSquare = "chevron.left.square"
///
case chevronLeftSquareFill = "chevron.left.square.fill"
///
case chevronRight = "chevron.right"
///
case chevronRight2 = "chevron.right.2"
///
case chevronRightCircle = "chevron.right.circle"
///
case chevronRightCircleFill = "chevron.right.circle.fill"
///
case chevronRightSquare = "chevron.right.square"
///
case chevronRightSquareFill = "chevron.right.square.fill"
///
case chevronUp = "chevron.up"
///
case chevronUpChevronDown = "chevron.up.chevron.down"
///
case chevronUpCircle = "chevron.up.circle"
///
case chevronUpCircleFill = "chevron.up.circle.fill"
///
case chevronUpSquare = "chevron.up.square"
///
case chevronUpSquareFill = "chevron.up.square.fill"
///
case circle = "circle"
///
case circleBottomthirdSplit = "circle.bottomthird.split"
///
case circleFill = "circle.fill"
///
case circleGrid2x2 = "circle.grid.2x2"
///
case circleGrid2x2Fill = "circle.grid.2x2.fill"
///
case circleGrid3x3 = "circle.grid.3x3"
///
case circleGrid3x3Fill = "circle.grid.3x3.fill"
///
case circleGridHex = "circle.grid.hex"
///
case circleGridHexFill = "circle.grid.hex.fill"
///
case circleLefthalfFill = "circle.lefthalf.fill"
///
case circleRighthalfFill = "circle.righthalf.fill"
///
case clear = "clear"
///
case clearFill = "clear.fill"
///
case clock = "clock"
///
case clockFill = "clock.fill"
///
case cloud = "cloud"
///
case cloudBolt = "cloud.bolt"
///
case cloudBoltFill = "cloud.bolt.fill"
///
case cloudBoltRain = "cloud.bolt.rain"
///
case cloudBoltRainFill = "cloud.bolt.rain.fill"
///
case cloudDrizzle = "cloud.drizzle"
///
case cloudDrizzleFill = "cloud.drizzle.fill"
///
case cloudFill = "cloud.fill"
///
case cloudFog = "cloud.fog"
///
case cloudFogFill = "cloud.fog.fill"
///
case cloudHail = "cloud.hail"
///
case cloudHailFill = "cloud.hail.fill"
///
case cloudHeavyrain = "cloud.heavyrain"
///
case cloudHeavyrainFill = "cloud.heavyrain.fill"
///
case cloudMoon = "cloud.moon"
///
case cloudMoonBolt = "cloud.moon.bolt"
///
case cloudMoonBoltFill = "cloud.moon.bolt.fill"
///
case cloudMoonFill = "cloud.moon.fill"
///
case cloudMoonRain = "cloud.moon.rain"
///
case cloudMoonRainFill = "cloud.moon.rain.fill"
///
case cloudRain = "cloud.rain"
///
case cloudRainFill = "cloud.rain.fill"
///
case cloudSleet = "cloud.sleet"
///
case cloudSleetFill = "cloud.sleet.fill"
///
case cloudSnow = "cloud.snow"
///
case cloudSnowFill = "cloud.snow.fill"
///
case cloudSun = "cloud.sun"
///
case cloudSunBolt = "cloud.sun.bolt"
///
case cloudSunBoltFill = "cloud.sun.bolt.fill"
///
case cloudSunFill = "cloud.sun.fill"
///
case cloudSunRain = "cloud.sun.rain"
///
case cloudSunRainFill = "cloud.sun.rain.fill"
///
case coloncurrencysignCircle = "coloncurrencysign.circle"
///
case coloncurrencysignCircleFill = "coloncurrencysign.circle.fill"
///
case coloncurrencysignSquare = "coloncurrencysign.square"
///
case coloncurrencysignSquareFill = "coloncurrencysign.square.fill"
///
case command = "command"
///
case control = "control"
///
case creditcard = "creditcard"
///
case creditcardFill = "creditcard.fill"
///
case crop = "crop"
///
@available(iOS 14,*) case crownFill = "crown.fill"
///
case cropRotate = "crop.rotate"
///
case cruzeirosignCircle = "cruzeirosign.circle"
///
case cruzeirosignCircleFill = "cruzeirosign.circle.fill"
///
case cruzeirosignSquare = "cruzeirosign.square"
///
case cruzeirosignSquareFill = "cruzeirosign.square.fill"
///
case cube = "cube"
///
case cubeBox = "cube.box"
///
case cubeBoxFill = "cube.box.fill"
///
case cubeFill = "cube.fill"
///
case cursorRays = "cursor.rays"
///
case dCircle = "d.circle"
///
case dCircleFill = "d.circle.fill"
///
case dSquare = "d.square"
///
case dSquareFill = "d.square.fill"
///
case decreaseIndent = "decrease.indent"
///
case decreaseQuotelevel = "decrease.quotelevel"
///
case deleteLeft = "delete.left"
///
case deleteLeftFill = "delete.left.fill"
///
case deleteRight = "delete.right"
///
case deleteRightFill = "delete.right.fill"
///
case desktopcomputer = "desktopcomputer"
///
case dial = "dial"
///
case dialFill = "dial.fill"
///
case divide = "divide"
///
case divideCircle = "divide.circle"
///
case divideCircleFill = "divide.circle.fill"
///
case divideSquare = "divide.square"
///
case divideSquareFill = "divide.square.fill"
///
case doc = "doc"
///
case docAppend = "doc.append"
///
case docCircle = "doc.circle"
///
case docCircleFill = "doc.circle.fill"
///
case docFill = "doc.fill"
///
case docOnClipboard = "doc.on.clipboard"
///
case docOnClipboardFill = "doc.on.clipboard.fill"
///
case docOnDoc = "doc.on.doc"
///
case docOnDocFill = "doc.on.doc.fill"
///
case docPlaintext = "doc.plaintext"
///
case docRichtext = "doc.richtext"
///
case docText = "doc.text"
///
case docTextFill = "doc.text.fill"
///
case docTextMagnifyingglass = "doc.text.magnifyingglass"
///
case docTextViewfinder = "doc.text.viewfinder"
///
case dollarsignCircle = "dollarsign.circle"
///
case dollarsignCircleFill = "dollarsign.circle.fill"
///
case dollarsignSquare = "dollarsign.square"
///
case dollarsignSquareFill = "dollarsign.square.fill"
///
case dongsignCircle = "dongsign.circle"
///
case dongsignCircleFill = "dongsign.circle.fill"
///
case dongsignSquare = "dongsign.square"
///
case dongsignSquareFill = "dongsign.square.fill"
///
case dotRadiowavesLeftAndRight = "dot.radiowaves.left.and.right"
///
case dotRadiowavesRight = "dot.radiowaves.right"
///
case dotSquare = "dot.square"
///
case dotSquareFill = "dot.square.fill"
///
case dropTriangle = "drop.triangle"
///
case dropTriangleFill = "drop.triangle.fill"
///
case eCircle = "e.circle"
///
case eCircleFill = "e.circle.fill"
///
case eSquare = "e.square"
///
case eSquareFill = "e.square.fill"
///
case ear = "ear"
///
case eject = "eject"
///
case ejectFill = "eject.fill"
///
case ellipsesBubble = "ellipses.bubble"
///
case ellipsesBubbleFill = "ellipses.bubble.fill"
///
case ellipsis = "ellipsis"
///
case ellipsisCircle = "ellipsis.circle"
///
case ellipsisCircleFill = "ellipsis.circle.fill"
///
case envelope = "envelope"
///
case envelopeBadge = "envelope.badge"
///
case envelopeBadgeFill = "envelope.badge.fill"
///
case envelopeCircle = "envelope.circle"
///
case envelopeCircleFill = "envelope.circle.fill"
///
case envelopeFill = "envelope.fill"
///
case envelopeOpen = "envelope.open"
///
case envelopeOpenFill = "envelope.open.fill"
///
case equal = "equal"
///
case equalCircle = "equal.circle"
///
case equalCircleFill = "equal.circle.fill"
///
case equalSquare = "equal.square"
///
case equalSquareFill = "equal.square.fill"
///
case escape = "escape"
///
case eurosignCircle = "eurosign.circle"
///
case eurosignCircleFill = "eurosign.circle.fill"
///
case eurosignSquare = "eurosign.square"
///
case eurosignSquareFill = "eurosign.square.fill"
///
case exclamationmark = "exclamationmark"
///
case exclamationmarkBubble = "exclamationmark.bubble"
///
case exclamationmarkBubbleFill = "exclamationmark.bubble.fill"
///
case exclamationmarkCircle = "exclamationmark.circle"
///
case exclamationmarkCircleFill = "exclamationmark.circle.fill"
///
/// (Can only refer to Apple's iCloud service)
case exclamationmarkIcloud = "exclamationmark.icloud"
///
/// (Can only refer to Apple's iCloud service)
case exclamationmarkIcloudFill = "exclamationmark.icloud.fill"
///
case exclamationmarkOctagon = "exclamationmark.octagon"
///
case exclamationmarkOctagonFill = "exclamationmark.octagon.fill"
///
case exclamationmarkShield = "exclamationmark.shield"
///
case exclamationmarkShieldFill = "exclamationmark.shield.fill"
///
case exclamationmarkSquare = "exclamationmark.square"
///
case exclamationmarkSquareFill = "exclamationmark.square.fill"
///
case exclamationmarkTriangle = "exclamationmark.triangle"
///
case exclamationmarkTriangleFill = "exclamationmark.triangle.fill"
///
case eye = "eye"
///
case eyeFill = "eye.fill"
///
case eyeSlash = "eye.slash"
///
case eyeSlashFill = "eye.slash.fill"
///
case eyedropper = "eyedropper"
///
case eyedropperFull = "eyedropper.full"
///
case eyedropperHalffull = "eyedropper.halffull"
///
case eyeglasses = "eyeglasses"
///
case fCircle = "f.circle"
///
case fCircleFill = "f.circle.fill"
///
case fCursive = "f.cursive"
///
case fCursiveCircle = "f.cursive.circle"
///
case fCursiveCircleFill = "f.cursive.circle.fill"
///
case fSquare = "f.square"
///
case fSquareFill = "f.square.fill"
///
/// (Can only refer to Apple's Face ID)
case faceid = "faceid"
///
case film = "film"
///
case filmFill = "film.fill"
///
case flag = "flag"
///
case flagCircle = "flag.circle"
///
case flagCircleFill = "flag.circle.fill"
///
case flagFill = "flag.fill"
///
case flagSlash = "flag.slash"
///
case flagSlashFill = "flag.slash.fill"
///
case flame = "flame"
///
case flameFill = "flame.fill"
///
case flashlightOffFill = "flashlight.off.fill"
///
case flashlightOnFill = "flashlight.on.fill"
///
case flipHorizontal = "flip.horizontal"
///
case flipHorizontalFill = "flip.horizontal.fill"
///
case florinsignCircle = "florinsign.circle"
///
case florinsignCircleFill = "florinsign.circle.fill"
///
case florinsignSquare = "florinsign.square"
///
case florinsignSquareFill = "florinsign.square.fill"
///
case flowchart = "flowchart"
///
case flowchartFill = "flowchart.fill"
///
case folder = "folder"
///
case folderBadgeMinus = "folder.badge.minus"
///
case folderBadgePersonCrop = "folder.badge.person.crop"
///
case folderBadgePlus = "folder.badge.plus"
///
case folderCircle = "folder.circle"
///
case folderCircleFill = "folder.circle.fill"
///
case folderFill = "folder.fill"
///
case folderFillBadgeMinus = "folder.fill.badge.minus"
///
case folderFillBadgePersonCrop = "folder.fill.badge.person.crop"
///
case folderFillBadgePlus = "folder.fill.badge.plus"
///
case forward = "forward"
///
case forwardEnd = "forward.end"
///
case forwardEndAlt = "forward.end.alt"
///
case forwardEndAltFill = "forward.end.alt.fill"
///
case forwardEndFill = "forward.end.fill"
///
case forwardFill = "forward.fill"
///
case francsignCircle = "francsign.circle"
///
case francsignCircleFill = "francsign.circle.fill"
///
case francsignSquare = "francsign.square"
///
case francsignSquareFill = "francsign.square.fill"
///
case function = "function"
///
case fx = "fx"
///
case gCircle = "g.circle"
///
case gCircleFill = "g.circle.fill"
///
case gSquare = "g.square"
///
case gSquareFill = "g.square.fill"
///
case gamecontroller = "gamecontroller"
///
case gamecontrollerFill = "gamecontroller.fill"
///
case gauge = "gauge"
///
case gaugeBadgeMinus = "gauge.badge.minus"
///
case gaugeBadgePlus = "gauge.badge.plus"
///
case gear = "gear"
///
case gift = "gift"
///
case giftFill = "gift.fill"
///
case globe = "globe"
///
case gobackward = "gobackward"
///
case gobackward10 = "gobackward.10"
///
case gobackward10Ar = "gobackward.10.ar"
///
case gobackward10Hi = "gobackward.10.hi"
///
case gobackward15 = "gobackward.15"
///
case gobackward15Ar = "gobackward.15.ar"
///
case gobackward15Hi = "gobackward.15.hi"
///
case gobackward30 = "gobackward.30"
///
case gobackward30Ar = "gobackward.30.ar"
///
case gobackward30Hi = "gobackward.30.hi"
///
case gobackward45 = "gobackward.45"
///
case gobackward45Ar = "gobackward.45.ar"
///
case gobackward45Hi = "gobackward.45.hi"
///
case gobackward60 = "gobackward.60"
///
case gobackward60Ar = "gobackward.60.ar"
///
case gobackward60Hi = "gobackward.60.hi"
///
case gobackward75 = "gobackward.75"
///
case gobackward75Ar = "gobackward.75.ar"
///
case gobackward75Hi = "gobackward.75.hi"
///
case gobackward90 = "gobackward.90"
///
case gobackward90Ar = "gobackward.90.ar"
///
case gobackward90Hi = "gobackward.90.hi"
///
case gobackwardMinus = "gobackward.minus"
///
case goforward = "goforward"
///
case goforward10 = "goforward.10"
///
case goforward10Ar = "goforward.10.ar"
///
case goforward10Hi = "goforward.10.hi"
///
case goforward15 = "goforward.15"
///
case goforward15Ar = "goforward.15.ar"
///
case goforward15Hi = "goforward.15.hi"
///
case goforward30 = "goforward.30"
///
case goforward30Ar = "goforward.30.ar"
///
case goforward30Hi = "goforward.30.hi"
///
case goforward45 = "goforward.45"
///
case goforward45Ar = "goforward.45.ar"
///
case goforward45Hi = "goforward.45.hi"
///
case goforward60 = "goforward.60"
///
case goforward60Ar = "goforward.60.ar"
///
case goforward60Hi = "goforward.60.hi"
///
case goforward75 = "goforward.75"
///
case goforward75Ar = "goforward.75.ar"
///
case goforward75Hi = "goforward.75.hi"
///
case goforward90 = "goforward.90"
///
case goforward90Ar = "goforward.90.ar"
///
case goforward90Hi = "goforward.90.hi"
///
case goforwardPlus = "goforward.plus"
///
case greaterthan = "greaterthan"
///
case greaterthanCircle = "greaterthan.circle"
///
case greaterthanCircleFill = "greaterthan.circle.fill"
///
case greaterthanSquare = "greaterthan.square"
///
case greaterthanSquareFill = "greaterthan.square.fill"
///
case grid = "grid"
///
case gridCircle = "grid.circle"
///
case gridCircleFill = "grid.circle.fill"
///
case guaranisignCircle = "guaranisign.circle"
///
case guaranisignCircleFill = "guaranisign.circle.fill"
///
case guaranisignSquare = "guaranisign.square"
///
case guaranisignSquareFill = "guaranisign.square.fill"
///
case guitars = "guitars"
///
case hCircle = "h.circle"
///
case hCircleFill = "h.circle.fill"
///
case hSquare = "h.square"
///
case hSquareFill = "h.square.fill"
///
case hammer = "hammer"
///
case hammerFill = "hammer.fill"
///
case handDraw = "hand.draw"
///
case handDrawFill = "hand.draw.fill"
///
case handPointLeft = "hand.point.left"
///
case handPointLeftFill = "hand.point.left.fill"
///
case handPointRight = "hand.point.right"
///
case handPointRightFill = "hand.point.right.fill"
///
case handRaised = "hand.raised"
///
case handRaisedFill = "hand.raised.fill"
///
case handRaisedSlash = "hand.raised.slash"
///
case handRaisedSlashFill = "hand.raised.slash.fill"
///
case handThumbsdown = "hand.thumbsdown"
///
case handThumbsdownFill = "hand.thumbsdown.fill"
///
case handThumbsup = "hand.thumbsup"
///
case handThumbsupFill = "hand.thumbsup.fill"
///
case hare = "hare"
///
case hareFill = "hare.fill"
///
case headphones = "headphones"
///
case heart = "heart"
///
case heartCircle = "heart.circle"
///
case heartCircleFill = "heart.circle.fill"
///
case heartFill = "heart.fill"
///
case heartSlash = "heart.slash"
///
case heartSlashCircle = "heart.slash.circle"
///
case heartSlashCircleFill = "heart.slash.circle.fill"
///
case heartSlashFill = "heart.slash.fill"
///
case helm = "helm"
///
case hexagon = "hexagon"
///
case hexagonFill = "hexagon.fill"
///
case hifispeaker = "hifispeaker"
///
case hifispeakerFill = "hifispeaker.fill"
///
case hourglass = "hourglass"
///
case hourglassBottomhalfFill = "hourglass.bottomhalf.fill"
///
case hourglassTophalfFill = "hourglass.tophalf.fill"
///
case house = "house"
///
case houseFill = "house.fill"
///
case hryvniasignCircle = "hryvniasign.circle"
///
case hryvniasignCircleFill = "hryvniasign.circle.fill"
///
case hryvniasignSquare = "hryvniasign.square"
///
case hryvniasignSquareFill = "hryvniasign.square.fill"
///
case hurricane = "hurricane"
///
case iCircle = "i.circle"
///
case iCircleFill = "i.circle.fill"
///
case iSquare = "i.square"
///
case iSquareFill = "i.square.fill"
///
/// (Can only refer to Apple's iCloud service)
case icloud = "icloud"
///
/// (Can only refer to Apple's iCloud service)
case icloudAndArrowDown = "icloud.and.arrow.down"
///
/// (Can only refer to Apple's iCloud service)
case icloudAndArrowDownFill = "icloud.and.arrow.down.fill"
///
/// (Can only refer to Apple's iCloud service)
case icloudAndArrowUp = "icloud.and.arrow.up"
///
/// (Can only refer to Apple's iCloud service)
case icloudAndArrowUpFill = "icloud.and.arrow.up.fill"
///
/// (Can only refer to Apple's iCloud service)
case icloudCircle = "icloud.circle"
///
/// (Can only refer to Apple's iCloud service)
case icloudCircleFill = "icloud.circle.fill"
///
/// (Can only refer to Apple's iCloud service)
case icloudFill = "icloud.fill"
///
/// (Can only refer to Apple's iCloud service)
case icloudSlash = "icloud.slash"
///
/// (Can only refer to Apple's iCloud service)
case icloudSlashFill = "icloud.slash.fill"
///
case increaseIndent = "increase.indent"
///
case increaseQuotelevel = "increase.quotelevel"
///
case indianrupeesignCircle = "indianrupeesign.circle"
///
case indianrupeesignCircleFill = "indianrupeesign.circle.fill"
///
case indianrupeesignSquare = "indianrupeesign.square"
///
case indianrupeesignSquareFill = "indianrupeesign.square.fill"
///
case info = "info"
///
case infoCircle = "info.circle"
///
case infoCircleFill = "info.circle.fill"
///
case italic = "italic"
///
case jCircle = "j.circle"
///
case jCircleFill = "j.circle.fill"
///
case jSquare = "j.square"
///
case jSquareFill = "j.square.fill"
///
case kCircle = "k.circle"
///
case kCircleFill = "k.circle.fill"
///
case kSquare = "k.square"
///
case kSquareFill = "k.square.fill"
///
case keyboard = "keyboard"
///
case keyboardChevronCompactDown = "keyboard.chevron.compact.down"
///
case kipsignCircle = "kipsign.circle"
///
case kipsignCircleFill = "kipsign.circle.fill"
///
case kipsignSquare = "kipsign.square"
///
case kipsignSquareFill = "kipsign.square.fill"
///
case lCircle = "l.circle"
///
case lCircleFill = "l.circle.fill"
///
case lSquare = "l.square"
///
case lSquareFill = "l.square.fill"
///
case largecircleFillCircle = "largecircle.fill.circle"
///
case larisignCircle = "larisign.circle"
///
case larisignCircleFill = "larisign.circle.fill"
///
case larisignSquare = "larisign.square"
///
case larisignSquareFill = "larisign.square.fill"
///
case lasso = "lasso"
///
case leafArrowCirclepath = "leaf.arrow.circlepath"
///
case lessthan = "lessthan"
///
case lessthanCircle = "lessthan.circle"
///
case lessthanCircleFill = "lessthan.circle.fill"
///
case lessthanSquare = "lessthan.square"
///
case lessthanSquareFill = "lessthan.square.fill"
///
case lightMax = "light.max"
///
case lightMin = "light.min"
///
case lightbulb = "lightbulb"
///
case lightbulbFill = "lightbulb.fill"
///
case lightbulbSlash = "lightbulb.slash"
///
case lightbulbSlashFill = "lightbulb.slash.fill"
///
case lineHorizontal3 = "line.horizontal.3"
///
case lineHorizontal3Decrease = "line.horizontal.3.decrease"
///
case lineHorizontal3DecreaseCircle = "line.horizontal.3.decrease.circle"
///
case lineHorizontal3DecreaseCircleFill = "line.horizontal.3.decrease.circle.fill"
///
case link = "link"
///
case linkCircle = "link.circle"
///
case linkCircleFill = "link.circle.fill"
///
/// (Can only refer to Apple's iCloud service)
case linkIcloud = "link.icloud"
///
/// (Can only refer to Apple's iCloud service)
case linkIcloudFill = "link.icloud.fill"
///
case lirasignCircle = "lirasign.circle"
///
case lirasignCircleFill = "lirasign.circle.fill"
///
case lirasignSquare = "lirasign.square"
///
case lirasignSquareFill = "lirasign.square.fill"
///
case listBullet = "list.bullet"
///
case listBulletBelowRectangle = "list.bullet.below.rectangle"
///
case listBulletIndent = "list.bullet.indent"
///
case listDash = "list.dash"
///
case listNumber = "list.number"
///
/// (Can only refer to Apple's Live Photos)
case livephoto = "livephoto"
///
/// (Can only refer to Apple's Live Photos)
case livephotoPlay = "livephoto.play"
///
/// (Can only refer to Apple's Live Photos)
case livephotoSlash = "livephoto.slash"
///
case location = "location"
///
case locationCircle = "location.circle"
///
case locationCircleFill = "location.circle.fill"
///
case locationFill = "location.fill"
///
case locationNorth = "location.north"
///
case locationNorthFill = "location.north.fill"
///
case locationNorthLine = "location.north.line"
///
case locationNorthLineFill = "location.north.line.fill"
///
case locationSlash = "location.slash"
///
case locationSlashFill = "location.slash.fill"
///
case lock = "lock"
///
case lockCircle = "lock.circle"
///
case lockCircleFill = "lock.circle.fill"
///
case lockFill = "lock.fill"
///
/// (Can only refer to Apple's iCloud service)
case lockIcloud = "lock.icloud"
///
/// (Can only refer to Apple's iCloud service)
case lockIcloudFill = "lock.icloud.fill"
///
case lockOpen = "lock.open"
///
case lockOpenFill = "lock.open.fill"
///
case lockRotation = "lock.rotation"
///
case lockRotationOpen = "lock.rotation.open"
///
case lockShield = "lock.shield"
///
case lockShieldFill = "lock.shield.fill"
///
case lockSlash = "lock.slash"
///
case lockSlashFill = "lock.slash.fill"
///
case mCircle = "m.circle"
///
case mCircleFill = "m.circle.fill"
///
case mSquare = "m.square"
///
case mSquareFill = "m.square.fill"
///
case macwindow = "macwindow"
///
case magnifyingglass = "magnifyingglass"
///
case magnifyingglassCircle = "magnifyingglass.circle"
///
case magnifyingglassCircleFill = "magnifyingglass.circle.fill"
///
case manatsignCircle = "manatsign.circle"
///
case manatsignCircleFill = "manatsign.circle.fill"
///
case manatsignSquare = "manatsign.square"
///
case manatsignSquareFill = "manatsign.square.fill"
///
case map = "map"
///
case mapFill = "map.fill"
///
case mappin = "mappin"
///
case mappinAndEllipse = "mappin.and.ellipse"
///
case mappinCircle = "mappin.circle"
///
case mappinCircleFill = "mappin.circle.fill"
///
case mappinSlash = "mappin.slash"
///
case memories = "memories"
///
case memoriesBadgeMinus = "memories.badge.minus"
///
case memoriesBadgePlus = "memories.badge.plus"
///
/// (Can only refer to Apple's Messages app)
case message = "message"
///
/// (Can only refer to Apple's Messages app)
case messageCircle = "message.circle"
///
/// (Can only refer to Apple's Messages app)
case messageCircleFill = "message.circle.fill"
///
/// (Can only refer to Apple's Messages app)
case messageFill = "message.fill"
///
case metronome = "metronome"
///
case mic = "mic"
///
case micCircle = "mic.circle"
///
case micCircleFill = "mic.circle.fill"
///
case micFill = "mic.fill"
///
case micSlash = "mic.slash"
///
case micSlashFill = "mic.slash.fill"
///
case millsignCircle = "millsign.circle"
///
case millsignCircleFill = "millsign.circle.fill"
///
case millsignSquare = "millsign.square"
///
case millsignSquareFill = "millsign.square.fill"
///
case minus = "minus"
///
case minusCircle = "minus.circle"
///
case minusCircleFill = "minus.circle.fill"
///
case minusMagnifyingglass = "minus.magnifyingglass"
///
case minusRectangle = "minus.rectangle"
///
case minusRectangleFill = "minus.rectangle.fill"
///
case minusSlashPlus = "minus.slash.plus"
///
case minusSquare = "minus.square"
///
case minusSquareFill = "minus.square.fill"
///
case moon = "moon"
///
case moonCircle = "moon.circle"
///
case moonCircleFill = "moon.circle.fill"
///
case moonFill = "moon.fill"
///
case moonStars = "moon.stars"
///
case moonStarsFill = "moon.stars.fill"
///
case moonZzz = "moon.zzz"
///
case moonZzzFill = "moon.zzz.fill"
///
case multiply = "multiply"
///
case multiplyCircle = "multiply.circle"
///
case multiplyCircleFill = "multiply.circle.fill"
///
case multiplySquare = "multiply.square"
///
case multiplySquareFill = "multiply.square.fill"
///
case musicHouse = "music.house"
///
case musicHouseFill = "music.house.fill"
///
case musicMic = "music.mic"
///
case musicNote = "music.note"
///
case musicNoteList = "music.note.list"
///
case nCircle = "n.circle"
///
case nCircleFill = "n.circle.fill"
///
case nSquare = "n.square"
///
case nSquareFill = "n.square.fill"
///
case nairasignCircle = "nairasign.circle"
///
case nairasignCircleFill = "nairasign.circle.fill"
///
case nairasignSquare = "nairasign.square"
///
case nairasignSquareFill = "nairasign.square.fill"
///
case nosign = "nosign"
///
case number = "number"
///
case numberCircle = "number.circle"
///
case numberCircleFill = "number.circle.fill"
///
case numberSquare = "number.square"
///
case numberSquareFill = "number.square.fill"
///
case oCircle = "o.circle"
///
case oCircleFill = "o.circle.fill"
///
case oSquare = "o.square"
///
case oSquareFill = "o.square.fill"
///
case option = "option"
///
case pCircle = "p.circle"
///
case pCircleFill = "p.circle.fill"
///
case pSquare = "p.square"
///
case pSquareFill = "p.square.fill"
///
case paintbrush = "paintbrush"
///
case paintbrushFill = "paintbrush.fill"
///
case pano = "pano"
///
case panoFill = "pano.fill"
///
case paperclip = "paperclip"
///
case paperclipCircle = "paperclip.circle"
///
case paperclipCircleFill = "paperclip.circle.fill"
///
case paperplane = "paperplane"
///
case paperplaneFill = "paperplane.fill"
///
case paragraph = "paragraph"
///
case pause = "pause"
///
case pauseCircle = "pause.circle"
///
case pauseCircleFill = "pause.circle.fill"
///
case pauseFill = "pause.fill"
///
case pauseRectangle = "pause.rectangle"
///
case pauseRectangleFill = "pause.rectangle.fill"
///
case pencil = "pencil"
///
case pencilAndEllipsisRectangle = "pencil.and.ellipsis.rectangle"
///
case pencilAndOutline = "pencil.and.outline"
///
case pencilCircle = "pencil.circle"
///
case pencilCircleFill = "pencil.circle.fill"
///
case pencilSlash = "pencil.slash"
///
/// (Can only refer to Apple's Markup feature)
case pencilTip = "pencil.tip"
///
/// (Can only refer to Apple's Markup feature)
case pencilTipCropCircle = "pencil.tip.crop.circle"
///
/// (Can only refer to Apple's Markup feature)
case pencilTipCropCircleBadgeMinus = "pencil.tip.crop.circle.badge.minus"
///
/// (Can only refer to Apple's Markup feature)
case pencilTipCropCircleBadgePlus = "pencil.tip.crop.circle.badge.plus"
///
case percent = "percent"
///
case person = "person"
///
case person2 = "person.2"
///
case person2Fill = "person.2.fill"
///
case person2SquareStack = "person.2.square.stack"
///
case person2SquareStackFill = "person.2.square.stack.fill"
///
case person3 = "person.3"
///
case person3Fill = "person.3.fill"
///
case personBadgeMinus = "person.badge.minus"
///
case personBadgeMinusFill = "person.badge.minus.fill"
///
case personBadgePlus = "person.badge.plus"
///
case personBadgePlusFill = "person.badge.plus.fill"
///
case personCircle = "person.circle"
///
case personCircleFill = "person.circle.fill"
///
case personCropCircle = "person.crop.circle"
///
case personCropCircleBadgeCheckmark = "person.crop.circle.badge.checkmark"
///
case personCropCircleBadgeExclam = "person.crop.circle.badge.exclam"
///
case personCropCircleBadgeMinus = "person.crop.circle.badge.minus"
///
case personCropCircleBadgePlus = "person.crop.circle.badge.plus"
///
case personCropCircleBadgeXmark = "person.crop.circle.badge.xmark"
///
case personCropCircleFill = "person.crop.circle.fill"
///
case personCropCircleFillBadgeCheckmark = "person.crop.circle.fill.badge.checkmark"
///
case personCropCircleFillBadgeExclam = "person.crop.circle.fill.badge.exclam"
///
case personCropCircleFillBadgeMinus = "person.crop.circle.fill.badge.minus"
///
case personCropCircleFillBadgePlus = "person.crop.circle.fill.badge.plus"
///
case personCropCircleFillBadgeXmark = "person.crop.circle.fill.badge.xmark"
///
case personCropRectangle = "person.crop.rectangle"
///
case personCropRectangleFill = "person.crop.rectangle.fill"
///
case personCropSquare = "person.crop.square"
///
case personCropSquareFill = "person.crop.square.fill"
///
case personFill = "person.fill"
///
/// (Can only refer to Apple's iCloud service)
case personIcloud = "person.icloud"
///
/// (Can only refer to Apple's iCloud service)
case personIcloudFill = "person.icloud.fill"
///
case personalhotspot = "personalhotspot"
///
case perspective = "perspective"
///
case pesetasignCircle = "pesetasign.circle"
///
case pesetasignCircleFill = "pesetasign.circle.fill"
///
case pesetasignSquare = "pesetasign.square"
///
case pesetasignSquareFill = "pesetasign.square.fill"
///
case pesosignCircle = "pesosign.circle"
///
case pesosignCircleFill = "pesosign.circle.fill"
///
case pesosignSquare = "pesosign.square"
///
case pesosignSquareFill = "pesosign.square.fill"
///
case phone = "phone"
///
case phoneArrowDownLeft = "phone.arrow.down.left"
///
case phoneArrowRight = "phone.arrow.right"
///
case phoneArrowUpRight = "phone.arrow.up.right"
///
case phoneBadgePlus = "phone.badge.plus"
///
case phoneCircle = "phone.circle"
///
case phoneCircleFill = "phone.circle.fill"
///
case phoneDown = "phone.down"
///
case phoneDownCircle = "phone.down.circle"
///
case phoneDownCircleFill = "phone.down.circle.fill"
///
case phoneDownFill = "phone.down.fill"
///
case phoneFill = "phone.fill"
///
case phoneFillArrowDownLeft = "phone.fill.arrow.down.left"
///
case phoneFillArrowRight = "phone.fill.arrow.right"
///
case phoneFillArrowUpRight = "phone.fill.arrow.up.right"
///
case phoneFillBadgePlus = "phone.fill.badge.plus"
///
case photo = "photo"
///
case photoFill = "photo.fill"
///
case photoFillOnRectangleFill = "photo.fill.on.rectangle.fill"
///
case photoOnRectangle = "photo.on.rectangle"
///
case pin = "pin"
///
case pinCircle = "pin.circle"
///
case pinCircleFill = "pin.circle.fill"
///
case pinFill = "pin.fill"
///
case pinSlash = "pin.slash"
///
case pinSlashFill = "pin.slash.fill"
///
case play = "play"
///
case playCircle = "play.circle"
///
case playCircleFill = "play.circle.fill"
///
case playFill = "play.fill"
///
case playRectangle = "play.rectangle"
///
case playRectangleFill = "play.rectangle.fill"
///
case playpause = "playpause"
///
case playpauseFill = "playpause.fill"
///
case plus = "plus"
///
case plusApp = "plus.app"
///
case plusAppFill = "plus.app.fill"
///
case plusBubble = "plus.bubble"
///
case plusBubbleFill = "plus.bubble.fill"
///
case plusCircle = "plus.circle"
///
case plusCircleFill = "plus.circle.fill"
///
case plusMagnifyingglass = "plus.magnifyingglass"
///
case plusRectangle = "plus.rectangle"
///
case plusRectangleFill = "plus.rectangle.fill"
///
case plusRectangleFillOnRectangleFill = "plus.rectangle.fill.on.rectangle.fill"
///
case plusRectangleOnRectangle = "plus.rectangle.on.rectangle"
///
case plusSlashMinus = "plus.slash.minus"
///
case plusSquare = "plus.square"
///
case plusSquareFill = "plus.square.fill"
///
case plusSquareFillOnSquareFill = "plus.square.fill.on.square.fill"
///
case plusSquareOnSquare = "plus.square.on.square"
///
case plusminus = "plusminus"
///
case plusminusCircle = "plusminus.circle"
///
case plusminusCircleFill = "plusminus.circle.fill"
///
case power = "power"
///
case printer = "printer"
///
case printerFill = "printer.fill"
///
case projective = "projective"
///
case purchased = "purchased"
///
case purchasedCircle = "purchased.circle"
///
case purchasedCircleFill = "purchased.circle.fill"
///
case qCircle = "q.circle"
///
case qCircleFill = "q.circle.fill"
///
case qSquare = "q.square"
///
case qSquareFill = "q.square.fill"
///
case qrcode = "qrcode"
///
case qrcodeViewfinder = "qrcode.viewfinder"
///
case questionmark = "questionmark"
///
case questionmarkCircle = "questionmark.circle"
///
case questionmarkCircleFill = "questionmark.circle.fill"
///
case questionmarkDiamond = "questionmark.diamond"
///
case questionmarkDiamondFill = "questionmark.diamond.fill"
///
case questionmarkSquare = "questionmark.square"
///
case questionmarkSquareFill = "questionmark.square.fill"
///
/// (Can only refer to Apple's FaceTime app)
case questionmarkVideo = "questionmark.video"
///
/// (Can only refer to Apple's FaceTime app)
case questionmarkVideoFill = "questionmark.video.fill"
///
case quoteBubble = "quote.bubble"
///
case quoteBubbleFill = "quote.bubble.fill"
///
case rCircle = "r.circle"
///
case rCircleFill = "r.circle.fill"
///
case rSquare = "r.square"
///
case rSquareFill = "r.square.fill"
///
case radiowavesLeft = "radiowaves.left"
///
case radiowavesRight = "radiowaves.right"
///
case rays = "rays"
///
case recordingtape = "recordingtape"
///
case rectangle = "rectangle"
///
case rectangle3Offgrid = "rectangle.3.offgrid"
///
case rectangle3OffgridFill = "rectangle.3.offgrid.fill"
///
case rectangleAndArrowUpRightAndArrowDownLeft = "rectangle.and.arrow.up.right.and.arrow.down.left"
///
case rectangleAndArrowUpRightAndArrowDownLeftSlash = "rectangle.and.arrow.up.right.and.arrow.down.left.slash"
///
case rectangleAndPaperclip = "rectangle.and.paperclip"
///
case rectangleBadgeCheckmark = "rectangle.badge.checkmark"
///
case rectangleBadgeXmark = "rectangle.badge.xmark"
///
case rectangleCompressVertical = "rectangle.compress.vertical"
///
case rectangleDock = "rectangle.dock"
///
case rectangleExpandVertical = "rectangle.expand.vertical"
///
case rectangleFill = "rectangle.fill"
///
case rectangleFillBadgeCheckmark = "rectangle.fill.badge.checkmark"
///
case rectangleFillBadgeXmark = "rectangle.fill.badge.xmark"
///
case rectangleFillOnRectangleAngledFill = "rectangle.fill.on.rectangle.angled.fill"
///
case rectangleFillOnRectangleFill = "rectangle.fill.on.rectangle.fill"
///
case rectangleGrid1x2 = "rectangle.grid.1x2"
///
case rectangleGrid1x2Fill = "rectangle.grid.1x2.fill"
///
case rectangleGrid2x2 = "rectangle.grid.2x2"
///
case rectangleGrid2x2Fill = "rectangle.grid.2x2.fill"
///
case rectangleGrid3x2 = "rectangle.grid.3x2"
///
case rectangleGrid3x2Fill = "rectangle.grid.3x2.fill"
///
case rectangleOnRectangle = "rectangle.on.rectangle"
///
case rectangleOnRectangleAngled = "rectangle.on.rectangle.angled"
///
case rectangleSplit3x1 = "rectangle.split.3x1"
///
case rectangleSplit3x1Fill = "rectangle.split.3x1.fill"
///
case rectangleSplit3x3 = "rectangle.split.3x3"
///
case rectangleSplit3x3Fill = "rectangle.split.3x3.fill"
///
case rectangleStack = "rectangle.stack"
///
case rectangleStackBadgeMinus = "rectangle.stack.badge.minus"
///
case rectangleStackBadgePersonCrop = "rectangle.stack.badge.person.crop"
///
case rectangleStackBadgePlus = "rectangle.stack.badge.plus"
///
case rectangleStackFill = "rectangle.stack.fill"
///
case rectangleStackFillBadgeMinus = "rectangle.stack.fill.badge.minus"
///
case rectangleStackFillBadgePersonCrop = "rectangle.stack.fill.badge.person.crop"
///
case rectangleStackFillBadgePlus = "rectangle.stack.fill.badge.plus"
///
case rectangleStackPersonCrop = "rectangle.stack.person.crop"
///
case rectangleStackPersonCropFill = "rectangle.stack.person.crop.fill"
///
case repeat1 = "repeat.1"
///
case rhombus = "rhombus"
///
case rhombusFill = "rhombus.fill"
///
case rosette = "rosette"
///
case rotateLeft = "rotate.left"
///
case rotateLeftFill = "rotate.left.fill"
///
case rotateRight = "rotate.right"
///
case rotateRightFill = "rotate.right.fill"
///
case rublesignCircle = "rublesign.circle"
///
case rublesignCircleFill = "rublesign.circle.fill"
///
case rublesignSquare = "rublesign.square"
///
case rublesignSquareFill = "rublesign.square.fill"
///
case rupeesignCircle = "rupeesign.circle"
///
case rupeesignCircleFill = "rupeesign.circle.fill"
///
case rupeesignSquare = "rupeesign.square"
///
case rupeesignSquareFill = "rupeesign.square.fill"
///
case sCircle = "s.circle"
///
case sCircleFill = "s.circle.fill"
///
case sSquare = "s.square"
///
case sSquareFill = "s.square.fill"
///
/// (Can only refer to Apple's Safari browser)
case safari = "safari"
///
/// (Can only refer to Apple's Safari browser)
case safariFill = "safari.fill"
///
case scissors = "scissors"
///
case scissorsBadgeEllipsis = "scissors.badge.ellipsis"
///
case scope = "scope"
///
case scribble = "scribble"
///
case selectionPinInOut = "selection.pin.in.out"
///
case sheqelsignCircle = "sheqelsign.circle"
///
case sheqelsignCircleFill = "sheqelsign.circle.fill"
///
case sheqelsignSquare = "sheqelsign.square"
///
case sheqelsignSquareFill = "sheqelsign.square.fill"
///
case shield = "shield"
///
case shieldFill = "shield.fill"
///
case shieldLefthalfFill = "shield.lefthalf.fill"
///
case shieldSlash = "shield.slash"
///
case shieldSlashFill = "shield.slash.fill"
///
case shift = "shift"
///
case shiftFill = "shift.fill"
///
case shuffle = "shuffle"
///
case sidebarLeft = "sidebar.left"
///
case sidebarRight = "sidebar.right"
///
case signature = "signature"
///
case skew = "skew"
///
case slashCircle = "slash.circle"
///
case slashCircleFill = "slash.circle.fill"
///
case sliderHorizontal3 = "slider.horizontal.3"
///
case sliderHorizontalBelowRectangle = "slider.horizontal.below.rectangle"
///
case slowmo = "slowmo"
///
case smallcircleCircle = "smallcircle.circle"
///
case smallcircleCircleFill = "smallcircle.circle.fill"
///
case smallcircleFillCircle = "smallcircle.fill.circle"
///
case smallcircleFillCircleFill = "smallcircle.fill.circle.fill"
///
case smiley = "smiley"
///
case smileyFill = "smiley.fill"
///
case smoke = "smoke"
///
case smokeFill = "smoke.fill"
///
case snow = "snow"
///
case sparkles = "sparkles"
///
case speaker = "speaker"
///
case speaker1 = "speaker.1"
///
case speaker1Fill = "speaker.1.fill"
///
case speaker2 = "speaker.2"
///
case speaker2Fill = "speaker.2.fill"
///
case speaker3 = "speaker.3"
///
case speaker3Fill = "speaker.3.fill"
///
case speakerFill = "speaker.fill"
///
case speakerSlash = "speaker.slash"
///
case speakerSlashFill = "speaker.slash.fill"
///
case speakerZzz = "speaker.zzz"
///
case speakerZzzFill = "speaker.zzz.fill"
///
case speedometer = "speedometer"
///
case sportscourt = "sportscourt"
///
case sportscourtFill = "sportscourt.fill"
///
case square = "square"
///
case squareAndArrowDown = "square.and.arrow.down"
///
case squareAndArrowDownFill = "square.and.arrow.down.fill"
///
case squareAndArrowDownOnSquare = "square.and.arrow.down.on.square"
///
case squareAndArrowDownOnSquareFill = "square.and.arrow.down.on.square.fill"
///
case squareAndArrowUp = "square.and.arrow.up"
///
case squareAndArrowUpFill = "square.and.arrow.up.fill"
///
case squareAndArrowUpOnSquare = "square.and.arrow.up.on.square"
///
case squareAndArrowUpOnSquareFill = "square.and.arrow.up.on.square.fill"
///
case squareAndLineVerticalAndSquare = "square.and.line.vertical.and.square"
///
case squareAndLineVerticalAndSquareFill = "square.and.line.vertical.and.square.fill"
///
case squareAndPencil = "square.and.pencil"
///
case squareFill = "square.fill"
///
case squareFillAndLineVerticalAndSquare = "square.fill.and.line.vertical.and.square"
///
case squareFillAndLineVerticalSquareFill = "square.fill.and.line.vertical.square.fill"
///
case squareFillOnCircleFill = "square.fill.on.circle.fill"
///
case squareFillOnSquareFill = "square.fill.on.square.fill"
///
case squareGrid2x2 = "square.grid.2x2"
///
case squareGrid2x2Fill = "square.grid.2x2.fill"
///
case squareGrid3x2 = "square.grid.3x2"
///
case squareGrid3x2Fill = "square.grid.3x2.fill"
///
case squareGrid4x3Fill = "square.grid.4x3.fill"
///
case squareLefthalfFill = "square.lefthalf.fill"
///
case squareOnCircle = "square.on.circle"
///
case squareOnSquare = "square.on.square"
///
case squareRighthalfFill = "square.righthalf.fill"
///
case squareSplit1x2 = "square.split.1x2"
///
case squareSplit1x2Fill = "square.split.1x2.fill"
///
case squareSplit2x1 = "square.split.2x1"
///
case squareSplit2x1Fill = "square.split.2x1.fill"
///
case squareSplit2x2 = "square.split.2x2"
///
case squareSplit2x2Fill = "square.split.2x2.fill"
///
case squareStack = "square.stack"
///
case squareStack3dDownDottedline = "square.stack.3d.down.dottedline"
///
case squareStack3dDownRight = "square.stack.3d.down.right"
///
case squareStack3dDownRightFill = "square.stack.3d.down.right.fill"
///
case squareStack3dUp = "square.stack.3d.up"
///
case squareStack3dUpFill = "square.stack.3d.up.fill"
///
case squareStack3dUpSlash = "square.stack.3d.up.slash"
///
case squareStack3dUpSlashFill = "square.stack.3d.up.slash.fill"
///
case squareStackFill = "square.stack.fill"
///
case squaresBelowRectangle = "squares.below.rectangle"
///
case star = "star"
///
case starCircle = "star.circle"
///
case starCircleFill = "star.circle.fill"
///
case starFill = "star.fill"
///
case starLefthalfFill = "star.lefthalf.fill"
///
case starSlash = "star.slash"
///
case starSlashFill = "star.slash.fill"
///
case staroflife = "staroflife"
///
case staroflifeFill = "staroflife.fill"
///
case sterlingsignCircle = "sterlingsign.circle"
///
case sterlingsignCircleFill = "sterlingsign.circle.fill"
///
case sterlingsignSquare = "sterlingsign.square"
///
case sterlingsignSquareFill = "sterlingsign.square.fill"
///
case stop = "stop"
///
case stopCircle = "stop.circle"
///
case stopCircleFill = "stop.circle.fill"
///
case stopFill = "stop.fill"
///
case stopwatch = "stopwatch"
///
case stopwatchFill = "stopwatch.fill"
///
case strikethrough = "strikethrough"
///
case studentdesk = "studentdesk"
///
case suitClub = "suit.club"
///
case suitClubFill = "suit.club.fill"
///
case suitDiamond = "suit.diamond"
///
case suitDiamondFill = "suit.diamond.fill"
///
case suitHeart = "suit.heart"
///
case suitHeartFill = "suit.heart.fill"
///
case suitSpade = "suit.spade"
///
case suitSpadeFill = "suit.spade.fill"
///
case sum = "sum"
///
case sunDust = "sun.dust"
///
case sunDustFill = "sun.dust.fill"
///
case sunHaze = "sun.haze"
///
case sunHazeFill = "sun.haze.fill"
///
case sunMax = "sun.max"
///
case sunMaxFill = "sun.max.fill"
///
case sunMin = "sun.min"
///
case sunMinFill = "sun.min.fill"
///
case sunrise = "sunrise"
///
case sunriseFill = "sunrise.fill"
///
case sunset = "sunset"
///
case sunsetFill = "sunset.fill"
///
case tBubble = "t.bubble"
///
case tBubbleFill = "t.bubble.fill"
///
case tCircle = "t.circle"
///
case tCircleFill = "t.circle.fill"
///
case tSquare = "t.square"
///
case tSquareFill = "t.square.fill"
///
case table = "table"
///
case tableBadgeMore = "table.badge.more"
///
case tableBadgeMoreFill = "table.badge.more.fill"
///
case tableFill = "table.fill"
///
case tag = "tag"
///
case tagCircle = "tag.circle"
///
case tagCircleFill = "tag.circle.fill"
///
case tagFill = "tag.fill"
///
/// (Can only refer to Apple's Teletype feature)
case teletype = "teletype"
///
case teletypeAnswer = "teletype.answer"
///
case tengesignCircle = "tengesign.circle"
///
case tengesignCircleFill = "tengesign.circle.fill"
///
case tengesignSquare = "tengesign.square"
///
case tengesignSquareFill = "tengesign.square.fill"
///
case textAligncenter = "text.aligncenter"
///
case textAlignleft = "text.alignleft"
///
case textAlignright = "text.alignright"
///
case textAppend = "text.append"
///
case textBadgeCheckmark = "text.badge.checkmark"
///
case textBadgeMinus = "text.badge.minus"
///
case textBadgePlus = "text.badge.plus"
///
case textBadgeStar = "text.badge.star"
///
case textBadgeXmark = "text.badge.xmark"
///
case textBubble = "text.bubble"
///
case textBubbleFill = "text.bubble.fill"
///
case textCursor = "text.cursor"
///
case textInsert = "text.insert"
///
case textJustify = "text.justify"
///
case textJustifyleft = "text.justifyleft"
///
case textJustifyright = "text.justifyright"
///
case textQuote = "text.quote"
///
case textbox = "textbox"
///
case textformat = "textformat"
///
case textformat123 = "textformat.123"
///
case textformatAbc = "textformat.abc"
///
case textformatAbcDottedunderline = "textformat.abc.dottedunderline"
///
case textformatAlt = "textformat.alt"
///
case textformatSize = "textformat.size"
///
case textformatSubscript = "textformat.subscript"
///
case textformatSuperscript = "textformat.superscript"
///
case thermometer = "thermometer"
///
case thermometerSnowflake = "thermometer.snowflake"
///
case thermometerSun = "thermometer.sun"
///
case timelapse = "timelapse"
///
case timer = "timer"
///
case tornado = "tornado"
///
case tortoise = "tortoise"
///
case tortoiseFill = "tortoise.fill"
///
case tramFill = "tram.fill"
///
case trash = "trash"
///
case trashCircle = "trash.circle"
///
case trashCircleFill = "trash.circle.fill"
///
case trashFill = "trash.fill"
///
case trashSlash = "trash.slash"
///
case trashSlashFill = "trash.slash.fill"
///
case tray = "tray"
///
case tray2 = "tray.2"
///
case tray2Fill = "tray.2.fill"
///
case trayAndArrowDown = "tray.and.arrow.down"
///
case trayAndArrowDownFill = "tray.and.arrow.down.fill"
///
case trayAndArrowUp = "tray.and.arrow.up"
///
case trayAndArrowUpFill = "tray.and.arrow.up.fill"
///
case trayFill = "tray.fill"
///
case trayFull = "tray.full"
///
case trayFullFill = "tray.full.fill"
///
case triangle = "triangle"
///
case triangleFill = "triangle.fill"
///
case triangleLefthalfFill = "triangle.lefthalf.fill"
///
case triangleRighthalfFill = "triangle.righthalf.fill"
///
case tropicalstorm = "tropicalstorm"
///
case tugriksignCircle = "tugriksign.circle"
///
case tugriksignCircleFill = "tugriksign.circle.fill"
///
case tugriksignSquare = "tugriksign.square"
///
case tugriksignSquareFill = "tugriksign.square.fill"
///
case tuningfork = "tuningfork"
///
case turkishlirasignCircle = "turkishlirasign.circle"
///
case turkishlirasignCircleFill = "turkishlirasign.circle.fill"
///
case turkishlirasignSquare = "turkishlirasign.square"
///
case turkishlirasignSquareFill = "turkishlirasign.square.fill"
///
case tv = "tv"
///
case tvCircle = "tv.circle"
///
case tvCircleFill = "tv.circle.fill"
///
case tvFill = "tv.fill"
///
case tvMusicNote = "tv.music.note"
///
case tvMusicNoteFill = "tv.music.note.fill"
///
case uCircle = "u.circle"
///
case uCircleFill = "u.circle.fill"
///
case uSquare = "u.square"
///
case uSquareFill = "u.square.fill"
///
case uiwindowSplit2x1 = "uiwindow.split.2x1"
///
case umbrella = "umbrella"
///
case umbrellaFill = "umbrella.fill"
///
case underline = "underline"
///
case vCircle = "v.circle"
///
case vCircleFill = "v.circle.fill"
///
case vSquare = "v.square"
///
case vSquareFill = "v.square.fill"
///
/// (Can only refer to Apple's FaceTime app)
case video = "video"
///
/// (Can only refer to Apple's FaceTime app)
case videoBadgePlus = "video.badge.plus"
///
/// (Can only refer to Apple's FaceTime app)
case videoBadgePlusFill = "video.badge.plus.fill"
///
/// (Can only refer to Apple's FaceTime app)
case videoCircle = "video.circle"
///
/// (Can only refer to Apple's FaceTime app)
case videoCircleFill = "video.circle.fill"
///
/// (Can only refer to Apple's FaceTime app)
case videoFill = "video.fill"
///
/// (Can only refer to Apple's FaceTime app)
case videoSlash = "video.slash"
///
/// (Can only refer to Apple's FaceTime app)
case videoSlashFill = "video.slash.fill"
///
case view2d = "view.2d"
///
case view3d = "view.3d"
///
case viewfinder = "viewfinder"
///
case viewfinderCircle = "viewfinder.circle"
///
case viewfinderCircleFill = "viewfinder.circle.fill"
///
case wCircle = "w.circle"
///
case wCircleFill = "w.circle.fill"
///
case wSquare = "w.square"
///
case wSquareFill = "w.square.fill"
///
case wandAndRays = "wand.and.rays"
///
case wandAndRaysInverse = "wand.and.rays.inverse"
///
case wandAndStars = "wand.and.stars"
///
case wandAndStarsInverse = "wand.and.stars.inverse"
///
case waveform = "waveform"
///
case waveformCircle = "waveform.circle"
///
case waveformCircleFill = "waveform.circle.fill"
///
case waveformPath = "waveform.path"
///
case waveformPathBadgeMinus = "waveform.path.badge.minus"
///
case waveformPathBadgePlus = "waveform.path.badge.plus"
///
case waveformPathEcg = "waveform.path.ecg"
///
case wifi = "wifi"
///
case wifiExclamationmark = "wifi.exclamationmark"
///
case wifiSlash = "wifi.slash"
///
case wind = "wind"
///
case windSnow = "wind.snow"
///
case wonsignCircle = "wonsign.circle"
///
case wonsignCircleFill = "wonsign.circle.fill"
///
case wonsignSquare = "wonsign.square"
///
case wonsignSquareFill = "wonsign.square.fill"
///
case wrench = "wrench"
///
case wrenchFill = "wrench.fill"
///
case xCircle = "x.circle"
///
case xCircleFill = "x.circle.fill"
///
case xSquare = "x.square"
///
case xSquareFill = "x.square.fill"
///
case xSquareroot = "x.squareroot"
///
case xmark = "xmark"
///
case xmarkCircle = "xmark.circle"
///
case xmarkCircleFill = "xmark.circle.fill"
///
/// (Can only refer to Apple's iCloud service)
case xmarkIcloud = "xmark.icloud"
///
/// (Can only refer to Apple's iCloud service)
case xmarkIcloudFill = "xmark.icloud.fill"
///
case xmarkOctagon = "xmark.octagon"
///
case xmarkOctagonFill = "xmark.octagon.fill"
///
case xmarkRectangle = "xmark.rectangle"
///
case xmarkRectangleFill = "xmark.rectangle.fill"
///
case xmarkSeal = "xmark.seal"
///
case xmarkSealFill = "xmark.seal.fill"
///
case xmarkShield = "xmark.shield"
///
case xmarkShieldFill = "xmark.shield.fill"
///
case xmarkSquare = "xmark.square"
///
case xmarkSquareFill = "xmark.square.fill"
///
case yCircle = "y.circle"
///
case yCircleFill = "y.circle.fill"
///
case ySquare = "y.square"
///
case ySquareFill = "y.square.fill"
///
case yensignCircle = "yensign.circle"
///
case yensignCircleFill = "yensign.circle.fill"
///
case yensignSquare = "yensign.square"
///
case yensignSquareFill = "yensign.square.fill"
///
case zCircle = "z.circle"
///
case zCircleFill = "z.circle.fill"
///
case zSquare = "z.square"
///
case zSquareFill = "z.square.fill"
///
case zzz = "zzz"
}
| apache-2.0 | a9e3a0e5836c31c066b347c7235be071 | 17.705628 | 113 | 0.569418 | 2.776749 | false | false | false | false |
bsorrentino/slidesOnTV | slides/slides/SearchViews.swift | 1 | 4688 | //
// SearchView.swift
// slides
//
// Created by Bartolomeo Sorrentino on 07/11/21.
// Copyright © 2021 bsorrentino. All rights reserved.
//
import SwiftUI
import SDWebImageSwiftUI
fileprivate let Const = (
cardSize: CGSize( width: 490, height: 300 ),
ProgressView: (fill:Color.white.opacity(0.5), radius:CGFloat(10))
)
private struct SearchResultImageView<T> : View where T : SlideItem {
@Environment(\.isFocused) var focused: Bool
var item: T
var onFocusChange: (T,Bool) -> Void = { _,_ in }
private var placeholderView:some View {
Rectangle().foregroundColor(.gray)
}
private var imageLoadError:Bool {
item.thumbnail == nil || WebImageId > 0
}
private var url:URL? {
guard let thumbnail = item.thumbnail, WebImageId == 0 else {
return URL.fromXCAsset(name: "slideshow" )
}
return URL(string: thumbnail)
}
@State private var WebImageId = 0
var body: some View {
Group {
if( isInPreviewMode ) {
Image("slideshow")
.resizable()
.scaledToFit()
}
else {
VStack {
// Supports options and context, like `.delayPlaceholder` to show placeholder only when error
WebImage(url: url , options: .delayPlaceholder )
.placeholder( Image(systemName: "photo") ) // Placeholder Image
.resizable() // Resizable like SwiftUI.Image, you must use this modifier or the view will use the image bitmap size
// .onSuccess { image, data, cacheType in }
.onFailure { err in WebImageId += 1 } // force refresh @ref https://stackoverflow.com/a/65095862/521197
.indicator(.activity) // Activity Indicator
.transition(.fade(duration: 0.5)) // Fade Transition with duration
.scaledToFit()
.id( WebImageId )
if( imageLoadError ) {
Divider()
Text( "\(item.title)" )
.foregroundColor(Color.black)
}
}
}
}
.onChange(of: focused, perform: {
print( "ThumbnailView(\(item.title)): old:\(focused) new:\($0)")
onFocusChange( item, $0 ) // Workaround for 'CardButtonStyle' bug
})
// .frame(width: item.thumbnailSize.width, height: item.thumbnailSize.height, alignment: .center)
}
}
struct SearchCardView<T> : View where T : SlideItem {
@EnvironmentObject var downloadManager:DownloadManager<T>
var item: T
var onFocusChange: (T, Bool) -> Void
var body: some View {
SearchResultImageView( item: item, onFocusChange: onFocusChange)
.if( self.downloadManager.isDownloading(item: item) ) {
$0.overlay( DownloadProgressView(), alignment: .bottom )
}
.padding()
.frame( width: Const.cardSize.width, height: Const.cardSize.height)
.background(Color.white)
}
func DownloadProgressView() -> some View {
ZStack {
Rectangle()
.fill( Const.ProgressView.fill )
.cornerRadius(Const.ProgressView.radius)
.shadow( color: Color.black, radius: Const.ProgressView.radius )
ProgressView( "Download: \(self.downloadManager.downloadingDescription)", value: self.downloadManager.downloadProgress?.0, total:1)
.progressViewStyle(BlueShadowProgressViewStyle())
.padding()
}
}
}
/**
* TITLE VIEW
*/
func TitleView<T>( selectedItem: T?) -> some View where T : SlideItem {
Group {
if let item = selectedItem {
VStack(spacing:0) {
Text( item.title )
.font(.system(.headline).weight(.semibold))
.truncationMode(.tail)
.padding(EdgeInsets(top: 0,leading: 10,bottom: 0,trailing: 10))
.foregroundColor(.blue)
.fixedSize(horizontal: false, vertical: false)
.lineLimit(1)
if let updated = item.updated {
Divider()
Text( "\(updated)")
.font(.system(.subheadline))
.foregroundColor(.purple)
}
}
}
else {
EmptyView()
}
}
}
| mit | cbb603e749ffbae7302c0b4ffffbea4b | 31.324138 | 143 | 0.524216 | 4.872141 | false | false | false | false |
niunaruto/DeDaoAppSwift | DeDaoSwift/DeDaoSwift/Home/View/DDHomeTableHeadView.swift | 1 | 6917 | //
// DDHomeTableHeadView.swift
// DeDaoSwift
//
// Created by niuting on 2017/3/14.
// Copyright © 2017年 niuNaruto. All rights reserved.
//
import UIKit
class DDHomeTableHeadView: DDBaseTableHeaderFooterView {
lazy var leftLiveImage : UIImageView = UIImageView(image: UIImage(named: "homeLiveLight"))
override func setHeadFootViewModel(_ model: Any?) {
if let modelT = model as? Array<Any> {
guard modelT.count >= 2 else {
return
}
let type = modelT[1] as? String
let dataModel = modelT[0] as? DDHomeDataModel
settingNormalUI()
setSubViewContent(type, dataModel)
}
}
lazy var leftLabel : UILabel = {
let leftLabel = UILabel()
leftLabel.textColor = UIColor.init("#333333")
leftLabel.font = UIFont.systemFont(ofSize: 13)
return leftLabel
}()
lazy var rightLabel : UILabel = {
let rightLabel = UILabel()
rightLabel.textColor = UIColor.init("#999999")
rightLabel.font = UIFont.systemFont(ofSize: 12)
return rightLabel
}()
lazy var rightImageView = UIImageView()
override func setUI() {
contentView.addSubview(leftLiveImage)
contentView.addSubview(leftLabel)
contentView.addSubview(rightLabel)
contentView.addSubview(rightImageView)
leftLiveImage.isHidden = true
let bottomLine = UIView()
bottomLine.backgroundColor = UIColor.init("#efefef")
contentView.addSubview(bottomLine)
bottomLine.snp.makeConstraints { (make) in
make.bottom.equalToSuperview()
make.right.equalTo(rightImageView.snp.right).offset(-10)
make.left.equalTo(leftLabel.snp.left)
make.height.equalTo(1)
}
}
override func setLayout() {
leftLiveImage.snp.makeConstraints { (make) in
make.centerY.equalToSuperview()
make.left.equalToSuperview().offset(10)
}
rightImageView.snp.makeConstraints { (make) in
make.centerY.equalToSuperview()
make.right.equalToSuperview().offset(0)
}
leftLabel.snp.makeConstraints { (make) in
make.centerY.equalToSuperview()
make.left.equalTo(leftLiveImage.snp.left)
}
rightLabel.snp.makeConstraints { (make) in
make.centerY.equalToSuperview()
make.right.equalTo(rightImageView.snp.left).offset(16)
}
}
func settingNormalUI() {
self.leftLabel.textColor = UIColor.init("#333333")
leftLiveImage.isHidden = true
rightImageView.isHidden = false
rightImageView.image = UIImage.init(named: "new_main_subscribe_right")
rightImageView.transform = CGAffineTransform(rotationAngle: CGFloat(0));
rightLabel.snp.remakeConstraints { (make) in
make.centerY.equalToSuperview()
make.right.equalTo(rightImageView.snp.left).offset(16)
}
rightImageView.snp.remakeConstraints { (make) in
make.centerY.equalToSuperview()
make.right.equalToSuperview().offset(0)
}
self.leftLabel.snp.remakeConstraints({ (make) in
make.centerY.equalToSuperview()
make.left.equalTo(leftLiveImage.snp.left)
})
self.rightLabel.snp.remakeConstraints { (make) in
make.centerY.equalToSuperview()
make.right.equalTo(rightImageView.snp.left).offset(16)
}
}
func setSubViewContent(_ type : String?, _ dataModel :DDHomeDataModel? ) {
var rightText = ""
var leftText = ""
if type == structureType.structureTypeNew.rawValue {
rightText = dataModel?.new?.rightTitle ?? ""
leftText = dataModel?.new?.title ?? ""
}else if type == structureType.structureTypeDataMiningAduioOrBook.rawValue {
leftText = dataModel?.dataMiningAduioOrBook?.title ?? ""
rightText = (dataModel?.dataMiningAduioOrBook?.rightTitle ?? "").characters.count > 0 ? (dataModel?.dataMiningAduioOrBook?.rightTitle ?? "") : "换一换"
setRightLabelIsChangeUI()
}else if type == structureType.structureTypeFreeAudio.rawValue {
rightText = dataModel?.freeAudio?.rightTitle ?? ""
leftText = dataModel?.freeAudio?.title ?? ""
}else if type == structureType.structureTypeColumn.rawValue { //
rightText = (dataModel?.column?.rightTitle ?? "").characters.count > 0 ? (dataModel?.column?.rightTitle ?? "") : "换一换"
leftText = dataModel?.column?.title ?? ""
setRightLabelIsChangeUI()
}else if type == structureType.structureTypeStorytell.rawValue {
leftText = dataModel?.storytell?.title ?? ""
rightText = "查看书单"
}else if type == "live" {
var descStatus = "预约"
if dataModel?.live?.data?.status == 1 {
leftText = "正在直播"
descStatus = "在线"
}else{
leftText = "直播未开始"
}
if let cont = dataModel?.live?.data?.online_num {
rightText = "\(cont)人" + descStatus
}
leftLiveImage.isHidden = false
rightImageView.isHidden = true
self.leftLabel.snp.remakeConstraints({ (make) in
make.centerY.equalToSuperview()
make.left.equalTo(leftLiveImage.snp.right).offset(3)
})
self.rightLabel.snp.remakeConstraints({ (make) in
make.centerY.equalToSuperview()
make.right.equalTo(rightImageView.snp.right).offset(-10)
})
self.leftLabel.textColor = UIColor.orange
}
self.leftLabel.text = leftText
self.rightLabel.text = rightText
}
/// RightLabel为换一换时的UI
func setRightLabelIsChangeUI() {
rightImageView.image = UIImage.init(named: "subscribe_positive")
rightImageView.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_2));
self.rightLabel.snp.remakeConstraints { (make) in
make.centerY.equalToSuperview()
make.right.equalToSuperview().offset(-14)
}
rightImageView.snp.remakeConstraints({ (make) in
make.centerY.equalToSuperview()
make.right.equalTo(self.rightLabel.snp.left).offset(-3)
})
}
}
| mit | ed144ead4926770728bf923dc4118361 | 32.598039 | 160 | 0.569886 | 4.864443 | false | false | false | false |
Mclarenyang/medicine_aid | medicine aid/homeViewController.swift | 1 | 9667 | //
// homeViewController.swift
// medicine aid
//
// Created by nexuslink mac 2 on 2017/5/10.
// Copyright © 2017年 NMID. All rights reserved.
//
import UIKit
import RealmSwift
class homeViewController: UIViewController,UIScrollViewDelegate {
// 滚动页预设参数
let SCROLL_WIDTH = UIScreen.main.bounds.width
let SCROLL_HEIGHT = UIScreen.main.bounds.height/2
var scrollView :UIScrollView? //轮播图
var pageC :UIPageControl? //小点
var timer :Timer? //定时器
var scArray :NSMutableArray? //图片数组
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
/// 设置状态栏颜色
UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent;
/// 导航栏显示
self.navigationController?.navigationBar.isHidden = false
// 隐藏返回按钮
self.navigationItem.hidesBackButton = true
self.navigationController?.navigationBar.barTintColor = UIColor(red:255/255,green:60/255,blue:40/255 ,alpha:1)
self.navigationItem.title = "选择"
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
/// 设置底部导航背景色
//self.tabBarController?.tabBar.barTintColor = UIColor(red:255/255,green:60/255,blue:40/255 ,alpha:1)
/// 创建按钮
let prescribeBtn = UIButton(frame: CGRect(x:SCROLL_WIDTH*2/7-75,y:SCROLL_HEIGHT+SCROLL_HEIGHT*1/7,width:150,height:220))
prescribeBtn.setBackgroundImage(UIImage(named:"prescribe_bt"), for: UIControlState.normal)
prescribeBtn.addTarget(self, action: #selector(prescribeBtnTap(_:)), for: UIControlEvents.touchUpInside)
self.view.addSubview(prescribeBtn)
let treatBtn = UIButton(frame: CGRect(x:SCROLL_WIDTH*5/7-75,y:SCROLL_HEIGHT+SCROLL_HEIGHT*1/7,width:150,height:220))
treatBtn.setBackgroundImage(UIImage(named:"treat_bt"), for: UIControlState.normal)
treatBtn.addTarget(self, action: #selector(treatBtnTap(_:)), for: UIControlEvents.touchUpInside)
self.view.addSubview(treatBtn)
/// 创建滚动视图
// 图片数组
scArray = ["scroll_image_2","scroll_image_1","scroll_image_4","scroll_image_5","scroll_image_3"]
// 初始化轮播图
scrollView = UIScrollView.init(frame: CGRect(x:0,y:64, width:SCROLL_WIDTH, height:SCROLL_HEIGHT*4/5))
scrollView?.backgroundColor = UIColor.white
// ScrollView滚动量
scrollView?.contentSize = CGSize(width:SCROLL_WIDTH * CGFloat((scArray?.count)!), height:0)
// ScrollView偏移量
scrollView?.contentOffset = CGPoint(x:SCROLL_WIDTH, y:0)
// 是否按页滚动
scrollView?.isPagingEnabled = true
// 是否显示水平滑条
scrollView?.showsHorizontalScrollIndicator = false
scrollView?.showsVerticalScrollIndicator = false
scrollView?.delegate = self
self.view.addSubview(scrollView!)
// 遍历图片数组
for i in 0 ..< (scArray?.count)! {
let str :String = (scArray?.object(at: i))! as! String
let img = UIImage(named: str)
//初始化imageView
let imgV :UIImageView = UIImageView()
//添加图片
imgV.image = img
imgV.backgroundColor = UIColor.white
//设置图片位置及大小
imgV.frame = CGRect(x:(CGFloat(i) * SCROLL_WIDTH),y:0, width:SCROLL_WIDTH, height:SCROLL_HEIGHT*4/5)
scrollView?.addSubview(imgV)
//轻拍手势
let tap = UITapGestureRecognizer.init(target: self, action: #selector(tapImageV(tap:)))
imgV.tag = 1000 + i
//打开用户交互
imgV.isUserInteractionEnabled = true
//给图片添加轻拍手势
imgV.addGestureRecognizer(tap)
}
//设置小点的位置大小
pageC = UIPageControl.init(frame: CGRect(x:(SCROLL_WIDTH - 200) / 2, y:SCROLL_HEIGHT - 50, width:200, height:50))
//设置小点背景色
pageC?.backgroundColor = UIColor.clear
//设置小点个数
pageC?.numberOfPages = (scArray?.count)! - 2
//设置小点当前页码颜色
pageC?.currentPageIndicatorTintColor = UIColor.white
//设置小点未选中页码颜色
pageC?.pageIndicatorTintColor = UIColor.gray
//设置当前选中页
pageC?.currentPage = 0
self.view.addSubview(pageC!)
timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(change(timer:)), userInfo: nil, repeats: true)
/// 创建云朵图案
let cloudImage = UIImageView(frame:CGRect(x:0,y:SCROLL_HEIGHT-SCROLL_HEIGHT*2/11,width:SCROLL_WIDTH,height:100))
cloudImage.image = UIImage(named:"Redcloud")
self.view.addSubview(cloudImage)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//循环滚动方法
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
//如果图片在第一张的位置
if scrollView.contentOffset.x == 0 {
//就变到倒数第二张的位置上
scrollView.scrollRectToVisible(CGRect(x:scrollView.contentSize.width - 2 * SCROLL_WIDTH,y:0,width:SCROLL_WIDTH,height:SCROLL_HEIGHT), animated: false)
//如果图片是倒数第一张的位置
} else if scrollView.contentOffset.x == scrollView.contentSize.width - SCROLL_WIDTH {
//就变到第二张的位置
scrollView .scrollRectToVisible(CGRect(x:SCROLL_WIDTH, y:0, width:SCROLL_WIDTH, height:SCROLL_HEIGHT), animated: false)
}
pageC?.currentPage = Int(scrollView.contentOffset.x / SCROLL_WIDTH) - 1
}
//定时器执行方法
func change(timer :Timer) {
if pageC?.currentPage == (pageC?.numberOfPages)! - 1 {
pageC?.currentPage = 0
} else if (pageC?.currentPage)! < (pageC?.numberOfPages)! - 1 {
pageC?.currentPage = (pageC?.currentPage)! + 1
}
scrollView?.setContentOffset(CGPoint(x:(CGFloat(pageC!.currentPage + 1)) * SCROLL_WIDTH, y:0), animated: false)
}
//开启定时器
func addTimer() {
timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(change(timer:)), userInfo: nil, repeats: true)
}
//关闭定时器
func removeTimer() {
timer?.invalidate()
}
//开始拖拽时调用
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
//关闭定时器
removeTimer()
}
//拖拽结束后调用
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
//开启定时器
addTimer()
}
//轻拍事件
func tapImageV(tap :UITapGestureRecognizer) {
print((tap.view?.tag)! - 1001)
}
// 按键响应事件
// 跳转事件
func prescribeBtnTap(_ button:UIButton){
//ID
let defaults = UserDefaults.standard
let UserID = defaults.value(forKey: "UserID")!
//读Type
let realm = try! Realm()
let type = realm.objects(UserText.self).filter("UserID = '\(UserID)'")[0].UserType
if type == "doctor" {
/// push界面
let queueView = queueViewController()
queueView.doctorID = UserID as! String
// 隐藏tabbar
queueView.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(queueView, animated: true)
}else{
//警告
let alert = UIAlertController(title: "警告", message: "没有权限", preferredStyle: .alert)
let action = UIAlertAction(title: "好", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}
func treatBtnTap(_ button:UIButton){
//状态
let defaults = UserDefaults.standard
let status = String(describing: defaults.value(forKey: "status")!)
if status == "no" {
/// push界面
let qrScanView = QRCodeViewController()
// 隐藏tabbar
qrScanView.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(qrScanView, animated: true)
}else{
let queueView = queueViewController()
queueView.doctorID = String(describing: defaults.value(forKey: "doctorID")!)
self.navigationController?.pushViewController(queueView, animated: true)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 55f6522f2a7bf8c349b152f7f7b0b11a | 35.023904 | 162 | 0.604291 | 4.419355 | false | false | false | false |
Ben21hao/edx-app-ios-new | Source/CourseOutline.swift | 1 | 8075 | //
// CourseOutline.swift
// edX
//
// Created by Akiva Leffert on 4/29/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
import edXCore
public typealias CourseBlockID = String
public struct CourseOutline {
enum Fields : String, RawStringExtractable {
case Root = "root"
case Blocks = "blocks"
case BlockCounts = "block_counts"
case BlockType = "type"
case Descendants = "descendants"
case DisplayName = "display_name"
case Format = "format"
case Graded = "graded"
case LMSWebURL = "lms_web_url"
case StudentViewMultiDevice = "student_view_multi_device"
case StudentViewURL = "student_view_url"
case StudentViewData = "student_view_data"
case Summary = "summary"
}
public let root : CourseBlockID
public let blocks : [CourseBlockID:CourseBlock]
private let parents : [CourseBlockID:CourseBlockID]
public init(root : CourseBlockID, blocks : [CourseBlockID:CourseBlock]) {
self.root = root
self.blocks = blocks
var parents : [CourseBlockID:CourseBlockID] = [:]
for (blockID, block) in blocks {
for child in block.children {
parents[child] = blockID
}
}
self.parents = parents
}
public init?(json : JSON) {
if let root = json[Fields.Root].string, blocks = json[Fields.Blocks].dictionaryObject {
var validBlocks : [CourseBlockID:CourseBlock] = [:]
for (blockID, blockBody) in blocks {
let body = JSON(blockBody)
let webURL = NSURL(string: body[Fields.LMSWebURL].stringValue)
let children = body[Fields.Descendants].arrayObject as? [String] ?? []
let name = body[Fields.DisplayName].string
let blockURL = body[Fields.StudentViewURL].string.flatMap { NSURL(string:$0) }
let format = body[Fields.Format].string
let typeName = body[Fields.BlockType].string ?? ""
let multiDevice = body[Fields.StudentViewMultiDevice].bool ?? false
let blockCounts : [String:Int] = (body[Fields.BlockCounts].object as? NSDictionary)?.mapValues {
$0 as? Int ?? 0
} ?? [:]
let graded = body[Fields.Graded].bool ?? false
var type : CourseBlockType
if let category = CourseBlock.Category(rawValue: typeName) {
switch category {
case CourseBlock.Category.Course:
type = .Course
case CourseBlock.Category.Chapter:
type = .Chapter
case CourseBlock.Category.Section:
type = .Section
case CourseBlock.Category.Unit:
type = .Unit
case CourseBlock.Category.HTML:
type = .HTML
case CourseBlock.Category.Problem:
type = .Problem
case CourseBlock.Category.Video :
let bodyData = (body[Fields.StudentViewData].object as? NSDictionary).map { [Fields.Summary.rawValue : $0 ] }
let summary = OEXVideoSummary(dictionary: bodyData ?? [:], videoID: blockID, name : name ?? Strings.untitled)
type = .Video(summary)
case CourseBlock.Category.Discussion:
// Inline discussion is in progress feature. Will remove this code when it's ready to ship
type = .Unknown(typeName)
if OEXConfig.sharedConfig().discussionsEnabled {
let bodyData = body[Fields.StudentViewData].object as? NSDictionary
let discussionModel = DiscussionModel(dictionary: bodyData ?? [:])
type = .Discussion(discussionModel)
}
}
}
else {
type = .Unknown(typeName)
}
validBlocks[blockID] = CourseBlock(
type: type,
children: children,
blockID: blockID,
name: name,
blockCounts : blockCounts,
blockURL : blockURL,
webURL: webURL,
format : format,
multiDevice : multiDevice,
graded : graded
)
}
self = CourseOutline(root: root, blocks: validBlocks)
}
else {
return nil
}
}
func parentOfBlockWithID(blockID : CourseBlockID) -> CourseBlockID? {
return self.parents[blockID]
}
}
public enum CourseBlockType {
case Unknown(String)
case Course
case Chapter // child of course
case Section // child of chapter
case Unit // child of section
case Video(OEXVideoSummary)
case Problem
case HTML
case Discussion(DiscussionModel)
public var asVideo : OEXVideoSummary? {
switch self {
case let .Video(summary):
return summary
default:
return nil
}
}
}
public class CourseBlock {
/// Simple list of known block categories strings
public enum Category : String {
case Chapter = "chapter"
case Course = "course"
case HTML = "html"
case Problem = "problem"
case Section = "sequential"
case Unit = "vertical"
case Video = "video"
case Discussion = "discussion"
}
public let type : CourseBlockType
public let blockID : CourseBlockID
/// Children in the navigation hierarchy.
/// Note that this may be different than the block's list of children, server side
/// Since we flatten out the hierarchy for display
public let children : [CourseBlockID]
/// Title of block. Keep this private so people don't use it as the displayName by accident
private let name : String?
/// Actual title of the block. Not meant to be user facing - see displayName
public var internalName : String? {
return name
}
/// User visible name of the block.
public var displayName : String {
guard let name = name where !name.isEmpty else {
return Strings.untitled
}
return name
}
/// TODO: Match final API name
/// The type of graded component
public let format : String?
/// Mapping between block types and number of blocks of that type in this block's
/// descendants (recursively) for example ["video" : 3]
public let blockCounts : [String:Int]
/// Just the block content itself as a web page.
/// Suitable for embedding in a web view.
public let blockURL : NSURL?
/// If this is web content, can we actually display it.
public let multiDevice : Bool
/// A full web page for the block.
/// Suitable for opening in a web browser.
public let webURL : NSURL?
/// Whether or not the block is graded.
/// TODO: Match final API name
public let graded : Bool?
public init(type : CourseBlockType,
children : [CourseBlockID],
blockID : CourseBlockID,
name : String?,
blockCounts : [String:Int] = [:],
blockURL : NSURL? = nil,
webURL : NSURL? = nil,
format : String? = nil,
multiDevice : Bool,
graded : Bool = false) {
self.type = type
self.children = children
self.name = name
self.blockCounts = blockCounts
self.blockID = blockID
self.blockURL = blockURL
self.webURL = webURL
self.graded = graded
self.format = format
self.multiDevice = multiDevice
}
}
| apache-2.0 | 40bfb742222e15e219afcb06345b21ab | 34.262009 | 133 | 0.551827 | 5.202964 | false | false | false | false |
xiaoxinghu/swift-org | Sources/Section.swift | 1 | 2782 | //
// Section.swift
// SwiftOrg
//
// Created by Xiaoxing Hu on 21/09/16.
// Copyright © 2016 Xiaoxing Hu. All rights reserved.
//
import Foundation
public struct Section: Node {
// MARK: properties
public var index: OrgIndex?
public var title: String?
public var stars: Int
public var keyword: String?
public var priority: Priority?
public var tags: [String]?
public var content = [Node]()
public var drawers: [Drawer]? {
let ds = content.filter { node in
return node is Drawer
}.map { node in
return node as! Drawer
}
return ds
}
public var planning: Planning? {
return content.first { $0 is Planning } as? Planning
}
// MARK: func
public init(stars l: Int, title t: String?, todos: [String]) {
stars = l
// TODO limit charset on tags
let pattern = "^(?:(\(todos.joined(separator: "|")))\\s+)?(?:\\[#([ABCabc])\\]\\s+)?(.*?)(?:\\s+((?:\\:.+)+\\:)\\s*)?$"
if let text = t, let m = text.match(pattern) {
keyword = m[1]
if let p = m[2] {
priority = Priority(rawValue: p.uppercased())
}
title = m[3]
if let t = m[4] {
tags = t.components(separatedBy: ":").filter({ !$0.isEmpty })
}
} else {
title = t
}
}
public var description: String {
return "Section[\(index)](stars: \(stars), keyword: \(keyword)), priority: \(priority)), title: \(title)\n - tags: \(tags)\n - \(drawers)\n - \(content)"
}
}
public struct Planning: Node {
public let keyword: PlanningKeyword
public let timestamp: Timestamp?
public var description: String {
return "Planning(keyword: \(keyword), timestamp: \(timestamp))"
}
}
extension OrgParser {
func parseSection(_ index: OrgIndex) throws -> Node? {
skipBlanks() // in a section, you don't care about blanks
guard let (_, token) = tokens.peek() else {
return nil
}
switch token {
case let .headline(l, t):
if l < index.indexes.count {
return nil
}
_ = tokens.dequeue()
var section = Section(stars: l, title: t, todos: document.todos.flatMap{ $0 })
section.index = index
var subIndex = index.in
while let subSection = try parseSection(subIndex) {
section.content.append(subSection)
subIndex = subIndex.next
}
return section
case .footnote:
return try parseFootnote()
default:
return try parseTheRest()
}
}
}
| mit | 6f44115f7132e11404e6888ca872cc62 | 27.96875 | 161 | 0.520316 | 4.252294 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Components/Controllers/NavigationController.swift | 1 | 5697 | //
// Wire
// Copyright (C) 2022 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
import WireUtilities
class NavigationController: UINavigationController, SpinnerCapable {
var dismissSpinner: SpinnerCompletion?
fileprivate lazy var pushTransition = NavigationTransition(operation: .push)
fileprivate lazy var popTransition = NavigationTransition(operation: .pop)
fileprivate var dismissGestureRecognizer: UIScreenEdgePanGestureRecognizer!
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.setup()
}
override init(navigationBarClass: AnyClass?, toolbarClass: AnyClass?) {
super.init(navigationBarClass: navigationBarClass, toolbarClass: toolbarClass)
self.setup()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init?(coder aDecoder: NSCoder) is not implemented")
}
private func setup() {
self.delegate = self
self.transitioningDelegate = self
}
var useDefaultPopGesture: Bool = false {
didSet {
self.interactivePopGestureRecognizer?.isEnabled = useDefaultPopGesture
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = SemanticColors.View.backgroundDefault
self.useDefaultPopGesture = false
self.navigationBar.tintColor = SemanticColors.Label.textDefault
self.navigationBar.titleTextAttributes = DefaultNavigationBar.titleTextAttributes(for: .dark)
self.dismissGestureRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(NavigationController.onEdgeSwipe(gestureRecognizer:)))
self.dismissGestureRecognizer.edges = [.left]
self.dismissGestureRecognizer.delegate = self
self.view.addGestureRecognizer(self.dismissGestureRecognizer)
}
override func setViewControllers(_ viewControllers: [UIViewController], animated: Bool) {
viewControllers.forEach { $0.hideDefaultButtonTitle() }
super.setViewControllers(viewControllers, animated: animated)
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
viewController.hideDefaultButtonTitle()
super.pushViewController(viewController, animated: animated)
}
@objc func onEdgeSwipe(gestureRecognizer: UIScreenEdgePanGestureRecognizer) {
if gestureRecognizer.state == .recognized {
self.popViewController(animated: true)
}
}
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if let avoiding = viewController as? KeyboardAvoidingViewController {
updateGesture(for: avoiding.viewController)
} else {
updateGesture(for: viewController)
}
}
private func updateGesture(for viewController: UIViewController) {
let translucentBackground = viewController.view.backgroundColor?.alpha < 1.0
useDefaultPopGesture = !translucentBackground
}
// MARK: - status bar
override var childForStatusBarStyle: UIViewController? {
return topViewController
}
override var childForStatusBarHidden: UIViewController? {
return topViewController
}
}
extension NavigationController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController,
animationControllerFor operation: UINavigationController.Operation,
from fromVC: UIViewController,
to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if self.useDefaultPopGesture {
return nil
}
switch operation {
case .push:
return pushTransition
case .pop:
return popTransition
default:
fatalError()
}
}
}
extension NavigationController: UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return SwizzleTransition(direction: .vertical)
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return SwizzleTransition(direction: .vertical)
}
}
extension NavigationController: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if self.useDefaultPopGesture && gestureRecognizer == self.dismissGestureRecognizer {
return false
}
return true
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| gpl-3.0 | 4778f11f05f90fce93b75c5bf2c6ed64 | 35.993506 | 177 | 0.716693 | 5.891417 | false | false | false | false |
Trxy/TRX | Sources/scheduler/Proxy.swift | 1 | 562 | func ==(lhs: Scheduler.Proxy, rhs: Scheduler.Proxy) -> Bool {
return lhs === rhs
}
extension Scheduler {
class Proxy: Subscriber, Hashable {
var subscriber: Subscriber
init(subscriber: Subscriber) {
self.subscriber = subscriber
}
var hashValue: Int {
return Unmanaged<AnyObject>.passUnretained(subscriber).toOpaque().hashValue
}
var keys: Set<String> {
return subscriber.keys
}
func tick(time timeStamp: TimeInterval) {
subscriber.tick(time: timeStamp)
}
}
}
| mit | 41f813e6c8cd9a51d00b4131f3c1cc61 | 18.37931 | 81 | 0.617438 | 4.606557 | false | false | false | false |
omise/omise-ios | OmiseSDK/InternetBankingSourceChooserViewController.swift | 1 | 3489 | import UIKit
import os
@objc(OMSInternetBankingSourceChooserViewController)
// swiftlint:disable:next type_name
class InternetBankingSourceChooserViewController: AdaptableStaticTableViewController<PaymentInformation.InternetBanking>,
PaymentSourceChooser,
PaymentChooserUI {
var flowSession: PaymentCreatorFlowSession?
override var showingValues: [PaymentInformation.InternetBanking] {
didSet {
os_log("Internet Banking Chooser: Showing options - %{private}@",
log: uiLogObject,
type: .info,
showingValues.map { $0.description }.joined(separator: ", "))
}
}
@IBOutlet var internetBankingNameLabels: [UILabel]!
@IBInspectable var preferredPrimaryColor: UIColor? {
didSet {
applyPrimaryColor()
}
}
@IBInspectable var preferredSecondaryColor: UIColor? {
didSet {
applySecondaryColor()
}
}
override func viewDidLoad() {
super.viewDidLoad()
applyPrimaryColor()
applySecondaryColor()
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}
override func staticIndexPath(forValue value: PaymentInformation.InternetBanking) -> IndexPath {
switch value {
case .bbl:
return IndexPath(row: 0, section: 0)
case .scb:
return IndexPath(row: 1, section: 0)
case .bay:
return IndexPath(row: 2, section: 0)
case .ktb:
return IndexPath(row: 3, section: 0)
case .other:
preconditionFailure("This value is not supported for the built-in chooser")
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
if let cell = cell as? PaymentOptionTableViewCell {
cell.separatorView.backgroundColor = currentSecondaryColor
}
cell.accessoryView?.tintColor = currentSecondaryColor
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
tableView.deselectRow(at: indexPath, animated: true)
let bank = element(forUIIndexPath: indexPath)
os_log("Internet Banking Chooser: %{private}@ was selected", log: uiLogObject, type: .info, bank.description)
let oldAccessoryView = cell?.accessoryView
let loadingIndicator = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.gray)
loadingIndicator.color = currentSecondaryColor
cell?.accessoryView = loadingIndicator
loadingIndicator.startAnimating()
view.isUserInteractionEnabled = false
flowSession?.requestCreateSource(.internetBanking(bank)) { _ in
cell?.accessoryView = oldAccessoryView
self.view.isUserInteractionEnabled = true
}
}
private func applyPrimaryColor() {
guard isViewLoaded else {
return
}
internetBankingNameLabels.forEach {
$0.textColor = currentPrimaryColor
}
}
private func applySecondaryColor() {}
}
| mit | be8d1b15b3ee47c458ae1c77bbad99a0 | 34.969072 | 121 | 0.623388 | 5.529319 | false | false | false | false |
google/iosched-ios | Source/IOsched/Screens/Search/SearchResultMatcher.swift | 1 | 4775 | //
// Copyright (c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
public protocol Searchable {
var title: String { get }
var subtext: String { get }
}
public class SearchResultsMatcher {
private lazy var linguisticTagger: NSLinguisticTagger = {
let tagger = NSLinguisticTagger(tagSchemes: [.lexicalClass], options: 0)
return tagger
}()
private lazy var queryTokenizer: NSLinguisticTagger = {
let tagger = NSLinguisticTagger(tagSchemes: [.tokenType], options: 0)
return tagger
}()
let resultLimit = 20
private func enumerateQueryTokens(query: String, _ closure: @escaping (String) -> Void) {
let range = NSRange(location: 0, length: query.utf16.count)
let options: NSLinguisticTagger.Options = [.omitPunctuation, .omitWhitespace]
queryTokenizer.string = query
let tagHandler: (NSLinguisticTag?, NSRange) -> Void = { tag, range in
guard tag != nil else { return }
let taggedString = (query as NSString).substring(with: range)
closure(taggedString)
}
if #available(iOS 11, *) {
queryTokenizer.enumerateTags(in: range,
unit: .word,
scheme: .tokenType,
options: options) { (tag, range, _) in
tagHandler(tag, range)
}
} else {
queryTokenizer.enumerateTags(in: range,
scheme: .tokenType,
options: options) { (tag, tokenRange, _, _) in
tagHandler(tag, tokenRange)
}
}
}
public func fuzzyMatch(_ query: String, in text: String) -> Double {
var matches: Double = 0
let lowercaseQuery = query.lowercased()
let tagger = linguisticTagger
let range = NSRange(location: 0, length: text.utf16.count)
let options: NSLinguisticTagger.Options = [.omitPunctuation, .omitWhitespace]
tagger.string = text
let tagMatcher: (NSLinguisticTag?, NSRange) -> Void = { tag, range in
guard let tag = tag, tag == .noun else { return }
let taggedString = (text as NSString).substring(with: range).lowercased()
self.enumerateQueryTokens(query: lowercaseQuery) { (queryFragment) in
let partialMatch: Double = taggedString.contains(queryFragment) ? 1 : 0
matches += partialMatch
}
}
if #available(iOS 11.0, *) {
tagger.enumerateTags(in: range,
unit: .word,
scheme: .lexicalClass,
options: options) { (tag, range, _) in
tagMatcher(tag, range)
}
} else {
tagger.enumerateTags(in: range,
scheme: .lexicalClass,
options: options) { (tag, tokenRange, _, _) in
tagMatcher(tag, tokenRange)
}
}
return matches
}
/// The matches for a query in an item. There may be more than one.
public func match<T: Searchable>(query: String,
in items: [T]) -> [SearchResult] {
var fuzzyMatchResults: [(Double, T)] = []
let threshold: Double = 1
for item in items {
let matches = [
fuzzyMatch(query, in: item.title),
fuzzyMatch(query, in: item.subtext)
]
var highestMatch: Double = 0
for match in matches where highestMatch < match {
highestMatch = match
}
if highestMatch >= threshold {
fuzzyMatchResults.append((highestMatch, item))
}
}
fuzzyMatchResults.sort { (lhs, rhs) -> Bool in
return lhs.0 > rhs.0
}
return fuzzyMatchResults.prefix(resultLimit).map {
let accuracy: SearchResultMatchAccuracy = .partial
return SearchResult(title: $0.1.title,
subtext: $0.1.subtext,
matchAccuracy: accuracy,
wrappedItem: $0.1)
}
}
}
extension InfoDetail: Searchable {
public var subtext: String {
return attributedDescription()?.string ?? ""
}
}
extension Session: Searchable {
public var subtext: String {
return detail
}
}
extension AgendaItem: Searchable {
public var subtext: String {
return displayableTimeInterval
}
}
| apache-2.0 | 684fa8b8fa20d28041bd9047ad9fa381 | 28.658385 | 91 | 0.606492 | 4.392824 | false | false | false | false |
khizkhiz/swift | validation-test/compiler_crashers_fixed/01702-swift-type-walk.swift | 1 | 953 | // 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
}
protocol c {
class a<T> Int = B)
func e> String {
S()-> {
class d<d
func f, range.Type) ->(T, 3)
class a {
c<f == {
}
typealias B == f<f = c({
class A : Any, b = B<T> T, d, e == compose<T>Bool))) -> Self {
typealias h: T>((")
var e: A, y)
static let foo as a(A, (self.dynamicType)
func e({
}
func a(h> () {
}
struct S {
class c()
}
protocol b {
import Foundation
}
}
}
}
}
extension NSSet {
print())
protocol b {
}
}
var b[()
}
(""
return g, k : T, () -> e? = 1, x = i().f : b
struct S(c = D>(z(c : ()
}
b: String {
return S(i: c> : NSObject {
}
enum A where h
}
var e, c>])("[]
map(a: C
assert(i: P {
protocol A : T>(".B
typealias e : B(t: Sequence, f<T>, e)
f() -> Int = f, i(")
enum B : c(f(c(x(""")
enum A = [Byte])
func g<C: B.a:
| apache-2.0 | dab6758a2dfcedc0ee8b9f3cbc9d2e35 | 14.883333 | 87 | 0.56978 | 2.456186 | false | false | false | false |
KoCMoHaBTa/MHAppKit | MHAppKit/Animators/UINavigationControllerPerspectiveAnimator.swift | 1 | 6309 | //
// UINavigationControllerPerspectiveAnimator.swift
// MHAppKit
//
// Created by Milen Halachev on 11/10/15.
// Copyright © 2015 Milen Halachev. All rights reserved.
//
#if canImport(UIKit) && !os(watchOS)
import UIKit
///An animator object represeting `UIViewControllerAnimatedTransitioning` that performs perspective animation based on given `UINavigationControllerOperation` and duration
open class UINavigationControllerPerspectiveAnimator: NSObject, UIViewControllerAnimatedTransitioning {
///The `UINavigationControllerOperation`. Based on this value - the perspective animation has reverse effect
public let operation: UINavigationController.Operation
///The duration of the animation
public let duration: TimeInterval
///Creates an instance of the receiver with a given `UINavigationControllerOperation` and duration. Duration defaults to 0.35
public init(operation: UINavigationController.Operation, duration: TimeInterval = 0.35) {
self.operation = operation
self.duration = duration
}
//MARK: - UIViewControllerAnimatedTransitioning
open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return self.duration
}
open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
switch self.operation {
case .push:
self.animatePushTransition(using: transitionContext)
return
case .pop:
self.animatePopTransition(using: transitionContext)
return
case .none:
return;
@unknown default:
return
}
}
//MARK: - Custom Animations
open func animatePushTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard
let fromViewController = transitionContext.viewController(forKey: .from),
let toViewController = transitionContext.viewController(forKey: .to)
else {
return
}
let containerView = transitionContext.containerView
let duration = self.transitionDuration(using: transitionContext)
//put the showing view to initial state before animation - prepare for sliding
containerView.addSubview(toViewController.view)
toViewController.view.frame = containerView.bounds
toViewController.view.frame.origin.x = containerView.bounds.size.width
UIView.animate(withDuration: duration, delay: 0, options: [], animations: { () -> Void in
//apply perspective transform on the view that is going out
self.applyTransform(self.perspectiveTransform(), view: fromViewController.view)
//apply slide animation on the view that is showing
toViewController.view.frame.origin.x = 0
fromViewController.view.alpha = 0
}) { (finished) -> Void in
let completed = finished && !transitionContext.transitionWasCancelled
if completed {
//apply the original transform of the view that is no longer visible - this is required because the transform is kept and if this view comes on screen by any other way - it will appear transformed, which will be unexpected
self.applyTransform(self.originalTransform(), view: fromViewController.view)
fromViewController.view.removeFromSuperview()
fromViewController.view.alpha = 1
}
transitionContext.completeTransition(completed)
}
}
open func animatePopTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard
let fromViewController = transitionContext.viewController(forKey: .from),
let toViewController = transitionContext.viewController(forKey: .to)
else {
return
}
let containerView = transitionContext.containerView
let duration = self.transitionDuration(using: transitionContext)
//put the showing view to initial state before animation - apply the perspective transform
containerView.addSubview(toViewController.view)
toViewController.view.frame = containerView.bounds
self.applyTransform(self.perspectiveTransform(), view: toViewController.view)
toViewController.view.alpha = 0
UIView.animate(withDuration: duration, delay: 0, options: [], animations: { () -> Void in
//apply the original transform of the view that is showing
self.applyTransform(self.originalTransform(), view: toViewController.view)
//apply slide animation on the view that is going out
fromViewController.view.frame.origin.x = containerView.bounds.size.width
toViewController.view.alpha = 1
}) { (finished) -> Void in
let completed = finished && !transitionContext.transitionWasCancelled
if completed {
fromViewController.view.removeFromSuperview()
}
transitionContext.completeTransition(completed)
}
}
//MARK: - Trasnforms
private func perspectiveTransform() -> CATransform3D {
//i have no idea what these numbers means
//found them here: http://whackylabs.com/rants/?p=1198
let eyePosition:Float = 40.0;
var transform:CATransform3D = CATransform3DIdentity
transform.m34 = CGFloat(-1/eyePosition)
transform = CATransform3DTranslate(transform, 0, 0, -40)
return transform
}
private func originalTransform() -> CATransform3D {
return CATransform3DIdentity
}
private func applyTransform(_ transform: CATransform3D, view: UIView) {
view.layer.transform = transform
}
}
#endif
| mit | 947bd152e7db2c8bf1f9de452b1c7453 | 36.325444 | 238 | 0.632847 | 6.172211 | false | false | false | false |
helloglance/betterbeeb | BetterBeeb/SectionCell.swift | 1 | 7250 |
//
// SectionCell.swift
// BetterBeeb
//
// Created by Hudzilla on 15/10/2014.
// Copyright (c) 2014 Paul Hudson. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class SectionCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
weak var parentViewController: StoriesViewController!
var section: Section!
var leftLabel: UILabel!
var rightLabel: UILabel!
var collectionView: UICollectionView!
var flowLayout: UICollectionViewFlowLayout!
required override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .None
backgroundColor = UIColor.beebBackgroundGrey()
let topRow = UIView()
let bottomRow = UIView()
leftLabel = UILabel()
rightLabel = UILabel()
topRow.translatesAutoresizingMaskIntoConstraints = false;
bottomRow.translatesAutoresizingMaskIntoConstraints = false;
leftLabel.translatesAutoresizingMaskIntoConstraints = false;
rightLabel.translatesAutoresizingMaskIntoConstraints = false;
rightLabel.textAlignment = .Right
flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .Horizontal
collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.delegate = self
collectionView.dataSource = self
flowLayout.sectionInset = UIEdgeInsetsMake(0, 6, 0, 6)
flowLayout.minimumInteritemSpacing = 6
flowLayout.itemSize = CGSizeMake(128, 134)
collectionView.backgroundColor = UIColor.beebBackgroundGrey()
collectionView.showsHorizontalScrollIndicator = false
collectionView.scrollsToTop = false
collectionView.decelerationRate = UIScrollViewDecelerationRateFast
collectionView.registerClass(StoryCell.self, forCellWithReuseIdentifier: "Story")
topRow.addSubview(leftLabel)
topRow.addSubview(rightLabel)
bottomRow.addSubview(collectionView)
contentView.addSubview(topRow)
contentView.addSubview(bottomRow)
let viewsDictionary = ["topRow" : topRow, "bottomRow" : bottomRow, "leftLabel" : leftLabel, "rightLabel" : rightLabel, "collectionView" : collectionView]
topRow.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(==6)-[leftLabel]|", options: [], metrics: nil, views: viewsDictionary))
topRow.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(==8)-[leftLabel]-(==8)-|", options: [], metrics: nil, views: viewsDictionary))
topRow.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[rightLabel]-(==6)-|", options: [], metrics: nil, views: viewsDictionary))
topRow.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(==8)-[rightLabel]-(==8)-|", options: [], metrics: nil, views: viewsDictionary))
bottomRow.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[collectionView]|", options: [], metrics: nil, views: viewsDictionary))
bottomRow.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[collectionView(==134)]|", options: [], metrics: nil, views: viewsDictionary))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[topRow]|", options: [], metrics: nil, views: viewsDictionary))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[bottomRow]|", options: [], metrics: nil, views: viewsDictionary))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[topRow][bottomRow]|", options: [], metrics: nil, views: viewsDictionary))
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
func setSectionTitle(str: String) {
let attrs = [NSForegroundColorAttributeName : UIColor.whiteColor(), NSFontAttributeName : UIFont.boldSystemFontOfSize(16)]
let title = NSAttributedString(string: str.uppercaseString, attributes: attrs)
leftLabel.attributedText = title
}
func setSectionDate(str: String) {
let attr = [NSForegroundColorAttributeName : UIColor.whiteColor(), NSFontAttributeName : UIFont.boldSystemFontOfSize(11)]
let title = NSAttributedString(string: str, attributes: attr)
rightLabel.attributedText = title
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if self.section == nil { return 0 }
return self.section.stories.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Story", forIndexPath: indexPath) as! StoryCell
let story = section.stories[indexPath.item]
cell.SetStory(story)
if parentViewController.selectedStoryID != nil && parentViewController.selectedStoryID == story.id {
cell.setHighlightedStory(true)
} else {
cell.setHighlightedStory(false)
}
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
parentViewController.showStory(section.stories[indexPath.item])
}
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let visibleWidth = 10 + flowLayout.itemSize.width
let indexOfItemToSnap: Int = Int(round(targetContentOffset.memory.x / visibleWidth))
if (targetContentOffset.memory.x >= scrollView.contentSize.width - scrollView.bounds.size.width) {
// we're trying to scroll to the very last element, so scroll to the end
targetContentOffset.memory = CGPointMake(collectionView.contentSize.width - collectionView.bounds.size.width, 0)
} else {
// we're trying to scroll to any element that is not the last, so snap to it
targetContentOffset.memory = CGPointMake(CGFloat(indexOfItemToSnap) * visibleWidth, 0)
}
}
func highlightStory(highlighted: Story) {
let visibleCells = collectionView.visibleCells() as! [StoryCell]
for cell in visibleCells {
if cell.story.id == highlighted.id {
cell.setHighlightedStory(true)
} else {
cell.setHighlightedStory(false)
}
}
}
}
| mit | 7c5a73cebb4cec9ffcc79cadde467717 | 41.151163 | 156 | 0.774345 | 4.763469 | false | false | false | false |
elpassion/el-space-ios | ELSpace/Commons/Extensions/DateFormatter_Formatters.swift | 1 | 1131 | import Foundation
extension DateFormatter {
static var shortDateFormatter: DateFormatter {
let dateFormatter = DateFormatter.warsawTimeZoneFormatter
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter
}
static var dayFormatter: DateFormatter {
let dateFormatter = DateFormatter.warsawTimeZoneFormatter
dateFormatter.dateFormat = "d E"
return dateFormatter
}
static var monthFormatter: DateFormatter {
let dateFormatter = DateFormatter.warsawTimeZoneFormatter
dateFormatter.dateFormat = "MMMM yyyy"
return dateFormatter
}
static var activityFormatter: DateFormatter {
let dateFormatter = DateFormatter.warsawTimeZoneFormatter
dateFormatter.dateFormat = "E, d MMM yyyy"
return dateFormatter
}
// MARK: - Private
private static var warsawTimeZoneFormatter: DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en")
dateFormatter.timeZone = TimeZone(identifier: "Europe/Warsaw")
return dateFormatter
}
}
| gpl-3.0 | 0f08ccc72664fe85870ccdafc2734d0d | 28.763158 | 70 | 0.697613 | 5.655 | false | false | false | false |
onmyway133/XcodeWay | XcodeWayExtensions/Helper/ScriptRunner.swift | 1 | 1820 | //
// ScriptRunner.swift
// XcodeWayExtensions
//
// Created by Khoa Pham on 18.10.2017.
// Copyright © 2017 Fantageek. All rights reserved.
//
import AppKit
import Carbon
class ScriptRunner {
var scriptPath: URL? {
return try? FileManager.default.url(
for: .applicationScriptsDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)
}
func fileScriptPath(fileName: String) -> URL? {
return scriptPath?
.appendingPathComponent(fileName)
.appendingPathExtension("scpt")
}
func eventDescriptior(functionName: String) -> NSAppleEventDescriptor {
var psn = ProcessSerialNumber(highLongOfPSN: 0, lowLongOfPSN: UInt32(kCurrentProcess))
let target = NSAppleEventDescriptor(
descriptorType: typeProcessSerialNumber,
bytes: &psn,
length: MemoryLayout<ProcessSerialNumber>.size
)
let event = NSAppleEventDescriptor(
eventClass: UInt32(kASAppleScriptSuite),
eventID: UInt32(kASSubroutineEvent),
targetDescriptor: target,
returnID: Int16(kAutoGenerateReturnID),
transactionID: Int32(kAnyTransactionID)
)
let function = NSAppleEventDescriptor(string: functionName)
event.setParam(function, forKeyword: AEKeyword(keyASSubroutineName))
return event
}
func run(functionName: String) {
guard let filePath = fileScriptPath(fileName: "XcodeWayScript") else {
return
}
guard FileManager.default.fileExists(atPath: filePath.path) else {
return
}
guard let script = try? NSUserAppleScriptTask(url: filePath) else {
return
}
let event = eventDescriptior(functionName: functionName)
script.execute(withAppleEvent: event, completionHandler: { _, error in
if let error = error {
print(error)
}
})
}
}
| mit | 4269c0a744ea42246b4e9ed62645c965 | 24.985714 | 90 | 0.693238 | 4.172018 | false | false | false | false |
supertommy/craft | craftTests/craftTests.swift | 1 | 12575 | //
// craftTests.swift
// craftTests
//
// Created by Tommy Leung on 6/28/14.
// Copyright (c) 2014 Tommy Leung. All rights reserved.
//
import XCTest
import craft
/**
* custom infix operator as a shorthand for GCD operation where 'lhs' is an async
* task that is followed by 'rhs' which a task on the main thread
*
* uses @autoclosure so that statement can be as concise as:
*
* usleep(250 * 1000) ~> resolve(value: value)
*
* which is to sleep in the background and then resolve on the main thread
*/
infix operator ~> {}
func ~> (@autoclosure(escaping) lhs: () -> Any, @autoclosure(escaping) rhs: () -> ())
{
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue, {
lhs()
dispatch_sync(dispatch_get_main_queue(), rhs)
})
}
//Promises/A+ spec: http://promises-aplus.github.io/promises-spec/
class craftTests: 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 testCreatePromise()
{
let p : Promise = Craft.promise()
XCTAssertNotNil(p, "promise was not created")
}
//spec 2.2.4
func testResolveAsync()
{
let expectation = expectationWithDescription("resolveAsync");
let p : Promise = createImmediateResolvePromise()
p.then {
(value: Value) -> Value in
expectation.fulfill()
return nil;
}
/**
* proceeding uses of waitForExpectationsWithTimeout will use trailing closure syntax
* and shorthand argument names for conciseness
*/
waitForExpectationsWithTimeout(5.0) { print($0) };
}
//spec 2.2.4
func testRejectAsync()
{
let expectation = expectationWithDescription("rejectAsync");
let p : Promise = createImmediateRejectPromise()
p.then(nil, reject: {
(value: Value) -> Value in
expectation.fulfill()
return nil;
})
waitForExpectationsWithTimeout(5.0) { print($0) };
}
func testThenable()
{
let expectation = expectationWithDescription("thenable");
let p : Promise = createImmediateResolvePromise()
p.then({
(value: Value) -> Value in
expectation.fulfill()
return nil;
},
reject: {
(value: Value) -> Value in
return nil;
})
waitForExpectationsWithTimeout(5.0) { print($0) };
}
func testThenableNoReject()
{
let expectation = expectationWithDescription("thenableNoReject");
let p : Promise = createImmediateResolvePromise()
p.then {
(value: Value) -> Value in
expectation.fulfill()
return nil;
}
waitForExpectationsWithTimeout(5.0) { print($0) };
}
//spec 2.2.6
func testMultiThenResolve()
{
let expectation1 = expectationWithDescription("multiThenResolve1");
let expectation2 = expectationWithDescription("multiThenResolve2");
let p : Promise = createImmediateResolvePromise()
p.then {
(value: Value) -> Value in
expectation1.fulfill()
return nil
}
p.then {
(value: Value) -> Value in
expectation2.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0) { print($0) };
}
//spec 2.2.6
func testMultiThenReject()
{
let expectation1 = expectationWithDescription("multiThenReject1");
let expectation2 = expectationWithDescription("multiThenReject2");
let p : Promise = createImmediateRejectPromise()
p.`catch` {
(value: Value) -> Value in
expectation1.fulfill()
return nil
}
p.`catch` {
(value: Value) -> Value in
expectation2.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0) { print($0) };
}
func testChainable()
{
let expectation = expectationWithDescription("chainable");
let p : Promise = createWillResolvePromise()
p.then {
(value: Value) -> Value in
return "hello"
}
.then {
(value: Value) -> Value in
let v: String = value as! String
return v + " world"
}
.then {
(value: Value) -> Value in
expectation.fulfill()
return nil;
}
waitForExpectationsWithTimeout(5.0) { print($0) };
}
//spec 2.2.7.3
func testChainableResolveWithHole()
{
let expectation = expectationWithDescription("chainableResolveWithHole");
let p : Promise = createWillResolvePromise()
let p2 = p.then()
p2.then {
(value: Value) -> Value in
print(value)
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0) { print($0) };
}
//spec 2.2.7.4
func testChainableRejectWithHole()
{
let expectation = expectationWithDescription("chainableRejectWithHole");
let p : Promise = createWillRejectPromise()
let p2 = p.then()
p2.`catch` {
(value: Value) -> Value in
print(value)
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0) { print($0) };
}
//spec 2.3.2
func testChainablePromise()
{
let expectation = expectationWithDescription("chainablePromise");
let p : Promise = createWillResolvePromise()
p.then {
(value: Value) -> Value in
return self.createWillResolvePromise("promise value")
}
.then {
(value: Value) -> Value in
print(value)
expectation.fulfill()
return nil;
}
waitForExpectationsWithTimeout(5.0) { print($0) };
}
func testChainTypeError()
{
let expectation = expectationWithDescription("chainTypeError");
let p : Promise = createWillResolvePromise()
p.then {
(value: Value) -> Value in
return p
}
.`catch` {
(value: Value) -> Value in
print(value)
expectation.fulfill()
return nil;
}
waitForExpectationsWithTimeout(5.0) { print($0) };
}
func testPromiseResolve()
{
let expectation = expectationWithDescription("resolve");
let p = createWillResolvePromise()
p.then {
(value: Value) -> Value in
print(value)
expectation.fulfill()
return nil;
}
waitForExpectationsWithTimeout(5.0) { print($0) };
}
func testPromiseReject()
{
let expectation = expectationWithDescription("reject");
let p = createWillRejectPromise()
p.then({
(value: Value) -> Value in
return nil;
}, reject: {
(value: Value) -> Value in
print(value)
expectation.fulfill()
return nil
})
waitForExpectationsWithTimeout(5.0) { print($0) };
}
func testPromiseCatch()
{
let expectation = expectationWithDescription("catch")
let p = createWillRejectPromise()
p.`catch` {
(value: Value) -> Value in
print(value)
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0) { print($0) };
}
func testAllResolve()
{
let expectation = expectationWithDescription("allResolve");
let a = [
createImmediateResolvePromise(),
createImmediateResolvePromise(),
createImmediateResolvePromise()
]
Craft.all(a).then {
(value: Value) -> Value in
if let v: [Value] = value as? [Value]
{
XCTAssertEqual(a.count, v.count)
for var i = 0; i < v.count; ++i
{
if let result = v[i]
{
//createImmediateResolvePromise resolves with String
XCTAssertTrue(result is String)
}
}
expectation.fulfill()
}
return nil
}
waitForExpectationsWithTimeout(5.0) { print($0) };
}
func testAllReject()
{
let expectation = expectationWithDescription("allReject");
let a = [
createImmediateResolvePromise(),
createImmediateRejectPromise(),
createImmediateResolvePromise()
]
Craft.all(a).`catch` {
(value: Value) -> Value in
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0) { print($0) };
}
func testAllSettled()
{
let expectation = expectationWithDescription("allSettled");
let a = [
createImmediateResolvePromise(),
createImmediateRejectPromise(),
createImmediateResolvePromise()
]
Craft.allSettled(a).then {
if let v: [Value] = $0 as? [Value]
{
XCTAssertEqual(a.count, v.count)
for var i = 0; i < v.count; ++i
{
if let result = v[i]
{
//allSettled resolutions are wrapped in SettleResult to determine state
XCTAssertTrue(result is SettledResult)
//createImmediate[Resolve|Reject]Promise resolves/rejects with String
XCTAssertTrue((result as! SettledResult).value is String)
}
}
expectation.fulfill()
}
return nil
}
waitForExpectationsWithTimeout(5.0) { print($0) };
}
//MARK: helpers
func createImmediateResolvePromise() -> Promise
{
return Craft.promise {
(resolve: (value: Value) -> (), reject: (value: Value) -> ()) -> () in
resolve(value: "immediate resolve")
}
}
func createImmediateRejectPromise() -> Promise
{
return Craft.promise {
(resolve: (value: Value) -> (), reject: (value: Value) -> ()) -> () in
reject(value: "immediate reject")
}
}
func createWillResolvePromise() -> Promise
{
return createWillResolvePromise("resolved")
}
func createWillResolvePromise(value: Value) -> Promise
{
return Craft.promise {
(resolve: (value: Value) -> (), reject: (value: Value) -> ()) -> () in
//some async action
usleep(250 * 1000) ~> resolve(value: value)
};
}
func createWillRejectPromise() -> Promise
{
return createWillRejectPromise("rejected")
}
func createWillRejectPromise(value: Value) -> Promise
{
return Craft.promise {
(resolve: (value: Value) -> (), reject: (value: Value) -> ()) -> () in
//some async action
usleep(250 * 1000) ~> reject(value: value)
}
}
}
| mit | 2c31f95912e54526028f1e4e36d387ba | 25.418067 | 111 | 0.499085 | 5.207039 | false | true | false | false |
baic989/iPhone-ANN | ANN/Modules/MainMenu/MainMenuTransitionAnimator.swift | 2 | 2145 | //
// MainMenuTransitionAnimator.swift
// ANN
//
// Created by Super Hrvoje on 08/07/2017.
// Copyright © 2017 Hrvoje Baic. All rights reserved.
//
import UIKit
class MainMenuTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning {
var navigationOption: MainMenuNavigationOption = .train
let animationDuration = 0.4
var operation: UINavigationControllerOperation = .push
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return animationDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
guard let fromViewController = transitionContext.viewController(forKey: .from) as? MainMenuViewController else { return }
guard let toViewController = transitionContext.viewController(forKey: .to) as? DrawingViewController else { return }
containerView.addSubview(toViewController.view)
containerView.addSubview(fromViewController.view)
var button: UIButton
switch navigationOption {
case .test: button = fromViewController.testButton
case .train: button = fromViewController.trainButton
}
let scale = (fromViewController.view.frame.height / button.frame.height) * 1.5
toViewController.view.alpha = 0.0
UIView.animate(withDuration: 0.01) {
button.titleLabel?.alpha = 0
}
UIView.animate(withDuration: animationDuration / 2, animations: {
button.transform = CGAffineTransform(scaleX: scale, y: scale)
}, completion: { finished in
containerView.bringSubview(toFront: toViewController.view)
UIView.animate(withDuration: self.animationDuration / 2, animations: {
toViewController.view.alpha = 1
}, completion: { finished in
transitionContext.completeTransition(true)
})
})
}
}
| mit | 10f14f6f5837de8142e906dea60a3dbe | 35.965517 | 129 | 0.658116 | 5.778976 | false | false | false | false |
RMizin/PigeonMessenger-project | FalconMessenger/ChatsControllers/BaseMessageCell+CellDeletionHandlers.swift | 1 | 13280 | //
// BaseMessageCell+CellDeletionHandlers.swift
// Pigeon-project
//
// Created by Roman Mizin on 12/12/17.
// Copyright © 2017 Roman Mizin. All rights reserved.
//
import UIKit
import FTPopOverMenu_Swift
import Firebase
struct ContextMenuItems {
static let copyItem = "Copy"
static let copyPreviewItem = "Copy image preview"
static let deleteItem = "Delete for myself"
static let reportItem = "Report"
static func contextMenuItems(for messageType: MessageType, _ isIncludedReport: Bool) -> [String] {
guard isIncludedReport else {
return defaultMenuItems(for: messageType)
}
switch messageType {
case .textMessage:
return [ContextMenuItems.copyItem, ContextMenuItems.deleteItem, ContextMenuItems.reportItem]
case .photoMessage:
return [ContextMenuItems.deleteItem, ContextMenuItems.reportItem]
case .videoMessage:
return [ContextMenuItems.deleteItem, ContextMenuItems.reportItem]
case .voiceMessage:
return [ContextMenuItems.deleteItem, ContextMenuItems.reportItem]
case .sendingMessage:
return [ContextMenuItems.copyItem]
}
}
static func defaultMenuItems(for messageType: MessageType) -> [String] {
switch messageType {
case .textMessage, .photoMessage:
return [ContextMenuItems.deleteItem, ContextMenuItems.copyItem]
case .videoMessage:
return [ContextMenuItems.deleteItem]
case .voiceMessage:
return [ContextMenuItems.deleteItem]
case .sendingMessage:
return [ContextMenuItems.copyItem]
}
}
}
extension BaseMessageCell {
func bubbleImage(currentColor: UIColor) -> UIColor {
switch currentColor {
case ThemeManager.currentTheme().outgoingBubbleTintColor:
return ThemeManager.currentTheme().selectedOutgoingBubbleTintColor
case ThemeManager.currentTheme().incomingBubbleTintColor:
return ThemeManager.currentTheme().selectedIncomingBubbleTintColor
default:
return currentColor
}
}
@objc func handleLongTap(_ longPressGesture: UILongPressGestureRecognizer) {
guard longPressGesture.state == .began else { return }
let generator = UIImpactFeedbackGenerator(style: .medium)
generator.impactOccurred()
guard let indexPath = self.chatLogController?.collectionView.indexPath(for: self) else { return }
let message = chatLogController?.groupedMessages[indexPath.section].messages[indexPath.row]
let isOutgoing = message?.fromId == Auth.auth().currentUser?.uid
var contextMenuItems = ContextMenuItems.contextMenuItems(for: .textMessage, !isOutgoing)
let config = chatLogController?.configureCellContextMenuView() ?? FTConfiguration()
let expandedMenuWidth: CGFloat = 150
let defaultMenuWidth: CGFloat = 100
config.menuWidth = expandedMenuWidth
if let cell = self.chatLogController?.collectionView.cellForItem(at: indexPath) as? OutgoingVoiceMessageCell {
if message?.status == messageStatusSending || message?.status == messageStatusNotSent { return }
cell.bubbleView.tintColor = bubbleImage(currentColor: cell.bubbleView.tintColor)
contextMenuItems = ContextMenuItems.contextMenuItems(for: .voiceMessage, !isOutgoing)
}
if let cell = self.chatLogController?.collectionView.cellForItem(at: indexPath) as? IncomingVoiceMessageCell {
if message?.status == messageStatusSending || message?.status == messageStatusNotSent { return }
contextMenuItems = ContextMenuItems.contextMenuItems(for: .voiceMessage, !isOutgoing)
cell.bubbleView.tintColor = bubbleImage(currentColor: cell.bubbleView.tintColor)
}
if let cell = self.chatLogController?.collectionView.cellForItem(at: indexPath) as? PhotoMessageCell {
cell.bubbleView.tintColor = bubbleImage(currentColor: cell.bubbleView.tintColor)
if !cell.playButton.isHidden {
contextMenuItems = ContextMenuItems.contextMenuItems(for: .videoMessage, !isOutgoing)
config.menuWidth = expandedMenuWidth
} else {
contextMenuItems = ContextMenuItems.contextMenuItems(for: .photoMessage, !isOutgoing)
config.menuWidth = expandedMenuWidth
}
}
if let cell = self.chatLogController?.collectionView.cellForItem(at: indexPath) as? IncomingPhotoMessageCell {
cell.bubbleView.tintColor = bubbleImage(currentColor: cell.bubbleView.tintColor)
if !cell.playButton.isHidden {
contextMenuItems = ContextMenuItems.contextMenuItems(for: .videoMessage, !isOutgoing)
config.menuWidth = expandedMenuWidth
} else {
contextMenuItems = ContextMenuItems.contextMenuItems(for: .photoMessage, !isOutgoing)
config.menuWidth = expandedMenuWidth
}
}
if let cell = self.chatLogController?.collectionView.cellForItem(at: indexPath) as? OutgoingTextMessageCell {
cell.bubbleView.tintColor = bubbleImage(currentColor: cell.bubbleView.tintColor)
}
if let cell = self.chatLogController?.collectionView.cellForItem(at: indexPath) as? IncomingTextMessageCell {
cell.bubbleView.tintColor = bubbleImage(currentColor: cell.bubbleView.tintColor)
}
if message?.messageUID == nil || message?.status == messageStatusSending || message?.status == messageStatusNotSent {
config.menuWidth = defaultMenuWidth
contextMenuItems = ContextMenuItems.contextMenuItems(for: .sendingMessage, !isOutgoing)
}
FTPopOverMenu.showForSender(sender: bubbleView, with: contextMenuItems, menuImageArray: nil, popOverPosition: .automatic, config: config, done: { (selectedIndex) in
guard contextMenuItems[selectedIndex] != ContextMenuItems.reportItem else {
self.handleReport(indexPath: indexPath)
print("handlong report")
return
}
guard contextMenuItems[selectedIndex] != ContextMenuItems.deleteItem else {
self.handleDeletion(indexPath: indexPath)
print("handling deletion")
return
}
print("handling coly")
self.handleCopy(indexPath: indexPath)
}) {
self.chatLogController?.collectionView.reloadItems(at: [indexPath])
}
}
fileprivate func handleReport(indexPath: IndexPath) {
chatLogController?.collectionView.reloadItems(at: [indexPath])
chatLogController?.inputContainerView.resignAllResponders()
let reportAlert = ReportAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
reportAlert.controller = chatLogController
reportAlert.indexPath = indexPath
reportAlert.reportedMessage = chatLogController?.groupedMessages[indexPath.section].messages[indexPath.row]
reportAlert.popoverPresentationController?.sourceView = bubbleView
reportAlert.popoverPresentationController?.sourceRect = CGRect(x: bubbleView.bounds.midX, y: bubbleView.bounds.maxY,
width: 0, height: 0)
chatLogController?.present(reportAlert, animated: true, completion: nil)
}
fileprivate func handleCopy(indexPath: IndexPath) {
self.chatLogController?.collectionView.reloadItems(at: [indexPath])
if let cell = self.chatLogController?.collectionView.cellForItem(at: indexPath) as? PhotoMessageCell {
if cell.messageImageView.image == nil {
guard let controllerToDisplayOn = self.chatLogController else { return }
basicErrorAlertWith(title: basicErrorTitleForAlert,
message: copyingImageError,
controller: controllerToDisplayOn)
return
}
UIPasteboard.general.image = cell.messageImageView.image
} else if let cell = self.chatLogController?.collectionView.cellForItem(at: indexPath) as? IncomingPhotoMessageCell {
if cell.messageImageView.image == nil {
guard let controllerToDisplayOn = self.chatLogController else { return }
basicErrorAlertWith(title: basicErrorTitleForAlert,
message: copyingImageError,
controller: controllerToDisplayOn)
return
}
UIPasteboard.general.image = cell.messageImageView.image
} else if let cell = self.chatLogController?.collectionView.cellForItem(at: indexPath) as? OutgoingTextMessageCell {
UIPasteboard.general.string = cell.textView.text
} else if let cell = self.chatLogController?.collectionView.cellForItem(at: indexPath) as? IncomingTextMessageCell {
UIPasteboard.general.string = cell.textView.text
} else {
return
}
}
func handleDeletion(indexPath: IndexPath) {
guard let message = chatLogController?.groupedMessages[indexPath.section].messages[indexPath.row] else { return }
guard let uid = Auth.auth().currentUser?.uid, let partnerID = message.chatPartnerId(),
let messageID = message.messageUID, self.currentReachabilityStatus != .notReachable else {
self.chatLogController?.collectionView.reloadItems(at: [indexPath])
guard let controllerToDisplayOn = self.chatLogController else { return }
basicErrorAlertWith(title: basicErrorTitleForAlert, message: noInternetError, controller: controllerToDisplayOn)
return
}
var deletionReference: DatabaseReference!
if let isGroupChat = self.chatLogController?.conversation?.isGroupChat.value, isGroupChat {
guard let conversationID = self.chatLogController?.conversation?.chatID else { return }
deletionReference = Database.database().reference().child("user-messages").child(uid).child(conversationID).child(userMessagesFirebaseFolder).child(messageID)
} else {
deletionReference = Database.database().reference().child("user-messages").child(uid).child(partnerID).child(userMessagesFirebaseFolder).child(messageID)
}
if message.isInvalidated == false {
try! RealmKeychain.defaultRealm.safeWrite {
// to make previous message crooked if needed
if message.isCrooked.value == true, indexPath.row > 0 {
self.chatLogController!.groupedMessages[indexPath.section].messages[indexPath.row - 1].isCrooked.value = true
let lastIndexPath = IndexPath(row: indexPath.row - 1, section: indexPath.section)
self.chatLogController?.collectionView.reloadItems(at: [lastIndexPath])
}
RealmKeychain.defaultRealm.delete(message)
chatLogController?.collectionView.deleteItems(at: [indexPath])
// to show delivery status on last message
if indexPath.row - 1 >= 0 {
let lastIndexPath = IndexPath(row: indexPath.row - 1, section: indexPath.section)
self.chatLogController?.collectionView.reloadItems(at: [lastIndexPath])
}
if self.chatLogController?.collectionView.numberOfItems(inSection: indexPath.section) == 0 {
print("removing section")
self.chatLogController?.collectionView.performBatchUpdates({
self.chatLogController?.groupedMessages.remove(at: indexPath.section)
UIView.performWithoutAnimation {
self.chatLogController?.collectionView.deleteSections(IndexSet([indexPath.section]))
}
if self.chatLogController!.groupedMessages.count > 0, indexPath.section - 1 >= 0 {
var rowIndex = 0
if let messages = self.chatLogController?.groupedMessages[indexPath.section - 1].messages {
rowIndex = messages.count - 1 >= 0 ? messages.count - 1 : 0
}
UIView.performWithoutAnimation {
self.chatLogController?.collectionView.reloadItems(at: [IndexPath(row: rowIndex, section: indexPath.section - 1)])
}
}
}, completion: { (isCompleted) in
print("delete section completed")
guard self.chatLogController!.groupedMessages.count == 0 else { return }
self.chatLogController?.navigationController?.popViewController(animated: true)
})
}
}
}
deletionReference.removeValue(completionBlock: { (error, reference) in
guard let controllerToDisplayOn = self.chatLogController else { return }
guard error == nil else {
print("firebase error")
basicErrorAlertWith(title: basicErrorTitleForAlert, message: deletionErrorMessage, controller: controllerToDisplayOn)
return
}
if let isGroupChat = self.chatLogController?.conversation?.isGroupChat.value, isGroupChat {
guard let conversationID = self.chatLogController?.conversation?.chatID else { return }
var lastMessageReference = Database.database().reference().child("user-messages").child(uid).child(conversationID).child(messageMetaDataFirebaseFolder)
if let lastMessageID = self.chatLogController?.groupedMessages.last?.messages.last?.messageUID {
lastMessageReference.updateChildValues(["lastMessageID": lastMessageID])
} else {
lastMessageReference = lastMessageReference.child("lastMessageID")
lastMessageReference.removeValue()
}
} else {
var lastMessageReference = Database.database().reference().child("user-messages").child(uid).child(partnerID).child(messageMetaDataFirebaseFolder)
if let lastMessageID = self.chatLogController?.groupedMessages.last?.messages.last?.messageUID {
lastMessageReference.updateChildValues(["lastMessageID": lastMessageID])
} else {
lastMessageReference = lastMessageReference.child("lastMessageID")
lastMessageReference.removeValue()
}
}
})
}
}
| gpl-3.0 | 5447788da42f6a82fe4c6229fb6bae12 | 46.256228 | 168 | 0.727314 | 4.730673 | false | false | false | false |
gauuni/iOSProjectTemplate | iOSProjectTemplate/iOSProjectTemplate/Utilities/RootColor.swift | 1 | 1610 | //
// AppDelegate.swift
// Fitness
//
// Created by Duc Nguyen on 10/1/16.
// Copyright © 2016 Reflect Apps Inc. All rights reserved.
//
import Foundation
import UIKit
class RootColor {
var hex : String {
didSet {
update()
}
}
private(set) var color : UIColor
init(hex : String){
self.hex = hex
self.color = UIColor.colorWithHexString(hex: hex)
}
private func update() {
self.color = UIColor.colorWithHexString(hex: hex)
}
func redComponent() -> CGFloat {
return UIColor.redComponentFromHexString(hex: self.hex)
}
func greenComponent() -> CGFloat {
return UIColor.greenComponentFromHexString(hex: self.hex)
}
func blueComponent() -> CGFloat {
return UIColor.blueComponentFromHexString(hex: self.hex)
}
func alphaComponent() -> CGFloat {
return UIColor.alphaComponentFromHexString(hex: self.hex)
}
func colorWithAdjustedBrightness(byPercent percent: CGFloat) -> RootColor {
var hue : CGFloat = 0
var saturation : CGFloat = 0
var brightness : CGFloat = 0
var alpha : CGFloat = 0
if color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
let newColor = UIColor(hue: hue, saturation: saturation, brightness: brightness * (1+percent), alpha: alpha)
if let hex = UIColor.hexStringFromColor(color: newColor) {
return RootColor(hex: hex)
}
}
return self
}
}
| mit | ac7e7cef68493fb6a09f2c49e10b19f3 | 25.377049 | 120 | 0.594158 | 4.558074 | false | false | false | false |
hollance/swift-algorithm-club | Segment Tree/SegmentTree.playground/Contents.swift | 4 | 5064 | //: Playground - noun: a place where people can play
// last checked with Xcode 9.0b4
#if swift(>=4.0)
print("Hello, Swift 4!")
#endif
public class SegmentTree<T> {
private var value: T
private var function: (T, T) -> T
private var leftBound: Int
private var rightBound: Int
private var leftChild: SegmentTree<T>?
private var rightChild: SegmentTree<T>?
public init(array: [T], leftBound: Int, rightBound: Int, function: @escaping (T, T) -> T) {
self.leftBound = leftBound
self.rightBound = rightBound
self.function = function
if leftBound == rightBound {
value = array[leftBound]
} else {
let middle = (leftBound + rightBound) / 2
leftChild = SegmentTree<T>(array: array, leftBound: leftBound, rightBound: middle, function: function)
rightChild = SegmentTree<T>(array: array, leftBound: middle+1, rightBound: rightBound, function: function)
value = function(leftChild!.value, rightChild!.value)
}
}
public convenience init(array: [T], function: @escaping (T, T) -> T) {
self.init(array: array, leftBound: 0, rightBound: array.count-1, function: function)
}
public func query(leftBound: Int, rightBound: Int) -> T {
if self.leftBound == leftBound && self.rightBound == rightBound {
return self.value
}
guard let leftChild = leftChild else { fatalError("leftChild should not be nil") }
guard let rightChild = rightChild else { fatalError("rightChild should not be nil") }
if leftChild.rightBound < leftBound {
return rightChild.query(leftBound: leftBound, rightBound: rightBound)
} else if rightChild.leftBound > rightBound {
return leftChild.query(leftBound: leftBound, rightBound: rightBound)
} else {
let leftResult = leftChild.query(leftBound: leftBound, rightBound: leftChild.rightBound)
let rightResult = rightChild.query(leftBound:rightChild.leftBound, rightBound: rightBound)
return function(leftResult, rightResult)
}
}
public func replaceItem(at index: Int, withItem item: T) {
if leftBound == rightBound {
value = item
} else if let leftChild = leftChild, let rightChild = rightChild {
if leftChild.rightBound >= index {
leftChild.replaceItem(at: index, withItem: item)
} else {
rightChild.replaceItem(at: index, withItem: item)
}
value = function(leftChild.value, rightChild.value)
}
}
}
let array = [1, 2, 3, 4]
let sumSegmentTree = SegmentTree(array: array, function: +)
print(sumSegmentTree.query(leftBound: 0, rightBound: 3)) // 1 + 2 + 3 + 4 = 10
print(sumSegmentTree.query(leftBound: 1, rightBound: 2)) // 2 + 3 = 5
print(sumSegmentTree.query(leftBound: 0, rightBound: 0)) // 1 = 1
sumSegmentTree.replaceItem(at: 0, withItem: 2) //our array now is [2, 2, 3, 4]
print(sumSegmentTree.query(leftBound: 0, rightBound: 0)) // 2 = 2
print(sumSegmentTree.query(leftBound: 0, rightBound: 1)) // 2 + 2 = 4
//you can use any associative function (i.e (a+b)+c == a+(b+c)) as function for segment tree
func gcd(_ m: Int, _ n: Int) -> Int {
var a = 0
var b = max(m, n)
var r = min(m, n)
while r != 0 {
a = b
b = r
r = a % b
}
return b
}
let gcdArray = [2, 4, 6, 3, 5]
let gcdSegmentTree = SegmentTree(array: gcdArray, function: gcd)
print(gcdSegmentTree.query(leftBound: 0, rightBound: 1)) // gcd(2, 4) = 2
print(gcdSegmentTree.query(leftBound: 2, rightBound: 3)) // gcd(6, 3) = 3
print(gcdSegmentTree.query(leftBound: 1, rightBound: 3)) // gcd(4, 6, 3) = 1
print(gcdSegmentTree.query(leftBound: 0, rightBound: 4)) // gcd(2, 4, 6, 3, 5) = 1
gcdSegmentTree.replaceItem(at: 3, withItem: 10) //gcdArray now is [2, 4, 6, 10, 5]
print(gcdSegmentTree.query(leftBound: 3, rightBound: 4)) // gcd(10, 5) = 5
//example of segment tree which finds minimum on given range
let minArray = [2, 4, 1, 5, 3]
let minSegmentTree = SegmentTree(array: minArray, function: min)
print(minSegmentTree.query(leftBound: 0, rightBound: 4)) // min(2, 4, 1, 5, 3) = 1
print(minSegmentTree.query(leftBound: 0, rightBound: 1)) // min(2, 4) = 2
minSegmentTree.replaceItem(at: 2, withItem: 10) // minArray now is [2, 4, 10, 5, 3]
print(minSegmentTree.query(leftBound: 0, rightBound: 4)) // min(2, 4, 10, 5, 3) = 2
//type of elements in array can be any type which has some associative function
let stringArray = ["a", "b", "c", "A", "B", "C"]
let stringSegmentTree = SegmentTree(array: stringArray, function: +)
print(stringSegmentTree.query(leftBound: 0, rightBound: 1)) // "a"+"b" = "ab"
print(stringSegmentTree.query(leftBound: 2, rightBound: 3)) // "c"+"A" = "cA"
print(stringSegmentTree.query(leftBound: 1, rightBound: 3)) // "b"+"c"+"A" = "bcA"
print(stringSegmentTree.query(leftBound: 0, rightBound: 5)) // "a"+"b"+"c"+"A"+"B"+"C" = "abcABC"
stringSegmentTree.replaceItem(at: 0, withItem: "I")
stringSegmentTree.replaceItem(at: 1, withItem: " like")
stringSegmentTree.replaceItem(at: 2, withItem: " algorithms")
stringSegmentTree.replaceItem(at: 3, withItem: " and")
stringSegmentTree.replaceItem(at: 4, withItem: " swift")
stringSegmentTree.replaceItem(at: 5, withItem: "!")
print(stringSegmentTree.query(leftBound: 0, rightBound: 5))
| mit | f192543c85f0e00ca71147b6f7c9c0f5 | 35.695652 | 109 | 0.694313 | 3.349206 | false | false | false | false |
STShenZhaoliang/iOS-GuidesAndSampleCode | 精通Swift设计模式/Chapter 05/Initialization.playground/section-1.swift | 1 | 1477 | //: Playground - noun: a place where people can play
import Foundation
// 1.如果实现是NSCopying 协议,需要重写copy方法
class Sum : NSObject , NSCopying{
var resultsCache: [[Int]];
var firstValue:Int;
var secondValue:Int;
init(first:Int, second:Int) {
resultsCache = [[Int]].init(repeating: [Int].init(repeating: 0, count: 10), count: 10);
for i in 0..<10 {
for j in 0..<10 {
resultsCache[i][j] = i*10 + j;
}
}
firstValue = first;
secondValue = second;
}
private init(first:Int, second:Int, cache:[[Int]]) {
firstValue = first;
secondValue = second;
resultsCache = cache;
}
var Result:Int {
get {
return firstValue < resultsCache.count
&& secondValue < resultsCache[firstValue].count
? resultsCache[firstValue][secondValue]
: firstValue + secondValue;
}
}
func copy(with zone: NSZone? = nil) -> Any {
return Sum.init(first: self.firstValue, second: self.secondValue, cache: self.resultsCache)
}
}
var prototype = Sum(first:3, second:9);
var clone = prototype;
var calc1 = prototype.Result;
clone.firstValue = 3;
clone.secondValue = 8;
var calc2 = clone.Result;
print("Calc1: \(calc1) Calc2: \(calc2)");
print("\(prototype)");
print("\(clone)");
var cloneCopy = clone.copy()
print("\(cloneCopy)");
| mit | 9bf2d47e89a3ff20e068efe43e67ff0e | 24.875 | 99 | 0.57695 | 3.9375 | false | false | false | false |
davidprochazka/HappyDay | HappyDaysCollectionVersion/HappyDaysCollectionVersion/PersonStatisticsViewController.swift | 1 | 2053 | //
// StatsViewController.swift
// HappyDaysCollectionVersion
//
// Created by David Prochazka on 24/05/16.
// Copyright © 2016 David Prochazka. All rights reserved.
//
import UIKit
import CoreData
import MessageUI
protocol PersonStatisticsViewControllerDelegate {
func didCloseStats()
}
class PersonStatisticsViewController: UIViewController, NSFetchedResultsControllerDelegate {
var managedObjectContext: NSManagedObjectContext? = nil
var selectedPerson: Person? = nil
var selectedMood: Int? = nil
var delegate: PersonStatisticsViewControllerDelegate? = nil
@IBOutlet weak var currentMoodLabel: UILabel!
@IBOutlet weak var weekMoodLabel: UILabel!
@IBOutlet weak var monthMoodLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = selectedPerson!.name! + "'s statistics"
// po navratu z hodnoticiho view muze byt view bez MOC
if self.managedObjectContext == nil {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
self.managedObjectContext = appDelegate.managedObjectContext
}
configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func closeClicked(sender: AnyObject) {
delegate?.didCloseStats()
dismissViewControllerAnimated(true, completion: nil)
}
func configureView(){
let stats = PersonStatistics(person: selectedPerson!, moc: managedObjectContext!)
stats.calculate()
currentMoodLabel.text = selectedMood?.description
weekMoodLabel.text = (round(stats.avg7*10)/10).description
monthMoodLabel.text = (round(stats.avg30*10)/10).description
}
@IBAction func exportData(sender: AnyObject) {
let export = StatisticsExport(ctrl: self, moc: managedObjectContext!)
export.sendCsvInMail()
}
}
| gpl-3.0 | d3b0d4dd6aa771214d515f3a33811537 | 29.626866 | 92 | 0.689571 | 5.091811 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/UI/NotesView.swift | 1 | 14899 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import third_party_objective_c_material_components_ios_components_Buttons_Buttons
import third_party_objective_c_material_components_ios_components_Palettes_Palettes
import third_party_objective_c_material_components_ios_components_Typography_Typography
/// View that lets a user take notes.
class NotesView: UIView {
class SendButtonView: UIView {
/// The send button.
let sendButton = MDCFlatButton(type: .custom)
init() {
super.init(frame: .zero)
configureView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureView()
}
func configureView() {
sendButton.disabledAlpha = 0.4
let sendButtonImage = UIImage(named: "ic_send")?.imageFlippedForRightToLeftLayoutDirection()
sendButton.setImage(sendButtonImage, for: .normal)
sendButton.autoresizesSubviews = false
sendButton.contentEdgeInsets = .zero
sendButton.imageEdgeInsets = .zero
sendButton.inkColor = .clear
sendButton.tintColor = MDCPalette.blue.tint500
addSubview(sendButton)
sendButton.translatesAutoresizingMaskIntoConstraints = false
sendButton.pinToEdgesOfView(self)
sendButton.accessibilityLabel = String.addTextNoteContentDescription
}
}
/// Styles for displaying the send button.
///
/// - toolbar: As a toolbar below the text view.
/// - button: As a button to the right of the text view.
enum SendButtonStyle {
case toolbar
case button
}
enum Metrics {
static let sendFABPadding: CGFloat = 32.0
static let sendFABDisabledAlpha: CGFloat = 0.4
static let sendFABImage = UIImage(named: "ic_send")?.imageFlippedForRightToLeftLayoutDirection()
static let sendFABContentInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0)
}
// MARK: - Properties
/// The text view.
let textView = UITextView()
/// The send button action bar.
let sendButtonActionBar = ActionBar(buttonType: .send)
/// The send button view.
let sendButtonView = SendButtonView()
/// Button for action area design
let sendFAB = MDCFloatingButton()
/// The text view's placeholder label.
let placeholderLabel = UILabel()
/// The maximum text height for the custom drawer position.
lazy var maximumCustomTextHeight: CGFloat = {
return self.threeLineTextHeight + self.textView.textContainerInset.top +
self.textView.textContainerInset.bottom
}()
/// One line text height.
lazy var oneLineTextHeight: CGFloat = {
guard let textViewFont = self.textView.font else { return 0 }
return "onelinestring".labelHeight(withConstrainedWidth: 0, font: textViewFont)
}()
/// Three line text height.
lazy var threeLineTextHeight: CGFloat = {
guard let textViewFont = self.textView.font else { return 0 }
return "three\nline\nstring".labelHeight(withConstrainedWidth: 0, font: textViewFont)
}()
private var placeholderLabelLeadingConstraint: NSLayoutConstraint?
private var placeholderLabelTopConstraint: NSLayoutConstraint?
private var placeholderLabelTrailingConstraint: NSLayoutConstraint?
private var sendButtonActionBarWrapperBottomConstraint: NSLayoutConstraint?
private var sendButtonActionBarWrapperHeightConstraint: NSLayoutConstraint?
private let sendButtonViewHorizontalInset: CGFloat = 16
private let sendButtonViewTopInset: CGFloat = 40
private static let textContainerHorizontalInset: CGFloat = 16
private let textViewHorizontalBuffer: CGFloat = 5
private var sendButtonStyle = SendButtonStyle.button
private let sendButtonActionBarWrapper = UIView()
private var sendButtonViewTrailingConstraint: NSLayoutConstraint?
private var sendFABBottomConstraint: NSLayoutConstraint?
private var textViewTextContainerInset: UIEdgeInsets {
return UIEdgeInsets(top: 18,
left: NotesView.textContainerHorizontalInset + safeAreaInsetsOrZero.left,
bottom: 16,
right: NotesView.textContainerHorizontalInset + safeAreaInsetsOrZero.right)
}
// MARK: - Public
override init(frame: CGRect) {
super.init(frame: frame)
configureView()
registerForNotifications()
setSendButtonStyle(.toolbar)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureView()
registerForNotifications()
setSendButtonStyle(.toolbar)
}
override func safeAreaInsetsDidChange() {
updateActionBarHeight()
updateTextViewTextContainerInset()
sendButtonViewTrailingConstraint?.constant =
-sendButtonViewHorizontalInset - safeAreaInsetsOrZero.right
}
/// Returns the height of the notes view that fits the current text.
var heightFittingText: CGFloat {
return textHeight + textView.textContainerInset.top + textView.textContainerInset.bottom
}
/// Sets the alpha, constraints and insets for the send button style.
func setSendButtonStyle(_ sendButtonStyle: SendButtonStyle, animated: Bool = false) {
guard self.sendButtonStyle != sendButtonStyle else { return }
self.sendButtonStyle = sendButtonStyle
updateTextViewTextContainerInset()
let duration: TimeInterval = animated ? 0.4 : 0
UIView.animate(withDuration: duration, animations: {
switch sendButtonStyle {
case .toolbar:
self.sendButtonView.alpha = 0
case .button:
self.sendButtonView.alpha = 1
}
})
animateToolbarAndUpdateInsets(withDuration: 0.2)
}
/// The current text view text height.
var textHeight: CGFloat {
guard let textViewFont = textView.font else { return 0 }
let textViewWidth = textView.bounds.size.width - textView.textContainerInset.left -
textView.textContainerInset.right - textViewHorizontalBuffer * 2
return textView.text.labelHeight(withConstrainedWidth: textViewWidth, font: textViewFont)
}
/// Adjusts the action bar to extend into the bottom safe area, when the keyboard is not up.
func updateActionBarHeight() {
sendButtonActionBarWrapperHeightConstraint?.constant =
!textView.isFirstResponder ? safeAreaInsetsOrZero.bottom : 0
}
// MARK: - Private
private func configureView() {
// Text view.
textView.alwaysBounceVertical = false
textView.font = MDCTypography.fontLoader().regularFont(ofSize: 16)
addSubview(textView)
textView.translatesAutoresizingMaskIntoConstraints = false
textView.pinToEdgesOfView(self)
// Send button action bar.
sendButtonActionBar.translatesAutoresizingMaskIntoConstraints = false
sendButtonActionBar.setContentHuggingPriority(.defaultHigh, for: .vertical)
sendButtonActionBarWrapper.addSubview(sendButtonActionBar)
sendButtonActionBar.topAnchor.constraint(
equalTo: sendButtonActionBarWrapper.topAnchor).isActive = true
sendButtonActionBar.leadingAnchor.constraint(
equalTo: sendButtonActionBarWrapper.leadingAnchor).isActive = true
sendButtonActionBar.trailingAnchor.constraint(
equalTo: sendButtonActionBarWrapper.trailingAnchor).isActive = true
sendButtonActionBar.button.accessibilityLabel = String.addTextNoteContentDescription
sendButtonActionBarWrapper.backgroundColor = DrawerView.actionBarBackgroundColor
sendButtonActionBarWrapper.translatesAutoresizingMaskIntoConstraints = false
addSubview(sendButtonActionBarWrapper)
sendButtonActionBarWrapper.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
sendButtonActionBarWrapper.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
sendButtonActionBarWrapperBottomConstraint =
sendButtonActionBarWrapper.bottomAnchor.constraint(equalTo: bottomAnchor)
sendButtonActionBarWrapperBottomConstraint?.isActive = true
sendButtonActionBarWrapperHeightConstraint = sendButtonActionBarWrapper.heightAnchor.constraint(
equalTo: sendButtonActionBar.heightAnchor)
sendButtonActionBarWrapperHeightConstraint?.isActive = true
// Send button view.
addSubview(sendButtonView)
sendButtonView.translatesAutoresizingMaskIntoConstraints = false
sendButtonView.bottomAnchor.constraint(equalTo: topAnchor,
constant: sendButtonViewTopInset).isActive = true
sendButtonViewTrailingConstraint = sendButtonView.trailingAnchor.constraint(
equalTo: trailingAnchor, constant: -sendButtonViewHorizontalInset)
sendButtonViewTrailingConstraint?.isActive = true
if FeatureFlags.isActionAreaEnabled {
// We don't use the action bar but it has dependencies elsewhere in the code and we still
// need to support that until cleanup, so just hide it for now.
sendButtonActionBarWrapper.isHidden = true
sendButtonView.isHidden = true
addSubview(sendFAB)
sendFAB.accessibilityLabel = String.addPictureNoteContentDescription
sendFAB.setImage(Metrics.sendFABImage, for: .normal)
sendFAB.contentEdgeInsets = Metrics.sendFABContentInsets
sendFAB.disabledAlpha = Metrics.sendFABDisabledAlpha
sendFAB.translatesAutoresizingMaskIntoConstraints = false
sendFAB.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
sendFABBottomConstraint = sendFAB.bottomAnchor.constraint(
equalTo: bottomAnchor,
constant: -1 * Metrics.sendFABPadding)
sendFABBottomConstraint?.isActive = true
}
// Placeholder label.
placeholderLabel.font = textView.font
placeholderLabel.numberOfLines = 0
placeholderLabel.text = String.textLabelHint
placeholderLabel.textColor = .lightGray
textView.addSubview(placeholderLabel)
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
placeholderLabelTopConstraint =
placeholderLabel.topAnchor.constraint(equalTo: textView.topAnchor)
placeholderLabelTopConstraint?.isActive = true
placeholderLabelLeadingConstraint =
placeholderLabel.leadingAnchor.constraint(equalTo: textView.leadingAnchor)
placeholderLabelLeadingConstraint?.isActive = true
placeholderLabelTrailingConstraint =
placeholderLabel.trailingAnchor.constraint(equalTo: textView.trailingAnchor)
placeholderLabelTrailingConstraint?.isActive = true
updateTextViewTextContainerInset()
}
private func registerForNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(handleKeyboardNotification(_:)),
name: .keyboardObserverWillShow,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(handleKeyboardNotification(_:)),
name: .keyboardObserverWillHide,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(handleKeyboardNotification(_:)),
name: .keyboardObserverWillChangeFrame,
object: nil)
}
// Animates the toolbar and updates the text view insets for the current keyboard height and send
// button style.
private func animateToolbarAndUpdateInsets(withDuration duration: TimeInterval,
options: UIView.AnimationOptions = []) {
let convertedKeyboardFrame = convert(KeyboardObserver.shared.currentKeyboardFrame, from: nil)
let keyboardOffset = KeyboardObserver.shared.isKeyboardVisible ?
bounds.intersection(convertedKeyboardFrame).height : 0
var sendButtonActionBarBottomConstraintConstant: CGFloat
switch sendButtonStyle {
case .toolbar:
sendButtonActionBar.isHidden = false
textView.contentInset.bottom = keyboardOffset +
sendButtonActionBar.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
sendButtonActionBarBottomConstraintConstant = -keyboardOffset
case .button:
textView.contentInset.bottom = keyboardOffset
sendButtonActionBarBottomConstraintConstant = -keyboardOffset +
sendButtonActionBar.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
}
textView.scrollIndicatorInsets = textView.contentInset
UIView.animate(withDuration: duration, delay: 0, options: options, animations: {
self.sendButtonActionBarWrapperBottomConstraint?.constant =
sendButtonActionBarBottomConstraintConstant
self.sendFABBottomConstraint?.constant = sendButtonActionBarBottomConstraintConstant -
Metrics.sendFABPadding
self.layoutIfNeeded()
}) { (_) in
if self.sendButtonStyle == .button {
self.sendButtonActionBar.isHidden = true
}
}
}
private func updateTextViewTextContainerInset() {
var textInset = textViewTextContainerInset
var textViewHorizontalInset: CGFloat {
switch sendButtonStyle {
case .button:
return sendButtonViewHorizontalInset * 2 +
sendButtonView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).width
case .toolbar:
return NotesView.textContainerHorizontalInset
}
}
if UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft {
textInset.left = textViewHorizontalInset + safeAreaInsetsOrZero.left
} else {
textInset.right = textViewHorizontalInset + safeAreaInsetsOrZero.right
}
textView.textContainerInset = textInset
placeholderLabelTopConstraint?.constant = textView.textContainerInset.top
placeholderLabelLeadingConstraint?.constant = textView.textContainerInset.left +
textViewHorizontalBuffer
placeholderLabelTrailingConstraint?.constant = -textView.textContainerInset.right -
textViewHorizontalBuffer
}
// MARK: - Notifications
@objc func handleKeyboardNotification(_ notification: Notification) {
guard let duration = KeyboardObserver.animationDuration(fromKeyboardNotification: notification),
let animationCurve =
KeyboardObserver.animationCurve(fromKeyboardNotification: notification) else { return }
animateToolbarAndUpdateInsets(withDuration: duration, options: [animationCurve])
}
}
| apache-2.0 | 88d0525edf1a22a4c3134d4ad72c74fc | 40.157459 | 100 | 0.736425 | 5.501846 | false | false | false | false |
verticon/MecklenburgTrailOfHistory | Trail of History/List View/ListViewController.swift | 1 | 5368 | //
// DummyListTableViewController.swift
// Trail of History
//
// Created by Robert Vaessen on 8/24/16.
// Copyright © 2018 Robert Vaessen. All rights reserved.
//
import UIKit
import VerticonsToolbox
class ListViewController : UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageSwiper: PageSwiper!
var pageViewController: PageViewController?
fileprivate let poiCellReuseIdentifier = "PointOfInterestCell"
fileprivate var pointsOfInterest = [PointOfInterest]()
private var listenerToken: PointOfInterest.ListenerToken!
override func viewDidLoad() {
super.viewDidLoad()
pageSwiper.backgroundColor = UIColor.tohGreyishBrownTwoColor
pageSwiper.direction = .left
// Hide the left button. It is only there to keep the title in the same position as on the Map View (which has left and right buttons).
navigationItem.leftBarButtonItem?.tintColor = UIColor.tohGreyishBrownTwoColor // navigationController?.navigationBar.barTintColor
navigationItem.leftBarButtonItem?.isEnabled = false
navigationItem.rightBarButtonItem?.tintColor = UIColor.tohTerracotaColor
let poiCellNib: UINib? = UINib(nibName: "PointOfInterestCell", bundle: nil)
collectionView?.register(poiCellNib, forCellWithReuseIdentifier: poiCellReuseIdentifier)
listenerToken = PointOfInterest.addListener(poiListener)
_ = UserLocation.instance.addListener(self, handlerClassMethod: ListViewController.userLocationEventHandler)
}
override func viewWillAppear(_ animated: Bool) {
navigationItem.hidesBackButton = true
if let pageVC = pageViewController {
pageVC.navigationItem.leftBarButtonItems = self.navigationItem.leftBarButtonItems
pageVC.navigationItem.rightBarButtonItems = self.navigationItem.rightBarButtonItems
}
}
func poiListener(event: Firebase.Observer.Event, key: Firebase.Observer.Key, poi: PointOfInterest) {
guard Thread.current.isMainThread else { fatalError("Poi observer not on main thread: \(Thread.current)") }
switch event {
case .added:
print("List View: added \(poi.name)")
pointsOfInterest.append(poi)
pointsOfInterest = pointsOfInterest.sorted { $0.location.coordinate.latitude > $1.location.coordinate.latitude } // northmost first
case .updated:
pointsOfInterest = pointsOfInterest.filter { $0 != poi }
pointsOfInterest.append(poi)
case .removed:
pointsOfInterest = pointsOfInterest.filter { $0 != poi }
}
collectionView?.reloadData()
}
private func userLocationEventHandler(event: UserLocationEvent) {
switch event {
case .locationUpdate: collectionView.reloadData()
default: break
}
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if let pageVC = pageViewController {
pageVC.switchPages(sender: self)
return false
}
return true
}
@IBAction func unwind(_ segue:UIStoryboardSegue) {
}
}
extension ListViewController : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return pointsOfInterest.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let poi = pointsOfInterest[indexPath.item]
let poiCell = collectionView.dequeueReusableCell(withReuseIdentifier: poiCellReuseIdentifier, for: indexPath) as! PointOfInterestCell
let imageView = UIImageView(image: poi.image)
imageView.contentMode = .scaleAspectFill
let scrollView = UIScrollView()
scrollView.addSubview(imageView)
poiCell.backgroundView = scrollView
poiCell.nameLabel.text = poi.name
poiCell.distanceLabel.text = poi.distanceToUserText
return poiCell
}
}
extension ListViewController : UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if let scrollView = cell.backgroundView, let imageView = scrollView.subviews[0] as? UIImageView {
imageView.frame.size = imageView.image!.aspectFill(in: scrollView.frame.size)
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: false)
let frame = collectionView.cellForItem(at: indexPath)!.frame
DetailView.present(poi: pointsOfInterest[indexPath.item], startingFrom: frame)
}
}
extension ListViewController : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let barHeight = navigationController?.navigationBar.frame.maxY ?? UIApplication.shared.statusBarFrame.height
return CGSize(width: collectionView.bounds.size.width, height: CGFloat((UIScreen.main.bounds.height - barHeight)/4))
}
}
| mit | 2a96eabc9d2bf1472cd64f2bc4c8bbfa | 39.659091 | 160 | 0.713061 | 5.48773 | false | false | false | false |
eKasztany/4ania | ios/Queue/Pods/AlamofireImage/Source/UIButton+AlamofireImage.swift | 4 | 19417 | //
// UIButton+AlamofireImage.swift
//
// Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 Alamofire
import Foundation
import UIKit
extension UIButton {
// MARK: - Private - AssociatedKeys
private struct AssociatedKey {
static var imageDownloader = "af_UIButton.ImageDownloader"
static var sharedImageDownloader = "af_UIButton.SharedImageDownloader"
static var imageReceipts = "af_UIButton.ImageReceipts"
static var backgroundImageReceipts = "af_UIButton.BackgroundImageReceipts"
}
// MARK: - Properties
/// The instance image downloader used to download all images. If this property is `nil`, the `UIButton` will
/// fallback on the `af_sharedImageDownloader` for all downloads. The most common use case for needing to use a
/// custom instance image downloader is when images are behind different basic auth credentials.
public var af_imageDownloader: ImageDownloader? {
get {
return objc_getAssociatedObject(self, &AssociatedKey.imageDownloader) as? ImageDownloader
}
set {
objc_setAssociatedObject(self, &AssociatedKey.imageDownloader, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// The shared image downloader used to download all images. By default, this is the default `ImageDownloader`
/// instance backed with an `AutoPurgingImageCache` which automatically evicts images from the cache when the memory
/// capacity is reached or memory warning notifications occur. The shared image downloader is only used if the
/// `af_imageDownloader` is `nil`.
public class var af_sharedImageDownloader: ImageDownloader {
get {
guard let
downloader = objc_getAssociatedObject(self, &AssociatedKey.sharedImageDownloader) as? ImageDownloader
else {
return ImageDownloader.default
}
return downloader
}
set {
objc_setAssociatedObject(self, &AssociatedKey.sharedImageDownloader, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
private var imageRequestReceipts: [UInt: RequestReceipt] {
get {
guard let
receipts = objc_getAssociatedObject(self, &AssociatedKey.imageReceipts) as? [UInt: RequestReceipt]
else {
return [:]
}
return receipts
}
set {
objc_setAssociatedObject(self, &AssociatedKey.imageReceipts, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
private var backgroundImageRequestReceipts: [UInt: RequestReceipt] {
get {
guard let
receipts = objc_getAssociatedObject(self, &AssociatedKey.backgroundImageReceipts) as? [UInt: RequestReceipt]
else {
return [:]
}
return receipts
}
set {
objc_setAssociatedObject(self, &AssociatedKey.backgroundImageReceipts, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Image Downloads
/// Asynchronously downloads an image from the specified URL and sets it once the request is finished.
///
/// If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be
/// set immediately, and then the remote image will be set once the image request is finished.
///
/// - parameter state: The control state of the button to set the image on.
/// - parameter url: The URL used for your image request.
/// - parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the
/// image will not change its image until the image request finishes. Defaults
/// to `nil`.
/// - parameter progress: The closure to be executed periodically during the lifecycle of the request.
/// Defaults to `nil`.
/// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue.
/// - parameter completion: A closure to be executed when the image request finishes. The closure takes a
/// single response value containing either the image or the error that occurred. If
/// the image was returned from the image cache, the response will be `nil`. Defaults
/// to `nil`.
public func af_setImage(
for state: UIControlState,
url: URL,
placeHolderImage: UIImage? = nil,
progress: ImageDownloader.ProgressHandler? = nil,
progressQueue: DispatchQueue = DispatchQueue.main,
completion: ((DataResponse<UIImage>) -> Void)? = nil)
{
af_setImage(
for: state,
urlRequest: urlRequest(with: url),
placeholderImage: placeHolderImage,
progress: progress,
progressQueue: progressQueue,
completion: completion
)
}
/// Asynchronously downloads an image from the specified URL request and sets it once the request is finished.
///
/// If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be
/// set immediately, and then the remote image will be set once the image request is finished.
///
/// - parameter state: The control state of the button to set the image on.
/// - parameter urlRequest: The URL request.
/// - parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the
/// image will not change its image until the image request finishes. Defaults
/// to `nil`.
/// - parameter progress: The closure to be executed periodically during the lifecycle of the request.
/// Defaults to `nil`.
/// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue.
/// - parameter completion: A closure to be executed when the image request finishes. The closure takes a
/// single response value containing either the image or the error that occurred. If
/// the image was returned from the image cache, the response will be `nil`. Defaults
/// to `nil`.
public func af_setImage(
for state: UIControlState,
urlRequest: URLRequestConvertible,
placeholderImage: UIImage? = nil,
progress: ImageDownloader.ProgressHandler? = nil,
progressQueue: DispatchQueue = DispatchQueue.main,
completion: ((DataResponse<UIImage>) -> Void)? = nil)
{
guard !isImageURLRequest(urlRequest, equalToActiveRequestURLForState: state) else { return }
af_cancelImageRequest(for: state)
let imageDownloader = af_imageDownloader ?? UIButton.af_sharedImageDownloader
let imageCache = imageDownloader.imageCache
// Use the image from the image cache if it exists
if
let request = urlRequest.urlRequest,
let image = imageCache?.image(for: request, withIdentifier: nil)
{
let response = DataResponse<UIImage>(
request: urlRequest.urlRequest,
response: nil,
data: nil,
result: .success(image)
)
completion?(response)
setImage(image, for: state)
return
}
// Set the placeholder since we're going to have to download
if let placeholderImage = placeholderImage { setImage(placeholderImage, for: state) }
// Generate a unique download id to check whether the active request has changed while downloading
let downloadID = UUID().uuidString
// Download the image, then set the image for the control state
let requestReceipt = imageDownloader.download(
urlRequest,
receiptID: downloadID,
filter: nil,
progress: progress,
progressQueue: progressQueue,
completion: { [weak self] response in
guard let strongSelf = self else { return }
completion?(response)
guard
strongSelf.isImageURLRequest(response.request, equalToActiveRequestURLForState: state) &&
strongSelf.imageRequestReceipt(for: state)?.receiptID == downloadID
else {
return
}
if let image = response.result.value {
strongSelf.setImage(image, for: state)
}
strongSelf.setImageRequestReceipt(nil, for: state)
}
)
setImageRequestReceipt(requestReceipt, for: state)
}
/// Cancels the active download request for the image, if one exists.
public func af_cancelImageRequest(for state: UIControlState) {
guard let receipt = imageRequestReceipt(for: state) else { return }
let imageDownloader = af_imageDownloader ?? UIButton.af_sharedImageDownloader
imageDownloader.cancelRequest(with: receipt)
setImageRequestReceipt(nil, for: state)
}
// MARK: - Background Image Downloads
/// Asynchronously downloads an image from the specified URL and sets it once the request is finished.
///
/// If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be
/// set immediately, and then the remote image will be set once the image request is finished.
///
/// - parameter state: The control state of the button to set the image on.
/// - parameter url: The URL used for the image request.
/// - parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the
/// background image will not change its image until the image request finishes.
/// Defaults to `nil`.
/// - parameter progress: The closure to be executed periodically during the lifecycle of the request.
/// Defaults to `nil`.
/// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue.
/// - parameter completion: A closure to be executed when the image request finishes. The closure takes a
/// single response value containing either the image or the error that occurred. If
/// the image was returned from the image cache, the response will be `nil`. Defaults
/// to `nil`.
public func af_setBackgroundImage(
for state: UIControlState,
url: URL,
placeHolderImage: UIImage? = nil,
progress: ImageDownloader.ProgressHandler? = nil,
progressQueue: DispatchQueue = DispatchQueue.main,
completion: ((DataResponse<UIImage>) -> Void)? = nil)
{
af_setBackgroundImage(
for: state,
urlRequest: urlRequest(with: url),
placeholderImage: placeHolderImage,
completion: completion)
}
/// Asynchronously downloads an image from the specified URL request and sets it once the request is finished.
///
/// If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be
/// set immediately, and then the remote image will be set once the image request is finished.
///
/// - parameter state: The control state of the button to set the image on.
/// - parameter urlRequest: The URL request.
/// - parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the
/// background image will not change its image until the image request finishes.
/// Defaults to `nil`.
/// - parameter progress: The closure to be executed periodically during the lifecycle of the request.
/// Defaults to `nil`.
/// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue.
/// - parameter completion: A closure to be executed when the image request finishes. The closure takes a
/// single response value containing either the image or the error that occurred. If
/// the image was returned from the image cache, the response will be `nil`. Defaults
/// to `nil`.
public func af_setBackgroundImage(
for state: UIControlState,
urlRequest: URLRequestConvertible,
placeholderImage: UIImage? = nil,
progress: ImageDownloader.ProgressHandler? = nil,
progressQueue: DispatchQueue = DispatchQueue.main,
completion: ((DataResponse<UIImage>) -> Void)? = nil)
{
guard !isImageURLRequest(urlRequest, equalToActiveRequestURLForState: state) else { return }
af_cancelBackgroundImageRequest(for: state)
let imageDownloader = af_imageDownloader ?? UIButton.af_sharedImageDownloader
let imageCache = imageDownloader.imageCache
// Use the image from the image cache if it exists
if
let request = urlRequest.urlRequest,
let image = imageCache?.image(for: request, withIdentifier: nil)
{
let response = DataResponse<UIImage>(
request: urlRequest.urlRequest,
response: nil,
data: nil,
result: .success(image)
)
completion?(response)
setBackgroundImage(image, for: state)
return
}
// Set the placeholder since we're going to have to download
if let placeholderImage = placeholderImage { self.setBackgroundImage(placeholderImage, for: state) }
// Generate a unique download id to check whether the active request has changed while downloading
let downloadID = UUID().uuidString
// Download the image, then set the image for the control state
let requestReceipt = imageDownloader.download(
urlRequest,
receiptID: downloadID,
filter: nil,
progress: progress,
progressQueue: progressQueue,
completion: { [weak self] response in
guard let strongSelf = self else { return }
completion?(response)
guard
strongSelf.isBackgroundImageURLRequest(response.request, equalToActiveRequestURLForState: state) &&
strongSelf.backgroundImageRequestReceipt(for: state)?.receiptID == downloadID
else {
return
}
if let image = response.result.value {
strongSelf.setBackgroundImage(image, for: state)
}
strongSelf.setBackgroundImageRequestReceipt(nil, for: state)
}
)
setBackgroundImageRequestReceipt(requestReceipt, for: state)
}
/// Cancels the active download request for the background image, if one exists.
public func af_cancelBackgroundImageRequest(for state: UIControlState) {
guard let receipt = backgroundImageRequestReceipt(for: state) else { return }
let imageDownloader = af_imageDownloader ?? UIButton.af_sharedImageDownloader
imageDownloader.cancelRequest(with: receipt)
setBackgroundImageRequestReceipt(nil, for: state)
}
// MARK: - Internal - Image Request Receipts
func imageRequestReceipt(for state: UIControlState) -> RequestReceipt? {
guard let receipt = imageRequestReceipts[state.rawValue] else { return nil }
return receipt
}
func setImageRequestReceipt(_ receipt: RequestReceipt?, for state: UIControlState) {
var receipts = imageRequestReceipts
receipts[state.rawValue] = receipt
imageRequestReceipts = receipts
}
// MARK: - Internal - Background Image Request Receipts
func backgroundImageRequestReceipt(for state: UIControlState) -> RequestReceipt? {
guard let receipt = backgroundImageRequestReceipts[state.rawValue] else { return nil }
return receipt
}
func setBackgroundImageRequestReceipt(_ receipt: RequestReceipt?, for state: UIControlState) {
var receipts = backgroundImageRequestReceipts
receipts[state.rawValue] = receipt
backgroundImageRequestReceipts = receipts
}
// MARK: - Private - URL Request Helpers
private func isImageURLRequest(
_ urlRequest: URLRequestConvertible?,
equalToActiveRequestURLForState state: UIControlState)
-> Bool
{
if
let currentURL = imageRequestReceipt(for: state)?.request.task?.originalRequest?.url,
let requestURL = urlRequest?.urlRequest?.url,
currentURL == requestURL
{
return true
}
return false
}
private func isBackgroundImageURLRequest(
_ urlRequest: URLRequestConvertible?,
equalToActiveRequestURLForState state: UIControlState)
-> Bool
{
if
let currentRequestURL = backgroundImageRequestReceipt(for: state)?.request.task?.originalRequest?.url,
let requestURL = urlRequest?.urlRequest?.url,
currentRequestURL == requestURL
{
return true
}
return false
}
private func urlRequest(with url: URL) -> URLRequest {
var urlRequest = URLRequest(url: url)
for mimeType in DataRequest.acceptableImageContentTypes {
urlRequest.addValue(mimeType, forHTTPHeaderField: "Accept")
}
return urlRequest
}
}
| apache-2.0 | 44c3f18b0f5c8aa71e234dfe6246336e | 43.432494 | 128 | 0.630581 | 5.592454 | false | false | false | false |
material-motion/motion-animator-objc | tests/unit/TimeScaleFactorTests.swift | 2 | 3191 | /*
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 TimeScaleFactorTests: XCTestCase {
let traits = MDMAnimationTraits(duration: 1)
var layer: CALayer!
var addedAnimations: [CAAnimation]!
var animator: MotionAnimator!
override func setUp() {
super.setUp()
addedAnimations = []
animator = MotionAnimator()
animator.addCoreAnimationTracer { (_, animation) in
self.addedAnimations.append(animation)
}
layer = CALayer()
}
override func tearDown() {
layer = nil
addedAnimations = nil
animator = nil
super.tearDown()
}
func testDefaultTimeScaleFactorDoesNotModifyDuration() {
animator.animate(with: traits, between: [0, 1], layer: layer, keyPath: .rotation)
XCTAssertEqual(addedAnimations.count, 1)
let animation = addedAnimations.last!
XCTAssertEqual(animation.duration, 1)
}
func testExplicitTimeScaleFactorChangesDuration() {
animator.timeScaleFactor = 0.5
animator.animate(with: traits, between: [0, 1], layer: layer, keyPath: .rotation)
XCTAssertEqual(addedAnimations.count, 1)
let animation = addedAnimations.last!
XCTAssertEqual(animation.duration, traits.duration * 0.5)
}
func testTransactionTimeScaleFactorChangesDuration() {
CATransaction.begin()
CATransaction.mdm_setTimeScaleFactor(0.5)
animator.animate(with: traits, between: [0, 1], layer: layer, keyPath: .rotation)
CATransaction.commit()
XCTAssertEqual(addedAnimations.count, 1)
let animation = addedAnimations.last!
XCTAssertEqual(animation.duration, traits.duration * 0.5)
}
func testTransactionTimeScaleFactorOverridesAnimatorTimeScaleFactor() {
animator.timeScaleFactor = 2
CATransaction.begin()
CATransaction.mdm_setTimeScaleFactor(0.5)
animator.animate(with: traits, between: [0, 1], layer: layer, keyPath: .rotation)
CATransaction.commit()
XCTAssertEqual(addedAnimations.count, 1)
let animation = addedAnimations.last!
XCTAssertEqual(animation.duration, traits.duration * 0.5)
}
func testNilTransactionTimeScaleFactorUsesAnimatorTimeScaleFactor() {
animator.timeScaleFactor = 2
CATransaction.begin()
CATransaction.mdm_setTimeScaleFactor(0.5)
CATransaction.mdm_setTimeScaleFactor(nil)
animator.animate(with: traits, between: [0, 1], layer: layer, keyPath: .rotation)
CATransaction.commit()
XCTAssertEqual(addedAnimations.count, 1)
let animation = addedAnimations.last!
XCTAssertEqual(animation.duration, traits.duration * 2)
}
}
| apache-2.0 | 0dadb04a9064a3eb6d6d92949ad97000 | 27.747748 | 85 | 0.740207 | 4.341497 | false | true | false | false |
austinzheng/swift | test/attr/accessibility_proto.swift | 4 | 2970 | // RUN: %target-typecheck-verify-swift
// RUN: %target-swift-frontend -typecheck -disable-access-control %s
public protocol ProtoWithReqs {
associatedtype Assoc
func foo()
}
public struct Adopter<T> : ProtoWithReqs {}
// expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
// expected-error@-2 {{type alias 'Assoc' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
extension Adopter {
typealias Assoc = Int
// expected-note@-1 {{mark the type alias as 'public' to satisfy the requirement}} {{3-3=public }}
func foo() {}
// expected-note@-1 {{mark the instance method as 'public' to satisfy the requirement}} {{3-3=public }}
}
public class AnotherAdopterBase {
typealias Assoc = Int
// expected-note@-1 {{mark the type alias as 'public' to satisfy the requirement}} {{3-3=public }}
func foo() {}
// expected-note@-1 {{mark the instance method as 'public' to satisfy the requirement}} {{3-3=public }}
}
public class AnotherAdopterSub : AnotherAdopterBase, ProtoWithReqs {}
// expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
// expected-error@-2 {{type alias 'Assoc' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
public protocol ReqProvider {}
extension ReqProvider {
func foo() {}
// expected-note@-1 {{mark the instance method as 'public' to satisfy the requirement}} {{3-3=public }}
}
public struct AdoptViaProtocol : ProtoWithReqs, ReqProvider {
// expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
public typealias Assoc = Int
}
public protocol ReqProvider2 {}
extension ProtoWithReqs where Self : ReqProvider2 {
func foo() {}
// expected-note@-1 {{mark the instance method as 'public' to satisfy the requirement}} {{3-3=public }}
}
public struct AdoptViaCombinedProtocol : ProtoWithReqs, ReqProvider2 {
// expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
public typealias Assoc = Int
}
public protocol PublicInitProto {
var value: Int { get }
init(value: Int)
}
public struct NonPublicInitStruct: PublicInitProto {
public var value: Int
init(value: Int) {
// expected-error@-1 {{initializer 'init(value:)' must be declared public because it matches a requirement in public protocol 'PublicInitProto'}}
// expected-note@-2 {{mark the initializer as 'public' to satisfy the requirement}}
self.value = value
}
}
public struct NonPublicMemberwiseInitStruct: PublicInitProto {
// expected-error@-1 {{initializer 'init(value:)' must be declared public because it matches a requirement in public protocol 'PublicInitProto'}}
public var value: Int
}
| apache-2.0 | 6e3c6266dd0b7ad84107d4861d6d2049 | 45.40625 | 147 | 0.73165 | 3.991935 | false | false | false | false |
wireapp/wire-ios-sync-engine | Source/Notifications/Push notifications/Helpers/ZMLocalNotificationSet.swift | 1 | 5178 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
import WireTransport
import UserNotifications
@objc public protocol ZMSynchonizableKeyValueStore: KeyValueStore {
func enqueueDelayedSave()
}
@objc final class ZMLocalNotificationSet: NSObject {
let archivingKey: String
let keyValueStore: ZMSynchonizableKeyValueStore
var notificationCenter: UserNotificationCenter = UNUserNotificationCenter.current()
fileprivate(set) var notifications = Set<ZMLocalNotification>() {
didSet { updateArchive() }
}
private(set) var oldNotifications = [NotificationUserInfo]()
private var allNotifications: [NotificationUserInfo] {
return notifications.compactMap { $0.userInfo } + oldNotifications
}
init(archivingKey: String, keyValueStore: ZMSynchonizableKeyValueStore) {
self.archivingKey = archivingKey
self.keyValueStore = keyValueStore
super.init()
unarchiveOldNotifications()
}
/// Unarchives all previously created notifications that haven't been cancelled yet
func unarchiveOldNotifications() {
guard let archive = keyValueStore.storedValue(key: archivingKey) as? Data,
let unarchivedNotes = NSKeyedUnarchiver.unarchiveObject(with: archive) as? [NotificationUserInfo]
else { return }
self.oldNotifications = unarchivedNotes
}
/// Archives all scheduled notifications - this could be optimized
func updateArchive() {
let data = NSKeyedArchiver.archivedData(withRootObject: allNotifications)
keyValueStore.store(value: data as NSData, key: archivingKey)
keyValueStore.enqueueDelayedSave() // we need to save otherwise changes might not be stored
}
@discardableResult func remove(_ notification: ZMLocalNotification) -> ZMLocalNotification? {
return notifications.remove(notification)
}
func addObject(_ notification: ZMLocalNotification) {
notifications.insert(notification)
}
func replaceObject(_ toReplace: ZMLocalNotification, newObject: ZMLocalNotification) {
notifications.remove(toReplace)
notifications.insert(newObject)
}
/// Cancels all notifications
func cancelAllNotifications() {
let ids = allNotifications.compactMap { $0.requestID?.uuidString }
notificationCenter.removeAllNotifications(withIdentifiers: ids)
notifications = Set()
oldNotifications = []
}
/// This cancels all notifications of a specific conversation
func cancelNotifications(_ conversation: ZMConversation) {
cancelOldNotifications(conversation)
cancelCurrentNotifications(conversation)
}
/// Cancel all notifications created in this run
func cancelCurrentNotifications(_ conversation: ZMConversation) {
guard notifications.count > 0 else { return }
let toRemove = notifications.filter { $0.conversationID == conversation.remoteIdentifier }
notificationCenter.removeAllNotifications(withIdentifiers: toRemove.map { $0.id.uuidString })
notifications.subtract(toRemove)
}
/// Cancels all notifications created in previous runs
func cancelOldNotifications(_ conversation: ZMConversation) {
guard oldNotifications.count > 0 else { return }
oldNotifications = oldNotifications.filter { userInfo in
guard
userInfo.conversationID == conversation.remoteIdentifier,
let requestID = userInfo.requestID?.uuidString
else { return true }
notificationCenter.removeAllNotifications(withIdentifiers: [requestID])
return false
}
}
/// Cancal all notifications with the given message nonce
func cancelCurrentNotifications(messageNonce: UUID) {
guard notifications.count > 0 else { return }
let toRemove = notifications.filter { $0.messageNonce == messageNonce }
notificationCenter.removeAllNotifications(withIdentifiers: toRemove.map { $0.id.uuidString })
notifications.subtract(toRemove)
}
}
// Event Notifications
extension ZMLocalNotificationSet {
func cancelNotificationForIncomingCall(_ conversation: ZMConversation) {
let toRemove = notifications.filter {
$0.conversationID == conversation.remoteIdentifier && $0.isCallingNotification
}
notificationCenter.removeAllNotifications(withIdentifiers: toRemove.map { $0.id.uuidString })
notifications.subtract(toRemove)
}
}
| gpl-3.0 | 4c659c073c81c8b1415f7496ca92218d | 37.355556 | 106 | 0.716686 | 5.360248 | false | false | false | false |
hughbe/swift | stdlib/public/core/Unicode.swift | 2 | 38125 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Conversions between different Unicode encodings. Note that UTF-16 and
// UTF-32 decoding are *not* currently resilient to erroneous data.
/// The result of one Unicode decoding step.
///
/// Each `UnicodeDecodingResult` instance can represent a Unicode scalar value,
/// an indication that no more Unicode scalars are available, or an indication
/// of a decoding error.
@_fixed_layout
public enum UnicodeDecodingResult : Equatable {
/// A decoded Unicode scalar value.
case scalarValue(Unicode.Scalar)
/// An indication that no more Unicode scalars are available in the input.
case emptyInput
/// An indication of a decoding error.
case error
public static func == (
lhs: UnicodeDecodingResult,
rhs: UnicodeDecodingResult
) -> Bool {
switch (lhs, rhs) {
case (.scalarValue(let lhsScalar), .scalarValue(let rhsScalar)):
return lhsScalar == rhsScalar
case (.emptyInput, .emptyInput):
return true
case (.error, .error):
return true
default:
return false
}
}
}
/// A Unicode encoding form that translates between Unicode scalar values and
/// form-specific code units.
///
/// The `UnicodeCodec` protocol declares methods that decode code unit
/// sequences into Unicode scalar values and encode Unicode scalar values
/// into code unit sequences. The standard library implements codecs for the
/// UTF-8, UTF-16, and UTF-32 encoding schemes as the `UTF8`, `UTF16`, and
/// `UTF32` types, respectively. Use the `Unicode.Scalar` type to work with
/// decoded Unicode scalar values.
public protocol UnicodeCodec : Unicode.Encoding {
/// Creates an instance of the codec.
init()
/// Starts or continues decoding a code unit sequence into Unicode scalar
/// values.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-8 encoded bytes of a string into an
/// array of `Unicode.Scalar` instances:
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf8))
/// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]"
///
/// var bytesIterator = str.utf8.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf8Decoder = UTF8()
/// Decode: while true {
/// switch utf8Decoder.decode(&bytesIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires four code units for its UTF-8
/// representation. The following code uses the `UTF8` codec to encode a
/// fermata in UTF-8:
///
/// var bytes: [UTF8.CodeUnit] = []
/// UTF8.encode("𝄐", into: { bytes.append($0) })
/// print(bytes)
/// // Prints "[240, 157, 132, 144]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
)
/// Searches for the first occurrence of a `CodeUnit` that is equal to 0.
///
/// Is an equivalent of `strlen` for C-strings.
///
/// - Complexity: O(*n*)
static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int
}
/// A codec for translating between Unicode scalar values and UTF-8 code
/// units.
extension Unicode.UTF8 : UnicodeCodec {
/// Creates an instance of the UTF-8 codec.
public init() { self = ._swift3Buffer(ForwardParser()) }
/// Starts or continues decoding a UTF-8 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-8 encoded bytes of a string into an
/// array of `Unicode.Scalar` instances. This is a demonstration only---if
/// you need the Unicode scalar representation of a string, use its
/// `unicodeScalars` view.
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf8))
/// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]"
///
/// var bytesIterator = str.utf8.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf8Decoder = UTF8()
/// Decode: while true {
/// switch utf8Decoder.decode(&bytesIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
@inline(__always)
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
guard case ._swift3Buffer(var parser) = self else {
Builtin.unreachable()
}
defer { self = ._swift3Buffer(parser) }
switch parser.parseScalar(from: &input) {
case .valid(let s): return .scalarValue(UTF8.decode(s))
case .error: return .error
case .emptyInput: return .emptyInput
}
}
/// Attempts to decode a single UTF-8 code unit sequence starting at the LSB
/// of `buffer`.
///
/// - Returns:
/// - result: The decoded code point if the code unit sequence is
/// well-formed; `nil` otherwise.
/// - length: The length of the code unit sequence in bytes if it is
/// well-formed; otherwise the *maximal subpart of the ill-formed
/// sequence* (Unicode 8.0.0, Ch 3.9, D93b), i.e. the number of leading
/// code units that were valid or 1 in case none were valid. Unicode
/// recommends to skip these bytes and replace them by a single
/// replacement character (U+FFFD).
///
/// - Requires: There is at least one used byte in `buffer`, and the unused
/// space in `buffer` is filled with some value not matching the UTF-8
/// continuation byte form (`0b10xxxxxx`).
public // @testable
static func _decodeOne(_ buffer: UInt32) -> (result: UInt32?, length: UInt8) {
// Note the buffer is read least significant byte first: [ #3 #2 #1 #0 ].
if buffer & 0x80 == 0 { // 1-byte sequence (ASCII), buffer: [ ... ... ... CU0 ].
let value = buffer & 0xff
return (value, 1)
}
var p = ForwardParser()
p._buffer._storage = buffer
p._buffer._bitCount = 32
var i = EmptyCollection<UInt8>().makeIterator()
switch p.parseScalar(from: &i) {
case .valid(let s):
return (
result: UTF8.decode(s).value,
length: UInt8(extendingOrTruncating: s.count))
case .error(let l):
return (result: nil, length: UInt8(extendingOrTruncating: l))
case .emptyInput: Builtin.unreachable()
}
}
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires four code units for its UTF-8
/// representation. The following code encodes a fermata in UTF-8:
///
/// var bytes: [UTF8.CodeUnit] = []
/// UTF8.encode("𝄐", into: { bytes.append($0) })
/// print(bytes)
/// // Prints "[240, 157, 132, 144]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
@inline(__always)
public static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
) {
var s = encode(input)!._biasedBits
processCodeUnit(UInt8(extendingOrTruncating: s) &- 0x01)
s &>>= 8
if _fastPath(s == 0) { return }
processCodeUnit(UInt8(extendingOrTruncating: s) &- 0x01)
s &>>= 8
if _fastPath(s == 0) { return }
processCodeUnit(UInt8(extendingOrTruncating: s) &- 0x01)
s &>>= 8
if _fastPath(s == 0) { return }
processCodeUnit(UInt8(extendingOrTruncating: s) &- 0x01)
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// UTF-8 continuation byte.
///
/// Continuation bytes take the form `0b10xxxxxx`. For example, a lowercase
/// "e" with an acute accent above it (`"é"`) uses 2 bytes for its UTF-8
/// representation: `0b11000011` (195) and `0b10101001` (169). The second
/// byte is a continuation byte.
///
/// let eAcute = "é"
/// for codePoint in eAcute.utf8 {
/// print(codePoint, UTF8.isContinuation(codePoint))
/// }
/// // Prints "195 false"
/// // Prints "169 true"
///
/// - Parameter byte: A UTF-8 code unit.
/// - Returns: `true` if `byte` is a continuation byte; otherwise, `false`.
public static func isContinuation(_ byte: CodeUnit) -> Bool {
return byte & 0b11_00__0000 == 0b10_00__0000
}
public static func _nullCodeUnitOffset(
in input: UnsafePointer<CodeUnit>
) -> Int {
return Int(_swift_stdlib_strlen_unsigned(input))
}
// Support parsing C strings as-if they are UTF8 strings.
public static func _nullCodeUnitOffset(
in input: UnsafePointer<CChar>
) -> Int {
return Int(_swift_stdlib_strlen(input))
}
}
// @available(swift, obsoleted: 4.0, renamed: "Unicode.UTF8")
public typealias UTF8 = Unicode.UTF8
/// A codec for translating between Unicode scalar values and UTF-16 code
/// units.
extension Unicode.UTF16 : UnicodeCodec {
/// Creates an instance of the UTF-16 codec.
public init() { self = ._swift3Buffer(ForwardParser()) }
/// Starts or continues decoding a UTF-16 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-16 encoded bytes of a string into an
/// array of `Unicode.Scalar` instances. This is a demonstration only---if
/// you need the Unicode scalar representation of a string, use its
/// `unicodeScalars` view.
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf16))
/// // Prints "[10024, 85, 110, 105, 99, 111, 100, 101, 10024]"
///
/// var codeUnitIterator = str.utf16.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf16Decoder = UTF16()
/// Decode: while true {
/// switch utf16Decoder.decode(&codeUnitIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
guard case ._swift3Buffer(var parser) = self else {
Builtin.unreachable()
}
defer { self = ._swift3Buffer(parser) }
switch parser.parseScalar(from: &input) {
case .valid(let s): return .scalarValue(UTF16.decode(s))
case .error: return .error
case .emptyInput: return .emptyInput
}
}
/// Try to decode one Unicode scalar, and return the actual number of code
/// units it spanned in the input. This function may consume more code
/// units than required for this scalar.
@_versioned
internal mutating func _decodeOne<I : IteratorProtocol>(
_ input: inout I
) -> (UnicodeDecodingResult, Int) where I.Element == CodeUnit {
let result = decode(&input)
switch result {
case .scalarValue(let us):
return (result, UTF16.width(us))
case .emptyInput:
return (result, 0)
case .error:
return (result, 1)
}
}
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires two code units for its UTF-16
/// representation. The following code encodes a fermata in UTF-16:
///
/// var codeUnits: [UTF16.CodeUnit] = []
/// UTF16.encode("𝄐", into: { codeUnits.append($0) })
/// print(codeUnits)
/// // Prints "[55348, 56592]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
public static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
) {
var s = encode(input)!._storage
processCodeUnit(UInt16(extendingOrTruncating: s))
s &>>= 16
if _fastPath(s == 0) { return }
processCodeUnit(UInt16(extendingOrTruncating: s))
}
}
// @available(swift, obsoleted: 4.0, renamed: "Unicode.UTF16")
public typealias UTF16 = Unicode.UTF16
/// A codec for translating between Unicode scalar values and UTF-32 code
/// units.
extension Unicode.UTF32 : UnicodeCodec {
/// Creates an instance of the UTF-32 codec.
public init() { self = ._swift3Codec }
/// Starts or continues decoding a UTF-32 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-16 encoded bytes of a string
/// into an array of `Unicode.Scalar` instances. This is a demonstration
/// only---if you need the Unicode scalar representation of a string, use
/// its `unicodeScalars` view.
///
/// // UTF-32 representation of "✨Unicode✨"
/// let codeUnits: [UTF32.CodeUnit] =
/// [10024, 85, 110, 105, 99, 111, 100, 101, 10024]
///
/// var codeUnitIterator = codeUnits.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf32Decoder = UTF32()
/// Decode: while true {
/// switch utf32Decoder.decode(&codeUnitIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
return UTF32._decode(&input)
}
internal static func _decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
var parser = ForwardParser()
switch parser.parseScalar(from: &input) {
case .valid(let s): return .scalarValue(UTF32.decode(s))
case .error: return .error
case .emptyInput: return .emptyInput
}
}
/// Encodes a Unicode scalar as a UTF-32 code unit by calling the given
/// closure.
///
/// For example, like every Unicode scalar, the musical fermata symbol ("𝄐")
/// can be represented in UTF-32 as a single code unit. The following code
/// encodes a fermata in UTF-32:
///
/// var codeUnit: UTF32.CodeUnit = 0
/// UTF32.encode("𝄐", into: { codeUnit = $0 })
/// print(codeUnit)
/// // Prints "119056"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
public static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
) {
processCodeUnit(UInt32(input))
}
}
// @available(swift, obsoleted: 4.0, renamed: "Unicode.UTF32")
public typealias UTF32 = Unicode.UTF32
/// Translates the given input from one Unicode encoding to another by calling
/// the given closure.
///
/// The following example transcodes the UTF-8 representation of the string
/// `"Fermata 𝄐"` into UTF-32.
///
/// let fermata = "Fermata 𝄐"
/// let bytes = fermata.utf8
/// print(Array(bytes))
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 240, 157, 132, 144]"
///
/// var codeUnits: [UTF32.CodeUnit] = []
/// let sink = { codeUnits.append($0) }
/// transcode(bytes.makeIterator(), from: UTF8.self, to: UTF32.self,
/// stoppingOnError: false, into: sink)
/// print(codeUnits)
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 119056]"
///
/// The `sink` closure is called with each resulting UTF-32 code unit as the
/// function iterates over its input.
///
/// - Parameters:
/// - input: An iterator of code units to be translated, encoded as
/// `inputEncoding`. If `stopOnError` is `false`, the entire iterator will
/// be exhausted. Otherwise, iteration will stop if an encoding error is
/// detected.
/// - inputEncoding: The Unicode encoding of `input`.
/// - outputEncoding: The destination Unicode encoding.
/// - stopOnError: Pass `true` to stop translation when an encoding error is
/// detected in `input`. Otherwise, a Unicode replacement character
/// (`"\u{FFFD}"`) is inserted for each detected error.
/// - processCodeUnit: A closure that processes one `outputEncoding` code
/// unit at a time.
/// - Returns: `true` if the translation detected encoding errors in `input`;
/// otherwise, `false`.
@inline(__always)
public func transcode<
Input : IteratorProtocol,
InputEncoding : Unicode.Encoding,
OutputEncoding : Unicode.Encoding
>(
_ input: Input,
from inputEncoding: InputEncoding.Type,
to outputEncoding: OutputEncoding.Type,
stoppingOnError stopOnError: Bool,
into processCodeUnit: (OutputEncoding.CodeUnit) -> Void
) -> Bool
where InputEncoding.CodeUnit == Input.Element {
var input = input
// NB. It is not possible to optimize this routine to a memcpy if
// InputEncoding == OutputEncoding. The reason is that memcpy will not
// substitute U+FFFD replacement characters for ill-formed sequences.
var p = InputEncoding.ForwardParser()
var hadError = false
loop:
while true {
switch p.parseScalar(from: &input) {
case .valid(let s):
let t = OutputEncoding.transcode(s, from: inputEncoding)
guard _fastPath(t != nil), let s = t else { break }
s.forEach(processCodeUnit)
continue loop
case .emptyInput:
return hadError
case .error:
if _slowPath(stopOnError) { return true }
hadError = true
}
OutputEncoding.encodedReplacementCharacter.forEach(processCodeUnit)
}
}
/// Transcode UTF-16 to UTF-8, replacing ill-formed sequences with U+FFFD.
///
/// Returns the index of the first unhandled code unit and the UTF-8 data
/// that was encoded.
internal func _transcodeSomeUTF16AsUTF8<Input : Collection>(
_ input: Input, _ startIndex: Input.Index
) -> (Input.Index, _StringCore._UTF8Chunk)
where Input.Element == UInt16 {
typealias _UTF8Chunk = _StringCore._UTF8Chunk
let endIndex = input.endIndex
let utf8Max = MemoryLayout<_UTF8Chunk>.size
var result: _UTF8Chunk = 0
var utf8Count = 0
var nextIndex = startIndex
while nextIndex != input.endIndex && utf8Count != utf8Max {
let u = UInt(input[nextIndex])
let shift = _UTF8Chunk(utf8Count * 8)
var utf16Length: Input.IndexDistance = 1
if _fastPath(u <= 0x7f) {
result |= _UTF8Chunk(u) &<< shift
utf8Count += 1
} else {
var scalarUtf8Length: Int
var r: UInt
if _fastPath((u &>> 11) != 0b1101_1) {
// Neither high-surrogate, nor low-surrogate -- well-formed sequence
// of 1 code unit, decoding is trivial.
if u < 0x800 {
r = 0b10__00_0000__110__0_0000
r |= u &>> 6
r |= (u & 0b11_1111) &<< 8
scalarUtf8Length = 2
}
else {
r = 0b10__00_0000__10__00_0000__1110__0000
r |= u &>> 12
r |= ((u &>> 6) & 0b11_1111) &<< 8
r |= (u & 0b11_1111) &<< 16
scalarUtf8Length = 3
}
} else {
let unit0 = u
if _slowPath((unit0 &>> 10) == 0b1101_11) {
// `unit0` is a low-surrogate. We have an ill-formed sequence.
// Replace it with U+FFFD.
r = 0xbdbfef
scalarUtf8Length = 3
} else if _slowPath(input.index(nextIndex, offsetBy: 1) == endIndex) {
// We have seen a high-surrogate and EOF, so we have an ill-formed
// sequence. Replace it with U+FFFD.
r = 0xbdbfef
scalarUtf8Length = 3
} else {
let unit1 = UInt(input[input.index(nextIndex, offsetBy: 1)])
if _fastPath((unit1 &>> 10) == 0b1101_11) {
// `unit1` is a low-surrogate. We have a well-formed surrogate
// pair.
let v = 0x10000 + (((unit0 & 0x03ff) &<< 10) | (unit1 & 0x03ff))
r = 0b10__00_0000__10__00_0000__10__00_0000__1111_0__000
r |= v &>> 18
r |= ((v &>> 12) & 0b11_1111) &<< 8
r |= ((v &>> 6) & 0b11_1111) &<< 16
r |= (v & 0b11_1111) &<< 24
scalarUtf8Length = 4
utf16Length = 2
} else {
// Otherwise, we have an ill-formed sequence. Replace it with
// U+FFFD.
r = 0xbdbfef
scalarUtf8Length = 3
}
}
}
// Don't overrun the buffer
if utf8Count + scalarUtf8Length > utf8Max {
break
}
result |= numericCast(r) &<< shift
utf8Count += scalarUtf8Length
}
nextIndex = input.index(nextIndex, offsetBy: utf16Length)
}
// FIXME: Annoying check, courtesy of <rdar://problem/16740169>
if utf8Count < MemoryLayout.size(ofValue: result) {
result |= ~0 &<< numericCast(utf8Count * 8)
}
return (nextIndex, result)
}
/// Instances of conforming types are used in internal `String`
/// representation.
public // @testable
protocol _StringElement {
static func _toUTF16CodeUnit(_: Self) -> UTF16.CodeUnit
static func _fromUTF16CodeUnit(_ utf16: UTF16.CodeUnit) -> Self
}
extension UTF16.CodeUnit : _StringElement {
public // @testable
static func _toUTF16CodeUnit(_ x: UTF16.CodeUnit) -> UTF16.CodeUnit {
return x
}
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF16.CodeUnit {
return utf16
}
}
extension UTF8.CodeUnit : _StringElement {
public // @testable
static func _toUTF16CodeUnit(_ x: UTF8.CodeUnit) -> UTF16.CodeUnit {
_sanityCheck(x <= 0x7f, "should only be doing this with ASCII")
return UTF16.CodeUnit(extendingOrTruncating: x)
}
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF8.CodeUnit {
_sanityCheck(utf16 <= 0x7f, "should only be doing this with ASCII")
return UTF8.CodeUnit(extendingOrTruncating: utf16)
}
}
extension UTF16 {
/// Returns the number of code units required to encode the given Unicode
/// scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let anA: Unicode.Scalar = "A"
/// print(anA.value)
/// // Prints "65"
/// print(UTF16.width(anA))
/// // Prints "1"
///
/// let anApple: Unicode.Scalar = "🍎"
/// print(anApple.value)
/// // Prints "127822"
/// print(UTF16.width(anApple))
/// // Prints "2"
///
/// - Parameter x: A Unicode scalar value.
/// - Returns: The width of `x` when encoded in UTF-16, either `1` or `2`.
public static func width(_ x: Unicode.Scalar) -> Int {
return x.value <= 0xFFFF ? 1 : 2
}
/// Returns the high-surrogate code unit of the surrogate pair representing
/// the specified Unicode scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let apple: Unicode.Scalar = "🍎"
/// print(UTF16.leadSurrogate(apple)
/// // Prints "55356"
///
/// - Parameter x: A Unicode scalar value. `x` must be represented by a
/// surrogate pair when encoded in UTF-16. To check whether `x` is
/// represented by a surrogate pair, use `UTF16.width(x) == 2`.
/// - Returns: The leading surrogate code unit of `x` when encoded in UTF-16.
public static func leadSurrogate(_ x: Unicode.Scalar) -> UTF16.CodeUnit {
_precondition(width(x) == 2)
return 0xD800 + UTF16.CodeUnit(extendingOrTruncating:
(x.value - 0x1_0000) &>> (10 as UInt32))
}
/// Returns the low-surrogate code unit of the surrogate pair representing
/// the specified Unicode scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let apple: Unicode.Scalar = "🍎"
/// print(UTF16.trailSurrogate(apple)
/// // Prints "57166"
///
/// - Parameter x: A Unicode scalar value. `x` must be represented by a
/// surrogate pair when encoded in UTF-16. To check whether `x` is
/// represented by a surrogate pair, use `UTF16.width(x) == 2`.
/// - Returns: The trailing surrogate code unit of `x` when encoded in UTF-16.
public static func trailSurrogate(_ x: Unicode.Scalar) -> UTF16.CodeUnit {
_precondition(width(x) == 2)
return 0xDC00 + UTF16.CodeUnit(extendingOrTruncating:
(x.value - 0x1_0000) & (((1 as UInt32) &<< 10) - 1))
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// high-surrogate code unit.
///
/// Here's an example of checking whether each code unit in a string's
/// `utf16` view is a lead surrogate. The `apple` string contains a single
/// emoji character made up of a surrogate pair when encoded in UTF-16.
///
/// let apple = "🍎"
/// for unit in apple.utf16 {
/// print(UTF16.isLeadSurrogate(unit))
/// }
/// // Prints "true"
/// // Prints "false"
///
/// This method does not validate the encoding of a UTF-16 sequence beyond
/// the specified code unit. Specifically, it does not validate that a
/// low-surrogate code unit follows `x`.
///
/// - Parameter x: A UTF-16 code unit.
/// - Returns: `true` if `x` is a high-surrogate code unit; otherwise,
/// `false`.
public static func isLeadSurrogate(_ x: CodeUnit) -> Bool {
return 0xD800...0xDBFF ~= x
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// low-surrogate code unit.
///
/// Here's an example of checking whether each code unit in a string's
/// `utf16` view is a trailing surrogate. The `apple` string contains a
/// single emoji character made up of a surrogate pair when encoded in
/// UTF-16.
///
/// let apple = "🍎"
/// for unit in apple.utf16 {
/// print(UTF16.isTrailSurrogate(unit))
/// }
/// // Prints "false"
/// // Prints "true"
///
/// This method does not validate the encoding of a UTF-16 sequence beyond
/// the specified code unit. Specifically, it does not validate that a
/// high-surrogate code unit precedes `x`.
///
/// - Parameter x: A UTF-16 code unit.
/// - Returns: `true` if `x` is a low-surrogate code unit; otherwise,
/// `false`.
public static func isTrailSurrogate(_ x: CodeUnit) -> Bool {
return 0xDC00...0xDFFF ~= x
}
public // @testable
static func _copy<T : _StringElement, U : _StringElement>(
source: UnsafeMutablePointer<T>,
destination: UnsafeMutablePointer<U>,
count: Int
) {
if MemoryLayout<T>.stride == MemoryLayout<U>.stride {
_memcpy(
dest: UnsafeMutablePointer(destination),
src: UnsafeMutablePointer(source),
size: UInt(count) * UInt(MemoryLayout<U>.stride))
}
else {
for i in 0..<count {
let u16 = T._toUTF16CodeUnit((source + i).pointee)
(destination + i).pointee = U._fromUTF16CodeUnit(u16)
}
}
}
/// Returns the number of UTF-16 code units required for the given code unit
/// sequence when transcoded to UTF-16, and a Boolean value indicating
/// whether the sequence was found to contain only ASCII characters.
///
/// The following example finds the length of the UTF-16 encoding of the
/// string `"Fermata 𝄐"`, starting with its UTF-8 representation.
///
/// let fermata = "Fermata 𝄐"
/// let bytes = fermata.utf8
/// print(Array(bytes))
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 240, 157, 132, 144]"
///
/// let result = transcodedLength(of: bytes.makeIterator(),
/// decodedAs: UTF8.self,
/// repairingIllFormedSequences: false)
/// print(result)
/// // Prints "Optional((10, false))"
///
/// - Parameters:
/// - input: An iterator of code units to be translated, encoded as
/// `sourceEncoding`. If `repairingIllFormedSequences` is `true`, the
/// entire iterator will be exhausted. Otherwise, iteration will stop if
/// an ill-formed sequence is detected.
/// - sourceEncoding: The Unicode encoding of `input`.
/// - repairingIllFormedSequences: Pass `true` to measure the length of
/// `input` even when `input` contains ill-formed sequences. Each
/// ill-formed sequence is replaced with a Unicode replacement character
/// (`"\u{FFFD}"`) and is measured as such. Pass `false` to immediately
/// stop measuring `input` when an ill-formed sequence is encountered.
/// - Returns: A tuple containing the number of UTF-16 code units required to
/// encode `input` and a Boolean value that indicates whether the `input`
/// contained only ASCII characters. If `repairingIllFormedSequences` is
/// `false` and an ill-formed sequence is detected, this method returns
/// `nil`.
public static func transcodedLength<
Input : IteratorProtocol,
Encoding : Unicode.Encoding
>(
of input: Input,
decodedAs sourceEncoding: Encoding.Type,
repairingIllFormedSequences: Bool
) -> (count: Int, isASCII: Bool)?
where Encoding.CodeUnit == Input.Element {
var utf16Count = 0
var i = input
var d = Encoding.ForwardParser()
// Fast path for ASCII in a UTF8 buffer
if sourceEncoding == Unicode.UTF8.self {
var peek: Encoding.CodeUnit = 0
while let u = i.next() {
peek = u
guard _fastPath(peek < 0x80) else { break }
utf16Count = utf16Count + 1
}
if _fastPath(peek < 0x80) { return (utf16Count, true) }
var d1 = UTF8.ForwardParser()
d1._buffer.append(numericCast(peek))
d = _identityCast(d1, to: Encoding.ForwardParser.self)
}
var utf16BitUnion: CodeUnit = 0
while true {
let s = d.parseScalar(from: &i)
if _fastPath(s._valid != nil), let scalarContent = s._valid {
let utf16 = transcode(scalarContent, from: sourceEncoding)
._unsafelyUnwrappedUnchecked
utf16Count += utf16.count
for x in utf16 { utf16BitUnion |= x }
}
else if let _ = s._error {
guard _fastPath(repairingIllFormedSequences) else { return nil }
utf16Count += 1
utf16BitUnion |= 0xFFFD
}
else {
return (utf16Count, utf16BitUnion < 0x80)
}
}
}
}
// Unchecked init to avoid precondition branches in hot code paths where we
// already know the value is a valid unicode scalar.
extension Unicode.Scalar {
/// Create an instance with numeric value `value`, bypassing the regular
/// precondition checks for code point validity.
@_versioned
internal init(_unchecked value: UInt32) {
_sanityCheck(value < 0xD800 || value > 0xDFFF,
"high- and low-surrogate code points are not valid Unicode scalar values")
_sanityCheck(value <= 0x10FFFF, "value is outside of Unicode codespace")
self._value = value
}
}
extension UnicodeCodec {
public static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int {
var length = 0
while input[length] != 0 {
length += 1
}
return length
}
}
@available(*, unavailable, renamed: "UnicodeCodec")
public typealias UnicodeCodecType = UnicodeCodec
extension UnicodeCodec {
@available(*, unavailable, renamed: "encode(_:into:)")
public static func encode(
_ input: Unicode.Scalar,
output put: (CodeUnit) -> Void
) {
Builtin.unreachable()
}
}
@available(*, unavailable, message: "use 'transcode(_:from:to:stoppingOnError:into:)'")
public func transcode<Input, InputEncoding, OutputEncoding>(
_ inputEncoding: InputEncoding.Type, _ outputEncoding: OutputEncoding.Type,
_ input: Input, _ output: (OutputEncoding.CodeUnit) -> Void,
stopOnError: Bool
) -> Bool
where
Input : IteratorProtocol,
InputEncoding : UnicodeCodec,
OutputEncoding : UnicodeCodec,
InputEncoding.CodeUnit == Input.Element {
Builtin.unreachable()
}
extension UTF16 {
@available(*, unavailable, message: "use 'transcodedLength(of:decodedAs:repairingIllFormedSequences:)'")
public static func measure<Encoding, Input>(
_: Encoding.Type, input: Input, repairIllFormedSequences: Bool
) -> (Int, Bool)?
where
Encoding : UnicodeCodec,
Input : IteratorProtocol,
Encoding.CodeUnit == Input.Element {
Builtin.unreachable()
}
}
/// A namespace for Unicode utilities.
public enum Unicode {}
| apache-2.0 | 3b07069a2caf5529b238c630558f384a | 36.530572 | 106 | 0.633146 | 3.914421 | false | false | false | false |
natecook1000/swift | stdlib/public/core/BridgeObjectiveC.swift | 2 | 24034 | //===----------------------------------------------------------------------===//
//
// 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 Swift Array or Dictionary of types conforming to
/// `_ObjectiveCBridgeable` can be passed to Objective-C as an NSArray or
/// NSDictionary, respectively. The elements of the resulting NSArray
/// or NSDictionary will be the result of calling `_bridgeToObjectiveC`
/// on each element of the source container.
public protocol _ObjectiveCBridgeable {
associatedtype _ObjectiveCType : AnyObject
/// Convert `self` to Objective-C.
func _bridgeToObjectiveC() -> _ObjectiveCType
/// Bridge from an Objective-C object of the bridged class type to a
/// value of the Self type.
///
/// This bridging operation is used for forced downcasting (e.g.,
/// via as), and may defer complete checking until later. For
/// example, when bridging from `NSArray` to `Array<Element>`, we can defer
/// the checking for the individual elements of the array.
///
/// - parameter result: The location where the result is written. The optional
/// will always contain a value.
static func _forceBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout Self?
)
/// Try to bridge from an Objective-C object of the bridged class
/// type to a value of the Self type.
///
/// This conditional bridging operation is used for conditional
/// downcasting (e.g., via as?) and therefore must perform a
/// complete conversion to the value type; it cannot defer checking
/// to a later time.
///
/// - parameter result: The location where the result is written.
///
/// - Returns: `true` if bridging succeeded, `false` otherwise. This redundant
/// information is provided for the convenience of the runtime's `dynamic_cast`
/// implementation, so that it need not look into the optional representation
/// to determine success.
@discardableResult
static func _conditionallyBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout Self?
) -> Bool
/// Bridge from an Objective-C object of the bridged class type to a
/// value of the Self type.
///
/// This bridging operation is used for unconditional bridging when
/// interoperating with Objective-C code, either in the body of an
/// Objective-C thunk or when calling Objective-C code, and may
/// defer complete checking until later. For example, when bridging
/// from `NSArray` to `Array<Element>`, we can defer the checking
/// for the individual elements of the array.
///
/// \param source The Objective-C object from which we are
/// bridging. This optional value will only be `nil` in cases where
/// an Objective-C method has returned a `nil` despite being marked
/// as `_Nonnull`/`nonnull`. In most such cases, bridging will
/// generally force the value immediately. However, this gives
/// bridging the flexibility to substitute a default value to cope
/// with historical decisions, e.g., an existing Objective-C method
/// that returns `nil` to for "empty result" rather than (say) an
/// empty array. In such cases, when `nil` does occur, the
/// implementation of `Swift.Array`'s conformance to
/// `_ObjectiveCBridgeable` will produce an empty array rather than
/// dynamically failing.
static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-> Self
}
#if _runtime(_ObjC)
//===--- Bridging for metatypes -------------------------------------------===//
/// A stand-in for a value of metatype type.
///
/// The language and runtime do not yet support protocol conformances for
/// structural types like metatypes. However, we can use a struct that contains
/// a metatype, make it conform to _ObjectiveCBridgeable, and its witness table
/// will be ABI-compatible with one that directly provided conformance to the
/// metatype type itself.
@_fixed_layout
public struct _BridgeableMetatype: _ObjectiveCBridgeable {
@usableFromInline // FIXME(sil-serialize-all)
internal var value: AnyObject.Type
@inlinable // FIXME(sil-serialize-all)
internal init(value: AnyObject.Type) {
self.value = value
}
public typealias _ObjectiveCType = AnyObject
@inlinable // FIXME(sil-serialize-all)
public func _bridgeToObjectiveC() -> AnyObject {
return value
}
@inlinable // FIXME(sil-serialize-all)
public static func _forceBridgeFromObjectiveC(
_ source: AnyObject,
result: inout _BridgeableMetatype?
) {
result = _BridgeableMetatype(value: source as! AnyObject.Type)
}
@inlinable // FIXME(sil-serialize-all)
public static func _conditionallyBridgeFromObjectiveC(
_ source: AnyObject,
result: inout _BridgeableMetatype?
) -> Bool {
if let type = source as? AnyObject.Type {
result = _BridgeableMetatype(value: type)
return true
}
result = nil
return false
}
@inlinable // FIXME(sil-serialize-all)
public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?)
-> _BridgeableMetatype {
var result: _BridgeableMetatype?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
//===--- Bridging facilities written in Objective-C -----------------------===//
// Functions that must discover and possibly use an arbitrary type's
// conformance to a given protocol. See ../runtime/Metadata.cpp for
// implementations.
//===----------------------------------------------------------------------===//
/// Bridge an arbitrary value to an Objective-C object.
///
/// - If `T` is a class type, it is always bridged verbatim, the function
/// returns `x`;
///
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`,
/// returns the result of `x._bridgeToObjectiveC()`;
///
/// - otherwise, we use **boxing** to bring the value into Objective-C.
/// The value is wrapped in an instance of a private Objective-C class
/// that is `id`-compatible and dynamically castable back to the type of
/// the boxed value, but is otherwise opaque.
///
/// COMPILER_INTRINSIC
@inlinable // FIXME(sil-serialize-all)
public func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return unsafeBitCast(x, to: AnyObject.self)
}
return _bridgeAnythingNonVerbatimToObjectiveC(x)
}
@_silgen_name("")
public func _bridgeAnythingNonVerbatimToObjectiveC<T>(_ x: __owned T) -> AnyObject
/// Convert a purportedly-nonnull `id` value from Objective-C into an Any.
///
/// Since Objective-C APIs sometimes get their nullability annotations wrong,
/// this includes a failsafe against nil `AnyObject`s, wrapping them up as
/// a nil `AnyObject?`-inside-an-`Any`.
///
/// COMPILER_INTRINSIC
@inlinable // FIXME(sil-serialize-all)
public func _bridgeAnyObjectToAny(_ possiblyNullObject: AnyObject?) -> Any {
if let nonnullObject = possiblyNullObject {
return nonnullObject // AnyObject-in-Any
}
return possiblyNullObject as Any
}
/// Convert `x` from its Objective-C representation to its Swift
/// representation.
///
/// - If `T` is a class type:
/// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged
/// verbatim, the function returns `x`;
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`:
/// + if the dynamic type of `x` is not `T._ObjectiveCType`
/// or a subclass of it, trap;
/// + otherwise, returns the result of `T._forceBridgeFromObjectiveC(x)`;
/// - otherwise, trap.
@inlinable // FIXME(sil-serialize-all)
public func _forceBridgeFromObjectiveC<T>(_ x: AnyObject, _: T.Type) -> T {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return x as! T
}
var result: T?
_bridgeNonVerbatimFromObjectiveC(x, T.self, &result)
return result!
}
/// Convert `x` from its Objective-C representation to its Swift
/// representation.
/// COMPILER_INTRINSIC
@inlinable // FIXME(sil-serialize-all)
public func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable> (
_ x: T._ObjectiveCType,
_: T.Type
) -> T {
var result: T?
T._forceBridgeFromObjectiveC(x, result: &result)
return result!
}
/// Attempt to convert `x` from its Objective-C representation to its Swift
/// representation.
///
/// - If `T` is a class type:
/// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged
/// verbatim, the function returns `x`;
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`:
/// + otherwise, if the dynamic type of `x` is not `T._ObjectiveCType`
/// or a subclass of it, the result is empty;
/// + otherwise, returns the result of
/// `T._conditionallyBridgeFromObjectiveC(x)`;
/// - otherwise, the result is empty.
@inlinable // FIXME(sil-serialize-all)
public func _conditionallyBridgeFromObjectiveC<T>(
_ x: AnyObject,
_: T.Type
) -> T? {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return x as? T
}
var result: T?
_ = _bridgeNonVerbatimFromObjectiveCConditional(x, T.self, &result)
return result
}
/// Attempt to convert `x` from its Objective-C representation to its Swift
/// representation.
/// COMPILER_INTRINSIC
@inlinable // FIXME(sil-serialize-all)
public func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>(
_ x: T._ObjectiveCType,
_: T.Type
) -> T? {
var result: T?
T._conditionallyBridgeFromObjectiveC (x, result: &result)
return result
}
@_silgen_name("")
public func _bridgeNonVerbatimFromObjectiveC<T>(
_ x: AnyObject,
_ nativeType: T.Type,
_ result: inout T?
)
/// Helper stub to upcast to Any and store the result to an inout Any?
/// on the C++ runtime's behalf.
@_silgen_name("_bridgeNonVerbatimFromObjectiveCToAny")
internal func _bridgeNonVerbatimFromObjectiveCToAny(
_ x: AnyObject,
_ result: inout Any?
) {
result = x as Any
}
/// Helper stub to upcast to Optional on the C++ runtime's behalf.
@_silgen_name("_bridgeNonVerbatimBoxedValue")
internal func _bridgeNonVerbatimBoxedValue<NativeType>(
_ x: UnsafePointer<NativeType>,
_ result: inout NativeType?
) {
result = x.pointee
}
/// Runtime optional to conditionally perform a bridge from an object to a value
/// type.
///
/// - parameter result: Will be set to the resulting value if bridging succeeds, and
/// unchanged otherwise.
///
/// - Returns: `true` to indicate success, `false` to indicate failure.
@_silgen_name("")
public func _bridgeNonVerbatimFromObjectiveCConditional<T>(
_ x: AnyObject,
_ nativeType: T.Type,
_ result: inout T?
) -> Bool
/// Determines if values of a given type can be converted to an Objective-C
/// representation.
///
/// - If `T` is a class type, returns `true`;
/// - otherwise, returns whether `T` conforms to `_ObjectiveCBridgeable`.
@inlinable // FIXME(sil-serialize-all)
public func _isBridgedToObjectiveC<T>(_: T.Type) -> Bool {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return true
}
return _isBridgedNonVerbatimToObjectiveC(T.self)
}
@_silgen_name("")
public func _isBridgedNonVerbatimToObjectiveC<T>(_: T.Type) -> Bool
/// A type that's bridged "verbatim" does not conform to
/// `_ObjectiveCBridgeable`, and can have its bits reinterpreted as an
/// `AnyObject`. When this function returns true, the storage of an
/// `Array<T>` can be `unsafeBitCast` as an array of `AnyObject`.
@inlinable // FIXME(sil-serialize-all)
public func _isBridgedVerbatimToObjectiveC<T>(_: T.Type) -> Bool {
return _isClassOrObjCExistential(T.self)
}
/// Retrieve the Objective-C type to which the given type is bridged.
@inlinable // FIXME(sil-serialize-all)
public func _getBridgedObjectiveCType<T>(_: T.Type) -> Any.Type? {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return T.self
}
return _getBridgedNonVerbatimObjectiveCType(T.self)
}
@_silgen_name("")
public func _getBridgedNonVerbatimObjectiveCType<T>(_: T.Type) -> Any.Type?
// -- Pointer argument bridging
@usableFromInline @_transparent
internal var _nilNativeObject: AnyObject? {
return nil
}
/// A mutable pointer-to-ObjC-pointer argument.
///
/// This type has implicit conversions to allow passing any of the following
/// to a C or ObjC API:
///
/// - `nil`, which gets passed as a null pointer,
/// - an inout argument of the referenced type, which gets passed as a pointer
/// to a writeback temporary with autoreleasing ownership semantics,
/// - an `UnsafeMutablePointer<Pointee>`, which is passed as-is.
///
/// Passing pointers to mutable arrays of ObjC class pointers is not
/// directly supported. Unlike `UnsafeMutablePointer<Pointee>`,
/// `AutoreleasingUnsafeMutablePointer<Pointee>` must reference storage that
/// does not own a reference count to the referenced
/// value. UnsafeMutablePointer's operations, by contrast, assume that
/// the referenced storage owns values loaded from or stored to it.
///
/// This type does not carry an owner pointer unlike the other C*Pointer types
/// because it only needs to reference the results of inout conversions, which
/// already have writeback-scoped lifetime.
@_fixed_layout
public struct AutoreleasingUnsafeMutablePointer<Pointee /* TODO : class */>
: _Pointer {
public let _rawValue: Builtin.RawPointer
@_transparent
public // COMPILER_INTRINSIC
init(_ _rawValue: Builtin.RawPointer) {
self._rawValue = _rawValue
}
/// Access the `Pointee` instance referenced by `self`.
///
/// - Precondition: the pointee has been initialized with an instance of type
/// `Pointee`.
@inlinable
public var pointee: Pointee {
/// Retrieve the value the pointer points to.
@_transparent get {
// We can do a strong load normally.
return UnsafePointer(self).pointee
}
/// Set the value the pointer points to, copying over the previous value.
///
/// AutoreleasingUnsafeMutablePointers are assumed to reference a
/// value with __autoreleasing ownership semantics, like 'NSFoo**'
/// in ARC. This autoreleases the argument before trivially
/// storing it to the referenced memory.
@_transparent nonmutating set {
// Autorelease the object reference.
typealias OptionalAnyObject = AnyObject?
let newAnyObject = unsafeBitCast(newValue, to: OptionalAnyObject.self)
Builtin.retain(newAnyObject)
Builtin.autorelease(newAnyObject)
// Trivially assign it as an OpaquePointer; the pointer references an
// autoreleasing slot, so retains/releases of the original value are
// unneeded.
typealias OptionalUnmanaged = Unmanaged<AnyObject>?
UnsafeMutablePointer<Pointee>(_rawValue).withMemoryRebound(
to: OptionalUnmanaged.self, capacity: 1) {
if let newAnyObject = newAnyObject {
$0.pointee = Unmanaged.passUnretained(newAnyObject)
}
else {
$0.pointee = nil
}
}
}
}
/// Access the `i`th element of the raw array pointed to by
/// `self`.
///
/// - Precondition: `self != nil`.
@inlinable // unsafe-performance
public subscript(i: Int) -> Pointee {
@_transparent
get {
// We can do a strong load normally.
return (UnsafePointer<Pointee>(self) + i).pointee
}
}
/// Explicit construction from a UnsafePointer.
///
/// This is inherently unsafe because UnsafePointers do not imply
/// mutability.
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@usableFromInline @_transparent
internal init<U>(_ from: UnsafePointer<U>) {
self._rawValue = from._rawValue
}
/// Explicit construction from a UnsafePointer.
///
/// Returns nil if `from` is nil.
///
/// This is inherently unsafe because UnsafePointers do not imply
/// mutability.
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@usableFromInline @_transparent
internal init?<U>(_ from: UnsafePointer<U>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
}
extension UnsafeMutableRawPointer {
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert.
@_transparent
public init<T>(_ other: AutoreleasingUnsafeMutablePointer<T>) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(_ other: AutoreleasingUnsafeMutablePointer<T>?) {
guard let unwrapped = other else { return nil }
self.init(unwrapped)
}
}
extension UnsafeRawPointer {
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert.
@_transparent
public init<T>(_ other: AutoreleasingUnsafeMutablePointer<T>) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(_ other: AutoreleasingUnsafeMutablePointer<T>?) {
guard let unwrapped = other else { return nil }
self.init(unwrapped)
}
}
internal struct _CocoaFastEnumerationStackBuf {
// Clang uses 16 pointers. So do we.
internal var _item0: UnsafeRawPointer?
internal var _item1: UnsafeRawPointer?
internal var _item2: UnsafeRawPointer?
internal var _item3: UnsafeRawPointer?
internal var _item4: UnsafeRawPointer?
internal var _item5: UnsafeRawPointer?
internal var _item6: UnsafeRawPointer?
internal var _item7: UnsafeRawPointer?
internal var _item8: UnsafeRawPointer?
internal var _item9: UnsafeRawPointer?
internal var _item10: UnsafeRawPointer?
internal var _item11: UnsafeRawPointer?
internal var _item12: UnsafeRawPointer?
internal var _item13: UnsafeRawPointer?
internal var _item14: UnsafeRawPointer?
internal var _item15: UnsafeRawPointer?
@_transparent
internal var count: Int {
return 16
}
internal init() {
_item0 = nil
_item1 = _item0
_item2 = _item0
_item3 = _item0
_item4 = _item0
_item5 = _item0
_item6 = _item0
_item7 = _item0
_item8 = _item0
_item9 = _item0
_item10 = _item0
_item11 = _item0
_item12 = _item0
_item13 = _item0
_item14 = _item0
_item15 = _item0
_sanityCheck(MemoryLayout.size(ofValue: self) >=
MemoryLayout<Optional<UnsafeRawPointer>>.size * count)
}
}
/// Get the ObjC type encoding for a type as a pointer to a C string.
///
/// This is used by the Foundation overlays. The compiler will error if the
/// passed-in type is generic or not representable in Objective-C
@_transparent
public func _getObjCTypeEncoding<T>(_ type: T.Type) -> UnsafePointer<Int8> {
// This must be `@_transparent` because `Builtin.getObjCTypeEncoding` is
// only supported by the compiler for concrete types that are representable
// in ObjC.
return UnsafePointer(Builtin.getObjCTypeEncoding(type))
}
#endif
//===--- Bridging without the ObjC runtime --------------------------------===//
#if !_runtime(_ObjC)
/// Convert `x` from its Objective-C representation to its Swift
/// representation.
/// COMPILER_INTRINSIC
@inlinable // FIXME(sil-serialize-all)
public func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable> (
_ x: T._ObjectiveCType,
_: T.Type
) -> T {
var result: T?
T._forceBridgeFromObjectiveC(x, result: &result)
return result!
}
/// Attempt to convert `x` from its Objective-C representation to its Swift
/// representation.
/// COMPILER_INTRINSIC
@inlinable // FIXME(sil-serialize-all)
public func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>(
_ x: T._ObjectiveCType,
_: T.Type
) -> T? {
var result: T?
T._conditionallyBridgeFromObjectiveC (x, result: &result)
return result
}
public // SPI(Foundation)
protocol _NSSwiftValue: class {
init(_ value: Any)
var value: Any { get }
static var null: AnyObject { get }
}
@usableFromInline
internal class _SwiftValue {
@usableFromInline
let value: Any
@usableFromInline
init(_ value: Any) {
self.value = value
}
@usableFromInline
static let null = _SwiftValue(Optional<Any>.none as Any)
}
// Internal stdlib SPI
@_silgen_name("swift_unboxFromSwiftValueWithType")
public func swift_unboxFromSwiftValueWithType<T>(
_ source: inout AnyObject,
_ result: UnsafeMutablePointer<T>
) -> Bool {
if source === _nullPlaceholder {
if let unpacked = Optional<Any>.none as? T {
result.initialize(to: unpacked)
return true
}
}
if let box = source as? _SwiftValue {
if let value = box.value as? T {
result.initialize(to: value)
return true
}
} else if let box = source as? _NSSwiftValue {
if let value = box.value as? T {
result.initialize(to: value)
return true
}
}
return false
}
// Internal stdlib SPI
@_silgen_name("swift_swiftValueConformsTo")
public func _swiftValueConformsTo<T>(_ type: T.Type) -> Bool {
if let foundationType = _foundationSwiftValueType {
return foundationType is T.Type
} else {
return _SwiftValue.self is T.Type
}
}
@_silgen_name("_swift_extractDynamicValue")
public func _extractDynamicValue<T>(_ value: T) -> AnyObject?
@_silgen_name("_swift_bridgeToObjectiveCUsingProtocolIfPossible")
public func _bridgeToObjectiveCUsingProtocolIfPossible<T>(_ value: T) -> AnyObject?
@usableFromInline
protocol _Unwrappable {
func unwrap() -> Any?
}
extension Optional: _Unwrappable {
func unwrap() -> Any? {
return self
}
}
private let _foundationSwiftValueType = _typeByName("Foundation._SwiftValue") as? _NSSwiftValue.Type
@usableFromInline
internal var _nullPlaceholder: AnyObject {
if let foundationType = _foundationSwiftValueType {
return foundationType.null
} else {
return _SwiftValue.null
}
}
@usableFromInline
func _makeSwiftValue(_ value: Any) -> AnyObject {
if let foundationType = _foundationSwiftValueType {
return foundationType.init(value)
} else {
return _SwiftValue(value)
}
}
/// Bridge an arbitrary value to an Objective-C object.
///
/// - If `T` is a class type, it is always bridged verbatim, the function
/// returns `x`;
///
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`,
/// returns the result of `x._bridgeToObjectiveC()`;
///
/// - otherwise, we use **boxing** to bring the value into Objective-C.
/// The value is wrapped in an instance of a private Objective-C class
/// that is `id`-compatible and dynamically castable back to the type of
/// the boxed value, but is otherwise opaque.
///
/// COMPILER_INTRINSIC
@inlinable // FIXME(sil-serialize-all)
public func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject {
var done = false
var result: AnyObject!
let source: Any = x
if let dynamicSource = _extractDynamicValue(x) {
result = dynamicSource as AnyObject
done = true
}
if !done, let wrapper = source as? _Unwrappable {
if let value = wrapper.unwrap() {
result = value as AnyObject
} else {
result = _nullPlaceholder
}
done = true
}
if !done {
if type(of: source) as? AnyClass != nil {
result = unsafeBitCast(x, to: AnyObject.self)
} else if let object = _bridgeToObjectiveCUsingProtocolIfPossible(source) {
result = object
} else {
result = _makeSwiftValue(source)
}
}
return result
}
#endif // !_runtime(_ObjC)
| apache-2.0 | 9172bd1933b4eed02dac9be5fb92e820 | 31.347241 | 100 | 0.687568 | 4.229849 | false | false | false | false |
pawrsccouk/Stereogram | Stereogram-iPad/Result.swift | 1 | 7081 | //
// Result.swift
// PicSplitter
//
// Created by Patrick Wallace on 31/12/2014.
// Copyright (c) 2014 Patrick Wallace. All rights reserved.
//
import Foundation
// This is a workaround-wrapper class for a bug in the Swift compiler. DO NOT USE THIS CLASS!
// Swift needs to know the size of an enum at compile time, so instead of <T> which can be any value
// we use pointer-to-wrapper-class<T>, which is always the size of a pointer.
public class FailableValueWrapper<T> {
public let value: T
public init(_ value: T) { self.value = value }
}
// Return status from a function. Returns Success() if OK, Error(NSError) if not.
public enum Result {
case Success()
case Error(NSError) // If the error is nil, we will substitute a default NSError object.
// True if the result was a success, false if it failed.
var success: Bool {
switch self {
case .Success: return true
case .Error: return false
}
}
// Returns the error if we were in an error state, or nil otherwise.
var error: NSError? {
switch self {
case .Error(let e): return e
default: return nil
}
}
// Performs the function fn on this object, if it has a valid value.
// If not, just propagates the error.
func map<U>(fn: Void -> ResultOf<U>) -> ResultOf<U> {
switch self {
case .Success(): return fn()
case .Error(let e): return .Error(e)
}
}
// As map(), but returns a value with no data, i.e. only success and fail options.
func map0(fn: Void -> Result) -> Result {
switch self {
case .Success(let w): return fn()
case .Error(let e): return .Error(e)
}
}
// If an error was found, run the given handler, passing the error in.
// Useful when we only want to handle errors, but no need to handle the success case.
func onError(handler: (NSError) -> Void ) {
switch self {
case .Error(var error):
handler(error)
case .Success():
break
}
}
}
// Return value from functions. Returns Success(value) if OK, Error(NSError) if not.
public enum ResultOf<T> {
case Success(FailableValueWrapper<T>)
case Error(NSError) // We will substitute a default error if the one provided is nil.
// Initialise with the value directly, to hide the use of the wrapper.
init(_ value: T) {
self = .Success(FailableValueWrapper(value))
}
init(_ error: NSError) {
self = .Error(error)
}
// True if the result was a success, false if it failed.
var success: Bool {
switch self {
case .Success: return true
case .Error: return false
}
}
// Returns the error if we were in an error state, or nil otherwise.
var error: NSError? {
switch self {
case .Error(let e): return e
default: return nil
}
}
// Performs the function fn on this object, if it has a valid value.
// If not, just propagates the error.
func map<U>(fn: T -> ResultOf<U>) -> ResultOf<U> {
switch self {
case .Success(let w): return fn(w.value)
case .Error(let e): return .Error(e)
}
}
// As map(), but returns a value with no data, i.e. only success and fail options.
func map0(fn: T -> Result) -> Result {
switch self {
case .Success(let w): return fn(w.value)
case .Error(let e): return .Error(e)
}
}
// Boolean result: If successful it returns .Success(),
// if it failed, return the error code.
// Useful if we care that it succeeded, but don't need the returned value.
public var result: Result {
switch self {
case .Success(_): return .Success()
case .Error(let e): return .Error(e)
}
}
}
/// Shortcut function to return a given error in the form of a ResultOf type.
func returnError<T>(location: String, operation: String) -> ResultOf<T> {
let err = NSError.unknownErrorWithLocation(location, target: operation)
return .Error(err)
}
/// Shortcut function to return a given error in the form of a Result type.
func returnError(location: String, operation: String) -> Result {
let err = NSError.unknownErrorWithLocation(location, target: operation)
return .Error(err)
}
// Takes a collection of objects and a function to call on each one of them.
// Returns success only if all the function calls returned success.
// If any of them returns Error, then return immediately with that error.
public func eachOf<T: SequenceType>(seq: T, fnc: (Int, T.Generator.Element) -> Result) -> Result {
for (i, s) in enumerate(seq) {
switch fnc(i, s) {
case .Error(let e): return .Error(e)
default: break // do nothing. Continue to next iteration of the sequence.
}
}
return .Success() // Only return success if all of the f(s) performed successfully.
}
// Wrap any function that doesn't return anything, so it returns Success().
public func alwaysOk<T>(fnc: (t: T) -> Void) -> ((t: T) -> Result) {
return { fnc(t: $0)
return .Success()
}
}
/// Similar to the map() methods on each result object, but more readable for outside observers.
///
/// :param: functions Array of functions which all take a type and return a ResultOf the same type.
/// :returns: The error if any failed, success and the final value if any succeeded.
public func map<T>(functions: [(T)->ResultOf<T>], first: T) -> ResultOf<T> {
var res = first
for f: (T)->ResultOf in functions {
switch f(res) {
case .Error(let e):
return .Error(e)
case .Success(let v):
res = v.value
}
}
return ResultOf(res)
}
/// Given two values of type ResultOf<T>, if both are successful, return the results as a tuple.
/// If either fails, then return the error.
public func and<T,U>(r1: ResultOf<T>, r2: ResultOf<U>) -> ResultOf<(T,U)> {
typealias TupleT = (T, U)
switch r1 {
case .Success(let a1):
switch r2 {
case .Success(let a2):
let tuple = (a1.value, a2.value)
let wrapper = FailableValueWrapper<TupleT>(tuple)
return .Success(wrapper)
case .Error(let e): return .Error(e)
}
case .Error(let e): return .Error(e)
}
}
/// Return success only if r1 and r2 both succeed. Otherwise return the first value that failed.
///
/// Note: This doesn't short-circuit. Both r1 and r2 are evaluated.
public func and(r1: Result, r2: Result) -> Result {
return and([r1, r2])
}
/// Returns the first error it finds in the array, or Success if none are found.
///
/// :param: result An array of Result objects to test.
/// :returns: .Error(NSError) if any of the results are errors, otherwise Success.
///
/// Note: This doesn't short-circuit. All expressions in result are evaluated.
public func and(results: [Result]) -> Result {
if let firstError = results.filter({ $0.success }).first {
return firstError
}
return .Success()
}
| mit | a435037bd5e23d1f8bd9fa58b3a79717 | 31.631336 | 100 | 0.626465 | 3.79882 | false | false | false | false |
CD1212/Doughnut | Pods/GRDB.swift/GRDB/Core/DatabaseValueConvertible.swift | 1 | 20019 | #if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
// MARK: - DatabaseValueConvertible
/// Types that adopt DatabaseValueConvertible can be initialized from
/// database values.
///
/// The protocol comes with built-in methods that allow to fetch cursors,
/// arrays, or single values:
///
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
/// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
/// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
/// try String.fetchAll(statement, arguments:...) // [String]
/// try String.fetchOne(statement, arguments:...) // String?
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
public protocol DatabaseValueConvertible : SQLExpressible {
/// Returns a value that can be stored in the database.
var databaseValue: DatabaseValue { get }
/// Returns a value initialized from *dbValue*, if possible.
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
}
extension DatabaseValueConvertible {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public var sqlExpression: SQLExpression {
return databaseValue
}
}
/// A cursor of database values extracted from a single column.
/// For example:
///
/// try dbQueue.inDatabase { db in
/// let urls: DatabaseValueCursor<URL> = try URL.fetchCursor(db, "SELECT url FROM links")
/// while let url = urls.next() { // URL
/// print(url)
/// }
/// }
public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
private let statement: SelectStatement
private let sqliteStatement: SQLiteStatement
private let columnIndex: Int32
private var done = false
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
self.statement = statement
// We'll read from leftmost column at index 0, unless adapter mangles columns
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
self.sqliteStatement = statement.sqliteStatement
statement.cursorReset(arguments: arguments)
}
public func next() throws -> Value? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
case SQLITE_DONE:
done = true
return nil
case SQLITE_ROW:
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex)
return dbValue.losslessConvert() as Value
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
}
}
}
/// A cursor of optional database values extracted from a single column.
/// For example:
///
/// try dbQueue.inDatabase { db in
/// let urls: NullableDatabaseValueCursor<URL> = try Optional<URL>.fetchCursor(db, "SELECT url FROM links")
/// while let url = urls.next() { // URL?
/// print(url)
/// }
/// }
public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
private let statement: SelectStatement
private let sqliteStatement: SQLiteStatement
private let columnIndex: Int32
private var done = false
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
self.statement = statement
// We'll read from leftmost column at index 0, unless adapter mangles columns
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
self.sqliteStatement = statement.sqliteStatement
statement.cursorReset(arguments: arguments)
}
public func next() throws -> Value?? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
case SQLITE_DONE:
done = true
return nil
case SQLITE_ROW:
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex)
return dbValue.losslessConvert() as Value?
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
}
}
}
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
/// cursors, arrays, or single values:
///
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
/// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
/// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
/// try String.fetchAll(statement, arguments:...) // [String]
/// try String.fetchOne(statement, arguments:...) // String
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
extension DatabaseValueConvertible {
// MARK: Fetching From SelectStatement
/// Returns a cursor over values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let names = try String.fetchCursor(statement) // Cursor of String
/// while let name = try names.next() { // String
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
return try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
}
/// Returns an array of values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let names = try String.fetchAll(statement) // [String]
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
/// Returns a single value fetched from a prepared statement.
///
/// The result is nil if the query returns no row, or if no value can be
/// extracted from the first row.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let name = try String.fetchOne(statement) // String?
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
// fetchOne returns nil if there is no row, or if there is a row with a null value
let cursor = try NullableDatabaseValueCursor<Self>(statement: statement, arguments: arguments, adapter: adapter)
return try cursor.next() ?? nil
}
}
extension DatabaseValueConvertible {
// MARK: Fetching From Request
/// Returns a cursor over values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn)
/// let names = try String.fetchCursor(db, request) // Cursor of String
/// for let name = try names.next() { // String
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - request: A fetch request.
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseValueCursor<Self> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn)
/// let names = try String.fetchAll(db, request) // [String]
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] {
let (statement, adapter) = try request.prepare(db)
return try fetchAll(statement, adapter: adapter)
}
/// Returns a single value fetched from a fetch request.
///
/// The result is nil if the query returns no row, or if no value can be
/// extracted from the first row.
///
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn)
/// let name = try String.fetchOne(db, request) // String?
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: Request) throws -> Self? {
let (statement, adapter) = try request.prepare(db)
return try fetchOne(statement, adapter: adapter)
}
}
extension DatabaseValueConvertible {
// MARK: Fetching From SQL
/// Returns a cursor over values fetched from an SQL query.
///
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // Cursor of String
/// while let name = try name.next() { // String
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of values fetched from an SQL query.
///
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String]
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
/// Returns a single value fetched from an SQL query.
///
/// The result is nil if the query returns no row, or if no value can be
/// extracted from the first row.
///
/// let name = try String.fetchOne(db, "SELECT name FROM ...") // String?
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
}
/// Swift's Optional comes with built-in methods that allow to fetch cursors
/// and arrays of optional DatabaseValueConvertible:
///
/// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String?
/// try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
extension Optional where Wrapped: DatabaseValueConvertible {
// MARK: Fetching From SelectStatement
/// Returns a cursor over optional values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
return try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
}
/// Returns an array of optional values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let names = try Optional<String>.fetchAll(statement) // [String?]
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
}
extension Optional where Wrapped: DatabaseValueConvertible {
// MARK: Fetching From Request
/// Returns a cursor over optional values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn)
/// let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - requet: A fetch request.
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: Request) throws -> NullableDatabaseValueCursor<Wrapped> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of optional values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn)
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Wrapped?] {
let (statement, adapter) = try request.prepare(db)
return try fetchAll(statement, adapter: adapter)
}
}
extension Optional where Wrapped: DatabaseValueConvertible {
// MARK: Fetching From SQL
/// Returns a cursor over optional values fetched from an SQL query.
///
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of optional values fetched from an SQL query.
///
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String?]
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - parameter arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
}
| gpl-3.0 | fb09e619ade1b4d8cef86f0ac57fda37 | 43.388027 | 180 | 0.638443 | 4.704818 | false | false | false | false |
qiuncheng/study-for-swift | YLLoginManager/YLLoginManager/YLShareManager.swift | 1 | 5185 | enum YLSharePlatform {
case qq
case qqZone
case wechatTimeline
case wechatSesssion
}
class YLShareMessage {
var title: String?
var content: String?
var url: String?
}
class YLWechatMessage: YLShareMessage {
var thumbImage: UIImage?
var thumbData: Data?
}
class YLQQMessage: YLShareMessage {
var previewImageData: Data?
var previewImageURL: String?
}
typealias ShareSuccess = () -> Void
typealias ShareFail = (Error?) -> Void
class YLShareManager: NSObject {
// MARK: - Public property
static let manager = YLShareManager()
var success: ShareSuccess?
var fail: ShareFail?
// MARK: - Private property
fileprivate override init() {
super.init()
}
func share(withPlatform platform: YLSharePlatform, message: YLShareMessage, success: ShareSuccess?, fail: ShareFail?) {
self.success = success
self.fail = fail
switch platform {
case .wechatSesssion:
let req = wechatUrlMessage(message: message)
req.scene = Int32(WXSceneSession.rawValue)
WXApi.send(req)
case .wechatTimeline:
let req = wechatUrlMessage(message: message)
req.scene = Int32(WXSceneTimeline.rawValue)
WXApi.send(req)
case .qq:
let req = qqUrlMessage(message: message)
let statusCode = QQApiInterface.send(req)
handleQQStatusCode(statusCode: statusCode)
case .qqZone:
let req = qqZoneUrlMessage(message: message)
let statusCode = QQApiInterface.send(req)
handleQQStatusCode(statusCode: statusCode)
}
}
fileprivate func wechatUrlMessage(message: YLShareMessage) -> SendMessageToWXReq {
let mediaMsg = WXMediaMessage()
mediaMsg.title = message.title
mediaMsg.description = message.content
if let wechatMessage = message as? YLWechatMessage,
let image = wechatMessage.thumbImage {
mediaMsg.setThumbImage(image)
}
if let wechatMessage = message as? YLWechatMessage,
let data = wechatMessage.thumbData {
mediaMsg.thumbData = data
}
let webpageObj = WXWebpageObject()
webpageObj.webpageUrl = message.url
mediaMsg.mediaObject = webpageObj
let req = SendMessageToWXReq()
req.bText = false
req.message = mediaMsg
return req
}
fileprivate func qqUrlMessage(message: YLShareMessage) -> SendMessageToQQReq? {
if let urlStr = message.url,
let url = URL(string: urlStr) {
let obj = QQApiURLObject(url: url, title: message.title, description: message.content, previewImageData: nil, targetContentType: QQApiURLTargetTypeVideo)
if let qqMessage = message as? YLQQMessage,
let data = qqMessage.previewImageData {
obj?.previewImageData = data
}
if let qqMessage = message as? YLQQMessage,
let imageUrlStr = qqMessage.previewImageURL,
let imageUrl = URL(string: imageUrlStr) {
obj?.previewImageURL = imageUrl
}
obj?.shareDestType = ShareDestTypeQQ
return SendMessageToQQReq(content: obj)
}
else {
return nil
}
}
fileprivate func qqZoneUrlMessage(message: YLShareMessage) -> SendMessageToQQReq? {
if let qqMessage = message as? YLQQMessage,
let urlStr = message.url,
let url = URL(string: urlStr) {
var urlObj: QQApiNewsObject?
let title = message.title ?? ""
let desc = message.content ?? ""
if let data = qqMessage.previewImageData {
urlObj = QQApiNewsObject.object(with: url, title: title, description: desc, previewImageData: data) as? QQApiNewsObject
}
if let previewImageUrl = qqMessage.previewImageURL,
let imageUrl = URL(string: previewImageUrl) {
urlObj = QQApiNewsObject(url: url, title: title, description: desc, previewImageURL: imageUrl, targetContentType: QQApiURLTargetTypeNews)
}
urlObj?.cflag = UInt64(kQQAPICtrlFlagQZoneShareOnStart)
urlObj?.shareDestType = ShareDestTypeQQ
return SendMessageToQQReq(content: urlObj)
}
else {
return nil
}
}
fileprivate func handleQQStatusCode(statusCode: QQApiSendResultCode) {
if statusCode == EQQAPISENDSUCESS {
success?()
}
else if statusCode == EQQAPIQQNOTINSTALLED {
let error = YLAuthError(description: "应用未安装", codeType: .appNotInstalled)
fail?(error)
}
else if statusCode == EQQAPIQQNOTSUPPORTAPI {
let error = YLAuthError(description: "应用不支持", codeType: .versionUnsupport)
fail?(error)
}
else {
let error = YLAuthError(description: "分享失败", codeType: .unknown)
fail?(error)
}
}
}
| mit | 9f23dfa3d83899c7659371e8b9af3fdc | 33.844595 | 165 | 0.605779 | 4.51972 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/People/PeopleCellViewModel.swift | 1 | 1398 | import Foundation
import WordPressShared
struct PeopleCellViewModel {
let displayName: String
let username: String
let role: Role?
let superAdmin: Bool
let avatarURL: URL?
init(person: Person, role: Role?) {
self.displayName = person.displayName
self.username = person.username
self.role = role
self.superAdmin = person.isSuperAdmin
self.avatarURL = person.avatarURL as URL?
}
var usernameText: String {
return "@" + username
}
var usernameColor: UIColor {
return .text
}
var roleBorderColor: UIColor {
return role?.color ?? WPStyleGuide.People.otherRoleColor
}
var roleBackgroundColor: UIColor {
return role?.color ?? WPStyleGuide.People.otherRoleColor
}
var roleTextColor: UIColor {
return WPStyleGuide.People.RoleBadge.textColor
}
var roleText: String {
return role?.name ?? ""
}
var roleHidden: Bool {
return roleText.isEmpty
}
var superAdminText: String {
return NSLocalizedString("Super Admin", comment: "User role badge")
}
var superAdminBorderColor: UIColor {
return superAdminBackgroundColor
}
var superAdminBackgroundColor: UIColor {
return WPStyleGuide.People.superAdminColor
}
var superAdminHidden: Bool {
return !superAdmin
}
}
| gpl-2.0 | 4895d3704d97b73b68b0a55ec2af362f | 21.548387 | 75 | 0.645207 | 4.922535 | false | false | false | false |
hooman/swift | test/attr/attributes.swift | 4 | 12579 | // RUN: %target-typecheck-verify-swift -enable-objc-interop
@unknown func f0() {} // expected-error{{unknown attribute 'unknown'}}
@unknown(x,y) func f1() {} // expected-error{{unknown attribute 'unknown'}}
enum binary {
case Zero
case One
init() { self = .Zero }
}
func f5(x: inout binary) {}
//===---
//===--- IB attributes
//===---
@IBDesignable
class IBDesignableClassTy {
@IBDesignable func foo() {} // expected-error {{'@IBDesignable' attribute cannot be applied to this declaration}} {{3-17=}}
}
@IBDesignable // expected-error {{'@IBDesignable' attribute cannot be applied to this declaration}} {{1-15=}}
struct IBDesignableStructTy {}
@IBDesignable // expected-error {{'@IBDesignable' attribute cannot be applied to this declaration}} {{1-15=}}
protocol IBDesignableProtTy {}
@IBDesignable // expected-error {{@IBDesignable can only be applied to classes and extensions of classes}} {{1-15=}}
extension IBDesignableStructTy {}
class IBDesignableClassExtensionTy {}
@IBDesignable // okay
extension IBDesignableClassExtensionTy {}
class Inspect {
@IBInspectable var value : Int = 0 // okay
@GKInspectable var value2: Int = 0 // okay
@IBInspectable func foo() {} // expected-error {{@IBInspectable may only be used on 'var' declarations}} {{3-18=}}
@GKInspectable func foo2() {} // expected-error {{@GKInspectable may only be used on 'var' declarations}} {{3-18=}}
@IBInspectable class var cval: Int { return 0 } // expected-error {{only instance properties can be declared @IBInspectable}} {{3-18=}}
@GKInspectable class var cval2: Int { return 0 } // expected-error {{only instance properties can be declared @GKInspectable}} {{3-18=}}
}
@IBInspectable var ibinspectable_global : Int // expected-error {{only instance properties can be declared @IBInspectable}} {{1-16=}}
@GKInspectable var gkinspectable_global : Int // expected-error {{only instance properties can be declared @GKInspectable}} {{1-16=}}
func foo(x: @convention(block) Int) {} // expected-error {{@convention attribute only applies to function types}}
func foo(x: @convention(block) (Int) -> Int) {}
@_transparent
func zim() {}
@_transparent
func zung<T>(_: T) {}
@_transparent // expected-error{{'@_transparent' attribute cannot be applied to stored properties}} {{1-15=}}
var zippity : Int
func zoom(x: @_transparent () -> ()) { } // expected-error{{attribute can only be applied to declarations, not types}} {{1-1=@_transparent }} {{14-28=}}
protocol ProtoWithTransparent {
@_transparent// expected-error{{'@_transparent' attribute is not supported on declarations within protocols}} {{3-16=}}
func transInProto()
}
class TestTranspClass : ProtoWithTransparent {
@_transparent // expected-error{{'@_transparent' attribute is not supported on declarations within classes}} {{3-17=}}
init () {}
@_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{3-17=}}
deinit {}
@_transparent // expected-error{{'@_transparent' attribute is not supported on declarations within classes}} {{3-17=}}
class func transStatic() {}
@_transparent// expected-error{{'@_transparent' attribute is not supported on declarations within classes}} {{3-16=}}
func transInProto() {}
}
struct TestTranspStruct : ProtoWithTransparent{
@_transparent
init () {}
@_transparent
init <T> (x : T) { }
@_transparent
static func transStatic() {}
@_transparent
func transInProto() {}
}
@_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{1-15=}}
struct CannotHaveTransparentStruct {
func m1() {}
}
@_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{1-15=}}
extension TestTranspClass {
func tr1() {}
}
@_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{1-15=}}
extension TestTranspStruct {
func tr1() {}
}
@_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{1-15=}}
extension binary {
func tr1() {}
}
class transparentOnClassVar {
@_transparent var max: Int { return 0xFF }; // expected-error {{'@_transparent' attribute is not supported on declarations within classes}} {{3-17=}}
func blah () {
var _: Int = max
}
};
class transparentOnClassVar2 {
var max: Int {
@_transparent // expected-error {{'@_transparent' attribute is not supported on declarations within classes}} {{5-19=}}
get {
return 0xFF
}
}
func blah () {
var _: Int = max
}
};
@thin // expected-error {{attribute can only be applied to types, not declarations}}
func testThinDecl() -> () {}
protocol Class : class {}
protocol NonClass {}
@objc
class Ty0 : Class, NonClass {
init() { }
}
// Attributes that should be reported by parser as unknown
// See rdar://19533915
@__setterAccess struct S__accessibility {} // expected-error{{unknown attribute '__setterAccess'}}
@__raw_doc_comment struct S__raw_doc_comment {} // expected-error{{unknown attribute '__raw_doc_comment'}}
@__objc_bridged struct S__objc_bridged {} // expected-error{{unknown attribute '__objc_bridged'}}
weak
var weak0 : Ty0?
weak
var weak0x : Ty0?
weak unowned var weak1 : Ty0? // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
weak weak var weak2 : Ty0? // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
unowned var weak3 : Ty0
unowned var weak3a : Ty0
unowned(safe) var weak3b : Ty0
unowned(unsafe) var weak3c : Ty0
unowned unowned var weak4 : Ty0 // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
unowned weak var weak5 : Ty0 // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
weak
var weak6 : Int? // expected-error {{'weak' may only be applied to class and class-bound protocol types, not 'Int'}}
unowned
var weak7 : Int // expected-error {{'unowned' may only be applied to class and class-bound protocol types, not 'Int'}}
weak
var weak8 : Class? = Ty0()
// expected-warning@-1 {{instance will be immediately deallocated because variable 'weak8' is 'weak'}}
// expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-3 {{'weak8' declared here}}
unowned var weak9 : Class = Ty0()
// expected-warning@-1 {{instance will be immediately deallocated because variable 'weak9' is 'unowned'}}
// expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-3 {{'weak9' declared here}}
weak
var weak10 : NonClass? = Ty0() // expected-error {{'weak' must not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}}
unowned
var weak11 : NonClass = Ty0() // expected-error {{'unowned' must not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}}
unowned
var weak12 : NonClass = Ty0() // expected-error {{'unowned' must not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}}
unowned
var weak13 : NonClass = Ty0() // expected-error {{'unowned' must not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}}
weak
var weak14 : Ty0 // expected-error {{'weak' variable should have optional type 'Ty0?'}}
weak
var weak15 : Class // expected-error {{'weak' variable should have optional type 'Class?'}}
weak var weak16 : Class!
@weak var weak17 : Class? // expected-error {{'weak' is a declaration modifier, not an attribute}} {{1-2=}}
@_exported var exportVar: Int // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}}
@_exported func exportFunc() {} // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}}
@_exported struct ExportStruct {} // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}}
// Function result type attributes.
var func_result_type_attr : () -> @xyz Int // expected-error {{unknown attribute 'xyz'}}
func func_result_attr() -> @xyz Int { // expected-error {{unknown attribute 'xyz'}}
return 4
}
func func_with_unknown_attr1(@unknown(*) x: Int) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr2(x: @unknown(_) Int) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr3(x: @unknown(Int) -> Int) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr4(x: @unknown(Int) throws -> Int) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr5(x: @unknown (x: Int, y: Int)) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr6(x: @unknown(x: Int, y: Int)) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr7(x: @unknown (Int) () -> Int) {} // expected-error {{unknown attribute 'unknown'}}
func func_type_attribute_with_space(x: @convention (c) () -> Int) {} // OK. Known attributes can have space before its paren.
// @thin and @pseudogeneric are not supported except in SIL.
var thinFunc : @thin () -> () // expected-error {{unknown attribute 'thin'}}
var pseudoGenericFunc : @pseudogeneric () -> () // expected-error {{unknown attribute 'pseudogeneric'}}
@inline(never) func nolineFunc() {}
@inline(never) var noinlineVar : Int { return 0 }
@inline(never) class FooClass { // expected-error {{'@inline(never)' attribute cannot be applied to this declaration}} {{1-16=}}
}
@inline(__always) func AlwaysInlineFunc() {}
@inline(__always) var alwaysInlineVar : Int { return 0 }
@inline(__always) class FooClass2 { // expected-error {{'@inline(__always)' attribute cannot be applied to this declaration}} {{1-19=}}
}
@_optimize(speed) func OspeedFunc() {}
@_optimize(speed) var OpeedVar : Int // expected-error {{'@_optimize(speed)' attribute cannot be applied to stored properties}} {{1-19=}}
@_optimize(speed) class OspeedClass { // expected-error {{'@_optimize(speed)' attribute cannot be applied to this declaration}} {{1-19=}}
}
class A {
@inline(never) init(a : Int) {}
var b : Int {
@inline(never) get {
return 42
}
@inline(never) set {
}
}
}
class B {
@inline(__always) init(a : Int) {}
var b : Int {
@inline(__always) get {
return 42
}
@inline(__always) set {
}
}
}
class C {
@_optimize(speed) init(a : Int) {}
var b : Int {
@_optimize(none) get {
return 42
}
@_optimize(size) set {
}
}
@_optimize(size) var c : Int // expected-error {{'@_optimize(size)' attribute cannot be applied to stored properties}}
}
class HasStorage {
@_hasStorage var x : Int = 42 // ok, _hasStorage is allowed here
}
@_show_in_interface protocol _underscored {}
@_show_in_interface class _notapplicable {} // expected-error {{may only be used on 'protocol' declarations}}
// Error recovery after one invalid attribute
@_invalid_attribute_ // expected-error {{unknown attribute '_invalid_attribute_'}}
@inline(__always)
public func sillyFunction() {}
// rdar://problem/45732251: unowned/unowned(unsafe) optional lets are permitted
func unownedOptionals(x: C) {
unowned let y: C? = x
unowned(unsafe) let y2: C? = x
_ = y
_ = y2
}
// @_nonEphemeral attribute
struct S1<T> {
func foo(@_nonEphemeral _ x: String) {} // expected-error {{@_nonEphemeral attribute only applies to pointer types}}
func bar(@_nonEphemeral _ x: T) {} // expected-error {{@_nonEphemeral attribute only applies to pointer types}}
func baz<U>(@_nonEphemeral _ x: U) {} // expected-error {{@_nonEphemeral attribute only applies to pointer types}}
func qux(@_nonEphemeral _ x: UnsafeMutableRawPointer) {}
func quux(@_nonEphemeral _ x: UnsafeMutablePointer<Int>?) {}
}
@_nonEphemeral struct S2 {} // expected-error {{@_nonEphemeral may only be used on 'parameter' declarations}}
protocol P {}
extension P {
// Allow @_nonEphemeral on the protocol Self type, as the protocol could be adopted by a pointer type.
func foo(@_nonEphemeral _ x: Self) {}
func bar(@_nonEphemeral _ x: Self?) {}
}
enum E1 {
case str(@_nonEphemeral _: String) // expected-error {{expected parameter name followed by ':'}}
case ptr(@_nonEphemeral _: UnsafeMutableRawPointer) // expected-error {{expected parameter name followed by ':'}}
func foo() -> @_nonEphemeral UnsafeMutableRawPointer? { return nil } // expected-error {{attribute can only be applied to declarations, not types}}
}
| apache-2.0 | d90ace3bac937fdf0dfc8067dd7e99d4 | 39.317308 | 174 | 0.695524 | 3.934626 | false | false | false | false |
haitran2011/Rocket.Chat.iOS | Rocket.Chat/Controllers/MainViewController.swift | 1 | 2721 | //
// MainViewController.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/8/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import UIKit
final class MainViewController: BaseViewController {
@IBOutlet weak var labelAuthenticationStatus: UILabel!
@IBOutlet weak var buttonConnect: UIButton!
var activityIndicator: LoaderView!
@IBOutlet weak var activityIndicatorContainer: UIView! {
didSet {
let width = activityIndicatorContainer.bounds.width
let height = activityIndicatorContainer.bounds.height
let frame = CGRect(x: 0, y: 0, width: width, height: height)
let activityIndicator = LoaderView(frame: frame)
activityIndicatorContainer.addSubview(activityIndicator)
self.activityIndicator = activityIndicator
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if AuthManager.isAuthenticated() == nil {
performSegue(withIdentifier: "Auth", sender: nil)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let auth = AuthManager.isAuthenticated() {
labelAuthenticationStatus.isHidden = true
buttonConnect.isHidden = true
activityIndicator.startAnimating()
AuthManager.resume(auth, completion: { [weak self] response in
guard !response.isError() else {
self?.labelAuthenticationStatus.isHidden = false
self?.buttonConnect.isHidden = false
self?.activityIndicator.stopAnimating()
return
}
SubscriptionManager.updateSubscriptions(auth, completion: { _ in
AuthManager.updatePublicSettings(auth, completion: { _ in
})
UserManager.userDataChanges()
UserManager.changes()
SubscriptionManager.changes(auth)
if let userIdentifier = auth.userId {
PushManager.updateUser(userIdentifier)
}
// Open chat
let storyboardChat = UIStoryboard(name: "Chat", bundle: Bundle.main)
let controller = storyboardChat.instantiateInitialViewController()
let application = UIApplication.shared
if let window = application.keyWindow {
window.rootViewController = controller
}
})
})
} else {
buttonConnect.isEnabled = true
}
}
}
| mit | 816ac56e31412e4f78934fa048e95cb6 | 33 | 88 | 0.582721 | 5.925926 | false | false | false | false |
jeffreybergier/WaterMe2 | WaterMe/WaterMe/CoreDataMigration/CoreDataMigrator.swift | 1 | 10437 | //
// CoreDataMigrator.swift
// WaterMe
//
// Created by Jeffrey Bergier on 29/12/17.
// Copyright © 2017 Saturday Apps.
//
// This file is part of WaterMe. Simple Plant Watering Reminders for iOS.
//
// WaterMe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// WaterMe is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with WaterMe. If not, see <http://www.gnu.org/licenses/>.
//
import Datum
import CoreData
import Foundation
protocol CoreDataMigratable {
var progress: Progress { get }
func start(with: BasicController, completion: @escaping (Bool) -> Void)
func deleteCoreDataStoreWithoutMigrating()
}
class CoreDataMigrator: CoreDataMigratable {
// MARK: Core Data Locations on Disk
private static let momName = "WaterMeData"
private static let storeURL = CoreDataMigrator.storeDirectory.appendingPathComponent("WaterMeData.sqlite")
private static let storeDirectoryPostMigration = CoreDataMigrator.storeDirectory.appendingPathComponent("WaterMe1.coredata", isDirectory: true)
fileprivate static let storeDirectory: URL = {
let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
let storeDirectory = appSupport.appendingPathComponent("WaterMe", isDirectory: true)
return storeDirectory
}()
private static let storeFilesToMove: [URL] = {
return [
CoreDataMigrator.storeURL,
CoreDataMigrator.storeDirectory.appendingPathComponent("WaterMeData.sqlite-shm"),
CoreDataMigrator.storeDirectory.appendingPathComponent("WaterMeData.sqlite-wal")
]
}()
// MARK: Properties
private let container: NSPersistentContainer
let progress = Progress()
// MARK: Helper for Counting Plants
private var numberOfPlantsToMigrate: Int? {
do {
return try self.container.viewContext.count(for: NSFetchRequest(entityName: String(describing: PlantEntity.self)))
} catch {
let message = "CoreDataError Fetching Count of old plants: \(error)"
log.error(message)
Analytics.log(error: error)
assertionFailure(message)
return nil
}
}
// MARK: Init
// Looks for a core data file on disk. If it exists, that means the user upgraded from WaterMe 1
// If it exists, initialization succeeds. Otherwise, it returns NIL
init?() {
let sqLiteURL = CoreDataMigrator.storeURL
// if the file doesn't exist then they never had the old version of the app.
guard FileManager.default.fileExists(atPath: sqLiteURL.path) == true else { return nil }
self.container = WaterMePersistentContainer(name: CoreDataMigrator.momName)
self.container.persistentStoreDescriptions.first?.isReadOnly = true
self.container.loadPersistentStores() { _, error in
guard error == nil else {
let message = "Error Loading Core Data Model. This leaves the Migrator in an invalid state: \(error!)"
log.error(message)
Analytics.log(error: error!)
assertionFailure(message)
return
}
let count = self.numberOfPlantsToMigrate
self.progress.totalUnitCount = Int64(count ?? -1)
self.progress.completedUnitCount = 0
}
log.debug("Loaded Core Data Stack: Ready for Migration.")
}
// MARK: Perform the Migration
// This function just loads the data from Core Data and iterates over it
// Each iteration it creates a new object in REALM
// It also updates the progress object
// Finally it shuts down the core data stack and moves the underlying files
// Moving the files means the data is not lost but its not detected on next boot
// Which means it won't try to migrate again.
// swiftlint:disable:next function_body_length
func start(with basicRC: BasicController, completion: @escaping (Bool) -> Void) {
let count = self.numberOfPlantsToMigrate ?? -1
self.progress.totalUnitCount = Int64(count)
self.progress.completedUnitCount = 0
self.container.performBackgroundTask() { c in
var migrated = 0 {
didSet {
self.progress.completedUnitCount = Int64(migrated)
}
}
var plants = type(of: self).plants(from: c)
// weird loop so core data memory can be drained in each iteration
for _ in 0 ..< plants.count {
autoreleasepool() {
// needs more testing but the ReminderGedeg was sometimes
// crashing when migration happened at full speed
Thread.sleep(forTimeInterval: 0.1)
// popping them out of the array allows the memory to be freed in the release pool
let _plant = plants.popLast()
guard let plant = _plant as? PlantEntity else {
let error = "Object in PlantArray is not PlantEntity: \(String(describing: _plant))"
log.error(error)
assertionFailure(error)
return
}
let imageEmoji = plant.cd_00100_imageEmojiTransformable as? ImageEmojiObject
let vesselName = plant.cd_00100_nameString
let vesselImage = imageEmoji?.emojiImage
let vesselEmoji = imageEmoji?.emojiString
let reminderInterval = plant.cd_00100_wateringIntervalNumber
let reminderLastPerformDate = plant.cd_00100_lastWateredDate
let result = basicRC.coreDataMigration(vesselName: vesselName,
vesselImage: vesselImage,
vesselEmoji: vesselEmoji,
reminderInterval: reminderInterval,
reminderLastPerformDate: reminderLastPerformDate)
switch result {
case .failure(let error):
let description = "Error while migrating plant named: \(vesselName!): \(error)"
log.error(description)
assertionFailure(description)
case .success:
migrated += 1
}
}
}
self.closeCoreDataStoresAndMoveUnderlyingFiles()
DispatchQueue.main.async {
if migrated == count {
Analytics.log(event: Analytics.CoreDataMigration.migrationComplete,
extras: Analytics.CoreDataMigration.extras(migrated: migrated, total: count))
} else {
Analytics.log(event: Analytics.CoreDataMigration.migrationPartial,
extras: Analytics.CoreDataMigration.extras(migrated: migrated, total: count))
}
completion(migrated == count)
}
}
}
func deleteCoreDataStoreWithoutMigrating() {
self.closeCoreDataStoresAndMoveUnderlyingFiles()
}
// MARK: Helper functions for capturing errors
private func closeCoreDataStoresAndMoveUnderlyingFiles() {
do {
// close all the stores before moving the files
try self.container.persistentStoreCoordinator.persistentStores.forEach() {
try self.container.persistentStoreCoordinator.remove($0)
}
// move the underlying files
try type(of: self).moveCoreDataStoreToPostMigrationLocation()
} catch {
let message = "Error Moving Core Data Store Files: \(error)"
log.error(message)
Analytics.log(error: error)
assertionFailure(message)
}
}
private class func plants(from c: NSManagedObjectContext) -> [Any] {
do {
return try c.fetch(NSFetchRequest(entityName: String(describing: PlantEntity.self)))
} catch {
let message = "CoreDataError Fetching old plants: \(error)"
log.error(message)
Analytics.log(error: error)
assertionFailure(message)
return []
}
}
// MARK: Move the underlying files
// Checks to see if there is a location on disk to move the files to
// If not, it makes a folder. If a file exists with the same name as folder
// It deletes the file and then makes the folder
// Lastly it moves the core data files there
private class func moveCoreDataStoreToPostMigrationLocation() throws {
let fm = FileManager.default
let destinationDir = self.storeDirectoryPostMigration
let filesToMove = self.storeFilesToMove
var isDir: ObjCBool = false
let exists = fm.fileExists(atPath: destinationDir.path, isDirectory: &isDir)
switch (exists, isDir.boolValue) {
case (true, false):
try fm.removeItem(at: destinationDir)
fallthrough
case (false, _):
try fm.createDirectory(at: destinationDir, withIntermediateDirectories: false, attributes: nil)
fallthrough
case (true, true):
try filesToMove.forEach() { sourceURL in
let destination = destinationDir.appendingPathComponent(sourceURL.lastPathComponent)
try fm.moveItem(at: sourceURL, to: destination)
}
}
}
}
// MARK: Custom Subclass of NSPersistentContainer
// Subclass needed to give Core Data my custom directory from WaterMe1
private class WaterMePersistentContainer: NSPersistentContainer {
override class func defaultDirectoryURL() -> URL {
return CoreDataMigrator.storeDirectory
}
}
| gpl-3.0 | bcf4b65b408ee35550f6ee85cf6c4a27 | 43.033755 | 147 | 0.619203 | 5.202393 | false | false | false | false |
knorrium/firefox-ios | Sync/Synchronizers/LoginsSynchronizer.swift | 19 | 8324 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import XCGLogger
private let log = Logger.syncLogger
private let PasswordsStorageVersion = 1
private func makeDeletedLoginRecord(guid: GUID) -> Record<LoginPayload> {
// Local modified time is ignored in upload serialization.
let modified: Timestamp = 0
// Arbitrary large number: deletions sync down first.
let sortindex = 5_000_000
let json: JSON = JSON([
"id": guid,
"deleted": true,
])
let payload = LoginPayload(json)
return Record<LoginPayload>(id: guid, payload: payload, modified: modified, sortindex: sortindex)
}
func makeLoginRecord(login: Login) -> Record<LoginPayload> {
let id = login.guid
let modified: Timestamp = 0 // Ignored in upload serialization.
let sortindex = 1
let tLU = NSNumber(unsignedLongLong: login.timeLastUsed / 1000)
let tPC = NSNumber(unsignedLongLong: login.timePasswordChanged / 1000)
let tC = NSNumber(unsignedLongLong: login.timeCreated / 1000)
let dict: [String: AnyObject] = [
"id": id,
"hostname": login.hostname,
"httpRealm": login.httpRealm ?? JSON.null,
"formSubmitURL": login.formSubmitURL ?? JSON.null,
"username": login.username ?? "",
"password": login.password,
"usernameField": login.usernameField ?? "",
"passwordField": login.passwordField ?? "",
"timesUsed": login.timesUsed,
"timeLastUsed": tLU,
"timePasswordChanged": tPC,
"timeCreated": tC,
]
let payload = LoginPayload(JSON(dict))
return Record<LoginPayload>(id: id, payload: payload, modified: modified, sortindex: sortindex)
}
/**
* Our current local terminology ("logins") has diverged from the terminology in
* use when Sync was built ("passwords"). I've done my best to draw a reasonable line
* between the server collection/record format/etc. and local stuff: local storage
* works with logins, server records and collection are passwords.
*/
public class LoginsSynchronizer: IndependentRecordSynchronizer, Synchronizer {
public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs) {
super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, collection: "passwords")
}
override var storageVersion: Int {
return PasswordsStorageVersion
}
func getLogin(record: Record<LoginPayload>) -> ServerLogin {
let guid = record.id
let payload = record.payload
let modified = record.modified
let login = ServerLogin(guid: guid, hostname: payload.hostname, username: payload.username, password: payload.password, modified: modified)
login.formSubmitURL = payload.formSubmitURL
login.httpRealm = payload.httpRealm
login.usernameField = payload.usernameField
login.passwordField = payload.passwordField
// Microseconds locally, milliseconds remotely. We should clean this up.
login.timeCreated = 1000 * (payload.timeCreated ?? 0)
login.timeLastUsed = 1000 * (payload.timeLastUsed ?? 0)
login.timePasswordChanged = 1000 * (payload.timePasswordChanged ?? 0)
login.timesUsed = payload.timesUsed ?? 0
return login
}
func applyIncomingToStorage(storage: SyncableLogins, records: [Record<LoginPayload>], fetched: Timestamp) -> Success {
return self.applyIncomingToStorage(records, fetched: fetched) { rec in
let guid = rec.id
let payload = rec.payload
// We apply deletions immediately. That might not be exactly what we want -- perhaps you changed
// a password locally after deleting it remotely -- but it's expedient.
if payload.deleted {
return storage.deleteByGUID(guid, deletedAt: rec.modified)
}
return storage.applyChangedLogin(self.getLogin(rec))
}
}
private func uploadModifiedLogins(logins: [Login], lastTimestamp: Timestamp, fromStorage storage: SyncableLogins, withServer storageClient: Sync15CollectionClient<LoginPayload>) -> DeferredTimestamp {
return self.uploadRecords(logins.map(makeLoginRecord), by: 50, lastTimestamp: lastTimestamp, storageClient: storageClient, onUpload: { storage.markAsSynchronized($0, modified: $1) })
}
private func uploadDeletedLogins(guids: [GUID], lastTimestamp: Timestamp, fromStorage storage: SyncableLogins, withServer storageClient: Sync15CollectionClient<LoginPayload>) -> DeferredTimestamp {
let records = guids.map(makeDeletedLoginRecord)
// Deletions are smaller, so upload 100 at a time.
return self.uploadRecords(records, by: 100, lastTimestamp: lastTimestamp, storageClient: storageClient, onUpload: { storage.markAsDeleted($0) >>> always($1) })
}
// Find any records for which a local overlay exists. If we want to be really precise,
// we can find the original server modified time for each record and use it as
// If-Unmodified-Since on a PUT, or just use the last fetch timestamp, which should
// be equivalent.
// We will already have reconciled any conflicts on download, so this upload phase should
// be as simple as uploading any changed or deleted items.
private func uploadOutgoingFromStorage(storage: SyncableLogins, lastTimestamp: Timestamp, withServer storageClient: Sync15CollectionClient<LoginPayload>) -> Success {
let uploadDeleted: Timestamp -> DeferredTimestamp = { timestamp in
storage.getDeletedLoginsToUpload()
>>== { guids in
return self.uploadDeletedLogins(guids, lastTimestamp: timestamp, fromStorage: storage, withServer: storageClient)
}
}
let uploadModified: Timestamp -> DeferredTimestamp = { timestamp in
storage.getModifiedLoginsToUpload()
>>== { logins in
return self.uploadModifiedLogins(logins, lastTimestamp: timestamp, fromStorage: storage, withServer: storageClient)
}
}
return deferMaybe(lastTimestamp)
>>== uploadDeleted
>>== uploadModified
>>> effect({ log.debug("Done syncing.") })
>>> succeed
}
public func synchronizeLocalLogins(logins: SyncableLogins, withServer storageClient: Sync15StorageClient, info: InfoCollections) -> SyncResult {
if let reason = self.reasonToNotSync(storageClient) {
return deferMaybe(.NotStarted(reason))
}
let encoder = RecordEncoder<LoginPayload>(decode: { LoginPayload($0) }, encode: { $0 })
if let passwordsClient = self.collectionClient(encoder, storageClient: storageClient) {
let since: Timestamp = self.lastFetched
log.debug("Synchronizing \(self.collection). Last fetched: \(since).")
let applyIncomingToStorage: StorageResponse<[Record<LoginPayload>]> -> Success = { response in
let ts = response.metadata.timestampMilliseconds
let lm = response.metadata.lastModifiedMilliseconds!
log.debug("Applying incoming password records from response timestamped \(ts), last modified \(lm).")
log.debug("Records header hint: \(response.metadata.records)")
return self.applyIncomingToStorage(logins, records: response.value, fetched: lm)
}
return passwordsClient.getSince(since)
>>== applyIncomingToStorage
// TODO: If we fetch sorted by date, we can bump the lastFetched timestamp
// to the last successfully applied record timestamp, no matter where we fail.
// There's no need to do the upload before bumping -- the storage of local changes is stable.
>>> { self.uploadOutgoingFromStorage(logins, lastTimestamp: 0, withServer: passwordsClient) }
>>> { return deferMaybe(.Completed) }
}
log.error("Couldn't make logins factory.")
return deferMaybe(FatalError(message: "Couldn't make logins factory."))
}
} | mpl-2.0 | 660f9e7b794775adfb8ee4b33558156b | 46.571429 | 204 | 0.677198 | 5.014458 | false | false | false | false |
tjw/swift | benchmark/single-source/Exclusivity.swift | 4 | 3488 | //===--- Exclusivity.swift -------------------------------------------------===//
//
// 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 set of tests for measuring the enforcement overhead of memory access
// exclusivity rules.
//
//===----------------------------------------------------------------------===//
import TestsUtils
public let Exclusivity = [
// At -Onone
// 25% swift_beginAccess
// 15% tlv_get_addr
// 15% swift_endAccess
BenchmarkInfo(
name: "ExclusivityGlobal",
runFunction: run_accessGlobal,
tags: [.runtime, .cpubench]
),
// At -Onone
// 23% swift_retain
// 22% swift_release
// 9% swift_beginAccess
// 3% swift_endAccess
BenchmarkInfo(
name: "ExclusivityInMatSet",
runFunction: run_accessInMatSet,
tags: [.runtime, .cpubench, .unstable]
),
// At -Onone
// 25% swift_release
// 23% swift_retain
// 16% swift_beginAccess
// 8% swift_endAccess
BenchmarkInfo(
name: "ExclusivityIndependent",
runFunction: run_accessIndependent,
tags: [.runtime, .cpubench]
),
]
// Initially these benchmarks only measure access checks at -Onone. In
// the future, access checks will also be emitted at -O.
// Measure memory access checks on a trivial global.
// ---
public var globalCounter: Int = 0
// TODO:
// - Merge begin/endAccess when no calls intervene (~2x speedup).
// - Move Swift runtime into the OS (~2x speedup).
// - Whole module analysis can remove exclusivity checks (> 10x speedup now, 4x speedup with runtime in OS).
// (The global's "public" qualifier should make the benchmark immune to this optimization.)
@inline(never)
public func run_accessGlobal(_ N: Int) {
globalCounter = 0
for _ in 1...10000*N {
globalCounter += 1
}
CheckResults(globalCounter == 10000*N)
}
// Measure memory access checks on a class property.
//
// Note: The end_unpaired_access forces a callback on the property's
// materializeForSet!
// ---
// Hopefully the optimizer will not see this as "final" and optimize away the
// materializeForSet.
public class C {
var counter = 0
func inc() {
counter += 1
}
}
// Thunk
@inline(never)
func updateClass(_ c: C) {
c.inc()
}
// TODO: Replacing materializeForSet accessors with yield-once
// accessors should make the callback overhead go away.
@inline(never)
public func run_accessInMatSet(_ N: Int) {
let c = C()
for _ in 1...10000*N {
updateClass(c)
}
CheckResults(c.counter == 10000*N)
}
// Measure nested access to independent objects.
//
// A single access set is still faster than hashing for up to four accesses.
// ---
struct Var {
var val = 0
}
@inline(never)
func update(a: inout Var, b: inout Var, c: inout Var, d: inout Var) {
a.val += 1
b.val += 1
c.val += 1
d.val += 1
}
@inline(never)
public func run_accessIndependent(_ N: Int) {
var a = Var()
var b = Var()
var c = Var()
var d = Var()
let updateVars = {
update(a: &a, b: &b, c: &c, d: &d)
}
for _ in 1...1000*N {
updateVars()
}
CheckResults(a.val == 1000*N && b.val == 1000*N && c.val == 1000*N
&& d.val == 1000*N)
}
| apache-2.0 | b37249ba0b380bf5c9294553ec8144a5 | 24.275362 | 108 | 0.62156 | 3.706695 | false | false | false | false |
shhuangtwn/ProjectLynla | Pods/SwiftCharts/SwiftCharts/AxisValues/ChartAxisValue.swift | 1 | 1727 | //
// ChartAxisValue.swift
// swift_charts
//
// Created by ischuetz on 01/03/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
/**
A ChartAxisValue models a value along a particular chart axis. For example, two ChartAxisValues represent the two components of a ChartPoint. It has a backing Double scalar value, which provides a canonical form for all subclasses to be laid out along an axis. It also has one or more labels that are drawn in the chart.
This class is not meant to be instantiated directly. Use one of the existing subclasses or create a new one.
*/
public class ChartAxisValue: Equatable, CustomStringConvertible {
/// The backing value for all other types of axis values
public let scalar: Double
public let labelSettings: ChartLabelSettings
public var hidden = false
/// The labels that will be displayed in the chart
public var labels: [ChartAxisLabel] {
let axisLabel = ChartAxisLabel(text: self.description, settings: self.labelSettings)
axisLabel.hidden = self.hidden
return [axisLabel]
}
public init(scalar: Double, labelSettings: ChartLabelSettings = ChartLabelSettings()) {
self.scalar = scalar
self.labelSettings = labelSettings
}
public var copy: ChartAxisValue {
return self.copy(self.scalar)
}
public func copy(scalar: Double) -> ChartAxisValue {
return ChartAxisValue(scalar: scalar, labelSettings: self.labelSettings)
}
// MARK: CustomStringConvertible
public var description: String {
return String(scalar)
}
}
public func ==(lhs: ChartAxisValue, rhs: ChartAxisValue) -> Bool {
return lhs.scalar == rhs.scalar
}
| mit | d83810dfa9ac62f8e16419d645a20436 | 32.862745 | 321 | 0.709323 | 4.837535 | false | false | false | false |
WhisperSystems/Signal-iOS | SignalMessaging/Views/Tooltips/StickerTooltip.swift | 1 | 8099 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import YYImage
@objc
public class StickerTooltip: UIView {
private let stickerPack: StickerPack
private let block: (() -> Void)?
// MARK: Initializers
@objc
required public init(fromView: UIView,
widthReferenceView: UIView,
tailReferenceView: UIView,
stickerPack: StickerPack,
block: (() -> Void)?) {
self.stickerPack = stickerPack
self.block = block
super.init(frame: .zero)
createContents(fromView: fromView,
widthReferenceView: widthReferenceView,
tailReferenceView: tailReferenceView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc
public class func presentTooltip(fromView: UIView,
widthReferenceView: UIView,
tailReferenceView: UIView,
stickerPack: StickerPack,
block: (() -> Void)?) -> UIView {
let tooltip = StickerTooltip(fromView: fromView,
widthReferenceView: widthReferenceView,
tailReferenceView: tailReferenceView,
stickerPack: stickerPack,
block: block)
return tooltip
}
private let tailHeight: CGFloat = 8
private let tailWidth: CGFloat = 16
private let bubbleRounding: CGFloat = 8
private let iconView = YYAnimatedImageView()
private func createContents(fromView: UIView,
widthReferenceView: UIView,
tailReferenceView: UIView) {
backgroundColor = .clear
isOpaque = false
isUserInteractionEnabled = true
addGestureRecognizer(UITapGestureRecognizer(target: self,
action: #selector(handleTap)))
// Bubble View
let bubbleView = OWSLayerView()
let shapeLayer = CAShapeLayer()
shapeLayer.shadowColor = UIColor.black.cgColor
shapeLayer.shadowOffset = CGSize(width: 0, height: 40)
shapeLayer.shadowRadius = 40
shapeLayer.shadowOpacity = 0.33
shapeLayer.fillColor = Theme.backgroundColor.cgColor
bubbleView.layer.addSublayer(shapeLayer)
addSubview(bubbleView)
bubbleView.autoPinEdgesToSuperviewEdges()
bubbleView.layoutCallback = { [weak self] view in
guard let self = self else {
return
}
let bezierPath = UIBezierPath()
// Bubble
var bubbleBounds = view.bounds
bubbleBounds.size.height -= self.tailHeight
bezierPath.append(UIBezierPath(roundedRect: bubbleBounds, cornerRadius: self.bubbleRounding))
// Tail
//
// The tail should _try_ to point to the "tail reference view".
let tailReferenceFrame = self.convert(tailReferenceView.bounds, from: tailReferenceView)
let tailHalfWidth = self.tailWidth * 0.5
let tailHCenterMin = self.bubbleRounding + tailHalfWidth
let tailHCenterMax = bubbleBounds.width - tailHCenterMin
let tailHCenter = tailReferenceFrame.center.x.clamp(tailHCenterMin, tailHCenterMax)
let tailBottom = CGPoint(x: tailHCenter, y: view.bounds.height)
let tailLeft = CGPoint(x: tailHCenter - tailHalfWidth, y: bubbleBounds.height)
let tailRight = CGPoint(x: tailHCenter + tailHalfWidth, y: bubbleBounds.height)
bezierPath.move(to: tailBottom)
bezierPath.addLine(to: tailLeft)
bezierPath.addLine(to: tailRight)
bezierPath.addLine(to: tailBottom)
shapeLayer.path = bezierPath.cgPath
shapeLayer.frame = view.bounds
}
// Bubble Contents
iconView.autoSetDimensions(to: CGSize(width: 24, height: 24))
updateIconView()
let label = UILabel()
label.text = NSLocalizedString("STICKER_PACK_INSTALLED_TOOLTIP",
comment: "Tooltip indicating that a sticker pack was installed.")
label.font = UIFont.ows_dynamicTypeBody.ows_mediumWeight()
label.textColor = Theme.primaryColor
let stackView = UIStackView(arrangedSubviews: [
iconView,
label
])
stackView.axis = .horizontal
stackView.alignment = .center
stackView.spacing = 6
stackView.layoutMargins = UIEdgeInsets(top: 7, left: 12, bottom: 7, right: 12)
stackView.isLayoutMarginsRelativeArrangement = true
addSubview(stackView)
stackView.autoPinEdgesToSuperviewMargins()
layoutMargins = UIEdgeInsets(top: 0, left: 0, bottom: tailHeight, right: 0)
fromView.addSubview(self)
autoPinEdge(.bottom, to: .top, of: tailReferenceView, withOffset: -0)
// Insist on the tooltip fitting within the margins of the widthReferenceView.
autoPinEdge(.left, to: .left, of: widthReferenceView, withOffset: 20, relation: .greaterThanOrEqual)
autoPinEdge(.right, to: .right, of: widthReferenceView, withOffset: -20, relation: .lessThanOrEqual)
NSLayoutConstraint.autoSetPriority(UILayoutPriority.defaultLow) {
// Prefer that the tooltip's tail is as far as possible.
// It should point at the center of the "tail reference view".
let edgeOffset = bubbleRounding + tailWidth * 0.5 - tailReferenceView.width() * 0.5
autoPinEdge(.right, to: .right, of: tailReferenceView, withOffset: edgeOffset)
}
NotificationCenter.default.addObserver(self,
selector: #selector(stickersOrPacksDidChange),
name: StickerManager.stickersOrPacksDidChange,
object: nil)
}
private func updateIconView() {
guard iconView.image == nil else {
iconView.isHidden = true
return
}
let stickerInfo = stickerPack.coverInfo
guard let filePath = StickerManager.filepathForInstalledSticker(stickerInfo: stickerInfo) else {
// This sticker is not downloaded; try to download now.
StickerManager.tryToDownloadSticker(stickerPack: stickerPack, stickerInfo: stickerInfo)
.done { [weak self] (stickerData: Data) in
guard let self = self else {
return
}
self.updateIconView(imageData: stickerData)
}.catch {(error) in
owsFailDebug("error: \(error)")
}.retainUntilComplete()
return
}
guard let image = YYImage(contentsOfFile: filePath) else {
owsFailDebug("could not load asset.")
return
}
iconView.image = image
iconView.isHidden = false
}
private func updateIconView(imageData: Data) {
guard iconView.image == nil else {
iconView.isHidden = true
return
}
guard let image = YYImage(data: imageData) else {
owsFailDebug("could not load asset.")
return
}
iconView.image = image
iconView.isHidden = false
}
// MARK: Events
@objc func stickersOrPacksDidChange() {
AssertIsOnMainThread()
updateIconView()
}
@objc
func handleTap(sender: UIGestureRecognizer) {
guard sender.state == .recognized else {
return
}
Logger.verbose("")
removeFromSuperview()
block?()
}
}
| gpl-3.0 | a052841568baa2538f9dda076e8f09e3 | 36.845794 | 108 | 0.582911 | 5.487127 | false | false | false | false |
nathawes/swift | stdlib/public/core/CharacterProperties.swift | 22 | 12351 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension Character {
@inlinable
internal var _firstScalar: Unicode.Scalar {
return self.unicodeScalars.first!
}
@inlinable
internal var _isSingleScalar: Bool {
return self.unicodeScalars.index(
after: self.unicodeScalars.startIndex
) == self.unicodeScalars.endIndex
}
/// A Boolean value indicating whether this is an ASCII character.
@inlinable
public var isASCII: Bool {
return asciiValue != nil
}
/// The ASCII encoding value of this character, if it is an ASCII character.
///
/// let chars: [Character] = ["a", " ", "™"]
/// for ch in chars {
/// print(ch, "-->", ch.asciiValue)
/// }
/// // Prints:
/// // a --> Optional(97)
/// // --> Optional(32)
/// // ™ --> nil
///
/// A character with the value "\r\n" (CR-LF) is normalized to "\n" (LF) and
/// has an `asciiValue` property equal to 10.
///
/// let cr = "\r" as Character
/// // cr.asciiValue == 13
/// let lf = "\n" as Character
/// // lf.asciiValue == 10
/// let crlf = "\r\n" as Character
/// // crlf.asciiValue == 10
@inlinable
public var asciiValue: UInt8? {
if _slowPath(self == "\r\n") { return 0x000A /* LINE FEED (LF) */ }
if _slowPath(!_isSingleScalar || _firstScalar.value >= 0x80) { return nil }
return UInt8(_firstScalar.value)
}
/// A Boolean value indicating whether this character represents whitespace,
/// including newlines.
///
/// For example, the following characters all represent whitespace:
///
/// - "\t" (U+0009 CHARACTER TABULATION)
/// - " " (U+0020 SPACE)
/// - U+2029 PARAGRAPH SEPARATOR
/// - U+3000 IDEOGRAPHIC SPACE
public var isWhitespace: Bool {
return _firstScalar.properties.isWhitespace
}
/// A Boolean value indicating whether this character represents a newline.
///
/// For example, the following characters all represent newlines:
///
/// - "\n" (U+000A): LINE FEED (LF)
/// - U+000B: LINE TABULATION (VT)
/// - U+000C: FORM FEED (FF)
/// - "\r" (U+000D): CARRIAGE RETURN (CR)
/// - "\r\n" (U+000D U+000A): CR-LF
/// - U+0085: NEXT LINE (NEL)
/// - U+2028: LINE SEPARATOR
/// - U+2029: PARAGRAPH SEPARATOR
@inlinable
public var isNewline: Bool {
switch _firstScalar.value {
case 0x000A...0x000D /* LF ... CR */: return true
case 0x0085 /* NEXT LINE (NEL) */: return true
case 0x2028 /* LINE SEPARATOR */: return true
case 0x2029 /* PARAGRAPH SEPARATOR */: return true
default: return false
}
}
/// A Boolean value indicating whether this character represents a number.
///
/// For example, the following characters all represent numbers:
///
/// - "7" (U+0037 DIGIT SEVEN)
/// - "⅚" (U+215A VULGAR FRACTION FIVE SIXTHS)
/// - "㊈" (U+3288 CIRCLED IDEOGRAPH NINE)
/// - "𝟠" (U+1D7E0 MATHEMATICAL DOUBLE-STRUCK DIGIT EIGHT)
/// - "๒" (U+0E52 THAI DIGIT TWO)
public var isNumber: Bool {
return _firstScalar.properties.numericType != nil
}
/// A Boolean value indicating whether this character represents a whole
/// number.
///
/// For example, the following characters all represent whole numbers:
///
/// - "1" (U+0031 DIGIT ONE) => 1
/// - "५" (U+096B DEVANAGARI DIGIT FIVE) => 5
/// - "๙" (U+0E59 THAI DIGIT NINE) => 9
/// - "万" (U+4E07 CJK UNIFIED IDEOGRAPH-4E07) => 10_000
@inlinable
public var isWholeNumber: Bool {
return wholeNumberValue != nil
}
/// The numeric value this character represents, if it represents a whole
/// number.
///
/// If this character does not represent a whole number, or the value is too
/// large to represent as an `Int`, the value of this property is `nil`.
///
/// let chars: [Character] = ["4", "④", "万", "a"]
/// for ch in chars {
/// print(ch, "-->", ch.wholeNumberValue)
/// }
/// // Prints:
/// // 4 --> Optional(4)
/// // ④ --> Optional(4)
/// // 万 --> Optional(10000)
/// // a --> nil
public var wholeNumberValue: Int? {
guard _isSingleScalar else { return nil }
guard let value = _firstScalar.properties.numericValue else { return nil }
return Int(exactly: value)
}
/// A Boolean value indicating whether this character represents a
/// hexadecimal digit.
///
/// Hexadecimal digits include 0-9, Latin letters a-f and A-F, and their
/// fullwidth compatibility forms. To get the character's value, use the
/// `hexDigitValue` property.
@inlinable
public var isHexDigit: Bool {
return hexDigitValue != nil
}
/// The numeric value this character represents, if it is a hexadecimal digit.
///
/// Hexadecimal digits include 0-9, Latin letters a-f and A-F, and their
/// fullwidth compatibility forms. If the character does not represent a
/// hexadecimal digit, the value of this property is `nil`.
///
/// let chars: [Character] = ["1", "a", "F", "g"]
/// for ch in chars {
/// print(ch, "-->", ch.hexDigitValue)
/// }
/// // Prints:
/// // 1 --> Optional(1)
/// // a --> Optional(10)
/// // F --> Optional(15)
/// // g --> nil
public var hexDigitValue: Int? {
guard _isSingleScalar else { return nil }
let value = _firstScalar.value
switch value {
// DIGIT ZERO..DIGIT NINE
case 0x0030...0x0039: return Int(value &- 0x0030)
// LATIN CAPITAL LETTER A..LATIN CAPITAL LETTER F
case 0x0041...0x0046: return Int((value &+ 10) &- 0x0041)
// LATIN SMALL LETTER A..LATIN SMALL LETTER F
case 0x0061...0x0066: return Int((value &+ 10) &- 0x0061)
// FULLWIDTH DIGIT ZERO..FULLWIDTH DIGIT NINE
case 0xFF10...0xFF19: return Int(value &- 0xFF10)
// FULLWIDTH LATIN CAPITAL LETTER A..FULLWIDTH LATIN CAPITAL LETTER F
case 0xFF21...0xFF26: return Int((value &+ 10) &- 0xFF21)
// FULLWIDTH LATIN SMALL LETTER A..FULLWIDTH LATIN SMALL LETTER F
case 0xFF41...0xFF46: return Int((value &+ 10) &- 0xFF41)
default: return nil
}
}
/// A Boolean value indicating whether this character is a letter.
///
/// For example, the following characters are all letters:
///
/// - "A" (U+0041 LATIN CAPITAL LETTER A)
/// - "é" (U+0065 LATIN SMALL LETTER E, U+0301 COMBINING ACUTE ACCENT)
/// - "ϴ" (U+03F4 GREEK CAPITAL THETA SYMBOL)
/// - "ڈ" (U+0688 ARABIC LETTER DDAL)
/// - "日" (U+65E5 CJK UNIFIED IDEOGRAPH-65E5)
/// - "ᚨ" (U+16A8 RUNIC LETTER ANSUZ A)
public var isLetter: Bool {
return _firstScalar.properties.isAlphabetic
}
/// Returns an uppercased version of this character.
///
/// Because case conversion can result in multiple characters, the result
/// of `uppercased()` is a string.
///
/// let chars: [Character] = ["e", "é", "и", "π", "ß", "1"]
/// for ch in chars {
/// print(ch, "-->", ch.uppercased())
/// }
/// // Prints:
/// // e --> E
/// // é --> É
/// // и --> И
/// // π --> Π
/// // ß --> SS
/// // 1 --> 1
public func uppercased() -> String { return String(self).uppercased() }
/// Returns a lowercased version of this character.
///
/// Because case conversion can result in multiple characters, the result
/// of `lowercased()` is a string.
///
/// let chars: [Character] = ["E", "É", "И", "Π", "1"]
/// for ch in chars {
/// print(ch, "-->", ch.lowercased())
/// }
/// // Prints:
/// // E --> e
/// // É --> é
/// // И --> и
/// // Π --> π
/// // 1 --> 1
public func lowercased() -> String { return String(self).lowercased() }
@usableFromInline
internal var _isUppercased: Bool { return String(self) == self.uppercased() }
@usableFromInline
internal var _isLowercased: Bool { return String(self) == self.lowercased() }
/// A Boolean value indicating whether this character is considered uppercase.
///
/// Uppercase characters vary under case-conversion to lowercase, but not when
/// converted to uppercase. The following characters are all uppercase:
///
/// - "É" (U+0045 LATIN CAPITAL LETTER E, U+0301 COMBINING ACUTE ACCENT)
/// - "И" (U+0418 CYRILLIC CAPITAL LETTER I)
/// - "Π" (U+03A0 GREEK CAPITAL LETTER PI)
@inlinable
public var isUppercase: Bool {
if _fastPath(_isSingleScalar && _firstScalar.properties.isUppercase) {
return true
}
return _isUppercased && isCased
}
/// A Boolean value indicating whether this character is considered lowercase.
///
/// Lowercase characters change when converted to uppercase, but not when
/// converted to lowercase. The following characters are all lowercase:
///
/// - "é" (U+0065 LATIN SMALL LETTER E, U+0301 COMBINING ACUTE ACCENT)
/// - "и" (U+0438 CYRILLIC SMALL LETTER I)
/// - "π" (U+03C0 GREEK SMALL LETTER PI)
@inlinable
public var isLowercase: Bool {
if _fastPath(_isSingleScalar && _firstScalar.properties.isLowercase) {
return true
}
return _isLowercased && isCased
}
/// A Boolean value indicating whether this character changes under any form
/// of case conversion.
@inlinable
public var isCased: Bool {
if _fastPath(_isSingleScalar && _firstScalar.properties.isCased) {
return true
}
return !_isUppercased || !_isLowercased
}
/// A Boolean value indicating whether this character represents a symbol.
///
/// This property is `true` only for characters composed of scalars in the
/// "Math_Symbol", "Currency_Symbol", "Modifier_Symbol", or "Other_Symbol"
/// categories in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
///
/// For example, the following characters all represent symbols:
///
/// - "®" (U+00AE REGISTERED SIGN)
/// - "⌹" (U+2339 APL FUNCTIONAL SYMBOL QUAD DIVIDE)
/// - "⡆" (U+2846 BRAILLE PATTERN DOTS-237)
public var isSymbol: Bool {
return _firstScalar.properties.generalCategory._isSymbol
}
/// A Boolean value indicating whether this character represents a symbol
/// that naturally appears in mathematical contexts.
///
/// For example, the following characters all represent math symbols:
///
/// - "+" (U+002B PLUS SIGN)
/// - "∫" (U+222B INTEGRAL)
/// - "ϰ" (U+03F0 GREEK KAPPA SYMBOL)
///
/// The set of characters that have an `isMathSymbol` value of `true` is not
/// a strict subset of those for which `isSymbol` is `true`. This includes
/// characters used both as letters and commonly in mathematical formulas.
/// For example, "ϰ" (U+03F0 GREEK KAPPA SYMBOL) is considered both a
/// mathematical symbol and a letter.
///
/// This property corresponds to the "Math" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isMathSymbol: Bool {
return _firstScalar.properties.isMath
}
/// A Boolean value indicating whether this character represents a currency
/// symbol.
///
/// For example, the following characters all represent currency symbols:
///
/// - "$" (U+0024 DOLLAR SIGN)
/// - "¥" (U+00A5 YEN SIGN)
/// - "€" (U+20AC EURO SIGN)
public var isCurrencySymbol: Bool {
return _firstScalar.properties.generalCategory == .currencySymbol
}
/// A Boolean value indicating whether this character represents punctuation.
///
/// For example, the following characters all represent punctuation:
///
/// - "!" (U+0021 EXCLAMATION MARK)
/// - "؟" (U+061F ARABIC QUESTION MARK)
/// - "…" (U+2026 HORIZONTAL ELLIPSIS)
/// - "—" (U+2014 EM DASH)
/// - "“" (U+201C LEFT DOUBLE QUOTATION MARK)
public var isPunctuation: Bool {
return _firstScalar.properties.generalCategory._isPunctuation
}
}
| apache-2.0 | f4c0ccaccb5362417089330f560f57fd | 34.456647 | 84 | 0.611184 | 3.715324 | false | false | false | false |
nicolas-miari/EditableButton | EditableButton Demo App/EditableButton Demo App/ViewController.swift | 1 | 2714 | //
// ViewController.swift
// EditableButton Demo App
//
// Created by Nicolás Fernando Miari on 2017/01/31.
// Copyright © 2017 Nicolas Miari. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
/// Edited with keyboard
@IBOutlet weak var textButton: EditableButton!
/// Edited with date picker
@IBOutlet weak var dateButton: EditableButton!
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
configureTextButton()
configureDateButton()
}
private func configureTextButton() {
textButton.setTitle("Sample Text", for: .normal)
let textToolbar = UIToolbar(frame: CGRect.zero)
textToolbar.barStyle = .default
let textDoneButton = UIBarButtonItem(
barButtonSystemItem: .done,
target: self,
action: #selector(ViewController.textDone(_:)))
let textSpacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
textToolbar.items = [textSpacer, textDoneButton]
textToolbar.sizeToFit()
textButton.inputAccessoryView = textToolbar
}
private func configureDateButton() {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateButton.setTitle(dateFormatter.string(from: Date()), for: .normal)
let datePicker = UIDatePicker()
datePicker.datePickerMode = .date
dateButton.inputView = datePicker
datePicker.addTarget(self, action: #selector(ViewController.dateChanged(_:)), for: .valueChanged)
let dateToolbar = UIToolbar(frame: CGRect.zero)
dateToolbar.barStyle = .default
let dateDoneButton = UIBarButtonItem(
barButtonSystemItem: .done,
target: self,
action: #selector(ViewController.dateDone(_:)))
let dateSpacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
dateToolbar.items = [dateSpacer, dateDoneButton]
dateToolbar.sizeToFit()
dateButton.inputAccessoryView = dateToolbar
}
// MARK: - Control Actions
@IBAction func dateChanged(_ sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateButton.setTitle(dateFormatter.string(from: sender.date), for: .normal)
}
@IBAction func dateDone(_ sender: UIBarButtonItem) {
dateButton.resignFirstResponder()
}
@IBAction func textDone(_ sender: UIBarButtonItem) {
textButton.resignFirstResponder()
}
}
| mit | a224affc71176a260bb1cd3f63ae78d6 | 29.47191 | 105 | 0.667773 | 5.022222 | false | false | false | false |
EmmaXiYu/SE491 | DonateParkSpot/DonateParkSpot/SettingViewController.swift | 1 | 2518 | //
// SettingViewController.swift
// DonateParkSpot
//
// Created by Apple on 11/16/15.
// Copyright © 2015 Apple. All rights reserved.
//
import UIKit
import Parse
class SettingViewController: UIViewController {
@IBOutlet weak var Stepper: UIStepper!
var radium : Int = 0
@IBOutlet weak var RadiumLable: UILabel!
@IBOutlet weak var Menu: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad();
Menu.target = self.revealViewController()
Menu.action = Selector("revealToggle:")
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
self.title = "Settings"
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
Stepper.wraps = true
Stepper.autorepeat = true
Stepper.maximumValue = 100
var radiumUser = PFUser.currentUser()!["SearchRadium"] as? String
if radiumUser == nil
{
Stepper.value = 1
RadiumLable.text = "1"
}
else{
Stepper.value = Double(radiumUser!)!
RadiumLable.text = radiumUser}
}
@IBAction func StepperChangeValue(sender: UIStepper) {
RadiumLable.text = Int(sender.value).description
}
@IBAction func UpdateSettings(sender: AnyObject) {
let user = PFUser.currentUser()
user!["SearchRadium"] = RadiumLable.text
user!.saveInBackgroundWithBlock({
(success: Bool, error: NSError?) -> Void in
if error == nil {
self.displayMyAlertMessage("Updated sucessfully.")
self.viewDidLoad()
}else {
print(error)
self.displayMyAlertMessage("data uploaded fail" );
}
})
}
func displayMyAlertMessage(usermessage:String)
{
let myAlert=UIAlertController(title: "Alert", message:usermessage,
preferredStyle: UIAlertControllerStyle.Alert);
let okayAction=UIAlertAction(title: "Okay", style:UIAlertActionStyle.Default, handler:nil)
myAlert.addAction(okayAction);
self.presentViewController(myAlert, animated: true, completion: nil);}
}
| apache-2.0 | 61e710a0caf42b3d950f793a2b58d418 | 22.091743 | 98 | 0.554231 | 5.332627 | false | false | false | false |
Logicalshift/SwiftRebound | SwiftRebound/Binding/BindingContext.swift | 1 | 7657 | //
// BindingContext.swift
// SwiftRebound
//
// Created by Andrew Hunter on 10/07/2016.
//
//
import Foundation
///
/// Key used to retrieve the binding context on the current queue
///
private let _contextSpecificName = DispatchSpecificKey<QueueBindingContext>();
///
/// Semaphore used to decide which context queue to use
///
private let _queueSemaphore = DispatchSemaphore(value: 1);
///
/// Semaphore that is held as long as there are 0 queues available
///
private let _queueWaitSemaphore = DispatchSemaphore(value: 1);
///
/// Queues used to
///
private var _contextQueues = BindingQueuePool.createContextQueues(8);
///
/// Stores the binding context for the current queue
///
private class QueueBindingContext {
var context: BindingContext;
init(context: BindingContext) {
self.context = context;
}
}
///
/// Retrieves/returns binding context queues
///
private class BindingQueuePool {
///
/// Creates a set of context queues
///
static func createContextQueues(_ count: Int) -> [DispatchQueue] {
var result = [DispatchQueue]();
for _ in 0..<count {
let queue = BindingQueuePool.createQueueWithNewContext();
result.append(queue);
}
return result;
}
///
/// Creates a new dispatch queue with a new binding context
///
static func createQueueWithNewContext() -> DispatchQueue {
// Generate a new context
let newContext = BindingContext();
// Create a queue to use the context in
let queue = DispatchQueue(label: "io.logicalshift.binding", attributes: []);
let storage = QueueBindingContext(context: newContext);
queue.setSpecific(key: _contextSpecificName, value: storage);
return queue;
}
///
/// Retrieves a context queue, or waits for one to become available
///
static func retrieveContextQueue() -> DispatchQueue {
// Acquire the semaphore
_queueSemaphore.wait();
defer { _queueSemaphore.signal(); }
// If there are no queues available, then wait for someone to signal the wait semaphore
while _contextQueues.count <= 0 {
// Release the queue semaphore so that queues can be returned
_queueSemaphore.signal();
// Wait for the wait semaphore to be signaled (indicates a queue was returned to the pool)
_queueWaitSemaphore.wait();
_queueWaitSemaphore.signal();
// Re-acquire the queue semaphore so we can check for queues
_queueSemaphore.wait();
}
// If we got the semaphore, there is always at least one queue available in the list
let queue = _contextQueues.popLast()!;
// If we just got the last queue, then acquire the wait semaphore so we can block anything waiting for a queue
if _contextQueues.count == 0 {
_queueWaitSemaphore.wait();
}
// Release the semaphore and return the result
return queue;
}
///
/// Returns a context queue to the pool
///
static func returnContextQueue(_ queue: DispatchQueue) {
// Acquire the semaphore
_queueSemaphore.wait();
defer { _queueSemaphore.signal(); }
// If this is the first queue back in the pool, then wake any threads waiting for more queues
if _contextQueues.count == 0 {
_queueWaitSemaphore.signal();
}
// Return queue to the pool
_contextQueues.append(queue);
}
}
///
/// The binding context is used to keep track of what bindings are being accessed
///
public class BindingContext {
///
/// The dependencies that have been created in this context
///
fileprivate var _dependencies = CombinedChangeable();
///
/// Dependencies that we expected to see
///
fileprivate var _expectedDependencies: CombinedChangeable?;
///
/// Call BindingContext.current to get the binding context for the current queue
///
fileprivate init() {
}
fileprivate static var currentStorage: QueueBindingContext? {
@inline(__always)
get {
// Get the context pointer from the queue
return DispatchQueue.getSpecific(key: _contextSpecificName);
}
}
///
/// Retrieves the binding context for the current queue (or nil if there isn't one)
///
public static var current: BindingContext? {
get {
return currentStorage?.context;
}
}
///
/// Creates a new binding context (which can be retrieved with current) and performs the specified action with
/// it in effect
///
public static func withNewContext(_ action: () -> ()) {
if let existingStorage = BindingContext.currentStorage {
// Generate a new context
let oldContext = existingStorage.context;
let newContext = BindingContext();
// If there's an existing context, append the new context to it and perform the action rather than creating a whole new context
// Creating new contexts is expensive
existingStorage.context = newContext;
action();
existingStorage.context = oldContext;
} else {
// Current queue doesn't have any context stored, move on to a queue
// Could also call createQueueWithNewContext() here, but that is slow
let queue = BindingQueuePool.retrieveContextQueue();
defer { BindingQueuePool.returnContextQueue(queue); }
queue.sync(execute: {
let existingStorage = BindingContext.currentStorage!;
// Generate a new context
let oldContext = existingStorage.context;
let newContext = BindingContext();
// If there's an existing context, append the new context to it and perform the action rather than creating a whole new context
// Creating new contexts is expensive
existingStorage.context = newContext;
action();
existingStorage.context = oldContext;
});
}
}
///
/// Sets the set of expected dependencies for this item
///
public final func setExpectedDependencies(_ dependencies: CombinedChangeable) {
_expectedDependencies = dependencies;
}
///
/// Adds a new dependency to the current context (the current context item will be marked as changed)
///
public final func addDependency(_ dependentOn: Changeable) {
_dependencies.addChangeable(dependentOn);
}
///
/// The changeable objects that have been added as dependencies for this context
///
public final var dependencies: CombinedChangeable {
get {
return _dependencies;
}
}
///
/// True if the expected dependencies and the actual dependencies differ
///
public final var dependenciesDiffer: Bool {
get {
if let expectedDependencies = _expectedDependencies {
return !expectedDependencies.isSameAs(_dependencies);
} else {
return true;
}
}
}
///
/// Begins tracking a new set of dependencies
///
public final func resetDependencies() {
_dependencies = CombinedChangeable();
}
};
| apache-2.0 | 62332496a0f5b027228864b8781eb790 | 30.510288 | 143 | 0.603108 | 5.201766 | false | false | false | false |
IngmarStein/swift | validation-test/stdlib/CoreGraphics-verifyOnly.swift | 4 | 4339 | // RUN: %target-parse-verify-swift
// REQUIRES: objc_interop
import CoreGraphics
//===----------------------------------------------------------------------===//
// CGColorSpace
//===----------------------------------------------------------------------===//
// CGColorSpace.colorTable
// TODO: has memory issues as a runtime test, so make it verify-only for now
let table: [UInt8] = [0,0,0, 255,0,0, 0,0,255, 0,255,0,
255,255,0, 255,0,255, 0,255,255, 255,255,255]
let space = CGColorSpace(indexedBaseSpace: CGColorSpaceCreateDeviceRGB(),
last: table.count - 1, colorTable: table)!
// expectOptionalEqual(table, space.colorTable)
//===----------------------------------------------------------------------===//
// CGContext
//===----------------------------------------------------------------------===//
func testCGContext(context: CGContext, image: CGImage, glyph: CGGlyph) {
context.setLineDash(phase: 0.5, lengths: [0.1, 0.2])
context.move(to: CGPoint.zero)
context.addLine(to: CGPoint(x: 0.5, y: 0.5))
context.addCurve(to: CGPoint(x: 1, y: 1), control1: CGPoint(x: 1, y: 0), control2: CGPoint(x: 0, y: 1))
context.addQuadCurve(to: CGPoint(x: 0.5, y: 0.5), control: CGPoint(x: 0.5, y: 0))
context.addRects([CGRect(x: 0, y: 0, width: 100, height: 100)])
context.addLines(between: [CGPoint(x: 0.5, y: 0.5)])
context.addArc(center: CGPoint(x: 0.5, y: 0.5), radius: 1, startAngle: 0, endAngle: .pi, clockwise: false)
context.addArc(tangent1End: CGPoint(x: 1, y: 1), tangent2End: CGPoint(x: 0.5, y: 0.5), radius: 0.5)
context.fill([CGRect(x: 0, y: 0, width: 100, height: 100)])
context.fillPath()
context.fillPath(using: .evenOdd)
context.strokeLineSegments(between: [CGPoint(x: 0.5, y: 0.5), CGPoint(x: 0, y: 0.5)])
context.clip(to: [CGRect(x: 0, y: 0, width: 100, height: 100)])
context.clip()
context.clip(using: .evenOdd)
context.draw(image, in: CGRect(x: 0, y: 0, width: 100, height: 100), byTiling: true)
print(context.textPosition)
context.showGlyphs([glyph], at: [CGPoint(x: 0.5, y: 0.5)])
}
//===----------------------------------------------------------------------===//
// CGDirectDisplay
//===----------------------------------------------------------------------===//
#if os(macOS)
let (dx, dy) = CGGetLastMouseDelta()
#endif
//===----------------------------------------------------------------------===//
// CGImage
//===----------------------------------------------------------------------===//
func testCGImage(image: CGImage) -> CGImage? {
return image.copy(maskingColorComponents: [1, 0, 0])
}
//===----------------------------------------------------------------------===//
// CGLayer
//===----------------------------------------------------------------------===//
func testDrawLayer(in context: CGContext) {
let layer = CGLayer(context, size: CGSize(width: 512, height: 384),
auxiliaryInfo: nil)!
context.draw(layer, in: CGRect(origin: .zero, size: layer.size))
context.draw(layer, at: CGPoint(x: 20, y: 20))
}
func testCGPath(path: CGPath) {
let dashed = path.copy(dashingWithPhase: 1, lengths: [0.2, 0.3, 0.5])
let stroked = path.copy(strokingWithWidth: 1, lineCap: .butt,
lineJoin: .miter, miterLimit: 0.1)
let mutable = stroked.mutableCopy()!
// test inferred transform parameter for all below
print(path.contains(CGPoint(x: 0.5, y: 0.5)))
print(path.contains(CGPoint(x: 0.5, y: 0.5), using: .evenOdd))
mutable.move(to: .zero)
mutable.addLine(to: CGPoint(x: 0.5, y: 0.5))
mutable.addCurve(to: CGPoint(x: 1, y: 1), control1: CGPoint(x: 1, y: 0), control2: CGPoint(x: 0, y: 1))
mutable.addQuadCurve(to: CGPoint(x: 0.5, y: 0.5), control: CGPoint(x: 0.5, y: 0))
mutable.addRect(CGRect(x: 0, y: 0, width: 10, height: 10))
mutable.addRects([CGRect(x: 0, y: 0, width: 100, height: 100)])
mutable.addLines(between: [CGPoint(x: 0.5, y: 0.5)])
mutable.addEllipse(in: CGRect(x: 0, y: 0, width: 50, height: 70))
mutable.addArc(center: CGPoint(x: 0.5, y: 0.5), radius: 1, startAngle: 0, endAngle: .pi, clockwise: false)
mutable.addArc(tangent1End: CGPoint(x: 1, y: 1), tangent2End: CGPoint(x: 0.5, y: 0.5), radius: 0.5)
mutable.addRelativeArc(center: CGPoint(x: 1, y: 1), radius: 0.5,
startAngle: .pi, delta: .pi/2)
mutable.addPath(dashed)
}
| apache-2.0 | 1863939418f597076f2caa637d72cb04 | 33.436508 | 109 | 0.535607 | 3.460128 | false | false | false | false |
lukaszwas/mcommerce-api | Sources/App/Models/Stripe/Models/FruadDetails.swift | 1 | 1105 | //
// FruadDetails.swift
// Stripe
//
// Created by Anthony Castelli on 4/15/17.
//
//
import Foundation
import Vapor
/*
Fraud Details
https://stripe.com/docs/api/curl#charge_object-fraud_details
*/
public enum FraudReport: String {
case safe = "safe"
case fraudulent = "fraudulent"
}
public final class FraudDetails: StripeModelProtocol {
public var userReport: FraudReport?
public var stripeReport: FraudReport?
public init(node: Node) throws {
if let value: String? = try node.get("user_report") {
if let value = value {
self.userReport = FraudReport(rawValue: value)
}
}
if let value: String? = try node.get("stripe_report") {
if let value = value {
self.stripeReport = FraudReport(rawValue: value)
}
}
}
public func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
"user_report": self.userReport?.rawValue,
"stripe_report": self.stripeReport?.rawValue
])
}
}
| mit | 4ad65f7401ba2e84ccca913e5c6f2b72 | 22.510638 | 64 | 0.58733 | 4.003623 | false | false | false | false |
stomp1128/TIY-Assignments | 34-FirstContact/34-FirstContact/ContactListViewController.swift | 1 | 4102 | //
// ViewController.swift
// 34-FirstContact
//
// Created by Chris Stomp on 11/19/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import RealmSwift
class ContactListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
{
@IBOutlet weak var tableSortedSegementedControl: UISegmentedControl!
@IBOutlet weak var tableView: UITableView!
let realm = try! Realm()
var people: Results<Person>!
var currentCreateAction: UIAlertAction!
override func viewDidLoad()
{
super.viewDidLoad()
people = realm.objects(Person).sorted("name")
//self.navigationItem.leftBarButtonItem = self.editButtonItem();
}
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(true)
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return people.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("ContactCell", forIndexPath: indexPath)
let aPerson = people[indexPath.row]
cell.textLabel?.text = aPerson.name
cell.detailTextLabel?.text = "\(aPerson.friendCount)"
return cell
}
@IBAction func addFriend(sender: UIBarButtonItem)
{
let alertController = UIAlertController(title: "Add Person", message: "Type the person's name.", preferredStyle: UIAlertControllerStyle.Alert)
currentCreateAction = UIAlertAction(title: "Create", style: .Default) { (action) -> Void in
let personName = alertController.textFields?.first?.text
let newPerson = Person()
newPerson.name = personName!
try! self.realm.write({ () -> Void in
self.realm.add(newPerson) //saves person object to realm
self.tableView.reloadData() //reload to have person appear
})
}
alertController.addAction(currentCreateAction)//add createAction from above to the alert controller
currentCreateAction.enabled = false //set to false to start so button is off as default
alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
alertController.addTextFieldWithConfigurationHandler {(textField) -> Void in
textField.placeholder = "Name"
textField.addTarget(self, action: "personNameFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged) //runs every time the text field changes
}
self.presentViewController(alertController, animated: true, completion: nil) //causes pop up to appear
}
@IBAction func changeSortCriteria(sender: UISegmentedControl)
{
if sender.selectedSegmentIndex == 0
{
people = people.sorted("name")
}
else
{
people = people.sorted("contactCount", ascending: false)
}
tableView.reloadData()
}
func personNameFieldDidChange(sender: UITextField)
{
self.currentCreateAction.enabled = sender.text?.characters.count > 0 //set to false above in alert controller
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let personDetailVC = storyboard?.instantiateViewControllerWithIdentifier("PersonDetailViewController") as! PersonDetailViewController
personDetailVC.person = people[indexPath.row]
navigationController?.pushViewController(personDetailVC, animated: true)
}
}
| cc0-1.0 | ed85ee132c9ae2a392133bd1f2f8dc8f | 32.341463 | 165 | 0.664228 | 5.446215 | false | false | false | false |
intelygenz/NetClient-iOS | URLSession/NetURLSession+Download.swift | 1 | 1953 | //
// NetURLSession+Download.swift
// Net
//
// Created by Alex Rupérez on 17/3/17.
//
//
extension NetURLSession {
public func download(_ resumeData: Data) -> NetTask {
var netDownloadTask: NetTask?
let task = session.downloadTask(withResumeData: resumeData) { [weak self] (url, response, error) in
let netResponse = self?.netResponse(response, netDownloadTask, url)
let netError = self?.netError(error, url, response)
self?.process(netDownloadTask, netResponse, netError)
}
netDownloadTask = netTask(task)
return netDownloadTask!
}
public func download(_ request: NetRequest) -> NetTask {
var netDownloadTask: NetTask?
let task = session.downloadTask(with: urlRequest(request)) { [weak self] (url, response, error) in
let netResponse = self?.netResponse(response, netDownloadTask, url)
let netError = self?.netError(error, url, response)
self?.process(netDownloadTask, netResponse, netError)
}
netDownloadTask = netTask(task, request)
return netDownloadTask!
}
public func download(_ request: URLRequest) throws -> NetTask {
guard let netRequest = request.netRequest else {
throw netError(URLError(.badURL))!
}
return download(netRequest)
}
public func download(_ url: URL, cachePolicy: NetRequest.NetCachePolicy? = nil, timeoutInterval: TimeInterval? = nil) -> NetTask {
return download(netRequest(url, cache: cachePolicy, timeout: timeoutInterval))
}
public func download(_ urlString: String, cachePolicy: NetRequest.NetCachePolicy? = nil, timeoutInterval: TimeInterval? = nil) throws -> NetTask {
guard let url = URL(string: urlString) else {
throw netError(URLError(.badURL))!
}
return download(url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval)
}
}
| mit | 5a8a00728ccb9f1ef3fdb81a38577f31 | 37.27451 | 150 | 0.656762 | 4.406321 | false | false | false | false |
fgengine/quickly | Quickly/Compositions/Standart/QTitleButtonComposition.swift | 1 | 5587 | //
// Quickly
//
open class QTitleButtonComposable : QComposable {
public typealias Closure = (_ composable: QTitleButtonComposable) -> Void
public var titleStyle: QLabelStyleSheet
public var buttonStyle: QButtonStyleSheet
public var buttonIsHidden: Bool
public var buttonHeight: CGFloat
public var buttonSpacing: CGFloat
public var buttonIsSpinnerAnimating: Bool
public var buttonPressed: Closure
public init(
edgeInsets: UIEdgeInsets = UIEdgeInsets.zero,
titleStyle: QLabelStyleSheet,
buttonStyle: QButtonStyleSheet,
buttonIsHidden: Bool = false,
buttonHeight: CGFloat = 44,
buttonSpacing: CGFloat = 4,
buttonPressed: @escaping Closure
) {
self.titleStyle = titleStyle
self.buttonStyle = buttonStyle
self.buttonIsHidden = buttonIsHidden
self.buttonHeight = buttonHeight
self.buttonSpacing = buttonSpacing
self.buttonIsSpinnerAnimating = false
self.buttonPressed = buttonPressed
super.init(edgeInsets: edgeInsets)
}
}
open class QTitleButtonComposition< Composable: QTitleButtonComposable > : QComposition< Composable > {
public private(set) lazy var titleView: QLabel = {
let view = QLabel(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(view)
return view
}()
public private(set) lazy var buttonView: QButton = {
let view = QButton(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
view.setContentHuggingPriority(
horizontal: UILayoutPriority(rawValue: 252),
vertical: UILayoutPriority(rawValue: 252)
)
view.onPressed = { [weak self] _ in
guard let self = self, let composable = self.composable else { return }
composable.buttonPressed(composable)
}
self.contentView.addSubview(view)
return view
}()
private var _edgeInsets: UIEdgeInsets?
private var _buttonIsHidden: Bool?
private var _buttonSpacing: CGFloat?
private var _constraints: [NSLayoutConstraint] = [] {
willSet { self.contentView.removeConstraints(self._constraints) }
didSet { self.contentView.addConstraints(self._constraints) }
}
open override class func size(composable: Composable, spec: IQContainerSpec) -> CGSize {
let availableWidth = spec.containerSize.width - (composable.edgeInsets.left + composable.edgeInsets.right)
let textSize = composable.titleStyle.size(width: availableWidth)
return CGSize(
width: spec.containerSize.width,
height: composable.edgeInsets.top + max(textSize.height, composable.buttonHeight) + composable.edgeInsets.bottom
)
}
open override func preLayout(composable: Composable, spec: IQContainerSpec) {
if self._edgeInsets != composable.edgeInsets || self._buttonIsHidden != composable.buttonIsHidden || self._buttonSpacing != composable.buttonSpacing {
self._edgeInsets = composable.edgeInsets
self._buttonIsHidden = composable.buttonIsHidden
self._buttonSpacing = composable.buttonSpacing
var constraints: [NSLayoutConstraint] = [
self.titleView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top),
self.titleView.leadingLayout == self.contentView.leadingLayout.offset(composable.edgeInsets.left),
self.titleView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom),
self.buttonView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top),
self.buttonView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom),
self.buttonView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right)
]
if composable.buttonIsHidden == false {
constraints.append(contentsOf: [
self.titleView.trailingLayout == self.buttonView.leadingLayout.offset(-composable.buttonSpacing)
])
} else {
constraints.append(contentsOf: [
self.titleView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right)
])
}
self._constraints = constraints
}
}
open override func apply(composable: Composable, spec: IQContainerSpec) {
self.titleView.apply(composable.titleStyle)
self.buttonView.apply(composable.buttonStyle)
}
open override func postLayout(composable: Composable, spec: IQContainerSpec) {
self.buttonView.alpha = (composable.buttonIsHidden == false) ? 1 : 0
if composable.buttonIsSpinnerAnimating == true {
self.buttonView.startSpinner()
} else {
self.buttonView.stopSpinner()
}
}
public func isSpinnerAnimating() -> Bool {
return self.buttonView.isSpinnerAnimating()
}
public func startSpinner() {
if let composable = self.composable {
composable.buttonIsSpinnerAnimating = true
self.buttonView.startSpinner()
}
}
public func stopSpinner() {
if let composable = self.composable {
composable.buttonIsSpinnerAnimating = false
self.buttonView.stopSpinner()
}
}
}
| mit | afd1f8a03af8d26b409be528c2984374 | 39.485507 | 158 | 0.665652 | 5.3413 | false | false | false | false |
tidepool-org/nutshell-ios | Nutshell/Utilities and Extensions/NutUtils.swift | 1 | 11677 | /*
* Copyright (c) 2015, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import UIKit
import CoreData
import Photos
class NutUtils {
class func onIPad() -> Bool {
return UIDevice.current.userInterfaceIdiom == .pad
}
class func dispatchBoolToVoidAfterSecs(_ secs: Float, result: Bool, boolToVoid: @escaping (Bool) -> (Void)) {
let time = DispatchTime.now() + Double(Int64(secs * Float(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time){
boolToVoid(result)
}
}
class func delay(_ delay:Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
class func compressImage(_ image: UIImage) -> UIImage {
var actualHeight : CGFloat = image.size.height
var actualWidth : CGFloat = image.size.width
let maxHeight : CGFloat = 600.0
let maxWidth : CGFloat = 800.0
var imgRatio : CGFloat = actualWidth/actualHeight
let maxRatio : CGFloat = maxWidth/maxHeight
let compressionQuality : CGFloat = 0.5 //50 percent compression
if ((actualHeight > maxHeight) || (actualWidth > maxWidth)){
if(imgRatio < maxRatio){
//adjust height according to maxWidth
imgRatio = maxWidth / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = maxWidth;
}
else{
actualHeight = maxHeight;
actualWidth = maxWidth;
}
}
let rect = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight)
UIGraphicsBeginImageContext(rect.size)
image.draw(in: rect)
let img : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
let imageData = UIImageJPEGRepresentation(img, compressionQuality)
UIGraphicsEndImageContext()
NSLog("Compressed length: \(imageData!.count)")
return UIImage(data: imageData!)!
}
class func photosDirectoryPath() -> String? {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
var photoDirPath: String? = path + "/photos/" + NutDataController.controller().currentUserId! + "/"
let fm = FileManager.default
var dirExists = false
do {
_ = try fm.contentsOfDirectory(atPath: photoDirPath!)
//NSLog("Photos dir: \(dirContents)")
dirExists = true
} catch let error as NSError {
NSLog("Need to create dir at \(photoDirPath), error: \(error)")
}
if !dirExists {
do {
try fm.createDirectory(atPath: photoDirPath!, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
NSLog("Failed to create dir at \(photoDirPath), error: \(error)")
photoDirPath = nil
}
}
return photoDirPath
}
class func urlForNewPhoto() -> String {
let baseFilename = "file_" + UUID().uuidString + ".jpg"
return baseFilename
}
class func filePathForPhoto(_ photoUrl: String) -> String? {
if let dirPath = NutUtils.photosDirectoryPath() {
return dirPath + photoUrl
}
return nil
}
class func deleteLocalPhoto(_ url: String) {
if url.hasPrefix("file_") {
if let filePath = filePathForPhoto(url) {
let fm = FileManager.default
do {
try fm.removeItem(atPath: filePath)
NSLog("Deleted photo: \(url)")
} catch let error as NSError {
NSLog("Failed to delete photo at \(filePath), error: \(error)")
}
}
}
}
class func photoInfo(_ url: String) -> String {
var result = "url: " + url
if url.hasPrefix("file_") {
if let filePath = filePathForPhoto(url) {
let fm = FileManager.default
do {
let fileAttributes = try fm.attributesOfItem(atPath: filePath)
result += "size: " + String(describing: fileAttributes[FileAttributeKey.size])
result += "created: " + String(describing: fileAttributes[FileAttributeKey.creationDate])
} catch let error as NSError {
NSLog("Failed to get attributes for file \(filePath), error: \(error)")
}
}
}
return result
}
class func loadImage(_ url: String, imageView: UIImageView) {
if let image = UIImage(named: url) {
imageView.image = image
imageView.isHidden = false
} else if url.hasPrefix("file_") {
if let filePath = filePathForPhoto(url) {
let image = UIImage(contentsOfFile: filePath)
if let image = image {
imageView.isHidden = false
imageView.image = image
} else {
NSLog("Failed to load photo from local file: \(url)!")
}
}
} else {
if let nsurl = URL(string:url) {
let fetchResult = PHAsset.fetchAssets(withALAssetURLs: [nsurl], options: nil)
if let asset = fetchResult.firstObject {
// TODO: move this to file system! Would need current event to update it as well!
var targetSize = imageView.frame.size
// bump up resolution...
targetSize.height *= 2.0
targetSize.width *= 2.0
let options = PHImageRequestOptions()
PHImageManager.default().requestImage(for: asset, targetSize: targetSize, contentMode: PHImageContentMode.aspectFit, options: options) {
(result, info) in
if let result = result {
imageView.isHidden = false
imageView.image = result
}
}
}
}
}
}
class func dateFromJSON(_ json: String?) -> Date? {
if let json = json {
var result = jsonDateFormatter.date(from: json)
if result == nil {
result = jsonAltDateFormatter.date(from: json)
}
return result
}
return nil
}
class func dateToJSON(_ date: Date) -> String {
return jsonDateFormatter.string(from: date)
}
class func decimalFromJSON(_ json: String?) -> NSDecimalNumber? {
if let json = json {
return NSDecimalNumber(string: json)
}
return nil
}
/** Date formatter for JSON date strings */
class var jsonDateFormatter : DateFormatter {
struct Static {
static let instance: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
dateFormatter.timeZone = TimeZone(identifier: "GMT")
return dateFormatter
}()
}
return Static.instance
}
class var jsonAltDateFormatter : DateFormatter {
struct Static {
static let instance: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
dateFormatter.timeZone = TimeZone(identifier: "GMT")
return dateFormatter
}()
}
return Static.instance
}
/** Date formatter for date strings in the UI */
fileprivate class var dateFormatter : DateFormatter {
struct Static {
static let instance: DateFormatter = {
let df = DateFormatter()
df.dateFormat = Styles.uniformDateFormat
return df
}()
}
return Static.instance
}
// NOTE: these date routines are not localized, and do not take into account user preferences for date display.
/// Call setFormatterTimezone to set time zone before calling standardUIDayString or standardUIDateString
class func setFormatterTimezone(_ timezoneOffsetSecs: Int) {
let df = NutUtils.dateFormatter
df.timeZone = TimeZone(secondsFromGMT:timezoneOffsetSecs)
}
/// Returns delta time different due to a different daylight savings time setting for a date different from the current time, assuming the location-based time zone is the same as the current default.
class func dayLightSavingsAdjust(_ dateInPast: Date) -> Int {
let thisTimeZone = TimeZone.autoupdatingCurrent
let dstOffsetForThisDate = thisTimeZone.daylightSavingTimeOffset(for: Date())
let dstOffsetForPickerDate = thisTimeZone.daylightSavingTimeOffset(for: dateInPast)
let dstAdjust = dstOffsetForPickerDate - dstOffsetForThisDate
return Int(dstAdjust)
}
/// Returns strings like "Mar 17, 2016", "Today", "Yesterday"
/// Note: call setFormatterTimezone before this!
class func standardUIDayString(_ date: Date) -> String {
let df = NutUtils.dateFormatter
df.dateFormat = "MMM d, yyyy"
var dayString = df.string(from: date)
// If this year, remove year.
df.dateFormat = ", yyyy"
let thisYearString = df.string(from: Date())
dayString = dayString.replacingOccurrences(of: thisYearString, with: "")
// Replace with today, yesterday if appropriate: only check if it's in the last 48 hours
// TODO: look at using NSCalendar.startOfDayForDate and then time intervals to determine today, yesterday, Saturday, etc., back a week.
if (date.timeIntervalSinceNow > -48 * 60 * 60) {
if Calendar.current.isDateInToday(date) {
dayString = "Today"
} else if Calendar.current.isDateInYesterday(date) {
dayString = "Yesterday"
}
}
return dayString
}
/// Returns strings like "Yesterday at 9:17 am"
/// Note: call setFormatterTimezone before this!
class func standardUIDateString(_ date: Date) -> String {
let df = NutUtils.dateFormatter
let dayString = NutUtils.standardUIDayString(date)
// Figure the hour/minute part...
df.dateFormat = "h:mm a"
var hourString = df.string(from: date)
// Replace uppercase PM and AM with lowercase versions
hourString = hourString.replacingOccurrences(of: "PM", with: "pm", options: NSString.CompareOptions.literal, range: nil)
hourString = hourString.replacingOccurrences(of: "AM", with: "am", options: NSString.CompareOptions.literal, range: nil)
return dayString + " at " + hourString
}
}
| bsd-2-clause | a88e63ed9692b0cb877de7a3b2c11b6f | 39.686411 | 203 | 0.588764 | 5.125988 | false | false | false | false |
MrSongzj/MSDouYuZB | MSDouYuZB/MSDouYuZB/Classes/Tools/Constant.swift | 1 | 490 | //
// Constant.swift
// MSDouYuZB
//
// Created by jiayuan on 2017/7/31.
// Copyright © 2017年 mrsong. All rights reserved.
//
import UIKit
// bar 的尺寸
let kStatusBarH: CGFloat = 20
let kNavigationBarH: CGFloat = 44
let kNavigationBarBottom: CGFloat = kStatusBarH + kNavigationBarH
let kTabBarH: CGFloat = 49
// 屏幕尺寸
let kScreenS = UIScreen.main.bounds.size
let kScreenW = kScreenS.width
let kScreenH = kScreenS.height
// 一个像素
let kOnePX = 1/UIScreen.main.scale
| mit | 0620312e24a78c737c0090818fd54786 | 22.25 | 65 | 0.739785 | 3.444444 | false | false | false | false |
valine/octotap | octo-tap/octo-tap/ViewControllers/TemperatureViewController.swift | 1 | 4672 | // Copyright © 2017 Lukas Valine
//
// 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 Charts
class TemperatureViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, OctoPrintDelegate {
@IBOutlet weak var toolTableView: UITableView!
var temperatures:Array<OctoWSFrame.Temp>?
var cellsOpen = Array(repeating: true, count: 3)
//@IBOutlet weak var temperatureChart: TemperatureChart!
override func viewDidLoad() {
super.viewDidLoad()
toolTableView.delegate = self
toolTableView.dataSource = self
let octoprintWs = OctoWebSockets.instance
octoprintWs.delegate = self
// let populationData :[Int : Double] = [
// 1990 : 123456.0,
// 2000 : 233456.0,
// 2010 : 343456.0
// ]
//
// let ySeries = populationData.map { x, y in
// return ChartDataEntry(x: Double(x), y: y)
// }
//
// let data = LineChartData()
// let dataset = LineChartDataSet(values: ySeries, label: "Hello")
// dataset.colors = [NSUIColor.red]
// data.addDataSet(dataset)
//
// temperatureChart.data = data
//
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//TODO pull number of tools
return 3
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if cellsOpen[indexPath.item]{
return Constants.Dimensions.cellClosedHeight
} else {
return Constants.Dimensions.cellOpenHeight
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:ToolCell = self.toolTableView.dequeueReusableCell(withIdentifier: Constants.TabelCellResuseIDs.toolCell.rawValue) as! ToolCell!
if (indexPath.item == indexPath.endIndex) {
cell.hideExtruderControls()
cell.toolNameLabel.text = Constants.Strings.bedToolName
} else {
cell.toolNameLabel.text = "\(Constants.Strings.toolName) \(indexPath.item)"
let tap = UILongPressGestureRecognizer(target: self, action: #selector(tapHandler))
tap.minimumPressDuration = 0
cell.displayDetails.tag = indexPath.item
cell.displayDetails.addGestureRecognizer(tap)
}
cell.item = indexPath.item
if let temperaturesSet = temperatures {
switch indexPath.item {
case 0:
cell.actualTemperature.text = "\((temperaturesSet[0].tool0!.actual)!)°C"
case 1:
cell.actualTemperature.text = "\((temperaturesSet[0].tool1!.actual)!)°C"
case 2:
cell.actualTemperature.text = "\((temperaturesSet[0].bed!.actual)!)°C"
default:
print("error setting temp label")
}
}
return cell
}
func tapHandler(gesture: UITapGestureRecognizer) {
let tag = gesture.view?.tag
if gesture.state == .ended {
cellsOpen[tag!] = !cellsOpen[tag!]
toolTableView.beginUpdates()
toolTableView.endUpdates()
}
}
func refresh() {
if let temperaturesSet = temperatures {
if let tool0 = toolTableView.cellForRow(at: IndexPath(item: 0, section: 0)) as? ToolCell {
tool0.actualTemperature.text = "\((temperaturesSet[0].tool0!.actual)!)°C"
if (temperaturesSet[0].tool0!.target)! == 0 {
tool0.targetTemperature.placeholder = "Off"
} else {
tool0.targetTemperature.placeholder = "\((temperaturesSet[0].tool0!.target)!)°C"
}
}
if let tool1 = toolTableView.cellForRow(at: IndexPath(item: 1, section: 0)) as? ToolCell {
tool1.actualTemperature.text = "\((temperaturesSet[0].tool1!.actual)!)°C"
if (temperaturesSet[0].tool1!.target)! == 0 {
tool1.targetTemperature.placeholder = "Off"
} else {
tool1.targetTemperature.placeholder = "\((temperaturesSet[0].tool1!.target)!)°C"
}
}
if let bed = toolTableView.cellForRow(at: IndexPath(item: 2, section: 0)) as? ToolCell {
bed.actualTemperature.text = "\((temperaturesSet[0].bed!.actual)!)°C"
if (temperaturesSet[0].bed!.target)! == 0 {
bed.targetTemperature.placeholder = "Off"
} else {
bed.targetTemperature.placeholder = "\((temperaturesSet[0].bed!.target)!)°C"
}
}
}
}
func temperatureUpdate(temp: Array<OctoWSFrame.Temp>) {
temperatures = temp
refresh()
}
}
| apache-2.0 | 38bfc04f26b54e4573d2872cc536d69b | 28.506329 | 138 | 0.692836 | 3.531818 | false | false | false | false |
yanfeng0107/ios-charts | Charts/Classes/Data/BarLineScatterCandleChartDataSet.swift | 59 | 1086 | //
// BarLineScatterCandleChartDataSet.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 UIKit
public class BarLineScatterCandleChartDataSet: ChartDataSet
{
public var highlightColor = UIColor(red: 255.0/255.0, green: 187.0/255.0, blue: 115.0/255.0, alpha: 1.0)
public var highlightLineWidth = CGFloat(0.5)
public var highlightLineDashPhase = CGFloat(0.0)
public var highlightLineDashLengths: [CGFloat]?
// MARK: NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
var copy = super.copyWithZone(zone) as! BarLineScatterCandleChartDataSet
copy.highlightColor = highlightColor
copy.highlightLineWidth = highlightLineWidth
copy.highlightLineDashPhase = highlightLineDashPhase
copy.highlightLineDashLengths = highlightLineDashLengths
return copy
}
}
| apache-2.0 | 6ff8196a630d28f0eefe73dc6ecc785b | 30.028571 | 108 | 0.720994 | 4.621277 | false | false | false | false |
CoderST/DYZB | DYZB/DYZB/Class/Profile/Controller/MyAccountViewController.swift | 1 | 2854 | //
// MyAccountViewController.swift
// DYZB
//
// Created by xiudou on 2017/7/20.
// Copyright © 2017年 xiudo. All rights reserved.
// 我的账户
import UIKit
class MyAccountViewController: ProfileInforViewController {
fileprivate lazy var baseViewModel : BaseViewModel = BaseViewModel()
override func viewDidLoad() {
// super.viewDidLoad()
automaticallyAdjustsScrollViewInsets = false
view.addSubview(collectionView)
title = "我的账户"
// 消费记录
let cost = ArrowItem(icon: "image_cost_record", title: "消费记录", VcClass: MyTaskViewController.self)
let costModelFrame = SettingItemFrame(cost)
// 票务中心
let ticket = ArrowItem(icon: "Image_ticket", title: "票务中心", VcClass: CostRecordViewController.self)
let ticketModelFrame = SettingItemFrame(ticket)
// 我的淘宝订单
let myorder = ArrowItem(icon: "usercenter_myorder", title: "我的淘宝订单", VcClass: CostRecordViewController.self)
let myorderModelFrame = SettingItemFrame(myorder)
let settingGroup : SettingGroup = SettingGroup()
settingGroup.settingGroup = [costModelFrame,ticketModelFrame,myorderModelFrame]
groups.removeAll()
groups.append(settingGroup)
collectionView.reloadData()
}
}
extension MyAccountViewController {
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let group = groups[indexPath.section]
let settingItemFrame = group.settingGroup[indexPath.item]
if settingItemFrame.settingItem.optionHandler != nil {
settingItemFrame.settingItem.optionHandler!()
}else if settingItemFrame.settingItem is ArrowItem{
let arrowItem = settingItemFrame.settingItem as! ArrowItem
guard let desClass = arrowItem.VcClass else { return }
guard let desVCType = desClass as? UIViewController.Type else { return }
let desVC = desVCType.init()
desVC.title = arrowItem.title
// 消费记录
if desVC is MyTaskViewController{
let desvc = desVC as! MyTaskViewController
baseViewModel.updateDate({
guard let time = userDefaults.object(forKey: dateKey) as? Int else { return }
desvc.open_url = "http://apiv2.douyucdn.cn/H5nc/welcome/to?aid=ios&client_sys=ios&id=1&time=\(time)&token=\(TOKEN)&auth=\(AUTH)"
self.navigationController?.pushViewController(desVC, animated: true)
})
}else{
navigationController?.pushViewController(desVC, animated: true)
}
}
}
}
| mit | deb57895a16ec6c45a00d94e5016e475 | 37.486111 | 148 | 0.635872 | 4.580165 | false | false | false | false |
stevebrambilla/autolayout-expressions | Tests/LayoutExpressionsTests/LayoutBuilderTests.swift | 2 | 3590 | // Copyright © 2019 Steve Brambilla. All rights reserved.
import LayoutExpressions
import XCTest
class LayoutBuilderTests: XCTestCase {
var container = View()
var subview = View()
override func setUp() {
super.setUp()
container = View()
subview = View()
container.addSubview(subview)
}
func testSingleExpression() {
let constraints = Constraint.evaluateLayout {
subview.anchors.top == container.anchors.top
}
let top = extractSingleConstraint(constraints, withAttributes: .top)
assertConstraint(top, first: subview, second: container)
}
func testMultipleExpressions() {
let constraints = Constraint.evaluateLayout {
subview.anchors.top == container.anchors.top
subview.anchors.bottom == container.anchors.bottom
}
let top = extractSingleConstraint(constraints, withAttributes: .top)
assertConstraint(top, first: subview, second: container)
let bottom = extractSingleConstraint(constraints, withAttributes: .bottom)
assertConstraint(bottom, first: subview, second: container)
}
func testIfConditionTrue() {
let pinToTop = true
let constraints = Constraint.evaluateLayout {
if pinToTop {
subview.anchors.top == container.anchors.top
} else {
subview.anchors.bottom == container.anchors.bottom
}
}
XCTAssert(constraints.count == 1)
let top = extractSingleConstraint(constraints, withAttributes: .top)
assertConstraint(top, first: subview, second: container)
}
func testIfConditionFalse() {
let pinToTop = false
let constraints = Constraint.evaluateLayout {
if pinToTop {
subview.anchors.top == container.anchors.top
} else {
subview.anchors.bottom == container.anchors.bottom
}
}
XCTAssert(constraints.count == 1)
let bottom = extractSingleConstraint(constraints, withAttributes: .bottom)
assertConstraint(bottom, first: subview, second: container)
}
func testIfWithoutElse() {
var pinToTop = true
let constraintsShouldHaveOne = Constraint.evaluateLayout {
if pinToTop {
subview.anchors.top == container.anchors.top
}
}
XCTAssert(constraintsShouldHaveOne.count == 1)
pinToTop = false
let constraintsShouldBeEmpty = Constraint.evaluateLayout {
if pinToTop {
subview.anchors.top == container.anchors.top
}
}
XCTAssert(constraintsShouldBeEmpty.isEmpty)
}
func testMultiConditionIf() {
let stringAttribute = "leading"
let constraints = Constraint.evaluateLayout {
if stringAttribute == "top" {
subview.anchors.top == container.anchors.top
} else if stringAttribute == "leading" {
subview.anchors.leading == container.anchors.leading
} else {
subview.anchors.bottom == container.anchors.bottom
}
}
XCTAssert(constraints.count == 1)
let leading = extractSingleConstraint(constraints, withAttributes: .leading)
assertConstraint(leading, first: subview, second: container)
}
}
| mit | 4928320ffef279ffba5f66f5e02a3d2b | 30.761062 | 84 | 0.587072 | 5.388889 | false | true | false | false |
binarylevel/Tinylog-iOS | Tinylog/View Controllers/Tasks/TLITasksViewController.swift | 1 | 38213 | //
// TLITasksViewController.swift
// Tinylog
//
// Created by Spiros Gerokostas on 18/10/15.
// Copyright © 2015 Spiros Gerokostas. All rights reserved.
//
import UIKit
import TTTAttributedLabel
class TLITasksViewController: TLICoreDataTableViewController, TLIAddTaskViewDelegate, TTTAttributedLabelDelegate, TLIEditTaskViewControllerDelegate {
let kCellIdentifier = "CellIdentifier"
let kReminderCellIdentifier = "ReminderCellIdentifier"
var list:TLIList? = nil
var offscreenCells:NSMutableDictionary?
var estimatedRowHeightCache:NSMutableDictionary?
var currentIndexPath:NSIndexPath?
var focusTextField:Bool?
var topConstraint: NSLayoutConstraint?
var heightConstraint: NSLayoutConstraint?
var tasksFooterView:TLITasksFooterView? = {
let tasksFooterView = TLITasksFooterView.newAutoLayoutView()
return tasksFooterView
}()
var orientation:String = "portrait"
var enableDidSelectRowAtIndexPath = true
var didSetupContraints = false
lazy var addTransparentLayer:UIView? = {
let addTransparentLayer:UIView = UIView.newAutoLayoutView()
addTransparentLayer.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleBottomMargin]
addTransparentLayer.backgroundColor = UIColor(white: 1.0, alpha: 0.9)
addTransparentLayer.alpha = 0.0
let tapGestureRecognizer:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(TLITasksViewController.transparentLayerTapped(_:)))
addTransparentLayer.addGestureRecognizer(tapGestureRecognizer)
return addTransparentLayer
}()
lazy var noTasksLabel:UILabel? = {
let noTasksLabel:UILabel = UILabel.newAutoLayoutView()
noTasksLabel.font = UIFont.regularFontWithSize(18.0)
noTasksLabel.textColor = UIColor.tinylogTextColor()
noTasksLabel.text = "Tap text field to create a new task."
noTasksLabel.hidden = true
return noTasksLabel
}()
lazy var noListSelected:UILabel? = {
let noListSelected:UILabel = UILabel.newAutoLayoutView()
noListSelected.font = UIFont.regularFontWithSize(16.0)
noListSelected.textColor = UIColor.tinylogTextColor()
noListSelected.textAlignment = NSTextAlignment.Center
noListSelected.text = "No List Selected"
noListSelected.sizeToFit()
noListSelected.hidden = true
return noListSelected
}()
lazy var addTaskView:TLIAddTaskView? = {
let header:TLIAddTaskView = TLIAddTaskView(frame: CGRectMake(0.0, 0.0, self.tableView!.bounds.size.width, TLIAddTaskView.height()))
header.closeButton?.addTarget(self, action: #selector(TLITasksViewController.transparentLayerTapped(_:)), forControlEvents: UIControlEvents.TouchDown)
header.delegate = self
return header
}()
func getDetailViewSize() -> CGSize {
var detailViewController: UIViewController
if (self.splitViewController?.viewControllers.count > 1) {
detailViewController = (self.splitViewController?.viewControllers[1])!
} else {
detailViewController = (self.splitViewController?.viewControllers[0])!
}
return detailViewController.view.frame.size
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
var managedObject:TLIList? {
willSet {
if newValue != nil {
self.noListSelected?.hidden = true
} else {
self.noListSelected?.hidden = false
}
let cdc:TLICDController = TLICDController.sharedInstance
let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "Task")
let positionDescriptor = NSSortDescriptor(key: "position", ascending: false)
let displayLongTextDescriptor = NSSortDescriptor(key: "displayLongText", ascending: true)
fetchRequest.sortDescriptors = [positionDescriptor, displayLongTextDescriptor]
fetchRequest.predicate = NSPredicate(format: "list = %@ AND archivedAt = nil", newValue!)
fetchRequest.fetchBatchSize = 20
self.frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: cdc.context!, sectionNameKeyPath: nil, cacheName: nil)
self.frc?.delegate = self
do {
try self.frc?.performFetch()
self.tableView?.reloadData()
self.checkForTasks()
updateFooterInfoText(newValue!)
} catch let error as NSError {
fatalError(error.localizedDescription)
}
}
didSet {
}
}
func configureFetch() {
if list == nil {
return
}
let cdc:TLICDController = TLICDController.sharedInstance
let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "Task")
let positionDescriptor = NSSortDescriptor(key: "position", ascending: false)
let displayLongTextDescriptor = NSSortDescriptor(key: "displayLongText", ascending: true)
fetchRequest.sortDescriptors = [positionDescriptor, displayLongTextDescriptor]
fetchRequest.predicate = NSPredicate(format: "list = %@ AND archivedAt = nil", self.list!)
fetchRequest.fetchBatchSize = 20
self.frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: cdc.context!, sectionNameKeyPath: nil, cacheName: nil)
self.frc?.delegate = self
do {
try self.frc?.performFetch()
} catch let error as NSError {
fatalError(error.localizedDescription)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(red: 250.0 / 255.0, green: 250.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0)
self.tableView?.backgroundColor = UIColor(red: 250.0 / 255.0, green: 250.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0)
self.tableView?.separatorStyle = UITableViewCellSeparatorStyle.None
self.tableView?.registerClass(TLITaskTableViewCell.self, forCellReuseIdentifier: kCellIdentifier)
self.tableView?.registerClass(TLIReminderTaskTableViewCell.self, forCellReuseIdentifier: kReminderCellIdentifier)
self.tableView?.rowHeight = UITableViewAutomaticDimension
self.tableView?.estimatedRowHeight = TLITableViewCell.cellHeight()
self.tableView?.frame = CGRectMake(0.0, 0.0, self.view.frame.size.width, self.view.frame.size.height - 50.0)
tasksFooterView?.exportTasksButton?.addTarget(self, action: #selector(TLITasksViewController.exportTasks(_:)), forControlEvents: UIControlEvents.TouchDown)
tasksFooterView?.archiveButton?.addTarget(self, action: #selector(TLITasksViewController.displayArchive(_:)), forControlEvents: UIControlEvents.TouchDown)
let IS_IPAD = (UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad)
if IS_IPAD {
self.title = managedObject?.title
} else {
self.title = list?.title
configureFetch()
updateFooterInfoText(list!)
}
setEditing(false, animated: false)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TLITasksViewController.onChangeSize(_:)), name: UIContentSizeCategoryDidChangeNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TLITasksViewController.syncActivityDidEndNotification(_:)), name: IDMSyncActivityDidEndNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TLITasksViewController.syncActivityDidBeginNotification(_:)), name: IDMSyncActivityDidBeginNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TLITasksViewController.appBecomeActive), name: UIApplicationDidBecomeActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TLITasksViewController.updateFonts), name: TLINotifications.kTLIFontDidChangeNotification as String, object: nil)
}
func updateFonts() {
self.tableView?.reloadData()
}
func appBecomeActive() {
startSync()
}
func startSync() {
let syncManager:TLISyncManager = TLISyncManager.sharedSyncManager()
if syncManager.canSynchronize() {
syncManager.synchronizeWithCompletion { (error) -> Void in
}
}
}
func updateFooterInfoText(list:TLIList) {
//Fetch all objects from list
let cdc:TLICDController = TLICDController.sharedInstance
let fetchRequestTotal:NSFetchRequest = NSFetchRequest(entityName: "Task")
let positionDescriptor = NSSortDescriptor(key: "position", ascending: false)
fetchRequestTotal.sortDescriptors = [positionDescriptor]
fetchRequestTotal.predicate = NSPredicate(format: "archivedAt = nil AND list = %@", list)
fetchRequestTotal.fetchBatchSize = 20
do {
let results:NSArray = try cdc.context!.executeFetchRequest(fetchRequestTotal)
let fetchRequestCompleted:NSFetchRequest = NSFetchRequest(entityName: "Task")
fetchRequestCompleted.sortDescriptors = [positionDescriptor]
fetchRequestCompleted.predicate = NSPredicate(format: "archivedAt = nil AND completed = %@ AND list = %@", NSNumber(bool: false), list)
fetchRequestCompleted.fetchBatchSize = 20
let resultsCompleted:NSArray = try cdc.context!.executeFetchRequest(fetchRequestCompleted)
let total:Int = results.count - resultsCompleted.count
if total == results.count {
tasksFooterView?.updateInfoLabel("All tasks completed")
} else {
if total > 1 {
tasksFooterView?.updateInfoLabel("\(total) completed tasks")
} else {
tasksFooterView?.updateInfoLabel("\(total) completed task")
}
}
} catch let error as NSError {
fatalError(error.localizedDescription)
}
}
func syncActivityDidEndNotification(notification:NSNotification) {
if TLISyncManager.sharedSyncManager().canSynchronize() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
checkForTasks()
}
}
func syncActivityDidBeginNotification(notification:NSNotification) {
if TLISyncManager.sharedSyncManager().canSynchronize() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
checkForTasks()
}
}
override func loadView() {
super.loadView()
view.addSubview(noListSelected!)
view.addSubview(noTasksLabel!)
view.addSubview(tasksFooterView!)
view.addSubview(addTransparentLayer!)
view.setNeedsUpdateConstraints()
}
override func updateViewConstraints() {
if !didSetupContraints {
noListSelected?.autoCenterInSuperview()
noTasksLabel?.autoCenterInSuperview()
tasksFooterView?.autoMatchDimension(.Width, toDimension: .Width, ofView: self.view)
tasksFooterView?.autoSetDimension(.Height, toSize: 51.0)
tasksFooterView?.autoPinEdgeToSuperviewEdge(.Left)
tasksFooterView?.autoPinEdgeToSuperviewEdge(.Bottom)
addTransparentLayer?.autoMatchDimension(.Width, toDimension: .Width, ofView: self.view)
didSetupContraints = true
}
topConstraint?.autoRemove()
heightConstraint?.autoRemove()
var posY:CGFloat = 0.0
if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad {
if self.orientation == "portrait" {
posY = 64.0 + TLIAddTaskView.height()
} else {
posY = 64.0 + TLIAddTaskView.height()
}
} else {
if self.orientation == "portrait" {
posY = 64.0 + TLIAddTaskView.height()
} else {
posY = 32.0 + TLIAddTaskView.height()
}
}
topConstraint = addTransparentLayer?.autoPinEdgeToSuperviewEdge(.Top, withInset: posY)
heightConstraint = addTransparentLayer?.autoMatchDimension(.Height, toDimension: .Height, ofView: self.view, withOffset: -51.0 - posY)
super.updateViewConstraints()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.checkForTasks()
let IS_IPAD = (UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad)
if IS_IPAD {
self.noListSelected?.hidden = false
}
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
setEditing(false, animated: false)
}
func displayArchive(button:TLIArchiveButton) {
let viewController:TLIArchiveTasksViewController = TLIArchiveTasksViewController()
let IS_IPAD = (UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad)
if IS_IPAD {
viewController.list = managedObject
} else {
viewController.list = list
}
let navigationController:UINavigationController = UINavigationController(rootViewController: viewController);
navigationController.modalPresentationStyle = UIModalPresentationStyle.FormSheet;
self.navigationController?.presentViewController(navigationController, animated: true, completion: nil)
TLIAnalyticsTracker.trackMixpanelEvent("Display Archive Tasks", properties: nil)
}
func checkForTasks() {
if self.frc?.fetchedObjects?.count == 0 {
self.noTasksLabel?.hidden = false
} else {
self.noTasksLabel?.hidden = true
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if (focusTextField != nil) {
self.addTaskView?.textField?.becomeFirstResponder()
focusTextField = false
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)) {
self.orientation = "landscape"
}
if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)) {
self.orientation = "portrait"
}
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
// Code here will execute before the rotation begins.
// Equivalent to placing it in the deprecated method -[willRotateToInterfaceOrientation:duration:]
coordinator.animateAlongsideTransition({ (context) -> Void in
// Place code here to perform animations during the rotation.
// You can pass nil for this closure if not necessary.
}, completion: { (context) -> Void in
self.tableView?.reloadData()
self.view.setNeedsUpdateConstraints()
})
}
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
if editing {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(TLITasksViewController.toggleEditMode(_:)))
} else {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Edit", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(TLITasksViewController.toggleEditMode(_:)))
}
}
func toggleEditMode(sender:UIBarButtonItem) {
setEditing(!editing, animated: true)
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
let archiveRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Archive", handler:{action, indexpath in
let task:TLITask = self.frc?.objectAtIndexPath(indexpath) as! TLITask
let cdc:TLICDController = TLICDController.sharedInstance
//First we must delete local notification if reminder exists
if let _ = task.reminder {
let app:UIApplication = UIApplication.sharedApplication()
let notifications:NSArray = app.scheduledLocalNotifications!
for notification in notifications {
let temp:UILocalNotification = notification as! UILocalNotification
if let userInfo:NSDictionary = temp.userInfo {
let uniqueIdentifier: String? = userInfo.valueForKey("uniqueIdentifier") as? String
if let taskNotification = task.notification {
if uniqueIdentifier == taskNotification.uniqueIdentifier {
let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "Notification")
let positionDescriptor = NSSortDescriptor(key: "uniqueIdentifier", ascending: false)
fetchRequest.sortDescriptors = [positionDescriptor]
fetchRequest.predicate = NSPredicate(format: "uniqueIdentifier = %@", uniqueIdentifier!)
fetchRequest.fetchLimit = 1
do {
let results:NSArray = try cdc.context!.executeFetchRequest(fetchRequest)
let notification:TLINotification = results.lastObject as! TLINotification
cdc.context?.deleteObject(notification)
app.cancelLocalNotification(temp)
} catch let error as NSError {
fatalError(error.localizedDescription)
}
}
}
}
}
}
task.archivedAt = NSDate()
//update counter list
//Fetch all objects from list
let fetchRequestTotal:NSFetchRequest = NSFetchRequest(entityName: "Task")
let positionDescriptor = NSSortDescriptor(key: "position", ascending: false)
fetchRequestTotal.sortDescriptors = [positionDescriptor]
fetchRequestTotal.predicate = NSPredicate(format: "archivedAt = nil AND list = %@", task.list!)
fetchRequestTotal.fetchBatchSize = 20
do {
let results:NSArray = try cdc.context!.executeFetchRequest(fetchRequestTotal)
let fetchRequestCompleted:NSFetchRequest = NSFetchRequest(entityName: "Task")
fetchRequestCompleted.sortDescriptors = [positionDescriptor]
fetchRequestCompleted.predicate = NSPredicate(format: "archivedAt = nil AND completed = %@ AND list = %@", NSNumber(bool: true), task.list!)
fetchRequestCompleted.fetchBatchSize = 20
let resultsCompleted:NSArray = try cdc.context!.executeFetchRequest(fetchRequestCompleted)
let total:Int = results.count - resultsCompleted.count
task.list!.total = total
cdc.backgroundSaveContext()
self.setEditing(false, animated: true)
self.checkForTasks()
} catch let error as NSError {
fatalError(error.localizedDescription)
}
});
archiveRowAction.backgroundColor = UIColor.tinylogMainColor()
return [archiveRowAction];
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func taskAtIndexPath(indexPath:NSIndexPath)->TLITask? {
let task = self.frc?.objectAtIndexPath(indexPath) as! TLITask!
return task
}
func updateTask(task:TLITask, sourceIndexPath:NSIndexPath, destinationIndexPath:NSIndexPath) {
var fetchedTasks:[AnyObject] = self.frc?.fetchedObjects as [AnyObject]!
fetchedTasks = fetchedTasks.filter() { $0 as! TLITask != task }
let index = destinationIndexPath.row
fetchedTasks.insert(task, atIndex: index)
var i:NSInteger = fetchedTasks.count
for (_, task) in fetchedTasks.enumerate() {
let t = task as! TLITask
t.position = NSNumber(integer: i--)
}
}
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
if sourceIndexPath.row == destinationIndexPath.row {
return;
}
//Disable fetched results controller
self.ignoreNextUpdates = true
let task = self.taskAtIndexPath(sourceIndexPath)!
updateTask(task, sourceIndexPath: sourceIndexPath, destinationIndexPath: destinationIndexPath)
let cdc:TLICDController = TLICDController.sharedInstance
cdc.backgroundSaveContext()
}
func onChangeSize(notification:NSNotification) {
self.tableView?.reloadData()
}
override func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let task:TLITask = self.frc?.objectAtIndexPath(indexPath) as! TLITask
if cell is TLIReminderTaskTableViewCell {
let taskReminderTableViewCell:TLIReminderTaskTableViewCell = cell as! TLIReminderTaskTableViewCell
taskReminderTableViewCell.currentTask = task
} else if cell is TLITaskTableViewCell {
let taskTableViewCell:TLITaskTableViewCell = cell as! TLITaskTableViewCell
taskTableViewCell.currentTask = task
}
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if enableDidSelectRowAtIndexPath {
return self.addTaskView
}
return nil
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if enableDidSelectRowAtIndexPath {
return TLIAddTaskView.height()
}
return 0
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return floor(getEstimatedCellHeightFromCache(indexPath, defaultHeight: 52)!)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let task:TLITask = self.frc?.objectAtIndexPath(indexPath) as! TLITask
if task.reminder != nil {
let cell:TLIReminderTaskTableViewCell = tableView.dequeueReusableCellWithIdentifier(kReminderCellIdentifier) as! TLIReminderTaskTableViewCell!
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.checkBoxButton.addTarget(self, action: #selector(TLITasksViewController.toggleComplete(_:)), forControlEvents: UIControlEvents.TouchUpInside)
cell.taskLabel.delegate = self
configureCell(cell, atIndexPath: indexPath)
let height = isEstimatedRowHeightInCache(indexPath)
if (height != nil) {
let cellSize:CGSize = cell.systemLayoutSizeFittingSize(CGSizeMake(self.view.frame.size.width, 0), withHorizontalFittingPriority: 1000, verticalFittingPriority: 52)
putEstimatedCellHeightToCache(indexPath, height: cellSize.height)
}
return cell
} else {
let cell:TLITaskTableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as! TLITaskTableViewCell!
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.checkBoxButton.addTarget(self, action: #selector(TLITasksViewController.toggleComplete(_:)), forControlEvents: UIControlEvents.TouchUpInside)
cell.taskLabel.delegate = self
configureCell(cell, atIndexPath: indexPath)
let height = isEstimatedRowHeightInCache(indexPath)
if (height != nil) {
let cellSize:CGSize = cell.systemLayoutSizeFittingSize(CGSizeMake(self.view.frame.size.width, 0), withHorizontalFittingPriority: 1000, verticalFittingPriority: 52)
putEstimatedCellHeightToCache(indexPath, height: cellSize.height)
}
return cell
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if enableDidSelectRowAtIndexPath {
let itemID:NSManagedObjectID = self.frc!.objectAtIndexPath(indexPath).objectID!
do {
let task:TLITask = try self.frc?.managedObjectContext.existingObjectWithID(itemID) as! TLITask
dispatch_async(dispatch_get_main_queue()) {
self.editTask(task, indexPath: indexPath)
}
} catch let error as NSError {
fatalError(error.localizedDescription)
}
}
}
func toggleComplete(button:TLICheckBoxButton) {
if enableDidSelectRowAtIndexPath {
let cdc:TLICDController = TLICDController.sharedInstance
let button:TLICheckBoxButton = button as TLICheckBoxButton
let indexPath:NSIndexPath? = self.tableView?.indexPathForCell(button.tableViewCell!)!
if !(indexPath != nil) {
return
}
let task:TLITask = self.frc?.objectAtIndexPath(indexPath!) as! TLITask
if task.completed!.boolValue {
task.completed = NSNumber(bool: false)
task.checkBoxValue = "false"
task.completedAt = nil
} else {
task.completed = NSNumber(bool: true)
task.checkBoxValue = "true"
task.completedAt = NSDate()
}
task.updatedAt = NSDate()
let animation:CABasicAnimation = CABasicAnimation(keyPath: "transform.scale")
animation.fromValue = NSNumber(float: 1.4)
animation.toValue = NSNumber(float: 1.0)
animation.duration = 0.2
animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.4, 1.3, 1, 1)
button.layer.addAnimation(animation, forKey: "bounceAnimation")
cdc.backgroundSaveContext()
let IS_IPAD = (UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad)
if IS_IPAD {
updateFooterInfoText(self.managedObject!)
} else {
updateFooterInfoText(self.list!)
}
TLIAnalyticsTracker.trackMixpanelEvent("Toggle Task", properties: nil)
}
}
// MARK: TLIAddTaskViewDelegate
func addTaskViewDidBeginEditing(addTaskView: TLIAddTaskView) {
displayTransparentLayer();
}
func addTaskViewDidEndEditing(addTaskView: TLIAddTaskView) {
hideTransparentLayer()
}
func addTaskView(addTaskView: TLIAddTaskView, title: NSString) {
do {
let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "Task")
let positionDescriptor = NSSortDescriptor(key: "position", ascending: false)
let IS_IPAD = (UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad)
if IS_IPAD {
fetchRequest.predicate = NSPredicate(format: "list = %@", self.managedObject!)
} else {
fetchRequest.predicate = NSPredicate(format: "list = %@", self.list!)
}
fetchRequest.sortDescriptors = [positionDescriptor]
let results:NSArray = try TLICDController.sharedInstance.context!.executeFetchRequest(fetchRequest)
let cdc:TLICDController = TLICDController.sharedInstance
let task:TLITask = NSEntityDescription.insertNewObjectForEntityForName("Task", inManagedObjectContext: cdc.context!) as! TLITask
task.displayLongText = title as String
if IS_IPAD {
task.list = self.managedObject!
} else {
task.list = self.list!
}
task.position = NSNumber(integer: results.count + 1)
task.createdAt = NSDate()
task.checkBoxValue = "false"
task.completed = false
cdc.backgroundSaveContext()
checkForTasks()
if IS_IPAD {
updateFooterInfoText(self.managedObject!)
} else {
updateFooterInfoText(self.list!)
}
TLIAnalyticsTracker.trackMixpanelEvent("Add New Task", properties: nil)
} catch let error as NSError {
fatalError(error.localizedDescription)
}
}
func displayTransparentLayer() {
self.tableView?.scrollEnabled = false
let addTransparentLayer:UIView = self.addTransparentLayer!
UIView.animateWithDuration(0.3, delay: 0.0,
options: [.CurveEaseInOut, .AllowUserInteraction], animations: {
addTransparentLayer.alpha = 1.0
}, completion: nil)
}
func hideTransparentLayer() {
self.tableView?.scrollEnabled = true
UIView.animateWithDuration(0.3, delay: 0, options: [UIViewAnimationOptions.CurveEaseInOut, UIViewAnimationOptions.AllowUserInteraction], animations: {
self.addTransparentLayer!.alpha = 0.0
}, completion: { finished in
if finished {
//self.addTransparentLayer?.removeFromSuperview()
}
})
}
// MARK: TTTAttributedLabelDelegate
func attributedLabel(label: TTTAttributedLabel!, didSelectLinkWithURL url: NSURL!) {
if url.scheme == "tag" {
let tasksTagsViewController:TLITagsViewController = TLITagsViewController()
tasksTagsViewController.tag = url.host!
self.navigationController?.pushViewController(tasksTagsViewController, animated: true)
TLIAnalyticsTracker.trackMixpanelEvent("Display Tags", properties: nil)
} else if url.scheme == "http" {
UIApplication.sharedApplication().openURL(NSURL(string: NSString(format: "http://%@", url.host!) as String)!)
TLIAnalyticsTracker.trackMixpanelEvent("Display Link", properties: nil)
} else if url.scheme == "mention" {
let mentionsViewController:TLIMentionsViewController = TLIMentionsViewController()
mentionsViewController.mention = url.host!
self.navigationController?.pushViewController(mentionsViewController, animated: true)
TLIAnalyticsTracker.trackMixpanelEvent("Display Mentions", properties: nil)
}
}
func transparentLayerTapped(gesture:UITapGestureRecognizer) {
self.addTaskView?.textField?.resignFirstResponder()
}
// MARK: Edit Task
func editTask(task:TLITask, indexPath:NSIndexPath) {
let editTaskViewController:TLIEditTaskViewController = TLIEditTaskViewController()
editTaskViewController.task = task
editTaskViewController.indexPath = indexPath
editTaskViewController.delegate = self
let navigationController:UINavigationController = UINavigationController(rootViewController: editTaskViewController)
navigationController.modalPresentationStyle = UIModalPresentationStyle.FormSheet
self.navigationController?.presentViewController(navigationController, animated: true, completion: nil)
TLIAnalyticsTracker.trackMixpanelEvent("Edit Task", properties: nil)
}
func putEstimatedCellHeightToCache(indexPath:NSIndexPath, height:CGFloat) {
initEstimatedRowHeightCacheIfNeeded()
estimatedRowHeightCache?.setValue(height, forKey: NSString(format: "%ld", indexPath.row) as String)
}
func initEstimatedRowHeightCacheIfNeeded() {
if estimatedRowHeightCache == nil {
estimatedRowHeightCache = NSMutableDictionary()
}
}
func getEstimatedCellHeightFromCache(indexPath:NSIndexPath, defaultHeight:CGFloat)->CGFloat? {
initEstimatedRowHeightCacheIfNeeded()
let height:CGFloat? = estimatedRowHeightCache!.valueForKey(NSString(format: "%ld", indexPath.row) as String) as? CGFloat
if( height != nil) {
return height!
}
return defaultHeight
}
func isEstimatedRowHeightInCache(indexPath:NSIndexPath)->Bool? {
let value = getEstimatedCellHeightFromCache(indexPath, defaultHeight: 0)
if value > 0 {
return true
}
return false
}
func tableViewReloadData() {
estimatedRowHeightCache = NSMutableDictionary()
self.tableView?.reloadData()
}
func onClose(editTaskViewController:TLIEditTaskViewController, indexPath:NSIndexPath) {
self.currentIndexPath = indexPath
self.tableView?.reloadData()
}
func exportTasks(sender:UIButton) {
if self.managedObject != nil || self.list != nil {
do {
let cdc:TLICDController = TLICDController.sharedInstance
let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "Task")
let positionDescriptor = NSSortDescriptor(key: "position", ascending: false)
let displayLongTextDescriptor = NSSortDescriptor(key: "displayLongText", ascending: true)
fetchRequest.sortDescriptors = [positionDescriptor, displayLongTextDescriptor]
let IS_IPAD = (UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad)
if IS_IPAD {
fetchRequest.predicate = NSPredicate(format: "list = %@", self.managedObject!)
} else {
fetchRequest.predicate = NSPredicate(format: "list = %@", self.list!)
}
fetchRequest.fetchBatchSize = 20
let tasks:NSArray = try cdc.context!.executeFetchRequest(fetchRequest)
var output:NSString = ""
var listTitle:NSString = ""
if IS_IPAD {
listTitle = self.managedObject!.title!
} else {
listTitle = self.list!.title!
}
output = output.stringByAppendingString(NSString(format: "%@\n", listTitle) as String)
for task in tasks {
let taskItem:TLITask = task as! TLITask
let displayLongText:NSString = NSString(format: "- %@\n", taskItem.displayLongText!)
output = output.stringByAppendingString(displayLongText as String)
}
let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: [output], applicationActivities: nil)
activityViewController.excludedActivityTypes = [
UIActivityTypePostToTwitter,
UIActivityTypePostToFacebook,
UIActivityTypePostToWeibo,
UIActivityTypeCopyToPasteboard,
UIActivityTypeAssignToContact,
UIActivityTypeSaveToCameraRoll,
UIActivityTypeAddToReadingList,
UIActivityTypePostToFlickr,
UIActivityTypePostToVimeo,
UIActivityTypePostToTencentWeibo
]
if IS_IPAD {
let popup:UIPopoverController = UIPopoverController(contentViewController: activityViewController)
popup.presentPopoverFromRect(sender.bounds, inView: sender, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
} else {
self.navigationController?.presentViewController(activityViewController, animated: true, completion: nil)
}
TLIAnalyticsTracker.trackMixpanelEvent("Export Tasks", properties: nil)
} catch let error as NSError {
fatalError(error.localizedDescription)
}
}
}
}
| mit | 486a5a9774b8cb9f5635fcc34f53f55c | 43.849765 | 200 | 0.631713 | 5.785314 | false | false | false | false |
josefdolezal/fit-cvut | BI-IOS/assignments/assignment-1/bi-ios-recognizers/PanelView.swift | 1 | 4314 | //
// PanelView.swift
// bi-ios-recognizers
//
// Created by Dominik Vesely on 03/11/15.
// Copyright © 2015 Ackee s.r.o. All rights reserved.
//
import Foundation
import UIKit
class PanelView : UIView {
var delegate : PanelViewDelegate?
// closure, anonymni funkce
var onSliderChange : ((CGFloat) -> ())?
var syncValue : Double = 0 {
didSet {
if !uswitch.on {
syncValue = oldValue
}
slider.value = Float(syncValue)
stepper.value = syncValue
}
}
weak var slider : UISlider!
weak var stepper : UIStepper!
weak var uswitch : UISwitch!
weak var segment : UISegmentedControl!
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.lightGrayColor()
let slider = UISlider()
slider.minimumValue = 0
slider.maximumValue = 15
slider.addTarget(self, action: "sliderChanged:", forControlEvents: UIControlEvents.ValueChanged)
addSubview(slider)
self.slider = slider
let stepper = UIStepper()
stepper.minimumValue = 0;
stepper.maximumValue = 15;
stepper.stepValue = 0.5;
stepper.addTarget(self, action: "stepperChanged:", forControlEvents: UIControlEvents.ValueChanged)
addSubview(stepper)
self.stepper = stepper
let uswitch = UISwitch()
uswitch.setOn(true, animated: false)
addSubview( uswitch )
self.uswitch = uswitch
let segment = UISegmentedControl(items: ["Red", "Green", "Blue"])
segment.selectedSegmentIndex = 0
segment.addTarget(self, action: "colorChanged:", forControlEvents: .ValueChanged );
addSubview(segment)
self.segment = segment
// Automaticky se spusti, vola funkci fireTimer na self
let timer = NSTimer.scheduledTimerWithTimeInterval(1/30, target: self, selector: "fireTimer:", userInfo: nil, repeats: true)
//timer.performSelector("invalidate", withObject: nil, afterDelay: 5)
// nelze volat selector (protoze nebere argument) -> musim si udelat vlastni metodu
// po 5 vterinach zavola invalidateTimer
self.performSelector("invalidateTimer:", withObject: timer, afterDelay: 5)
}
// Nastavuje natvrdo velikost views
override func layoutSubviews() {
super.layoutSubviews()
self.uswitch.frame = CGRectMake(8, 8, CGRectGetWidth(self.bounds) - 16, 44)
self.segment.frame = CGRectMake(CGRectGetWidth(self.bounds) - 8 - CGRectGetWidth(segment.bounds), 8, 140, 30)
self.stepper.frame = CGRectMake(CGRectGetWidth(slider.bounds) + 16, 59, CGRectGetWidth(self.bounds), 44)
self.slider.frame = CGRectMake(8, 8+44, CGRectGetWidth(self.bounds) - CGRectGetWidth(stepper.bounds) - 24, 44)
}
func invalidateTimer(timer: NSTimer) {
timer.invalidate()
}
//MARK: Action
func fireTimer(timer:NSTimer) {
syncValue = Double(self.slider.value + 0.01)
delegate?.syncedValueChanged(syncValue, panel: self)
}
func sliderChanged(slider : UISlider) {
syncValue = Double(slider.value)
delegate?.syncedValueChanged(syncValue, panel: self)
}
func stepperChanged(stepper: UIStepper) {
syncValue = stepper.value
delegate?.syncedValueChanged(syncValue, panel: self)
}
func colorChanged(segment: UISegmentedControl) {
let color : [UIColor] = [ .redColor(), .greenColor(), .blueColor() ]
if segment.selectedSegmentIndex < color.count {
delegate?.selectedColorChanged(color[segment.selectedSegmentIndex], panel: self)
return
}
delegate?.selectedColorChanged(.blackColor(), panel: self)
}
// Kvuli prepisovani initializeru
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
protocol PanelViewDelegate {
func syncedValueChanged(syncedValue : Double, panel: PanelView)
func selectedColorChanged(color: UIColor, panel: PanelView )
}
| mit | c64ee77a9268e151fce7436cd3052580 | 30.713235 | 132 | 0.620682 | 4.602988 | false | false | false | false |
zmeyc/xgaf | Sources/xgaf/GrammaticalCases.swift | 1 | 1249 | // XGAF file format parser for Swift.
// (c) 2016 Andrey Fidrya. MIT license. See LICENSE for more information.
import Foundation
class GrammaticalCases {
typealias Cases = [String]
var animateByNominativeCase = [String: Cases]()
var inanimateByNominativeCase = [String: Cases]()
func add(cases: [String]) {
let splitted = cases.map { splitCase(word: $0) }
guard let nominative = splitted.first else { return }
animateByNominativeCase[nominative.animate] = splitted.map {
$0.animate
}
inanimateByNominativeCase[nominative.inanimate] = splitted.map {
$0.inanimate
}
}
// *-a: ["", "a"]
// жом-жем: ["жом", "жем"]
private func splitCase(word: String) -> (inanimate: String, animate: String) {
let words = word.components(separatedBy: "-").map {
$0.replacingOccurrences(of: "*", with: "")
}
switch words.count {
case 1:
return (inanimate: words[0], animate: words[0])
case 2:
return (inanimate: words[0], animate: words[1])
default:
break
}
return (inanimate: "", animate: "")
}
}
| mit | 4dc7863f4e4c4891205fdc02c0c35486 | 29.170732 | 82 | 0.561843 | 3.914557 | false | false | false | false |
hachinobu/SamuraiTransition | SamuraiTransition/Zan/Config/JaggedZanConfig.swift | 1 | 4683 | //
// JaggedZanConfig.swift
// SamuraiTransition
//
// Created by Nishinobu.Takahiro on 2016/12/16.
// Copyright © 2016年 hachinobu. All rights reserved.
//
import Foundation
class JaggedZanConfig: ZanLineProtocol, SamuraiConfigProtocol {
let containerFrame: CGRect
let zanPoint: CGPoint
let lineWidth: CGFloat
let lineColor: UIColor
let jaggedWidth: CGFloat
fileprivate lazy var jaggedRatio: CGFloat = {
let zanWidth = self.containerFrame.maxX - self.zanPoint.x
let ratio = self.zanPoint.y / zanWidth
if ratio.isInfinite {
fatalError("It will be infinite.")
}
return ratio
}()
fileprivate lazy var jaggedHeight: CGFloat = {
return self.jaggedWidth * self.jaggedRatio
}()
fileprivate lazy var jaggedStartPoint: CGPoint = {
return CGPoint(x: self.containerFrame.maxX - self.lineWidth, y: self.containerFrame.minY)
}()
fileprivate var leftAreaOffsetSize: CGSize
fileprivate var rightAreaOffsetSize: CGSize
//conform SamuraiConfigProtocol
lazy var lineLayers: [CAShapeLayer] = {
let path = self.jaggedPath()
let lineLayer = self.zanLineLayer(from: path, width: self.lineWidth, color: self.lineColor)
return [lineLayer]
}()
lazy var zanViewConfigList: [ZanViewConfigProtocol] = {
let left = self.containerFrame
let right = self.containerFrame
let maskLayer = self.zanMaskLayers()
let oneSideConfig = ZanViewConfig(inSideFrame: left, outSideFrame: left.offsetBy(dx: -self.leftAreaOffsetSize.width, dy: -self.leftAreaOffsetSize.height), mask: maskLayer.leftAreaMask)
let otherSideConfig = ZanViewConfig(inSideFrame: right, outSideFrame: right.offsetBy(dx: self.rightAreaOffsetSize.width, dy: self.rightAreaOffsetSize.height), mask: maskLayer.rightAreaMask)
return [oneSideConfig, otherSideConfig]
}()
init(containerFrame: CGRect, zanPoint: CGPoint, lineWidth: CGFloat, lineColor: UIColor, jaggedWidth: CGFloat) {
self.containerFrame = containerFrame
self.zanPoint = zanPoint
self.lineWidth = lineWidth
self.lineColor = lineColor
self.jaggedWidth = jaggedWidth > 0.0 ? jaggedWidth : 4.0
self.leftAreaOffsetSize = self.containerFrame.size
self.rightAreaOffsetSize = self.containerFrame.size
}
}
extension JaggedZanConfig {
fileprivate func zanMaskLayers() -> (leftAreaMask: CAShapeLayer, rightAreaMask: CAShapeLayer) {
let leftAreaMaskLayer = CAShapeLayer()
let leftAreaPath = serratedLeftAreaPath()
leftAreaMaskLayer.path = leftAreaPath.cgPath
let rightAreaMaskLayer = CAShapeLayer()
let rightAreaPath = serratedRightAreaPath()
rightAreaMaskLayer.path = rightAreaPath.cgPath
return (leftAreaMaskLayer, rightAreaMaskLayer)
}
fileprivate func jaggedPath() -> UIBezierPath {
let stepWidth = jaggedWidth * 2
let path = UIBezierPath()
path.move(to: jaggedStartPoint)
while true {
path.addLine(to: CGPoint(x: path.currentPoint.x + jaggedWidth, y: path.currentPoint.y + jaggedHeight))
path.addLine(to: CGPoint(x: path.currentPoint.x - stepWidth, y: path.currentPoint.y))
if path.currentPoint.y > containerFrame.maxY || path.currentPoint.x < 0.0 {
break
}
}
return path
}
private func serratedLeftAreaPath() -> UIBezierPath {
let path = jaggedPath()
leftAreaOffsetSize = CGSize(width: jaggedStartPoint.x, height: path.currentPoint.y)
path.addLine(to: CGPoint(x: containerFrame.minX, y: containerFrame.maxY))
path.addLine(to: CGPoint(x: containerFrame.minX, y: containerFrame.minY))
path.addLine(to: jaggedStartPoint)
return path
}
private func serratedRightAreaPath() -> UIBezierPath {
let path = jaggedPath()
let rightAreaWidth = path.currentPoint.x <= 0.0 ? containerFrame.maxX : containerFrame.maxX - path.currentPoint.x
rightAreaOffsetSize = CGSize(width: rightAreaWidth, height: containerFrame.maxY)
path.addLine(to: CGPoint(x: path.currentPoint.x, y: containerFrame.maxY))
path.addLine(to: CGPoint(x: containerFrame.maxX, y: containerFrame.maxY))
path.addLine(to: CGPoint(x: containerFrame.maxX, y: containerFrame.minY))
path.addLine(to: jaggedStartPoint)
return path
}
}
| mit | 6b019a617f061539deeabeb8fb30467f | 35 | 197 | 0.655128 | 4.325323 | false | true | false | false |
KelvinJin/AnimatedCollectionViewLayout | Sources/AnimatedCollectionViewLayout/Animators/ParallaxAttributesAnimator.swift | 1 | 2504 | //
// ParallexAnimator.swift
// AnimatedCollectionViewLayout
//
// Created by Jin Wang on 8/2/17.
// Copyright © 2017 Uthoft. All rights reserved.
//
import UIKit
/// An animator that implemented the parallax effect by moving the content of the cell
/// slower than the cell itself.
public struct ParallaxAttributesAnimator: LayoutAttributesAnimator {
/// The higher the speed is, the more obvious the parallax.
/// It's recommended to be in range [0, 1] where 0 means no parallax. 0.5 by default.
public var speed: CGFloat
public init(speed: CGFloat = 0.5) {
self.speed = speed
}
public func animate(collectionView: UICollectionView, attributes: AnimatedCollectionViewLayoutAttributes) {
let position = attributes.middleOffset
let direction = attributes.scrollDirection
guard let contentView = attributes.contentView else { return }
if abs(position) >= 1 {
// Reset views that are invisible.
contentView.frame = attributes.bounds
} else if direction == .horizontal {
let width = collectionView.frame.width
let transitionX = -(width * speed * position)
let transform = CGAffineTransform(translationX: transitionX, y: 0)
let newFrame = attributes.bounds.applying(transform)
if #available(iOS 14, *) {
contentView.transform = transform
} else {
contentView.frame = newFrame
}
} else {
let height = collectionView.frame.height
let transitionY = -(height * speed * position)
let transform = CGAffineTransform(translationX: 0, y: transitionY)
// By default, the content view takes all space in the cell
let newFrame = attributes.bounds.applying(transform)
// We don't use transform here since there's an issue if layoutSubviews is called
// for every cell due to layout changes in binding method.
//
// Update for iOS 14: It seems that setting frame of content view
// won't work for iOS 14. And transform on the other hand doesn't work pre iOS 14
// so we adapt the changes here.
if #available(iOS 14, *) {
contentView.transform = transform
} else {
contentView.frame = newFrame
}
}
}
}
| mit | 67d88e1005ada8fedc15e340e4779550 | 38.109375 | 111 | 0.603276 | 5.160825 | false | false | false | false |
SwiftKit/Lipstick | Source/CGRect+Init.swift | 1 | 667 | //
// CGRect+Init.swift
// Lipstick
//
// Created by Filip Dolnik on 16.10.16.
// Copyright © 2016 Brightify. All rights reserved.
//
import UIKit
extension CGRect {
public init(x: CGFloat = 0, y: CGFloat = 0, width: CGFloat = 0, height: CGFloat = 0) {
self.init(origin: CGPoint(x: x, y: y), size: CGSize(width: width, height: height))
}
public init(x: CGFloat = 0, y: CGFloat = 0, size: CGSize) {
self.init(origin: CGPoint(x: x, y: y), size: size)
}
public init(origin: CGPoint, width: CGFloat = 0, height: CGFloat = 0) {
self.init(origin: origin, size: CGSize(width: width, height: height))
}
}
| mit | 71777bc9227cea56eddd1d5b764b2979 | 26.75 | 90 | 0.602102 | 3.264706 | false | false | false | false |
nguyenantinhbk77/practice-swift | Courses/stanford/stanford/cs193p/2015/Trax/Trax/ViewController.swift | 3 | 781 | //
// ViewController.swift
// Trax
//
// Created by Domenico on 12.04.15.
// Copyright (c) 2015 Domenico Solazzo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
let center = NSNotificationCenter.defaultCenter()
let queue = NSOperationQueue.mainQueue()
let appDelegate = UIApplication.sharedApplication().delegate
center.addObserverForName(GPXURL.Notification, object: appDelegate, queue: queue){ notification in
if let url = notification?.userInfo?[GPXURL.Key] as? NSURL{
self.textView.text = "Received \(url)"
}
}
}
}
| mit | f4ad27c1642a96ded554c3d51fa54692 | 25.033333 | 106 | 0.631242 | 4.943038 | false | false | false | false |
welbesw/easypost-swift | Pod/Classes/EasyPostUserApiKeys.swift | 1 | 1637 | //
// EasyPostUserApiKeys.swift
// Pods
//
// Created by William Welbes on 11/3/15.
//
//
import Foundation
enum EasyPostUserApiKeyMode : String {
case Production = "production"
case Test = "test"
}
open class EasyPostUserApiKeys {
open var userId:String?
open var productionKey:String?
open var testKey:String?
public init() {
}
public init(jsonDictionary: [String: Any]) {
//Load the JSON dictionary
if let stringValue = jsonDictionary["id"] as? String {
userId = stringValue
}
if let keysArray = jsonDictionary["keys"] as? NSArray {
for keyItem in keysArray {
if let keyDict = keyItem as? NSDictionary {
var keyMode:EasyPostUserApiKeyMode?
var key:String?
if let stringValue = keyDict["mode"] as? String {
if let mode = EasyPostUserApiKeyMode(rawValue: stringValue) {
keyMode = mode
}
}
if let stringValue = keyDict["key"] as? String {
key = stringValue
}
if(key != nil && keyMode != nil) {
switch(keyMode!) {
case .Production:
productionKey = key
case .Test:
testKey = key
}
}
}
}
}
}
}
| mit | 7a2239a4e676a5ebb9ee773e8f390c2a | 26.283333 | 85 | 0.437996 | 5.42053 | false | true | false | false |
ravero/CoreDataContext | CoreDataContext/Helpers/CoreDataTableViewController.swift | 1 | 4733 | //
// CoreDataTableViewController.swift
// CoreDataContext
//
// Created by Rafael Veronezi on 9/30/14.
// Copyright (c) 2014 Syligo. All rights reserved.
//
import UIKit
import CoreData
public class CoreDataTableViewController: UITableViewController, NSFetchedResultsControllerDelegate {
//
// MARK: - Properties
public var fetchedResultsController: NSFetchedResultsController? {
didSet {
if self.fetchedResultsController !== oldValue {
if let frc = self.fetchedResultsController {
// Set title if it is empty
if (self.title == nil || self.title == oldValue?.fetchRequest.entity?.name) &&
(self.navigationController == nil || self.navigationItem.title == nil) {
self.title = frc.fetchRequest.entity!.name
}
frc.delegate = self
self.performFetch()
} else {
self.tableView.reloadData()
}
}
}
}
//
// MARK: - Support Methods
public func performFetch() {
if let frc = self.fetchedResultsController {
var error: NSError?
var success = frc.performFetch(&error)
if !success {
NSLog("performFetch: failed")
}
if let e = error {
NSLog("%@ (%@)", e.localizedDescription, e.localizedFailureReason!)
}
} else {
}
self.tableView.reloadData()
}
//
// MARK: - UITableViewDataSource
override public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
var sections = self.fetchedResultsController?.sections?.count ?? 0
return sections
}
override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rows = 0
var sections = self.fetchedResultsController?.sections?.count ?? 0
if sections > 0 {
var sectionInfo = self.fetchedResultsController!.sections![section] as! NSFetchedResultsSectionInfo
rows = sectionInfo.numberOfObjects
}
return rows
}
override public func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if let frc = self.fetchedResultsController {
if let sectionInfo = frc.sections?[section] as? NSFetchedResultsSectionInfo {
return sectionInfo.name
}
}
return nil
}
override public func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
return self.fetchedResultsController?.sectionForSectionIndexTitle(title, atIndex: index) ?? 0
}
override public func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! {
return self.fetchedResultsController?.sectionIndexTitles
}
//
// MARK: - FetchedResultsControllerDelegate
public func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
public func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
break
}
}
public func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
self.tableView.insertRowsAtIndexPaths([ newIndexPath! ], withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteRowsAtIndexPaths([ indexPath! ], withRowAnimation: .Fade)
case .Update:
self.tableView.reloadRowsAtIndexPaths([ indexPath! ], withRowAnimation: .Fade)
case .Move:
self.tableView.deleteRowsAtIndexPaths([ indexPath! ], withRowAnimation: .Fade)
self.tableView.insertRowsAtIndexPaths([ newIndexPath! ], withRowAnimation: .Fade)
}
}
public func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
}
| mit | f0d5efd064f33e7fb8c71909445e68d9 | 36.267717 | 218 | 0.625396 | 6.067949 | false | false | false | false |
qRoC/Loobee | Tests/LoobeeTests/Library/AssertionConcern/AssertionGroupLazyTests.swift | 1 | 2228 | // This file is part of the Loobee package.
//
// (c) Andrey Savitsky <[email protected]>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
import XCTest
#if canImport(Loobee)
import Loobee
#else
import LoobeeAssertionConcern
#endif
internal final class AssertionGroupLazyTests: XCTestCase {
///
func testAssignValue() {
_ = AssertionGroup.lazy(4) { value, _ in
XCTAssertEqual(value, 4)
}
}
///
func testEmptyBlock() {
let assertionGroup = AssertionGroup.lazy("test") { _, _ in }
XCTAssertTrue(assertionGroup.notifications.isEmpty)
}
///
func testWithValidAssertions() {
let assertionGroup = AssertionGroup.lazy("test") { value, yield in
yield(assert("t", containedIn: value))
yield(assert("e", containedIn: value))
yield(assert("a", notContainedIn: value))
yield(assert("s", containedIn: value))
}
XCTAssertTrue(assertionGroup.notifications.isEmpty)
}
///
func testExecuteBeforeFirstFail() {
var callCount = 0
let checker: (_ container: String, _ value: Character) -> AssertionNotification? = { container, value in
callCount += 1
return assert(value, containedIn: container)
}
_ = AssertionGroup.lazy("test") { value, yield in
yield(checker(value, "t"))
yield(checker(value, "a"))
yield(checker(value, "e"))
yield(checker(value, "b"))
yield(checker(value, "s"))
yield(checker(value, "c"))
}
XCTAssertEqual(callCount, 2)
}
///
func testExecuteResultIfFailed() {
let assertionGroup = AssertionGroup.lazy("test") { value, yield in
yield(assert("t", containedIn: value))
yield(assert("e", containedIn: value))
yield(assert("a", containedIn: value, orNotification: "FAIL"))
yield(assert("s", containedIn: value))
}
XCTAssertEqual(assertionGroup.notifications.count, 1)
XCTAssertEqual(assertionGroup.notifications.first?.message, "FAIL")
}
}
| mit | ed2a04681df34a8a85cfa33784c1e657 | 28.706667 | 112 | 0.604578 | 4.411881 | false | true | false | false |
gribozavr/swift | test/Driver/Dependencies/crash-simple.swift | 1 | 1347 | /// crash ==> main | crash --> other
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/crash-simple/* %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -disable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./crash.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// CHECK-FIRST-NOT: warning
// CHECK-FIRST: Handled main.swift
// CHECK-FIRST: Handled crash.swift
// CHECK-FIRST: Handled other.swift
// RUN: touch -t 201401240006 %t/crash.swift
// RUN: cd %t && not %swiftc_driver -disable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./crash.swift ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s
// CHECK-SECOND: Handled crash.swift
// CHECK-SECOND-NOT: Handled main.swift
// CHECK-SECOND-NOT: Handled other.swift
// RUN: %FileCheck -check-prefix=CHECK-RECORD %s < %t/main~buildrecord.swiftdeps
// CHECK-RECORD-DAG: "./crash.swift": !dirty [
// CHECK-RECORD-DAG: "./main.swift": !dirty [
// CHECK-RECORD-DAG: "./other.swift": !private [
| apache-2.0 | 6f27505bdb37e649a5f79b584445633c | 52.88 | 342 | 0.706756 | 3.161972 | false | false | false | false |
skladek/SKWebServiceController | SampleProject/SampleProject/Application/AppDelegate.swift | 1 | 709 | // swiftlint:disable line_length
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
let postsViewController = PostsViewController()
let navigationController = UINavigationController(rootViewController: postsViewController)
navigationController.navigationBar.isTranslucent = false
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
return true
}
}
| mit | d2c6e084d2bc552aeccddbb42b88e9ba | 34.45 | 144 | 0.755994 | 6.274336 | false | false | false | false |
CodaFi/APL.swift | APL/Operators.swift | 1 | 5815 | //
// Operators.swift
// APL
//
// Created by Robert Widmann on 8/16/14.
// Copyright (c) 2014 Robert Widmann. All rights reserved.
//
import Foundation
// MARK: Math
//prefix operator + {} Defined by the STL
//prefix operator - {} Defined by the STL
/// Minus
prefix operator - {}
/// Trend | The trend of a number is its sign or zero.
prefix operator × {}
/// Times | Returns the result of e**(log(⍺) - log(1.0 / ⍵)), or the product of two numbers.
infix operator × { associativity right }
/// Per | Returns a result of (1 / ⍵)
prefix operator ÷ {}
/// Per | Returns the result of (⍺ / ⍵)
infix operator ÷ { associativity right }
/// Floor | Gives the floor or integer part of ⍵
prefix operator ⌊ {}
/// Minimum | Yields the lesser of a and ⍵
infix operator ⌊ { associativity right }
/// Ceiling | Rounds upward, then yields the integer part of ⍵
prefix operator ⌈ {}
/// Maximum | Yields the greater of ⍺ and ⍵
infix operator ⌈ { associativity right }
/// Size | Yields the size or "absolute value" for a real or complex argument.
prefix operator | {}
/// Residue | TODO: Relax definition from fmod to "tolerant" residue
/// ⍺|⍵ ←→ ⍵-⍺×⌊s if (⍺≠0)^(⌈s)≠⌊s←⍵÷⍺+⍺=0
/// ←→ ⍵×⍺=0 otherwise
infix operator | { associativity right }
/// Factorial | Returns the product of the list of integers from 1 to ⍵
/// TODO: Extend to reals and complex numbers with gamma:
/// Gamma(x) = (x - 1)! | x ∊ N
/// Gamma(t) = Integral(0, Inf, (x**(t-1))× **-x, dx) | otherwise
prefix operator ! {}
/// Out of | Yields the number of ways of selecting ⍺ things from ⍵. Useful for producing
/// binomial coefficients.
infix operator ! { associativity right }
/// Power | Returns the exponential of ⍵; that is, e ** ⍵
prefix operator ** {}
/// Power | Returns ⍺ ** ⍵
infix operator ** { associativity right }
/// Log | Returns the natural log of ⍵
prefix operator ⍟ {}
/// Log | Returns the log base ⍺ of ⍵
infix operator ⍟ { associativity right }
/// Pi | Returns pi × ⍵, where pi is the ratio of the circumference of a circle to its diameter.
prefix operator ○ {}
/// Circle | Given some constant k in the range [-15...15], produces several families of related
/// functions. Trigonometric for k∊1 2 3, hyperbolic for k∊5 6 7, pythagorean for k∊0 4 8, and
/// complex for k∊9 10 11 12. Negative cases correspond to the inverse of the corresponding
/// positive operation such that ⍵≡k○(-k)○⍵ or ⍵≡(-k)○k○⍵ hold
infix operator ○ { associativity right }
/// Reverse | Reverses the order of a list
prefix operator ⌽ {}
/// Rotate | Cycles the elements of a list.
infix operator ⌽ { associativity right }
/// Roll | Returns a random number from ⍳w
prefix operator ¿ {}
/// Deal | Returns a vector of numbers ⍺ long randomly selected from ⍳w. The returned array will
/// always contain unique numbers.
infix operator ¿ { associativity right }
//prefix operator ⊥ {}
infix operator ⊥ { associativity right }
infix operator ⊤ { associativity right }
// MARK: Logic and Comparison
//prefix operator < {}
//infix operator < { associativity right }
//
//prefix operator ≤ {}
//infix operator ≤ { associativity right }
//
//prefix operator > {}
//infix operator > { associativity right }
//
//prefix operator ≥{}
//infix operator ≥ { associativity right }
//------------------//
//prefix operator = {}
//infix operator = { associativity right }
prefix operator ≠ {}
infix operator ≠ { associativity right }
/// Match | Returns whether the arguments match in shape, size, and boxing structure
infix operator ≡ { associativity right }
/// Not | Negates only boolean arguments
//prefix operator ~ {}
/// Less | Returns an array whose major cells are the major cells of ⍺ less the major cells of ⍵.
infix operator ~ { associativity right }
/// And | Logical AND
/// Least Common Multiple | The least common divisor of ⍺ and ⍵
infix operator ∧ { associativity right }
/// Or | Logical OR
/// Greatest Common Multiple | The greatest common divisor or ⍺ and ⍵
infix operator ∨ { associativity right }
/// Nor | Logical NOR
infix operator ⍱ { associativity right }
/// Nand | Logical NAND
infix operator ⍲ { associativity right }
/// Right | Identity
prefix operator ⊢ {}
/// Right | Yields the argument to its right. aka const
infix operator ⊢ { associativity right }
/// Left | Identity
prefix operator ⊣ {}
/// Left | Yields the argument to its left. aka flip const
infix operator ⊣ { associativity right }
//------------------//
prefix operator ∊ {}
infix operator ∊ { associativity right }
prefix operator ⍷ {}
infix operator ⍷ { associativity right }
//------------------//
prefix operator ⍳ {}
infix operator ⍳ { associativity right }
prefix operator ⊖ {}
infix operator ⊖ {}
/// Cant | This function reverses the order of axes of its argument.
prefix operator ⍉ {}
//infix operator ⍉ {}
//------------------//
prefix operator ↑ {}
infix operator ↑ { associativity right }
prefix operator ↓ {}
infix operator ↓ { associativity right }
infix operator ⌿ {}
//infix operator ⍸ { associativity right }
prefix operator ⍴ {}
infix operator ⍴ {}
// MARK: Miscellaneous
/// Ravel | "Ravels" (that is, the antonym of unravel) a nested array in normal order.
prefix operator 、{}
/// Table | Cants ⍺ and ⍵, concats them together, then cants the result again.
infix operator 、{}
//prefix operator ⍎ {}
//infix operator ⍎ { associativity right }
//
//prefix operator ⍕ {}
//infix operator ⍕ { associativity right }
prefix operator ⍪ {}
/// Over | Concatenates the major cells of ⍺ and ⍵
infix operator ⍪ {}
| mit | 051a5fafc552c1c73577a2809d6b1e22 | 24.731481 | 97 | 0.662828 | 3.531131 | false | false | false | false |
GreatfeatServices/gf-mobile-app | olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Observables/Implementations/ObserveOnSerialDispatchQueue.swift | 57 | 2501 | //
// ObserveOnSerialDispatchQueue.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/31/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if TRACE_RESOURCES
fileprivate var _numberOfSerialDispatchQueueObservables: AtomicInt = 0
extension Resources {
/**
Counts number of `SerialDispatchQueueObservables`.
Purposed for unit tests.
*/
public static var numberOfSerialDispatchQueueObservables: Int32 {
return _numberOfSerialDispatchQueueObservables.valueSnapshot()
}
}
#endif
class ObserveOnSerialDispatchQueueSink<O: ObserverType> : ObserverBase<O.E> {
let scheduler: SerialDispatchQueueScheduler
let observer: O
let cancel: Cancelable
var cachedScheduleLambda: ((ObserveOnSerialDispatchQueueSink<O>, Event<E>) -> Disposable)!
init(scheduler: SerialDispatchQueueScheduler, observer: O, cancel: Cancelable) {
self.scheduler = scheduler
self.observer = observer
self.cancel = cancel
super.init()
cachedScheduleLambda = { sink, event in
sink.observer.on(event)
if event.isStopEvent {
sink.dispose()
}
return Disposables.create()
}
}
override func onCore(_ event: Event<E>) {
let _ = self.scheduler.schedule((self, event), action: cachedScheduleLambda)
}
override func dispose() {
super.dispose()
cancel.dispose()
}
}
class ObserveOnSerialDispatchQueue<E> : Producer<E> {
let scheduler: SerialDispatchQueueScheduler
let source: Observable<E>
init(source: Observable<E>, scheduler: SerialDispatchQueueScheduler) {
self.scheduler = scheduler
self.source = source
#if TRACE_RESOURCES
let _ = Resources.incrementTotal()
let _ = AtomicIncrement(&_numberOfSerialDispatchQueueObservables)
#endif
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E {
let sink = ObserveOnSerialDispatchQueueSink(scheduler: scheduler, observer: observer, cancel: cancel)
let subscription = source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
#if TRACE_RESOURCES
deinit {
let _ = Resources.decrementTotal()
let _ = AtomicDecrement(&_numberOfSerialDispatchQueueObservables)
}
#endif
}
| apache-2.0 | 70dd5a1d702c85cb2c17e6e64ea35aab | 27.735632 | 139 | 0.6596 | 4.789272 | false | false | false | false |
WebberLai/WLComics | Pods/SwiftyDropbox/Source/SwiftyDropbox/Shared/Handwritten/OAuth.swift | 1 | 17348 | ///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
import SystemConfiguration
import Foundation
public protocol SharedApplication {
func presentErrorMessage(_ message: String, title: String)
func presentErrorMessageWithHandlers(_ message: String, title: String, buttonHandlers: Dictionary<String, () -> Void>)
func presentPlatformSpecificAuth(_ authURL: URL) -> Bool
func presentAuthChannel(_ authURL: URL, tryIntercept: @escaping ((URL) -> Bool), cancelHandler: @escaping (() -> Void))
func presentExternalApp(_ url: URL)
func canPresentExternalApp(_ url: URL) -> Bool
}
/// Manages access token storage and authentication
///
/// Use the `DropboxOAuthManager` to authenticate users through OAuth2, save access tokens, and retrieve access tokens.
///
/// @note OAuth flow webviews localize to enviroment locale.
///
open class DropboxOAuthManager {
public let locale: Locale?
let appKey: String
let redirectURL: URL
let host: String
var urls: Array<URL>
// MARK: Shared instance
/// A shared instance of a `DropboxOAuthManager` for convenience
public static var sharedOAuthManager: DropboxOAuthManager!
// MARK: Functions
public init(appKey: String, host: String) {
self.appKey = appKey
self.redirectURL = URL(string: "db-\(self.appKey)://2/token")!
self.host = host
self.urls = [self.redirectURL]
self.locale = nil;
}
///
/// Create an instance
/// parameter appKey: The app key from the developer console that identifies this app.
///
convenience public init(appKey: String) {
self.init(appKey: appKey, host: "www.dropbox.com")
}
///
/// Try to handle a redirect back into the application
///
/// - parameter url: The URL to attempt to handle
///
/// - returns `nil` if SwiftyDropbox cannot handle the redirect URL, otherwise returns the `DropboxOAuthResult`.
///
open func handleRedirectURL(_ url: URL) -> DropboxOAuthResult? {
// check if url is a cancel url
if (url.host == "1" && url.path == "/cancel") || (url.host == "2" && url.path == "/cancel") {
return .cancel
}
if !self.canHandleURL(url) {
return nil
}
let result = extractFromUrl(url)
switch result {
case .success(let token):
_ = Keychain.set(token.uid, value: token.accessToken)
return result
default:
return result
}
}
///
/// Present the OAuth2 authorization request page by presenting a web view controller modally
///
/// - parameter controller: The controller to present from
///
open func authorizeFromSharedApplication(_ sharedApplication: SharedApplication) {
let cancelHandler: (() -> Void) = {
let cancelUrl = URL(string: "db-\(self.appKey)://2/cancel")!
sharedApplication.presentExternalApp(cancelUrl)
}
if !Reachability.connectedToNetwork() {
let message = "Try again once you have an internet connection"
let title = "No internet connection"
let buttonHandlers: [String: () -> Void] = [
"Cancel": { cancelHandler() },
"Retry": { self.authorizeFromSharedApplication(sharedApplication) },
]
sharedApplication.presentErrorMessageWithHandlers(message, title: title, buttonHandlers: buttonHandlers)
return
}
if !self.conformsToAppScheme() {
let message = "DropboxSDK: unable to link; app isn't registered for correct URL scheme (db-\(self.appKey)). Add this scheme to your project Info.plist file, under \"URL types\" > \"URL Schemes\"."
let title = "SwiftyDropbox Error"
sharedApplication.presentErrorMessage(message, title:title)
return
}
let url = self.authURL()
if checkAndPresentPlatformSpecificAuth(sharedApplication) {
return
}
let tryIntercept: ((URL) -> Bool) = { url in
if self.canHandleURL(url) {
sharedApplication.presentExternalApp(url)
return true
} else {
return false
}
}
sharedApplication.presentAuthChannel(url, tryIntercept: tryIntercept, cancelHandler: cancelHandler)
}
fileprivate func conformsToAppScheme() -> Bool {
let appScheme = "db-\(self.appKey)"
let urlTypes = Bundle.main.object(forInfoDictionaryKey: "CFBundleURLTypes") as? [ [String: AnyObject] ] ?? []
for urlType in urlTypes {
let schemes = urlType["CFBundleURLSchemes"] as? [String] ?? []
for scheme in schemes {
if scheme == appScheme {
return true
}
}
}
return false
}
func authURL() -> URL {
var components = URLComponents()
components.scheme = "https"
components.host = self.host
components.path = "/oauth2/authorize"
let locale = Bundle.main.preferredLocalizations.first ?? "en"
let state = ProcessInfo.processInfo.globallyUniqueString
UserDefaults.standard.setValue(state, forKey: Constants.kCSERFKey)
components.queryItems = [
URLQueryItem(name: "response_type", value: "token"),
URLQueryItem(name: "client_id", value: self.appKey),
URLQueryItem(name: "redirect_uri", value: self.redirectURL.absoluteString),
URLQueryItem(name: "disable_signup", value: "true"),
URLQueryItem(name: "locale", value: self.locale?.identifier ?? locale),
URLQueryItem(name: "state", value: state),
]
return components.url!
}
fileprivate func canHandleURL(_ url: URL) -> Bool {
for known in self.urls {
if url.scheme == known.scheme && url.host == known.host && url.path == known.path {
return true
}
}
return false
}
func extractFromRedirectURL(_ url: URL) -> DropboxOAuthResult {
var results = [String: String]()
let pairs = url.fragment?.components(separatedBy: "&") ?? []
for pair in pairs {
let kv = pair.components(separatedBy: "=")
results.updateValue(kv[1], forKey: kv[0])
}
if let error = results["error"] {
let desc = results["error_description"]?.replacingOccurrences(of: "+", with: " ").removingPercentEncoding
if results["error"] != "access_denied" {
return .cancel
}
return .error(OAuth2Error(errorCode: error), desc ?? "")
} else {
let state = results["state"]
let storedState = UserDefaults.standard.string(forKey: Constants.kCSERFKey)
if state == nil || storedState == nil || state != storedState {
return .error(OAuth2Error(errorCode: "inconsistent_state"), "Auth flow failed because of inconsistent state.")
} else {
// reset upon success
UserDefaults.standard.setValue(nil, forKey: Constants.kCSERFKey)
}
let accessToken = results["access_token"]!
let uid = results["uid"]!
return .success(DropboxAccessToken(accessToken: accessToken, uid: uid))
}
}
func extractFromUrl(_ url: URL) -> DropboxOAuthResult {
return extractFromRedirectURL(url)
}
func checkAndPresentPlatformSpecificAuth(_ sharedApplication: SharedApplication) -> Bool {
return false
}
///
/// Retrieve all stored access tokens
///
/// - returns: a dictionary mapping users to their access tokens
///
open func getAllAccessTokens() -> [String : DropboxAccessToken] {
let users = Keychain.getAll()
var ret = [String : DropboxAccessToken]()
for user in users {
if let accessToken = Keychain.get(user) {
ret[user] = DropboxAccessToken(accessToken: accessToken, uid: user)
}
}
return ret
}
///
/// Check if there are any stored access tokens
///
/// - returns: Whether there are stored access tokens
///
open func hasStoredAccessTokens() -> Bool {
return self.getAllAccessTokens().count != 0
}
///
/// Retrieve the access token for a particular user
///
/// - parameter user: The user whose token to retrieve
///
/// - returns: An access token if present, otherwise `nil`.
///
open func getAccessToken(_ user: String?) -> DropboxAccessToken? {
if let user = user {
if let accessToken = Keychain.get(user) {
return DropboxAccessToken(accessToken: accessToken, uid: user)
}
}
return nil
}
///
/// Delete a specific access token
///
/// - parameter token: The access token to delete
///
/// - returns: whether the operation succeeded
///
open func clearStoredAccessToken(_ token: DropboxAccessToken) -> Bool {
return Keychain.delete(token.uid)
}
///
/// Delete all stored access tokens
///
/// - returns: whether the operation succeeded
///
open func clearStoredAccessTokens() -> Bool {
return Keychain.clear()
}
///
/// Save an access token
///
/// - parameter token: The access token to save
///
/// - returns: whether the operation succeeded
///
open func storeAccessToken(_ token: DropboxAccessToken) -> Bool {
return Keychain.set(token.uid, value: token.accessToken)
}
///
/// Utility function to return an arbitrary access token
///
/// - returns: the "first" access token found, if any (otherwise `nil`)
///
open func getFirstAccessToken() -> DropboxAccessToken? {
return self.getAllAccessTokens().values.first
}
}
/// A Dropbox access token
open class DropboxAccessToken: CustomStringConvertible {
/// The access token string
public let accessToken: String
/// The associated user
public let uid: String
public init(accessToken: String, uid: String) {
self.accessToken = accessToken
self.uid = uid
}
open var description: String {
return self.accessToken
}
}
/// A failed authorization.
/// See RFC6749 4.2.2.1
public enum OAuth2Error {
/// The client is not authorized to request an access token using this method.
case unauthorizedClient
/// The resource owner or authorization server denied the request.
case accessDenied
/// The authorization server does not support obtaining an access token using this method.
case unsupportedResponseType
/// The requested scope is invalid, unknown, or malformed.
case invalidScope
/// The authorization server encountered an unexpected condition that prevented it from fulfilling the request.
case serverError
/// The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server.
case temporarilyUnavailable
/// The state param received from the authorization server does not match the state param stored by the SDK.
case inconsistentState
/// Some other error (outside of the OAuth2 specification)
case unknown
/// Initializes an error code from the string specced in RFC6749
init(errorCode: String) {
switch errorCode {
case "unauthorized_client": self = .unauthorizedClient
case "access_denied": self = .accessDenied
case "unsupported_response_type": self = .unsupportedResponseType
case "invalid_scope": self = .invalidScope
case "server_error": self = .serverError
case "temporarily_unavailable": self = .temporarilyUnavailable
case "inconsistent_state": self = .inconsistentState
default: self = .unknown
}
}
}
internal let kDBLinkNonce = "dropbox.sync.nonce"
/// The result of an authorization attempt.
public enum DropboxOAuthResult {
/// The authorization succeeded. Includes a `DropboxAccessToken`.
case success(DropboxAccessToken)
/// The authorization failed. Includes an `OAuth2Error` and a descriptive message.
case error(OAuth2Error, String)
/// The authorization was manually canceled by the user.
case cancel
}
class Keychain {
static let checkAccessibilityMigrationOneTime: () = {
Keychain.checkAccessibilityMigration()
}()
class func queryWithDict(_ query: [String : AnyObject]) -> CFDictionary {
let bundleId = Bundle.main.bundleIdentifier ?? ""
var queryDict = query
queryDict[kSecClass as String] = kSecClassGenericPassword
queryDict[kSecAttrService as String] = "\(bundleId).dropbox.authv2" as AnyObject?
queryDict[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
return queryDict as CFDictionary
}
class func set(_ key: String, value: String) -> Bool {
if let data = value.data(using: String.Encoding.utf8) {
return set(key, value: data)
} else {
return false
}
}
class func set(_ key: String, value: Data) -> Bool {
let query = Keychain.queryWithDict([
(kSecAttrAccount as String): key as AnyObject,
( kSecValueData as String): value as AnyObject
])
SecItemDelete(query)
return SecItemAdd(query, nil) == noErr
}
class func getAsData(_ key: String) -> Data? {
let query = Keychain.queryWithDict([
(kSecAttrAccount as String): key as AnyObject,
( kSecReturnData as String): kCFBooleanTrue,
( kSecMatchLimit as String): kSecMatchLimitOne
])
var dataResult: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &dataResult)
if status == noErr {
return dataResult as? Data
}
return nil
}
class func getAll() -> [String] {
let query = Keychain.queryWithDict([
( kSecReturnAttributes as String): kCFBooleanTrue,
( kSecMatchLimit as String): kSecMatchLimitAll
])
var dataResult: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &dataResult)
if status == noErr {
let results = dataResult as? [[String : AnyObject]] ?? []
return results.map { d in d["acct"] as! String }
}
return []
}
class func get(_ key: String) -> String? {
if let data = getAsData(key) {
return String(data: data, encoding: .utf8)
} else {
return nil
}
}
class func delete(_ key: String) -> Bool {
let query = Keychain.queryWithDict([
(kSecAttrAccount as String): key as AnyObject
])
return SecItemDelete(query) == noErr
}
class func clear() -> Bool {
let query = Keychain.queryWithDict([:])
return SecItemDelete(query) == noErr
}
class func checkAccessibilityMigration() {
let kAccessibilityMigrationOccurredKey = "KeychainAccessibilityMigration"
let MigrationOccurred = UserDefaults.standard.string(forKey: kAccessibilityMigrationOccurredKey)
if (MigrationOccurred != "true") {
let bundleId = Bundle.main.bundleIdentifier ?? ""
let queryDict = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: "\(bundleId).dropbox.authv2" as AnyObject?]
let attributesToUpdateDict = [kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly]
SecItemUpdate(queryDict as CFDictionary, attributesToUpdateDict as CFDictionary)
UserDefaults.standard.set("true", forKey: kAccessibilityMigrationOccurredKey)
}
}
}
class Reachability {
/// From http://stackoverflow.com/questions/25623272/how-to-use-scnetworkreachability-in-swift/25623647#25623647.
///
/// This method uses `SCNetworkReachabilityCreateWithAddress` to create a reference to monitor the example host
/// defined by our zeroed `zeroAddress` struct. From this reference, we can extract status flags regarding the
/// reachability of this host, using `SCNetworkReachabilityGetFlags`.
class func connectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return false
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
}
| mit | 4c05df8ed81e4ed828c332e6e7a74964 | 33.216963 | 208 | 0.624107 | 4.963662 | false | false | false | false |
SwiftOnEdge/Edge | Sources/TCP/Server.swift | 1 | 6061 | //
// Server.swift
// Edge
//
// Created by Tyler Fleming Cloutier on 4/30/16.
//
//
#if os(Linux)
import Glibc
#else
import Darwin
#endif
import Dispatch
import StreamKit
import POSIX
import IOStream
public final class Server {
public static let defaultReuseAddress = false
public static let defaultReusePort = false
private let fd: SocketFileDescriptor
private let listeningSource: DispatchSourceRead
public convenience init(reuseAddress: Bool = defaultReuseAddress, reusePort: Bool = defaultReusePort) throws {
let fd = try SocketFileDescriptor(
socketType: SocketType.stream,
addressFamily: AddressFamily.inet
)
try self.init(fd: fd, reuseAddress: reuseAddress, reusePort: reusePort)
}
public init(fd: SocketFileDescriptor, reuseAddress: Bool = defaultReuseAddress, reusePort: Bool = defaultReusePort) throws {
self.fd = fd
if reuseAddress {
// Set SO_REUSEADDR
var reuseAddr = 1
let error = setsockopt(
self.fd.rawValue,
SOL_SOCKET,
SO_REUSEADDR,
&reuseAddr,
socklen_t(MemoryLayout<Int>.stride)
)
if error != 0 {
throw SystemError(errorNumber: errno)!
}
}
if reusePort {
// Set SO_REUSEPORT
var reusePort = 1
let error = setsockopt(
self.fd.rawValue,
SOL_SOCKET,
SO_REUSEPORT,
&reusePort,
socklen_t(MemoryLayout<Int>.stride)
)
if let systemError = SystemError(errorNumber: error) {
throw systemError
}
}
self.listeningSource = DispatchSource.makeReadSource(
fileDescriptor: self.fd.rawValue,
queue: .main
)
}
public func bind(host: String, port: Port) throws {
var addrInfoPointer: UnsafeMutablePointer<addrinfo>? = nil
#if os(Linux)
var hints = Glibc.addrinfo(
ai_flags: 0,
ai_family: fd.addressFamily.rawValue,
ai_socktype: Int32(SOCK_STREAM.rawValue),
ai_protocol: Int32(IPPROTO_TCP),
ai_addrlen: 0,
ai_addr: nil,
ai_canonname: nil,
ai_next: nil
)
#else
var hints = Darwin.addrinfo(
ai_flags: 0,
ai_family: fd.addressFamily.rawValue,
ai_socktype: SOCK_STREAM,
ai_protocol: IPPROTO_TCP,
ai_addrlen: 0,
ai_canonname: nil,
ai_addr: nil,
ai_next: nil
)
#endif
let ret = getaddrinfo(host, String(port), &hints, &addrInfoPointer)
if let systemError = SystemError(errorNumber: ret) {
throw systemError
}
let addressInfo = addrInfoPointer!.pointee
#if os(Linux)
let bindRet = Glibc.bind(
fd.rawValue,
addressInfo.ai_addr,
socklen_t(MemoryLayout<sockaddr>.stride)
)
#else
let bindRet = Darwin.bind(
fd.rawValue,
addressInfo.ai_addr,
socklen_t(MemoryLayout<sockaddr>.stride)
)
#endif
freeaddrinfo(addrInfoPointer)
if bindRet != 0 {
throw SystemError(errorNumber: errno)!
}
}
public func listen(backlog: Int = 32) -> Source<Socket> {
return Source { [listeningSource = self.listeningSource, fd = self.fd] observer in
#if os(Linux)
let ret = Glibc.listen(fd.rawValue, Int32(backlog))
#else
let ret = Darwin.listen(fd.rawValue, Int32(backlog))
#endif
if ret != 0 {
observer.sendFailed(SystemError(errorNumber: errno)!)
return nil
}
listeningSource.setEventHandler {
var socketAddress = sockaddr()
var sockLen = socklen_t(MemoryLayout<sockaddr>.size)
// Accept connections
let numPendingConnections: UInt = listeningSource.data
for _ in 0..<numPendingConnections {
#if os(Linux)
let ret = Glibc.accept(fd.rawValue, &socketAddress, &sockLen)
#else
let ret = Darwin.accept(fd.rawValue, &socketAddress, &sockLen)
#endif
if ret == StandardFileDescriptor.invalid.rawValue {
observer.sendFailed(SystemError(errorNumber: errno)!)
}
let clientFileDescriptor = SocketFileDescriptor(
rawValue: ret,
socketType: SocketType.stream,
addressFamily: fd.addressFamily,
blocking: false
)
do {
// Create the client connection socket
let clientConnection = try Socket(fd: clientFileDescriptor)
observer.sendNext(clientConnection)
} catch let systemError as SystemError {
observer.sendFailed(systemError)
return
} catch {
fatalError("Unexpected error ")
}
}
}
// Close the socket when the source is canceled.
listeningSource.setCancelHandler {
fd.close()
}
if #available(OSX 10.12, *) {
listeningSource.activate()
} else {
listeningSource.resume()
}
return ActionDisposable {
listeningSource.cancel()
}
}
}
}
| mit | 93d52f90abb173ab5be097e0e7003b36 | 31.411765 | 128 | 0.506022 | 5.175918 | false | false | false | false |
chess-cf/chess.cf-ios | Chess/SettingsViewController.swift | 1 | 1739 | //
// SettingsViewController.swift
// Chess
//
// Created by Alex Studnicka on 23/12/14.
// Copyright (c) 2014 Alex Studnička. All rights reserved.
//
import UIKit
class SettingsViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserverForName("CHESSAPP_LOGIN", object: nil, queue: NSOperationQueue.mainQueue()) { _ in self.tableView.reloadData() }
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - UITableViewDataSource & UITableViewDelegate
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)
if indexPath == NSIndexPath(forRow: 0, inSection: 0) {
cell.textLabel?.text = ~"USER"
if let loginInfo = LoginInfo.fromDefaults() {
cell.detailTextLabel?.text = loginInfo.username
} else {
cell.detailTextLabel?.text = "-"
}
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath == NSIndexPath(forRow: 1, inSection: 0) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
logout()
}
}
// MARK: - Actions
func logout() {
let ud = NSUserDefaults.standardUserDefaults()
ud.setValue(nil, forKey: "token")
ud.setValue(nil, forKey: "username")
ud.synchronize()
self.tabBarController!.performSegueWithIdentifier("LoginSegue", sender: self)
}
}
| mit | f6a02724b0194525a83c7320b6d166af | 25.333333 | 162 | 0.710587 | 4.4 | false | false | false | false |
lixiangzhou/ZZSwiftTool | ZZSwiftTool/ZZSwiftTool/ZZExtension/ZZUIExtension/UITextField+ZZExtension.swift | 1 | 873 | //
// UITextField+ZZExtension.swift
// ZZSwiftTool
//
// Created by lixiangzhou on 2017/3/17.
// Copyright © 2017年 lixiangzhou. All rights reserved.
//
import UIKit
public extension UITextField {
/// 选中所有文字
func zz_selectAllText() {
guard let range = textRange(from: beginningOfDocument, to: endOfDocument) else {
return
}
selectedTextRange = range
}
/// 选中指定范围的文字
///
/// - parameter selectedRange: 指定的范围
func zz_set(selectedRange range: NSRange) {
guard let start = position(from: beginningOfDocument, offset: range.location),
let end = position(from: beginningOfDocument, offset: NSMaxRange(range)) else {
return;
}
selectedTextRange = textRange(from: start, to: end)
}
}
| mit | 622944558903b358b09a8da2dbe965b2 | 23.411765 | 91 | 0.607229 | 4.391534 | false | false | false | false |
luckymore0520/leetcode | MergeTwoSortedArray.playground/Contents.swift | 1 | 1333 | //: Playground - noun: a place where people can play
import UIKit
//
//Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
//
//Subscribe to see which companies asked this question.
//链接两个有序链表
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
}
class Solution {
func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
let result:ListNode = ListNode(0)
var head = result;
var l1 = l1;
var l2 = l2;
while l1 != nil && l2 != nil {
if (l1!.val < l2!.val) {
head.next = l1
l1 = l1?.next
} else {
head.next = l2
l2 = l2?.next
}
head = head.next!
}
if (l1 != nil) {
head.next = l1
} else if (l2 != nil) {
head.next = l2
}
return result.next
}
}
| mit | 64db7ce7b5da7b9a33a4e27fe6583809 | 22.105263 | 143 | 0.509491 | 3.648199 | false | false | false | false |
teodorpatras/EasyTipView | Sources/EasyTipView/UIKitExtensions.swift | 1 | 1458 | //
// UIKitExtensions.swift
// EasyTipView
//
// Created by Teodor Patras on 29/06/16.
// Copyright © 2016 teodorpatras. All rights reserved.
//
#if canImport(UIKit)
import UIKit
// MARK: - UIBarItem extension -
extension UIBarItem {
var view: UIView? {
if let item = self as? UIBarButtonItem, let customView = item.customView {
return customView
}
return self.value(forKey: "view") as? UIView
}
}
// MARK:- UIView extension -
extension UIView {
func hasSuperview(_ superview: UIView) -> Bool{
return viewHasSuperview(self, superview: superview)
}
fileprivate func viewHasSuperview(_ view: UIView, superview: UIView) -> Bool {
if let sview = view.superview {
if sview === superview {
return true
} else{
return viewHasSuperview(sview, superview: superview)
}
} else{
return false
}
}
}
// MARK:- CGRect extension -
extension CGRect {
var x: CGFloat {
get {
return self.origin.x
}
set {
self.origin.x = newValue
}
}
var y: CGFloat {
get {
return self.origin.y
}
set {
self.origin.y = newValue
}
}
var center: CGPoint {
return CGPoint(x: self.x + self.width / 2, y: self.y + self.height / 2)
}
}
#endif
| mit | 1dde167f2fe63a20c88c6b75f83480b9 | 19.814286 | 82 | 0.536033 | 4.310651 | false | false | false | false |
KeithPiTsui/Pavers | Pavers/Sources/UI/ReactiveCocoa/NSObject+Intercepting.swift | 1 | 16702 | import Foundation
import PaversFRP
/// Whether the runtime subclass has already been prepared for method
/// interception.
fileprivate let interceptedKey = AssociationKey(default: false)
/// Holds the method signature cache of the runtime subclass.
fileprivate let signatureCacheKey = AssociationKey<SignatureCache>()
/// Holds the method selector cache of the runtime subclass.
fileprivate let selectorCacheKey = AssociationKey<SelectorCache>()
internal let noImplementation: IMP = unsafeBitCast(Int(0), to: IMP.self)
extension Reactive where Base: NSObject {
/// Create a signal which sends a `next` event at the end of every
/// invocation of `selector` on the object.
///
/// It completes when the object deinitializes.
///
/// - note: Observers to the resulting signal should not call the method
/// specified by the selector.
///
/// - parameters:
/// - selector: The selector to observe.
///
/// - returns: A trigger signal.
public func trigger(for selector: Selector) -> Signal<(), Never> {
return base.intercept(selector).map { _ in }
}
/// Create a signal which sends a `next` event, containing an array of
/// bridged arguments, at the end of every invocation of `selector` on the
/// object.
///
/// It completes when the object deinitializes.
///
/// - note: Observers to the resulting signal should not call the method
/// specified by the selector.
///
/// - parameters:
/// - selector: The selector to observe.
///
/// - returns: A signal that sends an array of bridged arguments.
public func signal(for selector: Selector) -> Signal<[Any?], Never> {
return base.intercept(selector).map(unpackInvocation)
}
}
extension NSObject {
/// Setup the method interception.
///
/// - parameters:
/// - object: The object to be intercepted.
/// - selector: The selector of the method to be intercepted.
///
/// - returns: A signal that sends the corresponding `NSInvocation` after
/// every invocation of the method.
@nonobjc fileprivate func intercept(_ selector: Selector) -> Signal<AnyObject, Never> {
guard let method = class_getInstanceMethod(objcClass, selector) else {
fatalError("Selector `\(selector)` does not exist in class `\(String(describing: objcClass))`.")
}
let typeEncoding = method_getTypeEncoding(method)!
assert(checkTypeEncoding(typeEncoding))
return synchronized(self) {
let alias = selector.alias
let stateKey = AssociationKey<InterceptingState?>(alias)
let interopAlias = selector.interopAlias
if let state = associations.value(forKey: stateKey) {
return state.signal
}
let subclass: AnyClass = swizzleClass(self)
let subclassAssociations = Associations(subclass as AnyObject)
PaversUI.synchronized(subclass) {
let isSwizzled = subclassAssociations.value(forKey: interceptedKey)
let signatureCache: SignatureCache
let selectorCache: SelectorCache
if isSwizzled {
signatureCache = subclassAssociations.value(forKey: signatureCacheKey)
selectorCache = subclassAssociations.value(forKey: selectorCacheKey)
} else {
signatureCache = SignatureCache()
selectorCache = SelectorCache()
subclassAssociations.setValue(signatureCache, forKey: signatureCacheKey)
subclassAssociations.setValue(selectorCache, forKey: selectorCacheKey)
subclassAssociations.setValue(true, forKey: interceptedKey)
enableMessageForwarding(subclass, selectorCache)
setupMethodSignatureCaching(subclass, signatureCache)
}
selectorCache.cache(selector)
if signatureCache[selector] == nil {
let signature = NSMethodSignature.objcSignature(withObjCTypes: typeEncoding)
signatureCache[selector] = signature
}
// If an immediate implementation of the selector is found in the
// runtime subclass the first time the selector is intercepted,
// preserve the implementation.
//
// Example: KVO setters if the instance is swizzled by KVO before RAC
// does.
if !class_respondsToSelector(subclass, interopAlias) {
let immediateImpl = class_getImmediateMethod(subclass, selector)
.flatMap(method_getImplementation)
.flatMap { $0 != _rac_objc_msgForward ? $0 : nil }
if let impl = immediateImpl {
let succeeds = class_addMethod(subclass, interopAlias, impl, typeEncoding)
precondition(succeeds, "RAC attempts to swizzle a selector that has message forwarding enabled with a runtime injected implementation. This is unsupported in the current version.")
}
}
}
let state = InterceptingState(lifetime: reactive.lifetime)
associations.setValue(state, forKey: stateKey)
// Start forwarding the messages of the selector.
_ = class_replaceMethod(subclass, selector, _rac_objc_msgForward, typeEncoding)
return state.signal
}
}
}
/// Swizzle `realClass` to enable message forwarding for method interception.
///
/// - parameters:
/// - realClass: The runtime subclass to be swizzled.
private func enableMessageForwarding(_ realClass: AnyClass, _ selectorCache: SelectorCache) {
let perceivedClass: AnyClass = class_getSuperclass(realClass)!
typealias ForwardInvocationImpl = @convention(block) (Unmanaged<NSObject>, AnyObject) -> Void
let newForwardInvocation: ForwardInvocationImpl = { objectRef, invocation in
let selector = invocation.selector!
let alias = selectorCache.alias(for: selector)
let interopAlias = selectorCache.interopAlias(for: selector)
defer {
let stateKey = AssociationKey<InterceptingState?>(alias)
if let state = objectRef.takeUnretainedValue().associations.value(forKey: stateKey) {
state.observer.send(value: invocation)
}
}
let method = class_getInstanceMethod(perceivedClass, selector)
let typeEncoding: String
if let runtimeTypeEncoding = method.flatMap(method_getTypeEncoding) {
typeEncoding = String(cString: runtimeTypeEncoding)
} else {
let methodSignature = (objectRef.takeUnretainedValue() as AnyObject)
.objcMethodSignature(for: selector)
let encodings = (0 ..< methodSignature.objcNumberOfArguments!)
.map { UInt8(methodSignature.objcArgumentType(at: $0).pointee) }
typeEncoding = String(bytes: encodings, encoding: .ascii)!
}
if class_respondsToSelector(realClass, interopAlias) {
// RAC has preserved an immediate implementation found in the runtime
// subclass that was supplied by an external party.
//
// As the KVO setter relies on the selector to work, it has to be invoked
// by swapping in the preserved implementation and restore to the message
// forwarder afterwards.
//
// However, the IMP cache would be thrashed due to the swapping.
let topLevelClass: AnyClass = object_getClass(objectRef.takeUnretainedValue())!
// The locking below prevents RAC swizzling attempts from intervening the
// invocation.
//
// Given the implementation of `swizzleClass`, `topLevelClass` can only be:
// (1) the same as `realClass`; or (2) a subclass of `realClass`. In other
// words, this would deadlock only if the locking order is not followed in
// other nested locking scenarios of these metaclasses at compile time.
synchronized(topLevelClass) {
func swizzle() {
let interopImpl = class_getMethodImplementation(topLevelClass, interopAlias)!
let previousImpl = class_replaceMethod(topLevelClass, selector, interopImpl, typeEncoding)
invocation.objcInvoke()
_ = class_replaceMethod(topLevelClass, selector, previousImpl ?? noImplementation, typeEncoding)
}
if topLevelClass != realClass {
synchronized(realClass) {
// In addition to swapping in the implementation, the message
// forwarding needs to be temporarily disabled to prevent circular
// invocation.
_ = class_replaceMethod(realClass, selector, noImplementation, typeEncoding)
swizzle()
_ = class_replaceMethod(realClass, selector, _rac_objc_msgForward, typeEncoding)
}
} else {
swizzle()
}
}
return
}
let impl: IMP = method.map(method_getImplementation) ?? _rac_objc_msgForward
if impl != _rac_objc_msgForward {
// The perceived class, or its ancestors, responds to the selector.
//
// The implementation is invoked through the selector alias, which
// reflects the latest implementation of the selector in the perceived
// class.
if class_getMethodImplementation(realClass, alias) != impl {
// Update the alias if and only if the implementation has changed, so as
// to avoid thrashing the IMP cache.
_ = class_replaceMethod(realClass, alias, impl, typeEncoding)
}
invocation.objcSetSelector(alias)
invocation.objcInvoke()
return
}
// Forward the invocation to the closest `forwardInvocation(_:)` in the
// inheritance hierarchy, or the default handler returned by the runtime
// if it finds no implementation.
typealias SuperForwardInvocation = @convention(c) (Unmanaged<NSObject>, Selector, AnyObject) -> Void
let forwardInvocationImpl = class_getMethodImplementation(perceivedClass, ObjCSelector.forwardInvocation)
let forwardInvocation = unsafeBitCast(forwardInvocationImpl, to: SuperForwardInvocation.self)
forwardInvocation(objectRef, ObjCSelector.forwardInvocation, invocation)
}
_ = class_replaceMethod(realClass,
ObjCSelector.forwardInvocation,
imp_implementationWithBlock(newForwardInvocation as Any),
ObjCMethodEncoding.forwardInvocation)
}
/// Swizzle `realClass` to accelerate the method signature retrieval, using a
/// signature cache that covers all known intercepted selectors of `realClass`.
///
/// - parameters:
/// - realClass: The runtime subclass to be swizzled.
/// - signatureCache: The method signature cache.
private func setupMethodSignatureCaching(_ realClass: AnyClass, _ signatureCache: SignatureCache) {
let perceivedClass: AnyClass = class_getSuperclass(realClass)!
let newMethodSignatureForSelector: @convention(block) (Unmanaged<NSObject>, Selector) -> AnyObject? = { objectRef, selector in
if let signature = signatureCache[selector] {
return signature
}
typealias SuperMethodSignatureForSelector = @convention(c) (Unmanaged<NSObject>, Selector, Selector) -> AnyObject?
let impl = class_getMethodImplementation(perceivedClass, ObjCSelector.methodSignatureForSelector)
let methodSignatureForSelector = unsafeBitCast(impl, to: SuperMethodSignatureForSelector.self)
return methodSignatureForSelector(objectRef, ObjCSelector.methodSignatureForSelector, selector)
}
_ = class_replaceMethod(realClass,
ObjCSelector.methodSignatureForSelector,
imp_implementationWithBlock(newMethodSignatureForSelector as Any),
ObjCMethodEncoding.methodSignatureForSelector)
}
/// The state of an intercepted method specific to an instance.
private final class InterceptingState {
let (signal, observer) = Signal<AnyObject, Never>.pipe()
/// Initialize a state specific to an instance.
///
/// - parameters:
/// - lifetime: The lifetime of the instance.
init(lifetime: Lifetime) {
lifetime.ended.observeCompleted(observer.sendCompleted)
}
}
private final class SelectorCache {
private var map: [Selector: (main: Selector, interop: Selector)] = [:]
init() {}
/// Cache the aliases of the specified selector in the cache.
///
/// - warning: Any invocation of this method must be synchronized against the
/// runtime subclass.
@discardableResult
func cache(_ selector: Selector) -> (main: Selector, interop: Selector) {
if let pair = map[selector] {
return pair
}
let aliases = (selector.alias, selector.interopAlias)
map[selector] = aliases
return aliases
}
/// Get the alias of the specified selector.
///
/// - parameters:
/// - selector: The selector alias.
func alias(for selector: Selector) -> Selector {
if let (main, _) = map[selector] {
return main
}
return selector.alias
}
/// Get the secondary alias of the specified selector.
///
/// - parameters:
/// - selector: The selector alias.
func interopAlias(for selector: Selector) -> Selector {
if let (_, interop) = map[selector] {
return interop
}
return selector.interopAlias
}
}
// The signature cache for classes that have been swizzled for method
// interception.
//
// Read-copy-update is used here, since the cache has multiple readers but only
// one writer.
private final class SignatureCache {
// `Dictionary` takes 8 bytes for the reference to its storage and does CoW.
// So it should not encounter any corrupted, partially updated state.
private var map: [Selector: AnyObject] = [:]
init() {}
/// Get or set the signature for the specified selector.
///
/// - warning: Any invocation of the setter must be synchronized against the
/// runtime subclass.
///
/// - parameters:
/// - selector: The method signature.
subscript(selector: Selector) -> AnyObject? {
get {
return map[selector]
}
set {
if map[selector] == nil {
map[selector] = newValue
}
}
}
}
/// Assert that the method does not contain types that cannot be intercepted.
///
/// - parameters:
/// - types: The type encoding C string of the method.
///
/// - returns: `true`.
private func checkTypeEncoding(_ types: UnsafePointer<CChar>) -> Bool {
// Some types, including vector types, are not encoded. In these cases the
// signature starts with the size of the argument frame.
assert(types.pointee < Int8(UInt8(ascii: "1")) || types.pointee > Int8(UInt8(ascii: "9")),
"unknown method return type not supported in type encoding: \(String(cString: types))")
assert(types.pointee != Int8(UInt8(ascii: "(")), "union method return type not supported")
assert(types.pointee != Int8(UInt8(ascii: "{")), "struct method return type not supported")
assert(types.pointee != Int8(UInt8(ascii: "[")), "array method return type not supported")
assert(types.pointee != Int8(UInt8(ascii: "j")), "complex method return type not supported")
return true
}
/// Extract the arguments of an `NSInvocation` as an array of objects.
///
/// - parameters:
/// - invocation: The `NSInvocation` to unpack.
///
/// - returns: An array of objects.
private func unpackInvocation(_ invocation: AnyObject) -> [Any?] {
let invocation = invocation as AnyObject
let methodSignature = invocation.objcMethodSignature!
let count = methodSignature.objcNumberOfArguments!
var bridged = [Any?]()
bridged.reserveCapacity(Int(count - 2))
// Ignore `self` and `_cmd` at index 0 and 1.
for position in 2 ..< count {
let rawEncoding = methodSignature.objcArgumentType(at: position)
let encoding = ObjCTypeEncoding(rawValue: rawEncoding.pointee) ?? .undefined
func extract<U>(_ type: U.Type) -> U {
let pointer = UnsafeMutableRawPointer.allocate(byteCount: MemoryLayout<U>.size,
alignment: MemoryLayout<U>.alignment)
defer {
pointer.deallocate()
}
invocation.objcCopy(to: pointer, forArgumentAt: Int(position))
return pointer.assumingMemoryBound(to: type).pointee
}
let value: Any?
switch encoding {
case .char:
value = NSNumber(value: extract(CChar.self))
case .int:
value = NSNumber(value: extract(CInt.self))
case .short:
value = NSNumber(value: extract(CShort.self))
case .long:
value = NSNumber(value: extract(CLong.self))
case .longLong:
value = NSNumber(value: extract(CLongLong.self))
case .unsignedChar:
value = NSNumber(value: extract(CUnsignedChar.self))
case .unsignedInt:
value = NSNumber(value: extract(CUnsignedInt.self))
case .unsignedShort:
value = NSNumber(value: extract(CUnsignedShort.self))
case .unsignedLong:
value = NSNumber(value: extract(CUnsignedLong.self))
case .unsignedLongLong:
value = NSNumber(value: extract(CUnsignedLongLong.self))
case .float:
value = NSNumber(value: extract(CFloat.self))
case .double:
value = NSNumber(value: extract(CDouble.self))
case .bool:
value = NSNumber(value: extract(CBool.self))
case .object:
value = extract((AnyObject?).self)
case .type:
value = extract((AnyClass?).self)
case .selector:
value = extract((Selector?).self)
case .undefined:
var size = 0, alignment = 0
NSGetSizeAndAlignment(rawEncoding, &size, &alignment)
let buffer = UnsafeMutableRawPointer.allocate(byteCount: size, alignment: alignment)
defer { buffer.deallocate() }
invocation.objcCopy(to: buffer, forArgumentAt: Int(position))
value = NSValue(bytes: buffer, objCType: rawEncoding)
}
bridged.append(value)
}
return bridged
}
| mit | 87a457cfe0114f11a0f210859fe6fed8 | 34.688034 | 186 | 0.716022 | 4.262889 | false | false | false | false |
HQL-yunyunyun/SinaWeiBo | SinaWeiBo/SinaWeiBo/Class/HQLConsant.swift | 1 | 1176 | //
// HQLConsant.swift
// SinaWeiBo
//
// Created by 何启亮 on 16/5/12.
// Copyright © 2016年 HQL. All rights reserved.
//
import UIKit
// 不是在类里面的代码,全局的
// 全局的打印方法,在debug模式下会输出,在release模式下不输出
/// 哪个文件,哪一行,哪个方法
func CZPrint(file: String = #file, line: Int = #line, function: String = #function, items: Any) {
// 默认参数,如果调用的人不传递使用默认参数
// Swift在DEBUG模式下并没有这个宏, 需要自己手动配置 buildSetting -> 搜索 swift flag,在DEBUG模式下配置 -D DEBUG
#if DEBUG
print("文件: \((file as NSString).lastPathComponent), 行数: \(line), 函数: \(function): => \(items) \n")
#endif
}
/// 全局的背景颜色
let GlobalBKColor: UIColor = UIColor.whiteColor()
/// 网址:https://api.weibo.com/oauth2/authorize
let oauthURLString = "https://api.weibo.com/oauth2/authorize"
/// 申请应用的id 4291339252
let client_id = "4291339252"
/// 密码 申请应用时分配的AppSecret
let client_secret = "399defe2546b1b78d601717e56a7e98c"
/// 回调网址
let redirect_uri = "http://www.baidu.com" | apache-2.0 | 54c7a43bf7bfb4b6a8de2f65a7ee1f53 | 25.285714 | 106 | 0.68988 | 2.656069 | false | false | false | false |
romankisil/eqMac2 | native/app/Source/UI/UIDataBus.swift | 1 | 6280 | //
// UIRoute.swift
// eqMac
//
// Created by Roman Kisil on 26/12/2018.
// Copyright © 2018 Roman Kisil. All rights reserved.
//
import Foundation
import SwiftyJSON
import EmitterKit
class UIDataBus: DataBus {
var state: UIState {
return Application.store.state.ui
}
var isShownChangedListener: EventListener<Bool>?
required init(route: String, bridge: Bridge) {
super.init(route: route, bridge: bridge)
self.on(.GET, "/close") { _, _ in
UI.close()
return "Closed"
}
self.on(.GET, "/hide") { _, _ in
UI.hide()
return "Hidden"
}
self.on(.GET, "/height") { _, res in
DispatchQueue.main.async {
res.send([ "height": self.state.height ])
}
return nil
}
self.on(.POST, "/height") { data, _ in
guard let height = data["height"] as? Double, height > 0 else {
throw "Please provide a valid 'height' parameter."
}
Application.dispatchAction(UIAction.setHeight(height, true))
return "UI Height has been set"
}
self.on(.GET, "/width") { _, res in
DispatchQueue.main.async {
res.send([ "width": self.state.width ])
}
return nil
}
self.on(.GET, "/width") { _, res in
DispatchQueue.main.async {
res.send([ "width": self.state.width ])
}
return nil
}
self.on(.POST, "/width") { data, _ in
guard let width = data["width"] as? Double, width > 0 else {
throw "Please provide a valid 'width' parameter."
}
Application.dispatchAction(UIAction.setWidth(width, true))
return "UI Width has been set"
}
self.on(.GET, "/settings") { _, _ in
return self.state.settings
}
self.on(.GET, "/settings") { _, _ in
return self.state.settings
}
self.on(.POST, "/settings") { data, _ in
if let newSettings = data {
if let settings = try? self.state.settings.merged(with: newSettings) {
Application.dispatchAction(UIAction.setSettings(settings))
return settings
}
}
return self.state.settings
}
self.on(.GET, "/mode") { data, _ in
return [ "mode": Application.store.state.ui.mode.rawValue ]
}
self.on(.POST, "/mode") { data, _ in
let uiModeRaw = data["mode"] as? String
if uiModeRaw != nil, let uiMode = UIMode(rawValue: uiModeRaw!) {
Application.dispatchAction(UIAction.setMode(uiMode))
return "UI Mode has been set"
}
throw "Please provide a valid 'uiMode' parameter."
}
self.on(.GET, "/shown") { data, res in
DispatchQueue.main.async {
res.send([ "isShown": UI.isShown ])
}
return nil
}
self.on(.POST, "/loaded") { _, _ in
UI.hasLoaded = true
UI.loaded.emit()
return "Thanks"
}
self.on(.GET, "/always-on-top") { _, _ in
return [ "alwaysOnTop": self.state.alwaysOnTop ]
}
self.on(.POST, "/always-on-top") { data, _ in
let alwaysOnTop = data["alwaysOnTop"] as? Bool
if alwaysOnTop == nil {
throw "Invalid 'alwaysOnTop' parameter, must be a boolean."
}
Application.dispatchAction(UIAction.setAlwaysOnTop(alwaysOnTop!))
return "Always on top has been set."
}
self.on(.GET, "/status-item-icon-type") { _, _ in
return [ "statusItemIconType": self.state.statusItemIconType.rawValue ]
}
self.on(.POST, "/status-item-icon-type") { data, _ in
let typeRaw = data["statusItemIconType"] as? String
if typeRaw != nil, let type = StatusItemIconType(rawValue: typeRaw!) {
Application.dispatchAction(UIAction.setStatusItemIconType(type))
return "Status Item Icon type has been set"
}
throw "Please provide a valid 'statusItemIconType' parameter"
}
self.on(.GET, "/min-height") { _, _ in
return [ "minHeight": self.state.minHeight ]
}
self.on(.POST, "/min-height") { data, _ in
guard let minHeight = data["minHeight"] as? Double else {
throw "Please provide a valid 'minHeight' parameter, must be a Float value"
}
Application.dispatchAction(UIAction.setMinHeight(minHeight))
return "Min Height has been set"
}
self.on(.GET, "/min-width") { _, _ in
return [ "minWidth": self.state.minWidth ]
}
self.on(.POST, "/min-width") { data, _ in
guard let minWidth = data["minWidth"] as? Double else {
throw "Please provide a valid 'minWidth' parameter, must be a Float value"
}
Application.dispatchAction(UIAction.setMinWidth(minWidth))
return "Min Width has been set"
}
self.on(.GET, "/max-height") { _, _ in
return [ "maxHeight": self.state.maxHeight ]
}
self.on(.POST, "/max-height") { data, _ in
let maxHeight = data["maxHeight"] as? Double
Application.dispatchAction(UIAction.setMaxHeight(maxHeight))
return "Max Height has been set"
}
self.on(.GET, "/max-width") { _, _ in
return [ "maxWidth": self.state.maxWidth ]
}
self.on(.POST, "/max-width") { data, _ in
let maxWidth = data["maxWidth"] as? Double
Application.dispatchAction(UIAction.setMaxWidth(maxWidth))
return "Min Width has been set"
}
self.on(.GET, "/scale") { _, _ in
return [ "scale": self.state.scale ]
}
self.on(.POST, "/scale") { data, _ in
guard let scale = data["scale"] as? Double, (0.5...2.0).contains(scale) else {
throw "Invalid 'scale' parameter, must be a Double in range 0.5...2.0"
}
Application.dispatchAction(UIAction.setScale(scale))
return "UI Scale has been set"
}
self.isShownChangedListener = UI.isShownChanged.on { isShown in
self.send(to: "/shown", data: JSON([ "isShown": isShown ]))
}
self.on(.GET, "/resizable") { _, _ in
return [ "resizable": self.state.resizable ]
}
self.on(.POST, "/resizable") { data, _ in
guard let resizable = data["resizable"] as? Bool else {
throw "Invalid 'resizable' parameter, must be a boolean."
}
Application.dispatchAction(UIAction.setResizable(resizable))
return "Resizable parameter has been set"
}
}
}
| mit | 381dd3d73f25758cbcc5784bb8591dff | 27.156951 | 84 | 0.589584 | 3.812386 | false | false | false | false |
luckyx1/flicks | flicks/DetailViewController.swift | 1 | 1762 | //
// DetailViewController.swift
// flicks
//
// Created by Rob Hernandez on 1/22/17.
// Copyright © 2017 Robert Hernandez. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var infoView: UIView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var posterView: UIImageView!
@IBOutlet weak var overviewLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
var movie: NSDictionary!
override func viewDidLoad() {
super.viewDidLoad()
scrollView.contentSize = CGSize(width: scrollView.frame.size.width, height: infoView.frame.origin.y + infoView.frame.size.height)
let title = movie["title"] as? String
titleLabel.text = title
let overview = movie["overview"] as? String
overviewLabel.text = overview
overviewLabel.sizeToFit()
// Attempt to get the poster_path and set into the cell
if let posterPath = movie["poster_path"] as? String{
let baseUrl = "https://image.tmdb.org/t/p/w500/"
let imageUrl = NSURL(string: baseUrl + posterPath)
posterView.setImageWith(imageUrl as! URL)
}
}
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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 7e440f6619fdcc60fe7e2c843ff8ff89 | 29.894737 | 137 | 0.654742 | 4.746631 | false | false | false | false |
haskellswift/swift-package-manager | Tests/PackageGraphTests/RepositoryPackageContainerProviderTests.swift | 1 | 6855 | /*
This source file is part of the Swift.org open source project
Copyright 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import Basic
import PackageDescription
import PackageLoading
import PackageModel
import PackageGraph
import SourceControl
import TestSupport
private class MockRepository: Repository {
/// The fake URL of the repository.
let url: String
/// The known repository versions, as a map of tags to manifests.
let versions: [Version: Manifest]
init(url: String, versions: [Version: Manifest]) {
self.url = url
self.versions = versions
}
var specifier: RepositorySpecifier {
return RepositorySpecifier(url: url)
}
var tags: [String] {
return versions.keys.map{ String(describing: $0) }
}
func resolveRevision(tag: String) throws -> Revision {
assert(versions.index(forKey: Version(tag)!) != nil)
return Revision(identifier: tag)
}
func fetch() throws {
fatalError("Unexpected API call")
}
func remove() throws {
fatalError("Unexpected API call")
}
func openFileView(revision: Revision) throws -> FileSystem {
assert(versions.index(forKey: Version(revision.identifier)!) != nil)
// This isn't actually used, see `MockManifestLoader`.
return InMemoryFileSystem()
}
}
private class MockRepositories: RepositoryProvider {
/// The known repositories, as a map of URL to repository.
let repositories: [String: MockRepository]
/// A mock manifest loader for all repositories.
let manifestLoader: MockManifestLoader
init(repositories repositoryList: [MockRepository]) {
var allManifests: [MockManifestLoader.Key: Manifest] = [:]
var repositories: [String: MockRepository] = [:]
for repository in repositoryList {
assert(repositories.index(forKey: repository.url) == nil)
repositories[repository.url] = repository
for (version, manifest) in repository.versions {
allManifests[MockManifestLoader.Key(url: repository.url, version: version)] = manifest
}
}
self.repositories = repositories
self.manifestLoader = MockManifestLoader(manifests: allManifests)
}
func fetch(repository: RepositorySpecifier, to path: AbsolutePath) throws {
// No-op.
assert(repositories.index(forKey: repository.url) != nil)
}
func open(repository: RepositorySpecifier, at path: AbsolutePath) throws -> Repository {
return repositories[repository.url]!
}
func cloneCheckout(repository: RepositorySpecifier, at sourcePath: AbsolutePath, to destinationPath: AbsolutePath, editable: Bool) throws {
fatalError("unexpected API call")
}
func openCheckout(at path: AbsolutePath) throws -> WorkingCheckout {
fatalError("unexpected API call")
}
}
private class MockResolverDelegate: DependencyResolverDelegate, RepositoryManagerDelegate {
typealias Identifier = RepositoryPackageContainer.Identifier
var addedContainers: [Identifier] = []
var fetched = [RepositorySpecifier]()
func added(container identifier: Identifier) {
addedContainers.append(identifier)
}
func fetching(handle: RepositoryManager.RepositoryHandle, to path: AbsolutePath) {
fetched += [handle.repository]
}
}
private struct MockDependencyResolver {
let tmpDir: TemporaryDirectory
let repositories: MockRepositories
let delegate: MockResolverDelegate
private let resolver: DependencyResolver<RepositoryPackageContainerProvider, MockResolverDelegate>
init(repositories: MockRepository...) {
self.tmpDir = try! TemporaryDirectory()
self.repositories = MockRepositories(repositories: repositories)
self.delegate = MockResolverDelegate()
let repositoryManager = RepositoryManager(path: self.tmpDir.path, provider: self.repositories, delegate: self.delegate)
let provider = RepositoryPackageContainerProvider(
repositoryManager: repositoryManager, manifestLoader: self.repositories.manifestLoader)
self.resolver = DependencyResolver(provider, delegate)
}
func resolve(constraints: [RepositoryPackageConstraint]) throws -> [(container: RepositorySpecifier, version: Version)] {
return try resolver.resolve(constraints: constraints)
}
}
// Some handy versions & ranges.
//
// The convention is that the name matches how specific the version is, so "v1"
// means "any 1.?.?", and "v1_1" means "any 1.1.?".
private let v1: Version = "1.0.0"
private let v2: Version = "2.0.0"
private let v1Range: VersionSetSpecifier = .range("1.0.0" ..< "2.0.0")
class RepositoryPackageContainerProviderTests: XCTestCase {
func testBasics() {
mktmpdir{ path in
let repoA = MockRepository(
url: "A",
versions: [
v1: Manifest(
path: AbsolutePath("/Package.swift"),
url: "A",
package: PackageDescription.Package(
name: "Foo",
dependencies: [
.Package(url: "B", majorVersion: 2)
]
),
products: [],
version: v1
)
])
let repoB = MockRepository(
url: "B",
versions: [
v2: Manifest(
path: AbsolutePath("/Package.swift"),
url: "B",
package: PackageDescription.Package(
name: "Bar"),
products: [],
version: v2
)
])
let resolver = MockDependencyResolver(repositories: repoA, repoB)
let constraints = [
RepositoryPackageConstraint(
container: repoA.specifier,
versionRequirement: v1Range)
]
let result = try resolver.resolve(constraints: constraints)
XCTAssertEqual(result, [
repoA.specifier: v1,
repoB.specifier: v2,
])
XCTAssertEqual(resolver.delegate.addedContainers, [repoA.specifier, repoB.specifier])
XCTAssertEqual(resolver.delegate.fetched, [repoA.specifier, repoB.specifier])
}
}
static var allTests = [
("testBasics", testBasics),
]
}
| apache-2.0 | c05ae91b42eb7fb3224c0f4c5e6c0b66 | 33.621212 | 143 | 0.622319 | 5.146396 | false | false | false | false |
grahamearley/YoungChefs | Source/Young Chefs/Young Chefs/ScreenView.swift | 1 | 2294 | //
// ScreenView.swift
// Young Chefs
//
// Julia Bindler
// Graham Earley
// Charlie Imhoff
//
import WebKit
import UIKit
/**
ScreenView is a subclass of WKWebView for rendering and interacting with Screens.
Experiment pages are stored as HTML files, and this class presents them in a subview of the experiment view (in a smaller section).
*/
class ScreenView : WKWebView {
//MARK: - Screen Content
/// The currently displayed screen (read-only)
private(set) var currentScreen : Screen
/// Inits a new ScreenView with the specified frame, configuration, and screen
init(frame: CGRect, configuration: WKWebViewConfiguration, screen: Screen) {
self.currentScreen = screen
super.init(frame: frame, configuration: configuration)
self.loadScreen(self.currentScreen)
}
/// Loads a new screen into this view
func loadScreen(newScreen: Screen) {
if let fixedURL = WKWebView.convertURLToBugCompatibleURL(newScreen.htmlURL) {
let request = NSURLRequest(URL: fixedURL, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
self.loadRequest(request)
self.currentScreen = newScreen
} else {
println("failed to copy web resouce to `temp/www` directory")
}
}
//MARK: - JavaSwift
/**
Runs through the file and calls 'fillKeyedHTMLWithValue()' for each key in the responseKeys dictionary passed into it.
This basically fills question boxes with previously answered values.
*/
func fillKeyedHTMLWithValues(keysAndValues : [String:String]) {
for key in keysAndValues.keys {
if let value = keysAndValues[key] {
//you have to escape newline characters twice, because they feed through the Swift (1 time)
//and then into the js (2ed time)
let cleanedVal = value.stringByReplacingOccurrencesOfString("\n", withString: "\\n", options: nil, range: nil)
self.evaluateJavaScriptNoReturn("fillKeyedHTMLWithValue(\"\(key)\",\"\(cleanedVal)\");")
}
}
}
/// Shorthand for evaluating a JavaScript string with no return value. Prints errors to console.
func evaluateJavaScriptNoReturn(javascript: String) {
self.evaluateJavaScript(javascript, completionHandler: { (returnedVal:AnyObject!, error:NSError?) -> Void in
if error != nil {
println(error!.description)
}
})
}
} | mit | 10f874907ffc71f4de8a0d7f6e75ca3a | 31.323944 | 131 | 0.732781 | 4.017513 | false | true | false | false |
BelledonneCommunications/linphone-iphone | Classes/Swift/Voip/Widgets/FormButton.swift | 1 | 1696 | /*
* Copyright (c) 2010-2020 Belledonne Communications SARL.
*
* This file is part of linphone-iphone
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
import UIKit
import SwiftUI
class FormButton : ButtonWithStateBackgrounds {
let button_radius = 3.0
let button_height = 40.0
required init?(coder: NSCoder) {
super.init(coder: coder)
}
var title: String? {
didSet {
setTitle(title, for: .normal)
addSidePadding()
}
}
init (backgroundStateColors: [UInt: LightDarkColor], bold:Bool = true) {
super.init(backgroundStateColors: backgroundStateColors)
layer.cornerRadius = button_radius
clipsToBounds = true
applyTitleStyle(bold ? VoipTheme.form_button_bold : VoipTheme.form_button_light)
height(button_height).done()
addSidePadding()
}
convenience init (title:String, backgroundStateColors: [UInt: LightDarkColor], bold:Bool = true, fixedSize:Bool = true) {
self.init(backgroundStateColors: backgroundStateColors,bold:bold)
self.title = title
setTitle(title, for: .normal)
if (!fixedSize) {
addSidePadding()
}
}
}
| gpl-3.0 | a41b4c4037c9b8d2e3589f5218350dd1 | 27.266667 | 122 | 0.733491 | 3.639485 | false | false | false | false |
williamgp/ENSwiftSideMenu | Library/ENSideMenu.swift | 5 | 15705 | //
// SideMenu.swift
// SwiftSideMenu
//
// Created by Evgeny on 24.07.14.
// Copyright (c) 2014 Evgeny Nazarov. All rights reserved.
//
import UIKit
@objc public protocol ENSideMenuDelegate {
optional func sideMenuWillOpen()
optional func sideMenuWillClose()
optional func sideMenuDidOpen()
optional func sideMenuDidClose()
optional func sideMenuShouldOpenSideMenu () -> Bool
}
@objc public protocol ENSideMenuProtocol {
var sideMenu : ENSideMenu? { get }
func setContentViewController(contentViewController: UIViewController)
}
public enum ENSideMenuAnimation : Int {
case None
case Default
}
/**
The position of the side view on the screen.
- Left: Left side of the screen
- Right: Right side of the screen
*/
public enum ENSideMenuPosition : Int {
case Left
case Right
}
public extension UIViewController {
/**
Changes current state of side menu view.
*/
public func toggleSideMenuView () {
sideMenuController()?.sideMenu?.toggleMenu()
}
/**
Hides the side menu view.
*/
public func hideSideMenuView () {
sideMenuController()?.sideMenu?.hideSideMenu()
}
/**
Shows the side menu view.
*/
public func showSideMenuView () {
sideMenuController()?.sideMenu?.showSideMenu()
}
/**
Returns a Boolean value indicating whether the side menu is showed.
:returns: BOOL value
*/
public func isSideMenuOpen () -> Bool {
let sieMenuOpen = self.sideMenuController()?.sideMenu?.isMenuOpen
return sieMenuOpen!
}
/**
* You must call this method from viewDidLayoutSubviews in your content view controlers so it fixes size and position of the side menu when the screen
* rotates.
* A convenient way to do it might be creating a subclass of UIViewController that does precisely that and then subclassing your view controllers from it.
*/
func fixSideMenuSize() {
if let navController = self.navigationController as? ENSideMenuNavigationController {
navController.sideMenu?.updateFrame()
}
}
/**
Returns a view controller containing a side menu
:returns: A `UIViewController`responding to `ENSideMenuProtocol` protocol
*/
public func sideMenuController () -> ENSideMenuProtocol? {
var iteration : UIViewController? = self.parentViewController
if (iteration == nil) {
return topMostController()
}
do {
if (iteration is ENSideMenuProtocol) {
return iteration as? ENSideMenuProtocol
} else if (iteration?.parentViewController != nil && iteration?.parentViewController != iteration) {
iteration = iteration!.parentViewController
} else {
iteration = nil
}
} while (iteration != nil)
return iteration as? ENSideMenuProtocol
}
internal func topMostController () -> ENSideMenuProtocol? {
var topController : UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController
if (topController is UITabBarController) {
topController = (topController as! UITabBarController).selectedViewController
}
while (topController?.presentedViewController is ENSideMenuProtocol) {
topController = topController?.presentedViewController
}
return topController as? ENSideMenuProtocol
}
}
public class ENSideMenu : NSObject, UIGestureRecognizerDelegate {
/// The width of the side menu view. The default value is 160.
public var menuWidth : CGFloat = 160.0 {
didSet {
needUpdateApperance = true
updateFrame()
}
}
private var menuPosition:ENSideMenuPosition = .Left
/// A Boolean value indicating whether the bouncing effect is enabled. The default value is TRUE.
public var bouncingEnabled :Bool = true
/// The duration of the slide animation. Used only when `bouncingEnabled` is FALSE.
public var animationDuration = 0.4
private let sideMenuContainerView = UIView()
private var menuViewController : UIViewController!
private var animator : UIDynamicAnimator!
private var sourceView : UIView!
private var needUpdateApperance : Bool = false
/// The delegate of the side menu
public weak var delegate : ENSideMenuDelegate?
private(set) var isMenuOpen : Bool = false
/// A Boolean value indicating whether the left swipe is enabled.
public var allowLeftSwipe : Bool = true
/// A Boolean value indicating whether the right swipe is enabled.
public var allowRightSwipe : Bool = true
/**
Initializes an instance of a `ENSideMenu` object.
:param: sourceView The parent view of the side menu view.
:param: menuPosition The position of the side menu view.
:returns: An initialized `ENSideMenu` object, added to the specified view.
*/
public init(sourceView: UIView, menuPosition: ENSideMenuPosition) {
super.init()
self.sourceView = sourceView
self.menuPosition = menuPosition
self.setupMenuView()
animator = UIDynamicAnimator(referenceView:sourceView)
animator.delegate = self
// Add right swipe gesture recognizer
let rightSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleGesture:")
rightSwipeGestureRecognizer.delegate = self
rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Right
// Add left swipe gesture recognizer
let leftSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleGesture:")
leftSwipeGestureRecognizer.delegate = self
leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Left
if (menuPosition == .Left) {
sourceView.addGestureRecognizer(rightSwipeGestureRecognizer)
sideMenuContainerView.addGestureRecognizer(leftSwipeGestureRecognizer)
}
else {
sideMenuContainerView.addGestureRecognizer(rightSwipeGestureRecognizer)
sourceView.addGestureRecognizer(leftSwipeGestureRecognizer)
}
}
/**
Initializes an instance of a `ENSideMenu` object.
:param: sourceView The parent view of the side menu view.
:param: menuViewController A menu view controller object which will be placed in the side menu view.
:param: menuPosition The position of the side menu view.
:returns: An initialized `ENSideMenu` object, added to the specified view, containing the specified menu view controller.
*/
public convenience init(sourceView: UIView, menuViewController: UIViewController, menuPosition: ENSideMenuPosition) {
self.init(sourceView: sourceView, menuPosition: menuPosition)
self.menuViewController = menuViewController
self.menuViewController.view.frame = sideMenuContainerView.bounds
self.menuViewController.view.autoresizingMask = .FlexibleHeight | .FlexibleWidth
sideMenuContainerView.addSubview(self.menuViewController.view)
}
/*
public convenience init(sourceView: UIView, view: UIView, menuPosition: ENSideMenuPosition) {
self.init(sourceView: sourceView, menuPosition: menuPosition)
view.frame = sideMenuContainerView.bounds
view.autoresizingMask = .FlexibleHeight | .FlexibleWidth
sideMenuContainerView.addSubview(view)
}
*/
/**
Updates the frame of the side menu view.
*/
func updateFrame() {
var width:CGFloat
var height:CGFloat
(width, height) = adjustFrameDimensions( sourceView.frame.size.width, height: sourceView.frame.size.height)
let menuFrame = CGRectMake(
(menuPosition == .Left) ?
isMenuOpen ? 0 : -menuWidth-1.0 :
isMenuOpen ? width - menuWidth : width+1.0,
sourceView.frame.origin.y,
menuWidth,
height
)
sideMenuContainerView.frame = menuFrame
}
private func adjustFrameDimensions( width: CGFloat, height: CGFloat ) -> (CGFloat,CGFloat) {
if floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1 &&
(UIApplication.sharedApplication().statusBarOrientation == UIInterfaceOrientation.LandscapeRight ||
UIApplication.sharedApplication().statusBarOrientation == UIInterfaceOrientation.LandscapeLeft) {
// iOS 7.1 or lower and landscape mode -> interchange width and height
return (height, width)
}
else {
return (width, height)
}
}
private func setupMenuView() {
// Configure side menu container
updateFrame()
sideMenuContainerView.backgroundColor = UIColor.clearColor()
sideMenuContainerView.clipsToBounds = false
sideMenuContainerView.layer.masksToBounds = false
sideMenuContainerView.layer.shadowOffset = (menuPosition == .Left) ? CGSizeMake(1.0, 1.0) : CGSizeMake(-1.0, -1.0)
sideMenuContainerView.layer.shadowRadius = 1.0
sideMenuContainerView.layer.shadowOpacity = 0.125
sideMenuContainerView.layer.shadowPath = UIBezierPath(rect: sideMenuContainerView.bounds).CGPath
sourceView.addSubview(sideMenuContainerView)
if (NSClassFromString("UIVisualEffectView") != nil) {
// Add blur view
var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) as UIVisualEffectView
visualEffectView.frame = sideMenuContainerView.bounds
visualEffectView.autoresizingMask = .FlexibleHeight | .FlexibleWidth
sideMenuContainerView.addSubview(visualEffectView)
}
else {
// TODO: add blur for ios 7
}
}
private func toggleMenu (shouldOpen: Bool) {
if (shouldOpen && delegate?.sideMenuShouldOpenSideMenu?() == false) {
return
}
updateSideMenuApperanceIfNeeded()
isMenuOpen = shouldOpen
var width:CGFloat
var height:CGFloat
(width, height) = adjustFrameDimensions( sourceView.frame.size.width, height: sourceView.frame.size.height)
if (bouncingEnabled) {
animator.removeAllBehaviors()
var gravityDirectionX: CGFloat
var pushMagnitude: CGFloat
var boundaryPointX: CGFloat
var boundaryPointY: CGFloat
if (menuPosition == .Left) {
// Left side menu
gravityDirectionX = (shouldOpen) ? 1 : -1
pushMagnitude = (shouldOpen) ? 20 : -20
boundaryPointX = (shouldOpen) ? menuWidth : -menuWidth-2
boundaryPointY = 20
}
else {
// Right side menu
gravityDirectionX = (shouldOpen) ? -1 : 1
pushMagnitude = (shouldOpen) ? -20 : 20
boundaryPointX = (shouldOpen) ? width-menuWidth : width+menuWidth+2
boundaryPointY = -20
}
let gravityBehavior = UIGravityBehavior(items: [sideMenuContainerView])
gravityBehavior.gravityDirection = CGVectorMake(gravityDirectionX, 0)
animator.addBehavior(gravityBehavior)
let collisionBehavior = UICollisionBehavior(items: [sideMenuContainerView])
collisionBehavior.addBoundaryWithIdentifier("menuBoundary", fromPoint: CGPointMake(boundaryPointX, boundaryPointY),
toPoint: CGPointMake(boundaryPointX, height))
animator.addBehavior(collisionBehavior)
let pushBehavior = UIPushBehavior(items: [sideMenuContainerView], mode: UIPushBehaviorMode.Instantaneous)
pushBehavior.magnitude = pushMagnitude
animator.addBehavior(pushBehavior)
let menuViewBehavior = UIDynamicItemBehavior(items: [sideMenuContainerView])
menuViewBehavior.elasticity = 0.25
animator.addBehavior(menuViewBehavior)
}
else {
var destFrame :CGRect
if (menuPosition == .Left) {
destFrame = CGRectMake((shouldOpen) ? -2.0 : -menuWidth, 0, menuWidth, height)
}
else {
destFrame = CGRectMake((shouldOpen) ? width-menuWidth : width+2.0,
0,
menuWidth,
height)
}
UIView.animateWithDuration(
animationDuration,
animations: { () -> Void in
self.sideMenuContainerView.frame = destFrame
},
completion: { (Bool) -> Void in
if (self.isMenuOpen) {
self.delegate?.sideMenuDidOpen?()
} else {
self.delegate?.sideMenuDidClose?()
}
})
}
if (shouldOpen) {
delegate?.sideMenuWillOpen?()
} else {
delegate?.sideMenuWillClose?()
}
}
public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer is UISwipeGestureRecognizer {
let swipeGestureRecognizer = gestureRecognizer as! UISwipeGestureRecognizer
if !self.allowLeftSwipe {
if swipeGestureRecognizer.direction == .Left {
return false
}
}
if !self.allowRightSwipe {
if swipeGestureRecognizer.direction == .Right {
return false
}
}
}
return true
}
internal func handleGesture(gesture: UISwipeGestureRecognizer) {
toggleMenu((self.menuPosition == .Right && gesture.direction == .Left)
|| (self.menuPosition == .Left && gesture.direction == .Right))
}
private func updateSideMenuApperanceIfNeeded () {
if (needUpdateApperance) {
var frame = sideMenuContainerView.frame
frame.size.width = menuWidth
sideMenuContainerView.frame = frame
sideMenuContainerView.layer.shadowPath = UIBezierPath(rect: sideMenuContainerView.bounds).CGPath
needUpdateApperance = false
}
}
/**
Toggles the state of the side menu.
*/
public func toggleMenu () {
if (isMenuOpen) {
toggleMenu(false)
}
else {
updateSideMenuApperanceIfNeeded()
toggleMenu(true)
}
}
/**
Shows the side menu if the menu is hidden.
*/
public func showSideMenu () {
if (!isMenuOpen) {
toggleMenu(true)
}
}
/**
Hides the side menu if the menu is showed.
*/
public func hideSideMenu () {
if (isMenuOpen) {
toggleMenu(false)
}
}
}
extension ENSideMenu: UIDynamicAnimatorDelegate {
public func dynamicAnimatorDidPause(animator: UIDynamicAnimator) {
if (self.isMenuOpen) {
self.delegate?.sideMenuDidOpen?()
} else {
self.delegate?.sideMenuDidClose?()
}
}
public func dynamicAnimatorWillResume(animator: UIDynamicAnimator) {
println("resume")
}
}
| mit | 7ae255b641c6e9aad627362d6ff81a50 | 36.21564 | 158 | 0.625597 | 5.855705 | false | false | false | false |
velvetroom/columbus | Source/View/Settings/VSettingsListCellDetailLevelList+Label.swift | 1 | 2627 | import UIKit
extension VSettingsListCellDetailLevelList
{
//MARK: private
private func factoryString(item:MSettingsDetailLevelProtocol) -> NSAttributedString
{
let title:NSAttributedString = factoryTitle(item:item)
let descr:NSAttributedString = factoryDescr(item:item)
let mutableString:NSMutableAttributedString = NSMutableAttributedString()
mutableString.append(title)
mutableString.append(descr)
return mutableString
}
private func factoryTitle(item:MSettingsDetailLevelProtocol) -> NSAttributedString
{
let attributes:[NSAttributedStringKey:Any] = [
NSAttributedStringKey.font : UIFont.regular(
size:VSettingsListCellDetailLevelList.Constants.fontSize),
NSAttributedStringKey.foregroundColor : UIColor.colourBackgroundDark]
let string:NSAttributedString = NSAttributedString(
string:item.title,
attributes:attributes)
return string
}
private func factoryDescr(item:MSettingsDetailLevelProtocol) -> NSAttributedString
{
let attributes:[NSAttributedStringKey:Any] = [
NSAttributedStringKey.font : UIFont.regular(
size:VSettingsListCellDetailLevelList.Constants.fontSize),
NSAttributedStringKey.foregroundColor : UIColor(white:0, alpha:0.4)]
let string:NSAttributedString = NSAttributedString(
string:item.descr,
attributes:attributes)
return string
}
private func factoryHeight(string:NSAttributedString) -> CGFloat
{
let width:CGFloat = label.bounds.width
let maxHeight:CGFloat = bounds.height
let size:CGSize = CGSize(
width:width,
height:maxHeight)
let options:NSStringDrawingOptions = NSStringDrawingOptions([
NSStringDrawingOptions.usesLineFragmentOrigin,
NSStringDrawingOptions.usesFontLeading])
let boundingRect:CGRect = string.boundingRect(
with:size,
options:options,
context:nil)
let height:CGFloat = ceil(boundingRect.height)
return height
}
//MARK: internal
func updateLabel(
item:MSettingsDetailLevelProtocol)
{
let string:NSAttributedString = factoryString(item:item)
let height:CGFloat = factoryHeight(string:string)
label.attributedText = string
layoutLabelHeight.constant = height
}
}
| mit | 4c80b0c3585c6fcca874f5ffbced6561 | 31.8375 | 87 | 0.642558 | 6.025229 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/00182-swift-astcontext-getconformance.swift | 1 | 1902 | // 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
protocol a {
class func c()
}
class b: a {
c T) {
}
f(true as Boolean)
func f() {
({})
}
import Foundation
class Foo<T>: 1)
func c<d {
enum c {
func e
var _ = e
}
}
struct c<d : Sequence> {
var b: d
}
func a<enum b {
case c
}
}
func String {\(with): \(g())" } i {}
struct A<T> {
let a: [(T, () -> ())] = []
}
f
e)
func f<g>() -> (g, g -> g) -> g {
d j d.i 1, a(2, 3)))
class a {
typealias b = b
}
func i(c: () -> ()) {
}
class a {
var _ = i() {
}
}
class a<f : b, g : b where f.d == g> {
}
protocol b {
typealias d
typealias e
}
struct c<h : b> : b {
typealias d = h
typealias e = a<c<h>, d>
}
func a(b: Int = 0) {
}
let c = a
c()
protocol A {
typealias B
}
class C<D> {
init <A: A where A.B == D>(e: A.B) {
}
}
func e<k>() -> (k, k -> k) -> k {
f j f.i = {
}
{
k) {
n }
}
m e {
class func i()
}
class f: e{ class func i {}
func n<i>() {
k k {
f j
}
-> T) -> String {
return { g in "\(with): \(g())" }
}
struct d<f : e, g: e where g.h == f.h> {
}
protocol e {
typealias h
}
protocol a : a {
}
func a<T>() -> (T, T -> T) -> T)!c : b { func b
protocol A {
typeal= D>(e: A.B) {
}
}
var x1 = 1
var f1: Int -> Int = {
return $0
}
let succee""
}
}
class C: B, A {
override func d() -> String {
return ""
}
func}
class c {
func b((Any, c))(Any, AnyObject
typealias b = b
}
struct A<T> {
let a: [(T, () -> ())] = []
}
| apache-2.0 | d28dde3ed2a571405f20b97419172d39 | 14.85 | 79 | 0.491588 | 2.667602 | false | false | false | false |
gmunhoz/CollieGallery | Pod/Classes/CollieGallery.swift | 1 | 24387 | //
// CollieGallery.swift
//
// Copyright (c) 2016 Guilherme Munhoz <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/// Class used to display the gallery
open class CollieGallery: UIViewController, UIScrollViewDelegate, CollieGalleryViewDelegate {
// MARK: - Private properties
fileprivate let transitionManager = CollieGalleryTransitionManager()
fileprivate var theme = CollieGalleryTheme.dark
fileprivate var pictures: [CollieGalleryPicture] = []
fileprivate var pictureViews: [CollieGalleryView] = []
fileprivate var isShowingLandscapeView: Bool {
let orientation = UIApplication.shared.statusBarOrientation
switch (orientation) {
case UIInterfaceOrientation.landscapeLeft, UIInterfaceOrientation.landscapeRight:
return true
default:
return false
}
}
fileprivate var isShowingActionControls: Bool {
get {
return !closeButton.isHidden
}
}
fileprivate var activityController: UIActivityViewController!
// MARK: - Internal properties
internal var options = CollieGalleryOptions()
internal var displayedView: CollieGalleryView {
get {
return pictureViews[currentPageIndex]
}
}
// MARK: - Public properties
/// The delegate
open weak var delegate: CollieGalleryDelegate?
/// The current page index
open var currentPageIndex: Int = 0
/// The scrollview used for paging
open var pagingScrollView: UIScrollView!
/// The close button
open var closeButton: UIButton!
/// The action button
open var actionButton: UIButton?
/// The view used to show the progress
open var progressTrackView: UIView?
/// The background view of the progress bar
open var progressBarView: UIView?
/// The view used to display the title and caption properties
open var captionView: CollieGalleryCaptionView!
/// The currently displayed imageview
open var displayedImageView: UIImageView {
get {
return displayedView.imageView
}
}
// MARK: - Initializers
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nil, bundle: nil)
}
/**
Default gallery initializer
- Parameters:
- pictures: The pictures to display in the gallery
- options: An optional object with the customization options
- theme: An optional theme to customize the gallery appearance
*/
public convenience init(pictures: [CollieGalleryPicture],
options: CollieGalleryOptions? = nil,
theme: CollieGalleryTheme? = nil)
{
self.init(nibName: nil, bundle: nil)
self.pictures = pictures
self.options = (options != nil) ? options! : CollieGalleryOptions.sharedOptions
self.theme = (theme != nil) ? theme! : CollieGalleryTheme.defaultTheme
}
// MARK: - UIViewController functions
open override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if !UIApplication.shared.isStatusBarHidden {
UIApplication.shared.setStatusBarHidden(true, with: UIStatusBarAnimation.slide)
}
pagingScrollView.delegate = self
if self.pagingScrollView.contentOffset.x == 0.0 {
scrollToIndex(options.openAtIndex, animated: false)
}
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
updateCaptionText()
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
captionView.layoutIfNeeded()
captionView.setNeedsLayout()
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if UIApplication.shared.isStatusBarHidden {
UIApplication.shared.setStatusBarHidden(false, with: UIStatusBarAnimation.none)
}
pagingScrollView.delegate = nil
}
open override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
clearImagesFarFromIndex(currentPageIndex)
}
override open var prefersStatusBarHidden : Bool {
return true
}
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { [weak self] _ in
self?.updateView(size)
}, completion: nil)
}
// MARK: - Private functions
fileprivate func setupView() {
view.backgroundColor = theme.backgroundColor
setupScrollView()
setupPictures()
setupCloseButton()
if options.enableSave {
setupActionButton()
}
setupCaptionView()
if options.showProgress {
setupProgressIndicator()
}
loadImagesNextToIndex(currentPageIndex)
}
fileprivate func setupScrollView() {
let avaiableSize = getInitialAvaiableSize()
let scrollFrame = getScrollViewFrame(avaiableSize)
let contentSize = getScrollViewContentSize(scrollFrame)
pagingScrollView = UIScrollView(frame: scrollFrame)
pagingScrollView.isPagingEnabled = true
pagingScrollView.showsHorizontalScrollIndicator = !options.showProgress
pagingScrollView.backgroundColor = UIColor.clear
pagingScrollView.contentSize = contentSize
switch theme {
case .dark:
pagingScrollView.indicatorStyle = .white
case .light:
pagingScrollView.indicatorStyle = .black
default:
pagingScrollView.indicatorStyle = .default
}
view.addSubview(pagingScrollView)
}
fileprivate func setupPictures() {
let avaiableSize = getInitialAvaiableSize()
let scrollFrame = getScrollViewFrame(avaiableSize)
for i in 0 ..< pictures.count {
let picture = pictures[i]
let pictureFrame = getPictureFrame(scrollFrame, pictureIndex: i)
let pictureView = CollieGalleryView(picture: picture, frame: pictureFrame, options: options, theme: theme)
pictureView.delegate = self
pagingScrollView.addSubview(pictureView)
pictureViews.append(pictureView)
}
}
fileprivate func setupCloseButton() {
if self.closeButton != nil {
self.closeButton.removeFromSuperview()
}
let avaiableSize = getInitialAvaiableSize()
let closeButtonFrame = getCloseButtonFrame(avaiableSize)
let closeButton = UIButton(frame: closeButtonFrame)
if let customImageName = options.customCloseImageName,
let image = UIImage(named: customImageName) {
closeButton.setImage(image, for: UIControl.State())
} else {
closeButton.setTitle("+", for: UIControl.State())
closeButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Medium", size: 30)
closeButton.setTitleColor(theme.closeButtonColor, for: UIControl.State())
closeButton.transform = CGAffineTransform(rotationAngle: CGFloat(CGFloat.pi / 4))
}
closeButton.addTarget(self, action: #selector(closeButtonTouched), for: .touchUpInside)
var shouldBeHidden = false
if self.closeButton != nil {
shouldBeHidden = closeButton.isHidden
}
closeButton.isHidden = shouldBeHidden
self.closeButton = closeButton
view.addSubview(self.closeButton)
}
fileprivate func setupActionButton() {
if let actionButton = self.actionButton {
actionButton.removeFromSuperview()
}
let avaiableSize = getInitialAvaiableSize()
let closeButtonFrame = getActionButtonFrame(avaiableSize)
let actionButton = UIButton(frame: closeButtonFrame)
if let customImageName = options.customOptionsImageName,
let image = UIImage(named: customImageName) {
closeButton.setImage(image, for: UIControl.State())
} else {
actionButton.setTitle("•••", for: UIControl.State())
actionButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Thin", size: 15)
actionButton.setTitleColor(theme.closeButtonColor, for: UIControl.State())
}
actionButton.addTarget(self, action: #selector(actionButtonTouched), for: .touchUpInside)
var shouldBeHidden = false
if self.actionButton != nil {
shouldBeHidden = self.actionButton!.isHidden
}
actionButton.isHidden = shouldBeHidden
self.actionButton = actionButton
view.addSubview(actionButton)
}
fileprivate func setupProgressIndicator() {
let avaiableSize = getInitialAvaiableSize()
let progressFrame = getProgressViewFrame(avaiableSize)
let progressBarFrame = getProgressInnerViewFrame(progressFrame)
let progressTrackView = UIView(frame: progressFrame)
progressTrackView.backgroundColor = UIColor(white: 0.6, alpha: 0.2)
progressTrackView.clipsToBounds = true
self.progressTrackView = progressTrackView
let progressBarView = UIView(frame: progressBarFrame)
progressBarView.backgroundColor = theme.progressBarColor
progressBarView.clipsToBounds = true
self.progressBarView = progressBarView
progressTrackView.addSubview(progressBarView)
if let progressTrackView = self.progressTrackView {
view.addSubview(progressTrackView)
}
}
fileprivate func setupCaptionView() {
let avaiableSize = getInitialAvaiableSize()
let captionViewFrame = getCaptionViewFrame(avaiableSize)
let captionView = CollieGalleryCaptionView(frame: captionViewFrame)
self.captionView = captionView
if options.showCaptionView {
view.addSubview(self.captionView)
}
}
fileprivate func updateView(_ avaiableSize: CGSize) {
pagingScrollView.frame = getScrollViewFrame(avaiableSize)
pagingScrollView.contentSize = getScrollViewContentSize(pagingScrollView.frame)
for i in 0 ..< pictureViews.count {
let innerView = pictureViews[i]
innerView.frame = getPictureFrame(pagingScrollView.frame, pictureIndex: i)
}
if let progressTrackView = progressTrackView {
progressTrackView.frame = getProgressViewFrame(avaiableSize)
}
var popOverPresentationRect = getActionButtonFrame(view.frame.size)
popOverPresentationRect.origin.x += popOverPresentationRect.size.width
activityController?.popoverPresentationController?.sourceView = view
activityController?.popoverPresentationController?.sourceRect = popOverPresentationRect
setupCloseButton()
setupActionButton()
updateContentOffset()
updateCaptionText()
}
fileprivate func loadImagesNextToIndex(_ index: Int) {
pictureViews[index].loadImage()
let imagesToLoad = options.preLoadedImages
for i in 1 ... imagesToLoad {
let previousIndex = index - i
let nextIndex = index + i
if previousIndex >= 0 {
pictureViews[previousIndex].loadImage()
}
if nextIndex < pictureViews.count {
pictureViews[nextIndex].loadImage()
}
}
}
fileprivate func clearImagesFarFromIndex(_ index: Int) {
let imagesToLoad = options.preLoadedImages
let firstIndex = max(index - imagesToLoad, 0)
let lastIndex = min(index + imagesToLoad, pictureViews.count - 1)
var imagesCleared = 0
for i in 0 ..< pictureViews.count {
if i < firstIndex || i > lastIndex {
pictureViews[i].clearImage()
imagesCleared += 1
}
}
print("\(imagesCleared) images cleared.")
}
fileprivate func updateContentOffset() {
pagingScrollView.setContentOffset(CGPoint(x: pagingScrollView.frame.size.width * CGFloat(currentPageIndex), y: 0), animated: false)
}
fileprivate func getInitialAvaiableSize() -> CGSize {
return view.bounds.size
}
fileprivate func getScrollViewFrame(_ avaiableSize: CGSize) -> CGRect {
let x: CGFloat = -options.gapBetweenPages
let y: CGFloat = 0.0
let width: CGFloat = avaiableSize.width + options.gapBetweenPages
let height: CGFloat = avaiableSize.height
return CGRect(x: x, y: y, width: width, height: height)
}
fileprivate func getScrollViewContentSize(_ scrollFrame: CGRect) -> CGSize {
let width = scrollFrame.size.width * CGFloat(pictures.count)
let height = scrollFrame.size.height
return CGSize(width: width, height: height)
}
fileprivate func getPictureFrame(_ scrollFrame: CGRect, pictureIndex: Int) -> CGRect {
let x: CGFloat = ((scrollFrame.size.width) * CGFloat(pictureIndex)) + options.gapBetweenPages
let y: CGFloat = 0.0
let width: CGFloat = scrollFrame.size.width - (1 * options.gapBetweenPages)
let height: CGFloat = scrollFrame.size.height
return CGRect(x: x, y: y, width: width, height: height)
}
fileprivate func toggleControlsVisibility() {
if isShowingActionControls {
hideControls()
} else {
showControls()
}
}
fileprivate func showControls() {
closeButton.isHidden = false
actionButton?.isHidden = false
progressTrackView?.isHidden = false
captionView.isHidden = captionView.titleLabel.text == nil && captionView.captionLabel.text == nil
UIView.animate(withDuration: 0.2, delay: 0.0,
options: UIView.AnimationOptions(),
animations: { [weak self] in
self?.closeButton.alpha = 1.0
self?.actionButton?.alpha = 1.0
self?.progressTrackView?.alpha = 1.0
self?.captionView.alpha = 1.0
}, completion: nil)
}
fileprivate func hideControls() {
UIView.animate(withDuration: 0.2, delay: 0.0,
options: UIView.AnimationOptions(),
animations: { [weak self] in
self?.closeButton.alpha = 0.0
self?.actionButton?.alpha = 0.0
self?.progressTrackView?.alpha = 0.0
self?.captionView.alpha = 0.0
},
completion: { [weak self] _ in
self?.closeButton.isHidden = true
self?.actionButton?.isHidden = true
self?.progressTrackView?.isHidden = true
self?.captionView.isHidden = true
})
}
fileprivate func getCaptionViewFrame(_ availableSize: CGSize) -> CGRect {
return CGRect(x: 0.0, y: availableSize.height - 70, width: availableSize.width, height: 70)
}
fileprivate func getProgressViewFrame(_ avaiableSize: CGSize) -> CGRect {
return CGRect(x: 0.0, y: avaiableSize.height - 2, width: avaiableSize.width, height: 2)
}
fileprivate func getProgressInnerViewFrame(_ progressFrame: CGRect) -> CGRect {
return CGRect(x: 0, y: 0, width: 0, height: progressFrame.size.height)
}
fileprivate func getCloseButtonFrame(_ avaiableSize: CGSize) -> CGRect {
return CGRect(x: 0, y: 0, width: 50, height: 50)
}
fileprivate func getActionButtonFrame(_ avaiableSize: CGSize) -> CGRect {
return CGRect(x: avaiableSize.width - 50, y: 0, width: 50, height: 50)
}
fileprivate func getCustomButtonFrame(_ avaiableSize: CGSize, forIndex index: Int) -> CGRect {
let position = index + 2
return CGRect(x: avaiableSize.width - CGFloat(50 * position), y: 0, width: 50, height: 50)
}
fileprivate func updateCaptionText () {
let picture = pictures[currentPageIndex]
captionView.titleLabel.text = picture.title
captionView.captionLabel.text = picture.caption
captionView.adjustView()
}
fileprivate func updateProgressBar() {
if let progressBarView = progressBarView,
let progressTrackView = progressTrackView,
let scrollView = self.pagingScrollView {
if pictures.count > 1 {
let maxProgress = progressTrackView.frame.size.width * CGFloat(pictures.count - 1)
let currentGap = CGFloat(currentPageIndex) * options.gapBetweenPages
let offset = scrollView.contentOffset.x - currentGap
let progress = (maxProgress - (maxProgress - offset)) / CGFloat(pictures.count - 1)
progressBarView.frame.size.width = max(progress, 0)
} else if pictures.count == 1 {
progressBarView.frame.size.width = progressTrackView.frame.size.width
}
}
}
// MARK: - Internal functions
@objc internal func closeButtonTouched(_ sender: AnyObject) {
dismiss(animated: true, completion: nil)
}
@objc internal func actionButtonTouched(_ sender: AnyObject) {
if let customHandleBlock = options.customOptionsBlock {
customHandleBlock()
return
}
showShareActivity()
}
internal func showShareActivity() {
if let image = displayedImageView.image {
let objectsToShare = [image]
activityController = UIActivityViewController(activityItems: objectsToShare, applicationActivities: options.customActions)
activityController.excludedActivityTypes = options.excludedActions
var popOverPresentationRect = getActionButtonFrame(view.frame.size)
popOverPresentationRect.origin.x += popOverPresentationRect.size.width
activityController.popoverPresentationController?.sourceView = view
activityController.popoverPresentationController?.sourceRect = popOverPresentationRect
activityController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.up
present(activityController, animated: true, completion: nil)
activityController.view.layoutIfNeeded()
}
}
// MARK: - UIScrollView delegate
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
for i in 0 ..< pictureViews.count {
pictureViews[i].scrollView.contentOffset = CGPoint(x: (scrollView.contentOffset.x - pictureViews[i].frame.origin.x + options.gapBetweenPages) * -options.parallaxFactor, y: 0)
}
updateProgressBar()
}
open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
if page != currentPageIndex {
delegate?.gallery?(self, indexChangedTo: page)
}
currentPageIndex = page
loadImagesNextToIndex(currentPageIndex)
updateCaptionText()
}
// MARK: - CollieGalleryView delegate
func galleryViewTapped(_ scrollview: CollieGalleryView) {
let scrollView = pictureViews[currentPageIndex].scrollView
if scrollView?.zoomScale == scrollView?.minimumZoomScale {
toggleControlsVisibility()
}
}
func galleryViewPressed(_ scrollview: CollieGalleryView) {
if options.enableSave {
showControls()
showShareActivity()
}
}
func galleryViewDidRestoreZoom(_ galleryView: CollieGalleryView) {
showControls()
}
func galleryViewDidZoomIn(_ galleryView: CollieGalleryView) {
hideControls()
}
func galleryViewDidEnableScroll(_ galleryView: CollieGalleryView) {
pagingScrollView.isScrollEnabled = false
}
func galleryViewDidDisableScroll(_ galleryView: CollieGalleryView) {
pagingScrollView.isScrollEnabled = true
}
// MARK: - Public functions
/**
Scrolls the gallery to an index
- Parameters:
- index: The index to scroll
- animated: Indicates if it should be animated or not
*/
open func scrollToIndex(_ index: Int, animated: Bool = true) {
currentPageIndex = index
loadImagesNextToIndex(currentPageIndex)
pagingScrollView.setContentOffset(CGPoint(x: pagingScrollView.frame.size.width * CGFloat(index), y: 0), animated: animated)
updateProgressBar()
}
/**
Presents the gallery from a view controller
- Parameters:
- sourceViewController: The source view controller
- transitionType: The transition type used to present the gallery
*/
open func presentInViewController(_ sourceViewController: UIViewController, transitionType: CollieGalleryTransitionType? = nil) {
let type = transitionType == nil ? CollieGalleryTransitionType.defaultType : transitionType!
transitionManager.enableInteractiveTransition = options.enableInteractiveDismiss
transitionManager.transitionType = type
transitionManager.sourceViewController = sourceViewController
transitionManager.targetViewController = self
modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
transitioningDelegate = transitionManager
sourceViewController.present(self, animated: type.animated, completion: nil)
}
}
| mit | 66ff3d81c9ce5573bb9d425bb6335917 | 34.907216 | 186 | 0.620442 | 5.524813 | false | false | false | false |
julienbodet/wikipedia-ios | Wikipedia/Code/NewsCollectionViewCell.swift | 1 | 1491 | import UIKit
public class NewsCollectionViewCell: SideScrollingCollectionViewCell {
var descriptionFont:UIFont? = nil
var descriptionLinkFont:UIFont? = nil
override public func updateFonts(with traitCollection: UITraitCollection) {
super.updateFonts(with: traitCollection)
descriptionFont = UIFont.wmf_font(.subheadline, compatibleWithTraitCollection: traitCollection)
descriptionLinkFont = UIFont.wmf_font(.semiboldSubheadline, compatibleWithTraitCollection: traitCollection)
updateDescriptionHTMLStyle()
}
override public func updateBackgroundColorOfLabels() {
super.updateBackgroundColorOfLabels()
collectionView.backgroundColor = labelBackgroundColor
}
func updateDescriptionHTMLStyle() {
guard
let descriptionHTML = descriptionHTML,
let descriptionFont = descriptionFont,
let descriptionLinkFont = descriptionLinkFont
else {
descriptionLabel.text = nil
return
}
let attributedString = descriptionHTML.wmf_attributedStringFromHTML(with: descriptionFont, boldFont: descriptionLinkFont, italicFont: descriptionFont, boldItalicFont: descriptionLinkFont, withAdditionalBoldingForMatchingSubstring:nil, boldLinks: true).wmf_trim()
descriptionLabel.attributedText = attributedString
}
var descriptionHTML: String? {
didSet {
updateDescriptionHTMLStyle()
}
}
}
| mit | ccf7da2db58fdd50765961a773a08e1f | 39.297297 | 270 | 0.719651 | 6.161157 | false | false | false | false |
mrdepth/Neocom | Legacy/Neocom/Neocom/NCNPCPickerTypesViewController.swift | 2 | 3580 | //
// NCNPCPickerTypesViewController.swift
// Neocom
//
// Created by Artem Shimanski on 21.07.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import UIKit
import CoreData
import EVEAPI
import Futures
class NCNPCPickerTypesViewController: NCTreeViewController, NCSearchableViewController {
private let gate = NCGate()
var predicate: NSPredicate?
override func viewDidLoad() {
super.viewDidLoad()
tableView.register([Prototype.NCHeaderTableViewCell.default,
Prototype.NCDefaultTableViewCell.compact,
Prototype.NCModuleTableViewCell.default,
Prototype.NCShipTableViewCell.default,
Prototype.NCChargeTableViewCell.default,
])
if navigationController != nil {
setupSearchController(searchResultsController: UIStoryboard.killReports.instantiateViewController(withIdentifier: "NCZKillboardTypesViewController"))
}
}
private let root = TreeNode()
override func content() -> Future<TreeNode?> {
reloadData()
return .init(root)
}
func reloadData() {
gate.perform {
NCDatabase.sharedDatabase?.performTaskAndWait({ (managedObjectContext) in
let section = NCDatabaseTypesSection(managedObjectContext: managedObjectContext, predicate: self.predicate, sectionNode: NCDefaultFetchedResultsSectionNode<NSDictionary>.self, objectNode: NCDatabaseTypePickerRow.self)
try? section.resultsController.performFetch()
DispatchQueue.main.async {
self.root.children = [section]
self.tableView.backgroundView = (section.resultsController.fetchedObjects?.count ?? 0) == 0 ? NCTableViewBackgroundLabel(text: NSLocalizedString("No Results", comment: "")) : nil
}
})
}
}
override func didReceiveMemoryWarning() {
if !isViewLoaded || view.window == nil {
treeController?.content = nil
}
}
//MARK: - TreeControllerDelegate
override func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) {
super.treeController(treeController, didSelectCellWithNode: node)
guard let row = node as? NCDatabaseTypePickerRow else {return}
guard let typeID = row.object["typeID"] as? Int else {return}
guard let type = NCDatabase.sharedDatabase?.invTypes[typeID] else {return}
guard let picker = (navigationController as? NCNPCPickerViewController) ?? presentingViewController?.navigationController as? NCNPCPickerViewController else {return}
picker.completionHandler(picker, type)
}
override func treeController(_ treeController: TreeController, accessoryButtonTappedWithNode node: TreeNode) {
super.treeController(treeController, accessoryButtonTappedWithNode: node)
guard let row = node as? NCDatabaseTypePickerRow else {return}
guard let typeID = row.object["typeID"] as? Int else {return}
Router.Database.TypeInfo(typeID).perform(source: self, sender: treeController.cell(for: node))
}
//MARK: NCSearchableViewController
var searchController: UISearchController?
func updateSearchResults(for searchController: UISearchController) {
let predicate: NSPredicate
guard let controller = searchController.searchResultsController as? NCDatabaseTypesViewController else {return}
if let text = searchController.searchBar.text, let other = self.predicate, text.count > 2 {
predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [other, NSPredicate(format: "typeName CONTAINS[C] %@", text)])
}
else {
predicate = NSPredicate(value: false)
}
controller.predicate = predicate
controller.reloadData()
}
}
| lgpl-2.1 | c6c089c65a3a63565a2bef438300e8e4 | 35.896907 | 221 | 0.751607 | 4.703022 | false | false | false | false |
OpenSourceContributions/SwiftOCR | framework/SwiftOCR/SwiftOCR.swift | 1 | 27239 | //
// SwiftOCR.swift
// SwiftOCR
//
// Created by Nicolas Camenisch on 18.04.16.
// Copyright © 2016 Nicolas Camenisch. All rights reserved.
//
import GPUImage
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l >= r
default:
return !(lhs < rhs)
}
}
///The characters the globalNetwork can recognize.
///It **must** be in the **same order** as the network got trained
public var recognizableCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
///The FFNN network used for OCR
public var globalNetwork = FFNN.fromFile(Bundle(for: SwiftOCR.self).url(forResource: "OCR-Network", withExtension: nil)!)!
open class SwiftOCR {
fileprivate var network = globalNetwork
//MARK: Setup
///SwiftOCR's delegate
open weak var delegate: SwiftOCRDelegate?
///Radius in x axis for merging blobs
open var xMergeRadius:CGFloat = 1
///Radius in y axis for merging blobs
open var yMergeRadius:CGFloat = 3
///Only recognize characters on White List
open var characterWhiteList: String? = nil
///Don't recognize characters on Black List
open var characterBlackList: String? = nil
///Confidence must be bigger than the threshold
open var confidenceThreshold:Float = 0.1
//MARK: Recognition data
///All SwiftOCRRecognizedBlob from the last recognition
open var currentOCRRecognizedBlobs = [SwiftOCRRecognizedBlob]()
//MARK: Init
public init(){}
public init(image: OCRImage, delegate: SwiftOCRDelegate?, _ completionHandler: @escaping (String) -> Void){
self.delegate = delegate
self.recognize(image, completionHandler)
}
/**
Performs ocr on the image.
- Parameter image: The image used for OCR
- Parameter completionHandler: The completion handler that gets invoked after the ocr is finished.
*/
open func recognize(_ image: OCRImage, _ completionHandler: @escaping (String) -> Void){
func indexToCharacter(_ index: Int) -> Character {
return Array(recognizableCharacters.characters)[index]
}
func checkWhiteAndBlackListForCharacter(_ character: Character) -> Bool {
let whiteList = characterWhiteList?.characters.contains(character) ?? true
let blackList = !(characterBlackList?.characters.contains(character) ?? false)
return whiteList && blackList
}
DispatchQueue.global(qos: .userInitiated).async {
let preprocessedImage = self.delegate?.preprocessImageForOCR(image) ?? self.preprocessImageForOCR(image)
let blobs = self.extractBlobs(preprocessedImage)
var recognizedString = ""
var ocrRecognizedBlobArray = [SwiftOCRRecognizedBlob]()
for blob in blobs {
do {
let blobData = self.convertImageToFloatArray(blob.0, resize: true)
let networkResult = try self.network.update(inputs: blobData)
//Generate Output Character
if networkResult.max() >= self.confidenceThreshold {
/*
let recognizedChar = Array(recognizableCharacters.characters)[networkResult.indexOf(networkResult.maxElement() ?? 0) ?? 0]
recognizedString.append(recognizedChar)
*/
for (networkIndex, _) in networkResult.enumerated().sorted(by: {$0.0.element > $0.1.element}) {
let character = indexToCharacter(networkIndex)
guard checkWhiteAndBlackListForCharacter(character) else {
continue
}
recognizedString.append(character)
break
}
}
//Generate SwiftOCRRecognizedBlob
var ocrRecognizedBlobCharactersWithConfidenceArray = [(character: Character, confidence: Float)]()
let ocrRecognizedBlobConfidenceThreshold = networkResult.reduce(0, +)/Float(networkResult.count)
for networkResultIndex in 0..<networkResult.count {
let characterConfidence = networkResult[networkResultIndex]
let character = indexToCharacter(networkResultIndex)
guard characterConfidence >= ocrRecognizedBlobConfidenceThreshold && checkWhiteAndBlackListForCharacter(character) else {
continue
}
ocrRecognizedBlobCharactersWithConfidenceArray.append((character: character, confidence: characterConfidence))
}
let currentRecognizedBlob = SwiftOCRRecognizedBlob(charactersWithConfidence: ocrRecognizedBlobCharactersWithConfidenceArray, boundingBox: blob.1)
ocrRecognizedBlobArray.append(currentRecognizedBlob)
} catch {
print(error)
}
}
self.currentOCRRecognizedBlobs = ocrRecognizedBlobArray
completionHandler(recognizedString)
}
}
/**
Performs ocr on the image in a specified rect.
- Parameter image: The image used for OCR
- Parameter rect: The rect in which recognition should take place.
- Parameter completionHandler: The completion handler that gets invoked after the ocr is finished.
*/
open func recognizeInRect(_ image: OCRImage, rect: CGRect, completionHandler: @escaping (String) -> Void){
DispatchQueue.global(qos: .userInitiated).async {
#if os(iOS)
let cgImage = image.cgImage
let croppedCGImage = cgImage?.cropping(to: rect)!
let croppedImage = OCRImage(cgImage: croppedCGImage!)
#else
let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil)!
let croppedCGImage = cgImage.cropping(to: rect)!
let croppedImage = OCRImage(cgImage: croppedCGImage, size: rect.size)
#endif
self.recognize(croppedImage, completionHandler)
}
}
/**
Extracts the characters using [Connected-component labeling](https://en.wikipedia.org/wiki/Connected-component_labeling).
- Parameter image: The image which will be used for the connected-component labeling. If you pass in nil, the `SwiftOCR().image` will be used.
- Returns: An array containing the extracted and cropped Blobs and their bounding box.
*/
internal func extractBlobs(_ image: OCRImage) -> [(OCRImage, CGRect)] {
#if os(iOS)
let pixelData = image.cgImage?.dataProvider?.data
let bitmapData: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let cgImage = image.cgImage
#else
let bitmapRep = NSBitmapImageRep(data: image.tiffRepresentation!)!
let bitmapData: UnsafeMutablePointer<UInt8> = bitmapRep.bitmapData!
let cgImage = bitmapRep.cgImage
#endif
//data <- bitmapData
let numberOfComponents = (cgImage?.bitsPerPixel)! / (cgImage?.bitsPerComponent)!
let bytesPerRow = cgImage?.bytesPerRow
let imageHeight = cgImage?.height
let imageWidth = bytesPerRow! / numberOfComponents
var data = [[UInt16]](repeating: [UInt16](repeating: 0, count: Int(imageWidth)), count: Int(imageHeight!))
let yBitmapDataIndexStride = Array(stride(from: 0, to: imageHeight!*bytesPerRow!, by: bytesPerRow!)).enumerated()
let xBitmapDataIndexStride = Array(stride(from: 0, to: imageWidth*numberOfComponents, by: numberOfComponents)).enumerated()
for (y, yBitmapDataIndex) in yBitmapDataIndexStride {
for (x, xBitmapDataIndex) in xBitmapDataIndexStride {
let bitmapDataIndex = yBitmapDataIndex + xBitmapDataIndex
data[y][x] = bitmapData[bitmapDataIndex] < 127 ? 0 : 255
}
}
//MARK: First Pass
var currentLabel:UInt16 = 0 {
didSet {
if currentLabel == 255 {
currentLabel = 256
}
}
}
var labelsUnion = UnionFind<UInt16>()
for y in 0..<Int(imageHeight!) {
for x in 0..<Int(imageWidth) {
if data[y][x] == 0 { //Is Black
if x == 0 { //Left no pixel
if y == 0 { //Top no pixel
currentLabel += 1
labelsUnion.addSetWith(currentLabel)
data[y][x] = currentLabel
} else if y > 0 { //Top pixel
if data[y - 1][x] != 255 { //Top Label
data[y][x] = data[y - 1][x]
} else { //Top no Label
currentLabel += 1
labelsUnion.addSetWith(currentLabel)
data[y][x] = currentLabel
}
}
} else { //Left pixel
if y == 0 { //Top no pixel
if data[y][x - 1] != 255 { //Left Label
data[y][x] = data[y][x - 1]
} else { //Left no Label
currentLabel += 1
labelsUnion.addSetWith(currentLabel)
data[y][x] = currentLabel
}
} else if y > 0 { //Top pixel
if data[y][x - 1] != 255 { //Left Label
if data[y - 1][x] != 255 { //Top Label
if data[y - 1][x] != data[y][x - 1] {
labelsUnion.unionSetsContaining(data[y - 1][x], and: data[y][x - 1])
}
data[y][x] = data[y - 1][x]
} else { //Top no Label
data[y][x] = data[y][x - 1]
}
} else { //Left no Label
if data[y - 1][x] != 255 { //Top Label
data[y][x] = data[y - 1][x]
} else { //Top no Label
currentLabel += 1
labelsUnion.addSetWith(currentLabel)
data[y][x] = currentLabel
}
}
}
}
}
}
}
//MARK: Second Pass
let parentArray = Array(Set(labelsUnion.parent))
var labelUnionSetOfXArray = Dictionary<UInt16, Int>()
for label in 0...currentLabel {
if label != 255 {
labelUnionSetOfXArray[label] = parentArray.index(of: labelsUnion.setOf(label) ?? 255)
}
}
for y in 0..<Int(imageHeight!) {
for x in 0..<Int(imageWidth) {
let luminosity = data[y][x]
if luminosity != 255 {
data[y][x] = UInt16(labelUnionSetOfXArray[luminosity] ?? 255)
}
}
}
//MARK: MinX, MaxX, MinY, MaxY
var minMaxXYLabelDict = Dictionary<UInt16, (minX: Int, maxX: Int, minY: Int, maxY: Int)>()
for label in 0..<parentArray.count {
minMaxXYLabelDict[UInt16(label)] = (minX: Int(imageWidth), maxX: 0, minY: Int(imageHeight!), maxY: 0)
}
for y in 0..<Int(imageHeight!) {
for x in 0..<Int(imageWidth) {
let luminosity = data[y][x]
if luminosity != 255 {
var value = minMaxXYLabelDict[luminosity]!
value.minX = min(value.minX, x)
value.maxX = max(value.maxX, x)
value.minY = min(value.minY, y)
value.maxY = max(value.maxY, y)
minMaxXYLabelDict[luminosity] = value
}
}
}
//MARK: Merge labels
var mergeLabelRects = [CGRect]()
for label in minMaxXYLabelDict.keys {
let value = minMaxXYLabelDict[label]!
let minX = value.minX
let maxX = value.maxX
let minY = value.minY
let maxY = value.maxY
//Filter blobs
let minMaxCorrect = (minX < maxX && minY < maxY)
let notToTall = Double(maxY - minY) < Double(imageHeight!) * 0.75
let notToWide = Double(maxX - minX) < Double(imageWidth ) * 0.25
let notToShort = Double(maxY - minY) > Double(imageHeight!) * 0.08
let notToThin = Double(maxX - minX) > Double(imageWidth ) * 0.01
let notToSmall = (maxX - minX)*(maxY - minY) > 100
let positionIsOK = minY != 0 && minX != 0 && maxY != Int(imageHeight! - 1) && maxX != Int(imageWidth - 1)
let aspectRatio = Double(maxX - minX) / Double(maxY - minY)
if minMaxCorrect && notToTall && notToWide && notToShort && notToThin && notToSmall && positionIsOK &&
aspectRatio < 1 {
let labelRect = CGRect(x: CGFloat(CGFloat(minX) - xMergeRadius), y: CGFloat(CGFloat(minY) - yMergeRadius), width: CGFloat(CGFloat(maxX - minX) + 2*xMergeRadius + 1), height: CGFloat(CGFloat(maxY - minY) + 2*yMergeRadius + 1))
mergeLabelRects.append(labelRect)
} else if minMaxCorrect && notToTall && notToShort && notToThin && notToSmall && positionIsOK && aspectRatio <= 2.5 && aspectRatio >= 1 {
// MARK: Connected components: Find thinnest part of connected components
guard minX + 2 < maxX - 2 else {
continue
}
let transposedData = Array(data[minY...maxY].map({return $0[(minX + 2)...(maxX - 2)]})).transpose() // [y][x] -> [x][y]
let reducedMaxIndexArray = transposedData.map({return $0.reduce(0, {return UInt32($0.0) + UInt32($0.1)})}) //Covert to UInt32 to prevent overflow
let maxIndex = reducedMaxIndexArray.enumerated().max(by: {return $0.1 < $1.1})?.0 ?? 0
let cutXPosition = minX + 2 + maxIndex
let firstLabelRect = CGRect(x: CGFloat(CGFloat(minX) - xMergeRadius), y: CGFloat(CGFloat(minY) - yMergeRadius), width: CGFloat(CGFloat(maxIndex) + 2 * xMergeRadius), height: CGFloat(CGFloat(maxY - minY) + 2 * yMergeRadius))
let secondLabelRect = CGRect(x: CGFloat(CGFloat(cutXPosition) - xMergeRadius), y: CGFloat(CGFloat(minY) - yMergeRadius), width: CGFloat(CGFloat(Int(maxX - minX) - maxIndex) + 2 * xMergeRadius), height: CGFloat(CGFloat(maxY - minY) + 2 * yMergeRadius))
if firstLabelRect.width >= 5 + (2 * xMergeRadius) && secondLabelRect.width >= 5 + (2 * xMergeRadius) {
mergeLabelRects.append(firstLabelRect)
mergeLabelRects.append(secondLabelRect)
} else {
let labelRect = CGRect(x: CGFloat(CGFloat(minX) - xMergeRadius), y: CGFloat(CGFloat(minY) - yMergeRadius), width: CGFloat(CGFloat(maxX - minX) + 2*xMergeRadius + 1), height: CGFloat(CGFloat(maxY - minY) + 2*yMergeRadius + 1))
mergeLabelRects.append(labelRect)
}
}
}
//Merge rects
var filteredMergeLabelRects = [CGRect]()
for rect in mergeLabelRects {
var intersectCount = 0
for (filteredRectIndex, filteredRect) in filteredMergeLabelRects.enumerated() {
if rect.intersects(filteredRect) {
intersectCount += 1
filteredMergeLabelRects[filteredRectIndex] = filteredRect.union(rect)
}
}
if intersectCount == 0 {
filteredMergeLabelRects.append(rect)
}
}
mergeLabelRects = filteredMergeLabelRects
//Filter rects: - Not to small
let insetMergeLabelRects = mergeLabelRects.map({return $0.insetBy(dx: CGFloat(xMergeRadius), dy: CGFloat(yMergeRadius))})
filteredMergeLabelRects.removeAll()
for rect in insetMergeLabelRects {
let widthOK = rect.size.width >= 7
let heightOK = rect.size.height >= 14
if widthOK && heightOK {
filteredMergeLabelRects.append(rect)
}
}
mergeLabelRects = filteredMergeLabelRects
var outputImages = [(OCRImage, CGRect)]()
//MARK: Crop image to blob
for rect in mergeLabelRects {
if let croppedCGImage = cgImage?.cropping(to: rect) {
#if os(iOS)
let croppedImage = UIImage(cgImage: croppedCGImage)
#else
let croppedImage = NSImage(cgImage: croppedCGImage, size: rect.size)
#endif
outputImages.append((croppedImage, rect))
}
}
outputImages.sort(by: {return $0.0.1.origin.x < $0.1.1.origin.x})
return outputImages
}
/**
Takes an array of images and then resized them to **16x20px**. This is the standard size for the input for the neural network.
- Parameter blobImages: The array of images that should get resized.
- Returns: An array containing the resized images.
*/
internal func resizeBlobs(_ blobImages: [OCRImage]) -> [OCRImage] {
var resizedBlobs = [OCRImage]()
for blobImage in blobImages {
let cropSize = CGSize(width: 16, height: 20)
//Downscale
#if os(iOS)
let cgImage = blobImage.cgImage
#else
let bitmapRep = NSBitmapImageRep(data: blobImage.tiffRepresentation!)!
let cgImage = bitmapRep.cgImage
#endif
let width = cropSize.width
let height = cropSize.height
let bitsPerComponent = 8
let bytesPerRow = 0
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGImageAlphaInfo.noneSkipLast.rawValue
let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo)
context!.interpolationQuality = CGInterpolationQuality.none
context?.draw(cgImage!, in: CGRect(x: 0, y: 0, width: cropSize.width, height: cropSize.height))
let resizedCGImage = context?.makeImage()?.cropping(to: CGRect(x: 0, y: 0, width: cropSize.width, height: cropSize.height))!
#if os(iOS)
let resizedOCRImage = UIImage(cgImage: resizedCGImage!)
#else
let resizedOCRImage = NSImage(cgImage: resizedCGImage!, size: cropSize)
#endif
resizedBlobs.append(resizedOCRImage)
}
return resizedBlobs
}
/**
Uses the default preprocessing algorithm to binarize the image. It uses the [GPUImage framework](https://github.com/BradLarson/GPUImage2).
- Parameter image: The image which should be binarized. If you pass in nil, the `SwiftOCR().image` will be used.
- Returns: The binarized image.
*/
open func preprocessImageForOCR(_ inputImage:OCRImage) -> OCRImage {
let imageA = PictureInput.init(image: inputImage)
let imageB = PictureInput.init(image: inputImage)
// Set up silter operations
let bilateralOperation = BilateralBlur()
let blurOperation = BoxBlur()
let brightnessOperationA = BrightnessAdjustment()
let brightnessOperationB = BrightnessAdjustment()
let contrastOperation = ContrastAdjustment()
let dodgeOperation = ColorDodgeBlend()
let invertOperation = ColorInversion()
let luminanceOperationA = Luminance()
let luminanceOperationB = Luminance()
let medianOperation = MedianFilter()
let opacityOperation = OpacityAdjustment()
let openingOperation = OpeningFilter()
let thresholdOperation = LuminanceThreshold()
// Update parameters
//bilateralOperation.texelSpacingMultiplier = 0.8
bilateralOperation.distanceNormalizationFactor = 1.6
blurOperation.blurRadiusInPixels = 9
brightnessOperationA.brightness = -0.28
brightnessOperationB.brightness = -0.08
contrastOperation.contrast = 2.35
opacityOperation.opacity = 0.93
thresholdOperation.threshold = 0.7
// Prepare for output
var processedImage = inputImage
let output = PictureOutput()
output.imageAvailableCallback = {image in
processedImage = image
}
// Build and execute the filter chain
imageA --> luminanceOperationA --> invertOperation --> blurOperation --> dodgeOperation
imageB --> luminanceOperationB --> dodgeOperation --> medianOperation --> openingOperation --> bilateralOperation --> brightnessOperationA --> contrastOperation --> brightnessOperationB --> thresholdOperation --> output
imageA.processImage(synchronously: true)
imageB.processImage(synchronously: true)
return processedImage
}
/**
Takes an image and converts it to an array of floats. The array gets generated by taking the pixel-data of the red channel and then converting it into floats. This array can be used as input for the neural network.
- Parameter image: The image which should get converted to the float array.
- Parameter resize: If you set this to true, the image firsts gets resized. The default value is `true`.
- Returns: The array containing the pixel-data of the red channel.
*/
internal func convertImageToFloatArray(_ image: OCRImage, resize: Bool = true) -> [Float] {
let resizedBlob: OCRImage = {
if resize {
return resizeBlobs([image]).first!
} else {
return image
}
}()
#if os(iOS)
let pixelData = resizedBlob.cgImage?.dataProvider?.data
let bitmapData: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let cgImage = resizedBlob.cgImage
#else
let bitmapRep = NSBitmapImageRep(data: resizedBlob.tiffRepresentation!)!
let bitmapData = bitmapRep.bitmapData!
let cgImage = bitmapRep.cgImage
#endif
let numberOfComponents = (cgImage?.bitsPerPixel)! / (cgImage?.bitsPerComponent)!
var imageData = [Float]()
let height = Int(resizedBlob.size.height)
let width = Int(resizedBlob.size.width)
for yPixelInfo in stride(from: 0, to: height*width*numberOfComponents, by: width*numberOfComponents) {
for xPixelInfo in stride(from: 0, to: width*numberOfComponents, by: numberOfComponents) {
let pixelInfo: Int = yPixelInfo + xPixelInfo
imageData.append(bitmapData[pixelInfo] < 127 ? 0 : 1)
}
}
let aspectRatio = Float(image.size.width / image.size.height)
imageData.append(aspectRatio)
return imageData
}
}
// MARK: SwiftOCRDelegate
public protocol SwiftOCRDelegate: class {
/**
Implement this method for a custom image preprocessing algorithm. Only return a binary image.
- Parameter inputImage: The image to preprocess.
- Returns: The preprocessed, binarized image that SwiftOCR should use for OCR. If you return nil SwiftOCR will use its default preprocessing algorithm.
*/
func preprocessImageForOCR(_ inputImage: OCRImage) -> OCRImage?
}
extension SwiftOCRDelegate {
func preprocessImageForOCR(_ inputImage: OCRImage) -> OCRImage? {
return nil
}
}
// MARK: SwiftOCRRecognizedBlob
public struct SwiftOCRRecognizedBlob {
public let charactersWithConfidence: [(character: Character, confidence: Float)]!
public let boundingBox: CGRect!
init(charactersWithConfidence: [(character: Character, confidence: Float)]!, boundingBox: CGRect) {
self.charactersWithConfidence = charactersWithConfidence.sorted(by: {return $0.0.confidence > $0.1.confidence})
self.boundingBox = boundingBox
}
}
| apache-2.0 | 23c6944dd8f481b7d7d172d2b3d5567f | 39.836582 | 267 | 0.528893 | 5.170463 | false | false | false | false |
cplaverty/KeitaiWaniKani | AlliCrab/Extensions/ResourceRepository.swift | 1 | 3922 | //
// ResourceRepository.swift
// AlliCrab
//
// Copyright © 2017 Chris Laverty. All rights reserved.
//
import Foundation
import os
import WaniKaniKit
private var currentFetchRequest: Progress?
private let fetchRequestLock = NSLock()
private typealias UpdateFunction = (TimeInterval, @escaping (ResourceRefreshResult) -> Void) -> Progress
extension ResourceRepository {
var lastAppDataUpdateDate: Date? {
return try! getEarliestLastUpdateDate(for: [ .assignments, .levelProgression, .reviewStatistics, .studyMaterials, .subjects, .user ])
}
@discardableResult func updateAppData(minimumFetchInterval: TimeInterval, completionHandler: @escaping (ResourceRefreshResult) -> Void) -> Progress {
fetchRequestLock.lock()
defer { fetchRequestLock.unlock() }
if let currentFetchRequest = currentFetchRequest {
os_log("Resource fetch requested but returning currently executing fetch request", type: .debug)
return currentFetchRequest
}
let weightedUpdateOperations: [(weight: Int64, UpdateFunction)] = [
(4, updateAssignments),
(1, updateLevelProgression),
(2, updateReviewStatistics),
(2, updateStudyMaterials),
(4, updateSubjects),
(1, updateUser)
]
let expectedResultCount = weightedUpdateOperations.count
let expectedTotalUnitCount = weightedUpdateOperations.reduce(1, { $0 + $1.weight })
os_log("Scheduling resource fetch request", type: .debug)
var results = [ResourceRefreshResult]()
results.reserveCapacity(expectedResultCount)
let progress = Progress(totalUnitCount: expectedTotalUnitCount)
progress.completedUnitCount = 1
let backgroundTaskID = UIApplication.shared.beginBackgroundTask(withName: "ResourceRepository.updateAppData") {
os_log("Cancelling background task from expiration handler", type: .debug)
progress.cancel()
}
os_log("Begun background task %d", type: .debug, backgroundTaskID.rawValue)
let sharedCompletionHandler: (ResourceRefreshResult) -> Void = { result in
switch result {
case .success, .noData:
results.append(result)
if results.count == expectedResultCount {
defer { currentFetchRequest = nil }
os_log("All resources received. Notifying completion.", type: .debug)
if results.contains(.success) {
completionHandler(.success)
} else {
completionHandler(.noData)
}
os_log("End background task %d", type: .debug, backgroundTaskID.rawValue)
UIApplication.shared.endBackgroundTask(backgroundTaskID)
} else if results.count > expectedResultCount {
fatalError("Received more results than expected!")
}
case .error(_):
defer { currentFetchRequest = nil }
os_log("Received error on resource fetch. Cancelling request and notifying completion.", type: .debug)
guard !progress.isCancelled else {
break
}
progress.cancel()
completionHandler(result)
os_log("End background task %d", type: .debug, backgroundTaskID.rawValue)
UIApplication.shared.endBackgroundTask(backgroundTaskID)
}
}
for (weight, operation) in weightedUpdateOperations {
progress.addChild(
operation(minimumFetchInterval, sharedCompletionHandler),
withPendingUnitCount: weight)
}
return progress
}
}
| mit | 5a1debf0dd71099034de867fd370febf | 39.84375 | 153 | 0.605713 | 5.625538 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.