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
ciamic/Smashtag
Smashtag/TweetTableViewController.swift
1
15981
// // TweetTableViewController.swift // // Copyright (c) 2017 michelangelo // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Twitter ///Displays the results of tweet searches in a table and store into the database newly fetched tweets class TweetTableViewController: UITableViewController { // MARK: - Model //an array of array of tweets var tweets = [Array<Twitter.Tweet>]() //the search term var searchText: String? { didSet { searchBar?.text = searchText searchBar?.resignFirstResponder() lastTwitterRequest = nil tweets.removeAll() tableView.reloadData() searchForTweets() title = searchText } } // MARK: - Outlets @IBOutlet weak var searchBar: UISearchBar! { didSet { searchBar.delegate = self searchBar.text = searchText } } // results view and labels @IBOutlet var resultsView: UIView! @IBOutlet weak var resultsNoSearchLabel: UILabel! @IBOutlet weak var resultsNoResultsLabel: UILabel! @IBOutlet weak var resultsErrorOccurredLabel: UILabel! // MARK: - Private Properties fileprivate var twitterRequest: Twitter.Request? { if var query = searchText, !query.isEmpty { //not nil and not empty if query.hasPrefix(TwitterConstants.UserPrefix) { //search for tweets that mentions the user or are posted by the user query = "\(query) \(TwitterConstants.OrFromSearchKeyword) \(query)" } else { //search for the hashtag but no retweets query = query + TwitterConstants.NoRetweetsFilter } return Twitter.Request(search: query, count: TwitterConstants.NoOfTweetsPerRequest) } return nil } fileprivate weak var showImagesBarButtonItem: UIBarButtonItem? fileprivate weak var showTweetersBarButtonItem: UIBarButtonItem? fileprivate let loadingSpinner = UIActivityIndicatorView() // MARK: - Properties //keeps track of the last request in order to avoid to make some requests that take //very long time to complete and show up after a while when the user searched for something else fileprivate var lastTwitterRequest: Twitter.Request? // MARK: - Controller Life Cycle override func viewDidLoad() { super.viewDidLoad() setupTableView() setupRightBarButtonItems() setupLoadingSpinner() updateVisibilityForBarButtonItems() if isFirstNavigationController() { //removes unwind button for the first nav controller navigationItem.rightBarButtonItems?.removeFirst() } } private func setupLoadingSpinner() { loadingSpinner.activityIndicatorViewStyle = .whiteLarge loadingSpinner.color = UIColor.darkGray loadingSpinner.hidesWhenStopped = true } private func setupTableView() { tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = UITableViewAutomaticDimension tableView.separatorStyle = .none if tweets.isEmpty && (searchText == nil || searchText != nil && searchText!.isEmpty) { // no tweets and no search text updateTableViewResultsView(with: .EmptySearch) } tableView.isScrollEnabled = false tableView.delegate = self tableView.dataSource = self } //gets and stores references to ShowImages and ShowTweeters bar button items fileprivate func setupRightBarButtonItems() { if let rightBarButtonItems = navigationItem.rightBarButtonItems { for button in rightBarButtonItems { switch button.tag { case Storyboard.ShowImagesBarButtonTag: showImagesBarButtonItem = button case Storyboard.ShowTweetersBarButtonTag: showTweetersBarButtonItem = button default: break } } } } fileprivate func isFirstNavigationController() -> Bool { return self == navigationController?.viewControllers.first } // MARK: - Actions @IBAction func refreshControlValueChanged(_ sender: UIRefreshControl) { searchForTweets() } @IBAction func unwindToRoot(_ sender: UIStoryboardSegue) { //unwind destination } @IBAction func tweetMediaItemsButtonTapped(_ sender: UIBarButtonItem) { performSegue(withIdentifier: Storyboard.ShowTweetsCollectionView, sender: sender) } // MARK: - Navigation override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { if identifier == Storyboard.ShowMentionsSegue { if let tweetCell = sender as? TweetTableViewCell { if let tweet = tweetCell.tweet { if !tweetHasMentions(tweet) { return false } } } } return true } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let identifier = segue.identifier { switch identifier { case Storyboard.ShowMentionsSegue: if let tmtvc = segue.destination as? TweetMentionsTableViewController { if let tweetCell = sender as? TweetTableViewCell { tmtvc.tweet = tweetCell.tweet } } case Storyboard.ShowTweetsCollectionView: if let tcvc = segue.destination as? TweetCollectionViewController { tcvc.tweets = tweets } default: break } } } override func canPerformUnwindSegueAction(_ action: Selector, from fromViewController: UIViewController, withSender sender: Any) -> Bool { //skip all the controllers and stops at the root one if isFirstNavigationController() { return true } return false } // MARK: - Utils func insertTweets(_ newTweets: [Twitter.Tweet]) { tweets.insert(newTweets, at: 0) tableView.insertSections([0], with: .fade) } /// called before searching for tweets in order to fire up activity indicators private func startRefreshing() { tableView.separatorStyle = .none tableView.backgroundView = loadingSpinner loadingSpinner.startAnimating() // NOTE: no need to call refreshControl.beginRefreshing // but need to stop it when the refreshing ends. } /// called after seaching for tweets in order to stop activity indicators private func endRefreshing() { loadingSpinner.stopAnimating() refreshControl?.endRefreshing() } // Reasons for updating the table view fileprivate enum TableViewUpdateReason { case EmptySearch case SearchWithError case SuccessfulSearch } private func updateTableViewResultsView(with reason: TableViewUpdateReason) { resultsNoSearchLabel.isHidden = true resultsNoResultsLabel.isHidden = true resultsErrorOccurredLabel.isHidden = true tableView.backgroundView = resultsView tableView.isScrollEnabled = false tableView.separatorStyle = .none switch reason { case .EmptySearch: resultsNoSearchLabel.isHidden = false case .SearchWithError: resultsErrorOccurredLabel.isHidden = false case .SuccessfulSearch: if tweets.isEmpty { resultsNoResultsLabel.isHidden = false } else { tableView.separatorStyle = .singleLine tableView.isScrollEnabled = true tableView.backgroundView = nil } } } private func requestForTweets() -> Request? { if searchText != nil && !TweetHistory().contains(searchTerm: searchText!) { return twitterRequest } else { return lastTwitterRequest?.newer ?? twitterRequest } } fileprivate func handleSearchError(_ error: Error) { var message: String var alertActionOk: UIAlertAction! var alertActionCancel: UIAlertAction? switch error { case TwitterAccountError.noAccountsAvailable, TwitterAccountError.noPermissionGranted: message = AlertControllerMessages.NoAccountsAvailableOrNoPermissionGranted alertActionOk = UIAlertAction(title: AlertControllerMessages.Settings, style: .default) { alertAction in UIApplication.shared.open(URL(string: AlertControllerMessages.UrlToTwitterSettings)!) } alertActionCancel = UIAlertAction(title: AlertControllerMessages.Cancel, style: .cancel, handler: nil) case TwitterAccountError.noResponseFromTwitter: message = AlertControllerMessages.InternetConnectionOrTwitterNotAvailable alertActionOk = UIAlertAction(title: AlertControllerMessages.Ok, style: .default, handler: nil) default: message = AlertControllerMessages.GenericErrorOccurred alertActionOk = UIAlertAction(title: AlertControllerMessages.Ok, style: .default, handler: nil) } let alertController = UIAlertController(title: AlertControllerMessages.Error, message: message, preferredStyle: .alert) alertController.addAction(alertActionOk) if let alertActionCancel = alertActionCancel { alertController.addAction(alertActionCancel) } updateTableViewResultsView(with: .SearchWithError) present(alertController, animated: true, completion: nil) } //note that this function resolves two of the most common problems with asynchronous requests: //1) memory cycle: we use weak self in order to not have a strong reference to self that keeps it in the heap. //When this can happen? For example if the network request goes off to the internet and the closure never gets //executed for some reason (i.e. failure), and the user moves on onto a new controller and this needs to leave the //heap. This will not happen if there is a strong pointer to the controller! Weak self resolves this memory cycle. //2) the "world" can be changed when the callback closure comes back so we have to make sure that the content //is still "fresh". In this case, that the last request is still the request that caused this closure to get //called. See also the lastTwitterRequest property. fileprivate func searchForTweets() { if let request = requestForTweets() { lastTwitterRequest = request startRefreshing() request.fetchTweets { [weak self] newTweets, error in DispatchQueue.main.async { if let error = error { self?.handleSearchError(error) } else { // check that when the asynchronous call is made, the search is still relevant if request == self?.lastTwitterRequest { if let searchText = self?.searchText, searchText.characters.count > 0 { TweetHistory().add(searchText) } if !newTweets.isEmpty { self?.insertTweets(newTweets) } self?.updateTableViewResultsView(with: .SuccessfulSearch) } } self?.endRefreshing() self?.updateVisibilityForBarButtonItems() } } } else { endRefreshing() updateTableViewResultsView(with: .SearchWithError) } } ///Returns true iff the tweet has at least one mention item fileprivate func tweetHasMentions(_ tweet: Twitter.Tweet) -> Bool { return tweet.hashtags.count + tweet.urls.count + tweet.userMentions.count + tweet.media.count > 0 } ///Returns true iff the tweet has at least one media item fileprivate func tweetHasMedias(_ tweet: Twitter.Tweet) -> Bool { return tweet.media.count > 0 } fileprivate func updateVisibilityForBarButtonItems() { showImagesBarButtonItem?.isEnabled = false showTweetersBarButtonItem?.isEnabled = false if tweets.count > 0 { showTweetersBarButtonItem?.isEnabled = true tweets.forEach { $0.forEach { if tweetHasMedias($0) { showImagesBarButtonItem?.isEnabled = true return } } } } } } extension TweetTableViewController { // MARK: - UITableViewDataSource and UITableViewDelegate override func numberOfSections(in tableView: UITableView) -> Int { return tweets.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tweets[section].count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.TweetCellIdentifier, for: indexPath) let tweet = tweets[indexPath.section][indexPath.row] if let tweetCell = cell as? TweetTableViewCell { tweetCell.tweet = tweet cell.accessoryType = tweetHasMentions(tweet) ? .disclosureIndicator : .none } return cell } override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { return tweetHasMentions(tweets[indexPath.section][indexPath.row]) } } extension TweetTableViewController: UISearchBarDelegate { // MARK: - UISearchBarDelegate func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { searchBar.showsCancelButton = true } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.text = searchText searchBar.showsCancelButton = false searchBar.resignFirstResponder() } func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool { searchBar.resignFirstResponder() return true } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchText = searchBar.text searchBar.showsCancelButton = false } }
mit
28e65c6c0840802ef57fa51cc9885806
38.07335
142
0.632063
5.675071
false
false
false
false
imeraj/TestApp-Vapor1.0
Sources/App/Models/Sighting.swift
1
1280
import Vapor import HTTP import Node import Foundation final class Sighting: Model { var id: Node? var bird: String var time: Int var exists: Bool = false init(bird: String, time: Double) { self.bird = bird self.time = Int(time) } convenience init(bird: String) { self.init(bird: bird, time: NSDate().timeIntervalSince1970.doubleValue) } init(node: Node, in context: Context) throws { id = try node.extract("id") bird = try node.extract("bird") time = try node.extract("time") } func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, "bird": bird, "time": time, "date": DateFormatter.localizedString(from: NSDate(timeIntervalSince1970:TimeInterval(time)) as Date, dateStyle: .short, timeStyle: .short) ]) } static func prepare(_ database: Database) throws { try database.create("Sightings") { sightings in sightings.id() sightings.string("bird", optional: false) sightings.int("time") } } static func revert(_ database: Database) throws { try database.delete("Sightings") } }
mit
910fe420f9d025ac001e8cbc8826596e
25.666667
151
0.574219
4.266667
false
false
false
false
developerkitchen/Swift3Projects
SwiftInternetController/Pods/SwiftMessages/SwiftMessages/TopBottomAnimation.swift
1
6595
// // TopBottomAnimation.swift // SwiftMessages // // Created by Timothy Moose on 6/4/17. // Copyright © 2017 SwiftKick Mobile. All rights reserved. // import UIKit public class TopBottomAnimation: NSObject, Animator { enum Style { case top case bottom } public weak var delegate: AnimationDelegate? var style: Style var translationConstraint: NSLayoutConstraint! = nil weak var messageView: UIView? weak var containerView: UIView? init(style: Style, delegate: AnimationDelegate) { self.style = style self.delegate = delegate } public func show(context: AnimationContext, completion: @escaping AnimationCompletion) { install(context: context) showAnimation(completion: completion) } public func hide(context: AnimationContext, completion: @escaping AnimationCompletion) { let view = context.messageView let container = context.containerView UIView.animate(withDuration: 0.2, delay: 0, options: [.beginFromCurrentState, .curveEaseIn], animations: { let size = view.systemLayoutSizeFitting(UILayoutFittingCompressedSize) self.translationConstraint.constant -= size.height container.layoutIfNeeded() }, completion: { completed in completion(completed) }) } func install(context: AnimationContext) { let view = context.messageView let container = context.containerView messageView = view containerView = container if let adjustable = context.messageView as? MarginAdjustable { bounceOffset = adjustable.bounceAnimationOffset } view.translatesAutoresizingMaskIntoConstraints = false container.addSubview(view) let leading = NSLayoutConstraint(item: view, attribute: .leading, relatedBy: .equal, toItem: container, attribute: .leading, multiplier: 1.00, constant: 0.0) let trailing = NSLayoutConstraint(item: view, attribute: .trailing, relatedBy: .equal, toItem: container, attribute: .trailing, multiplier: 1.00, constant: 0.0) switch style { case .top: translationConstraint = NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: container, attribute: .top, multiplier: 1.00, constant: 0.0) case .bottom: translationConstraint = NSLayoutConstraint(item: container, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.00, constant: 0.0) } container.addConstraints([leading, trailing, translationConstraint]) if let adjustable = view as? MarginAdjustable { var top: CGFloat = 0.0 var bottom: CGFloat = 0.0 switch style { case .top: top += adjustable.bounceAnimationOffset if context.behindStatusBar { top += adjustable.statusBarOffset } case .bottom: bottom += adjustable.bounceAnimationOffset } view.layoutMargins = UIEdgeInsets(top: top, left: 0.0, bottom: bottom, right: 0.0) } let size = view.systemLayoutSizeFitting(UILayoutFittingCompressedSize) translationConstraint.constant -= size.height container.layoutIfNeeded() if context.interactiveHide { let pan = UIPanGestureRecognizer() pan.addTarget(self, action: #selector(pan(_:))) if let view = view as? BackgroundViewable { view.backgroundView.addGestureRecognizer(pan) } else { view.addGestureRecognizer(pan) } } } func showAnimation(completion: @escaping AnimationCompletion) { guard let container = containerView else { completion(false) return } let animationDistance = self.translationConstraint.constant + bounceOffset // Cap the initial velocity at zero because the bounceOffset may not be great // enough to allow for greater bounce induced by a quick panning motion. let initialSpringVelocity = animationDistance == 0.0 ? 0.0 : min(0.0, closeSpeed / animationDistance) UIView.animate(withDuration: 0.4, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: initialSpringVelocity, options: [.beginFromCurrentState, .curveLinear, .allowUserInteraction], animations: { self.translationConstraint.constant = -self.bounceOffset container.layoutIfNeeded() }, completion: { completed in completion(completed) }) } fileprivate var bounceOffset: CGFloat = 5 /* MARK: - Pan to close */ fileprivate var closing = false fileprivate var closeSpeed: CGFloat = 0.0 fileprivate var closePercent: CGFloat = 0.0 fileprivate var panTranslationY: CGFloat = 0.0 @objc func pan(_ pan: UIPanGestureRecognizer) { switch pan.state { case .changed: guard let view = pan.view else { return } let height = view.bounds.height - bounceOffset if height <= 0 { return } let point = pan.location(ofTouch: 0, in: view) var velocity = pan.velocity(in: view) var translation = pan.translation(in: view) if case .top = style { velocity.y *= -1.0 translation.y *= -1.0 } if !closing { if view.bounds.contains(point) && velocity.y > 0.0 && velocity.x / velocity.y < 5.0 { closing = true pan.setTranslation(CGPoint.zero, in: view) delegate?.panStarted(animator: self) } } if !closing { return } let translationAmount = -bounceOffset - max(0.0, translation.y) translationConstraint.constant = translationAmount closeSpeed = velocity.y closePercent = translation.y / height panTranslationY = translation.y case .ended, .cancelled: if closeSpeed > 750.0 || closePercent > 0.33 { delegate?.hide(animator: self) } else { closing = false closeSpeed = 0.0 closePercent = 0.0 panTranslationY = 0.0 showAnimation(completion: { (completed) in self.delegate?.panEnded(animator: self) }) } default: break } } }
gpl-3.0
d5f20430d43163233d0877385c124cdd
38.48503
214
0.61192
5.08404
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Views/Cells/LineItemTableViewCell/Pasteboard/PasteboardingLineItemCellPresenter.swift
1
5299
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import DIKit import PlatformKit import RxCocoa import RxRelay import RxSwift import ToolKit public final class PasteboardingLineItemCellPresenter: LineItemCellPresenting { // MARK: - Input public struct Input { let title: String let titleInteractionText: String let description: String let descriptionInteractionText: String let interactionDuration: Int let analyticsEvent: AnalyticsEvent? public init( title: String, titleInteractionText: String, description: String, descriptionInteractionText: String, analyticsEvent: AnalyticsEvent? = nil, interactionDuration: Int = 4 ) { self.title = title self.titleInteractionText = titleInteractionText self.description = description self.descriptionInteractionText = descriptionInteractionText self.interactionDuration = interactionDuration self.analyticsEvent = analyticsEvent } } // MARK: - Properties public let titleLabelContentPresenter: LabelContentPresenting public let descriptionLabelContentPresenter: LabelContentPresenting /// The background color relay let backgroundColorRelay = BehaviorRelay<UIColor>(value: .clear) /// The background color of the button public var backgroundColor: Driver<UIColor> { backgroundColorRelay.asDriver() } public var image: Driver<UIImage?> { imageRelay.asDriver() } /// This is fixed at 22px for pasteboard line items public let imageWidth: Driver<CGFloat> /// The background color relay let imageRelay = BehaviorRelay<UIImage?>(value: #imageLiteral(resourceName: "clipboard")) // MARK: - PasteboardLineItemPresenting /// Streams events when the component is being tapped public let tapRelay = PublishRelay<Void>() // MARK: - Private Properties private let disposeBag = DisposeBag() private let analyticsRecorder: AnalyticsEventRecorderAPI public var interactor: LineItemCellInteracting // MARK: - Init public init( input: Input, pasteboard: Pasteboarding = resolve(), analyticsRecorder: AnalyticsEventRecorderAPI, accessibilityIdPrefix: String ) { self.analyticsRecorder = analyticsRecorder let titleInteractor = PasteboardLabelContentInteractor( text: input.title, interactionText: input.titleInteractionText, interactionDuration: input.interactionDuration ) let descriptionInteractor = PasteboardLabelContentInteractor( text: input.description, interactionText: input.descriptionInteractionText, interactionDuration: input.interactionDuration ) imageWidth = Driver.just(22) interactor = DefaultLineItemCellInteractor(title: titleInteractor, description: descriptionInteractor) titleLabelContentPresenter = PasteboardLabelContentPresenter( interactor: titleInteractor, descriptors: .lineItemTitle(accessibilityIdPrefix: accessibilityIdPrefix) ) descriptionLabelContentPresenter = PasteboardLabelContentPresenter( interactor: descriptionInteractor, descriptors: .lineItemDescription(accessibilityIdPrefix: accessibilityIdPrefix) ) tapRelay .bindAndCatch(to: titleInteractor.pasteboardTriggerRelay) .disposed(by: disposeBag) tapRelay .bindAndCatch(to: descriptionInteractor.pasteboardTriggerRelay) .disposed(by: disposeBag) tapRelay .bind { let feedbackGenerator = UIImpactFeedbackGenerator(style: .light) feedbackGenerator.prepare() feedbackGenerator.impactOccurred() } .disposed(by: disposeBag) tapRelay .map { "green-checkmark-bottom-sheet" } .map { UIImage(named: $0) } .bindAndCatch(to: imageRelay) .disposed(by: disposeBag) tapRelay .map { .affirmativeBackground } .bindAndCatch(to: backgroundColorRelay) .disposed(by: disposeBag) tapRelay .withLatestFrom(descriptionInteractor.originalValueState) .bind { state in pasteboard.string = state.value?.text ?? input.description } .disposed(by: disposeBag) tapRelay .compactMap { input.analyticsEvent } .subscribe(onNext: analyticsRecorder.record(event:)) .disposed(by: disposeBag) let delay = tapRelay .debounce( .seconds(input.interactionDuration), scheduler: ConcurrentDispatchQueueScheduler(qos: .userInitiated) ) .share(replay: 1) delay .map { "clipboard" } .map { UIImage(named: $0) } .bindAndCatch(to: imageRelay) .disposed(by: disposeBag) delay .map { .clear } .bindAndCatch(to: backgroundColorRelay) .disposed(by: disposeBag) } }
lgpl-3.0
a411b4a3ac24aacfe8bb4923c197aa40
31.109091
110
0.646659
5.721382
false
false
false
false
lovecrafts/Veneer
Veneer/Classes/VeneerDimmingView.swift
1
2669
// // VeneerDimmingView.swift // Pods // // Created by Sam Watts on 30/01/2017. // // import UIKit public class VeneerDimmingView: UIView { @available(*, unavailable, message: "init(frame:) is unavailable, use init() instead") override init(frame: CGRect) { fatalError() } @available(*, unavailable, message: "init?(coder:) is unavailable, use init() instead") public required init?(coder aDecoder: NSCoder) { fatalError() } private let maskLayer: CAShapeLayer = { let mask = CAShapeLayer() mask.fillRule = kCAFillRuleEvenOdd return mask }() var inverseMaskViews: [UIView] = [] { didSet { self.setNeedsLayout() } } var maskInsets: UIEdgeInsets = .zero { didSet { self.setNeedsLayout() } } var maskCornerRadius: CGFloat = 0 { didSet { self.setNeedsLayout() } } required public init(inverseMaskViews: [UIView], maskInsets: UIEdgeInsets = .zero, maskCornerRadius: CGFloat = 0) { super.init(frame: .zero) if maskCornerRadius != 0 && inverseMaskViews.count > 1 { preconditionFailure("Corner radius is not supported on view union masking") } //check if we have an appearance value configured before setting default background if let appearanceBackgroundColor = VeneerDimmingView.appearance().backgroundColor { self.backgroundColor = appearanceBackgroundColor } else { self.backgroundColor = UIColor.black.withAlphaComponent(0.3) } self.inverseMaskViews = inverseMaskViews self.maskInsets = maskInsets self.maskCornerRadius = maskCornerRadius self.layer.mask = maskLayer } override public func layoutSubviews() { super.layoutSubviews() maskLayer.path = maskPath } private var maskPath: CGPath { let path = UIBezierPath() path.append(UIBezierPath(rect: self.bounds)) //calculate enclosing path for inverse mask views if inverseMaskViews.isEmpty == false { let frames = inverseMaskViews.map { $0.frame } let inverseMaskPath: UIBezierPath if frames.count > 1 { inverseMaskPath = UIBezierPath(outliningViewFrames: frames) } else { inverseMaskPath = UIBezierPath(roundedRect: frames.first ?? .zero, cornerRadius: maskCornerRadius) } path.append(inverseMaskPath) } return path.cgPath } }
mit
6713b8a7e1ea067907253e6344b89b03
28.988764
119
0.598351
5.054924
false
false
false
false
huonw/swift
test/SILGen/synthesized_conformance_enum.swift
1
4502
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-silgen %s -swift-version 4 | %FileCheck %s enum Enum<T> { case a(T), b(T) } // CHECK-LABEL: enum Enum<T> { // CHECK: case a(T), b(T) // CHECK: } enum NoValues { case a, b } // CHECK-LABEL: enum NoValues { // CHECK: case a, b // CHECK: @_implements(Equatable, ==(_:_:)) static func __derived_enum_equals(_ a: NoValues, _ b: NoValues) -> Bool // CHECK: var hashValue: Int { get } // CHECK: func hash(into hasher: inout Hasher) // CHECK: } // CHECK-LABEL: extension Enum : Equatable where T : Equatable { // CHECK: @_implements(Equatable, ==(_:_:)) static func __derived_enum_equals(_ a: Enum<T>, _ b: Enum<T>) -> Bool // CHECK: } // CHECK-LABEL: extension Enum : Hashable where T : Hashable { // CHECK: var hashValue: Int { get } // CHECK: func hash(into hasher: inout Hasher) // CHECK: } // CHECK-LABEL: extension NoValues : CaseIterable { // CHECK: typealias AllCases = [NoValues] // CHECK: static var allCases: [NoValues] { get } // CHECK: } extension Enum: Equatable where T: Equatable {} // CHECK-LABEL: // static Enum<A>.__derived_enum_equals(_:_:) // CHECK-NEXT: sil hidden @$S28synthesized_conformance_enum4EnumOAAs9EquatableRzlE010__derived_C7_equalsySbACyxG_AFtFZ : $@convention(method) <T where T : Equatable> (@in_guaranteed Enum<T>, @in_guaranteed Enum<T>, @thin Enum<T>.Type) -> Bool { extension Enum: Hashable where T: Hashable {} // CHECK-LABEL: // Enum<A>.hashValue.getter // CHECK-NEXT: sil hidden @$S28synthesized_conformance_enum4EnumOAAs8HashableRzlE9hashValueSivg : $@convention(method) <T where T : Hashable> (@in_guaranteed Enum<T>) -> Int { // CHECK-LABEL: // Enum<A>.hash(into:) // CHECK-NEXT: sil hidden @$S28synthesized_conformance_enum4EnumOAAs8HashableRzlE4hash4intoys6HasherVz_tF : $@convention(method) <T where T : Hashable> (@inout Hasher, @in_guaranteed Enum<T>) -> () { extension NoValues: CaseIterable {} // CHECK-LABEL: // static NoValues.allCases.getter // CHECK-NEXT: sil hidden @$S28synthesized_conformance_enum8NoValuesO8allCasesSayACGvgZ : $@convention(method) (@thin NoValues.Type) -> @owned Array<NoValues> { // Witness tables for Enum // CHECK-LABEL: sil_witness_table hidden <T where T : Equatable> Enum<T>: Equatable module synthesized_conformance_enum { // CHECK-NEXT: method #Equatable."=="!1: <Self where Self : Equatable> (Self.Type) -> (Self, Self) -> Bool : @$S28synthesized_conformance_enum4EnumOyxGs9EquatableAAsAERzlsAEP2eeoiySbx_xtFZTW // protocol witness for static Equatable.== infix(_:_:) in conformance <A> Enum<A> // CHECK-NEXT: conditional_conformance (T: Equatable): dependent // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden <T where T : Hashable> Enum<T>: Hashable module synthesized_conformance_enum { // CHECK-NEXT: base_protocol Equatable: <T where T : Equatable> Enum<T>: Equatable module synthesized_conformance_enum // CHECK-NEXT: method #Hashable.hashValue!getter.1: <Self where Self : Hashable> (Self) -> () -> Int : @$S28synthesized_conformance_enum4EnumOyxGs8HashableAAsAERzlsAEP9hashValueSivgTW // protocol witness for Hashable.hashValue.getter in conformance <A> Enum<A> // CHECK-NEXT: method #Hashable.hash!1: <Self where Self : Hashable> (Self) -> (inout Hasher) -> () : @$S28synthesized_conformance_enum4EnumOyxGs8HashableAAsAERzlsAEP4hash4intoys6HasherVz_tFTW // protocol witness for Hashable.hash(into:) in conformance <A> Enum<A> // CHECK-NEXT: method #Hashable._rawHashValue!1: <Self where Self : Hashable> (Self) -> ((UInt64, UInt64)) -> Int : @$S28synthesized_conformance_enum4EnumOyxGs8HashableAAsAERzlsAEP13_rawHashValue4seedSis6UInt64V_AJt_tFTW // protocol witness for Hashable._rawHashValue(seed:) in conformance <A> Enum<A> // CHECK-NEXT: conditional_conformance (T: Hashable): dependent // CHECK-NEXT: } // Witness tables for NoValues // CHECK-LABEL: sil_witness_table hidden NoValues: CaseIterable module synthesized_conformance_enum { // CHECK-NEXT: associated_type AllCases: Array<NoValues> // CHECK-NEXT: associated_type_protocol (AllCases: Collection): [NoValues]: specialize <NoValues> (<Element> Array<Element>: Collection module Swift) // CHECK-NEXT: method #CaseIterable.allCases!getter.1: <Self where Self : CaseIterable> (Self.Type) -> () -> Self.AllCases : @$S28synthesized_conformance_enum8NoValuesOs12CaseIterableAAsADP8allCases03AllI0QzvgZTW // protocol witness for static CaseIterable.allCases.getter in conformance NoValues // CHECK-NEXT: }
apache-2.0
61c44490224b93843ddd3a442f7048fc
60.671233
303
0.723456
3.415781
false
false
false
false
PekanMmd/Pokemon-XD-Code
Objects/scripts/Colosseum/CMScriptOps.swift
1
7460
// // CMScriptOps.swift // GoD Tool // // Created by Stars Momodu on 06/10/2020. // import Foundation enum CMScriptOps: CustomStringConvertible { case nop case exit // Possibly only used to mark the last instruction of the entire script case pushMinus1 // Seems to push -1 onto the stack case pop(unused: CMScriptVar, count: UInt16) case call(functionID: UInt32, returnCount: UInt16, argCount: UInt16) case return_op case jump(offset: UInt32) case jumpFalse(offset: UInt32) case pushImmediate(type: CMScriptValueTypes, value: UInt32) // pushes a literal value case and(var1: CMScriptVar, var2: CMScriptVar) // arithmetic and case or(var1: CMScriptVar, var2: CMScriptVar) // arithmetic or case pushVar(var1: CMScriptVar) case pushMultiVar(var1: CMScriptVar, count: UInt16) // pushes a var multiple times. Seems to be used instead of pushVar even if count is 1 case not(var1: CMScriptVar) case negate(var1: CMScriptVar) case pushVar2(var1: CMScriptVar) // Doesn't seem to perform any operation on the variable case multiply(var1: CMScriptVar, var2: CMScriptVar) case divide(var1: CMScriptVar, var2: CMScriptVar) case mod(var1: CMScriptVar, var2: CMScriptVar) case add(var1: CMScriptVar, var2: CMScriptVar) case subtract(var1: CMScriptVar, var2: CMScriptVar) case lessThan(var1: CMScriptVar, var2: CMScriptVar) case lessThanEqual(var1: CMScriptVar, var2: CMScriptVar) // educated guess but not sure case greaterThan(var1: CMScriptVar, var2: CMScriptVar) case greaterThanEqual(var1: CMScriptVar, var2: CMScriptVar) // educated guess but not sure case equal(var1: CMScriptVar, var2: CMScriptVar) case notEqual(var1: CMScriptVar, var2: CMScriptVar) case setVar(source: CMScriptVar, target: CMScriptVar) case copyStruct(source: CMScriptVar, destination: CMScriptVar, length: UInt16) case andl(var1: CMScriptVar, var2: CMScriptVar) // logical and case orl(var1: CMScriptVar, var2: CMScriptVar) // logical or case printf(unused: UInt16, argCount: UInt16) // number of interpolated arguments to read from stack, followed by string pointer. Last arg at top of stack case yield(unused: UInt16, argCount: UInt16) case callStandard(returnCount: UInt16, argCount: UInt16) case invalid(id: Int) var opCode: Int { switch self { case .nop: return 0 case .exit: return 1 case .pushMinus1: return 2 case .pop: return 3 case .call: return 4 case .return_op: return 5 case .jump: return 6 case .jumpFalse: return 7 case .pushImmediate: return 8 // 9-12 are invalid case .and: return 13 case .or: return 14 case .pushVar: return 15 case .pushMultiVar: return 16 case .not: return 17 case .negate: return 18 case .pushVar2: return 19 case .multiply: return 20 case .divide: return 21 case .mod: return 22 case .add: return 23 case .subtract: return 24 case .lessThan: return 25 case .lessThanEqual: return 26 case .greaterThan: return 27 case .greaterThanEqual: return 28 case .equal: return 29 case .notEqual: return 30 case .setVar: return 31 case .copyStruct: return 32 case .andl: return 33 case .orl: return 34 case .printf: return 35 case .yield: return 36 case .callStandard: return 37 case .invalid(let id): return id } } var length: Int { switch self { case .nop: return 1 case .exit: return 1 case .pushMinus1: return 1 case .pop: return 4 case .call: return 9 case .return_op: return 1 case .jump: return 5 case .jumpFalse: return 5 case .pushImmediate: return 6 case .and: return 3 case .or: return 3 case .pushVar: return 2 case .pushMultiVar: return 4 case .not: return 2 case .negate: return 2 case .pushVar2: return 2 case .multiply: return 3 case .divide: return 3 case .mod: return 3 case .add: return 3 case .subtract: return 3 case .lessThan: return 3 case .lessThanEqual: return 3 case .greaterThan: return 3 case .greaterThanEqual: return 3 case .equal: return 3 case .notEqual: return 3 case .setVar: return 3 case .copyStruct: return 5 case .andl: return 3 case .orl: return 3 case .printf: return 5 case .yield: return 5 case .callStandard: return 5 case .invalid: return 1 } } var description: String { switch self { case .nop: return "Nop" case .exit: return "Exit" case .pushMinus1: return "PushMinus1" case .pop(_, count: let count): return "Pop \(count)" case .call(functionID: let functionID, returnCount: let returnCount, argCount: let argCount): return "CallFromScript function\(functionID)(argc:\(argCount)) -> returns:\(returnCount)" case .return_op: return "Return" case .jump(offset: let offset): return "Jump @\(offset.hex())" case .jumpFalse(offset: let offset): return "JumpFalse @\(offset.hex())" case .pushImmediate(type: let type, value: let value): let valueString: String switch type { case .integer: valueString = value.int32 > 0xFF ? value.int32.hexString() : value.int32.string case .float: valueString = value.hexToSignedFloat().string default: valueString = value.hexString() + " (type: \(type))" } return "Push \(valueString)" case .and(var1: let var1, var2: let var2): return "\(var1) & \(var2)" case .or(var1: let var1, var2: let var2): return "\(var1) | \(var2)" case .pushVar(var1: let var1): return "PushVar \(var1)" case .pushMultiVar(var1: let var1, count: let count): return "PushMultiVar \(var1) x\(count)" case .not(var1: let var1): return "!\(var1)" case .negate(var1: let var1): return "-\(var1)" case .pushVar2(var1: let var1): return "PushVar2 \(var1)" case .multiply(var1: let var1, var2: let var2): return "\(var1) * \(var2)" case .divide(var1: let var1, var2: let var2): return "\(var1) / \(var2)" case .mod(var1: let var1, var2: let var2): return "\(var1) % \(var2)" case .add(var1: let var1, var2: let var2): return "\(var1) + \(var2)" case .subtract(var1: let var1, var2: let var2): return "\(var1) - \(var2)" case .lessThan(var1: let var1, var2: let var2): return "\(var1) > \(var2)" case .lessThanEqual(var1: let var1, var2: let var2): return "\(var1) >= \(var2)" case .greaterThan(var1: let var1, var2: let var2): return "\(var1) < \(var2)" case .greaterThanEqual(var1: let var1, var2: let var2): return "\(var1) <= \(var2)" case .equal(var1: let var1, var2: let var2): return "\(var1) == \(var2)" case .notEqual(var1: let var1, var2: let var2): return "\(var1) != \(var2)" case .setVar(source: let source, target: let target): return "SetVar \(target) to value of: \(source)" case .copyStruct(source: let source, destination: let destination, let length): return "Copy \(length) bytes from \(source) to \(destination)" case .andl(var1: let var1, var2: let var2): return "\(var1) && \(var2)" case .orl(var1: let var1, var2: let var2): return "\(var1) || \(var2)" case .printf(_, argCount: let unknown): return "Print_f argc:\(unknown)" case .yield(_, argCount: let count): return "Yield frames: x\(count)" case .callStandard(_, argCount: let argCount): return "CallStandard argc:\(argCount)" case .invalid(id: let id): return "Invalid OpCpde (\(id))" } } var argCount: Int { switch self { case .printf(_, let argc): return Int(argc) case .callStandard(_, argCount: let argc): return Int(argc) default: return 0 } } }
gpl-2.0
cf7826e0bf92c416612287ebd3a29fa5
32.909091
155
0.683244
2.935852
false
false
false
false
jeffreybergier/Cartwheel
Cartwheel/Cartwheel/MyPlayground.playground/Contents.swift
1
2791
//: Playground - noun: a place where people can play import Foundation // MARK: Implement the Protocols protocol DependencyDefinable { //TODO: Figure out how to add in Printable, Hashable without creating errors static func fileName() -> String //TODO: convert this to property when allowed by swift var name: String { get set } var location: NSURL { get set } func encodableCopy() -> EncodableDependencyDefinable // because these should be implemented as structs, this will require that they be encodable to disk } protocol EncodableDependencyDefinable: NSCoding { var name: String { get set } var location: NSURL { get set } //func decodedCopy<DD: DependencyDefinable>() -> DD func decodedCopy() -> DependencyDefinable } // MARK: Implement the Struct Type Cartfile struct Cartfile: DependencyDefinable { static func fileName() -> String { return "Cartfile" } var name: String var location: NSURL init(location: NSURL) { self.location = location self.name = location.lastPathComponent! } func encodableCopy() -> EncodableDependencyDefinable { return EncodableCartfile(location: self.location) } } extension Cartfile: CustomStringConvertible { var description: String { return "\(self.name) <\(self.location.path!)>" } } extension Cartfile: Hashable { var hashValue: Int { return self.name.hashValue } } extension Cartfile: Equatable {} func ==(lhs: Cartfile, rhs: Cartfile) -> Bool { if lhs.hashValue == rhs.hashValue { return true } else { return false } } // MARK: Implement the Encodable Class Type final class EncodableCartfile: NSObject, EncodableDependencyDefinable { var name: String var location: NSURL init(location: NSURL) { self.location = location self.name = location.lastPathComponent! super.init() } func decodedCopy() -> DependencyDefinable { return Cartfile(location: self.location) } required init?(coder aDecoder: NSCoder) { let location = aDecoder.decodeObjectForKey("location") as! NSURL self.location = location self.name = location.lastPathComponent! super.init() } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.location, forKey: "location") } } // MARK: Play with it in Playgrounds var mainArray = [DependencyDefinable]() let file = Cartfile(location: NSURL(string: "file:///Volumes/Drobo")!) mainArray += [file] as [DependencyDefinable] print(mainArray.count) let encodable = file.encodableCopy() let fileCopy = encodable.decodedCopy() print(fileCopy) if let cartfile = fileCopy as? Cartfile { print("yay!") }
mit
83bae48f69c50e8a5d07c54c957e114a
24.605505
156
0.672519
4.451356
false
false
false
false
CodeInventorGroup/CIComponentKit
Sources/CIComponentKit/CICUIViewController.swift
1
3963
// // UIViewController+CIKit.swift // CIComponentKit // // Created by ManoBoo on 2017/8/30. // Copyright © 2017年 CodeInventor. All rights reserved. // import UIKit public extension CIComponentKit where Base: UIViewController { var visibleViewController: UIViewController? { if let presentVC = base.presentedViewController { return presentVC.cic.visibleViewController } if let base = base as? UITabBarController { return base.selectedViewController?.cic.visibleViewController } else if let base = base as? UINavigationController { return base.visibleViewController?.cic.visibleViewController } if base.isViewLoaded && (base.view.window != nil) { return base } else { print("UIViewController \(base)") } return nil } } public extension UIViewController { struct cic { public static var appearance: CICUIViewController { return CICUIViewController() } public static func setVisibleUserInteractionEnabled(_ userInteractionEnabled: Bool) { if let keyWindow = UIApplication.shared.keyWindow?.rootViewController, let currentViewController = keyWindow.cic.visibleViewController { currentViewController.view.isUserInteractionEnabled = userInteractionEnabled } } } } public enum ControllerState<T> { case loading case loaded(data: T) case error(message: String) } public protocol CICViewControllerStateProtocol { associatedtype DataModel var state: ControllerState<DataModel> {get set} var loadingView: UIView { get } var errorView: UIView { get } func stateDidChanged() } extension CICViewControllerStateProtocol where Self: CICUIViewController { // public typealias DataModel = String } open class CICUIViewController: UIViewController, CICAppearance { public var loadingView = UIView() public var errorView = UIView() public var state: ControllerState<String> = .loading { didSet { stateDidChanged() } } public func stateDidChanged() { switch state { case .loading: print("正在加载") case .loaded(let str): print("data loaded: \(str)") case .error(let errorMessage): print("data loaded error: \(errorMessage)") } } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) NotificationCenter.default.addObserver(self, selector: #selector(CICAppearance.willToggleTheme), name: NSNotification.Name.cic.themeWillToggle, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(CICAppearance.didToggleTheme), name: NSNotification.Name.cic.themeWillToggle, object: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - 主题支持 open func willToggleTheme() { print("CICUIViewController willToggleTheme") } open func didToggleTheme() { print("CICUIViewController didToggleTheme") } // MARK: - 屏幕旋转 open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) } // MARK: - open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } }
mit
5a58a46827cfebe4144d0c08a7f0af70
30.488
117
0.622205
5.421488
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Healthcare
iOS/Healthcare/Controllers/RoutineOptionsViewController.swift
1
3636
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2014, 2015. All Rights Reserved. */ import UIKit /** View controller to show all the individual exercises. */ class RoutineOptionsViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet weak var videoRoutineTableView: UITableView! @IBOutlet weak var routineLabel: UILabel! var routineTitle = "" var currentExercises = ExerciseDataManager.exerciseDataManager.exercises var selectedCell: VideoTableViewCell? var selectedIndex: Int = 0 // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() self.navigationController?.interactivePopGestureRecognizer!.delegate = self routineLabel.text = routineTitle } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func popRoutineOptionsViewController(sender: AnyObject) { self.navigationController?.popViewControllerAnimated(true) } // MARK: UITableView delegate methods func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.currentExercises.count } /** This table view sets all the info on each videoTableViewCell */ func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("videoCell") as! VideoTableViewCell if var exercises = self.currentExercises { let exercise = exercises[indexPath.row] // Configure cell with video information // All data pulled from server except images, which are local let imageFile = "exercise_thumb\(indexPath.row + 1)" cell.thumbNail.image = UIImage(named: imageFile) cell.exerciseTitle.text = exercise.exerciseTitle == nil ? "" : exercise.exerciseTitle cell.exerciseDescription.text = exercise.exerciseDescription == nil ? "" : exercise.exerciseDescription cell.videoID = exercise.videoURL == nil ? "" : exercise.videoURL cell.tools = exercise.tools cell.setExerciseStats(exercise.minutes.integerValue, rep: exercise.repetitions.integerValue, sets: exercise.sets.integerValue) } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) selectedCell = tableView.cellForRowAtIndexPath(indexPath) as? VideoTableViewCell selectedIndex = indexPath.row self.performSegueWithIdentifier("videoSegue", sender: 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?) { if segue.identifier == "videoSegue" { let videoVC = segue.destinationViewController as! VideoPlayerViewController if let cell = selectedCell { videoVC.exerciseName = cell.exerciseDescription.text! videoVC.videoStats = cell.videoStats videoVC.tools = cell.tools videoVC.currentExercise = selectedIndex + 1 videoVC.totalExercises = self.currentExercises.count videoVC.currentVideoID = cell.videoID } } } }
epl-1.0
fcb63ddf089ce9bae805d9fef96c2984
37.263158
138
0.674828
5.679688
false
false
false
false
jovito-royeca/Decktracker
ios/Decktracker/ThumbnailTableViewCell.swift
1
7855
// // ThumbnailTableViewCell.swift // Decktracker // // Created by Jovit Royeca on 11/07/2016. // Copyright © 2016 Jovit Royeca. All rights reserved. // import UIKit import CoreData protocol ThumbnailDelegate : NSObjectProtocol { func seeAllAction(tag: Int) func didSelectItem(tag: Int, objectID: NSManagedObjectID, path: NSIndexPath) } class ThumbnailTableViewCell: UITableViewCell { // MARK: Constants static let CellHeight = CGFloat(128) // MARK: Variables weak var delegate: ThumbnailDelegate? private var _fetchRequest:NSFetchRequest? = nil var fetchRequest:NSFetchRequest? { get { return _fetchRequest } set (aNewValue) { if (_fetchRequest != aNewValue) { _fetchRequest = aNewValue // force reset the fetchedResultsController if let _fetchRequest = _fetchRequest { let context = CoreDataManager.sharedInstance.mainObjectContext fetchedResultsController = NSFetchedResultsController(fetchRequest: _fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) } } } } lazy var fetchedResultsController: NSFetchedResultsController = { let context = CoreDataManager.sharedInstance.mainObjectContext let fetchedResultsController = NSFetchedResultsController(fetchRequest: self.fetchRequest!, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) return fetchedResultsController }() private var shouldReloadCollectionView = false private var blockOperation:NSBlockOperation? // MARK: Outlets @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var seeAllButton: UIButton! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var flowLayout: UICollectionViewFlowLayout! // MARK: Actions @IBAction func seeAllAction(sender: UIButton) { if let delegate = delegate { delegate.seeAllAction(self.tag) } } // MARK: Overrides override func awakeFromNib() { super.awakeFromNib() // Initialization code let space = CGFloat(5.0) flowLayout.minimumInteritemSpacing = space flowLayout.minimumLineSpacing = space flowLayout.itemSize = CGSizeMake(80, 100) collectionView.registerNib(UINib(nibName: "SetCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "Set") collectionView.dataSource = self collectionView.delegate = self } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } // MARK: Custom methods func loadData() { if (fetchRequest) != nil { do { try fetchedResultsController.performFetch() } catch {} fetchedResultsController.delegate = self } collectionView.reloadData() } } // MARK: UICollectionViewDataSource extension ThumbnailTableViewCell: UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if (fetchRequest) != nil, let sections = fetchedResultsController.sections { let sectionInfo = sections[section] let items = sectionInfo.numberOfObjects return items } else { return 0 } } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Set", forIndexPath: indexPath) as! SetCollectionViewCell if let set = fetchedResultsController.objectAtIndexPath(indexPath) as? Set { cell.setOID = set.objectID } return cell } } // MARK: UICollectionViewDelegate extension ThumbnailTableViewCell: UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if let delegate = delegate, let object = fetchedResultsController.objectAtIndexPath(indexPath) as? NSManagedObject { delegate.didSelectItem(self.tag, objectID: object.objectID, path: indexPath) } } } // MARK: NSFetchedResultsControllerDelegate extension ThumbnailTableViewCell : NSFetchedResultsControllerDelegate { func controllerWillChangeContent(controller: NSFetchedResultsController) { shouldReloadCollectionView = false blockOperation = NSBlockOperation() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: blockOperation!.addExecutionBlock({ self.collectionView.insertSections(NSIndexSet(index: sectionIndex)) }) case .Delete: blockOperation!.addExecutionBlock({ self.collectionView.deleteSections(NSIndexSet(index: sectionIndex)) }) case .Update: blockOperation!.addExecutionBlock({ self.collectionView.reloadSections(NSIndexSet(index: sectionIndex)) }) default: return } } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: blockOperation!.addExecutionBlock({ self.collectionView.insertItemsAtIndexPaths([newIndexPath!]) }) case .Delete: blockOperation!.addExecutionBlock({ self.collectionView.deleteItemsAtIndexPaths([indexPath!]) }) case .Update: if let indexPath = indexPath { // if let cell = collectionView.cellForItemAtIndexPath(indexPath) { // if let c = cell as? WeatherThumbnailCollectionViewCell, // let weather = fetchedResultsController.objectAtIndexPath(indexPath) as? Weather { // // blockOperation!.addExecutionBlock({ // self.configureCell(c, weather: weather) // }) // } // } } case .Move: return } } func controllerDidChangeContent(controller: NSFetchedResultsController) { // Checks if we should reload the collection view to fix a bug @ http://openradar.appspot.com/12954582 if shouldReloadCollectionView { collectionView.reloadData() } else { collectionView.performBatchUpdates({ if let blockOperation = self.blockOperation { blockOperation.start() } }, completion:nil) } } }
apache-2.0
bf7859b5103cea8861dfc89224cf4611
35.534884
211
0.596129
6.741631
false
false
false
false
tectijuana/iOS16b
FernandoDominguez/p3.swift
2
326
import Foundation ///lista de 20 enteros var lista=[20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1] let con=lista.count var lista2:[Int]=[] print("Lista original: ",lista) var num=19 var acumu=0 var acumu1=0 for i in 0...con-1 { acumu1=lista[num] lista2+=[acumu1] num=num-1 } print("lista actualizada: ",lista2)
mit
3710391ce5c66eeeaa83c485e88b64f4
11.538462
62
0.674847
2.144737
false
false
false
false
armadsen/CocoaHeads-SLC-Presentations
KVO-and-Related-Patterns-In-Swift/Best?SwiftKVODemo.playground/Contents.swift
1
1644
import Foundation struct PropertyObserver<T> { private weak var target: AnyObject? private let handler: (T) -> Void init(target: AnyObject, handler: @escaping (T) -> Void) { self.target = target self.handler = handler } func invoke(_ newValue: T) { if target != nil { self.handler(newValue) } } } class PropertyNotification<PropertyType> { private var observers = [PropertyObserver<PropertyType>]() func post(newValue: PropertyType) { self.observers.forEach {$0.invoke(newValue)} } func add(observer: AnyObject, handler: @escaping (PropertyType) -> Void) { observers.append(PropertyObserver(target: observer, handler: handler)) } } class Observable<T> { init(_ value: T) { self.value = value } var value: T { didSet { changeNotification.post(newValue: value) } } func addObserver(_ observer: AnyObject, handler: @escaping (T) -> Void) { self.changeNotification.add(observer: observer, handler: handler) } private let changeNotification = PropertyNotification<T>() } //: To make your object's properties observable, make them `Observable`s class Foo { var bar = Observable(0) } //: Let's try it out class TestObserver {} // <- Not an NSObject let foo = Foo() let testObserver = TestObserver() foo.bar.addObserver(testObserver) { (newValue) -> Void in print("foo.bar changed to \(newValue)") } foo.bar.value = 42 foo.bar.value = 27 //: However, we *cannot* use this in a non-ObjC class or struct now: /* struct ObserverStruct { let foo: Foo init() { foo = Foo() foo.bar.addObserver(self) { (newValue) -> Void in print("foo.bar changed to \(newValue)") } } } */
mit
46b0ae080142f53bf8cfbc2e2882ead3
19.04878
75
0.684307
3.341463
false
false
false
false
cactis/SwiftEasyKit
Source/Classes/SelectionViewController/SelectOption.swift
1
4808
// // SelectOption.swift // SwiftEasyKit // // Created by ctslin on 2016/11/25. // Copyright © 2016年 airfont. All rights reserved. // import UIKit // import RandomKit import SwiftRandom import ObjectMapper open class InputField: Mappable { public var key: String? public var label: String? public var value: String? open func mapping(map: Map) { key <- map["key"] label <- map["label"] value <- map["value"] } public required init?(map: Map) {} } open class SelectOption: Mappable { public var id: Int? public var name: String? public var title: String? public var parent: SelectOption? public var parent_id: Int? public var family: [SelectOption]? // var children: [SelectOption]?//Array<SelectOption>? //[SelectOption]? public var active: Bool! = true public var level: Int? public var url: String? public var children_url: String? public var inputFields: [InputField]? open func mapping(map: Map) { id <- map["id"] name <- map["name"] title <- map["title"] parent_id <- map["parent_id"] parent <- map["parent"] // children <- map["children"] level <- map["level"] active <- map["active"] family <- map["family"] url <- map["url"] children_url <- map["children_url"] inputFields <- map["input_fields"] } open class func new(_ id: Int, name: String) -> SelectOption { let item = SelectOption(JSON: ["id": id, "name": name, "level": 0])! item.family = [item] // item.family?.first?.id = id // item.family?.first?.name = item.name return item } public var breadcrumb: String! { get { _ = family?.popLast() return family != nil ? (family?.asBreadcrumb())! : name! } } public var forHuman: String! { get { return family != nil ? (family?.asBreadcrumb())! : name! } } open class func seeds(_ onComplete: (_ items: [SelectOption]) -> ()) { let items = Array(0...wizRandomInt(5, upper: 8)).map({ SelectOption(JSON: ["id": $0, "name": Randoms.randomFakeTag()])! }) onComplete(items) } open class func list(_ url: String!, onComplete: @escaping (_ items: [SelectOption]) -> ()) { var items = [SelectOption]() API.get(url) { (response, data) in switch response.result { case .success(let value): if let jsons = value as? [[String: AnyObject]] { jsons.forEach({ json in let item = SelectOption(JSON: json)! items.append(item) }) onComplete(items) } case .failure(let error): _logForUIMode(error.localizedDescription) } // onComplete(items) } } public func getChildren(_ onComplete: @escaping (_ items: [SelectOption]?) -> ()) { SelectOption.list(children_url) { (items) in onComplete(items) } } required public init?(map: Map) {} } extension Sequence where Iterator.Element == SelectOption { var ids: [Int] { get { return map({$0.id!}) } } public func asBreadcrumb(_ separator: String = " / ") -> String { return self.map({$0.name!}).join(separator) } public func prependDefaultOption(name: String! = "全部類別") -> [SelectOption] { return [SelectOption(JSON: ["id": 0, "name": name, "level": 0])!] + self } public func contains(_ ele: SelectOption) -> Bool { return ids.contains(ele.id!) } } //extension SequenceType where Iterator.Element == AnyObject { // func toSelectOption() -> [SelectOption] { // var selectOptions = [SelectOption]() // forEach({ obj in // if obj is [String: AnyObject] { // selectOptions.append(SelectOption(JSON: [ // "id": obj.objectForKey("id")!, // "name": obj.objectForKey("name")!, // "children": (obj.objectForKey("children") as? [AnyObject])! // ])!) // } // }) // return selectOptions // } //} open class SelectionCell: TableViewCell { var id: Int! var title = UILabel() public var checked = false { didSet { styleIcon() } } var icon = IconLabel(iconCode: K.Icons.check) func loadData(_ data: SelectOption) { if data.id != nil { id = data.id } title.text = data.name } func styleIcon() { if checked { icon.iconColor = K.Color.selectOptionChecked } else { icon.iconColor = UIColor.clear } } override open func layoutUI() { super.layoutUI() layout([title, icon]) } override open func styleUI() { super.styleUI() title.styled().darker().bold() backgroundColor = UIColor.white icon.iconSize = title.textHeight() * 1.4 styleIcon() } override open func layoutSubviews() { super.layoutSubviews() title.anchorAndFillEdge(.left, xPad: 20, yPad: 10, otherSize: width - 40) icon.anchorToEdge(.right, padding: 20, width: icon.iconSize!, height: icon.iconSize!) } }
mit
a84e80c4e07feb2aa2fed7a10fd26687
26.411429
126
0.612675
3.681504
false
false
false
false
SunLiner/Floral
Floral/Floral/Classes/Profile/Remind/Controller/RemindViewController.swift
1
2637
// // RemindViewController.swift // Floral // // Created by ALin on 16/6/6. // Copyright © 2016年 ALin. All rights reserved. // 消息提醒 import UIKit private let NormalReuseIdentifier = "NormalReuseIdentifier" private let InfoReuseIdentifier = "InfoReuseIdentifier" class RemindViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() setup() } private func setup() { tableView.tableFooterView = UIView() tableView.separatorStyle = .None tableView.registerClass(RemindNormalCell.self, forCellReuseIdentifier: NormalReuseIdentifier) tableView.registerClass(RemindInfoCell.self, forCellReuseIdentifier: InfoReuseIdentifier) navigationItem.title = "消息" } deinit{ ALinLog("") } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // 实际开发中, 后面的1需要根据系统返回的消息提醒来确定消息的数目. return titles.count + 1 } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.row > titles.count - 1 { return 100 } return 40 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row > titles.count - 1 { let cell = tableView.dequeueReusableCellWithIdentifier(InfoReuseIdentifier) as! RemindInfoCell return cell } let cell = tableView.dequeueReusableCellWithIdentifier(NormalReuseIdentifier) as! RemindNormalCell cell.title = titles[indexPath.row] cell.index = indexPath.row return cell } // MARK: - Table view data delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row > titles.count - 1 { KeyWindow.addSubview(notifyView) notifyView.snp_makeConstraints(closure: { (make) in make.edges.equalTo(0) }) }else{ UIAlertView(title: "花田小憩", message: "由于此项功能需要认证后的专栏作家才有相关的数据, 所以后期会尽量补上", delegate: nil, cancelButtonTitle: "好的").show() } } private lazy var titles = ["收到的评论", "收到的赞", "新的订阅"] /// 消息视图 private lazy var notifyView : RemindNotifyView = RemindNotifyView() }
mit
a726d34efd306ce703c92fae08cb1417
31.72
133
0.659332
4.621469
false
false
false
false
ph1ps/Food101-CoreML
Food101Prediction/ViewController.swift
1
2500
// // ViewController.swift // Food101Prediction // // Created by Philipp Gabriel on 21.06.17. // Copyright © 2017 Philipp Gabriel. All rights reserved. // import UIKit import CoreML class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var percentage: UILabel! override func viewDidLoad() { super.viewDidLoad() } @IBAction func buttonPressed(_ sender: Any) { let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let imagePickerView = UIImagePickerController() imagePickerView.delegate = self alert.addAction(UIAlertAction(title: "Choose Image", style: .default) { _ in imagePickerView.sourceType = .photoLibrary self.present(imagePickerView, animated: true, completion: nil) }) alert.addAction(UIAlertAction(title: "Take Image", style: .default) { _ in imagePickerView.sourceType = .camera self.present(imagePickerView, animated: true, completion: nil) }) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) { dismiss(animated: true, completion: nil) guard let image = info["UIImagePickerControllerOriginalImage"] as? UIImage else { return } processImage(image) } func processImage(_ image: UIImage) { let model = Food101() let size = CGSize(width: 299, height: 299) guard let buffer = image.resize(to: size)?.pixelBuffer() else { fatalError("Scaling or converting to pixel buffer failed!") } guard let result = try? model.prediction(image: buffer) else { fatalError("Prediction failed!") } let confidence = result.foodConfidence["\(result.classLabel)"]! * 100.0 let converted = String(format: "%.2f", confidence) imageView.image = image percentage.text = "\(result.classLabel) - \(converted) %" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
ec106db3522bd3961e672f7756dcb3c7
31.881579
118
0.660264
4.948515
false
false
false
false
santosli/100-Days-of-Swift-3
Project 36/Project 36/AppDelegate.swift
1
6159
// // AppDelegate.swift // Project 36 // // Created by Santos on 25/01/2017. // Copyright © 2017 santos. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.window = UIWindow(frame: UIScreen.main.bounds) self.window!.backgroundColor = UIColor(red:0.22, green:0.67, blue:0.96, alpha:1.00) self.window!.makeKeyAndVisible() // rootViewController from StoryBoard let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let mainViewController = mainStoryboard.instantiateViewController(withIdentifier: "mainView") self.window!.rootViewController = mainViewController // logo mask mainViewController.view.layer.mask = CALayer() mainViewController.view.layer.mask?.contents = UIImage(named: "twitterlogo.png")!.cgImage mainViewController.view.layer.mask?.bounds = CGRect(x: 0, y: 0, width: 75, height: 60) mainViewController.view.layer.mask?.anchorPoint = CGPoint(x: 0.5, y: 0.5) mainViewController.view.layer.mask?.position = CGPoint(x: mainViewController.view.frame.width / 2, y: mainViewController.view.frame.height / 2) // logo mask background view let maskBgView = UIView(frame: mainViewController.view.frame) maskBgView.backgroundColor = UIColor.white mainViewController.view.addSubview(maskBgView) mainViewController.view.bringSubview(toFront: maskBgView) // logo mask animation let transformAnimation = CAKeyframeAnimation(keyPath: "bounds") transformAnimation.duration = 1 transformAnimation.beginTime = CACurrentMediaTime() + 1 //add delay of 1 second let initalBounds = NSValue(cgRect: (mainViewController.view.layer.mask?.bounds)!) let secondBounds = NSValue(cgRect: CGRect(x: 0, y: 0, width: 60, height: 50)) let finalBounds = NSValue(cgRect: CGRect(x: 0, y: 0, width: 2500, height: 2000)) transformAnimation.values = [initalBounds, secondBounds, finalBounds] transformAnimation.keyTimes = [0, 0.5, 1] transformAnimation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)] transformAnimation.isRemovedOnCompletion = false transformAnimation.fillMode = kCAFillModeForwards mainViewController.view.layer.mask?.add(transformAnimation, forKey: "maskAnimation") // logo mask background view animation UIView.animate(withDuration: 0.1, delay: 1.35, options: UIViewAnimationOptions.curveEaseIn, animations: { maskBgView.alpha = 0.0 }, completion: { finished in maskBgView.removeFromSuperview() }) // root view animation UIView.animate(withDuration: 0.25, delay: 1.3, options: [], animations: { self.window!.rootViewController!.view.transform = CGAffineTransform(scaleX: 1.05, y: 1.05) }, completion: { finished in UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions.curveEaseInOut, animations: { self.window!.rootViewController!.view.transform = CGAffineTransform.identity }, completion: nil ) }) return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func animationDidStop(anim: CAAnimation!, finished flag: Bool) { // remove mask when animation completes self.window!.rootViewController!.view.layer.mask = nil } }
apache-2.0
4e492ac948442e1645b4273a65b1d1d4
51.632479
285
0.624066
5.848053
false
false
false
false
xiaoxionglaoshi/DNSwiftProject
DNSwiftProject/DNSwiftProject/Classes/Vendor/DNCycleView/DNCycleViewCell.swift
1
1967
// // DNCycleViewCell.swift // DNSwiftProject // // Created by mainone on 16/12/23. // Copyright © 2016年 wjn. All rights reserved. // import UIKit import SnapKit class DNCycleViewCell: UICollectionViewCell { /// 文字标题间距 private let KMargin = CGFloat(8) /// 轮播图片 lazy var imageView = UIImageView() /// 轮播标题 lazy var titleLab = UILabel() // 外接Model数据 var cycleModel: DNCycleModel? { didSet { if let imageStr = cycleModel?.imageString { imageView.kf.setImage(with: URL(string: imageStr), placeholder: UIImage(named: "placeHolder")) } titleLab.text = cycleModel?.title } } override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { imageView = UIImageView(frame: CGRect(x: 0, y: 0, width:bounds.width , height: bounds.height)) imageView.contentMode = .scaleAspectFill addSubview(imageView) let backView = UIView() backView.backgroundColor = UIColor.black.withAlphaComponent(0.5) addSubview(backView) titleLab = UILabel() titleLab.tag = 2 titleLab.textColor = UIColor.white titleLab.textAlignment = .left titleLab.numberOfLines = 0 titleLab.font = UIFont(name: "TimesNewRomanPS-ItalicMT", size: 13) backView.addSubview(titleLab) backView.snp.makeConstraints { (make) in make.left.equalTo(20) make.right.equalTo(-20) make.bottom.equalTo(-15) make.height.greaterThanOrEqualTo(20) } titleLab.snp.makeConstraints { (make) in make.edges.equalTo(backView).inset(UIEdgeInsetsMake(5, 5, 5, 5)) } } }
apache-2.0
014b22c03b66283d9e09a5713d0072bc
27.352941
110
0.596473
4.442396
false
false
false
false
FlaneurApp/FlaneurOpen
Example/FlaneurOpen/PortraitCollectionViewCell.swift
1
1503
// // PortraitCollectionViewCell.swift // FlaneurOpen_Example // // Created by Mickaël Floc'hlay on 25/01/2018. // Copyright © 2018 CocoaPods. All rights reserved. // import UIKit class PortraitCollectionViewCell: UICollectionViewCell { let portraitImageView = UIImageView() let nameLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) self.addSubview(portraitImageView) portraitImageView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(nameLabel) nameLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ portraitImageView.leftAnchor.constraint(equalTo: self.leftAnchor), portraitImageView.topAnchor.constraint(equalTo: self.topAnchor), portraitImageView.rightAnchor.constraint(equalTo: self.rightAnchor), portraitImageView.bottomAnchor.constraint(equalTo: self.bottomAnchor), nameLabel.leftAnchor.constraint(equalTo: self.leftAnchor), nameLabel.rightAnchor.constraint(equalTo: self.rightAnchor), nameLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor), ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var isSelected: Bool { didSet { debugPrint("New state: ", isSelected) backgroundColor = isSelected ? .yellow : .gray } } }
mit
093ff463f61f8c2c889be1a7f36f1334
32.355556
82
0.687542
5.248252
false
false
false
false
afrodev/PSPageControl
Example/PSPageControl/ViewController.swift
1
3247
// // ViewController.swift // PSPageControl // // Created by Piotr Sochalewski on 02/08/2016. // Copyright (c) 2016 Piotr Sochalewski. All rights reserved. // import UIKit import PSPageControl class ViewController: UIViewController { @IBOutlet weak var pageControl: PSPageControl! override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() // Delegate PageControl pageControl.delegate = self let loremIpsum = ["Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nibh augue, suscipit a, scelerisque sed, lacinia in, mi. Cras vel lorem. Etiam pellentesque aliquet tellus. Phasellus pharetra nulla ac diam. Quisque semper justo at risus.", "Donec venenatis, turpis vel hendrerit interdum, dui ligula ultricies purus, sed posuere libero dui id orci.", "Nam congue, pede vitae dapibus aliquet, elit magna vulputate arcu, vel tempus metus leo non est. Etiam sit amet lectus quis est congue mollis. Phasellus congue lacus eget neque.", "Phasellus ornare, ante vitae consectetuer consequat, purus sapien ultricies dolor, et mollis pede metus eget nisi. Praesent sodales velit quis augue.", "Cras suscipit, urna at aliquam rhoncus, urna quam viverra nisi, in interdum massa nibh nec erat."] pageControl.backgroundPicture = UIImage(named: "Background") pageControl.offsetPerPage = 40 // Prepare views to add var views = [UIView]() for index in 1...5 { let view = UIView(frame: self.view.frame) let label = UILabel(frame: CGRect(x: self.view.frame.width / 2.0 - 60.0, y: 40.0, width: 120.0, height: 30.0)) label.textColor = .white label.font = UIFont(name: "HelveticaNeue-Bold", size: 24.0) label.textAlignment = .center label.text = "View #\(index)" let description = UILabel(frame: CGRect(x: 30.0, y: 80.0, width: self.view.frame.width - 60.0, height: self.view.frame.height - 100.0)) description.lineBreakMode = .byWordWrapping description.numberOfLines = 0 description.textColor = .white description.font = UIFont(name: "HelveticaNeue-Light", size: 20.0) description.textAlignment = .center description.text = loremIpsum[index - 1] view.addSubview(label) view.addSubview(description) views.append(view) } pageControl.views = views } } // MARK: Protocol to get PSPageControl current index extension ViewController: PSPageControlDelegate { func didChange(index: Int) { print("PSPageControl - Current Index: \(index)") } }
mit
2489d7d4364ed9140f51c8ae0c37cab8
41.168831
264
0.567909
5.314239
false
false
false
false
kekearif/KACircleCropViewController
KACircleCropViewController.swift
2
6223
// // KACircleCropViewController.swift // Circle Crop View Controller // // Created by Keke Arif on 29/02/2016. // Copyright © 2016 Keke Arif. All rights reserved. // import UIKit protocol KACircleCropViewControllerDelegate { func circleCropDidCancel() func circleCropDidCropImage(_ image: UIImage) } class KACircleCropViewController: UIViewController, UIScrollViewDelegate { var delegate: KACircleCropViewControllerDelegate? var image: UIImage let imageView = UIImageView() let scrollView = KACircleCropScrollView(frame: CGRect(x: 0, y: 0, width: 240, height: 240)) let cutterView = KACircleCropCutterView() let label = UILabel(frame: CGRect(x: 0, y: 0, width: 130, height: 30)) let okButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 30)) let backButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 30)) init(withImage image: UIImage) { self.image = image super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: View management override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.black scrollView.backgroundColor = UIColor.black imageView.image = image imageView.frame = CGRect(origin: CGPoint.zero, size: image.size) scrollView.delegate = self scrollView.addSubview(imageView) scrollView.contentSize = image.size let scaleWidth = scrollView.frame.size.width / scrollView.contentSize.width scrollView.minimumZoomScale = scaleWidth if imageView.frame.size.width < scrollView.frame.size.width { print("We have the case where the frame is too small") scrollView.maximumZoomScale = scaleWidth * 2 } else { scrollView.maximumZoomScale = 1.0 } scrollView.zoomScale = scaleWidth //Center vertically scrollView.contentOffset = CGPoint(x: 0, y: (scrollView.contentSize.height - scrollView.frame.size.height)/2) //Add in the black view. Note we make a square with some extra space +100 pts to fully cover the photo when rotated cutterView.frame = view.frame cutterView.frame.size.height += 100 cutterView.frame.size.width = cutterView.frame.size.height //Add the label and buttons label.text = "Move and Scale" label.textAlignment = .center label.textColor = UIColor.white label.font = label.font.withSize(17) okButton.setTitle("OK", for: UIControlState()) okButton.setTitleColor(UIColor.white, for: UIControlState()) okButton.titleLabel?.font = backButton.titleLabel?.font.withSize(17) okButton.addTarget(self, action: #selector(didTapOk), for: .touchUpInside) backButton.setTitle("<", for: UIControlState()) backButton.setTitleColor(UIColor.white, for: UIControlState()) backButton.titleLabel?.font = backButton.titleLabel?.font.withSize(30) backButton.addTarget(self, action: #selector(didTapBack), for: .touchUpInside) setLabelAndButtonFrames() view.addSubview(scrollView) view.addSubview(cutterView) cutterView.addSubview(label) cutterView.addSubview(okButton) cutterView.addSubview(backButton) } func setLabelAndButtonFrames() { scrollView.center = view.center cutterView.center = view.center label.frame.origin = CGPoint(x: cutterView.frame.size.width/2 - label.frame.size.width/2, y: cutterView.frame.size.height/2 - view.frame.size.height/2 + 3) okButton.frame.origin = CGPoint(x: cutterView.frame.size.width/2 + view.frame.size.width/2 - okButton.frame.size.width - 12, y: cutterView.frame.size.height/2 - view.frame.size.height/2 + 3) backButton.frame.origin = CGPoint(x: cutterView.frame.size.width/2 - view.frame.size.width/2 + 3, y: cutterView.frame.size.height/2 - view.frame.size.height/2 + 1) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) -> Void in self.setLabelAndButtonFrames() }) { (UIViewControllerTransitionCoordinatorContext) -> Void in } } func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } override var prefersStatusBarHidden : Bool { return true } // MARK: Button taps func didTapOk() { let newSize = CGSize(width: image.size.width*scrollView.zoomScale, height: image.size.height*scrollView.zoomScale) let offset = scrollView.contentOffset UIGraphicsBeginImageContextWithOptions(CGSize(width: 240, height: 240), false, 0) let circlePath = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 240, height: 240)) circlePath.addClip() var sharpRect = CGRect(x: -offset.x, y: -offset.y, width: newSize.width, height: newSize.height) sharpRect = sharpRect.integral image.draw(in: sharpRect) let finalImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() if let imageData = UIImagePNGRepresentation(finalImage!) { if let pngImage = UIImage(data: imageData) { delegate?.circleCropDidCropImage(pngImage) } else { delegate?.circleCropDidCancel() } } else { delegate?.circleCropDidCancel() } } func didTapBack() { delegate?.circleCropDidCancel() } }
mit
bb1ebbb1b28edc2e8785a5470d104490
32.451613
198
0.628415
4.678195
false
false
false
false
ceicke/SimpleHomeControl
SimpleHomeControl/AppDelegate.swift
1
5783
// // AppDelegate.swift // SimpleHomeControl // // Created by Christoph Eicke on 12.01.16. // Copyright © 2016 Christoph Eicke. All rights reserved. // // TODO-1.1: // - check for timeout of refreshing and show message // - check if miniserver is available with username/password/ip combination // - where do we get the scenes from? // - adding new actors // - check if lamps are on/off // - force touch to turn on/off favorites // - refactor creation of rooms and actors into class // - move show in favorites to edit view import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Storage", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Storage") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." let mOptions = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true] do { try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: mOptions) } catch var error1 as NSError { error = error1 coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } catch { fatalError() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // end MARK }
mit
5e733a6736e7d21ea9e5fd9f29172364
52.045872
290
0.726565
5.713439
false
false
false
false
Azero123/JW-Broadcasting
JW Broadcasting/MediaOnDemandCategory.swift
1
21224
// // MediaOnDemandCategory.swift // JW Broadcasting // // Created by Austin Zelenka on 12/4/15. // Copyright © 2015 xquared. All rights reserved. // import UIKit import AVKit var streamingCell=true class MediaOnDemandCategory: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate { var _category="VODBible" var category:String { set (newValue){ _category=newValue renewContent() } get { return _category } } var _categoryIndex=0 var categoryIndex:Int { set (newValue){ _categoryIndex=newValue } get { return _categoryIndex } } /* let category="VideoOnDemand" let categoriesDirectory=base+"/"+version+"/categories/"+languageCode let categoryDataURL=categoriesDirectory+"/"+category+"?detailed=1" categoryToGoTo=unfold(categoryDataURL+"|category|subcategories|\(indexPath.row)|key") as! String*/ //pnr lg 1140,380 //wsr lg 1280,719 @IBOutlet weak var TopImage: UIImageView! @IBOutlet weak var previewImageView: UIImageView! @IBOutlet weak var previewDescription: UITextView! @IBOutlet weak var categoryTitle: UILabel! @IBOutlet weak var backgroundVisualEffect: UIVisualEffectView! @IBOutlet weak var backgroundImage: UIImageView! @IBOutlet weak var scrollView: UIScrollView! override func viewDidLoad() { super.viewDidLoad() //backgroundImage.alpha=0.5 //backgroundVisualEffect.alpha=0.85 let hMaskLayer:CAGradientLayer = CAGradientLayer() // defines the color of the background shadow effect let darkColor = UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: 0.75).CGColor let lightColor = UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: 0).CGColor // define a vertical gradient (up/bottom edges) let colorsForDarkness = [darkColor,lightColor] // without specifying startPoint and endPoint, we get a vertical gradient hMaskLayer.opacity = 1.0 hMaskLayer.colors = colorsForDarkness hMaskLayer.startPoint = CGPointMake(0.2, 0.5) hMaskLayer.endPoint = CGPointMake(1.0, 0.5) hMaskLayer.bounds = self.TopImage.bounds hMaskLayer.anchorPoint = CGPointZero self.TopImage.layer.insertSublayer(hMaskLayer, atIndex: 0) backgroundVisualEffect.alpha=0.99 let vMaskLayer:CAGradientLayer = CAGradientLayer() // defines the color of the background shadow effect let fadeIn = UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: 1.0).CGColor let fadeOut = UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: 0).CGColor // define a vertical gradient (up/bottom edges) let colors = [fadeIn, fadeIn ,fadeOut] let locations = [0.0, 0.7,0.98] // without specifying startPoint and endPoint, we get a vertical gradient vMaskLayer.opacity = 1.0 vMaskLayer.colors = colors vMaskLayer.locations = locations vMaskLayer.bounds = self.TopImage.bounds vMaskLayer.anchorPoint = CGPointZero //self.TopImage.layer.mask=vMaskLayer renewContent() // Do any additional setup after loading the view. } func renewContent(){ let categoriesDirectory=base+"/"+version+"/categories/"+languageCode let categoryDataURL=categoriesDirectory+"/"+category+"?detailed=1" fetchDataUsingCache(categoryDataURL, downloaded: { dispatch_async(dispatch_get_main_queue()) { self.categoryTitle.text=unfold("\(categoryDataURL)|category|name") as? String if (textDirection == .RightToLeft){//RTL alignment self.categoryTitle.textAlignment = .Right } else { self.categoryTitle.textAlignment = .Left } if (textDirection == .RightToLeft){//RTL alignment self.TopImage.transform = CGAffineTransformMakeScale(-1.0, 1.0) } else { self.TopImage.transform = CGAffineTransformMakeScale(1.0, 1.0) } let imageURL=unfold("\(categoryDataURL)|category|images|pnr|lg") as? String if (imageURL != nil){ fetchDataUsingCache(imageURL!, downloaded: { dispatch_async(dispatch_get_main_queue()) { print("image updated") /*UIView.animateWithDuration(2.0, animations: { self.TopImage.image=imageUsingCache(imageURL!) })*/ UIView.transitionWithView(self.TopImage, duration: 0.25, options: .TransitionCrossDissolve, animations: { self.TopImage.image=imageUsingCache(imageURL!) }, completion: nil) self.previewImageView.userInteractionEnabled=true self.previewImageView.adjustsImageWhenAncestorFocused = true } }) } for var i=0;i<unfold("\(categoryDataURL)|category|subcategories|count") as! Int ; i++ { let layout=CollectionViewHorizontalFlowLayout() layout.spacingPercentile=1.075 //layout.spacingPercentile=1.3 var collectionView=MODSubcategoryCollectionView(frame: CGRect(x: CGFloat(0), y:CGFloat(475*(i))+620, width: self.view.frame.size.width, height: CGFloat(425)), collectionViewLayout: layout) collectionView.categoryName=unfold("\(categoryDataURL)|category|subcategories|\(i)|name") as! String collectionView.clipsToBounds=false collectionView.contentInset=UIEdgeInsetsMake(0, 60, 0, 60) collectionView.prepare() if (self.subcategoryCollectionViews.count>i){ collectionView=self.subcategoryCollectionViews[i] } else { collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "mediaElement") collectionView.dataSource=self collectionView.delegate=self self.subcategoryCollectionViews.insert(collectionView, atIndex: i) if (i==0){ //continue } self.scrollView.addSubview(collectionView) self.scrollView.scrollEnabled=true self.scrollView.contentSize=CGSizeMake(self.scrollView.frame.size.width, collectionView.frame.origin.y+collectionView.frame.size.height+35) } collectionView.reloadData() if (textDirection == .RightToLeft){//RTL alignment collectionView.contentOffset=collectionView.centerPointFor(CGPointMake(collectionView.contentSize.width-collectionView.frame.size.width+collectionView.contentInset.right, 0)) } } } }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var subcategoryCollectionViews:[MODSubcategoryCollectionView]=[] func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let categoriesDirectory=base+"/"+version+"/categories/"+languageCode let categoryDataURL=categoriesDirectory+"/"+category+"?detailed=1" let subcategories=unfold("\(categoryDataURL)|category|subcategories|\(subcategoryCollectionViews.indexOf(collectionView as! MODSubcategoryCollectionView)!)|media|count") as? Int if (subcategories != nil){ if (streamingCell){ if (subcategoryCollectionViews.indexOf(collectionView as! MODSubcategoryCollectionView)! == 0){ return subcategories!+1 } } return subcategories! } return 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let categoriesDirectory=base+"/"+version+"/categories/"+languageCode let categoryDataURL=categoriesDirectory+"/"+category+"?detailed=1" let cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("mediaElement", forIndexPath: indexPath) for subview in cell.contentView.subviews { subview.removeFromSuperview() } cell.alpha=1 cell.clipsToBounds=false cell.contentView.layoutSubviews() var indexPathRow=indexPath.row if (streamingCell){ if (subcategoryCollectionViews.indexOf(collectionView as! MODSubcategoryCollectionView)! == 0){ indexPathRow-- if (indexPath.row==0){ let streamview=StreamView(frame: cell.bounds) streamview.streamID=categoryIndex let streamingScheduleURL=base+"/"+version+"/schedules/"+languageCode+"/Streaming?utcOffset=0" let imageURL:String?=unfold(nil, instructions: [streamingScheduleURL,"category","subcategories",streamview.streamID,"media",0,"images",["lsr","wss","cvr","lss","wsr","pss","pns",""],["lg","md","sm","xs",""]]) as? String if (imageURL != nil){ fetchDataUsingCache(imageURL!, downloaded: { dispatch_async(dispatch_get_main_queue()) { //let image=imageUsingCache(imageURL!) streamview.image=imageUsingCache(imageURL!) } }) } streamview.frame=CGRect(x: 0, y: 0, width: 860, height: 430)//(860.0, 430.0 let width:CGFloat=2 let height:CGFloat=1 var ratio:CGFloat=width/height streamview.frame=CGRect(x: (cell.frame.size.width-((cell.frame.size.height-60)*ratio))/2, y: 0, width: (cell.frame.size.height-60)*ratio, height: (cell.frame.size.height-60)) if (width>height){ ratio=height/width streamview.frame=CGRect(x: 0, y: 0, width: cell.frame.size.width, height: cell.frame.size.width*ratio) } //print("image size: \(image!.size) \(imageURL)") //let sizeOfStream=CGSize(width: , height: <#T##Double#>) streamview.frame=CGRect(x: (cell.frame.size.width-streamview.frame.size.width)/2, y: (cell.frame.size.height-streamview.frame.size.height)/2, width: streamview.frame.size.width, height: streamview.frame.size.height) cell.contentView.addSubview(streamview) } } } //lblNowPlaying let label=marqueeLabel(frame: CGRect(x: 0, y: cell.bounds.size.height/2+10, width: cell.bounds.size.width, height: cell.bounds.size.height)) label.fadeLength=15 label.fadePadding = 30 label.fadePaddingWhenFull = -5 label.textSideOffset=15 label.textColor=UIColor.darkGrayColor() label.textAlignment = .Center label.font=UIFont.systemFontOfSize(29) let retrievedVideo=unfold("\(categoryDataURL)|category|subcategories|\(subcategoryCollectionViews.indexOf(collectionView as! MODSubcategoryCollectionView)!)|media|\(indexPathRow)") /* Code for removing the repetitive JW Broadcasting - before all the names of all the monthly broadcasts. */ var title:String?=nil if (retrievedVideo != nil){ title=(retrievedVideo!.objectForKey("title") as? String) } if (title != nil){ let replacementStrings=["JW Broadcasting —","JW Broadcasting—","JW Broadcasting​ —","JW Broadcasting​—"] for replacement in replacementStrings { if (title!.containsString(replacement)){ title=title!.stringByReplacingOccurrencesOfString(replacement, withString: "") title=title!.stringByAppendingString(" Broadcast") /* replace " Broadcast" with a key from: base+"/"+version+"/languages/"+languageCode+"/web" so that this works with foreign languages*/ } } label.text=title label.layer.shadowColor=UIColor.darkGrayColor().CGColor label.layer.shadowRadius=5 label.numberOfLines=3 } if (subcategoryCollectionViews.indexOf(collectionView as! MODSubcategoryCollectionView)! == 0 && indexPath.row==0){ let streamingScheduleURL=base+"/"+version+"/schedules/"+languageCode+"/Streaming?utcOffset=0" let nowPlayingString=unfold("\(base)/\(version)/translations/\(languageCode)|translations|\(languageCode)|lblNowPlaying") as! String _=unfold(nil, instructions: [streamingScheduleURL,"category","subcategories",self.categoryIndex,"media","title"]) as? String label.text="\(nowPlayingString)" } if (retrievedVideo == nil){ //return cell } var imageURL:String?=nil if (retrievedVideo != nil){ imageURL=unfold(retrievedVideo, instructions: ["images",["lsr","wss","cvr","lss","wsr","pss","pns",""],["lg","md","sm","xs",""]]) as? String } let size=CGSize(width: 1,height: 1) UIGraphicsBeginImageContextWithOptions(size, true, 0) UIColor.whiteColor().setFill() UIRectFill(CGRectMake(0, 0, size.width, size.height)) //var image=UIGraphicsGetImageFromCurrentImageContext() //UIGraphicsEndImageContext() let imageView=UIImageView(frame: cell.bounds) cell.contentView.addSubview(imageView) //imageView.image=image if (imageURL != nil){ fetchDataUsingCache(imageURL!, downloaded: { dispatch_async(dispatch_get_main_queue()) { let image=imageUsingCache(imageURL!) var ratio=(image?.size.width)!/(image?.size.height)! imageView.frame=CGRect(x: (cell.frame.size.width-((cell.frame.size.height-60)*ratio))/2, y: 0, width: (cell.frame.size.height-60)*ratio, height: (cell.frame.size.height-60)) if (image?.size.width>(image!.size.height)){ ratio=(image?.size.height)!/(image?.size.width)! imageView.frame=CGRect(x: 0, y: 0, width: cell.frame.size.width, height: cell.frame.size.width*ratio) } imageView.image=image imageView.frame=CGRect(x: (cell.frame.size.width-imageView.frame.size.width)/2, y: (cell.frame.size.height-imageView.frame.size.height)/2, width: imageView.frame.size.width, height: imageView.frame.size.height) UIView.animateWithDuration(0.5, animations: { imageView.alpha=1 }) imageView.adjustsImageWhenAncestorFocused = true } }) } imageView.alpha=0 imageView.userInteractionEnabled = true imageView.layer.cornerRadius=5 cell.contentView.addSubview(label) return cell } func collectionView(collectionView: UICollectionView, shouldUpdateFocusInContext context: UICollectionViewFocusUpdateContext) -> Bool { /* This method provides the blue highlighting to the cells and sets variable selectedSlideShow:Bool. If selectedSlideShow==true (AKA the user is interacting with the slideshow) then the slide show will not roll to next slide. */ if (context.previouslyFocusedView?.superview?.isKindOfClass(MODSubcategoryCollectionView.self) == true && subcategoryCollectionViews.contains(context.previouslyFocusedView?.superview as! MODSubcategoryCollectionView) && context.previouslyFocusedIndexPath != nil){ (context.previouslyFocusedView?.superview as! MODSubcategoryCollectionView).cellShouldLoseFocus(context.previouslyFocusedView!, indexPath: context.previouslyFocusedIndexPath!) } if (context.nextFocusedView?.superview?.isKindOfClass(MODSubcategoryCollectionView.self) == true && subcategoryCollectionViews.contains(context.nextFocusedView?.superview as! MODSubcategoryCollectionView) && context.nextFocusedIndexPath != nil){ (context.nextFocusedView?.superview as! MODSubcategoryCollectionView).cellShouldFocus(context.nextFocusedView!, indexPath: context.nextFocusedIndexPath!) self.scrollView.scrollRectToVisible((context.nextFocusedView?.superview?.frame)!, animated: true) } return true } func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { /* let category="VideoOnDemand" let categoriesDirectory=base+"/"+version+"/categories/"+languageCode let categoryDataURL=categoriesDirectory+"/"+category+"?detailed=1" categoryToGoTo=unfold(categoryDataURL+"|category|subcategories|\(indexPath.row)|key") as! String print("category to go to \(categoryToGoTo)")*/ var indexPathRow=indexPath.row if (subcategoryCollectionViews.indexOf(collectionView as! MODSubcategoryCollectionView)! == 0){ indexPathRow-- if (indexPath.row==0){ self.performSegueWithIdentifier("presentStreaming", sender: self) } } let categoriesDirectory=base+"/"+version+"/categories/"+languageCode let categoryDataURL=categoriesDirectory+"/"+category+"?detailed=1" let player=SuperMediaPlayer() player.updatePlayerUsingDictionary(unfold("\(categoryDataURL)|category|subcategories|\(subcategoryCollectionViews.indexOf(collectionView as! MODSubcategoryCollectionView)!)|media|\(indexPathRow)") as! NSDictionary) player.playIn(self) return true } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSize(width: 560/1.05, height: 360/1.05)//588,378 } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { /* This method is used to pass data to other ViewControllers that are being presented. Currently the only data needed to be sent is the channel ID selected in ChannelSelector. This passes the information on what channel to watch. */ if (segue.destinationViewController.isKindOfClass(StreamingViewController.self)){ (segue.destinationViewController as! StreamingViewController).streamID=categoryIndex } } @IBOutlet weak var topImageTopPosition: NSLayoutConstraint! func scrollViewDidScroll(scrollView: UIScrollView) { print(scrollView.contentOffset.y) UIView.animateWithDuration(0.01, animations: { self.topImageTopPosition?.constant = min(0, -scrollView.contentOffset.y / 2.0) }) // only when scrolling down so we never let it be higher than 0 if (scrollView.isKindOfClass(SuperCollectionView.self)){ (scrollView as! SuperCollectionView).didScroll() } } }
mit
3b6a7a37282ef3130fe32cf1d53768e4
44.4197
271
0.588468
5.480879
false
false
false
false
tanweirush/TodayHistory
TodayHistory/view/THLoaddingPage.swift
1
3740
// // THLoaddingPage.swift // TodayHistory // // Created by 谭伟 on 15/9/11. // Copyright (c) 2015年 谭伟. All rights reserved. // import UIKit protocol HolderViewDelegate:class { func animateOver() } class THLoaddingPage: UIView { let ovalLayer = OvalLayer() let triangleLayer = TriangleLayer() let redRectangleLayer = RectangleLayer() let blueRectangleLayer = RectangleLayer() let arcLayer = ArcLayer() var parentFrame :CGRect = CGRectZero weak var delegate:HolderViewDelegate? override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clearColor() } required init?(coder: NSCoder) { super.init(coder: coder) } func addOval() { layer.addSublayer(ovalLayer) ovalLayer.expand() NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: "wobbleOval", userInfo: nil, repeats: false) } func wobbleOval() { layer.addSublayer(triangleLayer) ovalLayer.wobble() NSTimer.scheduledTimerWithTimeInterval(0.9, target: self, selector: "drawAnimatedTriangle", userInfo: nil, repeats: false) } func drawAnimatedTriangle() { triangleLayer.animate() NSTimer.scheduledTimerWithTimeInterval(0.9, target: self, selector: "spinAndTransform", userInfo: nil, repeats: false) } func spinAndTransform() { // 1 layer.anchorPoint = CGPointMake(0.5, 0.6) // 2 let rotationAnimation: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z") rotationAnimation.toValue = CGFloat(M_PI * 2.0) rotationAnimation.duration = 0.45 rotationAnimation.removedOnCompletion = true layer.addAnimation(rotationAnimation, forKey: nil) // 3 ovalLayer.contract() NSTimer.scheduledTimerWithTimeInterval(0.45, target: self, selector: "drawRedAnimatedRectangle", userInfo: nil, repeats: false) NSTimer.scheduledTimerWithTimeInterval(0.65, target: self, selector: "drawBlueAnimatedRectangle", userInfo: nil, repeats: false) } func drawRedAnimatedRectangle() { layer.addSublayer(redRectangleLayer) redRectangleLayer.animateStrokeWithColor(Colors.red) } func drawBlueAnimatedRectangle() { layer.addSublayer(blueRectangleLayer) blueRectangleLayer.animateStrokeWithColor(Colors.blue) NSTimer.scheduledTimerWithTimeInterval(0.40, target: self, selector: "drawArc", userInfo: nil, repeats: false) } func drawArc() { layer.addSublayer(arcLayer) arcLayer.animate() NSTimer.scheduledTimerWithTimeInterval(0.90, target: self, selector: "expandView", userInfo: nil, repeats: false) } func expandView() { // 1 backgroundColor = Colors.blue // 2 frame = CGRectMake(frame.origin.x - blueRectangleLayer.lineWidth, frame.origin.y - blueRectangleLayer.lineWidth, frame.size.width + blueRectangleLayer.lineWidth * 2, frame.size.height + blueRectangleLayer.lineWidth * 2) // 3 layer.sublayers = nil // 4 UIView.animateWithDuration(0.3, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.frame = self.parentFrame }, completion: { finished in self.addLabel() }) } func addLabel() { delegate?.animateOver() } }
mit
006b5e969d99e50d1c98db7471330da1
28.603175
99
0.614209
4.751592
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/next-permutation.swift
2
2401
/** * https://leetcode.com/problems/next-permutation/ * * */ /** Approach 2: Single Pass Approach Algorithm First, we observe that for any given sequence that is in descending order, no next larger permutation is possible. For example, no next permutation is possible for the following array: [9, 5, 4, 3, 1] We need to find the first pair of two successive numbers a[i] and a[i−1], from the right, which satisfy a[i]>a[i−1]. Now, no rearrangements to the right of a[i−1] can create a larger permutation since that subarray consists of numbers in descending order. Thus, we need to rearrange the numbers to the right of a[i−1] including itself. Now, what kind of rearrangement will produce the next larger number? We want to create the permutation just larger than the current one. Therefore, we need to replace the number a[i−1] with the number which is just larger than itself among the numbers lying to its right section, say a[j]. Next Permutation We swap the numbers a[i−1] and a[j]. We now have the correct number at index i−1. But still the current permutation isn't the permutation that we are looking for. We need the smallest permutation that can be formed by using the numbers only to the right of a[i−1]. Therefore, we need to place those numbers in ascending order to get their smallest permutation. But, recall that while scanning the numbers from the right, we simply kept decrementing the index until we found the pair a[i] and a[i−1] where, a[i]>a[i−1]. Thus, all numbers to the right of a[i−1] were already sorted in descending order. Furthermore, swapping a[i−1] and a[j] didn't change that order. Therefore, we simply need to reverse the numbers following a[i−1] to get the next smallest lexicographic permutation. */ class Solution { func nextPermutation(_ nums: inout [Int]) { var i = nums.count - 2 while i >= 0 { if nums[i] < nums[i + 1] { break } i -= 1 } if i < 0 { // Last permutation. nums.sort() return } var j = nums.count - 1 while j > i { if nums[j] > nums[i] { break } j -= 1 } nums.swapAt(i, j) i += 1 j = nums.count - 1 while i < j { nums.swapAt(i, j) i += 1 j -= 1 } } }
mit
b16aecf0861ec1353f9f3f4b6f3ce266
42.181818
422
0.648842
3.836834
false
false
false
false
zhangjk4859/MyWeiBoProject
sinaWeibo/sinaWeibo/Classes/NewFeatureController/JKNewfeatureVC.swift
1
5459
// // JKNewfeatureVC.swift // sinaWeibo // // Created by 张俊凯 on 16/7/7. // Copyright © 2016年 张俊凯. All rights reserved. // import UIKit //重用标识 private let reuseIdentifier = "reuseIdentifier" class JKNewfeatureVC: UICollectionViewController { /// 页面个数 private let pageCount = 4 /// 布局对象 private var layout: UICollectionViewFlowLayout = NewfeatureLayout() init(){ super.init(collectionViewLayout: layout) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() //NewfeatureCell.self = [NewfeatureCell class] collectionView?.registerClass(NewfeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier) // Do any additional setup after loading the view. } // MARK: UICollectionViewDataSource // 几个cell override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return pageCount } // 返回对应indexPath的cell override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // 1.获取cell let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewfeatureCell // 2.设置cell的数据 cell.imageIndex = indexPath.item // 3.返回cell return cell } // cell完全显示出来调用的方法 override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { // 让最后一个cell执行动画,显示按钮 let path = collectionView.indexPathsForVisibleItems().last! if path.item == (pageCount - 1) { let cell = collectionView.cellForItemAtIndexPath(path) as! NewfeatureCell cell.startBtnAnimation() } } // 自定义的类 class NewfeatureCell: UICollectionViewCell { //在同一文件中,即使是private 也可以被访问 private var imageIndex:Int? { didSet{ iconView.image = UIImage(named: "new_feature_\(imageIndex! + 1)") } } override init(frame: CGRect) { super.init(frame: frame) // 1.初始化UI setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { contentView.addSubview(iconView) contentView.addSubview(startButton) iconView.jk_Fill(contentView) startButton.jk_AlignInner(type: JK_AlignType.BottomCenter, referView: contentView, size: nil, offset: CGPoint(x: 0, y: -160)) } //按钮出现的时候来一个弹簧动画 func startBtnAnimation() { startButton.hidden = false // 执行动画 startButton.transform = CGAffineTransformMakeScale(0.0, 0.0) startButton.userInteractionEnabled = false // UIViewAnimationOptions(rawValue: 0) == OC knilOptions UIView.animateWithDuration(2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in // 清空形变 self.startButton.transform = CGAffineTransformIdentity }, completion: { (_) -> Void in self.startButton.userInteractionEnabled = true }) } //按钮点击进入主页 func customBtnClick() { print("-----") NSNotificationCenter.defaultCenter().postNotificationName(JKSwitchRootVCNotification, object: true) } // MARK: - 懒加载 private lazy var iconView = UIImageView() //cell上加一个按钮 private lazy var startButton: UIButton = { let btn = UIButton() btn.setBackgroundImage(UIImage(named: "new_feature_button"), forState: UIControlState.Normal) btn.setBackgroundImage(UIImage(named: "new_feature_button_highlighted"), forState: UIControlState.Highlighted) btn.hidden = true btn.addTarget(self, action: #selector(NewfeatureCell.customBtnClick), forControlEvents: UIControlEvents.TouchUpInside) return btn }() } private class NewfeatureLayout: UICollectionViewFlowLayout { override func prepareLayout() { // 1.设置layout布局,大小,间距,滚动方向 itemSize = UIScreen.mainScreen().bounds.size minimumInteritemSpacing = 0 minimumLineSpacing = 0 scrollDirection = UICollectionViewScrollDirection.Horizontal // 2.设置collectionView的属性 collectionView?.showsHorizontalScrollIndicator = false collectionView?.bounces = false collectionView?.pagingEnabled = true } } }
mit
896ec73242aace899a7cbce1fa10c45c
29.60355
181
0.604408
5.579288
false
false
false
false
lorentey/swift
tools/SourceKit/tools/swift-lang/SourceKitdResponse.swift
13
9708
//===--------------------- SourceKitdResponse.swift -----------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This file provides convenient APIs to interpret a SourceKitd response. //===----------------------------------------------------------------------===// import Foundation import sourcekitd public class SourceKitdResponse: CustomStringConvertible { public struct Dictionary: CustomStringConvertible, CustomReflectable { // The lifetime of this sourcekitd_variant_t is tied to the response it came // from, so keep a reference to the response too. private let dict: sourcekitd_variant_t private let context: SourceKitdResponse public init(dict: sourcekitd_variant_t, context: SourceKitdResponse) { assert(sourcekitd_variant_get_type(dict).rawValue == SOURCEKITD_VARIANT_TYPE_DICTIONARY.rawValue) self.dict = dict self.context = context } public func getString(_ key: SourceKitdUID) -> String { let value = sourcekitd_variant_dictionary_get_string(dict, key.uid)! return String(cString: value) } public func getInt(_ key: SourceKitdUID) -> Int { let value = sourcekitd_variant_dictionary_get_int64(dict, key.uid) return Int(value) } public func getBool(_ key: SourceKitdUID) -> Bool { let value = sourcekitd_variant_dictionary_get_bool(dict, key.uid) return value } public func getUID(_ key: SourceKitdUID) -> SourceKitdUID { let value = sourcekitd_variant_dictionary_get_uid(dict, key.uid)! return SourceKitdUID(uid: value) } public func getArray(_ key: SourceKitdUID) -> Array { let value = sourcekitd_variant_dictionary_get_value(dict, key.uid) return Array(arr: value, context: context) } public func getDictionary(_ key: SourceKitdUID) -> Dictionary { let value = sourcekitd_variant_dictionary_get_value(dict, key.uid) return Dictionary(dict: value, context: context) } public func getData(_ key: SourceKitdUID) -> Data { let value = sourcekitd_variant_dictionary_get_value(dict, key.uid) let size = sourcekitd_variant_data_get_size(value) guard let ptr = sourcekitd_variant_data_get_ptr(value), size > 0 else { return Data() } return Data(bytes: ptr, count: size) } public func getOptional(_ key: SourceKitdUID) -> Variant? { let value = sourcekitd_variant_dictionary_get_value(dict, key.uid) if sourcekitd_variant_get_type(value).rawValue == SOURCEKITD_VARIANT_TYPE_NULL.rawValue { return nil } return Variant(val: value, context: context) } public var description: String { return dict.description } public var customMirror: Mirror { return Mirror(self, children: [:]) } } public struct Array: CustomStringConvertible { // The lifetime of this sourcekitd_variant_t is tied to the response it came // from, so keep a reference to the response too. private let arr: sourcekitd_variant_t private let context: SourceKitdResponse public var count: Int { let count = sourcekitd_variant_array_get_count(arr) return Int(count) } public init(arr: sourcekitd_variant_t, context: SourceKitdResponse) { assert(sourcekitd_variant_get_type(arr).rawValue == SOURCEKITD_VARIANT_TYPE_ARRAY.rawValue) self.arr = arr self.context = context } public func getString(_ index: Int) -> String { let value = sourcekitd_variant_array_get_string(arr, index)! return String(cString: value) } public func getInt(_ index: Int) -> Int { let value = sourcekitd_variant_array_get_int64(arr, index) return Int(value) } public func getBool(_ index: Int) -> Bool { let value = sourcekitd_variant_array_get_bool(arr, index) return value } public func getUID(_ index: Int) -> SourceKitdUID { let value = sourcekitd_variant_array_get_uid(arr, index)! return SourceKitdUID(uid: value) } public func getArray(_ index: Int) -> Array { let value = sourcekitd_variant_array_get_value(arr, index) return Array(arr: value, context: context) } public func getDictionary(_ index: Int) -> Dictionary { let value = sourcekitd_variant_array_get_value(arr, index) return Dictionary(dict: value, context: context) } public func enumerate(_ applier: (_ index: Int, _ value: Variant) -> Bool) { // The block passed to sourcekit_variant_array_apply() does not actually // escape, it's synchronous and not called after returning. let context = self.context withoutActuallyEscaping(applier) { escapingApplier in _ = sourcekitd_variant_array_apply(arr) { (index, elem) -> Bool in return escapingApplier(Int(index), Variant(val: elem, context: context)) } } } public var description: String { return arr.description } } public struct Variant: CustomStringConvertible { // The lifetime of this sourcekitd_variant_t is tied to the response it came // from, so keep a reference to the response too. private let val: sourcekitd_variant_t fileprivate let context: SourceKitdResponse fileprivate init(val: sourcekitd_variant_t, context: SourceKitdResponse) { self.val = val self.context = context } public func getString() -> String { let value = sourcekitd_variant_string_get_ptr(val)! let length = sourcekitd_variant_string_get_length(val) return fromCStringLen(value, length: length)! } public func getStringBuffer() -> UnsafeBufferPointer<Int8> { return UnsafeBufferPointer(start: sourcekitd_variant_string_get_ptr(val), count: sourcekitd_variant_string_get_length(val)) } public func getInt() -> Int { let value = sourcekitd_variant_int64_get_value(val) return Int(value) } public func getBool() -> Bool { let value = sourcekitd_variant_bool_get_value(val) return value } public func getUID() -> SourceKitdUID { let value = sourcekitd_variant_uid_get_value(val)! return SourceKitdUID(uid:value) } public func getArray() -> Array { return Array(arr: val, context: context) } public func getDictionary() -> Dictionary { return Dictionary(dict: val, context: context) } public func getData() -> Data { let size = sourcekitd_variant_data_get_size(val) guard let ptr = sourcekitd_variant_data_get_ptr(val), size > 0 else { return Data() } return Data(bytes: ptr, count: size) } public var description: String { return val.description } } private let resp: sourcekitd_response_t public var value: Dictionary { return Dictionary(dict: sourcekitd_response_get_value(resp), context: self) } /// Copies the raw bytes of the JSON description of this documentation item. /// The caller is responsible for freeing the associated memory. public func copyRawJSONDocumentation() -> UnsafeMutablePointer<Int8>? { return sourcekitd_variant_json_description_copy( sourcekitd_response_get_value(resp)) } /// Whether or not this response represents an error. public var isError: Bool { return sourcekitd_response_is_error(resp) } /// Whether or not this response represents a notification. public var isNotification: Bool { return value.getOptional(.key_Notification) != nil } /// Whether or not this response represents a connection interruption error. public var isConnectionInterruptionError: Bool { return sourcekitd_response_is_error(resp) && sourcekitd_response_error_get_kind(resp) == SOURCEKITD_ERROR_CONNECTION_INTERRUPTED } /// Whether or not this response represents a compiler crash. public var isCompilerCrash: Bool { guard let notification = value.getOptional(.key_Notification)?.getUID() else { return false } return notification == .compilerCrashedNotification } /// If this is a document update notification, returns the name of the /// document to which this update applies. Otherwise, returns `nil`. public var documentUpdateNotificationDocumentName: String? { let response = value guard let notification = response.getOptional(.key_Notification)?.getUID(), notification == .source_notification_editor_documentupdate else { return nil } return response.getOptional(.key_Name)?.getString() } public init(resp: sourcekitd_response_t) { self.resp = resp } deinit { sourcekitd_response_dispose(resp) } public var description: String { let utf8Str = sourcekitd_response_description_copy(resp)! let result = String(cString: utf8Str) free(utf8Str) return result } } extension sourcekitd_variant_t: CustomStringConvertible { public var description: String { let utf8Str = sourcekitd_variant_description_copy(self)! let result = String(cString: utf8Str) free(utf8Str) return result } } private func fromCStringLen(_ ptr: UnsafePointer<Int8>, length: Int) -> String? { return String(decoding: Array(UnsafeBufferPointer(start: ptr, count: length)).map { UInt8(bitPattern: $0) }, as: UTF8.self) }
apache-2.0
8eee5629d2524bafe450db4199c3327d
32.591696
85
0.667285
4.291777
false
false
false
false
alblue/swift
test/attr/attr_implements_fp.swift
2
3253
// RUN: %empty-directory(%t) // RUN: echo 'main()' >%t/main.swift // RUN: %target-swiftc_driver -o %t/a.out %s %t/main.swift // RUN: %target-codesign %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s // REQUIRES: executable_test // This is a more-thorough and explicit test for rdar://43804798 that uses @_implements to // achieve "Comparable Floating Point values are FP-like when known to be FP, Comparable-like // when only known to be comparable". // Could calls to the different comparison operators. public var comparedAsComparablesCount : Int = 0 public var comparedAsFauxtsCount : Int = 0 public protocol FauxtingPoint : Comparable { static var nan: Self { get } static var one: Self { get } static var two: Self { get } } public protocol BinaryFauxtingPoint: FauxtingPoint { var bitPattern: UInt8 { get } } public extension BinaryFauxtingPoint { // This version of < will be called in a context that only knows it has a Comparable. @_implements(Comparable, <(_:_:)) static func _ComparableLessThan(_ lhs: Fauxt, _ rhs: Fauxt) -> Bool { print("compared as Comparables") comparedAsComparablesCount += 1 return lhs.bitPattern < rhs.bitPattern } } public enum State { case Nan case One case Two } public struct Fauxt { let state: State init(_ s: State) { state = s } public static var nan: Fauxt { return Fauxt(State.Nan) } public static var one: Fauxt { return Fauxt(State.One) } public static var two: Fauxt { return Fauxt(State.Two) } } extension Fauxt: BinaryFauxtingPoint { // Requirement from BinaryFauxtingPoint public var bitPattern: UInt8 { switch state { case .One: return 1 case .Two: return 2 case .Nan: return 0xff } } } public extension Fauxt { // This version of < will be called in a context that knows it has a Fauxt. // It is inside an extension of Fauxt rather than the declaration of Fauxt // itself in order to avoid a warning about near-matches with the defaulted // requirement from Comparable.< up above. static func <(_ lhs: Fauxt, _ rhs: Fauxt) -> Bool { print("compared as Fauxts") comparedAsFauxtsCount += 1 if lhs.state == .Nan || rhs.state == .Nan { return false } else { return lhs.bitPattern < rhs.bitPattern } } } public func compare_Comparables<T:Comparable>(_ x: T, _ y: T) -> Bool { return x < y } public func compare_Fauxts(_ x: Fauxt, _ y: Fauxt) -> Bool { return x < y } public func main() { assert(compare_Comparables(Fauxt.one, Fauxt.two)) assert(comparedAsComparablesCount == 1) // CHECK: compared as Comparables assert(compare_Comparables(Fauxt.one, Fauxt.nan)) assert(comparedAsComparablesCount == 2) // CHECK: compared as Comparables assert(!compare_Comparables(Fauxt.nan, Fauxt.one)) assert(comparedAsComparablesCount == 3) // CHECK: compared as Comparables assert(compare_Fauxts(Fauxt.one, Fauxt.two)) assert(comparedAsFauxtsCount == 1) // CHECK: compared as Fauxts assert(!compare_Fauxts(Fauxt.one, Fauxt.nan)) assert(comparedAsFauxtsCount == 2) // CHECK: compared as Fauxts assert(!compare_Fauxts(Fauxt.nan, Fauxt.one)) assert(comparedAsFauxtsCount == 3) // CHECK: compared as Fauxts }
apache-2.0
41ce7a3d814606a51586b86a35510ac7
27.043103
93
0.687366
3.309257
false
false
false
false
azadibogolubov/InterestDestroyer
iOS Version/Interest Destroyer/Charts/Classes/Renderers/ChartYAxisRendererRadarChart.swift
19
7600
// // ChartYAxisRendererRadarChart.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class ChartYAxisRendererRadarChart: ChartYAxisRenderer { private weak var _chart: RadarChartView! public init(viewPortHandler: ChartViewPortHandler, yAxis: ChartYAxis, chart: RadarChartView) { super.init(viewPortHandler: viewPortHandler, yAxis: yAxis, transformer: nil) _chart = chart } public override func computeAxis(yMin yMin: Double, yMax: Double) { computeAxisValues(min: yMin, max: yMax) } internal override func computeAxisValues(min yMin: Double, max yMax: Double) { let labelCount = _yAxis.labelCount let range = abs(yMax - yMin) if (labelCount == 0 || range <= 0) { _yAxis.entries = [Double]() return } let rawInterval = range / Double(labelCount) var interval = ChartUtils.roundToNextSignificant(number: Double(rawInterval)) let intervalMagnitude = pow(10.0, round(log10(interval))) let intervalSigDigit = Int(interval / intervalMagnitude) if (intervalSigDigit > 5) { // Use one order of magnitude higher, to avoid intervals like 0.9 or // 90 interval = floor(10 * intervalMagnitude) } // force label count if _yAxis.isForceLabelsEnabled { let step = Double(range) / Double(labelCount - 1) if _yAxis.entries.count < labelCount { // Ensure stops contains at least numStops elements. _yAxis.entries.removeAll(keepCapacity: true) } else { _yAxis.entries = [Double]() _yAxis.entries.reserveCapacity(labelCount) } var v = yMin for (var i = 0; i < labelCount; i++) { _yAxis.entries.append(v) v += step } } else { // no forced count // clean old values if (_yAxis.entries.count > 0) { _yAxis.entries.removeAll(keepCapacity: false) } // if the labels should only show min and max if (_yAxis.isShowOnlyMinMaxEnabled) { _yAxis.entries = [Double]() _yAxis.entries.append(yMin) _yAxis.entries.append(yMax) } else { let rawCount = Double(yMin) / interval var first = rawCount < 0.0 ? floor(rawCount) * interval : ceil(rawCount) * interval; if (first < yMin && _yAxis.isStartAtZeroEnabled) { // Force the first label to be at the 0 (or smallest negative value) first = yMin } if (first == 0.0) { // Fix for IEEE negative zero case (Where value == -0.0, and 0.0 == -0.0) first = 0.0 } let last = ChartUtils.nextUp(floor(Double(yMax) / interval) * interval) var f: Double var i: Int var n = 0 for (f = first; f <= last; f += interval) { ++n } if (isnan(_yAxis.customAxisMax)) { n += 1 } if (_yAxis.entries.count < n) { // Ensure stops contains at least numStops elements. _yAxis.entries = [Double](count: n, repeatedValue: 0.0) } for (f = first, i = 0; i < n; f += interval, ++i) { _yAxis.entries[i] = Double(f) } } } if !_yAxis.isStartAtZeroEnabled && _yAxis.entries[0] < yMin { // If startAtZero is disabled, and the first label is lower that the axis minimum, // Then adjust the axis minimum _yAxis.axisMinimum = _yAxis.entries[0] } _yAxis.axisMaximum = _yAxis.entries[_yAxis.entryCount - 1] _yAxis.axisRange = abs(_yAxis.axisMaximum - _yAxis.axisMinimum) } public override func renderAxisLabels(context context: CGContext?) { if (!_yAxis.isEnabled || !_yAxis.isDrawLabelsEnabled) { return } let labelFont = _yAxis.labelFont let labelTextColor = _yAxis.labelTextColor let center = _chart.centerOffsets let factor = _chart.factor let labelCount = _yAxis.entryCount let labelLineHeight = _yAxis.labelFont.lineHeight for (var j = 0; j < labelCount; j++) { if (j == labelCount - 1 && _yAxis.isDrawTopYLabelEntryEnabled == false) { break } let r = CGFloat(_yAxis.entries[j] - _yAxis.axisMinimum) * factor let p = ChartUtils.getPosition(center: center, dist: r, angle: _chart.rotationAngle) let label = _yAxis.getFormattedLabel(j) ChartUtils.drawText(context: context, text: label, point: CGPoint(x: p.x + 10.0, y: p.y - labelLineHeight), align: .Left, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]) } } public override func renderLimitLines(context context: CGContext?) { var limitLines = _yAxis.limitLines if (limitLines.count == 0) { return } CGContextSaveGState(context) let sliceangle = _chart.sliceAngle // calculate the factor that is needed for transforming the value to pixels let factor = _chart.factor let center = _chart.centerOffsets for (var i = 0; i < limitLines.count; i++) { let l = limitLines[i] CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor) CGContextSetLineWidth(context, l.lineWidth) if (l.lineDashLengths != nil) { CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } let r = CGFloat(l.limit - _chart.chartYMin) * factor CGContextBeginPath(context) for (var j = 0, count = _chart.data!.xValCount; j < count; j++) { let p = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(j) + _chart.rotationAngle) if (j == 0) { CGContextMoveToPoint(context, p.x, p.y) } else { CGContextAddLineToPoint(context, p.x, p.y) } } CGContextClosePath(context) CGContextStrokePath(context) } CGContextRestoreGState(context) } }
apache-2.0
fbf5ee219164b1cbf717bf47f17fd00b
30.151639
227
0.506842
5.100671
false
false
false
false
RealMeZJT/LogPocket
LogPocket/StandardPath.swift
1
1331
// // StandardPath.swift // LogPocket // // Created by TabZhou on 21/08/2017. // Copyright © 2017 ZJT. All rights reserved. // import Foundation //MARK: - StandardDirectory struct StandardDirectory : FileExplore { var logPocketHomeDir: URL { let dir = applicationSupportDir.appendingPathComponent("logpocket", isDirectory: true); createDirectoryIfNotExists(dir.path); return dir } var applicationSupportDir: URL { let fm = FileManager.default; let dirs = fm.urls(for: FileManager.SearchPathDirectory.applicationSupportDirectory, in: FileManager.SearchPathDomainMask.userDomainMask) let dir = dirs.first?.path ?? "" if (!directoryExists(atPath: dir)) { createDirectory(dir) } return URL(fileURLWithPath: dir) } } struct StandardLogFile : FileExplore { var uniqueFilePath: String { var fullPath = StandardDirectory().logPocketHomeDir let fileName = Date().description(with: Locale(identifier: "zh")) fullPath.appendPathComponent(fileName) var fullPathStr = fullPath.path if fileExists(atPath: fullPathStr) { fullPathStr.append(UUID().description) } fullPathStr.append(".txt") return fullPathStr } }
gpl-3.0
6989ebe034c7ad10f65824b78bb42aa6
27.297872
145
0.645865
4.75
false
false
false
false
bromas/Architect
UIArchitect/XibBasedView.swift
1
1465
// // ArchitectNibView.swift // LayoutArchitect // // Created by Brian Thomas on 8/2/14. // Copyright (c) 2014 Brian Thomas. All rights reserved. // import Foundation import UIKit public class XibBasedView : UIView { public var nibView : UIView? public override var backgroundColor : UIColor? { get { return nibView?.backgroundColor } set { nibView?.backgroundColor = newValue } } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInitialization() } override public init(frame: CGRect) { super.init(frame: frame) self.commonInitialization() } public init() { super.init(frame: CGRectZero) self.commonInitialization() } func commonInitialization () -> Void { self.backgroundColor = .clearColor() var stringToMessWith = NSStringFromClass(self.classForCoder) var classArray = stringToMessWith.componentsSeparatedByString(".") var classString = classArray.last if let className = classString { let views = NSBundle.mainBundle().loadNibNamed(className, owner: self, options: nil) assert(views.count > 0, "Could not find a nib to load") let possibleView = views.first as? UIView if let view = possibleView { self.nibView = view view.preppedForAutoLayout(inView: self) inset(view, with: [.Top: 0, .Right: 0, .Bottom: 0, .Left: 0]) } } } }
mit
b4f1b08faecfec40ef9b275e1906b755
23.416667
90
0.655973
4.234104
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/FacebookShare/Sources/Share/Dialogs/AppInvite/AppInvite.Dialog.swift
13
3882
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright notice shall be // included in all copies or substantial portions of the software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Foundation import UIKit import FBSDKShareKit extension AppInvite { /// A dialog to send app invites. public final class Dialog { fileprivate let sdkDialog: FBSDKAppInviteDialog fileprivate let sdkDelegate: SDKDelegate /// The invite to send. public let invite: AppInvite /** A UIViewController to present the dialog from. If not specified, the top most view controller will be automatically determined as best as possible. */ public var presentingViewController: UIViewController? { get { return sdkDialog.fromViewController } set { sdkDialog.fromViewController = newValue } } /// The completion handler to be invoked upon showing the dialog. public var completion: ((Result) -> Void)? { get { return sdkDelegate.completion } set { sdkDelegate.completion = newValue } } /** Create a dialog with an invite. - parameter invite: The invite to send. */ public init(invite: AppInvite) { sdkDialog = FBSDKAppInviteDialog() sdkDialog.content = invite.sdkInviteRepresentation sdkDelegate = SDKDelegate() sdkDelegate.setupAsDelegateFor(sdkDialog) self.invite = invite } /** Attempt to show the dialog modally. - throws: If the dialog fails to present. */ public func show() throws { var error: Error? let completionHandler = sdkDelegate.completion sdkDelegate.completion = { if case .failed(let resultError) = $0 { error = resultError } } sdkDialog.show() sdkDelegate.completion = completionHandler if let error = error { throw error } } /** Validates the contents of the reciever as valid. - throws: If the content is invalid. */ public func validate() throws { try sdkDialog.validate() } } } extension AppInvite.Dialog { /** Convenience method to show a `Dialog` with a `presentingViewController`, `invite`, and `completion`. - parameter viewController: The view controller to present from. - parameter invite: The invite to send. - parameter completion: The completion handler to invoke upon success. - throws: If the dialog fails to present. - returns: The dialog that has been presented. */ @discardableResult public static func show(from viewController: UIViewController, invite: AppInvite, completion: ((AppInvite.Result) -> Void)? = nil) throws -> Self { let dialog = self.init(invite: invite) dialog.presentingViewController = viewController dialog.completion = completion try dialog.show() return dialog } }
mit
3447fc4ed08a849010a315c2618157d4
29.809524
105
0.678259
4.834371
false
false
false
false
febus/HackingWithSwift
project9/Project7/DetailViewController.swift
20
885
// // DetailViewController.swift // Project7 // // Created by Hudzilla on 20/11/2014. // Copyright (c) 2014 Hudzilla. All rights reserved. // import UIKit import WebKit class DetailViewController: UIViewController { var webView: WKWebView! var detailItem: [String : String]! override func loadView() { webView = WKWebView() view = webView } override func viewDidLoad() { super.viewDidLoad() if let body = detailItem["body"] { var html = "<html>" html += "<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><style> body { font-size: 150%; } </style> </head>" html += "<body>" html += body html += "</body>" html += "</html>" webView.loadHTMLString(html, baseURL: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
unlicense
3fe6709aaa7bd50e89218d1e45e623f1
20.071429
141
0.661017
3.582996
false
false
false
false
Gitliming/Demoes
Demoes/Demoes/MyNote/MyNoteCell.swift
1
1477
// // MyNoteCell.swift // aha // // Created by xpming on 16/9/4. // Copyright © 2016年 Ledong. All rights reserved. // import UIKit import Foundation let notecell = "MyNoteCell" class MyNoteCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var selectedMark: UIImageView! @IBOutlet weak var titleLeading: NSLayoutConstraint! override func awakeFromNib() { super.awakeFromNib() backgroundColor = UIColor.clear } var isSelectedStatus: Bool = false{ didSet{ if !isEditingStatus{ return } if isSelectedStatus{ selectedMark.image = UIImage(named: "icon_selected") }else{ selectedMark.image = UIImage(named: "icon_unselect") } } } var isEditingStatus: Bool = false{ didSet{ selectedMark.isHidden = !isEditingStatus selectedMark.image = UIImage(named: "icon_unselect") if isEditingStatus { titleLeading.constant = 45 }else{ titleLeading.constant = 15 } } } var noteModel:MyNote? { didSet{ titleLabel.text = noteModel?.title guard let _ = noteModel?.createTime else{return} self.timeLabel.text = noteModel?.createTime } } }
apache-2.0
fe9a4c718382e3a17e45fb384c99eb12
23.983051
68
0.561737
4.679365
false
false
false
false
gnachman/iTerm2
SearchableComboListView/SearchableComboTableView.swift
2
658
// // SearchableComboTableView.swift // SearchableComboListView // // Created by George Nachman on 1/24/20. // import AppKit @objc(iTermSearchableComboTableView) class SearchableComboTableView: NSTableView { static let enterNotificationName = Notification.Name("SearchableComboTableView.Enter") private(set) var handlingKeyDown = false public override func keyDown(with event: NSEvent) { if event.characters == "\r" { delegate?.tableViewSelectionDidChange?(Notification(name: Self.enterNotificationName)) } handlingKeyDown = true super.keyDown(with: event) handlingKeyDown = false } }
gpl-2.0
8e32e00014cd0eab6b63a2980fb0e3ef
28.909091
98
0.712766
4.506849
false
false
false
false
apple/swift-async-algorithms
Sources/AsyncAlgorithms/AsyncAdjacentPairsSequence.swift
1
2523
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Async Algorithms open source project // // Copyright (c) 2022 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 // //===----------------------------------------------------------------------===// /// An `AsyncSequence` that iterates over the adjacent pairs of the original /// `AsyncSequence`. @frozen public struct AsyncAdjacentPairsSequence<Base: AsyncSequence>: AsyncSequence { public typealias Element = (Base.Element, Base.Element) @usableFromInline let base: Base @inlinable init(_ base: Base) { self.base = base } /// The iterator for an `AsyncAdjacentPairsSequence` instance. @frozen public struct Iterator: AsyncIteratorProtocol { public typealias Element = (Base.Element, Base.Element) @usableFromInline var base: Base.AsyncIterator @usableFromInline internal var previousElement: Base.Element? @inlinable init(_ base: Base.AsyncIterator) { self.base = base } @inlinable public mutating func next() async rethrows -> (Base.Element, Base.Element)? { if previousElement == nil { previousElement = try await base.next() } guard let previous = previousElement, let next = try await base.next() else { return nil } previousElement = next return (previous, next) } } @inlinable public func makeAsyncIterator() -> Iterator { Iterator(base.makeAsyncIterator()) } } extension AsyncSequence { /// An `AsyncSequence` that iterates over the adjacent pairs of the original /// original `AsyncSequence`. /// /// ``` /// for await (first, second) in (1...5).async.adjacentPairs() { /// print("First: \(first), Second: \(second)") /// } /// /// // First: 1, Second: 2 /// // First: 2, Second: 3 /// // First: 3, Second: 4 /// // First: 4, Second: 5 /// ``` /// /// - Returns: An `AsyncSequence` where the element is a tuple of two adjacent elements /// or the original `AsyncSequence`. @inlinable public func adjacentPairs() -> AsyncAdjacentPairsSequence<Self> { AsyncAdjacentPairsSequence(self) } } extension AsyncAdjacentPairsSequence: Sendable where Base: Sendable, Base.Element: Sendable { } @available(*, unavailable) extension AsyncAdjacentPairsSequence.Iterator: Sendable { }
apache-2.0
71128bf145bd6e18a34523dc77eef9b2
27.348315
95
0.631788
4.595628
false
false
false
false
chadaustin/sajson
swift/sajson/sajson.swift
2
13737
import Foundation // MARK: ValueReader /// Represents a JSON value decoded from the sajson AST. This type provides decoded access /// to array and object elements lazily. /// /// WARNING: Do NOT store these outside of your immediate parsing code - `ValueReader` /// accesses memory owned by the Document, and if the Document is deallocated before a /// ValueReader is used, Bad Things Will Happen. public enum ValueReader { case integer(Int32) case double(Float64) case null case bool(Bool) case string(String) case array(ArrayReader) case object(ObjectReader) // Deeply inflate this ValueReader into a typed Value. public var value: Value { switch self { case .integer(let i): return .integer(i) case .double(let d): return .double(d) case .null: return .null case .bool(let b): return .bool(b) case .string(let s): return .string(s) case .array(let reader): var result: [Value] = [] result.reserveCapacity(reader.count) for element in reader { result.append(element.value) } return .array(result) case .object(let reader): var result: [String: Value] = [:] for (key, element) in reader { result[key] = element.value } return .object(result) } } // Deeply inflate this ValueReader into an untyped Swift Any. public var valueAsAny: Any { switch self { case .integer(let i): return i case .double(let d): return d case .null: return NSNull() case .bool(let b): return b case .string(let s): return s case .array(let reader): var result: [Any] = [] result.reserveCapacity(reader.count) for element in reader { result.append(element.valueAsAny) } return result case .object(let reader): var result: [String: Any] = [:] for (key, element) in reader { result[key] = element.valueAsAny } return result } } } // Encapsulates logic required to read from an array. public struct ArrayReader: Sequence { fileprivate init(payload: UnsafePointer<UInt>, input: UnsafeBufferPointer<UInt8>) { self.payload = payload self.input = input } public subscript(i: Int)-> ValueReader { if i >= count { preconditionFailure("Index out of range: \(i)") } let element = payload[1 + i] let elementTag = UInt8(element & 7) let elementOffset = Int(element >> 3) return ASTNode(tag: elementTag, payload: payload.advanced(by: elementOffset), input: input).valueReader } public var count: Int { return Int(payload[0]) } // MARK: Sequence public struct Iterator: IteratorProtocol { fileprivate init(arrayReader: ArrayReader) { self.arrayReader = arrayReader } public mutating func next() -> ValueReader? { if currentIndex < arrayReader.count { let value = arrayReader[currentIndex] currentIndex += 1 return value } else { return nil } } private var currentIndex = 0 private let arrayReader: ArrayReader } public func makeIterator() -> ArrayReader.Iterator { return Iterator(arrayReader: self) } // MARK: Private private let payload: UnsafePointer<UInt> private let input: UnsafeBufferPointer<UInt8> } // Encapsulates logic required to read from an object. public struct ObjectReader: Sequence { fileprivate init(payload: UnsafePointer<UInt>, input: UnsafeBufferPointer<UInt8>) { self.payload = payload self.input = input } public var count: Int { return Int(payload[0]) } public subscript(i: Int) -> (String, ValueReader) { if i >= count { preconditionFailure("Index out of range: \(i)") } let start = Int(payload[1 + i * 3]) let end = Int(payload[2 + i * 3]) let value = Int(payload[3 + i * 3]) let key = decodeString(input, start, end) let valueTag = UInt8(value & 7) let valueOffset = Int(value >> 3) return (key, ASTNode(tag: valueTag, payload: payload.advanced(by: valueOffset), input: input).valueReader) } public subscript(key: String) -> ValueReader? { let objectLocation = sajson_find_object_key(payload, key, key.lengthOfBytes(using: .utf8), input.baseAddress!) if objectLocation >= count { return nil } let element = payload[3 + objectLocation * 3] let elementTag = UInt8(element & 7) let elementOffset = Int(element >> 3) return ASTNode(tag: elementTag, payload: payload.advanced(by: elementOffset), input: input).valueReader } /// Returns the object as a dictionary. Should generally be avoided, as it is less efficient than directly reading /// values. public func asDictionary() -> [String: ValueReader] { var result = [String: ValueReader](minimumCapacity: self.count) for i in 0..<self.count { let start = Int(payload[1 + i * 3]) let end = Int(payload[2 + i * 3]) let value = Int(payload[3 + i * 3]) let key = decodeString(input, start, end) let valueTag = UInt8(value & 7) let valueOffset = Int(value >> 3) result[key] = ASTNode(tag: valueTag, payload: payload.advanced(by: valueOffset), input: input).valueReader } return result } // MARK: Sequence public struct Iterator: IteratorProtocol { fileprivate init(objectReader: ObjectReader) { self.objectReader = objectReader } public mutating func next() -> (String, ValueReader)? { if currentIndex < objectReader.count { let value = objectReader[currentIndex] currentIndex += 1 return value } else { return nil } } private var currentIndex = 0 private let objectReader: ObjectReader } public func makeIterator() -> ObjectReader.Iterator { return Iterator(objectReader: self) } // MARK: Private private let payload: UnsafePointer<UInt> private let input: UnsafeBufferPointer<UInt8> } // MARK: Value /// Represents a fully-decoded JSON parse tree. This API is provided for convenience, but for /// optimal performance, consider using `ValueReader` instead. public enum Value { case integer(Int32) case double(Float64) case null case bool(Bool) case string(String) case array([Value]) case object([String: Value]) } // Internal type that represents a decodable sajson AST node. private struct ASTNode { // Keep this in sync with sajson::type private struct RawTag { static let integer: UInt8 = 0 static let double: UInt8 = 1 static let null: UInt8 = 2 static let bfalse: UInt8 = 3 static let btrue: UInt8 = 4 static let string: UInt8 = 5 static let array: UInt8 = 6 static let object: UInt8 = 7 } fileprivate init(tag: UInt8, payload: UnsafePointer<UInt>, input: UnsafeBufferPointer<UInt8>) { self.tag = tag self.payload = payload self.input = input } public var valueReader: ValueReader { switch tag { case RawTag.integer: // This syntax to read the bottom bits of a UInt as an Int32 is insane. return payload.withMemoryRebound(to: Int32.self, capacity: 1) { p in return .integer(p[0]) } case RawTag.double: if MemoryLayout<Int>.size == MemoryLayout<Int32>.size { let lo = UInt64(payload[0]) let hi = UInt64(payload[1]) let bitPattern = lo | (hi << 32) return .double(Float64(bitPattern: bitPattern)) } else { return .double(Float64(bitPattern: UInt64(payload[0]))) } case RawTag.null: return .null case RawTag.bfalse: return .bool(false) case RawTag.btrue: return .bool(true) case RawTag.string: let start = Int(payload[0]) let end = Int(payload[1]) return .string(decodeString(input, start, end)) case RawTag.array: return .array(ArrayReader(payload: payload, input: input)) case RawTag.object: return .object(ObjectReader(payload: payload, input: input)) default: fatalError("Unknown sajson value type - memory corruption detected?") } } // MARK: Private private let tag: UInt8 private let payload: UnsafePointer<UInt> private let input: UnsafeBufferPointer<UInt8> } // Internal function that, as cheaply as possible, converts an in-memory buffer // containing UTF-8 into a Swift string. private func decodeString(_ input: UnsafeBufferPointer<UInt8>, _ start: Int, _ end: Int) -> String { // TODO: are the following two lines a single copy? // Does it validate the correctness of the UTF-8 or can we force it to simply memcpy? let data = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: input.baseAddress!.advanced(by: start)), count: end - start, deallocator: .none) return String(data: data, encoding: .utf8)! } /// Represents a parsed JSON document and a handle to any referenced memory. public final class Document { internal init(doc: OpaquePointer!, input: Data) { self.doc = doc self.input = input let rootTag = sajson_get_root_tag(doc) let rootValuePaylod = sajson_get_root(doc)! let inputPointer = sajson_get_input(doc)! let inputLength = sajson_get_input_length(doc) self.rootNode = ASTNode( tag: rootTag, payload: rootValuePaylod, input: UnsafeBufferPointer(start: inputPointer, count: inputLength)) } deinit { sajson_free_document(doc) } /// Provides access to the root value reader of the JSON document. Using `ValueReader` /// is faster than `Value` because it avoids the need to construct intermediate Swift /// arrays and dictionaries. /// /// This function is structured as a closure rather than a property to prevent accidentally /// holding onto a `ValueReader` before the `Document` has been deallocated. public func withRootValueReader<T>(_ cb: (ValueReader) -> T) -> T { return cb(rootNode.valueReader) } /// Decodes the entire document into a Swift `Value` tree. /// This accessor is convenient, but for optimum performance, use `withRootValueReader` instead. var rootValue: Value { return withRootValueReader { rootReader in return rootReader.value } } // MARK: Private private let rootNode: ASTNode private let doc: OpaquePointer! private let input: Data // We need to hold onto the memory from the buffer we parsed } public final class ParseError: Error { internal init(line: Int, column: Int, message: String) { self.line = line self.column = column self.message = message } public let line: Int public let column: Int public let message: String } public enum AllocationStrategy { /// Allocates one machine word per byte in the input document. This mode is the fastest. case single /// Dynamically grows the AST buffer and parse stack at the cost of being about 10% slower. case dynamic } /// Parses an input document given a buffer of JSON data. For efficiency, this function /// mutates the given data. Use `parse(allocationStrategy:input:)` if you intend to use /// the passed buffer again. /// /// Throws `ParseError` on failure. public func parse(allocationStrategy: AllocationStrategy, mutating: inout Data) throws -> Document { let inputLength = mutating.count let dptr: OpaquePointer! = mutating.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<Int8>) in switch allocationStrategy { case .single: return sajson_parse_single_allocation(ptr, inputLength) case .dynamic: return sajson_parse_dynamic_allocation(ptr, inputLength) } } if dptr == nil { fatalError("Out of memory: failed to allocate document structure") } if sajson_has_error(dptr) != 0 { throw ParseError( line: sajson_get_error_line(dptr), column: sajson_get_error_column(dptr), message: String(cString: sajson_get_error_message(dptr))) } return Document(doc: dptr, input: mutating) } /// Parses an input document given a buffer of JSON data. /// /// Throws `ParseError` on failure. public func parse(allocationStrategy: AllocationStrategy, input: Data) throws -> Document { var copy = input return try parse(allocationStrategy: allocationStrategy, mutating: &copy) } /// Parses an input document given a String containing JSON. If you have binary data, it's /// more efficient to use `parse(allocationStrategy:input:)` or `parse(allocationStrategy:mutating:)` /// instead. /// /// Throws `ParseError` on failure. public func parse(allocationStrategy: AllocationStrategy, input: String) throws -> Document { var copy = input.data(using: .utf8)! return try parse(allocationStrategy: allocationStrategy, mutating: &copy) }
mit
ae404c2825dd46b4c1b25988ec29c3b3
32.586797
147
0.620878
4.424155
false
false
false
false
ReactiveCocoa/ReactiveSwift
Sources/Signal.swift
1
95248
import Foundation import Dispatch /// A push-driven stream that sends Events over time, parameterized by the type /// of values being sent (`Value`) and the type of failure that can occur /// (`Error`). If no failures should be possible, Never can be specified for /// `Error`. /// /// An observer of a Signal will see the exact same sequence of events as all /// other observers. In other words, events will be sent to all observers at the /// same time. /// /// Signals are generally used to represent event streams that are already “in /// progress,” like notifications, user input, etc. To represent streams that /// must first be _started_, see the SignalProducer type. /// /// A Signal is kept alive until either of the following happens: /// 1. its input observer receives a terminating event; or /// 2. it has no active observers, and is not being retained. public final class Signal<Value, Error: Swift.Error> { /// The `Signal` core which manages the event stream. /// /// A `Signal` is the externally retained shell of the `Signal` core. The separation /// enables an explicit metric for the `Signal` self-disposal in case of having no /// observer and no external retain. /// /// `Signal` ownership graph from the perspective of an operator. /// Note that there is no circular strong reference in the graph. /// ``` /// ------------ -------------- -------- /// | | | endObserve | | | /// | | <~~ weak ~~~ | disposable | <== strong === | | /// | | -------------- | | ... downstream(s) /// | Upstream | ------------ | | /// | Core | === strong ==> | Observer | === strong ==> | Core | /// ------------ ===\\ ------------ -------- ===\\ /// \\ ------------------ ^^ \\ /// \\ | Signal (shell) | === strong ==// \\ /// \\ ------------------ \\ /// || strong || strong /// vv vv /// ------------------- ------------------- /// | Other observers | | Other observers | /// ------------------- ------------------- /// ``` private let core: CoreBase private class CoreBase { func observe(_ observer: Observer) -> Disposable? { fatalError() } func signalDidDeinitialize() { fatalError() } } private final class Core<SendLock: LockProtocol>: CoreBase { /// The disposable associated with the signal. /// /// Disposing of `disposable` is assumed to remove the generator /// observer from its attached `Signal`, so that the generator observer /// as the last +1 retain of the `Signal` core may deinitialize. private let disposable: CompositeDisposable /// The state of the signal. private var state: State /// Used to ensure that all state accesses are serialized. private let stateLock: Lock /// Used to ensure that events are serialized during delivery to observers. private let sendLock: SendLock fileprivate init(_ generator: (Observer, Lifetime) -> Void) { state = .alive(Bag(), hasDeinitialized: false) stateLock = Lock.make() sendLock = SendLock.make() disposable = CompositeDisposable() super.init() // The generator observer retains the `Signal` core. generator(Observer(action: self.send, interruptsOnDeinit: true), Lifetime(disposable)) } @_specialize(kind: partial, where SendLock == Lock) @_specialize(kind: partial, where SendLock == NoLock) private func send(_ event: Event) { if event.isTerminating { // Recursive events are disallowed for `value` events, but are permitted // for termination events. Specifically: // // - `interrupted` // It can inadvertently be sent by downstream consumers as part of the // `SignalProducer` mechanics. // // - `completed` // If a downstream consumer weakly references an object, invocation of // such consumer may cause a race condition with its weak retain against // the last strong release of the object. If the `Lifetime` of the // object is being referenced by an upstream `take(during:)`, a // signal recursion might occur. // // So we would treat termination events specially. If it happens to // occur while the `sendLock` is acquired, the observer call-out and // the disposal would be delegated to the current sender, or // occasionally one of the senders waiting on `sendLock`. self.stateLock.lock() if case let .alive(observers, _) = state { self.state = .terminating(observers, .init(event)) self.stateLock.unlock() } else { self.stateLock.unlock() } tryToCommitTermination() } else { self.sendLock.lock() self.stateLock.lock() if case let .alive(observers, _) = self.state { self.stateLock.unlock() for observer in observers { observer.send(event) } } else { self.stateLock.unlock() } self.sendLock.unlock() // Check if the status has been bumped to `terminating` due to a // terminal event being sent concurrently or recursively. // // The check is deliberately made outside of the `sendLock` so that it // covers also any potential concurrent terminal event in one shot. // // Related PR: // https://github.com/ReactiveCocoa/ReactiveSwift/pull/112 // // While calling `tryToCommitTermination` is sufficient, this is a fast // path for the recurring value delivery. // // Note that this cannot be `try` since any concurrent observer bag // manipulation might then cause the terminating state being missed. stateLock.lock() if case .terminating = state { stateLock.unlock() tryToCommitTermination() } else { stateLock.unlock() } } } /// Observe the Signal by sending any future events to the given observer. /// /// - parameters: /// - observer: An observer to forward the events to. /// /// - returns: A `Disposable` which can be used to disconnect the observer, /// or `nil` if the signal has already terminated. fileprivate override func observe(_ observer: Observer) -> Disposable? { var token: Bag<Observer>.Token? stateLock.lock() if case let .alive(observers, hasDeinitialized) = state { var newObservers = observers token = newObservers.insert(observer) self.state = .alive(newObservers, hasDeinitialized: hasDeinitialized) } stateLock.unlock() if let token = token { return AnyDisposable { [weak self] in self?.removeObserver(with: token) } } else { observer.sendInterrupted() return nil } } /// Remove the observer associated with the given token. /// /// - parameters: /// - token: The token of the observer to remove. private func removeObserver(with token: Bag<Observer>.Token) { stateLock.lock() if case let .alive(observers, hasDeinitialized) = state { var newObservers = observers let observer = newObservers.remove(using: token) self.state = .alive(newObservers, hasDeinitialized: hasDeinitialized) // Ensure `observer` is deallocated after `stateLock` is // released to avoid deadlocks. withExtendedLifetime(observer) { // Start the disposal of the `Signal` core if the `Signal` has // deinitialized and there is no active observer. tryToDisposeSilentlyIfQualified(unlocking: stateLock) } } else { stateLock.unlock() } } /// Try to commit the termination, or in other words transition the signal from a /// terminating state to a terminated state. /// /// It fails gracefully if the signal is alive or has terminated. Calling this /// method as a result of a false positive `terminating` check is permitted. /// /// - precondition: `stateLock` must not be acquired by the caller. private func tryToCommitTermination() { // Acquire `stateLock`. If the termination has still not yet been // handled, take it over and bump the status to `terminated`. stateLock.lock() if case let .terminating(observers, terminationKind) = state { // Try to acquire the `sendLock`, and fail gracefully since the current // lock holder would attempt to commit after it is done anyway. if sendLock.try() { state = .terminated stateLock.unlock() if let event = terminationKind.materialize() { for observer in observers { observer.send(event) } } sendLock.unlock() disposable.dispose() return } } stateLock.unlock() } /// Try to dispose of the signal silently if the `Signal` has deinitialized and /// has no observer. /// /// It fails gracefully if the signal is terminating or terminated, has one or /// more observers, or has not deinitialized. /// /// - precondition: `stateLock` must have been acquired by the caller. /// /// - parameters: /// - stateLock: The `stateLock` acquired by the caller. private func tryToDisposeSilentlyIfQualified(unlocking stateLock: Lock) { assert(!stateLock.try(), "Calling `unconditionallyTerminate` without acquiring `stateLock`.") if case let .alive(observers, true) = state, observers.isEmpty { // Transition to `terminated` directly only if there is no event delivery // on going. if sendLock.try() { self.state = .terminated stateLock.unlock() sendLock.unlock() disposable.dispose() return } self.state = .terminating(Bag(), .silent) stateLock.unlock() tryToCommitTermination() return } stateLock.unlock() } /// Acknowledge the deinitialization of the `Signal`. fileprivate override func signalDidDeinitialize() { stateLock.lock() // Mark the `Signal` has now deinitialized. if case let .alive(observers, false) = state { state = .alive(observers, hasDeinitialized: true) } // Attempt to start the disposal of the signal if it has no active observer. tryToDisposeSilentlyIfQualified(unlocking: stateLock) } deinit { disposable.dispose() } } private init(_ core: CoreBase) { self.core = core } /// Initialize a Signal that will immediately invoke the given generator, /// then forward events sent to the given input observer. /// /// The input observer serializes events it received. In other words, it is thread safe, and /// can be called on multiple threads concurrently. /// /// - note: The disposable returned from the closure will be automatically /// disposed if a terminating event is sent to the observer. The /// Signal itself will remain alive until the observer is released. /// /// - parameters: /// - generator: A closure that accepts an implicitly created observer /// that will act as an event emitter for the signal. public convenience init(_ generator: (Observer, Lifetime) -> Void) { self.init(Core<Lock>(generator)) } /// Initialize a Signal that will immediately invoke the given generator, /// then forward events sent to the given non-serializing input observer. /// /// Unlike `init(_:)`, the provided input observer does not serialize the events it received, with the assumption /// that it can inherit mutual exclusion from its callers. /// /// Note that the created `Signal` still guarantees thread safe observer manipulation. /// /// - warning: The input observer **is not thread safe**. /// /// - note: The disposable returned from the closure will be automatically /// disposed if a terminating event is sent to the observer. The /// Signal itself will remain alive until the observer is released. /// /// - parameters: /// - generator: A closure that accepts an implicitly created observer /// that will act as an event emitter for the signal. public static func unserialized(_ generator: (Observer, Lifetime) -> Void) -> Signal { self.init(Core<NoLock>(generator)) } /// Initialize a Signal that will immediately invoke the given generator, /// then forward events sent to the given non-serializing, reentrant input observer. /// /// The provided input observer does not serialize the events it received — akin to `unserialized(_:)`. Meanwhile, /// it supports **reentrancy** via a queue drain strategy, which is otherwise unsupported in the default `Signal` /// variant. /// /// Recursively sent events are enqueued, and are drained first-in-first-out after the current event has completed /// calling out to all observers. /// /// Note that the created `Signal` still guarantees thread safe observer manipulation. /// /// - warning: The input observer **is not thread safe**. /// /// - note: The disposable returned from the closure will be automatically /// disposed if a terminating event is sent to the observer. The /// Signal itself will remain alive until the observer is released. /// /// - parameters: /// - generator: A closure that accepts an implicitly created observer /// that will act as an event emitter for the signal. public static func reentrantUnserialized(_ generator: (Observer, Lifetime) -> Void) -> Signal { self.init(Core<NoLock> { innerObserver, lifetime in var eventQueue: [Event] = [] var isInLoop = false let wrappedObserver = Observer { outerEvent in if !isInLoop { isInLoop = true innerObserver.send(outerEvent) while !eventQueue.isEmpty { innerObserver.send(eventQueue.removeLast()) } isInLoop = false } else { eventQueue.insert(outerEvent, at: 0) } } generator(wrappedObserver, lifetime) }) } /// Observe the Signal by sending any future events to the given observer. /// /// - note: If the Signal has already terminated, the observer will /// immediately receive an `interrupted` event. /// /// - parameters: /// - observer: An observer to forward the events to. /// /// - returns: A `Disposable` which can be used to disconnect the observer, /// or `nil` if the signal has already terminated. @discardableResult public func observe(_ observer: Observer) -> Disposable? { return core.observe(observer) } deinit { core.signalDidDeinitialize() } /// The state of a `Signal`. /// /// `SignalState` is guaranteed to be laid out as a tagged pointer by the Swift /// compiler in the support targets of the Swift 3.0.1 ABI. /// /// The Swift compiler has also an optimization for enums with payloads that are /// all reference counted, and at most one no-payload case. private enum State { // `TerminationKind` is constantly pointer-size large to keep `Signal.Core` // allocation size independent of the actual `Value` and `Error` types. enum TerminationKind { case completed case interrupted case failed(Swift.Error) case silent init(_ event: Event) { switch event { case .value: fatalError() case .interrupted: self = .interrupted case let .failed(error): self = .failed(error) case .completed: self = .completed } } func materialize() -> Event? { switch self { case .completed: return .completed case .interrupted: return .interrupted case let .failed(error): return .failed(error as! Error) case .silent: return nil } } } /// The `Signal` is alive. case alive(Bag<Observer>, hasDeinitialized: Bool) /// The `Signal` has received a termination event, and is about to be /// terminated. case terminating(Bag<Observer>, TerminationKind) /// The `Signal` has terminated. case terminated } } extension Signal { /// A Signal that never sends any events to its observers. public static var never: Signal { return self.init { observer, lifetime in // If `observer` deinitializes, the `Signal` would interrupt which is // undesirable for `Signal.never`. lifetime.observeEnded { _ = observer } } } /// A Signal that completes immediately without emitting any value. public static var empty: Signal { return self.init { observer, _ in observer.sendCompleted() } } /// Create a `Signal` that will be controlled by sending events to an /// input observer. /// /// The input observer serializes events it received. In other words, it is thread safe, and /// can be called on multiple threads concurrently. /// /// - note: The `Signal` will remain alive until a terminating event is sent /// to the input observer, or until it has no observers and there /// are no strong references to it. /// /// - parameters: /// - disposable: An optional disposable to associate with the signal, and /// to be disposed of when the signal terminates. /// /// - returns: A 2-tuple of the output end of the pipe as `Signal`, and the input end /// of the pipe as `Signal.Observer`. public static func pipe(disposable: Disposable? = nil) -> (output: Signal, input: Observer) { var observer: Observer! let signal = self.init { innerObserver, lifetime in observer = innerObserver lifetime += disposable } return (signal, observer) } /// Create a `Signal` that will be controlled by sending events to an /// non-serializing input observer. /// /// Unlike `init(_:)`, the provided input observer does not serialize the events it received, with the assumption /// that it can inherit mutual exclusion from its callers. /// /// Note that the created `Signal` still guarantees thread safe observer manipulation. /// /// - warning: The input observer **is not thread safe**. /// /// - note: The `Signal` will remain alive until a terminating event is sent /// to the input observer, or until it has no observers and there /// are no strong references to it. /// /// - parameters: /// - disposable: An optional disposable to associate with the signal, and /// to be disposed of when the signal terminates. /// /// - returns: A 2-tuple of the output end of the pipe as `Signal`, and the input end /// of the pipe as `Signal.Observer`. public static func unserializedPipe(disposable: Disposable? = nil) -> (output: Signal, input: Observer) { var observer: Observer! let signal = unserialized { innerObserver, lifetime in observer = innerObserver lifetime += disposable } return (signal, observer) } /// Create a `Signal` that will be controlled by sending events to an /// non-serializing, reentrant input observer. /// /// The provided input observer does not serialize the events it received — akin to `unserialized(_:)`. Meanwhile, /// it supports **reentrancy** via a queue drain strategy, which is otherwise unsupported in the default `Signal` /// variant. /// /// Recursively sent events are enqueued, and are drained first-in-first-out after the current event has completed /// calling out to all observers. /// /// Note that the created `Signal` still guarantees thread safe observer manipulation. /// /// - warning: The input observer **is not thread safe**. /// /// - note: The `Signal` will remain alive until a terminating event is sent /// to the input observer, or until it has no observers and there /// are no strong references to it. /// /// - parameters: /// - disposable: An optional disposable to associate with the signal, and /// to be disposed of when the signal terminates. /// /// - returns: A 2-tuple of the output end of the pipe as `Signal`, and the input end /// of the pipe as `Signal.Observer`. public static func reentrantUnserializedPipe(disposable: Disposable? = nil) -> (output: Signal, input: Observer) { var observer: Observer! let signal = reentrantUnserialized { innerObserver, lifetime in observer = innerObserver lifetime += disposable } return (signal, observer) } } public protocol SignalProtocol: AnyObject { /// The type of values being sent by `self`. associatedtype Value /// The type of error that can occur on `self`. associatedtype Error: Swift.Error /// The materialized `self`. var signal: Signal<Value, Error> { get } } extension Signal: SignalProtocol { public var signal: Signal<Value, Error> { return self } } extension Signal: SignalProducerConvertible { public var producer: SignalProducer<Value, Error> { return SignalProducer(self) } } extension Signal { /// Observe `self` for all events being emitted. /// /// - note: If `self` has terminated, the closure would be invoked with an /// `interrupted` event immediately. /// /// - parameters: /// - action: A closure to be invoked with every event from `self`. /// /// - returns: A disposable to detach `action` from `self`. `nil` if `self` has /// terminated. @discardableResult public func observe(_ action: @escaping Signal<Value, Error>.Observer.Action) -> Disposable? { return observe(Observer(action)) } /// Observe `self` for all values being emitted, and if any, the failure. /// /// - parameters: /// - action: A closure to be invoked with values from `self`, or the propagated /// error should any `failed` event is emitted. /// /// - returns: A disposable to detach `action` from `self`. `nil` if `self` has /// terminated. @discardableResult public func observeResult(_ action: @escaping (Result<Value, Error>) -> Void) -> Disposable? { return observe( Observer( value: { action(.success($0)) }, failed: { action(.failure($0)) } ) ) } /// Observe `self` for its completion. /// /// - parameters: /// - action: A closure to be invoked when a `completed` event is emitted. /// /// - returns: A disposable to detach `action` from `self`. `nil` if `self` has /// terminated. @discardableResult public func observeCompleted(_ action: @escaping () -> Void) -> Disposable? { return observe(Observer(completed: action)) } /// Observe `self` for its failure. /// /// - parameters: /// - action: A closure to be invoked with the propagated error, should any /// `failed` event is emitted. /// /// - returns: A disposable to detach `action` from `self`. `nil` if `self` has /// terminated. @discardableResult public func observeFailed(_ action: @escaping (Error) -> Void) -> Disposable? { return observe(Observer(failed: action)) } /// Observe `self` for its interruption. /// /// - note: If `self` has terminated, the closure would be invoked immediately. /// /// - parameters: /// - action: A closure to be invoked when an `interrupted` event is emitted. /// /// - returns: A disposable to detach `action` from `self`. `nil` if `self` has /// terminated. @discardableResult public func observeInterrupted(_ action: @escaping () -> Void) -> Disposable? { return observe(Observer(interrupted: action)) } } extension Signal where Error == Never { /// Observe `self` for all values being emitted. /// /// - parameters: /// - action: A closure to be invoked with values from `self`. /// /// - returns: A disposable to detach `action` from `self`. `nil` if `self` has /// terminated. @discardableResult public func observeValues(_ action: @escaping (Value) -> Void) -> Disposable? { return observe(Observer(value: action)) } } extension Signal { /// Perform an action upon every event from `self`. The action may generate zero or /// more events. /// /// - precondition: The action must be synchronous. /// /// - parameters: /// - transform: A closure that creates the said action from the given event /// closure. /// /// - returns: A signal that forwards events yielded by the action. internal func flatMapEvent<U, E>(_ transform: @escaping Event.Transformation<U, E>) -> Signal<U, E> { return Signal<U, E>.unserialized { output, lifetime in // Create an input sink whose events would go through the given // event transformation, and have the resulting events propagated // to the resulting `Signal`. let input = transform(output, lifetime) lifetime += self.observe(input.assumeUnboundDemand()) } } /// Map each value in the signal to a new value. /// /// - parameters: /// - transform: A closure that accepts a value from the `value` event and /// returns a new value. /// /// - returns: A signal that will send new values. public func map<U>(_ transform: @escaping (Value) -> U) -> Signal<U, Error> { return flatMapEvent(Signal.Event.map(transform)) } /// Map each value in the signal to a new constant value. /// /// - parameters: /// - value: A new value. /// /// - returns: A signal that will send new values. public func map<U>(value: U) -> Signal<U, Error> { return map { _ in value } } /// Map each value in the signal to a new value by applying a key path. /// /// - parameters: /// - keyPath: A key path relative to the signal's `Value` type. /// /// - returns: A signal that will send new values. public func map<U>(_ keyPath: KeyPath<Value, U>) -> Signal<U, Error> { return map { $0[keyPath: keyPath] } } /// Map errors in the signal to a new error. /// /// - parameters: /// - transform: A closure that accepts current error object and returns /// a new type of error object. /// /// - returns: A signal that will send new type of errors. public func mapError<F>(_ transform: @escaping (Error) -> F) -> Signal<Value, F> { return flatMapEvent(Signal.Event.mapError(transform)) } /// Maps each value in the signal to a new value, lazily evaluating the /// supplied transformation on the specified scheduler. /// /// - important: Unlike `map`, there is not a 1-1 mapping between incoming /// values, and values sent on the returned signal. If /// `scheduler` has not yet scheduled `transform` for /// execution, then each new value will replace the last one as /// the parameter to `transform` once it is finally executed. /// /// - parameters: /// - transform: The closure used to obtain the returned value from this /// signal's underlying value. /// /// - returns: A signal that sends values obtained using `transform` as this /// signal sends values. public func lazyMap<U>(on scheduler: Scheduler, transform: @escaping (Value) -> U) -> Signal<U, Error> { return flatMapEvent(Signal.Event.lazyMap(on: scheduler, transform: transform)) } /// Preserve only values which pass the given closure. /// /// - parameters: /// - isIncluded: A closure to determine whether a value from `self` should be /// included in the returned `Signal`. /// /// - returns: A signal that forwards the values passing the given closure. public func filter(_ isIncluded: @escaping (Value) -> Bool) -> Signal<Value, Error> { return flatMapEvent(Signal.Event.filter(isIncluded)) } /// Applies `transform` to values from `signal` and forwards values with non `nil` results unwrapped. /// - parameters: /// - transform: A closure that accepts a value from the `value` event and /// returns a new optional value. /// /// - returns: A signal that will send new values, that are non `nil` after the transformation. public func compactMap<U>(_ transform: @escaping (Value) -> U?) -> Signal<U, Error> { return flatMapEvent(Signal.Event.compactMap(transform)) } /// Applies `transform` to values from `signal` and forwards values with non `nil` results unwrapped. /// - parameters: /// - transform: A closure that accepts a value from the `value` event and /// returns a new optional value. /// /// - returns: A signal that will send new values, that are non `nil` after the transformation. @available(*, deprecated, renamed: "compactMap") public func filterMap<U>(_ transform: @escaping (Value) -> U?) -> Signal<U, Error> { return flatMapEvent(Signal.Event.compactMap(transform)) } } extension Signal where Value: OptionalProtocol { /// Unwrap non-`nil` values and forward them on the returned signal, `nil` /// values are dropped. /// /// - returns: A signal that sends only non-nil values. public func skipNil() -> Signal<Value.Wrapped, Error> { return flatMapEvent(Signal.Event.skipNil) } } extension Signal { /// Take up to `n` values from the signal and then complete. /// /// - precondition: `count` must be non-negative number. /// /// - parameters: /// - count: A number of values to take from the signal. /// /// - returns: A signal that will yield the first `count` values from `self` public func take(first count: Int) -> Signal<Value, Error> { precondition(count >= 0) guard count >= 1 else { return .empty } return flatMapEvent(Signal.Event.take(first: count)) } /// Collect all values sent by the signal then forward them as a single /// array and complete. /// /// - note: When `self` completes without collecting any value, it will send /// an empty array of values. /// /// - returns: A signal that will yield an array of values when `self` /// completes. public func collect() -> Signal<[Value], Error> { return flatMapEvent(Signal.Event.collect) } /// Collect at most `count` values from `self`, forward them as a single /// array and complete. /// /// - note: When the count is reached the array is sent and the signal /// starts over yielding a new array of values. /// /// - note: When `self` completes any remaining values will be sent, the /// last array may not have `count` values. Alternatively, if were /// not collected any values will sent an empty array of values. /// /// - precondition: `count` should be greater than zero. /// public func collect(count: Int) -> Signal<[Value], Error> { return flatMapEvent(Signal.Event.collect(count: count)) } /// Collect values from `self`, and emit them if the predicate passes. /// /// When `self` completes any remaining values will be sent, regardless of the /// collected values matching `shouldEmit` or not. /// /// If `self` completes without having emitted any value, an empty array would be /// emitted, followed by the completion of the returned `Signal`. /// /// ```` /// let (signal, observer) = Signal<Int, Never>.pipe() /// /// signal /// .collect { values in values.reduce(0, combine: +) == 8 } /// .observeValues { print($0) } /// /// observer.send(value: 1) /// observer.send(value: 3) /// observer.send(value: 4) /// observer.send(value: 7) /// observer.send(value: 1) /// observer.send(value: 5) /// observer.send(value: 6) /// observer.sendCompleted() /// /// // Output: /// // [1, 3, 4] /// // [7, 1] /// // [5, 6] /// ```` /// /// - parameters: /// - shouldEmit: A closure to determine, when every time a new value is received, /// whether the collected values should be emitted. The new value /// is included in the collected values. /// /// - returns: A signal of arrays of values, as instructed by the `shouldEmit` /// closure. public func collect(_ shouldEmit: @escaping (_ collectedValues: [Value]) -> Bool) -> Signal<[Value], Error> { return flatMapEvent(Signal.Event.collect(shouldEmit)) } /// Collect values from `self`, and emit them if the predicate passes. /// /// When `self` completes any remaining values will be sent, regardless of the /// collected values matching `shouldEmit` or not. /// /// If `self` completes without having emitted any value, an empty array would be /// emitted, followed by the completion of the returned `Signal`. /// /// ```` /// let (signal, observer) = Signal<Int, Never>.pipe() /// /// signal /// .collect { values, value in value == 7 } /// .observeValues { print($0) } /// /// observer.send(value: 1) /// observer.send(value: 1) /// observer.send(value: 7) /// observer.send(value: 7) /// observer.send(value: 5) /// observer.send(value: 6) /// observer.sendCompleted() /// /// // Output: /// // [1, 1] /// // [7] /// // [7, 5, 6] /// ```` /// /// - parameters: /// - shouldEmit: A closure to determine, when every time a new value is received, /// whether the collected values should be emitted. The new value /// is **not** included in the collected values, and is included when /// the next value is received. /// /// - returns: A signal of arrays of values, as instructed by the `shouldEmit` /// closure. public func collect(_ shouldEmit: @escaping (_ collected: [Value], _ latest: Value) -> Bool) -> Signal<[Value], Error> { return flatMapEvent(Signal.Event.collect(shouldEmit)) } /// Forward the latest values on `scheduler` every `interval`. /// /// - note: If `self` terminates while values are being accumulated, /// the behaviour will be determined by `discardWhenCompleted`. /// If `true`, the values will be discarded and the returned signal /// will terminate immediately. /// If `false`, that values will be delivered at the next interval. /// /// - parameters: /// - interval: A repetition interval. /// - scheduler: A scheduler to send values on. /// - skipEmpty: Whether empty arrays should be sent if no values were /// accumulated during the interval. /// - discardWhenCompleted: A boolean to indicate if the latest unsent /// values should be discarded on completion. /// /// - returns: A signal that sends all values that are sent from `self` at /// `interval` seconds apart. public func collect(every interval: DispatchTimeInterval, on scheduler: DateScheduler, skipEmpty: Bool = false, discardWhenCompleted: Bool = true) -> Signal<[Value], Error> { return flatMapEvent(Signal.Event.collect(every: interval, on: scheduler, skipEmpty: skipEmpty, discardWhenCompleted: discardWhenCompleted)) } /// Forward all events onto the given scheduler, instead of whichever /// scheduler they originally arrived upon. /// /// - parameters: /// - scheduler: A scheduler to deliver events on. /// /// - returns: A signal that will yield `self` values on provided scheduler. public func observe(on scheduler: Scheduler) -> Signal<Value, Error> { return flatMapEvent(Signal.Event.observe(on: scheduler)) } } extension Signal { /// Combine the latest value of the receiver with the latest value from the /// given signal. /// /// - note: The returned signal will not send a value until both inputs have /// sent at least one value each. /// /// - note: If either signal is interrupted, the returned signal will also /// be interrupted. /// /// - note: The returned signal will not complete until both inputs /// complete. /// /// - parameters: /// - otherSignal: A signal to combine `self`'s value with. /// /// - returns: A signal that will yield a tuple containing values of `self` /// and given signal. public func combineLatest<U>(with other: Signal<U, Error>) -> Signal<(Value, U), Error> { return Signal.combineLatest(self, other) } /// Merge the given signal into a single `Signal` that will emit all /// values from both of them, and complete when all of them have completed. /// /// - parameters: /// - other: A signal to merge `self`'s value with. /// /// - returns: A signal that sends all values of `self` and given signal. public func merge(with other: Signal<Value, Error>) -> Signal<Value, Error> { return Signal.merge(self, other) } /// Delay `value` and `completed` events by the given interval, forwarding /// them on the given scheduler. /// /// - note: failed and `interrupted` events are always scheduled /// immediately. /// /// - precondition: `interval` must be non-negative number. /// /// - parameters: /// - interval: Interval to delay `value` and `completed` events by. /// - scheduler: A scheduler to deliver delayed events on. /// /// - returns: A signal that will delay `value` and `completed` events and /// will yield them on given scheduler. public func delay(_ interval: TimeInterval, on scheduler: DateScheduler) -> Signal<Value, Error> { return flatMapEvent(Signal.Event.delay(interval, on: scheduler)) } /// Skip first `count` number of values then act as usual. /// /// - precondition: `count` must be non-negative number. /// /// - parameters: /// - count: A number of values to skip. /// /// - returns: A signal that will skip the first `count` values, then /// forward everything afterward. public func skip(first count: Int) -> Signal<Value, Error> { guard count != 0 else { return self } return flatMapEvent(Signal.Event.skip(first: count)) } /// Treat all Events from `self` as plain values, allowing them to be /// manipulated just like any other value. /// /// In other words, this brings Events “into the monad”. /// /// - note: When a Completed or Failed event is received, the resulting /// signal will send the Event itself and then complete. When an /// Interrupted event is received, the resulting signal will send /// the Event itself and then interrupt. /// /// - returns: A signal that sends events as its values. public func materialize() -> Signal<Event, Never> { return flatMapEvent(Signal.Event.materialize) } /// Treats all Results from the input producer as plain values, allowing them /// to be manipulated just like any other value. /// /// In other words, this brings Results “into the monad.” /// /// - note: When a Failed event is received, the resulting producer will /// send the `Result.failure` itself and then complete. /// /// - returns: A producer that sends results as its values. public func materializeResults() -> Signal<Result<Value, Error>, Never> { return flatMapEvent(Signal.Event.materializeResults) } } extension Signal where Value: EventProtocol, Error == Never { /// Translate a signal of `Event` _values_ into a signal of those events /// themselves. /// /// - returns: A signal that sends values carried by `self` events. public func dematerialize() -> Signal<Value.Value, Value.Error> { return flatMapEvent(Signal.Event.dematerialize) } } extension Signal where Error == Never { /// Translate a signal of `Result` _values_ into a signal of those events /// themselves. /// /// - returns: A signal that sends values carried by `self` events. public func dematerializeResults<Success, Failure>() -> Signal<Success, Failure> where Value == Result<Success, Failure> { return flatMapEvent(Signal.Event.dematerializeResults) } } extension Signal { /// Inject side effects to be performed upon the specified signal events. /// /// - parameters: /// - event: A closure that accepts an event and is invoked on every /// received event. /// - failed: A closure that accepts error object and is invoked for /// failed event. /// - completed: A closure that is invoked for `completed` event. /// - interrupted: A closure that is invoked for `interrupted` event. /// - terminated: A closure that is invoked for any terminating event. /// - disposed: A closure added as disposable when signal completes. /// - value: A closure that accepts a value from `value` event. /// /// - returns: A signal with attached side-effects for given event cases. public func on( event: ((Event) -> Void)? = nil, failed: ((Error) -> Void)? = nil, completed: (() -> Void)? = nil, interrupted: (() -> Void)? = nil, terminated: (() -> Void)? = nil, disposed: (() -> Void)? = nil, value: ((Value) -> Void)? = nil ) -> Signal<Value, Error> { return Signal.unserialized { observer, lifetime in if let action = disposed { lifetime.observeEnded(action) } lifetime += signal.observe { receivedEvent in event?(receivedEvent) switch receivedEvent { case let .value(v): value?(v) case let .failed(error): failed?(error) case .completed: completed?() case .interrupted: interrupted?() } if receivedEvent.isTerminating { terminated?() } observer.send(receivedEvent) } } } } private struct SampleState<Value> { var latestValue: Value? var isSignalCompleted: Bool = false var isSamplerCompleted: Bool = false } extension Signal { /// Forward the latest value from `self` with the value from `sampler` as a /// tuple, only when`sampler` sends a `value` event. /// /// - note: If `sampler` fires before a value has been observed on `self`, /// nothing happens. /// /// - parameters: /// - sampler: A signal that will trigger the delivery of `value` event /// from `self`. /// /// - returns: A signal that will send values from `self` and `sampler`, /// sampled (possibly multiple times) by `sampler`, then complete /// once both input signals have completed, or interrupt if /// either input signal is interrupted. public func sample<T>(with sampler: Signal<T, Never>) -> Signal<(Value, T), Error> { return Signal<(Value, T), Error> { observer, lifetime in let state = Atomic(SampleState<Value>()) lifetime += self.observe { event in switch event { case let .value(value): state.modify { $0.latestValue = value } case let .failed(error): observer.send(error: error) case .completed: let shouldComplete: Bool = state.modify { $0.isSignalCompleted = true return $0.isSamplerCompleted } if shouldComplete { observer.sendCompleted() } case .interrupted: observer.sendInterrupted() } } lifetime += sampler.observe { event in switch event { case .value(let samplerValue): if let value = state.value.latestValue { observer.send(value: (value, samplerValue)) } case .completed: let shouldComplete: Bool = state.modify { $0.isSamplerCompleted = true return $0.isSignalCompleted } if shouldComplete { observer.sendCompleted() } case .interrupted: observer.sendInterrupted() case .failed: break } } } } /// Forward the latest value from `self` whenever `sampler` sends a `value` /// event. /// /// - note: If `sampler` fires before a value has been observed on `self`, /// nothing happens. /// /// - parameters: /// - sampler: A signal that will trigger the delivery of `value` event /// from `self`. /// /// - returns: A signal that will send values from `self`, sampled (possibly /// multiple times) by `sampler`, then complete once both input /// signals have completed, or interrupt if either input signal /// is interrupted. public func sample(on sampler: Signal<(), Never>) -> Signal<Value, Error> { return sample(with: sampler) .map { $0.0 } } /// Forward the latest value from `samplee` with the value from `self` as a /// tuple, only when `self` sends a `value` event. /// This is like a flipped version of `sample(with:)`, but `samplee`'s /// terminal events are completely ignored. /// /// - note: If `self` fires before a value has been observed on `samplee`, /// nothing happens. /// /// - parameters: /// - samplee: A signal whose latest value is sampled by `self`. /// /// - returns: A signal that will send values from `self` and `samplee`, /// sampled (possibly multiple times) by `self`, then terminate /// once `self` has terminated. **`samplee`'s terminated events /// are ignored**. public func withLatest<U>(from samplee: Signal<U, Never>) -> Signal<(Value, U), Error> { return Signal<(Value, U), Error>.unserialized { observer, lifetime in let state = Atomic<U?>(nil) lifetime += samplee.observeValues { value in state.value = value } lifetime += self.observe { event in switch event { case let .value(value): if let value2 = state.value { observer.send(value: (value, value2)) } case .completed: observer.sendCompleted() case let .failed(error): observer.send(error: error) case .interrupted: observer.sendInterrupted() } } } } /// Forward the latest value from `samplee` with the value from `self` as a /// tuple, only when `self` sends a `value` event. /// This is like a flipped version of `sample(with:)`, but `samplee`'s /// terminal events are completely ignored. /// /// - note: If `self` fires before a value has been observed on `samplee`, /// nothing happens. /// /// - parameters: /// - samplee: A producer whose latest value is sampled by `self`. /// /// - returns: A signal that will send values from `self` and `samplee`, /// sampled (possibly multiple times) by `self`, then terminate /// once `self` has terminated. **`samplee`'s terminated events /// are ignored**. public func withLatest<U>(from samplee: SignalProducer<U, Never>) -> Signal<(Value, U), Error> { return Signal<(Value, U), Error> { observer, lifetime in samplee.startWithSignal { signal, disposable in lifetime += disposable lifetime += self.withLatest(from: signal).observe(observer) } } } /// Forward the latest value from `samplee` with the value from `self` as a /// tuple, only when `self` sends a `value` event. /// This is like a flipped version of `sample(with:)`, but `samplee`'s /// terminal events are completely ignored. /// /// - note: If `self` fires before a value has been observed on `samplee`, /// nothing happens. /// /// - parameters: /// - samplee: A producer whose latest value is sampled by `self`. /// /// - returns: A signal that will send values from `self` and `samplee`, /// sampled (possibly multiple times) by `self`, then terminate /// once `self` has terminated. **`samplee`'s terminated events /// are ignored**. public func withLatest<Samplee: SignalProducerConvertible>(from samplee: Samplee) -> Signal<(Value, Samplee.Value), Error> where Samplee.Error == Never { return withLatest(from: samplee.producer) } } extension Signal { /// Forwards events from `self` until `lifetime` ends, at which point the /// returned signal will complete. /// /// - parameters: /// - lifetime: A lifetime whose `ended` signal will cause the returned /// signal to complete. /// /// - returns: A signal that will deliver events until `lifetime` ends. public func take(during lifetime: Lifetime) -> Signal<Value, Error> { return Signal<Value, Error> { observer, innerLifetime in innerLifetime += self.observe(observer) innerLifetime += lifetime.observeEnded(observer.sendCompleted) } } /// Forward events from `self` until `trigger` sends a `value` or /// `completed` event, at which point the returned signal will complete. /// /// - parameters: /// - trigger: A signal whose `value` or `completed` events will stop the /// delivery of `value` events from `self`. /// /// - returns: A signal that will deliver events until `trigger` sends /// `value` or `completed` events. public func take(until trigger: Signal<(), Never>) -> Signal<Value, Error> { return Signal<Value, Error> { observer, lifetime in lifetime += self.observe(observer) lifetime += trigger.observe { event in switch event { case .value, .completed: observer.sendCompleted() case .failed, .interrupted: break } } } } /// Do not forward any values from `self` until `trigger` sends a `value` or /// `completed` event, at which point the returned signal behaves exactly /// like `signal`. /// /// - parameters: /// - trigger: A signal whose `value` or `completed` events will start the /// deliver of events on `self`. /// /// - returns: A signal that will deliver events once the `trigger` sends /// `value` or `completed` events. public func skip(until trigger: Signal<(), Never>) -> Signal<Value, Error> { return Signal { observer, lifetime in let disposable = SerialDisposable() lifetime += disposable disposable.inner = trigger.observe { event in switch event { case .value, .completed: disposable.inner = self.observe(observer) case .failed, .interrupted: break } } } } /// Forward events from `self` with history: values of the returned signal /// are a tuples whose first member is the previous value and whose second member /// is the current value. `initial` is supplied as the first member when `self` /// sends its first value. /// /// - parameters: /// - initial: A value that will be combined with the first value sent by /// `self`. /// /// - returns: A signal that sends tuples that contain previous and current /// sent values of `self`. public func combinePrevious(_ initial: Value) -> Signal<(Value, Value), Error> { return flatMapEvent(Signal.Event.combinePrevious(initial: initial)) } /// Forward events from `self` with history: values of the returned signal /// are a tuples whose first member is the previous value and whose second member /// is the current value. /// /// The returned `Signal` would not emit any tuple until it has received at least two /// values. /// /// - returns: A signal that sends tuples that contain previous and current /// sent values of `self`. public func combinePrevious() -> Signal<(Value, Value), Error> { return flatMapEvent(Signal.Event.combinePrevious(initial: nil)) } /// Combine all values from `self`, and forward only the final accumulated result. /// /// See `scan(_:_:)` if the resulting producer needs to forward also the partial /// results. /// /// - parameters: /// - initialResult: The value to use as the initial accumulating value. /// - nextPartialResult: A closure that combines the accumulating value and the /// latest value from `self`. The result would be used in the /// next call of `nextPartialResult`, or emit to the returned /// `Signal` when `self` completes. /// /// - returns: A signal that sends the final result as `self` completes. public func reduce<U>(_ initialResult: U, _ nextPartialResult: @escaping (U, Value) -> U) -> Signal<U, Error> { return flatMapEvent(Signal.Event.reduce(initialResult, nextPartialResult)) } /// Combine all values from `self`, and forward only the final accumulated result. /// /// See `scan(into:_:)` if the resulting producer needs to forward also the partial /// results. /// /// - parameters: /// - initialResult: The value to use as the initial accumulating value. /// - nextPartialResult: A closure that combines the accumulating value and the /// latest value from `self`. The result would be used in the /// next call of `nextPartialResult`, or emit to the returned /// `Signal` when `self` completes. /// /// - returns: A signal that sends the final result as `self` completes. public func reduce<U>(into initialResult: U, _ nextPartialResult: @escaping (inout U, Value) -> Void) -> Signal<U, Error> { return flatMapEvent(Signal.Event.reduce(into: initialResult, nextPartialResult)) } /// Combine all values from `self`, and forward the partial results and the final /// result. /// /// See `reduce(_:_:)` if the resulting producer needs to forward only the final /// result. /// /// - parameters: /// - initialResult: The value to use as the initial accumulating value. /// - nextPartialResult: A closure that combines the accumulating value and the /// latest value from `self`. The result would be forwarded, /// and would be used in the next call of `nextPartialResult`. /// /// - returns: A signal that sends the partial results of the accumuation, and the /// final result as `self` completes. public func scan<U>(_ initialResult: U, _ nextPartialResult: @escaping (U, Value) -> U) -> Signal<U, Error> { return flatMapEvent(Signal.Event.scan(initialResult, nextPartialResult)) } /// Combine all values from `self`, and forward the partial results and the final /// result. /// /// See `reduce(into:_:)` if the resulting producer needs to forward only the final /// result. /// /// - parameters: /// - initialResult: The value to use as the initial accumulating value. /// - nextPartialResult: A closure that combines the accumulating value and the /// latest value from `self`. The result would be forwarded, /// and would be used in the next call of `nextPartialResult`. /// /// - returns: A signal that sends the partial results of the accumuation, and the /// final result as `self` completes. public func scan<U>(into initialResult: U, _ nextPartialResult: @escaping (inout U, Value) -> Void) -> Signal<U, Error> { return flatMapEvent(Signal.Event.scan(into: initialResult, nextPartialResult)) } /// Accumulate all values from `self` as `State`, and send the value as `U`. /// /// - parameters: /// - initialState: The state to use as the initial accumulating state. /// - next: A closure that combines the accumulating state and the latest value /// from `self`. The result would be "next state" and "output" where /// "output" would be forwarded and "next state" would be used in the /// next call of `next`. /// /// - returns: A producer that sends the output that is computed from the accumuation. public func scanMap<State, U>(_ initialState: State, _ next: @escaping (State, Value) -> (State, U)) -> Signal<U, Error> { return flatMapEvent(Signal.Event.scanMap(initialState, next)) } /// Accumulate all values from `self` as `State`, and send the value as `U`. /// /// - parameters: /// - initialState: The state to use as the initial accumulating state. /// - next: A closure that combines the accumulating state and the latest value /// from `self`. The result would be "next state" and "output" where /// "output" would be forwarded and "next state" would be used in the /// next call of `next`. /// /// - returns: A producer that sends the output that is computed from the accumuation. public func scanMap<State, U>(into initialState: State, _ next: @escaping (inout State, Value) -> U) -> Signal<U, Error> { return flatMapEvent(Signal.Event.scanMap(into: initialState, next)) } } extension Signal where Value: Equatable { /// Forward only values from `self` that are not equal to its immediately preceding /// value. /// /// - note: The first value is always forwarded. /// /// - returns: A signal which conditionally forwards values from `self`. public func skipRepeats() -> Signal<Value, Error> { return flatMapEvent(Signal.Event.skipRepeats(==)) } } extension Signal { /// Forward only values from `self` that are not considered equivalent to its /// immediately preceding value. /// /// - note: The first value is always forwarded. /// /// - parameters: /// - isEquivalent: A closure to determine whether two values are equivalent. /// /// - returns: A signal which conditionally forwards values from `self`. public func skipRepeats(_ isEquivalent: @escaping (Value, Value) -> Bool) -> Signal<Value, Error> { return flatMapEvent(Signal.Event.skipRepeats(isEquivalent)) } /// Do not forward any value from `self` until `shouldContinue` returns `false`, at /// which point the returned signal starts to forward values from `self`, including /// the one leading to the toggling. /// /// - parameters: /// - shouldContinue: A closure to determine whether the skipping should continue. /// /// - returns: A signal which conditionally forwards values from `self`. public func skip(while shouldContinue: @escaping (Value) -> Bool) -> Signal<Value, Error> { return flatMapEvent(Signal.Event.skip(while: shouldContinue)) } /// Forward events from `self` until `replacement` begins sending events. /// /// - parameters: /// - replacement: A signal to wait to wait for values from and start /// sending them as a replacement to `self`'s values. /// /// - returns: A signal which passes through `value`, failed, and /// `interrupted` events from `self` until `replacement` sends /// an event, at which point the returned signal will send that /// event and switch to passing through events from `replacement` /// instead, regardless of whether `self` has sent events /// already. public func take(untilReplacement signal: Signal<Value, Error>) -> Signal<Value, Error> { return Signal { observer, lifetime in let signalDisposable = self.observe { event in switch event { case .completed: break case .value, .failed, .interrupted: observer.send(event) } } lifetime += signalDisposable lifetime += signal.observe { event in signalDisposable?.dispose() observer.send(event) } } } /// Wait until `self` completes and then forward the final `count` values /// on the returned signal. /// /// - parameters: /// - count: Number of last events to send after `self` completes. /// /// - returns: A signal that receives up to `count` values from `self` /// after `self` completes. public func take(last count: Int) -> Signal<Value, Error> { return flatMapEvent(Signal.Event.take(last: count)) } /// Forward any values from `self` until `shouldContinue` returns `false`, at which /// point the returned signal would complete. /// /// - parameters: /// - shouldContinue: A closure to determine whether the forwarding of values should /// continue. /// /// - returns: A signal which conditionally forwards values from `self`. /// - seealso: `take(until:)` public func take(while shouldContinue: @escaping (Value) -> Bool) -> Signal<Value, Error> { return flatMapEvent(Signal.Event.take(while: shouldContinue)) } /// Forward any values from `self` until `shouldContinue` returns `false`, at which /// point the returned signal forwards the last value and then it completes. /// This is equivalent to `take(while:)`, except it also forwards the last value that failed the check. /// /// - parameters: /// - shouldContinue: A closure to determine whether the forwarding of values should /// continue. /// /// - returns: A signal which conditionally forwards values from `self`. public func take(until shouldContinue: @escaping (Value) -> Bool) -> Signal<Value, Error> { return flatMapEvent(Signal.Event.take(until: shouldContinue)) } } extension Signal { /// Zip elements of two signals into pairs. The elements of any Nth pair /// are the Nth elements of the two input signals. /// /// - parameters: /// - otherSignal: A signal to zip values with. /// /// - returns: A signal that sends tuples of `self` and `otherSignal`. public func zip<U>(with other: Signal<U, Error>) -> Signal<(Value, U), Error> { return Signal.zip(self, other) } /// Forward the latest value on `scheduler` after at least `interval` /// seconds have passed since *the returned signal* last sent a value. /// /// If `self` always sends values more frequently than `interval` seconds, /// then the returned signal will send a value every `interval` seconds. /// /// To measure from when `self` last sent a value, see `debounce`. /// /// - seealso: `debounce` /// /// - note: If multiple values are received before the interval has elapsed, /// the latest value is the one that will be passed on. /// /// - note: If `self` terminates while a value is being throttled, that /// value will be discarded and the returned signal will terminate /// immediately. /// /// - note: If the device time changed backwards before previous date while /// a value is being throttled, and if there is a new value sent, /// the new value will be passed anyway. /// /// - precondition: `interval` must be non-negative number. /// /// - parameters: /// - interval: Number of seconds to wait between sent values. /// - scheduler: A scheduler to deliver events on. /// /// - returns: A signal that sends values at least `interval` seconds /// appart on a given scheduler. public func throttle(_ interval: TimeInterval, on scheduler: DateScheduler) -> Signal<Value, Error> { return flatMapEvent(Signal.Event.throttle(interval, on: scheduler)) } /// Conditionally throttles values sent on the receiver whenever /// `shouldThrottle` is true, forwarding values on the given scheduler. /// /// - note: While `shouldThrottle` remains false, values are forwarded on the /// given scheduler. If multiple values are received while /// `shouldThrottle` is true, the latest value is the one that will /// be passed on. /// /// - note: If the input signal terminates while a value is being throttled, /// that value will be discarded and the returned signal will /// terminate immediately. /// /// - note: If `shouldThrottle` completes before the receiver, and its last /// value is `true`, the returned signal will remain in the throttled /// state, emitting no further values until it terminates. /// /// - parameters: /// - shouldThrottle: A boolean property that controls whether values /// should be throttled. /// - scheduler: A scheduler to deliver events on. /// /// - returns: A signal that sends values only while `shouldThrottle` is false. public func throttle<P: PropertyProtocol>(while shouldThrottle: P, on scheduler: Scheduler) -> Signal<Value, Error> where P.Value == Bool { return Signal { observer, lifetime in let initial: ThrottleWhileState<Value> = .resumed let state = Atomic(initial) let schedulerDisposable = SerialDisposable() lifetime += schedulerDisposable lifetime += shouldThrottle.producer .skipRepeats() .startWithValues { shouldThrottle in let valueToSend = state.modify { state -> Value? in guard !state.isTerminated else { return nil } if shouldThrottle { state = .throttled(nil) } else { defer { state = .resumed } if case let .throttled(value?) = state { return value } } return nil } if let value = valueToSend { schedulerDisposable.inner = scheduler.schedule { observer.send(value: value) } } } lifetime += self.observe { event in let eventToSend = state.modify { state -> Event? in switch event { case let .value(value): switch state { case .throttled: state = .throttled(value) return nil case .resumed: return event case .terminated: return nil } case .completed, .interrupted, .failed: state = .terminated return event } } if let event = eventToSend { schedulerDisposable.inner = scheduler.schedule { observer.send(event) } } } } } /// Forward the latest value on `scheduler` after at least `interval` /// seconds have passed since `self` last sent a value. /// /// If `self` always sends values more frequently than `interval` seconds, /// then the returned signal will never send any values. /// /// To measure from when the *returned signal* last sent a value, see /// `throttle`. /// /// - seealso: `throttle` /// /// - note: If multiple values are received before the interval has elapsed, /// the latest value is the one that will be passed on. /// /// - note: If `self` terminates while a value is being debounced, /// the behaviour will be determined by `discardWhenCompleted`. /// If `true`, that value will be discarded and the returned producer /// will terminate immediately. /// If `false`, that value will be delivered at the next debounce /// interval. /// /// - precondition: `interval` must be non-negative number. /// /// - parameters: /// - interval: A number of seconds to wait before sending a value. /// - scheduler: A scheduler to send values on. /// - discardWhenCompleted: A boolean to indicate if the latest value /// should be discarded on completion. /// /// - returns: A signal that sends values that are sent from `self` at least /// `interval` seconds apart. public func debounce(_ interval: TimeInterval, on scheduler: DateScheduler, discardWhenCompleted: Bool = true) -> Signal<Value, Error> { return flatMapEvent(Signal.Event.debounce(interval, on: scheduler, discardWhenCompleted: discardWhenCompleted)) } } extension Signal { /// Forward only those values from `self` that have unique identities across /// the set of all values that have been seen. /// /// - note: This causes the identities to be retained to check for /// uniqueness. /// /// - parameters: /// - transform: A closure that accepts a value and returns identity /// value. /// /// - returns: A signal that sends unique values during its lifetime. public func uniqueValues<Identity: Hashable>(_ transform: @escaping (Value) -> Identity) -> Signal<Value, Error> { return flatMapEvent(Signal.Event.uniqueValues(transform)) } } extension Signal where Value: Hashable { /// Forward only those values from `self` that are unique across the set of /// all values that have been seen. /// /// - note: This causes the values to be retained to check for uniqueness. /// Providing a function that returns a unique value for each sent /// value can help you reduce the memory footprint. /// /// - returns: A signal that sends unique values during its lifetime. public func uniqueValues() -> Signal<Value, Error> { return uniqueValues { $0 } } } private enum ThrottleWhileState<Value> { case resumed case throttled(Value?) case terminated var isTerminated: Bool { switch self { case .terminated: return true case .resumed, .throttled: return false } } } private protocol SignalAggregateStrategy: AnyObject { /// Update the latest value of the signal at `position` to be `value`. /// /// - parameters: /// - value: The latest value emitted by the signal at `position`. /// - position: The position of the signal. func update(_ value: Any, at position: Int) /// Record the completion of the signal at `position`. /// /// - parameters: /// - position: The position of the signal. func complete(at position: Int) init(count: Int, action: @escaping (AggregateStrategyEvent) -> Void) } private enum AggregateStrategyEvent { case value(ContiguousArray<Any>) case completed } extension Signal { // Threading of `CombineLatestStrategy` and `ZipStrategy`. // // The threading models of these strategies mirror that of `Signal.Core` to allow // recursive termial event from the upstreams that is triggered by the combined // values. // // The strategies do not unique the delivery of `completed`, since `Signal` already // guarantees that no event would ever be delivered after a terminal event. private final class CombineLatestStrategy: SignalAggregateStrategy { private enum Placeholder { case none } var values: ContiguousArray<Any> private var _haveAllSentInitial: Bool private var haveAllSentInitial: Bool { get { if _haveAllSentInitial { return true } _haveAllSentInitial = values.allSatisfy { !($0 is Placeholder) } return _haveAllSentInitial } } private let count: Int private let lock: Lock private let completion: Atomic<Int> private let action: (AggregateStrategyEvent) -> Void func update(_ value: Any, at position: Int) { lock.lock() values[position] = value if haveAllSentInitial { action(.value(values)) } lock.unlock() if completion.value == self.count, lock.try() { action(.completed) lock.unlock() } } func complete(at position: Int) { let count: Int = completion.modify { count in count += 1 return count } if count == self.count, lock.try() { action(.completed) lock.unlock() } } init(count: Int, action: @escaping (AggregateStrategyEvent) -> Void) { self.count = count self.lock = Lock.make() self.values = ContiguousArray(repeating: Placeholder.none, count: count) self._haveAllSentInitial = false self.completion = Atomic(0) self.action = action } } private final class ZipStrategy: SignalAggregateStrategy { private let stateLock: Lock private let sendLock: Lock private var values: ContiguousArray<[Any]> private var canEmit: Bool { return values.reduce(true) { $0 && !$1.isEmpty } } private var hasConcurrentlyCompleted: Bool private var isCompleted: ContiguousArray<Bool> private var hasCompletedAndEmptiedSignal: Bool { return Swift.zip(values, isCompleted).contains(where: { $0.0.isEmpty && $0.1 }) } private var areAllCompleted: Bool { return isCompleted.reduce(true) { $0 && $1 } } private let action: (AggregateStrategyEvent) -> Void func update(_ value: Any, at position: Int) { stateLock.lock() values[position].append(value) if canEmit { var buffer = ContiguousArray<Any>() buffer.reserveCapacity(values.count) for index in values.indices { buffer.append(values[index].removeFirst()) } let shouldComplete = areAllCompleted || hasCompletedAndEmptiedSignal sendLock.lock() stateLock.unlock() action(.value(buffer)) if shouldComplete { action(.completed) } sendLock.unlock() stateLock.lock() if hasConcurrentlyCompleted { sendLock.lock() action(.completed) sendLock.unlock() } } stateLock.unlock() } func complete(at position: Int) { stateLock.lock() isCompleted[position] = true if hasConcurrentlyCompleted || areAllCompleted || hasCompletedAndEmptiedSignal { if sendLock.try() { stateLock.unlock() action(.completed) sendLock.unlock() return } hasConcurrentlyCompleted = true } stateLock.unlock() } init(count: Int, action: @escaping (AggregateStrategyEvent) -> Void) { self.values = ContiguousArray(repeating: [], count: count) self.hasConcurrentlyCompleted = false self.isCompleted = ContiguousArray(repeating: false, count: count) self.action = action self.sendLock = Lock.make() self.stateLock = Lock.make() } } private final class AggregateBuilder<Strategy: SignalAggregateStrategy> { fileprivate var startHandlers: [(_ index: Int, _ strategy: Strategy, _ action: @escaping (Signal<Never, Error>.Event) -> Void) -> Disposable?] init() { self.startHandlers = [] } @discardableResult func add<U>(_ signal: Signal<U, Error>) -> Self { startHandlers.append { index, strategy, action in return signal.observe { event in switch event { case let .value(value): strategy.update(value, at: index) case .completed: strategy.complete(at: index) case .interrupted: action(.interrupted) case let .failed(error): action(.failed(error)) } } } return self } } private convenience init<Strategy>(_ builder: AggregateBuilder<Strategy>, _ transform: @escaping (ContiguousArray<Any>) -> Value) { self.init { observer, lifetime in let strategy = Strategy(count: builder.startHandlers.count) { event in switch event { case let .value(value): observer.send(value: transform(value)) case .completed: observer.sendCompleted() } } for (index, action) in builder.startHandlers.enumerated() where !lifetime.hasEnded { lifetime += action(index, strategy) { observer.send($0.promoteValue()) } } } } private convenience init<Strategy: SignalAggregateStrategy, U, S: Sequence>(_ strategy: Strategy.Type, _ signals: S) where Value == [U], S.Iterator.Element == Signal<U, Error> { self.init(signals.reduce(AggregateBuilder<Strategy>()) { $0.add($1) }) { $0.map { $0 as! U } } } private convenience init<Strategy: SignalAggregateStrategy, A, B>(_ strategy: Strategy.Type, _ a: Signal<A, Error>, _ b: Signal<B, Error>) where Value == (A, B) { self.init(AggregateBuilder<Strategy>().add(a).add(b)) { return ($0[0] as! A, $0[1] as! B) } } private convenience init<Strategy: SignalAggregateStrategy, A, B, C>(_ strategy: Strategy.Type, _ a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>) where Value == (A, B, C) { self.init(AggregateBuilder<Strategy>().add(a).add(b).add(c)) { return ($0[0] as! A, $0[1] as! B, $0[2] as! C) } } private convenience init<Strategy: SignalAggregateStrategy, A, B, C, D>(_ strategy: Strategy.Type, _ a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>) where Value == (A, B, C, D) { self.init(AggregateBuilder<Strategy>().add(a).add(b).add(c).add(d)) { return ($0[0] as! A, $0[1] as! B, $0[2] as! C, $0[3] as! D) } } private convenience init<Strategy: SignalAggregateStrategy, A, B, C, D, E>(_ strategy: Strategy.Type, _ a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>) where Value == (A, B, C, D, E) { self.init(AggregateBuilder<Strategy>().add(a).add(b).add(c).add(d).add(e)) { return ($0[0] as! A, $0[1] as! B, $0[2] as! C, $0[3] as! D, $0[4] as! E) } } private convenience init<Strategy: SignalAggregateStrategy, A, B, C, D, E, F>(_ strategy: Strategy.Type, _ a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>) where Value == (A, B, C, D, E, F) { self.init(AggregateBuilder<Strategy>().add(a).add(b).add(c).add(d).add(e).add(f)) { return ($0[0] as! A, $0[1] as! B, $0[2] as! C, $0[3] as! D, $0[4] as! E, $0[5] as! F) } } private convenience init<Strategy: SignalAggregateStrategy, A, B, C, D, E, F, G>(_ strategy: Strategy.Type, _ a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>) where Value == (A, B, C, D, E, F, G) { self.init(AggregateBuilder<Strategy>().add(a).add(b).add(c).add(d).add(e).add(f).add(g)) { return ($0[0] as! A, $0[1] as! B, $0[2] as! C, $0[3] as! D, $0[4] as! E, $0[5] as! F, $0[6] as! G) } } private convenience init<Strategy: SignalAggregateStrategy, A, B, C, D, E, F, G, H>(_ strategy: Strategy.Type, _ a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>) where Value == (A, B, C, D, E, F, G, H) { self.init(AggregateBuilder<Strategy>().add(a).add(b).add(c).add(d).add(e).add(f).add(g).add(h)) { return ($0[0] as! A, $0[1] as! B, $0[2] as! C, $0[3] as! D, $0[4] as! E, $0[5] as! F, $0[6] as! G, $0[7] as! H) } } private convenience init<Strategy: SignalAggregateStrategy, A, B, C, D, E, F, G, H, I>(_ strategy: Strategy.Type, _ a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>) where Value == (A, B, C, D, E, F, G, H, I) { self.init(AggregateBuilder<Strategy>().add(a).add(b).add(c).add(d).add(e).add(f).add(g).add(h).add(i)) { return ($0[0] as! A, $0[1] as! B, $0[2] as! C, $0[3] as! D, $0[4] as! E, $0[5] as! F, $0[6] as! G, $0[7] as! H, $0[8] as! I) } } private convenience init<Strategy: SignalAggregateStrategy, A, B, C, D, E, F, G, H, I, J>(_ strategy: Strategy.Type, _ a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>, _ j: Signal<J, Error>) where Value == (A, B, C, D, E, F, G, H, I, J) { self.init(AggregateBuilder<Strategy>().add(a).add(b).add(c).add(d).add(e).add(f).add(g).add(h).add(i).add(j)) { return ($0[0] as! A, $0[1] as! B, $0[2] as! C, $0[3] as! D, $0[4] as! E, $0[5] as! F, $0[6] as! G, $0[7] as! H, $0[8] as! I, $0[9] as! J) } } /// Combines the values of all the given signals, in the manner described by /// `combineLatest(with:)`. public static func combineLatest<B>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>) -> Signal<(Value, B), Error> { return .init(CombineLatestStrategy.self, a, b) } /// Combines the values of all the given signals, in the manner described by /// `combineLatest(with:)`. public static func combineLatest<B, C>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>) -> Signal<(Value, B, C), Error> { return .init(CombineLatestStrategy.self, a, b, c) } /// Combines the values of all the given signals, in the manner described by /// `combineLatest(with:)`. public static func combineLatest<B, C, D>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>) -> Signal<(Value, B, C, D), Error> { return .init(CombineLatestStrategy.self, a, b, c, d) } /// Combines the values of all the given signals, in the manner described by /// `combineLatest(with:)`. public static func combineLatest<B, C, D, E>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>) -> Signal<(Value, B, C, D, E), Error> { return .init(CombineLatestStrategy.self, a, b, c, d, e) } /// Combines the values of all the given signals, in the manner described by /// `combineLatest(with:)`. public static func combineLatest<B, C, D, E, F>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>) -> Signal<(Value, B, C, D, E, F), Error> { return .init(CombineLatestStrategy.self, a, b, c, d, e, f) } /// Combines the values of all the given signals, in the manner described by /// `combineLatest(with:)`. public static func combineLatest<B, C, D, E, F, G>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>) -> Signal<(Value, B, C, D, E, F, G), Error> { return .init(CombineLatestStrategy.self, a, b, c, d, e, f, g) } /// Combines the values of all the given signals, in the manner described by /// `combineLatest(with:)`. public static func combineLatest<B, C, D, E, F, G, H>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>) -> Signal<(Value, B, C, D, E, F, G, H), Error> { return .init(CombineLatestStrategy.self, a, b, c, d, e, f, g, h) } /// Combines the values of all the given signals, in the manner described by /// `combineLatest(with:)`. public static func combineLatest<B, C, D, E, F, G, H, I>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>) -> Signal<(Value, B, C, D, E, F, G, H, I), Error> { return .init(CombineLatestStrategy.self, a, b, c, d, e, f, g, h, i) } /// Combines the values of all the given signals, in the manner described by /// `combineLatest(with:)`. public static func combineLatest<B, C, D, E, F, G, H, I, J>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>, _ j: Signal<J, Error>) -> Signal<(Value, B, C, D, E, F, G, H, I, J), Error> { return .init(CombineLatestStrategy.self, a, b, c, d, e, f, g, h, i, j) } /// Combines the values of all the given signals, in the manner described by /// `combineLatest(with:)`. No events will be sent if the sequence is empty. public static func combineLatest<S: Sequence>(_ signals: S) -> Signal<[Value], Error> where S.Iterator.Element == Signal<Value, Error> { return .init(CombineLatestStrategy.self, signals) } /// Zip the values of all the given signals, in the manner described by `zip(with:)`. public static func zip<B>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>) -> Signal<(Value, B), Error> { return .init(ZipStrategy.self, a, b) } /// Zip the values of all the given signals, in the manner described by `zip(with:)`. public static func zip<B, C>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>) -> Signal<(Value, B, C), Error> { return .init(ZipStrategy.self, a, b, c) } /// Zip the values of all the given signals, in the manner described by `zip(with:)`. public static func zip<B, C, D>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>) -> Signal<(Value, B, C, D), Error> { return .init(ZipStrategy.self, a, b, c, d) } /// Zip the values of all the given signals, in the manner described by `zip(with:)`. public static func zip<B, C, D, E>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>) -> Signal<(Value, B, C, D, E), Error> { return .init(ZipStrategy.self, a, b, c, d, e) } /// Zip the values of all the given signals, in the manner described by `zip(with:)`. public static func zip<B, C, D, E, F>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>) -> Signal<(Value, B, C, D, E, F), Error> { return .init(ZipStrategy.self, a, b, c, d, e, f) } /// Zip the values of all the given signals, in the manner described by `zip(with:)`. public static func zip<B, C, D, E, F, G>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>) -> Signal<(Value, B, C, D, E, F, G), Error> { return .init(ZipStrategy.self, a, b, c, d, e, f, g) } /// Zip the values of all the given signals, in the manner described by `zip(with:)`. public static func zip<B, C, D, E, F, G, H>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>) -> Signal<(Value, B, C, D, E, F, G, H), Error> { return .init(ZipStrategy.self, a, b, c, d, e, f, g, h) } /// Zip the values of all the given signals, in the manner described by `zip(with:)`. public static func zip<B, C, D, E, F, G, H, I>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>) -> Signal<(Value, B, C, D, E, F, G, H, I), Error> { return .init(ZipStrategy.self, a, b, c, d, e, f, g, h, i) } /// Zip the values of all the given signals, in the manner described by `zip(with:)`. public static func zip<B, C, D, E, F, G, H, I, J>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>, _ j: Signal<J, Error>) -> Signal<(Value, B, C, D, E, F, G, H, I, J), Error> { return .init(ZipStrategy.self, a, b, c, d, e, f, g, h, i, j) } /// Zips the values of all the given signals, in the manner described by /// `zip(with:)`. No events will be sent if the sequence is empty. public static func zip<S: Sequence>(_ signals: S) -> Signal<[Value], Error> where S.Iterator.Element == Signal<Value, Error> { return .init(ZipStrategy.self, signals) } } extension Signal { /// Forward events from `self` until `interval`. Then if signal isn't /// completed yet, fails with `error` on `scheduler`. /// /// - note: If the interval is 0, the timeout will be scheduled immediately. /// The signal must complete synchronously (or on a faster /// scheduler) to avoid the timeout. /// /// - precondition: `interval` must be non-negative number. /// /// - parameters: /// - error: Error to send with failed event if `self` is not completed /// when `interval` passes. /// - interval: Number of seconds to wait for `self` to complete. /// - scheudler: A scheduler to deliver error on. /// /// - returns: A signal that sends events for at most `interval` seconds, /// then, if not `completed` - sends `error` with failed event /// on `scheduler`. public func timeout(after interval: TimeInterval, raising error: Error, on scheduler: DateScheduler) -> Signal<Value, Error> { precondition(interval >= 0) return Signal { observer, lifetime in let date = scheduler.currentDate.addingTimeInterval(interval) lifetime += scheduler.schedule(after: date) { observer.send(error: error) } lifetime += self.observe(observer) } } } extension Signal where Error == Never { /// Promote a signal that does not generate failures into one that can. /// /// - note: This does not actually cause failures to be generated for the /// given signal, but makes it easier to combine with other signals /// that may fail; for example, with operators like /// `combineLatestWith`, `zipWith`, `flatten`, etc. /// /// - parameters: /// - _ An `ErrorType`. /// /// - returns: A signal that has an instantiatable `ErrorType`. public func promoteError<F>(_: F.Type = F.self) -> Signal<Value, F> { return flatMapEvent(Signal.Event.promoteError(F.self)) } /// Promote a signal that does not generate failures into one that can. /// /// - note: This does not actually cause failures to be generated for the /// given signal, but makes it easier to combine with other signals /// that may fail; for example, with operators like /// `combineLatestWith`, `zipWith`, `flatten`, etc. /// /// - parameters: /// - _ An `ErrorType`. /// /// - returns: A signal that has an instantiatable `ErrorType`. public func promoteError(_: Error.Type = Error.self) -> Signal<Value, Error> { return self } /// Forward events from `self` until `interval`. Then if signal isn't /// completed yet, fails with `error` on `scheduler`. /// /// - note: If the interval is 0, the timeout will be scheduled immediately. /// The signal must complete synchronously (or on a faster /// scheduler) to avoid the timeout. /// /// - parameters: /// - interval: Number of seconds to wait for `self` to complete. /// - error: Error to send with `failed` event if `self` is not completed /// when `interval` passes. /// - scheudler: A scheduler to deliver error on. /// /// - returns: A signal that sends events for at most `interval` seconds, /// then, if not `completed` - sends `error` with `failed` event /// on `scheduler`. public func timeout<NewError>( after interval: TimeInterval, raising error: NewError, on scheduler: DateScheduler ) -> Signal<Value, NewError> { return self .promoteError(NewError.self) .timeout(after: interval, raising: error, on: scheduler) } } extension Signal where Value == Never { /// Promote a signal that does not generate values, as indicated by `Never`, to be /// a signal of the given type of value. /// /// - note: The promotion does not result in any value being generated. /// /// - parameters: /// - _ The type of value to promote to. /// /// - returns: A signal that forwards all terminal events from `self`. public func promoteValue<U>(_: U.Type = U.self) -> Signal<U, Error> { return flatMapEvent(Signal.Event.promoteValue(U.self)) } /// Promote a signal that does not generate values, as indicated by `Never`, to be /// a signal of the given type of value. /// /// - note: The promotion does not result in any value being generated. /// /// - parameters: /// - _ The type of value to promote to. /// /// - returns: A signal that forwards all terminal events from `self`. public func promoteValue(_: Value.Type = Value.self) -> Signal<Value, Error> { return self } } extension Signal where Value == Bool { /// Create a signal that computes a logical NOT in the latest values of `self`. /// /// - returns: A signal that emits the logical NOT results. public func negate() -> Signal<Value, Error> { return self.map(!) } /// Create a signal that computes a logical AND between the latest values of `self` /// and `signal`. /// /// - parameters: /// - signal: Signal to be combined with `self`. /// /// - returns: A signal that emits the logical AND results. public func and(_ signal: Signal<Value, Error>) -> Signal<Value, Error> { return type(of: self).all([self, signal]) } /// Create a signal that computes a logical AND between the latest values of `booleans`. /// /// - parameters: /// - booleans: A collection of boolean signals to be combined. /// /// - returns: A signal that emits the logical AND results. public static func all<BooleansCollection: Collection>(_ booleans: BooleansCollection) -> Signal<Value, Error> where BooleansCollection.Element == Signal<Value, Error> { return combineLatest(booleans).map { $0.reduce(true) { $0 && $1 } } } /// Create a signal that computes a logical AND between the latest values of `booleans`. /// /// - parameters: /// - booleans: Boolean signals to be combined. /// /// - returns: A signal that emits the logical AND results. public static func all(_ booleans: Signal<Value, Error>...) -> Signal<Value, Error> { return .all(booleans) } /// Create a signal that computes a logical OR between the latest values of `self` /// and `signal`. /// /// - parameters: /// - signal: Signal to be combined with `self`. /// /// - returns: A signal that emits the logical OR results. public func or(_ signal: Signal<Value, Error>) -> Signal<Value, Error> { return type(of: self).any([self, signal]) } /// Create a signal that computes a logical OR between the latest values of `booleans`. /// /// - parameters: /// - booleans: A collection of boolean signals to be combined. /// /// - returns: A signal that emits the logical OR results. public static func any<BooleansCollection: Collection>(_ booleans: BooleansCollection) -> Signal<Value, Error> where BooleansCollection.Element == Signal<Value, Error> { return combineLatest(booleans).map { $0.reduce(false) { $0 || $1 } } } /// Create a signal that computes a logical OR between the latest values of `booleans`. /// /// - parameters: /// - booleans: Boolean signals to be combined. /// /// - returns: A signal that emits the logical OR results. public static func any(_ booleans: Signal<Value, Error>...) -> Signal<Value, Error> { return .any(booleans) } } extension Signal { /// Apply an action to every value from `self`, and forward the value if the action /// succeeds. If the action fails with an error, the returned `Signal` would propagate /// the failure and terminate. /// /// - parameters: /// - action: An action which yields a `Result`. /// /// - returns: A signal which forwards the values from `self` until the given action /// fails. public func attempt(_ action: @escaping (Value) -> Result<(), Error>) -> Signal<Value, Error> { return flatMapEvent(Signal.Event.attempt(action)) } /// Apply a transform to every value from `self`, and forward the transformed value /// if the action succeeds. If the action fails with an error, the returned `Signal` /// would propagate the failure and terminate. /// /// - parameters: /// - action: A transform which yields a `Result` of the transformed value or the /// error. /// /// - returns: A signal which forwards the transformed values. public func attemptMap<U>(_ transform: @escaping (Value) -> Result<U, Error>) -> Signal<U, Error> { return flatMapEvent(Signal.Event.attemptMap(transform)) } } extension Signal where Error == Never { /// Apply a throwable action to every value from `self`, and forward the values /// if the action succeeds. If the action throws an error, the returned `Signal` /// would propagate the failure and terminate. /// /// - parameters: /// - action: A throwable closure to perform an arbitrary action on the value. /// /// - returns: A signal which forwards the successful values of the given action. public func attempt(_ action: @escaping (Value) throws -> Void) -> Signal<Value, Swift.Error> { return self .promoteError(Swift.Error.self) .attempt(action) } /// Apply a throwable transform to every value from `self`, and forward the results /// if the action succeeds. If the transform throws an error, the returned `Signal` /// would propagate the failure and terminate. /// /// - parameters: /// - transform: A throwable transform. /// /// - returns: A signal which forwards the successfully transformed values. public func attemptMap<U>(_ transform: @escaping (Value) throws -> U) -> Signal<U, Swift.Error> { return self .promoteError(Swift.Error.self) .attemptMap(transform) } } extension Signal where Error == Swift.Error { /// Apply a throwable action to every value from `self`, and forward the values /// if the action succeeds. If the action throws an error, the returned `Signal` /// would propagate the failure and terminate. /// /// - parameters: /// - action: A throwable closure to perform an arbitrary action on the value. /// /// - returns: A signal which forwards the successful values of the given action. public func attempt(_ action: @escaping (Value) throws -> Void) -> Signal<Value, Error> { return flatMapEvent(Signal.Event.attempt(action)) } /// Apply a throwable transform to every value from `self`, and forward the results /// if the action succeeds. If the transform throws an error, the returned `Signal` /// would propagate the failure and terminate. /// /// - parameters: /// - transform: A throwable transform. /// /// - returns: A signal which forwards the successfully transformed values. public func attemptMap<U>(_ transform: @escaping (Value) throws -> U) -> Signal<U, Error> { return flatMapEvent(Signal.Event.attemptMap(transform)) } }
mit
ae05545b2721a6a1cc887039023c2abd
37.047143
395
0.649624
3.660657
false
false
false
false
optimizely/swift-sdk
Sources/Customization/DefaultUserProfileService.swift
1
3568
// // Copyright 1991, 2021, Optimizely, Inc. and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation // { // 124170 = { // "experiment_bucket_map" = { // 11174010269 = { // "variation_id" = 11198460034; // }; // 11178792174 = { // "variation_id" = 11192561814; // }; // }; // "user_id" = 124170; // }; // 133904 = { // "experiment_bucket_map" = { // 11174010269 = { // "variation_id" = 11193600046; // }; // 11178792174 = { // "variation_id" = 11192561814; // }; // }; // "user_id" = 133904; // }; // 205702 = { // "experiment_bucket_map" = { // 11174010269 = { // "variation_id" = 11198460034; // }; // 11178792174 = { // "variation_id" = 11146534908; // }; // }; // "user_id" = 205702; // }; // 261193 = { // "experiment_bucket_map" = { // 11174010269 = { // "variation_id" = 11193600046; // }; // 11178792174 = { // "variation_id" = 11146534908; // }; // }; // "user_id" = 261193; // }; // 89086 = { // "experiment_bucket_map" = { // 11178792174 = { // "variation_id" = 11192561814; // }; // }; // "user_id" = 89086; // }; // } open class DefaultUserProfileService: OPTUserProfileService { public typealias UserProfileData = [String: UPProfile] var profiles: UserProfileData? let lock = DispatchQueue(label: "com.optimizely.UserProfileService") let kStorageName = "user-profile-service" public required init() { lock.async { self.profiles = UserDefaults.standard.dictionary(forKey: self.kStorageName) as? UserProfileData ?? UserProfileData() } } open func lookup(userId: String) -> UPProfile? { var retVal: UPProfile? lock.sync { retVal = profiles?[userId] } return retVal } open func save(userProfile: UPProfile) { guard let userId = userProfile[UserProfileKeys.kUserId] as? String else { return } lock.async { self.profiles?[userId] = userProfile let defaults = UserDefaults.standard defaults.set(self.profiles, forKey: self.kStorageName) defaults.synchronize() } } open func reset(userProfiles: UserProfileData? = nil) { lock.async { self.profiles = userProfiles ?? UserProfileData() let defaults = UserDefaults.standard defaults.set(self.profiles, forKey: self.kStorageName) defaults.synchronize() } } }
apache-2.0
653c0a688c41e6209418c18b8ae356e2
30.026087
128
0.505605
3.929515
false
false
false
false
ayvazj/BrundleflyiOS
Pod/Classes/Model/BtfyInitialValues.swift
1
2094
/* * Copyright (c) 2015 James Ayvaz * * 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 struct BtfyInitialValues { let size: BtfySize let anchorPoint: BtfyPoint let backgroundColor: BtfyColor let opacity: Double let position: BtfyPoint let scale: BtfyPoint let rotation: Double let fontSize: Double? let textColor: BtfyColor let textStyle: String? let textAlign: NSTextAlignment init(size: BtfySize, anchorPoint: BtfyPoint, backgroundColor: BtfyColor, opacity: Double , position: BtfyPoint, scale: BtfyPoint, rotation: Double, fontSize: Double?, textColor: BtfyColor, textStyle: String?, textAlign: NSTextAlignment) { self.size = size self.anchorPoint = anchorPoint self.backgroundColor = backgroundColor self.opacity = opacity self.position = position self.scale = scale self.rotation = Double(rotation) self.fontSize = fontSize self.textColor = textColor self.textAlign = textAlign self.textStyle = textStyle } }
mit
5631e1eb4cc3adf79fb0e3d56d72cf8e
38.509434
242
0.731614
4.622517
false
false
false
false
tectijuana/patrones
Bloque1SwiftArchivado/PracticasSwift/AlejandroEspinoza/Ejercicio8.swift
1
857
/* Espinoza Covarrubias Alejandro 13211465 */ /* Patrones de diseño */ /* Capitulo 2 */ /* Ejercicio 8 */ /* Imprimir un número real N, su inverso aditivo y su multiplicativo inveros (si lo tiene) */ /* Importa librería para utlizar funciones matemáticas */ import Foundation /* Declaración de variables */ var numero = 1.0 print("\tNumero\t|\tAditivo inverso\t|\tMultiplicativo inverso\t") print("------------------------------------------------------------------------") /* Ciclo while que realiza la tabla */ while numero <= 10 { /* Calcular el inverso aditivo */ var InvAdi = numero /* Calcular el multiplicativo inverso */ var InvMul = 1 / numero /* Imprime los resultados */ print("\t\(numero)\t|\t-\(InvAdi)\t\t|\t" + (String(format:"%.5f",InvMul)) + "\t") /* Suma al valor de número una unidad */ numero = numero + 1 }
gpl-3.0
aed797ec42479b9d024f4ddb6c35aed1
21.578947
93
0.611435
3.116364
false
false
false
false
bernardotc/Recordando
Recordando/Recordando/AppDelegate.swift
1
6255
// // AppDelegate.swift // Recordando // // Created by Bernardo Trevino on 10/12/16. // Copyright © 2016 bernardo. All rights reserved. // import UIKit import Alamofire var categorias: [Categoria] = [Categoria(id: -1, nombre: "Todas")] @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? // Set alamogfire private let alamofireManager: Alamofire.SessionManager = { let configuration = URLSessionConfiguration.default configuration.timeoutIntervalForResource = 60 return Alamofire.SessionManager(configuration: configuration) }() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Request alamofire download_images from server let parameters: Parameters = [ "action": "DOWNLOAD_IMAGES" ] // Get JSON response from server alamofireManager.request("http://35.160.114.150/recordando/model.php", method: .post, parameters: parameters).validate().responseJSON { response in switch response.result { case .success(let JSON): self.loadData(JSON as! NSDictionary) break case .failure(let error): print(error) } } setStoryboard() return true } // Parse the JSON of the server func loadData(_ response: NSDictionary) { if (response["status"] as? String == "SUCCESS") { if let categories = response["categories"] as? [AnyObject] { for object in categories { // Create category let category = object as! NSDictionary let newCategory = Categoria(id: category["id"] as! Int, nombre: category["categoryName"] as! String) // Create image list var images: [Imagen] = [] // Append image from the category received. for object2 in category["images"] as! [AnyObject] { let image = object2 as! NSDictionary let newImage = Imagen(id: image["id"] as! Int, fileName: image["imageName"] as! String, descripcion: image["description"] as! String) images.append(newImage) } newCategory.imagenes = images categorias.append(newCategory) } } } } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Métodos para cargar varios storyboards // Elegir el storyboard a desplegar func setStoryboard() { let storyboard : UIStoryboard = self.grabStoryboard() self.setInitialScreen(storyboard) } // Decide el storyboard a usar en base al tamaño de la pantalla func grabStoryboard() -> UIStoryboard { // Obtiene el tamaño let screenHeight : Int = Int(UIScreen.main.bounds.size.height) var storyboard : UIStoryboard print(screenHeight) switch (screenHeight) { case 568: storyboard = UIStoryboard(name: "Main", bundle: nil) break; case 667: storyboard = UIStoryboard(name: "Main", bundle: nil) break; case 736: storyboard = UIStoryboard(name: "Main", bundle: nil) break; case 1024: storyboard = UIStoryboard(name: "MainiPad", bundle: nil) break; case 1366: storyboard = UIStoryboard(name: "MainiPad", bundle: nil) break; default: storyboard = UIStoryboard(name: "Main", bundle: nil) break } return storyboard } // Decide la pantalla principal de la aplicación. // Por ejemplo si el usuario ya había hecho login empieza en cierta pantalla, // y si no entonces presenta la pantalla de login func setInitialScreen( _ storyboard : UIStoryboard) { var initViewController : UIViewController initViewController = storyboard.instantiateViewController(withIdentifier: "First") self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = initViewController self.window?.makeKeyAndVisible() } }
mit
2939ce28ec3be7e5ab566cc051960161
38.802548
285
0.616579
5.41039
false
false
false
false
grpc/grpc-swift
Sources/GRPC/GRPCStatusMessageMarshaller.swift
1
6665
/* * 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. */ // swiftformat:disable:next enumNamespaces public struct GRPCStatusMessageMarshaller { /// Adds percent encoding to the given message. /// /// - Parameter message: Message to percent encode. /// - Returns: Percent encoded string, or `nil` if it could not be encoded. public static func marshall(_ message: String) -> String? { return percentEncode(message) } /// Removes percent encoding from the given message. /// /// - Parameter message: Message to remove encoding from. /// - Returns: The string with percent encoding removed, or the input string if the encoding /// could not be removed. public static func unmarshall(_ message: String) -> String { return removePercentEncoding(message) } } extension GRPCStatusMessageMarshaller { /// Adds percent encoding to the given message. /// /// gRPC uses percent encoding as defined in RFC 3986 § 2.1 but with a different set of restricted /// characters. The allowed characters are all visible printing characters except for (`%`, /// `0x25`). That is: `0x20`-`0x24`, `0x26`-`0x7E`. /// /// - Parameter message: The message to encode. /// - Returns: Percent encoded string, or `nil` if it could not be encoded. private static func percentEncode(_ message: String) -> String? { let utf8 = message.utf8 let encodedLength = self.percentEncodedLength(for: utf8) // Fast-path: all characters are valid, nothing to encode. if encodedLength == utf8.count { return message } var bytes: [UInt8] = [] bytes.reserveCapacity(encodedLength) for char in message.utf8 { switch char { // See: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#responses case 0x20 ... 0x24, 0x26 ... 0x7E: bytes.append(char) default: bytes.append(UInt8(ascii: "%")) bytes.append(self.toHex(char >> 4)) bytes.append(self.toHex(char & 0xF)) } } return String(bytes: bytes, encoding: .utf8) } /// Returns the percent encoded length of the given `UTF8View`. private static func percentEncodedLength(for view: String.UTF8View) -> Int { var count = view.count for byte in view { switch byte { case 0x20 ... 0x24, 0x26 ... 0x7E: () default: count += 2 } } return count } /// Encode the given byte as hexadecimal. /// /// - Precondition: Only the four least significant bits may be set. /// - Parameter nibble: The nibble to convert to hexadecimal. private static func toHex(_ nibble: UInt8) -> UInt8 { assert(nibble & 0xF == nibble) switch nibble { case 0 ... 9: return nibble &+ UInt8(ascii: "0") default: return nibble &+ (UInt8(ascii: "A") &- 10) } } /// Remove gRPC percent encoding from `message`. If any portion of the string could not be decoded /// then the encoded message will be returned. /// /// - Parameter message: The message to remove percent encoding from. /// - Returns: The decoded message. private static func removePercentEncoding(_ message: String) -> String { let utf8 = message.utf8 let decodedLength = self.percentDecodedLength(for: utf8) // Fast-path: no decoding to do! Note that we may also have detected that the encoding is // invalid, in which case we will return the encoded message: this is fine. if decodedLength == utf8.count { return message } var chars: [UInt8] = [] // We can't decode more characters than are already encoded. chars.reserveCapacity(decodedLength) var currentIndex = utf8.startIndex let endIndex = utf8.endIndex while currentIndex < endIndex { let byte = utf8[currentIndex] switch byte { case UInt8(ascii: "%"): guard let (nextIndex, nextNextIndex) = utf8.nextTwoIndices(after: currentIndex), let nextHex = fromHex(utf8[nextIndex]), let nextNextHex = fromHex(utf8[nextNextIndex]) else { // If we can't decode the message, aborting and returning the encoded message is fine // according to the spec. return message } chars.append((nextHex << 4) | nextNextHex) currentIndex = nextNextIndex default: chars.append(byte) } currentIndex = utf8.index(after: currentIndex) } return String(decoding: chars, as: Unicode.UTF8.self) } /// Returns the expected length of the decoded `UTF8View`. private static func percentDecodedLength(for view: String.UTF8View) -> Int { var encoded = 0 for byte in view { switch byte { case UInt8(ascii: "%"): // This can't overflow since it can't be larger than view.count. encoded &+= 1 default: () } } let notEncoded = view.count - (encoded * 3) guard notEncoded >= 0 else { // We've received gibberish: more '%' than expected. gRPC allows for the status message to // be left encoded should it be incorrectly encoded. We'll do exactly that by returning // the number of bytes in the view which will causes us to take the fast-path exit. return view.count } return notEncoded + encoded } private static func fromHex(_ byte: UInt8) -> UInt8? { switch byte { case UInt8(ascii: "0") ... UInt8(ascii: "9"): return byte &- UInt8(ascii: "0") case UInt8(ascii: "A") ... UInt8(ascii: "Z"): return byte &- (UInt8(ascii: "A") &- 10) case UInt8(ascii: "a") ... UInt8(ascii: "z"): return byte &- (UInt8(ascii: "a") &- 10) default: return nil } } } extension String.UTF8View { /// Return the next two valid indices after the given index. The indices are considered valid if /// they less than `endIndex`. fileprivate func nextTwoIndices(after index: Index) -> (Index, Index)? { let secondIndex = self.index(index, offsetBy: 2) guard secondIndex < self.endIndex else { return nil } return (self.index(after: index), secondIndex) } }
apache-2.0
d3f025924e6ecadd2c7689edede2579d
31.349515
100
0.64901
4.075841
false
false
false
false
alexzatsepin/omim
iphone/Maps/UI/Ads/RemoveAdsViewController.swift
3
9283
import SafariServices @objc protocol RemoveAdsViewControllerDelegate: AnyObject { func didCompleteSubscribtion(_ viewController: RemoveAdsViewController) func didCancelSubscribtion(_ viewController: RemoveAdsViewController) } @objc class RemoveAdsViewController: MWMViewController { typealias VC = RemoveAdsViewController private let transitioning = FadeTransitioning<RemoveAdsPresentationController>() @IBOutlet weak var loadingView: UIView! @IBOutlet weak var loadingIndicator: UIActivityIndicatorView! { didSet { loadingIndicator.color = .blackPrimaryText() } } @IBOutlet weak var payButton: UIButton! @IBOutlet weak var monthButton: UIButton! @IBOutlet weak var weekButton: UIButton! @IBOutlet weak var whySupportButton: UIButton! @IBOutlet weak var saveLabel: UILabel! @IBOutlet weak var productsLoadingIndicator: UIActivityIndicatorView! @IBOutlet weak var whySupportView: UIView! @IBOutlet weak var optionsView: UIView! { didSet { optionsView.layer.borderColor = UIColor.blackDividers().cgColor optionsView.layer.borderWidth = 1 } } @IBOutlet weak var moreOptionsButton: UIButton! { didSet { moreOptionsButton.setTitle(L("options_dropdown_title").uppercased(), for: .normal) } } @IBOutlet weak var moreOptionsButtonImage: UIImageView! { didSet { moreOptionsButtonImage.tintColor = UIColor.blackSecondaryText() } } @IBOutlet weak var titleLabel: UILabel! { didSet { titleLabel.text = L("remove_ads_title").uppercased() } } @IBOutlet weak var whySupportLabel: UILabel! { didSet { whySupportLabel.text = L("why_support").uppercased() } } @IBOutlet weak var optionsHeightConstraint: NSLayoutConstraint! @IBOutlet weak var whySupportConstraint: NSLayoutConstraint! @objc weak var delegate: RemoveAdsViewControllerDelegate? var subscriptions: [ISubscription]? private static func formatPrice(_ price: NSDecimalNumber?, locale: Locale?) -> String { guard let price = price else { return "" } guard let locale = locale else { return "\(price)" } let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.locale = locale return formatter.string(from: price) ?? "" } private static func calculateDiscount(_ price: NSDecimalNumber?, weeklyPrice: NSDecimalNumber?, period: SubscriptionPeriod) -> NSDecimalNumber? { guard let price = price, let weeklyPrice = weeklyPrice else { return nil } switch period { case .week: return 0 case .month: return weeklyPrice.multiplying(by: 52).subtracting(price.multiplying(by: 12)) case .year: return weeklyPrice.multiplying(by: 52).subtracting(price) case .unknown: return nil } } override func viewDidLoad() { super.viewDidLoad() SubscriptionManager.shared.addListener(self) SubscriptionManager.shared.getAvailableSubscriptions { (subscriptions, error) in self.subscriptions = subscriptions self.productsLoadingIndicator.stopAnimating() guard let subscriptions = subscriptions else { MWMAlertViewController.activeAlert().presentInfoAlert(L("bookmarks_convert_error_title"), text: L("purchase_error_subtitle")) self.delegate?.didCancelSubscribtion(self) return } self.saveLabel.isHidden = false self.optionsView.isHidden = false self.payButton.isEnabled = true assert(subscriptions.count == 3) let yearlyPrice = subscriptions[0].price let monthlyPrice = subscriptions[1].price let weeklyPrice = subscriptions[2].price let yearlyDiscount = VC.calculateDiscount(yearlyPrice, weeklyPrice: weeklyPrice, period: subscriptions[0].period) let monthlyDiscount = VC.calculateDiscount(monthlyPrice, weeklyPrice: weeklyPrice, period: subscriptions[1].period) let locale = subscriptions[0].priceLocale self.payButton.setTitle(String(coreFormat: L("paybtn_title"), arguments: [VC.formatPrice(yearlyPrice, locale: locale)]), for: .normal) self.saveLabel.text = String(coreFormat: L("paybtn_subtitle"), arguments: [VC.formatPrice(yearlyDiscount, locale: locale)]) self.monthButton.setTitle(String(coreFormat: L("options_dropdown_item1"), arguments: [VC.formatPrice(monthlyPrice ?? 0, locale: locale), VC.formatPrice(monthlyDiscount, locale: locale)]), for: .normal) self.weekButton.setTitle(String(coreFormat: L("options_dropdown_item2"), arguments: [VC.formatPrice(weeklyPrice ?? 0, locale: locale)]), for: .normal) Statistics.logEvent(kStatInappShow, withParameters: [kStatVendor : MWMPurchaseManager.adsRemovalVendorId(), kStatProduct : subscriptions[0].productId]) } } override var prefersStatusBarHidden: Bool { return true } deinit { SubscriptionManager.shared.removeListener(self) } @IBAction func onClose(_ sender: Any) { Statistics.logEvent(kStatInappCancel) delegate?.didCancelSubscribtion(self) } @IBAction func onPay(_ sender: UIButton) { subscribe(subscriptions?[0]) } @IBAction func onMonth(_ sender: UIButton) { subscribe(subscriptions?[1]) } @IBAction func onWeek(_ sender: UIButton) { subscribe(subscriptions?[2]) } @IBAction func onMoreOptions(_ sender: UIButton) { view.layoutIfNeeded() UIView.animate(withDuration: kDefaultAnimationDuration) { self.moreOptionsButtonImage.transform = CGAffineTransform(rotationAngle: -CGFloat.pi + 0.01) self.optionsHeightConstraint.constant = 109 self.view.layoutIfNeeded() } } @IBAction func onWhySupport(_ sender: UIButton) { whySupportView.isHidden = false whySupportView.alpha = 0 whySupportConstraint.priority = .defaultHigh UIView.animate(withDuration: kDefaultAnimationDuration) { self.whySupportView.alpha = 1 self.whySupportButton.alpha = 0 } } @IBAction func onTerms(_ sender: UIButton) { guard let url = URL(string: MWMAuthorizationViewModel.termsOfUseLink()) else { return } let safari = SFSafariViewController(url: url) self.present(safari, animated: true, completion: nil) } @IBAction func onPrivacy(_ sender: UIButton) { guard let url = URL(string: MWMAuthorizationViewModel.privacyPolicyLink()) else { return } let safari = SFSafariViewController(url: url) self.present(safari, animated: true, completion: nil) } private func subscribe(_ subscription: ISubscription?) { guard let subscription = subscription else { MWMAlertViewController.activeAlert().presentInfoAlert(L("bookmarks_convert_error_title"), text: L("purchase_error_subtitle")) self.delegate?.didCancelSubscribtion(self) return } Statistics.logEvent(kStatInappSelect, withParameters: [kStatProduct : subscription.productId]) Statistics.logEvent(kStatInappPay) showPurchaseProgress() SubscriptionManager.shared.subscribe(to: subscription) } private func showPurchaseProgress() { loadingView.isHidden = false loadingView.alpha = 0 UIView.animate(withDuration: kDefaultAnimationDuration) { self.loadingView.alpha = 1 } } private func hidePurchaseProgress() { UIView.animate(withDuration: kDefaultAnimationDuration, animations: { self.loadingView.alpha = 0 }) { _ in self.loadingView.isHidden = true } } override var transitioningDelegate: UIViewControllerTransitioningDelegate? { get { return transitioning } set { } } override var modalPresentationStyle: UIModalPresentationStyle { get { return .custom } set { } } } extension RemoveAdsViewController: SubscriptionManagerListener { func validationError() { hidePurchaseProgress() delegate?.didCompleteSubscribtion(self) } func didSubsribe(_ subscription: ISubscription) { hidePurchaseProgress() delegate?.didCompleteSubscribtion(self) } func didFailToValidate(_ subscription: ISubscription, error: Error?) { hidePurchaseProgress() MWMAlertViewController.activeAlert().presentInfoAlert(L("bookmarks_convert_error_title"), text: L("purchase_error_subtitle")) } func didDefer(_ subscription: ISubscription) { hidePurchaseProgress() delegate?.didCompleteSubscribtion(self) } func didFailToSubscribe(_ subscription: ISubscription, error: Error?) { if let error = error as NSError?, error.code != SKError.paymentCancelled.rawValue { MWMAlertViewController.activeAlert().presentInfoAlert(L("bookmarks_convert_error_title"), text: L("purchase_error_subtitle")) } hidePurchaseProgress() } }
apache-2.0
14dfc132abce12b34e03b17e9762c7f4
35.984064
133
0.67252
4.97748
false
false
false
false
el-hoshino/NotAutoLayout
Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/BottomRightCenter.Individual.swift
1
2770
// // BottomRightCenter.Individual.swift // NotAutoLayout // // Created by 史翔新 on 2017/06/20. // Copyright © 2017年 史翔新. All rights reserved. // import Foundation extension IndividualProperty { public struct BottomRightCenter { let bottomRight: LayoutElement.Point let center: LayoutElement.Horizontal } } // MARK: - Make Frame extension IndividualProperty.BottomRightCenter { private func makeFrame(bottomRight: Point, center: Float, top: Float) -> Rect { let height = (bottomRight.y - top).double return self.makeFrame(bottomRight: bottomRight, center: center, height: height) } private func makeFrame(bottomRight: Point, center: Float, middle: Float) -> Rect { let height = (bottomRight.y - middle).double return self.makeFrame(bottomRight: bottomRight, center: center, height: height) } private func makeFrame(bottomRight: Point, center: Float, height: Float) -> Rect { let width = (bottomRight.x - center).double let x = center - width.half let y = bottomRight.y - height let frame = Rect(x: x, y: y, width: width, height: height) return frame } } // MARK: - Set A Line - // MARK: Top extension IndividualProperty.BottomRightCenter: LayoutPropertyCanStoreTopToEvaluateFrameType { public func evaluateFrame(top: LayoutElement.Vertical, parameters: IndividualFrameCalculationParameters) -> Rect { let bottomRight = self.bottomRight.evaluated(from: parameters) let center = self.center.evaluated(from: parameters) let top = top.evaluated(from: parameters) return self.makeFrame(bottomRight: bottomRight, center: center, top: top) } } // MARK: Middle extension IndividualProperty.BottomRightCenter: LayoutPropertyCanStoreMiddleToEvaluateFrameType { public func evaluateFrame(middle: LayoutElement.Vertical, parameters: IndividualFrameCalculationParameters) -> Rect { let bottomRight = self.bottomRight.evaluated(from: parameters) let center = self.center.evaluated(from: parameters) let middle = middle.evaluated(from: parameters) return self.makeFrame(bottomRight: bottomRight, center: center, middle: middle) } } // MARK: - Set A Length - // MARK: Height extension IndividualProperty.BottomRightCenter: LayoutPropertyCanStoreHeightToEvaluateFrameType { public func evaluateFrame(height: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect { let bottomRight = self.bottomRight.evaluated(from: parameters) let center = self.center.evaluated(from: parameters) let width = (bottomRight.x - center).double let height = height.evaluated(from: parameters, withTheOtherAxis: .width(width)) return self.makeFrame(bottomRight: bottomRight, center: center, height: height) } }
apache-2.0
9dff928df231e013f01a5470d23dd940
26.277228
118
0.743013
4.124251
false
false
false
false
nsagora/validation-toolkit
Sources/Predicates/Standard/RegexPredicate.swift
1
1798
import Foundation /** The `RegexPredicate` struct is used to define regular expression based conditions used to evaluate input strings. ```swift let predicate = RegexPredicate(expression: "^\\d+$") let isValid = predicate.evaluate(with: "1234567890") ``` */ public struct RegexPredicate: Predicate { public typealias InputType = String private var expression: String /** Returns a new `RegexPredicate` instance. ```swift let predicate = RegexPredicate(expression: "^\\d+$") let isValid = predicate.evaluate(with: "1234567890") ``` - parameter expression: A `String` describing the regular expression. */ public init(expression: String) { self.expression = expression } /** Returns a `Boolean` value that indicates whether a given input matches the regular expression specified by the receiver. - parameter input: The input against which to evaluate the receiver. - returns: `true` if input matches the regular expression specified by the receiver, otherwise `false`. */ public func evaluate(with input: InputType) -> Bool { if let _ = input.range(of: expression, options: .regularExpression) { return true } return false } } // MARK: - Dynamic Lookup Extension extension Predicate where Self == RegexPredicate { /** Returns a new `RegexPredicate` instance. ```swift let predicate: RegexPredicate = .regex("^\\d+$") let isValid = predicate.evaluate(with: "1234567890") ``` - parameter expression: A `String` describing the regular expression. */ public static func regex(_ expression: String) -> Self { RegexPredicate(expression: expression) } }
mit
79561c40d67bde79d16cf0d9038f5e6e
28
125
0.647386
4.912568
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/WidgetView.swift
1
4312
// // WidgetView.swift // Telegram // // Created by Mikhail Filimonov on 08.07.2021. // Copyright © 2021 Telegram. All rights reserved. // import Foundation import TGUIKit struct WidgetData { struct Button { var text: ()->String var selected: ()->Bool var image: ()->CGImage var click:()->Void } var title: ()->String var desc: ()->String var descClick:()->Void var buttons:[Button] var contentHeight: CGFloat? = nil } final class WidgetView<T> : View where T:View { private let titleView = TextView() private let descView = TextView() var dataView: T? { didSet { oldValue?.removeFromSuperview() if let dataView = self.dataView { addSubview(dataView) } layout() } } private let buttonsView = View() required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(titleView) addSubview(buttonsView) addSubview(descView) layer?.cornerRadius = 20 titleView.userInteractionEnabled = false titleView.isSelectable = false descView.userInteractionEnabled = true descView.isSelectable = false } fileprivate var data: WidgetData? func update(_ data: WidgetData) { self.data = data buttonsView.removeAllSubviews() for data in data.buttons { let button = WidgetButton() buttonsView.addSubview(button) button.set(handler: { _ in data.click() }, for: .Click) } updateLocalizationAndTheme(theme: theme) needsLayout = true } override func updateLocalizationAndTheme(theme: PresentationTheme) { super.updateLocalizationAndTheme(theme: theme) self.backgroundColor = theme.colors.background guard let data = self.data else { return } for (i, buttonData) in data.buttons.enumerated() { let button = self.buttonsView.subviews[i] as! WidgetButton button.update(buttonData.selected(), icon: buttonData.image(), text: buttonData.text()) } let descAttr = parseMarkdownIntoAttributedString(data.desc(), attributes: MarkdownAttributes(body: MarkdownAttributeSet(font: .normal(.text), textColor: theme.colors.grayText), bold: MarkdownAttributeSet(font: .bold(.text), textColor: theme.colors.grayText), link: MarkdownAttributeSet(font: .normal(.text), textColor: theme.colors.link), linkAttribute: { contents in return (NSAttributedString.Key.link.rawValue, inAppLink.callback(contents, {_ in})) })) let descLayout = TextViewLayout(descAttr, alignment: .center) descLayout.interactions = TextViewInteractions(processURL:{ _ in data.descClick() }) descLayout.measure(width: frame.width - 30) descView.update(descLayout) let titleLayout = TextViewLayout(.initialize(string: data.title(), color: theme.colors.text, font: .medium(.text))) titleLayout.measure(width: frame.width - 30) titleView.update(titleLayout) } override func layout() { super.layout() titleView.centerX(y: 18) if buttonsView.subviews.isEmpty { dataView?.frame = NSMakeRect(15, 53, frame.width - 30, 144 + 50) } else { dataView?.frame = NSMakeRect(15, 103, frame.width - 30, self.data?.contentHeight ?? 144) } buttonsView.frame = NSMakeRect(15, 53, frame.width - 30, 30) let buttonsCount = CGFloat(buttonsView.subviews.count) let bestSize = (buttonsView.frame.width - 10 * (buttonsCount - 1)) / buttonsCount for (i, button) in buttonsView.subviews.enumerated() { let index: CGFloat = CGFloat(i) button.frame = NSMakeRect(index * bestSize + 10 * index, 0, bestSize, 30) } descView.centerX(y: frame.height - descView.frame.height - 20) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
f9313efb86e816f6e5c66a27758bd8b2
30.23913
375
0.596149
4.758278
false
false
false
false
rmannion/RMCore
RMCore/Table Manager/RMTableManager.swift
1
10829
// // RMTableManager.swift // RMCore // // Created by Ryan Mannion on 4/29/16. // Copyright © 2016 Ryan Mannion. All rights reserved. // import Foundation public protocol RMTableManagerDelegate: class { func tableManager(tableManager: RMTableManager, didSelectTableRow tableRow: RMTableRow) func tableManager(tableManager: RMTableManager, shouldDeleteTableRow tableRow: RMTableRow) -> Bool func tableManager(tableManager: RMTableManager, didDeleteTableRow tableRow: RMTableRow) func tableManager(tableManager: RMTableManager, didMoveTableRow tableRow: RMTableRow, fromIndexPath sourceIndexPath: IndexPath, toIndexPath destinationIndexPath: IndexPath) } public class RMTableManager : NSObject { public weak var delegate: RMTableManagerDelegate? public var sections = [RMTableSection]() { didSet { refreshIndexPaths() } } public var sectionIndexOffset = 0 public weak var tableView: UITableView? { didSet { if let tableView = tableView { tableView.dataSource = self tableView.delegate = self tableView.separatorStyle = .none tableView.estimatedRowHeight = 48 tableView.rowHeight = UITableViewAutomaticDimension tableView.backgroundColor = UIColor.clear tableView.estimatedSectionHeaderHeight = 0 tableView.sectionHeaderHeight = UITableViewAutomaticDimension } } } public override init() { super.init() } public func refreshIndexPaths() { var section = 0 for tableSection in sections { tableSection.section = section var row = 0 for tableRow in tableSection.rows { tableRow.indexPath = IndexPath(row: row, section: section) tableRow.isLastRow = false row += 1 } tableSection.rows.last?.isLastRow = true section += 1 } } public func row(for indexPath: IndexPath) -> RMTableRow? { let tableSection = sections[indexPath.section] let tableRow = tableSection.rows[indexPath.row] return tableRow } public func insertRow(row: RMTableRow, atIndexPath indexPath: IndexPath = IndexPath(row: 0, section: 0)) { let section = sections[indexPath.section] section.rows.insert(row, at: indexPath.row) tableView?.beginUpdates() tableView?.insertRows(at: [indexPath], with: .automatic) tableView?.endUpdates() refreshIndexPaths() } public func deleteRows(rows: [RMTableRow]) { var deletedIndexPaths = [IndexPath]() var deletedSections = IndexSet() for tableRow in rows { if let indexPath = tableRow.indexPath { let tableSection = sections[indexPath.section] if let index = tableSection.rows.index(where: { (aTableRow) -> Bool in aTableRow === tableRow }) { deletedIndexPaths.append(indexPath) tableSection.rows.remove(at: index) if tableSection.rows.count == 0 { deletedSections.insert(tableSection.section) } } } } sections = sections.filter({ (tableSection) -> Bool in deletedSections.contains(tableSection.section) == false }) if let aTableView = tableView { aTableView.beginUpdates() aTableView.deleteRows(at: deletedIndexPaths, with: .automatic) if deletedSections.count > 0 { aTableView.deleteSections(deletedSections, with: .automatic) } aTableView.endUpdates() } refreshIndexPaths() } public func allRows() -> [RMTableRow] { return sections.flatMap { (section) in return section.rows } } public func selectedRows() -> [RMTableRow] { return allRows().filter { (tableRow) -> Bool in return tableRow.isSelected.value } } public func unselectSelectedRows() { for row in selectedRows() { row.isSelected.value = false } } public func allIndexPaths() -> [IndexPath] { return allRows().flatMap { (row) in row.indexPath } } public func deleteAllRows() { let allIndexPaths = self.allIndexPaths() sections = [RMTableSection()] if let aTableView = tableView { aTableView.beginUpdates() aTableView.deleteRows(at: allIndexPaths, with: .automatic) aTableView.endUpdates() } } } extension RMTableManager : UITableViewDataSource { public func numberOfSections(in tableView: UITableView) -> Int { return sections.count } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let tableSection = sections[safe: section] else { return 0 } return tableSection.closed.value ? 0 : tableSection.rows.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let tableRow = row(for: indexPath)! let identifier = tableRow.cellIdentifier() let cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? RMTableViewCell ?? tableRow.cellClass.init(style: .default, reuseIdentifier: identifier) tableRow.indexPath = indexPath cell.tableRow = tableRow return cell } public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let tableSection = sections[section] return tableSection.headerText } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let tableSection = sections[safe: section] else { return nil } if let headerClass = tableSection.headerClass { return headerClass.init(tableSection: tableSection, delegate: tableSection.headerDelegate) } return nil } public func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat { guard let tableSection = sections[safe: section] else { return 0 } return tableSection.headerHeight } public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { guard let tableSection = sections[safe: section] else { return 0 } return tableSection.headerHeight } public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { guard let tableSection = sections[safe: section] else { return nil } if let footerClass = tableSection.footerClass { return footerClass.init(tableSection: tableSection, delegate: tableSection.headerDelegate) } return nil } public func tableView(_ tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat { guard let tableSection = sections[safe: section] else { return 0 } return tableSection.footerHeight } public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { guard let tableSection = sections[safe: section] else { return 0 } return tableSection.footerHeight } public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { var canEdit = false if let tableRow = row(for: indexPath) { canEdit = tableRow.editable || tableRow.deletable || (tableRow.editActions?.count ?? 0) > 0 } return canEdit } public func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { var canMove = false if let tableRow = row(for: indexPath) { canMove = tableRow.editable } return canMove } public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if let tableRow = row(for: indexPath) { let tableSection = sections[indexPath.section] if delegate?.tableManager(tableManager: self, shouldDeleteTableRow: tableRow) ?? false { tableSection.rows.remove(at: indexPath.row) tableView.beginUpdates() tableView.deleteRows(at: [indexPath], with: .fade) tableView.endUpdates() delegate?.tableManager(tableManager: self, didDeleteTableRow: tableRow) } } } public func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { if let tableRow = row(for: sourceIndexPath) { let sourceTableSection = sections[sourceIndexPath.section] sourceTableSection.rows.remove(at: sourceIndexPath.row) let destinationTableSection = sections[destinationIndexPath.section] destinationTableSection.rows.insert(tableRow, at: destinationIndexPath.row) delegate?.tableManager(tableManager: self, didMoveTableRow: tableRow, fromIndexPath: sourceIndexPath, toIndexPath: destinationIndexPath) } } public func sectionIndexTitles(for tableView: UITableView) -> [String]? { return sections.flatMap { $0.indexTitle } } public func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { return index + sectionIndexOffset } @objc(__workaroundTableView:editActionsForRowAtIndexPath:) public func __workaroundTableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { return row(for: indexPath)?.editActions } } extension RMTableManager : UITableViewDelegate { public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let tableRow = row(for: indexPath) { delegate?.tableManager(tableManager: self, didSelectTableRow: tableRow) } } }
mit
879f0cd358ace484ac1cc94ae0c21087
33.929032
176
0.612856
5.561376
false
false
false
false
radioboo/ListKitDemo
ListKitDemo/Cells/FeedCell.swift
1
1071
// // FeedCell.swift // ListKitDemo // // Created by 酒井篤 on 2016/12/10. // Copyright © 2016年 Atsushi Sakai. All rights reserved. // import UIKit class FeedCell: UICollectionViewCell { @IBOutlet weak var commentLabel: UILabel? @IBOutlet weak var imageView: UIImageView? lazy var separator: CALayer = { let layer = CALayer() layer.backgroundColor = UIColor(red: 200/255.0, green: 199/255.0, blue: 204/255.0, alpha: 1).cgColor self.contentView.layer.addSublayer(layer) return layer }() override func layoutSubviews() { super.layoutSubviews() let bounds = contentView.bounds let height: CGFloat = 0.5 let left = UIEdgeInsets(top: 8, left: 15, bottom: 8, right: 15).left separator.frame = CGRect(x: left, y: bounds.height - height, width: bounds.width - left, height: height) } override var isHighlighted: Bool { didSet { contentView.backgroundColor = UIColor(white: isHighlighted ? 0.9 : 1, alpha: 1) } } }
mit
f7e8bbafb8c85233fb4dba7963a22726
27.702703
112
0.627119
4.022727
false
false
false
false
tjw/swift
test/Inputs/conditional_conformance_subclass.swift
1
13107
public func takes_p1<T: P1>(_: T.Type) {} public protocol P1 { func normal() func generic<T: P3>(_: T) } public protocol P2 {} public protocol P3 {} public struct IsP2: P2 {} public class Base<A> {} extension Base: P1 where A: P2 { public func normal() {} public func generic<T: P3>(_: T) {} } // witness method for Base.normal // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$S32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlAaEP6normalyyFTW"(%T32conditional_conformance_subclass4BaseC.0** noalias nocapture swiftself dereferenceable(8), %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[A_P2:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8 // CHECK-NEXT: %"\CF\84_0_0.P2" = bitcast i8* [[A_P2]] to i8** // CHECK-NEXT: [[SELF:%.]] = load %T32conditional_conformance_subclass4BaseC.0*, %T32conditional_conformance_subclass4BaseC.0** %0 // CHECK-NEXT: call swiftcc void @"$S32conditional_conformance_subclass4BaseCA2A2P2RzlE6normalyyF"(i8** %"\CF\84_0_0.P2", %T32conditional_conformance_subclass4BaseC.0* swiftself [[SELF]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // witness method for Base.generic // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$S32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW"(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T32conditional_conformance_subclass4BaseC.1** noalias nocapture swiftself dereferenceable(8), %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[A_P2:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8 // CHECK-NEXT: %"\CF\84_0_0.P2" = bitcast i8* [[A_P2]] to i8** // CHECK-NEXT: [[SELF:%.]] = load %T32conditional_conformance_subclass4BaseC.1*, %T32conditional_conformance_subclass4BaseC.1** %1, align 8 // CHECK-NEXT: call swiftcc void @"$S32conditional_conformance_subclass4BaseCA2A2P2RzlE7genericyyqd__AA2P3Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_0_0.P2", i8** %"\CF\84_1_0.P3", %T32conditional_conformance_subclass4BaseC.1* swiftself [[SELF]]) // CHECK-NEXT: ret void // CHECK-NEXT: } public class SubclassGeneric<T>: Base<T> {} public class SubclassConcrete: Base<IsP2> {} public class SubclassGenericConcrete: SubclassGeneric<IsP2> {} public func subclassgeneric_generic<T: P2>(_: T.Type) { takes_p1(SubclassGeneric<T>.self) } // CHECK-LABEL: define{{( protected)?}} swiftcc void @"$S32conditional_conformance_subclass23subclassgeneric_genericyyxmAA2P2RzlF"(%swift.type*, %swift.type* %T, i8** %T.P2) // CHECK-NEXT: entry: // CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S32conditional_conformance_subclass15SubclassGenericCMa"(i64 0, %swift.type* %T) // CHECK-NEXT: [[SubclassGeneric_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[T_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** %T.P2, i8*** [[T_P2_PTR]], align 8 // CHECK-NEXT: [[Base_P1:%.*]] = call i8** @"$S32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWa"(%swift.type* [[SubclassGeneric_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]]) // CHECK-NEXT: call swiftcc void @"$S32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassGeneric_TYPE]], %swift.type* [[SubclassGeneric_TYPE]], i8** [[Base_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // witness table accessor for Base : P1 // CHECK-LABEL: define{{( protected)?}} i8** @"$S32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWa"(%swift.type*, i8***) // CHECK-NEXT: entry: // CHECK-NEXT: [[TABLE:%.*]] = call i8** @swift_getGenericWitnessTable(%swift.generic_witness_table_cache* @"$S32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWG", %swift.type* %0, i8*** %1) // CHECK-NEXT: ret i8** [[TABLE]] // CHECK-NEXT: } public func subclassgeneric_concrete() { takes_p1(SubclassGeneric<IsP2>.self) } // CHECK-LABEL: define{{( protected)?}} swiftcc void @"$S32conditional_conformance_subclass24subclassgeneric_concreteyyF"() // CHECK-NEXT: entry: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGMa"(i64 0) // CHECK-NEXT: [[SubclassGeneric_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[Base_P1:%.*]] = call i8** @"$S32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWl"() // CHECK-NEXT: call swiftcc void @"$S32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassGeneric_TYPE]], %swift.type* [[SubclassGeneric_TYPE]], i8** [[Base_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // Lazy witness table accessor for the concrete SubclassGeneric<IsP2> : Base. // CHECK-LABEL: define linkonce_odr hidden i8** @"$S32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWl"() // CHECK-NEXT: entry: // CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$S32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWL", align 8 // CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null // CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGMa"(i64 0) // CHECK-NEXT: [[SubclassGeneric_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$S32conditional_conformance_subclass4IsP2VAA0E0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8 // CHECK-NEXT: [[Base_P1:%.*]] = call i8** @"$S32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWa"(%swift.type* [[SubclassGeneric_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]]) // CHECK-NEXT: store atomic i8** [[Base_P1]], i8*** @"$S32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWL" release, align 8 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Base_P1]], %cacheIsNull ] // CHECK-NEXT: ret i8** [[T0]] // CHECK-NEXT: } public func subclassconcrete() { takes_p1(SubclassConcrete.self) } // CHECK-LABEL: define{{( protected)?}} swiftcc void @"$S32conditional_conformance_subclass16subclassconcreteyyF"() // CHECK-NEXT: entry: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S32conditional_conformance_subclass16SubclassConcreteCMa"(i64 0) // CHECK-NEXT: [[SubclassConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[SubclassConcrete_P1:%.*]] = call i8** @"$S32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"() // CHECK-NEXT: call swiftcc void @"$S32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassConcrete_TYPE]], %swift.type* [[SubclassConcrete_TYPE]], i8** [[SubclassConcrete_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK-LABEL: define linkonce_odr hidden i8** @"$S32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"() // CHECK-NEXT: entry: // CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$S32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL", align 8 // CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null // CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S32conditional_conformance_subclass16SubclassConcreteCMa"(i64 0) // CHECK-NEXT: [[SubclassConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$S32conditional_conformance_subclass4IsP2VAA0E0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8 // CHECK-NEXT: [[Base_P1:%.*]] = call i8** @"$S32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWa"(%swift.type* [[SubclassGeneric_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]]) // CHECK-NEXT: store atomic i8** [[Base_P1]], i8*** @"$S32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL" release, align 8 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Base_P1]], %cacheIsNull ] // CHECK-NEXT: ret i8** [[T0]] // CHECK-NEXT: } public func subclassgenericconcrete() { takes_p1(SubclassGenericConcrete.self) } // CHECK-LABEL: define{{( protected)?}} swiftcc void @"$S32conditional_conformance_subclass23subclassgenericconcreteyyF"() // CHECK-NEXT: entry: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S32conditional_conformance_subclass23SubclassGenericConcreteCMa"(i64 0) // CHECK-NEXT: [[SubclassGenericConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[SubclassGenericConcrete_P1:%.*]] = call i8** @"$S32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"() // CHECK-NEXT: call swiftcc void @"$S32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassGenericConcrete_TYPE]], %swift.type* [[SubclassGenericConcrete_TYPE]], i8** [[SubclassGenericConcrete_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK-LABEL: define linkonce_odr hidden i8** @"$S32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"() // CHECK-NEXT: entry: // CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$S32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL", align 8 // CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null // CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S32conditional_conformance_subclass23SubclassGenericConcreteCMa"(i64 0) // CHECK-NEXT: [[SubclassGenericConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$S32conditional_conformance_subclass4IsP2VAA0E0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8 // CHECK-NEXT: [[Base_P1:%.*]] = call i8** @"$S32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWa"(%swift.type* [[SubclassGeneric_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]]) // CHECK-NEXT: store atomic i8** [[Base_P1]], i8*** @"$S32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL" release, align 8 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Base_P1]], %cacheIsNull ] // CHECK-NEXT: ret i8** [[T0]] // CHECK-NEXT: } // witness tabel instantiation function for Base : P1 // CHECK-LABEL: define internal void @"$S32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWI"(i8**, %swift.type*, i8**) // CHECK-NEXT: entry: // CHECK-NEXT: [[TABLES:%.*]] = bitcast i8** %2 to i8*** // CHECK-NEXT: [[A_P2_SRC:%.*]] = getelementptr inbounds i8**, i8*** [[TABLES]], i32 0 // CHECK-NEXT: [[A_P2_DEST:%.*]] = getelementptr inbounds i8*, i8** %0, i32 -1 // CHECK-NEXT: [[A_P2:%.*]] = load i8**, i8*** [[A_P2_SRC]], align 8 // CHECK-NEXT: [[CAST_A_P2_DEST:%.*]] = bitcast i8** [[A_P2_DEST]] to i8*** // CHECK-NEXT: store i8** [[A_P2]], i8*** [[CAST_A_P2_DEST]], align 8 // CHECK-NEXT: ret void // CHECK-NEXT: }
apache-2.0
e3553e5ee47e5c9dcc065aae84206af3
66.561856
373
0.688029
3.141659
false
false
false
false
AlexHmelevski/AHContainerViewController
AHContainerViewController/Classes/Transitioners/CrossDissolveTransitioner.swift
1
592
// // CrossDissolveTransitioner.swift // AHContainerViewController // // Created by Alex Hmelevski on 2017-07-12. // import Foundation // Does cross dissolve between controllers final class CrossDissolveTransitioner: AnimationProvider { func transitionBlock(for context: AnimationContext) -> () -> Void { context.toVC.view.frame = context.transitionVC.view.frame context.toVC.view.alpha = 0 let animation = { context.toVC.view.alpha = 1.0 context.fromVC.view.alpha = 0 } return animation } }
mit
8634c5b81d8c06993dbb9e8658fdfccf
23.666667
71
0.641892
4.289855
false
false
false
false
wrutkowski/Lucid-Weather-Clock
Pods/Charts/Charts/Classes/Charts/BarLineChartViewBase.swift
5
68851
// // BarLineChartViewBase.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif /// Base-class of LineChart, BarChart, ScatterChart and CandleStickChart. open class BarLineChartViewBase: ChartViewBase, BarLineScatterCandleBubbleChartDataProvider, NSUIGestureRecognizerDelegate { /// the maximum number of entries to which values will be drawn /// (entry numbers greater than this value will cause value-labels to disappear) internal var _maxVisibleValueCount = 100 /// flag that indicates if auto scaling on the y axis is enabled private var _autoScaleMinMaxEnabled = false private var _autoScaleLastLowestVisibleXIndex: Int! private var _autoScaleLastHighestVisibleXIndex: Int! private var _pinchZoomEnabled = false private var _doubleTapToZoomEnabled = true private var _dragEnabled = true private var _scaleXEnabled = true private var _scaleYEnabled = true /// the color for the background of the chart-drawing area (everything behind the grid lines). open var gridBackgroundColor = NSUIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0) open var borderColor = NSUIColor.black open var borderLineWidth: CGFloat = 1.0 /// flag indicating if the grid background should be drawn or not open var drawGridBackgroundEnabled = false /// Sets drawing the borders rectangle to true. If this is enabled, there is no point drawing the axis-lines of x- and y-axis. open var drawBordersEnabled = false /// Sets the minimum offset (padding) around the chart, defaults to 10 open var minOffset = CGFloat(10.0) /// Sets whether the chart should keep its position (zoom / scroll) after a rotation (orientation change) /// **default**: false open var keepPositionOnRotation: Bool = false /// the object representing the left y-axis internal var _leftAxis: ChartYAxis! /// the object representing the right y-axis internal var _rightAxis: ChartYAxis! internal var _leftYAxisRenderer: ChartYAxisRenderer! internal var _rightYAxisRenderer: ChartYAxisRenderer! internal var _leftAxisTransformer: ChartTransformer! internal var _rightAxisTransformer: ChartTransformer! internal var _xAxisRenderer: ChartXAxisRenderer! internal var _tapGestureRecognizer: NSUITapGestureRecognizer! internal var _doubleTapGestureRecognizer: NSUITapGestureRecognizer! #if !os(tvOS) internal var _pinchGestureRecognizer: NSUIPinchGestureRecognizer! #endif internal var _panGestureRecognizer: NSUIPanGestureRecognizer! /// flag that indicates if a custom viewport offset has been set private var _customViewPortEnabled = false public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { stopDeceleration() } internal override func initialize() { super.initialize() _leftAxis = ChartYAxis(position: .left) _rightAxis = ChartYAxis(position: .right) _leftAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler) _rightAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler) _leftYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer) _rightYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer) _xAxisRenderer = ChartXAxisRenderer(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer) self.highlighter = ChartHighlighter(chart: self) _tapGestureRecognizer = NSUITapGestureRecognizer(target: self, action: #selector(BarLineChartViewBase.tapGestureRecognized(_:))) _doubleTapGestureRecognizer = NSUITapGestureRecognizer(target: self, action: #selector(BarLineChartViewBase.doubleTapGestureRecognized(_:))) _doubleTapGestureRecognizer.nsuiNumberOfTapsRequired = 2 _panGestureRecognizer = NSUIPanGestureRecognizer(target: self, action: #selector(BarLineChartViewBase.panGestureRecognized(_:))) _panGestureRecognizer.delegate = self self.addGestureRecognizer(_tapGestureRecognizer) self.addGestureRecognizer(_doubleTapGestureRecognizer) self.addGestureRecognizer(_panGestureRecognizer) _doubleTapGestureRecognizer.isEnabled = _doubleTapToZoomEnabled _panGestureRecognizer.isEnabled = _dragEnabled #if !os(tvOS) _pinchGestureRecognizer = NSUIPinchGestureRecognizer(target: self, action: #selector(BarLineChartViewBase.pinchGestureRecognized(_:))) _pinchGestureRecognizer.delegate = self self.addGestureRecognizer(_pinchGestureRecognizer) _pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { // Saving current position of chart. var oldPoint: CGPoint? if (keepPositionOnRotation && (keyPath == "frame" || keyPath == "bounds")) { oldPoint = viewPortHandler.contentRect.origin getTransformer(.left).pixelToValue(&oldPoint!) } // Superclass transforms chart. super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) // Restoring old position of chart if var newPoint = oldPoint, keepPositionOnRotation { getTransformer(.left).pointValueToPixel(&newPoint) viewPortHandler.centerViewPort(pt: newPoint, chart: self) } else { viewPortHandler.refresh(newMatrix: viewPortHandler.touchMatrix, chart: self, invalidate: true) } } open override func draw(_ rect: CGRect) { super.draw(rect) if _data === nil { return } let optionalContext = NSUIGraphicsGetCurrentContext() guard let context = optionalContext else { return } calcModulus() if (_xAxisRenderer !== nil) { _xAxisRenderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus) } if (renderer !== nil) { renderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus) } // execute all drawing commands drawGridBackground(context: context) if (_leftAxis.enabled) { _leftYAxisRenderer?.computeAxis(yMin: _leftAxis._axisMinimum, yMax: _leftAxis._axisMaximum) } if (_rightAxis.enabled) { _rightYAxisRenderer?.computeAxis(yMin: _rightAxis._axisMinimum, yMax: _rightAxis._axisMaximum) } _xAxisRenderer?.renderAxisLine(context: context) _leftYAxisRenderer?.renderAxisLine(context: context) _rightYAxisRenderer?.renderAxisLine(context: context) if (_autoScaleMinMaxEnabled) { let lowestVisibleXIndex = self.lowestVisibleXIndex, highestVisibleXIndex = self.highestVisibleXIndex if (_autoScaleLastLowestVisibleXIndex == nil || _autoScaleLastLowestVisibleXIndex != lowestVisibleXIndex || _autoScaleLastHighestVisibleXIndex == nil || _autoScaleLastHighestVisibleXIndex != highestVisibleXIndex) { calcMinMax() calculateOffsets() _autoScaleLastLowestVisibleXIndex = lowestVisibleXIndex _autoScaleLastHighestVisibleXIndex = highestVisibleXIndex } } // make sure the graph values and grid cannot be drawn outside the content-rect context.saveGState() context.clip(to: _viewPortHandler.contentRect) _xAxisRenderer?.renderGridLines(context: context) _leftYAxisRenderer?.renderGridLines(context: context) _rightYAxisRenderer?.renderGridLines(context: context) if _xAxis.drawLimitLinesBehindDataEnabled { _xAxisRenderer?.renderLimitLines(context: context) } if _leftAxis.drawLimitLinesBehindDataEnabled { _leftYAxisRenderer?.renderLimitLines(context: context) } if _rightAxis.drawLimitLinesBehindDataEnabled { _rightYAxisRenderer?.renderLimitLines(context: context) } renderer?.drawData(context: context) // if highlighting is enabled if (valuesToHighlight()) { renderer?.drawHighlighted(context: context, indices: _indicesToHighlight) } context.restoreGState() renderer!.drawExtras(context: context) context.saveGState() context.clip(to: _viewPortHandler.contentRect) if !_xAxis.drawLimitLinesBehindDataEnabled { _xAxisRenderer?.renderLimitLines(context: context) } if !_leftAxis.drawLimitLinesBehindDataEnabled { _leftYAxisRenderer?.renderLimitLines(context: context) } if !_rightAxis.drawLimitLinesBehindDataEnabled { _rightYAxisRenderer?.renderLimitLines(context: context) } context.restoreGState() _xAxisRenderer.renderAxisLabels(context: context) _leftYAxisRenderer.renderAxisLabels(context: context) _rightYAxisRenderer.renderAxisLabels(context: context) renderer!.drawValues(context: context) _legendRenderer.renderLegend(context: context) // drawLegend() drawMarkers(context: context) drawDescription(context: context) } internal func prepareValuePxMatrix() { _rightAxisTransformer.prepareMatrixValuePx(chartXMin: _xAxis._axisMinimum, deltaX: CGFloat(xAxis.axisRange), deltaY: CGFloat(_rightAxis.axisRange), chartYMin: _rightAxis._axisMinimum) _leftAxisTransformer.prepareMatrixValuePx(chartXMin: xAxis._axisMinimum, deltaX: CGFloat(xAxis.axisRange), deltaY: CGFloat(_leftAxis.axisRange), chartYMin: _leftAxis._axisMinimum) } internal func prepareOffsetMatrix() { _rightAxisTransformer.prepareMatrixOffset(_rightAxis.inverted) _leftAxisTransformer.prepareMatrixOffset(_leftAxis.inverted) } open override func notifyDataSetChanged() { calcMinMax() _leftAxis?._defaultValueFormatter = _defaultValueFormatter _rightAxis?._defaultValueFormatter = _defaultValueFormatter _leftYAxisRenderer?.computeAxis(yMin: _leftAxis._axisMinimum, yMax: _leftAxis._axisMaximum) _rightYAxisRenderer?.computeAxis(yMin: _rightAxis._axisMinimum, yMax: _rightAxis._axisMaximum) if let data = _data { _xAxisRenderer?.computeAxis(xValAverageLength: data.xValAverageLength, xValues: data.xVals) if (_legend !== nil) { _legendRenderer?.computeLegend(data) } } calculateOffsets() setNeedsDisplay() } internal override func calcMinMax() { if (_autoScaleMinMaxEnabled) { _data?.calcMinMax(start: lowestVisibleXIndex, end: highestVisibleXIndex) } // calculate / set x-axis range _xAxis._axisMaximum = Double((_data?.xVals.count ?? 0) - 1) _xAxis.axisRange = abs(_xAxis._axisMaximum - _xAxis._axisMinimum); // calculate axis range (min / max) according to provided data _leftAxis.calculate(min: _data?.getYMin(.left) ?? 0.0, max: _data?.getYMax(.left) ?? 0.0) _rightAxis.calculate(min: _data?.getYMin(.right) ?? 0.0, max: _data?.getYMax(.right) ?? 0.0) } internal func calculateLegendOffsets(offsetLeft: inout CGFloat, offsetTop: inout CGFloat, offsetRight: inout CGFloat, offsetBottom: inout CGFloat) { // setup offsets for legend if _legend !== nil && _legend.enabled && !_legend.drawInside { switch _legend.orientation { case .vertical: switch _legend.horizontalAlignment { case .left: offsetLeft += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset case .right: offsetRight += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset case .center: switch _legend.verticalAlignment { case .top: offsetTop += min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) + _legend.yOffset if xAxis.enabled && xAxis.drawLabelsEnabled { offsetTop += xAxis.labelRotatedHeight } case .bottom: offsetBottom += min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) + _legend.yOffset if xAxis.enabled && xAxis.drawLabelsEnabled { offsetBottom += xAxis.labelRotatedHeight } default: break; } } case .horizontal: switch _legend.verticalAlignment { case .top: offsetTop += min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) + _legend.yOffset if xAxis.enabled && xAxis.drawLabelsEnabled { offsetTop += xAxis.labelRotatedHeight } case .bottom: offsetBottom += min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) + _legend.yOffset if xAxis.enabled && xAxis.drawLabelsEnabled { offsetBottom += xAxis.labelRotatedHeight } default: break; } } } } internal override func calculateOffsets() { if (!_customViewPortEnabled) { var offsetLeft = CGFloat(0.0) var offsetRight = CGFloat(0.0) var offsetTop = CGFloat(0.0) var offsetBottom = CGFloat(0.0) calculateLegendOffsets(offsetLeft: &offsetLeft, offsetTop: &offsetTop, offsetRight: &offsetRight, offsetBottom: &offsetBottom) // offsets for y-labels if (leftAxis.needsOffset) { offsetLeft += leftAxis.requiredSize().width } if (rightAxis.needsOffset) { offsetRight += rightAxis.requiredSize().width } if (xAxis.enabled && xAxis.drawLabelsEnabled) { let xlabelheight = xAxis.labelRotatedHeight + xAxis.yOffset // offsets for x-labels if (xAxis.labelPosition == .bottom) { offsetBottom += xlabelheight } else if (xAxis.labelPosition == .top) { offsetTop += xlabelheight } else if (xAxis.labelPosition == .bothSided) { offsetBottom += xlabelheight offsetTop += xlabelheight } } offsetTop += self.extraTopOffset offsetRight += self.extraRightOffset offsetBottom += self.extraBottomOffset offsetLeft += self.extraLeftOffset _viewPortHandler.restrainViewPort( offsetLeft: max(self.minOffset, offsetLeft), offsetTop: max(self.minOffset, offsetTop), offsetRight: max(self.minOffset, offsetRight), offsetBottom: max(self.minOffset, offsetBottom)) } prepareOffsetMatrix() prepareValuePxMatrix() } /// calculates the modulus for x-labels and grid internal func calcModulus() { if (_xAxis === nil || !_xAxis.enabled) { return } if (!_xAxis.isAxisModulusCustom) { _xAxis.axisLabelModulus = Int(ceil((CGFloat(_data?.xValCount ?? 0) * _xAxis.labelRotatedWidth) / (_viewPortHandler.contentWidth * _viewPortHandler.touchMatrix.a))) } if (_xAxis.axisLabelModulus < 1) { _xAxis.axisLabelModulus = 1 } } open override func getMarkerPosition(entry e: ChartDataEntry, highlight: ChartHighlight) -> CGPoint { guard let data = _data else { return CGPoint.zero } let dataSetIndex = highlight.dataSetIndex var xPos = CGFloat(e.xIndex) var yPos = CGFloat(e.value) if (self is BarChartView) { let bd = _data as! BarChartData let space = bd.groupSpace let setCount = data.dataSetCount let i = e.xIndex if self is HorizontalBarChartView { // calculate the x-position, depending on datasetcount let y = CGFloat(i + i * (setCount - 1) + dataSetIndex) + space * CGFloat(i) + space / 2.0 yPos = y if let entry = e as? BarChartDataEntry { if entry.values != nil && highlight.range !== nil { xPos = CGFloat(highlight.range!.to) } else { xPos = CGFloat(e.value) } } } else { let x = CGFloat(i + i * (setCount - 1) + dataSetIndex) + space * CGFloat(i) + space / 2.0 xPos = x if let entry = e as? BarChartDataEntry { if entry.values != nil && highlight.range !== nil { yPos = CGFloat(highlight.range!.to) } else { yPos = CGFloat(e.value) } } } } // position of the marker depends on selected value index and value var pt = CGPoint(x: xPos, y: yPos * _animator.phaseY) getTransformer(data.getDataSetByIndex(dataSetIndex)!.axisDependency).pointValueToPixel(&pt) return pt } /// draws the grid background internal func drawGridBackground(context: CGContext) { if (drawGridBackgroundEnabled || drawBordersEnabled) { context.saveGState() } if (drawGridBackgroundEnabled) { // draw the grid background context.setFillColor(gridBackgroundColor.cgColor) context.fill(_viewPortHandler.contentRect) } if (drawBordersEnabled) { context.setLineWidth(borderLineWidth) context.setStrokeColor(borderColor.cgColor) context.stroke(_viewPortHandler.contentRect) } if (drawGridBackgroundEnabled || drawBordersEnabled) { context.restoreGState() } } // MARK: - Gestures private enum GestureScaleAxis { case both case x case y } private var _isDragging = false private var _isScaling = false private var _gestureScaleAxis = GestureScaleAxis.both private var _closestDataSetToTouch: IChartDataSet! private var _panGestureReachedEdge: Bool = false private weak var _outerScrollView: NSUIScrollView? private var _lastPanPoint = CGPoint() /// This is to prevent using setTranslation which resets velocity private var _decelerationLastTime: TimeInterval = 0.0 private var _decelerationDisplayLink: NSUIDisplayLink! private var _decelerationVelocity = CGPoint() @objc private func tapGestureRecognized(_ recognizer: NSUITapGestureRecognizer) { if _data === nil { return } if (recognizer.state == NSUIGestureRecognizerState.ended) { if !self.isHighLightPerTapEnabled { return } let h = getHighlightByTouchPoint(recognizer.location(in: self)) if (h === nil || h!.isEqual(self.lastHighlighted)) { self.highlightValue(highlight: nil, callDelegate: true) self.lastHighlighted = nil } else { self.lastHighlighted = h self.highlightValue(highlight: h, callDelegate: true) } } } @objc private func doubleTapGestureRecognized(_ recognizer: NSUITapGestureRecognizer) { if _data === nil { return } if (recognizer.state == NSUIGestureRecognizerState.ended) { if _data !== nil && _doubleTapToZoomEnabled { var location = recognizer.location(in: self) location.x = location.x - _viewPortHandler.offsetLeft if (isAnyAxinverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).inverted) { location.y = -(location.y - _viewPortHandler.offsetTop) } else { location.y = -(self.bounds.size.height - location.y - _viewPortHandler.offsetBottom) } self.zoom(scaleXEnabled ? 1.4 : 1.0, scaleY: scaleYEnabled ? 1.4 : 1.0, x: location.x, y: location.y) } } } #if !os(tvOS) @objc private func pinchGestureRecognized(_ recognizer: NSUIPinchGestureRecognizer) { if (recognizer.state == NSUIGestureRecognizerState.began) { stopDeceleration() if _data !== nil && (_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled) { _isScaling = true if (_pinchZoomEnabled) { _gestureScaleAxis = .both } else { let x = abs(recognizer.location(in: self).x - recognizer.nsuiLocationOf(touch: 1, in: self).x) let y = abs(recognizer.location(in: self).y - recognizer.nsuiLocationOf(touch: 1, in: self).y) if (x > y) { _gestureScaleAxis = .x } else { _gestureScaleAxis = .y } } } } else if (recognizer.state == NSUIGestureRecognizerState.ended || recognizer.state == NSUIGestureRecognizerState.cancelled) { if (_isScaling) { _isScaling = false // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } } else if (recognizer.state == NSUIGestureRecognizerState.changed) { let isZoomingOut = (recognizer.nsuiScale < 1) var canZoomMoreX = isZoomingOut ? _viewPortHandler.canZoomOutMoreX : _viewPortHandler.canZoomInMoreX var canZoomMoreY = isZoomingOut ? _viewPortHandler.canZoomOutMoreY : _viewPortHandler.canZoomInMoreY if (_isScaling) { canZoomMoreX = canZoomMoreX && _scaleXEnabled && (_gestureScaleAxis == .both || _gestureScaleAxis == .x); canZoomMoreY = canZoomMoreY && _scaleYEnabled && (_gestureScaleAxis == .both || _gestureScaleAxis == .y); if canZoomMoreX || canZoomMoreY { var location = recognizer.location(in: self) location.x = location.x - _viewPortHandler.offsetLeft if (isAnyAxinverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).inverted) { location.y = -(location.y - _viewPortHandler.offsetTop) } else { location.y = -(_viewPortHandler.chartHeight - location.y - _viewPortHandler.offsetBottom) } let scaleX = canZoomMoreX ? recognizer.nsuiScale : 1.0 let scaleY = canZoomMoreY ? recognizer.nsuiScale : 1.0 var matrix = CGAffineTransform(translationX: location.x, y: location.y) matrix = matrix.scaledBy(x: scaleX, y: scaleY) matrix = matrix.translatedBy(x: -location.x, y: -location.y) matrix = _viewPortHandler.touchMatrix.concatenating(matrix) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) if (delegate !== nil) { delegate?.chartScaled?(self, scaleX: scaleX, scaleY: scaleY) } } recognizer.nsuiScale = 1.0 } } } #endif @objc private func panGestureRecognized(_ recognizer: NSUIPanGestureRecognizer) { if (recognizer.state == NSUIGestureRecognizerState.began && recognizer.nsuiNumberOfTouches() > 0) { stopDeceleration() if _data === nil { // If we have no data, we have nothing to pan and no data to highlight return; } // If drag is enabled and we are in a position where there's something to drag: // * If we're zoomed in, then obviously we have something to drag. // * If we have a drag offset - we always have something to drag if self.dragEnabled && (!self.hasNoDragOffset || !self.isFullyZoomedOut) { _isDragging = true _closestDataSetToTouch = getDataSetByTouchPoint(recognizer.nsuiLocationOf(touch: 0, in: self)) let translation = recognizer.translation(in: self) let didUserDrag = (self is HorizontalBarChartView) ? translation.y != 0.0 : translation.x != 0.0 // Check to see if user dragged at all and if so, can the chart be dragged by the given amount if (didUserDrag && !performPanChange(translation: translation)) { if (_outerScrollView !== nil) { // We can stop dragging right now, and let the scroll view take control _outerScrollView = nil _isDragging = false } } else { if (_outerScrollView !== nil) { // Prevent the parent scroll view from scrolling _outerScrollView?.isScrollEnabled = false } } _lastPanPoint = recognizer.translation(in: self) } else if self.highlightPerDragEnabled { // We will only handle highlights on NSUIGestureRecognizerState.Changed _isDragging = false } } else if (recognizer.state == NSUIGestureRecognizerState.changed) { if (_isDragging) { let originalTranslation = recognizer.translation(in: self) let translation = CGPoint(x: originalTranslation.x - _lastPanPoint.x, y: originalTranslation.y - _lastPanPoint.y) performPanChange(translation: translation) _lastPanPoint = originalTranslation } else if (highlightPerDragEnabled) { let h = getHighlightByTouchPoint(recognizer.location(in: self)) let lastHighlighted = self.lastHighlighted if ((h === nil && lastHighlighted !== nil) || (h !== nil && lastHighlighted === nil) || (h !== nil && lastHighlighted !== nil && !h!.isEqual(lastHighlighted))) { self.lastHighlighted = h self.highlightValue(highlight: h, callDelegate: true) } } } else if (recognizer.state == NSUIGestureRecognizerState.ended || recognizer.state == NSUIGestureRecognizerState.cancelled) { if (_isDragging) { if (recognizer.state == NSUIGestureRecognizerState.ended && dragDecelerationEnabled) { stopDeceleration() _decelerationLastTime = CACurrentMediaTime() _decelerationVelocity = recognizer.velocity(in: self) _decelerationDisplayLink = NSUIDisplayLink(target: self, selector: #selector(BarLineChartViewBase.decelerationLoop)) _decelerationDisplayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes) } _isDragging = false } if (_outerScrollView !== nil) { _outerScrollView?.isScrollEnabled = true _outerScrollView = nil } } } @discardableResult private func performPanChange(translation: CGPoint) -> Bool { var translation = translation if (isAnyAxinverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).inverted) { if (self is HorizontalBarChartView) { translation.x = -translation.x } else { translation.y = -translation.y } } let originalMatrix = _viewPortHandler.touchMatrix var matrix = CGAffineTransform(translationX: translation.x, y: translation.y) matrix = originalMatrix.concatenating(matrix) matrix = _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) if (delegate !== nil) { delegate?.chartTranslated?(self, dX: translation.x, dY: translation.y) } // Did we managed to actually drag or did we reach the edge? return matrix.tx != originalMatrix.tx || matrix.ty != originalMatrix.ty } open func stopDeceleration() { if (_decelerationDisplayLink !== nil) { _decelerationDisplayLink.remove(from: RunLoop.main, forMode: RunLoopMode.commonModes) _decelerationDisplayLink = nil } } @objc private func decelerationLoop() { let currentTime = CACurrentMediaTime() _decelerationVelocity.x *= self.dragDecelerationFrictionCoef _decelerationVelocity.y *= self.dragDecelerationFrictionCoef let timeInterval = CGFloat(currentTime - _decelerationLastTime) let distance = CGPoint( x: _decelerationVelocity.x * timeInterval, y: _decelerationVelocity.y * timeInterval ) if (!performPanChange(translation: distance)) { // We reached the edge, stop _decelerationVelocity.x = 0.0 _decelerationVelocity.y = 0.0 } _decelerationLastTime = currentTime if (abs(_decelerationVelocity.x) < 0.001 && abs(_decelerationVelocity.y) < 0.001) { stopDeceleration() // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } } private func nsuiGestureRecognizerShouldBegin(_ gestureRecognizer: NSUIGestureRecognizer) -> Bool { if (gestureRecognizer == _panGestureRecognizer) { if _data === nil || !_dragEnabled || (self.hasNoDragOffset && self.isFullyZoomedOut && !self.highlightPerDragEnabled) { return false } } else { #if !os(tvOS) if (gestureRecognizer == _pinchGestureRecognizer) { if _data === nil || (!_pinchZoomEnabled && !_scaleXEnabled && !_scaleYEnabled) { return false } } #endif } return true } #if !os(OSX) open override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if (!super.gestureRecognizerShouldBegin(gestureRecognizer)) { return false } return nsuiGestureRecognizerShouldBegin(gestureRecognizer) } #endif #if os(OSX) open func gestureRecognizerShouldBegin(_ gestureRecognizer: NSGestureRecognizer) -> Bool { return nsuiGestureRecognizerShouldBegin(gestureRecognizer) } #endif open func gestureRecognizer(_ gestureRecognizer: NSUIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: NSUIGestureRecognizer) -> Bool { #if !os(tvOS) if ((gestureRecognizer is NSUIPinchGestureRecognizer) && (otherGestureRecognizer is NSUIPanGestureRecognizer)) || ((gestureRecognizer is NSUIPanGestureRecognizer) && (otherGestureRecognizer is NSUIPinchGestureRecognizer)) { return true } #endif if (gestureRecognizer is NSUIPanGestureRecognizer && otherGestureRecognizer is NSUIPanGestureRecognizer && ( gestureRecognizer == _panGestureRecognizer )) { var scrollView = self.superview while (scrollView !== nil && !(scrollView! is NSUIScrollView)) { scrollView = scrollView?.superview } // If there is two scrollview together, we pick the superview of the inner scrollview. // In the case of UITableViewWrepperView, the superview will be UITableView if let superViewOfScrollView = scrollView?.superview, superViewOfScrollView is NSUIScrollView { scrollView = superViewOfScrollView } var foundScrollView = scrollView as? NSUIScrollView if (foundScrollView !== nil && !foundScrollView!.isScrollEnabled) { foundScrollView = nil } var scrollViewPanGestureRecognizer: NSUIGestureRecognizer! if (foundScrollView !== nil) { for scrollRecognizer in foundScrollView!.nsuiGestureRecognizers! { if (scrollRecognizer is NSUIPanGestureRecognizer) { scrollViewPanGestureRecognizer = scrollRecognizer as! NSUIPanGestureRecognizer break } } } if (otherGestureRecognizer === scrollViewPanGestureRecognizer) { _outerScrollView = foundScrollView return true } } return false } /// MARK: Viewport modifiers /// Zooms in by 1.4, into the charts center. center. open func zoomIn() { let center = _viewPortHandler.contentCenter let matrix = _viewPortHandler.zoomIn(x: center.x, y: -center.y) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Zooms out by 0.7, from the charts center. center. open func zoomOut() { let center = _viewPortHandler.contentCenter let matrix = _viewPortHandler.zoomOut(x: center.x, y: -center.y) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Zooms in or out by the given scale factor. x and y are the coordinates /// (in pixels) of the zoom center. /// /// - parameter scaleX: if < 1 --> zoom out, if > 1 --> zoom in /// - parameter scaleY: if < 1 --> zoom out, if > 1 --> zoom in /// - parameter x: /// - parameter y: open func zoom(_ scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat) { let matrix = _viewPortHandler.zoom(scaleX: scaleX, scaleY: scaleY, x: x, y: y) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Zooms in or out by the given scale factor. /// x and y are the values (**not pixels**) which to zoom to or from (the values of the zoom center). /// /// - parameter scaleX: if < 1 --> zoom out, if > 1 --> zoom in /// - parameter scaleY: if < 1 --> zoom out, if > 1 --> zoom in /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: open func zoom( _ scaleX: CGFloat, scaleY: CGFloat, xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency) { let job = ZoomChartViewJob(viewPortHandler: viewPortHandler, scaleX: scaleX, scaleY: scaleY, xIndex: xIndex, yValue: yValue, transformer: getTransformer(axis), axis: axis, view: self) addViewportJob(job) } /// Zooms by the specified scale factor to the specified values on the specified axis. /// /// - parameter scaleX: /// - parameter scaleY: /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: which axis should be used as a reference for the y-axis /// - parameter duration: the duration of the animation in seconds /// - parameter easing: open func zoomAndCenterViewAnimated( scaleX: CGFloat, scaleY: CGFloat, xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency, duration: TimeInterval, easing: ChartEasingFunctionBlock?) { let origin = getValueByTouchPoint( pt: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop), axis: axis) let job = AnimatedZoomChartViewJob( viewPortHandler: viewPortHandler, transformer: getTransformer(axis), view: self, yAxis: getAxis(axis), xValCount: _xAxis.values.count, scaleX: scaleX, scaleY: scaleY, xOrigin: viewPortHandler.scaleX, yOrigin: viewPortHandler.scaleY, zoomCenterX: xIndex, zoomCenterY: CGFloat(yValue), zoomOriginX: origin.x, zoomOriginY: origin.y, duration: duration, easing: easing) addViewportJob(job) } /// Zooms by the specified scale factor to the specified values on the specified axis. /// /// - parameter scaleX: /// - parameter scaleY: /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: which axis should be used as a reference for the y-axis /// - parameter duration: the duration of the animation in seconds /// - parameter easing: open func zoomAndCenterViewAnimated( scaleX: CGFloat, scaleY: CGFloat, xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency, duration: TimeInterval, easingOption: ChartEasingOption) { zoomAndCenterViewAnimated(scaleX: scaleX, scaleY: scaleY, xIndex: xIndex, yValue: yValue, axis: axis, duration: duration, easing: easingFunctionFromOption(easingOption)) } /// Zooms by the specified scale factor to the specified values on the specified axis. /// /// - parameter scaleX: /// - parameter scaleY: /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: which axis should be used as a reference for the y-axis /// - parameter duration: the duration of the animation in seconds /// - parameter easing: open func zoomAndCenterViewAnimated( scaleX: CGFloat, scaleY: CGFloat, xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency, duration: TimeInterval) { zoomAndCenterViewAnimated(scaleX: scaleX, scaleY: scaleY, xIndex: xIndex, yValue: yValue, axis: axis, duration: duration, easingOption: .easeInOutSine) } /// Resets all zooming and dragging and makes the chart fit exactly it's bounds. open func fitScreen() { let matrix = _viewPortHandler.fitScreen() _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) calculateOffsets() setNeedsDisplay() } /// Sets the minimum scale value to which can be zoomed out. 1 = fitScreen open func setScaleMinima(_ scaleX: CGFloat, scaleY: CGFloat) { _viewPortHandler.setMinimumScaleX(scaleX) _viewPortHandler.setMinimumScaleY(scaleY) } /// Sets the size of the area (range on the x-axis) that should be maximum visible at once (no further zomming out allowed). /// If this is e.g. set to 10, no more than 10 values on the x-axis can be viewed at once without scrolling. open func setVisibleXRangeMaximum(_ maxXRange: CGFloat) { let xScale = CGFloat(_xAxis.axisRange) / maxXRange _viewPortHandler.setMinimumScaleX(xScale) } /// Sets the size of the area (range on the x-axis) that should be minimum visible at once (no further zooming in allowed). /// If this is e.g. set to 10, no less than 10 values on the x-axis can be viewed at once without scrolling. open func setVisibleXRangeMinimum(_ minXRange: CGFloat) { let xScale = CGFloat(_xAxis.axisRange) / minXRange _viewPortHandler.setMaximumScaleX(xScale) } /// Limits the maximum and minimum value count that can be visible by pinching and zooming. /// e.g. minRange=10, maxRange=100 no less than 10 values and no more that 100 values can be viewed /// at once without scrolling open func setVisibleXRange(minXRange: CGFloat, maxXRange: CGFloat) { let maxScale = CGFloat(_xAxis.axisRange) / minXRange let minScale = CGFloat(_xAxis.axisRange) / maxXRange _viewPortHandler.setMinMaxScaleX(minScaleX: minScale, maxScaleX: maxScale) } /// Sets the size of the area (range on the y-axis) that should be maximum visible at once. /// /// - parameter yRange: /// - parameter axis: - the axis for which this limit should apply open func setVisibleYRangeMaximum(_ maxYRange: CGFloat, axis: ChartYAxis.AxisDependency) { let yScale = getDeltaY(axis) / maxYRange _viewPortHandler.setMinimumScaleY(yScale) } /// Moves the left side of the current viewport to the specified x-index. /// This also refreshes the chart by calling setNeedsDisplay(). open func moveViewToX(_ xIndex: CGFloat) { let job = MoveChartViewJob( viewPortHandler: viewPortHandler, xIndex: xIndex, yValue: 0.0, transformer: getTransformer(.left), view: self) addViewportJob(job) } /// Centers the viewport to the specified y-value on the y-axis. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter yValue: /// - parameter axis: - which axis should be used as a reference for the y-axis open func moveViewToY(_ yValue: Double, axis: ChartYAxis.AxisDependency) { let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY let job = MoveChartViewJob( viewPortHandler: viewPortHandler, xIndex: 0, yValue: yValue + Double(valsInView) / 2.0, transformer: getTransformer(axis), view: self) addViewportJob(job) } /// This will move the left side of the current viewport to the specified x-index on the x-axis, and center the viewport to the specified y-value on the y-axis. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: - which axis should be used as a reference for the y-axis open func moveViewTo(xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency) { let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY let job = MoveChartViewJob( viewPortHandler: viewPortHandler, xIndex: xIndex, yValue: yValue + Double(valsInView) / 2.0, transformer: getTransformer(axis), view: self) addViewportJob(job) } /// This will move the left side of the current viewport to the specified x-position and center the viewport to the specified y-position animated. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: which axis should be used as a reference for the y-axis /// - parameter duration: the duration of the animation in seconds /// - parameter easing: open func moveViewToAnimated( xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency, duration: TimeInterval, easing: ChartEasingFunctionBlock?) { let bounds = getValueByTouchPoint( pt: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop), axis: axis) let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY let job = AnimatedMoveChartViewJob( viewPortHandler: viewPortHandler, xIndex: xIndex, yValue: yValue + Double(valsInView) / 2.0, transformer: getTransformer(axis), view: self, xOrigin: bounds.x, yOrigin: bounds.y, duration: duration, easing: easing) addViewportJob(job) } /// This will move the left side of the current viewport to the specified x-position and center the viewport to the specified y-position animated. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: which axis should be used as a reference for the y-axis /// - parameter duration: the duration of the animation in seconds /// - parameter easing: open func moveViewToAnimated( xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency, duration: TimeInterval, easingOption: ChartEasingOption) { moveViewToAnimated(xIndex: xIndex, yValue: yValue, axis: axis, duration: duration, easing: easingFunctionFromOption(easingOption)) } /// This will move the left side of the current viewport to the specified x-position and center the viewport to the specified y-position animated. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: which axis should be used as a reference for the y-axis /// - parameter duration: the duration of the animation in seconds /// - parameter easing: open func moveViewToAnimated( xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency, duration: TimeInterval) { moveViewToAnimated(xIndex: xIndex, yValue: yValue, axis: axis, duration: duration, easingOption: .easeInOutSine) } /// This will move the center of the current viewport to the specified x-index and y-value. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: - which axis should be used as a reference for the y-axis open func centerViewTo( xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency) { let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY let xsInView = CGFloat(xAxis.values.count) / _viewPortHandler.scaleX let job = MoveChartViewJob( viewPortHandler: viewPortHandler, xIndex: xIndex - xsInView / 2.0, yValue: yValue + Double(valsInView) / 2.0, transformer: getTransformer(axis), view: self) addViewportJob(job) } /// This will move the center of the current viewport to the specified x-value and y-value animated. /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: which axis should be used as a reference for the y-axis /// - parameter duration: the duration of the animation in seconds /// - parameter easing: open func centerViewToAnimated( xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency, duration: TimeInterval, easing: ChartEasingFunctionBlock?) { let bounds = getValueByTouchPoint( pt: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop), axis: axis) let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY let xsInView = CGFloat(xAxis.values.count) / _viewPortHandler.scaleX let job = AnimatedMoveChartViewJob( viewPortHandler: viewPortHandler, xIndex: xIndex - xsInView / 2.0, yValue: yValue + Double(valsInView) / 2.0, transformer: getTransformer(axis), view: self, xOrigin: bounds.x, yOrigin: bounds.y, duration: duration, easing: easing) addViewportJob(job) } /// This will move the center of the current viewport to the specified x-value and y-value animated. /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: which axis should be used as a reference for the y-axis /// - parameter duration: the duration of the animation in seconds /// - parameter easing: open func centerViewToAnimated( xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency, duration: TimeInterval, easingOption: ChartEasingOption) { centerViewToAnimated(xIndex: xIndex, yValue: yValue, axis: axis, duration: duration, easing: easingFunctionFromOption(easingOption)) } /// This will move the center of the current viewport to the specified x-value and y-value animated. /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: which axis should be used as a reference for the y-axis /// - parameter duration: the duration of the animation in seconds /// - parameter easing: open func centerViewToAnimated( xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency, duration: TimeInterval) { centerViewToAnimated(xIndex: xIndex, yValue: yValue, axis: axis, duration: duration, easingOption: .easeInOutSine) } /// Sets custom offsets for the current `ChartViewPort` (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use `resetViewPortOffsets()` to undo this. /// ONLY USE THIS WHEN YOU KNOW WHAT YOU ARE DOING, else use `setExtraOffsets(...)`. open func setViewPortOffsets(left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat) { _customViewPortEnabled = true if (Thread.isMainThread) { self._viewPortHandler.restrainViewPort(offsetLeft: left, offsetTop: top, offsetRight: right, offsetBottom: bottom) prepareOffsetMatrix() prepareValuePxMatrix() } else { DispatchQueue.main.async(execute: { self.setViewPortOffsets(left: left, top: top, right: right, bottom: bottom) }) } } /// Resets all custom offsets set via `setViewPortOffsets(...)` method. Allows the chart to again calculate all offsets automatically. open func resetViewPortOffsets() { _customViewPortEnabled = false calculateOffsets() } // MARK: - Accessors /// - returns: the delta-y value (y-value range) of the specified axis. open func getDeltaY(_ axis: ChartYAxis.AxisDependency) -> CGFloat { if (axis == .left) { return CGFloat(leftAxis.axisRange) } else { return CGFloat(rightAxis.axisRange) } } /// - returns: the position (in pixels) the provided Entry has inside the chart view open func getPosition(_ e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint { var vals = CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value)) getTransformer(axis).pointValueToPixel(&vals) return vals } /// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling). open var dragEnabled: Bool { get { return _dragEnabled } set { if (_dragEnabled != newValue) { _dragEnabled = newValue } } } /// is scaling enabled? (zooming in and out by gesture) for the chart (this does not affect dragging). open func setScaleEnabled(_ enabled: Bool) { if (_scaleXEnabled != enabled || _scaleYEnabled != enabled) { _scaleXEnabled = enabled _scaleYEnabled = enabled #if !os(tvOS) _pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } open var scaleXEnabled: Bool { get { return _scaleXEnabled } set { if (_scaleXEnabled != newValue) { _scaleXEnabled = newValue #if !os(tvOS) _pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } } open var scaleYEnabled: Bool { get { return _scaleYEnabled } set { if (_scaleYEnabled != newValue) { _scaleYEnabled = newValue #if !os(tvOS) _pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } } /// flag that indicates if double tap zoom is enabled or not open var doubleTapToZoomEnabled: Bool { get { return _doubleTapToZoomEnabled } set { if (_doubleTapToZoomEnabled != newValue) { _doubleTapToZoomEnabled = newValue _doubleTapGestureRecognizer.isEnabled = _doubleTapToZoomEnabled } } } /// flag that indicates if highlighting per dragging over a fully zoomed out chart is enabled open var highlightPerDragEnabled = true /// Set this to `true` to make the highlight full-bar oriented, `false` to make it highlight single values open var highlightFullBarEnabled: Bool = false /// - returns: the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the Line-, Scatter-, or CandleStick-Chart. open func getHighlightByTouchPoint(_ pt: CGPoint) -> ChartHighlight? { if _data === nil { Swift.print("Can't select by touch. No data set.") return nil } return self.highlighter?.getHighlight(x: pt.x, y: pt.y) } /// - returns: the x and y values in the chart at the given touch point /// (encapsulated in a `CGPoint`). This method transforms pixel coordinates to /// coordinates / values in the chart. This is the opposite method to /// `getPixelsForValues(...)`. open func getValueByTouchPoint(pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGPoint { var pt = pt getTransformer(axis).pixelToValue(&pt) return pt } /// Transforms the given chart values into pixels. This is the opposite /// method to `getValueByTouchPoint(...)`. open func getPixelForValue(_ x: Double, y: Double, axis: ChartYAxis.AxisDependency) -> CGPoint { var pt = CGPoint(x: CGFloat(x), y: CGFloat(y)) getTransformer(axis).pointValueToPixel(&pt) return pt } /// - returns: the y-value at the given touch position (must not necessarily be /// a value contained in one of the datasets) open func getYValueByTouchPoint(pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGFloat { return getValueByTouchPoint(pt: pt, axis: axis).y } /// - returns: the Entry object displayed at the touched position of the chart open func getEntryByTouchPoint(_ pt: CGPoint) -> ChartDataEntry! { let h = getHighlightByTouchPoint(pt) if (h !== nil) { return _data!.getEntryForHighlight(h!) } return nil } /// - returns: the DataSet object displayed at the touched position of the chart open func getDataSetByTouchPoint(_ pt: CGPoint) -> IBarLineScatterCandleBubbleChartDataSet! { let h = getHighlightByTouchPoint(pt) if (h !== nil) { return _data?.getDataSetByIndex(h!.dataSetIndex) as! IBarLineScatterCandleBubbleChartDataSet! } return nil } /// - returns: the current x-scale factor open var scaleX: CGFloat { if (_viewPortHandler === nil) { return 1.0 } return _viewPortHandler.scaleX } /// - returns: the current y-scale factor open var scaleY: CGFloat { if (_viewPortHandler === nil) { return 1.0 } return _viewPortHandler.scaleY } /// if the chart is fully zoomed out, return true open var isFullyZoomedOut: Bool { return _viewPortHandler.isFullyZoomedOut; } /// - returns: the left y-axis object. In the horizontal bar-chart, this is the /// top axis. open var leftAxis: ChartYAxis { return _leftAxis } /// - returns: the right y-axis object. In the horizontal bar-chart, this is the /// bottom axis. open var rightAxis: ChartYAxis { return _rightAxis; } /// - returns: the y-axis object to the corresponding AxisDependency. In the /// horizontal bar-chart, LEFT == top, RIGHT == BOTTOM open func getAxis(_ axis: ChartYAxis.AxisDependency) -> ChartYAxis { if (axis == .left) { return _leftAxis } else { return _rightAxis } } /// flag that indicates if pinch-zoom is enabled. if true, both x and y axis can be scaled simultaneously with 2 fingers, if false, x and y axis can be scaled separately open var pinchZoomEnabled: Bool { get { return _pinchZoomEnabled } set { if (_pinchZoomEnabled != newValue) { _pinchZoomEnabled = newValue #if !os(tvOS) _pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } } /// Set an offset in dp that allows the user to drag the chart over it's /// bounds on the x-axis. open func setDragOffsetX(_ offset: CGFloat) { _viewPortHandler.setDragOffsetX(offset) } /// Set an offset in dp that allows the user to drag the chart over it's /// bounds on the y-axis. open func setDragOffsetY(_ offset: CGFloat) { _viewPortHandler.setDragOffsetY(offset) } /// - returns: true if both drag offsets (x and y) are zero or smaller. open var hasNoDragOffset: Bool { return _viewPortHandler.hasNoDragOffset; } /// The X axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of ChartXAxisRenderer /// - returns: The current set X axis renderer open var xAxisRenderer: ChartXAxisRenderer { get { return _xAxisRenderer } set { _xAxisRenderer = newValue } } /// The left Y axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of ChartYAxisRenderer /// - returns: The current set left Y axis renderer open var leftYAxisRenderer: ChartYAxisRenderer { get { return _leftYAxisRenderer } set { _leftYAxisRenderer = newValue } } /// The right Y axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of ChartYAxisRenderer /// - returns: The current set right Y axis renderer open var rightYAxisRenderer: ChartYAxisRenderer { get { return _rightYAxisRenderer } set { _rightYAxisRenderer = newValue } } open override var chartYMax: Double { return max(leftAxis._axisMaximum, rightAxis._axisMaximum) } open override var chartYMin: Double { return min(leftAxis._axisMinimum, rightAxis._axisMinimum) } /// - returns: true if either the left or the right or both axes are inverted. open var isAnyAxinverted: Bool { return _leftAxis.inverted || _rightAxis.inverted } /// flag that indicates if auto scaling on the y axis is enabled. /// if yes, the y axis automatically adjusts to the min and max y values of the current x axis range whenever the viewport changes open var autoScaleMinMaxEnabled: Bool { get { return _autoScaleMinMaxEnabled; } set { _autoScaleMinMaxEnabled = newValue; } } /// Sets a minimum width to the specified y axis. open func setYAxisMinWidth(_ which: ChartYAxis.AxisDependency, width: CGFloat) { if (which == .left) { _leftAxis.minWidth = width } else { _rightAxis.minWidth = width } } /// **default**: 0.0 /// - returns: the (custom) minimum width of the specified Y axis. open func getYAxisMinWidth(_ which: ChartYAxis.AxisDependency) -> CGFloat { if (which == .left) { return _leftAxis.minWidth } else { return _rightAxis.minWidth } } /// Sets a maximum width to the specified y axis. /// Zero (0.0) means there's no maximum width open func setYAxisMaxWidth(_ which: ChartYAxis.AxisDependency, width: CGFloat) { if (which == .left) { _leftAxis.maxWidth = width } else { _rightAxis.maxWidth = width } } /// Zero (0.0) means there's no maximum width /// /// **default**: 0.0 (no maximum specified) /// - returns: the (custom) maximum width of the specified Y axis. open func getYAxisMaxWidth(_ which: ChartYAxis.AxisDependency) -> CGFloat { if (which == .left) { return _leftAxis.maxWidth } else { return _rightAxis.maxWidth } } /// - returns the width of the specified y axis. open func getYAxisWidth(_ which: ChartYAxis.AxisDependency) -> CGFloat { if (which == .left) { return _leftAxis.requiredSize().width } else { return _rightAxis.requiredSize().width } } // MARK: - BarLineScatterCandleBubbleChartDataProvider /// - returns: the Transformer class that contains all matrices and is /// responsible for transforming values into pixels on the screen and /// backwards. open func getTransformer(_ which: ChartYAxis.AxisDependency) -> ChartTransformer { if (which == .left) { return _leftAxisTransformer } else { return _rightAxisTransformer } } /// the number of maximum visible drawn values on the chart /// only active when `setDrawValues()` is enabled open var maxVisibleValueCount: Int { get { return _maxVisibleValueCount } set { _maxVisibleValueCount = newValue } } open func inverted(_ axis: ChartYAxis.AxisDependency) -> Bool { return getAxis(axis).inverted } /// - returns: the lowest x-index (value on the x-axis) that is still visible on he chart. open var lowestVisibleXIndex: Int { var pt = CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom) getTransformer(.left).pixelToValue(&pt) return (pt.x <= 0.0) ? 0 : Int(ceil(pt.x)) } /// - returns: the highest x-index (value on the x-axis) that is still visible on the chart. open var highestVisibleXIndex: Int { var pt = CGPoint( x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom) getTransformer(.left).pixelToValue(&pt) guard let data = _data else { return Int(round(pt.x)) } return min(data.xValCount - 1, Int(floor(pt.x))) } }
mit
7fdbcade53001f15a65596eab552c7c0
35.180242
238
0.581124
5.615447
false
false
false
false
apple/swift
stdlib/public/core/StringInterpolation.swift
13
10060
//===--- StringInterpolation.swift - String Interpolation -----------------===// // // 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 // //===----------------------------------------------------------------------===// /// Represents a string literal with interpolations while it is being built up. /// /// Do not create an instance of this type directly. It is used by the compiler /// when you create a string using string interpolation. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." /// /// When implementing an `ExpressibleByStringInterpolation` conformance, /// set the `StringInterpolation` associated type to /// `DefaultStringInterpolation` to get the same interpolation behavior as /// Swift's built-in `String` type and construct a `String` with the results. /// If you don't want the default behavior or don't want to construct a /// `String`, use a custom type conforming to `StringInterpolationProtocol` /// instead. /// /// Extending default string interpolation behavior /// =============================================== /// /// Code outside the standard library can extend string interpolation on /// `String` and many other common types by extending /// `DefaultStringInterpolation` and adding an `appendInterpolation(...)` /// method. For example: /// /// extension DefaultStringInterpolation { /// fileprivate mutating func appendInterpolation( /// escaped value: String, asASCII forceASCII: Bool = false) { /// for char in value.unicodeScalars { /// appendInterpolation(char.escaped(asASCII: forceASCII)) /// } /// } /// } /// /// print("Escaped string: \(escaped: string)") /// /// See `StringInterpolationProtocol` for details on `appendInterpolation` /// methods. /// /// `DefaultStringInterpolation` extensions should add only `mutating` members /// and should not copy `self` or capture it in an escaping closure. @frozen public struct DefaultStringInterpolation: StringInterpolationProtocol, Sendable { /// The string contents accumulated by this instance. @usableFromInline internal var _storage: String /// Creates a string interpolation with storage pre-sized for a literal /// with the indicated attributes. /// /// Do not call this initializer directly. It is used by the compiler when /// interpreting string interpolations. @inlinable public init(literalCapacity: Int, interpolationCount: Int) { let capacityPerInterpolation = 2 let initialCapacity = literalCapacity + interpolationCount * capacityPerInterpolation _storage = String._createEmpty(withInitialCapacity: initialCapacity) } /// Appends a literal segment of a string interpolation. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. @inlinable public mutating func appendLiteral(_ literal: String) { literal.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) where T: TextOutputStreamable, T: CustomStringConvertible { value.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = "If one cookie costs \(price) dollars, " + /// "\(number) cookies cost \(price * number) dollars." /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) where T: TextOutputStreamable { value.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) where T: CustomStringConvertible { value.description.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) { _print_unlocked(value, &self) } @_alwaysEmitIntoClient public mutating func appendInterpolation(_ value: Any.Type) { _typeName(value, qualified: false).write(to: &self) } /// Creates a string from this instance, consuming the instance in the /// process. @inlinable internal __consuming func make() -> String { return _storage } } extension DefaultStringInterpolation: CustomStringConvertible { @inlinable public var description: String { return _storage } } extension DefaultStringInterpolation: TextOutputStream { @inlinable public mutating func write(_ string: String) { _storage.append(string) } public mutating func _writeASCII(_ buffer: UnsafeBufferPointer<UInt8>) { _storage._guts.append(_StringGuts(buffer, isASCII: true)) } } // While not strictly necessary, declaring these is faster than using the // default implementation. extension String { /// Creates a new instance from an interpolated string literal. /// /// Do not call this initializer directly. It is used by the compiler when /// you create a string using string interpolation. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable @_effects(readonly) public init(stringInterpolation: DefaultStringInterpolation) { self = stringInterpolation.make() } } extension Substring { /// Creates a new instance from an interpolated string literal. /// /// Do not call this initializer directly. It is used by the compiler when /// you create a string using string interpolation. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable @_effects(readonly) public init(stringInterpolation: DefaultStringInterpolation) { self.init(stringInterpolation.make()) } }
apache-2.0
b75df0bf37aff2ff10b81a66db6b292a
37.544061
81
0.638966
4.85053
false
false
false
false
bustoutsolutions/siesta
Tests/Functional/ResourcePathsSpec.swift
1
10150
// // ResourcePathsSpec.swift // Siesta // // Created by Paul on 2015/7/5. // Copyright © 2016 Bust Out Solutions. All rights reserved. // import Siesta import Foundation import Quick import Nimble class ResourcePathsSpec: ResourceSpecBase { override var baseURL: String { "https://zingle.frotz/v1" } override func resourceSpec(_ service: @escaping () -> Service, _ resource: @escaping () -> Resource) { describe("child()") { func expectChild(_ childPath: String, toResolveTo url: String) { expect((resource(), childPath)).to(expandToChildURL(url)) } it("returns a resource with the same service") { expect(resource().child("c").service) == service() } it("resolves empty string as root") { expectChild("", toResolveTo: "https://zingle.frotz/v1/a/b/") } it("resolves bare paths as subpaths") { expectChild("c", toResolveTo: "https://zingle.frotz/v1/a/b/c") } it("resolves paths with / prefix as subpaths") { expectChild("/", toResolveTo: "https://zingle.frotz/v1/a/b/") expectChild("/c", toResolveTo: "https://zingle.frotz/v1/a/b/c") } it("does not resolve ./ or ../") { expectChild("./c", toResolveTo: "https://zingle.frotz/v1/a/b/./c") expectChild("./c/./d", toResolveTo: "https://zingle.frotz/v1/a/b/./c/./d") expectChild("../c", toResolveTo: "https://zingle.frotz/v1/a/b/../c") } it("treats URL-like strings as paths") { expectChild("//other.host/c", toResolveTo: "https://zingle.frotz/v1/a/b//other.host/c") expectChild("ftp://other.host/c", toResolveTo: "https://zingle.frotz/v1/a/b/ftp://other.host/c") } it("escapes characters when necessary") { expectChild("?foo", toResolveTo: "https://zingle.frotz/v1/a/b/%3Ffoo") expectChild(" •⇶", toResolveTo: "https://zingle.frotz/v1/a/b/%20%E2%80%A2%E2%87%B6") } } describe("relative()") { func expectRelativeOf(_ resource: Resource, _ childPath: String, toResolveTo url: String) { expect((resource, childPath)).to(expandToRelativeURL(url)) } func expectRelative(_ childPath: String, toResolveTo url: String) { expectRelativeOf(resource(), childPath, toResolveTo: url) } it("returns a resource with the same service") { expect(resource().relative("c").service) == service() } it("treats bare paths as if they are preceded by ./") { expectRelative("c", toResolveTo: "https://zingle.frotz/v1/a/c") } it("resolves ./") { expectRelative("./c", toResolveTo: "https://zingle.frotz/v1/a/c") expectRelative("././c", toResolveTo: "https://zingle.frotz/v1/a/c") expectRelative("./c/./d", toResolveTo: "https://zingle.frotz/v1/a/c/d") } it("resolves ../") { expectRelative("../c", toResolveTo: "https://zingle.frotz/v1/c") expectRelative("../../c", toResolveTo: "https://zingle.frotz/c") expectRelative("../c/../d", toResolveTo: "https://zingle.frotz/v1/d") } it("resolves absolute paths relative to host root") { expectRelative("/c", toResolveTo: "https://zingle.frotz/c") } it("resolves full URLs") { expectRelative("//other.host/c", toResolveTo: "https://other.host/c") expectRelative("ftp://other.host/c", toResolveTo: "ftp://other.host/c") } it("can add a query string") { expectRelative("?foo=1", toResolveTo: "https://zingle.frotz/v1/a/b?foo=1") expectRelative("c?foo=1", toResolveTo: "https://zingle.frotz/v1/a/c?foo=1") } it("does not alphabetize query string params, unlike withParam(_:_:)") { expectRelative("?foo=1&bar=2", toResolveTo: "https://zingle.frotz/v1/a/b?foo=1&bar=2") expectRelative("c?foo=1&bar=2", toResolveTo: "https://zingle.frotz/v1/a/c?foo=1&bar=2") } it("entirely replaces or removes an existing query string") { let resourceWithParam = resource().withParam("foo", "bar") expectRelativeOf(resourceWithParam, "?baz=fez", toResolveTo: "https://zingle.frotz/v1/a/b?baz=fez") expectRelativeOf(resourceWithParam, "./c", toResolveTo: "https://zingle.frotz/v1/a/c") } it("allows duplicate param keys in supplied query string") { let resourceWithParam = resource().withParam("foo", "bar") expectRelativeOf(resourceWithParam, "?baz=fez&baz=fuzz", toResolveTo: "https://zingle.frotz/v1/a/b?baz=fez&baz=fuzz") } } describe("optionalRelative()") { it("works like relative() if arg is present") { expect(resource().optionalRelative("c")) === resource().relative("c") } it("returns nil if arg is absent") { expect(resource().optionalRelative(nil)).to(beNil()) } } describe("withParam()") { it("adds params") { expect(resource().withParam("foo", "bar").url.absoluteString) == "https://zingle.frotz/v1/a/b?foo=bar" } it("escapes params") { expect(resource().withParam("fo=o", "ba r+baz").url.absoluteString) == "https://zingle.frotz/v1/a/b?fo%3Do=ba%20r%2Bbaz" } let resourceWithParams = specVar { resource().withParam("foo", "bar").withParam("zoogle", "oogle") } it("alphabetizes params (to help with resource uniqueness)") { expect(resourceWithParams().withParam("plop", "blop").url.absoluteString) == "https://zingle.frotz/v1/a/b?foo=bar&plop=blop&zoogle=oogle" } it("modifies existing params without affecting others") { expect(resourceWithParams().withParam("zoogle", "zonk").url.absoluteString) == "https://zingle.frotz/v1/a/b?foo=bar&zoogle=zonk" } it("treats empty string value as empty param") { expect(resourceWithParams().withParam("foo", "").url.absoluteString) == "https://zingle.frotz/v1/a/b?foo&zoogle=oogle" expect(resourceWithParams().withParam("foo", "").withParam("zoogle", "").url.absoluteString) == "https://zingle.frotz/v1/a/b?foo&zoogle" } it("treats nil value as removal") { expect(resourceWithParams().withParam("foo", nil).url.absoluteString) == "https://zingle.frotz/v1/a/b?zoogle=oogle" } it("drops query string if all params removed") { expect(resourceWithParams().withParam("foo", nil).withParam("zoogle", nil).url.absoluteString) == "https://zingle.frotz/v1/a/b" } it("accepts multiple parameters as a dictionary") { expect(resourceWithParams().withParams(["dogcow": "moof", "frogbear": "grribbit"]).url.absoluteString) == "https://zingle.frotz/v1/a/b?dogcow=moof&foo=bar&frogbear=grribbit&zoogle=oogle" } it("allows parameter alteration and removal via dictionary") { expect(resourceWithParams().withParams(["foo": "oof", "zoogle": nil]).url.absoluteString) == "https://zingle.frotz/v1/a/b?foo=oof" } } } } // MARK: - Custom matchers private func resourceExpansionMatcher( _ expectedURL: String, relationshipName: String, relationship: @escaping (Resource,String) -> Resource) -> Predicate<(Resource,String)> { Predicate { inputs in let (resource, path) = try! inputs.evaluate()!, actualURL = relationship(resource, path).url.absoluteString return PredicateResult( bool: actualURL == expectedURL, message: ExpectationMessage.fail( """ Incorrect resource URL resolution: Expected \(relationshipName) \(stringify(path)) of resource \(resource.url) to expand to \(stringify(expectedURL)) but got \(stringify(actualURL)) """)) } } private func expandToChildURL(_ expectedURL: String) -> Predicate<(Resource,String)> { resourceExpansionMatcher(expectedURL, relationshipName: "child") { resource, path in resource.child(path) } } private func expandToRelativeURL(_ expectedURL: String) -> Predicate<(Resource,String)> { resourceExpansionMatcher(expectedURL, relationshipName: "relative") { resource, path in resource.relative(path) } }
mit
1e37d5c0721751345896365743f30753
39.418327
133
0.502119
4.169749
false
false
false
false
PomTTcat/SourceCodeGuideRead_JEFF
RxSwiftGuideRead/RxSwift-master/Tests/RxCocoaTests/RxTest+Controls.swift
3
4304
// // RxTest+Controls.swift // Tests // // Created by Krunoslav Zaher on 3/12/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import RxCocoa import RxSwift import RxRelay import XCTest extension RxTest { func ensurePropertyDeallocated<C, T: Equatable>( _ createControl: () -> C, _ initialValue: T, file: StaticString = #file, line: UInt = #line, _ propertySelector: (C) -> ControlProperty<T> ) where C: NSObject { ensurePropertyDeallocated(createControl, initialValue, comparer: ==, file: file, line: line, propertySelector) } func ensurePropertyDeallocated<C, T>( _ createControl: () -> C, _ initialValue: T, comparer: (T, T) -> Bool, file: StaticString = #file, line: UInt = #line, _ propertySelector: (C) -> ControlProperty<T> ) where C: NSObject { let relay = BehaviorRelay(value: initialValue) let completeExpectation = XCTestExpectation(description: "completion") let deallocateExpectation = XCTestExpectation(description: "deallocation") var lastReturnedPropertyValue: T? autoreleasepool { var control: C! = createControl() let property = propertySelector(control) let disposable = relay.bind(to: property) _ = property.subscribe(onNext: { n in lastReturnedPropertyValue = n }, onCompleted: { completeExpectation.fulfill() disposable.dispose() }) _ = (control as NSObject).rx.deallocated.subscribe(onNext: { _ in deallocateExpectation.fulfill() }) control = nil } wait(for: [completeExpectation, deallocateExpectation], timeout: 3.0, enforceOrder: false) XCTAssertTrue( lastReturnedPropertyValue.map { comparer(initialValue, $0) } ?? false, "last property value (\(lastReturnedPropertyValue.map { "\($0)" } ?? "nil"))) does not match initial value (\(initialValue))", file: file, line: line ) } func ensureEventDeallocated<C, T>(_ createControl: @escaping () -> C, file: StaticString = #file, line: UInt = #line, _ eventSelector: (C) -> ControlEvent<T>) where C: NSObject { return ensureEventDeallocated({ () -> (C, Disposable) in (createControl(), Disposables.create()) }, file: file, line: line, eventSelector) } func ensureEventDeallocated<C, T>(_ createControl: () -> (C, Disposable), file: StaticString = #file, line: UInt = #line, _ eventSelector: (C) -> ControlEvent<T>) where C: NSObject { var completed = false var deallocated = false let outerDisposable = SingleAssignmentDisposable() autoreleasepool { let (control, disposable) = createControl() let eventObservable = eventSelector(control) _ = eventObservable.subscribe(onNext: { n in }, onCompleted: { completed = true }) _ = (control as NSObject).rx.deallocated.subscribe(onNext: { _ in deallocated = true }) outerDisposable.setDisposable(disposable) } outerDisposable.dispose() XCTAssertTrue(deallocated, "event not deallocated", file: file, line: line) XCTAssertTrue(completed, "event not completed", file: file, line: line) } func ensureControlObserverHasWeakReference<C, T>(file: StaticString = #file, line: UInt = #line, _ createControl: @autoclosure() -> (C), _ observerSelector: (C) -> AnyObserver<T>, _ observableSelector: () -> (Observable<T>)) where C: NSObject { var deallocated = false let disposeBag = DisposeBag() autoreleasepool { let control = createControl() let propertyObserver = observerSelector(control) let observable = observableSelector() observable.bind(to: propertyObserver).disposed(by: disposeBag) _ = (control as NSObject).rx.deallocated.subscribe(onNext: { _ in deallocated = true }) } XCTAssertTrue(deallocated, "control observer reference is over-retained", file: file, line: line) } }
mit
a924ab4b3219ed4946874975e59d0c38
34.270492
248
0.604927
4.856659
false
false
false
false
glimpseio/ChannelZ
Sources/ChannelZ/Operators.swift
1
10045
// // Tuples.swift // ChannelZ // // Created by Marc Prud'hommeaux on 2/4/15. // Copyright (c) 2015 glimpse.io. All rights reserved. // import Foundation // MARK: Operators /// Channel merge operation for two channels of the same type (operator form of `merge`) @inlinable public func + <S1, S2, T>(lhs: Channel<S1, T>, rhs: Channel<S2, T>)->Channel<(S1, S2), T> { return lhs.merge(rhs) } /// Channel concat operation for two channels of the same source and element types (operator form of `concat`) @inlinable public func + <S, T>(lhs: Channel<S, T>, rhs: Channel<S, T>)->Channel<[S], (S, T)> { return lhs.concat(rhs) } /// Operator for adding a receiver to the given channel @discardableResult @inlinable public func ∞> <S, T>(lhs: Channel<S, T>, rhs: @escaping (T)->Void)->Receipt { return lhs.receive(rhs) } infix operator ∞> : AssignmentPrecedence /// Sets the value of a channel's source that is sourced by a `Sink` @inlinable public func ∞= <T, S: ReceiverType>(lhs: Channel<S, T>, rhs: S.Pulse)->Void { lhs.source.receive(rhs) } infix operator ∞= : AssignmentPrecedence /// Reads the value from the given channel's source that is sourced by an Sink implementation @inlinable public postfix func ∞? <T, S: StateEmitterType>(c: Channel<S, T>)->S.RawValue { return c.source.rawValue } postfix operator ∞? /// Increments the value of the source of the channel; works, but only when we define one of them //@inlinable public postfix func ++ <T, S: ReceiverType where S.Value == Int>(channel: Channel<S, T>)->Void { channel ∞= channel∞? + 1 } //@inlinable public postfix func ++ <T, S: ReceiverType where S.Value == Int8>(channel: Channel<S, T>)->Void { channel ∞= channel∞? + 1 } //@inlinable public postfix func ++ <T, S: ReceiverType where S.Value == Int16>(channel: Channel<S, T>)->Void { channel ∞= channel∞? + 1 } //@inlinable public postfix func ++ <T, S: ReceiverType where S.Value == Float>(channel: Channel<S, T>)->Void { channel ∞= channel∞? + Float(1.0) } // MARK: Operators that create state channels prefix operator ∞ prefix operator ∞= prefix operator ∞?= postfix operator =∞ postfix operator ∞ // MARK: Prefix operators /// Creates a channel from the given state source such that emits items for every state operation @inlinable public prefix func ∞ <S: StateEmitterType, T>(source: S)->Channel<S, T> where S.RawValue == T { return source.transceive().new() } /// Creates a distinct sieved channel from the given Equatable state source such that only state changes are emitted /// /// - See: `Channel.changes` @inlinable public prefix func ∞= <S: StateEmitterType, T: Equatable>(source: S) -> Channel<S, T> where S.RawValue == T { return source.transceive().sieve().new() } @usableFromInline prefix func ∞?=<S: StateEmitterType, T: Equatable>(source: S) -> Channel<S, T?> where S.RawValue: _OptionalType, T == S.RawValue.Wrapped { let wrappedState: Channel<S, Mutation<S.RawValue>> = source.transceive() // each of the three following statements should be equivalent, but they return subtly different results! Only the first is correct. let unwrappedState: Channel<S, Mutation<T?>> = wrappedState.map({ pair in Mutation(old: pair.old?.toOptional(), new: pair.new.toOptional()) }) // let unwrappedState: Channel<S, (old: T??, new: T?)> = wrappedState.map({ pair in (pair.old?.map({$0}), pair.new.map({$0})) }) // func unwrap(pair: (S.Value?, S.Value)) -> (old: T??, new: T?) { return (pair.old?.unwrap, pair.new.unwrap) } // let unwrappedState: Channel<S, (old: T??, new: T?)> = wrappedState.map({ pair in unwrap(pair) }) let notEqual: Channel<S, Mutation<T?>> = unwrappedState.filter({ pair in pair.old == nil || pair.old! != pair.new }) let changedState: Channel<S, T?> = notEqual.map({ pair in pair.new }) return changedState } /// Creates a distinct sieved channel from the given Equatable Optional ValueTransceiver @inlinable public prefix func ∞= <T: Equatable>(source: ValueTransceiver<T?>) -> Channel<ValueTransceiver<T?>, T?> { return ∞?=source } // MARK: Postfix operators /// Creates a source for the given property that will emit state operations @inlinable public postfix func ∞ <T>(value: T) -> ValueTransceiver<T> { return ValueTransceiver(value) } /// Creates a source for the given property that will emit state operations @inlinable public postfix func =∞ <T: Equatable>(value: T) -> ValueTransceiver<T> { return ValueTransceiver(value) } /// Creates a source for the given property that will emit state operations @inlinable public postfix func =∞ <T: Equatable>(value: T?) -> ValueTransceiver<T?> { return value∞ } // MARK: Infix operators /// Creates a one-way pipe betweek a `Channel` and a `Sink`, such that all receiver emissions are sent to the sink. /// This is the operator form of `pipe` @discardableResult @inlinable public func ∞-> <S1, T, S2: ReceiverType>(r: Channel<S1, T>, s: S2) -> Receipt where T == S2.Pulse { return r.receive(s) } infix operator ∞-> : AssignmentPrecedence /// Creates a one-way pipe betweek a `Channel` and an `Equatable` `Sink`, such that all receiver emissions are sent to the sink. /// This is the operator form of `pipe` @discardableResult @inlinable public func ∞=> <S1, S2, T1, T2>(c1: Channel<S1, T1>, c2: Channel<S2, T2>) -> Receipt where S2: ReceiverType, S2.Pulse == T1 { return c1.conduct(c2) } infix operator ∞=> : AssignmentPrecedence /// Creates a two-way binding betweek two `Channel`s whose source is an `Equatable` `Sink`, such that when either side is /// changed, the other side is updated /// This is the operator form of `bind` @discardableResult @inlinable public func <=∞=> <S1, S2, T1, T2>(r1: Channel<S1, T1>, r2: Channel<S2, T2>)->Receipt where S1: TransceiverType, S2: TransceiverType, S1.RawValue == T2, S2.RawValue == T1, S1.RawValue: Equatable, S2.RawValue: Equatable { return r1.bind(r2) } infix operator <=∞=> : AssignmentPrecedence /// Creates a two-way conduit betweek two `Channel`s whose source is an `Equatable` `Sink`, such that when either side is /// changed, the other side is updated /// This is the operator form of `channel` @discardableResult @inlinable public func <∞> <S1, S2, T1, T2>(r1: Channel<S1, T1>, r2: Channel<S2, T2>)->Receipt where S1: ReceiverType, S2: ReceiverType, S1.Pulse == T2, S2.Pulse == T1 { return r1.conduit(r2) } infix operator <∞> : AssignmentPrecedence /// Lossy conduit conversion operators infix operator <~∞~> : AssignmentPrecedence ///// Conduit operator that filters out nil values with a custom transformer @discardableResult @inlinable public func <~∞~> <S1, S2, T1, T2>(lhs: (o: Channel<S1, T1>, f: (T1) -> Optional<S2.Pulse>), rhs: (o: Channel<S2, T2>, f: (T2) -> Optional<S1.Pulse>)) -> Receipt where S1: ReceiverType, S2: ReceiverType { let lhsf = lhs.f let lhsm: Channel<S1, S2.Pulse> = lhs.o.map({ lhsf($0) ?? nil }).some() let rhsf = rhs.f let rhsm: Channel<S2, S1.Pulse> = rhs.o.map({ rhsf($0) ?? nil }).some() return lhsm.conduit(rhsm) } /// Convert (possibly lossily) between two numeric types @discardableResult @inlinable public func <~∞~> <S1, S2, T1, T2>(lhs: Channel<S1, T1>, rhs: Channel<S2, T2>) -> Receipt where S1: ReceiverType, S2: ReceiverType, S1.Pulse: ConduitNumericCoercible, S2.Pulse: ConduitNumericCoercible, T1: ConduitNumericCoercible, T2: ConduitNumericCoercible { return lhs.map({ convertNumericType($0) }).conduit(rhs.map({ convertNumericType($0) })) } /// Convert (possibly lossily) between optional and non-optional types @discardableResult @inlinable public func <~∞~> <S1, S2, T1, T2>(lhs: Channel<S1, Optional<T1>>, rhs: Channel<S2, T2>) -> Receipt where S1: ReceiverType, S2: ReceiverType, S1.Pulse == T2, S2.Pulse == T1 { return lhs.some().conduit(rhs) } @discardableResult @inlinable public func <~∞~> <S1, S2, T1, T2>(lhs: Channel<S1, T1>, rhs: Channel<S2, Optional<T2>>) -> Receipt where S1: ReceiverType, S2: ReceiverType, S1.Pulse == T2, S2.Pulse == T1 { return lhs.conduit(rhs.some()) } #if !os(Linux) // MARK: KVO Operators /// Creates a source for the given property that will emit state operations @inlinable public postfix func ∞ <O, T>(kvt: KeyValueTarget<O, T>) -> KeyValueTransceiver<O, T> { return KeyValueTransceiver(target: kvt) } /// Creates a source for the given equatable property that will emit state operations @inlinable public postfix func =∞ <O, T: Equatable>(kvt: KeyValueTarget<O, T>) -> KeyValueTransceiver<O, T> { return KeyValueTransceiver(target: kvt) } // MARK: Infix operators /// Use the specified accessor to determine the keyPath for the given autoclosure /// For example, slider§slider.doubleValue will return: (slider, { slider.doubleValue }, "doubleValue") @inlinable public func § <O: NSObject, T>(object: O, keyPath: KeyPath<O, T>) -> KeyValueTarget<O, T> { return KeyValueTarget(target: object, keyPath: keyPath) } @inlinable public func § <O: NSObject, T>(object: O, keyPath: (KeyPath<O, T>, String)) -> KeyValueTarget<O, T> { return KeyValueTarget(target: object, keyPath: keyPath.0, path: keyPath.1) } infix operator § : NilCoalescingPrecedence /// Operation to create a channel from an object's keyPath; shorthand for ∞(object§getter)∞ @inlinable public func ∞ <O: NSObject, T>(object: O, keyPath: KeyPath<O, T>) -> KeyValueChannel<O, T> { return ∞(object§keyPath)∞ } /// Operation to create a channel from an object's keyPath; shorthand for ∞(object§getter)∞ @inlinable public func ∞ <O: NSObject, T>(object: O, keyPath: (KeyPath<O, T>, String)) -> KeyValueChannel<O, T> { return ∞(object§keyPath)∞ } /// Operation to create a channel from an object's equatable keyPath; shorthand for ∞=(object§getter)=∞ @inlinable public func ∞ <O: NSObject, T: Equatable>(object: O, keyPath: KeyPath<O, T>) -> KeyValueChannel<O, T> { return ∞=(object§keyPath)=∞ } infix operator ∞ : NilCoalescingPrecedence #endif
mit
f0558ef4708a4ae00626a443588a1311
45.341121
271
0.697691
3.352603
false
false
false
false
sawijaya/UIFloatPHTextField
UIFloatPHTextField/UIDropdownTextField.swift
1
14217
// // UIDropdownTextField.swift // // Created by Salim Wijaya // Copyright © 2017. All rights reserved. // import Foundation import UIKit public class UIDropdownTextField: UIFloatPHTextField { public struct MapDictionary { public var text: String public var value: String public var image: String } public var mapDictionary: MapDictionary = MapDictionary(text: "text", value: "value", image: "image") public var items:[Item<ItemImage>] = [] fileprivate var isFilter: Bool = false fileprivate var itemsFilter:[Item<ItemImage>] = [] public var selectedItem: Item<ItemImage>? public var value: String? private var listView: UITableView! private var dropdownTextFieldButton: UIButton! public var dropdownButtonTintColor: UIColor = UIColor.black { didSet{ if self.dropdownTextFieldButton != nil { self.dropdownTextFieldButton.imageView?.tintColor = self.dropdownButtonTintColor } } } private let actLoading: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray) fileprivate var imageView: UIImageView! public var isThumbnail: Bool = false // MARK: init override public func awakeFromNib() { super.awakeFromNib() self.setup() } override init(frame: CGRect) { super.init(frame: frame) self.setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } // MARK: - override func setup(){ super.setup() self.setupDropdownButton() self.setupAutoCompleteTable() self.setupImageView() } override public var isUnderline: Bool { didSet{ if let _ = self.listView { self.listView.layer.borderColor = self.isUnderline ? self.labelTextPassiveColor.cgColor : self.labelTextActiveColor.cgColor } } } private func setupAutoCompleteTable(){ if self.listView != nil { return } let tableView = UITableView(frame: CGRect.zero, style: .plain) tableView.alpha = 0 tableView.layer.borderColor = UIColor.clear.cgColor tableView.layer.borderWidth = 1 tableView.contentInset = UIEdgeInsets(top: 1, left: 0, bottom: 1, right: 0) let x: CGFloat = self.frame.origin.x let y: CGFloat = self.frame.maxY let tableFrame: CGRect = CGRect(x: x, y: y, width: self.frame.width, height: 0) tableView.frame = tableFrame tableView.showsVerticalScrollIndicator = false tableView.showsHorizontalScrollIndicator = false tableView.delegate = self tableView.dataSource = self tableView.bounces = false self.listView = tableView self.listView.tableHeaderView = nil } func setupImageView(){ if self.imageView != nil { return } self.imageView = UIImageView() self.imageView.frame = CGRect(x: 0, y: 0, width: 29, height: 16) self.leftViewMode = .always } override public func leftViewRect(forBounds bounds: CGRect) -> CGRect { var rect: CGRect = super.leftViewRect(forBounds: bounds) rect.origin.x = 6 rect.origin.y = 18 return rect } private func setupDropdownButton(){ if self.dropdownTextFieldButton != nil { return } let bundle: Bundle = Bundle(for: self.classForCoder) self.dropdownTextFieldButton = UIButton(type: .custom) let imageInvisible: UIImage = UIImage(named: "dropdown", in: bundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) ?? UIImage() self.dropdownTextFieldButton.setImage(imageInvisible, for: .normal) self.dropdownTextFieldButton.imageView?.contentMode = .center self.dropdownTextFieldButton.imageView?.tintColor = UIColor.black self.dropdownTextFieldButton.frame = CGRect(x: 0, y: 0, width: 30, height: 25) self.rightView = self.dropdownTextFieldButton self.rightViewMode = .always } private func toggleDropdownPropertiesWith(animationType: UIlabelAnimationType) { self.listView.alpha = (animationType == .show) ? 1 : 0 let tableViewHeight: CGFloat = (animationType == .show) ? 120 : 0 self.listView.layer.borderColor = (animationType == .show) ? self.labelTextActiveColor.cgColor : self.labelTextPassiveColor.cgColor let borderColor: CGColor = self.listView.layer.borderColor ?? UIColor.clear.cgColor self.listView.layer.borderColor = self.isUnderline ? borderColor : UIColor.clear.cgColor var frame: CGRect = self.listView.frame frame.size.height = tableViewHeight self.listView.frame = frame } func toggleDropdownAnimationType(_ animationType: UIlabelAnimationType) { let easingOptions: UIViewAnimationOptions = animationType == .show ? .curveEaseOut : .curveEaseIn if animationType == .show { self.listView.removeFromSuperview() let index: NSInteger = superview?.subviews.count ?? 0 self.superview?.insertSubview(self.listView, at: index) } let combinedOptions: UIViewAnimationOptions = [.beginFromCurrentState, easingOptions] let duration: CGFloat = animationType == .show ? 0.3 : 0.25 UIView.animate(withDuration: TimeInterval(duration), delay: 0, options: combinedOptions, animations: { self.toggleDropdownPropertiesWith(animationType: animationType) }, completion: nil) } private func layoutListView(){ if let listView = self.listView { var frame: CGRect = listView.frame let width: CGFloat = self.frame.width frame.size.width = width listView.frame = frame listView.separatorStyle = .none } } override public func layoutSubviews() { super.layoutSubviews() self.layoutListView() } override public func becomeFirstResponder() -> Bool { if super.becomeFirstResponder() { self.toggleDropdownAnimationType(.show) } return false } override public func resignFirstResponder() -> Bool { if self.canResignFirstResponder { self.toggleDropdownAnimationType(.hide) let item = self.items.filter({ (item: Item) -> Bool in if item.text?.lowercased() == self.text?.lowercased() { return true } return false }).first if item != nil { self.text = item?.text self.value = item?.value if self.isThumbnail { if let data = item?.image?.data { self.imageView.image = UIImage(data: data) self.leftView = self.imageView } else if let image = item?.image?.image { self.imageView.image = image self.leftView = self.imageView } else if let string = item?.image?.string { if let url: URL = URL(string: string) { self.imageView.fph_setImageFromURL(url) self.leftView = self.imageView } else { self.imageView.image = UIImage(named: string) self.leftView = self.imageView } } } } else { self.text = nil self.value = nil self.imageView.image = nil self.leftView = nil } return super.resignFirstResponder() } return false } public func fetchItemsFrom(ulrString: String) { self.listView.tableHeaderView = self.actLoading self.actLoading.startAnimating() let fetch: Fetch = Fetch<JSON>(URL: URL(string: ulrString)!) fetch.request(failure: { (error) in self.actLoading.stopAnimating() }, success: { (json) in if let items:[Any] = json.array { for _item in items { let _itemData:[String:Any] = _item as? [String:Any] ?? [:] var dataItem:[String: Any] = [:] dataItem["text"] = _itemData[self.mapDictionary.text] ?? "" dataItem["value"] = _itemData[self.mapDictionary.value] ?? "" dataItem["image"] = _itemData[self.mapDictionary.image] ?? "" let __item = Item<ItemImage>(data: dataItem) self.items.append(__item) self.listView.reloadData() self.listView.tableHeaderView = nil } } self.actLoading.stopAnimating() }) } override func textDidChange(notification: Notification) { super.textDidChange(notification: notification) guard let object: UITextField = notification.object as? UITextField else { return } if object == self { self.leftView = nil if self.text == nil || self.text == "" { self.isFilter = false self.listView.reloadData() } else { self.isFilter = true self.itemsFilter = [] let objectText: String = self.text?.lowercased() ?? "" for item in self.items { let _text: String = item.text?.lowercased() ?? "" let itemRange: Range? = _text.lowercased().range(of: objectText) if itemRange != nil { self.itemsFilter.append(item) } } self.listView.reloadData() } } } } extension UIDropdownTextField: UITableViewDelegate { public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 30 } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let row: Int = indexPath.row let item = self.isFilter ? self.itemsFilter[row] : self.items[row] self.selectedItem = item self.text = item.text self.value = item.value if self.isThumbnail { if let data = item.image?.data { self.imageView.image = UIImage(data: data) self.leftView = self.imageView } else if let image = item.image?.image { self.imageView.image = image self.leftView = self.imageView } else if let string = item.image?.string { if let url: URL = URL(string: string) { self.imageView.fph_setImageFromURL(url) self.leftView = self.imageView } else { self.imageView.image = UIImage(named: string) self.leftView = self.imageView } } } self.endEditing(true) } } extension UIDropdownTextField: UITableViewDataSource { func createImage(_ image: UIImage, scaleToSize newSize: CGSize) -> UIImage { UIGraphicsBeginImageContext( newSize ) image.draw(in: CGRect(x: 0,y: 0,width: newSize.width,height: newSize.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.isFilter ? self.itemsFilter.count : self.items.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = UITableViewCell(style: .default, reuseIdentifier: "IdentifierCell") let row: Int = indexPath.row let item = self.isFilter ? self.itemsFilter[row] : self.items[row] if self.isThumbnail { cell.imageView?.contentMode = .scaleAspectFit var image: UIImage = UIImage() if let data = item.image?.data { image = UIImage(data: data)! cell.imageView?.image = self.createImage(image, scaleToSize: CGSize(width: 39, height: 26)) } else if let _image = item.image?.image { image = _image cell.imageView?.image = self.createImage(image, scaleToSize: CGSize(width: 39, height: 26)) } else if let string = item.image?.string { if let url: URL = URL(string: string) { let placeholderImage = UIImage.imageWithColor(UIColor.clear, bounds: CGRect(x: 0, y: 0, width: 39, height: 26)) cell.imageView?.fph_setImageFromURL(url, placeholder: placeholderImage, failure: nil, success: { (_image) in UIView.transition(with: self, duration: 0.3, options: .transitionCrossDissolve, animations: { cell.imageView?.image = self.createImage(_image, scaleToSize: CGSize(width: 39, height: 26)) }, completion: nil) }) } else { image = UIImage(named: string)! cell.imageView?.image = self.createImage(image, scaleToSize: CGSize(width: 39, height: 26)) } } } let text: String = item.text ?? "" cell.textLabel?.text = text return cell } }
mit
8e5802b231d887171bf66bda3deff028
38.709497
156
0.56352
5.145132
false
false
false
false
cheeyi/ProjectSora
ProjectSora/ActivitiesTableViewController.swift
1
2541
// // ActivitiesTableViewController.swift // ProjectSora // // Created by Chee Yi Ong on 12/1/15. // Copyright © 2015 Expedia MSP. All rights reserved. // import Foundation import UIKit class ActivitiesTableViewController: UITableViewController { let msp = City(name: "Minneapolis", description: "Best city in the world") let sea = City(name: "Seattle", description: "Second best city in the world") let lax = City(name: "Los Angeles", description: "Third best city in the world") let jfk = City(name: "New York City", description: "Fourth best city in the world") var currentCity: City var activities: [Activity] required init?(coder aDecoder: NSCoder) { self.currentCity = City(name: "TBD", description: "TBD") // set this properly in prepareForSegue: self.activities = [] super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() let menuButton = UIBarButtonItem(title: "Book", style: UIBarButtonItemStyle.Bordered, target: self, action: "openDeeplink") self.navigationItem.rightBarButtonItem = menuButton // Network request let activitiesFetcher = ActivitiesFetcher(cityName: self.currentCity.name) let completion = { (activityArray:[Activity])->Void in self.activities = activityArray dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() }) } activitiesFetcher.startDownloadTask(completion) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.title = "Activities in " + self.currentCity.name } func openDeeplink() { UIApplication.sharedApplication().openURL(NSURL(string : "expda://hotelSearch?location=Minneapolis")!) } // MARK: UITableViewDelegate override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.activities.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("activityCell", forIndexPath: indexPath) dispatch_async(dispatch_get_main_queue(), { cell.imageView!.sd_setImageWithURL(self.activities[indexPath.row].imageURL) cell.textLabel?.text = self.activities[indexPath.row].title }) return cell } }
mit
8fd8bf602729c52789f7cfe2da099f82
36.367647
131
0.664567
4.747664
false
false
false
false
alessandrostone/SwiftGen
Sources/L10n/SwiftGenL10nEnumBuilder.swift
2
8211
import Foundation //@import SwiftIdentifier //@import SwiftGenIndentation public final class SwiftGenL10nEnumBuilder { public init() {} public func addEntry(entry: Entry) { parsedLines.append(entry) } // Localizable.strings files are generally UTF16, not UTF8! public func parseLocalizableStringsFile(path: String, encoding: UInt = NSUTF16StringEncoding) throws { let fileContent = try NSString(contentsOfFile: path, encoding: encoding) let lines = fileContent.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) for case let entry? in lines.map(Entry.init) { addEntry(entry) } } public func build(enumName enumName : String = "L10n", indentation indent : SwiftGenIndentation = .Spaces(4)) -> String { var text = "// Generated using SwiftGen, by O.Halligon — https://github.com/AliSoftware/SwiftGen\n\n" text += "import Foundation\n\n" let t = indent.string guard !parsedLines.isEmpty else { return text + "// No line found in Localizable.strings" } text += "enum \(enumName.asSwiftIdentifier()) {\n" for entry in parsedLines { let caseName = entry.key.asSwiftIdentifier(forbiddenChars: "_") text += "\(t)case \(caseName)" if !entry.types.isEmpty { text += "(" + entry.types.map{ $0.rawValue }.joinWithSeparator(", ") + ")" } text += "\n" } text += "}\n\n" text += "extension \(enumName.asSwiftIdentifier()) : CustomStringConvertible {\n" text += "\(t)var description : String { return self.string }\n\n" text += "\(t)var string : String {\n" text += "\(t)\(t)switch self {\n" for entry in parsedLines { let caseName = entry.key.asSwiftIdentifier(forbiddenChars: "_") text += "\(t)\(t)\(t)case .\(caseName)" if !entry.types.isEmpty { let params = (0..<entry.types.count).map { "let p\($0)" } text += "(" + params.joinWithSeparator(", ") + ")" } text += ":\n" text += "\(t)\(t)\(t)\(t)return \(enumName).tr(\"\(entry.key)\"" if !entry.types.isEmpty { text += ", " let params = (0..<entry.types.count).map { "p\($0)" } text += params.joinWithSeparator(", ") } text += ")\n" } text += "\(t)\(t)}\n" text += "\(t)}\n\n" text += "\(t)private static func tr(key: String, _ args: CVarArgType...) -> String {\n" text += "\(t)\(t)let format = NSLocalizedString(key, comment: \"\")\n" text += "\(t)\(t)return String(format: format, arguments: args)\n" text += "\(t)}\n" text += "}\n\n" text += "func tr(key: \(enumName)) -> String {\n" text += "\(t)return key.string\n" text += "}\n" return text } // MARK: - Public Enum types public enum PlaceholderType : String { case Object = "String" case Float = "Float" case Int = "Int" case Char = "Character" case CString = "UnsafePointer<unichar>" case Pointer = "UnsafePointer<Void>" case Unknown = "Any" init?(formatChar char: Character) { let lcChar = String(char).lowercaseString.characters.first! switch lcChar { case "@": self = .Object case "a", "e", "f", "g": self = .Float case "d", "i", "o", "u", "x": self = .Int case "c": self = .Char case "s": self = .CString case "p": self = .Pointer default: return nil } } public static func fromFormatString(format: String) -> [PlaceholderType] { return SwiftGenL10nEnumBuilder.typesFromFormatString(format) } } public struct Entry { let key: String let types: [PlaceholderType] init(key: String, types: [PlaceholderType]) { self.key = key self.types = types } init(key: String, types: PlaceholderType...) { self.key = key self.types = types } private static var lineRegEx = { return try! NSRegularExpression(pattern: "^\"([^\"]+)\"[ \t]*=[ \t]*\"(.*)\"[ \t]*;", options: []) }() init?(line: String) { let range = NSRange(location: 0, length: (line as NSString).length) if let match = Entry.lineRegEx.firstMatchInString(line, options: [], range: range) { let key = (line as NSString).substringWithRange(match.rangeAtIndex(1)) let translation = (line as NSString).substringWithRange(match.rangeAtIndex(2)) let types = PlaceholderType.fromFormatString(translation) self = Entry(key: key, types: types) } else { return nil } } } // MARK: - Private Helpers private var parsedLines = [Entry]() // "I give %d apples to %@" --> [.Int, .String] private static var formatTypesRegEx : NSRegularExpression = { let pattern_int = "(?:h|hh|l|ll|q|z|t|j)?([dioux])" // %d/%i/%o/%u/%x with their optional length modifiers like in "%lld" let pattern_float = "[aefg]" let position = "([1-9]\\d*\\$)?" // like in "%3$" to make positional specifiers let precision = "[-+]?\\d?(?:\\.\\d)?" // precision like in "%1.2f" return try! NSRegularExpression(pattern: "(?<!%)%\(position)\(precision)(@|\(pattern_int)|\(pattern_float)|[csp])", options: [.CaseInsensitive]) }() private static func typesFromFormatString(formatString: String) -> [PlaceholderType] { let range = NSRange(location: 0, length: (formatString as NSString).length) // Extract the list of chars (conversion specifiers) and their optional positional specifier let chars = formatTypesRegEx.matchesInString(formatString, options: [], range: range).map { match -> (String, Int?) in let range : NSRange if match.rangeAtIndex(3).location != NSNotFound { // [dioux] are in range #3 because in #2 there may be length modifiers (like in "lld") range = match.rangeAtIndex(3) } else { // otherwise, no length modifier, the conversion specifier is in #2 range = match.rangeAtIndex(2) } let char = (formatString as NSString).substringWithRange(range) let posRange = match.rangeAtIndex(1) if posRange.location == NSNotFound { // No positional specifier return (char, nil) } else { // Remove the "$" at the end of the positional specifier, and convert to Int let posRange1 = NSRange(location: posRange.location, length: posRange.length-1) let pos = (formatString as NSString).substringWithRange(posRange1) return (char, Int(pos)) } } // enumerate the conversion specifiers and their optionally forced position and build the array of PlaceholderTypes accordingly var list = [PlaceholderType]() var nextNonPositional = 1 for (str, pos) in chars { if let char = str.characters.first, let p = PlaceholderType(formatChar: char) { let insertionPos = pos ?? nextNonPositional++ if insertionPos > 0 { while list.count <= insertionPos-1 { list.append(.Unknown) } list[insertionPos-1] = p } } } return list } }
mit
ce510a2536e7b8ffe8c5c41e10a9adf9
37.181395
152
0.519674
4.688178
false
false
false
false
onevcat/CotEditor
CotEditor/Sources/SyntaxEditViewController.swift
1
9113
// // SyntaxEditViewController.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2014-04-03. // // --------------------------------------------------------------------------- // // © 2004-2007 nakamuxu // © 2014-2022 1024jp // // 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 // // https://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 Cocoa final class SyntaxEditViewController: NSViewController, NSTextFieldDelegate, NSTableViewDelegate { enum Mode { case edit(_ name: String) case copy(_ name: String) case new } // MARK: Public Properties var mode: Mode = .new { didSet { let manager = SyntaxManager.shared let style: SyntaxManager.StyleDictionary = { switch mode { case .edit(let name), .copy(let name): return manager.settingDictionary(name: name) ?? manager.blankSettingDictionary case .new: return manager.blankSettingDictionary } }() self.style.setDictionary(style) if case .edit(let name) = mode { let isBundled = manager.isBundledSetting(name: name) let isCustomized = manager.isCustomizedSetting(name: name) self.isBundledStyle = isBundled self.isRestoreble = isBundled && isCustomized } } } // MARK: Private Properties @objc private dynamic var menuTitles: [String] = [] // for binding private let style = NSMutableDictionary(dictionary: SyntaxManager.shared.blankSettingDictionary) @objc private dynamic var message: String? @objc private dynamic var isStyleNameValid = true @objc private dynamic var isRestoreble = false @objc private dynamic var isBundledStyle = false private var tabViewController: NSTabViewController? @IBOutlet private weak var menuTableView: NSTableView? @IBOutlet private weak var styleNameField: NSTextField? // MARK: - // MARK: Lifecycle /// prepare embeded TabViewController override func prepare(for segue: NSStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if let destinationController = segue.destinationController as? NSTabViewController { self.tabViewController = destinationController self.menuTitles = destinationController.tabViewItems.map(\.label.localized) destinationController.children.forEach { $0.representedObject = self.style } } } /// setup UI override func viewDidLoad() { super.viewDidLoad() // setup style name field self.styleNameField?.stringValue = { switch self.mode { case .edit(let name): return name case .copy(let name): return SyntaxManager.shared.savableSettingName(for: name, appendingCopySuffix: true) case .new: return "" } }() if self.isBundledStyle { self.styleNameField?.drawsBackground = false self.styleNameField?.isBezeled = false self.styleNameField?.isSelectable = false self.styleNameField?.isEditable = false self.styleNameField?.isBordered = true } if self.isBundledStyle { self.message = "Bundled styles can’t be renamed.".localized } } // MARK: Delegate // NSTextFieldDelegate < styleNameField /// style name did change func controlTextDidChange(_ obj: Notification) { guard let field = obj.object as? NSTextField, field == self.styleNameField else { return } // validate newly input name let styleName = field.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) self.validate(styleName: styleName) } // NSTableViewDelegate < menuTableView /// side menu tableView selection did change func tableViewSelectionDidChange(_ notification: Notification) { guard let tableView = notification.object as? NSTableView else { return assertionFailure() } // switch view self.endEditing() self.tabViewController?.selectedTabViewItemIndex = tableView.selectedRow } /// return if menu item is selectable func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool { // separator cannot be selected return (self.menuTitles[row] != .separator) } // MARK: Action Messages /// restore current settings in editor to default @IBAction func setToFactoryDefaults(_ sender: Any?) { guard case .edit(let name) = self.mode, let style = SyntaxManager.shared.bundledSettingDictionary(name: name) else { return } self.style.setDictionary(style) // update validation result if displayed (self.tabViewController?.tabView.selectedTabViewItem?.viewController as? SyntaxValidationViewController)?.validateStyle() } /// jump to style's destribution URL @IBAction func jumpToURL(_ sender: Any?) { guard let metadata = self.style[SyntaxKey.metadata] as? [String: Any], let urlString = metadata[MetadataKey.distributionURL] as? String, let url = URL(string: urlString) else { return NSSound.beep() } NSWorkspace.shared.open(url) } /// save edit and close editor @IBAction func save(_ sender: Any?) { // fix current input self.endEditing() // trim spaces/tab/newlines in style name let styleName = self.styleNameField?.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" self.styleNameField?.stringValue = styleName // style name validation guard self.validate(styleName: styleName) else { self.view.window?.makeFirstResponder(self.styleNameField) NSSound.beep() return } // validate syntax and display errors guard SyntaxStyleValidator.validate(self.style as! SyntaxManager.StyleDictionary).isEmpty else { // show "Validation" pane let index = self.tabViewController!.tabViewItems.firstIndex { ($0.identifier as? String) == "validation" }! self.menuTableView?.selectRowIndexes([index], byExtendingSelection: false) NSSound.beep() return } // NSMutableDictonary to StyleDictionary let styleDictionary: SyntaxManager.StyleDictionary = self.style.reduce(into: [:]) { (dictionary, item) in guard let key = item.key as? String else { return assertionFailure() } dictionary[key] = item.value } let oldName: String? = { guard case .edit(let name) = self.mode else { return nil } return name }() do { try SyntaxManager.shared.save(settingDictionary: styleDictionary, name: styleName, oldName: oldName) } catch { print(error) } self.dismiss(sender) } // MARK: Private Methods /// validate passed-in style name and return if valid @discardableResult private func validate(styleName: String) -> Bool { if case .edit = self.mode, self.isBundledStyle { return true } // cannot edit style name self.isStyleNameValid = true self.message = nil if case .edit(let name) = self.mode, (styleName.caseInsensitiveCompare(name) == .orderedSame) { return true } let originalName: String? = { guard case .edit(let name) = self.mode else { return nil } return name }() do { try SyntaxManager.shared.validate(settingName: styleName, originalName: originalName) } catch let error as InvalidNameError { self.isStyleNameValid = false self.message = "⚠️ " + error.localizedDescription + " " + error.recoverySuggestion! } catch { assertionFailure("Caught unknown error: \(error)") } return self.isStyleNameValid } }
apache-2.0
eb29ce2913626a11919ece4695c05e69
31.98913
129
0.59385
5.269097
false
false
false
false
PavelGnatyuk/SimplePurchase
SimplePurchase/SimplePurchaseTests/TestPurchaseController.swift
1
901
// // TestPurchaseController.swift // FairyTales // // Created by Pavel Gnatyuk on 26/05/2017. // // import Foundation class TestPurchaseController: PurchaseController { var isReadyToRequest = false var isReadyToPurchase = false var containsProducts = false var identifiers = Set<String>() var requestCounter: Int = 0 required init(identifiers: Set<String>) { self.identifiers = identifiers } convenience init() { self.init(identifiers: Set<String>()) } var onComplete: ((String, Bool, String) -> Void)? func start() { } func requestProducts() -> Bool { requestCounter += 1 return true } func price(identifier: String) -> String { return "" } func buy(identifier: String) -> Bool { return false } func restore() { } }
apache-2.0
5adbeea75e6c3a8d1d7eaf054ba4230b
17.770833
53
0.580466
4.373786
false
false
false
false
salutis/Image-ColorMap
Image+ColorMap.swift
1
2663
// The MIT License (MIT) // // Copyright (c) 2015 Rudolf Adamkovič // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit extension UIImage { func imageByApplyingColorMap(colorMap: ColorMap, quality: Float) -> UIImage { precondition((0 ... 1).contains(quality)) let colorCube = ColorCube(dimension: Int(64 * quality), colorMap: colorMap) return imageByApplyingColorCube(colorCube) } private func imageByApplyingColorCube(colorCube: ColorCube) -> UIImage { let inputCIImage = CoreImage.CIImage(image: self)! let filter = CIFilter(colorCube: colorCube, inputImage: inputCIImage) let outputCIImage = filter.valueForKey(kCIOutputImageKey) as! CoreImage.CIImage let outputCGImage = CIContext().createCGImage(outputCIImage, fromRect: outputCIImage.extent) return UIImage(CGImage: outputCGImage) } } private extension CIFilter { convenience init(colorCube: ColorCube, inputImage: CIImage) { self.init(name: "CIColorCube")! let cubeLength = colorCube.values.count * sizeof(Float) let cubeData = NSData(bytes: colorCube.values, length: cubeLength) setValue(inputImage, forKey: kCIInputImageKey) setValue(colorCube.dimension, forKey: "inputCubeDimension") setValue(cubeData, forKey: "inputCubeData") } var outputImage: UIImage { let outputCIImage = valueForKey(kCIOutputImageKey) as! CoreImage.CIImage let outputCGImage = CIContext().createCGImage(outputCIImage, fromRect: outputCIImage.extent) return UIImage(CGImage: outputCGImage) } }
mit
325db115f39d882f22b900a1be83e6e2
43.366667
100
0.726897
4.550427
false
false
false
false
HTWDD/HTWDresden-iOS
HTWDD/Components/Exams/Main/Views/ExamViewCell.swift
1
2779
// // ExamViewCell.swift // HTWDD // // Created by Mustafa Karademir on 07.08.19. // Copyright © 2019 HTW Dresden. All rights reserved. // import UIKit class ExamViewCell: UITableViewCell { // MARK: - Outlets @IBOutlet weak var main: UIView! @IBOutlet weak var lblExamName: UILabel! @IBOutlet weak var lblExamDate: BadgeLabel! @IBOutlet weak var lblExaminer: UILabel! @IBOutlet weak var lblExamType: BadgeLabel! @IBOutlet weak var lblExamRooms: BadgeLabel! @IBOutlet weak var lblExamBegin: UILabel! @IBOutlet weak var lblExamEnd: UILabel! @IBOutlet weak var separator: UIView! // MARK: - Lifecycle override func awakeFromNib() { super.awakeFromNib() main.apply { $0.backgroundColor = UIColor.htw.cellBackground $0.layer.cornerRadius = 4 } lblExamName.apply { $0.textColor = UIColor.htw.Label.primary } lblExamDate.apply { $0.backgroundColor = UIColor.htw.Badge.date $0.textColor = .white } lblExaminer.apply { $0.textColor = UIColor.htw.Label.secondary } lblExamType.apply { $0.backgroundColor = UIColor.htw.Badge.primary $0.textColor = UIColor.htw.Label.primary } lblExamRooms.apply { $0.backgroundColor = UIColor.htw.Badge.primary $0.textColor = UIColor.htw.Label.primary } lblExamBegin.apply { $0.textColor = UIColor.htw.Label.primary } lblExamEnd.apply { $0.textColor = UIColor.htw.Label.primary } } } // MARK: From Nibloadable extension ExamViewCell: FromNibLoadable { func setup(with model: ExamRealm) { separator.backgroundColor = model.id.materialColor lblExamName.text = model.title lblExamDate.text = model.day lblExamBegin.text = model.startTime.toTime()?.string(format: "HH:mm") ?? (model.startTime.nilWhenEmpty ?? "-") lblExamEnd.text = model.endTime.toTime()?.string(format: "HH:mm") ?? (model.endTime.nilWhenEmpty ?? "-") lblExaminer.text = R.string.localizable.examsExaminer(model.examiner.nilWhenEmpty ?? "-") lblExamType.apply { var examType = model.examType.replacingOccurrences(of: "SP", with: R.string.localizable.examsExamTypeWritten()) examType = examType.replacingOccurrences(of: "MP", with: R.string.localizable.examsExamTypeOral()) $0.text = examType as String } lblExamRooms.text = String(model.rooms.dropFirst().dropLast()).replacingOccurrences(of: "\"", with: "") } }
gpl-2.0
39ff50a5039cc4190b315869fe1bf8fa
32.878049
123
0.603312
4.171171
false
false
false
false
mathcamp/hldb
Example/Todotastic/Carthage/Checkouts/hldb/Carthage/Checkouts/BrightFutures/BrightFuturesTests/InvalidationTokenTests.swift
7
4186
// // InvalidationTokenTests.swift // BrightFutures // // Created by Thomas Visser on 19/01/15. // Copyright (c) 2015 Thomas Visser. All rights reserved. // import XCTest import BrightFutures import Result class InvalidationTokenTests: XCTestCase { func testInvalidationTokenInit() { let token = InvalidationToken() XCTAssert(!token.isInvalid, "a token is valid by default") } func testInvalidateToken() { let token = InvalidationToken() token.invalidate() XCTAssert(token.isInvalid, "a token should become invalid after invalidating") } func testInvalidationTokenFuture() { let token = InvalidationToken() XCTAssertNotNil(token.future, "token should have a future") XCTAssert(!token.future.isCompleted, "token should have a future and not be complete") token.invalidate() XCTAssert(token.future.result?.error != nil, "future should have an error") if let error = token.future.result?.error { XCTAssert(error == BrightFuturesError<NoError>.InvalidationTokenInvalidated) } } func testCompletionAfterInvalidation() { let token = InvalidationToken() let p = Promise<Int, NSError>() p.future.onSuccess(token.validContext) { val in XCTAssert(false, "onSuccess should not get called") }.onFailure(token.validContext) { error in XCTAssert(false, "onSuccess should not get called") } let e = self.expectation() Queue.global.async { token.invalidate() p.success(2) NSThread.sleepForTimeInterval(0.2); // make sure onSuccess is not called e.fulfill() } self.waitForExpectationsWithTimeout(2, handler: nil) } func testNonInvalidatedSucceededFutureOnSuccess() { let token = InvalidationToken() let e = self.expectation() Future<Int, NoError>(value: 3).onSuccess(token.validContext) { val in XCTAssertEqual(val, 3) e.fulfill() } self.waitForExpectationsWithTimeout(2, handler: nil) } func testNonInvalidatedSucceededFutureOnComplete() { let token = InvalidationToken() let e = self.expectation() Future<Int, NoError>(value: 3).onComplete(token.validContext) { res in XCTAssertEqual(res.value!, 3) e.fulfill() } self.waitForExpectationsWithTimeout(2, handler: nil) } func testNonInvalidatedFailedFutureOnFailure() { let token = InvalidationToken() let e = self.expectation() Future<Int, TestError>(error: TestError.JustAnError).onFailure(token.validContext) { err in XCTAssertEqual(err, TestError.JustAnError) e.fulfill() } self.waitForExpectationsWithTimeout(2, handler: nil) } func testStress() { class Counter { var i = 0 } let q = Queue() var token: InvalidationToken! let counter = Counter() for _ in 1...100 { token = InvalidationToken() let currentI = counter.i let e = self.expectation() future { () -> Bool in let sleep: NSTimeInterval = NSTimeInterval(arc4random() % 100) / 100000.0 NSThread.sleepForTimeInterval(sleep) return true }.onSuccess(token.validContext(q.context)) { _ in XCTAssert(!token.isInvalid) XCTAssertEqual(currentI, counter.i, "onSuccess should only get called if the counter did not increment") }.onComplete(Queue.global.context) { _ in NSThread.sleepForTimeInterval(0.0001); e.fulfill() } NSThread.sleepForTimeInterval(0.0005) q.sync { token.invalidate() counter.i += 1 } } self.waitForExpectationsWithTimeout(5, handler: nil) } }
mit
310733051a28e7a19441364f4ae62ab0
30.954198
120
0.582179
5.148831
false
true
false
false
WSDOT/wsdot-ios-app
wsdot/TerminalSelectionViewController.swift
2
2145
// // SailingSelectionViewController.swift // WSDOT // // Created by Logan Sims on 10/2/18. // Copyright © 2018 WSDOT. All rights reserved. import UIKit class TerminalSelectionViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { let cellIdentifier = "terminalCell" var my_parent: RouteDeparturesViewController? = nil var menu_options: [String] = [] var selectedIndex = 0 @IBAction func cancelAction(_ sender: UIBarButtonItem) { self.dismiss(animated: true, completion: {()->Void in}); } @IBAction func infoAction(_ sender: Any) { MyAnalytics.event(category: "Ferries", action: "UIAction", label: "sailings info") self.present(AlertMessages.getAlert("", message: "Select a departing terminal. If location services are enabled, the terminal closest to you will be automatically selected.", confirm: "OK"), animated: true) } override func viewDidLoad() { self.view.backgroundColor = ThemeManager.currentTheme().mainColor } // MARK: Table View Data Source Methods func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menu_options.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) // Configure Cell cell.textLabel?.text = menu_options[indexPath.row] if (indexPath.row == selectedIndex){ cell.accessoryType = .checkmark } else { cell.accessoryType = .none } return cell } // MARK: Table View Delegate Methods func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { MyAnalytics.event(category: "Ferries", action: "UIAction", label: "Select Sailing") my_parent!.terminalSelected(indexPath.row) self.dismiss(animated: true, completion: {()->Void in}); } }
gpl-3.0
7cb19190d0c017325353cd7cdd31905f
32.5
214
0.665112
4.861678
false
false
false
false
iampikuda/iOS-Scribbles
Autolayout 2.0/Autolayout 2/SwipingController+BottomControls.swift
1
3807
// // SwipingController.swift // Autolayout 2 // // Created by Oluwadamisi Pikuda on 24/12/2017. // Copyright © 2017 Oluwadamisi Pikuda. All rights reserved. // import UIKit class SwipingController: UICollectionViewController, UICollectionViewDelegateFlowLayout { override func viewDidLoad() { super.viewDidLoad() collectionView?.register(PageCell.self, forCellWithReuseIdentifier: "pageCell") setupBottomControlLayout() collectionView?.backgroundColor = .white collectionView?.isPagingEnabled = true } // Public Instance Variables public lazy var pageControl: UIPageControl = { let pc = UIPageControl() pc.currentPage = 0 pc.numberOfPages = viewModel.pages.count pc.currentPageIndicatorTintColor = .activePink pc.pageIndicatorTintColor = .inactivePink return pc }() public let viewModel = ViewModel() // Private Instance Variables public let nextButton: UIButton = { let button = UIButton(type: .system) button.tag = 1 button.setTitle("NEXT", for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14) button.setTitleColor(.activePink, for: .normal) button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: #selector(handleCellNav), for: .touchUpInside) return button }() public let previousButton: UIButton = { let button = UIButton(type: .system) button.tag = -1 button.setTitle("PREV", for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14) button.setTitleColor(.gray, for: .normal) button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: #selector(handleCellNav), for: .touchUpInside) return button }() // Private Instance Methods @objc private func handleCellNav(_ sender: UIButton) { var navTo: Int? if sender.tag < 1 { navTo = max(pageControl.currentPage - 1, 0) pageControl.currentPage = navTo! } else { navTo = min(pageControl.currentPage + 1, viewModel.pages.count - 1) pageControl.currentPage = navTo! } guard let navToPath = navTo else { return } let indexPath = IndexPath(item: navToPath, section: 0) collectionView?.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true) changeNavColour() } private func changeNavColour() { pageControl.currentPage != 0 ? previousButton.setTitleColor(.activePink, for: .normal) : previousButton.setTitleColor(.gray, for: .normal) pageControl.currentPage == viewModel.pages.count - 1 ? nextButton.setTitleColor(.gray, for: .normal) : nextButton.setTitleColor(.activePink, for: .normal) } private func setupBottomControlLayout() { let bottomControlsStackView = UIStackView(arrangedSubviews: [previousButton, pageControl, nextButton]) view.addSubview(bottomControlsStackView) bottomControlsStackView.translatesAutoresizingMaskIntoConstraints = false bottomControlsStackView.distribution = .fillEqually bottomControlsStackView.axis = .horizontal bottomControlsStackView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true bottomControlsStackView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true bottomControlsStackView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true bottomControlsStackView.heightAnchor.constraint(equalToConstant: 50).isActive = true } }
mit
60b06f94133ef89c23767362e3c22fcd
32.385965
123
0.684446
5.171196
false
false
false
false
zetasq/Aztec
Source/HTTP/HTTPRequest/Encoding/HTTPRequest+JSONEncoder.swift
1
1375
// // HTTPRequest+JSONEncoder.swift // Aztec // // Created by Zhu Shengqi on 23/04/2017. // Copyright © 2017 Zhu Shengqi. All rights reserved. // import Foundation extension HTTPRequest { public struct JSONEncoder: HTTPRequestParameterEncoding { public static let `default` = JSONEncoder(options: []) public let options: JSONSerialization.WritingOptions public init(options: JSONSerialization.WritingOptions) { self.options = options } public func encode(_ httpRequest: HTTPRequest, with parameters: HTTPRequest.Parameters) -> AZResult<HTTPRequest, HTTPError.ParameterEncodingError> { return encode(httpRequest, withJSONObject: parameters) } public func encode(_ httpRequest: HTTPRequest, withJSONObject jsonObject: Any) -> AZResult<HTTPRequest, HTTPError.ParameterEncodingError> { var urlRequest = httpRequest.urlRequest do { let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data return .success(HTTPRequest(request: urlRequest)) } catch { return .failure(.jsonEncodingFailed(error)) } } } }
mit
b289f088668354fcb1ebfb4292a782df
31.714286
152
0.688501
5.051471
false
false
false
false
immortal79/BetterUpdates
BetterUpdates/mas-cli/Utilities.swift
1
1129
// // Utilities.swift // mas-cli // // Created by Andrew Naylor on 14/09/2016. // Copyright © 2016 Andrew Naylor. All rights reserved. // /// A collection of output formatting helpers /// Terminal Control Sequence Indicator let csi = "\u{001B}[" func printInfo(_ message: String) { guard isatty(fileno(stdout)) != 0 else { print("==> \(message)") return } // Blue bold arrow, Bold text print("\(csi)1;34m==>\(csi)0m \(csi)1m\(message)\(csi)0m") } func printWarning(_ message: String) { guard isatty(fileno(stdout)) != 0 else { print("Warning: \(message)") return } // Yellow, underlined "Warning:" prefix print("\(csi)4;33mWarning:\(csi)0m \(message)") } func printError(_ message: String) { guard isatty(fileno(stdout)) != 0 else { print("Warning: \(message)") return } // Red, underlined "Error:" prefix print("\(csi)4;31mError:\(csi)0m \(message)") } func clearLine() { guard isatty(fileno(stdout)) != 0 else { return } print("\(csi)2K\(csi)0G", terminator: "") fflush(stdout) }
mit
51801f8ea3b26855df346318df7de597
21.117647
62
0.583333
3.327434
false
false
false
false
danwey/INSPhotoGallery
INSPhotoGallery/INSPhotosViewController.swift
1
17185
// // INSPhotosViewController.swift // INSPhotoViewer // // Created by Michal Zaborowski on 28.02.2016. // Copyright © 2016 Inspace Labs Sp z o. o. Spółka Komandytowa. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this library 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 public typealias INSPhotosViewControllerReferenceViewHandler = (photo: INSPhotoViewable) -> (UIView?) public typealias INSPhotosViewControllerNavigateToPhotoHandler = (photo: INSPhotoViewable) -> () public typealias INSPhotosViewControllerDismissHandler = (viewController: INSPhotosViewController) -> () public typealias INSPhotosViewControllerLongPressHandler = (photo: INSPhotoViewable, gestureRecognizer: UILongPressGestureRecognizer) -> (Bool) public class INSPhotosViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, UIViewControllerTransitioningDelegate { /* * Returns the view from which to animate for object conforming to INSPhotoViewable */ public var referenceViewForPhotoWhenDismissingHandler: INSPhotosViewControllerReferenceViewHandler? /* * Called when a new photo is displayed through a swipe gesture. */ public var navigateToPhotoHandler: INSPhotosViewControllerNavigateToPhotoHandler? /* * Called before INSPhotosViewController will start a user-initiated dismissal. */ public var willDismissHandler: INSPhotosViewControllerDismissHandler? /* * Called after the INSPhotosViewController has been dismissed by the user. */ public var didDismissHandler: INSPhotosViewControllerDismissHandler? /* * Called when a photo is long pressed. */ public var longPressGestureHandler: INSPhotosViewControllerLongPressHandler? /* * The overlay view displayed over photos, can be changed but must implement INSPhotosOverlayViewable */ public var overlayView: INSPhotosOverlayViewable = INSPhotosOverlayView(frame: CGRect.zero) { willSet { overlayView.view().removeFromSuperview() } didSet { overlayView.photosViewController = self overlayView.view().autoresizingMask = [.FlexibleWidth, .FlexibleHeight] overlayView.view().frame = view.bounds view.addSubview(overlayView.view()) } } /* * INSPhotoViewController is currently displayed by page view controller */ public var currentPhotoViewController: INSPhotoViewController? { return pageViewController.viewControllers?.first as? INSPhotoViewController } /* * Photo object that is currently displayed by INSPhotoViewController */ public var currentPhoto: INSPhotoViewable? { return currentPhotoViewController?.photo } // MARK: - Private private(set) var pageViewController: UIPageViewController! public var dataSource: INSPhotosDataSource let interactiveAnimator: INSPhotosInteractionAnimator = INSPhotosInteractionAnimator() let transitionAnimator: INSPhotosTransitionAnimator = INSPhotosTransitionAnimator() private(set) lazy var singleTapGestureRecognizer: UITapGestureRecognizer = { return UITapGestureRecognizer(target: self, action: #selector(INSPhotosViewController.handleSingleTapGestureRecognizer(_:))) }() private(set) lazy var panGestureRecognizer: UIPanGestureRecognizer = { return UIPanGestureRecognizer(target: self, action: #selector(INSPhotosViewController.handlePanGestureRecognizer(_:))) }() private var interactiveDismissal: Bool = false private var statusBarHidden = false private var shouldHandleLongPressGesture = false // MARK: - Initialization deinit { pageViewController.delegate = nil pageViewController.dataSource = nil } required public init?(coder aDecoder: NSCoder) { dataSource = INSPhotosDataSource(photos: []) super.init(nibName: nil, bundle: nil) initialSetupWithInitialPhoto(nil) } public override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) { dataSource = INSPhotosDataSource(photos: []) super.init(nibName: nil, bundle: nil) initialSetupWithInitialPhoto(nil) } /** The designated initializer that stores the array of objects implementing INSPhotoViewable - parameter photos: An array of objects implementing INSPhotoViewable. - parameter initialPhoto: The photo to display initially. Must be contained within the `photos` array. - parameter referenceView: The view from which to animate. - returns: A fully initialized object. */ public init(photos: [INSPhotoViewable], initialPhoto: INSPhotoViewable? = nil, referenceView: UIView? = nil) { dataSource = INSPhotosDataSource(photos: photos) super.init(nibName: nil, bundle: nil) initialSetupWithInitialPhoto(initialPhoto) transitionAnimator.startingView = referenceView transitionAnimator.endingView = currentPhotoViewController?.scalingImageView.imageView } private func initialSetupWithInitialPhoto(initialPhoto: INSPhotoViewable? = nil) { overlayView.photosViewController = self setupPageViewControllerWithInitialPhoto(initialPhoto) modalPresentationStyle = .Custom transitioningDelegate = self modalPresentationCapturesStatusBarAppearance = true navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: UIButton.init(type: UIButtonType.InfoLight)) setupOverlayViewInitialItems() } private func setupOverlayViewInitialItems() { let textColor = view.tintColor ?? UIColor.whiteColor() if let overlayView = overlayView as? INSPhotosOverlayView { overlayView.photosViewController = self overlayView.titleTextAttributes = [NSForegroundColorAttributeName: textColor] } } // MARK: - View Life Cycle override public func viewDidLoad() { super.viewDidLoad() view.tintColor = UIColor.whiteColor() view.backgroundColor = UIColor.blackColor() pageViewController.view.backgroundColor = UIColor.clearColor() pageViewController.view.addGestureRecognizer(panGestureRecognizer) pageViewController.view.addGestureRecognizer(singleTapGestureRecognizer) addChildViewController(pageViewController) view.addSubview(pageViewController.view) pageViewController.view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] pageViewController.didMoveToParentViewController(self) setupOverlayView() } public override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // This fix issue that navigationBar animate to up // when presentingViewController is UINavigationViewController statusBarHidden = false UIView.animateWithDuration(0.25) { () -> Void in self.setNeedsStatusBarAppearanceUpdate() } } private func setupOverlayView() { updateCurrentPhotosInformation() overlayView.view().autoresizingMask = [.FlexibleWidth, .FlexibleHeight] overlayView.view().frame = view.bounds view.addSubview(overlayView.view()) overlayView.setHidden(true, animated: false) } private func setupPageViewControllerWithInitialPhoto(initialPhoto: INSPhotoViewable? = nil) { pageViewController = UIPageViewController(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: [UIPageViewControllerOptionInterPageSpacingKey: 16.0]) pageViewController.view.backgroundColor = UIColor.clearColor() pageViewController.delegate = self pageViewController.dataSource = self if let photo = initialPhoto where dataSource.containsPhoto(photo) { changeToPhoto(photo, animated: false) } else if let photo = dataSource.photos.first { changeToPhoto(photo, animated: false) } } private func updateCurrentPhotosInformation() { if let currentPhoto = currentPhoto { overlayView.populateWithPhoto(currentPhoto) } } // MARK: - Public /** Displays the specified photo. Can be called before the view controller is displayed. Calling with a photo not contained within the data source has no effect. - parameter photo: The photo to make the currently displayed photo. - parameter animated: Whether to animate the transition to the new photo. */ public func changeToPhoto(photo: INSPhotoViewable, animated: Bool) { if !dataSource.containsPhoto(photo) { return } let photoViewController = initializePhotoViewControllerForPhoto(photo) pageViewController.setViewControllers([photoViewController], direction: .Forward, animated: animated, completion: nil) updateCurrentPhotosInformation() } // MARK: - Gesture Recognizers @objc private func handlePanGestureRecognizer(gestureRecognizer: UIPanGestureRecognizer) { if gestureRecognizer.state == .Began { interactiveDismissal = true dismissViewControllerAnimated(true, completion: nil) } else { interactiveDismissal = false interactiveAnimator.handlePanWithPanGestureRecognizer(gestureRecognizer, viewToPan: pageViewController.view, anchorPoint: CGPoint(x: view.bounds.midX, y: view.bounds.midY)) } } @objc private func handleSingleTapGestureRecognizer(gestureRecognizer: UITapGestureRecognizer) { overlayView.setHidden(!overlayView.view().hidden, animated: true) } // MARK: - View Controller Dismissal public override func dismissViewControllerAnimated(flag: Bool, completion: (() -> Void)?) { if presentedViewController != nil { super.dismissViewControllerAnimated(flag, completion: completion) return } var startingView: UIView? if currentPhotoViewController?.scalingImageView.imageView.image != nil { startingView = currentPhotoViewController?.scalingImageView.imageView } transitionAnimator.startingView = startingView if let currentPhoto = currentPhoto { transitionAnimator.endingView = referenceViewForPhotoWhenDismissingHandler?(photo: currentPhoto) } else { transitionAnimator.endingView = nil } let overlayWasHiddenBeforeTransition = overlayView.view().hidden overlayView.setHidden(true, animated: true) willDismissHandler?(viewController: self) super.dismissViewControllerAnimated(flag) { () -> Void in let isStillOnscreen = self.view.window != nil if isStillOnscreen && !overlayWasHiddenBeforeTransition { self.overlayView.setHidden(false, animated: true) } if !isStillOnscreen { self.didDismissHandler?(viewController: self) } completion?() } } // MARK: - UIPageViewControllerDataSource / UIPageViewControllerDelegate private func initializePhotoViewControllerForPhoto(photo: INSPhotoViewable) -> INSPhotoViewController { let photoViewController = INSPhotoViewController(photo: photo) singleTapGestureRecognizer.requireGestureRecognizerToFail(photoViewController.doubleTapGestureRecognizer) photoViewController.longPressGestureHandler = { [weak self] gesture in guard let weakSelf = self else { return } weakSelf.shouldHandleLongPressGesture = false if let gestureHandler = weakSelf.longPressGestureHandler { weakSelf.shouldHandleLongPressGesture = gestureHandler(photo: photo, gestureRecognizer: gesture) } weakSelf.shouldHandleLongPressGesture = !weakSelf.shouldHandleLongPressGesture if weakSelf.shouldHandleLongPressGesture { guard let view = gesture.view else { return } let menuController = UIMenuController.sharedMenuController() var targetRect = CGRectZero targetRect.origin = gesture.locationInView(view) menuController.setTargetRect(targetRect, inView: view) menuController.setMenuVisible(true, animated: true) } } return photoViewController } @objc public func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { guard let photoViewController = viewController as? INSPhotoViewController, let photoIndex = dataSource.indexOfPhoto(photoViewController.photo), let newPhoto = dataSource[photoIndex-1] else { return nil } return initializePhotoViewControllerForPhoto(newPhoto) } @objc public func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { guard let photoViewController = viewController as? INSPhotoViewController, let photoIndex = dataSource.indexOfPhoto(photoViewController.photo), let newPhoto = dataSource[photoIndex+1] else { return nil } return initializePhotoViewControllerForPhoto(newPhoto) } @objc public func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if completed { updateCurrentPhotosInformation() if let currentPhotoViewController = currentPhotoViewController { navigateToPhotoHandler?(photo: currentPhotoViewController.photo) } } } // MARK: - UIViewControllerTransitioningDelegate public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { transitionAnimator.dismissing = false return transitionAnimator } public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { transitionAnimator.dismissing = true return transitionAnimator } public func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { if interactiveDismissal { transitionAnimator.endingViewForAnimation = transitionAnimator.endingView?.ins_snapshotView() interactiveAnimator.animator = transitionAnimator interactiveAnimator.shouldAnimateUsingAnimator = transitionAnimator.endingView != nil interactiveAnimator.viewToHideWhenBeginningTransition = transitionAnimator.startingView != nil ? transitionAnimator.endingView : nil return interactiveAnimator } return nil } // MARK: - UIResponder @objc public override func copy(sender: AnyObject?) { UIPasteboard.generalPasteboard().image = currentPhoto?.image ?? currentPhotoViewController?.scalingImageView.image } public override func canBecomeFirstResponder() -> Bool { return true } public override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { if let _ = currentPhoto?.image ?? currentPhotoViewController?.scalingImageView.image where shouldHandleLongPressGesture && action == #selector(NSObject.copy(_:)) { return true } return false } // MARK: - Status Bar public override func prefersStatusBarHidden() -> Bool { if let parentStatusBarHidden = presentingViewController?.prefersStatusBarHidden() where parentStatusBarHidden == true { return parentStatusBarHidden } return statusBarHidden } public override func preferredStatusBarStyle() -> UIStatusBarStyle { return .Default } public override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation { return .Fade } }
apache-2.0
b49fbbdce4cfdd5f57e1e1f7b467d258
41.84788
224
0.700733
6.127675
false
false
false
false
longitachi/ZLPhotoBrowser
Sources/Edit/ZLFilter.swift
1
10227
// // ZLFilter.swift // ZLPhotoBrowser // // Created by long on 2020/10/9. // // Copyright (c) 2020 Long Zhang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit /// Filter code reference from https://github.com/Yummypets/YPImagePicker public typealias ZLFilterApplierType = (_ image: UIImage) -> UIImage @objc public enum ZLFilterType: Int { case normal case chrome case fade case instant case process case transfer case tone case linear case sepia case mono case noir case tonal var coreImageFilterName: String { switch self { case .normal: return "" case .chrome: return "CIPhotoEffectChrome" case .fade: return "CIPhotoEffectFade" case .instant: return "CIPhotoEffectInstant" case .process: return "CIPhotoEffectProcess" case .transfer: return "CIPhotoEffectTransfer" case .tone: return "CILinearToSRGBToneCurve" case .linear: return "CISRGBToneCurveToLinear" case .sepia: return "CISepiaTone" case .mono: return "CIPhotoEffectMono" case .noir: return "CIPhotoEffectNoir" case .tonal: return "CIPhotoEffectTonal" } } } public class ZLFilter: NSObject { public var name: String let applier: ZLFilterApplierType? @objc public init(name: String, filterType: ZLFilterType) { self.name = name if filterType != .normal { applier = { image -> UIImage in guard let ciImage = image.zl.toCIImage() else { return image } let filter = CIFilter(name: filterType.coreImageFilterName) filter?.setValue(ciImage, forKey: kCIInputImageKey) guard let outputImage = filter?.outputImage?.zl.toUIImage() else { return image } return outputImage } } else { applier = nil } } /// 可传入 applier 自定义滤镜 @objc public init(name: String, applier: ZLFilterApplierType?) { self.name = name self.applier = applier } } extension ZLFilter { class func clarendonFilter(image: UIImage) -> UIImage { guard let ciImage = image.zl.toCIImage() else { return image } let backgroundImage = getColorImage(red: 127, green: 187, blue: 227, alpha: Int(255 * 0.2), rect: ciImage.extent) let outputCIImage = ciImage.applyingFilter("CIOverlayBlendMode", parameters: [ "inputBackgroundImage": backgroundImage, ]) .applyingFilter("CIColorControls", parameters: [ "inputSaturation": 1.35, "inputBrightness": 0.05, "inputContrast": 1.1, ]) guard let outputImage = outputCIImage.zl.toUIImage() else { return image } return outputImage } class func nashvilleFilter(image: UIImage) -> UIImage { guard let ciImage = image.zl.toCIImage() else { return image } let backgroundImage = getColorImage(red: 247, green: 176, blue: 153, alpha: Int(255 * 0.56), rect: ciImage.extent) let backgroundImage2 = getColorImage(red: 0, green: 70, blue: 150, alpha: Int(255 * 0.4), rect: ciImage.extent) let outputCIImage = ciImage .applyingFilter("CIDarkenBlendMode", parameters: [ "inputBackgroundImage": backgroundImage, ]) .applyingFilter("CISepiaTone", parameters: [ "inputIntensity": 0.2, ]) .applyingFilter("CIColorControls", parameters: [ "inputSaturation": 1.2, "inputBrightness": 0.05, "inputContrast": 1.1, ]) .applyingFilter("CILightenBlendMode", parameters: [ "inputBackgroundImage": backgroundImage2, ]) guard let outputImage = outputCIImage.zl.toUIImage() else { return image } return outputImage } class func apply1977Filter(image: UIImage) -> UIImage { guard let ciImage = image.zl.toCIImage() else { return image } let filterImage = getColorImage(red: 243, green: 106, blue: 188, alpha: Int(255 * 0.1), rect: ciImage.extent) let backgroundImage = ciImage .applyingFilter("CIColorControls", parameters: [ "inputSaturation": 1.3, "inputBrightness": 0.1, "inputContrast": 1.05, ]) .applyingFilter("CIHueAdjust", parameters: [ "inputAngle": 0.3, ]) let outputCIImage = filterImage .applyingFilter("CIScreenBlendMode", parameters: [ "inputBackgroundImage": backgroundImage, ]) .applyingFilter("CIToneCurve", parameters: [ "inputPoint0": CIVector(x: 0, y: 0), "inputPoint1": CIVector(x: 0.25, y: 0.20), "inputPoint2": CIVector(x: 0.5, y: 0.5), "inputPoint3": CIVector(x: 0.75, y: 0.80), "inputPoint4": CIVector(x: 1, y: 1), ]) guard let outputImage = outputCIImage.zl.toUIImage() else { return image } return outputImage } class func toasterFilter(image: UIImage) -> UIImage { guard let ciImage = image.zl.toCIImage() else { return image } let width = ciImage.extent.width let height = ciImage.extent.height let centerWidth = width / 2.0 let centerHeight = height / 2.0 let radius0 = min(width / 4.0, height / 4.0) let radius1 = min(width / 1.5, height / 1.5) let color0 = getColor(red: 128, green: 78, blue: 15, alpha: 255) let color1 = getColor(red: 79, green: 0, blue: 79, alpha: 255) let circle = CIFilter(name: "CIRadialGradient", parameters: [ "inputCenter": CIVector(x: centerWidth, y: centerHeight), "inputRadius0": radius0, "inputRadius1": radius1, "inputColor0": color0, "inputColor1": color1, ])?.outputImage?.cropped(to: ciImage.extent) let outputCIImage = ciImage .applyingFilter("CIColorControls", parameters: [ "inputSaturation": 1.0, "inputBrightness": 0.01, "inputContrast": 1.1, ]) .applyingFilter("CIScreenBlendMode", parameters: [ "inputBackgroundImage": circle!, ]) guard let outputImage = outputCIImage.zl.toUIImage() else { return image } return outputImage } class func getColor(red: Int, green: Int, blue: Int, alpha: Int = 255) -> CIColor { return CIColor( red: CGFloat(Double(red) / 255.0), green: CGFloat(Double(green) / 255.0), blue: CGFloat(Double(blue) / 255.0), alpha: CGFloat(Double(alpha) / 255.0) ) } class func getColorImage(red: Int, green: Int, blue: Int, alpha: Int = 255, rect: CGRect) -> CIImage { let color = getColor(red: red, green: green, blue: blue, alpha: alpha) return CIImage(color: color).cropped(to: rect) } } public extension ZLFilter { @objc static let all: [ZLFilter] = [.normal, .clarendon, .nashville, .apply1977, .toaster, .chrome, .fade, .instant, .process, .transfer, .tone, .linear, .sepia, .mono, .noir, .tonal] @objc static let normal = ZLFilter(name: "Normal", filterType: .normal) @objc static let clarendon = ZLFilter(name: "Clarendon", applier: ZLFilter.clarendonFilter) @objc static let nashville = ZLFilter(name: "Nashville", applier: ZLFilter.nashvilleFilter) @objc static let apply1977 = ZLFilter(name: "1977", applier: ZLFilter.apply1977Filter) @objc static let toaster = ZLFilter(name: "Toaster", applier: ZLFilter.toasterFilter) @objc static let chrome = ZLFilter(name: "Chrome", filterType: .chrome) @objc static let fade = ZLFilter(name: "Fade", filterType: .fade) @objc static let instant = ZLFilter(name: "Instant", filterType: .instant) @objc static let process = ZLFilter(name: "Process", filterType: .process) @objc static let transfer = ZLFilter(name: "Transfer", filterType: .transfer) @objc static let tone = ZLFilter(name: "Tone", filterType: .tone) @objc static let linear = ZLFilter(name: "Linear", filterType: .linear) @objc static let sepia = ZLFilter(name: "Sepia", filterType: .sepia) @objc static let mono = ZLFilter(name: "Mono", filterType: .mono) @objc static let noir = ZLFilter(name: "Noir", filterType: .noir) @objc static let tonal = ZLFilter(name: "Tonal", filterType: .tonal) }
mit
5f86e6713237f544601eab2887385a4b
35.338078
187
0.589658
4.401293
false
false
false
false
AndyQ/CNCPlotter
CNCPlotter/GCodeRenderingView.swift
1
4806
// // GCodeRenderingView.swift // CNCPlotter // // Created by Andy Qua on 01/01/2017. // Copyright © 2017 Andy Qua. All rights reserved. // import Cocoa class GCodeRenderingView: NSView { var paths = [NSBezierPath]() var progressPaths = [NSBezierPath]() var gcodeFile : GCodeFile! var scale : Float = 1.0 // var plotSize = 300 var plotSize = 40 var xScale : CGFloat = 1 var yScale : CGFloat = 1 override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) if gcodeFile != nil { generatePaths() } NSColor.white.setFill() NSRectFill(dirtyRect); NSColor.black.set() // choose color for path in paths { path.stroke() } NSColor.red.set() // choose color for path in progressPaths { path.stroke() } } func generatePaths() { xScale = self.bounds.width / CGFloat(plotSize) yScale = self.bounds.height / CGFloat(plotSize) paths.removeAll() var drawing = false var currentPath = NSBezierPath() currentPath.lineWidth = 2 paths.append(currentPath) var lineNr = 0 for item in gcodeFile.items { lineNr += 1 if item.isPenDown() { drawing = true } else if item.isPenUp() { drawing = false currentPath = NSBezierPath() currentPath.lineWidth = 2 paths.append(currentPath) } else if item.isMove() { var (x,y) = item.getPosition() x *= CGFloat(scale) y *= CGFloat(scale) // Need to scale x and y to our view (in this app, x/y go between plotSize/2 (or 0-plotSize) x = (x + CGFloat(plotSize/2)) * xScale y = (y + CGFloat(plotSize/2)) * yScale // Drawing if !drawing { currentPath.move(to: NSMakePoint(x, y)) // start point } else { currentPath.line(to: NSMakePoint(x, y)) // destination } } } } func resetProgress() { self.progressPaths.removeAll() setNeedsDisplay(self.bounds) } var drawing = false var lastPoint : CGPoint? func showProgress( gcodeLine : GCodeItem ) { // Parse line if gcodeLine.isPenDown() { drawing = true } else if gcodeLine.isPenUp() { drawing = false } else if gcodeLine.isMove() { var (x,y) = gcodeLine.getPosition() x *= CGFloat(scale) y *= CGFloat(scale) // Need to scale x and y to our view (in this app, x/y go between plotSize/2 (or 0-plotSize) x = (x + CGFloat(plotSize/2)) * xScale y = (y + CGFloat(plotSize/2)) * yScale if let lp = lastPoint { if drawing { let path = NSBezierPath() path.lineWidth = 2 path.move(to: NSMakePoint(lp.x, lp.y)) // start point path.line(to: NSMakePoint(x, y)) // destination progressPaths.append(path) } lastPoint = CGPoint(x: x, y: y) } else { lastPoint = CGPoint(x: x, y: y) } } setNeedsDisplay(self.bounds) } func testData() -> [String] { let lines = [ "(Scribbled version of /var/folders/34/c1zmvxyx6_58fy_cbfdwff980000gn/T/ink_ext_XXXXXX.svgUW59SY @ 3500.00)", "( unicorn.py --tab=\"plotter_setup\" --pen-up-angle=50 --pen-down-angle=30 --start-delay=150 --stop-delay=150 --xy-feedrate=3500 --z-feedrate=150 --z-height=0 --finished-height=0 --register-pen=true --x-home=0 --y-home=0 --num-copies=1 --continuous=false --pause-on-layer-change=false /var/folders/34/c1zmvxyx6_58fy_cbfdwff980000gn/T/ink_ext_XXXXXX.svgUW59SY )", "G21 (metric ftw)", "G90 (absolute mode)", "G92 X0.00 Y0.00 Z0.00 (you are here)", "", "M300 S30 (pen down)", "G4 P150 (wait 150ms)", "M300 S50 (pen up)", "G4 P150 (wait 150ms)", "M18 (disengage drives)", "M01 (Was registration test successful?)", "M17 (engage drives if YES, and continue)", "", "(Polyline consisting of 12 segments.)", "G1 X10.85 Y13.59 F3500.00", "M300 S30.00 (pen down)", "G4 P150 (wait 150ms)"] return lines } }
apache-2.0
9f8ae03b0979b69b7df590e013b20977
30
375
0.498439
4.058277
false
false
false
false
Look-ARound/LookARound2
Pods/AZEmptyState/Sources/AZEmptyStateView.swift
1
5986
// // AZEmptyStateView.swift // // // Created by Antonio Zaitoun on 24/05/2017. // Copyright © 2017 Antonio Zaitoun. All rights reserved. // import UIKit @IBDesignable open class AZEmptyStateView: UIControl{ /// The image view fileprivate(set) open var imageView: UIImageView! /// The text label fileprivate(set) open var textLabel: UILabel! /// The button fileprivate(set) open var button: UIButton! /// The empty state image @IBInspectable open var image: UIImage{ get{ return imageView.image! }set{ imageView.image = newValue } } /// The empty state message @IBInspectable open var message: String{ get{ return textLabel.text ?? "" }set{ textLabel.text = newValue } } /// The button's text @IBInspectable open var buttonText: String{ get{ return button.title(for: [])! }set{ button.setTitle(newValue, for: []) } } /// The button tint color @IBInspectable open var buttonTint: UIColor{ get{ return button.tintColor }set{ button.layer.borderColor = newValue.cgColor button.tintColor = newValue } } /// Is the button visable @IBInspectable open var buttonHidden: Bool = false{ didSet{ button.isHidden = buttonHidden } } /// Convenience initailizer /// /// - Parameters: /// - image: The image of the empty state /// - message: The message of the empty sate /// - buttonText: The text on the button, if nil then button will be hidden. convenience public init(image: UIImage ,message: String, buttonText: String? = nil){ self.init(frame: CGRect.zero) self.image = image self.message = message if let buttonText = buttonText { self.buttonText = buttonText }else{ buttonHidden = true } } /// Init with Frame /// /// - Parameter frame: frame for the view. override public init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } /// When adding a target, it will be automatically added to the button. /// /// - Parameters: /// - target: The target object—that is, the object whose action method is called. If you specify nil, UIKit searches the responder chain for an object that responds to the specified action message and delivers the message to that object. /// - action: A selector identifying the action method to be called. You may specify a selector whose signature matches any of the signatures in UIControl. This parameter must not be nil. /// - controlEvents: A bitmask specifying the control-specific events for which the action method is called. Always specify at least one constant. For a list of possible constants, see UIControlEvents. final override public func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControlEvents) { button.addTarget(target, action: action, for: controlEvents) } /// A function that is called when it's time to setup the label. /// /// - Returns: The label view. open func setupLabel()->UILabel{ let textLabel = UILabel() textLabel.adjustsFontSizeToFitWidth = true textLabel.textAlignment = .center textLabel.numberOfLines = 2 return textLabel } /// A function that is called when it's time to setup the image view. /// /// - Returns: The image view. open func setupImage()->UIImageView{ return UIImageView() } /// A function that is called when it's time to setup the button. /// /// - Returns: The button. open func setupButton()->UIButton{ let button = UIButton(type: .system) button.layer.cornerRadius = 5 button.layer.borderColor = button.tintColor.cgColor button.layer.borderWidth = 1 return button } /// A function that is called when it's time to setup the stack of the empty state which contains all the views. /// /// - Parameters: /// - imageView: The image view of the empty state. /// - textLabel: The label of the empty state. /// - button: The button of the empty state. /// - Returns: The stack view. open func setupStack(_ imageView: UIImageView,_ textLabel: UILabel,_ button: UIButton)->UIStackView{ let stackView = UIStackView(arrangedSubviews: [imageView,textLabel,button]) stackView.axis = .vertical stackView.alignment = .fill stackView.distribution = .fill stackView.spacing = 10 return stackView } /// The setup function is called from the initializers private func setup(){ backgroundColor = .clear // Setup views imageView = setupImage() textLabel = setupLabel() button = setupButton() let stackView = setupStack(imageView,textLabel,button) // make imageView square imageView.translatesAutoresizingMaskIntoConstraints = false imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: 1.0).isActive = true // add constraints to stackview addSubview(stackView) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.topAnchor.constraint(equalTo: topAnchor).isActive = true stackView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true stackView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true stackView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true } }
apache-2.0
f06c7d919acb9ed9279f3727a52fc17e
30.994652
244
0.620592
5.015088
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Components/Views/UpsideDownTableView.swift
1
5188
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit final class UpsideDownTableView: UITableView { /// The view that allow pan gesture to scroll the tableview weak var pannableView: UIView? override init(frame: CGRect, style: UITableView.Style) { super.init(frame: frame, style: style) UIView.performWithoutAnimation({ self.transform = CGAffineTransform(scaleX: 1, y: -1) }) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var correctedContentInset: UIEdgeInsets { get { let insets = super.contentInset return UIEdgeInsets(top: insets.bottom, left: insets.left, bottom: insets.top, right: insets.right) } set { super.contentInset = UIEdgeInsets(top: newValue.bottom, left: newValue.left, bottom: newValue.top, right: newValue.right) } } var correctedScrollIndicatorInsets: UIEdgeInsets { get { let verticalInsets = super.verticalScrollIndicatorInsets let horizontalInsets = super.horizontalScrollIndicatorInsets return UIEdgeInsets(top: verticalInsets.bottom, left: horizontalInsets.left, bottom: verticalInsets.top, right: horizontalInsets.right) } set { super.scrollIndicatorInsets = UIEdgeInsets(top: newValue.bottom, left: newValue.left, bottom: newValue.top, right: newValue.right) } } var lockContentOffset: Bool = false override var contentOffset: CGPoint { get { return super.contentOffset } set { // Blindly ignoring the SOLID principles, we are modifying the functionality of the parent class. if lockContentOffset { return } /// do not set contentOffset if the user is panning on the bottom edge of pannableView (with 10 pt threshold) if let pannableView = pannableView, self.panGestureRecognizer.location(in: self.superview).y >= pannableView.frame.maxY - 10 { return } super.contentOffset = newValue } } override var tableHeaderView: UIView? { get { return super.tableFooterView } set(tableHeaderView) { tableHeaderView?.transform = CGAffineTransform(scaleX: 1, y: -1) super.tableFooterView = tableHeaderView } } override var tableFooterView: UIView? { get { return super.tableHeaderView } set(tableFooterView) { tableFooterView?.transform = CGAffineTransform(scaleX: 1, y: -1) super.tableHeaderView = tableFooterView } } override func dequeueReusableCell(withIdentifier identifier: String) -> UITableViewCell? { let cell = super.dequeueReusableCell(withIdentifier: identifier) cell?.transform = CGAffineTransform(scaleX: 1, y: -1) return cell } override func scrollToNearestSelectedRow(at scrollPosition: UITableView.ScrollPosition, animated: Bool) { super.scrollToNearestSelectedRow(at: inverseScrollPosition(scrollPosition), animated: animated) } override func scrollToRow(at indexPath: IndexPath, at scrollPosition: UITableView.ScrollPosition, animated: Bool) { super.scrollToRow(at: indexPath, at: inverseScrollPosition(scrollPosition), animated: animated) } override func dequeueReusableCell(withIdentifier identifier: String, for indexPath: IndexPath) -> UITableViewCell { let cell = super.dequeueReusableCell(withIdentifier: identifier, for: indexPath) cell.transform = CGAffineTransform(scaleX: 1, y: -1) return cell } func inverseScrollPosition(_ scrollPosition: UITableView.ScrollPosition) -> UITableView.ScrollPosition { if scrollPosition == .top { return .bottom } else if scrollPosition == .bottom { return .top } else { return scrollPosition } } }
gpl-3.0
546182b6e4e9f2c5291ad47bd7fee0e4
34.534247
147
0.611025
5.45531
false
false
false
false
einsteinx2/iSub
Carthage/Checkouts/KSHLSPlayer/Carthage/Checkouts/swifter/Sources/HttpRequest.swift
1
5869
// // HttpRequest.swift // Swifter // Copyright (c) 2015 Damian Kołakowski. All rights reserved. // import Foundation public class HttpRequest { public var path: String = "" public var queryParams: [(String, String)] = [] public var method: String = "" public var headers: [String: String] = [:] public var body: [UInt8] = [] public var address: String? = "" public var params: [String: String] = [:] public func parseUrlencodedForm() -> [(String, String)] { guard let contentTypeHeader = headers["content-type"] else { return [] } let contentTypeHeaderTokens = contentTypeHeader.split(";").map { $0.trim() } guard let contentType = contentTypeHeaderTokens.first where contentType == "application/x-www-form-urlencoded" else { return [] } return String.fromUInt8(body).split("&").map { (param: String) -> (String, String) in let tokens = param.split("=") if let name = tokens.first, value = tokens.last where tokens.count == 2 { return (name.replace("+", new: " ").removePercentEncoding(), value.replace("+", new: " ").removePercentEncoding()) } return ("","") } } public struct MultiPart { public let headers: [String: String] public let body: [UInt8] public var name: String? { return valueFor("content-disposition", parameterName: "name")?.unquote() } public var fileName: String? { return valueFor("content-disposition", parameterName: "filename")?.unquote() } private func valueFor(headerName: String, parameterName: String) -> String? { return headers.reduce([String]()) { (currentResults: [String], header: (key: String, value: String)) -> [String] in guard header.key == headerName else { return currentResults } let headerValueParams = header.value.split(";").map { $0.trim() } return headerValueParams.reduce(currentResults, combine: { (results:[String], token: String) -> [String] in let parameterTokens = token.split(1, separator: "=") if parameterTokens.first == parameterName, let value = parameterTokens.last { return results + [value] } return results }) }.first } } public func parseMultiPartFormData() -> [MultiPart] { guard let contentTypeHeader = headers["content-type"] else { return [] } let contentTypeHeaderTokens = contentTypeHeader.split(";").map { $0.trim() } guard let contentType = contentTypeHeaderTokens.first where contentType == "multipart/form-data" else { return [] } var boundary: String? = nil contentTypeHeaderTokens.forEach({ let tokens = $0.split("=") if let key = tokens.first where key == "boundary" && tokens.count == 2 { boundary = tokens.last } }) if let boundary = boundary where boundary.utf8.count > 0 { return parseMultiPartFormData(body, boundary: "--\(boundary)") } return [] } private func parseMultiPartFormData(data: [UInt8], boundary: String) -> [MultiPart] { var generator = data.generate() var result = [MultiPart]() while let part = nextMultiPart(&generator, boundary: boundary, isFirst: result.isEmpty) { result.append(part) } return result } private func nextMultiPart(inout generator: IndexingGenerator<[UInt8]>, boundary: String, isFirst: Bool) -> MultiPart? { if isFirst { guard nextMultiPartLine(&generator) == boundary else { return nil } } else { nextMultiPartLine(&generator) } var headers = [String: String]() while let line = nextMultiPartLine(&generator) where !line.isEmpty { let tokens = line.split(":") if let name = tokens.first, value = tokens.last where tokens.count == 2 { headers[name.lowercaseString] = value.trim() } } guard let body = nextMultiPartBody(&generator, boundary: boundary) else { return nil } return MultiPart(headers: headers, body: body) } private func nextMultiPartLine(inout generator: IndexingGenerator<[UInt8]>) -> String? { var result = String() while let value = generator.next() { if value > HttpRequest.CR { result.append(Character(UnicodeScalar(value))) } if value == HttpRequest.NL { break } } return result } static let CR = UInt8(13) static let NL = UInt8(10) private func nextMultiPartBody(inout generator: IndexingGenerator<[UInt8]>, boundary: String) -> [UInt8]? { var body = [UInt8]() let boundaryArray = [UInt8](boundary.utf8) var matchOffset = 0; while let x = generator.next() { matchOffset = ( x == boundaryArray[matchOffset] ? matchOffset + 1 : 0 ) body.append(x) if matchOffset == boundaryArray.count { body.removeRange(Range<Int>(start: body.count-matchOffset, end: body.count)) if body.last == HttpRequest.NL { body.removeLast() if body.last == HttpRequest.CR { body.removeLast() } } return body } } return nil } }
gpl-3.0
3458f3302ae11fe637b1619cc7287335
37.103896
127
0.546694
4.877805
false
false
false
false
steelwheels/KiwiControls
Source/Controls/KCRadioButton.swift
1
2150
/** * @file KCRadioButton.swift * @brief Define KCRadioButton class * @par Copyright * Copyright (C) 20202Steel Wheels Project */ #if os(OSX) import Cocoa #else import UIKit #endif import CoconutData public class KCRadioButton: KCInterfaceView { public typealias CallbackFunction = KCRadioButtonCore.CallbackFunction public typealias Status = KCRadioButtonCore.Status #if os(OSX) public override init(frame : NSRect){ super.init(frame: frame) ; setup() ; } #else public override init(frame: CGRect){ super.init(frame: frame) ; setup() } #endif public convenience init(){ #if os(OSX) let frame = NSRect(x: 0.0, y: 0.0, width: 160, height: 60) #else let frame = CGRect(x: 0.0, y: 0.0, width: 160, height: 60) #endif self.init(frame: frame) } public required init?(coder: NSCoder) { super.init(coder: coder) ; setup() ; } private func setup(){ KCView.setAutolayoutMode(view: self) if let newview = loadChildXib(thisClass: KCRadioButtonCore.self, nibName: "KCRadioButtonCore") as? KCRadioButtonCore { setCoreView(view: newview) newview.setup(frame: self.frame) allocateSubviewLayout(subView: newview) } else { fatalError("Can not load KCRadioButtonCore") } } public var buttonId: Int? { get { return coreView.buttonId } set(newval) { coreView.buttonId = newval } } public var title: String { get { return coreView.title } set(newval) { coreView.title = newval } } public var state: Bool { get { return coreView.state } set(newval) { coreView.state = newval } } public var isEnabled: Bool { get { return coreView.isEnabled } set(newval) { coreView.isEnabled = newval } } public var minLabelWidth: Int { get { return coreView.minLabelWidth } set(newval) { coreView.minLabelWidth = newval } } public var callback: CallbackFunction? { get { return coreView.callback } set(newval) { coreView.callback = newval } } open override func accept(visitor vis: KCViewVisitor){ vis.visit(radioButton: self) } private var coreView : KCRadioButtonCore { get { return getCoreView() } } }
lgpl-2.1
bf5a6266bacc89fa73bde8067bde1b13
21.631579
120
0.68186
3.125
false
false
false
false
sgr-ksmt/Alertift
Sources/ActionSheet.swift
1
4635
// // ActionSheet.swift // Alertift // // Created by Suguru Kishimoto on 4/27/17. // Copyright © 2017 Suguru Kishimoto. All rights reserved. // import Foundation import UIKit extension Alertift { /// ActionSheet final public class ActionSheet: AlertType, _AlertType { public typealias Handler = (UIAlertAction, Int) -> Void var _alertController: InnerAlertController! public var alertController: UIAlertController { return _alertController as UIAlertController } public static var backgroundColor: UIColor? public static var buttonTextColor: UIColor? public static var titleTextColor: UIColor? public static var messageTextColor: UIColor? /// Make action sheet /// /// - Parameters: /// - title: The title of the alert. Use this string to get the user’s attention and communicate the reason for the alert. /// - message: Descriptive text that provides additional details about the reason for the alert. /// - Returns: Instance of **ActionSheet** public init(title: String? = nil, message: String? = nil) { buildAlertControlelr(title: title, message: message, style: .actionSheet) } /// Add action to alertController public func action(_ action: Alertift.Action, handler: Handler?) -> Self { return self.action(action, image: nil, handler: handler) } public func action(_ action: Alertift.Action, handler: ShortHandler? = nil) -> Self { return self.action(action) { _, _ in handler?() } } /// Add action to alertController public func action(_ action: Alertift.Action, image: UIImage?, renderingMode: UIImage.RenderingMode = .automatic, handler: Handler?) -> Self { let alertAction = buildAlertAction(action, handler: merge(_alertController.actionHandler, handler ?? { (_, _) in }) ) if let image = image { alertAction.setValue(image.withRenderingMode(renderingMode), forKey: "image") } _alertController.addAction(alertAction) return self } public func action(_ action: Alertift.Action, image: UIImage?, renderingMode: UIImage.RenderingMode = .automatic, handler: ShortHandler? = nil) -> Self { return self.action(action, image: image, renderingMode: renderingMode) { _, _ in handler?() } } /// Add sourceView and sourceRect to **popoverPresentationController**. /// /// If you want to use action sheet on iPad, you have to use this method. /// - Parameters: /// - view: sourceView /// - rect: sourceRect /// - Returns: Myself public func popover(sourceView view: UIView?, sourceRect rect: CGRect) -> Self { _alertController.popoverPresentationController?.sourceView = view _alertController.popoverPresentationController?.sourceRect = rect return self } /// Add sourceView and sourceRect to **popoverPresentationController** using anchorView. /// /// If you want to use action sheet on iPad, you have to use this method. /// - Parameters: /// - anchorView: will be anchor of popoverPresentationController. /// - Returns: Myself public func popover(anchorView: UIView) -> Self { _alertController.popoverPresentationController?.sourceView = anchorView.superview _alertController.popoverPresentationController?.sourceRect = anchorView.frame return self } /// Add barButtonItem to **popoverPresentationController**. /// /// If you want to use action sheet on iPad, you have to use this method. /// - Parameters: /// - barButtonItem: UIBarButtonItem /// - Returns: Myself public func popover(barButtonItem: UIBarButtonItem?) -> Self { _alertController.popoverPresentationController?.barButtonItem = barButtonItem return self } func convertFinallyHandler(_ handler: Any) -> InnerAlertController.FinallyHandler { return { (action, index, _) in (handler as? Handler)?(action, index) } } public func image(_ image: UIImage?, imageTopMargin: Alertift.ImageTopMargin = .none) -> Self { _alertController.setImage(image, imageTopMargin: imageTopMargin) return self } deinit { Debug.log() } } }
mit
b314d58f2581bfabca7d1b510eb991e2
39.278261
161
0.617012
5.354913
false
false
false
false
Aster0id/Swift-StudyNotes
Swift-StudyNotes/L2-S2.swift
1
1405
// // L2-S2.swift // Swift-StudyNotes // // Created by 牛萌 on 15/5/12. // Copyright (c) 2015年 Aster0id.Team. All rights reserved. // import Foundation /** * @class * @brief 2.2 基本运算符 */ class Lesson2Section2 { func run(flag:Bool) { if !flag { return } //MARK: Begin Runing println("\n\n------------------------------------") println(">>>>> Lesson2-Section2 begin running\n\n") // ----------------------------------------- // MARK: 术语 // ----------------------------------------- //-- 多元组 let (a,b) = (3,4) println((a,b)) //-- 取余 //!!! 不同于 C 和 Objective-C, Swift 中是可以对浮点数进行求余的. let c = 8%2.5 //## 结果: 0.5 //-- 自增和自增运算 var i = 0 ++i // 现在 i = 1 // 当 ++ 前置的时候, 先自増再返回. // 当 ++ 后置的时候, 先返回再自增. i = 3 var l1 = (++i)+4 //## 结果: l1=8, i=4 i = 3 var l2 = (i++)+4 //## 结果: l2=7, i=4 //MARK: End Runing println("\n\nLesson2-Section2 end running <<<<<<<") println("------------------------------------\n\n") } }
mit
eb86b7d80d8a9c661578f803ee66ee0a
20.066667
60
0.337292
3.527933
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/LaytoutExtension/Dimension/AnchorSizeComposing.swift
1
2603
import UIKit protocol AnchorDimensionComposing { var root: AnchoringRoot { get } var type: AnchorType { get } @discardableResult func equalTo( _ root: AnchoringRoot, multiplier: CGFloat, constant: CGFloat, priority: UILayoutPriority ) -> NSLayoutConstraint @discardableResult func lessThanOrEqualTo( _ root: AnchoringRoot, multiplier: CGFloat, constant: CGFloat, priority: UILayoutPriority ) -> NSLayoutConstraint @discardableResult func greaterThanOrEqualTo( _ root: AnchoringRoot, multiplier: CGFloat, constant: CGFloat, priority: UILayoutPriority ) -> NSLayoutConstraint @discardableResult func equalTo( constant: CGFloat, priority: UILayoutPriority ) -> NSLayoutConstraint @discardableResult func lessThanOrEqualTo( constant: CGFloat, priority: UILayoutPriority ) -> NSLayoutConstraint @discardableResult func greaterThanOrEqualTo( constant: CGFloat, priority: UILayoutPriority ) -> NSLayoutConstraint } extension AnchorDimensionComposing { var width: ComposedDimensionAnchor { .init(root: root, anchors: [self, root.width]) } var height: ComposedDimensionAnchor { .init(root: root, anchors: [self, root.height]) } func equalToSuperview( multiplier: CGFloat = 1.0, constant: CGFloat = 0.0, priority: UILayoutPriority = .required ) -> NSLayoutConstraint { equalTo( rootSuperview, multiplier: multiplier, constant: constant, priority: priority ) } func lessThanOrEqualToSuperview( multiplier: CGFloat = 1.0, constant: CGFloat = 0.0, priority: UILayoutPriority = .required ) -> NSLayoutConstraint { lessThanOrEqualTo( rootSuperview, multiplier: multiplier, constant: constant, priority: priority ) } func greaterThanOrEqualToSuperview(multiplier: CGFloat = 1.0, constant: CGFloat = 0.0, priority: UILayoutPriority = .required) -> NSLayoutConstraint { greaterThanOrEqualTo( rootSuperview, multiplier: multiplier, constant: constant, priority: priority ) } } private extension AnchorDimensionComposing { var rootSuperview: UIView { if let superview = root.superview { return superview } preconditionFailure("Root doesn't have a superview") } }
mit
46315116cb953387fd22b3919ccc9d71
25.835052
154
0.626969
5.561966
false
false
false
false
SoneeJohn/WWDC
WWDC/TranscriptTableViewController.swift
1
6256
// // TranscriptTableViewController.swift // WWDC // // Created by Guilherme Rambo on 28/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa import ConfCore import RealmSwift extension Notification.Name { static let TranscriptControllerDidSelectAnnotation = Notification.Name("TranscriptControllerDidSelectAnnotation") } class TranscriptTableViewController: NSViewController { var viewModel: SessionViewModel? { didSet { guard viewModel?.identifier != oldValue?.identifier else { return } updateUI() } } init() { super.init(nibName: nil, bundle: nil) identifier = NSUserInterfaceItemIdentifier(rawValue: "transcriptList") } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } lazy var tableView: WWDCTableView = { let v = WWDCTableView() v.wantsLayer = true v.focusRingType = .none v.allowsMultipleSelection = true v.backgroundColor = .clear v.headerView = nil v.rowHeight = 36 v.autoresizingMask = [NSView.AutoresizingMask.width, NSView.AutoresizingMask.height] v.floatsGroupRows = true let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: "transcript")) v.addTableColumn(column) return v }() lazy var scrollView: NSScrollView = { let v = NSScrollView() v.focusRingType = .none v.backgroundColor = .clear v.drawsBackground = false v.borderType = .noBorder v.documentView = self.tableView v.hasVerticalScroller = true v.hasHorizontalScroller = false v.translatesAutoresizingMaskIntoConstraints = false return v }() override func loadView() { view = NSView(frame: NSRect(x: 0, y: 0, width: 300, height: MainWindowController.defaultRect.height)) view.wantsLayer = true view.layer?.backgroundColor = NSColor.darkWindowBackground.cgColor scrollView.frame = view.bounds tableView.frame = view.bounds view.heightAnchor.constraint(equalToConstant: 180).isActive = true view.setContentCompressionResistancePriority(NSLayoutConstraint.Priority.defaultLow, for: .vertical) view.addSubview(scrollView) scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true tableView.dataSource = self tableView.delegate = self } fileprivate var transcript: Transcript? override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(highlightTranscriptLine), name: .HighlightTranscriptAtCurrentTimecode, object: nil) } private func updateUI() { guard let transcript = viewModel?.session.transcript() else { return } self.transcript = transcript tableView.reloadData() } fileprivate var selectionLocked = false fileprivate func withTableViewSelectionLocked(then executeBlock: () -> Void) { selectionLocked = true executeBlock() perform(#selector(unlockTableViewSelection), with: nil, afterDelay: 0) } @objc fileprivate func unlockTableViewSelection() { selectionLocked = false } @objc private func highlightTranscriptLine(_ note: Notification) { withTableViewSelectionLocked { guard let transcript = transcript else { return } guard let timecode = note.object as? String else { return } let annotations = transcript.annotations.filter({ Transcript.roundedStringFromTimecode($0.timecode) == timecode }) guard let annotation = annotations.first else { return } guard let row = transcript.annotations.index(of: annotation) else { return } tableView.selectRowIndexes(IndexSet([row]), byExtendingSelection: false) tableView.scrollRowToVisible(row) } } } extension TranscriptTableViewController: NSTableViewDataSource, NSTableViewDelegate { private struct Constants { static let cellIdentifier = "annotation" static let rowIdentifier = "row" } func numberOfRows(in tableView: NSTableView) -> Int { return transcript?.annotations.count ?? 0 } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { guard let annotations = transcript?.annotations else { return nil } var cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: Constants.cellIdentifier), owner: tableView) as? TranscriptTableCellView if cell == nil { cell = TranscriptTableCellView(frame: .zero) cell?.identifier = NSUserInterfaceItemIdentifier(rawValue: Constants.cellIdentifier) } cell?.annotation = annotations[row] return cell } func tableViewSelectionDidChange(_ notification: Notification) { guard !selectionLocked else { return } guard let transcript = transcript else { return } guard tableView.selectedRow >= 0 && tableView.selectedRow < transcript.annotations.count else { return } let row = tableView.selectedRow let notificationObject = (transcript, transcript.annotations[row]) NotificationCenter.default.post(name: NSNotification.Name.TranscriptControllerDidSelectAnnotation, object: notificationObject) } func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? { var rowView = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: Constants.rowIdentifier), owner: tableView) as? WWDCTableRowView if rowView == nil { rowView = WWDCTableRowView(frame: .zero) rowView?.identifier = NSUserInterfaceItemIdentifier(rawValue: Constants.rowIdentifier) } return rowView } }
bsd-2-clause
4b3154311e7ee1c3eef41dd7c4107d91
32.095238
166
0.686811
5.337031
false
false
false
false
chadjaros/FirebaseMapper
FirebaseMapper/Mapping/SimplePropertyMapping.swift
1
1306
// // SimplePropertyMapping.swift // SwiftMapper // // Created by Chad Jaros on 10/26/15. // Copyright © 2015 Classkick. All rights reserved. // import UIKit class SimplePropertyMapping<ModelType, PropertyType>: PropertyMapping<ModelType> { typealias Setter = (ModelType, PropertyType) -> Void typealias Getter = (ModelType) -> PropertyType typealias OnValueUpdate = (ModelType) -> Void let setter: Setter let getter: Getter let didUpdate: OnValueUpdate? let codec: FirebaseValueCodec<PropertyType> init( uri: String, connectIndicator: ConnectIndicator, getter: Getter, setter: Setter, didUpdate: OnValueUpdate? = nil, codec: FirebaseValueCodec<PropertyType> = DefaultFirebaseValueCodec<PropertyType>()) { self.getter = getter self.setter = setter self.didUpdate = didUpdate self.codec = codec super.init(uri, connectIndicator) } func get(instance: ModelType) -> PropertyType { return getter(instance) } func set(instance: ModelType, value: PropertyType) { // Set value setter(instance, value) // Notify caller if let notify = self.didUpdate { notify(instance) } } }
mit
3e1c1619f73171fc84713dfe259d117e
24.588235
98
0.631418
4.644128
false
false
false
false
VadimPavlov/SMVC
PerfectProject/Classes/Flow/LoginFlow.swift
1
2832
// // LoginFlow.swift // PerfectProject // // Created by Vadim Pavlov on 10/7/16. // Copyright © 2016 Vadim Pavlov. All rights reserved. // import UIKit class LoginFlow { let session: Session let navigationController: UINavigationController typealias LoginFlowCompletion = (User?) -> Void let completion: LoginFlowCompletion init?(session: Session, completion: @escaping LoginFlowCompletion) { let storyboard = UIStoryboard(name: "Login", bundle: nil) if let initial = storyboard.instantiateInitialViewController() as? UINavigationController { self.session = session self.navigationController = initial self.completion = completion } else { assertionFailure("LoginFlow: Initial view controller ins't UINavigationController") return nil } } } // MARK: - Show extension LoginFlow { func showSignInScreen() { // SignIn is root controller in current NavigationController and already displayed /* View */ guard let view = navigationController.viewControllers.first as? LoginView else { assertionFailure("view is not LoginView"); return } /* Controller */ let actions = LoginController.Actions(signIn: session.network.signin, signUp: session.network.signup) let controller = LoginController(actions: actions) { [unowned self] flow in switch flow { case .signup: self.showSignUpScreen() case .user(let user): self.navigationController.dismiss(animated: true, completion: nil) self.completion(user) } } controller.view = view view.events = ViewEvents.onDidLoad(controller.updateState) view.actions = LoginView.Actions( login: controller.signIn, cancelLogin: controller.cancelLogin ) } func showSignUpScreen() { /* View */ let view = LoginView() //... somehow from storyboard /* Controller */ let actions = LoginController.Actions(signIn: session.network.signin, signUp: session.network.signup) let controller = LoginController(actions: actions) { [unowned self] flow in switch flow { case .signup: self.showSignUpScreen() case .user(let user): self.navigationController.dismiss(animated: true, completion: nil) self.completion(user) } } view.events = ViewEvents.onDidLoad(controller.updateState) view.actions = LoginView.Actions( login: controller.signUp, cancelLogin: controller.cancelLogin ) } }
mit
1ca7bfe6ecd73d1cd801e7a6cee8bba0
31.918605
109
0.605793
5.232902
false
false
false
false
clarenceji/Clarence-Ji
Clarence Ji/CJAltimeter.swift
1
1556
// // CJAltimeter.swift // Clarence Ji // // Created by Clarence Ji on 4/16/15. // Copyright (c) 2015 Clarence Ji. All rights reserved. // import Foundation import CoreMotion class CJAltimeter { let altimeter = CMAltimeter() var pressure: Float! func getPressure(_ completion: @escaping (_ success: Bool, _ reading: Float?) -> Void) { if CMAltimeter.isRelativeAltitudeAvailable() { altimeter.startRelativeAltitudeUpdates(to: OperationQueue.current!, withHandler: { (altdata, error) -> Void in self.pressure = altdata?.pressure.floatValue self.altimeter.stopRelativeAltitudeUpdates() completion(true, self.pressure * 10) }) } else { completion(false, nil) } } func setAppMode(_ isPressureAvailable: Bool) { UserDefaults.standard.set(false, forKey: "DarkMode") if isPressureAvailable && (pressure * 10) < 1000 { // Based on Air Pressure, Set Dark Mode UserDefaults.standard.set(true, forKey: "DarkMode") } if !isPressureAvailable { let date = Date() let calendar = Calendar.current let components = (calendar as NSCalendar).components([.hour, .minute], from: date) let hour = components.hour if hour! >= 18 || hour! <= 6 { // Based on Current Time, Set Dark Mode UserDefaults.standard.set(true, forKey: "DarkMode") } } } }
gpl-3.0
9874c337bb414823cd44400bbc55d752
31.416667
122
0.580334
4.523256
false
false
false
false
davidear/PasswordMenu
PasswordMenu/Module/PMDetailControllerCell.swift
1
3785
// // PMDetailControllerCell.swift // PasswordMenu // // Created by DaiFengyi on 15/11/20. // Copyright © 2015年 DaiFengyi. All rights reserved. // /** * 为什么不用accessoryView,因为在edit的状态下,accessoryView会被替换成移动的icon,所以坚持自己加rightButton 通过cell的edit来控制cell的各种形态不是个很好的注意,定制化太高,code很敏感,还是应该在数据源中设置type或者edit标签来控制 目前已更新为通过两个参数:hasRightButton和showRightButton来决定是否显示 */ import UIKit import SnapKit class PMDetailControllerCell: UITableViewCell , UITextFieldDelegate { weak var superController: PMDetailController? var hasRightButton = false // 该参数表示cell本身是否具有右侧按钮,由element的type决定 var showRightButton = false {// 该参数是提供给controller根据情况设置的,表示是否显示右侧按钮 didSet { let show = showRightButton && hasRightButton rightButton.hidden = !show rightButton.snp_updateConstraints(closure: { (make) -> Void in make.width.equalTo(show ? 30 : 0) }) } } /** * 通过ele的didSet来实现自定义类型cell */ var ele: Element? { didSet { if let lt = ele?.leftText { leftField.text = "\(lt)" }else { leftField.text = nil } if let rt = ele?.rightText { rightField.text = "\(rt)" }else { rightField.text = nil } switch ele!.type { case "text": rightButton.hidden = true rightButton.snp_updateConstraints(closure: { (make) -> Void in make.width.equalTo(0) }) hasRightButton = false case "password": // rightField.keyboardType = UIKeyboardType.ASCIICapable // rightField.secureTextEntry = true rightField.textColor = UIColor.orangeColor() hasRightButton = true case "date": rightButton.setImage(UIImage(named: "QQ"), forState: UIControlState.Normal) hasRightButton = true default: break } } } @IBOutlet weak var leftField: UITextField! @IBOutlet weak var rightField: UITextField! @IBOutlet weak var rightButton: UIButton! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } // MARK: - Button action @IBAction func rightButtonAction(sender: UIButton) { if let passwordGeneratorController = superController?.storyboard?.instantiateViewControllerWithIdentifier("PMPasswordGeneratorController") as? PMPasswordGeneratorController { passwordGeneratorController.success = { [unowned self](randomString: String) -> Void in self.ele?.rightText = randomString } superController?.showViewController(passwordGeneratorController, sender: nil) } } // MARK: - TextField func textFieldDidEndEditing(textField: UITextField) { if textField == leftField { ele?.leftText = textField.text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) }else { ele?.rightText = textField.text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } } }
mit
34e12c0ebdfc8d250f116ec3dee882c8
35.547368
182
0.616647
4.869565
false
false
false
false
mlilback/rc2SwiftClient
Rc2Common/DispatchReader.swift
1
1140
// // DispatchReader.swift // // Copyright ©2016 Mark Lilback. This file is licensed under the ISC license. // import Foundation public protocol DispatchReaderDelegate: class { func process(data: Data, reader: DispatchReader) func closed(reader: DispatchReader) } /// Reads data in chunks from a file descriptor public class DispatchReader { fileprivate let fd: Int32 fileprivate let source: DispatchSourceRead fileprivate weak var delegate: DispatchReaderDelegate? fileprivate let fileHandle: FileHandle init(_ fd: Int, delegate: DispatchReaderDelegate) { self.fd = Int32(fd) self.delegate = delegate self.source = DispatchSource.makeReadSource(fileDescriptor: self.fd) fileHandle = FileHandle(fileDescriptor: self.fd) source.setCancelHandler { [unowned self] in close(self.fd) self.delegate?.closed(reader: self) } source.setEventHandler { [unowned self] in //self.source.d let availSize: UInt = self.source.data let data = self.fileHandle.readData(ofLength: Int(availSize)) self.delegate?.process(data: data, reader: self) } source.activate() } func cancel() { source.cancel() } }
isc
1a8b8da7a8f581a2a444891aa98943a5
26.119048
78
0.744513
3.615873
false
false
false
false
behrang/SwiftParsec
Parsec/Error.swift
1
5629
/** The abstract data type `ParseError` represents parse errors. It provides the source position (`SourcePos`) of the error and a list of error messages (`Message`). A `ParseError` can be returned by the function `parse`. */ public struct ParseError: CustomStringConvertible { var pos: SourcePos var messages: [Message] init(_ pos: SourcePos, _ messages: [Message]) { self.pos = pos self.messages = messages } init(_ pos: SourcePos) { self.pos = pos self.messages = [] } init(_ pos: SourcePos, _ message: Message) { self.pos = pos self.messages = [message] } var sortedMessages: [Message] { return messages.sorted() } var isUnknown: Bool { return messages.isEmpty } mutating func addMessage (_ message: Message) { messages.append(message) } mutating func setPos (_ pos: SourcePos) { self.pos = pos } mutating func setMessage (_ message: Message) { messages = messages.filter({ $0 != message }) messages.append(message) } public var description: String { return String(describing: pos) + ":\n" + showErrorMessage(sortedMessages) } } func unknownError<c: Collection, u> (_ state: State<c, u>) -> ParseError { return ParseError(state.pos) } func sysUnExpectError<a, c: Collection, u> (_ msg: String, _ pos: SourcePos) -> Reply<a, c, u> { return .error(Lazy{ ParseError(pos, .sysUnExpect(msg)) }) } /** This abstract data type represents parse error messages. There are four kinds of messages. The fine distinction between different kinds of parse errors allows the system to generate quite good error messages for the user. Each kind of message is generated by different combinators: * A `sysUnExpect` message is automatically generated by the `satisfy` combinator. The argument is the unexpected input. * A `unExpect` message is generated by the `unexpected` combinator. The argument describes the unexpected item. * A `expect` message is generated by the `<?>` combinator. The argument describes the expected item. * A `Message` message is generated by the `fail` combinator. The argument is some general parser message. */ enum Message: Comparable { case sysUnExpect(String) // library generated unexpect case unExpect(String) // unexpected something case expect(String) // expecting something case message(String) // raw message // Extract the message string from an error message var string: String { switch self { case let .sysUnExpect(s): return String(reflecting: s) case let .unExpect(s): return String(reflecting: s) case let .expect(s): return String(reflecting: s) case let .message(s): return String(reflecting: s) } } var order: Int { switch self { case .sysUnExpect: return 0 case .unExpect: return 1 case .expect: return 2 case .message: return 3 } } } /** Return `true` only when orders are equal. */ func == (lhs: Message, rhs: Message) -> Bool { return lhs.order == rhs.order } /** Compares two error messages without looking at their content. Only the constructors are compared where: `sysUnExpect` < `unExpect` < `expect` < `message` */ func < (lhs: Message, rhs: Message) -> Bool { return lhs.order < rhs.order } func mergeError (_ e1: ParseError, _ e2: ParseError) -> ParseError { // prefer meaningful errors switch (e1.messages.isEmpty, e2.messages.isEmpty) { case (false, true): return e1 case (true, false): return e2 default: // select longest match if e1.pos > e2.pos { return e1 } else if e1.pos < e2.pos { return e2 } else { var messages = e1.messages messages.append(contentsOf: e2.messages) return ParseError(e1.pos, messages) } } } /** The standard function for showing error messages. Formats a list of error messages. The resulting string will be formatted like: unexpected {The first unExpect or a sysUnExpect message} expecting {comma separated list of expect messages} {comma separated list of Message messages} */ func showErrorMessage (_ msgs: [Message]) -> String { if msgs.isEmpty { return "unknown parse error" } else { let sysUnExpect = msgs.filter({ $0 == .sysUnExpect("") }) let unExpect = msgs.filter({ $0 == .unExpect("") }) let expect = msgs.filter({ $0 == .expect("") }) let messages = msgs.filter({ $0 == .message("") }) let showMessages = showMany("", messages) let showExpect = showMany("expecting", expect) let showUnExpect = showMany("unexpected", unExpect) var showSysUnExpect = "" if !unExpect.isEmpty || sysUnExpect.isEmpty { } else { let firstMsg = sysUnExpect.first?.string if let firstMsg = firstMsg, !firstMsg.isEmpty { showSysUnExpect = "unexpected \(firstMsg)" } else { showSysUnExpect = "unexpected end of input" } } return [showSysUnExpect, showUnExpect, showExpect, showMessages] .filter { !$0.isEmpty }.joined(separator: "\n") } } func showMany (_ pre: String, _ msgs: [Message]) -> String { let messages = msgs.map{ $0.string }.filter{ !$0.isEmpty } if messages.isEmpty { return "" } else if pre.isEmpty { return commasOr(messages) } else { return pre + " " + commasOr(messages) } } func commasOr (_ msgs: [String]) -> String { if msgs.isEmpty { return "" } else { var initial = msgs let last = initial.removeLast() if initial.isEmpty { return last } else { return initial.joined(separator: ", ") + " or " + last } } }
mit
048858d65f4f6c98b24b46e14b702f5a
27.286432
96
0.655179
3.906315
false
false
false
false
ravirani/algorithms
String/LongestPalindromicSubstring.swift
1
2284
// // LongestPalindromicSubstring.swift // // // Solved using Manacher's algorithm // https://en.wikipedia.org/wiki/Longest_palindromic_substring // // import Foundation extension String { subscript(index: Int) -> Character { return self[self.index(self.startIndex, offsetBy: index)] } } func longestPalindromicSubstring(inputString: String) -> Int { let stringLength = inputString.characters.count guard stringLength > 1 else { return stringLength } var palindromicStringLengths = Array(repeating: 1, count: stringLength) var indexWithMaxLength = 0, maxLength = Int.min var length = 1, indexGoingForward = 0, indexGoingBackward = 0 for currentIndex in 1..<stringLength { let rightEdgeIndex = palindromicStringLengths[indexWithMaxLength]/2 + indexWithMaxLength // Current index is entirely self contained in the previous max length palindrome if currentIndex < rightEdgeIndex { // Set the count to the left side equivalent because thats the min length palindrome that exists // at this index palindromicStringLengths[currentIndex] = palindromicStringLengths[indexWithMaxLength - (currentIndex - indexWithMaxLength)] // If the length of this palindrome ends here, we don't need to evaluate this character if currentIndex + palindromicStringLengths[currentIndex]/2 == currentIndex { continue } } length = 1 indexGoingBackward = currentIndex - 1 indexGoingForward = currentIndex + 1 while indexGoingBackward >= 0 && indexGoingForward < stringLength && inputString[indexGoingBackward] == inputString[indexGoingForward] { length += 2 indexGoingBackward -= 1 indexGoingForward += 1 } palindromicStringLengths[currentIndex] = length if length > maxLength { maxLength = length indexWithMaxLength = currentIndex } } return maxLength } // Base case assert(longestPalindromicSubstring(inputString: "abadefg") == 3) // Case checking right boundary condition assert(longestPalindromicSubstring(inputString: "abaxabaxabb") == 9) // Case checking guard conditions assert(longestPalindromicSubstring(inputString: "a") == 1) assert(longestPalindromicSubstring(inputString: "") == 0)
mit
8fc1d20fcb06fa4646020c296f8daef6
29.453333
129
0.716725
4.63286
false
false
false
false
ben-ng/swift
stdlib/public/core/ObjectIdentifier.swift
1
3827
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A unique identifier for a class instance or metatype. /// /// In Swift, only class instances and metatypes have unique identities. There /// is no notion of identity for structs, enums, functions, or tuples. public struct ObjectIdentifier : Hashable { internal let _value: Builtin.RawPointer // FIXME: Better hashing algorithm /// The identifier's hash value. /// /// The hash value is not guaranteed to be stable across different /// invocations of the same program. Do not persist the hash value across /// program runs. /// /// - SeeAlso: `Hashable` public var hashValue: Int { return Int(Builtin.ptrtoint_Word(_value)) } /// Creates an instance that uniquely identifies the given class instance. /// /// The following example creates an example class `A` and compares instances /// of the class using their object identifiers and the identical-to /// operator (`===`): /// /// class IntegerRef { /// let value: Int /// init(_ value: Int) { /// self.value = value /// } /// } /// /// let x = IntegerRef(10) /// let y = x /// /// print(ObjectIdentifier(x) == ObjectIdentifier(y)) /// // Prints "true" /// print(x === y) /// // Prints "true" /// /// let z = IntegerRef(10) /// print(ObjectIdentifier(x) == ObjectIdentifier(z)) /// // Prints "false" /// print(x === z) /// // Prints "false" /// /// - Parameter x: An instance of a class. public init(_ x: AnyObject) { self._value = Builtin.bridgeToRawPointer(x) } /// Creates an instance that uniquely identifies the given metatype. /// /// - Parameter: A metatype. public init(_ x: Any.Type) { self._value = unsafeBitCast(x, to: Builtin.RawPointer.self) } } extension ObjectIdentifier : CustomDebugStringConvertible { /// A textual representation of the identifier, suitable for debugging. public var debugDescription: String { return "ObjectIdentifier(\(_rawPointerToString(_value)))" } } extension ObjectIdentifier : Comparable { public static func < (lhs: ObjectIdentifier, rhs: ObjectIdentifier) -> Bool { return UInt(bitPattern: lhs) < UInt(bitPattern: rhs) } public static func == (x: ObjectIdentifier, y: ObjectIdentifier) -> Bool { return Bool(Builtin.cmp_eq_RawPointer(x._value, y._value)) } } extension UInt { /// Creates an integer that captures the full value of the given object /// identifier. public init(bitPattern objectID: ObjectIdentifier) { self.init(Builtin.ptrtoint_Word(objectID._value)) } } extension Int { /// Creates an integer that captures the full value of the given object /// identifier. public init(bitPattern objectID: ObjectIdentifier) { self.init(bitPattern: UInt(bitPattern: objectID)) } } extension ObjectIdentifier { @available(*, unavailable, message: "use the 'UInt(_:)' initializer") public var uintValue: UInt { Builtin.unreachable() } } extension UInt { @available(*, unavailable, renamed: "init(bitPattern:)") public init(_ objectID: ObjectIdentifier) { Builtin.unreachable() } } extension Int { @available(*, unavailable, renamed: "init(bitPattern:)") public init(_ objectID: ObjectIdentifier) { Builtin.unreachable() } }
apache-2.0
2e56f1e5343488b72c3e2f0ad9197ba7
29.616
80
0.633394
4.424277
false
false
false
false
Sai628/NirZhihuDaily
zhihuDaily/Controllers/MainTableViewController.swift
1
15929
// // MainTableViewController.swift // zhihuDaily 2.0 // // Created by Nirvana on 10/3/15. // Copyright © 2015 NSNirvana. All rights reserved. // import UIKit class MainTableViewController: UITableViewController, SDCycleScrollViewDelegate, ParallaxHeaderViewDelegate { @IBOutlet weak var dateLabel: UILabel! var animator: ZFModalTransitionAnimator! var cycleScrollView: SDCycleScrollView! var loadCircleView: PNCircleChart! var loadingView: UIActivityIndicatorView! var dragging = false var triggered = false // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() //创建leftBarButtonItem以及添加手势识别 let leftButton = UIBarButtonItem(image: UIImage(named: "menu"), style: .Plain, target: self.revealViewController(), action: "revealToggle:") leftButton.tintColor = UIColor.whiteColor() self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) self.view.addGestureRecognizer(self.revealViewController().tapGestureRecognizer()) //配置无限循环scrollView cycleScrollView = SDCycleScrollView(frame: CGRectMake(0, 0, self.tableView.frame.width, 154), imageURLStringsGroup: nil) cycleScrollView.infiniteLoop = true cycleScrollView.delegate = self cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated cycleScrollView.autoScrollTimeInterval = 6.0; cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleClassic cycleScrollView.titleLabelTextFont = UIFont(name: "STHeitiSC-Medium", size: 21) cycleScrollView.titleLabelBackgroundColor = UIColor.clearColor() cycleScrollView.titleLabelHeight = 60 //alpha在未设置的状态下默认为0 cycleScrollView.titleLabelAlpha = 1 //将其添加到ParallaxView let headerSubview: ParallaxHeaderView = ParallaxHeaderView.parallaxHeaderViewWithSubView(cycleScrollView, forSize: CGSizeMake(self.tableView.frame.width, 154)) as! ParallaxHeaderView headerSubview.delegate = self //将ParallaxView设置为tableHeaderView self.tableView.tableHeaderView = headerSubview //如果不是第一次展示 if appCloud().firstDisplay == false { updateData() } //如果是第一次启动 if appCloud().firstDisplay { //生成第二启动页背景 let launchView = UIView(frame: CGRectMake(0, -64, self.view.frame.width, self.view.frame.height)) launchView.alpha = 0.99 //得到第二启动页控制器并设置为子控制器 let launchViewController = storyboard?.instantiateViewControllerWithIdentifier("launchViewController") self.addChildViewController(launchViewController!) //将第二启动页放到背景上 launchView.addSubview(launchViewController!.view) //展示第二启动页并隐藏NavbarTitleView self.view.addSubview(launchView) self.navigationItem.titleView?.hidden = true //动画效果:第二启动页2.5s展示过后经0.2秒删除并恢复展示NavbarTitleView UIView.animateWithDuration(2.5, animations: { () -> Void in launchView.alpha = 1 }) { (finished) -> Void in UIView.animateWithDuration(0.2, animations: { () -> Void in launchView.alpha = 0 self.navigationItem.titleView?.hidden = false self.navigationItem.setLeftBarButtonItem(leftButton, animated: false) }, completion: { (finished) -> Void in launchView.removeFromSuperview() }) } //展示完成后更改为false appCloud().firstDisplay = false } else { self.navigationItem.setLeftBarButtonItem(leftButton, animated: false) } //设置透明NavBar self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor.clearColor()) self.navigationController?.navigationBar.shadowImage = UIImage() //tableView基础配置 self.tableView.dataSource = self self.tableView.delegate = self self.tableView.showsVerticalScrollIndicator = false self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 50 //初始化下拉加载loadCircleView let comp1 = self.dateLabel.frame.width/2 let comp2 = (self.dateLabel.text! as NSString).sizeWithAttributes(nil).width/2 let loadCircleViewXPosition = comp1 - comp2 - 35 loadCircleView = PNCircleChart(frame: CGRect(x: loadCircleViewXPosition, y: 3, width: 15, height: 15), total: 100, current: 0, clockwise: true, shadow: false, shadowColor: nil, displayCountingLabel: false, overrideLineWidth: 1) loadCircleView.backgroundColor = UIColor.clearColor() loadCircleView.strokeColor = UIColor.whiteColor() loadCircleView.strokeChart() loadCircleView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI)) self.dateLabel.addSubview(loadCircleView) //初始化下拉加载loadingView loadingView = UIActivityIndicatorView(frame: CGRect(x: loadCircleViewXPosition+2.5, y: 5.5, width: 10, height: 10)) self.dateLabel.addSubview(loadingView) //收到广播 NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateData", name: "todayDataGet", object: nil) } override func viewDidAppear(animated: Bool) { self.tableView.reloadData() } // MARK: - Data //收到广播后刷新数据 func updateData() { cycleScrollView.imageURLStringsGroup = [appCloud().topStory[0].image, appCloud().topStory[1].image, appCloud().topStory[2].image, appCloud().topStory[3].image, appCloud().topStory[4].image] cycleScrollView.titlesGroup = [appCloud().topStory[0].title, appCloud().topStory[1].title, appCloud().topStory[2].title, appCloud().topStory[3].title, appCloud().topStory[4].title] (self.cycleScrollView.subviews[0] as! UICollectionView).scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.None, animated: false) self.tableView.reloadData() } // MARK: - TableView override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return appCloud().contentStory.count + appCloud().pastContentStory.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //取得已读新闻数组以供配置 let readNewsIdArray = NSUserDefaults.standardUserDefaults().objectForKey(Keys.readNewsId) as! [String] if indexPath.row < appCloud().contentStory.count { let cell = tableView.dequeueReusableCellWithIdentifier("tableContentViewCell") as! TableContentViewCell let data = appCloud().contentStory[indexPath.row] //验证是否已被点击过 if let _ = readNewsIdArray.indexOf(data.id) { cell.titleLabel.textColor = UIColor.lightGrayColor() } else { cell.titleLabel.textColor = UIColor.blackColor() } cell.imagesView.sd_setImageWithURL(NSURL(string: data.images[0])) cell.titleLabel.text = data.title return cell } let newIndex = indexPath.row - appCloud().contentStory.count guard appCloud().pastContentStory.count != 0 else { return UITableViewCell() } if appCloud().pastContentStory[newIndex] is DateHeaderModel { let cell = tableView.dequeueReusableCellWithIdentifier("tableSeparatorViewCell") as! TableSeparatorViewCell let data = appCloud().pastContentStory[newIndex] as! DateHeaderModel cell.contentView.backgroundColor = UIColor(red: 1/255.0, green: 131/255.0, blue: 209/255.0, alpha: 1) cell.dateLabel.text = data.date return cell } let cell = tableView.dequeueReusableCellWithIdentifier("tableContentViewCell") as! TableContentViewCell let data = appCloud().pastContentStory[newIndex] as! ContentStoryModel //验证是否已被点击过 if let _ = readNewsIdArray.indexOf(data.id) { cell.titleLabel.textColor = UIColor.lightGrayColor() } else { cell.titleLabel.textColor = UIColor.blackColor() } cell.imagesView.sd_setImageWithURL(NSURL(string: data.images[0])) cell.titleLabel.text = data.title return cell } //设置滑动极限修改该值需要一并更改layoutHeaderViewForScrollViewOffset中的对应值 func lockDirection() { self.tableView.contentOffset.y = -154 } //tableView点击事件 override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //保证点击的是TableContentViewCell guard tableView.cellForRowAtIndexPath(indexPath) is TableContentViewCell else { return } //拿到webViewController let webViewController = self.storyboard?.instantiateViewControllerWithIdentifier("webViewController") as!WebViewController webViewController.index = indexPath.row //找到对应newsID if indexPath.row < appCloud().contentStory.count { let id = appCloud().contentStory[indexPath.row].id webViewController.newsId = id } else { let newIndex = indexPath.row - appCloud().contentStory.count let id = (appCloud().pastContentStory[newIndex] as! ContentStoryModel).id webViewController.newsId = id } //取得已读新闻数组以供修改 var readNewsIdArray = NSUserDefaults.standardUserDefaults().objectForKey(Keys.readNewsId) as! [String] //记录已被选中的id readNewsIdArray.append(webViewController.newsId) NSUserDefaults.standardUserDefaults().setObject(readNewsIdArray, forKey: Keys.readNewsId) //对animator进行初始化 animator = ZFModalTransitionAnimator(modalViewController: webViewController) self.animator.dragable = true self.animator.bounces = false self.animator.behindViewAlpha = 0.7 self.animator.behindViewScale = 0.9 self.animator.transitionDuration = 0.7 self.animator.direction = ZFModalTransitonDirection.Right //设置webViewController webViewController.transitioningDelegate = self.animator //实施转场 self.presentViewController(webViewController, animated: true) { () -> Void in } } //collectionView点击事件 func cycleScrollView(cycleScrollView: SDCycleScrollView!, didSelectItemAtIndex index: Int) { //拿到webViewController let webViewController = self.storyboard?.instantiateViewControllerWithIdentifier("webViewController") as!WebViewController webViewController.modalPresentationStyle = UIModalPresentationStyle.FullScreen //对animator进行初始化 animator = ZFModalTransitionAnimator(modalViewController: webViewController) self.animator.dragable = true self.animator.bounces = false self.animator.behindViewAlpha = 0.7 self.animator.behindViewScale = 0.9 self.animator.transitionDuration = 0.7 self.animator.direction = ZFModalTransitonDirection.Right //设置webViewController webViewController.transitioningDelegate = self.animator webViewController.newsId = appCloud().topStory[index].id webViewController.isTopStory = true //实施转场 self.presentViewController(webViewController, animated: true) { () -> Void in } } // MARK: - ScrollViewDelegate //记录下拉状态 override func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { dragging = false } override func scrollViewWillBeginDragging(scrollView: UIScrollView) { dragging = true } override func scrollViewDidScroll(scrollView: UIScrollView) { //Parallax效果 let header = self.tableView.tableHeaderView as! ParallaxHeaderView header.layoutHeaderViewForScrollViewOffset(scrollView.contentOffset) //NavBar及titleLabel透明度渐变 let color = UIColor(red: 1/255.0, green: 131/255.0, blue: 209/255.0, alpha: 1) let offsetY = scrollView.contentOffset.y let prelude: CGFloat = 90 if offsetY >= -64 { let alpha = min(1, (64 + offsetY) / (64 + prelude)) //titleLabel透明度渐变 (header.subviews[0].subviews[0] as! SDCycleScrollView).titleLabelAlpha = 1 - alpha (header.subviews[0].subviews[0].subviews[0] as! UICollectionView).reloadData() //NavBar透明度渐变 self.navigationController?.navigationBar.lt_setBackgroundColor(color.colorWithAlphaComponent(alpha)) if loadCircleView.hidden != true { loadCircleView.hidden = true } if triggered == true && offsetY == -64 { triggered = false } } else { let ratio = (-offsetY - 64)*2 if ratio <= 100 { if triggered == false && loadCircleView.hidden == true { loadCircleView.hidden = false } loadCircleView.updateChartByCurrent(ratio) } else { if loadCircleView.current != 100 { loadCircleView.updateChartByCurrent(100) } //第一次检测到松手 if !dragging && !triggered { loadCircleView.hidden = true loadingView.startAnimating() appCloud().requestAllNeededData({ () -> () in self.loadingView.stopAnimating() }) triggered = true } } } //依据contentOffsetY设置titleView的标题 for separatorData in appCloud().offsetYValue { guard offsetY > separatorData.0 else { if dateLabel.text != separatorData.1 { dateLabel.text = separatorData.1 } break } } } // MARK: - Other //获取总代理 func appCloud() -> AppDelegate { return UIApplication.sharedApplication().delegate as! AppDelegate } //设置StatusBar为白色 override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } } //拓展NavigationController以设置StatusBar extension UINavigationController { public override func childViewControllerForStatusBarStyle() -> UIViewController? { return self.topViewController } public override func childViewControllerForStatusBarHidden() -> UIViewController? { return self.topViewController } }
mit
3e0abb1b742238e5994dddf9eb1cd034
40.451087
235
0.638521
5.354159
false
false
false
false
frootloops/swift
test/DebugInfo/basic.swift
1
4808
// A (no longer) basic test for debug info. // -------------------------------------------------------------------- // Verify that we don't emit any debug info by default. // RUN: %target-swift-frontend %s -emit-ir -o - \ // RUN: | %FileCheck %s --check-prefix NDEBUG // NDEBUG-NOT: !dbg // NDEBUG-NOT: DW_TAG // -------------------------------------------------------------------- // Verify that we don't emit any debug info with -gnone. // RUN: %target-swift-frontend %s -emit-ir -gnone -o - \ // RUN: | %FileCheck %s --check-prefix NDEBUG // -------------------------------------------------------------------- // Verify that we don't emit any type info with -gline-tables-only. // RUN: %target-swift-frontend %s -emit-ir -gline-tables-only -o - \ // RUN: | %FileCheck %s --check-prefix CHECK-LINETABLES // CHECK: !dbg // CHECK-LINETABLES-NOT: DW_TAG_{{.*}}variable // CHECK-LINETABLES-NOT: DW_TAG_structure_type // CHECK-LINETABLES-NOT: DW_TAG_basic_type // -------------------------------------------------------------------- // Now check that we do generate line+scope info with -g. // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s // RUN: %target-swift-frontend %s -emit-ir -g -o - -disable-sil-linking \ // RUN: | %FileCheck %s --check-prefix=CHECK-NOSIL // -------------------------------------------------------------------- // Currently -gdwarf-types should give the same results as -g. // RUN: %target-swift-frontend %s -emit-ir -gdwarf-types -o - | %FileCheck %s // -------------------------------------------------------------------- // // CHECK: foo // CHECK-DAG: ret{{.*}}, !dbg ![[RET:[0-9]+]] // CHECK-DAG: ![[FOO:[0-9]+]] = distinct !DISubprogram(name: "foo",{{.*}} line: [[@LINE+2]],{{.*}} type: ![[FOOTYPE:[0-9]+]] public func foo(_ a: Int64, _ b: Int64) -> Int64 { var a = a var b = b // CHECK-DAG: !DILexicalBlock(scope: ![[FOO]],{{.*}} line: [[@LINE-3]], column: 43) // CHECK-DAG: ![[ASCOPE:.*]] = !DILocation(line: [[@LINE-4]], column: 10, scope: ![[FOO]]) // Check that a is the first and b is the second argument. // CHECK-DAG: store i64 %0, i64* [[AADDR:.*]], align // CHECK-DAG: store i64 %1, i64* [[BADDR:.*]], align // CHECK-DAG: [[AVAL:%.*]] = getelementptr inbounds {{.*}}, [[AMEM:.*]], i32 0, i32 0 // CHECK-DAG: [[BVAL:%.*]] = getelementptr inbounds {{.*}}, [[BMEM:.*]], i32 0, i32 0 // CHECK-DAG: call void @llvm.dbg.declare(metadata i64* [[AADDR]], metadata ![[AARG:.*]], metadata !DIExpression()), !dbg ![[ASCOPE]] // CHECK-DAG: call void @llvm.dbg.declare(metadata i64* [[BADDR]], metadata ![[BARG:.*]], metadata !DIExpression()) // CHECK-DAG: ![[AARG]] = !DILocalVariable(name: "a", arg: 1 // CHECK-DAG: ![[BARG]] = !DILocalVariable(name: "b", arg: 2 if b != 0 { // CHECK-DAG: !DILexicalBlock({{.*}} line: [[@LINE-1]] // Transparent inlined multiply: // CHECK-DAG: smul{{.*}}, !dbg ![[MUL:[0-9]+]] // CHECK-DAG: [[MUL]] = !DILocation(line: [[@LINE+4]], column: 16, // Runtime call to multiply function: // CHECK-NOSIL: @_T0s5Int64V1moiA2B_ABtFZ{{.*}}, !dbg ![[MUL:[0-9]+]] // CHECK-NOSIL: [[MUL]] = !DILocation(line: [[@LINE+1]], column: 16, return a*b } else { // CHECK-DAG: ![[PARENT:[0-9]+]] = distinct !DILexicalBlock({{.*}} line: [[@LINE-1]], column: 13) var c: Int64 = 42 // CHECK-DAG: ![[CONDITION:[0-9]+]] = distinct !DILexicalBlock(scope: ![[PARENT]], {{.*}}, line: [[@LINE+1]], if a == 0 { // CHECK-DAG: !DILexicalBlock(scope: ![[CONDITION]], {{.*}}, line: [[@LINE-1]], column: 18) // What about a nested scope? return 0 } return c } } // CHECK-DAG: ![[FILE_CWD:[0-9]+]] = !DIFile(filename: "{{.*}}DebugInfo/basic.swift", directory: "{{.*}}") // CHECK-DAG: ![[MAINFILE:[0-9]+]] = !DIFile(filename: "basic.swift", directory: "{{.*}}DebugInfo") // CHECK-DAG: !DICompileUnit(language: DW_LANG_Swift, file: ![[FILE_CWD]],{{.*}} producer: "{{.*}}Swift version{{.*}},{{.*}} flags: "{{[^"]*}}-emit-ir // CHECK-DAG: !DISubprogram(name: "main" // Function type for foo. // CHECK-DAG: ![[FOOTYPE]] = !DISubroutineType(types: ![[PARAMTYPES:[0-9]+]]) // CHECK-DAG: ![[INT64:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Int64", {{.*}}, identifier: "_T0s5Int64VD") // CHECK-DAG: ![[PARAMTYPES]] = !{![[INT64]], ![[INT64]], ![[INT64]]} // Import of the main module with the implicit name. // CHECK-DAG: !DIImportedEntity(tag: DW_TAG_imported_module, scope: ![[MAINFILE]], entity: ![[MAINMODULE:[0-9]+]], file: ![[MAINFILE]]) // CHECK-DAG: ![[MAINMODULE]] = !DIModule({{.*}}, name: "basic" // DWARF Version // CHECK-DAG: i32 2, !"Dwarf Version", i32 4} // Debug Info Version // CHECK-DAG: i32 2, !"Debug Info Version", i32
apache-2.0
9b8a5cc8d3c84147b08f876724f66379
54.264368
150
0.528078
3.381153
false
false
false
false
ollieatkinson/Expectation
Tests/Source/Matchers/Expectation+BeGreaterThanOrEqualTo_Spec.swift
1
1203
// // Expectation+BeGreaterThanOrEqualTo_Spec.swift // Expectation // // Created by Atkinson, Oliver (Developer) on 23/02/2016. // Copyright © 2016 Oliver. All rights reserved. // import XCTest @testable import Expectation class Expectation_BeGreaterThanOrEqualTo_Spec: XCTestCase { override func tearDown() { super.tearDown() ExpectationAssertFunctions.assertTrue = ExpectationAssertFunctions.ExpectationAssertTrue ExpectationAssertFunctions.assertFalse = ExpectationAssertFunctions.ExpectationAssertFalse ExpectationAssertFunctions.assertNil = ExpectationAssertFunctions.ExpectationAssertNil ExpectationAssertFunctions.assertNotNil = ExpectationAssertFunctions.ExpectationAssertNotNil ExpectationAssertFunctions.fail = ExpectationAssertFunctions.ExpectationFail } func testBeGreaterThanOrEqualToPass() { assertTrueValidate(True) { expect(2).to.beGreaterThanOrEqualTo(1) } assertTrueValidate(True) { expect(2).to.beGreaterThanOrEqualTo(2) } } func testBeGreaterThanOrEqualToFail() { assertTrueValidate(False) { expect(1).to.beGreaterThanOrEqualTo(2) } } }
mit
54e3b99c4782e1b3b874a04f9933ca59
25.711111
96
0.741265
5.590698
false
true
false
false
felipeuntill/WeddingPlanner
IOS/WeddingPlanner/NSDataProvider.swift
1
2804
// // NSDataProvider.swift // WeddingPlanner // // Created by Felipe Assunção on 5/22/16. // Copyright © 2016 Felipe Assunção. All rights reserved. // import Foundation public class NSDataProvider { static func LoadFromUri(address : String, method : String? = nil, json : String? = nil) -> NSString { let url: NSURL = NSURL(string: address)! let request: NSMutableURLRequest = NSMutableURLRequest(URL: url) let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil request.addValue("application/json",forHTTPHeaderField: "Content-Type") request.addValue("application/json",forHTTPHeaderField: "Accept") request.HTTPMethod = method == nil ? "GET" : method! request.HTTPBody = json == nil ? nil : json!.dataUsingEncoding(NSUTF8StringEncoding) do { let dataVal = try NSURLConnection.sendSynchronousRequest(request, returningResponse: response) do { let rawContent = NSString(data: dataVal, encoding: NSUTF8StringEncoding)! print(rawContent) return rawContent } } catch let error as NSError { print(error.localizedDescription) } return ""; } // // func HTTPPostJSON(url: String, data: NSData, // callback: (String, String?) -> Void) { // // var request = NSMutableURLRequest(URL: NSURL(string: url)!) // request.HTTPMethod = "POST" // request.addValue("application/json",forHTTPHeaderField: "Content-Type") // request.addValue("application/json",forHTTPHeaderField: "Accept") // request.HTTPBody = data // HTTPsendRequest(request, callback: callback) // } // // func HTTPsendRequest(request: NSMutableURLRequest, // callback: (String, String?) -> Void) { // let task = NSURLSession.sharedSession() // .dataTaskWithRequest(request) { // (data, response, error) -> Void in // if (error != nil) { // callback("", error.localizedDescription) // } else { // callback(NSString(data: data, // encoding: NSUTF8StringEncoding)! as String, nil) // } // } // // task.resume() // } // //use // var data :Dictionary<String, AnyObject> = yourDictionaryData<-- // var requestNSData:NSData = NSJSONSerialization.dataWithJSONObject(request, options:NSJSONWritingOptions(0), error: &err)! // HTTPPostJSON("http://yourPosturl..", data: requestNSData) { (response, error) -> Void in // if error != nil{ // //error // return; // } // // println(response); // } }
mit
f3c86055898865feb38489fce711454b
35.363636
127
0.582351
4.457006
false
false
false
false
certificate-helper/TLS-Inspector
TLS Inspector/Features/SupportType.swift
1
1571
import UIKit class SupportType { enum RequestType: String { case ReportABug = "Report a Bug" case RequestAFeature = "Request a Feature" case SomethingElse = "Something Else" static func allValues() -> [RequestType] { return [ .ReportABug, .RequestAFeature, .SomethingElse, ] } } private(set) var type: RequestType = .ReportABug private(set) var comments: String = "" private(set) var device: String = "" private(set) var deviceVersion: String = "" private(set) var appIdentifier: String = "" private(set) var appVersion: String = "" init(type: RequestType, comments: String) { self.type = type self.comments = comments self.device = UIDevice.current.platformName() self.deviceVersion = UIDevice.current.systemVersion self.appIdentifier = AppInfo.bundleName() self.appVersion = AppInfo.version() + " (" + AppInfo.build() + ")" } public func body() -> String { var body = "" body += "<p>Type: <strong>" + self.type.rawValue + "</strong><br>" body += "Device: <strong>" + self.device + "</strong><br>" body += "Device Version: <strong>" + self.deviceVersion + "</strong><br>" body += "App Identifier: <strong>" + self.appIdentifier + "</strong><br>" body += "App Version: <strong>" + self.appVersion + "</strong><br>" body += "Comments:<br></p>" body += "<p>" + self.comments + "</p>" return body } }
gpl-3.0
008e696218b7bf255e3922318b5e9aa6
33.911111
81
0.569701
4.211796
false
false
false
false
timd/MactsAsBeacon
ActsAsBeacon/IBeacon.swift
1
462
// // IBeacon.swift // MactsAsBeacon // // Created by Philipp Weiß on 10/03/2017. // import Foundation struct IBeacon { static let advertisementKey = "kCBAdvDataAppleBeaconKey" static let defaultUUID = "B0702880-A295-A8AB-F734-031A98A512DE" static let defaultMajor = "2" static let defaultMinor = "1000" static let defaultPower = "-58" var uuid: String var major: String var minor: String var power: String }
mit
bd5725f14b3a7a0b41c34b8f3e3f27d2
19.043478
67
0.672451
3.364964
false
false
false
false
WC2513754426/MyPersonalProjects
MyPersonalProjects/MyPersonalProjects/Classess/MainModule/Controller/MainTabBarViewController.swift
1
1975
// // MainTabBarViewController.swift // MyPersonalProjects // // Created by 吴超 on 2017/6/27. // Copyright © 2017年 wuchao. All rights reserved. // import UIKit class MainTabBarViewController: UITabBarController { let VCNameKey:String = "vcName" let VCImgNameKey:String = "imgName" let VCTitleKey:String = "vcTitle" var childredInfoArr:Array<Dictionary<String,String>>? override func viewDidLoad() { super.viewDidLoad() tabBar.isTranslucent = false ///获取信息plist let url = Bundle.main.url(forResource: "tabbar_info", withExtension: "plist")! let data = try! Data.init(contentsOf: url) childredInfoArr = try! PropertyListSerialization.propertyList(from: data, options: PropertyListSerialization.ReadOptions.mutableContainers, format: nil) as! Array<Dictionary<String, String>> initChildVC() initChildVcItem() } func initChildVC(){ for dict in childredInfoArr! { let clsType = NSClassFromString(Bundle.main.infoDictionary?["CFBundleName"] as! String + "." + dict[VCNameKey]!) as! UIViewController.Type let childVc = clsType.init() addChildViewController(childVc) } } func initChildVcItem(){ for i in 0..<childViewControllers.count { let childrenVc:UIViewController = childViewControllers[i] let imgName = childredInfoArr![i][VCImgNameKey]! let nomalImgName = "tab-bar-" + imgName + "-icon-normal" let selectedImgName = "tab-bar-" + imgName + "-icon-selected" let tabbarItem = childrenVc.tabBarItem! tabbarItem.image = UIImage.init(named: nomalImgName) tabbarItem.selectedImage = UIImage.init(named: selectedImgName) tabbarItem.title = childredInfoArr?[i][VCTitleKey] } } }
apache-2.0
e866a2217334b1958c063215ed943eb0
30.612903
199
0.621939
4.55814
false
false
false
false
banxi1988/BXiOSUtils
Pod/Classes/TextFactory.swift
1
1105
// // AttributedTextFactory.swift // Pods // // Created by Haizhen Lee on 15/12/23. // // import UIKit public struct AttributedText{ public var textColor:UIColor public var font:UIFont public fileprivate(set) var text:String public init(text:String,fontSize: CGFloat = 15,textColor:UIColor = UIColor.darkText){ self.init(text:text, font: UIFont.systemFont(ofSize: fontSize), textColor: textColor) } public init(text:String,font:UIFont = UIFont.systemFont(ofSize: 15),textColor:UIColor = UIColor.darkText){ self.text = text self.font = font self.textColor = textColor } public var attributedText:NSAttributedString{ return NSAttributedString(string: text, attributes: [NSFontAttributeName:font,NSForegroundColorAttributeName:textColor]) } } public struct TextFactory{ public static func createAttributedText(_ textAttributes:[AttributedText]) -> NSAttributedString{ let attributedText = NSMutableAttributedString() for attr in textAttributes{ attributedText.append(attr.attributedText) } return attributedText } }
mit
ce4abcaff1e19effbdc4608d0396a8ab
23.021739
124
0.735747
4.547325
false
false
false
false
httpswift/swifter
Xcode/Sources/HttpParser.swift
1
2472
// // HttpParser.swift // Swifter // // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved. // import Foundation enum HttpParserError: Error, Equatable { case invalidStatusLine(String) case negativeContentLength } public class HttpParser { public init() { } public func readHttpRequest(_ socket: Socket) throws -> HttpRequest { let statusLine = try socket.readLine() let statusLineTokens = statusLine.components(separatedBy: " ") if statusLineTokens.count < 3 { throw HttpParserError.invalidStatusLine(statusLine) } let request = HttpRequest() request.method = statusLineTokens[0] let encodedPath = statusLineTokens[1].addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? statusLineTokens[1] let urlComponents = URLComponents(string: encodedPath) request.path = urlComponents?.path ?? "" request.queryParams = urlComponents?.queryItems?.map { ($0.name, $0.value ?? "") } ?? [] request.headers = try readHeaders(socket) if let contentLength = request.headers["content-length"], let contentLengthValue = Int(contentLength) { // Prevent a buffer overflow and runtime error trying to create an `UnsafeMutableBufferPointer` with // a negative length guard contentLengthValue >= 0 else { throw HttpParserError.negativeContentLength } request.body = try readBody(socket, size: contentLengthValue) } return request } private func readBody(_ socket: Socket, size: Int) throws -> [UInt8] { return try socket.read(length: size) } private func readHeaders(_ socket: Socket) throws -> [String: String] { var headers = [String: String]() while case let headerLine = try socket.readLine(), !headerLine.isEmpty { let headerTokens = headerLine.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: true).map(String.init) if let name = headerTokens.first, let value = headerTokens.last { headers[name.lowercased()] = value.trimmingCharacters(in: .whitespaces) } } return headers } func supportsKeepAlive(_ headers: [String: String]) -> Bool { if let value = headers["connection"] { return "keep-alive" == value.trimmingCharacters(in: .whitespaces) } return false } }
bsd-3-clause
77a7fb299d1e07adb1f37e63cdd3ce18
37.609375
131
0.644678
4.751923
false
false
false
false
yunzixun/V2ex-Swift
Controller/AccountsManagerViewController.swift
1
5897
// // AccountManagerViewController.swift // V2ex-Swift // // Created by huangfeng on 2/11/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit /// 多账户管理 class AccountsManagerViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate { fileprivate var users:[LocalSecurityAccountModel] = [] fileprivate var _tableView :UITableView! fileprivate var tableView: UITableView { get{ if(_tableView != nil){ return _tableView!; } _tableView = UITableView(); _tableView.backgroundColor = V2EXColor.colors.v2_backgroundColor _tableView.estimatedRowHeight=100; _tableView.separatorStyle = UITableViewCellSeparatorStyle.none; regClass(_tableView, cell: BaseDetailTableViewCell.self); regClass(_tableView, cell: AccountListTableViewCell.self); regClass(_tableView, cell: LogoutTableViewCell.self) _tableView.delegate = self; _tableView.dataSource = self; return _tableView!; } } override func viewDidLoad() { super.viewDidLoad() self.title = NSLocalizedString("accounts") self.view.backgroundColor = V2EXColor.colors.v2_backgroundColor let warningButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) warningButton.contentMode = .center warningButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -20) warningButton.setImage(UIImage.imageUsedTemplateMode("ic_warning")!.withRenderingMode(.alwaysTemplate), for: UIControlState()) self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: warningButton) warningButton.addTarget(self, action: #selector(AccountsManagerViewController.warningClick), for: .touchUpInside) self.view.addSubview(self.tableView); self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0) self.tableView.snp.makeConstraints{ (make) -> Void in make.top.bottom.equalTo(self.view); make.center.equalTo(self.view); make.width.equalTo(SCREEN_WIDTH) } for (_,user) in V2UsersKeychain.sharedInstance.users { self.users.append(user) } } @objc func warningClick(){ let alertView = UIAlertView(title: "临时隐私声明", message: "当你登录时,软件会自动将你的账号与密码保存于系统的Keychain中(非常安全)。如果你不希望软件保存你的账号与密码,可以左滑账号并点击删除。\n后续会完善隐私声明页面,并添加 关闭保存账号密码机制 的选项。\n但我强烈推荐你不要关闭,因为这个会帮助你【登录过期自动重连】、或者【切换多账号】", delegate: nil, cancelButtonTitle: "我知道了") alertView.show() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // 账户数量 分割线 退出登录按钮 return self.users.count + 1 + 1 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row < self.users.count { return 55 } else if indexPath.row == self.users.count {//分割线 return 15 } else { //退出登录按钮 return 45 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row < self.users.count { let cell = getCell(tableView, cell: AccountListTableViewCell.self, indexPath: indexPath) cell.bind(self.users[indexPath.row]) return cell } else if indexPath.row == self.users.count {//分割线 let cell = getCell(tableView, cell: BaseDetailTableViewCell.self, indexPath: indexPath) cell.detailMarkHidden = true cell.backgroundColor = tableView.backgroundColor return cell } else{ return getCell(tableView, cell: LogoutTableViewCell.self, indexPath: indexPath) } } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if indexPath.row < self.users.count{ return true } return false } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { if let username = self.users[indexPath.row].username { self.users.remove(at: indexPath.row) V2UsersKeychain.sharedInstance.removeUser(username) tableView.deleteRows(at: [indexPath], with: .none) } } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.tableView.deselectRow(at: indexPath, animated: true) let totalNumOfRows = self.tableView(tableView, numberOfRowsInSection: 0) if indexPath.row == totalNumOfRows - 1{ //最后一行,也就是退出登录按钮那行 let alertView = UIAlertView(title: "确定注销当前账号吗?", message: "注销只会退出登录,并不会删除保存在Keychain中的账户名与密码。如需删除,请左滑需要删除的账号,然后点击删除按钮", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "注销") alertView.tag = 100000 alertView.show() } } func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int){ //注销登录的alertView if buttonIndex == 1 { V2User.sharedInstance.loginOut() self.navigationController?.popToRootViewController(animated: true) } } }
mit
1800822c02c5fa0ffe7b0e2a3d946399
39.466165
253
0.645857
4.518892
false
false
false
false
neilsardesai/chrono-swift
Sample Apps/ChronoSample/Chrono/ChronoParsedResult.swift
2
4347
// // ChronoParsedResult.swift // chrono-swift // // Created by Neil Sardesai on 2016-11-16. // Copyright © 2016 Neil Sardesai. All rights reserved. // import Foundation /// A struct that contains details about a parsed result from a call to `Chrono`’s `parsedResultsFrom(naturalLanguageString:referenceDate:)` method. You should not create instances of `ChronoParsedResult` yourself. struct ChronoParsedResult { /// The input natural language phrase private(set) var inputString: String? /// If the input natural language phrase were converted to an `Array` of `Character`s, this would be the index of the first `Character` of the discovered time phrase private(set) var indexOfStartingCharacterOfTimePhrase: Int? /// The discovered time phrase in the input natural language phrase private(set) var timePhrase: String? /// Text that was not part of the time phrase and was ignored private(set) var ignoredText: String? /// The reference date used for calculating `startDate` private(set) var referenceDate: Date? /// The date discovered in the input natural language phrase. If the time phrase in the natural language phrase describes an interval between two `Date`s, this is the start date of that interval private(set) var startDate: Date? /// If the time phrase in the input natural language phrase describes an interval between two `Date`s, this is the end date of that interval private(set) var endDate: Date? /// If the time phrase in the input natural language phrase describes an interval between two `Date`s, this is that `DateInterval` private(set) var dateInterval: DateInterval? init(inputString: String?, indexOfStartingCharacterOfTimePhrase: Int?, timePhrase: String?, ignoredText: String?, referenceDate: Date?, startDate: Date?, endDate: Date?, dateInterval: DateInterval?) { self.inputString = inputString self.indexOfStartingCharacterOfTimePhrase = indexOfStartingCharacterOfTimePhrase self.timePhrase = timePhrase self.ignoredText = ignoredText self.referenceDate = referenceDate self.startDate = startDate self.endDate = endDate self.dateInterval = dateInterval } } // Overriding output of `print(ChronoParsedResult)` to make it more useful extension ChronoParsedResult: CustomStringConvertible { var description: String { let inputStringDescription = self.inputString?.description ?? "nil" let indexOfStartingCharacterOfTimePhraseDescription = self.indexOfStartingCharacterOfTimePhrase?.description ?? "nil" let timePhraseDescription = self.timePhrase?.description ?? "nil" let ignoredTextDescription = self.ignoredText?.description ?? "nil" // Make the dates pretty let locale = Locale(identifier: "en_US") let dateFormatter = DateFormatter() dateFormatter.dateStyle = .long dateFormatter.timeStyle = .long dateFormatter.locale = locale var referenceDateDescription = "nil" if let referenceDate = self.referenceDate { referenceDateDescription = dateFormatter.string(from: referenceDate) } var startDateDescription = "nil" if let startDate = self.startDate { startDateDescription = dateFormatter.string(from: startDate) } var endDateDescription = "nil" if let endDate = self.endDate { endDateDescription = dateFormatter.string(from: endDate) } var dateIntervalDescription = "nil" if let dateInterval = self.dateInterval { let dateIntervalFormatter = DateIntervalFormatter() dateIntervalFormatter.dateStyle = .long dateIntervalFormatter.timeStyle = .long dateIntervalDescription = dateIntervalFormatter.string(from: dateInterval)! } return "inputString: \(inputStringDescription)\nindexOfStartingCharacterOfTimePhrase: \(indexOfStartingCharacterOfTimePhraseDescription)\ntimePhrase: \(timePhraseDescription)\nignoredText: \(ignoredTextDescription)\nreferenceDate: \(referenceDateDescription)\nstartDate: \(startDateDescription)\nendDate: \(endDateDescription)\ndateInterval: \(dateIntervalDescription)" } }
mit
3d6c22ccd92fe062ca4b19019b1b6430
48.363636
377
0.710175
5.098592
false
false
false
false
sgurnoor/TicTacToe
Tic Tac Toe/TicTacToe.swift
1
3226
// // TicTacToe.swift // Tic Tac Toe // // Created by Gurnoor Singh on 11/28/15. // Copyright © 2015 Cyberician. All rights reserved. // import Foundation import UIKit class TicTacToe: CustomStringConvertible { enum Player: String { case X case O } var board = [[Player?]]() var playerToPlay = Player.X let boardSize: Int func markTileInRow(row: Int, andColumn col: Int) -> Player? { if (row >= 0 && row < boardSize && col >= 0 && col < boardSize && board[row][col] == nil) { board[row][col] = playerToPlay let playerToReturn = playerToPlay if playerToPlay == .X { playerToPlay = .O } else { playerToPlay = .X } return playerToReturn } return nil } var description: String { get { return "\(board)" } } init(size: Int = 3) { boardSize = size resetGame() } private func checkWinner(player: Player) -> Bool { //check rows for row in board { var count = 0 for tile in row { if(tile == player) { count++ } } if (count == boardSize) { return true } } //check cols for var col = 0; col < boardSize; col++ { var count = 0 for var row = 0; row < boardSize; row++ { if (board[row][col] == player) { count++ } } if (count == boardSize) { return true } } //check diagonal(top-left to bottom-right var count = 0 for var i = 0; i < boardSize; i++ { if (board[i][i] == player) { count++ } } if (count == boardSize) { return true } //check diagonal(top-right to bottom-left count = 0 for var i = 0; i < boardSize; i++ { if (board[i][boardSize - i - 1] == player) { count++ } } if (count == boardSize) { return true } return false } func getWinner() -> Player? { if (checkWinner(Player.X)) { return Player.X } else if (checkWinner(Player.O)) { return Player.O } else { return nil } } func checkTie () -> Bool { var count = 0 for row in board { for tile in row { if (tile != nil) { count++ } } } if (count >= boardSize * boardSize) { return true } return false } func resetGame() { playerToPlay = Player.X board = Array(count: boardSize, repeatedValue: Array(count: boardSize, repeatedValue: nil)) } }
mit
a2e9304ff367a6f33efdd441f141ae5b
21.241379
99
0.405891
4.701166
false
false
false
false
borland/MTGLifeCounter2
MTGLifeCounter2/MainMenuViewController.swift
1
911
// // MainMenuViewController.swift // MTGLifeCounter2 // // Created by Orion Edwards on 6/09/14. // Copyright (c) 2014 Orion Edwards. All rights reserved. // import Foundation import UIKit class MainMenuViewController : UITableViewController { override func viewDidLoad() { self.navigationController?.navigationBar.barStyle = .black // white text } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if (indexPath as NSIndexPath).section == 1 && (indexPath as NSIndexPath).row == 0 { // Roll D20 let diceRollView = DiceRollView.create(finalValue: Int(arc4random_uniform(20) + 1), max: 20, winner:false, numCells: 30, orientation: .normal) diceRollView.showInView(view, callbackDuration:1, pauseDuration:1.3) tableView.deselectRow(at: indexPath, animated: true) } } }
mit
d0e14d9b2bed63b86a1e45e056cf5117
32.740741
154
0.678375
4.317536
false
false
false
false