repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/UI/PXReview/PXTermsAndConditionView.swift
1
5434
class PXTermsAndConditionView: PXComponentView { var SCREEN_TITLE = "terms_and_conditions_title" let DEFAULT_CREDITS_HEIGHT = CGFloat(80) private let termsAndConditionsText: MPTextView = MPTextView() var termsAndConditionsDto: PXTermsDto? weak var delegate: PXTermsAndConditionViewDelegate? init(shouldAddMargins: Bool = true, termsDto: PXTermsDto? = nil, delegate: PXTermsAndConditionViewDelegate? = nil) { super.init() self.delegate = delegate self.termsAndConditionsDto = termsDto self.termsAndConditionsText.backgroundColor = .clear translatesAutoresizingMaskIntoConstraints = false termsAndConditionsText.isUserInteractionEnabled = true termsAndConditionsText.isEditable = false termsAndConditionsText.delegate = self termsAndConditionsText.translatesAutoresizingMaskIntoConstraints = false termsAndConditionsText.attributedText = getTyCText() termsAndConditionsText.backgroundColor = .clear if termsAndConditionsDto == nil { // generic terms and conditions case, the whole cell will react presenting the generic tyc webview let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:))) tap.delegate = self self.addGestureRecognizer(tap) } addSubview(termsAndConditionsText) let URLAttribute: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: UIFont(name: ResourceManager.shared.DEFAULT_FONT_NAME, size: 12) ?? UIFont.systemFont(ofSize: 12), NSAttributedString.Key.foregroundColor: ThemeManager.shared.secondaryColor()] termsAndConditionsText.linkTextAttributes = URLAttribute let PERCENT_WIDTH: CGFloat = 90.0 PXLayout.matchWidth(ofView: termsAndConditionsText, toView: self, withPercentage: PERCENT_WIDTH).isActive = true PXLayout.centerHorizontally(view: termsAndConditionsText).isActive = true var topAndBottomMargins = PXLayout.S_MARGIN if !shouldAddMargins { topAndBottomMargins = PXLayout.ZERO_MARGIN } PXLayout.pinTop(view: termsAndConditionsText, withMargin: topAndBottomMargins).isActive = true PXLayout.pinBottom(view: termsAndConditionsText, withMargin: topAndBottomMargins).isActive = true let screenWidth = PXLayout.getScreenWidth(applyingMarginFactor: PERCENT_WIDTH) let dynamicSize: CGSize = termsAndConditionsText.sizeThatFits(CGSize(width: screenWidth, height: CGFloat.greatestFiniteMagnitude)) PXLayout.setHeight(owner: termsAndConditionsText, height: dynamicSize.height).isActive = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PXTermsAndConditionView { func getTyCText() -> NSMutableAttributedString { let termsAndConditionsText = termsAndConditionsDto?.text ?? "review_terms_and_conditions".localized let normalAttributes: [NSAttributedString.Key: AnyObject] = [NSAttributedString.Key.font: Utils.getFont(size: PXLayout.XXXS_FONT), NSAttributedString.Key.foregroundColor: ThemeManager.shared.labelTintColor()] let mutableAttributedString = NSMutableAttributedString(string: termsAndConditionsText, attributes: normalAttributes) let defaultLinkablePhrase = PXLinkablePhraseDto(textColor: "", phrase: SCREEN_TITLE.localized, link: SiteManager.shared.getTermsAndConditionsURL(), html: "", installments: nil) let phrases = termsAndConditionsDto?.linkablePhrases ?? [defaultLinkablePhrase] for linkablePhrase in phrases { if let customLink = linkablePhrase.link { let tycLinkRange = (termsAndConditionsText as NSString).range(of: linkablePhrase.phrase) mutableAttributedString.addAttribute(NSAttributedString.Key.link, value: customLink, range: tycLinkRange) } else if let customHtml = linkablePhrase.html { let htmlUrl = HtmlStorage.shared.set(customHtml) let tycLinkRange = (termsAndConditionsText as NSString).range(of: linkablePhrase.phrase) mutableAttributedString.addAttribute(NSAttributedString.Key.link, value: htmlUrl, range: tycLinkRange) } } let style = NSMutableParagraphStyle() style.alignment = .center style.lineSpacing = CGFloat(3) mutableAttributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: NSRange(location: 0, length: mutableAttributedString.length)) return mutableAttributedString } } extension PXTermsAndConditionView: UITextViewDelegate, UIGestureRecognizerDelegate { @objc func handleTap(_ sender: UITapGestureRecognizer) { if let url = URL(string: SiteManager.shared.getTermsAndConditionsURL()) { delegate?.shouldOpenTermsCondition(SCREEN_TITLE.localized, url: url) } } func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { if termsAndConditionsDto != nil { if let range = Range(characterRange, in: textView.text), let text = textView.text?[range] { let title = String(text).capitalized delegate?.shouldOpenTermsCondition(title, url: URL) } } return false } }
mit
7ef72828542c29dc8d8187ebba7a2b61
48.853211
264
0.719912
4.89991
false
false
false
false
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Observables/Observable+Binding.swift
54
8027
// // Observable+Binding.swift // RxSwift // // Created by Krunoslav Zaher on 3/1/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation // MARK: multicast extension ObservableType { /** Multicasts the source sequence notifications through the specified subject to the resulting connectable observable. Upon connection of the connectable observable, the subject is subscribed to the source exactly one, and messages are forwarded to the observers registered with the connectable observable. For specializations with fixed subject types, see `publish` and `replay`. - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) - parameter subject: Subject to push source elements into. - returns: A connectable observable sequence that upon connection causes the source sequence to push results into the specified subject. */ public func multicast<S: SubjectType>(_ subject: S) -> ConnectableObservable<S.E> where S.SubjectObserverType.E == E { return ConnectableObservableAdapter(source: self.asObservable(), subject: subject) } /** Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's invocation. For specializations with fixed subject types, see `publish` and `replay`. - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) - parameter subjectSelector: Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. - parameter selector: Selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ public func multicast<S: SubjectType, R>(_ subjectSelector: @escaping () throws -> S, selector: @escaping (Observable<S.E>) throws -> Observable<R>) -> Observable<R> where S.SubjectObserverType.E == E { return Multicast( source: self.asObservable(), subjectSelector: subjectSelector, selector: selector ) } } // MARK: publish extension ObservableType { /** Returns a connectable observable sequence that shares a single subscription to the underlying sequence. This operator is a specialization of `multicast` using a `PublishSubject`. - seealso: [publish operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. */ public func publish() -> ConnectableObservable<E> { return self.multicast(PublishSubject()) } } // MARK: replay extension ObservableType { /** Returns a connectable observable sequence that shares a single subscription to the underlying sequence replaying bufferSize elements. This operator is a specialization of `multicast` using a `ReplaySubject`. - seealso: [replay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) - parameter bufferSize: Maximum element count of the replay buffer. - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. */ public func replay(_ bufferSize: Int) -> ConnectableObservable<E> { return self.multicast(ReplaySubject.create(bufferSize: bufferSize)) } /** Returns a connectable observable sequence that shares a single subscription to the underlying sequence replaying all elements. This operator is a specialization of `multicast` using a `ReplaySubject`. - seealso: [replay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. */ public func replayAll() -> ConnectableObservable<E> { return self.multicast(ReplaySubject.createUnbounded()) } } // MARK: refcount extension ConnectableObservableType { /** Returns an observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence. - seealso: [refCount operator on reactivex.io](http://reactivex.io/documentation/operators/refCount.html) - returns: An observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence. */ public func refCount() -> Observable<E> { return RefCount(source: self) } } // MARK: share extension ObservableType { /** Returns an observable sequence that shares a single subscription to the underlying sequence. This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. - seealso: [share operator on reactivex.io](http://reactivex.io/documentation/operators/refcount.html) - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ public func share() -> Observable<E> { return self.publish().refCount() } } // MARK: shareReplay extension ObservableType { /** Returns an observable sequence that shares a single subscription to the underlying sequence, and immediately upon subscription replays maximum number of elements in buffer. This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) - parameter bufferSize: Maximum element count of the replay buffer. - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ public func shareReplay(_ bufferSize: Int) -> Observable<E> { if bufferSize == 1 { return ShareReplay1(source: self.asObservable()) } else { return self.replay(bufferSize).refCount() } } /** Returns an observable sequence that shares a single subscription to the underlying sequence, and immediately upon subscription replays latest element in buffer. This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. Unlike `shareReplay(bufferSize: Int)`, this operator will clear latest element from replay buffer in case number of subscribers drops from one to zero. In case sequence completes or errors out replay buffer is also cleared. - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ public func shareReplayLatestWhileConnected() -> Observable<E> { return ShareReplay1WhileConnected(source: self.asObservable()) } }
apache-2.0
eeb978f3f2a6b3645cc4ed3672cf77e7
43.342541
281
0.734986
5.215075
false
false
false
false
chess-cf/chess.cf-ios
Chess/LoginViewController.swift
1
2431
// // LoginViewController.swift // Chess // // Created by Alex Studnicka on 22/12/14. // Copyright (c) 2014 Alex Studnička. All rights reserved. // import UIKit class LoginViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var overlayView: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) usernameField.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { if textField == usernameField { if let text = usernameField.text where text.characters.count > 0 { passwordField.becomeFirstResponder() } } else if textField == passwordField { login() } return false } // MARK: - Actions @IBAction func login() { guard let username = usernameField.text, let password = passwordField.text where username.characters.count > 0 && password.characters.count > 0 else { return } usernameField.resignFirstResponder() passwordField.resignFirstResponder() self.navigationItem.rightBarButtonItem?.enabled = false UIView.animateWithDuration(0.25) { self.overlayView.alpha = 1 } API.login(username, password: password) { error in if let error = error { self.navigationItem.rightBarButtonItem?.enabled = true UIView.animateWithDuration(0.25) { self.overlayView.alpha = 0 } UIAlertView(title: ~"ERROR", message: ~error, delegate: nil, cancelButtonTitle: ~"DISMISS").show() } else { NSNotificationCenter.defaultCenter().postNotificationName("CHESSAPP_LOGIN", object: self) self.dismissViewControllerAnimated(true, completion: nil) } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
8b0c10447e4584c530e9bf8850ca9ee6
26.303371
106
0.704527
4.475138
false
false
false
false
michaelburk/OAuth2
OAuth2WebViewController.swift
1
6570
// // OAuth2WebViewController.swift // OAuth2 // // Created by Pascal Pfiffner on 7/15/14. // Copyright (c) 2014 Pascal Pfiffner. All rights reserved. // import UIKit extension OAuth2 { /** * Presents a web view controller, contained in a UINavigationController, on the supplied view controller and loads * the authorize URL. * * Automatically intercepts the redirect URL and performs the token exchange. It does NOT however dismiss the * web view controller automatically, you probably want to do this in the `afterAuthorizeOrFailure` closure. Simply * call this method first, then assign that closure in which you call `dismissViewController()` on the returned web * view controller instance. * @param redirect The redirect URL to use * @param scope The scope to use * @param params Optional additional URL parameters * @param from The view controller to use for presentation */ public func authorizeEmbedded(redirect: String, scope: String, params: [String: String]?, from: UIViewController) -> OAuth2WebViewController { let url = authorizeURLWithRedirect(redirect, scope: scope, params: params) let web = OAuth2WebViewController() web.startURL = url web.interceptURLString = redirect web.onIntercept = { url in self.handleRedirectURL(url) return true } web.onWillDismiss = { didCancel in if didCancel { self.didFail(nil) } } let navi = UINavigationController(rootViewController: web) from.presentViewController(navi, animated: true, completion: nil) return web } } /** * A simple iOS web view controller that allows you to display the login/authorization screen. */ public class OAuth2WebViewController: UIViewController, UIWebViewDelegate { /** The URL to load on first show. */ public var startURL: NSURL? { didSet(oldURL) { if nil != startURL && nil == oldURL && isViewLoaded() { loadURL(startURL!) } } } /** The URL string to intercept and respond to. */ var interceptURLString: String? { didSet(oldURL) { if nil != interceptURLString { if let url = NSURL(string: interceptURLString!) { interceptComponents = NSURLComponents(URL: url, resolvingAgainstBaseURL: true) } else { println("Failed to parse URL \(interceptURLString), discarding") interceptURLString = nil } } else { interceptComponents = nil } } } var interceptComponents: NSURLComponents? /** Closure called when the web view gets asked to load the redirect URL, specified in `interceptURLString`. */ var onIntercept: ((url: NSURL) -> Bool)? /** Called when the web view is about to be dismissed. */ var onWillDismiss: ((didCancel: Bool) -> Void)? var cancelButton: UIBarButtonItem? var webView: UIWebView! var loadingView: UIView? override init() { super.init(nibName: nil, bundle: nil) } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - View Handling override public func loadView() { title = "SMART" edgesForExtendedLayout = .All extendedLayoutIncludesOpaqueBars = true automaticallyAdjustsScrollViewInsets = true super.loadView() view.backgroundColor = UIColor.whiteColor() cancelButton = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: "cancel:") navigationItem.rightBarButtonItem = cancelButton // create a web view webView = UIWebView() webView.setTranslatesAutoresizingMaskIntoConstraints(false) webView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal webView.delegate = self view.addSubview(webView!) let views = NSDictionary(object: webView, forKey: "web") // doesn't like ["web": webView!] view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[web]|", options: nil, metrics: nil, views: views)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[web]|", options: nil, metrics: nil, views: views)) } override public func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if !webView.canGoBack { if nil != startURL { loadURL(startURL!) } else { webView.loadHTMLString("There is no `startURL`", baseURL: nil) } } } func showHideBackButton(show: Bool) { if show { let bb = UIBarButtonItem(barButtonSystemItem: .Rewind, target: self, action: "goBack:") navigationItem.leftBarButtonItem = bb } else { navigationItem.leftBarButtonItem = nil } } func showLoadingIndicator() { // TODO: implement } func hideLoadingIndicator() { // TODO: implement } func showErrorMessage(message: String, animated: Bool) { println("Error: \(message)") } // MARK: - Actions public func loadURL(url: NSURL) { webView.loadRequest(NSURLRequest(URL: url)) } func goBack(sender: AnyObject?) { webView.goBack() } func cancel(sender: AnyObject?) { dismiss(asCancel: true, animated: nil != sender ? true : false) } func dismiss(# animated: Bool) { dismiss(asCancel: false, animated: animated) } func dismiss(# asCancel: Bool, animated: Bool) { webView.stopLoading() if nil != self.onWillDismiss { self.onWillDismiss!(didCancel: asCancel) } presentingViewController?.dismissViewControllerAnimated(animated, nil) } // MARK: - Web View Delegate public func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool { // we compare the scheme and host first, then check the path (if there is any). Not sure if a simple string comparison // would work as there may be URL parameters attached if nil != onIntercept && request.URL.scheme == interceptComponents?.scheme && request.URL.host == interceptComponents?.host { let haveComponents = NSURLComponents(URL: request.URL, resolvingAgainstBaseURL: true) if haveComponents?.path == interceptComponents?.path { return onIntercept!(url: request.URL) } } return true } public func webViewDidStartLoad(webView: UIWebView!) { if "file" != webView.request?.URL.scheme { showLoadingIndicator() } } public func webViewDidFinishLoad(webView: UIWebView!) { hideLoadingIndicator() showHideBackButton(webView.canGoBack) } public func webView(webView: UIWebView!, didFailLoadWithError error: NSError!) { if NSURLErrorDomain == error.domain && NSURLErrorCancelled == error.code { return } // do we still need to intercept "WebKitErrorDomain" error 102? if nil != loadingView { showErrorMessage(error.localizedDescription, animated: true) } } }
mit
b63fd346feb20eeaa4ebae09245b8dfa
27.565217
143
0.717047
4.088363
false
false
false
false
justinmfischer/SwiftyExpandingCells
SwiftyExpandingCells/Src/SwiftyExpandingTransition.swift
1
7012
// // SwiftyExpandingTransition.swift // SwiftyExpandingCells // // Created by Fischer, Justin on 11/19/15. // Copyright © 2015 Fischer, Justin. All rights reserved. // import Foundation import UIKit class SwiftyExpandingTransition: NSObject, UIViewControllerAnimatedTransitioning { var operation: UINavigationControllerOperation? var imageViewTop: UIImageView? var imageViewBottom: UIImageView? var duration: TimeInterval = 0 var selectedCellFrame = CGRect.zero func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return self.duration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let sourceVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) else { return } guard let sourceView = sourceVC.view else { return } guard let destinationVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) else { return } guard let destinationView = destinationVC.view else { return } let container = transitionContext.containerView let initialFrame = transitionContext.initialFrame(for: sourceVC) let finalFrame = transitionContext.finalFrame(for: destinationVC) // must set final frame, because it could be (0.0, 64.0, 768.0, 960.0) // and the destinationView frame could be (0 0; 768 1024) destinationView.frame = finalFrame self.selectedCellFrame = CGRect(x: self.selectedCellFrame.origin.x, y: self.selectedCellFrame.origin.y + self.selectedCellFrame.height, width: self.selectedCellFrame.width, height: self.selectedCellFrame.height) let bounds = CGRect(x: 0, y: 0, width: (sourceView.bounds.size.width), height: (sourceView.bounds.size.height)) if self.operation == UINavigationControllerOperation.push { UIGraphicsBeginImageContextWithOptions((sourceView.bounds.size), true, 0) sourceView.drawHierarchy(in: bounds, afterScreenUpdates: false) guard let snapShot = UIGraphicsGetImageFromCurrentImageContext() else { UIGraphicsEndImageContext() return } UIGraphicsEndImageContext() let tempImageRef = snapShot.cgImage! let imageSize = snapShot.size let imageScale = snapShot.scale let midPoint = bounds.height / 2 let selectedFrame = self.selectedCellFrame.origin.y - (self.selectedCellFrame.height / 2) let padding = self.selectedCellFrame.height * imageScale var topHeight: CGFloat = 0.0 var bottomHeight: CGFloat = 0.0 if selectedFrame < midPoint { topHeight = self.selectedCellFrame.origin.y * imageScale bottomHeight = (imageSize.height - self.selectedCellFrame.origin.y) * imageScale } else { topHeight = (self.selectedCellFrame.origin.y * imageScale) - padding bottomHeight = ((imageSize.height - self.selectedCellFrame.origin.y) * imageScale) + padding } let topImageRect = CGRect(x: 0, y: 0, width: imageSize.width * imageScale, height: topHeight) let bottomImageRect = CGRect(x: 0, y: topHeight, width: imageSize.width * imageScale, height: bottomHeight) let topImageRef = tempImageRef.cropping(to: topImageRect)! let bottomImageRef = tempImageRef.cropping(to: bottomImageRect) self.imageViewTop = UIImageView(image: UIImage(cgImage: topImageRef, scale: snapShot.scale, orientation: UIImageOrientation.up)) if (bottomImageRef != nil) { self.imageViewBottom = UIImageView(image: UIImage(cgImage: bottomImageRef!, scale: snapShot.scale, orientation: UIImageOrientation.up)) } } var startFrameTop = self.imageViewTop!.frame var endFrameTop = startFrameTop var startFrameBottom = self.imageViewBottom!.frame var endFrameBottom = startFrameBottom // include any offset if view controllers are not initially at 0 y position let yOffset = self.operation == UINavigationControllerOperation.pop ? finalFrame.origin.y : initialFrame.origin.y if self.operation == UINavigationControllerOperation.pop { startFrameTop.origin.y = -startFrameTop.size.height + yOffset endFrameTop.origin.y = yOffset startFrameBottom.origin.y = startFrameTop.height + startFrameBottom.height + yOffset endFrameBottom.origin.y = startFrameTop.height + yOffset } else { startFrameTop.origin.y = yOffset endFrameTop.origin.y = -startFrameTop.size.height + yOffset startFrameBottom.origin.y = startFrameTop.size.height + yOffset endFrameBottom.origin.y = startFrameTop.height + startFrameBottom.height + yOffset } self.imageViewTop!.frame = startFrameTop self.imageViewBottom!.frame = startFrameBottom destinationView.alpha = 0 sourceView.alpha = 0 let backgroundView = UIView(frame: bounds) backgroundView.backgroundColor = UIColor.black if self.operation == UINavigationControllerOperation.pop { sourceView.alpha = 1 container.addSubview(backgroundView) container.addSubview(sourceView) container.addSubview(destinationView) container.addSubview(self.imageViewTop!) container.addSubview(self.imageViewBottom!) UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { () -> Void in self.imageViewTop!.frame = endFrameTop self.imageViewBottom!.frame = endFrameBottom sourceView.alpha = 0 }, completion: { (finish) -> Void in self.imageViewTop!.removeFromSuperview() self.imageViewBottom!.removeFromSuperview() destinationView.alpha = 1 transitionContext.completeTransition(true) }) } else { container.addSubview(backgroundView) container.addSubview(destinationView) container.addSubview(self.imageViewTop!) container.addSubview(self.imageViewBottom!) UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { () -> Void in self.imageViewTop!.frame = endFrameTop self.imageViewBottom!.frame = endFrameBottom destinationView.alpha = 1 }, completion: { (finish) -> Void in self.imageViewTop!.removeFromSuperview() self.imageViewBottom!.removeFromSuperview() transitionContext.completeTransition(true) }) } } }
mit
ab9271776097f5b7adcfbad511e1d5c4
42.01227
219
0.660248
5.468799
false
false
false
false
tjhancocks/Pixel
PixelApp/PixelApp/Document.swift
1
7942
// // Document.swift // PixelApp // // Created by Tom Hancocks on 02/08/2014. // Copyright (c) 2014 Tom Hancocks. All rights reserved. // import Cocoa class Document: NSDocument { // New Document Sheet var newDocumentSheet: NewDocumentController? // Main Editor Area var documentEditorView: PixelEditorView? @IBOutlet var documentScrollView: NSScrollView? @IBOutlet var pixelGridButton: NSButton? @IBOutlet var scalePopUp: NSPopUpButton? // Layers Pane @IBOutlet var layersTableView: NSTableView? @IBOutlet var layerOpacitySlider: NSSlider? @IBOutlet var layerBlendModePopup: NSPopUpButton? // Brush Settings Pane @IBOutlet var brushSize: NSTextField? @IBOutlet var toolSelection: NSSegmentedControl? @IBOutlet var solidShapeButton: NSButton? // Colors Palette Pane @IBOutlet var colorPalettePane: NSCollectionView? @IBOutlet var activeColorView: ColorSwatchActiveView? @IBOutlet var colorPaletteArrayController: NSArrayController? var colorSwatch = ColorSwatch() override func windowControllerDidLoadNib(aController: NSWindowController) { super.windowControllerDidLoadNib(aController) dispatch_after(500000, dispatch_get_main_queue()) { self.newDocumentSheet = NewDocumentController() self.newDocumentSheet!.parentWindow = aController.window if let window = aController.window { window.beginSheet(self.newDocumentSheet!.window!) { (response) -> Void in if response == NSOKButton { self.createEditorCanvasView(name: self.newDocumentSheet!.documentName, ofSize: self.newDocumentSheet!.canvasSize, atScale: 5.0, withBaseImageURL: self.newDocumentSheet!.baseImageURL) } else { aController.close() } } } } // Populate the scale popup menu with a number of items for s in 1...8 { var scale: Int = 0 if s <= 4 { scale = s * 25 } else if s > 4 { scale = (s - 4) * 250 } scalePopUp!.addItemWithTitle("\(scale)%") scalePopUp!.lastItem!.tag = scale } scalePopUp!.selectItemWithTag(500) // Make sure the color palette is selectable, and set up an observe for // its selection colorPalettePane!.selectable = true colorPalettePane!.allowsMultipleSelection = false colorPalettePane!.addObserver(self, forKeyPath: "selectionIndexes", options: NSKeyValueObservingOptions.New, context: nil) } override class func autosavesInPlace() -> Bool { return true } override var windowNibName: String { return "Document" } override func dataOfType(typeName: String?, error outError: NSErrorPointer) -> NSData? { outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) return nil } override func readFromData(data: NSData?, ofType typeName: String?, error outError: NSErrorPointer) -> Bool { outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) return false } // Retrieve a flattened version of the image, as it currently appears in the editor and then export it // to file system using the requested settings. // TODO! - Export Settings. Currently only PNG Exports are supported @IBAction func exportImage(sender: AnyObject!) { let savePanel = NSSavePanel() savePanel.prompt = "Export" savePanel.allowedFileTypes = ["png", "PNG"] savePanel.canCreateDirectories = true savePanel.nameFieldStringValue = "Export.png" if savePanel.runModal() == NSOKButton { let image = documentEditorView!.flattenedImage(atScale: 1.0) let imageRepresentation = image.unscaledBitmapImageRep() let properties = [NSObject : AnyObject]() let pngData = imageRepresentation.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: properties)! pngData.writeToURL(savePanel.URL!, options: .DataWritingAtomic, error: nil) } } /// Create a new canvas at the specified size and scale func createEditorCanvasView(#name: String, ofSize size: CGSize, atScale scale: CGFloat, withBaseImageURL url: NSURL?) { var canvasFrame = NSRect(x: 0, y: 0, width: size.width * scale, height: size.height * scale) documentEditorView = PixelEditorView(frame: canvasFrame, withSize: size) documentScrollView!.documentView = documentEditorView! documentEditorView!.layersTableView = layersTableView documentEditorView!.setName(name, ofLayerAtIndex: 0) documentEditorView!.setBaseImage(url, ofLayerAtIndex: 0) documentEditorView!.currentScaleFactor = scale if let actualURL = url? { colorSwatch.removeAll() colorSwatch.add(colorsFromImageAtURL: actualURL) colorPaletteArrayController!.rearrangeObjects() // Below is an ugly hack to make sure the array controller responsible for the color palette is // always up to date colorPaletteArrayController!.insertObject(NSColor.blackColor(), atArrangedObjectIndex: 0) colorPaletteArrayController!.removeObjectAtArrangedObjectIndex(0) } } @IBAction func updateBrush(sender: AnyObject!) { documentEditorView!.brushSize = brushSize!.integerValue } /// Action to add a new layer to the editor @IBAction func addLayer(sender: AnyObject!) { documentEditorView!.addPixelLayer() } /// Action to remove the currently selected layer from the editor @IBAction func removeLayer(sender: AnyObject!) { documentEditorView!.removePixelLayer(atIndex: documentEditorView!.activePixelLayer) } /// Action to change the opacity of the selected layer @IBAction func changeLayerOpacity(sender: AnyObject!) { documentEditorView!.setOpacity((sender as NSSlider).doubleValue, ofLayerAtIndex: documentEditorView!.activePixelLayer) } /// Toggle the Pixel Grid on the canvas @IBAction func togglePixelGrid(sender: AnyObject!) { let scale = scalePopUp!.selectedTag() if scale > 100 { documentEditorView!.wantsPixelGrid = ((sender as NSButton).state == NSOnState) } } /// Change the scale of the canvas @IBAction func updateCanvasScale(sender: AnyObject!) { let scale = (sender as NSPopUpButton).selectedTag() if scale <= 100 { documentEditorView!.wantsPixelGrid = false } else { documentEditorView!.wantsPixelGrid = (pixelGridButton!.state == NSOnState) } documentEditorView!.currentScaleFactor = CGFloat(Double(scale) / 100.0) } override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<()>) { // Listen for any changes to the selection of the color palette if (object as NSCollectionView) == colorPalettePane && keyPath == "selectionIndexes" { let selectedIndex = (change["new"] as NSIndexSet).firstIndex if let color = colorSwatch.color(atIndex: selectedIndex)? { documentEditorView!.brushColor = color activeColorView!.color = color } } } }
mit
eba3eea55b2f7571ff425b1d1df7a075
36.63981
154
0.632838
5.284098
false
false
false
false
warnerbros/cpe-manifest-ios-experience
Source/Utilities/StringUtils.swift
1
2062
// // StringUtils.swift // import Foundation import UIKit extension String { func removeAll(_ characters: [Character]) -> String { return String(self.filter({ !characters.contains($0) })) } func htmlDecodedString() -> String { if let encodedData = self.data(using: String.Encoding.utf8) { let attributedOptions: [String: AnyObject] = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType as AnyObject, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8 as AnyObject] do { let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil) return attributedString.string } catch { print("Error decoding HTML string: \(error)") return self } } return self } static func localize(_ key: String) -> String { return NSLocalizedString(key, tableName: "CPEManifestExperience", bundle: Bundle.frameworkResources, value: "", comment: "") } static func localize(_ key: String, variables: [String: String?]) -> String { var localizedString = String.localize(key) for (variableName, variableValue) in variables { localizedString = localizedString.replacingOccurrences(of: "%{" + variableName + "}", with: (variableValue ?? "")) } return localizedString } static func localizePlural(_ singularKey: String, pluralKey: String, count: Int) -> String { return localize(count == 1 ? singularKey : pluralKey, variables: ["count": String(count)]) } subscript (i: Int) -> Character { return self[self.index(self.startIndex, offsetBy: i)] } subscript (i: Int) -> String { return String(self[i] as Character) } subscript (r: Range<Int>) -> String { let start = self.index(startIndex, offsetBy: r.lowerBound) let end = index(start, offsetBy: r.upperBound - r.lowerBound) return self[start ..< end] } }
apache-2.0
e0860a8fd1377ca9ba046e9d4f79a2cd
33.366667
200
0.632396
4.806527
false
false
false
false
cache0928/CCWeibo
CCWeibo/CCWeibo/Classes/Common/Models/Status.swift
1
3483
// // Status.swift // CCWeibo // // Created by 徐才超 on 16/2/10. // Copyright © 2016年 徐才超. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import Kingfisher class Status: NSObject { var created_at: String? var createTimeFoTimeLabel: String { guard let createdAt = created_at where createdAt != "" else { return "" } return NSDate.dateFromeWeiboDateStr(createdAt).weiboDescriptionDate() } var id: Int = 1 var text: String? var source: String? { didSet { guard let str = source where str != "" else { return } let startIndex = str.characters.indexOf(">") let subStr = str.substringFromIndex(startIndex!.advancedBy(1)) let endIndex = subStr.characters.indexOf("<") source = subStr.substringToIndex(endIndex!) } } var reposts_count = 0 var comments_count = 0 var pic_urls: [[String: AnyObject]] = [] { didSet { if pic_urls.count > 0 { thumbnailURLs = [[],[],[]] for dict in pic_urls { if let URLStr = dict["thumbnail_pic"] as? String { // 大图 let bigURL = URLStr.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle") // 原图 let originURL = URLStr.stringByReplacingOccurrencesOfString("thumbnail", withString: "large") thumbnailURLs![0].append(NSURL(string: URLStr)!) thumbnailURLs![1].append(NSURL(string: bigURL)!) thumbnailURLs![2].append(NSURL(string: originURL)!) } } } } } // 原创微博缩略图或者转发微博图集的url数组,0:缩略图,1:大图,2:原图 var thumbnailURLs: [[NSURL]]? var user: User? var retweeted_status: Status? { didSet { if let URLs = retweeted_status?.thumbnailURLs { thumbnailURLs = URLs } } } init(dict: [String: AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } override func setValue(value: AnyObject?, forKey key: String) { if key == "user" { user = User(dict: value as! [String: AnyObject]) return } if key == "retweeted_status" { retweeted_status = Status(dict: value as! [String: AnyObject]) return } super.setValue(value, forKey: key) } override func setValue(value: AnyObject?, forUndefinedKey key: String) { } /// 加载最近的微博数据 class func loadStatuses(sinceId: Int?, maxId: Int?, completion: (statuses: [Status])->()) { Alamofire.request(WBRouter.FetchNewWeibo(accessToken: UserAccount.loadAccount()!.accessToken, sinceId: sinceId, maxId: maxId)).responseJSON { response in guard response.result.error == nil, let data = response.result.value else { print(response.result) completion(statuses: []) return } let json = JSON(data)["statuses"] var statuses = [Status]() for (_,subJson):(String, JSON) in json { let statusDict = subJson.dictionaryObject! let status = Status(dict: statusDict) statuses.append(status) } completion(statuses: statuses) } } }
mit
84322e853afd19d8a6ae8af173b546ac
32.86
161
0.561429
4.551075
false
false
false
false
rcasanovan/Social-Feed
Social Feed/Pods/HanekeSwift/Haneke/UIButton+Haneke.swift
20
11877
// // UIButton+Haneke.swift // Haneke // // Created by Joan Romano on 10/1/14. // Copyright (c) 2014 Haneke. All rights reserved. // import UIKit public extension UIButton { public var hnk_imageFormat : Format<UIImage> { let bounds = self.bounds assert(bounds.size.width > 0 && bounds.size.height > 0, "[\(Mirror(reflecting: self).description) \(#function)]: UIButton size is zero. Set its frame, call sizeToFit or force layout first. You can also set a custom format with a defined size if you don't want to force layout.") let contentRect = self.contentRect(forBounds: bounds) let imageInsets = self.imageEdgeInsets let scaleMode = self.contentHorizontalAlignment != UIControlContentHorizontalAlignment.fill || self.contentVerticalAlignment != UIControlContentVerticalAlignment.fill ? ImageResizer.ScaleMode.AspectFit : ImageResizer.ScaleMode.Fill let imageSize = CGSize(width: contentRect.width - imageInsets.left - imageInsets.right, height: contentRect.height - imageInsets.top - imageInsets.bottom) return HanekeGlobals.UIKit.formatWithSize(imageSize, scaleMode: scaleMode, allowUpscaling: scaleMode == ImageResizer.ScaleMode.AspectFit ? false : true) } public func hnk_setImageFromURL(_ URL: Foundation.URL, state: UIControlState = .normal, placeholder: UIImage? = nil, format: Format<UIImage>? = nil, failure fail: ((Error?) -> ())? = nil, success succeed: ((UIImage) -> ())? = nil) { let fetcher = NetworkFetcher<UIImage>(URL: URL) self.hnk_setImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, failure: fail, success: succeed) } public func hnk_setImage(_ image: UIImage, key: String, state: UIControlState = .normal, placeholder: UIImage? = nil, format: Format<UIImage>? = nil, success succeed: ((UIImage) -> ())? = nil) { let fetcher = SimpleFetcher<UIImage>(key: key, value: image) self.hnk_setImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, success: succeed) } public func hnk_setImageFromFile(_ path: String, state: UIControlState = .normal, placeholder: UIImage? = nil, format: Format<UIImage>? = nil, failure fail: ((Error?) -> ())? = nil, success succeed: ((UIImage) -> ())? = nil) { let fetcher = DiskFetcher<UIImage>(path: path) self.hnk_setImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, failure: fail, success: succeed) } public func hnk_setImageFromFetcher(_ fetcher: Fetcher<UIImage>, state: UIControlState = .normal, placeholder: UIImage? = nil, format: Format<UIImage>? = nil, failure fail: ((Error?) -> ())? = nil, success succeed: ((UIImage) -> ())? = nil){ self.hnk_cancelSetImage() self.hnk_imageFetcher = fetcher let didSetImage = self.hnk_fetchImageForFetcher(fetcher, state: state, format : format, failure: fail, success: succeed) if didSetImage { return } if let placeholder = placeholder { self.setImage(placeholder, for: state) } } public func hnk_cancelSetImage() { if let fetcher = self.hnk_imageFetcher { fetcher.cancelFetch() self.hnk_imageFetcher = nil } } // MARK: Internal Image // See: http://stackoverflow.com/questions/25907421/associating-swift-things-with-nsobject-instances var hnk_imageFetcher : Fetcher<UIImage>! { get { let wrapper = objc_getAssociatedObject(self, &HanekeGlobals.UIKit.SetImageFetcherKey) as? ObjectWrapper let fetcher = wrapper?.hnk_value as? Fetcher<UIImage> return fetcher } set (fetcher) { var wrapper : ObjectWrapper? if let fetcher = fetcher { wrapper = ObjectWrapper(value: fetcher) } objc_setAssociatedObject(self, &HanekeGlobals.UIKit.SetImageFetcherKey, wrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } func hnk_fetchImageForFetcher(_ fetcher : Fetcher<UIImage>, state : UIControlState = .normal, format : Format<UIImage>? = nil, failure fail : ((Error?) -> ())?, success succeed : ((UIImage) -> ())?) -> Bool { let format = format ?? self.hnk_imageFormat let cache = Shared.imageCache if cache.formats[format.name] == nil { cache.addFormat(format) } var animated = false let fetch = cache.fetch(fetcher: fetcher, formatName: format.name, failure: {[weak self] error in if let strongSelf = self { if strongSelf.hnk_shouldCancelImageForKey(fetcher.key) { return } strongSelf.hnk_imageFetcher = nil fail?(error) } }) { [weak self] image in if let strongSelf = self { if strongSelf.hnk_shouldCancelImageForKey(fetcher.key) { return } strongSelf.hnk_setImage(image, state: state, animated: animated, success: succeed) } } animated = true return fetch.hasSucceeded } func hnk_setImage(_ image : UIImage, state : UIControlState, animated : Bool, success succeed : ((UIImage) -> ())?) { self.hnk_imageFetcher = nil if let succeed = succeed { succeed(image) } else if animated { UIView.transition(with: self, duration: HanekeGlobals.UIKit.SetImageAnimationDuration, options: .transitionCrossDissolve, animations: { self.setImage(image, for: state) }, completion: nil) } else { self.setImage(image, for: state) } } func hnk_shouldCancelImageForKey(_ key:String) -> Bool { if self.hnk_imageFetcher?.key == key { return false } Log.debug(message: "Cancelled set image for \((key as NSString).lastPathComponent)") return true } // MARK: Background image public var hnk_backgroundImageFormat : Format<UIImage> { let bounds = self.bounds assert(bounds.size.width > 0 && bounds.size.height > 0, "[\(Mirror(reflecting: self).description) \(#function)]: UIButton size is zero. Set its frame, call sizeToFit or force layout first. You can also set a custom format with a defined size if you don't want to force layout.") let imageSize = self.backgroundRect(forBounds: bounds).size return HanekeGlobals.UIKit.formatWithSize(imageSize, scaleMode: .Fill) } public func hnk_setBackgroundImageFromURL(_ URL : Foundation.URL, state : UIControlState = .normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((Error?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil) { let fetcher = NetworkFetcher<UIImage>(URL: URL) self.hnk_setBackgroundImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, failure: fail, success: succeed) } public func hnk_setBackgroundImage(_ image : UIImage, key: String, state : UIControlState = .normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, success succeed : ((UIImage) -> ())? = nil) { let fetcher = SimpleFetcher<UIImage>(key: key, value: image) self.hnk_setBackgroundImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, success: succeed) } public func hnk_setBackgroundImageFromFile(_ path: String, state : UIControlState = .normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((Error?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil) { let fetcher = DiskFetcher<UIImage>(path: path) self.hnk_setBackgroundImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, failure: fail, success: succeed) } public func hnk_setBackgroundImageFromFetcher(_ fetcher : Fetcher<UIImage>, state : UIControlState = .normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((Error?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil) { self.hnk_cancelSetBackgroundImage() self.hnk_backgroundImageFetcher = fetcher let didSetImage = self.hnk_fetchBackgroundImageForFetcher(fetcher, state: state, format : format, failure: fail, success: succeed) if didSetImage { return } if let placeholder = placeholder { self.setBackgroundImage(placeholder, for: state) } } public func hnk_cancelSetBackgroundImage() { if let fetcher = self.hnk_backgroundImageFetcher { fetcher.cancelFetch() self.hnk_backgroundImageFetcher = nil } } // MARK: Internal Background image // See: http://stackoverflow.com/questions/25907421/associating-swift-things-with-nsobject-instances var hnk_backgroundImageFetcher : Fetcher<UIImage>! { get { let wrapper = objc_getAssociatedObject(self, &HanekeGlobals.UIKit.SetBackgroundImageFetcherKey) as? ObjectWrapper let fetcher = wrapper?.hnk_value as? Fetcher<UIImage> return fetcher } set (fetcher) { var wrapper : ObjectWrapper? if let fetcher = fetcher { wrapper = ObjectWrapper(value: fetcher) } objc_setAssociatedObject(self, &HanekeGlobals.UIKit.SetBackgroundImageFetcherKey, wrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } func hnk_fetchBackgroundImageForFetcher(_ fetcher: Fetcher<UIImage>, state: UIControlState = .normal, format: Format<UIImage>? = nil, failure fail: ((Error?) -> ())?, success succeed : ((UIImage) -> ())?) -> Bool { let format = format ?? self.hnk_backgroundImageFormat let cache = Shared.imageCache if cache.formats[format.name] == nil { cache.addFormat(format) } var animated = false let fetch = cache.fetch(fetcher: fetcher, formatName: format.name, failure: {[weak self] error in if let strongSelf = self { if strongSelf.hnk_shouldCancelBackgroundImageForKey(fetcher.key) { return } strongSelf.hnk_backgroundImageFetcher = nil fail?(error) } }) { [weak self] image in if let strongSelf = self { if strongSelf.hnk_shouldCancelBackgroundImageForKey(fetcher.key) { return } strongSelf.hnk_setBackgroundImage(image, state: state, animated: animated, success: succeed) } } animated = true return fetch.hasSucceeded } func hnk_setBackgroundImage(_ image: UIImage, state: UIControlState, animated: Bool, success succeed: ((UIImage) -> ())?) { self.hnk_backgroundImageFetcher = nil if let succeed = succeed { succeed(image) } else if animated { UIView.transition(with: self, duration: HanekeGlobals.UIKit.SetImageAnimationDuration, options: .transitionCrossDissolve, animations: { self.setBackgroundImage(image, for: state) }, completion: nil) } else { self.setBackgroundImage(image, for: state) } } func hnk_shouldCancelBackgroundImageForKey(_ key: String) -> Bool { if self.hnk_backgroundImageFetcher?.key == key { return false } Log.debug(message: "Cancelled set background image for \((key as NSString).lastPathComponent)") return true } }
apache-2.0
3c3ac5ec33a75ef06dcb1b7f6f9c42be
49.75641
286
0.629704
4.881628
false
false
false
false
OSzhou/MyTestDemo
PerfectDemoProject(swift写服务端)/.build/checkouts/PerfectLib.git-3712999737848873669/Package.swift
1
836
// // Package.swift // PerfectLib // // Created by Kyle Jessup on 3/22/16. // Copyright (C) 2016 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import PackageDescription var urls = [String]() #if os(Linux) urls += ["https://github.com/PerfectlySoft/Perfect-LinuxBridge.git"] #else #endif let package = Package( name: "PerfectLib", targets: [], dependencies: urls.map { .Package(url: $0, majorVersion: 2) }, exclude: [] )
apache-2.0
a5d9f7de327e84f8ce6a6d4c54a58814
22.885714
80
0.557416
4
false
false
false
false
iOS-mamu/SS
P/Pods/PSOperations/PSOperationsHealth/HealthCondition.swift
1
4496
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file shows an example of implementing the OperationCondition protocol. */ #if os(iOS) import HealthKit import UIKit import PSOperations /** A condition to indicate an `Operation` requires access to the user's health data. */ @available(*, deprecated, message: "use Capability(Health(...)) instead") public struct HealthCondition: OperationCondition { public static let name = "Health" static let healthDataAvailable = "HealthDataAvailable" static let unauthorizedShareTypesKey = "UnauthorizedShareTypes" public static let isMutuallyExclusive = false let shareTypes: Set<HKSampleType> let readTypes: Set<HKSampleType> /** The designated initializer. - parameter typesToWrite: An array of `HKSampleType` objects, indicating the kinds of data you wish to save to HealthKit. - parameter typesToRead: An array of `HKSampleType` objects, indicating the kinds of data you wish to read from HealthKit. */ public init(typesToWrite: Set<HKSampleType>, typesToRead: Set<HKSampleType>) { shareTypes = typesToWrite readTypes = typesToRead } public func dependencyForOperation(_ operation: PSOperations.Operation) -> Foundation.Operation? { if !HKHealthStore.isHealthDataAvailable() { return nil } if shareTypes.isEmpty && readTypes.isEmpty { return nil } return HealthPermissionOperation(shareTypes: shareTypes, readTypes: readTypes) } public func evaluateForOperation(_ operation: PSOperations.Operation, completion: @escaping (OperationConditionResult) -> Void) { if !HKHealthStore.isHealthDataAvailable() { failed(shareTypes, completion: completion) return } let store = HKHealthStore() /* Note that we cannot check to see if access to the "typesToRead" has been granted or not, as that is sensitive data. For example, a person with diabetes may choose to not allow access to Blood Glucose data, and the fact that this request has denied is itself an indicator that the user may have diabetes. Thus, we can only check to see if we've been given permission to write data to HealthKit. */ let unauthorizedShareTypes = shareTypes.filter { shareType in return store.authorizationStatus(for: shareType) != .sharingAuthorized } if !unauthorizedShareTypes.isEmpty { failed(Set(unauthorizedShareTypes), completion: completion) } else { completion(.satisfied) } } // Break this out in to its own method so we don't clutter up the evaluate... method. fileprivate func failed(_ unauthorizedShareTypes: Set<HKSampleType>, completion: (OperationConditionResult) -> Void) { let error = NSError(code: .conditionFailed, userInfo: [ OperationConditionKey: type(of: self).name, type(of: self).healthDataAvailable: HKHealthStore.isHealthDataAvailable(), type(of: self).unauthorizedShareTypesKey: unauthorizedShareTypes ]) completion(.failed(error)) } } /** A private `Operation` that will request access to the user's health data, if it has not already been granted. */ class HealthPermissionOperation: PSOperations.Operation { let shareTypes: Set<HKSampleType> let readTypes: Set<HKSampleType> init(shareTypes: Set<HKSampleType>, readTypes: Set<HKSampleType>) { self.shareTypes = shareTypes self.readTypes = readTypes super.init() addCondition(MutuallyExclusive<HealthPermissionOperation>()) addCondition(MutuallyExclusive<UIViewController>()) addCondition(AlertPresentation()) } override func execute() { DispatchQueue.main.async { let store = HKHealthStore() /* This method is smart enough to not re-prompt for access if access has already been granted. */ store.requestAuthorization(toShare: self.shareTypes, read: self.readTypes) { completed, error in self.finish() } } } } #endif
mit
deb94dd99bc2a1306f587c3754093143
33.045455
133
0.650423
5.101022
false
false
false
false
adrfer/swift
validation-test/compiler_crashers_fixed/27456-swift-abstractclosureexpr-setparams.swift
13
2379
// 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 } class b typealias e let end = " \ ( { {} class d protocol a T { struct Q<T{class B<T where f={ if true { class C(object1: a{ struct d=true { let end = " ) struct Q<T {c d<T> : Any) }class c{ typealias b let a {} struct c{ enum S<T where B<h:b a : d<T> : d<T NSObject { var f=true { } protocol A { struct d<T{ class C{ if true as S<T> func a() let f={ } enum B{ } class a {{ protocol A { var _=(object1 : d<T T{ for c d<T where f={ func g<T T> if true { class a { class d<T where class A{struct d< func<T where B : d { } protocol A:{struct e.b }} class c{ protocol A{ func g:A{class { protocol P{}class d<h:{} enum B{ enum S<T{class C if true { let a : whe if true {c e=e=""" class c{ protocol a {var e }struct D : a ifruct var e=(object1 : a { class C{ struct d<T where B : whe class a : d<T {class B enum B class C{ let end = " \ () { class c{{typealias b var f={ let end = D> ) { class a T NSObject { struct D : a func g:{ func a(object1 : = D> : d<T NSObject { struct B:A? { class C struct B func " ) func T{ func g: d<T where g<T where g:e:C( func g:b func g: T) { enum S struct Q<T {class B{ struct B protocol A { class B< T where B<T NSObject { } }} struct e() }protocol a T {} class c{ typealias e={ if true { class c{let f={} class A<T) { func g<T : T> {class C class c{ { class c{} } enum S<T{ }protocol b func a{} a { var _=(object1: a() } { class b if true {c d<T where T> : d<T where B { } "[1 let:A:A{class A{ } a : Any) func g:C { struct B{ class a"\ (object1 : = " ) } func T) {{let end = B class A{} } struct e:e.b func a class d<T where var f={ func<T NSObject { if true { { for c e={ struct B{ struct d<T{ func T> ) { struct c{ enum B } protocol A { enum B{ { protocol P{ protocol P{ } if true{} for c e="[1 func a( for c d var f {{ let end = " ) class d=true {let f=" protocol A? { func T> enum S<T where B : A{} { } struct B< T { class C{ } let f: d } struct Q<l where g:A{ class d<T where g<h:{ { func T{ }protocol P{ a : a( enum k protocol P{ struct B }class a T where B : a if true{ {} class A{ }class a {var d { { enum B struct d if true { class A{class d< var b ="[1 func a if true {} class c{ var e(object1: a<T where B<T where B : Any
apache-2.0
de5b1b1f89086d6dd674827880e2ee32
11.390625
87
0.617066
2.336935
false
false
false
false
CoderXiaoming/Ronaldo
SaleManager/SaleManager/Other/SAMStringExtension.swift
1
1176
// // SAMStringExtension.swift // SaleManager // // Created by apple on 16/11/18. // Copyright © 2016年 YZH. All rights reserved. // import UIKit extension String { //MARK: - 去掉字符串前后空白 func lxm_stringByTrimmingWhitespace() -> String? { return trimmingCharacters(in: CharacterSet.whitespaces) } //MARK: - 判断是不是纯数字 func lxm_stringisWholeNumber() -> Bool { if self == "" { return false } let str = trimmingCharacters(in: CharacterSet.decimalDigits) let nsStr = NSString(string: str) if nsStr.length > 0 { return false } return true } //MARK: - 判断最后一个是不是所传字符串,如果是就切掉 func lxm_stringByTrimmingLastIfis(_ lastString: String) ->String { let str = NSString(string: self) let strLength = str.length let lastStr = str.substring(from: strLength - 1) if lastStr == lastString { return str.substring(to: strLength - 1) }else { return self } } }
apache-2.0
3b45e1e1adea39b1c829f1a49d633fcf
16.412698
70
0.554239
4.139623
false
false
false
false
kunass2/BSSelectableView
SelectableView/Classes/SearchSelectableView.swift
2
3451
// // SearchSelectableView.swift // Pods // // Created by Bartłomiej Semańczyk on 14/03/2017. // // open class SearchSelectableView: SelectableView, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate { @IBOutlet open var textField: UITextField! open var selectedOption: SelectableOption? { didSet { textField.text = selectedOption?.title tableView.reloadData() expanded = false if let option = selectedOption { delegate?.searchSelectableView?(self, didSelect: option) } } } var filteredOptions: [SelectableOption] { return textField.text!.isEmpty ? options : options.filter { $0.title.lowercased().contains(textField.text!.lowercased()) } } override var expanded: Bool { didSet { super.expanded = expanded updateContentOptionsHeight(for: filteredOptions) } } //MARK: - Class Methods //MARK: - Initialization open override func awakeFromNib() { super.awakeFromNib() textField.delegate = self tableView.delegate = self tableView.dataSource = self textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) } //MARK: - Deinitialization //MARK: - Actions //MARK: - Open //MARK: - Internal @objc func textFieldDidChange(_ sender: UITextField) { tableView.reloadData() expanded = true if sender.text!.isEmpty { selectedOption = nil } } //MARK: - Private //MARK: - Overridden //MARK: - UITableViewDataSource open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredOptions.count } open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: SelectableTableViewCellIdentifier, for: indexPath) as! SelectableTableViewCell let option = filteredOptions[indexPath.row] cell.titleLabel.text = option.title cell.titleLabel.font = fontForOption cell.titleLabel.textColor = option.identifier == selectedOption?.identifier ? titleColorForSelectedOption : titleColorForOption cell.leftPaddingConstraint.constant = CGFloat(leftPaddingForOption) cell.layoutMargins = UIEdgeInsets.zero cell.accessoryType = option.identifier == selectedOption?.identifier ? .checkmark : .none cell.tintColor = tintColorForSelectedOption cell.selectionStyle = .none return cell } //MARK: - UITableViewDelegate open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedOption = filteredOptions[indexPath.row] } //MARK: - UITextFieldDelegate public func textFieldDidBeginEditing(_ textField: UITextField) { expanded = true } public func textFieldShouldClear(_ textField: UITextField) -> Bool { selectedOption = nil return true } public func textFieldDidEndEditing(_ textField: UITextField) { expanded = false } }
mit
16171fe14b6b8e5e3b69e0a53103729e
27.504132
143
0.61902
5.60813
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
Pods/HXPHPicker/Sources/HXPHPicker/Camera/Config/CameraConfiguration.swift
1
6672
// // CameraConfiguration.swift // HXPHPicker // // Created by Slience on 2021/8/30. // import UIKit import AVFoundation // MARK: 相机配置类 public class CameraConfiguration: BaseConfiguration { /// 相机类型 public var cameraType: CameraController.CameraType = .normal /// 相机分辨率 public var sessionPreset: Preset = .hd1280x720 /// 摄像头默认位置 public var position: DevicePosition = .back /// 默认闪光灯模式 public var flashMode: AVCaptureDevice.FlashMode = .auto /// 录制视频时设置的 `AVVideoCodecType` /// iPhone7 以下为 `.h264` public var videoCodecType: AVVideoCodecType = .h264 /// 视频最大录制时长 /// takePhotoMode = .click 支持不限制最大时长 (0 - 不限制) /// takePhotoMode = .press 最小 1 public var videoMaximumDuration: TimeInterval = 60 /// 视频最短录制时长 public var videoMinimumDuration: TimeInterval = 1 /// 拍照方式 public var takePhotoMode: TakePhotoMode = .press /// 主题色 public var tintColor: UIColor = .systemTintColor { didSet { #if HXPICKER_ENABLE_EDITOR setupEditorColor() #endif } } /// 摄像头最大缩放比例 public var videoMaxZoomScale: CGFloat = 6 /// 默认滤镜对应滤镜数组的下标,为 -1 默认不加滤镜 public var defaultFilterIndex: Int = -1 /// 切换滤镜显示名称 public var changeFilterShowName: Bool = true /// 拍照时的滤镜数组,请与 videoFilters 效果保持一致 /// 左滑/右滑切换滤镜 public lazy var photoFilters: [CameraFilter] = [ InstantFilter(), Apply1977Filter(), ToasterFilter(), TransferFilter() ] /// 录制视频的滤镜数组,请与 photoFilters 效果保持一致 /// 左滑/右滑切换滤镜 public lazy var videoFilters: [CameraFilter] = [ InstantFilter(), Apply1977Filter(), ToasterFilter(), TransferFilter() ] #if HXPICKER_ENABLE_EDITOR /// 允许编辑 /// true: 拍摄完成后会跳转到编辑界面 public var allowsEditing: Bool = true /// 照片编辑器配置 public lazy var photoEditor: PhotoEditorConfiguration = .init() /// 视频编辑器配置 public lazy var videoEditor: VideoEditorConfiguration = .init() #endif /// 允许启动定位 public var allowLocation: Bool = true public override init() { super.init() /// shouldAutorotate 能够旋转 /// supportedInterfaceOrientations 支持的方向 /// 隐藏状态栏 prefersStatusBarHidden = true appearanceStyle = .normal #if HXPICKER_ENABLE_EDITOR photoEditor.languageType = languageType videoEditor.languageType = languageType photoEditor.indicatorType = indicatorType videoEditor.indicatorType = indicatorType photoEditor.appearanceStyle = appearanceStyle videoEditor.appearanceStyle = appearanceStyle #endif } #if HXPICKER_ENABLE_EDITOR public override var languageType: LanguageType { didSet { photoEditor.languageType = languageType videoEditor.languageType = languageType } } public override var indicatorType: BaseConfiguration.IndicatorType { didSet { photoEditor.indicatorType = indicatorType videoEditor.indicatorType = indicatorType } } public override var appearanceStyle: AppearanceStyle { didSet { photoEditor.appearanceStyle = appearanceStyle videoEditor.appearanceStyle = appearanceStyle } } #endif } extension CameraConfiguration { public enum DevicePosition { /// 后置 case back /// 前置 case front } public enum TakePhotoMode { /// 长按 case press /// 点击(支持不限制最大时长) case click } public enum Preset { case vga640x480 case iFrame960x540 case hd1280x720 case hd1920x1080 case hd4K3840x2160 var system: AVCaptureSession.Preset { switch self { case .vga640x480: return .vga640x480 case .iFrame960x540: return .iFrame960x540 case .hd1280x720: return .hd1280x720 case .hd1920x1080: return .hd1920x1080 case .hd4K3840x2160: return .hd4K3840x2160 } } var size: CGSize { switch self { case .vga640x480: return CGSize(width: 480, height: 640) case .iFrame960x540: return CGSize(width: 540, height: 960) case .hd1280x720: return CGSize(width: 720, height: 1280) case .hd1920x1080: return CGSize(width: 1080, height: 1920) case .hd4K3840x2160: return CGSize(width: 2160, height: 3840) } } } #if HXPICKER_ENABLE_EDITOR fileprivate func setupEditorColor() { videoEditor.cropConfirmView.finishButtonBackgroundColor = tintColor videoEditor.cropConfirmView.finishButtonDarkBackgroundColor = tintColor videoEditor.cropSize.aspectRatioSelectedColor = tintColor videoEditor.toolView.finishButtonBackgroundColor = tintColor videoEditor.toolView.finishButtonDarkBackgroundColor = tintColor videoEditor.toolView.toolSelectedColor = tintColor videoEditor.toolView.musicSelectedColor = tintColor videoEditor.music.tintColor = tintColor videoEditor.text.tintColor = tintColor videoEditor.filter = .init( infos: videoEditor.filter.infos, selectedColor: tintColor ) photoEditor.toolView.toolSelectedColor = tintColor photoEditor.toolView.finishButtonBackgroundColor = tintColor photoEditor.toolView.finishButtonDarkBackgroundColor = tintColor photoEditor.cropConfimView.finishButtonBackgroundColor = tintColor photoEditor.cropConfimView.finishButtonDarkBackgroundColor = tintColor photoEditor.cropping.aspectRatioSelectedColor = tintColor photoEditor.filter = .init( infos: photoEditor.filter.infos, selectedColor: tintColor ) photoEditor.text.tintColor = tintColor } #endif }
mit
22d7d006899754aa5fe07624b0d024c4
28.393365
79
0.618671
4.687831
false
false
false
false
xwu/swift
test/decl/protocol/conforms/actor_derived.swift
3
1038
// RUN: %target-typecheck-verify-swift // REQUIRES: concurrency @available(SwiftStdlib 5.5, *) actor A1: Hashable { nonisolated func hash(into hasher: inout Hasher) { } static func ==(lhs: A1, rhs: A1) -> Bool { true } } @available(SwiftStdlib 5.5, *) actor A2: Hashable { nonisolated var hashValue: Int { 0 } // expected-warning{{'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'A2' to 'Hashable' by implementing 'hash(into:)' instead}} static func ==(lhs: A2, rhs: A2) -> Bool { true } } @available(SwiftStdlib 5.5, *) @MainActor class C1: Hashable { nonisolated func hash(into hasher: inout Hasher) { } nonisolated static func ==(lhs: C1, rhs: C1) -> Bool { true } } @available(SwiftStdlib 5.5, *) @MainActor class C2: Hashable { nonisolated var hashValue: Int { 0 } // expected-warning{{'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'C2' to 'Hashable' by implementing 'hash(into:)' instead}} nonisolated static func ==(lhs: C2, rhs: C2) -> Bool { true } }
apache-2.0
a1150c6974577d6b99bd3797e65ad71b
33.6
193
0.691715
3.518644
false
false
false
false
devpunk/velvet_room
Source/Model/Vita/MVitaPtpType.swift
1
488
enum MVitaPtpType:UInt32 { case unknown case commandRequest = 1 case commandRequestAccepted = 2 case eventRequest = 3 case eventRequestAccepted = 4 case command = 6 case commandAccepted = 7 case event = 8 case dataPacketStart = 9 case dataPacket = 10 case dataPacketEnd = 12 }
mit
92f697b77e7def30ea148fe3cc6cf0ff
33.857143
44
0.446721
5.483146
false
false
false
false
synergistic-fantasy/wakeonlan-osx
WakeOnLAN-OSX/Controllers/StatusTableViewController.swift
1
2908
// // StatusTableViewController.swift // WakeOnLAN-OSX // // Created by Mario Estrella on 12/12/15. // Copyright © 2015 Synergistic Fantasy LLC. All rights reserved. // import Cocoa class StatusTableViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource { // MARK: - Variables lazy var managedObjectContext : NSManagedObjectContext = { let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate var managedObjectContext = appDelegate.managedObjectContext return managedObjectContext }() let ipPredicate = NSPredicate(format: "ipAddress !='' ") let sort = NSSortDescriptor(key: "compName", ascending: true) var currentState: Dictionary<String,Bool> = [:] var computerList: [Computer] = [] @IBOutlet weak var statusTable: NSTableView! // MARK: - Overrides override func viewDidLoad() { super.viewDidLoad() populateTable() } // MARK: - Functions func populateTable() { let sort = NSSortDescriptor(key: "compName", ascending: true) let fetchRequest = NSFetchRequest(entityName: "Computer") fetchRequest.sortDescriptors = [sort] fetchRequest.predicate = ipPredicate do { computerList = try self.managedObjectContext.executeFetchRequest(fetchRequest) as! [Computer] } catch { print("There was an error") } statusTable.reloadData() } func numberOfRowsInTableView(tableView: NSTableView) -> Int { return computerList.count } func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { let cell = tableView.makeViewWithIdentifier((tableColumn?.identifier)!, owner: self) as! StatusCellView let textfield = cell.textField if tableColumn?.identifier == "Computer" { textfield?.stringValue = computerList[row].compName! } if tableColumn?.identifier == "IPv4Address" { textfield?.stringValue = computerList[row].ipAddress! } if tableColumn?.identifier == "Status" { let computerName = computerList[row].compName! if let cellStat = currentState[computerName] { cell.setStatus(cellStat) } else { cell.setStatus(false) } } return cell } @IBAction func refresh(sender: AnyObject) { performSegueWithIdentifier("progressSheet", sender: self) self.currentState = GetState().networkState self.statusTable.reloadData() self.dismissViewController((self.presentedViewControllers?.first)!) } @IBAction func close(sender: AnyObject) { dismissViewController(self) } }
gpl-3.0
dc94e4f4c5b54ff2eb93118b06d18c3a
28.969072
113
0.628139
5.333945
false
false
false
false
chenxtdo/UPImageMacApp
UPImage/AppHelper.swift
1
3967
// // AppHelper.swift // U图床 // // Created by Pro.chen on 16/7/13. // Copyright © 2016年 chenxt. All rights reserved. // import Foundation import AppKit import TMCache public enum Result<Value> { case success(Value) case failure(Value) public func Success( success: (_ value: Value) -> Void) -> Result<Value> { switch self { case .success(let value): success(value) default: break } return self } public func Failure( failure: (_ error: Value) -> Void) -> Result<Value> { switch self { case .failure(let error): failure(error) default: break } return self } } extension NSImage { func scalingImage() { let sW = self.size.width let sH = self.size.height let nW: CGFloat = 100 let nH = nW * sH / sW self.size = CGSize(width: nW, height: nH) } } func NotificationMessage(_ message: String, informative: String? = nil, isSuccess: Bool = false) { let notification = NSUserNotification() let notificationCenter = NSUserNotificationCenter.default notificationCenter.delegate = appDelegate as? NSUserNotificationCenterDelegate notification.title = message notification.informativeText = informative if isSuccess { notification.contentImage = NSImage(named: "success") notification.informativeText = "链接已经保存在剪贴板里,可以直接粘贴" } else { notification.contentImage = NSImage(named: "Failure") } notification.soundName = NSUserNotificationDefaultSoundName; notificationCenter.scheduleNotification(notification) } func arc() -> UInt32 { return arc4random() % 100000 } func timeInterval() -> Int { return Int(Date(timeIntervalSinceNow: 0).timeIntervalSince1970) } func getDateString() -> String { let dateformatter = DateFormatter() dateformatter.dateFormat = "YYYYMMdd" let dataString = dateformatter.string(from: Date(timeInterval: 0, since: Date())) return dataString } func checkImageFile(_ pboard: NSPasteboard) -> Bool { guard let pasteboard = pboard.propertyList(forType: NSPasteboard.PasteboardType(rawValue: "NSFilenamesPboardType")) as? NSArray, let path = pasteboard[0] as? String else { return false } let image = NSImage(contentsOfFile: path) guard let _ = image else { return false } return true } func getImageType(_ data: Data) -> String { var c: uint8 = 0 data.copyBytes(to: &c, count: 1) switch c { case 0xFF: return ".jpeg" case 0x89: return ".png" case 0x49: return ".tiff" case 0x4D: return ".tiff" case 0x52: guard data.count > 12, let str = String(data: data.subdata(in: 0..<13), encoding: .ascii), str.hasPrefix("RIFF"), str.hasPrefix("WEBP") else { return "" } return ".webp" default: return "" } } private let pngHeader: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] private let jpgHeaderSOI: [UInt8] = [0xFF, 0xD8] private let jpgHeaderIF: [UInt8] = [0xFF] private let gifHeader: [UInt8] = [0x47, 0x49, 0x46] enum ImageFormat : String { case unknown = "" case png = ".png" case jpeg = ".jpg" case gif = ".gif" } extension Data { var imageFormat: ImageFormat { var buffer = [UInt8](repeating: 0, count: 8) (self as NSData).getBytes(&buffer, length: 8) if buffer == pngHeader { return .png } else if buffer[0] == jpgHeaderSOI[0] && buffer[1] == jpgHeaderSOI[1] && buffer[2] == jpgHeaderIF[0] { return .jpeg } else if buffer[0] == gifHeader[0] && buffer[1] == gifHeader[1] && buffer[2] == gifHeader[2] { return .gif } return .unknown } }
mit
75a91d7208df52c966890132aff706d9
23.679245
150
0.602701
3.828293
false
false
false
false
debugsquad/Hyperborea
Hyperborea/View/Settings/VSettingsCellLanguage.swift
1
5372
import UIKit class VSettingsCellLanguage:VSettingsCell { private weak var buttonEnglish:VSettingsCellLanguageButton! private weak var buttonSpanish:VSettingsCellLanguageButton! private weak var layoutButtonEnglishLeft:NSLayoutConstraint! private let buttonsWidth:CGFloat private let kButtonSize:CGFloat = 60 private let kInterButtons:CGFloat = 10 private let kButtonTop:CGFloat = 40 private let kButtonBottom:CGFloat = -10 private let kLabelTitleTop:CGFloat = 20 private let kLabelTitleHeight:CGFloat = 17 override init(frame:CGRect) { buttonsWidth = kButtonSize + kButtonSize + kInterButtons super.init(frame:frame) let labelTitle:UILabel = UILabel() labelTitle.isUserInteractionEnabled = false labelTitle.translatesAutoresizingMaskIntoConstraints = false labelTitle.backgroundColor = UIColor.clear labelTitle.textAlignment = NSTextAlignment.center labelTitle.font = UIFont.bold(size:14) labelTitle.textColor = UIColor.white labelTitle.text = NSLocalizedString("VSettingsCellLanguage_labelTitle", comment:"") let buttonEnglish:VSettingsCellLanguageButton = VSettingsCellLanguageButton( imageOn:#imageLiteral(resourceName: "assetGenericEnglishOn"), imageOff:#imageLiteral(resourceName: "assetGenericEnglishOff")) buttonEnglish.addTarget( self, action:#selector(actionEnglish(sender:)), for:UIControlEvents.touchUpInside) self.buttonEnglish = buttonEnglish let buttonSpanish:VSettingsCellLanguageButton = VSettingsCellLanguageButton( imageOn:#imageLiteral(resourceName: "assetGenericSpanishOn"), imageOff:#imageLiteral(resourceName: "assetGenericSpanishOff")) buttonSpanish.addTarget( self, action:#selector(actionSpanish(sender:)), for:UIControlEvents.touchUpInside) self.buttonSpanish = buttonSpanish addSubview(labelTitle) addSubview(buttonEnglish) addSubview(buttonSpanish) NSLayoutConstraint.topToTop( view:buttonEnglish, toView:self, constant:kButtonTop) NSLayoutConstraint.bottomToBottom( view:buttonEnglish, toView:self, constant:kButtonBottom) layoutButtonEnglishLeft = NSLayoutConstraint.leftToLeft( view:buttonEnglish, toView:self) NSLayoutConstraint.width( view:buttonEnglish, constant:kButtonSize) NSLayoutConstraint.topToTop( view:buttonSpanish, toView:self, constant:kButtonTop) NSLayoutConstraint.bottomToBottom( view:buttonSpanish, toView:self, constant:kButtonBottom) NSLayoutConstraint.leftToRight( view:buttonSpanish, toView:buttonEnglish, constant:kInterButtons) NSLayoutConstraint.width( view:buttonSpanish, constant:kButtonSize) NSLayoutConstraint.topToTop( view:labelTitle, toView:self, constant:kLabelTitleTop) NSLayoutConstraint.height( view:labelTitle, constant:kLabelTitleHeight) NSLayoutConstraint.equalsHorizontal( view:labelTitle, toView:self) updateLanguages() } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { let width:CGFloat = bounds.maxX let remainWidth:CGFloat = width - buttonsWidth let marginLeft:CGFloat = remainWidth / 2.0 layoutButtonEnglishLeft.constant = marginLeft super.layoutSubviews() } //MARK: actions func actionEnglish(sender button:UIButton) { let languageEnglish:MLanguageEnglish = MLanguageEnglish() newLanguage(language:languageEnglish) } func actionSpanish(sender button:UIButton) { let languageSpanish:MLanguageSpanish = MLanguageSpanish() newLanguage(language:languageSpanish) } //MARK: private private func updateLanguages() { guard let language:MLanguage = MSession.sharedInstance.settings?.currentLanguage() else { return } if let _:MLanguageEnglish = language as? MLanguageEnglish { buttonEnglish.isSelected = true buttonSpanish.isSelected = false } else { buttonEnglish.isSelected = false buttonSpanish.isSelected = true } } private func newLanguage(language:MLanguage) { DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { MSession.sharedInstance.settings?.changeLanguage(language:language) DispatchQueue.main.async { [weak self] in self?.updateLanguages() } NotificationCenter.default.post( name:Notification.clearCache, object:nil) } } }
mit
815fdcffd2b5941ab6947a8b282eb0e9
30.415205
91
0.618392
5.727079
false
false
false
false
pubnative/pubnative-ios-integration-examples
sample/sample.medium/Swift/MediumSampleSwiftViewController.swift
1
2109
// // MediumSampleSwiftViewController.swift // sample // // Created by Can Soykarafakili on 04.08.17. // Copyright © 2017 Can Soykarafakili. All rights reserved. // import UIKit import Pubnative class MediumSampleSwiftViewController: UIViewController { var mediumLayout : PNMediumLayout? @IBOutlet weak var mediumAdContainer: UIView! @IBOutlet weak var loadingIndicator: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) mediumLayout?.stopTrackingView() } @IBAction func requestButtonTouchUpInside(_ sender: Any) { mediumAdContainer.isHidden = true; loadingIndicator.startAnimating() if (mediumLayout == nil) { mediumLayout = PNMediumLayout() } mediumLayout?.load(withAppToken: Settings.appToken(), placement: Settings.placement(), delegate: self) } } extension MediumSampleSwiftViewController : PNLayoutLoadDelegate { func layoutDidFinishLoading(_ layout: PNLayout!) { print("Layout loaded") if (mediumLayout == layout) { mediumAdContainer.isHidden = false; loadingIndicator.stopAnimating() layout.trackDelegate = self let layoutView = mediumLayout?.viewController.view mediumAdContainer.addSubview(layoutView!) mediumLayout?.startTrackingView() // You can access layout.viewController and customize the ad appearance with the predefined methods. } } func layout(_ layout: PNLayout!, didFailLoading error: Error!) { loadingIndicator.stopAnimating() print("Error: \(error.localizedDescription)") } } extension MediumSampleSwiftViewController : PNLayoutTrackDelegate { func layoutTrackImpression(_ layout: PNLayout!) { print("Layout impression tracked") } func layoutTrackClick(_ layout: PNLayout!) { print("Layout click tracked") } }
mit
7d5a362184689d2ac8bb0714c6a24112
27.106667
112
0.661765
4.96
false
false
false
false
Candyroot/DesignPattern
adapter/adapter/HomeTheaterFacade.swift
1
1370
// // HomeTheaterFacade.swift // adapter // // Created by Bing Liu on 11/20/14. // Copyright (c) 2014 UnixOSS. All rights reserved. // import Foundation class HomeTheaterFacade { let amp: Amplifier let tuner: Tuner let dvd: DvdPlayer let cd: CdPlayer let projector: Projector let lights: TheaterLights let screen: Screen let popper: PopcornPopper init(amp: Amplifier, tuner: Tuner, dvd: DvdPlayer, cd: CdPlayer, projector: Projector, screen: Screen, lights: TheaterLights, popper: PopcornPopper) { self.amp = amp self.tuner = tuner self.dvd = dvd self.cd = cd self.projector = projector self.lights = lights self.screen = screen self.popper = popper } func watchMovie(movie: String) { println("Get ready to watch a movie...") popper.on() popper.pop() lights.dim(10) screen.down() projector.on() projector.wideScreenMode() amp.on() amp.setDvd(dvd) amp.setVolume(5) dvd.on() dvd.play(movie) } func endMovie() { println("Shutting movie theater down...") popper.off() lights.on() screen.up() projector.off() amp.off() dvd.stop() dvd.eject() dvd.off() } }
apache-2.0
8977ab1cb52fa78f8bb4a7f55e33774c
21.833333
154
0.563504
3.672922
false
false
false
false
shu223/Pulsator
Example/PulsatorDemo/ViewController.swift
1
3276
// // ViewController.swift // Pulsator // // Created by Shuichi Tsutsumi on 4/9/16. // Copyright © 2016 Shuichi Tsutsumi. All rights reserved. // import UIKit let kMaxRadius: CGFloat = 200 let kMaxDuration: TimeInterval = 10 class ViewController: UIViewController { @IBOutlet weak var sourceView: UIImageView! @IBOutlet weak var countSlider: UISlider! @IBOutlet weak var radiusSlider: UISlider! @IBOutlet weak var durationSlider: UISlider! @IBOutlet weak var rSlider: UISlider! @IBOutlet weak var gSlider: UISlider! @IBOutlet weak var bSlider: UISlider! @IBOutlet weak var aSlider: UISlider! @IBOutlet weak var countLabel: UILabel! @IBOutlet weak var radiusLabel: UILabel! @IBOutlet weak var durationLabel: UILabel! @IBOutlet weak var rLabel: UILabel! @IBOutlet weak var gLabel: UILabel! @IBOutlet weak var bLabel: UILabel! @IBOutlet weak var aLabel: UILabel! let pulsator = Pulsator() override func viewDidLoad() { super.viewDidLoad() sourceView.layer.superlayer?.insertSublayer(pulsator, below: sourceView.layer) setupInitialValues() pulsator.start() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() view.layer.layoutIfNeeded() pulsator.position = sourceView.layer.position } private func setupInitialValues() { countSlider.value = 5 countChanged(sender: nil) radiusSlider.value = 0.7 radiusChanged(sender: nil) durationSlider.value = 0.5 durationChanged(sender: nil) rSlider.value = 0 gSlider.value = 0.455 bSlider.value = 0.756 aSlider.value = 1 colorChanged(sender: nil) } // MARK: - Actions @IBAction func countChanged(sender: UISlider?) { //you can specify the number of pulse by the property "numPulse" pulsator.numPulse = Int(countSlider.value) countLabel.text = "\(pulsator.numPulse)" } @IBAction func radiusChanged(sender: UISlider?) { pulsator.radius = CGFloat(radiusSlider.value) * kMaxRadius radiusLabel.text = String(format: "%.0f", pulsator.radius) } @IBAction func durationChanged(sender: UISlider?) { pulsator.animationDuration = Double(durationSlider.value) * kMaxDuration durationLabel.text = String(format: "%.1f", pulsator.animationDuration) } @IBAction func colorChanged(sender: UISlider?) { pulsator.backgroundColor = UIColor( red: CGFloat(rSlider.value), green: CGFloat(gSlider.value), blue: CGFloat(bSlider.value), alpha: CGFloat(aSlider.value)).cgColor rLabel.text = String(format: "%.2f", rSlider.value) gLabel.text = String(format: "%.2f", gSlider.value) bLabel.text = String(format: "%.2f", bSlider.value) aLabel.text = String(format: "%.2f", aSlider.value) } @IBAction func switchChanged(sender: UISwitch) { if sender.isOn { pulsator.start() } else { pulsator.stop() } } }
mit
04dfd820f30e8ce200f275f805872d7f
29.324074
86
0.638473
4.332011
false
false
false
false
vadymmarkov/Faker
Sources/Fakery/Data/Parser.swift
3
3828
import Foundation public final class Parser { public var locale: String { didSet { if locale != oldValue { loadData(forLocale: locale) } } } private var data = [String: Any]() let provider: Provider // MARK: - Initialization public init(locale: String = Config.defaultLocale) { self.locale = locale provider = Provider() loadData(forLocale: locale) if locale != Config.defaultLocale { loadData(forLocale: Config.defaultLocale) } } // MARK: - Parsing public func fetch(_ key: String) -> String { var parsed = "" guard let keyData = fetchRaw(key) else { return parsed } let subject = getSubject(key) if let value = keyData as? String { parsed = value } else if let array = keyData as? [String], let item = array.random() { parsed = item } if parsed.range(of: "#{") != nil { parsed = parse(parsed, forSubject: subject) } return parsed } public func fetchRaw(_ key: String) -> Any? { let result = fetchRaw(key, forLocale: locale) guard locale != Config.defaultLocale else { return result } return result ?? fetchRaw(key, forLocale: Config.defaultLocale) } func parse(_ template: String, forSubject subject: String) -> String { var text = "" let string = NSString(string: template) var regex: NSRegularExpression do { try regex = NSRegularExpression(pattern: "(\\(?)#\\{([A-Za-z]+\\.)?([^\\}]+)\\}([^#]+)?", options: .caseInsensitive) let matches = regex.matches(in: template, options: .reportCompletion, range: NSRange(location: 0, length: string.length)) guard !matches.isEmpty else { return template } for match in matches { if match.numberOfRanges < 4 { continue } let prefixRange = match.range(at: 1) let subjectRange = match.range(at: 2) let methodRange = match.range(at: 3) let otherRange = match.range(at: 4) if prefixRange.length > 0 { text += string.substring(with: prefixRange) } var subjectWithDot = subject + "." if subjectRange.length > 0 { subjectWithDot = string.substring(with: subjectRange) } if methodRange.length > 0 { let key = subjectWithDot.lowercased() + string.substring(with: methodRange) text += fetch(key) } if otherRange.length > 0 { text += string.substring(with: otherRange) } } } catch {} return text } private func fetchRaw(_ key: String, forLocale locale: String) -> Any? { let parts = key.components(separatedBy: ".") guard let localeData = data[locale] as? [String: Any], var parsed = localeData["faker"] as? [String: Any], !parts.isEmpty else { return nil } var result: Any? for part in parts { guard let parsedPart = parsed[part] as? [String: Any] else { result = parsed[part] continue } parsed = parsedPart result = parsedPart } return result } private func getSubject(_ key: String) -> String { var subject: String = "" let parts = key.components(separatedBy: ".") if !parts.isEmpty { subject = parts[0] } return subject } // MARK: - Data loading private func loadData(forLocale locale: String) { guard let localeData = provider.dataForLocale(locale), let parsedData = try? JSONSerialization.jsonObject(with: localeData, options: .allowFragments), let json = parsedData as? [String: Any], let localeJson = json[locale] else { print("JSON file for '\(locale)' locale was not found.") return } data[locale] = localeJson } }
mit
4d46829a724d977efc20d5cc2b99a711
23.227848
101
0.592215
4.262806
false
false
false
false
PopcornTimeTV/PopcornTimeTV
PopcornTime/Extensions/AVMetadataItem+Extension.swift
1
426
import Foundation import AVFoundation.AVMetadataItem extension AVMetadataItem { static func `init`<K: NSCopying & NSObjectProtocol, V: NSCopying & NSObjectProtocol>(key: K, value: V) -> AVMetadataItem { let item = AVMutableMetadataItem() item.key = key item.locale = .current item.keySpace = AVMetadataKeySpace.common item.value = value return item } }
gpl-3.0
21ab74199649a3759bc66b15e3d19dfb
24.058824
126
0.647887
4.733333
false
false
false
false
dfortuna/theCraic3
theCraic3/Main/New Event/NewEventButtonsTableViewCell.swift
1
2043
// // NewEventButtonsTableViewCell.swift // theCraic3 // // Created by Denis Fortuna on 13/5/18. // Copyright © 2018 Denis. All rights reserved. // import UIKit protocol ButtonsProtocol: class { func CreateButton(sender: NewEventButtonsTableViewCell) func deleteButton(sender: NewEventButtonsTableViewCell) func updateButton(sender: NewEventButtonsTableViewCell) } class NewEventButtonsTableViewCell: UITableViewCell { weak var delegate: ButtonsProtocol? @IBOutlet weak var updateButtonOutlet: UIButton! @IBOutlet weak var createButtonOutlet: UIButton! @IBOutlet weak var deleteButtonOutlet: UIButton! @objc func createButton(_ sender: UIButton) { print("create") delegate?.CreateButton(sender: self) } @objc func deleteButton(_ sender: UIButton) { print("delete") delegate?.deleteButton(sender: self) } @objc func updateButton(_ sender: UIButton) { print("update") delegate?.updateButton(sender: self) } func formatUI(eventStatus: EventStatus) { deleteButtonOutlet.addTarget(self, action: #selector(deleteButton), for: UIControlEvents.touchUpInside) createButtonOutlet.addTarget(self, action: #selector(createButton), for: UIControlEvents.touchUpInside) updateButtonOutlet.addTarget(self, action: #selector(updateButton), for: UIControlEvents.touchUpInside) if eventStatus == .editingEvent { updateButtonOutlet.isEnabled = true updateButtonOutlet.alpha = 1 deleteButtonOutlet.isEnabled = true deleteButtonOutlet.alpha = 1 createButtonOutlet.isEnabled = false createButtonOutlet.alpha = 0 } else { updateButtonOutlet.isEnabled = false updateButtonOutlet.alpha = 0 deleteButtonOutlet.isEnabled = false deleteButtonOutlet.alpha = 0 createButtonOutlet.isEnabled = true createButtonOutlet.alpha = 1 } } }
apache-2.0
52bba0636685d157b88d0f5ed29d68a3
33.033333
111
0.675808
5.054455
false
false
false
false
TheInfiniteKind/duckduckgo-iOS
Core/UIViewExtension.swift
1
2156
// // UIViewExtension.swift // DuckDuckGo // // Created by Mia Alexiou on 21/02/2017. // Copyright © 2017 DuckDuckGo. All rights reserved. // import Foundation extension UIView { public func addEqualSizeConstraints(subView: UIView) { addEqualWidthConstraint(subView: subView) addEqualHeightConstraint(subView: subView) } public func addEqualHeightConstraint(subView: UIView) { addConstraint(NSLayoutConstraint( item: subView, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1, constant: 0)) } public func addEqualWidthConstraint(subView: UIView) { addConstraint(NSLayoutConstraint( item: subView, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: 0)) } public func round(corners: UIRectCorner, radius: CGFloat) { let cornerRadii = CGSize(width: radius, height: radius) let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: cornerRadii) let maskLayer = CAShapeLayer() maskLayer.path = path.cgPath layer.mask = maskLayer } public func blur(style: UIBlurEffectStyle) { let blurView = UIVisualEffectView() blurView.translatesAutoresizingMaskIntoConstraints = false backgroundColor = UIColor.clear insertSubview(blurView, at: 0) addEqualWidthConstraint(subView: blurView) addEqualHeightConstraint(subView: blurView) UIView.animate(withDuration: 0.5) { blurView.effect = UIBlurEffect(style: style) } } public func displayDropShadow() { layer.masksToBounds = false layer.shadowColor = UIColor.darkGray.cgColor layer.shadowOffset = CGSize(width: 0, height: 1.5) layer.shadowOpacity = 0.2 layer.shadowRadius = 1.5 layer.shadowPath = UIBezierPath(rect: bounds).cgPath } public func clearSubviews() { for view in subviews { view.removeFromSuperview() } } }
apache-2.0
298477d22f914a1d1a569f07082771c0
31.651515
106
0.645476
4.954023
false
false
false
false
MrCcccC/DouYuZB
DouYuZB/DouYuZB/Classes/Main/View/PageTitleView.swift
1
4128
// // PageTitleView.swift // DouYuZB // // Created by Chuchet on 2017/7/14. // Copyright © 2017年 mytrainning. All rights reserved. // import UIKit let SrollerLineH :CGFloat = 2 protocol PageTitleViewDelegate : class{ func pageTitleView(titleView:PageTitleView,selectedIndex:Int) } class PageTitleView: UIView { //定义属性 var titles:[String] var currentIndex:Int = 0 weak var delegate:PageTitleViewDelegate? lazy var scrollerView:UIScrollView = { let scrollerView = UIScrollView() scrollerView.showsHorizontalScrollIndicator = false scrollerView.scrollsToTop = false scrollerView.bounces = false return scrollerView }() lazy var titleLabels:[UILabel] = [UILabel]() lazy var scrollLine : UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orange return scrollLine }() //自定义构造函数 init(frame: CGRect,titles:[String]) { self.titles = titles super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //设置UI extension PageTitleView{ func setupUI(){ //设置UIScroll addSubview(scrollerView) scrollerView.frame = bounds //添加title对应的额label setupTitleLabels() //设置底线。滚动滑块 setupBottomLineAndScrollerLine() } func setupTitleLabels(){ //设置label的frame let labelW:CGFloat = frame.width/CGFloat(titles.count) let labelH:CGFloat = frame.height - SrollerLineH let labelY:CGFloat = 0 for (index,title) in titles.enumerated(){ //创建UIlabel let label = UILabel() //设置label的属性 label.text = title label.tag = index label.font = UIFont.systemFont(ofSize: 16) label.textColor = UIColor.darkGray label.textAlignment = .center let labelX:CGFloat = labelW * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) scrollerView.addSubview(label) titleLabels.append(label) //给label添加手势 label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(tapGes:))) label.addGestureRecognizer(tapGes) } } func setupBottomLineAndScrollerLine(){ //添加底线 let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGray let LineH:CGFloat = 0.6 bottomLine.frame = CGRect(x: 0, y: frame.height-LineH, width:frame.width, height:LineH ) addSubview(bottomLine) //添加scrollLine guard let firstLebel = titleLabels.first else { return } firstLebel.textColor = UIColor.orange scrollerView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLebel.frame.origin.x, y: frame.height-SrollerLineH, width: firstLebel.frame.width, height: SrollerLineH) } } //监听lebel的点击事件 extension PageTitleView{ @objc func titleLabelClick(tapGes:UITapGestureRecognizer){ //获取当前label的下标志 guard let currentLable = tapGes.view as? UILabel else{ return } //获取之前的label let oldLabel = titleLabels[currentIndex] //切换颜色 currentLable.textColor = UIColor.orange oldLabel.textColor = UIColor.darkGray currentIndex = currentLable.tag //滚动条位置发生改变 let scrollLineX = CGFloat(currentLable.tag) * scrollLine.frame.width UIView.animate(withDuration: 0.35) { self.scrollLine.frame.origin.x = scrollLineX } //通知代理 delegate?.pageTitleView(titleView: self, selectedIndex: currentLable.tag) } }
mit
65f7f1a87e055dff06c0b75b216b78ed
28.470149
146
0.617878
4.815854
false
false
false
false
kevinvanderlugt/Exercism-Solutions
swift/robot-name/RobotNameTest.swift
1
1092
import XCTest class RobotNameTest: XCTestCase { func robotNameIsCorrectlyFormatted(name: String) -> Bool { let robotNameRegex = NSRegularExpression(pattern: "\\A\\w{2}\\d{3}\\z", options: NSRegularExpressionOptions.CaseInsensitive, error: nil) let matches = robotNameRegex?.matchesInString(name, options: .WithoutAnchoringBounds, range: NSMakeRange(0, countElements(name))) return matches!.count > 0 } func testHasName() { let robot = Robot() XCTAssert(robotNameIsCorrectlyFormatted(robot.name)) } func testNameSticks() { let robot = Robot() let name = robot.name XCTAssertEqual(name, robot.name) } func testDifferentRobotsHaveDifferentNames() { let firstRobot = Robot() let secondRobot = Robot() XCTAssertNotEqual(firstRobot.name, secondRobot.name) } func testResetName() { var robot = Robot() let firstName = robot.name robot.resetName() let secondName = robot.name XCTAssertNotEqual(firstName, secondName) } }
mit
934aebeb4f26308ce0a8ae4a592f902c
28.513514
144
0.65293
4.569038
false
true
false
false
evnaz/Design-Patterns-In-Swift
source/behavioral/memento.swift
2
2045
/*: 💾 Memento ---------- The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation. ### Example */ typealias Memento = [String: String] /*: Originator */ protocol MementoConvertible { var memento: Memento { get } init?(memento: Memento) } struct GameState: MementoConvertible { private enum Keys { static let chapter = "com.valve.halflife.chapter" static let weapon = "com.valve.halflife.weapon" } var chapter: String var weapon: String init(chapter: String, weapon: String) { self.chapter = chapter self.weapon = weapon } init?(memento: Memento) { guard let mementoChapter = memento[Keys.chapter], let mementoWeapon = memento[Keys.weapon] else { return nil } chapter = mementoChapter weapon = mementoWeapon } var memento: Memento { return [ Keys.chapter: chapter, Keys.weapon: weapon ] } } /*: Caretaker */ enum CheckPoint { private static let defaults = UserDefaults.standard static func save(_ state: MementoConvertible, saveName: String) { defaults.set(state.memento, forKey: saveName) defaults.synchronize() } static func restore(saveName: String) -> Any? { return defaults.object(forKey: saveName) } } /*: ### Usage */ var gameState = GameState(chapter: "Black Mesa Inbound", weapon: "Crowbar") gameState.chapter = "Anomalous Materials" gameState.weapon = "Glock 17" CheckPoint.save(gameState, saveName: "gameState1") gameState.chapter = "Unforeseen Consequences" gameState.weapon = "MP5" CheckPoint.save(gameState, saveName: "gameState2") gameState.chapter = "Office Complex" gameState.weapon = "Crossbow" CheckPoint.save(gameState, saveName: "gameState3") if let memento = CheckPoint.restore(saveName: "gameState1") as? Memento { let finalState = GameState(memento: memento) dump(finalState) }
gpl-3.0
8429f3f9d5e18d58184cc751528f6b77
23.60241
184
0.676298
3.889524
false
false
false
false
mzaks/FlatBuffersSwiftPerformanceTest
FBTest/bench_decode_eager.swift
1
2595
// // bench_createDefinitions.swift // FBTest // // Created by Maxim Zaks on 27.09.16. // Copyright © 2016 maxim.zaks. All rights reserved. // import Foundation public extension FooBar { private static func create(reader : FBReader, objectOffset : Offset?) -> FooBar? { guard let objectOffset = objectOffset else { return nil } if let cache = reader.cache, let o = cache.objectPool[objectOffset] { return o as? FooBar } let _result = FooBar() _result.sibling = reader.get(objectOffset, propertyIndex: 0) _result.name = reader.getStringBuffer(reader.getOffset(objectOffset, propertyIndex: 1))?§ _result.rating = reader.get(objectOffset, propertyIndex: 2, defaultValue: 0) _result.postfix = reader.get(objectOffset, propertyIndex: 3, defaultValue: 0) if let cache = reader.cache { cache.objectPool[objectOffset] = _result } return _result } } public extension FooBarContainer { private static func create(reader : FBReader, objectOffset : Offset?) -> FooBarContainer? { guard let objectOffset = objectOffset else { return nil } if let cache = reader.cache, let o = cache.objectPool[objectOffset] { return o as? FooBarContainer } let _result = FooBarContainer() let offset_list : Offset? = reader.getOffset(objectOffset, propertyIndex: 0) let length_list = reader.getVectorLength(offset_list) if(length_list > 0){ var index = 0 _result.list.reserveCapacity(length_list) while index < length_list { let element = FooBar.create(reader, objectOffset: reader.getVectorOffsetElement(offset_list, index: index)) _result.list.append(element) index += 1 } } _result.initialized = reader.get(objectOffset, propertyIndex: 1, defaultValue: false) _result.fruit = Enum(rawValue: reader.get(objectOffset, propertyIndex: 2, defaultValue: Enum.Apples.rawValue)) _result.location = reader.getStringBuffer(reader.getOffset(objectOffset, propertyIndex: 3))?§ if let cache = reader.cache { cache.objectPool[objectOffset] = _result } return _result } } public extension FooBarContainer { public static func fromReader(reader : FBReader) -> FooBarContainer? { let objectOffset = reader.rootObjectOffset return create(reader, objectOffset : objectOffset) } }
mit
8aaafc2e4ac1867b196fbe765d9b8510
37.117647
123
0.631173
4.579505
false
false
false
false
madhusamuel/PlacesExplorer
PlacesExplorer/Venues/ViewControllers/VenueListViewController.swift
1
9153
// // VenueListViewController.swift // PlacesExplorer // // Created by Madhu Samuel on 26/10/2015. // Copyright © 2015 Madhu. All rights reserved. // import UIKit import CoreLocation class VenueListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, CLLocationManagerDelegate { var locationManager: CLLocationManager? @IBOutlet weak var venuesTableView: UITableView! @IBOutlet weak var tableTopConstraint: NSLayoutConstraint! var refreshControl: UIRefreshControl! var venues: [Venue] = [] let venueDataService = VenueDataService() var isMainView = true var currentLocation: CLLocationCoordinate2D! var selectedVenueId: String? var selectedVenuesCategoryId: String? var selectedVenuesCategoryName: String? override func viewDidLoad() { super.viewDidLoad() if isMainView { self.title = "Locating You..." enableRefreshControl() findLocation() } else { //otherwise the top row is hidden behind the nav bar. tableTopConstraint.constant = 64 fetchVenues(currentLocation, categoryId: selectedVenuesCategoryId!, categoryName: selectedVenuesCategoryName!) } } //Ideally a refresh control uses a tableviewcontroller. Since we are using a uiviewcontroller, we create //a new tableviewcontroller just to use refreshcontrol. The below commented method also works, but there is a //slight "stutter". func enableRefreshControl() { let tableViewController = UITableViewController() tableViewController.tableView = venuesTableView refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: "refresh", forControlEvents: .ValueChanged) tableViewController.refreshControl = refreshControl } // For reference // func enableRefreshControl2() { // refreshControl = UIRefreshControl() // refreshControl.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged) // venuesTableView.addSubview(refreshControl) // } func refresh() { locationManager?.requestLocation() refreshControl.endRefreshing() } func findLocation() { if (locationManager == nil) { locationManager = CLLocationManager() } locationManager?.delegate = self locationManager?.desiredAccuracy = kCLLocationAccuracyBest locationManager?.distanceFilter = 100 // meteres locationManager?.requestWhenInUseAuthorization() ActivityManager.sharedManager().startActivityIndicator(view) locationManager?.requestLocation() } //MARK: locationManagerDelegate func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { print("Invoking didUpdateLocations") if (locations.count > 0) { print("Location -> \(locations[0])") self.currentLocation = locations[0].coordinate self.fetchVenues(locations[0].coordinate) } } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print("Location update FAILED") } //MARK: webservice access func fetchVenues(location: CLLocationCoordinate2D){ self.title = "Accessing Venues..." ActivityManager.sharedManager().startActivityIndicator(self.view) venueDataService.getNearByVenues(location, success: { (venues) -> () in print("Success \(venues.count)") dispatch_async(dispatch_get_main_queue(), { self.venues = self.sortVenues(venues) ActivityManager.sharedManager().stopActivityIndicator() self.venuesTableView.reloadData() self.title = "Nearby Venues" }) }, failure: { (error) -> () in print("Failure") }) } func fetchVenues(location: CLLocationCoordinate2D, categoryId: String, categoryName: String){ self.title = "Accessing Popular \(categoryName)s..." ActivityManager.sharedManager().startActivityIndicator(self.view) venueDataService.getNearByVenues(location, categoryId: categoryId, success: { (venues) -> () in print("Success \(venues.count)") dispatch_async(dispatch_get_main_queue(), { ActivityManager.sharedManager().stopActivityIndicator() self.venues = self.sortVenues(venues) self.venuesTableView.reloadData() self.title = "Popular \(categoryName)s" }) }, failure: { (error) -> () in print("Failure") self.title = "Couldn't Access Venues" }) } func fetchSimilarVenues(venueId: String){ print("Fetching similar venues...") ActivityManager.sharedManager().startActivityIndicator(self.view) venueDataService.getSimilarVenues(venueId, success: { (venues) -> () in print("Success \(venues.count)") dispatch_async(dispatch_get_main_queue(), { ActivityManager.sharedManager().stopActivityIndicator() self.venues = self.sortVenues(venues) self.venuesTableView.reloadData() }) }, failure: { (error) -> () in print("Failure") }) } func sortVenues(var venues: [Venue]) -> [Venue] { venues.sortInPlace{(venue1, venue2) -> Bool in guard let distance1 = venue1.venueLocation?.distance, let distance2 = venue2.venueLocation?.distance else { return false } return distance1 < distance2 } return venues } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return venues.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("venueTableViewCell") as! VenueListTableViewCell let venue = venues[indexPath.row] print("\(venue.name!)\n \(venue.venueLocation?.city) \(venue.venueLocation?.distance)") configureCell(cell, withVenue: venue) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if isMainView { let venue = venues[indexPath.row] print("Selected Venue \(venue.name) - \(venue.id)") let storyboard = UIStoryboard(name: "Main", bundle: nil) let newListViewController = storyboard.instantiateViewControllerWithIdentifier("VenueListViewController") as! VenueListViewController newListViewController.selectedVenueId = venue.id newListViewController.currentLocation = self.currentLocation newListViewController.isMainView = false if let categories = venue.categories { if categories.count > 0 { newListViewController.selectedVenuesCategoryId = categories[0].id newListViewController.selectedVenuesCategoryName = categories[0].name self.navigationController?.pushViewController(newListViewController, animated: true) } else { openAlertView("No Popular Venues found") } } else { openAlertView("No Popular Venues found") } } tableView.deselectRowAtIndexPath(indexPath, animated: true) } func openAlertView(message: String) { let alertViewController = UIAlertController(title: nil, message: message, preferredStyle: .Alert) alertViewController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(alertViewController, animated: true, completion: nil) } private func configureCell(cell: VenueListTableViewCell, withVenue venue: Venue) { cell.venueTitleLabel.text = venue.name if let categories = venue.categories { if categories.count > 0 { cell.venueTypeLabel.text = categories[0].name } } if let address = venue.venueLocation?.address { cell.venueAddressLabel.text = address } else { cell.venueAddressLabel.text = "-" } if let city = venue.venueLocation?.city { cell.venuePlaceLabel.text = city } else { cell.venuePlaceLabel.text = "-" } if let distance = venue.venueLocation!.distance { cell.venueDistanceLabel.text = String(distance) + " meters" } else { cell.venueDistanceLabel.text = "-" } } }
epl-1.0
333cf646113f66eff78caf06bef6831e
37.944681
145
0.624017
5.539952
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/Home/Cells/Polls/HomePollsCellItem.swift
1
1692
// // HomePollsCellItem.swift // PennMobile // // Created by Lucy Yuewei Yuan on 9/19/20. // Copyright © 2020 PennLabs. All rights reserved. // import Foundation import SwiftyJSON final class HomePollsCellItem: HomeCellItem { static func getHomeCellItem(_ completion: @escaping (([HomeCellItem]) -> Void)) { let formatter = DateFormatter() formatter.dateFormat = "yyyy/MM/dd HH:mm" let ddl = formatter.date(from: "2021/12/20 11:59") let pollOption1 = PollOption(id: 1, optionText: "Wharton Students", votes: 20, votesByYear: nil, votesBySchool: nil) let pollOption2 = PollOption(id: 2, optionText: "M&T Students", votes: 20, votesByYear: nil, votesBySchool: nil) let pollOption3 = PollOption(id: 3, optionText: "CIS Majors who are trying to transfer into Wharton", votes: 40, votesByYear: nil, votesBySchool: nil) let pollOption4 = PollOption(id: 4, optionText: "Armaan going to a Goldman info session", votes: 300, votesByYear: nil, votesBySchool: nil) let dummyQuestion = PollQuestion(title: "Who is more of a snake?", source: "The Daily Pennsylvanian", ddl: ddl!, options: [pollOption1, pollOption2, pollOption3, pollOption4], totalVoteCount: 380, optionChosenId: nil) completion([HomePollsCellItem(pollQuestion: dummyQuestion)]) } static var associatedCell: ModularTableViewCell.Type { return HomePollsCell.self } var pollQuestion: PollQuestion init(pollQuestion: PollQuestion) { self.pollQuestion = pollQuestion } func equals(item: ModularTableViewItem) -> Bool { return true } static var jsonKey: String { return "polls" } }
mit
17a6034fc059fe36526b7b35afc2360b
38.325581
225
0.69249
3.684096
false
false
false
false
billdonner/sheetcheats9
sc9/RecentsViewController.swift
1
4508
// // Recents.swift // // Created by william donner on 9/25/15. // import UIKit final class RecentsCell:UITableViewCell { } final class RecentsTableView: UITableView { var parentVC:RecentsViewController! var recents: RecentList! func setup(_ vc:RecentsViewController,flavor:SortFlavors = .ascendingAlpha) { self.parentVC = vc self.register(RecentsCell.self, forCellReuseIdentifier: "RecentsTableCellID") self.dataSource = self self.delegate = self // sort according to state of UISegmentedControl self.recents = Recents.shared.gRecents switch flavor { case .ascendingTime: self.recents.sort { $0.time < $1.time } case .descendingTime: self.recents.sort { $0.time > $1.time } case .ascendingAlpha: self.recents.sort { $0.title < $1.title } case .descendingAlpha: self.recents.sort { $0.title > $1.title } }// exhaustive } } extension RecentsTableView : UITableViewDelegate {// func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.parentVC.showDoc(self.parentVC,named: self.recents[(indexPath as NSIndexPath).item].title) } } extension RecentsTableView :UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.recents.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "RecentsTableCellID", for: indexPath) as! RecentsCell cell.configureCell(self.recents[(indexPath as NSIndexPath).item].title) return cell } } final class RecentsMainView: UIView { var parentVC:RecentsViewController! @IBOutlet weak var tableView: RecentsTableView! func setup(_ vc:RecentsViewController, idx n:Int ) { // value of segControl determines sorting self.parentVC = vc var sf: SortFlavors // let n = segControl.selectedSegmentIndex switch n { case 2: sf = .descendingTime case 0: sf = .ascendingAlpha case 1: sf = .descendingAlpha default: sf = .ascendingTime // probably not in play with current UI } self.tableView.setup(vc,flavor: sf) self.tableView.reloadData() } } final class RecentsViewController: UIViewController,ModelData { // modal //var xdelegate:RecentsViewDelegate? @IBAction func tapped(_ sender: Any) { print ("tappingForExport") performSegue(withIdentifier: "Esportid", sender: self) } @IBOutlet weak var recentsMainView : RecentsMainView! deinit { self.cleanupFontSizeAware(self) } // the view is completely redone everytime we re-appear override var prefersStatusBarHidden: Bool { get { return true } } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = Col.r(.tableBackground) self.setupFontSizeAware(self) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.recentsMainView.setup(self,idx:2) } } extension RecentsViewController : FontSizeAware { func refreshFontSizeAware(_ vc:RecentsViewController) { vc.recentsMainView.tableView.reloadData() } } extension RecentsViewController : SegueHelpers { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { self.prepForSegue(segue , sender: sender) } } extension RecentsViewController: HistoryStyleChosenProtocol { func passHistoryControllerChange( idx:Int, to:UIViewController) { // announces the pascontrol ack to us print("RecentsViewController passHistoryControllerChange \(idx)") refreshLayout() } } extension RecentsViewController: OrderingStyleChosenProtocol { func passOrdering( idx:Int, to:UIViewController) { //print("RecentsViewController passOrdering \(idx)") self.recentsMainView.setup(self,idx:idx) //refreshLayout() } func refreshLayout(){ self.recentsMainView.tableView.reloadData() } }
apache-2.0
9c9d49dd9d4e7648b74b81fe39da798b
28.657895
118
0.64685
4.595311
false
false
false
false
PekanMmd/Pokemon-XD-Code
GoDToolOSX/Views/PopUp Buttons/GoDGenderPopUpButton.swift
1
614
// // GoDGenderPopUpButton.swift // GoD Tool // // Created by StarsMmd on 06/09/2017. // // import Cocoa class GoDGenderPopUpButton: GoDPopUpButton { var selectedValue : XGGenders { return XGGenders(rawValue: self.indexOfSelectedItem) ?? .random } func selectGender(gender: XGGenders) { self.selectItem(withTitle: gender.string) } override func setUpItems() { var values = [String]() var genders : [XGGenders] = [.male,.female,.genderless] if game == .Colosseum { genders += [.random] } for g in genders { values.append(g.string) } self.setTitles(values: values) } }
gpl-2.0
234cd26c4eb03d2e19955600fcb9752e
17.058824
65
0.672638
3.054726
false
false
false
false
ExTEnS10N/CommonViewController
BINavigationController.swift
1
757
// // TENavigationController.swift // // Created by macsjh on 16/3/6. // Copyright © 2016年 TurboExtension. All rights reserved. // import UIKit class TENavigationController: UINavigationController, UIGestureRecognizerDelegate { private var _popGestureIsEnabled = false override func viewDidLoad() { super.viewDidLoad() enablePopGesture(true) } func enablePopGesture(enable:Bool) { _popGestureIsEnabled = enable self.interactivePopGestureRecognizer?.delegate = self } func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { guard gestureRecognizer == self.interactivePopGestureRecognizer else {return true} if self.viewControllers.count > 1{ return _popGestureIsEnabled } return false } }
gpl-3.0
63c070267c431e1580754cb9c933671d
23.322581
84
0.770557
4.165746
false
false
false
false
xivol/Swift-CS333
playgrounds/swift/SwiftBasics.playground/Pages/Optionals.xcplaygroundpage/Contents.swift
2
1647
/*: ## Optionals [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next) **** */ import Foundation var helloString: String? = nil type(of: helloString) helloString = "Hello, Optional!" //: ### Optional Initialisation //: - `nil` //: - Wrapped value //: //: Values can be wrapped into an opional type var optInt = Int?(4) // Int?(4) // optInt = nil if optInt == nil { "empty" } else { optInt } //: Some methods return optionals in case of a failure: let stringPi = "3.1415926535897932" let pi = Double(stringPi) type(of: pi) //: ### Conditional Unwrapping let conditionalThree = pi?.rounded() type(of: conditionalThree) helloString = nil let conditionalLowerString = helloString?.lowercased() type(of: conditionalLowerString) //: ### Optional Binding if let boundPi = Double(stringPi) { "rounded pi is \(boundPi.rounded())" } if let str = helloString { str.lowercased() } else { "empty string" } //: Guarded optional guard let guardedPi = Double(stringPi) else { fatalError("pi is nil") } type(of: guardedPi) //: ### Forced Unwrapping let forcedThree = pi!.rounded() type(of: forcedThree) //let forcedLowerString = helloString!.lowercased() //type(of: forcedLowerString) //: Forcedly Unwrapped Optional var forcedPi: Double! = nil forcedPi = Double(stringPi) let threeFromForcedPi = forcedPi.rounded() //: Optional Chaining helloString = "Hello, Playground" let chainedIndexOfSubstr = helloString?.range(of: "Hello")?.lowerBound let chainedBase64 = helloString?.data(using: .utf8)?.base64EncodedString() //: [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next)
mit
e2c0d9833af7c70cf035789d12c8f818
22.471429
80
0.700548
3.510684
false
false
false
false
timfuqua/Bourgeoisie
Bourgeoisie/Bourgeoisie/View Controller/GameplayViewController.swift
1
35999
// // GameplayViewController.swift // Bourgeoisie // // Created by Tim Fuqua on 11/24/15. // Copyright © 2015 FuquaProductions. All rights reserved. // import UIKit // MARK: GameplayViewController: UIViewController /** */ class GameplayViewController: UIViewController { // MARK: class vars /// The width of a card in the proletariat hand static let proletariatCardImageWidth: CGFloat = 96.0 /// The height of a card in the proletariat hand static let proletariatCardImageHeight: CGFloat = 128.0 /// The width of a card in the royals pool static let royalsPoolCardImageWidth: CGFloat = 96.0 /// The height of a card in the royals pool static let royalsPoolCardImageHeight: CGFloat = 128.0 /// The width of a common card static let commonCardImageWidth: CGFloat = 96.0 /// The height of a common card static let commonCardImageHeight: CGFloat = 128.0 /// The width of a revealed opponent mob card static let opponentMobCardImageWidth: CGFloat = 72.0 /// The height of a revealed opponent mob card static let opponentMobCardImageHeight: CGFloat = 96.0 /// The highlight color of the first mob static let firstMobHighlightColor: UIColor = UIColor.redColor() /// The highlight color of the second mob static let secondMobHighlightColor: UIColor = UIColor.blueColor() // MARK: private lets // MARK: private vars (computed) // MARK: private vars // MARK: private(set) vars // MARK: lets // MARK: vars (computed) // MARK: vars /// The number of opponents that was selected from the Title Screen var numOpponentsSelected: Int! /// The gameplay mode selected from the Title Screen var gameMode: GameplayMode! /// The entity that controls a full game of Bourgeoisie var bourgGameManager: BourgGameManager! // MARK: @IBOutlets @IBOutlet weak var paddingView: UIView! @IBOutlet weak var roundNumView: UIView! @IBOutlet weak var roundNumLabel: UILabel! @IBOutlet weak var roundStageInfoView: UIView! @IBOutlet weak var roundStageInfoLabel: UILabel! @IBOutlet weak var roundStageButtonView: UIView! @IBOutlet weak var roundStageButton: UIButton! @IBOutlet weak var pauseView: UIView! @IBOutlet weak var pauseButton: UIButton! @IBOutlet weak var opponentMobView: UIView! @IBOutlet weak var firstOppMobView: UIView! @IBOutlet weak var firstOppNameView: UIView! @IBOutlet weak var firstOppNameLabel: UILabel! @IBOutlet weak var firstOppRevealedMobView: UIView! @IBOutlet weak var firstOppRevealedMobCollectionView: UICollectionView! @IBOutlet weak var firstOppCommonAndScoreView: UIView! @IBOutlet weak var firstOppCommonCardView: UIView! @IBOutlet weak var firstOppCommonCardImage: UIImageView! @IBOutlet weak var firstOppScoreView: UIView! @IBOutlet weak var firstOppScoreValLabel: UILabel! @IBOutlet weak var firstOppScoreTextLabel: UILabel! @IBOutlet weak var firstOppSeparatorView: UIView! @IBOutlet weak var secondOppMobView: UIView! @IBOutlet weak var secondOppNameView: UIView! @IBOutlet weak var secondOppNameLabel: UILabel! @IBOutlet weak var secondOppRevealedMobView: UIView! @IBOutlet weak var secondOppRevealedMobCollectionView: UICollectionView! @IBOutlet weak var secondOppCommonAndScoreView: UIView! @IBOutlet weak var secondOppCommonCardView: UIView! @IBOutlet weak var secondOppCommonCardImage: UIImageView! @IBOutlet weak var secondOppScoreView: UIView! @IBOutlet weak var secondOppScoreValLabel: UILabel! @IBOutlet weak var secondOppScoreTextLabel: UILabel! @IBOutlet weak var secondOppSeparatorView: UIView! @IBOutlet weak var thirdOppMobView: UIView! @IBOutlet weak var thirdOppNameView: UIView! @IBOutlet weak var thirdOppNameLabel: UILabel! @IBOutlet weak var thirdOppRevealedMobView: UIView! @IBOutlet weak var thirdOppRevealedMobCollectionView: UICollectionView! @IBOutlet weak var thirdOppCommonAndScoreView: UIView! @IBOutlet weak var thirdOppCommonCardView: UIView! @IBOutlet weak var thirdOppCommonCardImage: UIImageView! @IBOutlet weak var thirdOppScoreView: UIView! @IBOutlet weak var thirdOppScoreValLabel: UILabel! @IBOutlet weak var thirdOppScoreTextLabel: UILabel! @IBOutlet weak var royalsView: UIView! @IBOutlet weak var royalsCollectionView: UICollectionView! @IBOutlet weak var playerView: UIView! @IBOutlet weak var proletariatView: UIView! @IBOutlet weak var playerCommonCardView: UIView! @IBOutlet weak var playerScoreView: UIView! @IBOutlet weak var playerMobStatisticsView: UIView! @IBOutlet weak var flushRankingLabel: UILabel! @IBOutlet weak var straightRankingLabel: UILabel! @IBOutlet weak var bookRankingLabel: UILabel! @IBOutlet weak var proletariatCollectionView: UICollectionView! @IBOutlet weak var playerCommonCardImage: UIImageView! @IBOutlet weak var scoreTextLabel: UILabel! @IBOutlet weak var scoreValLabel: UILabel! // MARK: init // MARK: vc lifecycle override func viewDidLoad() { super.viewDidLoad() clearViewBackgrounds() initializeBourgGameData() setUpGame() } // MARK: @IBActions @IBAction func roundStageButtonPressed(sender: UIButton) { print("") print("GameplayViewController::roundStageButtonPressed:") switch BourgGameState(rawValue: bourgGameManager.roundStageStateIndex)! { case BourgGameState.BeforeRound: fallthrough case BourgGameState.SubmitFirstMob: fallthrough case BourgGameState.SubmitSecondMob: fallthrough case BourgGameState.DeterminingJacksWinner: fallthrough case BourgGameState.DeterminingQueensWinner: fallthrough case BourgGameState.DeterminingKingsWinner: bourgGameManager.advanceRoundStageProcess() case BourgGameState.EndOfRound: if bourgGameManager.roundNum == BourgGameManager.maxRounds { performSegueWithIdentifier("unwindToTitleSegue", sender: self) } else { bourgGameManager.advanceRoundProcess() } } } @IBAction func pauseButtonPressed(sender: UIButton) { print("") print("GameplayViewController::pauseButtonPressed:") performSegueWithIdentifier("unwindToTitleSegue", sender: self) } // MARK: public funcs // MARK: private funcs /** Initializes the `BourgGameManager`, which in turn initializes the `BourgGameData` as well. */ private func initializeBourgGameData() { bourgGameManager = BourgGameManager(gameMode: gameMode, numOpponents: numOpponentsSelected) bourgGameManager.bourgGameManagerDelegate = self bourgGameManager.bourgGameData.bourgGameDataDelegate = self } /** Updates the text of the `roundNumLabel` */ private func updateRoundLabelText() { roundNumLabel.text = "Round \(bourgGameManager.roundNum) of \(BourgGameManager.maxRounds)" } /** Updates the text of the `roundStageInfoLabel` */ private func updateRoundStageInfoLabelText() { roundStageInfoLabel.text = BourgGameState.allBourgGameStates[bourgGameManager.roundStageStateIndex].description() } /** Updates the title of the `roundStageButton` */ private func updateRoundStageButtonTitle() { switch BourgGameState(rawValue: bourgGameManager.roundStageStateIndex)! { case BourgGameState.BeforeRound: roundStageButton.setTitle("Start Round", forState: UIControlState.Normal) case BourgGameState.SubmitFirstMob: roundStageButton.setTitle("Submit", forState: UIControlState.Normal) case BourgGameState.SubmitSecondMob: roundStageButton.setTitle("Submit", forState: UIControlState.Normal) case BourgGameState.DeterminingJacksWinner: roundStageButton.setTitle("Next", forState: UIControlState.Normal) case BourgGameState.DeterminingQueensWinner: roundStageButton.setTitle("Next", forState: UIControlState.Normal) case BourgGameState.DeterminingKingsWinner: roundStageButton.setTitle("Next", forState: UIControlState.Normal) case BourgGameState.EndOfRound: if bourgGameManager.roundNum == BourgGameManager.maxRounds { roundStageButton.setTitle("End Game", forState: UIControlState.Normal) } else { roundStageButton.setTitle("Next Round", forState: UIControlState.Normal) } } } /** Updates the title of the `roundStageButton` */ private func updateCommonCardVisibility() { func showCommonCards() { switch bourgGameManager.numOpponents { case 1: firstOppCommonCardImage.image = UIImage(named: "\(bourgGameManager.bourgGameData.opponents[0].commonCard!.rank.shorthand)_\(bourgGameManager.bourgGameData.opponents[0].commonCard!.suit.shorthand)") case 2: firstOppCommonCardImage.image = UIImage(named: "\(bourgGameManager.bourgGameData.opponents[0].commonCard!.rank.shorthand)_\(bourgGameManager.bourgGameData.opponents[0].commonCard!.suit.shorthand)") secondOppCommonCardImage.image = UIImage(named: "\(bourgGameManager.bourgGameData.opponents[1].commonCard!.rank.shorthand)_\(bourgGameManager.bourgGameData.opponents[1].commonCard!.suit.shorthand)") case 3: firstOppCommonCardImage.image = UIImage(named: "\(bourgGameManager.bourgGameData.opponents[0].commonCard!.rank.shorthand)_\(bourgGameManager.bourgGameData.opponents[0].commonCard!.suit.shorthand)") secondOppCommonCardImage.image = UIImage(named: "\(bourgGameManager.bourgGameData.opponents[1].commonCard!.rank.shorthand)_\(bourgGameManager.bourgGameData.opponents[1].commonCard!.suit.shorthand)") thirdOppCommonCardImage.image = UIImage(named: "\(bourgGameManager.bourgGameData.opponents[2].commonCard!.rank.shorthand)_\(bourgGameManager.bourgGameData.opponents[2].commonCard!.suit.shorthand)") default: fatalError("Shouldn't be more than 3 opponents") } } func hideCommonCards() { switch bourgGameManager.numOpponents { case 1: firstOppCommonCardImage.image = UIImage(named: "CardBack_Opp") case 2: firstOppCommonCardImage.image = UIImage(named: "CardBack_Opp") secondOppCommonCardImage.image = UIImage(named: "CardBack_Opp") case 3: firstOppCommonCardImage.image = UIImage(named: "CardBack_Opp") secondOppCommonCardImage.image = UIImage(named: "CardBack_Opp") thirdOppCommonCardImage.image = UIImage(named: "CardBack_Opp") default: fatalError("Shouldn't be more than 3 opponents") } } switch BourgGameState(rawValue: bourgGameManager.roundStageStateIndex)! { case BourgGameState.BeforeRound: fallthrough case BourgGameState.SubmitFirstMob: fallthrough case BourgGameState.SubmitSecondMob: hideCommonCards() case BourgGameState.DeterminingJacksWinner: fallthrough case BourgGameState.DeterminingQueensWinner: fallthrough case BourgGameState.DeterminingKingsWinner: showCommonCards() case BourgGameState.EndOfRound: hideCommonCards() playerCommonCardImage.image = UIImage(named: "CardBack_Player") } } /** */ private func updateMobRankingDebugText() { if !bourgGameManager.roundStageStateIndex.isBetweenInclusive(lower: BourgGameState.SubmitFirstMob.rawValue, upper: BourgGameState.SubmitSecondMob.rawValue) { flushRankingLabel.text = "" straightRankingLabel.text = "" bookRankingLabel.text = "" return } precondition(bourgGameManager.roundStageStateIndex.isBetweenInclusive(lower: BourgGameState.SubmitFirstMob.rawValue, upper: BourgGameState.SubmitSecondMob.rawValue)) precondition(bourgGameManager.bourgGameData.player.nextNeededMob != nil) let flushRanking: CGFloat = BourgAlgorithms.isAFlush(bourgGameManager.bourgGameData.player.nextNeededMob!.arrayCards)?.rankPercentile() ?? 0.0 let straightRanking: CGFloat = BourgAlgorithms.isAStraight(bourgGameManager.bourgGameData.player.nextNeededMob!.arrayCards)?.rankPercentile() ?? 0.0 let bookRanking: CGFloat = BourgAlgorithms.isABook(bourgGameManager.bourgGameData.player.nextNeededMob!.arrayCards)?.rankPercentile() ?? 0.0 // let flushRankingText: String = "Top " + String(format: "%.1f", flushRanking) + "% flush" // let straightRankingText: String = "Top " + String(format: "%.1f", straightRanking) + "% straight" // let bookRankingText: String = "Top " + String(format: "%.1f", bookRanking) + "% book" let flushRankingWithCommon: CGFloat = BourgAlgorithms.isAFlush(bourgGameManager.bourgGameData.player.nextNeededMob!.arrayCards + [bourgGameManager.bourgGameData.player.commonCard!])?.rankPercentile() ?? 0.0 let straightRankingWithCommon: CGFloat = BourgAlgorithms.isAStraight(bourgGameManager.bourgGameData.player.nextNeededMob!.arrayCards + [bourgGameManager.bourgGameData.player.commonCard!])?.rankPercentile() ?? 0.0 let bookRankingWithCommon: CGFloat = BourgAlgorithms.isABook(bourgGameManager.bourgGameData.player.nextNeededMob!.arrayCards + [bourgGameManager.bourgGameData.player.commonCard!])?.rankPercentile() ?? 0.0 let flushRankingTextWithCommon: String = "Top " + String(format: "%.1f", flushRanking) + "% flush (" + String(format: "%.1f", flushRankingWithCommon) + "%)" let straightRankingTextWithCommon: String = "Top " + String(format: "%.1f", straightRanking) + "% straight (" + String(format: "%.1f", straightRankingWithCommon) + "%)" let bookRankingTextWithCommon: String = "Top " + String(format: "%.1f", bookRanking) + "% book (" + String(format: "%.1f", bookRankingWithCommon) + "%)" // print("\(flushRankingText); \(straightRankingText); \(bookRankingText)") print("\(flushRankingTextWithCommon); \(straightRankingTextWithCommon); \(bookRankingTextWithCommon)") // flushRankingLabel.text = flushRankingText // straightRankingLabel.text = straightRankingText // bookRankingLabel.text = bookRankingText flushRankingLabel.text = flushRankingTextWithCommon straightRankingLabel.text = straightRankingTextWithCommon bookRankingLabel.text = bookRankingTextWithCommon } /** Updates the collection views that show the opponent's submitted mobs when resolving who won each royal. */ private func updateOppRevealedMobCollectionViews() { firstOppRevealedMobCollectionView.reloadData() secondOppRevealedMobCollectionView.reloadData() thirdOppRevealedMobCollectionView.reloadData() } /** Clears the backgrounds of all the views */ private func clearViewBackgrounds() { roundNumView.backgroundColor = UIColor.clearColor() roundStageInfoView.backgroundColor = UIColor.clearColor() roundStageButtonView.backgroundColor = UIColor.clearColor() pauseView.backgroundColor = UIColor.clearColor() opponentMobView.backgroundColor = UIColor.clearColor() firstOppScoreView.backgroundColor = UIColor.clearColor() secondOppScoreView.backgroundColor = UIColor.clearColor() thirdOppScoreView.backgroundColor = UIColor.clearColor() royalsView.backgroundColor = UIColor.clearColor() playerView.backgroundColor = UIColor.clearColor() proletariatView.backgroundColor = UIColor.clearColor() playerCommonCardView.backgroundColor = UIColor.clearColor() playerScoreView.backgroundColor = UIColor.clearColor() proletariatCollectionView.backgroundColor = UIColor.clearColor() royalsCollectionView.backgroundColor = UIColor.clearColor() } /** Makes outlines for each of the opponent mob views */ private func setOppMobViewOutlines() { firstOppMobView.setOutline(2.0, borderColor: UIColor.darkGrayColor()) secondOppMobView.setOutline(2.0, borderColor: UIColor.darkGrayColor()) thirdOppMobView.setOutline(2.0, borderColor: UIColor.darkGrayColor()) } /** Sets up a new game for the number of opponents selected from the Title Screen */ private func setUpGame() { print("") print("Setting up a new game for \(bourgGameManager.numOpponents!) opponents") bourgGameManager.setUpGame() } private func showHideOpponents() { switch bourgGameManager.numOpponents { case 1: firstOppMobView.hidden = false firstOppSeparatorView.hidden = true secondOppMobView.hidden = true secondOppSeparatorView.hidden = true thirdOppMobView.hidden = true case 2: firstOppMobView.hidden = false firstOppSeparatorView.hidden = false secondOppMobView.hidden = false secondOppSeparatorView.hidden = true thirdOppMobView.hidden = true case 3: firstOppMobView.hidden = false firstOppSeparatorView.hidden = false secondOppMobView.hidden = false secondOppSeparatorView.hidden = false thirdOppMobView.hidden = false default: break } } } // MARK: GameplayViewController: UICollectionViewDataSource extension GameplayViewController: UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch collectionView { case proletariatCollectionView: return numberOfCardsForProletariatCollectionView() case royalsCollectionView: return bourgGameManager.bourgGameData.royalsPool?.numberOfCards ?? 0 case firstOppRevealedMobCollectionView: return numberOfCardsForOppRevealedMobCollectionView(0) case secondOppRevealedMobCollectionView: return bourgGameManager.numOpponents < 2 ? 0 : numberOfCardsForOppRevealedMobCollectionView(1) case thirdOppRevealedMobCollectionView: return bourgGameManager.numOpponents < 3 ? 0 : numberOfCardsForOppRevealedMobCollectionView(2) default: fatalError() } } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { switch collectionView { case proletariatCollectionView: let player = bourgGameManager.bourgGameData.player if player.hand == nil { return UICollectionViewCell() } else { let cell: ProletariatCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("proletariatCell", forIndexPath: indexPath) as! ProletariatCollectionViewCell cell.cardImageView.image = imageForProletariatCollectionView(cellForItemAtIndexPath: indexPath) if player.firstMob != nil && !player.firstMob!.submitted && player.firstMob!.hasCard(player.hand.arrayCards[indexPath.item]) { cell.highlightBorder(usingColor: GameplayViewController.firstMobHighlightColor) } else if player.secondMob != nil && !player.secondMob!.submitted && player.secondMob!.hasCard(player.hand.arrayCards[indexPath.item]) { cell.highlightBorder(usingColor: GameplayViewController.secondMobHighlightColor) } else { cell.unhighlightBorder() } return cell } case royalsCollectionView: if bourgGameManager.bourgGameData.royalsPool == nil { return UICollectionViewCell() } else { let cell: RoyalsCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("royalsCell", forIndexPath: indexPath) as! RoyalsCollectionViewCell cell.cardImageView.image = UIImage(named: "\(bourgGameManager.bourgGameData.royalsPool.arrayCards[indexPath.item].rank.shorthand)_\(bourgGameManager.bourgGameData.royalsPool.arrayCards[indexPath.item].suit.shorthand)") return cell } case firstOppRevealedMobCollectionView: if bourgGameManager.bourgGameData.opponents[0].latestSubmittedMob == nil || bourgGameManager.bourgGameData.opponents[0].latestSubmittedMob!.submitted == false { return UICollectionViewCell() } else { let cell: OpponentMobCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("revealedMobCell", forIndexPath: indexPath) as! OpponentMobCollectionViewCell cell.cardImageView.image = imageForOppRevealedMobCollectionView(0, cellForItemAtIndexPath: indexPath) return cell } case secondOppRevealedMobCollectionView: if bourgGameManager.numOpponents < 2 { return UICollectionViewCell() } else if bourgGameManager.bourgGameData.opponents[1].mobs == nil { return UICollectionViewCell() } else { let cell: OpponentMobCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("revealedMobCell", forIndexPath: indexPath) as! OpponentMobCollectionViewCell cell.cardImageView.image = imageForOppRevealedMobCollectionView(1, cellForItemAtIndexPath: indexPath) return cell } case thirdOppRevealedMobCollectionView: if bourgGameManager.numOpponents < 3 { return UICollectionViewCell() } else if bourgGameManager.bourgGameData.opponents[2].mobs == nil { return UICollectionViewCell() } else { let cell: OpponentMobCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("revealedMobCell", forIndexPath: indexPath) as! OpponentMobCollectionViewCell cell.cardImageView.image = imageForOppRevealedMobCollectionView(2, cellForItemAtIndexPath: indexPath) return cell } default: fatalError() } } private func numberOfCardsForProletariatCollectionView() -> Int { let player = bourgGameManager.bourgGameData.player switch BourgGameState(rawValue: bourgGameManager.roundStageStateIndex)! { case BourgGameState.BeforeRound: return 0 case BourgGameState.SubmitFirstMob: return player.hand.numberOfCards ?? 0 case BourgGameState.SubmitSecondMob: return player.hand.numberOfCards ?? 0 case BourgGameState.DeterminingJacksWinner: if player.bestFlushMob?.numberOfCards ?? 0 == 0 { player.bestFlushMob?.numberOfCards } return player.bestFlushMob?.numberOfCards ?? 0 case BourgGameState.DeterminingQueensWinner: if player.bestStraightMob?.numberOfCards ?? 0 == 0 { player.bestStraightMob?.numberOfCards } return player.bestStraightMob?.numberOfCards ?? 0 case BourgGameState.DeterminingKingsWinner: if player.bestBookMob?.numberOfCards ?? 0 == 0 { player.bestBookMob?.numberOfCards } return player.bestBookMob?.numberOfCards ?? 0 case BourgGameState.EndOfRound: return 0 } } private func imageForProletariatCollectionView(cellForItemAtIndexPath indexPath: NSIndexPath) -> UIImage? { let player = bourgGameManager.bourgGameData.player switch BourgGameState(rawValue: bourgGameManager.roundStageStateIndex)! { case BourgGameState.BeforeRound: return nil case BourgGameState.SubmitFirstMob: fallthrough case BourgGameState.SubmitSecondMob: return UIImage(named: "\(player.hand.arrayCards[indexPath.item].rank.shorthand)_\(player.hand.arrayCards[indexPath.item].suit.shorthand)") case BourgGameState.DeterminingJacksWinner: if let bestMob = player.bestFlushMob { return UIImage(named: "\(bestMob.arrayCards[indexPath.item].rank.shorthand)_\(bestMob.arrayCards[indexPath.item].suit.shorthand)") } else { player.bestFlushMob return nil } case BourgGameState.DeterminingQueensWinner: if let bestMob = player.bestStraightMob { return UIImage(named: "\(bestMob.arrayCards[indexPath.item].rank.shorthand)_\(bestMob.arrayCards[indexPath.item].suit.shorthand)") } else { player.bestStraightMob return nil } case BourgGameState.DeterminingKingsWinner: if let bestMob = player.bestBookMob { return UIImage(named: "\(bestMob.arrayCards[indexPath.item].rank.shorthand)_\(bestMob.arrayCards[indexPath.item].suit.shorthand)") } else { player.bestBookMob return nil } case BourgGameState.EndOfRound: return nil } } private func numberOfCardsForOppRevealedMobCollectionView(oppIndex: Int) -> Int { let opponent = bourgGameManager.bourgGameData.opponents[oppIndex] switch BourgGameState(rawValue: bourgGameManager.roundStageStateIndex)! { case BourgGameState.BeforeRound: return 0 case BourgGameState.SubmitFirstMob: return opponent.firstMob?.numberOfCards ?? 0 case BourgGameState.SubmitSecondMob: return opponent.secondMob?.numberOfCards ?? 0 case BourgGameState.DeterminingJacksWinner: if opponent.bestFlushMob?.numberOfCards ?? 0 == 0 { opponent.bestFlushMob?.numberOfCards } return opponent.bestFlushMob?.numberOfCards ?? 0 case BourgGameState.DeterminingQueensWinner: if opponent.bestStraightMob?.numberOfCards ?? 0 == 0 { opponent.bestStraightMob?.numberOfCards } return opponent.bestStraightMob?.numberOfCards ?? 0 case BourgGameState.DeterminingKingsWinner: if opponent.bestBookMob?.numberOfCards ?? 0 == 0 { opponent.bestBookMob?.numberOfCards } return opponent.bestBookMob?.numberOfCards ?? 0 case BourgGameState.EndOfRound: return 0 } } private func imageForOppRevealedMobCollectionView(oppIndex: Int, cellForItemAtIndexPath indexPath: NSIndexPath) -> UIImage? { let opponent = bourgGameManager.bourgGameData.opponents[oppIndex] switch BourgGameState(rawValue: bourgGameManager.roundStageStateIndex)! { case BourgGameState.BeforeRound: return nil case BourgGameState.SubmitFirstMob: fallthrough case BourgGameState.SubmitSecondMob: return UIImage(named: "CardBack_Opp") case BourgGameState.DeterminingJacksWinner: if let bestMob = opponent.bestFlushMob { return UIImage(named: "\(bestMob.arrayCards[indexPath.item].rank.shorthand)_\(bestMob.arrayCards[indexPath.item].suit.shorthand)") } else { return nil } case BourgGameState.DeterminingQueensWinner: if let bestMob = opponent.bestStraightMob { return UIImage(named: "\(bestMob.arrayCards[indexPath.item].rank.shorthand)_\(bestMob.arrayCards[indexPath.item].suit.shorthand)") } else { return nil } case BourgGameState.DeterminingKingsWinner: if let bestMob = opponent.bestBookMob { return UIImage(named: "\(bestMob.arrayCards[indexPath.item].rank.shorthand)_\(bestMob.arrayCards[indexPath.item].suit.shorthand)") } else { return nil } case BourgGameState.EndOfRound: return nil } } } // MARK: GameplayViewController: UICollectionViewDelegate extension GameplayViewController: UICollectionViewDelegate { // switch collectionView { // case proletariatCollectionView: // case royalsCollectionView: // case firstOppRevealedMobCollectionView: // case secondOppRevealedMobCollectionView: // case thirdOppRevealedMobCollectionView: // default: // fatalError() // } func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { switch collectionView { case proletariatCollectionView: switch BourgGameState(rawValue: bourgGameManager.roundStageStateIndex)! { case BourgGameState.SubmitFirstMob: fallthrough case BourgGameState.SubmitSecondMob: return true default: return false } case royalsCollectionView: return false case firstOppRevealedMobCollectionView: fallthrough case secondOppRevealedMobCollectionView: fallthrough case thirdOppRevealedMobCollectionView: return false default: fatalError() } } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { switch collectionView { case proletariatCollectionView: print("") print("Selected \(bourgGameManager.bourgGameData.player.hand.arrayCards[indexPath.item].description)") switch BourgGameState(rawValue: bourgGameManager.roundStageStateIndex)! { case BourgGameState.SubmitFirstMob: if bourgGameManager.bourgGameData.player.firstMob!.hasCard(bourgGameManager.bourgGameData.player.hand.arrayCards[indexPath.item]) { print("Removing from Mob 1") bourgGameManager.bourgGameData.player.firstMob!.removeFirstOccurenceOfCard(bourgGameManager.bourgGameData.player.hand.arrayCards[indexPath.item]) } else if bourgGameManager.bourgGameData.player.firstMob!.numberOfCards < BourgMob.mobMaxSize { print("Adding to Mob 1") bourgGameManager.bourgGameData.player.firstMob!.addCardToTop(bourgGameManager.bourgGameData.player.hand.arrayCards[indexPath.item]) } else { print("Mob 1 full, can't select any more") } updateMobRankingDebugText() case BourgGameState.SubmitSecondMob: if bourgGameManager.bourgGameData.player.secondMob!.hasCard(bourgGameManager.bourgGameData.player.hand.arrayCards[indexPath.item]) { print("Removing from Mob 2") bourgGameManager.bourgGameData.player.secondMob!.removeFirstOccurenceOfCard(bourgGameManager.bourgGameData.player.hand.arrayCards[indexPath.item]) } else if bourgGameManager.bourgGameData.player.firstMob!.hasCard(bourgGameManager.bourgGameData.player.hand.arrayCards[indexPath.item]) { print("Mob 1 has this card selected, can't select it for Mob 2") } else if bourgGameManager.bourgGameData.player.secondMob!.numberOfCards < BourgMob.mobMaxSize { print("Adding to Mob 2") bourgGameManager.bourgGameData.player.secondMob!.addCardToTop(bourgGameManager.bourgGameData.player.hand.arrayCards[indexPath.item]) } else { print("Mob 2 full, can't select any more") } updateMobRankingDebugText() default: fatalError("Shouldn't be able to select unless on SubmitFirstMob or SubmitSecondMob stage of round") } collectionView.reloadData() case royalsCollectionView: fatalError("Royals collection view shouldn't be selectable") case firstOppRevealedMobCollectionView: fatalError("Opponent revealed mobs collection view shouldn't be selectable") case secondOppRevealedMobCollectionView: fatalError("Opponent revealed mobs collection view shouldn't be selectable") case thirdOppRevealedMobCollectionView: fatalError("Opponent revealed mobs collection view shouldn't be selectable") default: fatalError() } } } // MARK: GameplayViewController: UICollectionViewDelegateFlowLayout extension GameplayViewController: UICollectionViewDelegateFlowLayout { func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { switch collectionView { case proletariatCollectionView: return CGSize(width: GameplayViewController.proletariatCardImageWidth, height: GameplayViewController.proletariatCardImageHeight) case royalsCollectionView: return CGSize(width: GameplayViewController.royalsPoolCardImageWidth, height: GameplayViewController.royalsPoolCardImageHeight) case firstOppRevealedMobCollectionView: return CGSize(width: GameplayViewController.opponentMobCardImageWidth, height: GameplayViewController.opponentMobCardImageHeight) case secondOppRevealedMobCollectionView: return CGSize(width: GameplayViewController.opponentMobCardImageWidth, height: GameplayViewController.opponentMobCardImageHeight) case thirdOppRevealedMobCollectionView: return CGSize(width: GameplayViewController.opponentMobCardImageWidth, height: GameplayViewController.opponentMobCardImageHeight) default: fatalError() } } } // MARK: GameplayViewController: BourgGameManagerDelegate extension GameplayViewController: BourgGameManagerDelegate { func newGameWillStart() { print("") print("GameplayViewController::newGameWillStart:") updateRoundLabelText() updateRoundStageInfoLabelText() showHideOpponents() setOppMobViewOutlines() } func newGameDidStart() { print("") print("GameplayViewController::newGameDidStart:") updateRoundLabelText() updateRoundStageInfoLabelText() } func loadGameWillStart() { print("") print("GameplayViewController::loadGameWillStart:") } func loadGameDidStart() { print("") print("GameplayViewController::loadGameDidStart:") } func tutorialWillStart() { print("") print("GameplayViewController::tutorialWillStart:") } func tutorialDidStart() { print("") print("GameplayViewController::tutorialDidStart:") } func roundWillAdvance() { print("") print("GameplayViewController::roundWillAdvance:") } func roundDidAdvance() { print("") print("GameplayViewController::roundDidAdvance:") updateRoundLabelText() } func roundStageWillAdvance() { print("") print("GameplayViewController::roundStageWillAdvance:") let player = bourgGameManager.bourgGameData.player switch BourgGameState(rawValue: bourgGameManager.roundStageStateIndex)! { case BourgGameState.SubmitFirstMob: player.firstMob!.arrayCards.forEach({ bourgGameManager.bourgGameData.player.hand.removeFirstOccurenceOfCard($0) }) player.firstMob!.validate() player.firstMob!.submitted = true case BourgGameState.SubmitSecondMob: player.secondMob!.arrayCards.forEach({ bourgGameManager.bourgGameData.player.hand.removeFirstOccurenceOfCard($0) }) player.secondMob!.validate() player.secondMob!.submitted = true default: break } } func roundStageDidAdvance() { print("") print("GameplayViewController::roundStageDidAdvance:") updateOppRevealedMobCollectionViews() proletariatCollectionView.reloadData() royalsCollectionView.reloadData() updateMobRankingDebugText() updateCommonCardVisibility() updateRoundStageButtonTitle() updateRoundStageInfoLabelText() } } // MARK: GameplayViewController: BourgGameDataDelegate extension GameplayViewController: BourgGameDataDelegate { func playerHandChanged() { print("") print("GameplayViewController::playerHandChanged:") } func playerCommonCardChanged() { print("") print("GameplayViewController::playerCommonCardChanged:") if bourgGameManager.bourgGameData.player.commonCard != nil { playerCommonCardImage.image = UIImage(named: "\(bourgGameManager.bourgGameData.player.commonCard!.rank.shorthand)_\(bourgGameManager.bourgGameData.player.commonCard!.suit.shorthand)") } else { playerCommonCardImage.image = nil } } func playerScoreChanged() { print("") print("GameplayViewController::playerScoreChanged:") scoreValLabel.text = "\(bourgGameManager.bourgGameData.player.score)" } func opponentsScoresChanged() { print("") print("GameplayViewController::opponentsScoresChanged:") switch bourgGameManager.bourgGameData.numOpponents { case 1: self.firstOppScoreValLabel.text = "\(bourgGameManager.bourgGameData.firstOpponent.score)" case 2: self.firstOppScoreValLabel.text = "\(bourgGameManager.bourgGameData.firstOpponent.score)" self.secondOppScoreValLabel.text = "\(bourgGameManager.bourgGameData.secondOpponent!.score)" case 3: self.firstOppScoreValLabel.text = "\(bourgGameManager.bourgGameData.firstOpponent.score)" self.secondOppScoreValLabel.text = "\(bourgGameManager.bourgGameData.secondOpponent!.score)" self.thirdOppScoreValLabel.text = "\(bourgGameManager.bourgGameData.thirdOpponent!.score)" default: fatalError("Should be between 1 and 3 opponents") } } }
mit
0581547767521064e34520d266ed293f
38.514819
226
0.735985
4.397508
false
false
false
false
Jnosh/swift
validation-test/compiler_crashers_fixed/01282-swift-nominaltypedecl-getdeclaredtypeincontext.swift
65
1863
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck s)) func ^(a: Boolean, Bool) -> Bool { return !(a) } f e) func f<g>() -> (g, g -> g) -> g { d j d.i = { } { g) { h } } protocol f { class func i() } class d: f{ class func i {} enum S<T> { case C(T, () -> ()) } var x1 = 1 var f1: Int -> Int = { return $0 } let succeeds: Int = { (x: Int, f: Int -> Int) -> Int in return f(x) }(x1, f1) let crashes: Int = { x, f in return f(x) }(x1, f1) class c { func b((Any, c))(a: (Any, AnyObject)) { b(a) } } protocol a { typealias d typealias e = d typealias f = d } class b<h : c, i : c where h.g == i> : a { } class b<h, i> { } protocol c { typealias g } protocol a { } protocol b : a { } protocol c : a { } protocol d { typealias f = a } struct e : d { typealias f = b } func i<j : b, k : d where k.f == j> (n: k) { } func i<l : d where l.f == c> (n: l) { } i(e()) func c<d { enum c { func e var _ = e } } protocol A { } struct B : A { } struct C<D, E: A where D.C == E> { } struct c<d : Sequence> { var b: d } func a<d>() -> [c<d>] { return [] } protocol A { typealias B func b(B) } struct X<Y> : A { func b(b: X.Type) { } } class a<f : b, g : b where f.d == g> { } protocol b { typealias d typealias e pealias e = a<c<h>, d> } protocol a { class func c() } class b: a { class func c() { } } (b() as a).dynamicType.c() func prefix(with: String) -> <T>(() -> T) -> String { return { g in "\(with): \(g())" } } struct A<T> { let a: [(T, () -> ())] = [] } func a<T>() { enum b { case c } } func a(b: Int = 0) { } let c = a c
apache-2.0
694ec3db2824b3c1e5a5900e4c1bbb48
13.669291
79
0.56146
2.394602
false
false
false
false
el-hoshino/NotAutoLayout
Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/MiddleRightCenter.Individual.swift
1
2777
// // MiddleRightCenter.Individual.swift // NotAutoLayout // // Created by 史翔新 on 2017/06/20. // Copyright © 2017年 史翔新. All rights reserved. // import Foundation extension IndividualProperty { public struct MiddleRightCenter { let middleRight: LayoutElement.Point let center: LayoutElement.Horizontal } } // MARK: - Make Frame extension IndividualProperty.MiddleRightCenter { private func makeFrame(middleRight: Point, center: Float, top: Float) -> Rect { let height = (middleRight.y - top).double return self.makeFrame(middleRight: middleRight, center: center, height: height) } private func makeFrame(middleRight: Point, center: Float, bottom: Float) -> Rect { let height = (bottom - middleRight.y).double return self.makeFrame(middleRight: middleRight, center: center, height: height) } private func makeFrame(middleRight: Point, center: Float, height: Float) -> Rect { let width = (middleRight.x - center).double let x = middleRight.x - width let y = middleRight.y - height.half let frame = Rect(x: x, y: y, width: width, height: height) return frame } } // MARK: - Set A Line - // MARK: Top extension IndividualProperty.MiddleRightCenter: LayoutPropertyCanStoreTopToEvaluateFrameType { public func evaluateFrame(top: LayoutElement.Vertical, parameters: IndividualFrameCalculationParameters) -> Rect { let middleRight = self.middleRight.evaluated(from: parameters) let center = self.center.evaluated(from: parameters) let top = top.evaluated(from: parameters) return self.makeFrame(middleRight: middleRight, center: center, top: top) } } // MARK: Bottom extension IndividualProperty.MiddleRightCenter: LayoutPropertyCanStoreBottomToEvaluateFrameType { public func evaluateFrame(bottom: LayoutElement.Vertical, parameters: IndividualFrameCalculationParameters) -> Rect { let middleRight = self.middleRight.evaluated(from: parameters) let center = self.center.evaluated(from: parameters) let bottom = bottom.evaluated(from: parameters) return self.makeFrame(middleRight: middleRight, center: center, bottom: bottom) } } // MARK: - Set A Length - // MARK: Height extension IndividualProperty.MiddleRightCenter: LayoutPropertyCanStoreHeightToEvaluateFrameType { public func evaluateFrame(height: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect { let middleRight = self.middleRight.evaluated(from: parameters) let center = self.center.evaluated(from: parameters) let width = (middleRight.x - center).double let height = height.evaluated(from: parameters, withTheOtherAxis: .width(width)) return self.makeFrame(middleRight: middleRight, center: center, height: height) } }
apache-2.0
013cc84489b31a3a84c71c01c5fedf84
26.346535
118
0.743302
4.097923
false
false
false
false
kamarshad/CMT40
VideoResume/VideoResume/PlayVideoViewController.swift
1
3170
import UIKit import AVFoundation import AVKit class VideoViewController: UIViewController { override var prefersStatusBarHidden: Bool { return true } private var videoURL: URL var player: AVPlayer? var playerController : AVPlayerViewController? init(videoURL: URL) { self.videoURL = videoURL super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.doSetUp() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.playVideo() } fileprivate func doSetUp() { self.view.backgroundColor = UIColor.gray player = AVPlayer(url: videoURL) playerController = AVPlayerViewController() guard player != nil && playerController != nil else { return } playerController!.showsPlaybackControls = true playerController!.player = player! self.addChildViewController(playerController!) self.view.addSubview(playerController!.view) playerController!.view.frame = view.frame //NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.player!.currentItem) let cancelButton = UIButton(frame: CGRect(x: 10.0, y: 10.0, width: 30.0, height: 30.0)) cancelButton.setImage(#imageLiteral(resourceName: "cancel"), for: UIControlState()) cancelButton.addTarget(self, action: #selector(cancel), for: .touchUpInside) view.addSubview(cancelButton) let shareVideo = UIButton(frame: CGRect(x: self.view.frame.width-60, y: 10.0, width: 40.0, height: 30.0)) shareVideo.setImage(#imageLiteral(resourceName: "shareIcon"), for: UIControlState()) shareVideo.addTarget(self, action: #selector(shareResume), for: .touchUpInside) view.addSubview(shareVideo) } func playVideo() { player?.play() } func cancel() { dismiss(animated: true, completion: nil) } @objc fileprivate func playerItemDidReachEnd(_ notification: Notification) { if self.player != nil { self.player!.seek(to: kCMTimeZero) self.player!.play() } } func shareResume() { let sharableObject = [self.videoURL] let activityVC = UIActivityViewController(activityItems: sharableObject, applicationActivities: nil) activityVC.setValue("Video", forKey: "subject") activityVC.excludedActivityTypes = [UIActivityType.airDrop, UIActivityType.addToReadingList, UIActivityType.assignToContact, UIActivityType.copyToPasteboard, UIActivityType.mail, UIActivityType.message, UIActivityType.openInIBooks, UIActivityType.postToTencentWeibo, UIActivityType.postToVimeo, UIActivityType.postToWeibo, UIActivityType.print] self.present(activityVC, animated: true, completion: nil) } }
mit
1433457dfbba961b2ec0ef944dc60fe0
34.617978
352
0.667192
5.063898
false
false
false
false
maurovc/MyMarvel
MyMarvel/WalkthroughUtils.swift
1
2876
// // WalkthroughUtils.swift // MyMarvel // // Created by Mauro Vime Castillo on 27/10/16. // Copyright © 2016 Mauro Vime Castillo. All rights reserved. // import UIKit import BWWalkthrough typealias WalkthroughBlock = () -> Void /// Class that manages all the walkthrough logic. class WalkthroughUtils: NSObject { static let walkKey = "walkthrough_v2" static let sharedUtils = WalkthroughUtils() var viewController: UIViewController? var block: WalkthroughBlock? var walkthrough: CustomWalkthroughViewController? func showWalkInVC(viewController: UIViewController, block: WalkthroughBlock) { self.viewController = viewController self.block = block viewController.presentViewController(myWalkthrough(), animated: true) { UIApplication.sharedApplication().statusBarStyle = .Default } } func myWalkthrough() -> CustomWalkthroughViewController { let storyboard = UIStoryboard(name: "Walkthrough", bundle: nil) walkthrough = (storyboard.instantiateViewControllerWithIdentifier("walk") as! CustomWalkthroughViewController) let pageOne = storyboard.instantiateViewControllerWithIdentifier("walk1") let pageTwo = storyboard.instantiateViewControllerWithIdentifier("walk2") let pageThr = storyboard.instantiateViewControllerWithIdentifier("walk3") let pageFou = storyboard.instantiateViewControllerWithIdentifier("walk4") let pageFiv = storyboard.instantiateViewControllerWithIdentifier("walk5") let pageSix = storyboard.instantiateViewControllerWithIdentifier("walk6") walkthrough?.delegate = self walkthrough?.addViewController(pageOne) walkthrough?.addViewController(pageTwo) walkthrough?.addViewController(pageThr) walkthrough?.addViewController(pageFou) walkthrough?.addViewController(pageFiv) walkthrough?.addViewController(pageSix) walkthrough!.view.sendSubviewToBack(walkthrough!.backgroundView) return walkthrough! } class func needsToShowWalkthrough() -> Bool { return !NSUserDefaults.standardUserDefaults().boolForKey(walkKey) } class func setNeedsToShowWalkthrough(needs: Bool) { NSUserDefaults.standardUserDefaults().setBool(needs, forKey: walkKey) } } extension WalkthroughUtils: BWWalkthroughViewControllerDelegate { func walkthroughCloseButtonPressed() { if (walkthrough!.currentPage + 1) < walkthrough!.numberOfPages { walkthrough?.nextPage() } else { UIApplication.sharedApplication().statusBarStyle = .LightContent viewController?.dismissViewControllerAnimated(true, completion: nil) if let _ = block { block!() } } } }
mit
6fdc244d25c3c702ea2cdd6fe08a1be9
34.95
118
0.696348
5.715706
false
false
false
false
esttorhe/RxSwift
Playgrounds/ObservablesOperators/Observables+Connectable.playground/Contents.swift
1
4362
import Cocoa import RxSwift import XCPlayground /*: ## Connectable Observable Operators A Connectable Observable resembles an ordinary Observable, except that it does not begin emitting items when it is subscribed to, but only when its connect() method is called. In this way you can wait for all intended Subscribers to subscribe to the Observable before the Observable begins emitting items. Specialty Observables that have more precisely-controlled subscription dynamics. */ func sampleWithoutConnectableOperators() { let int1 = interval(1, MainScheduler.sharedInstance) int1 >- subscribeNext { print("first subscription \($0)") } delay(5) { int1 >- subscribeNext { print("second subscription \($0)") } } } sampleWithoutConnectableOperators() fu/*: ### `multicast` [More info in reactive.io website]( http://reactivex.io/documentation/operators/publish.html ) */ nc sampleWithMulticast() { let subject1 = PublishSubject<Int64>() subject1 >- subscribeNext { print("Subject \($0)") } let int1 = interval(1, MainScheduler.sharedInstance) >- multicast(subject1) int1 >- subscribeNext { print("first subscription \($0)") } delay(2) { int1.connect() } delay(4) { int1 >- subscribeNext { print("second subscription \($0)") print("---") } } delay(6) { int1 >- subscribeNext { print("thirth subscription \($0)") } } } //sampleWithMulticast() func sampleW/*: ### `replay` Ensure that all observers see the same sequence of emitted items, even if they subscribe after the Observable has begun emitting items. publish = multicast + replay subject [More info in reactive.io website]( http://reactivex.io/documentation/operators/replay.html ) */ ithReplayBuffer0() { let int1 = interval(1, MainScheduler.sharedInstance) >- replay(0) int1 >- subscribeNext { print("first subscription \($0)") } delay(2) { int1.connect() } delay(4) { int1 >- subscribeNext { print("second subscription \($0)") print("---") } } delay(6) { int1 >- subscribeNext { print("thirth subscription \($0)") } } } //sampleWithReplayBuffer0() func sampleWithReplayBuffer2() { print("--- sampleWithReplayBuffer2 ---\n") let int1 = interval(1, MainScheduler.sharedInstance) >- replay(2) int1 >- subscribeNext { print("first subscription \($0)") } delay(2) { int1.connect() } delay(4) { int1 >- subscribeNext { print("second subscription \($0)") print("---") } } delay(6) { int1 >- subscribeNext { print("third subscription \($0)") } } } //sampleWithReplayBuffer2() func sampleWithPublish() { /*: ### `publish` Convert an ordinary Observable into a connectable Observable. publish = multicast + publish subject so publish is basically replay(0) [More info in reactive.io website]( http://reactivex.io/documentation/operators/publish.html ) */ let int1 = interval(1, MainScheduler.sharedInstance) >- publish int1 >- subscribeNext { print("first subscription \($0)") } delay(2) { int1.connect() } delay(4) { int1 >- subscribeNext { print("second subscription \($0)") print("---") } } delay(6) { int1 >- subscribeNext { print("third subscription \($0)") } } } //sampleWithPublish() XCPSetExecutionShouldContinueIndefi/*: ### `refCount` Make a Connectable Observable behave like an ordinary Observable. [More info in reactive.io website]( http://reactivex.io/documentation/operators/refcount.html ) */ nit/*: ### `Variable` / `sharedWithCachedLastResult` */ ely(continueIndefinitely: true)
mit
ad63ccea8c131ba81dbebeb25a1cc5c8
18.560538
305
0.55823
4.655283
false
false
false
false
CatchChat/Yep
Yep/ViewControllers/DoNotDisturbPeriod/DoNotDisturbPeriodViewController.swift
1
5977
// // DoNotDisturbPeriodViewController.swift // Yep // // Created by NIX on 15/8/3. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit import RealmSwift import YepKit import YepNetworking final class DoNotDisturbPeriodViewController: UIViewController { var doNotDisturbPeriod = DoNotDisturbPeriod() var dirtyAction: (DoNotDisturbPeriod -> Void)? @IBOutlet private weak var fromButton: UIButton! @IBOutlet private weak var toButton: UIButton! @IBOutlet private weak var pickerView: UIPickerView! private enum ActiveTime { case From case To } private let max = Int(INT16_MAX) private var activeTime: ActiveTime = .From { willSet { switch newValue { case .From: fromButton.backgroundColor = UIColor.lightGrayColor().colorWithAlphaComponent(0.5) toButton.backgroundColor = UIColor.whiteColor() pickerView.selectRow(max / (2 * 24) * 24 + doNotDisturbPeriod.fromHour, inComponent: 0, animated: true) pickerView.selectRow(max / (2 * 60) * 60 + doNotDisturbPeriod.fromMinute, inComponent: 1, animated: true) case .To: fromButton.backgroundColor = UIColor.whiteColor() toButton.backgroundColor = UIColor.lightGrayColor().colorWithAlphaComponent(0.5) pickerView.selectRow(max / (2 * 24) * 24 + doNotDisturbPeriod.toHour, inComponent: 0, animated: true) pickerView.selectRow(max / (2 * 60) * 60 + doNotDisturbPeriod.toMinute, inComponent: 1, animated: true) } } } private var isDirty = false { didSet { updateDoNotDisturb(success: { [weak self] in if let strongSelf = self { strongSelf.dirtyAction?(strongSelf.doNotDisturbPeriod) } }) } } override func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("Mute", comment: "") activeTime = .From updateFromButton() updateToButton() } // MARK: - Actions private func updateDoNotDisturb(success success: () -> Void) { let info: JSONDictionary = [ "mute_started_at_string": doNotDisturbPeriod.serverFromString, "mute_ended_at_string": doNotDisturbPeriod.serverToString, ] updateMyselfWithInfo(info, failureHandler: { [weak self] (reason, errorMessage) in defaultFailureHandler(reason: reason, errorMessage: errorMessage) YepAlert.alertSorry(message: NSLocalizedString("Set Do Not Disturb Failed!", comment: ""), inViewController: self) }, completion: { _ in SafeDispatch.async { defer { success() } guard let realm = try? Realm() else { return } if let me = meInRealm(realm) { var userDoNotDisturb = me.doNotDisturb if userDoNotDisturb == nil { let _userDoNotDisturb = UserDoNotDisturb() _userDoNotDisturb.isOn = true let _ = try? realm.write { me.doNotDisturb = _userDoNotDisturb } userDoNotDisturb = _userDoNotDisturb } if let userDoNotDisturb = me.doNotDisturb { let _ = try? realm.write { userDoNotDisturb.fromHour = self.doNotDisturbPeriod.fromHour userDoNotDisturb.fromMinute = self.doNotDisturbPeriod.fromMinute userDoNotDisturb.toHour = self.doNotDisturbPeriod.toHour userDoNotDisturb.toMinute = self.doNotDisturbPeriod.toMinute } } } } }) } private func updateFromButton() { fromButton.setTitle(NSLocalizedString("From", comment: "") + " " + doNotDisturbPeriod.localFromString, forState: .Normal) } private func updateToButton() { toButton.setTitle(NSLocalizedString("To", comment: "") + " " + doNotDisturbPeriod.localToString, forState: .Normal) } @IBAction private func activeFrom() { activeTime = .From } @IBAction private func activeTo() { activeTime = .To } } // MARK: - UIPickerViewDataSource, UIPickerViewDelegate extension DoNotDisturbPeriodViewController: UIPickerViewDataSource, UIPickerViewDelegate { func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 2 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return max } func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { return 60 } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if component == 0 { return String(format: "%02d", row % 24) } else if component == 1 { return String(format: "%02d", row % 60) } return "" } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch activeTime { case .From: if component == 0 { doNotDisturbPeriod.fromHour = row % 24 } else if component == 1 { doNotDisturbPeriod.fromMinute = row % 60 } updateFromButton() case .To: if component == 0 { doNotDisturbPeriod.toHour = row % 24 } else if component == 1 { doNotDisturbPeriod.toMinute = row % 60 } updateToButton() } isDirty = true } }
mit
89ceceffc4858beb7db4faf00fbdabb8
28.875
129
0.574059
5.159758
false
false
false
false
emilstahl/swift
test/PlaygroundTransform/Inputs/PlaygroundsRuntime.swift
12
1703
// If you're modifying this file to add or modify function signatures, you // should be notifying the maintainer of PlaygroundLogger and also the // maintainer of lib/Sema/PlaygroundTransform.cpp. class LogRecord { let text : String init(api : String, object : Any, name : String, id : Int) { var object_description : String = "" print(object, terminator: "", toStream: &object_description) text = api + "[" + name + "='" + object_description + "']" } init(api : String, object : Any, name : String) { var object_description : String = "" print(object, terminator: "", toStream: &object_description) text = api + "[" + name + "='" + object_description + "']" } init(api : String, object: Any) { var object_description : String = "" print(object, terminator: "", toStream: &object_description) text = api + "['" + object_description + "']" } init(api: String) { text = api } } func $builtin_log<T>(object : T, _ name : String) -> AnyObject? { return LogRecord(api:"$builtin_log", object:object, name:name) } func $builtin_log_with_id<T>(object : T, _ name : String, _ id : Int) -> AnyObject? { return LogRecord(api:"$builtin_log", object:object, name:name, id:id) } func $builtin_log_scope_entry() -> AnyObject? { return LogRecord(api:"$builtin_log_scope_entry") } func $builtin_log_scope_exit() -> AnyObject? { return LogRecord(api:"$builtin_log_scope_exit") } func $builtin_postPrint() -> AnyObject? { return LogRecord(api:"$builtin_postPrint") } func $builtin_send_data(object:AnyObject?, _ sl: Int, _ el: Int, _ sc: Int, _ ec: Int) { let loc = "[\(sl):\(sc)-\(el):\(ec)]" print(loc + " " + (object as! LogRecord).text) }
apache-2.0
9afc761c63ed3df913ccdd1325337645
33.06
88
0.636524
3.372277
false
false
false
false
JeeLiu/ios-charts
Charts/Classes/Data/LineRadarChartDataSet.swift
17
1490
// // LineRadarChartDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 26/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class LineRadarChartDataSet: LineScatterCandleChartDataSet { public var fillColor = UIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0) public var fillAlpha = CGFloat(0.33) private var _lineWidth = CGFloat(1.0) public var drawFilledEnabled = false /// line width of the chart (min = 0.2, max = 10) /// :default: 1 public var lineWidth: CGFloat { get { return _lineWidth } set { _lineWidth = newValue if (_lineWidth < 0.2) { _lineWidth = 0.5 } if (_lineWidth > 10.0) { _lineWidth = 10.0 } } } public var isDrawFilledEnabled: Bool { return drawFilledEnabled } // MARK: NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { var copy = super.copyWithZone(zone) as! LineRadarChartDataSet copy.fillColor = fillColor copy._lineWidth = _lineWidth copy.drawFilledEnabled = drawFilledEnabled return copy } }
apache-2.0
dbad48ceeb8d534419197a519c89284a
23.032258
103
0.581208
4.408284
false
false
false
false
cocos543/LetCode-in-Swift
LetCodeInSwift/LetCodeInSwift/Solution_Add_Two_Numbers.swift
1
864
// // Solution_Add_Two_Numbers.swift // LetCodeInSwift // // Created by Cocos on 2017/7/20. // Copyright © 2017年 Cocos. All rights reserved. // import Foundation class Solution_Add_Two_Numbers { func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { let head = ListNode(0) var p1 = l1, p2 = l2 //carry var p = head, c = 0; while p1 != nil || p2 != nil || c != 0 { let add1 = p1 == nil ? 0: p1!.val let add2 = p2 == nil ? 0: p2!.val let s = add1 + add2 + c p.next = ListNode(s % 10) p = p.next! c = s / 10 if p1 != nil { p1 = p1!.next } if p2 != nil { p2 = p2!.next } } return head.next; } }
mit
acddc6b944ca376009766b6b411c2c81
22.916667
71
0.422764
3.444
false
false
false
false
aamays/insta-parse
InstaParse/ViewControllers/HomeViewController.swift
1
2857
// // HomeViewController.swift // InstaParse // // Created by Amay Singhal on 1/23/16. // Copyright © 2016 CodePath. All rights reserved. // import UIKit import Parse class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var gramsTableView: UITableView! var refreshControl: UIRefreshControl! var postedGrams: [UserMedia]? { didSet { gramsTableView?.reloadData() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. title = "Home" gramsTableView.delegate = self gramsTableView.dataSource = self // initialize refresh control view refreshControl = UIRefreshControl() refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh") refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged) // add refresh control to the table view gramsTableView.addSubview(refreshControl) // update table updateGramsTable() } // MARK: - Table View Delegate methods func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return postedGrams?.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("GramTableViewCell", forIndexPath: indexPath) as! GramTableViewCell cell.gramMedia = postedGrams![indexPath.row] return cell } // MARK: - Actions @IBAction func logoutUser(sender: UIButton) { NSLog("Logging out user") PFUser.logOut() view.window?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("LoginViewController") } // MARK: - Helper functions private func updateGramsTable() { UserMedia.fetchRecentMedia { (success: Bool, media: [UserMedia]?, error: NSError?) -> () in if success { for m in media! { print(m.likesCount) } self.postedGrams = media self.refreshControl.endRefreshing() } else { print(error?.localizedDescription) } } } func refresh(refControl: AnyObject?) { updateGramsTable() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
92bb1de21ee89ed8bc54ed1f974f92c1
31.089888
144
0.651261
5.164557
false
false
false
false
codestergit/swift
test/decl/protocol/protocols.swift
3
16791
// RUN: %target-typecheck-verify-swift protocol EmptyProtocol { } protocol DefinitionsInProtocols { init() {} // expected-error {{protocol initializers may not have bodies}} deinit {} // expected-error {{deinitializers may only be declared within a class}} } // Protocol decl. protocol Test { func setTitle(_: String) func erase() -> Bool var creator: String { get } var major : Int { get } var minor : Int { get } var subminor : Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} static var staticProperty: Int // expected-error{{property in protocol must have explicit { get } or { get set } specifier}} } protocol Test2 { var property: Int { get } var title: String = "The Art of War" { get } // expected-error{{initial value is not allowed here}} expected-error {{property in protocol must have explicit { get } or { get set } specifier}} static var title2: String = "The Art of War" // expected-error{{initial value is not allowed here}} expected-error {{property in protocol must have explicit { get } or { get set } specifier}} associatedtype mytype associatedtype mybadtype = Int } func test1() { var v1: Test var s: String v1.setTitle(s) v1.creator = "Me" // expected-error {{cannot assign to property: 'creator' is a get-only property}} } protocol Bogus : Int {} // expected-error{{inheritance from non-protocol, non-class type 'Int'}} // Explicit conformance checks (successful). protocol CustomStringConvertible { func print() } // expected-note{{protocol requires function 'print()' with type '() -> ()'}} expected-note{{protocol requires}} expected-note{{protocol requires}} expected-note{{protocol requires}} struct TestFormat { } protocol FormattedPrintable : CustomStringConvertible { func print(format: TestFormat) } struct X0 : Any, CustomStringConvertible { func print() {} } class X1 : Any, CustomStringConvertible { func print() {} } enum X2 : Any { } extension X2 : CustomStringConvertible { func print() {} } // Explicit conformance checks (unsuccessful) struct NotPrintableS : Any, CustomStringConvertible {} // expected-error{{type 'NotPrintableS' does not conform to protocol 'CustomStringConvertible'}} class NotPrintableC : CustomStringConvertible, Any {} // expected-error{{type 'NotPrintableC' does not conform to protocol 'CustomStringConvertible'}} enum NotPrintableO : Any, CustomStringConvertible {} // expected-error{{type 'NotPrintableO' does not conform to protocol 'CustomStringConvertible'}} struct NotFormattedPrintable : FormattedPrintable { // expected-error{{type 'NotFormattedPrintable' does not conform to protocol 'CustomStringConvertible'}} func print(format: TestFormat) {} // expected-note{{candidate has non-matching type '(TestFormat) -> ()'}} } // Circular protocols protocol CircleMiddle : CircleStart { func circle_middle() } // expected-error 2 {{circular protocol inheritance CircleMiddle}} // expected-error@-1{{circular protocol inheritance 'CircleMiddle' -> 'CircleStart' -> 'CircleEnd' -> 'CircleMiddle'}} // expected-error @+1 {{circular protocol inheritance CircleStart}} protocol CircleStart : CircleEnd { func circle_start() } // expected-error 2{{circular protocol inheritance CircleStart}} // expected-note@-1{{protocol 'CircleStart' declared here}} protocol CircleEnd : CircleMiddle { func circle_end()} // expected-note{{protocol 'CircleEnd' declared here}} protocol CircleEntry : CircleTrivial { } protocol CircleTrivial : CircleTrivial { } // expected-error 2{{circular protocol inheritance CircleTrivial}} struct Circle { func circle_start() {} func circle_middle() {} func circle_end() {} } func testCircular(_ circle: Circle) { // FIXME: It would be nice if this failure were suppressed because the protocols // have circular definitions. _ = circle as CircleStart // expected-error{{'Circle' is not convertible to 'CircleStart'; did you mean to use 'as!' to force downcast?}} {{14-16=as!}} } // <rdar://problem/14750346> protocol Q : C, H { } protocol C : E { } protocol H : E { } protocol E { } //===----------------------------------------------------------------------===// // Associated types //===----------------------------------------------------------------------===// protocol SimpleAssoc { associatedtype Associated // expected-note{{protocol requires nested type 'Associated'}} } struct IsSimpleAssoc : SimpleAssoc { struct Associated {} } struct IsNotSimpleAssoc : SimpleAssoc {} // expected-error{{type 'IsNotSimpleAssoc' does not conform to protocol 'SimpleAssoc'}} protocol StreamWithAssoc { associatedtype Element func get() -> Element // expected-note{{protocol requires function 'get()' with type '() -> NotAStreamType.Element'}} } struct AnRange<Int> : StreamWithAssoc { typealias Element = Int func get() -> Int {} } // Okay: Word is a typealias for Int struct AWordStreamType : StreamWithAssoc { typealias Element = Int func get() -> Int {} } struct NotAStreamType : StreamWithAssoc { // expected-error{{type 'NotAStreamType' does not conform to protocol 'StreamWithAssoc'}} typealias Element = Float func get() -> Int {} // expected-note{{candidate has non-matching type '() -> Int'}} } // Okay: Infers Element == Int struct StreamTypeWithInferredAssociatedTypes : StreamWithAssoc { func get() -> Int {} } protocol SequenceViaStream { associatedtype SequenceStreamTypeType : IteratorProtocol // expected-note{{protocol requires nested type 'SequenceStreamTypeType'}} func makeIterator() -> SequenceStreamTypeType } struct IntIterator : IteratorProtocol /*, Sequence, ReplPrintable*/ { typealias Element = Int var min : Int var max : Int var stride : Int mutating func next() -> Int? { if min >= max { return .none } let prev = min min += stride return prev } typealias Generator = IntIterator func makeIterator() -> IntIterator { return self } } extension IntIterator : SequenceViaStream { typealias SequenceStreamTypeType = IntIterator } struct NotSequence : SequenceViaStream { // expected-error{{type 'NotSequence' does not conform to protocol 'SequenceViaStream'}} typealias SequenceStreamTypeType = Int // expected-note{{possibly intended match 'NotSequence.SequenceStreamTypeType' (aka 'Int') does not conform to 'IteratorProtocol'}} func makeIterator() -> Int {} } protocol GetATuple { associatedtype Tuple func getATuple() -> Tuple } struct IntStringGetter : GetATuple { typealias Tuple = (i: Int, s: String) func getATuple() -> Tuple {} } //===----------------------------------------------------------------------===// // Default arguments //===----------------------------------------------------------------------===// // FIXME: Actually make use of default arguments, check substitutions, etc. protocol ProtoWithDefaultArg { func increment(_ value: Int = 1) // expected-error{{default argument not permitted in a protocol method}} } struct HasNoDefaultArg : ProtoWithDefaultArg { func increment(_: Int) {} } //===----------------------------------------------------------------------===// // Variadic function requirements //===----------------------------------------------------------------------===// protocol IntMaxable { func intmax(first: Int, rest: Int...) -> Int // expected-note 2{{protocol requires function 'intmax(first:rest:)' with type '(Int, Int...) -> Int'}} } struct HasIntMax : IntMaxable { func intmax(first: Int, rest: Int...) -> Int {} } struct NotIntMax1 : IntMaxable { // expected-error{{type 'NotIntMax1' does not conform to protocol 'IntMaxable'}} func intmax(first: Int, rest: [Int]) -> Int {} // expected-note{{candidate has non-matching type '(Int, [Int]) -> Int'}} } struct NotIntMax2 : IntMaxable { // expected-error{{type 'NotIntMax2' does not conform to protocol 'IntMaxable'}} func intmax(first: Int, rest: Int) -> Int {} // expected-note{{candidate has non-matching type '(Int, Int) -> Int'}} } //===----------------------------------------------------------------------===// // 'Self' type //===----------------------------------------------------------------------===// protocol IsEqualComparable { func isEqual(other: Self) -> Bool // expected-note{{protocol requires function 'isEqual(other:)' with type '(WrongIsEqual) -> Bool'}} } struct HasIsEqual : IsEqualComparable { func isEqual(other: HasIsEqual) -> Bool {} } struct WrongIsEqual : IsEqualComparable { // expected-error{{type 'WrongIsEqual' does not conform to protocol 'IsEqualComparable'}} func isEqual(other: Int) -> Bool {} // expected-note{{candidate has non-matching type '(Int) -> Bool'}} } //===----------------------------------------------------------------------===// // Using values of existential type. //===----------------------------------------------------------------------===// func existentialSequence(_ e: Sequence) { // expected-error{{has Self or associated type requirements}} // FIXME: Weird diagnostic var x = e.makeIterator() // expected-error{{'Sequence' is not convertible to 'Sequence.Iterator'}} x.next() x.nonexistent() } protocol HasSequenceAndStream { associatedtype R : IteratorProtocol, Sequence func getR() -> R } func existentialSequenceAndStreamType(_ h: HasSequenceAndStream) { // expected-error{{has Self or associated type requirements}} // FIXME: Crummy diagnostics. var x = h.getR() // expected-error{{member 'getR' cannot be used on value of protocol type 'HasSequenceAndStream'; use a generic constraint instead}} x.makeIterator() x.next() x.nonexistent() } //===----------------------------------------------------------------------===// // Subscripting //===----------------------------------------------------------------------===// protocol IntIntSubscriptable { subscript (i: Int) -> Int { get } } protocol IntSubscriptable { associatedtype Element subscript (i: Int) -> Element { get } } struct DictionaryIntInt { subscript (i: Int) -> Int { get { return i } } } func testSubscripting(_ iis: IntIntSubscriptable, i_s: IntSubscriptable) { // expected-error{{has Self or associated type requirements}} var i: Int = iis[17] var i2 = i_s[17] // expected-error{{member 'subscript' cannot be used on value of protocol type 'IntSubscriptable'; use a generic constraint instead}} } //===----------------------------------------------------------------------===// // Static methods //===----------------------------------------------------------------------===// protocol StaticP { static func f() } protocol InstanceP { func f() // expected-note{{protocol requires function 'f()' with type '() -> ()'}} } struct StaticS1 : StaticP { static func f() {} } struct StaticS2 : InstanceP { // expected-error{{type 'StaticS2' does not conform to protocol 'InstanceP'}} static func f() {} // expected-note{{candidate operates on a type, not an instance as required}} } struct StaticAndInstanceS : InstanceP { static func f() {} func f() {} } func StaticProtocolFunc() { let a: StaticP = StaticS1() a.f() // expected-error{{static member 'f' cannot be used on instance of type 'StaticP'}} } func StaticProtocolGenericFunc<t : StaticP>(_: t) { t.f() } //===----------------------------------------------------------------------===// // Operators //===----------------------------------------------------------------------===// protocol Eq { static func ==(lhs: Self, rhs: Self) -> Bool } extension Int : Eq { } // Matching prefix/postfix. prefix operator <> postfix operator <> protocol IndexValue { static prefix func <> (_ max: Self) -> Int static postfix func <> (min: Self) -> Int } prefix func <> (max: Int) -> Int { return 0 } postfix func <> (min: Int) -> Int { return 0 } extension Int : IndexValue {} //===----------------------------------------------------------------------===// // Class protocols //===----------------------------------------------------------------------===// protocol IntrusiveListNode : class { var next : Self { get } } final class ClassNode : IntrusiveListNode { var next : ClassNode = ClassNode() } struct StructNode : IntrusiveListNode { // expected-error{{non-class type 'StructNode' cannot conform to class protocol 'IntrusiveListNode'}} // expected-error@-1{{value type 'StructNode' cannot have a stored property that references itself}} var next : StructNode } final class ClassNodeByExtension { } struct StructNodeByExtension { } extension ClassNodeByExtension : IntrusiveListNode { var next : ClassNodeByExtension { get { return self } set {} } } extension StructNodeByExtension : IntrusiveListNode { // expected-error{{non-class type 'StructNodeByExtension' cannot conform to class protocol 'IntrusiveListNode'}} var next : StructNodeByExtension { get { return self } set {} } } final class GenericClassNode<T> : IntrusiveListNode { var next : GenericClassNode<T> = GenericClassNode() } struct GenericStructNode<T> : IntrusiveListNode { // expected-error{{non-class type 'GenericStructNode<T>' cannot conform to class protocol 'IntrusiveListNode'}} // expected-error@-1{{value type 'GenericStructNode<T>' cannot have a stored property that references itself}} var next : GenericStructNode<T> } // Refined protocols inherit class-ness protocol IntrusiveDListNode : IntrusiveListNode { var prev : Self { get } } final class ClassDNode : IntrusiveDListNode { var prev : ClassDNode = ClassDNode() var next : ClassDNode = ClassDNode() } struct StructDNode : IntrusiveDListNode { // expected-error{{non-class type 'StructDNode' cannot conform to class protocol 'IntrusiveDListNode'}} // expected-error@-1{{non-class type 'StructDNode' cannot conform to class protocol 'IntrusiveListNode'}} // expected-error@-2{{value type 'StructDNode' cannot have a stored property that references itself}} var prev : StructDNode var next : StructDNode } @objc protocol ObjCProtocol { func foo() // expected-note{{protocol requires function 'foo()' with type '() -> ()'}} } protocol NonObjCProtocol : class { //expected-note{{protocol 'NonObjCProtocol' declared here}} func bar() } class DoesntConformToObjCProtocol : ObjCProtocol { // expected-error{{type 'DoesntConformToObjCProtocol' does not conform to protocol 'ObjCProtocol'}} } @objc protocol ObjCProtocolRefinement : ObjCProtocol { } @objc protocol ObjCNonObjCProtocolRefinement : NonObjCProtocol { } //expected-error{{@objc protocol 'ObjCNonObjCProtocolRefinement' cannot refine non-@objc protocol 'NonObjCProtocol'}} // <rdar://problem/16079878> protocol P1 { associatedtype Assoc // expected-note 2{{protocol requires nested type 'Assoc'}} } protocol P2 { } struct X3<T : P1> where T.Assoc : P2 {} struct X4 : P1 { // expected-error{{type 'X4' does not conform to protocol 'P1'}} func getX1() -> X3<X4> { return X3() } } protocol ShouldntCrash { // rdar://16109996 let fullName: String { get } // expected-error {{'let' declarations cannot be computed properties}} // <rdar://problem/17200672> Let in protocol causes unclear errors and crashes let fullName2: String // expected-error {{immutable property requirement must be declared as 'var' with a '{ get }' specifier}} // <rdar://problem/16789886> Assert on protocol property requirement without a type var propertyWithoutType { get } // expected-error {{type annotation missing in pattern}} // expected-error@-1 {{computed property must have an explicit type}} {{26-26=: <# Type #>}} } // rdar://problem/18168866 protocol FirstProtocol { weak var delegate : SecondProtocol? { get } // expected-error{{'weak' may only be applied to class and class-bound protocol types, not 'SecondProtocol'}} } protocol SecondProtocol { func aMethod(_ object : FirstProtocol) } // <rdar://problem/19495341> Can't upcast to parent types of type constraints without forcing class C1 : P2 {} func f<T : C1>(_ x : T) { _ = x as P2 } class C2 {} func g<T : C2>(_ x : T) { x as P2 // expected-error{{'T' is not convertible to 'P2'; did you mean to use 'as!' to force downcast?}} {{5-7=as!}} } class C3 : P1 {} // expected-error{{type 'C3' does not conform to protocol 'P1'}} func h<T : C3>(_ x : T) { _ = x as P1 // expected-error{{protocol 'P1' can only be used as a generic constraint because it has Self or associated type requirements}} } protocol P4 { associatedtype T // expected-note {{protocol requires nested type 'T'}} } class C4 : P4 { // expected-error {{type 'C4' does not conform to protocol 'P4'}} associatedtype T = Int // expected-error {{associated types can only be defined in a protocol; define a type or introduce a 'typealias' to satisfy an associated type requirement}} {{3-17=typealias}} }
apache-2.0
16c571651646fab1fb1009dc54083fd4
34.498943
232
0.651004
4.531984
false
false
false
false
apple/swift
test/Parse/ternary_expr.swift
2
3441
// RUN: %target-swift-frontend -dump-ast %s | %FileCheck %s // CHECK: (func_decl{{.*}}"r13756261(_:_:)" func r13756261(_ x: Bool, _ y: Int) -> Int { // CHECK: (ternary_expr // CHECK: (declref_expr // CHECK: (ternary_expr // CHECK: (declref_expr // CHECK: (ternary_expr // CHECK: (declref_expr // CHECK: (declref_expr return (x) ? y : (x) ? y : (x) ? y : y } // CHECK: (func_decl{{.*}}"r13756221(_:_:)" func r13756221(_ x: Bool, _ y: Int) -> Int { // CHECK: (ternary_expr // CHECK: (declref_expr // CHECK: (ternary_expr // CHECK: (declref_expr // CHECK: (ternary_expr // CHECK: (declref_expr // CHECK: (declref_expr return (x) ? y : (x) ? y : (x) ? y : y } // CHECK: (func_decl{{.*}}"telescoping_if(_:_:)" func telescoping_if(_ x: Bool, _ y: Int) -> Int { // CHECK: (ternary_expr // CHECK: (ternary_expr // CHECK: (ternary_expr // CHECK: (declref_expr // CHECK: (declref_expr // CHECK: (declref_expr // CHECK: (declref_expr return (x) ? (x) ? (x) ? y : y : y : y } // Operator with precedence above ? : infix operator +>> : Rightwards precedencegroup Rightwards { associativity: left higherThan: TernaryPrecedence } // Operator with precedence below ? : infix operator +<< : Leftwards precedencegroup Leftwards { associativity: left lowerThan: TernaryPrecedence } // Operator with precedence equal to ? : infix operator +== : TernaryPrecedence func +>> (x: Bool, y: Bool) -> Bool {} func +<< (x: Bool, y: Bool) -> Bool {} func +== (x: Bool, y: Bool) -> Bool {} // CHECK: (func_decl{{.*}}"prec_above(_:_:_:)" func prec_above(_ x: Bool, _ y: Bool, _ z: Bool) -> Bool { // (x +>> y) ? (y +>> z) : ((x +>> y) ? (y +>> z) : (x +>> y)) // CHECK: (ternary_expr // CHECK: (binary_expr // CHECK: (binary_expr // CHECK: (ternary_expr // CHECK: (binary_expr // CHECK: (binary_expr // CHECK: (binary_expr return x +>> y ? y +>> z : x +>> y ? y +>> z : x +>> y } // CHECK: (func_decl{{.*}}"prec_below(_:_:_:)" func prec_below(_ x: Bool, _ y: Bool, _ z: Bool) -> Bool { // The middle arm of the ternary is max-munched, so this is: // ((x +<< (y ? (y +<< z) : x)) +<< (y ? (y +<< z) : x)) +<< y // CHECK: (binary_expr // CHECK: (binary_expr // CHECK: (binary_expr // CHECK: (declref_expr // CHECK: (ternary_expr // CHECK: (binary_expr // CHECK: (declref_expr // CHECK: (ternary_expr // CHECK: (binary_expr // CHECK: (declref_expr // CHECK: (declref_expr return x +<< y ? y +<< z : x +<< y ? y +<< z : x +<< y } // CHECK: (func_decl{{.*}}"prec_equal(_:_:_:)" func prec_equal(_ x: Bool, _ y: Bool, _ z: Bool) -> Bool { // The middle arm of the ternary is max-munched, so this is: // x +== (y ? (y +== z) : (x +== (y ? (y +== z) : (x +== y)))) // CHECK: (binary_expr // CHECK: (declref_expr // CHECK: (ternary_expr // CHECK: (binary_expr // CHECK: (declref_expr // CHECK: (declref_expr // CHECK: (binary_expr // CHECK: (declref_expr // CHECK: (ternary_expr // CHECK: (binary_expr // CHECK: (declref_expr // CHECK: (declref_expr // CHECK: (binary_expr // CHECK: (declref_expr // CHECK: (declref_expr return x +== y ? y +== z : x +== y ? y +== z : x +== y }
apache-2.0
d05b5665d5c45b96d66902c139971e2d
28.921739
64
0.509445
2.974071
false
false
false
false
sonsongithub/reddift
application/CommentContainerCellar.swift
1
20108
// // CommentContainerCellar.swift // reddift // // Created by sonson on 2016/03/14. // Copyright © 2016年 sonson. All rights reserved. // import reddift import Foundation let CommentContainerCellarDidLoadCommentsName = Notification.Name(rawValue: "CommentContainerCellarDidLoadComments") class CommentContainerCellar { static let reloadIndicesKey = "ReloadIndices" static let insertIndicesKey = "InsertIndices" static let deleteIndicesKey = "DeleteIndices" static let errorKey = "Error" static let initialLoadKey = "ReloadData" var link: Link = Link(id: "") var loading = false var containers: [CommentContainable] = [] var sort: CommentSort = .controversial /// Shared session configuration var sessionConfiguration: URLSessionConfiguration { get { let configuration = URLSessionConfiguration.default configuration.timeoutIntervalForRequest = 30 configuration.timeoutIntervalForResource = 30 return configuration } } /// Thumbnail var thumbnails: [Thumbnail] { get { return containers .compactMap({$0 as? CommentContainer}) .flatMap({$0.thumbnails}) } } /** Initialize CommentContainerCellar. - parameter link: To be written. - parameter delegate: To be written. - returns: To be written. */ init(link: Link?) { if let link = link { self.link = link } } /// func layout(with width: CGFloat, fontSize: CGFloat) { self.containers.forEach({$0.layout(with: width, fontSize: fontSize)}) } /** Expand child contents of the Thing objects. - parameter things: Array of Thing objects. The all child objects of the elements of the specified array will be expanded. - parameter width: Width of comment view. It is required to layout comment contents. - parameter depth: The depth of current Thing object in the specified array. */ func expandIncommingComments(things: [Thing], width: CGFloat, depth: Int = 1) -> [CommentContainable] { let incomming: [(Thing, Int)] = things .filter { $0 is Comment || $0 is More } .flatMap { reddift.extendAllReplies(in: $0, current: depth) } let list: [CommentContainable] = incomming.compactMap({ if $0.0 is More && $0.0.id == "_" { return nil } do { return try CommentContainable.createContainer(with: $0.0, depth: $0.1, width: width) } catch { return nil } }) return list } func appendNewComment(_ newComment: Comment, to parentComment: Comment?, width: CGFloat) -> IndexPath? { if let parentComment = parentComment { if let index = containers.index(where: {$0.thing.name == parentComment.name}) { let contaier = containers[index] do { let newContainer = try CommentContainable.createContainer(with: newComment, depth: contaier.depth + 1, width: width) containers.insert(newContainer, at: index + 1) return IndexPath(row: index + 1, section: 0) } catch { print(error) } } } else { do { let newContainer = try CommentContainable.createContainer(with: newComment, depth: 1, width: width) containers.append(newContainer) return IndexPath(row: containers.count - 1, section: 0) } catch { print(error) } } return nil } /** Starts to download More contents at specified index. This method is called when user selects a more cell. - parameter index: Index of contents array. This index is made from selected IndexPath object. - parameter width: Width of comment view. It is required to layout comment contents. */ func downloadChildComments(of moreContainer: MoreContainer, index: Int, width: CGFloat) { if moreContainer.isLoading { return } moreContainer.isLoading = true NotificationCenter.default.post(name: CommentContainerCellarDidLoadCommentsName, object: nil, userInfo: [CommentContainerCellar.reloadIndicesKey: [IndexPath(row: index, section: 0)]]) do { let children = moreContainer.more.children.reversed() as [String] try UIApplication.appDelegate()?.session?.getArticles(link, sort: sort, comments: children, completion: { (result) -> Void in moreContainer.isLoading = false switch result { case .failure(let error): NotificationCenter.default.post(name: CommentContainerCellarDidLoadCommentsName, object: nil, userInfo: [CommentContainerCellar.errorKey: error]) case .success(let tuple): let things: [Thing] = tuple.1.children.filter {($0 is Comment) || ($0 is More)} let temp = self.expandIncommingComments(things: things, width: width, depth: moreContainer.depth) self.prefetch(containers: temp) DispatchQueue.main.async(execute: { () -> Void in if let targetIndex = self.containers.index(where: {$0 === moreContainer}) { self.containers.remove(at: targetIndex) self.containers.insert(contentsOf: temp, at: targetIndex) var reloadIndices: [IndexPath] = [] var insertIndices: [IndexPath] = [] var deleteIndices: [IndexPath] = [] if temp.count == 0 { deleteIndices.append(IndexPath(row: targetIndex, section: 0)) } else if temp.count == 1 { reloadIndices.append(IndexPath(row: targetIndex, section: 0)) } else if temp.count > 1 { reloadIndices.append(IndexPath(row: targetIndex, section: 0)) insertIndices += (targetIndex + 1 ..< targetIndex + temp.count).map {IndexPath(row: $0, section: 0)} } NotificationCenter.default.post(name: CommentContainerCellarDidLoadCommentsName, object: nil, userInfo: [ CommentContainerCellar.reloadIndicesKey: reloadIndices, CommentContainerCellar.insertIndicesKey: insertIndices, CommentContainerCellar.deleteIndicesKey: deleteIndices ]) } }) } }) } catch { } } /** Starts to download Comment contents at specified index. This method is called when user selects a comment cell. - parameter index: Index of contents array. This index is made from selected IndexPath object. - parameter width: Width of comment view. It is required to layout comment contents. */ func downloadChildComments(of commentContainer: CommentContainer, index: Int, width: CGFloat) { if commentContainer.isLoading || !commentContainer.comment.isExpandable { return } commentContainer.isLoading = true NotificationCenter.default.post(name: CommentContainerCellarDidLoadCommentsName, object: nil, userInfo: [CommentContainerCellar.reloadIndicesKey: [IndexPath(row: index, section: 0)]]) do { try UIApplication.appDelegate()?.session?.getArticles(link, sort: .confidence, comments: [commentContainer.comment.id], completion: { (result) -> Void in commentContainer.isLoading = false switch result { case .failure(let error): NotificationCenter.default.post(name: CommentContainerCellarDidLoadCommentsName, object: nil, userInfo: [CommentContainerCellar.errorKey: error]) case .success(let (_, listing)): if listing.children.count == 1 && listing.children[0].id == commentContainer.comment.id && listing.children[0] is Comment { let temp = self.expandIncommingComments(things: listing.children, width: width, depth: commentContainer.depth) self.prefetch(containers: temp) DispatchQueue.main.async(execute: { () -> Void in if let targetIndex = self.containers.index(where: {$0 === commentContainer}) { self.containers.remove(at: targetIndex) self.containers.insert(contentsOf: temp, at: targetIndex) let reloadIndices = [IndexPath(row: targetIndex, section: 0)] var insertIndices: [IndexPath] = [] if temp.count > 1 { insertIndices += (targetIndex + 1 ..< targetIndex + temp.count).map {IndexPath(row: $0, section: 0)} } NotificationCenter.default.post(name: CommentContainerCellarDidLoadCommentsName, object: nil, userInfo: [CommentContainerCellar.reloadIndicesKey: reloadIndices, CommentContainerCellar.insertIndicesKey: insertIndices]) } }) } else { NotificationCenter.default.post(name: CommentContainerCellarDidLoadCommentsName, object: nil, userInfo: [CommentContainerCellar.errorKey: NSError(domain: "", code: 0, userInfo: nil)]) } } }) } catch { } } /** Starts to download More or Comment contents at specified index. This method is called when user selects a more or comment cell. - parameter index: Index of contents array. This index is made from selected IndexPath object. - parameter width: Width of comment view. It is required to layout comment contents. */ func download(index: Int, width: CGFloat) { switch containers[index] { case (let moreContainer as MoreContainer): downloadChildComments(of: moreContainer, index: index, width: width) case (let commentContainer as CommentContainer): downloadChildComments(of: commentContainer, index: index, width: width) default: print("error") } } /** Get start index and count of child element of the target comment. - parameter index: Index of target comment. - returns: Tuple. Start index of child elements and count of child elements. */ func indexOfChildren(index: Int) -> (Int, Int) { let commentThing = containers[index] var childIndex = 0 var childCount = 0 if index == containers.count - 1 { // this comment is the last object. } else if commentThing.depth == containers[index + 1].depth { // there are not any child objects. } else { // there are one or more child comments of the target. // so, search the index of the children. childIndex = index + 1 for i in (index + 1)..<containers.count { let c = containers[i] if c.depth > commentThing.depth { childCount = childCount + 1 } else { break } } } return (childIndex, childCount) } /** Collapse child elements that are specified by start index and count. - parameter fromIndex: Start index of the elements that will be collapsed. - parameter count: Count of the elements that will be collapsed. */ func collapseChildComments(from: Int, count: Int) { for i in from..<from + count { containers[i].isHidden = true } } /** Make child elements that are specified by start index and count visible. - parameter fromIndex: Start index of the elements that will be made visible. - parameter count: Count of the elements that will be made visible. */ func expandChildComments(from: Int, count: Int) { var prevDepth = containers[from].depth var prevIsHidden = false var prevIsCollapsed = false let depthOffset = containers[from].depth var isHiddenFlagStack: [Bool] = [] for i in from..<from + count { if prevDepth == containers[i].depth { // set invisible when prior element is invisible. containers[i].isHidden = prevIsHidden } else if prevDepth < containers[i].depth { // push stack when content's depth will be dropped down. if !prevIsCollapsed && !prevIsHidden { containers[i].isHidden = false isHiddenFlagStack.append(false) } else if !prevIsCollapsed && prevIsHidden { containers[i].isHidden = true isHiddenFlagStack.append(true) } else if prevIsCollapsed && !prevIsHidden { containers[i].isHidden = true isHiddenFlagStack.append(false) } else if prevIsCollapsed && !prevIsHidden { containers[i].isHidden = true isHiddenFlagStack.append(true) } } else { // pop stack when content's depth will be rised. let d = containers[i].depth - depthOffset containers[i].isHidden = isHiddenFlagStack[d] for _ in 0..<isHiddenFlagStack.count - d { isHiddenFlagStack.removeLast() } } prevIsHidden = containers[i].isHidden prevIsCollapsed = containers[i].isCollapsed prevDepth = containers[i].depth } } /** Toggle between expanding and closing children of the target comment. - parameter index: Index of the target comment. */ func toggleExpand(index: Int) { // toggle close flag and obtain child elements. containers[index].isCollapsed = !containers[index].isCollapsed let (childIndex, childCount) = indexOfChildren(index: index) // IndexPath array to send the table view. let reloadIndices = (index..<index + childCount + 1).map({IndexPath(row: $0, section: 0)}) // Update number of children, in order to display "x children" label. // This number includes own. containers[index].numberOfChildren = childCount + 1 // set collapsed flag of children if childCount > 0 { if !containers[index].isCollapsed { expandChildComments(from: childIndex, count: childCount) } else { collapseChildComments(from: childIndex, count: childCount) } } // Execute reloading table view. NotificationCenter.default.post(name: CommentContainerCellarDidLoadCommentsName, object: nil, userInfo: [ CommentContainerCellar.reloadIndicesKey: reloadIndices ]) } /** Try to generate image url list from link to imgur.com from contents which is included by the specified array. This method checks whether the contents at the specified index has url to imgur.com or not. If it has the url, this method downloads html of the url and extend image url list. - parameter index: The index of CommentContainer which you want to expand its image url ist. */ func prefetch(containers: [CommentContainable]) { containers.forEach({ if let commentContainer = $0 as? CommentContainer { for i in 0..<commentContainer.urlContainer.count { if let urlContainer = commentContainer.urlContainer[i] as? ImgurURLInComment { let url = urlContainer.sourceURL.httpsSchemaURL var request = URLRequest(url: url) request.addValue("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/601.1.56 (KHTML, like Gecko) Version/9.0 Safari/601.1.56", forHTTPHeaderField: "User-Agent") let session: URLSession = URLSession(configuration: self.sessionConfiguration) let task = session.dataTask(with: request, completionHandler: { (data, _, _) -> Void in if let data = data, let decoded = String(data: data, encoding: .utf8) { if !decoded.is404OfImgurcom { var new = ImgurURLInComment(sourceURL: url, parentID: commentContainer.comment.id) new.imageURL = decoded.extractImgurImageURL(parentID: commentContainer.comment.id) commentContainer.urlContainer[i] = new DispatchQueue.main.async(execute: { () -> Void in if let targetIndex = self.containers.index(where: {$0 === commentContainer}) { let reloadIndices = [IndexPath(row: targetIndex, section: 0)] NotificationCenter.default.post(name: CommentContainerCellarDidLoadCommentsName, object: nil, userInfo: [CommentContainerCellar.reloadIndicesKey: reloadIndices]) } }) } } }) task.resume() } } } }) } /** Start to load comments and link. - parameter width: Width of comment view. It is required to layout comment contents. */ func load(width: CGFloat) { do { try UIApplication.appDelegate()?.session?.getArticles(link, sort: sort, comments: nil, limit: nil, completion: { (result) -> Void in switch result { case .failure(let error): print(error) case .success(let tuple): let listing0 = tuple.0 if listing0.children.count == 1 { if let link = listing0.children[0] as? Link { if !link.selftextHtml.isEmpty { do { let comment = Comment(link: link) let c = try CommentContainer.createContainer(with: comment, depth: 1, width: width) c.isTop = true self.containers.append(c) } catch { } } } } let listing = tuple.1 self.containers.append(contentsOf: self.expandIncommingComments(things: listing.children, width: width)) self.prefetch(containers: self.containers) DispatchQueue.main.async(execute: { () -> Void in NotificationCenter.default.post(name: CommentContainerCellarDidLoadCommentsName, object: nil, userInfo: [CommentContainerCellar.initialLoadKey: true]) }) } }) } catch { } } }
mit
c956be22d3c67cfaa081d4bdb74deb49
47.213429
249
0.556628
5.320191
false
false
false
false
KyoheiG3/RxSwift
RxSwift/Observables/Implementations/Debounce.swift
1
2780
// // Debounce.swift // RxSwift // // Created by Krunoslav Zaher on 9/11/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import Foundation class DebounceSink<O: ObserverType> : Sink<O> , ObserverType , LockOwnerType , SynchronizedOnType { typealias Element = O.E typealias ParentType = Debounce<Element> private let _parent: ParentType let _lock = NSRecursiveLock() // state private var _id = 0 as UInt64 private var _value: Element? = nil let cancellable = SerialDisposable() init(parent: ParentType, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { let subscription = _parent._source.subscribe(self) return Disposables.create(subscription, cancellable) } func on(_ event: Event<Element>) { synchronizedOn(event) } func _synchronized_on(_ event: Event<Element>) { switch event { case .next(let element): _id = _id &+ 1 let currentId = _id _value = element let scheduler = _parent._scheduler let dueTime = _parent._dueTime let d = SingleAssignmentDisposable() self.cancellable.disposable = d d.setDisposable(scheduler.scheduleRelative(currentId, dueTime: dueTime, action: self.propagate)) case .error: _value = nil forwardOn(event) dispose() case .completed: if let value = _value { _value = nil forwardOn(.next(value)) } forwardOn(.completed) dispose() } } func propagate(_ currentId: UInt64) -> Disposable { _lock.lock(); defer { _lock.unlock() } // { let originalValue = _value if let value = originalValue, _id == currentId { _value = nil forwardOn(.next(value)) } // } return Disposables.create() } } class Debounce<Element> : Producer<Element> { fileprivate let _source: Observable<Element> fileprivate let _dueTime: RxTimeInterval fileprivate let _scheduler: SchedulerType init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) { _source = source _dueTime = dueTime _scheduler = scheduler } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = DebounceSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
mit
8a34136a441e7b6509e1ad4f697ae617
25.721154
144
0.593379
4.710169
false
false
false
false
DrabWeb/Komikan
Komikan/Komikan/KMMangaGroupItem.swift
1
1884
// // KMMangaGroupItem.swift // Komikan // // Created by Seth on 2016-03-16. // import Cocoa class KMMangaGroupItem: NSObject { /// The image to display as a "cover" for this group var groupImage : NSImage = NSImage(named: "NSCaution")!; /// The name of the group var groupName : String = "Error"; /// The type of group this item is var groupType : KMMangaGroupType = KMMangaGroupType.series; /// The label for how many items are in this group var countLabel : String = "(nil)"; // Blank init override init() { super.init(); self.groupImage = NSImage(named: "NSCaution")!; self.groupName = self.groupName + self.countLabel; } // Init with an image init(groupImage : NSImage) { self.groupImage = groupImage; self.groupName = self.groupName + self.countLabel; } // Init with an image and group name init(groupImage : NSImage, groupName : String) { self.groupImage = groupImage; self.groupName = groupName; self.groupName = self.groupName + self.countLabel; } // Init with an image, group name and group type init(groupImage : NSImage, groupName : String, groupType : KMMangaGroupType) { self.groupImage = groupImage; self.groupName = groupName; self.groupType = groupType; self.groupName = self.groupName + self.countLabel; } // Init with an image, group name, group type and count label init(groupImage : NSImage, groupName : String, groupType : KMMangaGroupType, countLabel : String) { self.groupImage = groupImage; self.groupName = groupName; self.groupType = groupType; self.countLabel = countLabel; self.groupName = self.groupName + self.countLabel; } }
gpl-3.0
9192f85b115485d0c9f18301e45ebf9d
27.984615
103
0.613588
4.243243
false
false
false
false
akihiko-fujii/dualmap_af
mapruler1/mapruler1/citySetFromRegionViewController.swift
2
9075
// // citySetFromRegionViewController.swift // mapruler1 // // Created by af2 on 3/5/16. // Copyright © 2016 af2. All rights reserved. // import UIKit class citySetFromRegionViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var regionName: UILabel! @IBOutlet var myTableView: UITableView! override func viewDidLoad() { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate super.viewDidLoad() regionName.text = appDelegate.choosingCityRegion // Do any additional setup after loading the view. let barHeight: CGFloat = 60 let displayWidth: CGFloat = self.view.frame.width let displayHeight: CGFloat = self.view.frame.height myTableView = UITableView(frame: CGRect(x: 0, y: barHeight, width: displayWidth, height: displayHeight - barHeight)) myTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "MyCell") myTableView.dataSource = self myTableView.delegate = self self.view.addSubview(myTableView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate var dict:Dictionary = Dictionary<String,String>() if(appDelegate.choosingCityRegion=="EastAsia"){ if(indexPath.row<appDelegate.dictionaries_eastAsia.count){ dict = appDelegate.dictionaries_eastAsia[indexPath.row] } } if(appDelegate.choosingCityRegion=="Africa"){ if(indexPath.row<appDelegate.dictionaries_Africa.count){ dict = appDelegate.dictionaries_Africa[indexPath.row] } } if(appDelegate.choosingCityRegion=="NorthAmerica"){ if(indexPath.row<appDelegate.dictionaries_northAmerica.count){ dict = appDelegate.dictionaries_northAmerica[indexPath.row] } } if(appDelegate.choosingCityRegion=="SouthAmerica"){ if(indexPath.row<appDelegate.dictionaries_southAmerica.count){ dict = appDelegate.dictionaries_southAmerica[indexPath.row] } } if(appDelegate.choosingCityRegion=="Pacific"){ if(indexPath.row<appDelegate.dictionaries_Pacific.count){ dict = appDelegate.dictionaries_Pacific[indexPath.row] } } if(appDelegate.choosingCityRegion=="Europe"){ if(indexPath.row<appDelegate.dictionaries_Europe.count){ dict = appDelegate.dictionaries_Europe[indexPath.row] } } if(appDelegate.choosingCityRegion=="SouthAsia"){ if(indexPath.row<appDelegate.dictionaries_southAsia.count){ dict = appDelegate.dictionaries_southAsia[indexPath.row] } } if(appDelegate.choosingCityRegion=="Poles"){ if(indexPath.row<appDelegate.dictionaries_Poles.count){ dict = appDelegate.dictionaries_Poles[indexPath.row] } } // }else{ // // if(indexPath.row<appDelegate.dictionaries.count){ // dict = appDelegate.dictionaries[indexPath.row] // } // } // let myDoubl = (dict["latitude"]! as NSString).doubleValue if(appDelegate.choosingCity1orCity2==1){ // set the city1 name. print("selected city is",dict["cityName"]!) appDelegate.selectedCityName1 = dict["cityName"]! // set the value of city1 latitude. let numberFormatter = NSNumberFormatter() var number = numberFormatter.numberFromString(dict["latitude"]!) appDelegate.selectedCityLatitude1 = number!.doubleValue // set the value of city1 longitude. number = numberFormatter.numberFromString(dict["longitude"]!) appDelegate.selectedCityLongitude1 = number!.doubleValue // set the value of city1 scale. number = numberFormatter.numberFromString(dict["scale"]!) appDelegate.selectedCityScale1 = number!.doubleValue }else{ // set the city2 name. print("selected city is",dict["cityName"]!) appDelegate.selectedCityName2 = dict["cityName"]! // set the value of city2 latitude. let numberFormatter = NSNumberFormatter() var number = numberFormatter.numberFromString(dict["latitude"]!) appDelegate.selectedCityLatitude2 = number!.doubleValue // set the value of city2 longitude. number = numberFormatter.numberFromString(dict["longitude"]!) appDelegate.selectedCityLongitude2 = number!.doubleValue // set the value of city2 scale. number = numberFormatter.numberFromString(dict["scale"]!) appDelegate.selectedCityScale2 = number!.doubleValue } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate if(appDelegate.choosingCityRegion=="EastAsia"){ return appDelegate.dictionaries_eastAsia.count } if(appDelegate.choosingCityRegion=="Europe"){ return appDelegate.dictionaries_Europe.count } if(appDelegate.choosingCityRegion=="Poles"){ return appDelegate.dictionaries_Poles.count } if(appDelegate.choosingCityRegion=="SouthAsia"){ return appDelegate.dictionaries_southAsia.count } if(appDelegate.choosingCityRegion=="Africa"){ return appDelegate.dictionaries_Africa.count } if(appDelegate.choosingCityRegion=="NorthAmerica"){ return appDelegate.dictionaries_northAmerica.count } if(appDelegate.choosingCityRegion=="SouthAmerica"){ return appDelegate.dictionaries_southAmerica.count } if(appDelegate.choosingCityRegion=="Pacific"){ return appDelegate.dictionaries_Pacific.count } return 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath) cell.backgroundColor = UIColor.grayColor() cell.textLabel?.textColor = UIColor.whiteColor() let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate var dict:Dictionary = Dictionary<String,String>() if(indexPath.row<appDelegate.dictionaries.count){ // ここを変える dict = appDelegate.dictionaries[indexPath.row] if(appDelegate.choosingCityRegion=="EastAsia"){ dict = appDelegate.dictionaries_eastAsia[indexPath.row] }else if(appDelegate.choosingCityRegion=="SouthAsia"){ dict = appDelegate.dictionaries_southAsia[indexPath.row] }else if(appDelegate.choosingCityRegion=="Africa"){ dict = appDelegate.dictionaries_Africa[indexPath.row] }else if(appDelegate.choosingCityRegion=="NorthAmerica"){ dict = appDelegate.dictionaries_northAmerica[indexPath.row] }else if(appDelegate.choosingCityRegion=="SouthAmerica"){ dict = appDelegate.dictionaries_southAmerica[indexPath.row] }else if(appDelegate.choosingCityRegion=="Pacific"){ dict = appDelegate.dictionaries_Pacific[indexPath.row] }else if(appDelegate.choosingCityRegion=="Poles"){ dict = appDelegate.dictionaries_Poles[indexPath.row] }else if(appDelegate.choosingCityRegion=="Europe"){ dict = appDelegate.dictionaries_Europe[indexPath.row] } } // let myDoubl = (dict["latitude"]! as NSString).doubleValue cell.textLabel!.text = dict["cityName"] // cell.imageView!.image = UIImage(named: String(dict["countryName"])) return cell } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-2.0
683a6d995e3b96249d0c5f9b8940bf9c
38.572052
124
0.622158
5.352628
false
false
false
false
glessard/swift-channels
ChannelsTests/SelectExamples.swift
1
4487
// // SelectTests.swift // Channels // // Created by Guillaume Lessard on 2015-01-15. // Copyright (c) 2015 Guillaume Lessard. All rights reserved. // import Darwin import Foundation import XCTest @testable import Channels class SelectExamples: XCTestCase { func testSelect() { let a: (tx: Sender<Int>, rx: Receiver<Int>) = Channel<Int>.Make(0) let b: (tx: Sender<Int>, rx: Receiver<Int>) = Channel<Int>.Make(1) let c: (tx: Sender<Int>, rx: Receiver<Int>) = Channel.Wrap(SBufferedChan<Int>.Make(1)) let d: (tx: Sender<Int>, rx: Receiver<Int>) = Channel<Int>.Make(2) let e: (tx: Sender<Int>, rx: Receiver<Int>) = Channel<Int>.Make(5) let channels = [a,b,c,d,e] let iterations = 10_000 async { let senders = channels.map { $0.tx } for _ in 0..<iterations { let index = Int(arc4random_uniform(UInt32(senders.count))) senders[index] <- index } for sender in senders { sender.close() } } var messages = Array(repeating: 0, count: channels.count) let selectables = channels.map { $0.rx as Selectable } while let selection = select_chan(selectables) { switch selection { case a.rx: if let p = a.rx.extract(selection) { messages[p] += 1 } case b.rx: if let p = b.rx.extract(selection) { messages[p] += 1 } case c.rx: if let p = c.rx.extract(selection) { messages[p] += 1 } case d.rx: if let p = d.rx.extract(selection) { messages[p] += 1 } case e.rx: if let p = e.rx.extract(selection) { messages[p] += 1 } default: continue // missed selection } } let i = messages.reduce(0, +) syncprint("\(messages), \(i) total messages.") syncprintwait() XCTAssert(i == iterations, "Received \(i) messages; expected \(iterations)") } func testRandomBits() { let c0: (tx: Sender<Bool>, rx: Receiver<Bool>) = Channel<Bool>.Make(8) let c1: (tx: Sender<Bool>, rx: Receiver<Bool>) = Channel<Bool>.Make(8) DispatchQueue.global(qos: DispatchQoS.QoSClass(rawValue: qos_class_self())!).async { for _ in 0..<8 { if let selection = select_chan(c0.tx, c1.tx) { switch selection.id { case c0.tx: c0.tx.insert(selection, newElement: false) case c1.tx: c1.tx.insert(selection, newElement: true) default: continue } } } c0.tx.close() c1.tx.close() } let merged = merge(c0.rx, c1.rx) while let b = <-merged { print("\(b ? 0:1)", terminator: "") } print("") } func testSendsAndReceives() { let capacity = 5 let c: (tx: Sender<Int>, rx: Receiver<Int>) = Channel<Int>.Make(capacity) var cap = 0 var count = 0 while let selection = select_chan([c.tx, c.rx], preventBlocking: false) { switch selection.id { case c.tx: if c.tx.insert(selection, newElement: count) { cap += 1 print(cap, terminator: "") count += 1 if count > 30 { c.tx.close() } } else { XCTFail("Attempted to insert into a full channel (probably)") } case c.rx: if let _ = c.rx.extract(selection) { cap -= 1 print(cap, terminator: "") } else { XCTFail("Attempted to extract from an empty channel (probably)") } default: continue } XCTAssert(cap >= 0 && cap <= capacity) } print("") } func testNonBlockingSends() { let c1 = Channel<UInt32>.Make() let c2 = Channel<UInt32>.Make() var attempts = 0 DispatchQueue.global(qos: DispatchQoS.QoSClass(rawValue: qos_class_self())!).async { while let selection = select_chan([c1.tx,c2.tx], preventBlocking: true) { switch selection { case c1.tx: c1.tx.insert(selection, newElement: arc4random()) case c2.tx: c2.tx.insert(selection, newElement: arc4random()) default: break } attempts += 1 guard attempts < 1000 else { break } usleep(1) } c1.tx.close() c2.tx.close() } let merged = merge(c1.rx, c2.rx) var messages = 0 while let _ = <-merged { messages += 1 usleep(100) } print("Sent \(messages) messages in \(attempts) attempts") } }
mit
2eaf488676347c62130adb24493a7385
22.867021
90
0.550925
3.572452
false
false
false
false
ndevenish/KerbalHUD
KerbalHUD/Textures.swift
1
1962
// // Textures.swift // KerbalHUD // // Created by Nicholas Devenish on 27/08/2015. // Copyright © 2015 Nicholas Devenish. All rights reserved. // import Foundation import GLKit struct Texture : Equatable { let glk : GLKTextureInfo? let name : GLuint let target : GLenum let size : Size2D<Int>? } func ==(first: Texture, second: Texture) -> Bool { return first.name == second.name } extension Texture { static var None : Texture { return Texture(glk: nil, name: 0, target: GLenum(GL_TEXTURE_2D), size: nil) } init (glk: GLKTextureInfo) { self.glk = glk self.name = glk.name self.target = glk.target self.size = Size2D(w: Int(glk.width), h: Int(glk.height)) } init (name: GLuint, width: UInt, height: UInt, target: GLenum = GLenum(GL_TEXTURE_2D)) { self.glk = nil self.name = name self.target = target self.size = Size2D(w: Int(width), h: Int(height)) } func debugName(name : String) { glLabelObjectEXT(GLenum(GL_TEXTURE), self.name, 0, name) } } extension DrawingTools { func deleteTexture(texture : Texture) { if texture.name != 0 { var val = texture.name glDeleteTextures(1, &val) } } } /// Builds a 1X1 white texture to use for non-texture drawing func generate1X1Texture() -> Texture { var tex : GLuint = 0 glGenTextures(1, &tex) glBindTexture(GLenum(GL_TEXTURE_2D), tex) glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), GL_REPEAT); glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), GL_REPEAT); glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GL_LINEAR); glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GL_LINEAR); var data : [GLubyte] = [255] glTexImage2D(GLenum(GL_TEXTURE_2D), 0, GL_LUMINANCE, 1, 1, 0, GLenum(GL_LUMINANCE), GLenum(GL_UNSIGNED_BYTE), &data) glBindTexture(GLenum(GL_TEXTURE_2D), 0) return Texture(name: tex, width: 1, height: 1) }
mit
6b585435a51a89c4e787b0bfd1ebca5c
27.838235
118
0.675166
3.003063
false
false
false
false
hooman/swift
test/SILGen/hop_to_executor_async_prop.swift
2
37257
// RUN: %target-swift-frontend -emit-silgen %s -module-name test -swift-version 5 -disable-availability-checking | %FileCheck --enable-var-scope %s --implicit-check-not 'hop_to_executor {{%[0-9]+}}' // REQUIRES: concurrency @propertyWrapper struct GiftWrapped<T> { private var _stored: T private var numReads : Int init(initially: T) { self._stored = initially } var wrappedValue: T { mutating get { numReads += 1 return _stored } set { _stored = newValue } } } actor Birb { private var _storage : Int = 24 var feathers : Int { _read { yield _storage } _modify { yield &_storage } } } actor Cat { @GlobalCat var leader : String { get { "Tiger" } } var storedBool : Bool = false private(set) var computedSweater : Sweater { get { return Sweater(self) } set {} } subscript(_ x : Int) -> Cat { get { self } set {} } var friend : Cat = Cat() var maybeFriend : Cat? @GiftWrapped<Birb>(initially: Birb()) var bestFriend : Birb } struct Sweater : Sendable { let owner : Cat init (_ owner : Cat) { self.owner = owner } } class CatBox { var cat : Cat = Cat() } @globalActor struct GlobalCat { static let shared : Cat = Cat() } @GlobalCat var globalBool : Bool = false @GlobalCat var someBirb : Birb { get { Birb() } set {} } // CHECK-LABEL: sil hidden [ossa] @$s4test015accessSweaterOfC03catAA0C0VAA3CatC_tYaF : $@convention(thin) @async (@guaranteed Cat) -> @owned Sweater { // CHECK: bb0([[CAT:%[0-9]+]] : @guaranteed $Cat): // CHECK: [[PREV_EXEC:%.*]] = builtin "getCurrentExecutor" // CHECK: hop_to_executor [[CAT]] : $Cat // CHECK: [[CAT_GETTER:%[0-9]+]] = class_method [[CAT]] : $Cat, #Cat.computedSweater!getter : (isolated Cat) -> () -> Sweater, $@convention(method) (@guaranteed Cat) -> @owned Sweater // CHECK: [[SWEATER1_REF:%[0-9]+]] = apply [[CAT_GETTER]]([[CAT]]) : $@convention(method) (@guaranteed Cat) -> @owned Sweater // CHECK: hop_to_executor [[PREV_EXEC]] // CHECK: [[SWEATER1:%[0-9]+]] = begin_borrow [[SWEATER1_REF]] : $Sweater // CHECK: [[SWEATER1_OWNER:%[0-9]+]] = struct_extract [[SWEATER1]] : $Sweater, #Sweater.owner // CHECK: [[CAT2_REF:%[0-9]+]] = copy_value [[SWEATER1_OWNER]] : $Cat // CHECK: end_borrow [[SWEATER1]] : $Sweater // CHECK: destroy_value [[SWEATER1_REF]] : $Sweater // CHECK: [[CAT2:%[0-9]+]] = begin_borrow [[CAT2_REF]] : $Cat // CHECK: [[PREV_EXEC:%.*]] = builtin "getCurrentExecutor" // CHECK: hop_to_executor [[CAT2]] : $Cat // CHECK: [[CAT2_FOR_LOAD:%[0-9]+]] = begin_borrow [[CAT2_REF]] : $Cat // CHECK: [[CAT2_GETTER:%[0-9]+]] = class_method [[CAT2_FOR_LOAD]] : $Cat, #Cat.computedSweater!getter : (isolated Cat) -> () -> Sweater, $@convention(method) (@guaranteed Cat) -> @owned Sweater // CHECK: [[SWEATER2_OWNER:%[0-9]+]] = apply [[CAT2_GETTER]]([[CAT2_FOR_LOAD]]) : $@convention(method) (@guaranteed Cat) -> @owned Sweater // CHECK: end_borrow [[CAT2_FOR_LOAD]] : $Cat // CHECK: end_borrow [[CAT2]] : $Cat // CHECK: hop_to_executor [[PREV_EXEC]] // CHECK: destroy_value [[CAT2_REF]] : $Cat // CHECK: return [[SWEATER2_OWNER]] : $Sweater // CHECK: } // end sil function '$s4test015accessSweaterOfC03catAA0C0VAA3CatC_tYaF' func accessSweaterOfSweater(cat : Cat) async -> Sweater { // note that Sweater is not an actor! return await cat.computedSweater.owner.computedSweater } // CHECK-LABEL: sil hidden [ossa] @$s4test26accessGlobalIsolatedMember3catSSAA3CatC_tYaF : $@convention(thin) @async (@guaranteed Cat) -> @owned String { // CHECK: bb0([[CAT:%[0-9]+]] : @guaranteed $Cat): // CHECK: [[GLOBAL_CAT_SHARED:%[0-9]+]] = function_ref @$s4test9GlobalCatV6sharedAA0C0Cvau : $@convention(thin) () -> Builtin.RawPointer // CHECK: [[GLOBAL_CAT_RAWPTR:%[0-9]+]] = apply [[GLOBAL_CAT_SHARED]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK: [[GLOBAL_CAT_ADDR:%[0-9]+]] = pointer_to_address [[GLOBAL_CAT_RAWPTR]] : $Builtin.RawPointer to [strict] $*Cat // CHECK: [[GLOBAL_CAT_REF:%[0-9]+]] = load [copy] [[GLOBAL_CAT_ADDR]] : $*Cat // CHECK: [[GLOBAL_CAT:%[0-9]+]] = begin_borrow [[GLOBAL_CAT_REF]] : $Cat // CHECK: [[PREV_EXEC:%.*]] = builtin "getCurrentExecutor" // CHECK: hop_to_executor [[GLOBAL_CAT]] : $Cat // CHECK: [[GETTER:%[0-9]+]] = class_method [[CAT]] : $Cat, #Cat.leader!getter : (Cat) -> () -> String, $@convention(method) (@guaranteed Cat) -> @owned String // CHECK: [[THE_STRING:%[0-9]+]] = apply [[GETTER]]([[CAT]]) : $@convention(method) (@guaranteed Cat) -> @owned String // CHECK: end_borrow [[GLOBAL_CAT]] : $Cat // CHECK: hop_to_executor [[PREV_EXEC]] // CHECK: destroy_value [[GLOBAL_CAT_REF]] : $Cat // CHECK: return [[THE_STRING]] : $String // CHECK: } // end sil function '$s4test26accessGlobalIsolatedMember3catSSAA3CatC_tYaF' func accessGlobalIsolatedMember(cat : Cat) async -> String { return await cat.leader } actor Dog { // CHECK-LABEL: sil hidden [ossa] @$s4test3DogC15accessGlobalVarSbyYaF : $@convention(method) @async (@guaranteed Dog) -> Bool { // CHECK: [[GLOBAL_BOOL_ADDR:%[0-9]+]] = global_addr @$s4test10globalBoolSbvp : $*Bool // CHECK: hop_to_executor [[SELF:%[0-9]+]] : $Dog // CHECK: [[SHARED_REF_FN:%[0-9]+]] = function_ref @$s4test9GlobalCatV6sharedAA0C0Cvau : $@convention(thin) () -> Builtin.RawPointer // CHECK: [[SHARED_REF:%[0-9]+]] = apply [[SHARED_REF_FN]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK: [[SHARED_CAT_ADDR:%[0-9]+]] = pointer_to_address [[SHARED_REF]] : $Builtin.RawPointer to [strict] $*Cat // CHECK: [[CAT:%[0-9]+]] = load [copy] [[SHARED_CAT_ADDR]] : $*Cat // CHECK: [[BORROWED_CAT:%[0-9]+]] = begin_borrow [[CAT]] : $Cat // CHECK: hop_to_executor [[BORROWED_CAT]] : $Cat // CHECK: [[GLOBAL_BOOL_ACCESS:%[0-9]+]] = begin_access [read] [dynamic] [[GLOBAL_BOOL_ADDR]] : $*Bool // CHECK: [[THE_BOOL:%[0-9]+]] = load [trivial] [[GLOBAL_BOOL_ACCESS]] : $*Bool // CHECK: end_access [[GLOBAL_BOOL_ACCESS]] : $*Bool // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: end_borrow [[BORROWED_CAT]] : $Cat // CHECK: destroy_value [[CAT]] : $Cat // CHECK: return [[THE_BOOL]] : $Bool // CHECK: } // end sil function '$s4test3DogC15accessGlobalVarSbyYaF' func accessGlobalVar() async -> Bool { return await globalBool } // CHECK-LABEL: sil hidden [ossa] @$s4test3DogC24accessGlobalComputedPropSiyYaF : $@convention(method) @async (@guaranteed Dog) -> Int { // CHECK: bb0([[SELF:%[0-9]+]] : @guaranteed $Dog): // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: [[SHARED_REF_FN:%[0-9]+]] = function_ref @$s4test9GlobalCatV6sharedAA0C0Cvau : $@convention(thin) () -> Builtin.RawPointer // CHECK: [[SHARED_REF:%[0-9]+]] = apply [[SHARED_REF_FN]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK: [[SHARED_CAT_ADDR:%[0-9]+]] = pointer_to_address [[SHARED_REF]] : $Builtin.RawPointer to [strict] $*Cat // CHECK: [[CAT:%[0-9]+]] = load [copy] [[SHARED_CAT_ADDR]] : $*Cat // CHECK: [[BORROWED_CAT:%[0-9]+]] = begin_borrow [[CAT]] : $Cat // CHECK: hop_to_executor [[BORROWED_CAT]] : $Cat // CHECK: [[SOMEBIRB_GETTER:%[0-9]+]] = function_ref @$s4test8someBirbAA0C0Cvg : $@convention(thin) () -> @owned Birb // CHECK: [[BIRB:%[0-9]+]] = apply [[SOMEBIRB_GETTER]]() : $@convention(thin) () -> @owned Birb // CHECK: end_borrow [[BORROWED_CAT:%[0-9]+]] : $Cat // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: [[BORROWED_BIRB:%[0-9]+]] = begin_borrow [[BIRB]] : $Birb // CHECK: hop_to_executor [[BORROWED_BIRB]] : $Birb // CHECK: [[BORROWED_BIRB_FOR_LOAD:%[0-9]+]] = begin_borrow [[BIRB]] : $Birb // CHECK: [[FEATHER_GETTER:%[0-9]+]] = class_method [[BORROWED_BIRB_FOR_LOAD]] : $Birb, #Birb.feathers!getter : (isolated Birb) -> () -> Int, $@convention(method) (@guaranteed Birb) -> Int // CHECK: [[THE_INT:%[0-9]+]] = apply [[FEATHER_GETTER]]([[BORROWED_BIRB_FOR_LOAD]]) : $@convention(method) (@guaranteed Birb) -> Int // CHECK: end_borrow [[BORROWED_BIRB_FOR_LOAD]] : $Birb // CHECK: end_borrow [[BORROWED_BIRB]] : $Birb // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: destroy_value [[BIRB]] : $Birb // CHECK: destroy_value [[CAT]] : $Cat // CHECK: return [[THE_INT]] : $Int // CHECK: } // end sil function '$s4test3DogC24accessGlobalComputedPropSiyYaF' func accessGlobalComputedProp() async -> Int { return await someBirb.feathers } // CHECK-LABEL: sil hidden [ossa] @$s4test3DogC21accessWrappedProperty3catSiAA3CatC_tYaF : $@convention(method) @async (@guaranteed Cat, @guaranteed Dog) -> Int { // CHECK: bb0([[CAT:%[0-9]+]] : @guaranteed $Cat, [[SELF:%[0-9]+]] : @guaranteed $Dog): // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: hop_to_executor [[CAT]] : $Cat // CHECK: [[CAT_GETTER:%[0-9]+]] = class_method [[CAT]] : $Cat, #Cat.bestFriend!getter : (isolated Cat) -> () -> Birb, $@convention(method) (@guaranteed Cat) -> @owned Birb // CHECK: [[BIRB_REF:%[0-9]+]] = apply [[CAT_GETTER]]([[CAT]]) : $@convention(method) (@guaranteed Cat) -> @owned Birb // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: [[BIRB:%[0-9]+]] = begin_borrow [[BIRB_REF]] : $Birb // CHECK: hop_to_executor [[BIRB]] : $Birb // CHECK: [[BIRB_FOR_LOAD:%[0-9]+]] = begin_borrow [[BIRB_REF]] : $Birb // CHECK: [[BIRB_GETTER:%[0-9]+]] = class_method [[BIRB_FOR_LOAD]] : $Birb, #Birb.feathers!getter : (isolated Birb) -> () -> Int, $@convention(method) (@guaranteed Birb) -> Int // CHECK: [[THE_INT:%[0-9]+]] = apply [[BIRB_GETTER]]([[BIRB_FOR_LOAD]]) : $@convention(method) (@guaranteed Birb) -> Int // CHECK: end_borrow [[BIRB_FOR_LOAD]] : $Birb // CHECK: end_borrow [[BIRB]] : $Birb // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: destroy_value [[BIRB_REF]] : $Birb // CHECK: return [[THE_INT]] : $Int // CHECK: } // end sil function '$s4test3DogC21accessWrappedProperty3catSiAA3CatC_tYaF' func accessWrappedProperty(cat : Cat) async -> Int { return await cat.bestFriend.feathers } // CHECK-LABEL: sil hidden [ossa] @$s4test3DogC16accessFromRValueSbyYaF : $@convention(method) @async (@guaranteed Dog) -> Bool { // CHECK: hop_to_executor [[SELF:%[0-9]+]] : $Dog // CHECK: [[INIT:%[0-9]+]] = function_ref @$s4test3CatCACycfC : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK: [[CAT_REF:%[0-9]+]] = apply [[INIT]]({{%[0-9]+}}) : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK: [[CAT_BORROW_FOR_HOP:%[0-9]+]] = begin_borrow [[CAT_REF]] : $Cat // CHECK: hop_to_executor [[CAT_BORROW_FOR_HOP]] : $Cat // CHECK: [[CAT_BORROW_FOR_LOAD:%[0-9]+]] = begin_borrow [[CAT_REF]] : $Cat // CHECK: [[GETTER:%[0-9]+]] = class_method [[CAT_BORROW_FOR_LOAD]] : $Cat, #Cat.storedBool!getter : (isolated Cat) -> () -> Bool, $@convention(method) (@guaranteed Cat) -> Bool // CHECK: [[THE_BOOL:%[0-9]+]] = apply [[GETTER]]([[CAT_BORROW_FOR_LOAD]]) : $@convention(method) (@guaranteed Cat) -> Bool // CHECK: end_borrow [[CAT_BORROW_FOR_LOAD]] : $Cat // CHECK: end_borrow [[CAT_BORROW_FOR_HOP]] : $Cat // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: destroy_value [[CAT_REF]] : $Cat // CHECK: return [[THE_BOOL]] : $Bool // CHECK: } // end sil function '$s4test3DogC16accessFromRValueSbyYaF' func accessFromRValue() async -> Bool { return await Cat().storedBool } // CHECK-LABEL: sil hidden [ossa] @$s4test3DogC23accessFromRValueChainedSbyYaF : $@convention(method) @async (@guaranteed Dog) -> Bool { // CHECK: hop_to_executor [[SELF:%[0-9]+]] : $Dog // CHECK: [[INIT:%[0-9]+]] = function_ref @$s4test3CatCACycfC : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK: [[CAT_REF:%[0-9]+]] = apply [[INIT]]({{%[0-9]+}}) : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK: [[CAT_BORROW_FOR_HOP:%[0-9]+]] = begin_borrow [[CAT_REF]] : $Cat // CHECK: hop_to_executor [[CAT_BORROW_FOR_HOP]] : $Cat // CHECK: [[CAT_BORROW_FOR_LOAD:%[0-9]+]] = begin_borrow [[CAT_REF]] : $Cat // CHECK: [[FRIEND_GETTER:%[0-9]+]] = class_method [[CAT_BORROW_FOR_LOAD]] : $Cat, #Cat.friend!getter : (isolated Cat) -> () -> Cat, $@convention(method) (@guaranteed Cat) -> @owned Cat // CHECK: [[FRIEND_REF:%[0-9]+]] = apply [[FRIEND_GETTER]]([[CAT_BORROW_FOR_LOAD]]) : $@convention(method) (@guaranteed Cat) -> @owned Cat // CHECK: end_borrow [[CAT_BORROW_FOR_LOAD]] : $Cat // CHECK: end_borrow [[CAT_BORROW_FOR_HOP]] : $Cat // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: destroy_value [[CAT_REF]] : $Cat // CHECK: [[FRIEND_BORROW_FOR_HOP:%[0-9]+]] = begin_borrow [[FRIEND_REF]] : $Cat // CHECK: hop_to_executor [[FRIEND_BORROW_FOR_HOP]] : $Cat // CHECK: [[FRIEND_BORROW_FOR_LOAD:%[0-9]+]] = begin_borrow [[FRIEND_REF]] : $Cat // CHECK: [[BOOL_GETTER:%[0-9]+]] = class_method [[FRIEND_BORROW_FOR_LOAD]] : $Cat, #Cat.storedBool!getter : (isolated Cat) -> () -> Bool, $@convention(method) (@guaranteed Cat) -> Bool // CHECK: [[THE_BOOL:%[0-9]+]] = apply [[BOOL_GETTER]]([[FRIEND_BORROW_FOR_LOAD]]) : $@convention(method) (@guaranteed Cat) -> Bool // CHECK: end_borrow [[FRIEND_BORROW_FOR_LOAD]] : $Cat // CHECK: end_borrow [[FRIEND_BORROW_FOR_HOP]] : $Cat // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: destroy_value [[FRIEND_REF]] : $Cat // CHECK: return [[THE_BOOL]] : $Bool // CHECK: } // end sil function '$s4test3DogC23accessFromRValueChainedSbyYaF' func accessFromRValueChained() async -> Bool { return await Cat().friend.storedBool } // CHECK-LABEL: sil hidden [ossa] @$s4test3DogC15accessSubscript3catAA3CatCAG_tYaF : $@convention(method) @async (@guaranteed Cat, @guaranteed Dog) -> @owned Cat { // CHECK: bb0([[CAT:%[0-9]+]] : @guaranteed $Cat, [[DOG:%[0-9]+]] : @guaranteed $Dog): // CHECK: hop_to_executor [[DOG]] : $Dog // CHECK: [[INTEGER1:%[0-9]+]] = apply {{%[0-9]+}}({{%[0-9]+}}, {{%[0-9]+}}) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK: hop_to_executor [[CAT]] : $Cat // CHECK: [[SUBSCRIPT_FN:%[0-9]+]] = class_method [[CAT]] : $Cat, #Cat.subscript!getter : (isolated Cat) -> (Int) -> Cat, $@convention(method) (Int, @guaranteed Cat) -> @owned Cat // CHECK: [[OTHER_CAT:%[0-9]+]] = apply [[SUBSCRIPT_FN]]([[INTEGER1]], [[CAT]]) : $@convention(method) (Int, @guaranteed Cat) -> @owned Cat // CHECK: hop_to_executor [[DOG]] : $Dog // CHECK: return [[OTHER_CAT]] : $Cat // CHECK: } // end sil function '$s4test3DogC15accessSubscript3catAA3CatCAG_tYaF' func accessSubscript(cat : Cat) async -> Cat { return await cat[1] } // CHECK-LABEL: sil hidden [ossa] @$s4test3DogC27accessRValueNestedSubscriptAA3CatCyYaF : $@convention(method) @async (@guaranteed Dog) -> @owned Cat { // CHECK: hop_to_executor [[SELF:%[0-9]+]] : $Dog // CHECK: [[RVALUE_CAT_REF:%[0-9]+]] = apply {{%[0-9]+}}({{%[0-9]+}}) : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK: [[LIT_ONE:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 1 // CHECK: [[INT_ONE:%[0-9]+]] = apply {{%[0-9]+}}([[LIT_ONE]], {{%[0-9]+}}) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK: [[RVALUE_CAT:%[0-9]+]] = begin_borrow [[RVALUE_CAT_REF]] : $Cat // CHECK: hop_to_executor [[RVALUE_CAT]] : $Cat // CHECK: [[RVALUE_CAT_FOR_LOAD:%[0-9]+]] = begin_borrow [[RVALUE_CAT_REF]] : $Cat // CHECK: [[RVALUE_CAT_SUBSCRIPT:%[0-9]+]] = class_method [[RVALUE_CAT_FOR_LOAD]] : $Cat, #Cat.subscript!getter : (isolated Cat) -> (Int) -> Cat, $@convention(method) (Int, @guaranteed Cat) -> @owned Cat // CHECK: [[FIRST_CAT_REF:%[0-9]+]] = apply [[RVALUE_CAT_SUBSCRIPT]]([[INT_ONE]], [[RVALUE_CAT_FOR_LOAD]]) : $@convention(method) (Int, @guaranteed Cat) -> @owned Cat // CHECK: end_borrow [[RVALUE_CAT_FOR_LOAD]] : $Cat // CHECK: end_borrow [[RVALUE_CAT]] : $Cat // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: destroy_value [[RVALUE_CAT_REF]] : $Cat // CHECK: [[LIT_TWO:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 2 // CHECK: [[INT_TWO:%[0-9]+]] = apply {{%[0-9]+}}([[LIT_TWO]], {{%[0-9]+}}) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK: [[FIRST_CAT:%[0-9]+]] = begin_borrow [[FIRST_CAT_REF]] : $Cat // CHECK: hop_to_executor [[FIRST_CAT]] : $Cat // CHECK: [[FIRST_CAT_FOR_LOAD:%[0-9]+]] = begin_borrow [[FIRST_CAT_REF]] : $Cat // CHECK: [[FIRST_CAT_SUBSCRIPT:%[0-9]+]] = class_method [[FIRST_CAT_FOR_LOAD]] : $Cat, #Cat.subscript!getter : (isolated Cat) -> (Int) -> Cat, $@convention(method) (Int, @guaranteed Cat) -> @owned Cat // CHECK: [[SECOND_CAT_REF:%[0-9]+]] = apply [[FIRST_CAT_SUBSCRIPT]]([[INT_TWO]], [[FIRST_CAT_FOR_LOAD]]) : $@convention(method) (Int, @guaranteed Cat) -> @owned Cat // CHECK: end_borrow [[FIRST_CAT_FOR_LOAD]] : $Cat // CHECK: end_borrow [[FIRST_CAT]] : $Cat // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: destroy_value [[FIRST_CAT_REF]] : $Cat // CHECK: return [[SECOND_CAT_REF]] : $Cat // CHECK: } // end sil function '$s4test3DogC27accessRValueNestedSubscriptAA3CatCyYaF' func accessRValueNestedSubscript() async -> Cat { return await Cat()[1][2] } // CHECK-LABEL: sil hidden [ossa] @$s4test3DogC33accessStoredPropFromRefProjection3boxSbAA6CatBoxC_tYaF : $@convention(method) @async (@guaranteed CatBox, @guaranteed Dog) -> Bool { // CHECK: bb0([[BOX:%[0-9]+]] : @guaranteed $CatBox, [[SELF:%[0-9]+]] : @guaranteed $Dog): // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: [[BOX_GETTER:%[0-9]+]] = class_method [[BOX]] : $CatBox, #CatBox.cat!getter : (CatBox) -> () -> Cat, $@convention(method) (@guaranteed CatBox) -> @owned Cat // CHECK: [[CAT_REF:%[0-9]+]] = apply [[BOX_GETTER]]([[BOX]]) : $@convention(method) (@guaranteed CatBox) -> @owned Cat // CHECK: [[CAT:%[0-9]+]] = begin_borrow [[CAT_REF]] : $Cat // CHECK: hop_to_executor [[CAT]] : $Cat // CHECK: [[CAT_FOR_LOAD:%[0-9]+]] = begin_borrow [[CAT_REF:%[0-9]+]] : $Cat // CHECK: [[GETTER:%[0-9]+]] = class_method [[CAT_FOR_LOAD]] : $Cat, #Cat.storedBool!getter : (isolated Cat) -> () -> Bool, $@convention(method) (@guaranteed Cat) -> Bool // CHECK: [[THE_BOOL:%[0-9]+]] = apply [[GETTER]]([[CAT_FOR_LOAD]]) : $@convention(method) (@guaranteed Cat) -> Bool // CHECK: end_borrow [[CAT_FOR_LOAD]] : $Cat // CHECK: end_borrow [[CAT]] : $Cat // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: destroy_value [[CAT_REF]] : $Cat // CHECK: return [[THE_BOOL]] : $Bool // CHECK: } // end sil function '$s4test3DogC33accessStoredPropFromRefProjection3boxSbAA6CatBoxC_tYaF' func accessStoredPropFromRefProjection(box : CatBox) async -> Bool { return await box.cat.storedBool } // CHECK-LABEL: sil hidden [ossa] @$s4test3DogC015accessSweaterOfD03catAA0D0VAA3CatC_tYaF : $@convention(method) @async (@guaranteed Cat, @guaranteed Dog) -> @owned Sweater { // CHECK: bb0([[CAT:%[0-9]+]] : @guaranteed $Cat, [[SELF:%[0-9]+]] : @guaranteed $Dog): // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: hop_to_executor [[CAT]] : $Cat // CHECK: [[CAT_GETTER:%[0-9]+]] = class_method [[CAT]] : $Cat, #Cat.computedSweater!getter : (isolated Cat) -> () -> Sweater, $@convention(method) (@guaranteed Cat) -> @owned Sweater // CHECK: [[SWEATER1_REF:%[0-9]+]] = apply [[CAT_GETTER]]([[CAT]]) : $@convention(method) (@guaranteed Cat) -> @owned Sweater // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: [[SWEATER1:%[0-9]+]] = begin_borrow [[SWEATER1_REF]] : $Sweater // CHECK: [[SWEATER1_OWNER:%[0-9]+]] = struct_extract [[SWEATER1]] : $Sweater, #Sweater.owner // CHECK: [[CAT2_REF:%[0-9]+]] = copy_value [[SWEATER1_OWNER]] : $Cat // CHECK: end_borrow [[SWEATER1]] : $Sweater // CHECK: destroy_value [[SWEATER1_REF]] : $Sweater // CHECK: [[CAT2:%[0-9]+]] = begin_borrow [[CAT2_REF]] : $Cat // CHECK: hop_to_executor [[CAT2]] : $Cat // CHECK: [[CAT2_FOR_LOAD:%[0-9]+]] = begin_borrow [[CAT2_REF]] : $Cat // CHECK: [[CAT2_GETTER:%[0-9]+]] = class_method [[CAT2_FOR_LOAD]] : $Cat, #Cat.computedSweater!getter : (isolated Cat) -> () -> Sweater, $@convention(method) (@guaranteed Cat) -> @owned Sweater // CHECK: [[SWEATER2_OWNER:%[0-9]+]] = apply [[CAT2_GETTER]]([[CAT2_FOR_LOAD]]) : $@convention(method) (@guaranteed Cat) -> @owned Sweater // CHECK: end_borrow [[CAT2_FOR_LOAD]] : $Cat // CHECK: end_borrow [[CAT2]] : $Cat // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: destroy_value [[CAT2_REF]] : $Cat // CHECK: return [[SWEATER2_OWNER]] : $Sweater // CHECK: } // end sil function '$s4test3DogC015accessSweaterOfD03catAA0D0VAA3CatC_tYaF' func accessSweaterOfSweater(cat : Cat) async -> Sweater { // note that Sweater is not an actor! return await cat.computedSweater.owner.computedSweater } // CHECK-LABEL: sil hidden [ossa] @$s4test3DogC13accessCatList3catAA0D0CAG_tYaF : $@convention(method) @async (@guaranteed Cat, @guaranteed Dog) -> @owned Cat { // CHECK: bb0([[CAT:%[0-9]+]] : @guaranteed $Cat, [[SELF:%[0-9]+]] : @guaranteed $Dog): // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: hop_to_executor [[CAT]] : $Cat // CHECK: [[CAT_GETTER:%[0-9]+]] = class_method [[CAT]] : $Cat, #Cat.friend!getter : (isolated Cat) -> () -> Cat, $@convention(method) (@guaranteed Cat) -> @owned Cat // CHECK: [[FRIEND1_REF:%[0-9]+]] = apply [[CAT_GETTER]]([[CAT]]) : $@convention(method) (@guaranteed Cat) -> @owned Cat // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: [[FRIEND1:%[0-9]+]] = begin_borrow [[FRIEND1_REF]] : $Cat // CHECK: hop_to_executor [[FRIEND1]] : $Cat // CHECK: [[FRIEND1_FOR_LOAD:%[0-9]+]] = begin_borrow [[FRIEND1_REF]] : $Cat // CHECK: [[FRIEND1_GETTER:%[0-9]+]] = class_method [[FRIEND1_FOR_LOAD]] : $Cat, #Cat.friend!getter : (isolated Cat) -> () -> Cat, $@convention(method) (@guaranteed Cat) -> @owned Cat // CHECK: [[FRIEND2_REF:%[0-9]+]] = apply [[FRIEND1_GETTER]]([[FRIEND1_FOR_LOAD]]) : $@convention(method) (@guaranteed Cat) -> @owned Cat // CHECK: end_borrow [[FRIEND1_FOR_LOAD]] : $Cat // CHECK: end_borrow [[FRIEND1]] : $Cat // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: destroy_value [[FRIEND1_REF]] : $Cat // CHECK: return [[FRIEND2_REF]] : $Cat // CHECK: } // end sil function '$s4test3DogC13accessCatList3catAA0D0CAG_tYaF' func accessCatList(cat : Cat) async -> Cat { return await cat.friend.friend } // CHECK-LABEL: sil hidden [ossa] @$s4test3DogC21accessOptionalCatList3catAA0E0CSgAG_tYaF : $@convention(method) @async (@guaranteed Cat, @guaranteed Dog) -> @owned Optional<Cat> { // CHECK: bb0([[CAT:%[0-9]+]] : @guaranteed $Cat, [[SELF:%[0-9]+]] : @guaranteed $Dog): // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: [[FRIEND1_STACK:%[0-9]+]] = alloc_stack $Optional<Cat> // CHECK: hop_to_executor [[CAT]] : $Cat // CHECK: [[MAYBE_GETTER:%[0-9]+]] = class_method [[CAT]] : $Cat, #Cat.maybeFriend!getter : (isolated Cat) -> () -> Cat?, $@convention(method) (@guaranteed Cat) -> @owned Optional<Cat> // CHECK: [[MAYBE_FRIEND:%[0-9]+]] = apply [[MAYBE_GETTER]]([[CAT]]) : $@convention(method) (@guaranteed Cat) -> @owned Optional<Cat> // CHECK: store [[MAYBE_FRIEND]] to [init] [[FRIEND1_STACK]] : $*Optional<Cat> // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: [[IS_SOME:%[0-9]+]] = select_enum_addr [[FRIEND1_STACK]] : $*Optional<Cat> // CHECK: cond_br [[IS_SOME]], bb1, bb3 // CHECK: bb1: // CHECK: [[FRIEND1_ADDR:%[0-9]+]] = unchecked_take_enum_data_addr [[FRIEND1_STACK]] : $*Optional<Cat>, #Optional.some!enumelt // CHECK: [[FRIEND1_REF:%[0-9]+]] = load [copy] [[FRIEND1_ADDR]] : $*Cat // CHECK: destroy_addr [[FRIEND1_STACK]] : $*Optional<Cat> // CHECK: [[FRIEND1:%[0-9]+]] = begin_borrow [[FRIEND1_REF]] : $Cat // CHECK: hop_to_executor [[FRIEND1]] : $Cat // CHECK: [[FRIEND1_FOR_LOAD:%[0-9]+]] = begin_borrow [[FRIEND1_REF]] : $Cat // CHECK: [[FRIEND1_GETTER:%[0-9]+]] = class_method [[FRIEND1_FOR_LOAD]] : $Cat, #Cat.friend!getter : (isolated Cat) -> () -> Cat, $@convention(method) (@guaranteed Cat) -> @owned Cat // CHECK: [[FRIEND2_REF:%[0-9]+]] = apply [[FRIEND1_GETTER]]([[FRIEND1_FOR_LOAD]]) : $@convention(method) (@guaranteed Cat) -> @owned Cat // CHECK: end_borrow [[FRIEND1_FOR_LOAD]] : $Cat // CHECK: end_borrow [[FRIEND1]] : $Cat // CHECK: hop_to_executor [[SELF]] : $Dog // CHECK: destroy_value [[FRIEND1_REF]] : $Cat // CHECK: [[FRIEND2_OPTIONAL:%[0-9]+]] = enum $Optional<Cat>, #Optional.some!enumelt, [[FRIEND2_REF]] : $Cat // CHECK: dealloc_stack [[FRIEND1_STACK]] : $*Optional<Cat> // CHECK: br bb2([[FRIEND2_OPTIONAL]] : $Optional<Cat>) // CHECK-NOT: hop_to_executor // CHECK: } // end sil function '$s4test3DogC21accessOptionalCatList3catAA0E0CSgAG_tYaF' func accessOptionalCatList(cat : Cat) async -> Cat? { return await cat.maybeFriend?.friend } } // END OF DOG ACTOR class Point { var pt: (Int, Int) = (0, 0) } @MainActor var globalCircle: ((Int, Int)?, Float) = (nil, 1.1) struct Container { @MainActor static var counter: Int = 10 @MainActor static var this: Container? @MainActor static var staticCircle: ((Int, Int)?, Float) = (nil, 2.1) var noniso: Int = 20 @GlobalCat var iso: Float = 1.0 @GlobalCat var isoRef: CatBox = CatBox() // CHECK-LABEL: sil hidden [ossa] @$s4test9ContainerV12accessTuple1SfyYaF : $@convention(method) @async (@guaranteed Container) -> Float { // CHECK: hop_to_executor {{%[0-9]+}} : $MainActor // CHECK: [[ACCESS:%[0-9]+]] = begin_access [read] [dynamic] {{%[0-9]+}} : $*(Optional<(Int, Int)>, Float) // CHECK: [[ADDR:%[0-9]+]] = tuple_element_addr [[ACCESS]] : $*(Optional<(Int, Int)>, Float), 1 // CHECK: {{%[0-9]+}} = load [trivial] [[ADDR]] : $*Float // CHECK: end_access [[ACCESS]] : $*(Optional<(Int, Int)>, Float) // CHECK: hop_to_executor {{%[0-9]+}} : $Optional<Builtin.Executor> // CHECK: } // end sil function '$s4test9ContainerV12accessTuple1SfyYaF' func accessTuple1() async -> Float { return await globalCircle.1 } // CHECK-LABEL: sil hidden [ossa] @$s4test9ContainerV12accessTuple2SiSgyYaFZ : $@convention(method) @async (@thin Container.Type) -> Optional<Int> { // CHECK: hop_to_executor {{%[0-9]+}} : $MainActor // CHECK: [[ACCESS:%[0-9]+]] = begin_access [read] [dynamic] {{%[0-9]+}} : $*(Optional<(Int, Int)>, Float) // CHECK: [[ADDR:%[0-9]+]] = tuple_element_addr [[ACCESS]] : $*(Optional<(Int, Int)>, Float), 0 // CHECK: switch_enum_addr [[SCRUTINEE:%[0-9]+]] : $*Optional<(Int, Int)>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[CRASH_BB:bb[0-9]+]] // CHECK: [[CRASH_BB]]: // CHECK-NOT: hop_to_executor {{%[0-9]+}} // CHECK: unreachable // CHECK: [[SOME_BB]]: // CHECK: [[TUPLE_ADDR:%[0-9]+]] = unchecked_take_enum_data_addr [[SCRUTINEE]] : $*Optional<(Int, Int)>, #Optional.some!enumelt // CHECK: [[ELM_ADDR:%[0-9]+]] = tuple_element_addr [[TUPLE_ADDR]] : $*(Int, Int), 0 // CHECK: {{%[0-9]+}} = load [trivial] [[ELM_ADDR]] : $*Int // CHECK: end_access [[ACCESS]] : $*(Optional<(Int, Int)>, Float) // CHECK: hop_to_executor {{%[0-9]+}} : $Optional<Builtin.Executor> // CHECK: } // end sil function '$s4test9ContainerV12accessTuple2SiSgyYaFZ' static func accessTuple2() async -> Int? { return await globalCircle.0!.0 } // CHECK-LABEL: sil hidden [ossa] @$s4test9ContainerV12accessTuple3SfyYaF : $@convention(method) @async (@guaranteed Container) -> Float { // CHECK: hop_to_executor {{%[0-9]+}} : $MainActor // CHECK: [[ACCESS:%[0-9]+]] = begin_access [read] [dynamic] {{%[0-9]+}} : $*(Optional<(Int, Int)>, Float) // CHECK: [[ADDR:%[0-9]+]] = tuple_element_addr [[ACCESS]] : $*(Optional<(Int, Int)>, Float), 1 // CHECK: {{%[0-9]+}} = load [trivial] [[ADDR]] : $*Float // CHECK: end_access [[ACCESS]] : $*(Optional<(Int, Int)>, Float) // CHECK: hop_to_executor {{%[0-9]+}} : $Optional<Builtin.Executor> // CHECK: } // end sil function '$s4test9ContainerV12accessTuple3SfyYaF' func accessTuple3() async -> Float { return await Container.staticCircle.1 } // CHECK-LABEL: sil hidden [ossa] @$s4test9ContainerV12accessTuple4SiSgyYaFZ : $@convention(method) @async (@thin Container.Type) -> Optional<Int> { // CHECK: hop_to_executor {{%[0-9]+}} : $MainActor // CHECK: [[ACCESS:%[0-9]+]] = begin_access [read] [dynamic] {{%[0-9]+}} : $*(Optional<(Int, Int)>, Float) // CHECK: [[ADDR:%[0-9]+]] = tuple_element_addr [[ACCESS]] : $*(Optional<(Int, Int)>, Float), 0 // CHECK: switch_enum_addr [[SCRUTINEE:%[0-9]+]] : $*Optional<(Int, Int)>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[CRASH_BB:bb[0-9]+]] // CHECK: [[CRASH_BB]]: // CHECK-NOT: hop_to_executor {{%[0-9]+}} // CHECK: unreachable // CHECK: [[SOME_BB]]: // CHECK: [[TUPLE_ADDR:%[0-9]+]] = unchecked_take_enum_data_addr [[SCRUTINEE]] : $*Optional<(Int, Int)>, #Optional.some!enumelt // CHECK: [[ELM_ADDR:%[0-9]+]] = tuple_element_addr [[TUPLE_ADDR]] : $*(Int, Int), 0 // CHECK: {{%[0-9]+}} = load [trivial] [[ELM_ADDR]] : $*Int // CHECK: end_access [[ACCESS]] : $*(Optional<(Int, Int)>, Float) // CHECK: hop_to_executor {{%[0-9]+}} : $Optional<Builtin.Executor> // CHECK: } // end sil function '$s4test9ContainerV12accessTuple4SiSgyYaFZ' static func accessTuple4() async -> Int? { return await Container.staticCircle.0!.0 } // CHECK-LABEL: sil hidden [ossa] @$s4test9ContainerV8getCountSiyYaFZ : $@convention(method) @async (@thin Container.Type) -> Int { // CHECK: hop_to_executor {{%[0-9]+}} : $MainActor // CHECK: {{%[0-9]+}} = begin_access [read] [dynamic] {{%[0-9]+}} : $*Int // CHECK: {{%[0-9]+}} = load [trivial] {{%[0-9]+}} : $*Int // CHECK: hop_to_executor {{%[0-9]+}} : $Optional<Builtin.Executor> // CHECK: } // end sil function '$s4test9ContainerV8getCountSiyYaFZ' static func getCount() async -> Int { return await counter } // CHECK-LABEL: sil hidden [ossa] @$s4test9ContainerV8getValueSiSgyYaFZ : $@convention(method) @async (@thin Container.Type) -> Optional<Int> { // CHECK: bb0(%0 : $@thin Container.Type): // CHECK: [[MAIN:%[0-9]+]] = begin_borrow {{%[0-9]+}} : $MainActor // CHECK: [[PREV:%[0-9]+]] = builtin "getCurrentExecutor"() : $Optional<Builtin.Executor> // CHECK: hop_to_executor [[MAIN]] : $MainActor // CHECK: [[ACCESS:%[0-9]+]] = begin_access [read] [dynamic] {{%[0-9]+}} : $*Optional<Container> // CHECK: cond_br {{%[0-9]+}}, [[TRUE_BB:bb[0-9]+]], [[FALSE_BB:bb[0-9]+]] // // CHECK: [[TRUE_BB]]: // CHECK: {{%[0-9]+}} = load [trivial] {{%[0-9]+}} : $*Int // CHECK: end_access [[ACCESS]] : $*Optional<Container> // CHECK: hop_to_executor [[PREV]] : $Optional<Builtin.Executor> // // CHECK: [[FALSE_BB]]: // CHECK: end_access [[ACCESS]] : $*Optional<Container> // CHECK: hop_to_executor [[PREV]] : $Optional<Builtin.Executor> // // CHECK: } // end sil function '$s4test9ContainerV8getValueSiSgyYaFZ' static func getValue() async -> Int? { return await this?.noniso } // CHECK-LABEL: sil hidden [ossa] @$s4test9ContainerV10getOrCrashSfyYaFZ : $@convention(method) @async (@thin Container.Type) -> Float { // CHECK: bb0({{%[0-9]+}} : $@thin Container.Type): // CHECK: [[MAIN:%[0-9]+]] = begin_borrow {{%[0-9]+}} : $MainActor // CHECK: [[PREV:%[0-9]+]] = builtin "getCurrentExecutor"() : $Optional<Builtin.Executor> // CHECK: hop_to_executor [[MAIN]] : $MainActor // CHECK: [[ACCESS:%[0-9]+]] = begin_access [read] [dynamic] {{%[0-9]+}} : $*Optional<Container> // CHECK: switch_enum_addr %11 : $*Optional<Container>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[CRASH_BB:bb[0-9]+]] // // CHECK: [[CRASH_BB]]: // CHECK-NOT: hop_to_executor {{%[0-9]+}} // CHECK: unreachable // // CHECK: [[SOME_BB]]: // CHECK: [[DATA_ADDR:%[0-9]+]] = unchecked_take_enum_data_addr %11 : $*Optional<Container>, #Optional.some!enumelt // CHECK: [[ELEM_ADDR:%[0-9]+]] = struct_element_addr %22 : $*Container, #Container.iso // CHECK: [[PREV_AGAIN:%[0-9]+]] = builtin "getCurrentExecutor"() : $Optional<Builtin.Executor> // CHECK: hop_to_executor {{%[0-9]+}} : $Cat // CHECK: {{%[0-9]+}} = load [trivial] [[ELEM_ADDR]] : $*Float // CHECK: hop_to_executor [[PREV]] : $Optional<Builtin.Executor> // CHECK: hop_to_executor [[PREV_AGAIN]] : $Optional<Builtin.Executor> // CHECK: } // end sil function '$s4test9ContainerV10getOrCrashSfyYaFZ' static func getOrCrash() async -> Float { return await this!.iso } // CHECK-LABEL: sil hidden [ossa] @$s4test9ContainerV13getRefOrCrashAA6CatBoxCyYaFZ : $@convention(method) @async (@thin Container.Type) -> @owned CatBox { // CHECK: bb0({{%[0-9]+}} : $@thin Container.Type): // CHECK: [[MAIN:%[0-9]+]] = begin_borrow {{%[0-9]+}} : $MainActor // CHECK: [[PREV:%[0-9]+]] = builtin "getCurrentExecutor"() : $Optional<Builtin.Executor> // CHECK: hop_to_executor [[MAIN]] : $MainActor // CHECK: [[ACCESS:%[0-9]+]] = begin_access [read] [dynamic] {{%[0-9]+}} : $*Optional<Container> // CHECK: switch_enum_addr %11 : $*Optional<Container>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[CRASH_BB:bb[0-9]+]] // // CHECK: [[CRASH_BB]]: // CHECK-NOT: hop_to_executor {{%[0-9]+}} // CHECK: unreachable // // CHECK: [[SOME_BB]]: // CHECK: [[DATA_ADDR:%[0-9]+]] = unchecked_take_enum_data_addr %11 : $*Optional<Container>, #Optional.some!enumelt // CHECK: [[ELEM_ADDR:%[0-9]+]] = struct_element_addr %22 : $*Container, #Container.iso // CHECK: [[PREV_AGAIN:%[0-9]+]] = builtin "getCurrentExecutor"() : $Optional<Builtin.Executor> // CHECK: hop_to_executor {{%[0-9]+}} : $Cat // CHECK: {{%[0-9]+}} = load [copy] [[ELEM_ADDR]] : $*CatBox // CHECK: hop_to_executor [[PREV]] : $Optional<Builtin.Executor> // CHECK: hop_to_executor [[PREV_AGAIN]] : $Optional<Builtin.Executor> // CHECK: } // end sil function '$s4test9ContainerV13getRefOrCrashAA6CatBoxCyYaFZ' static func getRefOrCrash() async -> CatBox { return await this!.isoRef } } @propertyWrapper struct StateObject<ObjectType> { @MainActor(unsafe) var wrappedValue: ObjectType { fatalError() } init(wrappedValue: ObjectType) {} } final private actor Coordinactor { var someValue: Int? } struct Blah { @StateObject private var coordinator = Coordinactor() // closure #1 in Blah.test() // CHECK-LABEL: sil private [ossa] @$s4test4BlahVAAyyFyyYaYbcfU_ : $@convention(thin) @Sendable @async (Blah) -> () { // CHECK: hop_to_executor {{%[0-9]+}} : $MainActor // CHECK: [[ACTOR_OBJ_RAW:%[0-9]+]] = apply {{%[0-9]+}}({{%[0-9]+}}) : $@convention(method) (Blah) -> @owned Coordinactor // CHECK: hop_to_executor {{%[0-9]+}} : $Optional<Builtin.Executor> // CHECK: [[ACTOR_OBJ:%[0-9]+]] = begin_borrow [[ACTOR_OBJ_RAW]] : $Coordinactor // CHECK: [[VAL:%[0-9]+]] = ref_element_addr [[ACTOR_OBJ]] : $Coordinactor, #Coordinactor.someValue // CHECK: hop_to_executor [[ACTOR_OBJ]] // CHECK: [[VAL_ACCESS:%[0-9]+]] = begin_access [read] [dynamic] [[VAL]] : $*Optional<Int> // CHECK: {{%[0-9]+}} = load [trivial] %17 : $*Optional<Int> // CHECK: end_access %17 : $*Optional<Int> // CHECK: hop_to_executor {{%[0-9]+}} : $Optional<Builtin.Executor> // CHECK: } // end sil function '$s4test4BlahVAAyyFyyYaYbcfU_' @available(SwiftStdlib 5.5, *) func test() { Task.detached { if await coordinator.someValue == nil { fatalError() } } } }
apache-2.0
a8fe9dc46ac05488ce352d5263abf918
56.674923
209
0.58075
3.108636
false
true
false
false
hanjoes/Smashtag
Smashtag/TweetTableViewCell.swift
1
3118
// // TweetTableViewCell.swift // Smashtag // // Created by Hanzhou Shi on 1/5/16. // Copyright © 2016 USF. All rights reserved. // import UIKit class TweetTableViewCell: UITableViewCell { @IBOutlet weak var tweetProfileImageView: UIImageView! @IBOutlet weak var tweetScreenNameLabel: UILabel! @IBOutlet weak var tweetTextLabel: UILabel! @IBOutlet weak var tweetTimeLabel: UILabel! var tweet: Tweet? { didSet { updateUI() } } func updateUI() { // reset any existing tweet information tweetTextLabel?.attributedText = nil tweetScreenNameLabel?.text = nil tweetProfileImageView?.image = nil // tweetCreatedLabel?.text = nil // load new information from our tweet (if any) if let tweet = self.tweet { tweetTextLabel?.text = tweet.text if tweetTextLabel?.text != nil { // highlight mentions let mutableAttributedString = NSMutableAttributedString(attributedString: tweetTextLabel.attributedText!) let attributesForUrl = [NSForegroundColorAttributeName: UIColor.darkGrayColor(), NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue] let _ = tweet.urls.map({ (kw) -> Void in mutableAttributedString.addAttributes(attributesForUrl, range: kw.nsrange!) }) let attributesForHashTags = [NSForegroundColorAttributeName: UIColor.blueColor(), NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue] let _ = tweet.hashtags.map({ (kw) -> Void in mutableAttributedString.addAttributes(attributesForHashTags, range: kw.nsrange!) }) let attributesForMentions = [NSForegroundColorAttributeName: UIColor.orangeColor()] let _ = tweet.userMentions.map({ (kw) -> Void in mutableAttributedString.addAttributes(attributesForMentions, range: kw.nsrange!) }) tweetTextLabel.attributedText = mutableAttributedString for _ in tweet.media { tweetTextLabel.text! += " 📷" } } tweetScreenNameLabel?.text = "\(tweet.user)" if let profileImageURL = tweet.user.profileImageURL { if let imageData = NSData(contentsOfURL: profileImageURL) { // blocks main thread!! tweetProfileImageView?.image = UIImage(data: imageData) } } let formatter = NSDateFormatter() if NSDate().timeIntervalSinceDate(tweet.created) > 24*60*60 { formatter.dateStyle = NSDateFormatterStyle.ShortStyle } else { formatter.timeStyle = NSDateFormatterStyle.ShortStyle } tweetTimeLabel?.text = formatter.stringFromDate(tweet.created) } } }
mit
d1ca6f9bc5ab2036d0196ec04f184ed2
39.441558
121
0.585421
6.082031
false
false
false
false
AEvgeniy/Sample
Sample/Application/Authentication/AuthenticationView.swift
1
4244
// // AuthenticationView.swift // Sample // // Created by Evgeniy Abashkin on 7/23/17. // Copyright © 2017 com.evgeniy. All rights reserved. // import Foundation import UIKit class AuthenticationView: UIViewController { var viewModel: AuthenticationViewModel! var keyboardHandler: KeyboardHandler! @IBOutlet fileprivate weak var controlsMiddle: NSLayoutConstraint! @IBOutlet fileprivate weak var emailField: TextField! @IBOutlet fileprivate weak var passwordField: TextField! @IBOutlet fileprivate weak var loginButton: Button! @IBOutlet fileprivate weak var loginIndicator: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() viewModel.delegate = self keyboardHandler.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) keyboardHandler.beginWatchForKeyboard() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) keyboardHandler.endWatchForKeyboard() } @IBAction fileprivate func rememberPassword(_ sender: Any) { view.endEditing(true) } @IBAction fileprivate func authenticate(_ sender: Any) { view.endEditing(true) startLoadingIndication() viewModel.authenticate(email: emailField.text ?? "", password: passwordField.text ?? "") } @IBAction fileprivate func register(_ sender: Any) { view.endEditing(true) } @IBAction fileprivate func hideKeyboard(_ sender: Any) { view.endEditing(true) } fileprivate func startLoadingIndication() { loginButton.isHidden = true loginIndicator.startAnimating() } fileprivate func stopLoadingIndication() { loginButton.isHidden = false loginIndicator.stopAnimating() } } extension AuthenticationView: AuthenticationViewModelDelegate { func showValidationResult(errors: [Error]) { stopLoadingIndication() for error in errors { switch error { case PasswordValidationError.passwordInvalid: passwordField.isHighlightedError = true case EmailValidationError.emailInvalid: emailField.isHighlightedError = true default: break } } } func showWeather(weather: String) { stopLoadingIndication() let alert = UIAlertController(title: NSLocalizedString("Погода", comment: ""), message: weather, preferredStyle: .alert) alert.view.accessibilityIdentifier = "WeatherAlert" alert.addAction(UIAlertAction(title: NSLocalizedString("Закрыть", comment: ""), style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } } extension AuthenticationView: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { (textField as? TextField)?.isHighlightedError = false return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { switch textField { case emailField: passwordField.becomeFirstResponder() case passwordField: textField.resignFirstResponder() authenticate(self) default: break } return true } } extension AuthenticationView: KeyboardHandlerDelegate { func keyboardFrameChangeHandler(keyboardNotification: KeyboardNotification) { if keyboardNotification.frameEnd.origin.y >= UIScreen.main.bounds.height { controlsMiddle.constant = 0.0 } else { controlsMiddle.constant = -keyboardNotification.frameEnd.height / 2 } UIView.animate(withDuration: keyboardNotification.duration, delay: TimeInterval(0), options: keyboardNotification.animationOptions, animations: { self.view.layoutIfNeeded() }, completion: nil) } }
mit
f4eb099a1dfb60002df7b86b2462aa6b
28.788732
118
0.643026
5.731707
false
false
false
false
dreamsxin/swift
test/Constraints/default_literals.swift
3
913
// RUN: %target-parse-verify-swift func acceptInt(_ : inout Int) {} func acceptDouble(_ : inout Double) {} var i1 = 1 acceptInt(&i1) var i2 = 1 + 2.0 + 1 acceptDouble(&i2) func ternary<T>(_ cond: Bool, _ ifTrue: @autoclosure () -> T, _ ifFalse: @autoclosure () -> T) -> T {} _ = ternary(false, 1, 2.5) _ = ternary(false, 2.5, 1) // <rdar://problem/18447543> _ = ternary(false, 1, 2 as Int32) _ = ternary(false, 1, 2 as Float) func genericFloatingLiteral<T : FloatLiteralConvertible>(_ x: T) { var _ : T = 2.5 } var d = 3.5 genericFloatingLiteral(d) extension UInt32 { func asChar() -> UnicodeScalar { return UnicodeScalar(self) } } var ch = UInt32(65).asChar() // <rdar://problem/14634379> extension Int { func call0() {} typealias Signature = (a: String, b: String) func call(_ x: Signature) {} } 3.call((a: "foo", b: "bar")) var (div, mod) = (9 / 4, 9 % 4)
apache-2.0
cc7ee450e6e1dfea56b0a487b69b0fcc
19.75
66
0.596933
2.835404
false
false
false
false
McNight/ChronoDiderot
CDKit/CDExporter.swift
1
6109
// // CDExporter.swift // ChronoDiderot // // Created by McNight on 26/10/2015. // Copyright © 2015 McNight. All rights reserved. // import Foundation import EventKit public enum CDExporterResult { case NothingSpecial case SuccessCreate case SuccessUpdate case FailureCreate case FailureUpdate case CalendarNotCreated case CalendarNotFound } public class CDExporter { // Phase de tests avec le framework EventKit (que je ne connais pas...) private let eventStore = EKEventStore() public init() { } public func requestAuthorization(completionHandler: (authorized: Bool, error: NSError?) -> Void) { self.eventStore.requestAccessToEntityType(.Event) { success, error in dispatch_async(dispatch_get_main_queue()) { completionHandler(authorized: success, error: error) } } } public func resetCalendarContext() -> Bool { let result = self.removeCalendar() CDHelpers.sharedHelper.setEventsParsedDate(nil) CDHelpers.sharedHelper.storeEventsParsedCount(-1) return result } public func renameCalendar() { guard let calendarIdentifier = CDHelpers.sharedHelper.customCalendarIdentifier() else { print("No Identifier Found...") return } guard let calendar = self.eventStore.calendarWithIdentifier(calendarIdentifier) else { print("Could not get Calendar with this identifier") return } let calendarName = CDHelpers.sharedHelper.preferredCalendarName() calendar.title = calendarName! do { try self.eventStore.saveCalendar(calendar, commit: true) CDHelpers.sharedHelper.storeCustomCalendarIdentifier(calendar.calendarIdentifier) } catch _ { print("Error saving calendar") } } public func createCalendar() { let calendarName = CDHelpers.sharedHelper.preferredCalendarName() let calendar = EKCalendar(forEntityType: .Event, eventStore: self.eventStore) calendar.title = calendarName == nil ? "Emploi du temps Diderot" : calendarName! let source = self.eventStore.defaultCalendarForNewEvents.source calendar.source = source do { try self.eventStore.saveCalendar(calendar, commit: true) CDHelpers.sharedHelper.storeCustomCalendarIdentifier(calendar.calendarIdentifier) CDHelpers.sharedHelper.setCustomCalendarCreated(true) } catch _ { print("Error saving calendar") } } private func removeCalendar() -> Bool { guard let calendarIdentifier = CDHelpers.sharedHelper.customCalendarIdentifier() else { print("No Identifier Found...") return false } guard let calendar = self.eventStore.calendarWithIdentifier(calendarIdentifier) else { print("Could not get Calendar with this identifier") return false } do { try self.eventStore.removeCalendar(calendar, commit: true) CDHelpers.sharedHelper.storeCustomCalendarIdentifier(nil) return true } catch _ { print("Error removing calendar") return false } } /// TODO: Better Error Handling... public func createOrUpdateEvents(events: [CDEvent]) -> CDExporterResult { guard CDHelpers.sharedHelper.customCalendarCreated() == true else { print("Calendar not created...") return .CalendarNotCreated } guard let calendarIdentifier = CDHelpers.sharedHelper.customCalendarIdentifier() else { print("No Identifier Found...") return .CalendarNotFound } guard let calendar = self.eventStore.calendarWithIdentifier(calendarIdentifier) else { print("Could not get the calendar with this identifier...") return .CalendarNotFound } // On va comparer le numéro de la semaine de l'année de la date courante par rapport à celle que l'on a précédemment stockée. // S'ils différent, c'est qu'on entame une nouvelle semaine et qu'il faut créer de nouveaux événements. // À l'inverse, s'ils sont identiques, alors c'est qu'on a relancé le processus et qu'il faut mettre à jour les événements déjà crées // en les récupérant à l'aide de leurs identifiants uniques (crées par le framework) var createMode = false var eventsIdentifiers: [String]! let currentDate = NSDate() let components = NSCalendar.currentCalendar().components([.WeekOfYear, .Weekday], fromDate: currentDate) var weekOfYearToCompare = components.weekOfYear if components.weekday == 1 || components.weekday == 7{ weekOfYearToCompare += 1 } let lastEventsParsedWeek = CDHelpers.sharedHelper.eventsParsedWeek() if lastEventsParsedWeek == -1 || (lastEventsParsedWeek != weekOfYearToCompare) { createMode = true CDHelpers.sharedHelper.setEventsParsedDate(currentDate) eventsIdentifiers = [String]() } else { eventsIdentifiers = CDHelpers.sharedHelper.eventsParsedIdentifiers() } print("Create Mode : \(createMode)") let locationWanted = CDHelpers.sharedHelper.userWantsLocation() for (index,data) in events.enumerate() { var event: EKEvent! if createMode { event = EKEvent(eventStore: self.eventStore) } else { event = self.eventStore.eventWithIdentifier(eventsIdentifiers[index]) // On ne sait jamais... if event == nil { event = EKEvent(eventStore: self.eventStore) } } event.title = data.humanReadableTitle() event.startDate = data.beginDate event.endDate = data.endDate event.location = locationWanted == true ? data.location : nil event.calendar = calendar do { // Au départ, j'avais mis false pour commit // Mais si on ne fait que saveEvent, on ne peut pas accéder au eventIdentifier... try self.eventStore.saveEvent(event, span: .ThisEvent, commit: true) print("Event saved and commited !") if createMode { eventsIdentifiers.append(event.eventIdentifier) } } catch _ { print("Error saving Event") return createMode ? .FailureCreate : .FailureUpdate } } CDHelpers.sharedHelper.storeEventsParsedIdentifiers(eventsIdentifiers) return createMode ? .SuccessCreate : .SuccessUpdate } }
mit
4e2e7e50a8c4ef34ec3a5320771515e8
30.045918
135
0.708909
4.015842
false
false
false
false
benlangmuir/swift
test/DebugInfo/patternmatching.swift
10
4095
// RUN: %target-swift-frontend -primary-file %s -emit-ir -g -o %t.ll // RUN: %FileCheck %s < %t.ll // RUN: %FileCheck --check-prefix=CHECK-SCOPES %s < %t.ll // RUN: %target-swift-frontend -emit-sil -emit-verbose-sil -primary-file %s -o - | %FileCheck %s --check-prefix=SIL-CHECK // This comment must be at line 10 for the test to work. func markUsed<T>(_ t: T) {} // CHECK-SCOPES: define {{.*}}classifyPoint2 func classifyPoint2(_ p: (Double, Double)) { func return_same (_ input : Double) -> Double { return input; // return_same gets called in both where statements } switch p { case (let x, let y) where // CHECK: call {{.*}}double {{.*}}return_same{{.*}}, !dbg ![[LOC1:.*]] // CHECK: br {{.*}}, label {{.*}}, label {{.*}}, !dbg ![[LOC2:.*]] // CHECK: call{{.*}}markUsed{{.*}}, !dbg ![[LOC3:.*]] // CHECK: ![[LOC1]] = !DILocation(line: [[@LINE+2]], // CHECK: ![[LOC2]] = !DILocation(line: [[@LINE+1]], return_same(x) == return_same(y): // CHECK: ![[LOC3]] = !DILocation(line: [[@LINE+1]], markUsed(x) // SIL-CHECK: dealloc_stack{{.*}}line:[[@LINE-1]]:17:cleanup // Verify that the branch has a location >= the cleanup. // SIL-CHECK-NEXT: br{{.*}}auto_gen case (let x, let y) where x == -y: markUsed(x) case (let x, let y) where x >= -10 && x < 10 && y >= -10 && y < 10: markUsed(x) case (let x, let y): markUsed(x) } switch p { case (let x, let y) where x == 0: if y == 0 { markUsed(x) } else { markUsed(y) } // SIL-CHECK-NOT: br{{.*}}line:[[@LINE]]:31:cleanup case (let x, let y): do { if y == 0 { markUsed(x) } else { markUsed(y) } } // SIL-CHECK: br{{.*}}line:[[@LINE]]:5:cleanup } // Test the scopes for the switch at line 20. // CHECK-SCOPES: call void @llvm.dbg{{.*}}metadata ![[P:[0-9]+]], // CHECK-SCOPES: call void @llvm.dbg{{.*}}metadata ![[X1:[0-9]+]], // CHECK-SCOPES-SAME: !dbg ![[X1LOC:[0-9]+]] // CHECK-SCOPES: call void @llvm.dbg{{.*}}metadata ![[Y1:[0-9]+]], // CHECK-SCOPES-SAME: !dbg ![[Y1LOC:[0-9]+]] // CHECK-SCOPES: call void @llvm.dbg{{.*}}metadata ![[X2:[0-9]+]], // CHECK-SCOPES-SAME: !dbg ![[X2LOC:[0-9]+]] // CHECK-SCOPES: call void @llvm.dbg{{.*}}metadata ![[Y2:[0-9]+]], // CHECK-SCOPES-SAME: !dbg ![[Y2LOC:[0-9]+]] // CHECK-SCOPES: call void @llvm.dbg{{.*}}metadata ![[X3:[0-9]+]], // CHECK-SCOPES-SAME: !dbg ![[X3LOC:[0-9]+]] // CHECK-SCOPES: call void @llvm.dbg{{.*}}metadata ![[Y3:[0-9]+]], // CHECK-SCOPES-SAME: !dbg ![[Y3LOC:[0-9]+]] // CHECK-SCOPES: call void @llvm.dbg{{.*}}metadata ![[X4:[0-9]+]], // CHECK-SCOPES-SAME: !dbg ![[X4LOC:[0-9]+]] // CHECK-SCOPES: call void @llvm.dbg{{.*}}metadata ![[Y4:[0-9]+]], // CHECK-SCOPES-SAME: !dbg ![[Y4LOC:[0-9]+]] // CHECK-SCOPES: call void @llvm.dbg{{.*}}metadata ![[X5:[0-9]+]], // CHECK-SCOPES-SAME: !dbg ![[X5LOC:[0-9]+]] // CHECK-SCOPES: call void @llvm.dbg{{.*}}metadata ![[Y5:[0-9]+]], // CHECK-SCOPES-SAME: !dbg ![[Y5LOC:[0-9]+]] // CHECK-SCOPES: call void @llvm.dbg{{.*}}metadata ![[X6:[0-9]+]], // CHECK-SCOPES-SAME: !dbg ![[X6LOC:[0-9]+]] // CHECK-SCOPES: call void @llvm.dbg{{.*}}metadata ![[Y6:[0-9]+]], // CHECK-SCOPES-SAME: !dbg ![[Y6LOC:[0-9]+]] // Verify that variables end up in separate appropriate scopes. // CHECK-SCOPES: ![[X1]] = {{.*}}name: "x", scope: ![[SCOPE1:[0-9]+]], {{.*}}line: 37 // CHECK-SCOPES: ![[SCOPE1]] = distinct !DILexicalBlock(scope: ![[SWITCH1:[0-9]+]], {{.*}}line: 37 // CHECK-SCOPES: ![[SWITCH1]] = distinct !DILexicalBlock({{.*}}, line: 20 // CHECK-SCOPES: ![[Y1]] = {{.*}}name: "y", scope: ![[SCOPE1]], {{.*}}line: 37 // CHECK-SCOPES: ![[X1LOC]] = {{.*}}line: 37 // CHECK-SCOPES: ![[Y1LOC]] = {{.*}}line: 37 // CHECK: !DILocation(line: [[@LINE+1]], }
apache-2.0
d340cb8650e34768ffed50ce34356f35
39.95
121
0.503297
3.060538
false
false
false
false
pointfreeco/swift-web
Web.playground/Pages/HttpPipeline.xcplaygroundpage/Contents.swift
1
493
import Foundation import Html import HttpPipeline import Prelude let doc: Node = .document( .html( .body( .p("Hello world!"), .p("Goodbye!"), .a(attributes: [.href("/")], "Home") ) ) ) let middleware = writeStatus(.ok) >=> writeHeader(.contentType(.html)) >=> closeHeaders >=> send(Data(render(doc).utf8)) let request = URLRequest(url: URL(string: "/")!) let conn = connection(from: request).map(const(Data())) print(middleware(conn).perform())
mit
931f96077d1f1ed97076734dffd88b5a
18.72
55
0.616633
3.423611
false
false
false
false
AkkeyLab/STYouTube
STYouTube/ViewController/VideoSelectViewController.swift
1
2451
// // VideoSelectViewController.swift // STYouTube // // Created by AKIO on 2017/06/25. // Copyright © 2017 AKIO. All rights reserved. // import UIKit class VideoSelectViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! let name: [String] = ["はじめしゃちょー", "HikakinTV", "瀬戸弘司", "すしらーめん"] let id: [String] = ["iUtiwvuFprI", "cQ9kGR8Mq0M", "rivpSDucSfk", "dcbmUiuHIeY"] override func viewDidLoad() { super.viewDidLoad() // どこでデータを渡しますか? tableView.dataSource = self // アクションをどこで受け取りますか? tableView.delegate = self } // 準備するセルの個数を設定 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return name.count } // セルを渡すところ func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "VideoCell") cell.textLabel?.text = name[indexPath.row] return cell } // タップされた時にどうするか func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // 遷移に用いるSegueをIDで指定 performSegue(withIdentifier: "videoSegue", sender: nil) } 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. if segue.identifier == "videoSegue" { // 選択した添字を取得 if let indexPath = tableView.indexPathForSelectedRow { // 遷移先のオブジェクトを生成 let videoPlayVC: VideoPlayViewController = segue.destination as! VideoPlayViewController // 遷移先に値をセット videoPlayVC.videoID = id[indexPath.row] } } } }
mit
1b649a02c4a534722693009fba8d4675
32.424242
119
0.660925
4.17803
false
false
false
false
agrippa1994/iOS-FH-Widget
FH-Widget/FHPI.swift
1
2516
// // FHPI.swift // iOS-FH-Widget // // Created by Manuel Leitold on 19.02.16. // Copyright © 2016 mani1337. All rights reserved. // import Foundation import EVReflection import XMLDictionary import ReactiveCocoa class EventInfo : EVObject { var title = "" var lecturer = "" var location = "" var type = "" var start = 0 var end = 0 var startDate: NSDate { return NSDate(timeIntervalSince1970: NSTimeInterval(start)) } var endDate: NSDate { return NSDate(timeIntervalSince1970: NSTimeInterval(end)) } } @objc(TimeTable) class TimeTable : EVObject { var __name = "" var status = "" var course = "" var year = 0 var Event: [EventInfo]? = [] var events : [EventInfo] { return Event ?? [] } } class FHPI { var department: String var year: Int init(department: String, year: Int) { self.department = department self.year = year } func timeTable(maxElements: Int?, filter: [String]?) -> SignalProducer<TimeTable, NSError> { let url = NSURL(string: "https://ws.fh-joanneum.at/getschedule.php?c=\(department)&y=\(year)&k=LOvkZCPesk")! let urlRequest = NSURLRequest(URL: url) let session = NSURLSession.sharedSession() return session.rac_dataWithRequest(urlRequest) .map { (data, response) -> TimeTable in return TimeTable(dictionary: NSDictionary(XMLData: data)) } .map({ (timeTable) -> TimeTable in if maxElements == nil && filter == nil { return timeTable } // Apply filter if var events = timeTable.Event where events.count > 0 && filter != nil { for var i = 0; i < events.count; i++ { for f in filter! { if events[i].type == f { events.removeAtIndex(i--) break } } } timeTable.Event = events } // Apply max count if maxElements != nil { if var events = timeTable.Event where events.count > maxElements! { events.removeRange(maxElements! ..< events.count) timeTable.Event = events } } return timeTable }) .observeOn(UIScheduler()) } }
mit
921aa94ad5f8d5401ff2458992c90d6f
26.648352
116
0.518887
4.556159
false
false
false
false
KrishMunot/swift
stdlib/public/core/ObjCMirrors.swift
6
2493
//===--- ObjCMirrors.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims #if _runtime(_ObjC) @_silgen_name("swift_ObjCMirror_count") func _getObjCCount(_: _MagicMirrorData) -> Int @_silgen_name("swift_ObjCMirror_subscript") func _getObjCChild<T>(_: Int, _: _MagicMirrorData) -> (T, _Mirror) func _getObjCSummary(_ data: _MagicMirrorData) -> String { let theDescription = _swift_stdlib_objcDebugDescription(data._loadValue()) return _cocoaStringToSwiftString_NonASCII(theDescription) } public // SPI(runtime) struct _ObjCMirror : _Mirror { let data: _MagicMirrorData public var value: Any { return data.objcValue } public var valueType: Any.Type { return data.objcValueType } public var objectIdentifier: ObjectIdentifier? { return data._loadValue() as ObjectIdentifier } public var count: Int { return _getObjCCount(data) } public subscript(i: Int) -> (String, _Mirror) { return _getObjCChild(i, data) } public var summary: String { return _getObjCSummary(data) } public var quickLookObject: PlaygroundQuickLook? { let object = _swift_ClassMirror_quickLookObject(data) return _getClassPlaygroundQuickLook(object) } public var disposition: _MirrorDisposition { return .objCObject } } public // SPI(runtime) struct _ObjCSuperMirror : _Mirror { let data: _MagicMirrorData public var value: Any { return data.objcValue } public var valueType: Any.Type { return data.objcValueType } // Suppress the value identifier for super mirrors. public var objectIdentifier: ObjectIdentifier? { return nil } public var count: Int { return _getObjCCount(data) } public subscript(i: Int) -> (String, _Mirror) { return _getObjCChild(i, data) } public var summary: String { return _getObjCSummary(data) } public var quickLookObject: PlaygroundQuickLook? { let object = _swift_ClassMirror_quickLookObject(data) return _getClassPlaygroundQuickLook(object) } public var disposition: _MirrorDisposition { return .objCObject } } #endif
apache-2.0
05839bc7bca4063fca4f19aec4d6f7a4
31.376623
80
0.685118
4.298276
false
false
false
false
aiaio/DesignStudioExpress
DesignStudioExpress/ViewModels/ActivityDetailViewModel.swift
1
2812
// // ActivityDetailViewModel.swift // DesignStudioExpress // // Created by Kristijan Perusko on 12/1/15. // Copyright © 2015 Alexander Interactive. All rights reserved. // import RealmSwift class ActivityDetailViewModel { lazy var realm = try! Realm() private var data: Activity! let saveActivityLabelText = "SAVE ACTIVITY" let saveNotesLabelText = "SAVE NOTES" let backLabelText = "CLOSE" let saveErrorMsg = "Couldn't save the activity: " let deleteErrorMsg = "Couldn't delete the activity" var title: String = "" var duration: Int = 0 var description: String = "" var notes: String = "" var editingEnabled: Bool { get { return !self.data.finished && self.data.id != AppDelegate.designStudio.currentActivity?.id && !self.locked } } // we're using this flag when loading/showing templates // which are locked for editing var locked: Bool { return self.data.challenge.designStudio.template } var saveActivityLabel: String { get { if self.editingEnabled { return self.saveActivityLabelText } else if self.locked { return self.backLabelText }else { return self.saveNotesLabelText } } } func setActivity(newActivity: Activity) { self.loadActivity(newActivity) } func loadActivity(newActivity: Activity) { self.data = newActivity self.title = newActivity.title self.duration = newActivity.duration self.description = newActivity.activityDescription self.notes = newActivity.notes } func saveActivity() -> String? { if self.locked { return nil } do { try realm.write { // we can update only notes when editing is disabled if self.editingEnabled { self.data.title = self.title self.data.duration = self.duration self.data.activityDescription = self.description } self.data.notes = self.notes self.realm.add(self.data, update: true) } } catch let error as NSError { print(self.saveErrorMsg + error.localizedDescription) return self.saveErrorMsg } return nil } func deleteActivity() -> String? { do { try realm.write { self.realm.delete(self.data) } } catch let error as NSError { print(self.deleteErrorMsg + error.localizedDescription) return self.deleteErrorMsg } return nil } }
mit
f7dffddb7eb1117ff2f9dbc27b254781
27.11
79
0.566346
4.805128
false
false
false
false
LYM-mg/DemoTest
其他功能/SwiftyDemo/Pods/Kingfisher/Sources/General/KingfisherManager.swift
5
20537
// // KingfisherManager.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// The downloading progress block type. /// The parameter value is the `receivedSize` of current response. /// The second parameter is the total expected data length from response's "Content-Length" header. /// If the expected length is not available, this block will not be called. public typealias DownloadProgressBlock = ((_ receivedSize: Int64, _ totalSize: Int64) -> Void) /// Represents the result of a Kingfisher retrieving image task. public struct RetrieveImageResult { /// Gets the image object of this result. public let image: Image /// Gets the cache source of the image. It indicates from which layer of cache this image is retrieved. /// If the image is just downloaded from network, `.none` will be returned. public let cacheType: CacheType /// The `Source` from which the retrieve task begins. public let source: Source } /// Main manager class of Kingfisher. It connects Kingfisher downloader and cache, /// to provide a set of convenience methods to use Kingfisher for tasks. /// You can use this class to retrieve an image via a specified URL from web or cache. public class KingfisherManager { /// Represents a shared manager used across Kingfisher. /// Use this instance for getting or storing images with Kingfisher. public static let shared = KingfisherManager() // Mark: Public Properties /// The `ImageCache` used by this manager. It is `ImageCache.default` by default. /// If a cache is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be /// used instead. public var cache: ImageCache /// The `ImageDownloader` used by this manager. It is `ImageDownloader.default` by default. /// If a downloader is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be /// used instead. public var downloader: ImageDownloader /// Default options used by the manager. This option will be used in /// Kingfisher manager related methods, as well as all view extension methods. /// You can also passing other options for each image task by sending an `options` parameter /// to Kingfisher's APIs. The per image options will overwrite the default ones, /// if the option exists in both. public var defaultOptions = KingfisherOptionsInfo.empty // Use `defaultOptions` to overwrite the `downloader` and `cache`. private var currentDefaultOptions: KingfisherOptionsInfo { return [.downloader(downloader), .targetCache(cache)] + defaultOptions } private let processingQueue: CallbackQueue private convenience init() { self.init(downloader: .default, cache: .default) } /// Creates an image setting manager with specified downloader and cache. /// /// - Parameters: /// - downloader: The image downloader used to download images. /// - cache: The image cache which stores memory and disk images. public init(downloader: ImageDownloader, cache: ImageCache) { self.downloader = downloader self.cache = cache let processQueueName = "com.onevcat.Kingfisher.KingfisherManager.processQueue.\(UUID().uuidString)" processingQueue = .dispatch(DispatchQueue(label: processQueueName)) } // Mark: Getting Images /// Gets an image from a given resource. /// /// - Parameters: /// - resource: The `Resource` object defines data information like key or URL. /// - options: Options to use when creating the animated image. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. `progressBlock` is always called in /// main queue. /// - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked /// from the `options.callbackQueue`. If not specified, the main queue will be used. /// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource, /// the started `DownloadTask` is returned. Otherwise, `nil` is returned. /// /// - Note: /// This method will first check whether the requested `resource` is already in cache or not. If cached, /// it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it /// will download the `resource`, store it in cache, then call `completionHandler`. /// @discardableResult public func retrieveImage( with resource: Resource, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask? { let source = Source.network(resource) return retrieveImage( with: source, options: options, progressBlock: progressBlock, completionHandler: completionHandler ) } /// Gets an image from a given resource. /// /// - Parameters: /// - source: The `Source` object defines data information from network or a data provider. /// - options: Options to use when creating the animated image. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. `progressBlock` is always called in /// main queue. /// - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked /// from the `options.callbackQueue`. If not specified, the main queue will be used. /// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource, /// the started `DownloadTask` is returned. Otherwise, `nil` is returned. /// /// - Note: /// This method will first check whether the requested `source` is already in cache or not. If cached, /// it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it /// will try to load the `source`, store it in cache, then call `completionHandler`. /// public func retrieveImage( with source: Source, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask? { let options = currentDefaultOptions + (options ?? .empty) var info = KingfisherParsedOptionsInfo(options) if let block = progressBlock { info.onDataReceived = (info.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] } return retrieveImage( with: source, options: info, completionHandler: completionHandler) } func retrieveImage( with source: Source, options: KingfisherParsedOptionsInfo, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask? { if options.forceRefresh { return loadAndCacheImage( source: source, options: options, completionHandler: completionHandler)?.value } else { let loadedFromCache = retrieveImageFromCache( source: source, options: options, completionHandler: completionHandler) if loadedFromCache { return nil } if options.onlyFromCache { let error = KingfisherError.cacheError(reason: .imageNotExisting(key: source.cacheKey)) completionHandler?(.failure(error)) return nil } return loadAndCacheImage( source: source, options: options, completionHandler: completionHandler)?.value } } func provideImage( provider: ImageDataProvider, options: KingfisherParsedOptionsInfo, completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)?) { guard let completionHandler = completionHandler else { return } provider.data { result in switch result { case .success(let data): (options.processingQueue ?? self.processingQueue).execute { let processor = options.processor let processingItem = ImageProcessItem.data(data) guard let image = processor.process(item: processingItem, options: options) else { options.callbackQueue.execute { let error = KingfisherError.processorError( reason: .processingFailed(processor: processor, item: processingItem)) completionHandler(.failure(error)) } return } options.callbackQueue.execute { let result = ImageLoadingResult(image: image, url: nil, originalData: data) completionHandler(.success(result)) } } case .failure(let error): options.callbackQueue.execute { let error = KingfisherError.imageSettingError( reason: .dataProviderError(provider: provider, error: error)) completionHandler(.failure(error)) } } } } @discardableResult func loadAndCacheImage( source: Source, options: KingfisherParsedOptionsInfo, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask.WrappedTask? { func cacheImage(_ result: Result<ImageLoadingResult, KingfisherError>) { switch result { case .success(let value): // Add image to cache. let targetCache = options.targetCache ?? self.cache targetCache.store( value.image, original: value.originalData, forKey: source.cacheKey, options: options, toDisk: !options.cacheMemoryOnly) { _ in if options.waitForCache { let result = RetrieveImageResult(image: value.image, cacheType: .none, source: source) completionHandler?(.success(result)) } } // Add original image to cache if necessary. let needToCacheOriginalImage = options.cacheOriginalImage && options.processor != DefaultImageProcessor.default if needToCacheOriginalImage { let originalCache = options.originalCache ?? targetCache originalCache.storeToDisk( value.originalData, forKey: source.cacheKey, processorIdentifier: DefaultImageProcessor.default.identifier, expiration: options.diskCacheExpiration) } if !options.waitForCache { let result = RetrieveImageResult(image: value.image, cacheType: .none, source: source) completionHandler?(.success(result)) } case .failure(let error): completionHandler?(.failure(error)) } } switch source { case .network(let resource): let downloader = options.downloader ?? self.downloader guard let task = downloader.downloadImage( with: resource.downloadURL, options: options, completionHandler: cacheImage) else { return nil } return .download(task) case .provider(let provider): provideImage(provider: provider, options: options, completionHandler: cacheImage) return .dataProviding } } /// Retrieves image from memory or disk cache. /// /// - Parameters: /// - source: The target source from which to get image. /// - key: The key to use when caching the image. /// - url: Image request URL. This is not used when retrieving image from cache. It is just used for /// `RetrieveImageResult` callback compatibility. /// - options: Options on how to get the image from image cache. /// - completionHandler: Called when the image retrieving finishes, either with succeeded /// `RetrieveImageResult` or an error. /// - Returns: `true` if the requested image or the original image before being processed is existing in cache. /// Otherwise, this method returns `false`. /// /// - Note: /// The image retrieving could happen in either memory cache or disk cache. The `.processor` option in /// `options` will be considered when searching in the cache. If no processed image is found, Kingfisher /// will try to check whether an original version of that image is existing or not. If there is already an /// original, Kingfisher retrieves it from cache and processes it. Then, the processed image will be store /// back to cache for later use. func retrieveImageFromCache( source: Source, options: KingfisherParsedOptionsInfo, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> Bool { // 1. Check whether the image was already in target cache. If so, just get it. let targetCache = options.targetCache ?? cache let key = source.cacheKey let targetImageCached = targetCache.imageCachedType( forKey: key, processorIdentifier: options.processor.identifier) let validCache = targetImageCached.cached && (options.fromMemoryCacheOrRefresh == false || targetImageCached == .memory) if validCache { targetCache.retrieveImage(forKey: key, options: options) { result in guard let completionHandler = completionHandler else { return } options.callbackQueue.execute { result.match( onSuccess: { cacheResult in let value: Result<RetrieveImageResult, KingfisherError> if let image = cacheResult.image { value = result.map { RetrieveImageResult(image: image, cacheType: $0.cacheType, source: source) } } else { value = .failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key))) } completionHandler(value) }, onFailure: { _ in completionHandler(.failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key)))) } ) } } return true } // 2. Check whether the original image exists. If so, get it, process it, save to storage and return. let originalCache = options.originalCache ?? targetCache // No need to store the same file in the same cache again. if originalCache === targetCache && options.processor == DefaultImageProcessor.default { return false } // Check whether the unprocessed image existing or not. let originalImageCached = originalCache.imageCachedType( forKey: key, processorIdentifier: DefaultImageProcessor.default.identifier).cached if originalImageCached { // Now we are ready to get found the original image from cache. We need the unprocessed image, so remove // any processor from options first. var optionsWithoutProcessor = options optionsWithoutProcessor.processor = DefaultImageProcessor.default originalCache.retrieveImage(forKey: key, options: optionsWithoutProcessor) { result in result.match( onSuccess: { cacheResult in guard let image = cacheResult.image else { return } let processor = options.processor (options.processingQueue ?? self.processingQueue).execute { let item = ImageProcessItem.image(image) guard let processedImage = processor.process(item: item, options: options) else { let error = KingfisherError.processorError( reason: .processingFailed(processor: processor, item: item)) options.callbackQueue.execute { completionHandler?(.failure(error)) } return } var cacheOptions = options cacheOptions.callbackQueue = .untouch targetCache.store( processedImage, forKey: key, options: cacheOptions, toDisk: !options.cacheMemoryOnly) { _ in if options.waitForCache { let value = RetrieveImageResult(image: processedImage, cacheType: .none, source: source) options.callbackQueue.execute { completionHandler?(.success(value)) } } } if !options.waitForCache { let value = RetrieveImageResult(image: processedImage, cacheType: .none, source: source) options.callbackQueue.execute { completionHandler?(.success(value)) } } } }, onFailure: { _ in // This should not happen actually, since we already confirmed `originalImageCached` is `true`. // Just in case... options.callbackQueue.execute { completionHandler?(.failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key)))) } } ) } return true } return false } }
mit
bbee14b0a56686d19621d9d2f4de446c
46.760465
124
0.592686
5.809618
false
false
false
false
zhoujihang/SwiftNetworkAgent
SwiftNetworkAgent/SwiftNetworkAgent/Tool/LoadingHUD/LoadingTool.swift
1
3733
// // LoadingTool.swift // SwiftNetworkAgent // // Created by 周际航 on 2016/12/29. // Copyright © 2016年 com.maramara. All rights reserved. // import UIKit class LoadingTool { static let tool = LoadingTool() var loadingView: LoadingView? // window上的弹窗 var loadingVCArray: [UIViewController] = [] // 记录正在显示loading视图的 vc } // window 级别的弹窗 extension LoadingTool { static func show() { guard self.tool.loadingView == nil else {return} guard let window = UIApplication.shared.delegate?.window else {return} guard let win = window else {return} if let currentVC = win.ext_currentViewController() { currentVC.ldt_hideLoading(true) } self.tool.loadingView = LoadingView.addTo(win) } static func dismiss() { guard self.tool.loadingView != nil else {return} guard let window = UIApplication.shared.delegate?.window else {return} guard let win = window else {return} if let currentVC = win.ext_currentViewController() { currentVC.ldt_hideLoading(false) } self.tool.loadingView?.removeFromSuperview() self.tool.loadingView = nil } } // MARK: - 扩展 BaseViewController loading弹窗扩展 private var kLoadingViewKey: Void? private var kLoadingCountKey: Void? private var kIsHideLoadingKey: Void? extension UIViewController { // loading视图 private var ldt_loadingView: LoadingView? { get {return objc_getAssociatedObject(self, &kLoadingViewKey) as? LoadingView} set {objc_setAssociatedObject(self, &kLoadingViewKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)} } // loading计数器 private var ldt_loadingCount: NSNumber { get {return (objc_getAssociatedObject(self, &kLoadingCountKey) as? NSNumber) ?? 0} set {objc_setAssociatedObject(self, &kLoadingCountKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)} } // 隐藏vc的loading private var ldt_isHideLoading: NSNumber { get {return (objc_getAssociatedObject(self, &kIsHideLoadingKey) as? NSNumber) ?? 0} set {objc_setAssociatedObject(self, &kIsHideLoadingKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)} } // 修改loading计数 func ldt_loadingCountAdd() { let count = self.ldt_loadingCount.intValue + 1 self.ldt_loadingCount = NSNumber(integerLiteral: count) self.ldt_showLoading() "\(self) add loadingCount \(count)".ext_debugPrint() } func ldt_loadingCountReduce() { let count = self.ldt_loadingCount.intValue > 0 ? self.ldt_loadingCount.intValue-1 : 0 self.ldt_loadingCount = NSNumber(integerLiteral: count) count > 0 ? self.ldt_showLoading() : self.ldt_dismissLoading() "\(self) reduce loadingCount \(count)".ext_debugPrint() } private func ldt_showLoading() { guard self.ldt_loadingView == nil else {return} let loadingView = LoadingView.addTo(self.view) self.ldt_loadingView = loadingView let isHide = self.ldt_isHideLoading==0 ? false : true loadingView.isHidden = isHide } private func ldt_dismissLoading() { guard let loadingView = self.ldt_loadingView else {return} loadingView.removeFromSuperview() self.ldt_loadingView = nil } fileprivate func ldt_hideLoading(_ hide: Bool) { guard let loadingView = self.ldt_loadingView else {return} guard self.ldt_loadingCount.intValue > 0 else {return} loadingView.isHidden = hide self.ldt_isHideLoading = NSNumber(booleanLiteral: hide) } }
mit
618a9bf9bf5a7867bbd76ee80f19f71a
34.803922
110
0.658269
4.16895
false
false
false
false
duke-compsci408-fall2014/Pawns
BayAreaChess/BayAreaChess/UserUpdate.swift
1
2870
// // UserUpdate.swift // BayAreaChess // // Created by Carlos Reyes on 11/4/14. // Copyright (c) 2014 Bay Area Chess. All rights reserved. // import UIKit class UserUpdate : UIViewController { @IBOutlet var first_name : UITextField!; @IBOutlet var last_name : UITextField!; @IBOutlet var email : UITextField!; @IBOutlet var username : UITextField!; @IBOutlet var phone : UITextField!; let AMP : String = "&"; var myUsername : String?; var request = HTTPTask(); override func viewDidLoad() { super.viewDidLoad(); first_name.attributedPlaceholder = NSAttributedString(string:Constants.Label.lastName, attributes:[NSForegroundColorAttributeName: UIColor.lightTextColor()]); last_name.attributedPlaceholder = NSAttributedString(string:Constants.Label.lastName, attributes:[NSForegroundColorAttributeName: UIColor.lightTextColor()]); email.attributedPlaceholder = NSAttributedString(string:Constants.Label.email, attributes:[NSForegroundColorAttributeName: UIColor.lightTextColor()]); username.attributedPlaceholder = NSAttributedString(string:Constants.Label.user, attributes:[NSForegroundColorAttributeName: UIColor.lightTextColor()]); phone.attributedPlaceholder = NSAttributedString(string:Constants.Label.phone, attributes:[NSForegroundColorAttributeName: UIColor.lightTextColor()]); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning(); } /** * Button press sends PUT event to the API server. Event updates the user information with * values inputted in the fields, such as an updated email or name * * @param sender Sending object */ @IBAction func buttonPressed(sender: AnyObject) { var obj : Dictionary<String, String> = ["email":self.email.text, "first_name":self.first_name.text, "last_name":self.last_name.text, "username":self.username.text]; var urlString : String = Constants.Base.updateURL + self.myUsername! + "/"; request.requestSerializer = JSONRequestSerializer(); request.PUT(urlString, parameters: obj, success: {(response: HTTPResponse) in let data : NSData = response.responseObject as NSData; let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as NSDictionary; (self.presentingViewController? as User).populateFields(json); self.dismissViewControllerAnimated(true, completion: nil); },failure: {(error: NSError, response: HTTPResponse?) in println("There was an error, LOL"); }); } @IBAction func back() { dismissViewControllerAnimated(true, completion: nil); } }
mit
8d2d09ad291b810da63c862f9af0cd9f
40
172
0.66899
5.227687
false
false
false
false
zalando/ModularDemo
ZContainer/ZContainerTests/EmptyContainerTests.swift
1
1523
// // EmptyContainerTests.swift // ZContainerTests // // Created by Oliver Eikemeier on 25.09.15. // Copyright © 2015 Zalando SE. All rights reserved. // import XCTest @testable import ZContainer class EmptyContainerTests: XCTestCase { var registry: ZRegistry! var container: ZContainer! override func setUp() { super.setUp() registry = ZContainer.createRegistry(check: false) container = registry.container() } func testNonexistent() { let service: Service! service = container.resolve() XCTAssertNil(service) } func testFactory() { registry.register { ServiceImplementation() as Service } let service1: Service let service2: Service service1 = container.resolve() service2 = container.resolve() XCTAssertNotEqual(service1.identity, service2.identity) } func testSingletonFactory() { registry.register { ServiceImplementation.sharedInstance() as Service } let service1: Service let service2: Service service1 = container.resolve() service2 = container.resolve() XCTAssertEqual(service1.identity, service2.identity) } func testLookupPerformance() { registry.register { ServiceImplementation.sharedInstance() as Service } measureBlock { for _ in 1...10_000 { let _: Service = self.container.resolve() } } } }
bsd-2-clause
50b9ba8bd106758e62a1a04e38661821
25.701754
79
0.618265
4.847134
false
true
false
false
huangboju/Moots
Examples/Lumia/Lumia/Component/CustomPaging/Collection/SliderView.swift
1
5254
// // SliderView.swift // CustomPaging // // Created by Ilya Lobanov on 27/08/2018. // Copyright © 2018 Ilya Lobanov. All rights reserved. // import UIKit final class CPSliderView: UIView { var value: CGFloat { get { return CGFloat(slider.value) } set { slider.value = Float(newValue) updateValueLabel() } } var defaultValue: CGFloat? = nil var limits: ClosedRange<CGFloat> { get { return CGFloat(slider.minimumValue)...CGFloat(slider.maximumValue) } set { slider.minimumValue = Float(newValue.lowerBound) slider.maximumValue = Float(newValue.upperBound) updateLimitTitles() } } var title: String = "" { didSet { titleButton.setTitle(title, for: .normal) } } var minTitle: String? { didSet { updateLimitTitles() } } var maxTitle: String? { didSet { updateLimitTitles() } } var onChange: ((CGFloat) -> Void)? = nil override init(frame: CGRect) { super.init(frame: frame) setupViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private private let slider = UISlider() private let titleButton = UIButton(type: .system) private let minLabel = UILabel() private let maxLabel = UILabel() private let valueLabel = UILabel() private func setupViews() { addSubview(slider) slider.addTarget(self, action: #selector(CPSliderView.handleSlider), for: .valueChanged) slider.thumbTintColor = .applicationTintColor slider.minimumTrackTintColor = .lightGray slider.maximumTrackTintColor = .lightGray addSubview(titleButton) titleButton.titleLabel?.font = .systemFont(ofSize: 16, weight: .bold) titleButton.contentHorizontalAlignment = .left titleButton.tintColor = .black titleButton.addTarget(self, action: #selector(handleTitleButton), for: .touchUpInside) addSubview(minLabel) minLabel.font = .systemFont(ofSize: 14, weight: .regular) addSubview(maxLabel) maxLabel.textAlignment = .right maxLabel.font = .systemFont(ofSize: 14, weight: .regular) addSubview(valueLabel) valueLabel.textAlignment = .center valueLabel.font = .systemFont(ofSize: 14, weight: .bold) setupLayout() updateLimitTitles() } private func setupLayout() { titleButton.translatesAutoresizingMaskIntoConstraints = false titleButton.leftAnchor.constraint(equalTo: leftAnchor).isActive = true titleButton.topAnchor.constraint(equalTo: topAnchor).isActive = true titleButton.rightAnchor.constraint(equalTo: rightAnchor).isActive = true slider.translatesAutoresizingMaskIntoConstraints = false slider.leftAnchor.constraint(equalTo: leftAnchor).isActive = true slider.rightAnchor.constraint(equalTo: rightAnchor).isActive = true minLabel.translatesAutoresizingMaskIntoConstraints = false minLabel.leftAnchor.constraint(equalTo: leftAnchor).isActive = true minLabel.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true maxLabel.translatesAutoresizingMaskIntoConstraints = false maxLabel.rightAnchor.constraint(equalTo: rightAnchor).isActive = true maxLabel.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true valueLabel.translatesAutoresizingMaskIntoConstraints = false valueLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true valueLabel.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true minLabel.rightAnchor.constraint(equalTo: valueLabel.leftAnchor).isActive = true valueLabel.rightAnchor.constraint(equalTo: maxLabel.leftAnchor).isActive = true titleButton.bottomAnchor.constraint(equalTo: slider.topAnchor).isActive = true slider.bottomAnchor.constraint(equalTo: maxLabel.topAnchor).isActive = true slider.bottomAnchor.constraint(equalTo: minLabel.topAnchor).isActive = true } private func updateValueLabel() { valueLabel.text = value.stringDescription } private func updateLimitTitles() { minLabel.text = minTitle ?? limits.lowerBound.stringDescription maxLabel.text = maxTitle ?? limits.upperBound.stringDescription } @objc private func handleSlider() { updateValueLabel() onChange?(value) } @objc private func handleTitleButton() { if let v = defaultValue { value = v } } } private extension CGFloat { var stringDescription: String { let formatter = NumberFormatter() formatter.minimumIntegerDigits = 1 formatter.minimumFractionDigits = 0 formatter.maximumFractionDigits = 4 return formatter.string(from: NSNumber(value: Double(self))) ?? "\(self)" } }
mit
e75c31266356aedff02f5192aba27261
31.425926
96
0.643442
5.263527
false
false
false
false
alimysoyang/CommunicationDebugger
CommunicationDebugger/AYHButton.swift
1
3492
// // AYHButton.swift // CommunicationDebugger // // Created by alimysoyang on 15/11/23. // Copyright © 2015年 alimysoyang. All rights reserved. // import Foundation class AYHButton: UIButton { // MARK: - properties private let defaultBackgroundColor:UIColor = UIColor(red: 49.0 / 255.0, green: 182.0 / 255.0, blue: 9.0 / 255.0, alpha: 1.0); private let disabledBackgroundColor:UIColor = UIColor(red: 91.0 / 255.0, green: 213.0 / 255.0, blue: 85.0 / 255.0, alpha: 1.0); private let titleDefaultColor:UIColor = UIColor.whiteColor(); private let titleDisabledColor:UIColor = UIColor(red: 150.0 / 255.0, green: 230.0 / 255.0, blue: 146.0 / 255.0, alpha: 1.0); private let titleHighlightedColor:UIColor = UIColor(red: 85.0 / 255.0, green: 197.0 / 255.0, blue: 80.0 / 255.0, alpha: 1.0); private let borderDefaultColor:UIColor = UIColor(red: 39.0 / 255.0, green: 144.0 / 255.0, blue: 20.0 / 255.0, alpha: 1.0); private let borderDisabledColor:UIColor = UIColor(red: 102.0 / 255.0, green: 188.0 / 255.0, blue: 98.0 / 255.0, alpha: 1.0); private let borderHighlightedColor:UIColor = UIColor(red: 34.0 / 255.0, green: 128.0 / 255.0, blue: 18.0 / 255.0, alpha: 1.0); private let touchLayerBackgroundColor:UIColor = UIColor(red: 43.0 / 255.0, green: 160.0 / 255.0, blue: 8.0 / 255.0, alpha: 1.0); private var touchLayer:CALayer?; override var enabled:Bool { didSet { if enabled { self.backgroundColor = self.defaultBackgroundColor; self.layer.borderColor = self.borderDefaultColor.CGColor; } else { self.backgroundColor = self.disabledBackgroundColor; self.layer.borderColor = self.borderDisabledColor.CGColor; } } } // MARK: - life cycle override init(frame: CGRect) { super.init(frame: frame); self.layer.cornerRadius = 5.0; self.layer.borderWidth = 1.0; self.enabled = false; self.setTitleColor(self.titleDefaultColor, forState: UIControlState.Normal); self.setTitleColor(self.titleDisabledColor, forState: UIControlState.Disabled); self.setTitleColor(self.titleHighlightedColor, forState: UIControlState.Highlighted); self.touchLayer = CALayer(); self.touchLayer?.frame = CGRectMake(0.0, 0.0, frame.size.width, frame.size.height); self.touchLayer?.cornerRadius = 5.0; self.touchLayer?.backgroundColor = self.touchLayerBackgroundColor.CGColor; } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event); self.interfaceHighlighted(); } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesEnded(touches, withEvent: event); self.interfaceNormal(); } // MARK: - private methods private func interfaceNormal() { self.layer.borderColor = self.borderDefaultColor.CGColor; self.touchLayer?.removeFromSuperlayer(); } private func interfaceHighlighted() { self.layer.borderColor = self.borderHighlightedColor.CGColor; self.layer.addSublayer(self.touchLayer!); self.bringSubviewToFront(self.titleLabel!); } }
mit
d8ad76ec1d2ca6533cacf1e010b40d47
38.213483
132
0.640871
3.951302
false
false
false
false
jkascend/free-blur
free-blur/BlurSelectionView.swift
1
1075
// // SelectBlur.swift // free-blur // // Created by Justin Kambic on 6/3/17. // import UIKit import CoreImage class BlurSelectionView : UIView { var shouldBlurFace = false var ciFaceCoords : CGRect init(frame: CGRect, ciFaceCoords: CGRect) { self.ciFaceCoords = ciFaceCoords super.init(frame: frame) self.isUserInteractionEnabled = true self.layer.borderWidth = 1 self.layer.borderColor = UIColor.yellow.cgColor self.clipsToBounds = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) if self.shouldBlurFace { self.shouldBlurFace = false self.backgroundColor = UIColor.clear } else { self.shouldBlurFace = true self.backgroundColor = UIColor(red: 0.239, green: 0.863, blue: 0.265, alpha: 0.685) } } }
mit
8427f850b2915f9d10cce63fd7ab98e5
25.219512
95
0.615814
4.166667
false
false
false
false
hackersatcambridge/hac-website
Sources/HaCWebsiteLib/Models/Workshop+init.swift
1
9819
import Foundation import Yaml private let filePaths = ( metadata: "/.hac_workshop/metadata.yaml", description: "/.hac_workshop/description.md", prerequisites: "/.hac_workshop/prerequisites.md", promoImagesDirectory: "/.hac_workshop/promo_images", notesMarkdown: "/.hac_workshop/notes.md", examplesDirectory: "/", presenterGuide: "/.hac_workshop/presenter_guide.md", setupInstructions: "/.hac_workshop/setup_instructions.md" ) private let validImageExtensions = ["jpg", "svg", "png", "gif"] extension Workshop { /// Create a Workshop from a local path init(localPath: String, headCommitSha: String) throws { workshopId = try Workshop.getWorkshopId(localPath: localPath) let metadata = try Workshop.getMetadata(localPath: localPath) let builder = WorkshopBuilder(localPath: localPath, commitSha: headCommitSha, workshopId: workshopId, metadata: metadata) presenterGuide = try builder.getPresenterGuide() promoImageBackground = try builder.getPromoImageBackground() promoImageForeground = try builder.getPromoImageForeground().absoluteString description = try builder.getDescription() prerequisites = try builder.getPrerequisites() setupInstructions = try builder.getSetupInstructions() examplesLink = try builder.getExamplesLink() notes = try builder.getNotes() title = try builder.getTitle() contributors = try builder.getContributors() thanks = try builder.getThanks() furtherReadingLinks = try builder.getFurtherReadingLinks() recordingLink = try builder.getRecordingLink() slidesLink = try builder.getSlidesLink() tags = try builder.getTags() license = try builder.getLicense() } private static func getWorkshopId(localPath: String) throws -> String { let directoryName = localPath.components(separatedBy: "/").last ?? localPath if directoryName.hasPrefix("workshop-") { return String(directoryName.dropFirst("workshop-".count)) } else { throw WorkshopError.invalidPath } } private static func getMetadata(localPath: String) throws -> Yaml { let metadataString: String do { metadataString = try String(contentsOfFile: localPath + filePaths.metadata, encoding: .utf8) } catch { throw WorkshopError.missingMetadata } return try Yaml.load(metadataString) } } private enum WorkshopError: Swift.Error { case invalidPath case missingMetadata case malformedMetadata(String) case missingPromoImageBackground case missingPromoImageForeground case missingMetadataKey(String) case multiplePromoImageForegrounds case multiplePromoImageBackgrounds case invalidPromoImageForegroundFormat case invalidPromoImageBackgroundFormat case missingMarkdown(String) case badURLInNotes(String) case emptyExamples case invalidURL(String) } private struct WorkshopBuilder { let localPath: String let commitSha: String let workshopId: String let metadata: Yaml func getMarkdown(relativePath: String) throws -> Markdown { do { let markdown = try Markdown(contentsOfFile: localPath + relativePath) return markdown.resolvingRelativeURLs(relativeTo: try fileServingUrl(relativePath: relativePath)) } catch { throw WorkshopError.missingMarkdown(relativePath) } } func getDescription() throws -> Markdown { return try getMarkdown(relativePath: filePaths.description) } func getPrerequisites() throws -> Markdown { return try getMarkdown(relativePath: filePaths.prerequisites) } func getSetupInstructions() throws -> Markdown { return try getMarkdown(relativePath: filePaths.setupInstructions) } func getPresenterGuide() throws -> Markdown? { return try? getMarkdown(relativePath: filePaths.presenterGuide) } func getNotes() throws -> Markdown { return try getMarkdown(relativePath: filePaths.notesMarkdown) } private func repoUrl(origin: String, relativePath: String) throws -> URL { let urlString = "\(origin)hackersatcambridge/workshop-\(workshopId)\(relativePath)" if let url = URL(string: urlString) { return url } else { throw WorkshopError.invalidURL(urlString) } } func fileServingUrl(relativePath: String) throws -> URL { return try repoUrl(origin: "https://cdn.jsdelivr.net/gh/", relativePath: "@\(commitSha)\(relativePath)") } func remoteRepoUrl(relativePath: String) throws -> URL { return try repoUrl(origin: "https://github.com/", relativePath: "/tree/master\(relativePath)"); } /// Return the CDN url of the foreground of the promotional image func getPromoImageForeground() throws -> URL { let promoImageFileNames = try FileManager.default.contentsOfDirectory(atPath: localPath + filePaths.promoImagesDirectory) let foregroundImageFileNames = promoImageFileNames.filter { $0.hasPrefix("fg.") } guard foregroundImageFileNames.count == 1 else { if foregroundImageFileNames.count < 1 { throw WorkshopError.missingPromoImageForeground } else { throw WorkshopError.multiplePromoImageForegrounds } } let foregroundImageFileName = foregroundImageFileNames[0] guard validImageExtensions.contains(getFileExtension(fromPath: foregroundImageFileName) ?? "") else { throw WorkshopError.invalidPromoImageForegroundFormat } let relativePathFromRepo = filePaths.promoImagesDirectory + "/" + foregroundImageFileName return try fileServingUrl(relativePath: relativePathFromRepo) } /// The `Background` of the promotional image func getPromoImageBackground() throws -> Background { let promoImageFileNames = try FileManager.default.contentsOfDirectory(atPath: localPath + filePaths.promoImagesDirectory) let backgroundFileNames = promoImageFileNames.filter { $0.hasPrefix("bg.") } guard backgroundFileNames.count == 1 else { if backgroundFileNames.count < 1 { throw WorkshopError.missingPromoImageBackground } else { throw WorkshopError.multiplePromoImageBackgrounds } } let backgroundFileName = backgroundFileNames[0] let fileExtension = getFileExtension(fromPath: backgroundFileName) ?? "" if fileExtension == "color" { let fileContents = try String(contentsOfFile: localPath + filePaths.promoImagesDirectory + "/" + backgroundFileName, encoding: .utf8) return Background.color(fileContents) } else if validImageExtensions.contains(fileExtension) { // Get the CDN url of the image let relativePathFromRepo = filePaths.promoImagesDirectory + "/" + backgroundFileName return Background.image(try fileServingUrl(relativePath: relativePathFromRepo).absoluteString) } else { throw WorkshopError.invalidPromoImageBackgroundFormat } } func getExamplesLink() throws -> URL? { let examplesPath = localPath + filePaths.examplesDirectory // If there are non-hidden directories in the examples path, link to it if try FileManager.default.contentsOfDirectory(atPath: examplesPath).contains { !$0.starts(with: ".") } { return try remoteRepoUrl(relativePath: filePaths.examplesDirectory) } else { return nil } } func getTitle() throws -> String { if let title = metadata["title"].string { return title } else { throw WorkshopError.malformedMetadata("Missing title") } } func getContributors() throws -> [String] { return try stringsArray(for: "contributors", in: metadata) } func getThanks() throws -> [String] { do { return try stringsArray(for: "thanks", in: metadata) } catch WorkshopError.missingMetadataKey(_) { return [] } } func getFurtherReadingLinks() throws -> [Link] { guard let links = metadata["further_reading_links"].array else { return [] } return try links.map({ guard let text = $0["text"].string, let urlString = $0["url"].string else { throw WorkshopError.malformedMetadata("Links should have a 'text' and a 'url' property") } guard let url = URL(string: urlString) else { throw WorkshopError.malformedMetadata("Links should have valid URLs") } return Link(text: text, url: url) }) } func getRecordingLink() throws -> URL? { guard let urlString = metadata["recording_link"].string else { return nil } guard let url = URL(string: urlString) else { throw WorkshopError.malformedMetadata("Recording link should be a valid URL") } return url } func getSlidesLink() throws -> URL? { guard let urlString = metadata["slides_link"].string else { return nil } guard let url = URL(string: urlString, relativeTo: try fileServingUrl(relativePath: filePaths.metadata)) else { throw WorkshopError.malformedMetadata("Slides link should be a valid URL") } return url } func getTags() throws -> [String] { return try stringsArray(for: "tags", in: metadata) } func getLicense() throws -> String { if let license = metadata["license"].string { return license } else { throw WorkshopError.malformedMetadata("Missing license") } } } /// Get the extension of a file. Returns nil if no file extension is present private func getFileExtension(fromPath filePath: String) -> String? { if filePath.contains(".") { return filePath.components(separatedBy: ".").last } else { return nil } } private func stringsArray(for key: Yaml, in metadata: Yaml) throws -> [String] { guard let values = metadata[key].array else { throw WorkshopError.missingMetadataKey("Missing \(key) list") } return try values.map({ if let stringValue = $0.string { return stringValue } else { throw WorkshopError.malformedMetadata("Expected values in \(key) to be strings") } }) }
mit
9be32db4a94d12322939cd2cea1cb8f5
32.742268
139
0.713922
4.550046
false
false
false
false
grpc/grpc-swift
Tests/GRPCTests/ClientCancellingTests.swift
1
2835
/* * Copyright 2019, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import EchoModel import Foundation import GRPC import XCTest class ClientCancellingTests: EchoTestCaseBase { func testUnary() { let statusReceived = self.expectation(description: "status received") let responseReceived = self.expectation(description: "response received") let call = client.get(Echo_EchoRequest(text: "foo bar baz")) call.cancel(promise: nil) call.response.whenFailure { error in XCTAssertEqual((error as? GRPCStatus)?.code, .cancelled) responseReceived.fulfill() } call.status.whenSuccess { status in XCTAssertEqual(status.code, .cancelled) statusReceived.fulfill() } waitForExpectations(timeout: self.defaultTestTimeout) } func testClientStreaming() throws { let statusReceived = self.expectation(description: "status received") let responseReceived = self.expectation(description: "response received") let call = client.collect() call.cancel(promise: nil) call.response.whenFailure { error in XCTAssertEqual((error as? GRPCStatus)?.code, .cancelled) responseReceived.fulfill() } call.status.whenSuccess { status in XCTAssertEqual(status.code, .cancelled) statusReceived.fulfill() } waitForExpectations(timeout: self.defaultTestTimeout) } func testServerStreaming() { let statusReceived = self.expectation(description: "status received") let call = client.expand(Echo_EchoRequest(text: "foo bar baz")) { _ in XCTFail("response should not be received after cancelling call") } call.cancel(promise: nil) call.status.whenSuccess { status in XCTAssertEqual(status.code, .cancelled) statusReceived.fulfill() } waitForExpectations(timeout: self.defaultTestTimeout) } func testBidirectionalStreaming() { let statusReceived = self.expectation(description: "status received") let call = client.update { _ in XCTFail("response should not be received after cancelling call") } call.cancel(promise: nil) call.status.whenSuccess { status in XCTAssertEqual(status.code, .cancelled) statusReceived.fulfill() } waitForExpectations(timeout: self.defaultTestTimeout) } }
apache-2.0
be3f3f9404c939ce775008ca808efde7
29.483871
77
0.717813
4.492868
false
true
false
false
grpc/grpc-swift
Performance/QPSBenchmark/Sources/QPSBenchmark/Runtime/ClientUtilities.swift
1
1592
/* * Copyright 2020, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import GRPC import NIOCore extension Grpc_Testing_ClientConfig { /// Work out how many theads to use - defaulting to core count if not specified. /// - returns: The number of threads to use. func threadsToUse() -> Int { return self.asyncClientThreads > 0 ? Int(self.asyncClientThreads) : System.coreCount } /// Get the server targets parsed into a useful format. /// - returns: Server targets as hosts and ports. func parsedServerTargets() throws -> [ConnectionTarget] { let serverTargets = self.serverTargets return try serverTargets.map { target in if let splitIndex = target.lastIndex(of: ":") { let host = target[..<splitIndex] let portString = target[(target.index(after: splitIndex))...] if let port = Int(portString) { return ConnectionTarget.host(String(host), port: port) } } throw GRPCStatus(code: .invalidArgument, message: "Server targets could not be parsed") } } }
apache-2.0
79bd29d693f66b3830e7185f83274829
36.904762
93
0.699749
4.245333
false
false
false
false
nathanlanza/Reuse
Source/UIView+Extension.swift
1
559
import UIKit public extension UIView { public func setBorder(color: UIColor, width: CGFloat, radius: CGFloat) { layer.borderColor = color.cgColor layer.borderWidth = width layer.cornerRadius = radius } public func setShadow(offsetWidth: CGFloat, offsetHeight: CGFloat, radius: CGFloat, opacity: Float, color: UIColor) { layer.shadowOffset = CGSize(width: offsetWidth, height: offsetHeight) layer.shadowRadius = radius layer.shadowOpacity = opacity layer.shadowColor = color.cgColor } }
mit
5ea3a8d85cbf7a3e884137068498271d
36.266667
121
0.690519
4.777778
false
false
false
false
mercadopago/sdk-ios
MercadoPagoSDK/MercadoPagoSDK/GenericErrorView.swift
1
2910
// // GenericErrorView.swift // MercadoPagoSDK // // Created by Matias Gualino on 7/4/15. // Copyright (c) 2015 MercadoPago. All rights reserved. // import Foundation import UIKit public class GenericErrorView : UIView { let kErrorOffset : CGFloat = 4 let kArrowHeight : CGFloat = 8 let kLabelXOffset : CGFloat = 12 var backgroundImageView : UIImageView! var errorLabel : UILabel! var minimumHeight : CGFloat = 0 var bundle : NSBundle? = MercadoPago.getBundle() public override init(frame: CGRect) { super.init(frame: frame) self.minimumHeight = 40 self.backgroundImageView = UIImageView(frame: CGRectMake(-1, -1 * kArrowHeight, self.frame.size.width + 1, self.frame.size.height + kArrowHeight)) self.backgroundImageView.image = MercadoPago.getImage("ErrorBackground.png")!.stretchableImageWithLeftCapWidth(0, topCapHeight: 20) self.backgroundImageView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth] self.backgroundImageView.contentMode = UIViewContentMode.ScaleToFill self.backgroundImageView.layer.cornerRadius = 0 self.backgroundImageView.layer.masksToBounds = false self.addSubview(self.backgroundImageView) self.errorLabel = UILabel(frame: CGRectMake(kLabelXOffset, 0, self.frame.size.width - 2*kLabelXOffset, self.frame.size.height)) self.errorLabel.numberOfLines = 0 self.errorLabel.textColor = UIColor().errorCellColor() self.errorLabel.font = UIFont(name: "HelveticaNeue-Light", size: 13) self.errorLabel.autoresizingMask = UIViewAutoresizing.FlexibleHeight self.errorLabel.backgroundColor = UIColor.clearColor() self.addSubview(self.errorLabel) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public func setErrorMessage(errorMessage: String) { let maxSize : CGSize = CGSizeMake(self.errorLabel.frame.size.width, CGFloat.max) let textRect : CGRect = (errorMessage as NSString).boundingRectWithSize(maxSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: self.errorLabel.font], context: nil) let newSize : CGSize = textRect.size var viewHeight : CGFloat = newSize.height + 2*kErrorOffset if viewHeight < self.minimumHeight { viewHeight = self.minimumHeight } else { viewHeight = self.minimumHeight + 2*kErrorOffset } self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, viewHeight) self.errorLabel.text = errorMessage self.errorLabel.frame = CGRectMake(self.errorLabel.frame.origin.x, (self.frame.size.height - newSize.height)/2, self.errorLabel.frame.size.width, newSize.height) } }
mit
80d9380be2963e4504d6786a7e7094ce
41.808824
215
0.702405
4.68599
false
false
false
false
zhuyihao/Top4Swift
Top4Swift/reviewPool.swift
2
6274
// // ViewController.swift // Top4Swift // // Created by james on 14-11-18. // Copyright (c) 2014年 woowen. All rights reserved. // import UIKit class reviewPool: UIViewController,HttpProtocol,UITableViewDataSource,UITableViewDelegate { var timeLineUrl = "http://top.mogujie.com/top/zadmin/app/tuijian?_adid=99000537220553" @IBOutlet weak var tableView: UITableView! var eHttp: HttpController = HttpController() var base: baseClass = baseClass() var tmpListData: NSMutableArray = NSMutableArray() var listData: NSMutableArray = NSMutableArray() var page = 1 //page var imageCache = Dictionary<String,UIImage>() var tid: String = "" var sign: String = String() let cellImg = 1 let cellLbl1 = 2 let cellLbl2 = 3 let cellLbl3 = 4 let refreshControl = UIRefreshControl() //Refresh func func setupRefresh(){ self.tableView.addHeaderWithCallback({ let delayInSeconds:Int64 = 1000000000 * 2 var popTime:dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW,delayInSeconds) dispatch_after(popTime, dispatch_get_main_queue(), { self.tableView.reloadData() self.tableView.headerEndRefreshing() }) }) self.tableView.addFooterWithCallback({ var nextPage = String(self.page + 1) var tmpTimeLineUrl = self.timeLineUrl + "&page=" + nextPage as NSString self.eHttp.delegate = self self.eHttp.get(tmpTimeLineUrl) let delayInSeconds:Int64 = 1000000000 * 2 var popTime:dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW,delayInSeconds) dispatch_after(popTime, dispatch_get_main_queue(), { self.tableView.footerEndRefreshing() if(self.tmpListData != self.listData){ if(self.tmpListData.count != 0){ var tmpListDataCount = self.tmpListData.count for(var i:Int = 0; i < tmpListDataCount; i++){ self.listData.addObject(self.tmpListData[i]) } } self.tableView.reloadData() self.tmpListData.removeAllObjects() } }) }) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //获取sign self.sign = base.cacheGetString("sign") eHttp.delegate = self self.timeLineUrl = self.timeLineUrl + "&sign=" + self.sign eHttp.get(self.timeLineUrl) self.setupRefresh() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ if(self.listData.count == 0){ if(self.tmpListData.count != 0){ self.listData = self.tmpListData } } return listData.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ var cell: AnyObject? = tableView.dequeueReusableCellWithIdentifier("list", forIndexPath: indexPath) let rowData: NSDictionary = self.listData[indexPath.row] as NSDictionary let imgUrl = rowData["cover"] as String var img = cell?.viewWithTag(cellImg) as UIImageView img.image = UIImage(named: "default.png") if(imgUrl != ""){ let image = self.imageCache[imgUrl] as UIImage? if(image != ""){ let imageUrl = NSURL(string: imgUrl) let request: NSURLRequest = NSURLRequest(URL: imageUrl!) //异步获取 NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!)-> Void in let imgTmp = UIImage(data: data) img.image = imgTmp self.imageCache[imgUrl] = imgTmp }) }else{ img.image = image } } //标题 var label1 = cell?.viewWithTag(cellLbl1) as UILabel //换行 label1.numberOfLines = 0 label1.lineBreakMode = NSLineBreakMode.ByWordWrapping label1.text = rowData["content"] as NSString var label2 = cell?.viewWithTag(cellLbl2) as UILabel label2.text = rowData["user"]?["uname"] as NSString var label3 = cell?.viewWithTag(cellLbl3) as UILabel //时间格式转换 var outputFormat = NSDateFormatter() outputFormat.dateFormat = "yyyy/MM/dd HH:mm:ss" outputFormat.locale = NSLocale(localeIdentifier: "shanghai") //发布时间 let pubTime = NSDate(timeIntervalSince1970: rowData["pubTime"] as NSTimeInterval) label3.text = outputFormat.stringFromDate(pubTime) return cell as UITableViewCell } //点击事件处理 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ let trueData: NSDictionary = self.listData[indexPath.row] as NSDictionary self.tid = trueData["tid"] as NSString self.performSegueWithIdentifier("detail", sender: self) } //跳转传参方法 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "detail" { var instance = segue.destinationViewController as detailViewController instance.tid = self.tid } } func didRecieveResult(result: NSDictionary){ if(result["result"]?["list"] != nil && result["result"]?["isEnd"] as NSNumber != 1){ self.tmpListData = result["result"]?["list"] as NSMutableArray //list数据 self.page = result["result"]?["page"] as Int self.tableView.reloadData() } } //返回按钮 @IBAction func close(segue: UIStoryboardSegue){ } }
mit
9a576f1481add462cb7c5acda59ddc56
35.662722
188
0.591511
4.894155
false
false
false
false
LQJJ/demo
86-DZMeBookRead-master/DZMeBookRead/DZMeBookRead/other/custom/DZMUserDefaults.swift
1
3618
// // DZMUserDefaults.swift // DZMeBookRead // // Created by 邓泽淼 on 2017/5/11. // Copyright © 2017年 DZM. All rights reserved. // import UIKit class DZMUserDefaults: NSObject { // MARK: -- 清理 NSUserDefaults /// 清空 NSUserDefaults class func UserDefaultsClear() { let defaults:UserDefaults = UserDefaults.standard let dictionary = defaults.dictionaryRepresentation() for key in dictionary.keys { defaults.removeObject(forKey: key) defaults.synchronize() } } /// 删除 对应Key 的值 class func removeObjectForKey(_ key:String) { let defaults:UserDefaults = UserDefaults.standard defaults.removeObject(forKey: key) defaults.synchronize() } // MARK: -- 存 /// 存储Object class func setObject(_ value:Any?,key:String) { let defaults:UserDefaults = UserDefaults.standard defaults.set(value, forKey: key) defaults.synchronize() } /// 存储String class func setString(_ value:String?,key:String) { DZMUserDefaults.setObject(value, key: key) } /// 存储NSInteger class func setInteger(_ value:NSInteger,key:String) { let defaults:UserDefaults = UserDefaults.standard defaults.set(value, forKey: key) defaults.synchronize() } /// 存储Bool class func setBool(_ value:Bool,key:String) { let defaults:UserDefaults = UserDefaults.standard defaults.set(value, forKey: key) defaults.synchronize() } /// 存储Float class func setFloat(_ value:Float,key:String) { let defaults:UserDefaults = UserDefaults.standard defaults.set(value, forKey: key) defaults.synchronize() } /// 存储Double class func setDouble(_ value:Double,key:String) { let defaults:UserDefaults = UserDefaults.standard defaults.set(value, forKey: key) defaults.synchronize() } /// 存储URL class func setURL(_ value:URL?,key:String) { let defaults:UserDefaults = UserDefaults.standard defaults.set(value, forKey: key) defaults.synchronize() } // MARK: -- 取 /// 获取Object class func objectForKey(_ key:String) -> Any? { let defaults:UserDefaults = UserDefaults.standard return defaults.object(forKey: key) } /// 获取String class func stringForKey(_ key:String) -> String { let defaults:UserDefaults = UserDefaults.standard let string = defaults.object(forKey: key) as? String return string ?? "" } /// 获取Bool class func boolForKey(_ key:String) -> Bool { let defaults:UserDefaults = UserDefaults.standard return defaults.bool(forKey: key) } /// 获取NSInteger class func integerForKey(_ key:String) -> NSInteger { let defaults:UserDefaults = UserDefaults.standard return defaults.integer(forKey: key) } /// 获取Float class func floatForKey(_ key:String) -> Float { let defaults:UserDefaults = UserDefaults.standard return defaults.float(forKey: key) } /// 获取Double class func doubleForKey(_ key:String) -> Double { let defaults:UserDefaults = UserDefaults.standard return defaults.double(forKey: key) } /// 获取URL class func URLForKey(_ key:String) -> URL? { let defaults:UserDefaults = UserDefaults.standard return defaults.url(forKey: key) } }
apache-2.0
1faa29ccd34e70030747267f77398161
26.570313
60
0.615755
4.661823
false
false
false
false
marty-suzuki/QiitaWithFluxSample
QiitaWithFluxSample/Source/Search/View/SearchTopViewCell.swift
1
1124
// // SearchTopViewCell.swift // QiitaWithFluxSample // // Created by marty-suzuki on 2017/04/16. // Copyright © 2017年 marty-suzuki. All rights reserved. // import UIKit import Nuke import QiitaSession final class SearchTopViewCell: UITableViewCell, ReusableViewProtocol { typealias RegisterType = RegisterNib @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var thumbnailImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func configure(with item: Item) { userNameLabel.text = "\(item.user.id)が\(item.createdDateString)に投稿" titleLabel.text = item.title descriptionLabel.text = item.newLineExcludedBody thumbnailImageView.image = nil if let url = URL(string: item.user.profileImageUrl) { loadImage(with: url, into: thumbnailImageView) } } }
mit
1dc9cbbc579108f4d0983b80b7f54349
28.289474
75
0.691824
4.506073
false
false
false
false
randallli/material-components-ios
components/TextFields/examples/TextFieldSemanticColorThemer.swift
1
9486
/* Copyright 2018-present the Material Components for iOS 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. */ // swiftlint:disable function_body_length import MaterialComponents.MaterialTextFields final class TextFieldSemanticColorThemer: UIViewController { var colorScheme = MDCSemanticColorScheme() var typographyScheme = MDCTypographyScheme() let textfieldStandard: MDCTextField = { let textfield = MDCTextField() textfield.translatesAutoresizingMaskIntoConstraints = false return textfield }() let textfieldAlternative: MDCTextField = { let textfield = MDCTextField() textfield.translatesAutoresizingMaskIntoConstraints = false return textfield }() let standardController: MDCTextInputControllerOutlined let alternativeController: MDCTextInputControllerFilled let scrollView = UIScrollView() override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { standardController = MDCTextInputControllerOutlined(textInput: textfieldStandard) alternativeController = MDCTextInputControllerFilled(textInput: textfieldAlternative) super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white title = "Text Field Theming" setupScrollView() setupTextFields() registerKeyboardNotifications() addGestureRecognizer() // Apply the themes to the controllers MDCOutlinedTextFieldColorThemer.applySemanticColorScheme(colorScheme, to: standardController) MDCTextFieldTypographyThemer.applyTypographyScheme(typographyScheme, to: standardController) MDCFilledTextFieldColorThemer.applySemanticColorScheme(colorScheme, to: alternativeController) MDCTextFieldTypographyThemer.applyTypographyScheme(typographyScheme, to: alternativeController) } func setupTextFields() { scrollView.addSubview(textfieldStandard) textfieldStandard.text = "Grace Hopper" standardController.placeholderText = "Standard" scrollView.addSubview(textfieldAlternative) textfieldAlternative.text = "" alternativeController.placeholderText = "Alternative" //NOTE: In iOS 9+, you could accomplish this with a UILayoutGuide. let views = [ "standard": textfieldStandard, "alternative": textfieldAlternative, ] var constraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[standard]-[alternative]", options: [.alignAllLeading, .alignAllTrailing], metrics: nil, views: views) constraints += [NSLayoutConstraint(item: textfieldStandard, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leadingMargin, multiplier: 1, constant: 0)] constraints += [NSLayoutConstraint(item: textfieldStandard, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailingMargin, multiplier: 1, constant: 0)] #if swift(>=3.2) if #available(iOS 11.0, *) { constraints += [NSLayoutConstraint(item: textfieldStandard, attribute: .top, relatedBy: .equal, toItem: scrollView.contentLayoutGuide, attribute: .top, multiplier: 1, constant: 20), NSLayoutConstraint(item: textfieldAlternative, attribute: .bottom, relatedBy: .equal, toItem: scrollView.contentLayoutGuide, attribute: .bottomMargin, multiplier: 1, constant: -20)] } else { constraints += [NSLayoutConstraint(item: textfieldStandard, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .top, multiplier: 1, constant: 20), NSLayoutConstraint(item: textfieldAlternative, attribute: .bottom, relatedBy: .equal, toItem: scrollView, attribute: .bottomMargin, multiplier: 1, constant: -20)] } #else constraints += [NSLayoutConstraint(item: textfieldStandard, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .top, multiplier: 1, constant: 20), NSLayoutConstraint(item: textfieldAlternative, attribute: .bottom, relatedBy: .equal, toItem: scrollView, attribute: .bottomMargin, multiplier: 1, constant: -20)] #endif NSLayoutConstraint.activate(constraints) } func setupScrollView() { view.addSubview(scrollView) scrollView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:|[scrollView]|", options: [], metrics: nil, views: ["scrollView": scrollView])) NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|", options: [], metrics: nil, views: ["scrollView": scrollView])) let marginOffset: CGFloat = 16 let margins = UIEdgeInsets(top: 0, left: marginOffset, bottom: 0, right: marginOffset) scrollView.layoutMargins = margins } func addGestureRecognizer() { let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapDidTouch(sender: ))) self.scrollView.addGestureRecognizer(tapRecognizer) } // MARK: - Actions @objc func tapDidTouch(sender: Any) { self.view.endEditing(true) } } // MARK: - Keyboard Handling extension TextFieldSemanticColorThemer { func registerKeyboardNotifications() { let notificationCenter = NotificationCenter.default notificationCenter.addObserver( self, selector: #selector(keyboardWillShow(notif:)), name: .UIKeyboardWillChangeFrame, object: nil) notificationCenter.addObserver( self, selector: #selector(keyboardWillShow(notif:)), name: .UIKeyboardWillShow, object: nil) notificationCenter.addObserver( self, selector: #selector(keyboardWillHide(notif:)), name: .UIKeyboardWillHide, object: nil) } @objc func keyboardWillShow(notif: Notification) { guard let frame = notif.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect else { return } scrollView.contentInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: frame.height, right: 0.0) } @objc func keyboardWillHide(notif: Notification) { scrollView.contentInset = UIEdgeInsets.zero } } // MARK: - Status Bar Style extension TextFieldSemanticColorThemer { @objc class func catalogBreadcrumbs() -> [String] { return ["Text Field", "Theming Text Fields"] } }
apache-2.0
9092eafee612a435db97380b43997222
39.365957
100
0.536475
6.675581
false
false
false
false
sadawi/ModelKit
ModelKit/Models/ModelValueTransformer.swift
1
3594
// // ModelValueTransformer.swift // Pods // // Created by Sam Williams on 12/8/15. // // import Foundation open class ModelValueTransformer<T: Model>: ValueTransformer<T> { var fields: ((T)->[FieldType])? public convenience init(fields: @escaping ((T)->[FieldType])) { self.init() self.fields = fields } public required init() { super.init() } open override func importValue(_ value: Any?, in context: ValueTransformerContext = .defaultContext) -> T? { // TODO: conditionally casting to AttributeDictionary might be slowish if let value = value as? AttributeDictionary { return T.from(dictionaryValue: value, in: context) } else { return nil } } open override func exportValue(_ value: T?, in context: ValueTransformerContext = .defaultContext) -> Any? { var seenFields: [FieldType] = [] var fields: [FieldType]? = nil if let fieldGenerator = self.fields, let model = value { fields = fieldGenerator(model) } return self.exportValue(value, fields: fields, seenFields: &seenFields, in: context) } open func exportValue(_ value: T?, fields: [FieldType]?=nil, seenFields: inout [FieldType], in context: ValueTransformerContext = .defaultContext) -> Any? { // Why do I have to cast it to Model? T is already a Model. if let value = value as? Model { return value.dictionaryValue(fields: fields, seenFields: &seenFields, in: context) as Any } else { return type(of: self).nullValue(explicit: context.explicitNull) } } } open class ModelForeignKeyValueTransformer<T: Model>: ValueTransformer<T> { public required init() { super.init(importAction: { value, context in // Normally we'd check for null by simply trying to cast to the correct type, but only a model instance knows the type of its identifier field. if let value = value , !ModelForeignKeyValueTransformer<T>.valueIsNull(value) { // Attempt to initialize an object with just an id value if let idField = T.prototype().identifierField, let idKey = idField.key { let attributes = [idKey: value] let model = T.from(dictionaryValue: attributes, in: context) { model, isNew in // We only know it's definitely a shell if it wasn't reused from an existing model if isNew { model.loadState = .incomplete } } return model } } return nil }, exportAction: { value, context in if let value = value as? Model { return value.identifierField?.anyObjectValue } else { return nil } } ) } } open class ModelArrayValueTransformer<T: Model>: ArrayValueTransformer<T> { open func exportValue(_ value: [T]?, seenFields: inout [FieldType], in context: ValueTransformerContext = .defaultContext) -> Any? { if let value = value, let innerTransformer = self.innerTransformer as? ModelValueTransformer<T> { let arrayValue = value.map { innerTransformer.exportValue($0, seenFields: &seenFields, in: context) }.flatMap { $0 } return self.scalarValue(arrayValue) } else { return nil } } }
mit
60a94e7a2cee61b61bcb20f231281440
38.065217
160
0.582359
4.779255
false
false
false
false
1024jp/WFColorCode
Sources/ColorCode/ColorCode.swift
1
7139
// // ColorCode.swift // // Created by 1024jp on 2021-05-08. /* The MIT License (MIT) © 2014-2022 1024jp Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation public enum ColorCodeType: Int, CaseIterable, Sendable { /// 6-digit hexadecimal color code with # symbol. For example: `#ffffff` case hex = 1 /// 3-digit hexadecimal color code with # symbol. For example: `#fff` case shortHex /// CSS style color code in RGB. For example: `rgb(255,255,255)` case cssRGB /// CSS style color code in RGB with alpha channel. For example: `rgba(255,255,255,1)` case cssRGBa /// CSS style color code in HSL. For example: `hsl(0,0%,100%)` case cssHSL /// CSS style color code in HSL with alpha channel. For example: `hsla(0,0%,100%,1)` case cssHSLa /// CSS style color code with keyrowd. For example: `White` case cssKeyword } // MARK: Color Components enum ColorComponents { case rgb(Double, Double, Double, alpha: Double = 1) case hsl(Double, Double, Double, alpha: Double = 1) case hsb(Double, Double, Double, alpha: Double = 1) } extension ColorComponents { /// Initialize with the given hex color code. Or returns `nil` if color code is invalid. /// /// Example usage: /// ``` /// let redComponents = ColorComponents(hex: 0xFF0000) /// ``` /// /// - Parameters: /// - hex: The 6-digit hexadecimal color code. init?(hex: Int) { guard (0...0xFFFFFF).contains(hex) else { return nil } let r = (hex >> 16) & 0xff let g = (hex >> 8) & 0xff let b = (hex) & 0xff self = .rgb(Double(r) / 255, Double(g) / 255, Double(b) / 255) } /// Initialize with the given color code. Or returns `nil` if color code is invalid. /// /// - Parameters: /// - colorCode: The CSS3 style color code string. The given code as hex or CSS keyword is case insensitive. /// - type: Upon return, contains the detected color code type. init?(colorCode: String, type: inout ColorCodeType?) { // initialize with `nil` anyway type = nil let code = colorCode.trimmingCharacters(in: .whitespacesAndNewlines) // detect code type guard let (detectedType, result) = ColorCodeType.allCases.lazy .compactMap({ type -> (ColorCodeType, NSTextCheckingResult)? in let pattern: String = { switch type { case .hex: return "^#[0-9a-fA-F]{6}$" case .shortHex: return "^#[0-9a-fA-F]{3}$" case .cssRGB: return "^rgb\\( *([0-9]{1,3}) *, *([0-9]{1,3}) *, *([0-9]{1,3}) *\\)$" case .cssRGBa: return "^rgba\\( *([0-9]{1,3}) *, *([0-9]{1,3}) *, *([0-9]{1,3}) *, *([0-9.]+) *\\)$" case .cssHSL: return "^hsl\\( *([0-9]{1,3}) *, *([0-9.]+)% *, *([0-9.]+)% *\\)$" case .cssHSLa: return "^hsla\\( *([0-9]{1,3}) *, *([0-9.]+)% *, *([0-9.]+)% *, *([0-9.]+) *\\)$" case .cssKeyword: return "^[a-zA-Z]+$" } }() let regex = try! NSRegularExpression(pattern: pattern) guard let match = regex.firstMatch(in: code, range: NSRange(0..<code.utf16.count)) else { return nil } return (type, match) }).first else { return nil } // create color from result switch detectedType { case .hex: let hex = Int(code.dropFirst(), radix: 16)! self.init(hex: hex) case .shortHex: let hex = Int(code.dropFirst(), radix: 16)! let r = (hex >> 8) & 0xff let g = (hex >> 4) & 0xff let b = (hex) & 0xff self = .rgb(Double(r) / 15, Double(g) / 15, Double(b) / 15) case .cssRGB: guard let r = result.double(in: code, at: 1), let g = result.double(in: code, at: 2), let b = result.double(in: code, at: 3) else { return nil } self = .rgb(r / 255, g / 255, b / 255) case .cssRGBa: guard let r = result.double(in: code, at: 1), let g = result.double(in: code, at: 2), let b = result.double(in: code, at: 3), let a = result.double(in: code, at: 4) else { return nil } self = .rgb(r / 255, g / 255, b / 255, alpha: a) case .cssHSL: guard let h = result.double(in: code, at: 1), let s = result.double(in: code, at: 2), let l = result.double(in: code, at: 3) else { return nil } self = .hsl(h / 360, s / 100, l / 100) case .cssHSLa: guard let h = result.double(in: code, at: 1), let s = result.double(in: code, at: 2), let l = result.double(in: code, at: 3), let a = result.double(in: code, at: 4) else { return nil } self = .hsl(h / 360, s / 100, l / 100, alpha: a) case .cssKeyword: guard let color = KeywordColor(keyword: code) else { return nil } self.init(hex: color.value) } type = detectedType } } private extension NSTextCheckingResult { func double(in string: String, at index: Int) -> Double? { let range = Range(self.range(at: index), in: string)! return Double(string[range]) } }
mit
78223e536bf20f727f10b3ee21294a60
33.819512
114
0.509667
4.099943
false
false
false
false
hip4yes/Animatics
Animatics/Animators/LayerAnimatics.swift
1
2504
// // LayerAnimatics.swift // PokeScrum // // Created by Nikita Arkhipov on 19.09.15. // Copyright © 2015 Anvics. All rights reserved. // import Foundation import UIKit class LayerFloatAnimatics: AnimationSettingsHolder, AnimaticsLayerChangesPerformer { typealias TargetType = UIView typealias ValueType = CGFloat let value: ValueType required init(_ v: ValueType){ value = v } func _animationKeyPath() -> String { fatalError("_animationKeyPath() is called but not implemented in \(self.dynamicType)") } } class ShadowRadiusAnimator: LayerFloatAnimatics { override func _animationKeyPath() -> String { return "shadowRadius" } } class ShadowOpacityAnimator: LayerFloatAnimatics { override func _animationKeyPath() -> String { return "shadowOpacity" } } class CornerRadiusAnimator: LayerFloatAnimatics { override func _animationKeyPath() -> String { return "cornerRadius" } } class BorderWidthAnimator: LayerFloatAnimatics { override func _animationKeyPath() -> String { return "borderWidth" } } class LayerTransformAnimatics: AnimationSettingsHolder, AnimaticsLayerChangesPerformer { typealias TargetType = UIView typealias ValueType = CATransform3D let value: ValueType required init(_ v: ValueType){ value = v } func _animationKeyPath() -> String { return "transform" } } class LayerColorAnimatics: AnimationSettingsHolder, AnimaticsLayerChangesPerformer { typealias TargetType = UIView typealias ValueType = UIColor let value: ValueType required init(_ v: ValueType){ value = v } func _animationKeyPath() -> String { fatalError("_animationKeyPath() is called but not implemented in \(self.dynamicType)") } } class BorderColorAnimator: LayerColorAnimatics { override func _animationKeyPath() -> String { return "borderColor" } } class GradientLayerPointAnimatics: AnimationSettingsHolder, AnimaticsLayerChangesPerformer { typealias TargetType = CAGradientLayer typealias ValueType = CGPoint let value: ValueType required init(_ v: ValueType){ value = v } func _animationKeyPath() -> String { fatalError("_animationKeyPath() is called but not implemented in \(self.dynamicType)") } } class GradientLayerStartPointAnimator: GradientLayerPointAnimatics { override func _animationKeyPath() -> String { return "startPoint" } } class GradientLayerEndPointAnimator: GradientLayerPointAnimatics { override func _animationKeyPath() -> String { return "endPoint" } }
mit
d71a10ae1cf59e34791c4c97f5e65036
29.52439
128
0.743108
4.635185
false
false
false
false
qiuncheng/study-for-swift
learn-rx-swift/Chocotastic-starter/Pods/RxSwift/RxSwift/Observables/Implementations/ShareReplay1WhileConnected.swift
6
2561
// // ShareReplay1WhileConnected.swift // Rx // // Created by Krunoslav Zaher on 12/6/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation // optimized version of share replay for most common case final class ShareReplay1WhileConnected<Element> : Observable<Element> , ObserverType , SynchronizedUnsubscribeType { typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType private let _source: Observable<Element> private var _lock = NSRecursiveLock() private var _connection: SingleAssignmentDisposable? private var _element: Element? private var _observers = Bag<AnyObserver<Element>>() init(source: Observable<Element>) { self._source = source } override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { _lock.lock(); defer { _lock.unlock() } return _synchronized_subscribe(observer) } func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { if let element = self._element { observer.on(.next(element)) } let initialCount = self._observers.count let disposeKey = self._observers.insert(AnyObserver(observer)) if initialCount == 0 { let connection = SingleAssignmentDisposable() _connection = connection connection.disposable = self._source.subscribe(self) } return SubscriptionDisposable(owner: self, key: disposeKey) } func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { _lock.lock(); defer { _lock.unlock() } _synchronized_unsubscribe(disposeKey) } func _synchronized_unsubscribe(_ disposeKey: DisposeKey) { // if already unsubscribed, just return if self._observers.removeKey(disposeKey) == nil { return } if _observers.count == 0 { _connection?.dispose() _connection = nil _element = nil } } func on(_ event: Event<E>) { _lock.lock(); defer { _lock.unlock() } _synchronized_on(event) } func _synchronized_on(_ event: Event<E>) { switch event { case .next(let element): _element = element _observers.on(event) case .error, .completed: _element = nil _connection?.dispose() _connection = nil let observers = _observers _observers = Bag() observers.on(event) } } }
mit
6ded29022c3c4f63d287bbc18a24ba2a
26.826087
96
0.603125
4.688645
false
false
false
false
Pluto-Y/SwiftyEcharts
DemoOptions/BarOptions.swift
1
58385
// // BarOptions.swift // SwiftyEcharts // // Created by Pluto-Y on 16/01/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // import SwiftyEcharts public final class BarOptions { // MARK: 柱状图动画延迟 /// 地址: http://echarts.baidu.com/demo.html#bar-animation-delay static func barAnimationDelayOption() -> Option { func calculateData(_ index: Float, function: (Double) -> Double) -> Float { var tmp: Float = Float(function(Double(index) / 5.0)) tmp *= (index / 5.0 - 1.0) tmp += index / 6.0 tmp *= 5.0 return tmp } var xAxisData: [Jsonable] = [] var data1: [Jsonable] = [] var data2: [Jsonable] = [] for i in 0..<100 { xAxisData.append("类目\(i)") data1.append(calculateData(Float(i), function: sin)) data2.append(calculateData(Float(i), function: cos)) } return Option( .title(Title( .text("柱状图动画延迟") )), .legend(Legend( .data(["bar", "bar2"]), .align(.left) )), .toolbox(Toolbox( .feature(ToolboxFeature( .magicType(ToolboxFeatureMagicType( .type([.stack, .tiled]) )), .dataView(ToolboxFeatureDataView( )), .saveAsImage(ToolboxFeatureSaveAsImage( .pixelRatio(2) )) )) )), .tooltip(Tooltip()), .xAxis(Axis( .data(xAxisData), .silent(false), .splitLine(SplitLine( .show(false) )) )), .yAxis(Axis()), .series([ BarSerie( .name("bar"), .data(data1), .animationDelay(.function("function seriesDelay(idx){ return idx * 10; }")) ), BarSerie( .name("bar2"), .data(data2), .animationDelay(.function("function seriesDelay2(idx){ return idx * 10 + 100; }")) ) ]), .animationEasing(.elasticOut), .animationDelayUpdate(.function("function optionDelayUpdate(idx){ return idx * 5; }")) ) } // MARK: 柱状图框选 /// 地址: http://echarts.baidu.com/demo.html#bar-brush static func barBrushOption() -> Option { // FIXME: 缺少事件 var xAxisData: [Jsonable] = [] var data1: [Jsonable] = [] var data2: [Jsonable] = [] var data3: [Jsonable] = [] var data4: [Jsonable] = [] var tmp: Double = 0.0 for i in 0..<10 { xAxisData.append("Class\(i)") tmp = Double((arc4random_uniform(100)+1)) / 100.0 * 2 data1.append(tmp) tmp = Double((arc4random_uniform(100)+1)) / -100.0 data2.append(tmp) tmp = Double((arc4random_uniform(100)+1)) / 100.0 * 5 data3.append(tmp) tmp = Double((arc4random_uniform(100)+1)) / 100.0 + 0.3 data4.append(tmp) } let itemStyle = ItemStyle( .normal(CommonItemStyleContent()), .emphasis(CommonItemStyleContent( // .barBorderWidth(1), // 这个属性在网页上好像没用 .shadowBlur(10), .shadowOffsetX(0), .shadowOffsetY(0), .shadowColor(.rgba(0, 0, 0, 0.5)) )) ) return Option( .backgroundColor(.hexColor("#eee")), .legend(Legend( .data(["bar", "bar2", "bar3", "bar4"]), .align(.left), .left(.value(10)) )), .brush(Brush( .toolbox([.rect, .polygon, .lineX, .lineY, .keep, .clear]), .xAxisIndex(.indexes([0])) )), .toolbox(Toolbox( .feature(ToolboxFeature( .magicType(ToolboxFeatureMagicType( .type([.stack, .tiled]) )), .dataView(ToolboxFeatureDataView()) )) )), .tooltip(Tooltip()), .xAxis(Axis( .data(xAxisData), .name("X Axis"), .silent(false), .axisLine(AxisLine( .onZero(true) )), .splitLine(SplitLine( .show(false) )), .splitArea(SplitArea( .show(false) )) )), .yAxis(Axis( .inverse(true), .splitArea(SplitArea( .show(false) )) )), .grid(Grid( .left(.value(100)) )), .visualMap(ContinuousVisualMap( .dimension(1), .text(["Hight", "Low"]), .inverse(true), .itemHeight(200), .calculable(true), .min(-2), .max(6), .top(.value(60)), .left(.value(10)), .inRange(["colorLightness": [0.4, 0.8]]), .outRange(["color": Color.hexColor("#bbb")]), .controller(VisualMapController( .inRange(["color": Color.hexColor("#2f4554")]) )) )), .series([ BarSerie( .name("bar"), .stack("one"), .itemStyle(itemStyle), .data(data1) ), BarSerie( .name("bar2"), .stack("one"), .itemStyle(itemStyle), .data(data2) ), BarSerie( .name("bar3"), .stack("two"), .itemStyle(itemStyle), .data(data3) ), BarSerie( .name("bar4"), .stack("two"), .itemStyle(itemStyle), .data(data4) ) ]) ) } // MARK: 特性示例:渐变色 阴影 点击缩放 /// 地址: http://echarts.baidu.com/demo.html#bar-gradient static func barGradientOption() -> Option { // FIXME: 缺少点击事件 let dataAxis: [Jsonable] = ["点", "击", "柱", "子", "或", "者", "两", "指", "在", "触", "屏", "上", "滑", "动", "能", "够", "自", "动", "缩", "放"] let yMax = 500 var dataShadow: [Jsonable] = [] for _ in 0..<dataAxis.count { dataShadow.append(yMax) } return Option( .title(Title( .text("特性示例:渐变色 阴影 点击缩放"), .subtext("Feature Sample: Gradient Color, Shadow, Click Zoom") )), .xAxis(Axis( .data(dataAxis), .axisLabel(AxisLabel( .inside(true), .color(.hexColor("#fff")) )), .axisTick(AxisTick( .show(false) )), .axisLine(AxisLine( .show(false) )), .z(10) )), .yAxis(Axis( .axisLine(AxisLine( .show(false) )), .axisTick(AxisTick( .show(false) )), .axisLabel(AxisLabel( .color(.hexColor("#999")) )) )), .dataZoom([InsideDataZoom( )]), .series([ BarSerie( .itemStyle(ItemStyle( .normal(CommonItemStyleContent( .color(.rgba(0, 0, 0, 0.05)) )) )), .barGap((-100)%), .barCategoryGap(40%), .data(dataShadow), .animation(false) ), BarSerie( .itemStyle(ItemStyle( .normal(CommonItemStyleContent( .color(.linearGradient(0, 0, 0, 1, [ ["offset": 0, "color": Color.hexColor("#83bff6")], ["offset": 0.5, "color": Color.hexColor("#188df0")], ["offset": 1, "color": Color.hexColor("#188df0")] ], false)) )), .emphasis(CommonItemStyleContent( .color(.linearGradient(0, 0, 0, 1, [ ["offset": 0, "color": Color.hexColor("#2378f7")], ["offset": 0.7, "color": Color.hexColor("#2378f7")], ["offset": 1, "color": Color.hexColor("#83bff6")] ], false)) )) )), .data([220, 182, 191, 234, 290, 330, 310, 123, 442, 321, 90, 149, 210, 122, 133, 334, 198, 123, 125, 220]) ) ]) ) } // MARK: 正负条形图 /// 地址:http://echarts.baidu.com/demo.html#bar-negative static func barNegativeOption() -> Option { return Option( .tooltip(Tooltip( .trigger(.axis), .axisPointer(AxisPointerForTooltip( .type(.shadow) )) )), .legend(Legend( .data(["利润", "支出", "收入"]) )), .xAxis(Axis( .type(.value) )), .yAxis(Axis( .type(.category), .axisTick(AxisTick( .show(false) )), .data(["周一","周二","周三","周四","周五","周六","周日"]) )), .series([ BarSerie( .name("利润"), .label(EmphasisLabel( .normal(LabelStyle( .show(true), .position(.inside) )) )), .data([200, 170, 240, 244, 200, 220, 210]) ), BarSerie( .name("收入"), .stack("总量"), .label(EmphasisLabel( .normal(LabelStyle( .show(true) )) )), .data([320, 302, 341, 374, 390, 450, 420]) ), BarSerie( .name("支出"), .stack("总量"), .label(EmphasisLabel( .normal(LabelStyle( .show(true), .position(.left) )) )), .data([-120, -132, -101, -134, -190, -230, -210]) ) ]) ) } // MARK: 交错正负轴标签 /// 地址: http://echarts.baidu.com/demo.html#bar-negative2 static func barNegative2Option() -> Option { let labelRight = FormattedLabel( .normal(FormattedLabelStyle( .position(.right) )) ) return Option( .title(Title( .text("交错正负轴标签"), .subtext("From ExcelHome"), .sublink("http://e.weibo.com/1341556070/AjwF2AgQm") )), .tooltip(Tooltip( .trigger(.axis), .axisPointer(AxisPointerForTooltip( .type(.shadow) )) )), .grid(Grid( .top(.value(80)), .bottom(.value(30)) )), .xAxis(Axis( .type(.value), .position(.top), .splitLine(SplitLine( .lineStyle(LineStyle( .type(.dashed) )) )) )), .yAxis(Axis( .type(.category), .axisLine(AxisLine( .show(false) )), .axisLabel(AxisLabel( .show(false) )), .axisTick(AxisTick( .show(false) )), .splitLine(SplitLine( .show(false) )), .data(["ten", "nine", "eight", "seven", "six", "five", "four", "three", "two", "one"]) )), .series([ BarSerie( .name("生活费"), .stack("总量"), .label(EmphasisLabel( .normal(LabelStyle( .show(true), .formatter(.string("{b}")) )) )), .data([ BarSerieData( .value(-0.07), .label(labelRight) ), BarSerieData( .value(-0.09), .label(labelRight) ), 0.2, 0.44, BarSerieData( .value(-0.23), .label(labelRight) ), 0.08, BarSerieData( .value(-0.17), .label(labelRight) ), 0.47, BarSerieData( .value(-0.36), .label(labelRight) ), 0.18 ]) ) ]) ) } // MARK: 堆叠柱状图 /// 地址: http://echarts.baidu.com/demo.html#bar-stack static func barStackOption() -> Option { return Option( .tooltip(Tooltip( .trigger(.axis), .axisPointer(AxisPointerForTooltip( .type(.shadow) )) )), .legend(Legend( .data(["直接访问","邮件营销","联盟广告","视频广告","搜索引擎","百度","谷歌","必应","其他"]) )), .grid(Grid( .left(.value(3%)), .right(.value(4%)), .bottom(.value(3%)), .containLabel(true) )), .xAxis(Axis( .type(.category), .data(["周一","周二","周三","周四","周五","周六","周日"]) )), .yAxis(Axis( .type(.value) )), .series([ BarSerie( .name("直接访问"), .data([320, 332, 301, 334, 390, 330, 320]) ), BarSerie( .name("邮件营销"), .stack("广告"), .data([120, 132, 101, 134, 90, 230, 210]) ), BarSerie( .name("联盟广告"), .stack("广告"), .data([220, 182, 191, 234, 290, 330, 310]) ), BarSerie( .name("视频广告"), .stack("广告"), .data([150, 232, 201, 154, 190, 330, 410]) ), BarSerie( .name("搜索引擎"), .data([820, 932, 901, 934, 1290, 1330, 1320]), .markLine(MarkLine( .lineStyle(EmphasisLineStyle( .normal(LineStyle( .type(.dashed) )) )), .data([ // 如果有两个点组成一条线,要将两个点放在一个数组中 [ MarkData( .type(.min) ), MarkData( .type(.max) )] ]) )) ), BarSerie( .name("百度"), .barWidth(5), .stack("搜索引擎"), .data([620, 732, 701, 734, 1090, 1130, 1120]) ), BarSerie( .name("谷歌"), .stack("搜索引擎"), .data([120, 132, 101, 134, 290, 230, 220]) ), BarSerie( .name("必应"), .stack("搜索引擎"), .data([60, 72, 71, 74, 190, 130, 110]) ), BarSerie( .name("其他"), .stack("搜索引擎"), .data([62, 82, 91, 84, 109, 110, 120]) ) ]) ) } // MARK: 坐标轴刻度与标签对齐 /// 地址: http://echarts.baidu.com/demo.html#bar-tick-align static func barTickAlignOption() -> Option { return Option( .color([.hexColor("#3398DB")]), .tooltip(Tooltip( .trigger(.axis), .axisPointer(AxisPointerForTooltip( .type(.shadow) )) )), .grid(Grid( .left(.value(3%)), .right(.value(4%)), .bottom(.value(3%)), .containLabel(true) )), .xAxis(Axis( .type(.category), .data(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]), .axisTick(AxisTick( .alignWithLabel(true) )) )), .yAxis(Axis( .type(.value) )), .series([ BarSerie( .name("直接访问"), .barWidth(60%), .data([10, 52, 200, 334, 390, 330, 220]) ) ]) ) } // MARK: 深圳月最低生活费组成(单位:元) /// 地址: http://echarts.baidu.com/demo.html#bar-waterfall static func barWaterfallOption() -> Option { return Option( .title(Title( .text("深圳月最低生活费组成(单位:元)"), .subtext("From ExcelHome"), .sublink("http://e.weibo.com/1341556070/AjQH99che") )), .tooltip(Tooltip( .trigger(.axis), .axisPointer(AxisPointerForTooltip( .type(.shadow) )), .formatter(.function("function tooltipFomatter(params) { var tar = params[1]; return tar.name + '<br/>' + tar.seriesName + ' : ' + tar.value;}")) )), .grid(Grid( .left(.value(3%)), .right(.value(4%)), .bottom(.value(3%)), .containLabel(true) )), .xAxis(Axis( .type(.category), .splitLine(SplitLine( .show(false) )), .data(["总费用","房租","水电费","交通费","伙食费","日用品数"]) )), .yAxis(Axis( .type(.value) )), .series([ BarSerie( .name("辅助"), .stack("总量"), .itemStyle(ItemStyle( .normal(CommonItemStyleContent( .borderColor(.rgba(0, 0, 0, 0)), .color(.rgba(0, 0, 0, 0)) )), .emphasis(CommonItemStyleContent( .borderColor(.rgba(0, 0, 0, 0)), .color(.rgba(0, 0, 0, 0)) )) )), .data([0, 1700, 1400, 1200, 300, 0]) ), BarSerie( .name("生活费"), .stack("总量"), .label(EmphasisLabel( .normal(LabelStyle( .show(true), .position(.inside) )) )), .data([2900, 1200, 300, 200, 900, 300]) ) ]) ) } // MARK: 阶梯瀑布图 /// 地址:http://echarts.baidu.com/demo.html#bar-waterfall2 static func barWaterfall2Option() -> Option { var list: [Jsonable] = [] for i in 1...11 { list.append("11月\(i)日") } return Option( .title(Title( .text("阶梯瀑布图"), .subtext("From ExcelHome"), .sublink("http://e.weibo.com/1341556070/Aj1J2x5a5") )), .tooltip(Tooltip( .trigger(.axis), .axisPointer(AxisPointerForTooltip( .type(.shadow) )), .formatter(.function("function axisPointer(params){ var tar; if(params[1].value != '-') { tar = params[1]; } else { tar = param[0]; } return tar.name + '<br/>' + tar.seriesName + ' : ' + tar.value}")) )), .legend(Legend( .data(["支出","收入"]) )), .grid(Grid( .left(.value(3%)), .right(.value(4%)), .bottom(.value(3%)), .containLabel(true) )), .xAxis(Axis( .type(.category), .splitLine(SplitLine( .show(false) )), .data(list) )), .yAxis(Axis( .type(.value) )), .series([ BarSerie( .name("辅助"), .stack("总量"), .itemStyle(ItemStyle( .normal(CommonItemStyleContent( .borderColor(.rgba(0, 0, 0, 0)), .color(.rgba(0, 0, 0, 0)) )), .emphasis(CommonItemStyleContent( .borderColor(.rgba(0, 0, 0, 0)), .color(.rgba(0, 0, 0, 0)) )) )), .data([0, 900, 1245, 1530, 1376, 1376, 1511, 1689, 1856, 1495, 1292]) ), BarSerie( .name("收入"), .stack("总量"), .label(EmphasisLabel( .normal(LabelStyle( .show(true), .position(.top) )) )), .data([900, 345, 393, "-", "-", 135, 178, 286, "-", "-", "-"]) ), BarSerie( .name("支出"), .stack("总量"), .label(EmphasisLabel( .normal(LabelStyle( .show(true), .position(.bottom) )) )), .data(["-", "-", "-", 108, 154, "-", "-", "-", 119, 361, 203]) ) ]) ) } // MARK: 堆叠条形图 /// 地址: http://echarts.baidu.com/demo.html#bar-y-category-stack static func barYCategoryStackOption() -> Option { return Option( .tooltip(Tooltip( .trigger(.axis), .axisPointer(AxisPointerForTooltip( .type(.shadow) )) )), .legend(Legend( .data(["邮件营销","联盟广告","视频广告","直接访问","搜索引擎"]) )), .grid(Grid( .left(.value(3%)), .right(.value(4%)), .bottom(.value(3%)), .containLabel(true) )), .xAxis(Axis( .type(.value) )), .yAxis(Axis( .type(.category), .data(["周一","周二","周三","周四","周五","周六","周日"]) )), .series([ BarSerie( .name("直接访问"), .stack("总量"), .label(EmphasisLabel( .normal(LabelStyle( .show(true), .position(.insideRight) )) )), .data([320, 332, 301, 334, 390, 330, 320]) ), BarSerie( .name("邮件营销"), .stack("总量"), .label(EmphasisLabel( .normal(LabelStyle( .show(true), .position(.insideRight) )) )), .data([120, 132, 101, 134, 90, 230, 210]) ), BarSerie( .name("联盟广告"), .stack("总量"), .label(EmphasisLabel( .normal(LabelStyle( .show(true), .position(.insideRight) )) )), .data([220, 182, 191, 234, 290, 330, 310]) ), BarSerie( .name("视频广告"), .stack("总量"), .label(EmphasisLabel( .normal(LabelStyle( .show(true), .position(.insideRight) )) )), .data([150, 232, 201, 154, 190, 330, 410]) ), BarSerie( .name("搜索引擎"), .stack("总量"), .label(EmphasisLabel( .normal(LabelStyle( .show(true), .position(.insideRight) )) )), .data([820, 932, 901, 934, 1290, 1330, 1320]) ) ]) ) } // MARK: 世界人口总量 - 条形图 /// 地址:http://echarts.baidu.com/demo.html#bar-y-category static func barYCategoryOption() -> Option { return Option( .title(Title( .text("世界人口总量"), .subtext("数据来自网络") )), .tooltip(Tooltip( .trigger(.axis), .axisPointer(AxisPointerForTooltip( .type(.shadow) )) )), .legend(Legend( .data(["2011年", "2012年"]) )), .grid(Grid( .left(.value(3%)), .right(.value(4%)), .bottom(.value(3%)), .containLabel(true) )), .xAxis(Axis( .type(.value), .boundaryGap(.notCategory([0, 0.01])) )), .yAxis(Axis( .type(.category), .data(["巴西","印尼","美国","印度","中国","世界人口(万)"]) )), .series([ BarSerie( .name("2011年"), .data([18203, 23489, 29034, 104970, 131744, 630230]) ), BarSerie( .name("2012年"), .data([19325, 23438, 31000, 121594, 134141, 681807]) ) ]) ) } // MARK: 某地区蒸发量和降水量 /// 地址: http://echarts.baidu.com/demo.html#bar1 static func bar1Option() -> Option { return Option( .title(Title( .text("某地区蒸发量和降水量"), .subtext("纯属虚构") )), .tooltip(Tooltip( .trigger(.axis) )), .legend(Legend( .data(["蒸发量","降水量"]) )), .toolbox(Toolbox( .show(true), .feature(ToolboxFeature( .dataView(ToolboxFeatureDataView( .show(true), .readOnly(false) )), .magicType(ToolboxFeatureMagicType( .show(true), .type([.line, .bar]) )), .restore(ToolboxFeatureRestore( .show(true) )), .saveAsImage(ToolboxFeatureSaveAsImage( .show(true) )) )) )), .xAxis(Axis( .type(.category), .data(["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"]) )), .yAxis(Axis( .type(.value) )), .series([ BarSerie( .name("蒸发量"), .data([2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]), .markPoint(MarkPoint( .data([ MarkData( .type(.max), .name("最大值") ), MarkData( .type(.min), .name("最小值") ) ]) )), .markLine(MarkLine( .data([ MarkData( .type(.average), .name("平均值") ) ]) )) ), BarSerie( .name("降水量"), .data([2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]), .markPoint(MarkPoint( .data([ MarkData( .name("年最高"), .value(182.2), .xAxis("7"), .yAxis("183") ), MarkData( .name("年最低"), .value(2.3), .xAxis("11"), .yAxis("3") ) ]) )), .markLine(MarkLine( .data([ MarkData( .type(.average), .name("平均值") ) ]) )) ) ]) ) } // MARK: Stacked Bar in Polar System /// 地址: http://echarts.baidu.com/demo.html#bar-polar-stack static func barPolarStackOption() -> Option { return Option( .angleAxis(AngleAxis()), .radiusAxis(RadiusAxis( .type(.category), .data(["周一", "周二", "周三", "周四"]), .z(10) )), .polar(Polar()), .series([ BarSerie( .data([1, 2, 3, 4]), .coordinateSystem(.polar), .name("A"), .stack("a") ), BarSerie( .data([2, 4, 6, 8]), .coordinateSystem(.polar), .name("B"), .stack("a") ), BarSerie( .data([1, 2, 3, 4]), .coordinateSystem(.polar), .name("C"), .stack("a") ) ]), .legend(Legend( .show(true), .data(["A", "B", "C"]) )) ) } // MARK: Stacked Bar in Polar System /// 地址: http://echarts.baidu.com/demo.html#bar-polar-stack-radial static func barPolarStackRadialOption() -> Option { return Option( .angleAxis(AngleAxis( .type(.category), .data(["周一", "周二", "周三", "周四", "周五", "周六", "周日"]), .z(10) )), .radiusAxis(RadiusAxis()), .polar(Polar()), .series([ BarSerie( .data([1, 2, 3, 4, 3, 5, 1]), .coordinateSystem(.polar), .name("A"), .stack("a") ), BarSerie( .data([2, 4, 6, 1, 3, 2, 1]), .coordinateSystem(.polar), .name("B"), .stack("a") ), BarSerie( .data([1, 2, 3, 4, 1, 2, 5]), .coordinateSystem(.polar), .name("C"), .stack("a") ) ]), .legend(Legend( .show(true), .data(["A", "B", "C"]) )) ) } // MARK: 在中国租个房子有多贵 /// 地址: http://echarts.baidu.com/demo.html#bar-polar-real-estate static func barPolarRealEstateOption() -> Option { let data: [[Float]] = [ [5000, 10000, 6785.71], [4000, 10000, 6825], [3000, 6500, 4463.33], [2500, 5600, 3793.83], [2000, 4000, 3060], [2000, 4000, 3222.33], [2500, 4000, 3133.33], [1800, 4000, 3100], [2000, 3500, 2750], [2000, 3000, 2500], [1800, 3000, 2433.33], [2000, 2700, 2375], [1500, 2800, 2150], [1500, 2300, 2100], [1600, 3500, 2057.14], [1500, 2600, 2037.5], [1500, 2417.54, 1905.85], [1500, 2000, 1775], [1500, 1800, 1650] ] let cities: [Jsonable] = ["北京", "上海", "深圳", "广州", "苏州", "杭州", "南京", "福州", "青岛", "济南", "长春", "大连", "温州", "郑州", "武汉", "成都", "东莞", "沈阳", "烟台"] let barHeight: Float = 50 return Option( .title(Title( .text("在中国租个房子有多贵?"), .subtext("市中心一室月租费(数据来源:https://www.numbeo.com)") )), .legend(Legend( .show(true), .data(["价格范围", "均值"]) )), .grid(Grid( .top(Position.value(100)) )), .angleAxis(AngleAxis( .type(.category), .data(cities) )), .tooltip(Tooltip( .show(true), .formatter(.string("function (params) { var id = params.dataIndex; return cities[id] + '<br>最低:' + data[id][0] + '<br>最高:' + data[id][1] + '<br>平均:' + data[id][2]; }")) )), .radiusAxis(RadiusAxis()), .polar(Polar()), .series([ BarSerie( .itemStyle(ItemStyle( .normal(CommonItemStyleContent( .color(Color.transparent) )) )), .data(data.map{ $0[0] }), .coordinateSystem(.polar), .stack("最大最小值"), .silent(true) ), BarSerie( .data(data.map { $0[1] - $0[0] }), .coordinateSystem(.polar), .name("价格范围"), .stack("最大最小值") ), BarSerie( .itemStyle(ItemStyle( .normal(CommonItemStyleContent( .color(Color.transparent) )) )), .data(data.map { $0[2] - barHeight }), .coordinateSystem(.polar), .stack("均值"), .silent(true), .z(10) ), BarSerie( .data(data.map { _ in barHeight * 2 }), .coordinateSystem(.polar), .name("均值"), .stack("均值"), .barGap((-100)%), .z(10) ) ]), .legend(Legend( .show(true), .data(["A", "B", "C"]) )) ) } // MARK: 标签旋转 /// 地址: http://echarts.baidu.com/demo.html#bar-label-rotation static func barLabelRotationOption() -> Option { // TODO: 添加实现 return Option( ) } // MARK: 富文本标签 /// 地址: http://echarts.baidu.com/demo.html#bar-rich-text static func barRichTextOption() -> Option { let weatherIcons: [String: Jsonable] = [ "Sunny": "http://echarts.baidu.com/data/asset/img/weather/sunny_128.png", "Cloudy": "http://echarts.baidu.com/data/asset/img/weather/cloudy_128.png", "Showers": "http://echarts.baidu.com/data/asset/img/weather/showers_128.png" ] let seriesLabel = EmphasisLabel( .normal(LabelStyle( .show(true), .textBorderColor(.hexColor("#333")), .textBorderWidth(2) )) ) return Option( .title(Title( .text("Wheater Statistics") )), .tooltip(Tooltip( .trigger(.axis), .axisPointer(AxisPointerForTooltip( .type(.shadow) )) )), .legend(Legend( .data(["City Alpha", "City Beta", "City Gamma"]) )), .grid(Grid( .left(Position.value(100)) )), .toolbox(Toolbox( .show(true), .feature(ToolboxFeature( .saveAsImage(ToolboxFeatureSaveAsImage()) )) )), .xAxis(Axis( .type(.value), .name("Days"), .axisLabel(AxisLabel( .formatter(.string("{value}")) )) )), .yAxis(Axis( .type(.category), .inverse(true), .data(["Sunny", "Cloudy", "Showers"]), .axisLabel(AxisLabel( .formatter(.function("function (value) { return '{' + value + '| }\\n{value|' + value + '}'; }")), .margin(20), .rich([ "value": [ "lineHeight": 30, "align": "center" ], "Sunny": [ "height": 40, "align": "center", "backgroundColor": (["image": weatherIcons["Sunny"]] as Jsonable) ], "Cloudy": [ "height": 40, "width": 40, "align": "center", "backgroundColor": (["image": weatherIcons["Cloudy"]] as Jsonable) ], "Showers": [ "height": 40, "align": "center", "backgroundColor": (["image": weatherIcons["Showers"]] as Jsonable) ] ]) )) )), .series([ BarSerie( .name("City Alpha"), .data([165, 170, 30]), .label(seriesLabel), .markPoint(MarkPoint( .symbolSize(1), .symbolOffset([0, 50%]), .label(EmphasisLabel( .normal(LabelStyle( .formatter(.string("{a|{a}\\n}{b|{b} }{c|{c}}")), .backgroundColor(rgb(242, 242, 242)), .borderColor("#aaa"), .borderWidth(1), .borderRadius(4), .padding([4, 10]), .lineHeight(13), .position(.right), // .distance(20), .rich([ "a": [ "align": "center", "color": "#fff", "fontSize": 9, "textShadowBlur": 2, "textShadowColor": "#000", "textShadowOffsetX": 0, "textShadowOffsetY": 1, "textBorderColor": "#333", "textBorderWidth": 2 ], "b": ["color": "#333"], "c": [ "color": "#ff8811", "textBorderColor": "#000", "textBorderWidth": 1, "fontSize": 11 ] ]) )) )), .data([ ["type": "max","name": "max days: "], ["type": "min","name": "min days: "] ]) )) ), BarSerie( .name("City Beta"), .label(seriesLabel), .data([150, 105, 110]) ), BarSerie( .name("City Gamma"), .label(seriesLabel), .data([220, 82, 63]) ) ]) ) } // MARK: 动态数据 /// 地址: http://echarts.baidu.com/demo.html#dynamic-data static func dynamicDataOption() -> Option { var xAxisData1: [Jsonable] = [] var xAxisData2: [Jsonable] = [] var date = Date() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "hh:mm:ss a" for i in 0..<10 { xAxisData1.append(dateFormatter.string(from: date)) xAxisData2.append(i) date = Date(timeIntervalSince1970: date.timeIntervalSince1970) } var seriesData1: [Jsonable] = [] var seriesData2: [Jsonable] = [] for _ in 0..<10 { seriesData1.append(arc4random_uniform(1000) + 1) seriesData2.append(Double(arc4random_uniform(100) + 1) / 10.0 + 5) } return Option( .title(Title( .text("动态数据"), .subtext("纯属虚构") )), .tooltip(Tooltip( .trigger(.axis) )), .legend(Legend( .data(["最新成交价", "预购队列"]) )), .toolbox(Toolbox( .show(true), .feature(ToolboxFeature( .dataView(ToolboxFeatureDataView(.readOnly(false))), .restore(ToolboxFeatureRestore()), .saveAsImage(ToolboxFeatureSaveAsImage()) )) )), .dataZoom([SliderDataZoom( .show(false), .start(0), .end(100) )]), .xAxises([ Axis( .type(.category), .boundaryGap(true), .data(xAxisData1) ), Axis( .type(.category), .boundaryGap(true), .data(xAxisData2) ) ]), .yAxises([ Axis( .type(.value), .scale(true), .name("价格"), .max(30), .min(0), .boundaryGap(.notCategory([0.2, 0.2])) ), Axis( .type(.value), .scale(true), .name("预购量"), .max(1200), .min(0), .boundaryGap(.notCategory([0.2, 0.2])) ) ]), .series([ BarSerie( .name("预购队列"), .xAxisIndex(1), .yAxisIndex(1), .data(seriesData1) ), LineSerie( .name("最新的成交价"), .data(seriesData2) ) ]) ) } // MARK: 折柱混合 /// 地址: http://echarts.baidu.com/demo.html#mix-line-bar static func mixLineBarOption() -> Option { return Option( .tooltip(Tooltip( .trigger(.axis) )), .toolbox(Toolbox( .feature(ToolboxFeature( .dataView(ToolboxFeatureDataView( .show(true), .readOnly(false) )), .magicType(ToolboxFeatureMagicType( .show(true), .type([.line, .bar]) )), .restore(ToolboxFeatureRestore( .show(true) )), .saveAsImage(ToolboxFeatureSaveAsImage( .show(true) )) )) )), .legend(Legend( .data(["蒸发量","降水量","平均温度"]) )), .xAxis(Axis( .type(.category), .data(["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"]) )), .yAxises([ Axis( .type(.value), .name("水量"), .min(0), .max(250), .interval(50), .axisLabel(AxisLabel( .formatter(.string("{value} ml")) )) ), Axis( .type(.value), .name("温度"), .min(0), .max(25), .interval(5), .axisLabel(AxisLabel( .formatter(.string("{value} °C")) )) ) ]), .series([ BarSerie( .name("蒸发量"), .data([2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]) ), BarSerie( .name("降水量"), .data([2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]) ), LineSerie( .name("平均温度"), .yAxisIndex(1), .data([2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2]) ) ]) ) } // MARK: 全国宏观经济 /// 地址: http://echarts.baidu.com/demo.html#mix-timeline-finance static func mixTimelineFinanceOption() -> Option { // TODO: 添加实现 return Option( ) } // MARK: Budge /// 地址: http://echarts.baidu.com/demo.html#mix-zoom-on-value static func mixZoomOnValueOption() -> Option { // FIXME: 缺少showLoading和hideLoading guard let jsonUrl = Bundle.main.url(forResource: "MixZoomOnValue", withExtension: "json"), let jsonData = try? Data(contentsOf: jsonUrl), let jsonObj = try? JSONSerialization.jsonObject(with: jsonData, options: []) else { return Option() } let data = jsonObj as! [String: Any] return Option( .tooltip(Tooltip( .trigger(.axis), .axisPointer(AxisPointerForTooltip(// 没有label .type(.shadow)//, // .label(EmphasisLabel()) )) )), .toolbox(Toolbox( .show(true), .feature(ToolboxFeature(// 好像没有mark .dataView(ToolboxFeatureDataView(.show(true), .readOnly(false))), .magicType(ToolboxFeatureMagicType(.show(true), .type([.line, .bar]))), .restore(ToolboxFeatureRestore(.show(true))), .saveAsImage(ToolboxFeatureSaveAsImage(.show(true))) )) )), // .calculable(true),// FIXME: 没有calculable .legend(Legend( .data(["Growth", "Budget 2011", "Budget 2012"]), .itemGap(5) )), .grid(Grid( .top(Position.value(12%)), .left(.value(1%)), .right(.value(10%)), .containLabel(true) )), .xAxis(Axis( .type(.category), .data((data["names"] as! [String])) )), .yAxis(Axis( .type(.value), .name("Budget (million USD)"), .axisLabel(AxisLabel( .formatter(.function("function (a) { a = +a; return isFinite(a) ? echarts.format.addCommas(+a / 1000) : ''; }")) )) )), .dataZoom([ SliderDataZoom( .show(true), .start(94), .end(100) ), InsideDataZoom( .start(94), .end(100) ), SliderDataZoom( .show(true), .xAxisIndex(0), .filterMode(.empty), .width(30), .height(80%), .showDataShadow("false"), .left(.value(93%)) ) ]), .series([ BarSerie( .name("Budget 2011"), .data((data["budget2011List"] as! [Any]).map { return $0 as! Jsonable }) ), BarSerie( .name("Budget 2012"), .data((data["budget2012List"] as! [Any]).map { return $0 as! Jsonable } ) ) ]) ) } // MARK: 多 Y 轴示例 /// 地址: http://echarts.baidu.com/demo.html#multiple-y-axis static func multipleYAxisOption() -> Option { let colors: [Color] = [.hexColor("#5793f3"), .hexColor("#d14a61"), .hexColor("#675bba")] return Option( .color(colors), .tooltip(Tooltip( .trigger(.axis) )), .grid(Grid( .right(.value(20%)) )), .toolbox(Toolbox( .feature(ToolboxFeature( .dataView(ToolboxFeatureDataView( .show(true), .readOnly(false) )), .restore(ToolboxFeatureRestore( .show(true) )), .saveAsImage(ToolboxFeatureSaveAsImage( .show(true) )) )) )), .legend(Legend( .data(["蒸发量","降水量","平均温度"]) )), .xAxis(Axis( .type(.category), .axisTick(AxisTick( .alignWithLabel(true) )), .data(["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"]) )), .yAxises([ Axis( .type(.value), .name("蒸发量"), .min(0), .max(250), .position(.right), .axisLine(AxisLine( .lineStyle(LineStyle( .color(colors[0]) )) )), .axisLabel(AxisLabel( .formatter(.string("{value} ml")) )) ), Axis( .type(.value), .name("降水量"), .min(0), .max(250), .position(.right), .offset(40), // 针对屏幕小进行调整 .axisLine(AxisLine( .lineStyle(LineStyle( .color(colors[1]) )) )), .axisLabel(AxisLabel( .formatter(.string("{value} ml")) )) ), Axis( .type(.value), .name("平均温度"), .min(0), .max(25), .position(.left), .axisLine(AxisLine( .lineStyle(LineStyle( .color(colors[2]) )) )), .axisLabel(AxisLabel( .formatter(.string("{value} °C")) )) ) ]), .series([ BarSerie( .name("蒸发量"), .data([2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]) ), BarSerie( .name("降水量"), .yAxisIndex(1), .data([2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]) ), LineSerie( .name("平均温度"), .yAxisIndex(2), .data([2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2]) ) ]) ) } // MARK: 水印 - ECharts 下载统计 /// 地址: http://echarts.baidu.com/demo.html#watermark static func watermarkOption() -> Option { // TODO: 添加实现 return Option( ) } // MARK: Histogram /// 地址: http://echarts.baidu.com/demo.html#bar-histogram static func barHistogramOption() -> Option { // TODO: 添加实现 return Option( ) } }
mit
de9040f1bfac5cedff0c5d93e446a4e3
34.102978
229
0.3266
4.948059
false
false
false
false
hooman/swift
validation-test/compiler_crashers_2_fixed/rdar80704984.swift
11
1546
// RUN: %empty-directory(%t) // RUN: %target-clang %S/Inputs/rdar80704984.m -I %S/Inputs -c -o %t/rdar80704984.o // RUN: %target-build-swift -Xfrontend -disable-availability-checking -import-objc-header %S/Inputs/rdar80704984.h -Xlinker %t/rdar80704984.o -parse-as-library %s -o %t/a.out // RUN: %target-codesign %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop // rdar://82123254 // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime func run1(on object: PFXObject) async throws { do { try await object.enqueueErroryRequest() fatalError(); } catch let error { // CHECK: Domain=d Code=1 print(error) } } func run2(on object: PFXObject) async throws { // CHECK: (0, 1) print(try await object.enqueueSyncSuccessfulErroryRequest()) } func run3(on object: PFXObject) async throws { // CHECK: (0, 2) print(try await object.enqueueAsyncSuccessfulErroryRequest()) } func runAll(on object: PFXObject) async throws { do { try await object.enqueueErroryRequest() fatalError(); } catch let error { // CHECK: Domain=d Code=1 print(error) } // CHECK: (0, 1) print(try await object.enqueueSyncSuccessfulErroryRequest()) // CHECK: (0, 2) print(try await object.enqueueAsyncSuccessfulErroryRequest()) } @main struct Main { static func main() async throws { let object = PFXObject() try await run1(on: object) try await run2(on: object) try await run3(on: object) try await runAll(on: object) } }
apache-2.0
d753bc44f6fd40044be0a35a6f0a1d4e
27.109091
174
0.688228
3.110664
false
false
false
false
visenze/visearch-sdk-swift
Example/Example/Lib/SwiftHUEColorPicker.swift
1
9889
// // SwiftHUEColorPicker.swift // SwiftHUEColorPicker // // Created by Maxim Bilan on 5/6/15. // Copyright (c) 2015 Maxim Bilan. All rights reserved. // import UIKit public protocol SwiftHUEColorPickerDelegate : class { func valuePicked(_ color: UIColor, type: SwiftHUEColorPicker.PickerType) } open class SwiftHUEColorPicker: UIView { // MARK: - Type public enum PickerType: Int { case color case saturation case brightness case alpha } // MARK: - Direction public enum PickerDirection: Int { case horizontal case vertical } // MARK: - Constants let HUEMaxValue: CGFloat = 360 let PercentMaxValue: CGFloat = 100 // MARK: - Main public properties open weak var delegate: SwiftHUEColorPickerDelegate! open var type: PickerType = .color open var direction: PickerDirection = .horizontal open var currentColor: UIColor { get { return color } set(newCurrentColor) { color = newCurrentColor var hue: CGFloat = 0 var s: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 if color.getHue(&hue, saturation: &s, brightness: &b, alpha: &a) { var needUpdate = false if hueValue != hue { needUpdate = true } hueValue = hue saturationValue = s brightnessValue = b alphaValue = a if needUpdate && hueValue > 0 && hueValue < 1 { update() setNeedsDisplay() } } } } // MARK: - Additional public properties open var labelFontColor: UIColor = UIColor.white open var labelBackgroundColor: UIColor = UIColor.black open var labelFont = UIFont(name: "Helvetica Neue", size: 12) open var cornerRadius: CGFloat = 10.0 // MARK: - Private properties fileprivate var color: UIColor = UIColor.clear fileprivate var currentSelectionY: CGFloat = 0.0 fileprivate var currentSelectionX: CGFloat = 0.0 fileprivate var hueImage: UIImage! fileprivate var hueValue: CGFloat = 0.0 fileprivate var saturationValue: CGFloat = 1.0 fileprivate var brightnessValue: CGFloat = 1.0 fileprivate var alphaValue: CGFloat = 1.0 // MARK: - Initialization required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.backgroundColor = UIColor.clear } override public init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clear } override open func layoutSubviews() { super.layoutSubviews() if !self.isHidden { update() } } // MARK: - Prerendering func generateHUEImage(_ size: CGSize) -> UIImage { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(size, false, 0) UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip() if direction == .horizontal { for x: Int in 0 ..< Int(size.width) { switch type { case .color: UIColor(hue: CGFloat(CGFloat(x) / size.width), saturation: 1.0, brightness: 1.0, alpha: 1.0).set() break case .saturation: UIColor(hue: hueValue, saturation: CGFloat(CGFloat(x) / size.width), brightness: 1.0, alpha: 1.0).set() break case .brightness: UIColor(hue: hueValue, saturation: 1.0, brightness: CGFloat(CGFloat(x) / size.width), alpha: 1.0).set() break case .alpha: UIColor(hue: hueValue, saturation: 1.0, brightness: 1.0, alpha: CGFloat(CGFloat(x) / size.width)).set() break } let temp = CGRect(x: CGFloat(x), y: 0, width: 1, height: size.height) UIRectFill(temp) } } else { for y: Int in 0 ..< Int(size.height) { switch type { case .color: UIColor(hue: CGFloat(CGFloat(y) / size.height), saturation: 1.0, brightness: 1.0, alpha: 1.0).set() break case .saturation: UIColor(hue: hueValue, saturation: CGFloat(CGFloat(y) / size.height), brightness: 1.0, alpha: 1.0).set() break case .brightness: UIColor(hue: hueValue, saturation: 1.0, brightness: CGFloat(CGFloat(y) / size.height), alpha: 1.0).set() break case .alpha: UIColor(hue: hueValue, saturation: 1.0, brightness: 1.0, alpha: CGFloat(CGFloat(y) / size.height)).set() break } let temp = CGRect(x: 0, y: CGFloat(y), width: size.width, height: 1) UIRectFill(temp) } } let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } // MARK: - Updating func update() { let offset = (direction == .horizontal ? self.frame.size.height : self.frame.size.width) let halfOffset = offset * 0.5 var size = self.frame.size if direction == .horizontal { size.width -= offset } else { size.height -= offset } var value: CGFloat = 0 switch type { case .color: value = hueValue break case .saturation: value = saturationValue break case .brightness: value = brightnessValue break case .alpha: value = alphaValue break } currentSelectionX = (value * size.width) + halfOffset currentSelectionY = (value * size.height) + halfOffset hueImage = generateHUEImage(size) } // MARK: - Drawing override open func draw(_ rect: CGRect) { super.draw(rect) let radius = (direction == .horizontal ? self.frame.size.height : self.frame.size.width) let halfRadius = radius * 0.5 var circleX = currentSelectionX - halfRadius var circleY = currentSelectionY - halfRadius if circleX >= rect.size.width - radius { circleX = rect.size.width - radius } else if circleX < 0 { circleX = 0 } if circleY >= rect.size.height - radius { circleY = rect.size.height - radius } else if circleY < 0 { circleY = 0 } let circleRect = (direction == .horizontal ? CGRect(x: circleX, y: 0, width: radius, height: radius) : CGRect(x: 0, y: circleY, width: radius, height: radius)) let circleColor = labelBackgroundColor var hueRect = rect if hueImage != nil { if direction == .horizontal { hueRect.size.width -= radius hueRect.origin.x += halfRadius } else { hueRect.size.height -= radius hueRect.origin.y += halfRadius } hueImage.draw(in: hueRect) } let context = UIGraphicsGetCurrentContext() circleColor.set() context!.addEllipse(in: circleRect) context!.setFillColor(circleColor.cgColor) context!.fillPath() context!.strokePath() let textParagraphStyle = NSMutableParagraphStyle() textParagraphStyle.alignment = .center let attributes: NSDictionary = [convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): labelFontColor, convertFromNSAttributedStringKey(NSAttributedString.Key.paragraphStyle): textParagraphStyle, convertFromNSAttributedStringKey(NSAttributedString.Key.font): labelFont!] var value: CGFloat = 0 switch type { case .color: value = hueValue break case .saturation: value = saturationValue break case .brightness: value = brightnessValue break case .alpha: value = alphaValue break } let textValue = Int(value * (type == .color ? HUEMaxValue : PercentMaxValue)) let text = String(textValue) as NSString var textRect = circleRect textRect.origin.y += (textRect.size.height - (labelFont?.lineHeight)!) * 0.5 text.draw(in: textRect, withAttributes: convertToOptionalNSAttributedStringKeyDictionary(attributes as? [String : AnyObject])) } // MARK: - Touch events open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touch: AnyObject? = touches.first if let point = touch?.location(in: self) { handleTouch(point) } } open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { let touch: AnyObject? = touches.first if let point = touch?.location(in: self) { handleTouch(point) } } open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { let touch: AnyObject? = touches.first if let point = touch?.location(in: self) { handleTouch(point) } } open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { } // MARK: - Touch handling func handleTouch(_ touchPoint: CGPoint) { currentSelectionX = touchPoint.x currentSelectionY = touchPoint.y let offset = (direction == .horizontal ? self.frame.size.height : self.frame.size.width) let halfOffset = offset * 0.5 if currentSelectionX < halfOffset { currentSelectionX = halfOffset } else if currentSelectionX >= self.frame.size.width - halfOffset { currentSelectionX = self.frame.size.width - halfOffset } if currentSelectionY < halfOffset { currentSelectionY = halfOffset } else if currentSelectionY >= self.frame.size.height - halfOffset { currentSelectionY = self.frame.size.height - halfOffset } let value = (direction == .horizontal ? CGFloat((currentSelectionX - halfOffset) / (self.frame.size.width - offset)) : CGFloat((currentSelectionY - halfOffset) / (self.frame.size.height - offset))) switch type { case .color: hueValue = value break case .saturation: saturationValue = value break case .brightness: brightnessValue = value break case .alpha: alphaValue = value break } color = UIColor(hue: hueValue, saturation: saturationValue, brightness: brightnessValue, alpha: alphaValue) if delegate != nil { delegate.valuePicked(color, type: type) } setNeedsDisplay() } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String { return input.rawValue } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)}) }
mit
8a187e954e819e05f710e499163daa8f
26.167582
161
0.684498
3.596
false
false
false
false
ysk1031/PokeBu-Swift
Pokebu/HatenaConfigTableViewController.swift
1
3121
// // HatenaConfigTableViewController.swift // Pokebu // // Created by Yusuke Aono on 8/21/15. // Copyright © 2015 Yusuke Aono. All rights reserved. // import UIKit import HatenaBookmarkSDK class HatenaConfigTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let alert = UIAlertController( title: "確認", message: "はてなブックマークアカウントの連携を解除してもよろしいですか?", preferredStyle: UIAlertControllerStyle.Alert ) let okAction = UIAlertAction( title: "OK", style: UIAlertActionStyle.Default, handler: { action in HTBHatenaBookmarkManager.sharedManager().logout() self.navigationController?.popViewControllerAnimated(true) } ) let cancelAction = UIAlertAction( title: "キャンセル", style: UIAlertActionStyle.Default, handler: { action in return } ) alert.addAction(okAction) alert.addAction(cancelAction) presentViewController(alert, animated: true, completion: nil) tableView.deselectRowAtIndexPath(indexPath, animated: true) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("HatenaAccount", forIndexPath: indexPath) cell.textLabel?.text = "連携を解除" cell.detailTextLabel?.text = HTBHatenaBookmarkManager.sharedManager().username return cell } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "はてなブックマークアカウント" } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
d2b13aebee0c88a60619dc9c9f3d27be
33.159091
118
0.673985
5.236934
false
false
false
false
shajrawi/swift
test/Constraints/construction.swift
1
5546
// RUN: %target-typecheck-verify-swift struct X { var i : Int, j : Int } struct Y { init (_ x : Int, _ y : Float, _ z : String) {} } enum Z { case none case char(UnicodeScalar) case string(String) case point(Int, Int) init() { self = .none } init(_ c: UnicodeScalar) { self = .char(c) } init(_ s: String) { self = .string(s) } init(_ x: Int, _ y: Int) { self = .point(x, y) } } enum Optional<T> { // expected-note {{'T' declared as parameter to type 'Optional'}} case none case value(T) init() { self = .none } init(_ t: T) { self = .value(t) } } class Base { } class Derived : Base { } var d : Derived typealias Point = (x : Int, y : Int) var hello : String = "hello"; var world : String = "world"; var i : Int var z : Z = .none func acceptZ(_ z: Z) {} func acceptString(_ s: String) {} Point(1, 2) // expected-warning {{expression of type '(x: Int, y: Int)' is unused}} var db : Base = d X(i: 1, j: 2) // expected-warning{{unused}} Y(1, 2, "hello") // expected-warning{{unused}} // Unions Z(UnicodeScalar("a")) // expected-warning{{unused}} Z(1, 2) // expected-warning{{unused}} acceptZ(.none) acceptZ(.char("a")) acceptString("\(hello), \(world) #\(i)!") Optional<Int>(1) // expected-warning{{unused}} Optional(1) // expected-warning{{unused}} _ = .none as Optional<Int> Optional(.none) // expected-error{{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{9-9=<Any>}} // Interpolation _ = "\(hello), \(world) #\(i)!" class File { init() { fd = 0 body = "" } var fd : Int32, body : String func replPrint() { print("File{\n fd=\(fd)\n body=\"\(body)\"\n}", terminator: "") } } // Non-trivial references to metatypes. struct Foo { struct Inner { } } extension Foo { func getInner() -> Inner { return Inner() } } // Downcasting var b : Base _ = b as! Derived // Construction doesn't permit conversion. // NOTE: Int and other integer-literal convertible types // are special cased in the library. Int(i) // expected-warning{{unused}} _ = i as Int Z(z) // expected-error{{cannot invoke initializer for type 'Z' with an argument list of type '(Z)'}} // expected-note @-1 {{overloads for 'Z' exist with these partially matching parameter lists: (String), (UnicodeScalar)}} Z.init(z) // expected-error {{cannot invoke 'Z.Type.init' with an argument list of type '(Z)'}} // expected-note @-1 {{overloads for 'Z.Type.init' exist with these partially matching parameter lists: (String), (UnicodeScalar)}} _ = z as Z // Construction from inouts. struct FooRef { } struct BarRef { init(x: inout FooRef) {} init(x: inout Int) {} } var f = FooRef() var x = 0 BarRef(x: &f) // expected-warning{{unused}} BarRef(x: &x) // expected-warning{{unused}} // Construction from a Type value not immediately resolved. struct S1 { init(i: Int) { } } struct S2 { init(i: Int) { } } func getMetatype(_ i: Int) -> S1.Type { return S1.self } func getMetatype(_ d: Double) -> S2.Type { return S2.self } var s1 = getMetatype(1).init(i: 5) s1 = S1(i: 5) var s2 = getMetatype(3.14).init(i: 5) s2 = S2(i: 5) // rdar://problem/19254404 let i32 = Int32(123123123) Int(i32 - 2 + 1) // expected-warning{{unused}} // rdar://problem/19459079 let xx: UInt64 = 100 let yy = ((xx + 10) - 5) / 5 let zy = (xx + (10 - 5)) / 5 // rdar://problem/30588177 struct S3 { init() { } } let s3a = S3() extension S3 { init?(maybe: S3) { return nil } } let s3b = S3(maybe: s3a) // SR-5245 - Erroneous diagnostic - Type of expression is ambiguous without more context class SR_5245 { struct S { enum E { case e1 case e2 } let e: [E] } init(s: S) {} } SR_5245(s: SR_5245.S(f: [.e1, .e2])) // expected-error@-1 {{incorrect argument label in call (have 'f:', expected 'e:')}} {{22-23=e}} // rdar://problem/34670592 - Compiler crash on heterogeneous collection literal _ = Array([1, "hello"]) // Ok func init_via_non_const_metatype(_ s1: S1.Type) { _ = s1(i: 42) // expected-error {{initializing from a metatype value must reference 'init' explicitly}} {{9-9=.init}} _ = s1.init(i: 42) // ok } // rdar://problem/45535925 - diagnostic is attached to invalid source location func rdar_45535925() { struct S { var addr: String var port: Int private init(addr: String, port: Int?) { // expected-note@-1 {{'init(addr:port:)' declared here}} self.addr = addr self.port = port ?? 31337 } private init(port: Int) { self.addr = "localhost" self.port = port } private func foo(_: Int) {} // expected-note {{'foo' declared here}} private static func bar() {} // expected-note {{'bar()' declared here}} } _ = S(addr: "localhost", port: nil) // expected-error@-1 {{'S' initializer is inaccessible due to 'private' protection level}} func baz(_ s: S) { s.foo(42) // expected-error@-1 {{'foo' is inaccessible due to 'private' protection level}} S.bar() // expected-error@-1 {{'bar' is inaccessible due to 'private' protection level}} } } // rdar://problem/50668864 func rdar_50668864() { struct Foo { init(anchors: [Int]) { // TODO: This would be improved when argument conversions are diagnosed via new diagnostic framework, // actual problem here is that `[Int]` cannot be converted to function type represented by a closure. self = .init { _ in [] } // expected-error {{type of expression is ambiguous without more context}} } } }
apache-2.0
957acee106f31879ddf6568062c84cd4
23.981982
171
0.619365
3.174585
false
false
false
false
Archerlly/ACRouter
ACRouter/Classes/ACCommonExtension.swift
1
2263
// // ACCommonExtension.swift // Pods // // Created by SnowCheng on 14/03/2017. // // import Foundation extension String { public func ac_dropFirst(_ count: Int) -> String { // String.init(describing: utf8.dropFirst(count)) return substring(from: index(startIndex, offsetBy: count)) } public func ac_dropLast(_ count: Int) -> String { return substring(to: index(endIndex, offsetBy: -count)) } public func ac_matchClass() -> AnyClass?{ if var appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String { if appName == "" { appName = ((Bundle.main.bundleIdentifier!).characters.split{$0 == "."}.map { String($0) }).last ?? "" } var clsStr = self if !clsStr.contains("\(appName)."){ clsStr = appName + "." + clsStr } let strArr = clsStr.components(separatedBy: ".") var className = "" let num = strArr.count if num > 2 || strArr.contains(appName) { var nameStringM = "_TtC" + String(repeating: "C", count: num - 2) for (_, s): (Int, String) in strArr.enumerated(){ nameStringM += "\(s.characters.count)\(s)" } className = nameStringM } else { className = clsStr } return NSClassFromString(className) } return nil; } } extension Dictionary { mutating func ac_combine(_ dict: Dictionary) { var tem = self dict.forEach({ (key, value) in if let existValue = tem[key] { //combine same name query if let arrValue = existValue as? [Value] { tem[key] = (arrValue + [value]) as? Value } else { tem[key] = ([existValue, value]) as? Value } } else { tem[key] = value } }) self = tem } }
mit
4e783590583514b15b53a2b28fe9919c
27.2875
117
0.448962
4.898268
false
false
false
false
tlax/GaussSquad
GaussSquad/Model/Scanner/Filter/MScannerFilterItemDefine.swift
1
1325
import Foundation import MetalKit import MetalPerformanceShaders class MScannerFilterItemDefine:MScannerFilterItem { static func filterTexture(device:MTLDevice, library:MTLLibrary, texture:MTLTexture) -> MTLTexture? { let width:Int = texture.width let height:Int = texture.height let blankTexture:MTLTexture = MScannerFilter.blankTexure( device:device, width:width, height:height) let commandQueue:MTLCommandQueue = device.makeCommandQueue() let commandBuffer:MTLCommandBuffer = commandQueue.makeCommandBuffer() let corners:Float = -1 let center:Float = 5 let weights:[Float] = [ corners, 0, corners, 0, center, 0, corners, 0, corners ] let convolution:MPSImageConvolution = MPSImageConvolution( device:device, kernelWidth:3, kernelHeight:3, weights:weights) convolution.edgeMode = MPSImageEdgeMode.zero convolution.encode( commandBuffer:commandBuffer, sourceTexture:texture, destinationTexture:blankTexture) commandBuffer.commit() commandBuffer.waitUntilCompleted() return blankTexture } }
mit
c129d36b91a2d7bb01baa9f5a58d360a
29.813953
102
0.618868
5.430328
false
false
false
false
artyom-stv/TextInputKit
TextInputKit/TextInputKit/Code/SpecializedTextInput/PhoneNumber/PhoneNumberUtils.swift
1
4923
// // PhoneNumberUtils.swift // TextInputKit // // Created by Artem Starosvetskiy on 11/01/2017. // Copyright © 2017 Artem Starosvetskiy. All rights reserved. // import Foundation struct PhoneNumberUtils { private init() {} } extension PhoneNumberUtils { struct CursorPositionInvariant { let numberOfDigitsAfterCursor: Int } static func cursorPositionInvariant( from cursorIndex: String.Index, in string: String ) -> CursorPositionInvariant { let stringView = string.unicodeScalars let cursorIndex = cursorIndex.samePosition(in: stringView)! let numberOfDigitsAfterCursor = stringView.suffix(from: cursorIndex).reduce(0) { (result, unicodeScalar) in return StringUtils.isDigit(unicodeScalar) ? result + 1 : result } return CursorPositionInvariant(numberOfDigitsAfterCursor: numberOfDigitsAfterCursor) } static func cursorIndex( from invariant: CursorPositionInvariant, in string: String ) -> String.Index { let stringView = string.unicodeScalars var cursorIndex = stringView.endIndex var numberOfDigits = 0 while cursorIndex > stringView.startIndex { if numberOfDigits == invariant.numberOfDigitsAfterCursor { break } cursorIndex = stringView.index(before: cursorIndex) if StringUtils.isDigit(stringView[cursorIndex]) { numberOfDigits += 1 } } return cursorIndex.samePosition(in: string)! } } extension PhoneNumberUtils { static func adjustedEditedRange( forEditing originalString: String, withSelection originalSelectedRange: Range<String.Index>, replacing replacementString: String, at editedRange: Range<String.Index>) -> Range<String.Index> { let wasPressedBackspaceOrDeleteWithEmptySelection = originalSelectedRange.isEmpty && !editedRange.isEmpty if wasPressedBackspaceOrDeleteWithEmptySelection { assert(originalString.distance(from: editedRange.lowerBound, to: editedRange.upperBound) == 1, "Edited range can be non-empty while selected range is empty only when user presses 'backspace' or 'delete' key.") let originalStringView = originalString.unicodeScalars let wasPressedBackspace = (originalSelectedRange.lowerBound == editedRange.upperBound) if wasPressedBackspace { // Backspace var adjustedLowerBound = editedRange.lowerBound.samePosition(in: originalStringView)! while adjustedLowerBound != originalStringView.startIndex { if StringUtils.isDigit(originalStringView[adjustedLowerBound]) { break } adjustedLowerBound = originalStringView.index(before: adjustedLowerBound) } return adjustedLowerBound.samePosition(in: originalString)! ..< editedRange.upperBound } else { // Delete var adjustedUpperBound = editedRange.upperBound.samePosition(in: originalStringView)! while adjustedUpperBound != originalStringView.endIndex { if StringUtils.isDigit(originalStringView[adjustedUpperBound]) { break } adjustedUpperBound = originalStringView.index(after: adjustedUpperBound) } return editedRange.lowerBound ..< adjustedUpperBound.samePosition(in: originalString)! } } return editedRange } static func adjustedString( afterEditing originalString: String, replacing replacementString: String, at editedRange: Range<String.Index>) -> String { var editedString = originalString.replacingCharacters(in: editedRange, with: replacementString) if let firstUnicodeScalar = editedString.unicodeScalars.first, !StringUtils.isPlus(firstUnicodeScalar) { editedString.insert("+", at: editedString.startIndex) } return editedString } } extension PhoneNumberUtils { static func isValidPhoneNumber(_ phoneNumberString: String) -> Bool { return phoneNumberString.rangeOfCharacter(from: deniedCharacters) == nil } private static let deniedCharacters: CharacterSet = { var allowedCharacters = CharacterSet.decimalDigits allowedCharacters.formUnion(StringUtils.plusCharacters) allowedCharacters.formUnion(StringUtils.spaceCharacters) allowedCharacters.formUnion(StringUtils.dashCharacters) allowedCharacters.formUnion(StringUtils.paranthesisCharacters) allowedCharacters.formUnion(StringUtils.pointCharacters) return allowedCharacters.inverted }() }
mit
325a3418f413822628ff18ac1d7b6688
34.410072
133
0.662332
5.811098
false
false
false
false
snakajima/SwipeBrowser
ios/SwipeBrowser/SwipeBrowser/SwipeParser.swift
1
15784
// // SwipeParser.swift // Swipe // // Created by satoshi on 6/4/15. // Copyright (c) 2015 Satoshi Nakajima. All rights reserved. // // http://stackoverflow.com/questions/23790143/how-do-i-set-uicolor-to-this-exact-shade-green-that-i-want/23790739#23790739 // dropFirst http://stackoverflow.com/questions/28445917/what-is-the-most-succinct-way-to-remove-the-first-character-from-a-string-in-swi/28446142#28446142 #if os(OSX) import Cocoa public typealias UIColor = NSColor public typealias UIFont = NSFont #else import UIKit #endif import ImageIO class SwipeParser { //let color = NSRegularExpression(pattern: "#[0-9A-F]6", options: NSRegularExpressionOptions.CaseInsensitive, error: nil) static let colorMap = [ "red":UIColor.red, "black":UIColor.black, "blue":UIColor.blue, "white":UIColor.white, "green":UIColor.green, "yellow":UIColor.yellow, "purple":UIColor.purple, "gray":UIColor.gray, "darkGray":UIColor.darkGray, "lightGray":UIColor.lightGray, "brown":UIColor.brown, "orange":UIColor.orange, "cyan":UIColor.cyan, "magenta":UIColor.magenta ] static let regexColor = try! NSRegularExpression(pattern: "^#[A-F0-9]*$", options: NSRegularExpression.Options.caseInsensitive) static func parseColor(_ value:Any?, defaultColor:CGColor = UIColor.clear.cgColor) -> CGColor { if value == nil { return defaultColor } if let rgba = value as? [String: Any] { var red:CGFloat = 0.0, blue:CGFloat = 0.0, green:CGFloat = 0.0 var alpha:CGFloat = 1.0 if let v = rgba["r"] as? CGFloat { red = v } if let v = rgba["g"] as? CGFloat { green = v } if let v = rgba["b"] as? CGFloat { blue = v } if let v = rgba["a"] as? CGFloat { alpha = v } return UIColor(red: red, green: green, blue: blue, alpha: alpha).cgColor } else if let key = value as? String { if let color = colorMap[key] { return color.cgColor } else { let results = regexColor.matches(in: key, options: NSRegularExpression.MatchingOptions(), range: NSMakeRange(0, key.characters.count)) if results.count > 0 { let hex = String(key.characters.dropFirst()) let cstr = hex.cString(using: String.Encoding.ascii) let v = strtoll(cstr!, nil, 16) //NSLog("SwipeParser hex=\(hex), \(value)") var r = Int64(0), g = Int64(0), b = Int64(0), a = Int64(255) switch(hex.characters.count) { case 3: r = v / 0x100 * 0x11 g = v / 0x10 % 0x10 * 0x11 b = v % 0x10 * 0x11 case 4: r = v / 0x1000 * 0x11 g = v / 0x100 % 0x10 * 0x11 b = v / 0x10 % 0x10 * 0x11 a = v % 0x10 * 0x11 case 6: r = v / 0x10000 g = v / 0x100 b = v case 8: r = v / 0x1000000 g = v / 0x10000 b = v / 0x100 a = v default: break; } return UIColor(red: CGFloat(r)/255, green: CGFloat(g%256)/255, blue: CGFloat(b%256)/255, alpha: CGFloat(a%256)/255).cgColor } return UIColor.red.cgColor } } return UIColor.green.cgColor } static func transformedPath(_ path:CGPath, param:[String:Any]?, size:CGSize) -> CGPath? { if let value = param { var scale:CGSize? if let s = value["scale"] as? CGFloat { scale = CGSize(width: s, height: s) } if let scales = value["scale"] as? [CGFloat], scales.count == 2 { scale = CGSize(width: scales[0], height: scales[1]) } if let s = scale { var xf = CGAffineTransform(translationX: size.width / 2, y: size.height / 2) xf = xf.scaledBy(x: s.width, y: s.height) xf = xf.translatedBy(x: -size.width / 2, y: -size.height / 2) return path.copy(using: &xf)! } } return nil } static func parseTransform(_ param:[String:Any]?, scaleX:CGFloat, scaleY:CGFloat, base:[String:Any]?, fSkipTranslate:Bool, fSkipScale:Bool) -> CATransform3D? { if let p = param { var value = p var xf = CATransform3DIdentity var hasValue = false if let b = base { for key in ["translate", "rotate", "scale"] { if let v = b[key], value[key]==nil { value[key] = v } } } if fSkipTranslate { if let b = base, let translate = b["translate"] as? [CGFloat], translate.count == 2{ xf = CATransform3DTranslate(xf, translate[0] * scaleX, translate[1] * scaleY, 0) } } else { if let translate = value["translate"] as? [CGFloat] { if translate.count == 2 { xf = CATransform3DTranslate(xf, translate[0] * scaleX, translate[1] * scaleY, 0) } hasValue = true } } if let depth = value["depth"] as? CGFloat { xf = CATransform3DTranslate(xf, 0, 0, depth) hasValue = true } if let rot = value["rotate"] as? CGFloat { xf = CATransform3DRotate(xf, rot * CGFloat(M_PI / 180.0), 0, 0, 1) hasValue = true } if let rots = value["rotate"] as? [CGFloat], rots.count == 3 { let m = CGFloat(M_PI / 180.0) xf = CATransform3DRotate(xf, rots[0] * m, 1, 0, 0) xf = CATransform3DRotate(xf, rots[1] * m, 0, 1, 0) xf = CATransform3DRotate(xf, rots[2] * m, 0, 0, 1) hasValue = true } if !fSkipScale { if let scale = value["scale"] as? CGFloat { xf = CATransform3DScale(xf, scale, scale, 1.0) hasValue = true } // LATER: Use "where" if let scales = value["scale"] as? [CGFloat] { if scales.count == 2 { xf = CATransform3DScale(xf, scales[0], scales[1], 1.0) } hasValue = true } } return hasValue ? xf : nil } return nil } static func parseSize(_ param:Any?, defaultValue:CGSize = CGSize(width: 0.0, height: 0.0), scale:CGSize) -> CGSize { if let values = param as? [CGFloat], values.count == 2 { return CGSize(width: values[0] * scale.width, height: values[1] * scale.height) } return CGSize(width: defaultValue.width * scale.width, height: defaultValue.height * scale.height) } static func parseFloat(_ param:Any?, defaultValue:Float = 1.0) -> Float { if let value = param as? Float { return value } return defaultValue } static func parseCGFloat(_ param:Any?, defaultValue:CGFloat = 0.0) -> CGFloat { if let value = param as? CGFloat { return value } return defaultValue } // // This function performs the "deep inheritance" // Object property: Instance properties overrides Base properties // Array property: Merge (inherit properties in case of "id" matches, otherwise, just append) // static func inheritProperties(_ object:[String:Any], baseObject:[String:Any]?) -> [String:Any] { var ret = object if let prototype = baseObject { for (keyString, value) in prototype { if ret[keyString] == nil { // Only the baseObject has the property ret[keyString] = value } else if let arrayObject = ret[keyString] as? [[String:Any]], let arrayBase = value as? [[String:Any]] { // Each has the property array. We need to merge them var retArray = arrayBase var idMap = [String:Int]() for (index, item) in retArray.enumerated() { if let key = item["id"] as? String { idMap[key] = index } } for item in arrayObject { if let key = item["id"] as? String { if let index = idMap[key] { // id matches, merge them retArray[index] = SwipeParser.inheritProperties(item, baseObject: retArray[index]) } else { // no id match, just append retArray.append(item) } } else { // no id, just append retArray.append(item) } } ret[keyString] = retArray } else if let objects = ret[keyString] as? [String:Any], let objectsBase = value as? [String:Any] { // Each has the property objects. We need to merge them. Example: '"events" { }' var retObjects = objectsBase for (key, val) in objects { retObjects[key] = val } ret[keyString] = retObjects } } } return ret } /* static func imageWith(name:String) -> UIImage? { var components = name.componentsSeparatedByString("/") if components.count == 1 { return UIImage(named: name) } let filename = components.last components.removeLast() let dir = components.joinWithSeparator("/") if let path = NSBundle.mainBundle().pathForResource(filename, ofType: nil, inDirectory: dir) { //NSLog("ScriptParset \(path)") return UIImage(contentsOfFile: path) } return nil } static func imageSourceWith(name:String) -> CGImageSource? { var components = name.componentsSeparatedByString("/") let url:URL? if components.count == 1 { url = NSBundle.mainBundle().URLForResource(name, withExtension: nil) } else { let filename = components.last components.removeLast() let dir = components.joinWithSeparator("/") url = NSBundle.mainBundle().URLForResource(filename!, withExtension: nil, subdirectory: dir) } if let urlImage = url { return CGImageSourceCreateWithURL(urlImage, nil) } return nil } */ static let regexPercent = try! NSRegularExpression(pattern: "^[0-9\\.]+%$", options: NSRegularExpression.Options.caseInsensitive) static func parsePercent(_ value:String, full:CGFloat, defaultValue:CGFloat) -> CGFloat { let num = regexPercent.numberOfMatches(in: value, options: NSRegularExpression.MatchingOptions(), range: NSMakeRange(0, value.characters.count)) if num == 1 { return CGFloat((value as NSString).floatValue / 100.0) * full } return defaultValue } static func parsePercentAny(_ value:Any, full:CGFloat, defaultValue:CGFloat) -> CGFloat? { if let f = value as? CGFloat { return f } else if let str = value as? String { return SwipeParser.parsePercent(str, full: full, defaultValue: defaultValue) } return nil } static func parseFont(_ value:Any?, scale:CGSize, full:CGFloat) -> UIFont { let fontSize = parseFontSize(value, full: full, defaultValue: 20, markdown: true) let fontNames = parseFontName(value, markdown: true) for name in fontNames { if let font = UIFont(name: name, size: fontSize * scale.height) { return font } } return UIFont.systemFont(ofSize: fontSize * scale.height) } static func parseFontSize(_ value:Any?, full:CGFloat, defaultValue:CGFloat, markdown:Bool) -> CGFloat { let key = markdown ? "size" : "fontSize" if let info = value as? [String:Any] { if let sizeValue = info[key] as? CGFloat { return sizeValue } else if let percent = info[key] as? String { return SwipeParser.parsePercent(percent, full: full, defaultValue: defaultValue) } } return defaultValue } static func parseFontName(_ value:Any?, markdown:Bool) -> [String] { let key = markdown ? "name" : "fontName" if let info = value as? [String:Any] { if let name = info[key] as? String { return [name] } else if let names = info[key] as? [String] { return names } } return [] } static func parseShadow(_ value:Any?, scale:CGSize) -> NSShadow { let shadow = NSShadow() if let info = value as? [String:Any] { shadow.shadowOffset = SwipeParser.parseSize(info["offset"], defaultValue: CGSize(width: 1.0, height: 1.0), scale:scale) shadow.shadowBlurRadius = SwipeParser.parseCGFloat(info["radius"], defaultValue: 2) * scale.width shadow.shadowColor = UIColor(cgColor: SwipeParser.parseColor(info["color"], defaultColor: UIColor.black.cgColor)) } return shadow } static func localizedString(_ params:[String:Any], langId:String?) -> String? { if let key = langId, let text = params[key] as? String { return text } else if let text = params["*"] as? String { return text } return nil } static func preferredLangId(in languages: [[String : Any]]) -> String? { // 1st, find a lang id matching system language. // A lang id can be in "en-US", "en", "zh-Hans-CN" or "zh-Hans" formats (with/without a country code). // "en-US" or "zh-Hans-CN" formats with a country code have higher priority to match than "en" or "zh-Hans" without a country code. if let systemLanguage = NSLocale.preferredLanguages.first?.components(separatedBy: "-") { for rangeEnd in systemLanguage.indices.reversed() { let langId = systemLanguage[0...rangeEnd].joined(separator: "-") if languages.contains(where: { $0["id"] as? String == langId }) { return langId } } } // 2nd, use the default lang id ("*") if no lang id matches, and the default id exists. if languages.contains(where: { $0["id"] as? String == "*" }) { return "*" } // At last, use the first lang id in the language list if still no lang id is specified. if let langId = languages.first?["id"] as? String { return langId } return nil } }
mit
9ba331e21c9b35becb7d3d7ebbd04282
40.536842
163
0.512924
4.527826
false
false
false
false
rolson/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Features/Service feature table (cache)/OnInteractionCacheViewController.swift
1
2244
// Copyright 2016 Esri. // // 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 ArcGIS class OnInteractionCacheViewController: UIViewController { @IBOutlet private weak var mapView:AGSMapView! private var map:AGSMap! private let FEATURE_SERVICE_URL = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/PoolPermits/FeatureServer/0" override func viewDidLoad() { super.viewDidLoad() //add the source code button item to the right of navigation bar (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["OnInteractionCacheViewController"] //initialize map with light gray canvas basemap self.map = AGSMap(basemap: AGSBasemap.lightGrayCanvasBasemap()) //initial viewpoint self.map.initialViewpoint = AGSViewpoint(targetExtent: AGSEnvelope(XMin: -1.30758164047166E7, yMin: 4014771.46954516, xMax: -1.30730056797177E7, yMax: 4016869.78617381, spatialReference: AGSSpatialReference.webMercator())) //feature layer let featureTable = AGSServiceFeatureTable(URL: NSURL(string: FEATURE_SERVICE_URL)!) //set the request mode featureTable.featureRequestMode = AGSFeatureRequestMode.OnInteractionCache let featureLayer = AGSFeatureLayer(featureTable: featureTable) //add the feature layer to the map self.map.operationalLayers.addObject(featureLayer) self.mapView.map = self.map } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
2fb02f1a13b6d2d46329510e5a6222bc
37.689655
127
0.698307
4.617284
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/AutoremoMessagesController.swift
1
9562
// // AutoremoMessagesController.swift // Telegram // // Created by Mikhail Filimonov on 03.02.2021. // Copyright © 2021 Telegram. All rights reserved. // import Cocoa import TGUIKit import TelegramCore import Postbox import SwiftSignalKit private final class Arguments { let context: AccountContext let setTimeout:(Int32)->Void let clearHistory: ()->Void init(context: AccountContext, setTimeout:@escaping(Int32)->Void, clearHistory: @escaping()->Void) { self.context = context self.setTimeout = setTimeout self.clearHistory = clearHistory } } private struct State : Equatable { var autoremoveTimeout: CachedPeerAutoremoveTimeout? var timeout: Int32 let peer: PeerEquatable } private let _id_sticker = InputDataIdentifier("_id_sticker") private let _id_preview = InputDataIdentifier("_id_preview") private let _id_never = InputDataIdentifier("_id_never") private let _id_day = InputDataIdentifier("_id_day") private let _id_week = InputDataIdentifier("_id_week") private let _id_clear = InputDataIdentifier("_id_clear") private let _id_global = InputDataIdentifier("_id_global") private let _id_clear_both = InputDataIdentifier("_id_clear_both") private func entries(_ state: State, arguments: Arguments, onlyDelete: Bool) -> [InputDataEntry] { var entries:[InputDataEntry] = [] var sectionId:Int32 = 0 var index: Int32 = 0 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 if state.peer.peer.canClearHistory, !onlyDelete { entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_clear, data: .init(name: strings().chatContextClearHistory, color: theme.colors.redUI, icon: theme.icons.destruct_clear_history, type: .none, viewType: .singleItem, enabled: true, action: arguments.clearHistory))) index += 1 } else { entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_sticker, equatable: nil, comparable: nil, item: { initialSize, stableId in return AnimatedStickerHeaderItem(initialSize, stableId: stableId, context: arguments.context, sticker: LocalAnimatedSticker.destructor, text: .init()) })) index += 1 } if state.peer.peer.canManageDestructTimer && state.peer.peer.id != arguments.context.peerId { entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().autoremoveMessagesHeader), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem))) index += 1 entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_preview, equatable: InputDataEquatable(state), comparable: nil, item: { [weak arguments] initialSize, stableId in var values:[Int32] = [0, .secondsInDay, .secondsInWeek, .secondsInMonth] if !values.contains(state.timeout) { values.append(state.timeout) } values.sort(by: <) let titles: [String] = values.map { value in if value == 0 { return strings().autoremoveMessagesNever } else { return autoremoveLocalized(Int(value)) } } return SelectSizeRowItem(initialSize, stableId: stableId, current: state.timeout, sizes: values, hasMarkers: false, titles: titles, viewType: .singleItem, selectAction: { index in arguments?.setTimeout(values[index]) }) })) index += 1 if let _ = state.autoremoveTimeout?.timeout?.peerValue { entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().autoremoveMessagesDesc), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem))) index += 1 } else { entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().autoremoveMessagesDesc), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem))) index += 1 } } entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 return entries } func AutoremoveMessagesController(context: AccountContext, peer: Peer, onlyDelete: Bool = false) -> InputDataModalController { let peerId = peer.id let actionsDisposable = DisposableSet() let initialState = State(autoremoveTimeout: nil, timeout: 0, peer: PeerEquatable(peer)) var close:(()->Void)? = nil let statePromise = ValuePromise(initialState, ignoreRepeated: true) let stateValue = Atomic(value: initialState) let updateState: ((State) -> State) -> Void = { f in statePromise.set(stateValue.modify (f)) } let arguments = Arguments(context: context, setTimeout: { timeout in updateState { current in var current = current current.timeout = timeout return current } }, clearHistory: { var thridTitle: String? = nil var canRemoveGlobally: Bool = false if peerId.namespace == Namespaces.Peer.CloudUser && peerId != context.account.peerId && !peer.isBot { if context.limitConfiguration.maxMessageRevokeIntervalInPrivateChats == LimitsConfiguration.timeIntervalForever { canRemoveGlobally = true } } if canRemoveGlobally { thridTitle = strings().chatMessageDeleteForMeAndPerson(peer.displayTitle) } modernConfirm(for: context.window, account: context.account, peerId: peer.id, information: peer is TelegramUser ? peer.id == context.peerId ? strings().peerInfoConfirmClearHistorySavedMesssages : canRemoveGlobally || peerId.namespace == Namespaces.Peer.SecretChat ? strings().peerInfoConfirmClearHistoryUserBothSides : strings().peerInfoConfirmClearHistoryUser : strings().peerInfoConfirmClearHistoryGroup, okTitle: strings().peerInfoConfirmClear, thridTitle: thridTitle, thridAutoOn: false, successHandler: { result in _ = context.engine.messages.clearHistoryInteractively(peerId: peerId, threadId: nil, type: result == .thrid ? .forEveryone : .forLocalPeer).start() close?() }) }) let signal = statePromise.get() |> map { state in return InputDataSignalValue(entries: entries(state, arguments: arguments, onlyDelete: onlyDelete)) } let controller = InputDataController(dataSignal: signal, title: onlyDelete ? strings().autoremoveMessagesTitleDeleteOnly : strings().autoremoveMessagesTitle, hasDone: false) controller.onDeinit = { actionsDisposable.dispose() } actionsDisposable.add(context.account.viewTracker.peerView(peer.id).start(next: { peerView in let autoremoveTimeout: CachedPeerAutoremoveTimeout? if let cachedData = peerView.cachedData as? CachedGroupData { autoremoveTimeout = cachedData.autoremoveTimeout } else if let cachedData = peerView.cachedData as? CachedChannelData { autoremoveTimeout = cachedData.autoremoveTimeout } else if let cachedData = peerView.cachedData as? CachedUserData { autoremoveTimeout = cachedData.autoremoveTimeout } else { autoremoveTimeout = nil } updateState { current in var current = current current.autoremoveTimeout = autoremoveTimeout current.timeout = autoremoveTimeout?.timeout?.peerValue ?? 0 return current } })) controller.validateData = { _ in return .fail(.doSomething(next: { f in let state = stateValue.with { $0 } if let timeout = state.autoremoveTimeout?.timeout?.peerValue { if timeout == state.timeout { close?() return } } // var text: String? = nil // if state.timeout != 0 { // switch state.timeout { // case .secondsInDay: // text = strings().tipAutoDeleteTimerSetForDay // case .secondsInWeek: // text = strings().tipAutoDeleteTimerSetForWeek // default: // break // } // } else { // text = strings().tipAutoDeleteTimerSetOff // } _ = showModalProgress(signal: context.engine.peers.setChatMessageAutoremoveTimeoutInteractively(peerId: peerId, timeout: state.timeout == 0 ? nil : state.timeout), for: context.window).start(completed: { f(.success(.custom({ // if let text = text { // showModalText(for: context.window, text: text) // } close?() }))) }) })) } let modalInteractions = ModalInteractions(acceptTitle: strings().modalDone, accept: { [weak controller] in _ = controller?.returnKeyAction() }, drawBorder: true, height: 50, singleButton: true) let modalController = InputDataModalController(controller, modalInteractions: modalInteractions) controller.leftModalHeader = ModalHeaderData(image: theme.icons.modalClose, handler: { [weak modalController] in modalController?.close() }) close = { [weak modalController] in modalController?.modal?.close() } return modalController }
gpl-2.0
36c4144fc3a3196771a4e37915300230
39.341772
527
0.645121
4.673021
false
false
false
false
SwiftKitz/Storez
Sources/Storez/Stores/UserDefaults/UserDefaultsStore.swift
1
3101
// // UserDefaultsStore.swift // Storez // // Created by Mazyad Alabduljaleel on 11/5/15. // Copyright © 2015 kitz. All rights reserved. // import Foundation public final class UserDefaultsStore: Store { // MARK: - Properties public let defaults: UserDefaults // MARK: - Init & Dealloc public init(suite: String?) { defaults = UserDefaults(suiteName: suite)! } // MARK: - Private methods private func _read<K: KeyType, B: UserDefaultsTransaction>(_ key: K, boxType: B.Type) -> K.ValueType where K.ValueType == B.ValueType { let data = defaults.object(forKey: key.stringValue) as? Data return boxType.init(storedValue: data)?.value ?? key.defaultValue } private func _write<K: KeyType>(_ key: K, data: Data?) { K.NamespaceType.preCommitHook() defaults.set(data, forKey: key.stringValue) defaults.synchronize() K.NamespaceType.postCommitHook() } private func _set<K: KeyType, B: UserDefaultsTransaction>(_ key: K, box: B) where K.ValueType == B.ValueType { let oldValue = _read(key, boxType: B.self) let newValue = key.processChange(oldValue, newValue: box.value) let newBox = B(newValue) key.willChange(oldValue, newValue: newValue) _write(key, data: newBox.supportedType) key.didChange(oldValue, newValue: newValue) } // MARK: - Public methods public func clear() { defaults.dictionaryRepresentation() .forEach { defaults.removeObject(forKey: $0.0) } defaults.synchronize() } public func get<K: KeyType>(_ key: K) -> K.ValueType where K.ValueType: UserDefaultsConvertible { return _read(key, boxType: UserDefaultsConvertibleBox.self) } public func get<K: KeyType>(_ key: K) -> K.ValueType where K.ValueType: UserDefaultsSupportedType { return _read(key, boxType: UserDefaultsSupportedTypeBox.self) } public func get<K: KeyType, V: UserDefaultsSupportedType>(_ key: K) -> V? where K.ValueType == V? { return _read(key, boxType: UserDefaultsNullableSupportedTypeBox.self) } public func get<K: KeyType>(_ key: K) -> K.ValueType where K.ValueType: Codable { return _read(key, boxType: UserDefaultsCodableBox.self) } public func set<K: KeyType>(_ key: K, value: K.ValueType) where K.ValueType: UserDefaultsConvertible { _set(key, box: UserDefaultsConvertibleBox(value)) } public func set<K: KeyType>(_ key: K, value: K.ValueType) where K.ValueType: UserDefaultsSupportedType { _set(key, box: UserDefaultsSupportedTypeBox(value)) } public func set<K: KeyType, V: UserDefaultsSupportedType>(_ key: K, value: V?) where K.ValueType == V? { _set(key, box: UserDefaultsNullableSupportedTypeBox(value)) } public func set<K: KeyType>(_ key: K, value: K.ValueType) where K.ValueType: Codable { _set(key, box: UserDefaultsCodableBox(value)) } }
mit
ea0f9ff825c4f7b5d34a6ee30e2a73c9
30.958763
108
0.634194
4.138852
false
false
false
false
GuoMingJian/DouYuZB
DYZB/DYZB/Classes/Home/ViewModel/RecommendViewModel.swift
1
6455
// // RecommendViewModel.swift // DYZB // // Created by 郭明健 on 2017/10/27. // Copyright © 2017年 com.joy.www. All rights reserved. // import UIKit class RecommendViewModel { //MARK:- 懒加载属性 lazy var anchorGroups : [AnchorGroup] = [AnchorGroup]() lazy var cycleModels : [CycleModel] = [CycleModel]() private lazy var bigDataGroup : AnchorGroup = AnchorGroup() private lazy var prettyGroup : AnchorGroup = AnchorGroup() } //MARK:- 发送网络请求 extension RecommendViewModel { //请求推荐数据 func requestData(finishCallback : @escaping () -> ()) { //1.定义参数 let parameters = ["limit" : "4", "offset" : "0", "time" : NSDate.getCurrentTime()] //2.创建dispatchGroup let dGroup = DispatchGroup() //3.推荐数据 dGroup.enter() MJNetworkTools.requestData(type: .GET, urlString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time" : NSDate.getCurrentTime()], headers: nil) {(result) in //1.将result转成字典模型 guard let resultDict = result as? [String : NSObject] else {return} //2.根据data该key,获取数据 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return} //3.遍历字典,并且转成模型对象 //3.1 设置组的属性 self.bigDataGroup.tag_name = "热门" self.bigDataGroup.icon_name = "home_header_hot" //3.2 获取主播数据 for dict in dataArray { let anchor = AnchorModel(dict: dict) self.bigDataGroup.anchors.append(anchor) } //3.3 离开组 dGroup.leave() } //4.颜值数据 dGroup.enter() MJNetworkTools.requestData(type: .GET, urlString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: parameters, headers: nil) {(result) in //1.将result转成字典模型 guard let resultDict = result as? [String : NSObject] else {return} //2.根据data该key,获取数据 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return} //3.遍历字典,并且转成模型对象 //3.1 设置组的属性 self.prettyGroup.tag_name = "颜值" self.prettyGroup.icon_name = "home_header_phone" //3.2 获取主播数据 for dict in dataArray { let anchor = AnchorModel(dict: dict) self.prettyGroup.anchors.append(anchor) } //3.3 离开组 dGroup.leave() } //5.游戏数据 dGroup.enter() //http://capi.douyucdn.cn/api/v1/getHotCate?limit=4&offset=0&time=1509431328 MJNetworkTools.requestData(type: .GET, urlString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parameters, headers: nil) {(result) in //1.将result转成字典类型 guard let resultDict = result as? [String : NSObject] else {return} //2.根据data该key,获取数组 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return} //3.遍历数组,获取字典,并且将字典转成模型对象 for dict in dataArray { let group = AnchorGroup(dict: dict) self.anchorGroups.append(group) } //4 离开组 dGroup.leave() } //6.所有数据都请求到,之后进行排序 dGroup.notify(queue: DispatchQueue.main) { self.anchorGroups.insert(self.prettyGroup, at: 0) self.anchorGroups.insert(self.bigDataGroup, at: 0) finishCallback() } } //请求无限轮播数据 func requestCycleData(finishCallback : @escaping () -> ()) { MJNetworkTools.requestData(type: .GET, urlString: "http://www.douyutv.com/api/v1/slide/6", parameters: ["version" : "2.300"], headers: nil) { (result) in //1.获取整体字典数据 guard let resultDict = result as? [String : NSObject] else { return } //2.根据data的key获取数据 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return } //3.字典转模型 for dict in dataArray { self.cycleModels.append(CycleModel(dict : dict)) } finishCallback() } } }
mit
35af68ef47d57c0e5428be3e391b6ef6
42.085714
161
0.388926
6.09909
false
false
false
false