repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
kumabook/StickyNotesiOS
refs/heads/master
StickyNotes/WebViewController+NewPage.swift
mit
1
// // WebViewController+NewPage.swift // StickyNotes // // Created by Hiroki Kumamoto on 2017/04/28. // Copyright © 2017 kumabook. All rights reserved. // import Foundation import UIKit import RealmSwift extension WebViewController: UISearchControllerDelegate, UISearchResultsUpdating, UISearchBarDelegate { func enterViewMode() { navigationController?.navigationBar.topItem?.title = "" navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "search"), style: .plain, target: self, action: #selector(WebViewController.enterNewPageMode)) navigationItem.titleView = nil navigationItem.title = page?.title ?? "" collectionView?.removeFromSuperview() } func enterNewPageMode() { searchController = UISearchController(searchResultsController: nil) searchController?.searchBar.placeholder = "Search or enter address" searchController?.searchBar.returnKeyType = UIReturnKeyType.go searchController?.searchResultsUpdater = self searchController?.delegate = self searchController?.searchBar.delegate = self searchController?.hidesNavigationBarDuringPresentation = false searchController?.dimsBackgroundDuringPresentation = true navigationItem.titleView = searchController?.searchBar navigationItem.rightBarButtonItem = nil definesPresentationContext = true searchController?.searchBar.becomeFirstResponder() collectionView = createCollectionView() view.addSubview(collectionView!) } public func updateSearchResults(for searchController: UISearchController) { } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { guard let text = searchBar.text else { return } if let url = URL(string: text), let schema = url.scheme, schema == "http" || schema == "https" { loadURL(url) } else { let q = text.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed) ?? text loadURL(URL(string: "http://google.com/search?q=\(q)")!) } searchController?.isActive = false mode = .view } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { if page != nil { mode = .view } } } extension WebViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { var sites: [Site] { return Site.defaultSites } func createCollectionView() -> UICollectionView { let frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height - toolbarHeight) let collectionView = UICollectionView(frame: frame, collectionViewLayout: UICollectionViewFlowLayout()) collectionView.contentInset = UIEdgeInsets(top: topLayoutGuide.length, left: 0, bottom: 0, right: 0) collectionView.backgroundColor = UIColor.white collectionView.dataSource = self collectionView.delegate = self collectionView.register(SiteCollectionViewCell.self, forCellWithReuseIdentifier: "Cell") collectionView.autoresizesSubviews = true collectionView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleBottomMargin, UIViewAutoresizing.flexibleLeftMargin, UIViewAutoresizing.flexibleRightMargin, UIViewAutoresizing.flexibleTopMargin, UIViewAutoresizing.flexibleBottomMargin] collectionView.alwaysBounceVertical = true return collectionView } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return sites.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! SiteCollectionViewCell let site = sites[indexPath.row] cell.titleLabel.text = site.title cell.imageView.sd_setImage(with: site.imageURL, placeholderImage: UIImage(named: "no_image")) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let cellSize: CGFloat = view.frame.size.width / 3 return CGSize(width: cellSize, height: cellSize) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 1 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let site = sites[indexPath.row] loadURL(site.url) } }
3eea232541e5e1afdb4137c6d39e1484
44.806723
176
0.686846
false
false
false
false
Inquisitor0/LSB2
refs/heads/master
Cocoapods/Pods/PKHUD/PKHUD/FrameView.swift
apache-2.0
9
// // HUDView.swift // PKHUD // // Created by Philip Kluz on 6/16/14. // Copyright (c) 2016 NSExceptional. All rights reserved. // Licensed under the MIT license. // import UIKit /// Provides the general look and feel of the PKHUD, into which the eventual content is inserted. internal class FrameView: UIVisualEffectView { internal init() { super.init(effect: UIBlurEffect(style: .light)) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } fileprivate func commonInit() { backgroundColor = UIColor(white: 0.8, alpha: 0.36) layer.cornerRadius = 9.0 layer.masksToBounds = true contentView.addSubview(self.content) let offset = 20.0 let motionEffectsX = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis) motionEffectsX.maximumRelativeValue = offset motionEffectsX.minimumRelativeValue = -offset let motionEffectsY = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis) motionEffectsY.maximumRelativeValue = offset motionEffectsY.minimumRelativeValue = -offset let group = UIMotionEffectGroup() group.motionEffects = [motionEffectsX, motionEffectsY] addMotionEffect(group) } fileprivate var _content = UIView() internal var content: UIView { get { return _content } set { _content.removeFromSuperview() _content = newValue _content.alpha = 0.85 _content.clipsToBounds = true _content.contentMode = .center frame.size = _content.bounds.size addSubview(_content) } } }
26410e1005d73926bf8de243a14cf91f
27.492063
109
0.639554
false
false
false
false
TheSafo/Sinkr
refs/heads/master
ios stuff/Sinkr/Views/CupView.swift
gpl-3.0
1
// // CupView.swift // Sinkr // // Created by Jake Saferstein on 6/18/16. // Copyright © 2016 Jake Saferstein. All rights reserved. // import Foundation import UIKit protocol CupViewDelegate { func cupViewTapped(cupVw: CupView) } class CupView : UIView { static var cupWidthHeight: CGFloat { get { let cupWidth = (RackView.rackWidth - cupPadding*3)/4 return cupWidth } } var index: Index var status: CupStatus { didSet { self.updateCupForCurrentStatus() } } var delegate: CupViewDelegate? = nil init(index: Index, status: CupStatus) { self.index = index self.status = status super.init(frame: CGRectZero) let tapGr = UITapGestureRecognizer(target: self, action: #selector(self.cupTapped(_:))) tapGr.numberOfTapsRequired = 1 tapGr.numberOfTouchesRequired = 1 self.addGestureRecognizer(tapGr) self.layer.cornerRadius = CupView.cupWidthHeight/2 self.layer.borderWidth = 2 self.updateCupForCurrentStatus() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateCupForCurrentStatus() { switch status { case .DNE: self.hidden = true case .Full: self.backgroundColor = UIColor.redColor() case .Hit: self.backgroundColor = UIColor.greenColor() } } //MARK: Button handling func cupTapped(tapGR : UITapGestureRecognizer) { // self.delegate?.cupViewTapped(self) } }
9dd273532175037b1ca978bac1f93a54
21.866667
95
0.58484
false
false
false
false
LeonClover/DouYu
refs/heads/master
DouYuZB/DouYuZB/Classes/Tools/Common.swift
mit
1
// // Common.swift // DouYuZB // // Created by Leon on 2017/6/7. // Copyright © 2017年 pingan. All rights reserved. // import UIKit let kStatusBarH: CGFloat = 20 let kNavigationBarH: CGFloat = 44 let kTabbarH: CGFloat = 49 let kScreenW: CGFloat = UIScreen.main.bounds.width let kScreenH: CGFloat = UIScreen.main.bounds.height
a0ba1ecab819e92c58def7275c2536ce
15.9
51
0.710059
false
false
false
false
scotlandyard/expocity
refs/heads/master
expocity/View/Chat/Display/VChatDisplayMarks.swift
mit
1
import UIKit class VChatDisplayMarks:UIView { weak var controller:CChat! weak var button:UIButton? private let kItemSize:CGFloat = 50 private let itemSize_2:CGFloat init(controller:CChat) { itemSize_2 = kItemSize / 2.0 super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false self.controller = controller } required init?(coder:NSCoder) { fatalError() } //MARK: actions func actionButton(sender button:UIButton) { controller.displayDetail() } //MARK: public func addItems() { self.button?.removeFromSuperview() let imageWidth:CGFloat = bounds.maxX let imageHeight:CGFloat = bounds.maxY let button:UIButton = UIButton() button.backgroundColor = UIColor.clear button.translatesAutoresizingMaskIntoConstraints = false button.clipsToBounds = true button.addTarget( self, action:#selector(actionButton(sender:)), for:UIControlEvents.touchUpInside) self.button = button addSubview(button) let views:[String:UIView] = [ "button":button] let metrics:[String:CGFloat] = [:] addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[button]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[button]-0-|", options:[], metrics:metrics, views:views)) for modelItem:MChatDisplayAnnotationsItem in controller.model.annotations.items { let viewItem:VChatDisplayMarksItem = VChatDisplayMarksItem(controller:controller, model:modelItem) button.addSubview(viewItem) let percentX:CGFloat = modelItem.xPercent * imageWidth let percentY:CGFloat = modelItem.yPercent * imageHeight let itemLeft:CGFloat = percentX - itemSize_2 let itemTop:CGFloat = percentY - itemSize_2 let itemViews:[String:UIView] = [ "viewItem":viewItem] let itemMetrics:[String:CGFloat] = [ "itemSize":kItemSize, "itemLeft":itemLeft, "itemTop":itemTop] addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-(itemLeft)-[viewItem(itemSize)]", options:[], metrics:itemMetrics, views:itemViews)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-(itemTop)-[viewItem(itemSize)]", options:[], metrics:itemMetrics, views:itemViews)) } } }
de0db101fab2de8a4e10a8179967d1dc
29.79798
110
0.567727
false
false
false
false
notbenoit/tvOS-Twitch
refs/heads/develop
Code/tvOS/Controllers/Streams/StreamsViewController.swift
bsd-3-clause
1
// Copyright (c) 2015 Benoit Layer // // 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 AVKit import ReactiveSwift import ReactiveCocoa import DataSource import Result final class StreamsViewController: UIViewController { let streamCellWidth: CGFloat = 308.0 let horizontalSpacing: CGFloat = 50.0 let verticalSpacing: CGFloat = 100.0 let presentStream: Action<(stream: Stream, controller: UIViewController), AVPlayerViewController, AnyError> = Action(execute: controllerProducerForStream) @IBOutlet var collectionView: UICollectionView! @IBOutlet var loadingView: LoadingStateView! @IBOutlet var noItemsLabel: UILabel! @IBOutlet var loadingStreamView: UIView! @IBOutlet var loadingMessage: UILabel! let viewModel = MutableProperty<StreamList.ViewModelType?>(nil) let collectionDataSource = CollectionViewDataSource() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.twitchDark collectionDataSource.reuseIdentifierForItem = { _, item in if let item = item as? ReuseIdentifierProvider { return item.reuseIdentifier } fatalError() } loadingStreamView.reactive.isHidden <~ presentStream.isExecuting.producer.map(!) loadingMessage.reactive.text <~ presentStream.isExecuting.producer .filter { $0 } .map { _ in LoadingMessages.randomMessage } collectionDataSource.dataSource.innerDataSource <~ viewModel.producer.map { $0?.dataSource ?? EmptyDataSource() } collectionDataSource.collectionView = collectionView collectionView.dataSource = collectionDataSource noItemsLabel.text = NSLocalizedString("No game selected yet. Pick a game in the upper list.", comment: "") noItemsLabel.reactive.isHidden <~ viewModel.producer.map { $0 != nil } let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical layout.itemSize = CGSize(width: streamCellWidth, height: 250.0) layout.sectionInset = UIEdgeInsets(top: 60, left: 90, bottom: 60, right: 90) layout.minimumInteritemSpacing = horizontalSpacing layout.minimumLineSpacing = verticalSpacing collectionView.register(StreamCell.nib, forCellWithReuseIdentifier: StreamCell.identifier) collectionView.register(LoadMoreCell.nib, forCellWithReuseIdentifier: LoadMoreCell.identifier) collectionView.collectionViewLayout = layout collectionView.delegate = self collectionView.remembersLastFocusedIndexPath = true loadingView.reactive.loadingState <~ viewModel.producer.skipNil().chain { $0.paginator.loadingState } loadingView.reactive.isEmpty <~ viewModel.producer.skipNil().chain { $0.viewModels }.map { $0.isEmpty } loadingView.retry = { [weak self] in self?.viewModel.value?.paginator.loadFirst() } presentStream.values .observe(on: UIScheduler()) .observeValues { [weak self] in self?.present($0, animated: true, completion: nil) } } } extension StreamsViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let item = collectionDataSource.dataSource.item(at: indexPath) as? StreamViewModel { presentStream.apply((item.stream, self)).start() } } func scrollViewDidScroll(_ scrollView: UIScrollView) { let contentOffsetY = scrollView.contentOffset.y + scrollView.bounds.size.height let wholeHeight = scrollView.contentSize.height let remainingDistanceToBottom = wholeHeight - contentOffsetY if remainingDistanceToBottom <= 600 { viewModel.value?.loadMore() } } } private func controllerProducerForStream(_ stream: Stream, inController: UIViewController) -> SignalProducer<AVPlayerViewController, AnyError> { return TwitchAPIClient.sharedInstance.m3u8URLForChannel(stream.channel.channelName) .on(started: { UIApplication.shared.beginIgnoringInteractionEvents() }) .map { $0.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) } .map { $0.flatMap { URL(string: $0) } } .skipNil() .map { (url: URL) -> AVPlayerViewController in let playerController = AVPlayerViewController() playerController.view.frame = UIScreen.main.bounds let avPlayer = AVPlayer(url: url) playerController.player = avPlayer return playerController } .on() { _ in UIApplication.shared.endIgnoringInteractionEvents() } .on(terminated: { UIApplication.shared.endIgnoringInteractionEvents() }) .observe(on: UIScheduler()) .on() { $0.player?.play() } }
8ca19c6b1a1df2bb725c6da36477e776
40.761538
155
0.774544
false
false
false
false
thebinaryarchitect/list
refs/heads/master
Today/TodayViewController.swift
mit
1
// // TodayViewController.swift // Today // // Copyright (C) 2015 Xiao Yao. All Rights Reserved. // See LICENSE.txt for more information. // import UIKit import NotificationCenter import ListKit class TodayViewController: UITableViewController, NCWidgetProviding { var list: List override init(style: UITableViewStyle) { if let list = NSUserDefaults.groupUserDefaults().loadList() { self.list = list } else { self.list = List.init(title: "") } super.init(style: style) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.preferredContentSize = CGSizeMake(0.0, CGFloat(self.list.items.count) * 44.0) self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: NSStringFromClass(UITableViewCell.self)) self.tableView.separatorStyle = .None } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let list = NSUserDefaults.groupUserDefaults().loadList() { self.list = list } else { self.list = List.init(title: "") } self.tableView.reloadData() } // MARK: NCWidgetProviding func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) { // Perform any setup necessary in order to update the view. // If an error is encountered, use NCUpdateResult.Failed // If there's no update required, use NCUpdateResult.NoData // If there's an update, use NCUpdateResult.NewData completionHandler(NCUpdateResult.NewData) } // MARK: UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.list.items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(NSStringFromClass(UITableViewCell.self), forIndexPath: indexPath) let item = self.list.items[indexPath.row] cell.textLabel?.text = item.title cell.accessoryType = item.completed ? .Checkmark : .None cell.textLabel?.textColor = UIColor.whiteColor() return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { self.list.items.removeAtIndex(indexPath.row) self.list.save() tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { if sourceIndexPath.row != destinationIndexPath.row { let item = self.list.items[sourceIndexPath.row] self.list.items.removeAtIndex(sourceIndexPath.row) self.list.items.insert(item, atIndex: destinationIndexPath.row) self.list.save() } } // MARK: UITableViewDelegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let item = self.list.items[indexPath.row] item.completed = !item.completed self.list.save() let cell = tableView.cellForRowAtIndexPath(indexPath) cell?.accessoryType = item.completed ? .Checkmark : .None } }
49958d2c5b25f56a02aca6db8978ca0d
35.547826
157
0.670711
false
false
false
false
amraboelela/swift
refs/heads/master
test/SILGen/reabstract-tuple.swift
apache-2.0
12
// RUN: %target-swift-emit-silgen -verify %s | %FileCheck %s // SR-3090: class Box<T> { public let value: T public init(_ value: T) { self.value = value } } // CHECK: sil [ossa] @$s4main7testBoxyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: // function_ref closure #1 in testBox() // CHECK: [[CLOSURE:%.*]] = function_ref @$s4main7testBoxyyFyycfU_ : $@convention(thin) () -> () // CHECK: [[THICK:%.*]] = thin_to_thick_function [[CLOSURE]] : $@convention(thin) () -> () to $@callee_guaranteed () -> () // CHECK: [[TUPLEA:%.*]] = tuple (%{{.*}} : $Int, [[THICK]] : $@callee_guaranteed () -> ()) // CHECK: ([[ELTA_0:%.*]], [[ELTA_1:%.*]]) = destructure_tuple [[TUPLEA]] : $(Int, @callee_guaranteed () -> ()) // CHECK: [[THUNK1:%.*]] = function_ref @$sIeg_ytIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @out () // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[THUNK1]]([[ELTA_1]]) : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @out () // CHECK: [[TUPLEB:%.*]] = tuple ([[ELTA_0]] : $Int, [[PA]] : $@callee_guaranteed () -> @out ()) // CHECK: ([[TUPLEB_0:%.*]], [[TUPLEB_1:%.*]]) = destructure_tuple [[TUPLEB]] // CHECK: // function_ref Box.__allocating_init(_:) // CHECK: [[INIT_F:%.*]] = function_ref @$s4main3BoxCyACyxGxcfC : $@convention(method) <τ_0_0> (@in τ_0_0, @thick Box<τ_0_0>.Type) -> @owned Box<τ_0_0> // CHECK: [[CALL:%.*]] = apply [[INIT_F]]<(Int, () -> ())>(%{{.*}}, %{{.*}}) : $@convention(method) <τ_0_0> (@in τ_0_0, @thick Box<τ_0_0>.Type) -> @owned Box<τ_0_0> // CHECK: [[BORROW_CALL:%.*]] = begin_borrow [[CALL]] : $Box<(Int, () -> ())> // CHECK: [[REF:%.*]] = ref_element_addr [[BORROW_CALL]] : $Box<(Int, () -> ())>, #Box.value // CHECK: [[TUPLEC:%.*]] = load [copy] [[REF]] : $*(Int, @callee_guaranteed () -> @out ()) // CHECK: ([[TUPLEC_0:%.*]], [[TUPLEC_1:%.*]]) = destructure_tuple [[TUPLEC]] // CHECK: [[THUNK2:%.*]] = function_ref @$sytIegr_Ieg_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> @out ()) -> () // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] [[THUNK2]]([[TUPLEC_1]]) : $@convention(thin) (@guaranteed @callee_guaranteed () -> @out ()) -> () // CHECK: destroy_value [[PA2]] : $@callee_guaranteed () -> () // CHECK: end_borrow [[BORROW_CALL]] : $Box<(Int, () -> ())> // CHECK-LABEL: } // end sil function '$s4main7testBoxyyF' public func testBox() { let box = Box((22, { () in })) let foo = box.value.0 print(foo) } // Another crash -- re-abstracting function type inside optional in tuple // in-place func g<T>() -> (Int, T)? { } func f<T>(t: T) { let _: (Int, ((T) -> (), T))? = g() }
e4c97a910eaf1eac09f449fd387abbdc
52.058824
166
0.533999
false
true
false
false
resmio/TastyTomato
refs/heads/main
TastyTomato/Code/Types/CustomViews/ZoomView/ZoomView.swift
mit
1
// // ZoomView.swift // TastyTomato // // Created by Jan Nash on 11/29/16. // Copyright © 2016 resmio. All rights reserved. // import Foundation import SignificantSpices // MARK: // Public // MARK: - public protocol ZoomViewDelegate: AnyObject { func zoomed(to scale: CGFloat, in zoomView: ZoomView) } // MARK: - // MARK: Interface public extension ZoomView { // Setters func setDelegate(_ delegate: ZoomViewDelegate?) { self._delegate = delegate } func setScrollEnabled(_ enabled: Bool) { self._scrollView.isScrollEnabled = enabled } func setZoomThreshold(_ threshold: CGFloat) { self._zoomThreshold = threshold } func setMaximumScale(_ scale: CGFloat) { self._setMaximumZoomScale(scale) } func setShowsHorizontalScrollIndicator(_ shows: Bool) { self._scrollView.showsHorizontalScrollIndicator = shows } func setShowsVerticalScrollIndicator(_ shows: Bool) { self._scrollView.showsVerticalScrollIndicator = shows } func setDecelerationRate(_ rate: UIScrollView.DecelerationRate) { self._scrollView.decelerationRate = rate } func setBounces(_ bounces: Bool) { self._scrollView.bounces = bounces } func setBouncesZoom(_ bounces: Bool) { self._scrollView.bouncesZoom = bounces } func setDoubleTapEnabled(_ enabled: Bool) { self._setDoubleTapEnabled(enabled) } func setZoomOutTapEnabled(_ enabled: Bool) { self._setZoomOutTapEnabled(enabled) } func setCenterHorizontally(_ center: Bool) { self._setCenterHorizontally(center) } func setCenterVertically(_ center: Bool) { self._setCenterVertically(center) } func setContentInset(_ inset: UIEdgeInsets) { self._scrollView.contentInset = inset } // Functions func zoomOut(animated: Bool = true) { self._zoomOut(animated: animated) } // Call this when you changed the size of the // contentView to ensure that the minimum and // maximum zoomScale as well as the scrollView- // contentSize are updated accordingly func contentViewSizeChanged() { self._contentViewSizeChanged() } } // MARK: Class Declaration public class ZoomView: UIView { // Required Init required public init?(coder aDecoder: NSCoder) { fatalError("ZoomView does not support NSCoding") } // Privatized Inits private init() { fatalError() } private override init(frame: CGRect) { fatalError() } // Convenience Init public convenience init(contentView: UIView) { self.init(frame: contentView.bounds, contentView: contentView) } // Designated Init fileprivate init(frame: CGRect, contentView: UIView) { self._contentView = contentView super.init(frame: frame) self.addSubview(self._scrollView) self.setDoubleTapEnabled(true) self.setZoomOutTapEnabled(true) } // Private Weak Variables private weak var _delegate: ZoomViewDelegate? // Private Lazy Variables private lazy var _scrollView: ZoomToPointScrollView = self._createScrollView() // ALOs private lazy var _doubleTapRecognizer: ALO<UITapGestureRecognizer> = ALO({ [unowned self] in self._createDoubleTapRecognizer() }) private lazy var _zoomOutTapRecognizer: ALO<UITapGestureRecognizer> = ALO({ [unowned self] in self._createZoomOutTapRecognizer() }) // Private Variables private var _contentView: UIView private var _zoomThreshold: CGFloat = 0.2 private var _centerHorizontally: Bool = true private var _centerVertically: Bool = true private var __maximumZoomScale: CGFloat = 1 private var _doubleTapNextScale: CGFloat? // Frame / Size Overrides override public var frame: CGRect { get { return self._frame } set { self._frame = newValue } } override public var size: CGSize { get { return self._size } set { self._size = newValue } } override public var width: CGFloat { get { return self._width } set { self._width = newValue } } override public var height: CGFloat { get { return self._height } set { self._height = newValue } } } // MARK: Protocol Conformances // MARK: UIScrollViewDelegate extension ZoomView: UIScrollViewDelegate { public func viewForZooming(in scrollView: UIScrollView) -> UIView? { return self._contentView } public func scrollViewDidZoom(_ scrollView: UIScrollView) { self._didZoom(in: scrollView) } public func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { self._didZoom(in: scrollView) } } // MARK: // Private // MARK: Lazy Variable Creation private extension ZoomView { func _createScrollView() -> ZoomToPointScrollView { let contentView: UIView = self._contentView let scrollView: ZoomToPointScrollView = ZoomToPointScrollView(frame: self.bounds) scrollView.clipsToBounds = false scrollView.delegate = self scrollView.addSubview(contentView) scrollView.contentSize = contentView.size return scrollView } func _createDoubleTapRecognizer() -> UITapGestureRecognizer { let recognizer: UITapGestureRecognizer = UITapGestureRecognizer() recognizer.numberOfTapsRequired = 2 recognizer.addTarget(self, action: #selector(self._handleDoubleTap)) return recognizer } func _createZoomOutTapRecognizer() -> UITapGestureRecognizer { let recognizer: UITapGestureRecognizer = UITapGestureRecognizer() recognizer.numberOfTapsRequired = 2 recognizer.numberOfTouchesRequired = 2 recognizer.addTarget(self, action: #selector(self._handleZoomOutTap)) return recognizer } } // MARK: Setter Implementations private extension ZoomView { func _setMaximumZoomScale(_ scale: CGFloat) { let scrollView: UIScrollView = self._scrollView scrollView.maximumZoomScale = scale if scrollView.zoomScale > scale { scrollView.zoomIn(animated: false) } } func _setDoubleTapEnabled(_ enabled: Bool) { guard enabled == (self._doubleTapRecognizer¿ == nil) else { return } if enabled { self._scrollView.addGestureRecognizer(self._doubleTapRecognizer¡) } else { guard let recognizer: UITapGestureRecognizer = self._doubleTapRecognizer¿ else { return } self._scrollView.removeGestureRecognizer(recognizer) self._doubleTapRecognizer.clear() } } func _setZoomOutTapEnabled(_ enabled: Bool) { guard enabled == (self._zoomOutTapRecognizer¿ == nil) else { return } if enabled { self._scrollView.addGestureRecognizer(self._zoomOutTapRecognizer¡) } else { guard let recognizer: UITapGestureRecognizer = self._zoomOutTapRecognizer¿ else { return } self._scrollView.removeGestureRecognizer(recognizer) self._zoomOutTapRecognizer.clear() } } func _setCenterHorizontally(_ center: Bool) { self._centerHorizontally = center self._adjustScrollViewContentInsets() } func _setCenterVertically(_ center: Bool) { self._centerVertically = center self._adjustScrollViewContentInsets() } } // MARK: Frame / Size Override Implementations private extension ZoomView { var _frame: CGRect { get { return super.frame } set(newFrame) { super.frame = newFrame self._scrollView.size = newFrame.size self._updateZoomScalesAndAdjustScrollViewContentInsets() } } var _size: CGSize { get { return super.size } set(newSize) { super.size = newSize self._scrollView.size = newSize self._updateZoomScalesAndAdjustScrollViewContentInsets() } } var _width: CGFloat { get { return super.width } set(newWidth) { super.width = newWidth self._scrollView.width = newWidth self._updateZoomScalesAndAdjustScrollViewContentInsets() } } var _height: CGFloat { get { return super.height } set(newHeight) { super.height = newHeight self._scrollView.height = newHeight self._updateZoomScalesAndAdjustScrollViewContentInsets() } } } // MARK: Protocol Conformance Implementations // MARK: UIScrollViewDelegate private extension ZoomView/*: UIScrollViewDelegate*/ { func _didZoom(in scrollView: UIScrollView) { self._adjustScrollViewContentInsets() self._delegate?.zoomed(to: scrollView.zoomScale, in: self) } } // MARK: Target Selectors private extension ZoomView { @objc func _handleDoubleTap(_ recognizer: UITapGestureRecognizer) { let scrollView: ZoomToPointScrollView = self._scrollView let minScale: CGFloat = scrollView.minimumZoomScale let maxScale: CGFloat = scrollView.maximumZoomScale guard abs(minScale - maxScale) > self._zoomThreshold else { return } let midScale: CGFloat = (maxScale + minScale) / 2 let currentScale: CGFloat = scrollView.zoomScale var newScale: CGFloat = minScale switch currentScale { case let scale where abs(scale - midScale) < 0.01: newScale = self._doubleTapNextScale ?? minScale case let scale where abs(scale - maxScale) < 0.01: newScale = midScale self._doubleTapNextScale = minScale case let scale where scale < midScale - 0.01: newScale = midScale self._doubleTapNextScale = maxScale case let scale where scale < maxScale - 0.01: newScale = maxScale default: newScale = minScale } let point: CGPoint = recognizer.location(ofTouch: 0, in: scrollView) scrollView.zoom(to: point, with: newScale) } @objc func _handleZoomOutTap() { self._zoomOut(animated: true) } } // MARK: Interface Implementations private extension ZoomView { func _zoomOut(animated: Bool) { let animationDuration: TimeInterval = animated ? 0.2 : 0 UIView.animate(withDuration: animationDuration) { self._scrollView.zoomScale = self._scrollView.minimumZoomScale self._adjustScrollViewContentInsets() } } func _contentViewSizeChanged() { let scrollView: UIScrollView = self._scrollView let contentViewSize: CGSize = self._contentView.size guard scrollView.contentSize != contentViewSize else { return } scrollView.contentSize = contentViewSize self._updateZoomScalesAndAdjustScrollViewContentInsets() } } // MARK: Adjust Content Position / Update Zoom Scales private extension ZoomView { func _updateZoomScalesAndAdjustScrollViewContentInsets() { self._updateZoomScales() self._adjustScrollViewContentInsets() } func _adjustScrollViewContentInsets() { let centerH: Bool = self._centerHorizontally let centerV: Bool = self._centerVertically guard centerH || centerV else { return } let scrollView: UIScrollView = self._scrollView let boundsSize: CGSize = scrollView.bounds.size let contentSize: CGSize = scrollView.contentSize if centerH { let leftInset: CGFloat = (boundsSize.width - contentSize.width) / 2 scrollView.contentInset.left = max(0, leftInset) } if centerV { let topInset: CGFloat = (boundsSize.height - contentSize.height) / 2 scrollView.contentInset.top = max(0, topInset) } } func _updateZoomScales() { let scrollView: UIScrollView = self._scrollView let contentSize: CGSize = self._scrollView.contentSize let widthRatio: CGFloat = scrollView.width / contentSize.width let heightRatio: CGFloat = scrollView.height / contentSize.height let currentZoomScale: CGFloat = scrollView.zoomScale let minScale: CGFloat = min(widthRatio, heightRatio) * currentZoomScale scrollView.minimumZoomScale = minScale if currentZoomScale < minScale { self._scrollView.zoomOut(animated: false) } else { self._delegate?.zoomed(to: currentZoomScale, in: self) } } }
93de27194091e8bd6bdd6c0864aeee93
29.992771
135
0.639947
false
false
false
false
quen2404/absolute0
refs/heads/develop
Sources/App/Models/Post.swift
mit
1
import Vapor import Fluent import Foundation struct PostModel: Model { static var entity = "posts" var id: Node? var content: String var creationDate: Date? var user: UserModel var event: EventModel var exists: Bool = false } extension PostModel: NodeConvertible { init(node: Node, in context: Context) throws { id = try node.extract("id") content = try node.extract("content") creationDate = try node.extract("creationDate") user = try node.extract("user") event = try node.extract("event") } func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, "content": content, "creationDate": creationDate, "user": user, "event": event ]) } } extension PostModel: Preparation { static func prepare(_ database: Database) throws { try database.create(entity) { teams in teams.id() teams.string("content", optional: false) teams.double("creationDate", optional: true) teams.parent(EventModel.self, optional: false) teams.parent(UserModel.self, optional: false) } } static func revert(_ database: Database) throws { fatalError("unimplemented \(#function)") } }
4a79784b6863994e9294108a24e6339d
24.849057
58
0.583942
false
false
false
false
overtake/TelegramSwift
refs/heads/master
Telegram-Mac/EmptyComposeController.swift
gpl-2.0
1
// // EmptyComposeController.swift // TelegramMac // // Created by keepcoder on 27/11/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa import TGUIKit import SwiftSignalKit import TelegramCore class ComposeState<T> { let result:T init(_ result:T) { self.result = result } } class EmptyComposeController<I,T,R>: TelegramGenericViewController<R> where R:NSView { public let onChange:Promise<T> = Promise() public let onComplete:Promise<T> = Promise() public let onCancel:Promise<Void> = Promise() public var previousResult:ComposeState<I>? = nil func restart(with result:ComposeState<I>) { self.previousResult = result } }
74ef8a55e7ab591a66dd3b8d8028d0c6
21.870968
86
0.692525
false
false
false
false
steelwheels/Coconut
refs/heads/master
CoconutData/Source/Value/CNMutableSegment.swift
lgpl-2.1
1
/* * @file CNMutableSegmentValue.swift * @brief Define CNMutableSegmentValue class * @par Copyright * Copyright (C) 2022 Steel Wheels Project */ import Foundation public class CNMutableValueSegment: CNMutableValue { private var mSegmentValue: CNValueSegment private var mContext: CNMutableValue? public init(value val: CNValueSegment, sourceDirectory srcdir: URL, cacheDirectory cachedir: URL){ mSegmentValue = val mContext = nil super.init(type: .segment, sourceDirectory: srcdir, cacheDirectory: cachedir) } public var context: CNMutableValue? { get { return mContext }} public var sourceFile: URL { get { return self.sourceDirectory.appendingPathComponent(mSegmentValue.filePath) }} public var cacheFile: URL { get { return self.cacheDirectory.appendingPathComponent(mSegmentValue.filePath) }} public var description: String { get { return self.toValue().description }} public override func _value(forPath path: Array<CNValuePath.Element>, in root: CNMutableValue) -> Result<CNMutableValue?, NSError> { let result: Result<CNMutableValue?, NSError> switch load() { case .success(let mval): result = mval._value(forPath: path, in: root) case .failure(let err): result = .failure(err) } return result } public override func _set(value val: CNValue, forPath path: Array<CNValuePath.Element>, in root: CNMutableValue) -> NSError? { let result: NSError? switch load() { case .success(let mval): result = mval._set(value: val, forPath: path, in: root) case .failure(let err): result = err } return result } public override func _append(value val: CNValue, forPath path: Array<CNValuePath.Element>, in root: CNMutableValue) -> NSError? { let result: NSError? switch load() { case .success(let mval): result = mval._append(value: val, forPath: path, in: root) case .failure(let err): result = err } return result } public override func _delete(forPath path: Array<CNValuePath.Element>, in root: CNMutableValue) -> NSError? { let result: NSError? switch load() { case .success(let mval): result = mval._delete(forPath: path, in: root) case .failure(let err): result = err } return result } public func load() -> Result<CNMutableValue, NSError> { let result: Result<CNMutableValue, NSError> if let ctxt = mContext { result = .success(ctxt) } else { if let src = mSegmentValue.load(fromSourceDirectory: self.sourceDirectory, cacheDirectory: self.cacheDirectory) { let ctxt = toMutableValue(from: src) mContext = ctxt result = .success(ctxt) } else { result = .failure(NSError.parseError(message: "Failed to load: source=\(self.sourceFile.path) cache=\(self.cacheFile.path)")) } } return result } public override func _search(name nm: String, value val: String, in root: CNMutableValue) -> Result<Array<CNValuePath.Element>?, NSError> { let result: Result<Array<CNValuePath.Element>?, NSError> switch load() { case .success(let mval): result = mval._search(name: nm, value: val, in: root) case .failure(let err): result = .failure(err) } return result } public override func _makeLabelTable(property name: String, path pth: Array<CNValuePath.Element>) -> Dictionary<String, Array<CNValuePath.Element>> { switch load() { case .success(let mval): return mval._makeLabelTable(property: name, path: pth) case .failure(let err): CNLog(logLevel: .error, message: "Error: \(err.toString())", atFunction: #function, inFile: #file) return [:] } } public override func clone() -> CNMutableValue { return CNMutableValueSegment(value: mSegmentValue, sourceDirectory: self.sourceDirectory, cacheDirectory: self.cacheDirectory) } public override func toValue() -> CNValue { return .dictionaryValue(mSegmentValue.toValue()) } }
0bba933273f801feae96bdefeab90f30
30.130081
150
0.712196
false
false
false
false
JaSpa/swift
refs/heads/master
test/SILGen/scalar_to_tuple_args.swift
apache-2.0
2
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s func inoutWithDefaults(_ x: inout Int, y: Int = 0, z: Int = 0) {} func inoutWithCallerSideDefaults(_ x: inout Int, y: Int = #line) {} func scalarWithDefaults(_ x: Int, y: Int = 0, z: Int = 0) {} func scalarWithCallerSideDefaults(_ x: Int, y: Int = #line) {} func tupleWithDefaults(x x: (Int, Int), y: Int = 0, z: Int = 0) {} func variadicFirst(_ x: Int...) {} func variadicSecond(_ x: Int, _ y: Int...) {} var x = 0 // CHECK: [[X_ADDR:%.*]] = global_addr @_T020scalar_to_tuple_args1xSiv : $*Int // CHECK: [[INOUT_WITH_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args17inoutWithDefaultsySiz_Si1ySi1ztF // CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: apply [[INOUT_WITH_DEFAULTS]]([[X_ADDR]], [[DEFAULT_Y]], [[DEFAULT_Z]]) inoutWithDefaults(&x) // CHECK: [[INOUT_WITH_CALLER_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args27inoutWithCallerSideDefaultsySiz_Si1ytF // CHECK: [[LINE_VAL:%.*]] = integer_literal // CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]] // CHECK: apply [[INOUT_WITH_CALLER_DEFAULTS]]([[X_ADDR]], [[LINE]]) inoutWithCallerSideDefaults(&x) // CHECK: [[SCALAR_WITH_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args0A12WithDefaultsySi_Si1ySi1ztF // CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]] // CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: apply [[SCALAR_WITH_DEFAULTS]]([[X]], [[DEFAULT_Y]], [[DEFAULT_Z]]) scalarWithDefaults(x) // CHECK: [[SCALAR_WITH_CALLER_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args0A22WithCallerSideDefaultsySi_Si1ytF // CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]] // CHECK: [[LINE_VAL:%.*]] = integer_literal // CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]] // CHECK: apply [[SCALAR_WITH_CALLER_DEFAULTS]]([[X]], [[LINE]]) scalarWithCallerSideDefaults(x) // CHECK: [[TUPLE_WITH_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args0C12WithDefaultsySi_Sit1x_Si1ySi1ztF // CHECK: [[X1:%.*]] = load [trivial] [[X_ADDR]] // CHECK: [[X2:%.*]] = load [trivial] [[X_ADDR]] // CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: apply [[TUPLE_WITH_DEFAULTS]]([[X1]], [[X2]], [[DEFAULT_Y]], [[DEFAULT_Z]]) tupleWithDefaults(x: (x,x)) // CHECK: [[VARIADIC_FIRST:%.*]] = function_ref @_T020scalar_to_tuple_args13variadicFirstySaySiG_dtF // CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer) // CHECK: [[ARRAY:%.*]] = tuple_extract [[ALLOC_ARRAY]] {{.*}}, 0 // CHECK: [[MEMORY:%.*]] = tuple_extract [[ALLOC_ARRAY]] {{.*}}, 1 // CHECK: [[ADDR:%.*]] = pointer_to_address [[MEMORY]] // CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]] // CHECK: store [[X]] to [trivial] [[ADDR]] // CHECK: apply [[VARIADIC_FIRST]]([[ARRAY]]) variadicFirst(x) // CHECK: [[VARIADIC_SECOND:%.*]] = function_ref @_T020scalar_to_tuple_args14variadicSecondySi_SaySiGdtF // CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer) // CHECK: [[ARRAY:%.*]] = tuple_extract [[ALLOC_ARRAY]] {{.*}}, 0 // CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]] // CHECK: apply [[VARIADIC_SECOND]]([[X]], [[ARRAY]]) variadicSecond(x)
aab1e78414d663d5408742fc1b970ffa
52.123077
126
0.607588
false
false
false
false
nathantannar4/NTComponents
refs/heads/master
NTComponents/Extensions/UIColor.swift
mit
1
// // UIColor.swift // NTComponents // // Copyright © 2017 Nathan Tannar. // // 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. // // Created by Nathan Tannar on 2/12/17. // public extension UIColor { //**************************************/ // Convenience Initilizers //**************************************/ /// Takes a 6 character HEX string and initializes a corresponding UIColor. Initializes as UIColor.white /// any discrepancies are found. (A # character will be automatically removed if added) /// /// - Parameter hex: 6 HEX color code public convenience init(hex: String) { var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if (cString.hasPrefix("#")) { cString.remove(at: cString.startIndex) } if ((cString.characters.count) != 6) { self.init(red: 0, green: 0, blue: 0, alpha: 1) } else { var rgbValue:UInt32 = 0 Scanner(string: cString).scanHexInt32(&rgbValue) self.init( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } } /// Initializes a UIColor for its corresponding rgba UInt /// /// - Parameter rgba: UInt public convenience init(rgba: UInt){ let sRgba = min(rgba,0xFFFFFFFF) let red: CGFloat = CGFloat((sRgba & 0xFF000000) >> 24) / 255.0 let green: CGFloat = CGFloat((sRgba & 0x00FF0000) >> 16) / 255.0 let blue: CGFloat = CGFloat((sRgba & 0x0000FF00) >> 8) / 255.0 let alpha: CGFloat = CGFloat(sRgba & 0x000000FF) / 255.0 self.init(red: red, green: green, blue: blue, alpha: alpha) } public convenience init(r: CGFloat, g: CGFloat, b: CGFloat){ self.init(red: r / 255, green: g / 255, blue: b / 255, alpha: 1) } //**************************************/ // Functions //**************************************/ func lighter(by percentage: CGFloat = 30.0) -> UIColor { return self.adjust(by: abs(percentage)) ?? .white } func darker(by percentage: CGFloat = 30.0) -> UIColor { return self.adjust(by: -1 * abs(percentage)) ?? .black } /// Performs an equivalent to the .map({}) function, adjusting the current r, g, b value by the percentage /// /// - Parameter percentage: CGFloat /// - Returns: UIColor or nil if there was an error func adjust(by percentage: CGFloat = 30.0) -> UIColor? { var r:CGFloat=0, g:CGFloat=0, b:CGFloat=0, a:CGFloat=0; if (self.getRed(&r, green: &g, blue: &b, alpha: &a)){ return UIColor(red: min(r + percentage/100, 1.0), green: min(g + percentage/100, 1.0), blue: min(b + percentage/100, 1.0), alpha: a) } else{ return nil } } func withAlpha(_ alpha: CGFloat) -> UIColor { return self.withAlphaComponent(alpha) } func isDarker(than color: UIColor) -> Bool { return self.luminance < color.luminance } func isLighter(than color: UIColor) -> Bool { return !self.isDarker(than: color) } //**************************************/ // Extended Variables //**************************************/ var ciColor: CIColor { return CIColor(color: self) } var RGBA: [CGFloat] { return [ciColor.red, ciColor.green, ciColor.blue, ciColor.alpha] } var luminance: CGFloat { let RGBA = self.RGBA func lumHelper(c: CGFloat) -> CGFloat { return (c < 0.03928) ? (c/12.92): pow((c+0.055)/1.055, 2.4) } return 0.2126 * lumHelper(c: RGBA[0]) + 0.7152 * lumHelper(c: RGBA[1]) + 0.0722 * lumHelper(c: RGBA[2]) } var isDark: Bool { return self.luminance < 0.5 } var isLight: Bool { return !self.isDark } var isBlackOrWhite: Bool { let RGBA = self.RGBA let isBlack = RGBA[0] < 0.09 && RGBA[1] < 0.09 && RGBA[2] < 0.09 let isWhite = RGBA[0] > 0.91 && RGBA[1] > 0.91 && RGBA[2] > 0.91 return isBlack || isWhite } /// Apples default tint color static var lightBlue: UIColor { get { return UIColor(hex: "007AFF") } } }
6a65d595c404f38d9fbb6f1dffc80e76
33.277108
111
0.555009
false
false
false
false
eliakorkmaz/iCard
refs/heads/master
iCard/iCreditCard.swift
mit
1
// // iCreditCard.swift // iCard // // Created by xcodewarrior on 14.08.2017. // Copyright © 2017 EmrahKorkmaz. All rights reserved. // import UIKit class iCreditCard: UIView { lazy var contentView: UIView = { let view:UIView = UIView() view.backgroundColor = UIColor.clear return view }() lazy var bankNameLabel: UILabel = { let label:UILabel = UILabel() label.font = UIFont.init(name: "Avenir-Black", size: 20) label.text = "BANK NAME" label.textAlignment = .left label.textColor = UIColor.white return label }() lazy var topSeparator: UIView = { let view:UIView = UIView() view.backgroundColor = UIColor.white return view }() lazy var creditCardButton: UIButton = { let button:UIButton = UIButton() button.setImage(UIImage.init(named: "creditCardBackground"), for: .normal) button.layer.cornerRadius = 8 button.isUserInteractionEnabled = false button.showsTouchWhenHighlighted = false return button }() lazy var backgroundImageView: UIImageView = { let imageView:UIImageView = UIImageView() imageView.contentMode = .scaleToFill imageView.layer.masksToBounds = true imageView.layer.cornerRadius = 8 return imageView }() lazy var chipIconImageView: UIImageView = { let imageView:UIImageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.layer.masksToBounds = true imageView.layer.cornerRadius = 5 imageView.image = UIImage.init(named: "chip1") return imageView }() lazy var creditCardNumbers: UILabel = { let label:UILabel = UILabel() label.textAlignment = .left label.textColor = UIColor.white label.text = "4111 1111 1111 1111" label.font = UIFont.init(name: "Halter", size: 16) return label }() lazy var creditNumberTitleLabel: UILabel = { let label:UILabel = UILabel() label.text = "CARD NUMBER" label.font = UIFont.init(name: "Avenir-Light", size: 8) label.textColor = UIColor.white label.textAlignment = .left return label }() lazy var creditCardLastUsage: UILabel = { let label:UILabel = UILabel() label.text = "06/21" label.textColor = UIColor.white label.font = UIFont.init(name: "Halter", size: 14) label.textAlignment = .center return label }() lazy var lastUsageTitleLabel: UILabel = { let label:UILabel = UILabel() label.text = "MONTH/YEAR" label.textColor = UIColor.white label.font = UIFont.init(name: "Avenir-Light", size: 8) return label }() lazy var validThruLabel: UILabel = { let label:UILabel = UILabel() label.text = "VALID THRU" label.textAlignment = .center label.textColor = UIColor.white label.font = UIFont.init(name: "Avenir-Light", size: 8) label.numberOfLines = 0 return label }() lazy var cardBrandName: UILabel = { let label:UILabel = UILabel() label.text = "BANK NAME" label.font = UIFont.init(name: "Avenir-Black", size: 20) label.textAlignment = .left label.textColor = UIColor.white return label }() lazy var cardBrandImageView: UIImageView = { let imageView:UIImageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.layer.masksToBounds = true imageView.layer.cornerRadius = 5 imageView.image = UIImage.init(named: "maestro2Icon") return imageView }() lazy var cardBrandImageViewBottom: UIImageView = { let imageView:UIImageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.layer.masksToBounds = true imageView.layer.cornerRadius = 5 imageView.image = UIImage.init(named: "visaIcon") return imageView }() lazy var cardholderLabel: UILabel = { let label:UILabel = UILabel() label.text = "CARDHOLDER" label.font = UIFont.init(name: "Avenir-Black", size: 20) label.textColor = UIColor.white return label }() convenience init(){ self.init(cardStyleWithBackgroundColor: .withBothBankIcon, withCardColors: .yelloway, pinIcon: .chip1, creditIcons: .cirrusIcon) } convenience init(cardColors: cardColors){ self.init(cardStyleWithBackgroundColor: .withBothBankIcon, withCardColors: .yelloway, pinIcon: .chip2, creditIcons: .americanExpressIcon) } init(cardStyleWithBackgroundColor: cardStyle , withCardColors colors: cardColors , pinIcon: chipIcons , creditIcons: creditIcons){ super.init(frame: CGRect()) addItemsWithColors(cardStyleWithBackgroundColor, colors: colors, chipIcon: pinIcon, creditIcon: creditIcons) settingForLayout(cardStyle: cardStyleWithBackgroundColor, cardVisual: cardVisual.withBackgroundColor, withSeparator: true) } init(cardStyleWithBackgroundImage: cardStyle , withCardImage: UIImage?, pinIcon: chipIcons , creditIcons: creditIcons){ super.init(frame: CGRect()) addItemsWithImage(image: withCardImage, cardStyleWithBackgroundImage, chipIcon: pinIcon, creditIcon: creditIcons) settingForLayout(cardStyle: cardStyleWithBackgroundImage, cardVisual: cardVisual.withBackgroundImage, withSeparator: true) } fileprivate func addItemsWithImage(image backgroundImage: UIImage? , _ cardStyle: cardStyle, chipIcon: chipIcons , creditIcon: creditIcons){ self.addSubview(contentView) self.addSubview(backgroundImageView) self.addSubview(bankNameLabel) self.addSubview(creditCardButton) self.addSubview(chipIconImageView) self.addSubview(creditCardNumbers) self.addSubview(creditNumberTitleLabel) self.addSubview(creditCardLastUsage) self.addSubview(lastUsageTitleLabel) self.addSubview(validThruLabel) self.addSubview(cardBrandName) self.addSubview(cardholderLabel) if let image = backgroundImage{ self.backgroundImageView.image = image }else{ fillWithColor(color: cardColors.yelloway) } if cardStyle == .withBothBankIcon{ self.addSubview(cardBrandImageView) cardBrandImageView.image = creditIconImage(creditIcon: creditIcon) self.addSubview(cardBrandImageViewBottom) cardBrandImageViewBottom.image = creditIconImage(creditIcon: creditIcon) }else if cardStyle == .withTopBankIcon{ self.addSubview(cardBrandImageView) cardBrandImageView.image = creditIconImage(creditIcon: creditIcon) }else if cardStyle == .withBottomBankIcon{ self.addSubview(cardBrandImageViewBottom) cardBrandImageViewBottom.image = creditIconImage(creditIcon: creditIcon) }else{ // nothing will be added } switch chipIcon{ case .chip1: chipIconImageView.image = UIImage(named: "chip1") case .chip2: chipIconImageView.image = UIImage(named: "chip2") case .chip3: chipIconImageView.image = UIImage(named: "chip1") } self.addSubview(topSeparator) } fileprivate func addItemsWithColors(_ cardStyle: cardStyle , colors: cardColors , chipIcon: chipIcons , creditIcon: creditIcons){ self.addSubview(contentView) self.addSubview(bankNameLabel) self.addSubview(creditCardButton) self.addSubview(chipIconImageView) self.addSubview(creditCardNumbers) self.addSubview(creditNumberTitleLabel) self.addSubview(creditCardLastUsage) self.addSubview(lastUsageTitleLabel) self.addSubview(validThruLabel) self.addSubview(cardBrandName) self.addSubview(cardholderLabel) if cardStyle == .withBothBankIcon{ self.addSubview(cardBrandImageView) cardBrandImageView.image = creditIconImage(creditIcon: creditIcon) self.addSubview(cardBrandImageViewBottom) cardBrandImageViewBottom.image = creditIconImage(creditIcon: creditIcon) }else if cardStyle == .withTopBankIcon{ self.addSubview(cardBrandImageView) cardBrandImageView.image = creditIconImage(creditIcon: creditIcon) }else if cardStyle == .withBottomBankIcon{ self.addSubview(cardBrandImageViewBottom) cardBrandImageViewBottom.image = creditIconImage(creditIcon: creditIcon) }else{ // nothing will be added } switch chipIcon{ case .chip1: chipIconImageView.image = UIImage(named: "chip1") case .chip2: chipIconImageView.image = UIImage(named: "chip2") case .chip3: chipIconImageView.image = UIImage(named: "chip3") } self.addSubview(topSeparator) fillWithColor(color: colors) } fileprivate func fillWithColor(color: cardColors){ switch color { case .blueway: self.backgroundColor = UIColor(r: 28, g: 91, b: 140, alpha: 1) case .yelloway: self.backgroundColor = UIColor(r: 182, g: 152, b: 65, alpha: 1) case .greenway: self.backgroundColor = UIColor(r: 46, g: 204, b: 113, alpha: 1) } } fileprivate func settingForLayout(cardStyle style: cardStyle , cardVisual : cardVisual , withSeparator: Bool){ self.layer.cornerRadius = 8 if cardVisual == .withBackgroundImage { backgroundImageView.snp.makeConstraints({ (make) in make.left.equalTo(self.snp.left) make.right.equalTo(self.snp.right) make.top.equalTo(self.snp.top) make.bottom.equalTo(self.snp.bottom) }) } contentView.snp.makeConstraints({ (make) in make.left.equalTo(self.snp.left) make.right.equalTo(self.snp.right) make.top.equalTo(self.snp.top) make.bottom.equalTo(self.snp.bottom) }) chipIconImageView.snp.makeConstraints({ (make) in make.height.equalTo(40) make.width.equalTo(60) make.left.equalTo(self.snp.left).offset(15) make.bottom.equalTo(self.snp.centerY) }) creditCardNumbers.snp.makeConstraints({ (make) in make.left.equalTo(chipIconImageView.snp.left).offset(8) make.right.equalTo(self.snp.right).offset(-15) make.centerX.equalTo(self.snp.centerX) make.top.equalTo(chipIconImageView.snp.bottom).offset(5) }) creditNumberTitleLabel.snp.makeConstraints({ (make) in make.left.equalTo(creditCardNumbers) make.top.equalTo(creditCardNumbers.snp.bottom).offset(1) }) lastUsageTitleLabel.snp.makeConstraints({ (make) in make.centerX.equalTo(self.snp.centerX) make.centerY.equalTo(creditNumberTitleLabel.snp.centerY) }) creditCardLastUsage.snp.makeConstraints({ (make) in make.centerX.equalTo(lastUsageTitleLabel.snp.centerX) make.top.equalTo(lastUsageTitleLabel.snp.bottom).offset(1) }) validThruLabel.snp.makeConstraints({ (make) in make.centerY.equalTo(creditCardLastUsage) make.right.equalTo(creditCardLastUsage.snp.left).offset(-1) make.width.equalTo(30) }) if style == .withDefaultTitles{ cardBrandName.snp.makeConstraints({ (make) in make.top.equalTo(self.snp.top).offset(10) make.left.equalTo(self.snp.left).offset(10) }) topSeparator.snp.makeConstraints({ (make) in make.left.equalTo(self.snp.left) make.right.equalTo(self.snp.right) make.height.equalTo(2) make.top.equalTo(cardBrandName.snp.bottom).offset(1) }) }else if style == .withBottomBankIcon{ cardBrandImageViewBottom.snp.makeConstraints({ (make) in make.right.equalTo(self.snp.right).offset(-10) make.bottom.equalTo(self.snp.bottom).offset(-10) make.height.equalTo(30) make.width.equalTo(40) }) topSeparator.snp.makeConstraints({ (make) in make.left.equalTo(self.snp.left) make.right.equalTo(self.snp.right) make.height.equalTo(2) make.top.equalTo(self.snp.top).offset(41) }) }else if style == .withTopBankIcon{ cardBrandImageView.snp.makeConstraints({ (make) in make.top.equalTo(self.snp.top).offset(10) make.right.equalTo(self.snp.right).offset(-10) make.height.equalTo(30) make.width.equalTo(40) }) topSeparator.snp.makeConstraints({ (make) in make.left.equalTo(self.snp.left) make.right.equalTo(self.snp.right) make.height.equalTo(2) make.top.equalTo(cardBrandImageView.snp.bottom).offset(1) }) }else{ cardBrandImageView.snp.makeConstraints({ (make) in make.top.equalTo(self.snp.top).offset(10) make.right.equalTo(self.snp.right).offset(-10) make.height.equalTo(30) make.width.equalTo(40) }) cardBrandImageViewBottom.snp.makeConstraints({ (make) in make.right.equalTo(self.snp.right).offset(-10) make.bottom.equalTo(self.snp.bottom).offset(-10) make.height.equalTo(30) make.width.equalTo(40) }) topSeparator.snp.makeConstraints({ (make) in make.left.equalTo(self.snp.left) make.right.equalTo(self.snp.right) make.height.equalTo(2) make.top.equalTo(cardBrandImageView.snp.bottom).offset(1) }) } cardholderLabel.snp.makeConstraints({ (make) in make.left.equalTo(creditCardNumbers) make.bottom.equalTo(self.snp.bottom).offset(-10) }) } override init(frame: CGRect){ super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() } } public enum cardColors{ case blueway case yelloway case greenway } public enum cardVisual{ case withBackgroundColor case withBackgroundImage } public enum cardStyle{ case withDefaultTitles case withTopBankIcon case withBottomBankIcon case withBothBankIcon } public enum creditIcons{ case americanExpressIcon case bitcoinIcon case bluePayIcon case cirrusIcon case citiIcon case clickBank case cvsIcon case googleWalletIcon case hsbcIcon case maestroIcon case maestroIcon2 case masterCard case masterCardMini case masterCardDetail case moneyGramIcon case paypalIcon case paypalIconSimple case visaIcon case visaIconBigger case visaIconText case wePayIcon case westernUnionIcon } public enum chipIcons{ case chip1 case chip2 case chip3 } extension UIColor{ convenience init(r: Float, g: Float , b: Float , alpha: Int) { self.init(red: CGFloat(r/255), green: CGFloat(g/255), blue: CGFloat(b/255), alpha: CGFloat(alpha)) } } extension iCreditCard{ fileprivate func creditIconImage(creditIcon toImage: creditIcons) -> UIImage{ switch toImage { case .americanExpressIcon: return UIImage(named: "americanExpressIcon")! case .bitcoinIcon: return UIImage(named: "bitcoinIcon")! case .bluePayIcon: return UIImage(named: "bluePayIcon")! case .cirrusIcon: return UIImage(named: "cirrusIcon")! case .citiIcon: return UIImage(named: "citiIcon")! case .clickBank: return UIImage(named: "clickBank")! case .cvsIcon: return UIImage(named: "cvsIcon")! case .googleWalletIcon: return UIImage(named: "googleWalletIcon")! case .hsbcIcon: return UIImage(named: "hsbcIcon")! case .maestroIcon: return UIImage(named: "maestroIcon")! case .maestroIcon2: return UIImage(named: "maestro2Icon")! case .masterCard: return UIImage(named: "masterCard")! case .masterCardMini: return UIImage(named: "masterCardMini")! case .masterCardDetail: return UIImage(named: "masterCardDetail")! case .moneyGramIcon: return UIImage(named: "moneygramIcon")! case .paypalIcon: return UIImage(named: "paypal2Icon")! case .paypalIconSimple: return UIImage(named: "paypalIcon")! case .visaIcon: return UIImage(named: "visaIcon")! case .visaIconBigger: return UIImage(named: "visaIconBigger")! case .visaIconText: return UIImage(named: "visaIconText")! case .wePayIcon: return UIImage(named: "wepayIcon")! case .westernUnionIcon: return UIImage(named: "westernUnionIcon")! } } }
371ad5ac29db6ffc021f9e3cb80470d0
34.461538
145
0.613938
false
false
false
false
timfuqua/Bourgeoisie
refs/heads/master
Bourgeoisie/Pods/Buckets/Source/Graph.swift
mit
1
// // Graph.swift // Buckets // // Created by Mauricio Santos on 2/19/15. // Copyright (c) 2015 Mauricio Santos. All rights reserved. // import Foundation /// A simple directed graph: that is, one with no loops (edges /// connected at both ends to the same vertex) and no more than one edge /// in the same direction between any two different vertices. /// All vertices in the graph are unique. /// The preferred way to insert vertices and edges is using subscript notation. Example: /// `graph["NY", "Boston"] = distance` /// /// Conforms to `SequenceType`. public struct Graph<Vertex: Hashable, Edge> { private typealias GraphNode = VertexNode<Vertex, Edge> // MARK: Creating a Graph /// Creates an empty graph. public init() {} // MARK: Querying a Graph /// Number of vertices stored in the graph. public var count: Int { return nodes.count } /// Returns `true` if and only if `count == 0`. public var isEmpty: Bool { return count == 0 } /// Returns `true` if every pair of distinct vertices is connected by a /// unique edge (one in each direction). public var isComplete: Bool { return !nodes.values.contains { $0.adjacencyList.count != count - 1 } } /// Returns `true` if there's not a path starting and ending /// at the same vertex. public var isAcyclic: Bool { var visited = Set<GraphNode>() for sourceNode in nodes.values { var path = [Vertex]() for neighbor in sourceNode.successors { if containsPathFrom(neighbor, to: sourceNode, visited: &visited, path: &path) { return false } } } return true } /// Returns the vertices stored in the graph. public var vertices: Set<Vertex> { return Set(nodes.keys) } /// Returns the edges stored in the graph. public var edges: [Edge] { var edges = [Edge]() for node in nodes.values { edges += node.edges } return edges } /// Returns `true` if the graph contains the given vertex. public func containsVertex(vertex: Vertex) -> Bool { return nodes[vertex] != nil } /// Returns `true` if the graph contains an edge from `source` to `destination`. /// Subscript notation is preferred. public func containsEdgeFrom(source: Vertex, to destination: Vertex) -> Bool { return edgeFrom(source, to: destination) != nil } /// Returns the edge connecting `source` to `destination` if it exists. /// Subscript notation is preferred. public func edgeFrom(source: Vertex, to destination: Vertex) -> Edge? { if let sourceNode = nodes[source], destinationNode = nodes[destination] { return sourceNode.edgeConnectingTo(destinationNode) } return nil } /// Returns the set of direct successors of the given vertex. An empty set /// is returned if the vertex does not exist. public func neighbors(source: Vertex) -> Set<Vertex> { if let node = nodes[source] { return Set(node.successors.map{$0.data}) } return [] } /// Returns an array of vertices representing a path from `source` to `destination`, if it exists. /// /// - returns: An array containing at least two vertices (`source` and `destination`) or an empty array. public func pathFrom(source: Vertex, to destination: Vertex) -> [Vertex] { if let sourceNode = nodes[source], destinationNode = nodes[destination] { var path = [Vertex]() var visited = Set<GraphNode>() for successor in sourceNode.successors { if containsPathFrom(successor, to: destinationNode, visited: &visited, path: &path) { return [source] + path } } } return [] } /// Returns a generator iterating over the vertices in the specified order starting at the given vertex. /// Valid options are .DepthFirst and .BreadthFirst. /// /// The generator never returns the same vertex more than once. public func generateAt(source: Vertex, order: GraphTraversalOrder) -> AnyGenerator<Vertex> { if let sourceNode = nodes[source] { let nextNode: () -> GraphNode? let visitEventually: (GraphNode) -> Void switch order { case .DepthFirst: var nextVertices = Stack<GraphNode>() nextNode = {nextVertices.pop()} visitEventually = {nextVertices.push($0)} case .BreadthFirst: var nextVertices = Queue<GraphNode>() nextNode = {nextVertices.dequeue()} visitEventually = {nextVertices.enqueue($0)} } return vertexGenerator(sourceNode, nextNode: nextNode, visitEventually: visitEventually) } return anyGenerator(EmptyGenerator()) } // MARK: Adding and Removing Elements // Gets, sets, or deletes an edge between vertices. // The vertices are inserted if they don´t exist in the graph, except when removing. public subscript(source: Vertex, destination: Vertex) -> Edge? { get { return edgeFrom(source, to: destination) } set { if let newValue = newValue { insertEdge(newValue, from: source, to: destination) } else { removeEdgeFrom(source, to: destination) } } } /// Inserts the given vertex to the graph if it doesn't exist. public mutating func insertVertex(vertex: Vertex) { if !containsVertex(vertex) { copyMyself() nodes[vertex] = GraphNode(vertex) } } /// Removes and returns the given vertex from the graph if it was present. public mutating func removeVertex(vertex : Vertex) -> Vertex? { if containsVertex(vertex) { copyMyself() let value = nodes.removeValueForKey(vertex)?.data for other in nodes.keys { removeEdgeFrom(other, to: vertex) } return value } return nil } /// Connects two vertices with the given edge. If an edge already exists, it is replaced. /// Subscript notation is preferred. public mutating func insertEdge(edge: Edge, from source: Vertex, to destination: Vertex) { if source == destination { fatalError("Simple graphs can't have edges connected at both ends to the same vertex.") } copyMyself() insertVertex(source) insertVertex(destination) removeEdgeFrom(source, to: destination) nodes[source]?.connectTo(nodes[destination]!, withEdge: edge) } /// Removes and returns the edge connecting the given vertices if it exists. public mutating func removeEdgeFrom(source: Vertex, to destination: Vertex) -> Edge? { if containsVertex(source) && containsVertex(destination) { copyMyself() return nodes[source]!.removeConnectionTo(nodes[destination]!) } return nil } /// Removes all vertices and edges from the graph, and by default /// clears the underlying storage buffer. public mutating func removeAll(keepCapacity keep: Bool = true) { nodes.removeAll(keepCapacity: keep) } // MARK: Private Properties and Helper Methods /// Adjacency lists graph representation. private var nodes = [Vertex: GraphNode]() /// Unique identifier to perform copy-on-write. private var tag = Tag() /// Finds a path from `source` to `destination` recursively. private func containsPathFrom(source: GraphNode, to destination: GraphNode, inout visited: Set<GraphNode> , inout path: [Vertex]) -> Bool { if visited.contains(source) { return false } visited.insert(source) path.append(source.data) if source == destination { return true } for vertex in source.successors { if containsPathFrom(vertex, to: destination, visited: &visited, path: &path) { return true } } path.removeLast() return false } /// Returns a generator over the vertices starting at the given node. /// The generator never returns the same vertex twice. /// Using nextVertex and visitEventually allows you to specify the order of traversal. /// /// - parameter source: The first node to visit. /// - parameter nextNode: Returns the next node to visit. /// - parameter visitEventually: Gives a neighbor of the vertex previously returned by nextNode(). private func vertexGenerator(source: GraphNode, nextNode:() -> GraphNode?, visitEventually: (GraphNode)->Void) -> AnyGenerator<Vertex> { var visited = Set<GraphNode>() visitEventually(source) return anyGenerator { if let next = nextNode() { visited.insert(next) for successor in next.successors { if !visited.contains(successor) { visitEventually(successor) } } return next.data } return nil } } /// Creates a new copy of the nodes in the graph if there´s /// more than one strong reference pointing the graph's tag. /// /// The Graph itself is a value type but a VertexNode is a reference type, /// calling this method ensures copy-on-write behavior. private mutating func copyMyself() { if !isUniquelyReferencedNonObjC(&tag) { tag = Tag() var newNodes = [Vertex: GraphNode]() for vertex in nodes.keys { newNodes[vertex] = GraphNode(vertex) } for (vertex, oldNode) in nodes { let newNode = newNodes[vertex]! let edges = oldNode.edges let successors = oldNode.successors.map{newNodes[$0.data]!} for (index, successor) in successors.enumerate() { newNode.connectTo(successor, withEdge: edges[index]) } } nodes = newNodes } } } extension Graph: SequenceType { // MARK: SequenceType Protocol Conformance /// Provides for-in loop functionality. /// /// - returns: A generator over the vertices. public func generate() -> AnyGenerator<Vertex> { return anyGenerator(nodes.keys.generate()) } } // MARK: - Operators // MARK: Graph Operators /// Returns `true` if and only if the graphs contain the same vertices and edges per vertex. /// The underlying edges must conform to the `Equatable` protocol. public func ==<V, E: Equatable>(lhs: Graph<V,E>, rhs: Graph<V,E>) -> Bool { if lhs.count != rhs.count { return false } for (vertex, lNode) in lhs.nodes { if rhs.nodes[vertex] == nil { return false } let rNode = rhs.nodes[vertex]! if lNode.adjacencyList.count != rNode.adjacencyList.count { return false } let containsAllEdges = !lNode.successors.contains { rNode.edgeConnectingTo($0) != lNode.edgeConnectingTo($0) } if !containsAllEdges { return false } } return true } public func !=<V, E: Equatable>(lhs: Graph<V,E>, rhs: Graph<V,E>) -> Bool { return !(lhs == rhs) } // MARK: - GraphTraversalOrder public enum GraphTraversalOrder { case DepthFirst case BreadthFirst } // MARK: - VertexNode private class VertexNode<V: Hashable, E>: Hashable { typealias Bridge = (destination: VertexNode<V,E>, edge: E) let data : V var adjacencyList = [Bridge]() var successors: LazyCollection<[VertexNode<V, E>]> { return LazyCollection(LazyCollection(adjacencyList).map{$0.destination}) } var edges: LazyCollection<[E]> { return LazyCollection(LazyCollection(adjacencyList).map{$0.edge}) } var hashValue: Int { return data.hashValue } init(_ vertex: V) { self.data = vertex } func connectTo(vertex: VertexNode, withEdge edge: E) { adjacencyList.append((vertex, edge)) } func edgeConnectingTo(vertex: VertexNode) -> E? { for neighbor in adjacencyList { if neighbor.destination == vertex { return neighbor.edge } } return nil } func removeConnectionTo(vertex: VertexNode) -> E? { for (index, neighbor) in adjacencyList.enumerate() { if neighbor.destination == vertex { return adjacencyList.removeAtIndex(index).edge } } return nil } } private func ==<V, E>(lhs: VertexNode<V, E>, rhs: VertexNode<V, E>) -> Bool { return lhs.data == rhs.data } // MARK: - Tag private class Tag {}
3514bc7a505c950ebed9497328bb65ed
32.576142
143
0.593469
false
false
false
false
BOTDOTME/AZExpandableIconListView
refs/heads/master
Pod/Classes/AZExpandableIconListView.swift
mit
1
// // AZExpandableIconListView.swift // Pods // // Created by Chris Wu on 01/28/2016. // Copyright (c) 2016 Chris Wu. All rights reserved. // import Foundation open class AZExpandableIconListView: UIView { fileprivate var icons: [(UILabel, UIImageView)] = [] fileprivate var scrollView: UIScrollView fileprivate var contentView: UIView fileprivate var isSetupFinished: Bool = false open var isExpanded: Bool = false fileprivate var middleItemSpacingConstraint: NSLayoutConstraint? fileprivate var rightMiddleItemSpacingConstraint: NSLayoutConstraint? fileprivate var leftMiddleItemSpacingConstraint: NSLayoutConstraint? fileprivate var rightItemSpacingConstraints: [NSLayoutConstraint] = [] fileprivate var leftItemSpacingConstraints: [NSLayoutConstraint] = [] open var imageSpacing: CGFloat = 4.0 open var onExpanded: (()->())? open var onCollapsed:(()->())? /// Image width is set to be always 80% of container view's frame width fileprivate var imageWidth: CGFloat { return scrollView.frame.height * 0.6 } fileprivate var halfImageWidth: CGFloat { return imageWidth * 0.5 } fileprivate var stretchedImageWidth: CGFloat { return (CGFloat(icons.count) * imageWidth) + (CGFloat(icons.count) * imageSpacing) } fileprivate var contractedImageWidth: CGFloat { return imageWidth + 0.20*CGFloat(icons.count - 1)*imageWidth } fileprivate var realContractedCenterOffset: CGFloat { return contractedImageWidth/2.0 - (imageWidth + 0.20*9.0*imageWidth)/2.0 } fileprivate var needsToAdjust: Bool { return icons.count > 10 ? true : false } /** Initializer - parameter frame: The frame - parameter images: An array of images that are going to be displayed - returns: an AZExpandableIconListView */ ///////////////////////////////////////////////////////////////////////////// public init(frame: CGRect, views: [(UILabel, UIImageView)], imageSpacing: CGFloat) { let bounds = CGRect(x: 0, y: 0, width: frame.width, height: frame.height) scrollView = UIScrollView(frame: bounds) scrollView.isScrollEnabled = true scrollView.bounces = false scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.translatesAutoresizingMaskIntoConstraints = false contentView = UIView(frame: bounds) super.init(frame: bounds) self.imageSpacing = imageSpacing self.clipsToBounds = true let onTapView = UITapGestureRecognizer(target: self, action: #selector(AZExpandableIconListView.adjustView)) onTapView.numberOfTapsRequired = 2 scrollView.addGestureRecognizer(onTapView) var tag = views.count - 1 // Add the participantViews // Reverse the array of incoming participants so that the User is the last one added (is on top) for (label, image) in views.reversed() { image.frame = CGRect(x: 0, y: 0, width: imageWidth*0.5, height: imageWidth*0.5) image.tag = tag if tag > 9 { image.alpha = 0.0 } // if there are more than 10 participants, make the 11th - Nth participant invisible for now self.icons.append((label, image)) contentView.addSubview(image) tag -= 1 } // Reverse again so that constraints match in the future self.icons = self.icons.reversed() self.addSubview(scrollView) scrollView.addSubview(contentView) // constraints for scrollView and contentView self.addConstraint(NSLayoutConstraint(item: scrollView, attribute: NSLayoutAttribute.centerY, relatedBy: .equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: scrollView, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: 0)) scrollView.addConstraint(NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.centerY, relatedBy: .equal, toItem: scrollView, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)) updateConstraints() updateContentSize() } ///////////////////////////////////////////////////////////////////////////// public func adjustView(){ updateSpacingConstraints() isExpanded = !isExpanded displayNames() updateContentSize() UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.3, options: UIViewAnimationOptions(), animations: { [weak self] in self?.layoutIfNeeded() }, completion: { [weak self] finished in if let weakself = self { if weakself.isExpanded { weakself.onExpanded?() } else { weakself.onCollapsed?() } } }) } ///////////////////////////////////////////////////////////////////////////// public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } ///////////////////////////////////////////////////////////////////////////// open override func updateConstraints() { super.updateConstraints() if isSetupFinished == false { setupInitialLayout() } } ///////////////////////////////////////////////////////////////////////////// fileprivate func setupInitialLayout() { var layoutConstraints:[NSLayoutConstraint] = [] let hasMiddle = icons.count % 2 == 0 ? false : true let middleIndex = hasMiddle ? ((icons.count - 1) / 2) : (icons.count / 2) let avatarYoffset = -(self.frame.height / 8) var previousRightView = icons[middleIndex].1 var previousLeftView = hasMiddle ? icons[middleIndex].1 : icons[middleIndex - 1].1 // Add constraints for middle Avatar(s) if hasMiddle { let middleView = icons[middleIndex].1 layoutConstraints.append(NSLayoutConstraint(item: middleView, attribute: NSLayoutAttribute.centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: avatarYoffset)) layoutConstraints.append(NSLayoutConstraint(item: middleView, attribute: .width, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0)) layoutConstraints.append(NSLayoutConstraint(item: middleView, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0)) self.middleItemSpacingConstraint = NSLayoutConstraint(item: middleView, attribute: NSLayoutAttribute.centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1, constant: needsToAdjust ? realContractedCenterOffset : 1) layoutConstraints.append(self.middleItemSpacingConstraint!) } else { let middleRightView = icons[middleIndex].1 let middleLeftView = icons[middleIndex - 1].1 layoutConstraints.append(NSLayoutConstraint(item: middleRightView, attribute: NSLayoutAttribute.centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: avatarYoffset)) layoutConstraints.append(NSLayoutConstraint(item: middleRightView, attribute: .width, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0)) layoutConstraints.append(NSLayoutConstraint(item: middleRightView, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0)) self.rightMiddleItemSpacingConstraint = NSLayoutConstraint(item: middleRightView, attribute: NSLayoutAttribute.centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1, constant: needsToAdjust ? realContractedCenterOffset + (imageWidth / 10) : imageWidth / 10) layoutConstraints.append(NSLayoutConstraint(item: middleLeftView, attribute: NSLayoutAttribute.centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: avatarYoffset)) layoutConstraints.append(NSLayoutConstraint(item: middleLeftView, attribute: .width, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0)) layoutConstraints.append(NSLayoutConstraint(item: middleLeftView, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0)) self.leftMiddleItemSpacingConstraint = NSLayoutConstraint(item: middleLeftView, attribute: NSLayoutAttribute.centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1, constant: needsToAdjust ? realContractedCenterOffset - (imageWidth / 10) : -(imageWidth / 10)) layoutConstraints.append(self.rightMiddleItemSpacingConstraint!) layoutConstraints.append(self.leftMiddleItemSpacingConstraint!) } // Add constraints iteratively for the non-middle Avatars for index in (middleIndex + 1) ..< icons.count { let distanceFromCenter = index - middleIndex let rightView = icons[index].1 let leftView = hasMiddle ? icons[middleIndex - distanceFromCenter].1 : icons[(middleIndex - 1) - distanceFromCenter].1 // Proportion constraints layoutConstraints.append(NSLayoutConstraint(item: rightView, attribute: NSLayoutAttribute.centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: avatarYoffset)) layoutConstraints.append(NSLayoutConstraint(item: rightView, attribute: .width, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0)) layoutConstraints.append(NSLayoutConstraint(item: rightView, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0)) layoutConstraints.append(NSLayoutConstraint(item: leftView, attribute: NSLayoutAttribute.centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: avatarYoffset)) layoutConstraints.append(NSLayoutConstraint(item: leftView, attribute: .width, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0)) layoutConstraints.append(NSLayoutConstraint(item: leftView, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0)) // Spacing constraints self.rightItemSpacingConstraints.append(NSLayoutConstraint(item: rightView, attribute: .left, relatedBy: .equal, toItem: previousRightView, attribute: .right, multiplier: 1, constant: -imageWidth*0.8)) self.leftItemSpacingConstraints.append(NSLayoutConstraint(item: leftView, attribute: .right, relatedBy: .equal, toItem: previousLeftView, attribute: .left, multiplier: 1, constant: imageWidth*0.8)) previousRightView = rightView previousLeftView = leftView } layoutConstraints.append(contentsOf: rightItemSpacingConstraints) layoutConstraints.append(contentsOf: leftItemSpacingConstraints) contentView.addConstraints(layoutConstraints) isSetupFinished = true } ///////////////////////////////////////////////////////////////////////////// fileprivate func displayNames() { if (isExpanded) { var layoutConstraints: [NSLayoutConstraint] = [] for icon in self.icons { let label = icon.0 let image = icon.1 image.addSubview(label) layoutConstraints.append(NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.centerX, relatedBy: .equal, toItem: image, attribute: .centerX, multiplier: 1, constant: 0)) layoutConstraints.append(NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.centerY, relatedBy: .equal, toItem: image, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: imageWidth*0.75)) layoutConstraints.append(NSLayoutConstraint(item: label, attribute: .width, relatedBy: .equal, toItem: image, attribute: .width, multiplier: 1.50, constant: 1)) layoutConstraints.append(NSLayoutConstraint(item: label, attribute: .height, relatedBy: .equal, toItem: image, attribute: .height, multiplier: 0.25, constant: 1)) image.addConstraints(layoutConstraints) layoutConstraints = [] } } else { for icon in self.icons { icon.0.removeFromSuperview() } } } /** Update the contraints of image spacing based on whether the images are expanded or not. Update content size of the containing UIScrollView. */ ///////////////////////////////////////////////////////////////////////////// fileprivate func updateSpacingConstraints() { // Spacing constraints for expanding if !isExpanded { let width = stretchedImageWidth < scrollView.frame.width ? scrollView.frame.width : stretchedImageWidth contentView.frame = CGRect(x: scrollView.frame.origin.x, y: scrollView.frame.origin.y, width: width, height: scrollView.frame.height) scrollView.contentSize = CGSize(width: contentView.frame.width, height: scrollView.frame.height) if let midConstraint = self.middleItemSpacingConstraint { if needsToAdjust { midConstraint.constant = 1 } } for constraint in rightItemSpacingConstraints { constraint.constant = imageSpacing } for constraint in leftItemSpacingConstraints { constraint.constant = -imageSpacing } if let midRightConstraint = self.rightMiddleItemSpacingConstraint, let midLeftConstraint = self.leftMiddleItemSpacingConstraint { midRightConstraint.constant = (0.1 * imageWidth) + imageSpacing midLeftConstraint.constant = -((0.1 * imageWidth) + imageSpacing) } } // Spacing constraints for contracting else { contentView.frame = CGRect(x: scrollView.frame.origin.x, y: scrollView.frame.origin.y, width: scrollView.frame.width, height: scrollView.frame.height) scrollView.contentSize = CGSize(width: contentView.frame.width, height: scrollView.frame.height) if let midConstraint = self.middleItemSpacingConstraint { if needsToAdjust { midConstraint.constant = realContractedCenterOffset } } for constraint in rightItemSpacingConstraints { constraint.constant = -imageWidth*0.8 } for constraint in leftItemSpacingConstraints { constraint.constant = imageWidth*0.8 } if let midRightConstraint = self.rightMiddleItemSpacingConstraint, let midLeftConstraint = self.leftMiddleItemSpacingConstraint { midRightConstraint.constant = needsToAdjust ? realContractedCenterOffset + (imageWidth / 10) : imageWidth / 10 midLeftConstraint.constant = needsToAdjust ? realContractedCenterOffset - (imageWidth / 10) : -(imageWidth / 10) } } // Make participants visible / invisible appropriately for (_, image) in self.icons { if image.tag > 9 { image.alpha = isExpanded ? 0.0 : 1.0 } } } /** Update the content size of the containing UIScrollView based on whether the images are expanded or not. */ ///////////////////////////////////////////////////////////////////////////// fileprivate func updateContentSize() { let width = isExpanded ? stretchedImageWidth : contractedImageWidth scrollView.contentSize = CGSize(width: width, height: scrollView.frame.height) } /** Convert the passed in UIImage to a round UIImageView, plus add a white border around it. - parameter image: The icon - parameter frame: The container's frame of the image - returns: A circular UIImageView */ ///////////////////////////////////////////////////////////////////////////// fileprivate func buildCircularIconFrom(_ image:UIImage, containerFrame frame:CGRect) -> UIImageView { let newframe = CGRect(x: 0, y: 0, width: imageWidth, height: imageWidth) let imageView = UIImageView(frame:newframe) imageView.image = image let borderLayer = CALayer() let borderFrame = CGRect(x: -1, y: -1, width: newframe.width + 2, height: newframe.height + 2) borderLayer.backgroundColor = UIColor.clear.cgColor borderLayer.frame = borderFrame borderLayer.cornerRadius = newframe.width * 0.5 borderLayer.borderWidth = 2.0 borderLayer.borderColor = UIColor.clear.cgColor borderLayer.masksToBounds = false imageView.layer.addSublayer(borderLayer) imageView.clipsToBounds = false imageView.layer.cornerRadius = newframe.width * 0.5 return imageView } }
c62ce7b2d7af484818c57a92014a3017
54.835962
300
0.641243
false
false
false
false
DianQK/LearnRxSwift
refs/heads/master
LearnRxSwift/Rx.playground/Pages/Transforming.xcplaygroundpage/Contents.swift
mit
1
//: [上一节](@previous) - [目录](Index) import RxSwift /*: ## 变换 Observables 下面的这些操作符可以变换一个序列发射的值。这样我们的序列功能就强大了许多,创建,然后进行变换。甚至这里就类似于一条生产线。先做出一个原型,然后再进行各种加工,最后出我们想要的成品。 */ /*: ### `map` map 就是用你指定的方法去**变换每一个值**,这里非常类似 Swift 中的 map ,特别是对 SequenceType 的操作,几乎就是一个道理。一个一个的改变里面的值,并返回一个新的 functor 。 ![map](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/map.png) */ let disposeBag = DisposeBag() let originalSequence = Observable.of(1, 2, 3) originalSequence .map { number in number * 2 } .subscribe { print($0) } .addDisposableTo(disposeBag) /*: #### `mapWithIndex` 这是一个和 map 一起的操作,唯一的不同就是我们有了 **index** ,注意第一个是序列发射的值,第二个是 index 。 */ originalSequence .mapWithIndex { number, index in number * index } .subscribe { print($0) } .addDisposableTo(disposeBag) /*: ### `flatMap` 将一个序列发射的值**转换成序列**,然后将他们压平到一个序列。这也类似于 SequenceType 中的 `flatMap` 。 ![flatMap](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/flatmap.png) 我们来看这个有趣的例子: */ let sequenceInt = Observable.of(1, 2, 3) let sequenceString = Observable.of("A", "B", "C", "D", "E", "F", "--") sequenceInt .flatMap { (x:Int) -> Observable<String> in print("from sequenceInt \(x)") return sequenceString } .subscribe { print($0) } .addDisposableTo(disposeBag) /*: 可以看到每当 `sequenceInt` 发射一个值,最终订阅者都会依次收到 `A` `B` `C` `D` `E` `F` `--` ,但不会收到 Complete 。也就是说我们将三次转换的三个序列都压在了一起。只是这里的变换是每当发射一个整数,就发射一系列的字母和符号 `--` 。这很有意思,比简单的 map 强大很多。当你遇到数据异步变换或者更复杂的变换,记得尝试 `flatMap` 。比如像这样: Observable.of(1, 2, 4) .flatMap { fetch($0) } .subscribe { print($0) } .addDisposableTo(disposeBag) */ /*: #### `flatMapFirst` 将一个序列发射的值**转换成序列**,然后将他们压平到一个序列。这也类似于 SequenceType 中的 `flatMap` 。 ![flatMap](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/flatmap.png) */ /*: #### `flatMapLatest` 将一个序列发射的值**转换成序列**,然后将他们压平到一个序列。这也类似于 SequenceType 中的 `flatMap` 。 ![flatMap](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/flatmap.png) */ /*: #### `flatMapIndex` 将一个序列发射的值**转换成序列**,然后将他们压平到一个序列。这也类似于 SequenceType 中的 `flatMap` 。 ![flatMap](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/flatmap.png) */ /*: ### `scan` 应用一个 accumulator (累加) 的方法遍历一个序列,然后**返回累加的结果**。此外我们还需要一个初始的累加值。实时上这个操作就类似于 Swift 中的 `reduce` 。 ![scan](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/scan.png) */ let sequenceToSum = Observable.of(0, 1, 2, 3, 4, 5) sequenceToSum .scan(0) { acum, elem in acum + elem } .subscribe { print($0) }.addDisposableTo(disposeBag) /*: 图片就对应了这段代码的意思,每接收到一个值,就和上一次的累加值加起来并发射。这是一个很有趣的功能,你可以参见一下官方的计算器 Demo ,很有意思。记得,这里的 `scan` 以及 `reduce` 可不仅仅是只能用来累加,这是一个遍历所有值得过程,所以你可以在这做任何你想做的操作。 */ /*: ### `reduce` 和 `scan` 非常相似,唯一的不同是, `reduce` 会在序列结束时才发射最终的累加值。就是说,最终**只发射一个最终累加值** */ sequenceToSum .reduce(0) { acum, elem in acum + elem } .subscribe { print($0) }.addDisposableTo(disposeBag) /*: ### `buffer` 在特定的线程,定期定量收集序列发射的值,然后发射这些的值的集合。 ![buffer](http://reactivex.io/documentation/operators/images/Buffer.png) */ sequenceToSum .buffer(timeSpan: 5, count: 2, scheduler: MainScheduler.instance) .subscribe { print($0) }.addDisposableTo(disposeBag) /*: ### `window` window 和 buffer 非常类似。唯一的不同就是 window 发射的是序列, buffer 发射一系列值。 ![window](http://reactivex.io/documentation/operators/images/window.C.png) 我想这里对比 buffer 的图解就很好理解 window 的行为了。 我们可以看 API 的不同: /// buffer public func buffer(timeSpan timeSpan: RxSwift.RxTimeInterval, count: Int, scheduler: SchedulerType) -> RxSwift.Observable<[Self.E]> /// window public func window(timeSpan timeSpan: RxSwift.RxTimeInterval, count: Int, scheduler: SchedulerType) -> RxSwift.Observable<RxSwift.Observable<Self.E>> 从返回结果可以看到 `buffer` 返回的序列发射的值是 `[Self.E]` ,而 `window` 是 `RxSwift.Observable<Self.E>` 。 */ sequenceToSum .window(timeSpan: 5, count: 2, scheduler: MainScheduler.instance) .subscribe { print($0) }.addDisposableTo(disposeBag) //: [目录](@Index) - [下一节 >>](@next)
33b1155ede832f3b4834be65c1c8e718
22.27933
205
0.695224
false
false
false
false
LYM-mg/DemoTest
refs/heads/master
其他功能/SwiftyDemo/SwiftyDemo/Network/Tool + 普通封装/NetWorkTools+Extension.swift
mit
1
// // NetWorkTools+Extension.swift // SwiftyDemo // // Created by newunion on 2019/4/15. // Copyright © 2019 firestonetmt. All rights reserved. // 网络状态判断 import UIKit import Alamofire // MARK: - // MARK: - 判断网络类型 //(与官方风格一致,推荐使用) enum NetworkStatus { case noNetWork // 没有网络 case viaWWAN case viaWWAN2g // 2G case viaWWAN3g // 3G case viaWWAN4g // 4G case wifi // WIFI case other } extension NetWorkTools { /// 获取网络状态 class func getNetworkStates() -> NetworkStatus? { guard let object1 = UIApplication.shared.value(forKey: "statusBar") as? NSObject else { return nil } guard let object2 = object1.value(forKey: "foregroundView") as? UIView else { return nil } let subviews = object2.subviews var status = NetworkStatus.noNetWork for child in subviews { if child.isKind(of: NSClassFromString("UIStatusBarDataNetworkItemView")!) { // 获取到状态栏码 guard let networkType = child.value(forKey: "dataNetworkType") as? Int else { return nil } switch (networkType) { case 0: // 无网模式 status = NetworkStatus.noNetWork; case 1: // 2G模式 status = NetworkStatus.viaWWAN2g; case 2: // 3G模式 status = NetworkStatus.viaWWAN3g; case 3: // 4G模式 status = NetworkStatus.viaWWAN4g; case 5: // WIFI模式 status = NetworkStatus.wifi; default: break } } } // 返回网络类型 return status; } // MARK: - global function ///Alamofire监控网络,只能调用一次监听一次 func AlamofiremonitorNet(result: @escaping (NetworkStatus) -> Void) { let manager = NetworkReachabilityManager(host: "www.apple.com") manager?.listener = { status in print("网络状态: \(status)") if status == .reachable(.ethernetOrWiFi) { //WIFI result(.wifi) } else if status == .reachable(.wwan) { // 蜂窝网络 result(.viaWWAN) } else if status == .notReachable { // 无网络 result(.noNetWork) } else { // 其他 result(.other) } } manager?.startListening()//开始监听网络 } //Alamofire监控网络,只能调用一次监听一次 func NetWorkIsReachable() -> Bool { let manager = NetworkReachabilityManager(host: "www.apple.com") manager?.startListening()//开始监听网络 return manager?.isReachable ?? false; } }
4f84de87ce5819155924ff6d66dc1be7
30.309524
108
0.546008
false
false
false
false
DrGo/LearningSwift
refs/heads/master
PLAYGROUNDS/LSB_D003_NamedParameters.playground/section-2.swift
gpl-3.0
2
import UIKit /* // Named Parameters // // Based on: // https://skillsmatter.com/skillscasts/6142-swift-beauty-by-default /===================================*/ /*------------------------------------/ // Functions: Unnamed // // Looks like C /------------------------------------*/ func add(x: Int, y: Int) -> Int { return x + y } add(1, 2) /*------------------------------------/ // Methods: First is Unnamed, // Rest Named // // Because of Objective-C /------------------------------------*/ class Adder { class func addX(x:Int, y:Int) -> Int { return x + y } func addX(x: Int, y:Int) -> Int { return x + y } } Adder.addX(1, y: 2) Adder().addX(1, y: 2) /*------------------------------------/ // Initializer: Named // // Because of Objective-C /------------------------------------*/ class Rect { var x, y, width, height: Double init(x: Double, y: Double, width: Double, height: Double) { self.x = x self.y = y self.width = width self.height = height } } Rect(x: 0, y: 0, width: 100, height: 100) /*-----------------------------------------/ // Parameters with default value: Named // // Makes optional parameter clearer /-----------------------------------------*/ func greeting(name: String, yell: Bool = false) -> String { let greet = "Hello, \(name)" return yell ? greet.uppercaseString : greet } greeting("Jim") greeting("Jim", yell: true)
97fccfc199d23b6aa6f685d01fcc503a
18.066667
69
0.45035
false
false
false
false
wilfreddekok/Antidote
refs/heads/master
Antidote/HelperFunctions.swift
mpl-2.0
1
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. import Foundation func isAddressString(string: String) -> Bool { let nsstring = string as NSString if nsstring.length != Int(kOCTToxAddressLength) { return false } let validChars = NSCharacterSet(charactersInString: "1234567890abcdefABCDEF") let components = nsstring.componentsSeparatedByCharactersInSet(validChars) let leftChars = components.joinWithSeparator("") return leftChars.isEmpty }
68e8aca131aab1cb9c532c54727c6229
32.473684
81
0.735849
false
false
false
false
yakaolife/TrackLocations
refs/heads/master
Example/TrackLocations/ViewController.swift
mit
1
// // ViewController.swift // TrackLocations // // Created by yakaolife@gmail.com on 07/17/2017. // Copyright (c) 2017 yakaolife@gmail.com. All rights reserved. // import UIKit import TrackLocations class ViewController: UIViewController { var locations : [Location]? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //Any call to Tracker will trigger asking user for location service permission //Set up the callbacks, depend on applications Tracker.enterRegionCallback = enterLocation(_:) Tracker.trackRegionErrorCallback = onErrorTracking(_:_:) print("Download a list of locations") Tracker.load(requestURL: "https://mylocations-cc913.firebaseio.com/testing.json") { (success, locations, error) in print("Success: \(success)") self.locations = locations } } func enterLocation(_ location: Location){ print("Enter \(location.name)!") if UIApplication.shared.applicationState != .active{ //create notification let note = UILocalNotification() note.alertBody = "Entering \(location.name)" UIApplication.shared.presentLocalNotificationNow(note) } } func onErrorTracking(_ location: Location?,_ error: Error){ var name = "Unknown location" if let location = location{ name = location.name } print("Tracking \(name) results in error: \(error)") } @IBAction func trackLocations(_ sender: UIButton) { for loc in self.locations!{ print(loc) let result = Tracker.track(location: loc) switch(result){ case TrackLocationsError.NoError: print("Successfully add \(loc.name) to track") default: print("Error: \(result)") } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
9a47d6d110042302eedf487cb13a1fe7
28.813333
122
0.586315
false
false
false
false
2briancox/ioscreator
refs/heads/master
IOS8SwiftScreenEdgePanGesturesTutorial/IOS8SwiftScreenEdgePanGesturesTutorial/ViewController.swift
mit
40
// // ViewController.swift // IOS8SwiftScreenEdgePanGesturesTutorial // // Created by Arthur Knopper on 13/01/15. // Copyright (c) 2015 Arthur Knopper. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var imageView: UIImageView! var screenEdgeRecognizer: UIScreenEdgePanGestureRecognizer! var currentRadius:CGFloat = 0.0 func rotateBall(sender: UIScreenEdgePanGestureRecognizer) { if sender.state == .Ended { if self.currentRadius==360.0 { self.currentRadius=0.0 } UIView.animateWithDuration(1.0, animations: { self.currentRadius += 90.0 self.imageView.transform = CGAffineTransformMakeRotation((self.currentRadius * CGFloat(M_PI)) / 180.0) }) } } override func viewDidLoad() { super.viewDidLoad() screenEdgeRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: "rotateBall:") screenEdgeRecognizer.edges = .Left view.addGestureRecognizer(screenEdgeRecognizer) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
9686ada2f9571b6c115def8d877915c2
25.704545
110
0.707234
false
false
false
false
steelwheels/KiwiComponents
refs/heads/master
Source/Compiler/KMLinkEdgePass.swift
lgpl-2.1
1
/** * @file KMLinkEdgePass.swift * @brief Define KMLinkEdgePass class * @par Copyright * Copyright (C) 2017 Steel Wheels Project */ import KiwiControls import KiwiEngine import Canary import JavaScriptCore import Foundation public class KMLinkEdgePass: KMPass { public func linkEdge(rootView root: KMStackView) -> Bool { linkEdge(component: root) return errors.count == 0 } private func linkEdge(component comp: KMComponentProtocol) { /* Check self notations */ for notation in comp.notations { switch notation.value { case .PrimitiveValue(_), .ClassValue(_, _), .EventMethodValue(_, _), .ConnectionValue(_, _): break // Nothing have to do case .ListenerMethodValue(let type, let exps, _): let property = notation.identifier linkEdge(component: comp, property: property, type: type, pathExpressions: exps) } } /* Check sub components */ if let container = comp as? KMContainerProtocol { for subcomp in container.subComponents { linkEdge(component: subcomp) } } } private func linkEdge(component comp: KMComponentProtocol, property prop: String, type valtype: CNValueType, pathExpressions pathexps: Array<CNPathExpression>) { let dstptr = KMPointer(component: comp, propertyName: prop) for exp in pathexps { let (err0, ptr0) = KMPointer.make(component: comp, expression: exp) switch err0 { case .NoError: linkEdges(fromPointer: ptr0!, toPointer: dstptr, type: valtype, pathExpression: exp) default: addError(error: err0) } } } private func linkEdges(fromPointer fromptr: KMPointer, toPointer toptr: KMPointer, type typ: CNValueType, pathExpression exp: CNPathExpression) { if checkExistentLink(fromPointer: fromptr, toPointer: toptr, pathExpression: exp) { return } /* Allocate listener */ let fromdesc = fromptr.description let todesc = toptr.description console.print(string: "/* Add trigger edge: from \(fromdesc) to \(todesc) */\n") let fromtable = fromptr.pointedPropertyTable let fromname = fromptr.propertyName let totable = toptr.pointedPropertyTable let toname = toptr.propertyName //let totrigger = totable.get(toname + "_callback") //let tocomp = toptr.component fromtable.addListener(property: fromname, listener: { (Any) -> Void in totable.set(toname + "_trigger", JSValue(bool: true, in: self.context)) }) } private func checkExistentLink(fromPointer fromptr: KMPointer, toPointer toptr: KMPointer, pathExpression exp: CNPathExpression) -> Bool { let fromnode = fromptr.pointedNode let tonode = toptr.pointedNode let (isconnected, nodes) = CNGraph.isConnected(from: tonode, to: fromnode) if isconnected { let err = KMError.LoopDetectError(path: exp, nodes: nodes) addError(error: err) return true } else { /* Update graph by linking edge */ let newedge = graph.allocateEdge() CNGraph.link(from: fromnode, to: tonode, by: newedge) return false } } }
6c8a8d103bca8746750641d5d0a2cbf6
29.474227
160
0.716847
false
false
false
false
leotumwattana/WWC-Animations
refs/heads/master
WWC-Animations/Circle.swift
bsd-3-clause
1
// // Circle.swift // WWC-Animations // // Created by Leo Tumwattana on 27/5/15. // Copyright (c) 2015 Innovoso Ltd. All rights reserved. // import UIKit @IBDesignable class Circle: UIView { // ================== // MARK: - Properties // ================== @IBInspectable var cornerRadius:CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius clipsToBounds = cornerRadius > 0 } } var tap:UITapGestureRecognizer! var longPress:UILongPressGestureRecognizer! // ============ // MARK: - Init // ============ required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override init(frame: CGRect) { super.init(frame: frame) commonInit() } func commonInit() { tap = UITapGestureRecognizer(target: self, action: "tapped:") addGestureRecognizer(tap) longPress = UILongPressGestureRecognizer(target: self, action: "longPressed:") addGestureRecognizer(longPress) } // ====================== // MARK: - Event Handlers // ====================== func tapped(tap:UITapGestureRecognizer) { } func longPressed(longPressed:UILongPressGestureRecognizer) { } }
e52344974e4cadfed859f74ccb1ab35f
21.508475
86
0.542922
false
false
false
false
Allow2CEO/browser-ios
refs/heads/master
Client/Frontend/Widgets/SnackBar.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import SnapKit import Shared class SnackBarUX { static var MaxWidth: CGFloat = 400 } /** * A specialized version of UIButton for use in SnackBars. These are displayed evenly * spaced in the bottom of the bar. The main convenience of these is that you can pass * in a callback in the constructor (although these also style themselves appropriately). * *``SnackButton(title: "OK", { _ in print("OK", terminator: "\n") })`` */ class SnackButton : UIButton { let callback: (_ bar: SnackBar) -> Void fileprivate var bar: SnackBar! /** * An image to show as the background when a button is pressed. This is currently a 1x1 pixel blue color */ lazy var highlightImg: UIImage = { let size = CGSize(width: 1, height: 1) return UIImage.createWithColor(size, color: BraveUX.Blue.withAlphaComponent(0.2)) }() init(title: String, accessibilityIdentifier: String, callback: @escaping (_ bar: SnackBar) -> Void) { self.callback = callback super.init(frame: CGRect.zero) setTitle(title, for: .normal) titleLabel?.font = DynamicFontHelper.defaultHelper.DefaultStandardFontBold setBackgroundImage(highlightImg, for: .highlighted) setTitleColor(UIConstants.HighlightText, for: .highlighted) addTarget(self, action: #selector(SnackButton.onClick), for: .touchUpInside) self.accessibilityIdentifier = accessibilityIdentifier } override init(frame: CGRect) { self.callback = { bar in } super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func onClick() { callback(bar) } } /** * Presents some information to the user. Can optionally include some buttons and an image. Usage: * * ``let bar = SnackBar(text: "This is some text in the snackbar.", * img: UIImage(named: "bookmark"), * buttons: [ * SnackButton(title: "OK", { _ in print("OK", terminator: "\n") }), * SnackButton(title: "Cancel", { _ in print("Cancel", terminator: "\n") }), * SnackButton(title: "Maybe", { _ in print("Maybe", terminator: "\n") }) * ] * )`` */ class SnackBar: UIView { let imageView: UIImageView let textLabel: UILabel let contentView: UIView let backgroundView: UIView let buttonsView: Toolbar fileprivate var buttons = [SnackButton]() // The Constraint for the bottom of this snackbar. We use this to transition it var bottom: Constraint? convenience init(text: String, img: UIImage?, buttons: [SnackButton]?) { var attributes = [String: AnyObject]() attributes[NSFontAttributeName] = DynamicFontHelper.defaultHelper.DefaultMediumFont attributes[NSBackgroundColorAttributeName] = UIColor.clear let attrText = NSAttributedString(string: text, attributes: attributes) self.init(attrText: attrText, img: img, buttons: buttons) } init(attrText: NSAttributedString, img: UIImage?, buttons: [SnackButton]?) { imageView = UIImageView() textLabel = UILabel() contentView = UIView() buttonsView = Toolbar() backgroundView = UIView() backgroundView.backgroundColor = UIColor(rgb: 0xe8e8e8) super.init(frame: CGRect.zero) imageView.image = img textLabel.attributedText = attrText if let buttons = buttons { for button in buttons { addButton(button) } } setup() } fileprivate override init(frame: CGRect) { imageView = UIImageView() textLabel = UILabel() contentView = UIView() buttonsView = Toolbar() backgroundView = UIView() backgroundView.backgroundColor = UIColor(rgb: 0xe8e8e8) super.init(frame: frame) } fileprivate func setup() { textLabel.backgroundColor = nil addSubview(backgroundView) addSubview(contentView) contentView.addSubview(imageView) contentView.addSubview(textLabel) addSubview(buttonsView) self.backgroundColor = UIColor.clear buttonsView.drawTopBorder = true buttonsView.drawBottomBorder = false buttonsView.drawSeperators = false imageView.contentMode = UIViewContentMode.left textLabel.font = DynamicFontHelper.defaultHelper.DefaultStandardFont textLabel.textAlignment = .center textLabel.lineBreakMode = NSLineBreakMode.byWordWrapping textLabel.numberOfLines = 0 textLabel.backgroundColor = UIColor.clear } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let imageWidth: CGFloat if let img = imageView.image { imageWidth = img.size.width + UIConstants.DefaultPadding * 2 } else { imageWidth = 0 } self.textLabel.preferredMaxLayoutWidth = contentView.frame.width - (imageWidth + UIConstants.DefaultPadding) super.layoutSubviews() } /** * Called to check if the snackbar should be removed or not. By default, Snackbars persist forever. * Override this class or use a class like CountdownSnackbar if you want things expire * - returns: true if the snackbar should be kept alive */ func shouldPersist(_ browser: Browser) -> Bool { return true } override func updateConstraints() { super.updateConstraints() backgroundView.snp.remakeConstraints { make in make.bottom.left.right.equalTo(self) // Offset it by the width of the top border line so we can see the line from the super view make.top.equalTo(self).offset(1) } contentView.snp.remakeConstraints { make in make.top.left.right.equalTo(self).inset(UIEdgeInsetsMake(UIConstants.DefaultPadding, UIConstants.DefaultPadding, UIConstants.DefaultPadding, UIConstants.DefaultPadding)) } if let img = imageView.image { imageView.snp.remakeConstraints { make in make.left.centerY.equalTo(contentView) // To avoid doubling the padding, the textview doesn't have an inset on its left side. // Instead, it relies on the imageView to tell it where its left side should be. make.width.equalTo(img.size.width + UIConstants.DefaultPadding) make.height.equalTo(img.size.height + UIConstants.DefaultPadding) } } else { imageView.snp.remakeConstraints { make in make.width.height.equalTo(0) make.top.left.equalTo(self) make.bottom.lessThanOrEqualTo(contentView.snp.bottom) } } textLabel.snp.remakeConstraints { make in make.top.equalTo(contentView) make.left.equalTo(self.imageView.snp.right) make.trailing.equalTo(contentView) make.bottom.lessThanOrEqualTo(contentView.snp.bottom) } buttonsView.snp.remakeConstraints { make in make.top.equalTo(contentView.snp.bottom).offset(UIConstants.DefaultPadding) make.bottom.equalTo(self.snp.bottom) make.left.right.equalTo(self) if self.buttonsView.subviews.count > 0 { make.height.equalTo(UIConstants.SnackbarButtonHeight) } else { make.height.equalTo(0) } } } var showing: Bool { return alpha != 0 && self.superview != nil } /** * Helper for animating the Snackbar showing on screen. */ func show() { alpha = 1 bottom?.update(offset: 0) } /** * Helper for animating the Snackbar leaving the screen. */ func hide() { alpha = 0 var h = frame.height if h == 0 { h = UIConstants.ToolbarHeight } bottom?.update(offset: h) } fileprivate func addButton(_ snackButton: SnackButton) { snackButton.bar = self buttonsView.addButtons([snackButton]) buttonsView.setNeedsUpdateConstraints() } } /** * A special version of a snackbar that persists for at least a timeout. After that * it will dismiss itself on the next page load where this tab isn't showing. As long as * you stay on the current tab though, it will persist until you interact with it. */ class TimerSnackBar: SnackBar { fileprivate var prevURL: URL? = nil fileprivate var timer: Timer? = nil fileprivate var timeout: TimeInterval init(timeout: TimeInterval = 10, attrText: NSAttributedString, img: UIImage?, buttons: [SnackButton]?) { self.timeout = timeout super.init(attrText: attrText, img: img, buttons: buttons) } override init(frame: CGRect) { self.timeout = 0 super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func show() { self.timer = Timer(timeInterval: timeout, target: self, selector: #selector(TimerSnackBar.SELTimerDone), userInfo: nil, repeats: false) RunLoop.current.add(self.timer!, forMode: RunLoopMode.defaultRunLoopMode) super.show() } @objc func SELTimerDone() { self.timer = nil } override func shouldPersist(_ browser: Browser) -> Bool { if !showing { return timer != nil } return super.shouldPersist(browser) } }
aaa385c4106cca5ee984c62e46fceb2f
32.859589
181
0.639527
false
false
false
false
TonnyTao/HowSwift
refs/heads/master
Funny Swift.playground/Pages/subscript_dic.xcplaygroundpage/Contents.swift
mit
1
import Foundation extension Dictionary { subscript(input: [Key]) -> [Value] { get { var result = [Value]() result.reserveCapacity(input.count) for key in input { if let value = self[key] { result.append(value) } } return result } set { assert(input.count == newValue.count, "not supported") for (index, key) in input.enumerated() { self[key] = newValue[index] } } } } var dic = ["a": "1", "b":"2", "c": "3"] dic[["a", "c"]] dic[["a", "c"]] = ["0", "2"] print(dic)
0ae10fad1dc85da182b69cb643fa45fd
20.741935
66
0.4273
false
false
false
false
obdev/SocketWrapper
refs/heads/master
SocketWrapper/Extensions/String+UnsafeBufferPointer.swift
mit
1
// // String+UnsafeBufferPointer.swift // SocketWrapper // // Created by Christian Ludl on 2016-02-11. // Copyright © 2016 Objective Development. All rights reserved. // import Foundation extension String { /// Initializes a `String` from a sequence of `NUL`-terminated `UTF8.CodeUnit` as a `WithUnsafeBufferPointerType`. init?<T: WithUnsafeBufferPointerType where T.Element == UTF8.CodeUnit>(nulTerminatedUTF8: T) { guard let string = nulTerminatedUTF8.withUnsafeBufferPointer({ String(UTF8String: UnsafePointer($0.baseAddress))}) else { return nil } self = string } /// Initializes a `String` from a sequence of `UTF8.CodeUnit`s that conforms to `WithUnsafeBufferPointerType`. A `NUL`-terminator is not required. init?<T: WithUnsafeBufferPointerType where T.Element == UTF8.CodeUnit>(UTF8CodeUnits: T) { let string = UTF8CodeUnits.withUnsafeBufferPointer { NSString(bytes: $0.baseAddress, length: $0.count, encoding: NSUTF8StringEncoding) } if let string = string as? String { self = string } else { return nil } } /// Initializes a `String` from any sequence of `UTF8.CodeUnit`s. A `NUL`-terminator is not required. /// /// Note that this initializer may be slow because it must first convert the input sequence to an `Array`. init?<T: SequenceType where T.Generator.Element == UTF8.CodeUnit>(UTF8CodeUnitSequence: T) { self.init(UTF8CodeUnits: Array(UTF8CodeUnitSequence)) } /// Initializes a `String` from a buffer of `UTF8.CodeUnit`. A `NUL`-terminator is not required. init?(UTF8CodeUnits buffer: UnsafeBufferPointer<UTF8.CodeUnit>) { if let string = NSString(bytes: buffer.baseAddress, length: buffer.count, encoding: NSUTF8StringEncoding) { self = string as String } else { return nil } } /// Initializes a `String` from a mutable buffer of `UTF8.CodeUnit`. A `NUL`-terminator is not required. /// /// This is a convenience initializer for when a `UnsafeMutableBufferPointer` exists already. It does not modify the input. init?(UTF8CodeUnits buffer: UnsafeMutableBufferPointer<UTF8.CodeUnit>) { self.init(UTF8CodeUnits: UnsafeBufferPointer(start: buffer.baseAddress, count: buffer.count)) } /// Calls the given closure with a `UnsafeBufferPointer<UTF8.CodeUnit>` to an optionally `NUL`-terminated UTF-8 representation of the `String`. func withUTF8UnsafeBufferPointer<Result>(includeNulTerminator includeNulTerminator: Bool = true, @noescape f: UnsafeBufferPointer<UTF8.CodeUnit> throws -> Result) rethrows -> Result { return try nulTerminatedUTF8.withUnsafeBufferPointer { codeUnitBuffer in let cCharBufferCount = includeNulTerminator ? codeUnitBuffer.count : codeUnitBuffer.count - 1 let cCharBuffer = UnsafeBufferPointer<UTF8.CodeUnit>(start: UnsafePointer(codeUnitBuffer.baseAddress), count: cCharBufferCount) return try f(cCharBuffer) } } } /// A common protocol of all array-like types that implement a `withUnsafeBufferPointer()` method. protocol WithUnsafeBufferPointerType { associatedtype Element func withUnsafeBufferPointer<R>(@noescape body: (UnsafeBufferPointer<Element>) throws -> R) rethrows -> R } extension Array: WithUnsafeBufferPointerType { } extension ArraySlice: WithUnsafeBufferPointerType { } extension ContiguousArray: WithUnsafeBufferPointerType { }
a843011d68d481dbc4814a14c3f015ba
41.914634
187
0.710429
false
false
false
false
shnhrrsn/ImagePalette
refs/heads/master
src/ColorHistogram.swift
apache-2.0
1
// // ColorHistogram.swift // ImagePalette // // Original created by Google/Android // Ported to Swift/iOS by Shaun Harrison // import Foundation import UIKit /** Class which provides a histogram for RGB values. */ public struct ColorHistogram { /** An array containing all of the distinct colors in the image. */ private(set) public var colors = [Int64]() /** An array containing the frequency of a distinct colors within the image. */ private(set) public var colorCounts = [Int64]() /** Number of distinct colors in the image. */ private(set) public var numberOfColors: Int /** A new ColorHistogram instance. :param: Pixels array of image contents */ public init(pixels: [Int64]) { // Sort the pixels to enable counting below var pixels = pixels pixels.sort() // Count number of distinct colors self.numberOfColors = type(of: self).countDistinctColors(pixels) // Finally count the frequency of each color self.countFrequencies(pixels) } private static func countDistinctColors(_ pixels: [Int64]) -> Int { if pixels.count < 2 { // If we have less than 2 pixels we can stop here return pixels.count } // If we have at least 2 pixels, we have a minimum of 1 color... var colorCount = 1 var currentColor = pixels[0] // Now iterate from the second pixel to the end, counting distinct colors for pixel in pixels { // If we encounter a new color, increase the population if pixel != currentColor { currentColor = pixel colorCount += 1 } } return colorCount } private mutating func countFrequencies(_ pixels: [Int64]) { if pixels.count == 0 { return } var currentColorIndex = 0 var currentColor = pixels[0] self.colors.append(currentColor) self.colorCounts.append(1) if pixels.count == 1 { // If we only have one pixel, we can stop here return } // Now iterate from the second pixel to the end, population distinct colors for pixel in pixels { if pixel == currentColor { // We’ve hit the same color as before, increase population self.colorCounts[currentColorIndex] += 1 } else { // We’ve hit a new color, increase index currentColor = pixel currentColorIndex += 1 self.colors.append(currentColor) self.colorCounts.append(1) } } } }
7944147ce652c729239422d1330c4d81
21.300971
77
0.69003
false
false
false
false
fitpay/fitpay-ios-sdk
refs/heads/develop
FitpaySDK/Rest/RestClientCreditCard.swift
mit
1
import Foundation import Alamofire extension RestClient { // MARK: - Completion Handlers /** Completion handler - parameter result: Provides collection of credit cards, or nil if error occurs - parameter error: Provides error object, or nil if no error occurs */ public typealias CreditCardsHandler = (_ result: ResultCollection<CreditCard>?, _ error: ErrorResponse?) -> Void /** Completion handler - parameter creditCard: Provides credit card object, or nil if error occurs - parameter error: Provides error object, or nil if no error occurs */ public typealias CreditCardHandler = (_ creditCard: CreditCard?, _ error: ErrorResponse?) -> Void /** Completion handler - parameter pending: Provides pending flag, indicating that transition was accepted, but current status can be reviewed later. Note that CreditCard object is nil in this case - parameter card?: Provides updated CreditCard object, or nil if pending (Bool) flag is true or if error occurs - parameter error?: Provides error object, or nil if no error occurs */ public typealias CreditCardTransitionHandler = (_ pending: Bool, _ card: CreditCard?, _ error: ErrorResponse?) -> Void /** Completion handler - parameter pending: Provides pending flag, indicating that transition was accepted, but current status can be reviewed later. Note that VerificationMethod object is nil in this case - parameter verificationMethod: Provides VerificationMethod object, or nil if pending (Bool) flag is true or if error occurs - parameter error: Provides error object, or nil if no error occurs */ public typealias VerifyHandler = (_ pending: Bool, _ verificationMethod: VerificationMethod?, _ error: ErrorResponse?) -> Void /** Completion handler - parameter verificationMethods: Provides VerificationMethods objects, or nil if error occurs - parameter error: Provides error object, or nil if no error occurs */ public typealias VerifyMethodsHandler = (_ verificationMethods: ResultCollection<VerificationMethod>?, _ error: ErrorResponse?) -> Void /** Completion handler - parameter verificationMethod: Provides VerificationMethod object, or nil if error occurs - parameter error: Provides error object, or nil if no error occurs */ public typealias VerifyMethodHandler = (_ verificationMethod: VerificationMethod?, _ error: ErrorResponse?) -> Void // MARK: - Internal Functions func createCreditCard(_ url: String, cardInfo: CardInfo, deviceId: String?, completion: @escaping CreditCardHandler) { prepareAuthAndKeyHeaders { [weak self] (headers, error) in guard let strongSelf = self else { return } guard let headers = headers else { DispatchQueue.main.async { completion(nil, error) } return } guard let cardJSON = cardInfo.toJSONString() else { completion(nil, ErrorResponse(domain: RestClient.self, errorCode: nil, errorMessage: "Failed to parse JSON")) return } let jweObject = JWE(.A256GCMKW, enc: .A256GCM, payload: cardJSON, keyId: headers[RestClient.fpKeyIdKey]!) guard let encrypted = try? jweObject.encrypt(strongSelf.secret), let unwrappedEncrypted = encrypted else { completion(nil, ErrorResponse(domain: RestClient.self, errorCode: nil, errorMessage: "Failed to encrypt object")) return } var parameters: [String: String] = ["encryptedData": unwrappedEncrypted] if let deviceId = deviceId { parameters["deviceId"] = deviceId } self?.restRequest.makeRequest(url: url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers) { (resultValue, error) in guard let strongSelf = self else { return } guard let resultValue = resultValue else { completion(nil, error) return } let card = try? CreditCard(resultValue) card?.applySecret(strongSelf.secret, expectedKeyId: headers[RestClient.fpKeyIdKey]) card?.client = self completion(card, error) } } } func creditCards(_ url: String, excludeState: [String], limit: Int, offset: Int, deviceId: String?, completion: @escaping CreditCardsHandler) { var parameters: [String: Any] = ["excludeState": excludeState.joined(separator: ","), "limit": limit, "offset": offset] if let deviceId = deviceId { parameters["deviceId"] = deviceId } makeGetCall(url, parameters: parameters, completion: completion) } func getCreditCard(_ url: String, completion: @escaping CreditCardHandler) { makeGetCall(url, parameters: nil, completion: completion) } func updateCreditCard(_ url: String, name: String?, address: Address, completion: @escaping CreditCardHandler) { prepareAuthAndKeyHeaders { [weak self] (headers, error) in guard let strongSelf = self else { return } guard let headers = headers else { DispatchQueue.main.async { completion(nil, error) } return } var operations: [[String: String]] = [] var parameters: [String: Any] = [:] if let name = name { operations.append(["op": "replace", "path": "/name", "value": name]) } if let street1 = address.street1 { operations.append(["op": "replace", "path": "/address/street1", "value": street1]) } if let street2 = address.street2 { operations.append(["op": "replace", "path": "/address/street2", "value": street2]) } if let city = address.city { operations.append(["op": "replace", "path": "/address/city", "value": city]) } if let state = address.state { operations.append(["op": "replace", "path": "/address/state", "value": state]) } if let postalCode = address.postalCode { operations.append(["op": "replace", "path": "/address/postalCode", "value": postalCode]) } if let countryCode = address.countryCode { operations.append(["op": "replace", "path": "/address/countryCode", "value": countryCode]) } if let updateJSON = operations.JSONString { let jweObject = JWE(JWTAlgorithm.A256GCMKW, enc: JWTEncryption.A256GCM, payload: updateJSON, keyId: headers[RestClient.fpKeyIdKey]!) if let encrypted = try? jweObject.encrypt(strongSelf.secret)! { parameters["encryptedData"] = encrypted } } self?.makePatchCall(url, parameters: parameters, encoding: JSONEncoding.default, completion: completion) } } func acceptCall(_ url: String, completion: @escaping CreditCardTransitionHandler) { prepareAuthAndKeyHeaders { [weak self] (headers, error) in guard let headers = headers else { DispatchQueue.main.async { completion(false, nil, error) } return } self?.restRequest.makeRequest(url: url, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: headers) { (resultValue, error) in guard let resultValue = resultValue else { self?.handleTransitionResponse(error, completion: completion) return } let card = try? CreditCard(resultValue) card?.client = self completion(false, card, nil) } } } func selectVerificationType(_ url: String, completion: @escaping VerifyHandler) { prepareAuthAndKeyHeaders { [weak self] (headers, error) in guard let headers = headers else { DispatchQueue.main.async { completion(false, nil, error) } return } self?.restRequest.makeRequest(url: url, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: headers) { (resultValue, error) in guard let resultValue = resultValue else { self?.handleVerifyResponse(error, completion: completion) return } let verificationMethod = try? VerificationMethod(resultValue) verificationMethod?.client = self completion(false, verificationMethod, error) } } } func verify(_ url: String, verificationCode: String, completion: @escaping VerifyHandler) { prepareAuthAndKeyHeaders { [weak self] (headers, error) in guard let headers = headers else { DispatchQueue.main.async { completion(false, nil, error) } return } let params = ["verificationCode": verificationCode] self?.restRequest.makeRequest(url: url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers) { (resultValue, error) in guard let resultValue = resultValue else { self?.handleVerifyResponse(error, completion: completion) return } let verificationMethod = try? VerificationMethod(resultValue) verificationMethod?.client = self completion(false, verificationMethod, error) } } } func activationCall(_ url: String, causedBy: CreditCardInitiator, reason: String, completion: @escaping CreditCardTransitionHandler) { prepareAuthAndKeyHeaders { [weak self] (headers, error) in guard let headers = headers else { DispatchQueue.main.async { completion(false, nil, error) } return } let parameters = ["causedBy": causedBy.rawValue, "reason": reason] self?.restRequest.makeRequest(url: url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers) { (resultValue, error) in guard let resultValue = resultValue else { self?.handleTransitionResponse(error, completion: completion) return } let card = try? CreditCard(resultValue) card?.client = self completion(false, card, error) } } } func makeCreditCardDefault(_ url: String, deviceId: String?, completion: @escaping CreditCardTransitionHandler) { self.prepareAuthAndKeyHeaders { [weak self] (headers, error) in guard let headers = headers else { DispatchQueue.main.async { completion(false, nil, error) } return } let parameters: [String: Any]? = deviceId != nil ? ["deviceId": deviceId!] : nil self?.restRequest.makeRequest(url: url, method: .post, parameters: parameters, encoding: URLEncoding.queryString, headers: headers) { (resultValue, error) in guard let resultValue = resultValue else { self?.handleTransitionResponse(error, completion: completion) return } let card = try? CreditCard(resultValue) card?.client = self completion(false, card, error) } } } // MARK: - Private Functions private func handleVerifyResponse(_ response: ErrorResponse?, completion: @escaping VerifyHandler) { guard let statusCode = response?.status else { completion(false, nil, ErrorResponse.unhandledError(domain: RestClient.self)) return } switch statusCode { case 202: completion(true, nil, nil) default: completion(false, nil, response) } } private func handleTransitionResponse(_ response: ErrorResponse?, completion: @escaping CreditCardTransitionHandler) { guard let statusCode = response?.status else { completion(false, nil, ErrorResponse.unhandledError(domain: RestClient.self)) return } switch statusCode { case 202: completion(true, nil, nil) default: completion(false, nil, response) } } }
3863979d7747a66a5087e999cd552b3d
44.051724
198
0.588902
false
false
false
false
jstn/IndependentRotation
refs/heads/master
IndependentRotationWithCamera/IndependentRotationWithCamera/AppDelegate.swift
mit
1
// // AppDelegate.swift // IndependentRotationWithCamera // // Created by Justin Ouellette on 3/1/15. // Copyright (c) 2015 Justin Ouellette. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var fixedWindow: UIWindow! var rotatingWindow: UIWindow! func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { let screenBounds = UIScreen.mainScreen().bounds let inset: CGFloat = fabs(screenBounds.width - screenBounds.height) fixedWindow = UIWindow(frame: screenBounds) fixedWindow.rootViewController = FixedViewController() fixedWindow.backgroundColor = UIColor.blackColor() fixedWindow.hidden = false rotatingWindow = UIWindow(frame: CGRectInset(screenBounds, -inset, -inset)) rotatingWindow.rootViewController = RotatingViewController() rotatingWindow.backgroundColor = UIColor.clearColor() rotatingWindow.opaque = false rotatingWindow.makeKeyAndVisible() return true } }
7984b6bcb38293947bac076b3153cb7b
33.030303
128
0.724844
false
false
false
false
saraheolson/360iDevMin-PokeMongo
refs/heads/master
PokeMongo/PokeMongo/Scenes/GameScene.swift
gpl-3.0
1
// // GameScene.swift // PokeMongo // // Created by Floater on 8/21/16. // Copyright © 2016 SarahEOlson. All rights reserved. // import SpriteKit import GameplayKit class GameScene: SKScene { // So we can keep track of our monster! var monster: SKSpriteNode? // So we can keep track of our ball! var ball: SKSpriteNode? // Defines where user touched var startTouchLocation: CGPoint = CGPoint.zero var endTouchLocation: CGPoint = CGPoint.zero override func sceneDidLoad() { // If we don't already have a monster, create one. if monster == nil { createMonster() } // Add a ball to the scene if ball == nil { createBall() } } // MARK: - Monster functions func createMonster() { // Create the monster from an atlas instead of an image let textureAtlas = SKTextureAtlas(named: "PurpleMonster.atlas") let spriteArray = [textureAtlas.textureNamed("PurpleMonster1"), textureAtlas.textureNamed("PurpleMonster2")] monster = SKSpriteNode(texture: spriteArray[0]) if let monster = self.monster { monster.name = "monster" monster.position = CGPoint(x: 0, y: frame.height/2) monster.zPosition = 2 moveMonster() // Animate our monster let animateAction = SKAction.animate(with: spriteArray, timePerFrame: 0.2) let repeatAnimation = SKAction.repeatForever(animateAction) monster.run(repeatAnimation) addChild(monster) } } func moveMonster() { guard let monster = self.monster else { return } // Moves the monster to the right let moveRight = SKAction.move(to: CGPoint(x: self.size.width/2, y: self.size.height/2), duration: 1.0) // Moves the monster to the left let moveLeft = SKAction.move(to: CGPoint(x: -(self.size.width/2), y: self.size.height/2), duration: 1.0) // Groups the left and right actions together let moveSequence = SKAction.sequence([moveLeft, moveRight]) // Repeats the group of actions forever let repeatMovesForever = SKAction.repeatForever(moveSequence) // Runs the repeated group of actions monster.run(repeatMovesForever) } func monsterHit() { guard let monster = self.monster else { return } // Remove monster from scene monster.removeAllActions() monster.removeFromParent() // Explode our monster let spark: SKEmitterNode = SKEmitterNode(fileNamed: "SparkParticle")! spark.position = monster.position spark.particleColor = UIColor.purple addChild(spark) // Create a new monster self.monster = nil let waitAction = SKAction.wait(forDuration: 1) spark.run(waitAction) { // Display the monster self.createMonster() // Remove spark from scene spark.removeFromParent() } } // MARK: - Touch gesture methods /** * Called when a touch event is initiated. */ override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // Record the beginning of the touch event startTouchLocation = touches.first!.location(in: self) } /** * Called when a touch event moves. */ override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { // Move the ball along with the user's touch gesture let currentTouchLocation = touches.first!.location(in: self) if let ball = ball { ball.position = currentTouchLocation } } /** * Called when a touch event is ended. */ override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { // Record the end of the touch event endTouchLocation = touches.first!.location(in: self) // Continue the ball's movement along the same path as the touch gesture let factor: CGFloat = 50 let vector = CGVector(dx: factor * (endTouchLocation.x - startTouchLocation.x), dy: factor * (endTouchLocation.y - startTouchLocation.y)) ball?.physicsBody?.applyImpulse(vector) } /** * Called before each frame is rendered. */ override func update(_ currentTime: TimeInterval) { guard let ball = self.ball else { return } // Check to see if the ball node has left the scene bounds if (ball.position.x > self.size.width/2 + ball.size.width/2 || ball.position.x < -(self.size.width/2 + ball.size.width/2) || ball.position.y > self.size.height + ball.size.height) { // The ball is outside the bounds of the visible view resetBall() } checkCollisions() } // MARK: - Ball functions /** * Create a ball node and add it to the scene. */ func createBall() { // Create the ball node ball = SKSpriteNode(imageNamed: "Ball") if let ball = ball { ball.name = "ball" // Set position and scale ball.position = CGPoint(x: 0, y: 100) ball.zPosition = 2 ball.scale(to: CGSize(width: 50, height: 50)) // Add physics ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.size.width/2) ball.physicsBody?.isDynamic = true ball.physicsBody?.affectedByGravity = false ball.physicsBody?.allowsRotation = false ball.physicsBody?.mass = 50 // Add to the scene addChild(ball) } } /** * Reset the ball to the default position. */ func resetBall() { // Remove the current ball from the scene ball?.removeAllActions() ball?.removeFromParent() ball = nil // Reset touch locations startTouchLocation = CGPoint.zero endTouchLocation = CGPoint.zero // Create a new ball and add to the scene createBall() } // MARK: - Collision detection func checkCollisions() { guard let ball = self.ball, let monster = self.monster else { return } if ball.frame.insetBy(dx: 20, dy: 20).intersects(monster.frame) { monsterHit() } } }
7317d33dcd2f07aa59dfb45a89a328d8
28.325
145
0.543762
false
false
false
false
Ehrippura/firefox-ios
refs/heads/master
Sync/Synchronizers/Bookmarks/BookmarksSynchronizer.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Deferred import Foundation import Shared import Storage import XCGLogger private let log = Logger.syncLogger typealias UploadFunction = ([Record<BookmarkBasePayload>], _ lastTimestamp: Timestamp?, _ onUpload: @escaping (POSTResult, Timestamp?) -> DeferredTimestamp) -> DeferredTimestamp class TrivialBookmarkStorer: BookmarkStorer { let uploader: UploadFunction init(uploader: @escaping UploadFunction) { self.uploader = uploader } func applyUpstreamCompletionOp(_ op: UpstreamCompletionOp, itemSources: ItemSources, trackingTimesInto local: LocalOverrideCompletionOp) -> Deferred<Maybe<POSTResult>> { log.debug("Uploading \(op.records.count) modified records.") log.debug("Uploading \(op.amendChildrenFromBuffer.count) amended buffer records.") log.debug("Uploading \(op.amendChildrenFromMirror.count) amended mirror records.") log.debug("Uploading \(op.amendChildrenFromLocal.count) amended local records.") var records: [Record<BookmarkBasePayload>] = [] records.reserveCapacity(op.records.count + op.amendChildrenFromBuffer.count + op.amendChildrenFromLocal.count + op.amendChildrenFromMirror.count) records.append(contentsOf: op.records) func accumulateFromAmendMap(_ itemsWithNewChildren: [GUID: [GUID]], fetch: ([GUID: [GUID]]) -> Maybe<[GUID: BookmarkMirrorItem]>) throws /* MaybeErrorType */ { if itemsWithNewChildren.isEmpty { return } let fetched = fetch(itemsWithNewChildren) guard let items = fetched.successValue else { log.warning("Couldn't fetch items to amend.") throw fetched.failureValue! } items.forEach { (guid, item) in let payload = item.asPayloadWithChildren(itemsWithNewChildren[guid]) let mappedGUID = payload["id"].string ?? guid let record = Record<BookmarkBasePayload>(id: mappedGUID, payload: payload) records.append(record) } } do { try accumulateFromAmendMap(op.amendChildrenFromBuffer, fetch: { itemSources.buffer.getBufferItemsWithGUIDs($0.keys).value }) try accumulateFromAmendMap(op.amendChildrenFromMirror, fetch: { itemSources.mirror.getMirrorItemsWithGUIDs($0.keys).value }) try accumulateFromAmendMap(op.amendChildrenFromLocal, fetch: { itemSources.local.getLocalItemsWithGUIDs($0.keys).value }) } catch { return deferMaybe(error as MaybeErrorType) } var success: [GUID] = [] var failed: [GUID: String] = [:] func onUpload(_ result: POSTResult, lastModified: Timestamp?) -> DeferredTimestamp { success.append(contentsOf: result.success) result.failed.forEach { guid, message in failed[guid] = message } log.debug("Uploaded records got timestamp \(lastModified ??? "nil").") let modified = lastModified ?? 0 local.setModifiedTime(modified, guids: result.success) return deferMaybe(modified) } // Chain the last upload timestamp right into our lastFetched timestamp. // This is what Sync clients tend to do, but we can probably do better. return uploader(records, op.ifUnmodifiedSince, onUpload) // As if we uploaded everything in one go. >>> { deferMaybe(POSTResult(success: success, failed: failed)) } } } open class MalformedRecordError: MaybeErrorType, SyncPingFailureFormattable { open var description: String { return "Malformed record." } open var failureReasonName: SyncPingFailureReasonName { return .otherError } } // MARK: - External synchronizer interface. open class BufferingBookmarksSynchronizer: TimestampedSingleCollectionSynchronizer, Synchronizer { public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs, why: SyncReason) { super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, why: why, collection: "bookmarks") } override var storageVersion: Int { return BookmarksStorageVersion } fileprivate func buildMobileRootRecord(_ local: LocalItemSource, _ buffer: BufferItemSource, additionalChildren: [BookmarkMirrorItem], deletedChildren: [GUID]) -> Deferred<Maybe<Record<BookmarkBasePayload>>> { let newBookmarkGUIDs = additionalChildren.map { $0.guid } return buffer.getBufferItemWithGUID(BookmarkRoots.MobileFolderGUID).bind { maybeMobileRoot in // Update (or create!) the Mobile Root folder with its new children. if let mobileRoot = maybeMobileRoot.successValue { return buffer.getBufferChildrenGUIDsForParent(mobileRoot.guid) .map { $0.map({ (mobileRoot: mobileRoot, children: $0.filter { !deletedChildren.contains($0) } + newBookmarkGUIDs) }) } } else { return local.getLocalItemWithGUID(BookmarkRoots.MobileFolderGUID) .map { $0.map({ (mobileRoot: $0, children: newBookmarkGUIDs) }) } } } >>== { (mobileRoot: BookmarkMirrorItem, children: [GUID]) in let payload = mobileRoot.asPayloadWithChildren(children) guard let mappedGUID = payload["id"].string else { return deferMaybe(MalformedRecordError()) } return deferMaybe(Record<BookmarkBasePayload>(id: mappedGUID, payload: payload)) } } func buildMobileRootAndChildrenRecords(_ local: LocalItemSource, _ buffer: BufferItemSource, additionalChildren: [BookmarkMirrorItem], deletedChildren: [GUID]) -> Deferred<Maybe<(mobileRootRecord: Record<BookmarkBasePayload>, childrenRecords: [Record<BookmarkBasePayload>])>> { let childrenRecords = additionalChildren.map { bkm -> Record<BookmarkBasePayload> in let payload = bkm.asPayload() let mappedGUID = payload["id"].string ?? bkm.guid return Record<BookmarkBasePayload>(id: mappedGUID, payload: payload) } + deletedChildren.map { guid -> Record<BookmarkBasePayload> in let payload = BookmarkBasePayload.deletedPayload(guid) let mappedGUID = payload["id"].string ?? guid return Record<BookmarkBasePayload>(id: mappedGUID, payload: payload) } return self.buildMobileRootRecord(local, buffer, additionalChildren: additionalChildren, deletedChildren: deletedChildren) >>== { mobileRootRecord in return deferMaybe((mobileRootRecord: mobileRootRecord, childrenRecords: childrenRecords)) } } func uploadSomeLocalRecords(_ storage: SyncableBookmarks & LocalItemSource & MirrorItemSource, _ mirrorer: BookmarksMirrorer, _ bookmarksClient: Sync15CollectionClient<BookmarkBasePayload>, mobileRootRecord: Record<BookmarkBasePayload>, childrenRecords: [Record<BookmarkBasePayload>]) -> Success { var newBookmarkGUIDs: [GUID] = [] var deletedBookmarksGUIDs: [GUID] = [] for record in childrenRecords { // No mutable l-values in Swift :( if record.payload.deleted { deletedBookmarksGUIDs.append(record.id) } else { newBookmarkGUIDs.append(record.id) } } let records = [mobileRootRecord] + childrenRecords return self.uploadRecordsSingleBatch(records, lastTimestamp: mirrorer.lastModified, storageClient: bookmarksClient) >>== { (timestamp: Timestamp, succeeded: [GUID]) -> Success in let bufferValuesToMoveFromLocal = Set(newBookmarkGUIDs).intersection(Set(succeeded)) let deletedValues = Set(deletedBookmarksGUIDs).intersection(Set(succeeded)) let mobileRoot = (mobileRootRecord.payload as MirrorItemable).toMirrorItem(timestamp) let bufferOP = BufferUpdatedCompletionOp(bufferValuesToMoveFromLocal: bufferValuesToMoveFromLocal, deletedValues: deletedValues, mobileRoot: mobileRoot, modifiedTime: timestamp) return storage.applyBufferUpdatedCompletionOp(bufferOP) >>> { mirrorer.advanceNextDownloadTimestampTo(timestamp: timestamp) // We need to advance our batching downloader timestamp to match. See Bug 1253458. return succeed() } } } open func synchronizeBookmarksToStorage(_ storage: SyncableBookmarks & LocalItemSource & MirrorItemSource, usingBuffer buffer: BookmarkBufferStorage & BufferItemSource, withServer storageClient: Sync15StorageClient, info: InfoCollections, greenLight: @escaping () -> Bool, remoteClientsAndTabs: RemoteClientsAndTabs) -> SyncResult { if self.prefs.boolForKey("dateAddedMigrationDone") != true { self.lastFetched = 0 self.prefs.setBool(true, forKey: "dateAddedMigrationDone") } if let reason = self.reasonToNotSync(storageClient) { return deferMaybe(.notStarted(reason)) } let encoder = RecordEncoder<BookmarkBasePayload>(decode: BookmarkType.somePayloadFromJSON, encode: { $0.json }) guard let bookmarksClient = self.collectionClient(encoder, storageClient: storageClient) else { log.error("Couldn't make bookmarks factory.") return deferMaybe(FatalError(message: "Couldn't make bookmarks factory.")) } let start = Date.nowMicroseconds() let mirrorer = BookmarksMirrorer(storage: buffer, client: bookmarksClient, basePrefs: self.prefs, collection: "bookmarks", statsSession: self.statsSession) let storer = TrivialBookmarkStorer(uploader: { records, lastTimestamp, onUpload in let timestamp = lastTimestamp ?? self.lastFetched return self.uploadRecords(records, lastTimestamp: timestamp, storageClient: bookmarksClient, onUpload: onUpload) >>== effect { timestamp in // We need to advance our batching downloader timestamp to match. See Bug 1253458. self.setTimestamp(timestamp) mirrorer.advanceNextDownloadTimestampTo(timestamp: timestamp) } }) statsSession.start() let doMirror = mirrorer.go(info: info, greenLight: greenLight) let run: SyncResult if !AppConstants.shouldMergeBookmarks { run = doMirror >>== { result -> SyncResult in // Validate the buffer to report statistics. if case .completed = result { log.debug("Validating completed buffer download.") return buffer.validate().bind { validationResult in guard let invalidError = validationResult.failureValue as? BufferInvalidError else { return deferMaybe(result) } return buffer.getUpstreamRecordCount().bind { checked -> Success in self.statsSession.validationStats = self.validationStatsFrom(error: invalidError, checked: checked) return self.maybeStartRepairProcedure(greenLight: greenLight, error: invalidError, remoteClientsAndTabs: remoteClientsAndTabs) } >>> { return deferMaybe(result) } } } return deferMaybe(result) } >>== { result in guard AppConstants.MOZ_SIMPLE_BOOKMARKS_SYNCING else { return deferMaybe(result) } guard case .completed = result else { return deferMaybe(result) } // -1 because we also need to upload the mobile root. return (storage.getLocalBookmarksModifications(limit: bookmarksClient.maxBatchPostRecords - 1) >>== { (deletedGUIDs, newBookmarks) -> Success in guard newBookmarks.count > 0 || deletedGUIDs.count > 0 else { return succeed() } return self.buildMobileRootAndChildrenRecords(storage, buffer, additionalChildren: newBookmarks, deletedChildren: deletedGUIDs) >>== { (mobileRootRecord, childrenRecords) in return self.uploadSomeLocalRecords(storage, mirrorer, bookmarksClient, mobileRootRecord: mobileRootRecord, childrenRecords: childrenRecords) } }).bind { simpleSyncingResult in if let failure = simpleSyncingResult.failureValue { SentryIntegration.shared.send(message: "Failed to simple sync bookmarks: " + failure.description, tag: "BookmarksSyncing", severity: .error) } return deferMaybe(result) } } } else { run = doMirror >>== { result in // Only bother trying to sync if the mirror operation wasn't interrupted or partial. if case .completed = result { return buffer.validate().bind { result in if let invalidError = result.failureValue as? BufferInvalidError { return buffer.getUpstreamRecordCount().bind { checked in self.statsSession.validationStats = self.validationStatsFrom(error: invalidError, checked: checked) return self.maybeStartRepairProcedure(greenLight: greenLight, error: invalidError, remoteClientsAndTabs: remoteClientsAndTabs) >>> { return deferMaybe(invalidError) } } } let applier = MergeApplier(buffer: buffer, storage: storage, client: storer, statsSession: self.statsSession, greenLight: greenLight) return applier.go() } } return deferMaybe(result) } } run.upon { result in let end = Date.nowMicroseconds() let duration = end - start log.info("Bookmark \(AppConstants.shouldMergeBookmarks ? "sync" : "mirroring") took \(duration)µs. Result was \(result.successValue?.description ?? result.failureValue?.description ?? "failure")") } return run } private func validationStatsFrom(error: BufferInvalidError, checked: Int?) -> ValidationStats { let problems = error.inconsistencies.map { ValidationProblem(name: $0.trackingEvent, count: $1.count) } return ValidationStats(problems: problems, took: error.validationDuration, checked: checked) } private func maybeStartRepairProcedure(greenLight: () -> Bool, error: BufferInvalidError, remoteClientsAndTabs: RemoteClientsAndTabs) -> Success { guard AppConstants.MOZ_BOOKMARKS_REPAIR_REQUEST && greenLight() else { return succeed() } log.warning("Buffer inconsistent, starting repair procedure") let repairer = BookmarksRepairRequestor(scratchpad: self.scratchpad, basePrefs: self.basePrefs, remoteClients: remoteClientsAndTabs) return repairer.startRepairs(validationInfo: error.inconsistencies).bind { result in if let repairFailure = result.failureValue { SentryIntegration.shared.send(message: "Bookmarks repair failure: " + repairFailure.description, tag: "BookmarksRepair", severity: .error) } else { SentryIntegration.shared.send(message: "Bookmarks repair succeeded", tag: "BookmarksRepair", severity: .debug) } return succeed() } } } class MergeApplier { let greenLight: () -> Bool let buffer: BookmarkBufferStorage let storage: SyncableBookmarks let client: BookmarkStorer let merger: BookmarksStorageMerger let statsSession: SyncEngineStatsSession init(buffer: BookmarkBufferStorage & BufferItemSource, storage: SyncableBookmarks & LocalItemSource & MirrorItemSource, client: BookmarkStorer, statsSession: SyncEngineStatsSession, greenLight: @escaping () -> Bool) { self.greenLight = greenLight self.buffer = buffer self.storage = storage self.merger = ThreeWayBookmarksStorageMerger(buffer: buffer, storage: storage) self.client = client self.statsSession = statsSession } // Exposed for use from tests. func applyResult(_ result: BookmarksMergeResult) -> Success { return result.applyToClient(self.client, storage: self.storage, buffer: self.buffer) } func go() -> SyncResult { guard self.greenLight() else { log.info("Green light turned red; not merging bookmarks.") return deferMaybe(SyncStatus.completed(statsSession.end())) } return self.merger.merge() >>== self.applyResult >>> always(SyncStatus.completed(statsSession.end())) } } /** * The merger takes as input an existing storage state (mirror and local override), * a buffer of new incoming records that relate to the mirror, and performs a three-way * merge. * * The merge itself does not mutate storage. The result of the merge is conceptually a * tuple: a new mirror state, a set of reconciled + locally changed records to upload, * and two checklists of buffer and local state to discard. * * Typically the merge will be complete, resulting in a new mirror state, records to * upload, and completely emptied buffer and local. In the case of partial inconsistency * this will not be the case; incomplete subtrees will remain in the buffer. (We don't * expect local subtrees to ever be incomplete.) * * It is expected that the caller will immediately apply the result in this order: * * 1. Upload the remote changes, if any. If this fails we can retry the entire process. * * 2(a). Apply the local changes, if any. If this fails we will re-download the records * we just uploaded, and should reach the same end state. * This step takes a timestamp key from (1), because pushing a record into the mirror * requires a server timestamp. * * 2(b). Switch to the new mirror state. If this fails, we should find that our reconciled * server contents apply neatly to our mirror and empty local, and we'll reach the * same end state. * * Mirror state is applied in a sane order to respect relational constraints, even though * we configure sqlite to defer constraint validation until the transaction is committed. * That means: * * - Add any new records in the value table. * - Change any existing records in the value table. * - Update structure. * - Remove records from the value table. * * 3. Apply buffer changes. We only do this after the mirror has advanced; if we fail to * clean up the buffer, it'll reconcile neatly with the mirror on a subsequent try. * * 4. Update bookkeeping timestamps. If this fails we will download uploaded records, * find they match, and have no repeat merging work to do. * * The goal of merging is that the buffer is empty (because we reconciled conflicts and * updated the server), our local overlay is empty (because we reconciled conflicts and * applied our changes to the server), and the mirror matches the server. * * Note that upstream application is robust: we can use XIUS to ensure that writes don't * race. Buffer application is similarly robust, because this code owns all writes to the * buffer. Local and mirror application, however, is not: the user's actions can cause * changes to write to the database before we're done applying the results of a sync. * We mitigate this a little by being explicit about the local changes that we're flushing * (rather than, say, `DELETE FROM local`), but to do better we'd need change detection * (e.g., an in-memory monotonic counter) or locking to prevent bookmark operations from * racing. Later! */ protocol BookmarksStorageMerger: class { init(buffer: BookmarkBufferStorage & BufferItemSource, storage: SyncableBookmarks & LocalItemSource & MirrorItemSource) func merge() -> Deferred<Maybe<BookmarksMergeResult>> } class NoOpBookmarksMerger: BookmarksStorageMerger { let buffer: BookmarkBufferStorage & BufferItemSource let storage: SyncableBookmarks & LocalItemSource & MirrorItemSource required init(buffer: BookmarkBufferStorage & BufferItemSource, storage: SyncableBookmarks & LocalItemSource & MirrorItemSource) { self.buffer = buffer self.storage = storage } func merge() -> Deferred<Maybe<BookmarksMergeResult>> { return deferMaybe(BookmarksMergeResult.NoOp(ItemSources(local: self.storage, mirror: self.storage, buffer: self.buffer))) } } class ThreeWayBookmarksStorageMerger: BookmarksStorageMerger { let buffer: BookmarkBufferStorage & BufferItemSource let storage: SyncableBookmarks & LocalItemSource & MirrorItemSource required init(buffer: BookmarkBufferStorage & BufferItemSource, storage: SyncableBookmarks & LocalItemSource & MirrorItemSource) { self.buffer = buffer self.storage = storage } // MARK: - BookmarksStorageMerger. // Trivial one-way sync. fileprivate func applyLocalDirectlyToMirror() -> Deferred<Maybe<BookmarksMergeResult>> { // Theoretically, we do the following: // * Construct a virtual bookmark tree overlaying local on the mirror. // * Walk the tree to produce Sync records. // * Upload those records. // * Flatten that tree into the mirror, clearing local. // // This is simpler than a full three-way merge: it's tree delta then flatten. // // But we are confident that our local changes, when overlaid on the mirror, are // consistent. So we can take a little bit of a shortcut: process records // directly, rather than building a tree. // // So do the following: // * Take everything in `local` and turn it into a Sync record. This means pulling // folder hierarchies out of localStructure, values out of local, and turning // them into records. Do so in hierarchical order if we can, and set sortindex // attributes to put folders first. // * Upload those records in as few batches as possible. Ensure that each batch // is consistent, if at all possible, though we're hoping for server support for // atomic writes. // * Take everything in local that was successfully uploaded and move it into the // mirror, using the timestamps we tracked from the upload. // // Optionally, set 'again' to true in our response, and do this work only for a // particular subtree (e.g., a single root, or a single branch of changes). This // allows us to make incremental progress. // TODO log.debug("No special-case local-only merging yet. Falling back to three-way merge.") return self.threeWayMerge() } fileprivate func applyIncomingDirectlyToMirror() -> Deferred<Maybe<BookmarksMergeResult>> { // If the incoming buffer is consistent -- and the result of the mirrorer // gives us a hint about that! -- then we can move the buffer records into // the mirror directly. // // Note that this is also true for entire subtrees: if none of the children // of, say, 'menu________' are modified locally, then we can apply it without // merging. // // TODO log.debug("No special-case remote-only merging yet. Falling back to three-way merge.") return self.threeWayMerge() } // This is exposed for testing. func getMerger() -> Deferred<Maybe<ThreeWayTreeMerger>> { return self.storage.treesForEdges() >>== { (local, remote) in // At this point *might* have two empty trees. This should only be the case if // there are value-only changes (e.g., a renamed bookmark). // We don't fail in that case, but we could optimize here. // Find the mirror tree so we can compare. return self.storage.treeForMirror() >>== { mirror in // At this point we know that there have been changes both locally and remotely. // (Or, in the general case, changes either locally or remotely.) let itemSources = ItemSources(local: CachingLocalItemSource(source: self.storage), mirror: CachingMirrorItemSource(source: self.storage), buffer: CachingBufferItemSource(source: self.buffer)) return deferMaybe(ThreeWayTreeMerger(local: local, mirror: mirror, remote: remote, itemSources: itemSources)) } } } func getMergedTree() -> Deferred<Maybe<MergedTree>> { return self.getMerger() >>== { $0.produceMergedTree() } } func threeWayMerge() -> Deferred<Maybe<BookmarksMergeResult>> { return self.getMerger() >>== { $0.produceMergedTree() >>== $0.produceMergeResultFromMergedTree } } func merge() -> Deferred<Maybe<BookmarksMergeResult>> { return self.buffer.isEmpty() >>== { noIncoming in // TODO: the presence of empty desktop roots in local storage // isn't something we really need to worry about. Can we skip it here? return self.storage.isUnchanged() >>== { noOutgoing in switch (noIncoming, noOutgoing) { case (true, true): // Nothing to do! log.debug("No incoming and no outgoing records: no-op.") return deferMaybe(BookmarksMergeResult.NoOp(ItemSources(local: self.storage, mirror: self.storage, buffer: self.buffer))) case (true, false): // No incoming records to apply. Unilaterally apply local changes. return self.applyLocalDirectlyToMirror() case (false, true): // No outgoing changes. Unilaterally apply remote changes if they're consistent. return self.buffer.validate() >>> self.applyIncomingDirectlyToMirror default: // Changes on both sides. Merge. return self.buffer.validate() >>> self.threeWayMerge } } } } }
8da8361764329ba7554ea793358ac870
51.433333
336
0.656707
false
false
false
false
philipsawyer/visn
refs/heads/master
visn/Extensions/UIImageExtensions.swift
mit
1
// // UIImageExtensions.swift // visn // // Created by Philip Sawyer on 7/3/17. // Copyright © 2017 Philip Sawyer. All rights reserved. // import UIKit import Foundation extension UIImage { func toPixelBuffer() -> CVPixelBuffer? { let options = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue] as CFDictionary var pixelBufferOut: CVPixelBuffer? let status = CVPixelBufferCreate(kCFAllocatorDefault, Int(size.width), Int(size.height), kCVPixelFormatType_32ARGB, options, &pixelBufferOut) let rgbColorSpace = CGColorSpaceCreateDeviceRGB() guard status == kCVReturnSuccess, let pixelBuffer = pixelBufferOut else { return nil } CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: 0)) let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer) guard let context = CGContext(data: pixelData, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue) else { return nil } context.translateBy(x: 0, y: size.height) context.scaleBy(x: 1.0, y: -1) UIGraphicsPushContext(context) draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) UIGraphicsPopContext() CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: 0)) return pixelBuffer } }
3dc07b76ff2523c2d69427c64d38e2cf
39.65
262
0.694957
false
false
false
false
jcfausto/transit-app
refs/heads/master
TransitApp/TransitApp/Route.swift
mit
1
// // Route.swift // TransitApp // // Created by Julio Cesar Fausto on 24/02/16. // Copyright © 2016 Julio Cesar Fausto. All rights reserved. // import Foundation import Unbox /** This enumeration represents a certain position in the route The two supoorted ones are: - Start : The first position in the route - Finish : The last position in the route */ enum RoutePosition { case Start case Finish } struct Route: Unboxable { var type: String var provider: String var segments: [Segment] var price: Price? init(type: String, provider: String, segments: [Segment], price: Price){ self.type = type self.provider = provider self.segments = segments self.price = price } init(unboxer: Unboxer) { self.type = unboxer.unbox("type") self.provider = unboxer.unbox("provider") self.segments = unboxer.unbox("segments") self.price = unboxer.unbox("price") } } // MARK: Route struct extension extension Route { func timeStringRepresentation(from: RoutePosition) -> String { var result: String = "" switch from { case RoutePosition.Start: if let time = self.segments.first?.stops.first?.time { result = time.stringValueWithHourAndMinute } case RoutePosition.Finish: if let time = self.segments.last?.stops.last?.time { result += time.stringValueWithHourAndMinute } } return result } /** This is a computed var based on the route's segment stops. The duration is computed by the difference between the finish point time and the start point time. If the route does not have at least two segments, the duration will return 0. */ var duration: NSTimeInterval { guard let finish = self.segments.last?.stops.last?.time, let start = self.segments.first?.stops.first?.time else { return 0 } return finish.timeIntervalSinceDate(start) } /** A summary string of the route containing the price and the start and finish time. */ var summary: String { var result: String = "" if let price = self.price { result += "\(price.currency): \(price.amount)" } let start = self.timeStringRepresentation(RoutePosition.Start) let finish = self.timeStringRepresentation(RoutePosition.Finish) if (start != "" && finish != "") { if result != "" { result += " | \(start) -> \(finish)" } else { result += "\(start) -> \(finish)" } } return result } }
e0e9cde09f703e15583700af4a6447f0
24.72973
86
0.569177
false
false
false
false
dduan/swift
refs/heads/master
test/SILGen/function_conversion_objc.swift
apache-2.0
2
// RUN: %target-swift-frontend -sdk %S/Inputs %s -I %S/Inputs -enable-source-import -emit-silgen -verify | FileCheck %s import Foundation // REQUIRES: objc_interop // ==== Metatype to object conversions // CHECK-LABEL: sil hidden @_TF24function_conversion_objc20convMetatypeToObjectFFCSo8NSObjectMS0_T_ func convMetatypeToObject(f: NSObject -> NSObject.Type) { // CHECK: function_ref @_TTRXFo_oCSo8NSObject_dXMTS__XFo_oS__oPs9AnyObject__ // CHECK: partial_apply let _: NSObject -> AnyObject = f } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_oCSo8NSObject_dXMTS__XFo_oS__oPs9AnyObject__ : $@convention(thin) (@owned NSObject, @owned @callee_owned (@owned NSObject) -> @thick NSObject.Type) -> @owned AnyObject { // CHECK: apply %1(%0) // CHECK: thick_to_objc_metatype {{.*}} : $@thick NSObject.Type to $@objc_metatype NSObject.Type // CHECK: objc_metatype_to_object {{.*}} : $@objc_metatype NSObject.Type to $AnyObject // CHECK: return @objc protocol NSBurrito {} // CHECK-LABEL: sil hidden @_TF24function_conversion_objc31convExistentialMetatypeToObjectFFPS_9NSBurrito_PMPS0__T_ func convExistentialMetatypeToObject(f: NSBurrito -> NSBurrito.Type) { // CHECK: function_ref @_TTRXFo_oP24function_conversion_objc9NSBurrito__dXPMTPS0___XFo_oPS0___oPs9AnyObject__ // CHECK: partial_apply let _: NSBurrito -> AnyObject = f } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_oP24function_conversion_objc9NSBurrito__dXPMTPS0___XFo_oPS0___oPs9AnyObject__ : $@convention(thin) (@owned NSBurrito, @owned @callee_owned (@owned NSBurrito) -> @thick NSBurrito.Type) -> @owned AnyObject // CHECK: apply %1(%0) // CHECK: thick_to_objc_metatype {{.*}} : $@thick NSBurrito.Type to $@objc_metatype NSBurrito.Type // CHECK: objc_existential_metatype_to_object {{.*}} : $@objc_metatype NSBurrito.Type to $AnyObject // CHECK: return // CHECK-LABEL: sil hidden @_TF24function_conversion_objc28convProtocolMetatypeToObjectFFT_MPS_9NSBurrito_T_ func convProtocolMetatypeToObject(f: () -> NSBurrito.Protocol) { // CHECK: function_ref @_TTRXFo__dXMtP24function_conversion_objc9NSBurrito__XFo__oCSo8Protocol_ // CHECK: partial_apply let _: () -> Protocol = f } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__dXMtP24function_conversion_objc9NSBurrito__XFo__oCSo8Protocol_ : $@convention(thin) (@owned @callee_owned () -> @thin NSBurrito.Protocol) -> @owned Protocol // CHECK: apply %0() : $@callee_owned () -> @thin NSBurrito.Protocol // CHECK: objc_protocol #NSBurrito : $Protocol // CHECK: strong_retain // CHECK: return // ==== Representation conversions // CHECK-LABEL: sil hidden @_TF24function_conversion_objc11funcToBlockFFT_T_bT_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> @owned @convention(block) () -> () // CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] // CHECK: [[COPY:%.*]] = copy_block [[BLOCK]] : $@convention(block) () -> () // CHECK: return [[COPY]] func funcToBlock(x: () -> ()) -> @convention(block) () -> () { return x } // CHECK-LABEL: sil hidden @_TF24function_conversion_objc11blockToFuncFbT_T_FT_T_ : $@convention(thin) (@owned @convention(block) () -> ()) -> @owned @callee_owned () -> () // CHECK: [[COPIED:%.*]] = copy_block %0 // CHECK: [[THUNK:%.*]] = function_ref @_TTRXFdCb___XFo___ // CHECK: [[FUNC:%.*]] = partial_apply [[THUNK]]([[COPIED]]) // CHECK: return [[FUNC]] func blockToFunc(x: @convention(block) () -> ()) -> () -> () { return x } // ==== Representation change + function type conversion // CHECK-LABEL: sil hidden @_TF24function_conversion_objc22blockToFuncExistentialFbT_SiFT_P_ : $@convention(thin) (@owned @convention(block) () -> Int) -> @owned @callee_owned () -> @out protocol<> // CHECK: function_ref @_TTRXFdCb__dSi_XFo__dSi_ // CHECK: partial_apply // CHECK: function_ref @_TTRXFo__dSi_XFo__iP__ // CHECK: partial_apply // CHECK: return func blockToFuncExistential(x: @convention(block) () -> Int) -> () -> Any { return x } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFdCb__dSi_XFo__dSi_ : $@convention(thin) (@owned @convention(block) () -> Int) -> Int // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__dSi_XFo__iP__ : $@convention(thin) (@owned @callee_owned () -> Int) -> @out protocol<> // C function pointer conversions class A : NSObject {} class B : A {} // CHECK-LABEL: sil hidden @_TF24function_conversion_objc18cFuncPtrConversionFcCS_1AT_cCS_1BT_ func cFuncPtrConversion(x: @convention(c) A -> ()) -> @convention(c) B -> () { // CHECK: convert_function %0 : $@convention(c) (A) -> () to $@convention(c) (B) -> () // CHECK: return return x } func cFuncPtr(a: A) {} // CHECK-LABEL: sil hidden @_TF24function_conversion_objc19cFuncDeclConversionFT_cCS_1BT_ func cFuncDeclConversion() -> @convention(c) B -> () { // CHECK: function_ref @_TToF24function_conversion_objc8cFuncPtrFCS_1AT_ : $@convention(c) (A) -> () // CHECK: convert_function %0 : $@convention(c) (A) -> () to $@convention(c) (B) -> () // CHECK: return return cFuncPtr } func cFuncPtrConversionUnsupported(x: @convention(c) (@convention(block) () -> ()) -> ()) -> @convention(c) (@convention(c) () -> ()) -> () { return x // expected-error{{C function pointer signature '@convention(c) (@convention(block) () -> ()) -> ()' is not compatible with expected type '@convention(c) (@convention(c) () -> ()) -> ()'}} }
7ba7747523f82f0566df06d82bac4c1b
50.963964
275
0.647365
false
false
false
false
haskellswift/swift-package-manager
refs/heads/master
Sources/Utility/Versioning.swift
apache-2.0
2
/* This source file is part of the Swift.org open source project Copyright 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ // Import the custom version string (generated via the bootstrap script), if // available. #if HasCustomVersionString import VersionInfo #endif /// A Swift version number. /// /// Note that these are *NOT* semantically versioned numbers. public struct SwiftVersion { /// The version number. public var version: (major: Int, minor: Int, patch: Int) /// Whether or not this is a development version. public var isDevelopment: Bool /// Build information, as an unstructured string. public var buildIdentifier: String? /// The major component of the version number. public var major: Int { return version.major } /// The minor component of the version number. public var minor: Int { return version.minor } /// The patch component of the version number. public var patch: Int { return version.patch } /// The version as a readable string. public var displayString: String { var result = "\(major).\(minor).\(patch)" if isDevelopment { result += "-dev" } if let buildIdentifier = self.buildIdentifier { result += " (" + buildIdentifier + ")" } return result } /// The complete product version display string (including the name). public var completeDisplayString: String { var vendorPrefix = "" #if HasCustomVersionString vendorPrefix += String(cString: VersionInfo.VendorNameString()) + " " #endif return vendorPrefix + "Swift Package Manager - Swift " + displayString } /// The list of version specific identifiers to search when attempting to /// load version specific package or version information, in order of /// preference. public var versionSpecificKeys: [String] { return [ "@swift-\(major).\(minor).\(patch)", "@swift-\(major).\(minor)", "@swift-\(major)" ] } } private func getBuildIdentifier() -> String? { #if HasCustomVersionString return String(cString: VersionInfo.BuildIdentifierString()) #else return nil #endif } /// Version support for the package manager. public struct Versioning { /// The current version of the package manager. public static let currentVersion = SwiftVersion( version: (3, 0, 0), isDevelopment: true, buildIdentifier: getBuildIdentifier()) /// The list of version specific "keys" to search when attempting to load /// version specific package or version information, in order of preference. public static let currentVersionSpecificKeys = currentVersion.versionSpecificKeys }
d175b6fe76190965efe5a2c4b4e55193
31.644444
85
0.676991
false
false
false
false
hsavit1/LeetCode-Solutions-in-Swift
refs/heads/master
Solutions/SolutionsTests/Medium/Medium_022_Generate_Parentheses_Test.swift
mit
4
// // Medium_022_Generate_Parentheses_Test.swift // Solutions // // Created by Di Wu on 5/5/15. // Copyright (c) 2015 diwu. All rights reserved. // import XCTest class Medium_022_Generate_Parentheses_Test: XCTestCase { private static let ProblemName: String = "Medium_022_Generate_Parentheses" private static let TimeOutName = ProblemName + Default_Timeout_Suffix private static let TimeOut = Default_Timeout_Value func test_001() { let input: Int = 1 let expected: [String] = ["()"] asyncHelper(input: input, expected: expected) } func test_002() { let input: Int = 0 let expected: [String] = [""] asyncHelper(input: input, expected: expected) } func test_003() { let input: Int = 3 let expected: [String] = ["((()))", "(()())", "(())()", "()(())", "()()()"] asyncHelper(input: input, expected: expected) } private func asyncHelper(input input: Int, expected: [String]) { weak var expectation: XCTestExpectation? = self.expectationWithDescription(Medium_022_Generate_Parentheses_Test.TimeOutName) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in let result: [String] = Medium_022_Generate_Parentheses.generateParenthesis(input) assertHelper(Set(expected) == Set(result), problemName: Medium_022_Generate_Parentheses_Test.ProblemName, input: input, resultValue: result, expectedValue: expected) if let unwrapped = expectation { unwrapped.fulfill() } }) waitForExpectationsWithTimeout(Medium_022_Generate_Parentheses_Test.TimeOut) { (error: NSError?) -> Void in if error != nil { assertHelper(false, problemName: Medium_022_Generate_Parentheses_Test.ProblemName, input: input, resultValue: Medium_022_Generate_Parentheses_Test.TimeOutName, expectedValue: expected) } } } }
f4d00e4b77216edaf8812280326f9a5b
42.152174
200
0.64131
false
true
false
false
everald/JetPack
refs/heads/master
Sources/UI/TextField.swift
mit
1
import UIKit @objc(JetPack_TextField) open class TextField: UITextField { open var additionalHitZone = UIEdgeInsets() // TODO don't use UIEdgeInsets because actually we outset open var hitZoneFollowsCornerRadius = true open var userInteractionLimitedToSubviews = false public init() { super.init(frame: .zero) } public required init?(coder: NSCoder) { super.init(coder: coder) } open override func action(for layer: CALayer, forKey event: String) -> CAAction? { switch event { case "borderColor", "cornerRadius", "shadowColor", "shadowOffset", "shadowOpacity", "shadowPath", "shadowRadius": if let animation = super.action(for: layer, forKey: "opacity") as? CABasicAnimation { animation.fromValue = layer.value(forKey: event) animation.keyPath = event return animation } fallthrough default: return super.action(for: layer, forKey: event) } } open var borderColor: UIColor? { get { return layer.borderColor.map { UIColor(cgColor: $0) } } set { layer.borderColor = newValue?.cgColor } } open var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } open var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue } } public final override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { return pointInside(point, withEvent: event, additionalHitZone: additionalHitZone) } open func pointInside(_ point: CGPoint, withEvent event: UIEvent?, additionalHitZone: UIEdgeInsets) -> Bool { let originalHitZone = bounds let extendedHitZone = originalHitZone.insetBy(additionalHitZone.inverse) let hitZoneCornerRadius: CGFloat if hitZoneFollowsCornerRadius && cornerRadius > 0 { let halfOriginalHitZoneSize = (originalHitZone.width + originalHitZone.height) / 4 // middle between half height and half width let halfExtendedHitZoneSize = (extendedHitZone.width + extendedHitZone.height) / 4 // middle between half extended height and half extended width hitZoneCornerRadius = halfExtendedHitZoneSize * (cornerRadius / halfOriginalHitZoneSize) } else { hitZoneCornerRadius = 0 } return extendedHitZone.contains(point, cornerRadius: hitZoneCornerRadius) } // reference implementation open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { guard participatesInHitTesting else { return nil } guard self.point(inside: point, with: event) else { return nil } var hitView: UIView? for subview in subviews.reversed() { hitView = subview.hitTest(convert(point, to: subview), with: event) if hitView != nil { break } } if hitView == nil && !userInteractionLimitedToSubviews { hitView = self } return hitView } }
215f5540495ee739be6f00559ab7ce47
25.102804
149
0.725385
false
false
false
false
mzanoski/yacss
refs/heads/master
yacss/LicenseWindowController.swift
lgpl-3.0
1
import Foundation import Cocoa class LicenseWindowController: NSWindowController { @IBOutlet weak var licenseView: NSScrollView! @IBOutlet var licenseTextView: NSTextView! @IBOutlet weak var view: NSView! override init(window: NSWindow?){ super.init(window: window) } required init?(coder: NSCoder) { super.init(coder: coder) } override func windowDidLoad() { self.view.window?.titlebarAppearsTransparent = true self.view.window?.isMovableByWindowBackground = true self.view.window?.backgroundColor = NSColor.white self.view.layer?.backgroundColor = NSColor.white.cgColor if let licenseText = loadFileFromBundle(fileName: "license", type: "txt"){ self.licenseTextView.string = licenseText } } func loadFileFromBundle(fileName: String, type: String) -> String?{ if let filePath = Bundle.main.path(forResource: fileName, ofType: type){ if FileManager.default.fileExists(atPath: filePath){ let contents = FileManager.default.contents(atPath: filePath) return String(data: contents!, encoding: String.Encoding.utf8) } } return nil } }
f572b039caee54dc793c1cbb28893c09
33.081081
82
0.648692
false
false
false
false
grubFX/ICE
refs/heads/master
ICE/ViewController.swift
bsd-3-clause
1
// // ViewController.swift // ICE // // Created by Felix Gruber on 25.03.15. // Copyright (c) 2015 Felix Gruber. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource{ var numbers = [String]() var persondata: PersonData? let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext let personDataRequest = NSFetchRequest(entityName: "PersonData") let numbersRequest = NSFetchRequest(entityName: "NumberString") @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var name: UILabel! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var bloodType: UILabel! @IBOutlet weak var allergies: UILabel! @IBOutlet weak var medHist: UILabel! override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self; tableView.delegate = self; imageView.layer.borderWidth=1.0 imageView.layer.masksToBounds = false imageView.layer.borderColor = UIColor.grayColor().CGColor imageView.layer.cornerRadius = 13 imageView.layer.cornerRadius = imageView.frame.size.height/2 imageView.clipsToBounds = true loadPersonDataFromDB() tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(animated: Bool) { loadPersonDataFromDB() tableView.reloadData() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numbers.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell") cell!.textLabel!.text = numbers[indexPath.row] cell!.textLabel!.numberOfLines = 2 return cell! } func loadPersonDataFromDB(){ var error: NSError? var recordCount = context!.countForFetchRequest(personDataRequest, error: &error) var fetchedResults: [NSManagedObject]? = nil; if(recordCount>0){ do{ fetchedResults = try context!.executeFetchRequest(personDataRequest) as? [NSManagedObject] }catch _{} if let results = fetchedResults { persondata = results[0] as? PersonData if persondata != nil{ name.text = "\(persondata!.firstName) \(persondata!.lastName)" bloodType.text = persondata!.bloodType allergies.text = persondata!.allergies medHist.text = persondata!.medHist if let temp = UIImage(data: persondata!.img as NSData){ imageView.image = temp } } } } recordCount = context!.countForFetchRequest(numbersRequest, error: &error) if(recordCount>0){ do{ fetchedResults = try context!.executeFetchRequest(numbersRequest) as? [NSManagedObject] }catch _{} if let results = fetchedResults { numbers.removeAll(keepCapacity: false) for result in results { addNumber((result as! NumberString).number) } } }else{ numbers = ["here will be the numbers you choose","they will show up on the homescreen in this order","swipe left to remove"] } } func addNumber(number: String){ if !numbers.contains(number){ numbers.append(number) } } @IBAction func unwindSegue(segue: UIStoryboardSegue){ /*kinda useless*/ } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { numbers.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } } override func viewWillDisappear(animated: Bool) { var fetchedResults: [NSManagedObject]? = nil do{ fetchedResults = try context!.executeFetchRequest(numbersRequest) as? [NSManagedObject] }catch _{} if let results = fetchedResults { for result in results { context!.deleteObject(result as NSManagedObject) } } do { try context!.save() } catch _ { } for num in numbers { (NSEntityDescription.insertNewObjectForEntityForName("NumberString", inManagedObjectContext: context!) as! NumberString).number=num do { try context!.save() } catch _ { } } // save to userdefaults let defaults: NSUserDefaults = NSUserDefaults(suiteName: "group.at.fhooe.mc.MOM4.ICE")! defaults.setObject(numbers, forKey: "numbers") if persondata != nil{ defaults.setObject(persondata!.firstName + " " + persondata!.lastName, forKey: "name") defaults.setObject(persondata!.bloodType, forKey: "bloodtype") defaults.setObject(persondata!.medHist, forKey: "medhist") defaults.setObject(persondata!.allergies, forKey: "allergies") } defaults.synchronize() } }
c40a5ee23a35bf5054848e482c95fb93
36.245033
148
0.614619
false
false
false
false
biohazardlover/ROer
refs/heads/master
Roer/StatusCalculator.swift
mit
1
import Foundation import UIKit import JavaScriptCore let StatusCalculatorValueDidChangeNotification = "StatusCalculatorValueDidChangeNotification" var context: JSContext! var www: UIWebView! @objc protocol StatusCalculatorDelegate: NSObjectProtocol { @objc optional func statusCalculatorDidFinishLoad(_ statusCalculator: StatusCalculator) @objc optional func statusCalculator(_ statusCalculator: StatusCalculator, didFailLoadWithError error: NSError?) } class StatusCalculator: NSObject { weak var delegate: StatusCalculatorDelegate? class ElementSection { var title: String var elements: [AnyObject] init(title: String, elements: [AnyObject]) { self.title = title self.elements = elements } } class Element { fileprivate(set) var id: String! fileprivate(set) var name: String! fileprivate(set) var description: String? fileprivate var observer: NSObjectProtocol! fileprivate var idOrName: String { return id ?? name } init(id: String, description: String?) { self.id = id self.description = description addObserver() } init(name: String, description: String?) { self.name = name self.description = description addObserver() } deinit { removeObserver() } func addObserver() { observer = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: StatusCalculatorValueDidChangeNotification), object: nil, queue: OperationQueue.main) { [weak self] (note) -> Void in self?.clearCachedValues() } } func removeObserver() { NotificationCenter.default.removeObserver(observer) } func clearCachedValues() { } } class StaticTextElement: Element { fileprivate var _textContent: String? var textContent: String { get { if _textContent == nil { _textContent = context.evaluateScript("document.getElementById('" + id + "').textContent").toString() } return _textContent! } } override func clearCachedValues() { super.clearCachedValues() _textContent = nil } } class InputElement: Element { } class CheckboxInputElement: InputElement { fileprivate var _checked: Bool? var checked: Bool { set { context.evaluateScript("document.calcForm." + idOrName + ".checked = \(newValue)") context.evaluateScript("document.calcForm." + idOrName + ".onclick()") NotificationCenter.default.post(name: Notification.Name(rawValue: StatusCalculatorValueDidChangeNotification), object: nil) } get { if _checked == nil { _checked = context.evaluateScript("document.calcForm." + idOrName + ".checked").toBool() } return _checked! } } override func clearCachedValues() { super.clearCachedValues() _checked = nil } } class NumberInputElement: InputElement { fileprivate var _min: Int? = nil var min: Int { get { if _min == nil { _min = Int(context.evaluateScript("document.calcForm.\(idOrName).min").toInt32()) } return _min! } } fileprivate var _max: Int? = nil var max: Int { get { if _max == nil { _max = Int(context.evaluateScript("document.calcForm.\(idOrName).max").toInt32()) } return _max! } } fileprivate var _value: Int? = nil var value: Int { set { // context.evaluateScript("document.calcForm.\(idOrName).value = \(newValue)") // context.evaluateScript("document.calcForm.\(idOrName).onchange()") www.stringByEvaluatingJavaScript(from: "document.calcForm.\(idOrName).value = \(newValue)") www.stringByEvaluatingJavaScript(from: "document.calcForm.\(idOrName).onchange()") NotificationCenter.default.post(name: Notification.Name(rawValue: StatusCalculatorValueDidChangeNotification), object: nil) } get { if _value == nil { _value = Int(context.evaluateScript("document.calcForm.\(idOrName).value").toInt32()) } return _value! } } override func clearCachedValues() { super.clearCachedValues() _min = nil _max = nil _value = nil } } class TextInputElement: InputElement { var value: String? override func clearCachedValues() { super.clearCachedValues() } } class SelectElement: Element { fileprivate var _options: [Option]? var options: [Option] { get { if _options == nil { _options = [Option]() let length = context.evaluateScript("document.calcForm." + idOrName + ".options.length").toInt32() for i in 0..<length { let text = context.evaluateScript("document.calcForm." + idOrName + ".options[\(i)].text").toString() let value = context.evaluateScript("document.calcForm." + idOrName + ".options[\(i)].value").toString() let option = Option(text: text!, value: value!) _options!.append(option) } } return _options! } } fileprivate var _length: Int? var length: Int { get { if _length == nil { _length = Int(context.evaluateScript("document.calcForm." + idOrName + ".length").toInt32()) } return _length! } } fileprivate var _selectedIndex: Int? var selectedIndex: Int { set { let aaa = "document.calcForm.\(idOrName).selectedIndex = \(newValue);" + "document.calcForm.\(idOrName).onchange();" // context.performSelectorOnMainThread("evaluateScript:", withObject: aaa, waitUntilDone: true) www.stringByEvaluatingJavaScript(from: aaa) NotificationCenter.default.post(name: Notification.Name(rawValue: StatusCalculatorValueDidChangeNotification), object: nil) } get { if _selectedIndex == nil { _selectedIndex = Int(context.evaluateScript("document.calcForm." + idOrName + ".selectedIndex").toInt32()) } return _selectedIndex! } } fileprivate var _currentText: String? var currentText: String { get { if _currentText == nil { if selectedIndex >= 0 && selectedIndex < length { _currentText = context.evaluateScript("document.calcForm.\(idOrName).options[\(selectedIndex)].text").toString() } else { _currentText = "" } } return _currentText! } } override func clearCachedValues() { super.clearCachedValues() _options = nil _length = nil _selectedIndex = nil _currentText = nil } } class Option { var text: String var value: String init(text: String, value: String) { self.text = text self.value = value } } fileprivate var automaticallyAdjustsBaseLevel = CheckboxInputElement(name: "BLVauto", description: "") fileprivate var job = SelectElement(name: "A_JOB", description: "Class") fileprivate var baseLevel = SelectElement(name: "A_BaseLV", description: "Base Lv.") fileprivate var jobLevel = SelectElement(name: "A_JobLV", description: "Job Lv.") fileprivate var str = SelectElement(name: "A_STR", description: "STR") fileprivate var strPlus = StaticTextElement(id: "A_STRp", description: "STR Plus") fileprivate var agi = SelectElement(name: "A_AGI", description: "AGI") fileprivate var agiPlus = StaticTextElement(id: "A_AGIp", description: "AGI Plus") fileprivate var vit = SelectElement(name: "A_VIT", description: "VIT") fileprivate var vitPlus = StaticTextElement(id: "A_VITp", description: "VIT Plus") fileprivate var int = SelectElement(name: "A_INT", description: "INT") fileprivate var intPlus = StaticTextElement(id: "A_INTp", description: "INT Plus") fileprivate var dex = SelectElement(name: "A_DEX", description: "DEX") fileprivate var dexPlus = StaticTextElement(id: "A_DEXp", description: "DEX Plus") fileprivate var luk = SelectElement(name: "A_LUK", description: "LUK") fileprivate var lukPlus = StaticTextElement(id: "A_LUKp", description: "LUK Plus") fileprivate var maxHp = StaticTextElement(id: "A_MaxHP", description: "Max HP") fileprivate var maxSp = StaticTextElement(id: "A_MaxSP", description: "Max SP") fileprivate var atk = StaticTextElement(id: "A_ATK", description: "ATK") fileprivate var def = StaticTextElement(id: "A_totalDEF", description: "DEF") fileprivate var matk = StaticTextElement(id: "A_MATK", description: "MATK") fileprivate var mdef = StaticTextElement(id: "A_MDEF", description: "MDEF") fileprivate var hit = StaticTextElement(id: "A_HIT", description: "HIT") fileprivate var flee = StaticTextElement(id: "A_FLEE", description: "FLEE") fileprivate var perfectDodge = StaticTextElement(id: "A_LUCKY", description: "P. Dodge") fileprivate var critical = StaticTextElement(id: "A_CRI", description: "Critical") fileprivate var aspd = StaticTextElement(id: "A_ASPD", description: "ASPD") fileprivate var hpRegen = StaticTextElement(id: "A_HPR", description: "HP Regen") fileprivate var spRegen = StaticTextElement(id: "A_SPR", description: "SP Regen") fileprivate var statusPoint = StaticTextElement(id: "A_STPOINT", description: "Status Point") fileprivate var mainWeaponType = SelectElement(name: "A_WeaponType", description: "Weapon Type") fileprivate var mainWeaponName = SelectElement(name: "A_weapon1", description: "Name") fileprivate var mainWeaponRefining = SelectElement(name: "A_Weapon_ATKplus", description: nil) fileprivate var mainWeaponCardShortcuts = SelectElement(name: "A_SHORTCUT_R", description: "Card Shortcuts") fileprivate var mainWeaponCard1 = SelectElement(name: "A_weapon1_card1", description: "Card 1") fileprivate var mainWeaponCard2 = SelectElement(name: "A_weapon1_card2", description: "Card 2") fileprivate var mainWeaponCard3 = SelectElement(name: "A_weapon1_card3", description: "Card 3") fileprivate var mainWeaponCard4 = SelectElement(name: "A_weapon1_card4", description: "Card 4") fileprivate var mainWeaponElement = SelectElement(name: "A_Weapon_element", description: "Element") fileprivate var mainWeaponProjectile = SelectElement(name: "A_Arrow", description: "Projectile") fileprivate var armorCardShortcuts = SelectElement(name: "A_cardshort", description: nil) fileprivate var upperHeadgear = SelectElement(name: "A_head1", description: "Upper Headgear") fileprivate var upperHeadgearRefining = SelectElement(name: "A_HEAD_DEF_PLUS", description: nil) fileprivate var upperHeadgearCard = SelectElement(name: "A_head1_card", description: "") fileprivate var upperHeadgearEnchant = SelectElement(name: "A_HSE_HEAD1", description: nil) fileprivate var middleHeadgear = SelectElement(name: "A_head2", description: "Middle Headgear") fileprivate var middleHeadgearCard = SelectElement(name: "A_head2_card", description: "") fileprivate var lowerHeadgear = SelectElement(name: "A_head3", description: "Lower Headgear") fileprivate var armor = SelectElement(name: "A_body", description: "Armor") fileprivate var armorRefining = SelectElement(name: "A_BODY_DEF_PLUS", description: nil) fileprivate var armorCard = SelectElement(name: "A_body_card", description: "") fileprivate var armorEnchant = SelectElement(name: "A_HSE", description: nil) fileprivate var shield = SelectElement(name: "A_left", description: "Shield") fileprivate var shieldRefining = SelectElement(name: "A_LEFT_DEF_PLUS", description: nil) fileprivate var shieldCard = SelectElement(name: "A_left_card", description: "") fileprivate var garment = SelectElement(name: "A_shoulder", description: "Garment") fileprivate var garmentRefining = SelectElement(name: "A_SHOULDER_DEF_PLUS", description: nil) fileprivate var garmentCard = SelectElement(name: "A_shoulder_card", description: "") fileprivate var footgear = SelectElement(name: "A_shoes", description: "Footgear") fileprivate var footgearRefining = SelectElement(name: "A_SHOES_DEF_PLUS", description: nil) fileprivate var footgearCard = SelectElement(name: "A_shoes_card", description: "") fileprivate var accessory1 = SelectElement(name: "A_acces1", description: "Accessory") fileprivate var accessory1Card = SelectElement(name: "A_acces1_card", description: "") fileprivate var accessory2 = SelectElement(name: "A_acces2", description: "Accessory") fileprivate var accessory2Card = SelectElement(name: "A_acces2_card", description: "") fileprivate var strEnchant = NumberInputElement(id: "E_BOOST_STR", description: "STR") fileprivate var agiEnchant = NumberInputElement(id: "E_BOOST_AGI", description: "AGI") fileprivate var vitEnchant = NumberInputElement(id: "E_BOOST_VIT", description: "VIT") fileprivate var intEnchant = NumberInputElement(id: "E_BOOST_INT", description: "INT") fileprivate var dexEnchant = NumberInputElement(id: "E_BOOST_DEX", description: "DEX") fileprivate var lukEnchant = NumberInputElement(id: "E_BOOST_LUK", description: "LUK") fileprivate var atkEnchant = NumberInputElement(id: "E_BOOST_ATK", description: "ATK") fileprivate var atkPercentEnchant = NumberInputElement(id: "E_BOOST_ATK_PERC", description: "ATK %") fileprivate var matkEnchant = NumberInputElement(id: "E_BOOST_MATK", description: "MATK") fileprivate var matkPercentEnchant = NumberInputElement(id: "E_BOOST_MATK_PERC", description: "MATK %") fileprivate var hitEnchant = NumberInputElement(id: "E_BOOST_HIT", description: "HIT") fileprivate var fleeEnchant = NumberInputElement(id: "E_BOOST_FLEE", description: "FLEE") fileprivate var perfectDodgeEnchant = NumberInputElement(id: "E_BOOST_DODGE", description: "P. Dodge") fileprivate var criticalEnchant = NumberInputElement(id: "E_BOOST_CRIT", description: "CRIT") fileprivate var maxHpEnchant = NumberInputElement(id: "E_BOOST_HP", description: "MAX HP") fileprivate var maxSpEnchant = NumberInputElement(id: "E_BOOST_SP", description: "MAX SP") fileprivate var maxHpPercentEnchant = NumberInputElement(id: "E_BOOST_HP_PERC", description: "MAX HP %") fileprivate var maxSpPercentEnchant = NumberInputElement(id: "E_BOOST_SP_PERC", description: "MAX SP %") fileprivate var defEnchant = NumberInputElement(id: "E_BOOST_DEF", description: "DEF") fileprivate var mdefEnchant = NumberInputElement(id: "E_BOOST_MDEF", description: "MDEF") fileprivate var aspdEnchant = NumberInputElement(id: "E_BOOST_ASPD", description: "ASPD") fileprivate var aspdPercentEnchant = NumberInputElement(id: "E_BOOST_ASPD_PERC", description: "ASPD %") fileprivate var rangedDamagePercentEnchant = NumberInputElement(id: "E_BOOST_RANGED", description: "Ranged Damage %") fileprivate var damageReductionPercentEnchant = NumberInputElement(id: "E_BOOST_RED_PERC", description: "Damage Reduction %") fileprivate var castTimePercentEnchant = NumberInputElement(id: "E_BOOST_CASTING", description: "Cast Time %") fileprivate var blessing = SelectElement(id: "blessing", description: "Blessing") fileprivate var increaseAgi = SelectElement(id: "increaseAgi", description: "Increase AGI") fileprivate var angelus = SelectElement(id: "angelus", description: "Angelus") fileprivate var impositioManus = SelectElement(id: "imposito", description: "Impositio Manus") fileprivate var suffragium = SelectElement(id: "suffragium", description: "Suffragium") fileprivate var gloria = CheckboxInputElement(id: "gloria", description: "Gloria") fileprivate var assumptio = SelectElement(id: "assumptio", description: "Assumptio") fileprivate var spiritSpheres = SelectElement(id: "spheres", description: "Spirit Spheres") fileprivate var clementia = SelectElement(id: "clementia", description: "Clementia (bonus)") fileprivate var cantoCandidus = SelectElement(id: "candidus", description: "Canto Candidus (bonus)") fileprivate var expiatio = SelectElement(id: "expiatio", description: "Expiatio") fileprivate var sacrament = SelectElement(id: "sacrament", description: "Sacrament") fileprivate var laudaAgnus = SelectElement(id: "agnus", description: "Lauda Agnus") fileprivate var laudaRamus = SelectElement(id: "ramus", description: "Lauda Ramus") fileprivate var gentleTouchConvert = SelectElement(id: "ppChange", description: "Gentle Touch Convert") fileprivate var gentleTouchRevitalize = SelectElement(id: "ppRevitalize", description: "Gentle Touch Revitalize") fileprivate var suraStr = SelectElement(id: "suraStr", description: "Sura stats") fileprivate var suraAgi = SelectElement(id: "suraAgi", description: nil) fileprivate var suraVit = SelectElement(id: "suraVit", description: nil) fileprivate var suraInt = SelectElement(id: "suraInt", description: nil) fileprivate var suraDex = SelectElement(id: "suraDex", description: nil) fileprivate var bardSkills = SelectElement(id: "bardSkills", description: "Bard") fileprivate var bardSkillLevel = SelectElement(id: "bardSkillLevel", description: nil) fileprivate var musicLessons = SelectElement(id: "musicLessons", description: "") fileprivate var maestroSkills = SelectElement(id: "maestroSkills", description: "") fileprivate var maestroSkillLevel = SelectElement(id: "maestroSkillLevel", description: nil) fileprivate var voiceLessonsMaestro = SelectElement(id: "voiceLessonsM", description: "") fileprivate var bardAgi = SelectElement(id: "bardAgi", description: nil) fileprivate var bardInt = SelectElement(id: "bardInt", description: nil) fileprivate var bardDex = SelectElement(id: "bardDex", description: nil) fileprivate var bardVit = SelectElement(id: "bardVit", description: nil) fileprivate var bardJobLevel = SelectElement(id: "bardJob", description: "") fileprivate var dancerSkills = SelectElement(id: "dancerSkills", description: "Dancer") fileprivate var dancerSkillLevel = SelectElement(id: "dancerSkillLevel", description: nil) fileprivate var danceLessons = SelectElement(id: "danceLessons", description: "") fileprivate var wandererSkills = SelectElement(id: "wandererSkills", description: "") fileprivate var wandererSkillLevel = SelectElement(id: "wandererSkillLevel", description: nil) fileprivate var voiceLessonsWanderer = SelectElement(id: "voiceLessonsW", description: "") fileprivate var dancerAgi = SelectElement(id: "dancerAgi", description: nil) fileprivate var dancerInt = SelectElement(id: "dancerInt", description: nil) fileprivate var dancerDex = SelectElement(id: "dancerDex", description: nil) fileprivate var dancerLuk = SelectElement(id: "dancerLuk", description: nil) fileprivate var dancerJobLevel = SelectElement(id: "dancerJob", description: "") fileprivate var ensembleSkills = SelectElement(id: "ensembleSkills", description: "Group") fileprivate var bardLevel = SelectElement(id: "bardLevel", description: "") fileprivate var dancerLevel = SelectElement(id: "dancerLevel", description: nil) fileprivate var chorusSkill = SelectElement(id: "chorusSkill", description: "") fileprivate var chorusLevel = SelectElement(id: "chorusLevel", description: nil) fileprivate var performerCount = SelectElement(id: "performerCount", description: "") fileprivate var marionette = CheckboxInputElement(id: "marionetteControl", description: "Marionette") fileprivate var marionetteStr = SelectElement(id: "marionetteStr", description: nil) fileprivate var marionetteAgi = SelectElement(id: "marionetteAgi", description: nil) fileprivate var marionetteVit = SelectElement(id: "marionetteVit", description: nil) fileprivate var marionetteInt = SelectElement(id: "marionetteInt", description: nil) fileprivate var marionetteDex = SelectElement(id: "marionetteDex", description: nil) fileprivate var marionetteLuk = SelectElement(id: "marionetteLuk", description: nil) fileprivate var battleCommand = CheckboxInputElement(id: "guildSkill0", description: "Battle Command") fileprivate var greatLeadership = SelectElement(id: "guildSkill1", description: "Great Leadership") fileprivate var gloriousWounds = SelectElement(id: "guildSkill2", description: "Glorious Wounds") fileprivate var coldHeart = SelectElement(id: "guildSkill3", description: "Cold Heart") fileprivate var sharpGaze = SelectElement(id: "guildSkill4", description: "Sharp Gaze") fileprivate var regeneration = SelectElement(id: "guildSkill5", description: "Regeneration") fileprivate var allStatsPlus20 = CheckboxInputElement(id: "battleChant0", description: "All Stats +20") fileprivate var hpPlus100Percent = CheckboxInputElement(id: "battleChant1", description: "HP +100%") fileprivate var spPlus100Percent = CheckboxInputElement(id: "battleChant2", description: "SP +100%") fileprivate var atkPlus100Percent = CheckboxInputElement(id: "battleChant3", description: "ATK +100%") fileprivate var hitAndFleePlus100Percent = CheckboxInputElement(id: "battleChant4", description: "HIT & FLEE +50") fileprivate var damageReduced50Percent = CheckboxInputElement(id: "battleChant5", description: "Damage Reduced 50%") fileprivate var elementField = SelectElement(name: "eleField", description: nil) fileprivate var elementFieldLevel = SelectElement(name: "eleFieldLvl", description: nil) fileprivate var murdererBonus = SelectElement(name: "murderBonus", description: "Murderer Bonus") fileprivate var improveConcentrationLevel = SelectElement(name: "improveCon", description: "Improve Concentration Lv") fileprivate var selfMindBreaker = SelectElement(name: "mindBreaker", description: "Self Mind Breaker") fileprivate var selfProvoke = SelectElement(name: "provoke", description: "Self Provoke") fileprivate var bsSacrimenti = CheckboxInputElement(name: "bss", description: "BS Sacrimenti") fileprivate var andrenalineRush = SelectElement(name: "adrenalineRush", description: "Andrenaline Rush") fileprivate var weaponPerfection = CheckboxInputElement(name: "weaponPerfection", description: "Weapon Perfection") fileprivate var powerThrust = SelectElement(name: "powerThrust", description: "Power-Thrust") fileprivate var windWalk = SelectElement(name: "windWalker", description: "Wind Walk") fileprivate var magnumBreakBonus = CheckboxInputElement(name: "magnumBreak", description: "Magnum Break Bonus") fileprivate var aloevera = CheckboxInputElement(name: "aloe", description: "Aloevera") fileprivate var resistantSouls = SelectElement(name: "resistantSouls", description: "Resistant Souls") fileprivate var striking = SelectElement(name: "striking", description: "Striking") fileprivate var strikingEndowBonus = SelectElement(name: "strikingEndow", description: "Striking Endow Bonus") fileprivate var odinsPower = SelectElement(name: "odinsPower", description: "Odin's Power") fileprivate var petBonuses = SelectElement(id: "petBonus", description: "Pet Bonuses") fileprivate var tempEffect1 = SelectElement(id: "tempOne", description: "Temp Effect") fileprivate var tempEffect2 = SelectElement(id: "tempTwo", description: "Temp Effect") fileprivate var tempEffect3 = SelectElement(id: "tempThree", description: "Temp Effect") fileprivate var tempEffect4 = SelectElement(id: "tempFour", description: "Temp Effect") fileprivate var advanceFirstSpirit = CheckboxInputElement(id: "firstSpirit", description: "Advance 1st Spirit (Max Stats)") fileprivate var superNoviceMarriageBonus = CheckboxInputElement(id: "noviceMarried", description: "SN Marriage Bonus (Stats + 1)") fileprivate var numberOfEnemies = SelectElement(id: "numEnemies", description: "# of Enemies") fileprivate var quagmire = SelectElement(id: "playerQuaged", description: "Quagmire") fileprivate var agiDown = SelectElement(id: "playerAgiDowned", description: "AGI Down") fileprivate var setCriticalToZero = CheckboxInputElement(id: "playerNoCrit", description: "Set CRIT% to 0") fileprivate var poisoned = CheckboxInputElement(id: "playerPoisoned", description: "Poisoned") fileprivate var cursed = CheckboxInputElement(id: "playerCursed", description: "Cursed") fileprivate var aspdPotions = SelectElement(id: "speedPot", description: "ASPD Potions") fileprivate var strFood = SelectElement(id: "strFood", description: "STR Food") fileprivate var agiFood = SelectElement(id: "agiFood", description: "AGI Food") fileprivate var vitFood = SelectElement(id: "vitFood", description: "VIT Food") fileprivate var intFood = SelectElement(id: "intFood", description: "INT Food") fileprivate var dexFood = SelectElement(id: "dexFood", description: "DEX Food") fileprivate var lukFood = SelectElement(id: "lukFood", description: "LUK Food") fileprivate var vipBuffs = CheckboxInputElement(id: "vipBuff", description: "VIP Buffs (STATS +7)") fileprivate var luckyRiceCake = CheckboxInputElement(id: "luckyRiceCake", description: "Lucky Rice Cake (LUK +21)") fileprivate var sesamePastry = CheckboxInputElement(id: "sesamePastry", description: "Sesame Pastry (HIT +30)") fileprivate var honeyPastry = CheckboxInputElement(id: "honeyPastry", description: "Honey Pastry (FLEE +30)") fileprivate var rainbowCake = CheckboxInputElement(id: "rainbowCake", description: "Rainbow Cake (ATK/MATK +10)") fileprivate var militaryRationB = CheckboxInputElement(id: "militaryRationB", description: "Military Ration B (HIT +33)") fileprivate var militaryRationC = CheckboxInputElement(id: "militaryRationC", description: "Military Ration C (FLEE +33)") fileprivate var tastyPinkRation = CheckboxInputElement(id: "pinkRation", description: "Tasty Pink Ration (ATK +15)") fileprivate var tastyWhiteRation = CheckboxInputElement(id: "whiteRation", description: "Tasty White Ration (MATK +15)") fileprivate var boxOfResentment = CheckboxInputElement(id: "resentment", description: "Box of Resentment (ATK +20)") fileprivate var boxOfDrowsiness = CheckboxInputElement(id: "drowsiness", description: "Box of Drowsiness (MATK +20)") fileprivate var fireproofPotion = CheckboxInputElement(id: "fireproof", description: "Fireproof Potion") fileprivate var coldproofPotion = CheckboxInputElement(id: "coldproof", description: "Coldproof Potion") fileprivate var thunderproofPotion = CheckboxInputElement(id: "thunderproof", description: "Thunderproof Potion") fileprivate var earthproofPotion = CheckboxInputElement(id: "earthproof", description: "Earthproof Potion") fileprivate var celermineJuice = CheckboxInputElement(id: "celermineJuice", description: "Celermine Juice (ASPD +10%)") fileprivate var vitata500 = CheckboxInputElement(id: "vitataFiveHundred", description: "Vitata500 (SP +5%)") fileprivate var increaseHpPotion = SelectElement(id: "increaseHpPotion", description: "Increase HP Potion") fileprivate var increaseSpPotion = SelectElement(id: "increaseSpPotion", description: "Increase SP Potion") fileprivate var abrasive = CheckboxInputElement(id: "abrasive", description: "Abrasive (Crit +30)") fileprivate var runeStrawberryCake = CheckboxInputElement(id: "runeStrawberry", description: "Rune Strawberry Cake (ATK/MATK +5)") fileprivate var schwartzwaldPineJubilee = CheckboxInputElement(id: "pineJubilee", description: "Schwartzwald Pine Jubilee (HIT +10/FLEE +20)") fileprivate var arunafeltzDesertSandwich = CheckboxInputElement(id: "desertSandwich", description: "Arunafeltz Desert Sandwich (CRIT +7)") fileprivate var bucheDeNoel = CheckboxInputElement(id: "boucheDeNoel", description: "Buche de Noel (HIT +3/CRIT +7)") fileprivate var distilledFightingSpirit = CheckboxInputElement(id: "fightingSpirit", description: "Distilled Fighting Spirit (ATK +30)") fileprivate var durian = CheckboxInputElement(id: "durian", description: "Durian (ATK/MATK +10)") fileprivate var guaranaCandy = CheckboxInputElement(id: "guaranaCandy", description: "Guarana Candy (AGI LVL 5/ASPD +10%)") fileprivate var magicScrollOrYggdrasilLeafOrEtc = CheckboxInputElement(id: "castScrolls", description: "Magic Scroll/Yggdrasil Leaf/Etc") fileprivate var holyElementalScroll = CheckboxInputElement(id: "holyEl", description: "Holy Elemental Scroll") fileprivate var undeadElementalScroll = CheckboxInputElement(id: "undeadEl", description: "Undead Elemental Scroll") fileprivate(set) var statuses: ElementSection fileprivate(set) var properties: ElementSection fileprivate(set) var mainWeapon: ElementSection fileprivate(set) var armorSection: ElementSection fileprivate(set) var additionalEnchantsSection: ElementSection fileprivate(set) var acolyteSkillsSection: ElementSection fileprivate(set) var performerSkillsSection: ElementSection fileprivate(set) var guildSkillsSection: ElementSection fileprivate(set) var battleChantEffectsSection: ElementSection fileprivate(set) var otherBuffsSection: ElementSection fileprivate(set) var miscellaneousEffectsSection: ElementSection fileprivate(set) var items: ElementSection fileprivate var passiveSkillCount: Int { let script = "var job = n_A_JOB; var skillCount = 0; for ( skillCount; JobSkillPassOBJ[job][skillCount] !== 999; skillCount++ ); skillCount;" return Int(context.evaluateScript(script).toInt32()) } fileprivate var _passiveSkillSection: ElementSection? = nil var passiveSkillSection: ElementSection { var passiveSkills = [AnyObject]() if _passiveSkillSection == nil { for i in 0..<passiveSkillCount { let skillName = context.evaluateScript("document.getElementById('P_Skill\(i)').textContent").toString() let passiveSkill = SelectElement(name: "A_Skill\(i)", description: skillName) passiveSkills.append(passiveSkill) } } return ElementSection(title: "Self Passive/Duration Skills", elements: passiveSkills) } var webView = UIWebView() fileprivate(set) var loading = true fileprivate var observer: NSObjectProtocol! override init() { statuses = ElementSection(title: "Stats", elements: [ job, [baseLevel, jobLevel] as AnyObject, [str, strPlus, agi, agiPlus] as AnyObject, [vit, vitPlus, int, intPlus] as AnyObject, [dex, dexPlus, luk, lukPlus] as AnyObject ]) properties = ElementSection(title: "Properties", elements: [ [maxHp, maxSp] as AnyObject, [hit, flee] as AnyObject, [perfectDodge, critical] as AnyObject, [hpRegen, spRegen] as AnyObject, atk, matk, def, mdef, aspd, statusPoint ]) mainWeapon = ElementSection(title: "Main Weapon", elements: [ mainWeaponType, [mainWeaponRefining, mainWeaponName] as AnyObject, mainWeaponCardShortcuts, mainWeaponCard1, mainWeaponCard2, mainWeaponCard3, mainWeaponCard4, mainWeaponElement, mainWeaponProjectile ]) armorSection = ElementSection(title: "Armor", elements: [ armorCardShortcuts, [upperHeadgearRefining, upperHeadgear] as AnyObject, [upperHeadgearEnchant, upperHeadgearCard] as AnyObject, middleHeadgear, middleHeadgearCard, lowerHeadgear, [armorRefining, armor] as AnyObject, [armorEnchant, armorCard] as AnyObject, [shieldRefining, shield] as AnyObject, shieldCard, [garmentRefining, garment] as AnyObject, garmentCard, [footgearRefining, footgear] as AnyObject, footgearCard, accessory1, accessory1Card, accessory2, accessory2Card ]) additionalEnchantsSection = ElementSection(title: "Additional Enchants", elements: [ [strEnchant, agiEnchant] as AnyObject, [vitEnchant, intEnchant] as AnyObject, [dexEnchant, lukEnchant] as AnyObject, [atkEnchant, atkPercentEnchant] as AnyObject, [matkEnchant, matkPercentEnchant] as AnyObject, [hitEnchant, fleeEnchant] as AnyObject, [perfectDodgeEnchant, criticalEnchant] as AnyObject, [maxHpEnchant, maxSpEnchant] as AnyObject, [maxHpPercentEnchant, maxSpPercentEnchant] as AnyObject, [defEnchant, mdefEnchant] as AnyObject, [aspdEnchant, aspdPercentEnchant] as AnyObject, rangedDamagePercentEnchant, damageReductionPercentEnchant, castTimePercentEnchant ]) acolyteSkillsSection = ElementSection(title: "Acolyte Skills", elements: [ blessing, increaseAgi, angelus, impositioManus, suffragium, gloria, assumptio, spiritSpheres, clementia, cantoCandidus, expiatio, sacrament, laudaAgnus, laudaRamus, gentleTouchConvert, gentleTouchRevitalize, [suraStr, suraAgi] as AnyObject, [suraVit, suraInt, suraDex] as AnyObject ]) performerSkillsSection = ElementSection(title: "Performer Skills", elements: [ [bardSkills, bardSkillLevel] as AnyObject, musicLessons, [maestroSkills, maestroSkillLevel] as AnyObject, voiceLessonsMaestro, [bardAgi, bardInt, bardDex, bardVit] as AnyObject, bardJobLevel, [dancerSkills, dancerSkillLevel] as AnyObject, danceLessons, [wandererSkills, wandererSkillLevel] as AnyObject, voiceLessonsWanderer, [dancerAgi, dancerInt, dancerDex, dancerLuk] as AnyObject, dancerJobLevel, ensembleSkills, [bardLevel, dancerLevel] as AnyObject, [chorusSkill, chorusLevel] as AnyObject, performerCount, marionette, [marionetteStr, marionetteAgi, marionetteVit] as AnyObject, [marionetteInt, marionetteDex, marionetteLuk] as AnyObject ]) guildSkillsSection = ElementSection(title: "Guild Skills", elements: [ battleCommand, greatLeadership, gloriousWounds, coldHeart, sharpGaze, regeneration ]) battleChantEffectsSection = ElementSection(title: "Battle Chant Effects", elements: [ allStatsPlus20, hpPlus100Percent, spPlus100Percent, atkPlus100Percent, hitAndFleePlus100Percent, damageReduced50Percent ]) otherBuffsSection = ElementSection(title: "Other Buffs", elements: [ [elementField, elementFieldLevel] as AnyObject, murdererBonus, improveConcentrationLevel, selfMindBreaker, selfProvoke, bsSacrimenti, andrenalineRush, weaponPerfection, powerThrust, windWalk, magnumBreakBonus, aloevera, resistantSouls, striking, strikingEndowBonus, odinsPower, ]) miscellaneousEffectsSection = ElementSection(title: "Miscellaneous Effects", elements: [ petBonuses, tempEffect1, tempEffect2, tempEffect3, tempEffect4, advanceFirstSpirit, superNoviceMarriageBonus, numberOfEnemies, quagmire, agiDown, setCriticalToZero, poisoned, cursed, ]) let itemElements1 = [ aspdPotions, strFood, agiFood, vitFood, intFood, dexFood, lukFood, vipBuffs, luckyRiceCake, sesamePastry, honeyPastry, rainbowCake, militaryRationB, militaryRationC, tastyPinkRation, tastyWhiteRation, boxOfResentment, boxOfDrowsiness ] as [AnyObject] let itemElements2 = [ fireproofPotion, coldproofPotion, thunderproofPotion, earthproofPotion, celermineJuice, vitata500, increaseHpPotion, increaseSpPotion, abrasive, runeStrawberryCake, schwartzwaldPineJubilee, arunafeltzDesertSandwich, bucheDeNoel, distilledFightingSpirit, durian, guaranaCandy, magicScrollOrYggdrasilLeafOrEtc, holyElementalScroll, undeadElementalScroll ] as [AnyObject] items = ElementSection(title: "Items", elements: itemElements1 + itemElements2) super.init() addObserver() } deinit { removeObserver() } func addObserver() { observer = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: StatusCalculatorValueDidChangeNotification), object: nil, queue: OperationQueue.main) { [weak self] (note) -> Void in self?.clearCachedValues() } } func removeObserver() { NotificationCenter.default.removeObserver(observer) } func clearCachedValues() { _passiveSkillSection = nil } } extension StatusCalculator { func load() { let path = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "iW Stat Simulator/calc.irowiki.org")! let url = URL(fileURLWithPath: path) webView.delegate = self webView.loadRequest(URLRequest(url: url)) } func cancelLoad() { webView.stopLoading() } } extension StatusCalculator: UIWebViewDelegate { func webViewDidFinishLoad(_ webView: UIWebView) { loading = false www = webView context = webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext context.exceptionHandler = { context, exception in print("JS Error: \(String(describing: exception))") } automaticallyAdjustsBaseLevel.checked = false delegate?.statusCalculatorDidFinishLoad?(self) } func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { loading = false delegate?.statusCalculator?(self, didFailLoadWithError: error as NSError?) } }
8b33a8e6f7c653957815350dcfe3133c
50.230189
218
0.661412
false
false
false
false
luinily/hOme
refs/heads/master
hOme/Model/ScheduleCommand.swift
mit
1
// // ScheduleCommand.swift // IRKitApp // // Created by Coldefy Yoann on 2016/01/17. // Copyright © 2016年 YoannColdefy. All rights reserved. // import Foundation import CloudKit class ScheduleCommand: CloudKitObject { private var _commandInternalName: String private var _time: (hour: Int, minute: Int) = (0, 0) private var _days = Set<Weekday>() private var _isOneTimeCommand = false private var _isActive = true private var _currentCKRecordName: String? private var _getCommand: (_ commandInternalName: String) -> CommandProtocol? var command: CommandProtocol? { get {return _getCommand(_commandInternalName)} } var isActive: Bool { get {return _isActive} set {_isActive = newValue} } var days: Set<Weekday> {return _days} var hour: Int {return _time.hour} var minute: Int {return _time.minute} var timeString: String {return String(hour) + ":" + String(minute)} var isOneTimeCommand: Bool {return _isOneTimeCommand} init (commandInternalName: String, days: Set<Weekday>, time:(hour: Int, minute: Int), getCommand: @escaping (_ commandInternalName: String) -> CommandProtocol?) { _commandInternalName = commandInternalName _time = time _days = days _getCommand = getCommand updateCloudKit() } init (oneTimeCommandInternalName: String, day: Weekday, time: (hour: Int, minute: Int), getCommand: @escaping (_ commandInternalName: String) -> CommandProtocol?) { _commandInternalName = oneTimeCommandInternalName _time = time _days = [day] _getCommand = getCommand _isOneTimeCommand = true } func execute() { if _isActive { command?.execute() if _isOneTimeCommand { _isActive = false } } } private func setDays(_ days: [String]) { for day in days { if let day = stringToDay(day) { _days.formUnion([day]) } } } private func stringToDay(_ day: String) -> Weekday? { switch day { case "Monday": return Weekday.monday case "Tuesday": return Weekday.tuesday case "Wednesday": return Weekday.wednesday case "Thursday": return Weekday.thursday case "Friday": return Weekday.friday case "Saturday": return Weekday.saturday case "Sunday": return Weekday.sunday default: print("weekday not found") return nil } } private func makeDaysStringArray() -> [String] { var result = [String]() if _days.contains(.monday) { result.append("Monday") } if _days.contains(.tuesday) { result.append("Tuesday") } if _days.contains(.wednesday) { result.append("Wednesday") } if _days.contains(.thursday) { result.append("Thursday") } if _days.contains(.friday) { result.append("Friday") } if _days.contains(.saturday) { result.append("Saturday") } if _days.contains(.sunday) { result.append("Sunday") } return result } func getCommand() -> CommandProtocol? { return _getCommand(_commandInternalName) } //MARK: - CloudKitObject convenience init (ckRecord: CKRecord, getCommand: @escaping (_ commandInternalName: String) -> CommandProtocol?) throws { self.init(oneTimeCommandInternalName: "", day: .monday, time: (hour: 0, minute: 0), getCommand: getCommand) _currentCKRecordName = ckRecord.recordID.recordName guard let commandName = ckRecord["commandName"] as? String else { throw CommandClassError.noDeviceNameInCKRecord } guard let days = ckRecord["days"] as? [String] else { throw CommandClassError.noDeviceNameInCKRecord } guard let hour = ckRecord["hour"] as? Int else { throw CommandClassError.noDeviceNameInCKRecord } guard let minute = ckRecord["minute"] as? Int else { throw CommandClassError.noDeviceNameInCKRecord } self._commandInternalName = commandName self.setDays(days) self._time.hour = hour self._time.minute = minute } func getNewCKRecordName() -> String { if let command = command { return "ScheduleCommand:" + command.internalName + ":" + String(_time.hour) + ":" + String(_time.minute) } else { return "" } } func getCurrentCKRecordName() -> String? { return _currentCKRecordName } func getCKRecordType() -> String { return "ScheduleCommand" } func setUpCKRecord(_ record: CKRecord) { record["commandName"] = _commandInternalName as CKRecordValue? record["days"] = makeDaysStringArray() as CKRecordValue? record["hour"] = _time.hour as CKRecordValue? record["minute"] = _time.minute as CKRecordValue? } func updateCloudKit() { CloudKitHelper.sharedHelper.export(self) _currentCKRecordName = getNewCKRecordName() } }
92031136c2dc76905120e724cb6fda22
25.319767
165
0.695604
false
false
false
false
joshpar/Lyrebird
refs/heads/master
LyrebirdSynth/Lyrebird/LyrebirdTimer.swift
artistic-2.0
1
// // LyrebirdTimer.swift // Lyrebird // // Created by Joshua Parmenter on 6/5/16. // Copyright © 2016 Op133Studios. All rights reserved. // /** A function wrapper for queued delays - parameter delay: in Seconds - parameter queue: the dispatch queue to schedule on - parameter closure: the block to evaluate - Returns: nothing */ func delay(delay: Double, queue: DispatchQueue, closure: @escaping ()->()) { queue.asyncAfter( deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure ) } /** The block structure used for LyrebirdTimer's repeated function. Well, crap, this needs to be clock independant - so it can be scheduled on RT and NRT fashions. crap crap crap - parameter curTime: The current time, in seconds, since execution of the timer began - parameter inc: The number of times (0 based) that the timer has executed this block - Returns: Optional LyrebirdFloat in seconds. If the block returns a value greater than 0.0, execution of the block is scheduled for repeition */ public typealias LyrebirdTimerBlock = (_ curTime: LyrebirdFloat, _ inc: LyrebirdInt) -> LyrebirdFloat? /** The block structure used for LyrebirdTimer's finalizer function. This block is fired once and only once as the LyrebirdTimerBlock either returns nil or <= 0.0 for repeptiion, or when the block is removed - parameter curTime: The current time, in seconds, since execution of the timer began - Returns: Nothing */ public typealias LyrebirdTimerFinalizerBlock = (_ curTime: LyrebirdFloat) -> Void /** The base class for handling timed and repeated execution of a block */ public final class LyrebirdTimer { /// --- /// the closure the execute every time the timer runs. If the optional return is a float > 0.0, repeition is scheduled for that time in seconds /// public var block: LyrebirdTimerBlock? = nil /// --- /// a closure to be executed when no repetitions are scheduled OR if the block has been removed from this instance of a LyrebirdTimer /// public var finalizerBlock: LyrebirdTimerFinalizerBlock? = nil /// --- /// The time in seconds to delay the start of the timer execution. /// /// Note: This time is NOT included in the curTime value passed in to a LyrebirdTimerBlock public var delayStartTime: LyrebirdFloat = 0.0 /// --- /// The internal start time for the execution of the first iteration of the block /// fileprivate var startTime: LyrebirdFloat = -1.0 /// --- /// The name of this instance's thread that is visible in stack traces and debugging /// fileprivate var idString: String = "LyrebirdTimer" /// --- /// The queue for this thread. /// /// Note: LyrebirdTimer threads are concurrent. fileprivate var queue: DispatchQueue /// --- /// Internal keeper for the number of iterations of the block that have been performed. /// /// Note: The incrementer is zero based fileprivate var inc: LyrebirdInt = 0 /// --- /// A time stamp to compare to actual execution time. Differences between this and actual time will be removed during scheduling of the next repeition /// fileprivate var nextExpectedTime: LyrebirdFloat = 0.0 /** Convenience init that uses a 0.0 delay time and a default idString - parameter none: */ public convenience init(){ self.init(delayStartTime: 0.0, idString: "LyrebirdTimer") } /** Custom init that uses a given delay time and a custom idString - parameter delayStartTime: in seconds, the initial amount of time to wait before performing blocks - parameter idString: a custom identifier that helps find a thread in debugging tools or stack traces Note: the delayStartTime is NOT included in the curTime values passed into the blocks that are run. curTime starts at 0.0 */ public required init(delayStartTime: LyrebirdFloat, idString: String){ self.idString = idString self.delayStartTime = delayStartTime queue = DispatchQueue(label: self.idString, attributes: DispatchQueue.Attributes.concurrent) let q: DispatchQueue = DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.low) //queue.setTarget(queue: q) } /** Starts execution of the timer. The first block will be performed after any delayStartTime - parameter none: */ public final func run() { delay(delay: self.delayStartTime, queue: queue) { if (self.startTime < 0.0) { self.startTime = Date.timeIntervalSinceReferenceDate self.nextExpectedTime = 0.0 } self.next() } } /** The internal method that the internal thread fires over again. If a block returns a float greater than 0.0, the thread is scheduled for another execution. Because of execution time of the block and other timing considerations, the next function also tries to figure out how much error there is between the expected run time of a block, and compensates for it on the next iteration. - parameter none: */ fileprivate final func next() { let curTime = Date.timeIntervalSinceReferenceDate - self.startTime let error = self.nextExpectedTime - curTime if let block = block { let nextTime: LyrebirdFloat? = block(curTime, self.inc) if let nextTime = nextTime { self.inc = self.inc + 1 self.nextExpectedTime = self.nextExpectedTime + nextTime let now = Date.timeIntervalSinceReferenceDate - self.startTime let delayTime = (nextTime - (now - curTime)) + error delay(delay: delayTime, queue: queue, closure: { self.next() }) } else { finalizerBlock?(curTime) } } else { finalizerBlock?(0.0) } } }
fccee7fe43e38fc47f88212cf2e3e078
35.8
386
0.666667
false
false
false
false
yzhou65/DSWeibo
refs/heads/master
DSWeibo/Classes/Home/Popover/PopoverPresentationController.swift
apache-2.0
1
// // PopoverPresentationController.swift // DSWeibo // // Created by xiaomage on 15/9/9. // Copyright © 2015年 小码哥. All rights reserved. // import UIKit //UIPresentationController是ios8以后才能使用的 class PopoverPresentationController: UIPresentationController { ///定义属性保存菜单的大小 var presentFrame = CGRectZero /** 初始化方法, 用于创建负责转场动画的对象 :param: presentedViewController 被展现的控制器 :param: presentingViewController 发起的控制器, Xocde6是nil, Xcode7是野指针 :returns: 负责转场动画的对象 */ override init(presentedViewController: UIViewController, presentingViewController: UIViewController) { super.init(presentedViewController: presentedViewController, presentingViewController: presentingViewController) } /** 即将布局转场子视图时调用 */ override func containerViewWillLayoutSubviews() { // 1.修改弹出视图的大小 // containerView; // 容器视图 // presentedView() // 被展现的视图 if presentFrame == CGRectZero { presentedView()?.frame = CGRect(x: 100, y: 56, width: 200, height: 200) } else { presentedView()?.frame = presentFrame } // 2.在容器视图上添加一个蒙版, 插入到展现视图的下面 // 因为展现视图和蒙版都在都一个视图上, 而后添加的会盖住先添加的 // containerView?.addSubview(coverView) //后添加的会盖住先添加的,所以要insert containerView?.insertSubview(coverView, atIndex: 0) } // MARK: - 懒加载 private lazy var coverView: UIView = { // 1.创建view let view = UIView() view.backgroundColor = UIColor(white: 0.0, alpha: 0.2) view.frame = UIScreen.mainScreen().bounds // 2.添加监听 let tap = UITapGestureRecognizer(target: self, action: #selector(close)) view.addGestureRecognizer(tap) return view }() func close(){ // presentedViewController拿到当前弹出的控制器 presentedViewController.dismissViewControllerAnimated(true, completion: nil) } }
1ef24cdc6ae464d265bd6cb050482ad8
27.26087
120
0.641026
false
false
false
false
dclelland/AudioKit
refs/heads/master
AudioKit/OSX/AudioKit/AudioKit for OSX.playground/Sources/TouchKeyView.swift
mit
1
// // TouchKeyView.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2015 Aurelius Prochazka. All rights reserved. // import Cocoa public class TouchKeyView: NSButton { public var letters = "" public var number = "1" public init(numeral: String = "1", text: String = "") { super.init(frame: CGRect(x:0, y:0, width:100, height: 100)) letters = text number = numeral } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func drawRect(rect: CGRect) { drawKey(text: letters, numeral: number) } func drawKey(text text: String = "A B C", numeral: String = "1") { //// Gradient Declarations let gradient = NSGradient(startingColor: NSColor.darkGrayColor(), endingColor: NSColor.lightGrayColor())! //// Rectangle Drawing let rectanglePath = NSBezierPath(roundedRect: NSMakeRect(0, 0, 100, 100), xRadius: 20, yRadius: 20) gradient.drawInBezierPath(rectanglePath, angle: -90) //// Letters Drawing let lettersRect = NSMakeRect(0, 73, 100, 21) let lettersStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle lettersStyle.alignment = .Center let lettersFontAttributes = [NSFontAttributeName: NSFont(name: "HelveticaNeue", size: 25)!, NSForegroundColorAttributeName: NSColor.whiteColor(), NSParagraphStyleAttributeName: lettersStyle] let lettersTextHeight: CGFloat = NSString(string: text).boundingRectWithSize(NSMakeSize(lettersRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: lettersFontAttributes).size.height let lettersTextRect: NSRect = NSMakeRect(lettersRect.minX, lettersRect.minY + (lettersRect.height - lettersTextHeight) / 2, lettersRect.width, lettersTextHeight) NSGraphicsContext.saveGraphicsState() NSRectClip(lettersRect) NSString(string: text).drawInRect(NSOffsetRect(lettersTextRect, 0, 0), withAttributes: lettersFontAttributes) NSGraphicsContext.restoreGraphicsState() //// Number Drawing let numberRect = NSMakeRect(0, 0, 100, 73) let numberStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle numberStyle.alignment = .Center let numberFontAttributes = [NSFontAttributeName: NSFont(name: "HelveticaNeue", size: 60)!, NSForegroundColorAttributeName: NSColor.whiteColor(), NSParagraphStyleAttributeName: numberStyle] let numberTextHeight: CGFloat = NSString(string: numeral).boundingRectWithSize(NSMakeSize(numberRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: numberFontAttributes).size.height let numberTextRect: NSRect = NSMakeRect(numberRect.minX, numberRect.minY + (numberRect.height - numberTextHeight) / 2, numberRect.width, numberTextHeight) NSGraphicsContext.saveGraphicsState() NSRectClip(numberRect) NSString(string: numeral).drawInRect(NSOffsetRect(numberTextRect, 0, 0), withAttributes: numberFontAttributes) NSGraphicsContext.restoreGraphicsState() } } extension AKPlaygroundView { public func addTouchKey( num: String, text: String, action: Selector) -> TouchKeyView { let newButton = TouchKeyView(numeral: num, text: text) // Line up multiple buttons in a row if let button = lastButton { newButton.frame.origin.x += button.frame.origin.x + button.frame.width + 10 yPosition -= horizontalSpacing } horizontalSpacing = Int((newButton.frame.height)) + 10 yPosition += horizontalSpacing newButton.frame.origin.y = self.bounds.height - CGFloat(yPosition) newButton.target = self newButton.action = action self.addSubview(newButton) lastButton = newButton return newButton } }
1d0411316b0bda3d662c0806643109b7
44.467391
236
0.683959
false
false
false
false
migueloruiz/la-gas-app-swift
refs/heads/master
lasgasmx/DefaultCell.swift
mit
1
// // DefaultCell.swift // lasgasmx // // Created by Desarrollo on 3/29/17. // Copyright © 2017 migueloruiz. All rights reserved. // import UIKit class DefaultHeader: DefaultCell { override var datasourceItem: Any? { didSet { if datasourceItem == nil { label.text = "This is your default header" } } } override func setupViews() { super.setupViews() label.text = "Header Cell" label.textAlignment = .center } } class DefaultFooter: DefaultCell { override var datasourceItem: Any? { didSet { if datasourceItem == nil { label.text = "This is your default footer" } } } override func setupViews() { super.setupViews() label.text = "Footer Cell" label.textAlignment = .center } } class DefaultCell: CollectionDatasourceCell { override var datasourceItem: Any? { didSet { if let text = datasourceItem as? String { label.text = text } else { label.text = datasourceItem.debugDescription } } } let label = UILabel() override func setupViews() { super.setupViews() addSubview(label) label.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 0, leftConstant: 10, bottomConstant: 0, rightConstant: 10, widthConstant: 0, heightConstant: 0) } }
198d6f5e4558bef7edac5c7dbed6db00
22.769231
205
0.565696
false
false
false
false
moysklad/ios-remap-sdk
refs/heads/master
Sources/MoyskladiOSRemapSDK/Network/StatisticsParameters.swift
mit
1
// // StatisticsParameters.swift // MoyskladiOSRemapSDK // // Created by Nikolay on 31.07.17. // Copyright © 2017 Andrey Parshakov. All rights reserved. // import Foundation public enum StatisticsIntervalType: String { case hour case day case month } public struct StatisticsMoment: UrlParameter, Equatable { public let from: Date public let to: Date public var urlParameters: [String : String] { return ["momentFrom": from.toCurrentLocaleLongDate(), "momentTo": to.toCurrentLocaleLongDate()] } public init(from: Date, to: Date) { self.from = from self.to = to } public static func == (lhs: StatisticsMoment, rhs: StatisticsMoment) -> Bool { return lhs.from == rhs.from && lhs.to == rhs.to } } public struct StatisticsIntervalArgument: UrlParameter { public let type: StatisticsIntervalType public init(type: StatisticsIntervalType) { self.type = type } public var urlParameters: [String : String] { return ["interval": type.rawValue] } } public struct StatisticsRerailStoreArgument: UrlParameter { public let value: MSMeta public init(value: MSMeta) { self.value = value } public var urlParameters: [String : String] { return ["retailStore": value.href] } }
2613832d43c7add4b1a3f9b23e1d3868
23.035714
103
0.650074
false
false
false
false
DrGo/LearningSwift
refs/heads/master
PLAYGROUNDS/LSB_021_GlobalFunctions.playground/section-2.swift
gpl-3.0
2
import UIKit /* // Global Functions /===================================*/ advance(0,0) // <-- Command click this function to see the header file for global functions. /*------------------------------------/ // advance (Strideable) // // with: successor and predecessor // See also: Strings /------------------------------------*/ 2 + 2 advance(5, 2) 5.successor() 5.predecessor() /*---------------------------------/ // abs /---------------------------------*/ abs(-210) /*---------------------------------/ // assert // // Suggested Reading: // https://developer.apple.com/swift/blog/?id=4 // https://developer.apple.com/swift/blog/?id=15 /---------------------------------*/ assert(true, "BOOM!") assert(1 + 1000 > 1000, "BOOM!") /*---------------------------------/ // distance /---------------------------------*/ distance(1, 3) /*---------------------------------/ // count /---------------------------------*/ count(1...3) count(1..<5) count([1, 2, 3]) count("word") count(["a":1, "b":2]) /*---------------------------------/ // isEmpty /---------------------------------*/ isEmpty([Int]()) isEmpty([1,2]) isEmpty("") isEmpty("word") isEmpty([String:Int]()) isEmpty(["a":1, "b":2]) /*---------------------------------/ // last /---------------------------------*/ last([Int]()) last([1,2,3])! last("") last("word")! //last([String:Int]()) // No longer supported //last(["a":1, "b":2])!.0 // No longer supported //last(["a":1, "b":2])!.1 // No longer supported /*---------------------------------/ // max /---------------------------------*/ max(1,30,5) max(3.14, 22/7, 1.0) max("w", "o", "r", "d") /*---------------------------------/ // maxElement /---------------------------------*/ maxElement([1,30,5]) maxElement([3.14, 22/7, 1.0]) maxElement("word") maxElement(1...100) /*---------------------------------/ // min /---------------------------------*/ min(1, 30, 5) min(3.14, 22/7, 1.0) min("w", "o", "r", "d") /*---------------------------------/ // minElement /---------------------------------*/ minElement([1,30,5]) minElement([3.14, 22/7, 1.0]) minElement("word") minElement(1...100) /*---------------------------------/ // print /---------------------------------*/ print(1) print(3.14) print("word") print([1,2,3]) print(["a":1, "b":2]) /*---------------------------------/ // println /---------------------------------*/ println(1) println(3.14) println("word") println([1,2,3]) println(["a":1, "b":2]) /*---------------------------------/ // removeAll /---------------------------------*/ var v = [1,2,3] removeAll(&v, keepCapacity: true) v v = [1,2,3] removeAll(&v) v var s = "word" removeAll(&s, keepCapacity: true) s s = "word" removeAll(&s) s /*---------------------------------/ // removeAtIndex /---------------------------------*/ v = [1,2,3] removeAtIndex(&v, 1) v /*---------------------------------/ // removeLast /---------------------------------*/ v = [1, 2, 3] removeLast(&v) v s = "word" removeLast(&s) s /*---------------------------------/ // removeRange /---------------------------------*/ v = [1, 2, 3, 4, 5] removeRange(&v, 1...3) v /*---------------------------------/ // reverse /---------------------------------*/ v = [1, 2, 3] reverse(v) v /*---------------------------------/ // sort /---------------------------------*/ v = [10, 2, 5, 3, 200, 30, 2] sort(&v) v v = [10, 2, 5, 3, 200, 30, 2] sort(&v, { (a, b) -> Bool in a > b }) v v = [10, 2, 5, 3, 200, 30, 2] sort(&v) { $0 > $1 } v /*---------------------------------/ // sorted /---------------------------------*/ v = [10, 2, 5, 3, 200, 30, 2] sorted(v) v v = [10, 2, 5, 3, 200, 30, 2] sorted(v, { (a, b) -> Bool in b < a }) v v = [10, 2, 5, 3, 200, 30, 2] let newV = sorted(v) { $1 < $0 } newV v /*---------------------------------/ // split /---------------------------------*/ v = Array(1...10) split(v, maxSplit: 3, allowEmptySlices: true, isSeparator: {$0 == 5}) split(v, maxSplit: 3, allowEmptySlices: true) {$0 == 5} split(v) {$0 == 5} // This doesn't work though //split(v, { (x) -> Bool in // x == 5 //}) var aryOfIntArys = split(v) { $0 == 5 } aryOfIntArys v = Array(1...10) aryOfIntArys = split(v, maxSplit: 2, allowEmptySlices: true) { $0 % 2 == 0} aryOfIntArys v = Array(1...10) aryOfIntArys = split(v, maxSplit: 5, allowEmptySlices: true) { $0 < 3 || $0 % 2 == 0} aryOfIntArys v = Array(1...10) aryOfIntArys = split(v, maxSplit: 5, allowEmptySlices: false) { $0 < 3 || $0 % 2 == 0} aryOfIntArys s = "The quick brown fox jumped." //var words = split(s, { $0 == " " }, maxSplit: 3, allowEmptySlices: true) //words //words = split(s, { $0 == " " }) //words /*---------------------------------/ // swap /---------------------------------*/ var a = "one" var b = "two" swap(&a, &b) a b var ia = 1 var ib = 2 swap(&ia, &ib) ia ib /*---------------------------------/ // toString /---------------------------------*/ toString(a) toString(ia) struct Rect: Printable { var x, y, width, height: Double init(x: Double, y: Double, width: Double, height: Double) { self.x = x self.y = y self.width = width self.height = height } var description: String { return "Rect[x:\(x), y:\(y), width:\(width), height:\(height)]" } } let r = Rect(x: 0, y: 10, width: 20, height: 40) // This currently doesn't work in Playgrounds // http://stackoverflow.com/questions/24068506/how-can-i-change-the-textual-representation-displayed-for-a-type-in-swift toString(r) "\(r)" // should appear like this: r.description /*---------------------------------/ // dropFirst // on a Sliceable /---------------------------------*/ var animals = ["dog", "cat", "swan", "meerkat"] dropFirst(animals) /*---------------------------------/ // dropLast // on a Sliceable /---------------------------------*/ dropLast(animals) /*---------------------------------/ // first (optional) // on a Collection /---------------------------------*/ first(animals)! /*---------------------------------/ // last (optional) // on a Collection /---------------------------------*/ last(animals)! /*---------------------------------/ // prefix // on a Sliceable /---------------------------------*/ prefix(animals, 2) /*---------------------------------/ // suffix // on a Sliceable /---------------------------------*/ suffix(animals, 2) /*---------------------------------/ // reversed // on a Collection /---------------------------------*/ let reversedAnimals = reverse(animals) reversedAnimals animals /*---------------------------------/ // Backwards String // Combine String -> [Char] . reverse -> String /---------------------------------*/ let helloThere = "hello there" String(reverse(helloThere))
b90d7e2eb01db65beda2cb27b013345b
17.326975
120
0.3876
false
false
false
false
jm-schaeffer/JMWebImageView
refs/heads/master
JMWebImageView/JMWebImageDownloaderManager.swift
mit
1
// // WebImageDownloaderManager.swift // JMWebImageView // // Copyright (c) 2016 J.M. Schaeffer // // 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 ImageIO private final class WebImageDownloader { let url: NSURL let useCache: Bool let cacheDuration: NSTimeInterval let monitorProgress: Bool // Key: desired max pixel size (the max of the desired width and desired height) var completionsBySize: [CGFloat: [String: (error: NSError?, image: UIImage?, progress: Float?) -> Void]] = [:] var maxSize: CGFloat = 0.0 var images: [CGFloat: UIImage] = [:] weak var task: NSURLSessionDownloadTask? init(url: NSURL, useCache: Bool, cacheDuration: NSTimeInterval, monitorProgress: Bool) { self.url = url self.useCache = useCache self.cacheDuration = cacheDuration self.monitorProgress = monitorProgress } deinit { task?.cancel() } func register(completion: (error: NSError?, image: UIImage?, progress: Float?) -> Void, key: String, size: CGFloat? = nil) { let size = size ?? .max if completionsBySize[size] != nil { // completions is passed by copy so we need to use its reference completionsBySize[size]?[key] = completion } else { completionsBySize[size] = [key: completion] } } func unregister(key: String) { for (size, completions) in completionsBySize.reverse() { for currentKey in completions.keys.reverse() { if key == currentKey { // completions is passed by copy so we need to directly use its reference completionsBySize[size]?[key] = nil if completionsBySize[size]?.isEmpty == true { completionsBySize[size] = nil } } } } if completionsBySize.isEmpty { task?.cancel() } } func download(session: NSURLSession) { // We should think of a way to display the status bar network activity indicator // UIApplication.sharedApplication().networkActivityIndicatorVisible = true let request = NSURLRequest(URL: url) let task = session.downloadTaskWithRequest(request) self.task = task task.resume() } func didCompleteWithError(error: NSError?) { dispatch_async(dispatch_get_main_queue()) { for (size, completions) in self.completionsBySize { let image = self.images[min(self.maxSize, size)] completions.forEach({ $0.1(error: error, image: image, progress: nil) }) } // UIApplication.sharedApplication().networkActivityIndicatorVisible = false } } func didFinishDownloadingToURL(location: NSURL) { // CGImageSourceCreateWithURL cannot be used directly on 'location' because the file is ephemeral var source: CGImageSourceRef? if useCache { if let url = WebImageCacheManager.cacheImageOnDiskFromLocation(location, url: url, cacheDuration: cacheDuration) { source = CGImageSourceCreateWithURL(url, nil) // However after moving the file we can use its new URL } } else if let data = NSData(contentsOfURL: location) { source = CGImageSourceCreateWithData(data, nil) } if let source = source, dictionary = CGImageSourceCopyPropertiesAtIndex(source, 0, nil), properties = dictionary as NSDictionary as? [NSString: NSObject], width = properties[kCGImagePropertyPixelWidth as String] as? CGFloat, height = properties[kCGImagePropertyPixelHeight as String] as? CGFloat { maxSize = max(width, height) for size in completionsBySize.keys { let actualSize = min(maxSize, size) guard images[actualSize] == nil else { break } var image: UIImage? if size < maxSize { let options: [NSString: NSObject] = [ kCGImageSourceCreateThumbnailFromImageIfAbsent: true, kCGImageSourceThumbnailMaxPixelSize: size ] if let cgImage = CGImageSourceCreateThumbnailAtIndex(source, 0, options) { image = UIImage(CGImage: cgImage) } } else { if let cgImage = CGImageSourceCreateImageAtIndex(source, 0, nil) { image = UIImage(CGImage: cgImage) } } images[actualSize] = image if let image = image where useCache { WebImageCacheManager.cacheImageInMemory(image, url: url, size: actualSize, cacheDuration: cacheDuration) } } } else { print("INFO: 🖼 Couldn't load the image from the file from: \(url)") } } func didWriteData(bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { if monitorProgress { if totalBytesExpectedToWrite != NSURLSessionTransferSizeUnknown { let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite) dispatch_async(dispatch_get_main_queue()) { for completions in self.completionsBySize.values { completions.forEach({ $0.1(error: nil, image: nil, progress: progress) }) } } } } } } final class WebImageDownloaderManager: NSObject { static let sharedManager = WebImageDownloaderManager() private lazy var cacheSession: NSURLSession = { return NSURLSession( configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: nil) }() private lazy var noCacheSession: NSURLSession = { let noCacheConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration() noCacheConfiguration.requestCachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData return NSURLSession( configuration: noCacheConfiguration, delegate: self, delegateQueue: nil) }() private var imageDownloaders: [String: WebImageDownloader] = [:] // Key: URL absolute string func request(url: NSURL, key: String, size: CGFloat? = nil, useCache: Bool = true, cacheDuration: NSTimeInterval = 86400 /* 1 day */, useProtocolCachePolicy: Bool = true, monitorProgress: Bool = false, completion: (error: NSError?, image: UIImage?, progress: Float?) -> Void) { if let imageDownloader = imageDownloaders[url.absoluteString] { imageDownloader.register(completion, key: key, size: size) } else { let imageDownloader = WebImageDownloader(url: url, useCache: useCache, cacheDuration: cacheDuration, monitorProgress: monitorProgress) imageDownloader.register(completion, key: key, size: size) imageDownloaders[url.absoluteString] = imageDownloader imageDownloader.download(useProtocolCachePolicy ? cacheSession : noCacheSession) } } func cancel(url: NSURL, key: String) { if let imageDownloader = imageDownloaders[url.absoluteString] { imageDownloader.unregister(key) if imageDownloader.completionsBySize.isEmpty { imageDownloaders[url.absoluteString] = nil } } } func isDownloading(url: NSURL) -> Bool { return imageDownloaders[url.absoluteString] != nil } } extension WebImageDownloaderManager: NSURLSessionTaskDelegate { func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let request = task.originalRequest, url = request.URL, downloader = imageDownloaders[url.absoluteString] { downloader.didCompleteWithError(error) imageDownloaders[url.absoluteString] = nil } } } extension WebImageDownloaderManager: NSURLSessionDataDelegate { func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: (NSCachedURLResponse?) -> Void) { completionHandler(session === cacheSession ? proposedResponse : nil) } } extension WebImageDownloaderManager: NSURLSessionDownloadDelegate { func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { if let request = downloadTask.originalRequest, url = request.URL, downloader = imageDownloaders[url.absoluteString] { downloader.didFinishDownloadingToURL(location) } } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { if let request = downloadTask.originalRequest, url = request.URL, downloader = imageDownloaders[url.absoluteString] { downloader.didWriteData(bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite) } } }
d192087c50a00b10a279a98b0a2dcb25
40.879845
281
0.626839
false
false
false
false
devgabrielcoman/woodhouse
refs/heads/master
Pod/Classes/Services/Zomato/ZomatoSearch.swift
gpl-3.0
1
// // ZomatoService.swift // Pods // // Created by Gabriel Coman on 28/03/2016. // // import UIKit import Alamofire import Dollar import KeyPathTransformer public class ZomatoSearch: NSObject, ServiceProtocol { private var qry: String = "" private var lat: Float = 0 private var lng: Float = 0 private var rad: Float = 0 private var dataService: DataService = DataService() public override init() { super.init() dataService.serviceDelegate = self dataService.authDelgate = ZomatoAuth.sharedInstance } func apiurl() -> String { return "https://developers.zomato.com/api/v2.1/search" } func detailsURL() -> String? { return nil } func method() -> String { return "GET" } func query() -> [String : AnyObject]? { return [ "q":qry.urlEncode(), "lat":lat, "lon":lng, "radius":rad ] } func header() -> [String : AnyObject]? { return nil } func body() -> [String : AnyObject]? { return nil } func process(JSON: AnyObject) -> AnyObject { if let response = JSON as? [String:AnyObject], let venues = response["restaurants"] as? [AnyObject] as? [[String:AnyObject]] { return venues } return [:] } public func search(query qry: String?, latitude lat: Float?, longitude lng: Float?, radius rad: Float?) { if let qry = qry, lat = lat, lng = lng, rad = rad { self.qry = qry; self.lat = lat; self.lng = lng; self.rad = rad } dataService.execute() { result in print(result) print(">>>>><<<<<<<<<>>>>>>>>>><<<<<<<") print(">>>>><<<<<<<<<>>>>>>>>>><<<<<<<") if let venues = result as? [[String:AnyObject]] { $.each(venues) { (venue: [String:AnyObject]) in print(mapZomatoToOMenu(venue)) print("#######################") } } } } }
ba6385c42f569a3a241ed84b2fb706b5
24.392857
109
0.495077
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Platform/Sources/PlatformUIKit/Components/AccountPicker/Other/AccountAssetBalanceViewInteractor.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainNamespace import Combine import DIKit import MoneyKit import PlatformKit import RxRelay import RxSwift public final class AccountAssetBalanceViewInteractor: AssetBalanceViewInteracting { public typealias InteractionState = AssetBalanceViewModel.State.Interaction enum Source { case account(BlockchainAccount) case asset(CryptoAsset) } // MARK: - Exposed Properties public var state: Observable<InteractionState> { _ = setup return stateRelay.asObservable() } private let stateRelay = BehaviorRelay<InteractionState>(value: .loading) private let disposeBag = DisposeBag() private let fiatCurrencyService: FiatCurrencyServiceAPI private let refreshRelay = BehaviorRelay<Void>(value: ()) private let account: Source private let app: AppProtocol public init( account: BlockchainAccount, fiatCurrencyService: FiatCurrencyServiceAPI = resolve(), app: AppProtocol = resolve() ) { self.account = .account(account) self.fiatCurrencyService = fiatCurrencyService self.app = app } public init( cryptoAsset: CryptoAsset, fiatCurrencyService: FiatCurrencyServiceAPI = resolve(), app: AppProtocol = resolve() ) { account = .asset(cryptoAsset) self.fiatCurrencyService = fiatCurrencyService self.app = app } // MARK: - Setup private func balancePair(fiatCurrency: FiatCurrency) -> AnyPublisher<MoneyValuePair, Error> { switch account { case .account(let account): return account.balancePair(fiatCurrency: fiatCurrency) case .asset(let cryptoAsset): return app .modePublisher() .flatMap { appMode in cryptoAsset .accountGroup(filter: appMode.filter) } .compactMap { $0 } .flatMap { accountGroup in accountGroup.balancePair(fiatCurrency: fiatCurrency) } .eraseToAnyPublisher() } } private lazy var setup: Void = Observable .combineLatest( fiatCurrencyService.displayCurrencyPublisher.asObservable(), refreshRelay.asObservable() ) .map(\.0) .flatMapLatest(weak: self) { (self, fiatCurrency) -> Observable<MoneyValuePair> in self.balancePair(fiatCurrency: fiatCurrency).asObservable() } .map { moneyValuePair -> InteractionState in InteractionState.loaded( next: AssetBalanceViewModel.Value.Interaction( primaryValue: moneyValuePair.quote, secondaryValue: moneyValuePair.base, pendingValue: nil ) ) } .subscribe(onNext: { [weak self] state in self?.stateRelay.accept(state) }) .disposed(by: disposeBag) public func refresh() { refreshRelay.accept(()) } }
4ea9c0878a376f791f44bd1dc0dec70e
30.059406
97
0.617469
false
false
false
false
CoderST/STScrolPlay
refs/heads/master
STScrolPlay/STScrolPlay/Class/STPlayer/UIColor-Extension.swift
mit
1
// // UIColor-Extension.swift // // Created by xiudou on 2017/6/5. // Copyright © 2016年 CoderST. All rights reserved. // import UIKit extension UIColor { // 在extension中给系统的类扩充构造函数,只能扩充`便利构造函数` convenience init(r : CGFloat, g : CGFloat, b : CGFloat, alpha : CGFloat = 1.0) { self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: alpha) } convenience init?(hex : String, alpha : CGFloat = 1.0) { // 0xff0000 // 1.判断字符串的长度是否符合 guard hex.characters.count >= 6 else { return nil } // 2.将字符串转成大写 var tempHex = hex.uppercased() // 3.判断开头: 0x/#/## if tempHex.hasPrefix("0x") || tempHex.hasPrefix("##") { tempHex = (tempHex as NSString).substring(from: 2) } if tempHex.hasPrefix("#") { tempHex = (tempHex as NSString).substring(from: 1) } // 4.分别取出RGB // FF --> 255 var range = NSRange(location: 0, length: 2) let rHex = (tempHex as NSString).substring(with: range) range.location = 2 let gHex = (tempHex as NSString).substring(with: range) range.location = 4 let bHex = (tempHex as NSString).substring(with: range) // 5.将十六进制转成数字 emoji表情 var r : UInt32 = 0, g : UInt32 = 0, b : UInt32 = 0 Scanner(string: rHex).scanHexInt32(&r) Scanner(string: gHex).scanHexInt32(&g) Scanner(string: bHex).scanHexInt32(&b) self.init(r : CGFloat(r), g : CGFloat(g), b : CGFloat(b)) } class func randomColor() -> UIColor { return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256))) } class func getRGBDelta(_ firstColor : UIColor, seccondColor : UIColor) -> (CGFloat, CGFloat, CGFloat) { let firstRGB = firstColor.getRGB() let secondRGB = seccondColor.getRGB() return (firstRGB.0 - secondRGB.0, firstRGB.1 - secondRGB.1, firstRGB.2 - secondRGB.2) } func getRGB() -> (CGFloat, CGFloat, CGFloat) { let components = cgColor.components if (components?[0])! >= CGFloat(0) && (components?[1])! >= CGFloat(0) && (components?[2])! >= CGFloat(0){ return (components![0] * 255, components![1] * 255, components![2] * 255) }else{ fatalError("请使用RGB方式给Title赋值颜色") } } }
c2dcff79e0271c4b49b3f96c876ef9be
31.597403
133
0.554582
false
false
false
false
fancymax/12306ForMac
refs/heads/master
12306ForMac/Utilities/ReminderManager.swift
mit
1
// // ReminderManager.swift // 12306ForMac // // Created by fancymax on 2/24/2017. // Copyright © 2017年 fancy. All rights reserved. // import Foundation import EventKit class ReminderManager: NSObject { private let eventStore:EKEventStore private var isAccessToEventStoreGranted:Bool fileprivate static let sharedManager = ReminderManager() class var sharedInstance: ReminderManager { return sharedManager } private override init () { isAccessToEventStoreGranted = false eventStore = EKEventStore() } @discardableResult func updateAuthorizationStatus()->Bool { switch EKEventStore.authorizationStatus(for: .reminder) { case .authorized: self.isAccessToEventStoreGranted = true return true case .notDetermined: self.eventStore.requestAccess(to: .reminder, completion: {[unowned self] granted,error in DispatchQueue.main.async { self.isAccessToEventStoreGranted = granted } }) return false case .restricted, .denied: isAccessToEventStoreGranted = false return false } } func createReminder(_ title:String, startDate:Date) { if !isAccessToEventStoreGranted { return } let reminder = EKReminder(eventStore: self.eventStore) reminder.calendar = eventStore.defaultCalendarForNewReminders() reminder.title = title var date = Date(timeInterval: 5, since: Date()) var alarm = EKAlarm(absoluteDate: date) reminder.addAlarm(alarm) date = Date(timeInterval: 10, since: Date()) alarm = EKAlarm(absoluteDate: date) reminder.addAlarm(alarm) date = Date(timeInterval: 15, since: Date()) alarm = EKAlarm(absoluteDate: date) reminder.addAlarm(alarm) try! eventStore.save(reminder, commit: true) } }
c99369c5042822a8ea3b326276cc364b
28.3
101
0.612872
false
false
false
false
devincoughlin/swift
refs/heads/master
test/IRGen/outlined_copy_addr.swift
apache-2.0
8
// RUN: %target-swift-frontend -emit-ir -module-name outcopyaddr -primary-file %s | %FileCheck %s public protocol BaseProt { } public protocol ChildProt: BaseProt { } public struct BaseStruct<T: BaseProt> { public typealias Element = T public var elem1: Element public var elem2: Element } public struct StructWithBaseStruct<T: BaseProt> { public typealias Element = T var elem1: Element var elem2: BaseStruct<Element> } // CHECK-LABEL: define hidden swiftcc void @"$s11outcopyaddr010StructWithbc4BaseB0V4elemAA0bcdB0VyxGvg"(%T11outcopyaddr014StructWithBaseB0V.5* noalias nocapture sret, %swift.type* %"StructWithStructWithBaseStruct<T>", %T11outcopyaddr010StructWithbc4BaseB0V* noalias nocapture swiftself) // CHECK: call %T11outcopyaddr014StructWithBaseB0V.5* @"$s11outcopyaddr014StructWithBaseB0VyxGAA9ChildProtRzlWOc" public struct StructWithStructWithBaseStruct<T: ChildProt> { public typealias Element = T let elem: StructWithBaseStruct<Element> } protocol P { } class OtherPrivate<T> { } struct OtherInternal<T> { var myPrivate: OtherPrivate<T>? = nil } struct MyPrivate<T: P> { var otherHelper: OtherInternal<T>? = nil // CHECK-LABEL: define hidden swiftcc {{i32|i64}} @"$s11outcopyaddr9MyPrivateVyACyxGxcfC"(%swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.P) {{.*}} { // CHECK: call %T11outcopyaddr9MyPrivateV* @"$s11outcopyaddr9MyPrivateVyxGAA1PRzlWOh"(%T11outcopyaddr9MyPrivateV* {{%.*}}) // CHECK: ret init(_: T) { } } extension P { func foo(data: Any) { _ = MyPrivate(data as! Self) } } enum GenericError<T: BaseProt> { case payload(T) } func testIt<P: BaseProt>(_ f: GenericError<P>?) { } func dontCrash<P: BaseProt>(_ f: GenericError<P>) { testIt(f) } protocol Baz : class { } extension Baz { static func crash(setup: ((Self) -> ())?){ } } class Foobar { public static func dontCrash() -> Baz? { let cls : Baz.Type = Foobar1.self // This used to crash because we tried to outline the optional consume with // an opened payload existential type. cls.crash(setup: { (arg: Baz) -> () in }) return nil } } class Foobar1 : Foobar, Baz { }
827fa8cde3004ef46680d5c811ce8a2d
27.12987
286
0.708218
false
false
false
false
FengDeng/RxGitHubAPI
refs/heads/master
RxGitHubAPI/RxGitHubAPI/YYCommitDetail.swift
apache-2.0
1
// // YYCommitDetail.swift // RxGitHubAPI // // Created by 邓锋 on 16/2/2. // Copyright © 2016年 fengdeng. All rights reserved. // import Foundation public class YYCommitDetail: NSObject { public private(set) var author = YYCommitUser() public private(set) var committer = YYCommitUser() public private(set) var message = "" public private(set) var tree = YYTree() public private(set) var comment_count = 0 //api var url = "" }
43e02d6aa33652eea2961eb1aaba0480
22.2
54
0.663793
false
false
false
false
ngageoint/mage-ios
refs/heads/master
Mage/Extensions/UIWindowExtensions.swift
apache-2.0
1
// // UIWindowExtensions.swift // MAGE // // Created by Daniel Barela on 7/13/21. // Copyright © 2021 National Geospatial Intelligence Agency. All rights reserved. // import Foundation import UIKit extension UIWindow { @objc static var isLandscape: Bool { return UIApplication.shared.windows .first? .windowScene? .interfaceOrientation .isLandscape ?? false } @objc static func forceDarkMode() { if let window = UIApplication.shared.windows.filter({$0.isKeyWindow}).first { UIView.transition (with: window, duration: 0.4, options: .transitionCrossDissolve, animations: { window.overrideUserInterfaceStyle = .dark }, completion: nil) } } @objc static func forceLightMode() { if let window = UIApplication.shared.windows.filter({$0.isKeyWindow}).first { UIView.transition (with: window, duration: 0.4, options: .transitionCrossDissolve, animations: { window.overrideUserInterfaceStyle = .light }, completion: nil) } } @objc static func followSystemColors() { if let window = UIApplication.shared.windows.filter({$0.isKeyWindow}).first { UIView.transition (with: window, duration: 0.4, options: .transitionCrossDissolve, animations: { window.overrideUserInterfaceStyle = .unspecified }, completion: nil) } } @objc static func updateThemeFromPreferences() { if let window = UIApplication.shared.windows.filter({$0.isKeyWindow}).first { UIView.transition (with: window, duration: 0.4, options: .transitionCrossDissolve, animations: { window.overrideUserInterfaceStyle = UIUserInterfaceStyle(rawValue: UserDefaults.standard.themeOverride) ?? .unspecified }, completion: nil) } } @objc static func getInterfaceStyle() -> UIUserInterfaceStyle { return (UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.overrideUserInterfaceStyle) ?? .unspecified; } }
65d6b4b25ac34720ce0d80ff7903a03a
36.803571
135
0.643836
false
false
false
false
rvald/Wynfood.iOS
refs/heads/main
Wynfood/Reachability.swift
apache-2.0
1
// // Reachability.swift // NetworkReachabilityTutorial // // Created by craftman on 2/27/17. // Copyright © 2017 craftman. All rights reserved. // import Foundation import SystemConfiguration let ReachabilityDidChangeNotificationName = "ReachabilityDidChangeNotification" enum ReachabilityStatus { case NotReachable case ReachableViaWifi case ReachableViaWWAN } class Reachability: NSObject { // MARK: - Properties private var networkReachability: SCNetworkReachability? private var notifying = false private var flags: SCNetworkReachabilityFlags { var flags = SCNetworkReachabilityFlags(rawValue: 0) if let reachability = networkReachability, withUnsafeMutablePointer(to: &flags, { SCNetworkReachabilityGetFlags(reachability, UnsafeMutablePointer($0)) }) == true { return flags } else { return [] } } var currentReachabilityStatus: ReachabilityStatus { if flags.contains(.reachable) == false { // the target host is not reachable return .NotReachable } else if flags.contains(.isWWAN) == true { // WWAN connections are OK if the calling application is using the CFNetwork APIs return .ReachableViaWWAN } else if flags.contains(.connectionRequired) == false { // If the target host is reachable and no connection is required, then Wifi is working return .ReachableViaWifi } else if (flags.contains(.connectionOnDemand) == true || flags.contains(.connectionOnTraffic) == true) && flags.contains(.interventionRequired) == false { // the connection is on-demand (or on traffic) // if the calling application is using the CFSocketStream or higher APIs and // no user intervention is required return .ReachableViaWifi } else { return .NotReachable } } var isReachable: Bool { switch currentReachabilityStatus { case .NotReachable: return false case .ReachableViaWifi, .ReachableViaWWAN: return true } } // MARK: - Initialization init?(hostAddress: sockaddr_in) { var address = hostAddress guard let defaultRouteReachability = withUnsafePointer(to: &address, { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, $0) } }) else { return nil } networkReachability = defaultRouteReachability super.init() if networkReachability == nil { return nil } } // MARK: - Methods static func networkReachabilityForInternetConnection() -> Reachability? { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) return Reachability(hostAddress: zeroAddress) } static func networkReachabilityForLocalWifi() -> Reachability? { var localWifiAddress = sockaddr_in() localWifiAddress.sin_len = UInt8(MemoryLayout.size(ofValue: localWifiAddress)) localWifiAddress.sin_family = sa_family_t(AF_INET) localWifiAddress.sin_addr.s_addr = 0xA9FE0000 return Reachability(hostAddress: localWifiAddress) } func startNotifier() -> Bool { guard notifying == false else { return false } var context = SCNetworkReachabilityContext() context.info = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) guard let reachability = networkReachability, SCNetworkReachabilitySetCallback(reachability, { (networkReachability, flags, info) in if let currentInfo = info { let infoObject = Unmanaged<AnyObject>.fromOpaque(currentInfo).takeUnretainedValue() if infoObject is Reachability { let networkReachability = infoObject as! Reachability NotificationCenter.default.post(name: Notification.Name(rawValue: ReachabilityDidChangeNotificationName), object: networkReachability) } } }, &context) == true else { return false } guard SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode.rawValue) == true else { return false } notifying = true return notifying } func stopNotifier() { if let reachability = networkReachability, notifying == true { SCNetworkReachabilityUnscheduleFromRunLoop(reachability, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode as! CFString) notifying = false } } deinit { stopNotifier() } }
e0bde85532f1ac4e3681a77abaa65ccb
29.418994
172
0.584573
false
false
false
false
Sadmansamee/quran-ios
refs/heads/master
Quran/GaplessAudioPlayer.swift
mit
1
// // GaplessAudioPlayer.swift // Quran // // Created by Mohamed Afifi on 5/16/16. // Copyright © 2016 Quran.com. All rights reserved. // import Foundation import AVFoundation import UIKit import MediaPlayer private class GaplessPlayerItem: AVPlayerItem { let sura: Int init(URL: URL, sura: Int) { self.sura = sura super.init(asset: AVAsset(url: URL), automaticallyLoadedAssetKeys: nil) } fileprivate override var description: String { return super.description + " sura: \(sura)" } } class GaplessAudioPlayer: DefaultAudioPlayer { weak var delegate: AudioPlayerDelegate? let player = QueuePlayer() let timingRetriever: QariTimingRetriever fileprivate var ayahsDictionary: [AVPlayerItem: [AyahNumber]] = [:] init(timingRetriever: QariTimingRetriever) { self.timingRetriever = timingRetriever } func play(qari: Qari, startAyah: AyahNumber, endAyah: AyahNumber) { let (items, info) = playerItemsForQari(qari, startAyah: startAyah, endAyah: endAyah) timingRetriever.retrieveTimingForQari(qari, suras: items.map { $0.sura }) { [weak self] timingsResult in guard let timings = timingsResult.value else { return } var mutableTimings = timings if let timeArray = mutableTimings[startAyah.sura] { mutableTimings[startAyah.sura] = Array(timeArray.dropFirst(startAyah.ayah - 1)) } var times: [AVPlayerItem: [Double]] = [:] var ayahs: [AVPlayerItem: [AyahNumber]] = [:] for item in items { var array: [AyahTiming] = cast(mutableTimings[item.sura]) if array.last?.ayah == AyahNumber(sura: item.sura, ayah: 999) { array = Array(array.dropLast()) } times[item] = array.enumerated().map { $0 == 0 && $1.ayah.ayah == 1 ? 0 : $1.seconds } ayahs[item] = array.map { $0.ayah } } self?.ayahsDictionary = ayahs let startSuraTimes: [AyahTiming] = cast(mutableTimings[startAyah.sura]) let startTime = startAyah.ayah == 1 ? 0 : startSuraTimes[0].seconds self?.player.onPlaybackEnded = self?.onPlaybackEnded() self?.player.onPlaybackRateChanged = self?.onPlaybackRateChanged() self?.player.onPlaybackStartingTimeFrame = { [weak self] (item: AVPlayerItem, timeIndex: Int) in guard let item = item as? GaplessPlayerItem, let ayahs = self?.ayahsDictionary[item] else { return } self?.delegate?.playingAyah(ayahs[timeIndex]) } self?.player.play(startTimeInSeconds: startTime, items: items, info: info, boundaries: times) } } } extension GaplessAudioPlayer { fileprivate func playerItemsForQari(_ qari: Qari, startAyah: AyahNumber, endAyah: AyahNumber) -> ([GaplessPlayerItem], [PlayerItemInfo]) { let files = filesToPlay(qari: qari, startAyah: startAyah, endAyah: endAyah) let items = files.map { GaplessPlayerItem(URL: $0, sura: $1) } let info = files.map { PlayerItemInfo( title: Quran.nameForSura($1), artist: qari.name, artwork: qari.imageName.flatMap({UIImage(named: $0)}).flatMap { MPMediaItemArtwork(image: $0) }) } return (items, info) } fileprivate func filesToPlay(qari: Qari, startAyah: AyahNumber, endAyah: AyahNumber) -> [(URL, Int)] { guard case AudioType.gapless = qari.audioType else { fatalError("Unsupported qari type gapped. Only gapless qaris can be played here.") } // loop over the files var files: [(URL, Int)] = [] for sura in startAyah.sura...endAyah.sura { let fileName = String(format: "%03d", sura) let localURL = qari.localFolder().appendingPathComponent(fileName).appendingPathExtension(Files.audioExtension) files.append(localURL, sura) } return files } }
96352e51f030abb37a8eb22339c64837
36.850467
142
0.624198
false
false
false
false
kruzhkov/traccar-manager-ios
refs/heads/native
TraccarManager/CarAnnotationView.swift
apache-2.0
1
// // CustomPositionAnnotation.swift // TraccarManager // // Created by Sergey Kruzhkov on 28.07.17. // Copyright © 2017 Sergey Kruzhkov (s.kruzhkov@gmail.com). All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import UIKit import MapKit class CarAnnotationView: MKAnnotationView { var imgView: UIImageView! var shapeLayerCircle = CAShapeLayer() var shapeLayerArrow = CAShapeLayer() var label: UILabel? var radiusCircle = 10.0 var pa: CarAnnotation? let frameWidth = 70.0 let frameHeight = 30.0 override init(annotation: MKAnnotation?, reuseIdentifier: String?) { super.init(annotation: annotation, reuseIdentifier: reuseIdentifier) addObserver() renderAnnotation(annotation: annotation, xx: 0.0, yy: 0.0) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { removeObserver() } func renderAnnotation(annotation: MKAnnotation?, xx: Double, yy: Double) { pa = annotation as? CarAnnotation if pa?.selected != nil && (pa?.selected)! { radiusCircle = 15.0 } let imageName = "point_" + ((pa?.category != nil) ? (pa?.category)! : "default") self.imgView = UIImageView(image: UIImage(named: imageName)) self.backgroundColor = UIColor.clear self.canShowCallout = true self.frame = CGRect.init(x: xx, y:yy, width: frameWidth, height: frameHeight) drawCircle(xx: xx, yy: yy) self.imgView.tintColor = UIColor.black self.imgView.contentMode = .scaleAspectFit self.imgView.frame = self.bounds self.addSubview(self.imgView) let xl = frameWidth / 2 + (radiusCircle + 5) * cos(0) let yl = frameHeight / 2 + (radiusCircle + 5) * sin(0) + 5 label = UILabel(frame: CGRect(x: xl, y: yl, width: 150, height: 14)) label?.textAlignment = .left label?.textColor = UIColor.darkGray label?.font = label?.font.withSize(12) label?.text = pa?.title self.addSubview(label!) let tapAnnotation = UITapGestureRecognizer(target: self, action: #selector(self.tap)) self.addGestureRecognizer(tapAnnotation) } func drawCircle(xx: Double, yy: Double) { shapeLayerArrow = CAShapeLayer() let frameWidth = 70.0 let frameHeight = 30.0 var circleColor = UIColor.green.cgColor if pa?.status == "unknown" { circleColor = UIColor.init(red: 251 / 255, green: 231 / 255, blue: 185 / 255, alpha: 1).cgColor } else if pa?.status == "offline" { circleColor = UIColor.red.cgColor } if pa?.selected != nil && (pa?.selected)! { radiusCircle = 15.0 } let circlePath = UIBezierPath(arcCenter: CGPoint(x: frameWidth / 2, y: frameHeight / 2), radius: CGFloat(radiusCircle), startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true) shapeLayerCircle = CAShapeLayer() shapeLayerCircle.path = circlePath.cgPath shapeLayerCircle.fillColor = circleColor shapeLayerCircle.strokeColor = UIColor.darkGray.cgColor shapeLayerCircle.lineWidth = 1.5 self.layer.addSublayer(shapeLayerCircle) // add arrow layer cource drawArrow() } func drawArrow() { if pa?.status != "offline" { let angle = Double(truncating: (pa?.course)!) - 90.0 let arrowPath = UIBezierPath() let triangleHeight = radiusCircle + 5.0 let x1 = radiusCircle * cos((angle - 7) * (Double.pi / 180)) let y1 = radiusCircle * sin((angle - 7) * (Double.pi / 180)) let x2 = triangleHeight * cos(angle * (Double.pi / 180)) let y2 = triangleHeight * sin(angle * (Double.pi / 180)) let x3 = radiusCircle * cos((angle + 7) * (Double.pi / 180)) let y3 = radiusCircle * sin((angle + 7) * (Double.pi / 180)) arrowPath.move(to: CGPoint(x: x1 + frameWidth / 2, y: y1 + frameHeight / 2)) arrowPath.addLine(to: CGPoint(x: x2 + frameWidth / 2, y: y2 + frameHeight / 2)) arrowPath.addLine(to: CGPoint(x: x3 + frameWidth / 2, y: y3 + frameHeight / 2)) arrowPath.close() shapeLayerArrow.path = arrowPath.cgPath shapeLayerArrow.lineWidth = 0.5 shapeLayerArrow.fillColor = UIColor.darkGray.cgColor shapeLayerArrow.strokeColor = UIColor.darkGray.cgColor self.layer.addSublayer(shapeLayerArrow) } } @objc func tap(recognaizer: UITapGestureRecognizer) { UIView.animate(withDuration: 1.0) { self.imgView.tintColor = UIColor.gray self.imgView.tintColor = UIColor.black } } func addObserver() { if let annotation = annotation as? CarAnnotation { annotation.addObserver(self, forKeyPath: #keyPath(CarAnnotation.course), options: [.new, .old], context: nil) annotation.addObserver(self, forKeyPath: #keyPath(CarAnnotation.status), options: [.new, .old], context: nil) annotation.addObserver(self, forKeyPath: #keyPath(CarAnnotation.category), options: [.new, .old], context: nil) annotation.addObserver(self, forKeyPath: #keyPath(CarAnnotation.title), options: [.new, .old], context: nil) } } private func removeObserver() { if let annotation = annotation as? CarAnnotation { annotation.removeObserver(self, forKeyPath: #keyPath(CarAnnotation.course)) annotation.removeObserver(self, forKeyPath: #keyPath(CarAnnotation.status)) annotation.removeObserver(self, forKeyPath: #keyPath(CarAnnotation.category)) annotation.removeObserver(self, forKeyPath: #keyPath(CarAnnotation.title)) } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "course" { drawArrow() } else if keyPath == "status" { var circleColor = UIColor.green.cgColor if pa?.status == "unknown" { circleColor = UIColor.init(red: 251 / 255, green: 231 / 255, blue: 185 / 255, alpha: 1).cgColor } else if pa?.status == "offline" { circleColor = UIColor.red.cgColor } shapeLayerCircle.fillColor = circleColor } else if keyPath == "category" { let imageName = "point_" + ((pa?.category != nil) ? (pa?.category)! : "default") imgView.image = UIImage(named: imageName) } else if keyPath == "title" { label?.text = pa?.title } } }
878cb6b4235c96c7275894b2179ac03f
37.419192
201
0.600105
false
false
false
false
BalestraPatrick/HomeKitty
refs/heads/master
Sources/App/Models/HomeKitApp.swift
mit
1
// // Copyright © 2018 HomeKitty. All rights reserved. // import Foundation import FluentPostgreSQL import Vapor struct HomeKitApp: PostgreSQLModel { static var entity = "apps" var id: Int? let name: String let subtitle: String? let publisher: String let websiteLink: String let price: Double? let appStoreLink: String let appStoreIcon: String let approved: Bool let createdAt: Date let updatedAt: Date init(name: String, subtitle: String?, price: Double?, appStoreLink: String, appStoreIcon: String, publisher: String, websiteLink: String) { self.name = name self.subtitle = subtitle self.publisher = publisher self.websiteLink = websiteLink self.price = price self.appStoreLink = appStoreLink self.appStoreIcon = appStoreIcon self.approved = false self.createdAt = Date() self.updatedAt = Date() } enum CodingKeys: String, CodingKey { case id case name case subtitle case publisher case websiteLink = "website_link" case price case appStoreLink = "app_store_link" case appStoreIcon = "app_store_icon" case approved case createdAt case updatedAt } } extension HomeKitApp: PostgreSQLMigration { }
29a4865c1a4cb93c159002e6989e9bad
22.965517
52
0.618705
false
false
false
false
RACCommunity/Rex
refs/heads/master
Source/UIKit/UIControl.swift
mit
3
// // UIView.swift // Rex // // Created by Neil Pankey on 6/19/15. // Copyright (c) 2015 Neil Pankey. All rights reserved. // import ReactiveCocoa import UIKit import enum Result.NoError extension UIControl { #if os(iOS) /// Creates a producer for the sender whenever a specified control event is triggered. @warn_unused_result(message="Did you forget to use the property?") public func rex_controlEvents(events: UIControlEvents) -> SignalProducer<UIControl?, NoError> { return rac_signalForControlEvents(events) .toSignalProducer() .map { $0 as? UIControl } .flatMapError { _ in SignalProducer(value: nil) } } /// Creates a bindable property to wrap a control's value. /// /// This property uses `UIControlEvents.ValueChanged` and `UIControlEvents.EditingChanged` /// events to detect changes and keep the value up-to-date. // @warn_unused_result(message="Did you forget to use the property?") class func rex_value<Host: UIControl, T>(host: Host, getter: Host -> T, setter: (Host, T) -> ()) -> MutableProperty<T> { return associatedProperty(host, key: &valueChangedKey, initial: getter, setter: setter) { property in property <~ host.rex_controlEvents([.ValueChanged, .EditingChanged]) .filterMap { $0 as? Host } .filterMap(getter) } } #endif /// Wraps a control's `enabled` state in a bindable property. public var rex_enabled: MutableProperty<Bool> { return associatedProperty(self, key: &enabledKey, initial: { $0.enabled }, setter: { $0.enabled = $1 }) } /// Wraps a control's `selected` state in a bindable property. public var rex_selected: MutableProperty<Bool> { return associatedProperty(self, key: &selectedKey, initial: { $0.selected }, setter: { $0.selected = $1 }) } /// Wraps a control's `highlighted` state in a bindable property. public var rex_highlighted: MutableProperty<Bool> { return associatedProperty(self, key: &highlightedKey, initial: { $0.highlighted }, setter: { $0.highlighted = $1 }) } } private var enabledKey: UInt8 = 0 private var selectedKey: UInt8 = 0 private var highlightedKey: UInt8 = 0 private var valueChangedKey: UInt8 = 0
73b237b30b1782420d06a008cf37fe45
37.716667
124
0.655618
false
false
false
false
ProfileCreator/ProfileCreator
refs/heads/master
ProfileCreator/ProfileCreator/Value Import Processors/ValueImportProcessor.swift
mit
1
// // ValueImportProcessor.swift // ProfileCreator // // Created by Erik Berglund. // Copyright © 2018 Erik Berglund. All rights reserved. // import Foundation import ProfilePayloads class ValueImportProcessor { // FIMXE: Should add fileUTIs when initializing. // MARK: - // MARK: Variables let identifier: String var fileURL: URL? var fileUTI: String? var subkey: PayloadSubkey? var currentValue: Any? var allowedFileTypes: [String]? // MARK: - // MARK: Initialization init(identifier: String) { self.identifier = identifier } func addValue(forFile url: URL, toCurrentValue: [Any]?, subkey: PayloadSubkey, cellView: PayloadCellView, completionHandler: @escaping (_ value: Any?) -> Void) throws { // Subkey self.subkey = subkey // Allowed File Types self.allowedFileTypes = subkey.allowedFileTypes // File UTI self.fileURL = url // File UTI self.fileUTI = url.typeIdentifier try self.addValue(toCurrentValue: toCurrentValue, cellView: cellView, completionHandler: completionHandler) } // Override This func addValue(toCurrentValue: [Any]?, cellView: PayloadCellView, completionHandler: @escaping (_ value: Any?) -> Void) throws { // FIXME: Replace all this with a protocol for better control fatalError("This must be overridden by the subclass.") } }
332b56300d3f817fd916dd5c108c1c16
24.678571
172
0.662031
false
false
false
false
ScoutHarris/WordPress-iOS
refs/heads/develop
WordPress/Classes/Extensions/Notifications/NotificationBlock+Interface.swift
gpl-2.0
1
import Foundation import WordPressShared.WPStyleGuide /// This Extension implements helper methods to aid formatting a NotificationBlock's payload, /// for usage in several different spots of the app. /// For performance purposes, Attributed Strings get temporarily cached... and will get nuked whenever the /// related Notification object gets updated. /// extension NotificationBlock { /// Formats a NotificationBlock for usage in NoteTableViewCell, in the subject field /// var attributedSubjectText: NSAttributedString { let attributedText = memoize { let subject = self.textWithStyles(Styles.subjectRegularStyle as [String : AnyObject], quoteStyles: Styles.subjectItalicsStyle as [String : AnyObject]?, rangeStylesMap: Constants.subjectRangeStylesMap, linksColor: nil) return subject.trimNewlines() } return attributedText(MemoizeKeys.subject) } /// Formats a NotificationBlock for usage in NoteTableViewCell, in the snippet field /// var attributedSnippetText: NSAttributedString { let attributedText = memoize { let snippet = self.textWithStyles(Styles.snippetRegularStyle as [String : AnyObject], quoteStyles: nil, rangeStylesMap: nil, linksColor: nil) return snippet.trimNewlines() } return attributedText(MemoizeKeys.snippet) } /// Formats a NotificationBlock for usage in NoteBlockHeaderTableViewCell /// var attributedHeaderTitleText: NSAttributedString { let attributedText = memoize { return self.textWithStyles(Styles.headerTitleRegularStyle as [String : AnyObject], quoteStyles: nil, rangeStylesMap: Constants.headerTitleRangeStylesMap, linksColor: nil) } return attributedText(MemoizeKeys.headerTitle) } /// Formats a NotificationBlock for usage in NoteBlockFooterTableViewCell /// var attributedFooterText: NSAttributedString { let attributedText = memoize { return self.textWithStyles(Styles.footerRegularStyle as [String : AnyObject], quoteStyles: nil, rangeStylesMap: Constants.footerStylesMap, linksColor: nil) } return attributedText(MemoizeKeys.footer) } /// Formats a NotificationBlock for usage into both, NoteBlockTextTableViewCell and NoteBlockCommentTableViewCell. /// var attributedRichText: NSAttributedString { // Operations such as editing a comment may complete way before the Notification is updated. // TextOverride is a transient property meant to store, temporarily, the edited text if let textOverride = textOverride { return NSAttributedString(string: textOverride, attributes: Styles.contentBlockRegularStyle) } let attributedText = memoize { return self.textWithStyles(Styles.contentBlockRegularStyle as [String : AnyObject], quoteStyles: Styles.contentBlockBoldStyle as [String : AnyObject]?, rangeStylesMap: Constants.richRangeStylesMap, linksColor: Styles.blockLinkColor) } return attributedText(MemoizeKeys.text) } /// Formats a NotificationBlock for usage into Badge-Type notifications. This contains custom /// formatting that differs from regular notifications, such as centered texts. /// var attributedBadgeText: NSAttributedString { let attributedText = memoize { return self.textWithStyles(Styles.badgeRegularStyle as [String : AnyObject], quoteStyles: Styles.badgeBoldStyle as [String : AnyObject]?, rangeStylesMap: Constants.badgeRangeStylesMap, linksColor: Styles.badgeLinkColor) } return attributedText(MemoizeKeys.badge) } /// Given a set of URL's and the Images they reference to, this method will return a Dictionary /// with the NSRange's in which the given UIImage's should be injected. /// /// **Note:** If we've got a text override: Ranges may not match, and the new text may not even contain ranges! /// /// - Parameter mediaMap: A Dictionary mapping asset URL's to the already-downloaded assets /// /// - Returns: A Dictionary mapping Text-Ranges in which the UIImage's should be applied /// func buildRangesToImagesMap(_ mediaMap: [URL: UIImage]) -> [NSValue: UIImage]? { guard textOverride == nil else { return nil } var ranges = [NSValue: UIImage]() for theMedia in media { guard let mediaURL = theMedia.mediaURL else { continue } if let image = mediaMap[mediaURL as URL] { let rangeValue = NSValue(range: theMedia.range) ranges[rangeValue] = image } } return ranges } } // MARK: - Private Helpers // extension NotificationBlock { /// This method is meant to aid cache-implementation into all of the AttriutedString getters introduced /// in this extension. /// /// - Parameter fn: A Closure that, on execution, returns an attributed string. /// /// - Returns: A new Closure that on execution will either hit the cache, or execute the closure `fn` /// and store its return value in the cache. /// fileprivate func memoize(_ fn: @escaping () -> NSAttributedString) -> (String) -> NSAttributedString { return { cacheKey in if let cachedSubject = self.cacheValueForKey(cacheKey) as? NSAttributedString { return cachedSubject } let newValue = fn() self.setCacheValue(newValue, forKey: cacheKey) return newValue } } /// This method is an all-purpose helper to aid formatting the NotificationBlock's payload text. /// /// - Parameters: /// - attributes: Represents the attributes to be applied, initially, to the Text. /// - quoteStyles: The Styles to be applied to "any quoted text" /// - rangeStylesMap: A Dictionary object mapping NotificationBlock types to a dictionary of styles /// to be applied. /// - linksColor: The color that should be used on any links contained. /// /// - Returns: A NSAttributedString instance, formatted with all of the specified parameters /// fileprivate func textWithStyles(_ attributes: [String: AnyObject], quoteStyles: [String: AnyObject]?, rangeStylesMap: [NotificationRange.Kind: [String: AnyObject]]?, linksColor: UIColor?) -> NSAttributedString { guard let text = text else { return NSAttributedString() } let theString = NSMutableAttributedString(string: text, attributes: attributes) if let quoteStyles = quoteStyles { theString.applyAttributes(toQuotes: quoteStyles) } // Apply the Ranges var lengthShift = 0 for range in ranges { var shiftedRange = range.range shiftedRange.location += lengthShift if range.kind == .Noticon { let noticon = (range.value ?? String()) + " " theString.replaceCharacters(in: shiftedRange, with: noticon) lengthShift += noticon.characters.count shiftedRange.length += noticon.characters.count } if let rangeStyle = rangeStylesMap?[range.kind] { theString.addAttributes(rangeStyle, range: shiftedRange) } if let rangeURL = range.url, let linksColor = linksColor { theString.addAttribute(NSLinkAttributeName, value: rangeURL, range: shiftedRange) theString.addAttribute(NSForegroundColorAttributeName, value: linksColor, range: shiftedRange) } } return theString } // MARK: - Constants // fileprivate struct Constants { static let subjectRangeStylesMap: [NotificationRange.Kind: [String: AnyObject]] = [ .User: Styles.subjectBoldStyle as Dictionary<String, AnyObject>, .Post: Styles.subjectItalicsStyle as Dictionary<String, AnyObject>, .Comment: Styles.subjectItalicsStyle as Dictionary<String, AnyObject>, .Blockquote: Styles.subjectQuotedStyle as Dictionary<String, AnyObject>, .Noticon: Styles.subjectNoticonStyle ] static let headerTitleRangeStylesMap: [NotificationRange.Kind: [String: AnyObject]] = [ .User: Styles.headerTitleBoldStyle as Dictionary<String, AnyObject>, .Post: Styles.headerTitleContextStyle as Dictionary<String, AnyObject>, .Comment: Styles.headerTitleContextStyle as Dictionary<String, AnyObject> ] static let footerStylesMap: [NotificationRange.Kind: [String: AnyObject]] = [ .Noticon: Styles.blockNoticonStyle as Dictionary<String, AnyObject> ] static let richRangeStylesMap: [NotificationRange.Kind: [String: AnyObject]] = [ .Blockquote: Styles.contentBlockQuotedStyle as Dictionary<String, AnyObject>, .Noticon: Styles.blockNoticonStyle as Dictionary<String, AnyObject>, .Match: Styles.contentBlockMatchStyle as Dictionary<String, AnyObject> ] static let badgeRangeStylesMap: [NotificationRange.Kind: [String: AnyObject]] = [ .User: Styles.badgeBoldStyle as Dictionary<String, AnyObject>, .Post: Styles.badgeItalicsStyle as Dictionary<String, AnyObject>, .Comment: Styles.badgeItalicsStyle as Dictionary<String, AnyObject>, .Blockquote: Styles.badgeQuotedStyle as Dictionary<String, AnyObject> ] } fileprivate struct MemoizeKeys { static let subject = "subject" static let snippet = "snippet" static let headerTitle = "headerTitle" static let footer = "footer" static let text = "text" static let badge = "badge" } fileprivate typealias Styles = WPStyleGuide.Notifications }
1042288048f482e0dea0cf3fc10c0a94
39.66537
118
0.638216
false
false
false
false
AngryLi/Onmyouji
refs/heads/master
Carthage/Checkouts/realm-cocoa/RealmSwift/Tests/ObjectSchemaInitializationTests.swift
gpl-3.0
4
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import XCTest import RealmSwift import Realm.Private import Realm.Dynamic import Foundation class ObjectSchemaInitializationTests: TestCase { func testAllValidTypes() { let object = SwiftObject() let objectSchema = object.objectSchema let noSuchCol = objectSchema["noSuchCol"] XCTAssertNil(noSuchCol) let boolCol = objectSchema["boolCol"] XCTAssertNotNil(boolCol) XCTAssertEqual(boolCol!.name, "boolCol") XCTAssertEqual(boolCol!.type, PropertyType.bool) XCTAssertFalse(boolCol!.isIndexed) XCTAssertFalse(boolCol!.isOptional) XCTAssertNil(boolCol!.objectClassName) let intCol = objectSchema["intCol"] XCTAssertNotNil(intCol) XCTAssertEqual(intCol!.name, "intCol") XCTAssertEqual(intCol!.type, PropertyType.int) XCTAssertFalse(intCol!.isIndexed) XCTAssertFalse(intCol!.isOptional) XCTAssertNil(intCol!.objectClassName) let floatCol = objectSchema["floatCol"] XCTAssertNotNil(floatCol) XCTAssertEqual(floatCol!.name, "floatCol") XCTAssertEqual(floatCol!.type, PropertyType.float) XCTAssertFalse(floatCol!.isIndexed) XCTAssertFalse(floatCol!.isOptional) XCTAssertNil(floatCol!.objectClassName) let doubleCol = objectSchema["doubleCol"] XCTAssertNotNil(doubleCol) XCTAssertEqual(doubleCol!.name, "doubleCol") XCTAssertEqual(doubleCol!.type, PropertyType.double) XCTAssertFalse(doubleCol!.isIndexed) XCTAssertFalse(doubleCol!.isOptional) XCTAssertNil(doubleCol!.objectClassName) let stringCol = objectSchema["stringCol"] XCTAssertNotNil(stringCol) XCTAssertEqual(stringCol!.name, "stringCol") XCTAssertEqual(stringCol!.type, PropertyType.string) XCTAssertFalse(stringCol!.isIndexed) XCTAssertFalse(stringCol!.isOptional) XCTAssertNil(stringCol!.objectClassName) let binaryCol = objectSchema["binaryCol"] XCTAssertNotNil(binaryCol) XCTAssertEqual(binaryCol!.name, "binaryCol") XCTAssertEqual(binaryCol!.type, PropertyType.data) XCTAssertFalse(binaryCol!.isIndexed) XCTAssertFalse(binaryCol!.isOptional) XCTAssertNil(binaryCol!.objectClassName) let dateCol = objectSchema["dateCol"] XCTAssertNotNil(dateCol) XCTAssertEqual(dateCol!.name, "dateCol") XCTAssertEqual(dateCol!.type, PropertyType.date) XCTAssertFalse(dateCol!.isIndexed) XCTAssertFalse(dateCol!.isOptional) XCTAssertNil(dateCol!.objectClassName) let objectCol = objectSchema["objectCol"] XCTAssertNotNil(objectCol) XCTAssertEqual(objectCol!.name, "objectCol") XCTAssertEqual(objectCol!.type, PropertyType.object) XCTAssertFalse(objectCol!.isIndexed) XCTAssertTrue(objectCol!.isOptional) XCTAssertEqual(objectCol!.objectClassName!, "SwiftBoolObject") let arrayCol = objectSchema["arrayCol"] XCTAssertNotNil(arrayCol) XCTAssertEqual(arrayCol!.name, "arrayCol") XCTAssertEqual(arrayCol!.type, PropertyType.array) XCTAssertFalse(arrayCol!.isIndexed) XCTAssertFalse(arrayCol!.isOptional) XCTAssertEqual(objectCol!.objectClassName!, "SwiftBoolObject") let dynamicArrayCol = SwiftCompanyObject().objectSchema["employees"] XCTAssertNotNil(dynamicArrayCol) XCTAssertEqual(dynamicArrayCol!.name, "employees") XCTAssertEqual(dynamicArrayCol!.type, PropertyType.array) XCTAssertFalse(dynamicArrayCol!.isIndexed) XCTAssertFalse(arrayCol!.isOptional) XCTAssertEqual(dynamicArrayCol!.objectClassName!, "SwiftEmployeeObject") } func testInvalidObjects() { // Should be able to get a schema for a non-RLMObjectBase subclass let schema = RLMObjectSchema(forObjectClass: SwiftFakeObjectSubclass.self) XCTAssertEqual(schema.properties.count, 1) assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithAnyObject.self), "Should throw when not ignoring a property of a type we can't persist") assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithStringArray.self), "Should throw when not ignoring a property of a type we can't persist") assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithOptionalStringArray.self), "Should throw when not ignoring a property of a type we can't persist") assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithBadPropertyName.self), "Should throw when not ignoring a property with a name we don't support") // Shouldn't throw when not ignoring a property of a type we can't persist if it's not dynamic _ = RLMObjectSchema(forObjectClass: SwiftObjectWithEnum.self) // Shouldn't throw when not ignoring a property of a type we can't persist if it's not dynamic _ = RLMObjectSchema(forObjectClass: SwiftObjectWithStruct.self) assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithDatePrimaryKey.self), "Should throw when setting a non int/string primary key") assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithNSURL.self), "Should throw when not ignoring a property of a type we can't persist") assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithNonOptionalLinkProperty.self), "Should throw when not marking a link property as optional") assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithNSNumber.self), reason: "Can't persist NSNumber without default value: use a Swift-native number type " + "or provide a default value.", "Should throw when using not providing default value for NSNumber property on Swift model") assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithOptionalNSNumber.self), reason: "Can't persist NSNumber without default value: use a Swift-native number type " + "or provide a default value.", "Should throw when using not providing default value for NSNumber property on Swift model") } func testPrimaryKey() { XCTAssertNil(SwiftObject().objectSchema.primaryKeyProperty, "Object should default to having no primary key property") XCTAssertEqual(SwiftPrimaryStringObject().objectSchema.primaryKeyProperty!.name, "stringCol") } func testIgnoredProperties() { let schema = SwiftIgnoredPropertiesObject().objectSchema XCTAssertNil(schema["runtimeProperty"], "The object schema shouldn't contain ignored properties") XCTAssertNil(schema["runtimeDefaultProperty"], "The object schema shouldn't contain ignored properties") XCTAssertNil(schema["readOnlyProperty"], "The object schema shouldn't contain read-only properties") } func testIndexedProperties() { XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["stringCol"]!.isIndexed) XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["intCol"]!.isIndexed) XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["int8Col"]!.isIndexed) XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["int16Col"]!.isIndexed) XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["int32Col"]!.isIndexed) XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["int64Col"]!.isIndexed) XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["boolCol"]!.isIndexed) XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["dateCol"]!.isIndexed) XCTAssertFalse(SwiftIndexedPropertiesObject().objectSchema["floatCol"]!.isIndexed) XCTAssertFalse(SwiftIndexedPropertiesObject().objectSchema["doubleCol"]!.isIndexed) XCTAssertFalse(SwiftIndexedPropertiesObject().objectSchema["dataCol"]!.isIndexed) let unindexibleSchema = RLMObjectSchema(forObjectClass: SwiftObjectWithUnindexibleProperties.self) for propName in SwiftObjectWithUnindexibleProperties.indexedProperties() { XCTAssertFalse(unindexibleSchema[propName]!.indexed, "Shouldn't mark unindexible property '\(propName)' as indexed") } } func testOptionalProperties() { let schema = RLMObjectSchema(forObjectClass: SwiftOptionalObject.self) for prop in schema.properties { XCTAssertTrue(prop.optional) } let types = Set(schema.properties.map { $0.type }) XCTAssertEqual(types, Set([.string, .string, .data, .date, .object, .int, .float, .double, .bool])) } func testImplicitlyUnwrappedOptionalsAreParsedAsOptionals() { let schema = SwiftImplicitlyUnwrappedOptionalObject().objectSchema XCTAssertTrue(schema["optObjectCol"]!.isOptional) XCTAssertTrue(schema["optNSStringCol"]!.isOptional) XCTAssertTrue(schema["optStringCol"]!.isOptional) XCTAssertTrue(schema["optBinaryCol"]!.isOptional) XCTAssertTrue(schema["optDateCol"]!.isOptional) } func testNonRealmOptionalTypesDeclaredAsRealmOptional() { assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithNonRealmOptionalType.self)) } } class SwiftFakeObject: NSObject { @objc class func objectUtilClass(_ isSwift: Bool) -> AnyClass { return ObjectUtil.self } @objc class func primaryKey() -> String? { return nil } @objc class func ignoredProperties() -> [String] { return [] } @objc class func indexedProperties() -> [String] { return [] } @objc class func _realmObjectName() -> String? { return nil } } class SwiftObjectWithNSURL: SwiftFakeObject { @objc dynamic var url = NSURL(string: "http://realm.io")! } class SwiftObjectWithAnyObject: SwiftFakeObject { @objc dynamic var anyObject: AnyObject = NSObject() } class SwiftObjectWithStringArray: SwiftFakeObject { @objc dynamic var stringArray = [String]() } class SwiftObjectWithOptionalStringArray: SwiftFakeObject { @objc dynamic var stringArray: [String]? } enum SwiftEnum { case case1 case case2 } class SwiftObjectWithEnum: SwiftFakeObject { var swiftEnum = SwiftEnum.case1 } class SwiftObjectWithStruct: SwiftFakeObject { var swiftStruct = SortDescriptor(keyPath: "prop") } class SwiftObjectWithDatePrimaryKey: SwiftFakeObject { @objc dynamic var date = Date() override class func primaryKey() -> String? { return "date" } } class SwiftObjectWithNSNumber: SwiftFakeObject { @objc dynamic var number = NSNumber() } class SwiftObjectWithOptionalNSNumber: SwiftFakeObject { @objc dynamic var number: NSNumber? = NSNumber() } class SwiftFakeObjectSubclass: SwiftFakeObject { @objc dynamic var dateCol = Date() } class SwiftObjectWithUnindexibleProperties: SwiftFakeObject { @objc dynamic var boolCol = false @objc dynamic var intCol = 123 @objc dynamic var floatCol = 1.23 as Float @objc dynamic var doubleCol = 12.3 @objc dynamic var binaryCol = "a".data(using: String.Encoding.utf8)! @objc dynamic var dateCol = Date(timeIntervalSince1970: 1) @objc dynamic var objectCol: SwiftBoolObject? = SwiftBoolObject() let arrayCol = List<SwiftBoolObject>() dynamic override class func indexedProperties() -> [String] { return ["boolCol", "intCol", "floatCol", "doubleCol", "binaryCol", "dateCol", "objectCol", "arrayCol"] } } // swiftlint:disable:next type_name class SwiftObjectWithNonNullableOptionalProperties: SwiftFakeObject { @objc dynamic var optDateCol: Date? } class SwiftObjectWithNonOptionalLinkProperty: SwiftFakeObject { @objc dynamic var objectCol = SwiftBoolObject() } extension Set: RealmOptionalType { } class SwiftObjectWithNonRealmOptionalType: SwiftFakeObject { let set = RealmOptional<Set<Int>>() } class SwiftObjectWithBadPropertyName: SwiftFakeObject { @objc dynamic var newValue = false }
31d08743a419723ce6e123d2cd09d50e
42.171141
112
0.707268
false
false
false
false
rivetlogic/liferay-mobile-directory-ios
refs/heads/master
Liferay-Screens/Source/DDL/FormScreenlet/ServerOperations/LiferayDDLFormUploadOperation.swift
gpl-3.0
1
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library 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 Lesser General Public License for more * details. */ import UIKit public class LiferayDDLFormUploadOperation: ServerOperation, LRCallback, LRProgressDelegate { var document: DDLFieldDocument? var filePrefix: String? var repositoryId: Int64? var folderId: Int64? var onUploadedBytes: ((DDLFieldDocument, UInt, Int64, Int64) -> Void)? var uploadResult: [String:AnyObject]? internal override var hudFailureMessage: HUDMessage? { return (LocalizedString("ddlform-screenlet", "uploading-error", self), details: nil) } internal var formData: DDLFormData { return screenlet.screenletView as! DDLFormData } private var requestSemaphore: dispatch_semaphore_t? //MARK: ServerOperation override func validateData() -> Bool { if document == nil { return false } if document!.currentValue == nil { return false } if filePrefix == nil { return false } if repositoryId == nil { return false } if folderId == nil { return false } return true } override internal func doRun(#session: LRSession) { session.callback = self let fileName = "\(filePrefix!)\(NSUUID().UUIDString)" var size:Int64 = 0 let stream = document!.getStream(&size) let uploadData = LRUploadData( inputStream: stream, length: size, fileName: fileName, mimeType: document!.mimeType) uploadData.progressDelegate = self let service = LRDLAppService_v62(session: session) requestSemaphore = dispatch_semaphore_create(0) service.addFileEntryWithRepositoryId(repositoryId!, folderId: folderId!, sourceFileName: fileName, mimeType: document!.mimeType, title: fileName, description: LocalizedString("ddlform-screenlet", "upload-metadata-description", self), changeLog: LocalizedString("ddlform-screenlet", "upload-metadata-changelog", self), file: uploadData, serviceContext: nil, error: &lastError) dispatch_semaphore_wait(requestSemaphore!, DISPATCH_TIME_FOREVER) } //MARK: LRProgressDelegate public func onProgressBytes(bytes: UInt, sent: Int64, total: Int64) { document!.uploadStatus = .Uploading(UInt(sent), UInt(total)) onUploadedBytes?(document!, bytes, sent, total) } //MARK: LRCallback public func onFailure(error: NSError?) { lastError = error uploadResult = nil dispatch_semaphore_signal(requestSemaphore!) } public func onSuccess(result: AnyObject?) { lastError = nil uploadResult = result as? [String:AnyObject] dispatch_semaphore_signal(requestSemaphore!) } }
65b76bb0795c85a3cc76c4134c44e9c1
23.836066
93
0.732013
false
false
false
false
harenbrs/swix
refs/heads/master
swixUseCases/swix-OSX/swix/ndarray/ndarray.swift
mit
2
// // initing.swift // swix // // Created by Scott Sievert on 7/9/14. // Copyright (c) 2014 com.scott. All rights reserved. // import Foundation import Accelerate // the matrix definition and related functions go here // SLOW PARTS: x[ndarray, ndarray] set, modulo operator struct ndarray { let n: Int var count: Int var grid: [Double] init(n: Int) { self.n = n self.count = n grid = Array(count: n, repeatedValue: 0.0) } func reshape(shape: (Int,Int)) -> matrix{ assert(shape.0 * shape.1 == n, "Number of elements must not change.") var y:matrix = zeros(shape) y.flat = self return y } func copy() -> ndarray{ var y = zeros(n) cblas_dcopy(self.n.cint, !self, 1.cint, !y, 1.cint) return y } func sort(){ vDSP_vsortD(!self, vDSP_Length(self.n.cint), 1.cint) } func indexIsValidForRow(index: Int) -> Bool { return index >= 0 && index < n } func min() -> Double{ var m:CDouble=0 vDSP_minvD(!self, 1.cint, &m, vDSP_Length(self.n.cint)) return Double(m) } func max() -> Double{ var m:CDouble=0 vDSP_maxvD(!self, 1.cint, &m, vDSP_Length(self.n)) return m } func mean() -> Double{ return avg(self) } subscript(index: Int) -> Double { get { assert(indexIsValidForRow(index), "Index out of range") return grid[index] } set { assert(indexIsValidForRow(index), "Index out of range") grid[index] = newValue } } subscript(r: Range<Int>) -> ndarray { get { // assumes that r is not [0, 1, 2, 3...] not [0, 2, 4...] return self[asarray(r)] } set { self[asarray(r)].grid = newValue.grid} } subscript(idx: ndarray) -> ndarray { get { //assert((r%1.0) ~== zeros_like(r)) // ndarray has fractional parts, and those parts get truncated // dropped for speed results (depends on for-loop in C) assert((idx.max().int < self.n) && (idx.min() >= 0), "An index is out of bounds") var y = zeros(idx.n) vDSP_vindexD(!self, !idx, 1.cint, !y, 1.cint, vDSP_Length(idx.n)) return y } set { assert((idx.max().int < self.n) && (idx.min() >= 0), "An index is out of bounds") // asked stackoverflow question at [1] // [1]:http://stackoverflow.com/questions/24727674/modify-select-elements-of-an-array // tried basic optimization myself, but the compiler took care of that. index_xa_b_objc(!self, !idx, !newValue, idx.n.cint) } } }
c3fe5d368171743b70a764a839cb6cba
24.587156
97
0.531015
false
false
false
false
sotownsend/flok-apple
refs/heads/master
Pod/Classes/Controller.swift
mit
1
@objc class FlokControllerModule : FlokModule { override var exports: [String] { return ["if_controller_init:", "if_spec_controller_list:", "if_spec_controller_init:"] } static var cbpToView: WeakValueDictionary<Int, FlokView> = WeakValueDictionary() func if_controller_init(args: [AnyObject]) { let cbp = args[0] as! Int //Controller base-pointer let vbp = args[1] as! Int //View base-pointer //let cname = args[2] as! String //Controller name let info = args[3] as! [String:AnyObject] //Lookup up view that is part of this controller let view = FlokUiModule.uiTpToSelector[vbp] if view == nil { NSException(name: "FlokControllerModule", reason: "Tried to lookup view with pointer \(vbp) but it didn't exist", userInfo: nil).raise() return } if let view = view as? FlokView { view.cbp = cbp view.context = info self.dynamicType.cbpToView[cbp] = view view.didLoad() } else { NSException(name: "FlokControllerModule", reason: "For view with pointer \(vbp), it existed, but was not a FlokView", userInfo: nil).raise() } } func if_spec_controller_list(any: [AnyObject]) { //Will report incorrectly if called before the next loop as UIView's event //loop will need to remove the view dispatch_async(dispatch_get_main_queue()) { self.engine.int_dispatch([1, "spec", self.dynamicType.cbpToView.keys()]) } } func if_spec_controller_init(any: [AnyObject]) { } }
617b91c8c761c0c2cb519e47e06f8053
39.536585
152
0.598435
false
false
false
false
fousa/trackkit
refs/heads/master
Example/Tests/Tests/FIT/FITLiloSpecs.swift
mit
1
// // FITLiloSpecs.swift // Tests // // Created by Jelle Vandebeeck on 14/01/2018. // Copyright © 2018 CocoaPods. All rights reserved. // import Quick import Nimble import TrackKit class FITLiloSpecs: QuickSpec { override func spec() { describe("FIT") { context("Lilo") { var file: File! beforeEach { let url = Bundle(for: FITLiloSpecs.self).url(forResource: "Lilo", withExtension: "fit")! let data = try! Data(contentsOf: url) file = try! TrackParser(data: data, type: .fit).parse() } it("should have one course") { expect(file.courses?.count) == 1 } it("should have no activity") { expect(file.activities?.count) == 0 } context("points") { var point: Point! beforeEach { point = file.courses?.first?.points?.last! } it("should have a track point time") { expect(point.time?.description) == "2016-08-18 20:07:04 +0000" } it("should have a coordinate") { expect(point.coordinate?.latitude).to(beCloseTo(51.3066, within: 0.0001)) expect(point.coordinate?.longitude).to(beCloseTo(4.2904, within: 0.0001)) } it("should have a altitude in meters") { expect(point.elevation).to(beCloseTo(2, within: 0.0001)) } it("should have a distance in meters") { expect(point.distance).to(beCloseTo(15764.5498, within: 0.0001)) } it("should have a cadence") { expect(point.cadence).to(beNil()) } it("should have a heart rate") { expect(point.heartRate).to(beNil()) } } } } } }
c20a97b09326a77781af78ca1b6db8a7
34.257576
108
0.412119
false
false
false
false
VinlorJiang/DouYuWL
refs/heads/master
DouYuWL/DouYuWL/Classes/Main/Controller/BaseViewController.swift
mit
1
// // BaseViewController.swift // DouYuWL // // Created by dinpay on 2017/7/25. // Copyright © 2017年 apple. All rights reserved. // import UIKit class BaseViewController: UIViewController { // MARK:- 定义属性 var contentView : UIView? // MARK:- 懒加载属性 fileprivate lazy var animImageView : UIImageView = { [unowned self] in let imageView = UIImageView(image: UIImage(named: "img_loading_1")) imageView.center = self.view.center imageView.animationImages = [UIImage(named : "img_loading_1")!,UIImage(named : "img_loading_2")!] imageView.animationDuration = 0.5 imageView.animationRepeatCount = LONG_MAX imageView.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin] return imageView }() // MARK:- 系统回调 override func viewDidLoad() { super.viewDidLoad() setupUI() } } extension BaseViewController { func setupUI() { // 1.隐藏内容的view contentView?.isHidden = true // 2.添加执行动画的UIImageView view.addSubview(animImageView) // 3.给animImageView执行动画 animImageView.startAnimating() // 4.设置view的背景色 view.backgroundColor = UIColor(r: 250, g: 250, b: 250) } func loadDataFinished() { // 1.停止动画 animImageView.stopAnimating() // 2.隐藏animImageView animImageView.isHidden = true // 3.显示内容的view contentView?.isHidden = false } }
d335d60aba6a796766594c8b1fae5e29
23.171875
105
0.591467
false
false
false
false
DasHutch/minecraft-castle-challenge
refs/heads/develop
app/_src/XCGLogger.swift
gpl-2.0
1
// // XCGLogger.swift // XCGLogger: https://github.com/DaveWoodCom/XCGLogger // // Created by Dave Wood on 2014-06-06. // Copyright (c) 2014 Dave Wood, Cerebral Gardens. // Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt // import Foundation #if os(iOS) import UIKit #else import AppKit #endif // MARK: - XCGLogDetails // - Data structure to hold all info about a log message, passed to log destination classes public struct XCGLogDetails { public var logLevel: XCGLogger.LogLevel public var date: NSDate public var logMessage: String public var functionName: String public var fileName: String public var lineNumber: Int public init(logLevel: XCGLogger.LogLevel, date: NSDate, logMessage: String, functionName: String, fileName: String, lineNumber: Int) { self.logLevel = logLevel self.date = date self.logMessage = logMessage self.functionName = functionName self.fileName = fileName self.lineNumber = lineNumber } } // MARK: - XCGLogDestinationProtocol // - Protocol for output classes to conform to public protocol XCGLogDestinationProtocol: CustomDebugStringConvertible { var owner: XCGLogger {get set} var identifier: String {get set} var outputLogLevel: XCGLogger.LogLevel {get set} func processLogDetails(logDetails: XCGLogDetails) func processInternalLogDetails(logDetails: XCGLogDetails) // Same as processLogDetails but should omit function/file/line info func isEnabledForLogLevel(logLevel: XCGLogger.LogLevel) -> Bool } // MARK: - XCGBaseLogDestination // - A base class log destination that doesn't actually output the log anywhere and is intented to be subclassed public class XCGBaseLogDestination: XCGLogDestinationProtocol, CustomDebugStringConvertible { // MARK: - Properties public var owner: XCGLogger public var identifier: String public var outputLogLevel: XCGLogger.LogLevel = .Debug public var showFunctionName: Bool = true public var showThreadName: Bool = false public var showFileName: Bool = true public var showLineNumber: Bool = true public var showLogLevel: Bool = true public var showDate: Bool = true // MARK: - DebugPrintable public var debugDescription: String { get { return "\(extractClassName(self)): \(identifier) - LogLevel: \(outputLogLevel.description()) showFunctionName: \(showFunctionName) showThreadName: \(showThreadName) showLogLevel: \(showLogLevel) showFileName: \(showFileName) showLineNumber: \(showLineNumber) showDate: \(showDate)" } } // MARK: - Life Cycle public init(owner: XCGLogger, identifier: String = "") { self.owner = owner self.identifier = identifier } // MARK: - Methods to Process Log Details public func processLogDetails(logDetails: XCGLogDetails) { var extendedDetails: String = "" if showDate { var formattedDate: String = logDetails.date.description if let dateFormatter = owner.dateFormatter { formattedDate = dateFormatter.stringFromDate(logDetails.date) } extendedDetails += "\(formattedDate) " } if showLogLevel { extendedDetails += "[" + logDetails.logLevel.description() + "] " } if showThreadName { if NSThread.isMainThread() { extendedDetails += "[main] " } else { if let threadName = NSThread.currentThread().name where threadName != "" { extendedDetails += "[" + threadName + "] " } else { extendedDetails += "[" + String(format:"%p", NSThread.currentThread()) + "] " } } } if showFileName { extendedDetails += "[" + (logDetails.fileName as NSString).lastPathComponent + (showLineNumber ? ":" + String(logDetails.lineNumber) : "") + "] " } else if showLineNumber { extendedDetails += "[" + String(logDetails.lineNumber) + "] " } if showFunctionName { extendedDetails += "\(logDetails.functionName) " } output(logDetails, text: "\(extendedDetails)> \(logDetails.logMessage)") } public func processInternalLogDetails(logDetails: XCGLogDetails) { var extendedDetails: String = "" if showDate { var formattedDate: String = logDetails.date.description if let dateFormatter = owner.dateFormatter { formattedDate = dateFormatter.stringFromDate(logDetails.date) } extendedDetails += "\(formattedDate) " } if showLogLevel { extendedDetails += "[" + logDetails.logLevel.description() + "] " } output(logDetails, text: "\(extendedDetails)> \(logDetails.logMessage)") } // MARK: - Misc methods public func isEnabledForLogLevel (logLevel: XCGLogger.LogLevel) -> Bool { return logLevel >= self.outputLogLevel } // MARK: - Methods that must be overriden in subclasses public func output(logDetails: XCGLogDetails, text: String) { // Do something with the text in an overridden version of this method precondition(false, "Must override this") } } // MARK: - XCGConsoleLogDestination // - A standard log destination that outputs log details to the console public class XCGConsoleLogDestination: XCGBaseLogDestination { // MARK: - Properties public var xcodeColors: [XCGLogger.LogLevel: XCGLogger.XcodeColor]? = nil // MARK: - Misc Methods public override func output(logDetails: XCGLogDetails, text: String) { let adjustedText: String if let xcodeColor = (xcodeColors ?? owner.xcodeColors)[logDetails.logLevel] where owner.xcodeColorsEnabled { adjustedText = "\(xcodeColor.format())\(text)\(XCGLogger.XcodeColor.reset)" } else { adjustedText = text } print("\(adjustedText)") } } // MARK: - XCGNSLogDestination // - A standard log destination that outputs log details to the console using NSLog instead of println public class XCGNSLogDestination: XCGBaseLogDestination { // MARK: - Properties public var xcodeColors: [XCGLogger.LogLevel: XCGLogger.XcodeColor]? = nil public override var showDate: Bool { get { return false } set { // ignored, NSLog adds the date, so we always want showDate to be false in this subclass } } // MARK: - Misc Methods public override func output(logDetails: XCGLogDetails, text: String) { let adjustedText: String if let xcodeColor = (xcodeColors ?? owner.xcodeColors)[logDetails.logLevel] where owner.xcodeColorsEnabled { adjustedText = "\(xcodeColor.format())\(text)\(XCGLogger.XcodeColor.reset)" } else { adjustedText = text } NSLog(adjustedText) } } // MARK: - XCGFileLogDestination // - A standard log destination that outputs log details to a file public class XCGFileLogDestination: XCGBaseLogDestination { // MARK: - Properties private var writeToFileURL: NSURL? = nil { didSet { openFile() } } private var logFileHandle: NSFileHandle? = nil // MARK: - Life Cycle public init(owner: XCGLogger, writeToFile: AnyObject, identifier: String = "") { super.init(owner: owner, identifier: identifier) if writeToFile is NSString { writeToFileURL = NSURL.fileURLWithPath(writeToFile as! String) } else if writeToFile is NSURL { writeToFileURL = writeToFile as? NSURL } else { writeToFileURL = nil } openFile() } deinit { // close file stream if open closeFile() } // MARK: - File Handling Methods private func openFile() { if logFileHandle != nil { closeFile() } if let writeToFileURL = writeToFileURL, let path = writeToFileURL.path { NSFileManager.defaultManager().createFileAtPath(path, contents: nil, attributes: nil) do { logFileHandle = try NSFileHandle(forWritingToURL: writeToFileURL) } catch let error as NSError { owner._logln("Attempt to open log file for writing failed: \(error.localizedDescription)", logLevel: .Error) logFileHandle = nil return } owner.logAppDetails(self) let logDetails = XCGLogDetails(logLevel: .Info, date: NSDate(), logMessage: "XCGLogger writing to log to: \(writeToFileURL)", functionName: "", fileName: "", lineNumber: 0) owner._logln(logDetails.logMessage, logLevel: logDetails.logLevel) processInternalLogDetails(logDetails) } } private func closeFile() { logFileHandle?.closeFile() logFileHandle = nil } // MARK: - Misc Methods public override func output(logDetails: XCGLogDetails, text: String) { if let encodedData = "\(text)\n".dataUsingEncoding(NSUTF8StringEncoding) { logFileHandle?.writeData(encodedData) } } } // MARK: - XCGLogger // - The main logging class public class XCGLogger: CustomDebugStringConvertible { // MARK: - Constants public struct constants { public static let defaultInstanceIdentifier = "com.cerebralgardens.xcglogger.defaultInstance" public static let baseConsoleLogDestinationIdentifier = "com.cerebralgardens.xcglogger.logdestination.console" public static let nslogDestinationIdentifier = "com.cerebralgardens.xcglogger.logdestination.console.nslog" public static let baseFileLogDestinationIdentifier = "com.cerebralgardens.xcglogger.logdestination.file" public static let nsdataFormatterCacheIdentifier = "com.cerebralgardens.xcglogger.nsdataFormatterCache" public static let versionString = "3.0b2" } // MARK: - Enums public enum LogLevel: Int, Comparable { case Verbose case Debug case Info case Warning case Error case Severe case None public func description() -> String { switch self { case .Verbose: return "Verbose" case .Debug: return "Debug" case .Info: return "Info" case .Warning: return "Warning" case .Error: return "Error" case .Severe: return "Severe" case .None: return "None" } } } public struct XcodeColor { public static let escape = "\u{001b}[" public static let resetFg = "\u{001b}[fg;" public static let resetBg = "\u{001b}[bg;" public static let reset = "\u{001b}[;" public var fg: (Int, Int, Int)? = nil public var bg: (Int, Int, Int)? = nil public func format() -> String { guard fg != nil || bg != nil else { // neither set, return reset value return XcodeColor.reset } var format: String = "" if let fg = fg { format += "\(XcodeColor.escape)fg\(fg.0),\(fg.1),\(fg.2);" } else { format += XcodeColor.resetFg } if let bg = bg { format += "\(XcodeColor.escape)bg\(bg.0),\(bg.1),\(bg.2);" } else { format += XcodeColor.resetBg } return format } public init(fg: (Int, Int, Int)? = nil, bg: (Int, Int, Int)? = nil) { self.fg = fg self.bg = bg } #if os(iOS) public init(fg: UIColor, bg: UIColor? = nil) { var redComponent: CGFloat = 0 var greenComponent: CGFloat = 0 var blueComponent: CGFloat = 0 var alphaComponent: CGFloat = 0 fg.getRed(&redComponent, green: &greenComponent, blue: &blueComponent, alpha:&alphaComponent) self.fg = (Int(redComponent * 255), Int(greenComponent * 255), Int(blueComponent * 255)) if let bg = bg { bg.getRed(&redComponent, green: &greenComponent, blue: &blueComponent, alpha:&alphaComponent) self.bg = (Int(redComponent * 255), Int(greenComponent * 255), Int(blueComponent * 255)) } else { self.bg = nil } } #else public init(fg: NSColor, bg: NSColor? = nil) { if let fgColorSpaceCorrected = fg.colorUsingColorSpaceName(NSCalibratedRGBColorSpace) { self.fg = (Int(fgColorSpaceCorrected.redComponent * 255), Int(fgColorSpaceCorrected.greenComponent * 255), Int(fgColorSpaceCorrected.blueComponent * 255)) } else { self.fg = nil } if let bg = bg, let bgColorSpaceCorrected = bg.colorUsingColorSpaceName(NSCalibratedRGBColorSpace) { self.bg = (Int(bgColorSpaceCorrected.redComponent * 255), Int(bgColorSpaceCorrected.greenComponent * 255), Int(bgColorSpaceCorrected.blueComponent * 255)) } else { self.bg = nil } } #endif public static let red: XcodeColor = { return XcodeColor(fg: (255, 0, 0)) }() public static let green: XcodeColor = { return XcodeColor(fg: (0, 255, 0)) }() public static let blue: XcodeColor = { return XcodeColor(fg: (0, 0, 255)) }() public static let black: XcodeColor = { return XcodeColor(fg: (0, 0, 0)) }() public static let white: XcodeColor = { return XcodeColor(fg: (255, 255, 255)) }() public static let lightGrey: XcodeColor = { return XcodeColor(fg: (211, 211, 211)) }() public static let darkGrey: XcodeColor = { return XcodeColor(fg: (169, 169, 169)) }() public static let orange: XcodeColor = { return XcodeColor(fg: (255, 165, 0)) }() public static let whiteOnRed: XcodeColor = { return XcodeColor(fg: (255, 255, 255), bg: (255, 0, 0)) }() public static let darkGreen: XcodeColor = { return XcodeColor(fg: (0, 128, 0)) }() } // MARK: - Properties (Options) public var identifier: String = "" public var outputLogLevel: LogLevel = .Debug { didSet { for index in 0 ..< logDestinations.count { logDestinations[index].outputLogLevel = outputLogLevel } } } public var xcodeColorsEnabled: Bool = false public var xcodeColors: [XCGLogger.LogLevel: XCGLogger.XcodeColor] = [ .Verbose: .lightGrey, .Debug: .darkGrey, .Info: .blue, .Warning: .orange, .Error: .red, .Severe: .whiteOnRed ] // MARK: - Properties private var _dateFormatter: NSDateFormatter? = nil public var dateFormatter: NSDateFormatter? { get { if _dateFormatter != nil { return _dateFormatter } let defaultDateFormatter = NSDateFormatter() defaultDateFormatter.locale = NSLocale.currentLocale() defaultDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" _dateFormatter = defaultDateFormatter return _dateFormatter } set { _dateFormatter = newValue } } public var logDestinations: Array<XCGLogDestinationProtocol> = [] // MARK: - Life Cycle public init(identifier: String = "") { self.identifier = identifier // Check if XcodeColors is installed and enabled if let xcodeColors = NSProcessInfo.processInfo().environment["XcodeColors"] { xcodeColorsEnabled = xcodeColors == "YES" } // Setup a standard console log destination addLogDestination(XCGConsoleLogDestination(owner: self, identifier: XCGLogger.constants.baseConsoleLogDestinationIdentifier)) } // MARK: - Default instance public class func defaultInstance() -> XCGLogger { struct statics { static let instance: XCGLogger = XCGLogger(identifier: XCGLogger.constants.defaultInstanceIdentifier) } return statics.instance } // MARK: - Setup methods public class func setup(logLevel: LogLevel = .Debug, showFunctionName: Bool = true, showThreadName: Bool = false, showLogLevel: Bool = true, showFileNames: Bool = true, showLineNumbers: Bool = true, showDate: Bool = true, writeToFile: AnyObject? = nil, fileLogLevel: LogLevel? = nil) { defaultInstance().setup(logLevel, showFunctionName: showFunctionName, showThreadName: showThreadName, showLogLevel: showLogLevel, showFileNames: showFileNames, showLineNumbers: showLineNumbers, showDate: showDate, writeToFile: writeToFile) } public func setup(logLevel: LogLevel = .Debug, showFunctionName: Bool = true, showThreadName: Bool = false, showLogLevel: Bool = true, showFileNames: Bool = true, showLineNumbers: Bool = true, showDate: Bool = true, writeToFile: AnyObject? = nil, fileLogLevel: LogLevel? = nil) { outputLogLevel = logLevel; if let standardConsoleLogDestination = logDestination(XCGLogger.constants.baseConsoleLogDestinationIdentifier) as? XCGConsoleLogDestination { standardConsoleLogDestination.showFunctionName = showFunctionName standardConsoleLogDestination.showThreadName = showThreadName standardConsoleLogDestination.showLogLevel = showLogLevel standardConsoleLogDestination.showFileName = showFileNames standardConsoleLogDestination.showLineNumber = showLineNumbers standardConsoleLogDestination.showDate = showDate standardConsoleLogDestination.outputLogLevel = logLevel } logAppDetails() if let writeToFile: AnyObject = writeToFile { // We've been passed a file to use for logging, set up a file logger let standardFileLogDestination: XCGFileLogDestination = XCGFileLogDestination(owner: self, writeToFile: writeToFile, identifier: XCGLogger.constants.baseFileLogDestinationIdentifier) standardFileLogDestination.showFunctionName = showFunctionName standardFileLogDestination.showThreadName = showThreadName standardFileLogDestination.showLogLevel = showLogLevel standardFileLogDestination.showFileName = showFileNames standardFileLogDestination.showLineNumber = showLineNumbers standardFileLogDestination.showDate = showDate standardFileLogDestination.outputLogLevel = fileLogLevel ?? logLevel addLogDestination(standardFileLogDestination) } } // MARK: - Logging methods public class func logln(@autoclosure closure: () -> String?, logLevel: LogLevel = .Debug, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.defaultInstance().logln(logLevel, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public class func logln(logLevel: LogLevel = .Debug, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) { self.defaultInstance().logln(logLevel, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public func logln(@autoclosure closure: () -> String?, logLevel: LogLevel = .Debug, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.logln(logLevel, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public func logln(logLevel: LogLevel = .Debug, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) { let date = NSDate() var logDetails: XCGLogDetails? = nil for logDestination in self.logDestinations { if (logDestination.isEnabledForLogLevel(logLevel)) { if logDetails == nil { if let logMessage = closure() { logDetails = XCGLogDetails(logLevel: logLevel, date: date, logMessage: logMessage, functionName: functionName, fileName: fileName, lineNumber: lineNumber) } else { break } } logDestination.processLogDetails(logDetails!) } } } public class func exec(logLevel: LogLevel = .Debug, closure: () -> () = {}) { self.defaultInstance().exec(logLevel, closure: closure) } public func exec(logLevel: LogLevel = .Debug, closure: () -> () = {}) { if (!isEnabledForLogLevel(logLevel)) { return } closure() } public func logAppDetails(selectedLogDestination: XCGLogDestinationProtocol? = nil) { let date = NSDate() var buildString = "" if let infoDictionary = NSBundle.mainBundle().infoDictionary { if let CFBundleShortVersionString = infoDictionary["CFBundleShortVersionString"] as? String { buildString = "Version: \(CFBundleShortVersionString) " } if let CFBundleVersion = infoDictionary["CFBundleVersion"] as? String { buildString += "Build: \(CFBundleVersion) " } } let processInfo: NSProcessInfo = NSProcessInfo.processInfo() let XCGLoggerVersionNumber = XCGLogger.constants.versionString let logDetails: Array<XCGLogDetails> = [XCGLogDetails(logLevel: .Info, date: date, logMessage: "\(processInfo.processName) \(buildString)PID: \(processInfo.processIdentifier)", functionName: "", fileName: "", lineNumber: 0), XCGLogDetails(logLevel: .Info, date: date, logMessage: "XCGLogger Version: \(XCGLoggerVersionNumber) - LogLevel: \(outputLogLevel.description())", functionName: "", fileName: "", lineNumber: 0)] for logDestination in (selectedLogDestination != nil ? [selectedLogDestination!] : logDestinations) { for logDetail in logDetails { if !logDestination.isEnabledForLogLevel(.Info) { continue; } logDestination.processInternalLogDetails(logDetail) } } } // MARK: - Convenience logging methods // MARK: * Verbose public class func verbose(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.defaultInstance().logln(.Verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public class func verbose(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) { self.defaultInstance().logln(.Verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public func verbose(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.logln(.Verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public func verbose(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) { self.logln(.Verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } // MARK: * Debug public class func debug(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.defaultInstance().logln(.Debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public class func debug(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) { self.defaultInstance().logln(.Debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public func debug(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.logln(.Debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public func debug(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) { self.logln(.Debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } // MARK: * Info public class func info(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.defaultInstance().logln(.Info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public class func info(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) { self.defaultInstance().logln(.Info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public func info(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.logln(.Info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public func info(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) { self.logln(.Info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } // MARK: * Warning public class func warning(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.defaultInstance().logln(.Warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public class func warning(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) { self.defaultInstance().logln(.Warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public func warning(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.logln(.Warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public func warning(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) { self.logln(.Warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } // MARK: * Error public class func error(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.defaultInstance().logln(.Error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public class func error(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) { self.defaultInstance().logln(.Error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public func error(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.logln(.Error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public func error(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) { self.logln(.Error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } // MARK: * Severe public class func severe(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.defaultInstance().logln(.Severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public class func severe(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) { self.defaultInstance().logln(.Severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public func severe(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.logln(.Severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } public func severe(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) { self.logln(.Severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure) } // MARK: - Exec Methods // MARK: * Verbose public class func verboseExec(closure: () -> () = {}) { self.defaultInstance().exec(XCGLogger.LogLevel.Verbose, closure: closure) } public func verboseExec(closure: () -> () = {}) { self.exec(XCGLogger.LogLevel.Verbose, closure: closure) } // MARK: * Debug public class func debugExec(closure: () -> () = {}) { self.defaultInstance().exec(XCGLogger.LogLevel.Debug, closure: closure) } public func debugExec(closure: () -> () = {}) { self.exec(XCGLogger.LogLevel.Debug, closure: closure) } // MARK: * Info public class func infoExec(closure: () -> () = {}) { self.defaultInstance().exec(XCGLogger.LogLevel.Info, closure: closure) } public func infoExec(closure: () -> () = {}) { self.exec(XCGLogger.LogLevel.Info, closure: closure) } // MARK: * Warning public class func warningExec(closure: () -> () = {}) { self.defaultInstance().exec(XCGLogger.LogLevel.Warning, closure: closure) } public func warningExec(closure: () -> () = {}) { self.exec(XCGLogger.LogLevel.Warning, closure: closure) } // MARK: * Error public class func errorExec(closure: () -> () = {}) { self.defaultInstance().exec(XCGLogger.LogLevel.Error, closure: closure) } public func errorExec(closure: () -> () = {}) { self.exec(XCGLogger.LogLevel.Error, closure: closure) } // MARK: * Severe public class func severeExec(closure: () -> () = {}) { self.defaultInstance().exec(XCGLogger.LogLevel.Severe, closure: closure) } public func severeExec(closure: () -> () = {}) { self.exec(XCGLogger.LogLevel.Severe, closure: closure) } // MARK: - Misc methods public func isEnabledForLogLevel (logLevel: XCGLogger.LogLevel) -> Bool { return logLevel >= self.outputLogLevel } public func logDestination(identifier: String) -> XCGLogDestinationProtocol? { for logDestination in logDestinations { if logDestination.identifier == identifier { return logDestination } } return nil } public func addLogDestination(logDestination: XCGLogDestinationProtocol) -> Bool { let existingLogDestination: XCGLogDestinationProtocol? = self.logDestination(logDestination.identifier) if existingLogDestination != nil { return false } logDestinations.append(logDestination) return true } public func removeLogDestination(logDestination: XCGLogDestinationProtocol) { removeLogDestination(logDestination.identifier) } public func removeLogDestination(identifier: String) { logDestinations = logDestinations.filter({$0.identifier != identifier}) } // MARK: - Private methods private func _logln(logMessage: String, logLevel: LogLevel = .Debug) { let date = NSDate() var logDetails: XCGLogDetails? = nil for logDestination in self.logDestinations { if (logDestination.isEnabledForLogLevel(logLevel)) { if logDetails == nil { logDetails = XCGLogDetails(logLevel: logLevel, date: date, logMessage: logMessage, functionName: "", fileName: "", lineNumber: 0) } logDestination.processInternalLogDetails(logDetails!) } } } // MARK: - DebugPrintable public var debugDescription: String { get { var description: String = "\(extractClassName(self)): \(identifier) - logDestinations: \r" for logDestination in logDestinations { description += "\t \(logDestination.debugDescription)\r" } return description } } } // Implement Comparable for XCGLogger.LogLevel public func < (lhs:XCGLogger.LogLevel, rhs:XCGLogger.LogLevel) -> Bool { return lhs.rawValue < rhs.rawValue } // Temporary (hopefully) method to get the class name of an object, since reflect() was removed in Swift 2.0 // This is a crappy way to do it, hopefully we'll find a better way soon. func extractClassName(someObject: Any) -> String { var className = Mirror(reflecting: someObject).description if let rangeToRemove = className.rangeOfString("Mirror for ") { className.removeRange(rangeToRemove) } return className }
75e069d4afafcd6f3b129007ad4b4cd9
39.616114
293
0.637719
false
false
false
false
1170197998/SinaWeibo
refs/heads/master
SFWeiBo/SFWeiBo/Classes/Main/MainViewController.swift
apache-2.0
1
// // MainViewController.swift // SFWeiBo // // Created by mac on 16/3/22. // Copyright © 2016年 ShaoFeng. All rights reserved. // import UIKit class MainViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() //添加所有子控制器 addChildViewControllers() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) //从iOS7开始就不推荐在viewDidload中设置控件frame //添加 加号 按钮 setupComposeButton() } // MARK: - 中间按钮的监听事件 // 监听按钮点击的方法不能是私有方法(不能加private),因为是有运行循环触发的 func composeButtonClick() { let vc = ComposeViewController() let nav = UINavigationController(rootViewController: vc) presentViewController(nav, animated: true, completion: nil) } // MARK: - 添加 加号 按钮 private func setupComposeButton() { //添加 加号 按钮 tabBar.addSubview(composeButton) //调整 加号 按钮的位置 let width = UIScreen.mainScreen().bounds.size.width / CGFloat((viewControllers?.count)!) let rect = CGRect(x: 0, y: 0, width: width, height: 49) //第一个参数:frame的大小 //第二个参数:x方向偏移的大小 //第三个参数:y方向偏移的大小 composeButton.frame = CGRectOffset(rect, 2 * width, 0) } // MARK: - 添加所有子控制器 private func addChildViewControllers() { //1.获取json数据 let path = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil) //2.通过文件路径创建NSData if let jsonPath = path { let jsonData = NSData(contentsOfFile: jsonPath) do { //这里面放置有可能发生异常的代码 //3.序列化json数据 --> Array //try :发生异常会调到 catch 中继续执行 //try! : 发生异常直接崩溃 let dictArray = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers) //print(dictArray) //4.遍历数组,动态创建控制器和设置数据 //在Swift中,如果需要遍历一个数组,必须明确数据的类型 for dict in dictArray as! [[String:String]] { //addChildViewController下面的这个方法要求必须有参数,,但是字典的返回值是可选类型 addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!) } //如果服务器返回来数据,就从服务器加载数据(执行do里面的代码)加载控制器 //如果服务器没有返回数据(异常情况,就本地代码加载控制器,执行catch里面的代码) } catch { //发生异常会执行的代码 print(error) //添加子控制器(从本地加载创建控制器) addChildViewController("HomeTableViewController", title: "首页", imageName: "tabbar_home") addChildViewController("MessageTableViewController", title: "消息", imageName: "tabbar_message_center") addChildViewController("NullViewController", title: "", imageName: "") addChildViewController("DiscoverTableViewController", title: "广场", imageName: "tabbar_discover") addChildViewController("ProfileTableViewController", title: "我", imageName: "tabbar_profile") } } } // MARK: - 初始化子控制器(控制器名字,标题,图片) <传控制器的名字代替传控制器> // private func addChildViewController(childController: UIViewController, title:String, imageName:String) { private func addChildViewController(childControllerName: String, title:String, imageName:String) { //0.动态获取命名空间(CFBundleExecutable这个键对应的值就是项目名称,也就是命名空间) let nameSpace = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String //1.将字符串转化为类 //默认情况下,命名空间就是项目名称,但是命名空间是可以修改的 let cls:AnyClass? = NSClassFromString(nameSpace + "." + childControllerName) //SFWeiBo.是命名空间 //2.通过类创建对象 //2.1将anyClass转换为指定的类型 let viewControllerCls = cls as! UIViewController.Type //2.2通过class创建对象 let vc = viewControllerCls.init() //1设置tabbar对应的按钮数据 vc.tabBarItem.image = UIImage(named: imageName) vc.tabBarItem.selectedImage = UIImage(named: imageName + "highlighted") vc.title = title //2.给首页包装导航条 let nav = UINavigationController() nav.addChildViewController(vc) //3.将导航控制器添加到当前控制器 addChildViewController(nav) } // MARK: - 懒加载控件 private lazy var composeButton:UIButton = { let button = UIButton() //设置前景图片 button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal) button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted) //设置前景图片 button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState:UIControlState.Normal) button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted) //添加监听事件 button.addTarget(self, action: #selector(MainViewController.composeButtonClick), forControlEvents: UIControlEvents.TouchUpInside) return button }() }
67ed3eacfc52042cd59d316f99589f08
36.258993
137
0.608612
false
false
false
false
alvarozizou/Noticias-Leganes-iOS
refs/heads/develop
Pods/FeedKit/Sources/FeedKit/Models/JSON/JSONFeed.swift
mit
2
// // JSONFeed.swift // // Copyright (c) 2016 - 2018 Nuno Manuel Dias // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /// The JSON Feed format is a pragmatic syndication format, like RSS and Atom, /// but with one big difference: it's JSON instead of XML. /// See https://jsonfeed.org/version/1 public struct JSONFeed { /// (required, string) is the URL of the version of the format the feed /// uses. This should appear at the very top, though we recognize that not all /// JSON generators allow for ordering. public var version: String? /// (required, string) is the name of the feed, which will often correspond to /// the name of the website (blog, for instance), though not necessarily. public var title: String? /// (optional but strongly recommended, string) is the URL of the resource that /// the feed describes. This resource may or may not actually be a "home" page, /// but it should be an HTML page. If a feed is published on the public web, /// this should be considered as required. But it may not make sense in the /// case of a file created on a desktop computer, when that file is not shared /// or is shared only privately. public var homePageURL: String? /// (optional but strongly recommended, string) is the URL of the feed, and /// serves as the unique identifier for the feed. As with home_page_url, this /// should be considered required for feeds on the public web. public var feedUrl: String? /// (optional, string) provides more detail, beyond the title, on what the feed /// is about. A feed reader may display this text. public var description: String? /// (optional, string) is a description of the purpose of the feed. This is for /// the use of people looking at the raw JSON, and should be ignored by feed /// readers. public var userComment: String? /// (optional, string) is the URL of a feed that provides the next n items, /// where n is determined by the publisher. This allows for pagination, but /// with the expectation that reader software is not required to use it and /// probably won't use it very often. next_url must not be the same as /// feed_url, and it must not be the same as a previous next_url (to avoid /// infinite loops). public var nextUrl: String? /// (optional, string) is the URL of an image for the feed suitable to be used /// in a timeline, much the way an avatar might be used. It should be square /// and relatively large - such as 512 x 512 - so that it can be scaled-down /// and so that it can look good on retina displays. It should use transparency /// where appropriate, since it may be rendered on a non-white background. public var icon: String? /// (optional, string) is the URL of an image for the feed suitable to be used /// in a source list. It should be square and relatively small, but not smaller /// than 64 x 64 (so that it can look good on retina displays). As with icon, /// this image should use transparency where appropriate, since it may be /// rendered on a non-white background. public var favicon: String? /// (optional, object) specifies the feed author. The author object has /// several members. These are all optional - but if you provide an author /// object, then at least one is required. public var author: JSONFeedAuthor? /// (optional, boolean) says whether or not the feed is finished - that is, /// whether or not it will ever update again. A feed for a temporary event, /// such as an instance of the Olympics, could expire. If the value is true, /// then it's expired. Any other value, or the absence of expired, means the /// feed may continue to update. public var expired: Bool? /// (very optional, array of objects) describes endpoints that can be used to /// subscribe to real-time notifications from the publisher of this feed. Each /// object has a type and url, both of which are required. public var hubs: [JSONFeedHub]? /// The JSONFeed items. public var items: [JSONFeedItem]? } // MARK: - Equatable extension JSONFeed: Equatable {} // MARK: - Codable extension JSONFeed: Codable { enum CodingKeys: String, CodingKey { case version case title case user_comment case home_page_url case description case feed_url case next_url case icon case favicon case expired case author case hubs case items } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(version, forKey: .version) try container.encode(title, forKey: .title) try container.encode(userComment, forKey: .user_comment) try container.encode(homePageURL, forKey: .home_page_url) try container.encode(description, forKey: .description) try container.encode(feedUrl, forKey: .feed_url) try container.encode(nextUrl, forKey: .next_url) try container.encode(icon, forKey: .icon) try container.encode(favicon, forKey: .favicon) try container.encode(expired, forKey: .expired) try container.encode(author, forKey: .expired) try container.encode(hubs, forKey: .hubs) try container.encode(items, forKey: .items) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) version = try values.decodeIfPresent(String.self, forKey: .version) title = try values.decodeIfPresent(String.self, forKey: .title) userComment = try values.decodeIfPresent(String.self, forKey: .user_comment) homePageURL = try values.decodeIfPresent(String.self, forKey: .home_page_url) description = try values.decodeIfPresent(String.self, forKey: .description) feedUrl = try values.decodeIfPresent(String.self, forKey: .feed_url) nextUrl = try values.decodeIfPresent(String.self, forKey: .next_url) icon = try values.decodeIfPresent(String.self, forKey: .icon) favicon = try values.decodeIfPresent(String.self, forKey: .favicon) expired = try values.decodeIfPresent(Bool.self, forKey: .expired) author = try values.decodeIfPresent(JSONFeedAuthor.self, forKey: .author) hubs = try values.decodeIfPresent([JSONFeedHub].self, forKey: .hubs) items = try values.decodeIfPresent([JSONFeedItem].self, forKey: .items) } }
dafad72ed72cbc191d55c56dfb4eb7db
45.957576
85
0.685983
false
false
false
false
mownier/Umalahokan
refs/heads/master
Umalahokan/Source/UI/Drawer/DrawerMenuTransitioning.swift
mit
1
// // DrawerMenuTransitioning.swift // Umalahokan // // Created by Mounir Ybanez on 04/03/2017. // Copyright © 2017 Ner All rights reserved. // import UIKit class DrawerMenuTransitioning: NSObject, UIViewControllerTransitioningDelegate { weak var delegate: DrawerMenuTransitionDelegate? weak var interactiveTransition: DrawerMenuInteractiveTransition? var duration: TimeInterval = 0.5 func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { let transition = DrawerMenuTransition(style: .presentation) transition.duration = duration transition.delegate = delegate return transition } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { let transition = DrawerMenuTransition(style: .dismissal) transition.duration = duration transition.delegate = delegate return transition } func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactiveTransition?.hasStarted ?? false ? interactiveTransition : nil } func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactiveTransition?.hasStarted ?? false ? interactiveTransition : nil } }
4c53d2352ca2cdc844dc2c12bf6790e4
38.871795
170
0.756913
false
false
false
false
alesp56/APStopWatch
refs/heads/master
APStopwatch/APStopwatch/StopwatchRecord.swift
gpl-2.0
1
// // StopwatchRecord.swift // APStopwatch // // Created by Aleš Paulovič on 02/12/2016. // Copyright © 2016 paulovic.si. All rights reserved. // enum RecordType: String { case start = "Start" case lap = "Lap" case stop = "Stop" } import Foundation struct StopwatchRecord { var index: Int = 0 var timestamp: Date = Date() var message: String = "" var delta: Int = 0 init(index: Int, timestamp: Date, message: String = "", delta: Int) { self.index = index self.timestamp = timestamp self.message = message self.delta = delta } }
a2b53f770f3b1046b7bdd80936095b42
19.965517
73
0.606908
false
false
false
false
rabbitinspace/Tosoka
refs/heads/develop
Sources/Tosoka/Claim/ReservedClaim.swift
mit
1
import Foundation /// Registered claims /// /// Claims that is registered according to rfc7519 /// /// - issuer: "issuer" claim /// - subject: "subject" claim /// - audience: "audience" claim /// - expiring: "expiration time" claim /// - notBefore: "not before" claim /// - issued: "issued at" claim /// - id: "jwt id" claim public enum ReservedClaim { case issuer case subject case audience case expiring case notBefore case issued case id } // MARK: - Predefined claims /// Issuer claim public struct Issuer: Claim { public static var name: String { return ReservedClaim.issuer.name } public let content: String public init(content: String) { self.content = content } } /// Subject claim public struct Subject: Claim { public static var name: String { return ReservedClaim.subject.name } public let content: String public init(content: String) { self.content = content } } /// Audience claim public struct Audience: Claim { public static var name: String { return ReservedClaim.audience.name } public let content: Set<String> public var rawValue: [String] { return Array(content) } public init(content: Set<String>) { self.content = content } public init?(rawValue: [String]) { self.init(content: rawValue) } public func isValid(for requirment: Audience?) -> Bool { guard let requirment = requirment else { return content.isEmpty } return content.isSuperset(of: requirment.content) } } public extension Audience { public init(content: String) { let audience = [content] self.init(content: audience) } public init(content: [String]) { let audience = Set(content) self.init(content: audience) } } /// Expiring time claim public struct Expiring: Claim { public static var name: String { return ReservedClaim.expiring.name } public let content: Date public var rawValue: TimeInterval { return content.timeIntervalSince1970 } public init(content: Date) { self.content = content } public init?(rawValue: TimeInterval) { self.init(content: Date(timeIntervalSince1970: rawValue)) } public func isValid(for requirment: Expiring? = nil) -> Bool { return Date() < content } } /// Not before claim public struct NotBefore: Claim { public static var name: String { return ReservedClaim.notBefore.name } public let content: Date public var rawValue: TimeInterval { return content.timeIntervalSince1970 } public init(content: Date) { self.content = content } public init?(rawValue: TimeInterval) { self.init(content: Date(timeIntervalSince1970: rawValue)) } public func isValid(for requirment: NotBefore? = nil) -> Bool { return Date() >= content } } /// Issued at claim public struct Issued: Claim { public static var name: String { return ReservedClaim.issued.name } public let content: Date public var rawValue: TimeInterval { return content.timeIntervalSince1970 } public init(content: Date) { self.content = content } public init?(rawValue: TimeInterval) { self.init(content: Date(timeIntervalSince1970: rawValue)) } } /// JWT ID claim public struct ID: Claim { public static var name: String { return ReservedClaim.id.name } public let content: String public init(content: String) { self.content = content } } // MARK: - Internal extensions extension ReservedClaim { /// Name of the claim according to rfc7519 public var name: String { switch self { case .issuer: return "iss" case .subject: return "sub" case .audience: return "aud" case .expiring: return "exp" case .notBefore: return "nbf" case .issued: return "iat" case .id: return "jti" } } }
1f9d5d9004a270fe8934213e0c0a686d
19.504808
67
0.601876
false
false
false
false
boolkybear/iOS-Challenge
refs/heads/master
CatViewer/CatViewer/FavouriteCell.swift
mit
1
// // FavouriteCell.swift // CatViewer // // Created by Boolky Bear on 7/2/15. // Copyright (c) 2015 ByBDesigns. All rights reserved. // import UIKit class FavouriteCell: UITableViewCell { @IBOutlet var thumbnailImageView: UIImageView! @IBOutlet var dateLabel: UILabel! var favourite: Favourite? { didSet { self.thumbnailImageView?.image = nil self.dateLabel?.text = "" if let favourite = self.favourite { if let sinceDate = favourite.date { let formatter = NSDateFormatter() formatter.dateStyle = .MediumStyle formatter.timeStyle = .MediumStyle self.dateLabel?.text = formatter.stringFromDate(sinceDate) } } if let thumbnailData = self.favourite?.cat?.thumbnail?.data { self.thumbnailImageView?.image = UIImage(data: thumbnailData) } } } 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 } }
81c47d2bb45e677e925520b1d76c9a2f
20.882353
65
0.667563
false
false
false
false
MBKwon/SwiftTimer
refs/heads/master
TestSwift/TestSwift/Timer State/TimerRunning.swift
mit
1
// // TimerRunning.swift // TestSwift // // Created by MB KWON on 2014. 7. 28.. // Copyright (c) 2014년 UANGEL Corp. All rights reserved. // import Foundation import UIKit import CoreData class TimerRunning : NSObject, TimerProtocol { weak var timerController: TimerViewController? init(timerController: TimerViewController!) { if timerController != nil { self.timerController = timerController self.timerController!.stateLabel!.text = "Running State" self.timerController!.startBtn!.setTitle("Stop", forState: UIControlState.Normal) self.timerController!.resetBtn!.setTitle("Lap", forState: UIControlState.Normal) self.timerController!.resetBtn!.enabled = true self.timerController!.logBtn!.enabled = false } } func touchUpStartBtn() { timerController?.stopWatchTimer?.invalidate() timerController?.checkStopTime() self.timerController!.timerDelegate = TimerStop(timerController: self.timerController); } func touchUpResetBtn() { // record lap time if timerController?.currentLapTimeRecord == nil { timerController?.currentLapTimeRecord = (NSEntityDescription.insertNewObjectForEntityForName("TimeLapRecord", inManagedObjectContext: timerController?.coreDataHelper.backgroundContext) as TimeLapRecord) timerController?.currentLapTimeRecord?.setNewRecordRound(NSDate()) } var timeRecord: String = String().stringByAppendingFormat("%0.2lf", timerController!.displayTime) timerController?.currentLapTimeRecord?.addNewLapTime(timeRecord) timerController?.coreDataHelper.saveContext() } }
474f70b70166679c71b63aabd9f7ab1e
36.382979
214
0.685828
false
false
false
false
jacobwhite/firefox-ios
refs/heads/master
Client/Frontend/Settings/ClearPrivateDataTableViewController.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared private let SectionToggles = 0 private let SectionButton = 1 private let NumberOfSections = 2 private let SectionHeaderFooterIdentifier = "SectionHeaderFooterIdentifier" private let TogglesPrefKey = "clearprivatedata.toggles" private let log = Logger.browserLogger private let HistoryClearableIndex = 0 class ClearPrivateDataTableViewController: UITableViewController { fileprivate var clearButton: UITableViewCell? var profile: Profile! var tabManager: TabManager! fileprivate typealias DefaultCheckedState = Bool // TODO: The next person to add a new clearable in the UI here needs to // refactor how we store the saved values. We currently save an array of // `Bool`s which is highly insufficient. // Bug 1445687 -- https://bugzilla.mozilla.org/show_bug.cgi?id=1445687 fileprivate lazy var clearables: [(clearable: Clearable, checked: DefaultCheckedState)] = { var items: [(clearable: Clearable, checked: DefaultCheckedState)] = [ (HistoryClearable(profile: self.profile), true), (CacheClearable(tabManager: self.tabManager), true), (CookiesClearable(tabManager: self.tabManager), true), (SiteDataClearable(tabManager: self.tabManager), true) ] if #available(iOS 11, *) { items.append((TrackingProtectionClearable(), true)) } return items }() fileprivate lazy var toggles: [Bool] = { // If the number of saved toggles doesn't match the number of clearables, just reset // and return the default values for the clearables. if let savedToggles = self.profile.prefs.arrayForKey(TogglesPrefKey) as? [Bool], savedToggles.count == self.clearables.count { return savedToggles } return self.clearables.map { $0.checked } }() fileprivate var clearButtonEnabled = true { didSet { clearButton?.textLabel?.textColor = clearButtonEnabled ? UIConstants.DestructiveRed : UIColor.lightGray } } override func viewDidLoad() { super.viewDidLoad() title = Strings.SettingsClearPrivateDataTitle tableView.register(SettingsTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderFooterIdentifier) tableView.separatorColor = SettingsUX.TableViewSeparatorColor tableView.backgroundColor = SettingsUX.TableViewHeaderBackgroundColor let footer = SettingsTableSectionHeaderFooterView(frame: CGRect(width: tableView.bounds.width, height: SettingsUX.TableViewHeaderFooterHeight)) footer.showBottomBorder = false tableView.tableFooterView = footer } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: nil) if indexPath.section == SectionToggles { cell.textLabel?.text = clearables[indexPath.item].clearable.label let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged) control.isOn = toggles[indexPath.item] cell.accessoryView = control cell.selectionStyle = .none control.tag = indexPath.item } else { assert(indexPath.section == SectionButton) cell.textLabel?.text = Strings.SettingsClearPrivateDataClearButton cell.textLabel?.textAlignment = .center cell.textLabel?.textColor = UIConstants.DestructiveRed cell.accessibilityTraits = UIAccessibilityTraitButton cell.accessibilityIdentifier = "ClearPrivateData" clearButton = cell } return cell } override func numberOfSections(in tableView: UITableView) -> Int { return NumberOfSections } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == SectionToggles { return clearables.count } assert(section == SectionButton) return 1 } override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { guard indexPath.section == SectionButton else { return false } // Highlight the button only if it's enabled. return clearButtonEnabled } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard indexPath.section == SectionButton else { return } func clearPrivateData(_ action: UIAlertAction) { let toggles = self.toggles self.clearables .enumerated() .compactMap { (i, pair) in guard toggles[i] else { return nil } log.debug("Clearing \(pair.clearable).") return pair.clearable.clear() } .allSucceed() .uponQueue(.main) { result in assert(result.isSuccess, "Private data cleared successfully") LeanPlumClient.shared.track(event: .clearPrivateData) self.profile.prefs.setObject(self.toggles, forKey: TogglesPrefKey) // Disable the Clear Private Data button after it's clicked. self.clearButtonEnabled = false self.tableView.deselectRow(at: indexPath, animated: true) } } // We have been asked to clear history and we have an account. // (Whether or not it's in a good state is irrelevant.) if self.toggles[HistoryClearableIndex] && profile.hasAccount() { profile.syncManager.hasSyncedHistory().uponQueue(.main) { yes in // Err on the side of warning, but this shouldn't fail. let alert: UIAlertController if yes.successValue ?? true { // Our local database contains some history items that have been synced. // Warn the user before clearing. alert = UIAlertController.clearSyncedHistoryAlert(okayCallback: clearPrivateData) } else { alert = UIAlertController.clearPrivateDataAlert(okayCallback: clearPrivateData) } self.present(alert, animated: true, completion: nil) return } } else { let alert = UIAlertController.clearPrivateDataAlert(okayCallback: clearPrivateData) self.present(alert, animated: true, completion: nil) } tableView.deselectRow(at: indexPath, animated: false) } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderFooterIdentifier) as! SettingsTableSectionHeaderFooterView } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return SettingsUX.TableViewHeaderFooterHeight } @objc func switchValueChanged(_ toggle: UISwitch) { toggles[toggle.tag] = toggle.isOn // Dim the clear button if no clearables are selected. clearButtonEnabled = toggles.contains(true) } }
3c97cc5f2ccad490e08b227feba85b0e
40.766304
151
0.655172
false
false
false
false
linhaosunny/smallGifts
refs/heads/master
小礼品/小礼品/Classes/Module/Classify/Views/StrategySectionView.swift
mit
1
// // StrategySectionView.swift // 小礼品 // // Created by 李莎鑫 on 2017/4/21. // Copyright © 2017年 李莎鑫. All rights reserved. // import UIKit import SnapKit class StrategySectionView: UICollectionReusableView { //MARK: 属性 weak var delegate:StrategySectionViewDelegate? //MARK: 懒加载 lazy var marginTopView:UIView = { () -> UIView in let view = UIView() return view }() lazy var leftLabel:UILabel = { () -> UILabel in let label = UILabel() label.textColor = normalColor label.font = fontSize15 label.numberOfLines = 1 label.text = "分类" return label }() lazy var rightButton:UIButton = { () -> UIButton in let button = UIButton(type: .custom) button.titleLabel?.font = fontSize14 button.setTitleColor(UIColor.gray, for: .normal) button.setTitle("查看全部", for: .normal) button.setImage(#imageLiteral(resourceName: "celldisclosureindicator_nightmode"), for: .normal) button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -3, bottom: 0, right: 0) button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -141) return button }() //MARK: 构造方法 override init(frame: CGRect) { super.init(frame: frame) setupStrategySectionView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { marginTopView.snp.makeConstraints { (make) in make.left.right.top.equalToSuperview() make.height.equalTo(12) } leftLabel.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(margin*1.5) make.bottom.equalToSuperview() } rightButton.snp.makeConstraints { (make) in make.bottom.equalToSuperview() make.right.equalToSuperview().offset(-margin) make.width.equalTo(100) } } //MARK: 私有方法 private func setupStrategySectionView() { addSubview(marginTopView) addSubview(leftLabel) addSubview(rightButton) rightButton.addTarget(self, action: #selector(rightButtonClick), for: .touchUpInside) } //MARK: 内部处理 @objc private func rightButtonClick() { delegate?.strategySectionViewRightButtonClick() } } //MARK: 协议方法 protocol StrategySectionViewDelegate:NSObjectProtocol { func strategySectionViewRightButtonClick() }
398a9eac3301971d40864d73a944fe67
27.977273
103
0.623529
false
false
false
false
drumnkyle/music-notation-swift
refs/heads/master
Sources/Types.swift
mit
1
// // Types.swift // MusicNotation // // Created by Kyle Sherman on 6/12/15. // Copyright (c) 2015 Kyle Sherman. All rights reserved. // public enum Octave: Int { case octaveNegative1 = -1 case octave0 = 0 case octave1 = 1 case octave2 = 2 case octave3 = 3 case octave4 = 4 case octave5 = 5 case octave6 = 6 case octave7 = 7 case octave8 = 8 case octave9 = 9 } public enum Striking { case left, up case right, down } public enum Accidental { case sharp case doubleSharp case flat case doubleFlat case natural } extension Accidental: CustomDebugStringConvertible { public var debugDescription: String { switch self { case .sharp: return "♯" case .doubleSharp: return "𝄪" case .flat: return "♭" case .doubleFlat: return "𝄫" case .natural: return "♮" } } } public enum NoteLetter: Int { case c = 1 case d case e case f case g case a case b } public enum Instrument { case guitar6 case drums } public enum Accent { case standard case strong case ghost } public enum Dynamics { case ppp case pp case p case mp case mf case f case ff case fff } public enum Tie { case begin case end case beginAndEnd } public enum KeyType { case major case minor }
8e14a3c3e68ad9fa11a61c73083db850
12.651685
57
0.687243
false
false
false
false
yonaskolb/XcodeGen
refs/heads/master
Tests/XcodeGenKitTests/ProjectGeneratorTests.swift
mit
1
import PathKit import ProjectSpec import Spectre import XcodeGenKit import XcodeProj import XCTest import Yams import TestSupport private let app = Target( name: "MyApp", type: .application, platform: .iOS, settings: Settings(buildSettings: ["SETTING_1": "VALUE"]), dependencies: [Dependency(type: .target, reference: "MyFramework")] ) private let framework = Target( name: "MyFramework", type: .framework, platform: .iOS, settings: Settings(buildSettings: ["SETTING_2": "VALUE"]) ) private let optionalFramework = Target( name: "MyOptionalFramework", type: .framework, platform: .iOS ) private let uiTest = Target( name: "MyAppUITests", type: .uiTestBundle, platform: .iOS, settings: Settings(buildSettings: ["SETTING_3": "VALUE"]), dependencies: [Dependency(type: .target, reference: "MyApp")] ) private let targets = [app, framework, optionalFramework, uiTest] class ProjectGeneratorTests: XCTestCase { func testOptions() throws { describe { $0.it("generates bundle id") { let options = SpecOptions(bundleIdPrefix: "com.test") let project = Project(name: "test", targets: [framework], options: options) let pbxProj = try project.generatePbxProj() guard let target = pbxProj.nativeTargets.first, let buildConfigList = target.buildConfigurationList, let buildConfig = buildConfigList.buildConfigurations.first else { throw failure("Build Config not found") } try expect(buildConfig.buildSettings["PRODUCT_BUNDLE_IDENTIFIER"] as? String) == "com.test.MyFramework" } $0.it("clears setting presets") { let options = SpecOptions(settingPresets: .none) let project = Project(name: "test", targets: [framework], options: options) let pbxProj = try project.generatePbxProj() let allSettings = pbxProj.buildConfigurations.reduce([:]) { $0.merged($1.buildSettings) }.keys.sorted() try expect(allSettings) == ["SDKROOT", "SETTING_2"] } $0.it("generates development language") { let options = SpecOptions(developmentLanguage: "de") let project = Project(name: "test", options: options) let pbxProj = try project.generatePbxProj() let pbxProject = try unwrap(pbxProj.projects.first) try expect(pbxProject.developmentRegion) == "de" } $0.it("formats xcode version") { let versions: [String: String] = [ "0900": "0900", "1010": "1010", "9": "0900", "9.0": "0900", "9.1": "0910", "9.1.1": "0911", "10": "1000", "10.1": "1010", "10.1.2": "1012", ] for (version, expected) in versions { try expect(XCodeVersion.parse(version)) == expected } } $0.it("uses the default configuration name") { let options = SpecOptions(defaultConfig: "Bconfig") let project = Project(name: "test", configs: [Config(name: "Aconfig"), Config(name: "Bconfig")], targets: [framework], options: options) let pbxProject = try project.generatePbxProj() guard let projectConfigList = pbxProject.projects.first?.buildConfigurationList, let defaultConfigurationName = projectConfigList.defaultConfigurationName else { throw failure("Default configuration name not found") } try expect(defaultConfigurationName) == "Bconfig" } $0.it("uses the default configuration name for every target in a project") { let options = SpecOptions(defaultConfig: "Bconfig") let project = Project( name: "test", configs: [ Config(name: "Aconfig"), Config(name: "Bconfig"), ], targets: [ Target(name: "1", type: .framework, platform: .iOS), Target(name: "2", type: .framework, platform: .iOS), ], options: options ) let pbxProject = try project.generatePbxProj() try pbxProject.projects.first?.targets.forEach { target in guard let buildConfigurationList = target.buildConfigurationList, let defaultConfigurationName = buildConfigurationList.defaultConfigurationName else { throw failure("Default configuration name not found") } try expect(defaultConfigurationName) == "Bconfig" } } } } func testConfigGenerator() { describe { $0.it("generates config defaults") { let project = Project(name: "test") let pbxProj = try project.generatePbxProj() let configs = pbxProj.buildConfigurations try expect(configs.count) == 2 try expect(configs).contains(name: "Debug") try expect(configs).contains(name: "Release") } $0.it("generates configs") { let project = Project( name: "test", configs: [Config(name: "config1"), Config(name: "config2")] ) let pbxProj = try project.generatePbxProj() let configs = pbxProj.buildConfigurations try expect(configs.count) == 2 try expect(configs).contains(name: "config1") try expect(configs).contains(name: "config2") } $0.it("clears config settings when missing type") { let project = Project( name: "test", configs: [Config(name: "config")] ) let pbxProj = try project.generatePbxProj() let config = try unwrap(pbxProj.buildConfigurations.first) try expect(config.buildSettings.isEmpty).to.beTrue() } $0.it("merges settings") { let project = try Project(path: fixturePath + "settings_test.yml") let config = try unwrap(project.getConfig("config1")) let debugProjectSettings = project.getProjectBuildSettings(config: config) let target = try unwrap(project.getTarget("Target")) let targetDebugSettings = project.getTargetBuildSettings(target: target, config: config) var buildSettings = BuildSettings() buildSettings += ["SDKROOT": "iphoneos"] buildSettings += SettingsPresetFile.base.getBuildSettings() buildSettings += SettingsPresetFile.config(.debug).getBuildSettings() buildSettings += [ "SETTING": "value", "SETTING 5": "value 5", "SETTING 6": "value 6", ] try expect(debugProjectSettings.equals(buildSettings)).beTrue() var expectedTargetDebugSettings = BuildSettings() expectedTargetDebugSettings += SettingsPresetFile.platform(.iOS).getBuildSettings() expectedTargetDebugSettings += SettingsPresetFile.product(.application).getBuildSettings() expectedTargetDebugSettings += SettingsPresetFile.productPlatform(.application, .iOS).getBuildSettings() expectedTargetDebugSettings += ["SETTING 2": "value 2", "SETTING 3": "value 3", "SETTING": "value"] try expect(targetDebugSettings.equals(expectedTargetDebugSettings)).beTrue() } $0.it("applies partial config settings") { let project = Project( name: "test", configs: [ Config(name: "Release", type: .release), Config(name: "Staging Debug", type: .debug), Config(name: "Staging Release", type: .release), ], settings: Settings(configSettings: [ "staging": ["SETTING1": "VALUE1"], "debug": ["SETTING2": "VALUE2"], "Release": ["SETTING3": "VALUE3"], ]) ) var buildSettings = project.getProjectBuildSettings(config: project.configs[1]) try expect(buildSettings["SETTING1"] as? String) == "VALUE1" try expect(buildSettings["SETTING2"] as? String) == "VALUE2" // don't apply partial when exact match buildSettings = project.getProjectBuildSettings(config: project.configs[2]) try expect(buildSettings["SETTING3"]).beNil() } $0.it("sets project SDKROOT if there is only a single platform") { var project = Project( name: "test", targets: [ Target(name: "1", type: .application, platform: .iOS), Target(name: "2", type: .framework, platform: .iOS), ] ) var buildSettings = project.getProjectBuildSettings(config: project.configs.first!) try expect(buildSettings["SDKROOT"] as? String) == "iphoneos" project.targets.append(Target(name: "3", type: .application, platform: .tvOS)) buildSettings = project.getProjectBuildSettings(config: project.configs.first!) try expect(buildSettings["SDKROOT"]).beNil() } } } func testAggregateTargets() { describe { let otherTarget = Target(name: "Other", type: .framework, platform: .iOS, dependencies: [Dependency(type: .target, reference: "AggregateTarget")]) let otherTarget2 = Target(name: "Other2", type: .framework, platform: .iOS, dependencies: [Dependency(type: .target, reference: "Other")], transitivelyLinkDependencies: true) let aggregateTarget = AggregateTarget(name: "AggregateTarget", targets: ["MyApp", "MyFramework"]) let aggregateTarget2 = AggregateTarget(name: "AggregateTarget2", targets: ["AggregateTarget"]) let project = Project(name: "test", targets: [app, framework, otherTarget, otherTarget2], aggregateTargets: [aggregateTarget, aggregateTarget2]) $0.it("generates aggregate targets") { let pbxProject = try project.generatePbxProj() let nativeTargets = pbxProject.nativeTargets.sorted { $0.name < $1.name } let aggregateTargets = pbxProject.aggregateTargets.sorted { $0.name < $1.name } try expect(nativeTargets.count) == 4 try expect(aggregateTargets.count) == 2 let aggregateTarget1 = aggregateTargets.first { $0.name == "AggregateTarget" } try expect(aggregateTarget1?.dependencies.count) == 2 let aggregateTarget2 = aggregateTargets.first { $0.name == "AggregateTarget2" } try expect(aggregateTarget2?.dependencies.count) == 1 let target1 = nativeTargets.first { $0.name == "Other" } try expect(target1?.dependencies.count) == 1 let target2 = nativeTargets.first { $0.name == "Other2" } try expect(target2?.dependencies.count) == 2 try expect(pbxProject.targetDependencies.count) == 7 } } } func testTargets() { describe { let project = Project(name: "test", targets: targets) $0.it("generates targets") { let pbxProject = try project.generatePbxProj() let nativeTargets = pbxProject.nativeTargets try expect(nativeTargets.count) == 4 try expect(nativeTargets.contains { $0.name == app.name }).beTrue() try expect(nativeTargets.contains { $0.name == framework.name }).beTrue() try expect(nativeTargets.contains { $0.name == uiTest.name }).beTrue() try expect(nativeTargets.contains { $0.name == optionalFramework.name }).beTrue() } $0.it("generates legacy target") { let target = Target(name: "target", type: .application, platform: .iOS, dependencies: [.init(type: .target, reference: "legacy")]) let legacyTarget = Target(name: "legacy", type: .none, platform: .iOS, legacy: .init(toolPath: "path")) let project = Project(name: "test", targets: [target, legacyTarget]) let pbxProject = try project.generatePbxProj() try expect(pbxProject.legacyTargets.count) == 1 } $0.it("generates target attributes") { var appTargetWithAttributes = app appTargetWithAttributes.settings.buildSettings["DEVELOPMENT_TEAM"] = "123" appTargetWithAttributes.attributes = ["ProvisioningStyle": "Automatic"] var testTargetWithAttributes = uiTest testTargetWithAttributes.settings.buildSettings["CODE_SIGN_STYLE"] = "Manual" let project = Project(name: "test", targets: [appTargetWithAttributes, framework, optionalFramework, testTargetWithAttributes]) let pbxProject = try project.generatePbxProj() let targetAttributes = try unwrap(pbxProject.projects.first?.targetAttributes) let appTarget = try unwrap(pbxProject.targets(named: app.name).first) let uiTestTarget = try unwrap(pbxProject.targets(named: uiTest.name).first) try expect((targetAttributes[uiTestTarget]?["TestTargetID"] as? PBXNativeTarget)?.name) == app.name try expect(targetAttributes[uiTestTarget]?["ProvisioningStyle"] as? String) == "Manual" try expect(targetAttributes[appTarget]?["ProvisioningStyle"] as? String) == "Automatic" try expect(targetAttributes[appTarget]?["DevelopmentTeam"] as? String) == "123" } $0.it("generates platform version") { let target = Target(name: "Target", type: .application, platform: .watchOS, deploymentTarget: "2.0") let project = Project(name: "", targets: [target], options: .init(deploymentTarget: DeploymentTarget(iOS: "10.0", watchOS: "3.0"))) let pbxProject = try project.generatePbxProj() let projectConfig = try unwrap(pbxProject.projects.first?.buildConfigurationList?.buildConfigurations.first) let targetConfig = try unwrap(pbxProject.nativeTargets.first?.buildConfigurationList?.buildConfigurations.first) try expect(projectConfig.buildSettings["IPHONEOS_DEPLOYMENT_TARGET"] as? String) == "10.0" try expect(projectConfig.buildSettings["WATCHOS_DEPLOYMENT_TARGET"] as? String) == "3.0" try expect(projectConfig.buildSettings["TVOS_DEPLOYMENT_TARGET"]).beNil() try expect(targetConfig.buildSettings["IPHONEOS_DEPLOYMENT_TARGET"]).beNil() try expect(targetConfig.buildSettings["WATCHOS_DEPLOYMENT_TARGET"] as? String) == "2.0" try expect(targetConfig.buildSettings["TVOS_DEPLOYMENT_TARGET"]).beNil() } $0.it("generates dependencies") { let pbxProject = try project.generatePbxProj() let nativeTargets = pbxProject.nativeTargets let dependencies = pbxProject.targetDependencies.sorted { $0.target?.name ?? "" < $1.target?.name ?? "" } try expect(dependencies.count) == 2 let appTarget = nativeTargets.first { $0.name == app.name } let frameworkTarget = nativeTargets.first { $0.name == framework.name } try expect(dependencies).contains { $0.target == appTarget } try expect(dependencies).contains { $0.target == frameworkTarget } } $0.it("generates dependency from external project file") { let subproject: PBXProj prepareXcodeProj: do { let project = try! Project(path: fixturePath + "TestProject/AnotherProject/project.yml") let generator = ProjectGenerator(project: project) let writer = FileWriter(project: project) let xcodeProject = try! generator.generateXcodeProject() try! writer.writeXcodeProject(xcodeProject) try! writer.writePlists() subproject = xcodeProject.pbxproj } let externalProjectPath = fixturePath + "TestProject/AnotherProject/AnotherProject.xcodeproj" let projectReference = ProjectReference(name: "AnotherProject", path: externalProjectPath.string) var target = app target.dependencies = [ Dependency(type: .target, reference: "AnotherProject/ExternalTarget"), ] let project = Project( name: "test", targets: [target], schemes: [], projectReferences: [projectReference] ) let pbxProject = try project.generatePbxProj() let projectReferences = pbxProject.rootObject?.projects ?? [] try expect(projectReferences.count) == 1 try expect((projectReferences.first?["ProjectRef"])?.name) == "AnotherProject" let dependencies = pbxProject.targetDependencies let targetUuid = subproject.targets(named: "ExternalTarget").first?.uuid try expect(dependencies.count) == 1 try expect(dependencies).contains { dependency in guard let id = dependency.targetProxy?.remoteGlobalID else { return false } switch id { case .object(let object): return object.uuid == targetUuid case .string(let value): return value == targetUuid } } } $0.it("generates targets with correct transitive embeds") { // App # Embeds it's frameworks, so shouldn't embed in tests // dependencies: // - framework: FrameworkA.framework // - framework: FrameworkB.framework // embed: false // iOSFrameworkZ: // dependencies: [] // iOSFrameworkX: // dependencies: [] // StaticLibrary: // dependencies: // - target: iOSFrameworkZ // - framework: FrameworkZ.framework // - carthage: CarthageZ // ResourceBundle // dependencies: [] // iOSFrameworkA // dependencies: // - target: StaticLibrary // - target: ResourceBundle // # Won't embed FrameworkC.framework, so should embed in tests // - framework: FrameworkC.framework // - carthage: CarthageA // - carthage: CarthageB // embed: false // - package: RxSwift // product: RxSwift // - package: RxSwift // product: RxCocoa // - package: RxSwift // product: RxRelay // iOSFrameworkB // dependencies: // - target: iOSFrameworkA // # Won't embed FrameworkD.framework, so should embed in tests // - framework: FrameworkD.framework // - framework: FrameworkE.framework // embed: true // - framework: FrameworkF.framework // embed: false // - carthage: CarthageC // embed: true // AppTest // dependencies: // # Being an app, shouldn't be embedded // - target: App // - target: iOSFrameworkB // - carthage: CarthageD // # should be implicitly added // # - target: iOSFrameworkA // # embed: true // # - target: StaticLibrary // # embed: false // # - framework: FrameworkZ.framework // # - target: iOSFrameworkZ // # embed: true // # - carthage: CarthageZ // # embed: false // # - carthage: CarthageA // # embed: true // # - framework: FrameworkC.framework // # embed: true // # - framework: FrameworkD.framework // # embed: true // // AppTestWithoutTransitive // dependencies: // # Being an app, shouldn't be embedded // - target: App // - target: iOSFrameworkB // - carthage: CarthageD // // packages: // RxSwift: // url: https://github.com/ReactiveX/RxSwift // majorVersion: 5.1.0 var expectedResourceFiles: [String: Set<String>] = [:] var expectedBundlesFiles: [String: Set<String>] = [:] var expectedLinkedFiles: [String: Set<String>] = [:] var expectedEmbeddedFrameworks: [String: Set<String>] = [:] let app = Target( name: "App", type: .application, platform: .iOS, // Embeds it's frameworks, so they shouldn't embed in AppTest dependencies: [ Dependency(type: .framework, reference: "FrameworkA.framework"), Dependency(type: .framework, reference: "FrameworkB.framework", embed: false), ] ) expectedResourceFiles[app.name] = Set() expectedLinkedFiles[app.name] = Set([ "FrameworkA.framework", "FrameworkB.framework", ]) expectedEmbeddedFrameworks[app.name] = Set([ "FrameworkA.framework", ]) let iosFrameworkZ = Target( name: "iOSFrameworkZ", type: .framework, platform: .iOS, dependencies: [] ) expectedResourceFiles[iosFrameworkZ.name] = Set() expectedLinkedFiles[iosFrameworkZ.name] = Set() expectedEmbeddedFrameworks[iosFrameworkZ.name] = Set() let iosFrameworkX = Target( name: "iOSFrameworkX", type: .framework, platform: .iOS, dependencies: [] ) expectedResourceFiles[iosFrameworkX.name] = Set() expectedLinkedFiles[iosFrameworkX.name] = Set() expectedEmbeddedFrameworks[iosFrameworkX.name] = Set() let staticLibrary = Target( name: "StaticLibrary", type: .staticLibrary, platform: .iOS, dependencies: [ Dependency(type: .target, reference: iosFrameworkZ.name, link: true), Dependency(type: .framework, reference: "FrameworkZ.framework", link: true), Dependency(type: .target, reference: iosFrameworkX.name /* , link: false */ ), Dependency(type: .framework, reference: "FrameworkX.framework" /* , link: false */ ), Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "CarthageZ"), Dependency(type: .bundle, reference: "BundleA.bundle"), ] ) expectedResourceFiles[staticLibrary.name] = Set() expectedBundlesFiles[staticLibrary.name] = Set() expectedLinkedFiles[staticLibrary.name] = Set([ iosFrameworkZ.filename, "FrameworkZ.framework", ]) expectedEmbeddedFrameworks[staticLibrary.name] = Set() let resourceBundle = Target( name: "ResourceBundle", type: .bundle, platform: .iOS, dependencies: [] ) expectedResourceFiles[resourceBundle.name] = Set() expectedLinkedFiles[resourceBundle.name] = Set() expectedEmbeddedFrameworks[resourceBundle.name] = Set() let iosFrameworkA = Target( name: "iOSFrameworkA", type: .framework, platform: .iOS, dependencies: [ Dependency(type: .target, reference: resourceBundle.name), Dependency(type: .framework, reference: "FrameworkC.framework"), Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "CarthageA"), Dependency(type: .package(product: "RxSwift"), reference: "RxSwift"), Dependency(type: .package(product: "RxCocoa"), reference: "RxSwift"), Dependency(type: .package(product: "RxRelay"), reference: "RxSwift"), // Validate - Do not link package Dependency(type: .package(product: "KeychainAccess"), reference: "KeychainAccess", link: false), // Statically linked, so don't embed into test Dependency(type: .target, reference: staticLibrary.name), Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "CarthageB", embed: false), Dependency(type: .bundle, reference: "BundleA.bundle"), ] ) expectedResourceFiles[iosFrameworkA.name] = Set() expectedBundlesFiles[iosFrameworkA.name] = Set([ "BundleA.bundle", ]) expectedLinkedFiles[iosFrameworkA.name] = Set([ "FrameworkC.framework", iosFrameworkZ.filename, iosFrameworkX.filename, "FrameworkZ.framework", "FrameworkX.framework", "CarthageZ.framework", "CarthageA.framework", "CarthageB.framework", "RxSwift", "RxCocoa", "RxRelay", ]) expectedEmbeddedFrameworks[iosFrameworkA.name] = Set() let iosFrameworkB = Target( name: "iOSFrameworkB", type: .framework, platform: .iOS, dependencies: [ Dependency(type: .target, reference: iosFrameworkA.name), Dependency(type: .framework, reference: "FrameworkD.framework"), // Embedded into framework, so don't embed into test Dependency(type: .framework, reference: "FrameworkE.framework", embed: true), Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "CarthageC", embed: true), // Statically linked, so don't embed into test Dependency(type: .framework, reference: "FrameworkF.framework", embed: false), ] ) expectedResourceFiles[iosFrameworkB.name] = Set() expectedLinkedFiles[iosFrameworkB.name] = Set([ iosFrameworkA.filename, iosFrameworkZ.filename, iosFrameworkX.filename, "FrameworkZ.framework", "FrameworkX.framework", "CarthageZ.framework", "FrameworkC.framework", "FrameworkD.framework", "FrameworkE.framework", "FrameworkF.framework", "CarthageA.framework", "CarthageB.framework", "CarthageC.framework", "RxSwift", "RxCocoa", "RxRelay", ]) expectedEmbeddedFrameworks[iosFrameworkB.name] = Set([ "FrameworkE.framework", "CarthageC.framework", ]) let appTest = Target( name: "AppTest", type: .unitTestBundle, platform: .iOS, dependencies: [ Dependency(type: .target, reference: app.name), Dependency(type: .target, reference: iosFrameworkB.name), Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "CarthageD"), ], directlyEmbedCarthageDependencies: false ) expectedResourceFiles[appTest.name] = Set([ resourceBundle.filename, ]) expectedLinkedFiles[appTest.name] = Set([ iosFrameworkA.filename, staticLibrary.filename, iosFrameworkZ.filename, iosFrameworkX.filename, "FrameworkZ.framework", "FrameworkX.framework", "CarthageZ.framework", "FrameworkF.framework", "FrameworkC.framework", iosFrameworkB.filename, "FrameworkD.framework", "CarthageA.framework", "CarthageB.framework", "CarthageD.framework", "RxSwift", "RxCocoa", "RxRelay", ]) expectedEmbeddedFrameworks[appTest.name] = Set([ iosFrameworkA.filename, iosFrameworkZ.filename, iosFrameworkX.filename, "FrameworkZ.framework", "FrameworkX.framework", "FrameworkC.framework", iosFrameworkB.filename, "FrameworkD.framework", ]) var appTestWithoutTransitive = appTest appTestWithoutTransitive.name = "AppTestWithoutTransitive" appTestWithoutTransitive.transitivelyLinkDependencies = false expectedResourceFiles[appTestWithoutTransitive.name] = Set([]) expectedLinkedFiles[appTestWithoutTransitive.name] = Set([ iosFrameworkB.filename, "CarthageD.framework", ]) expectedEmbeddedFrameworks[appTestWithoutTransitive.name] = Set([ iosFrameworkB.filename, ]) let XCTestPath = "Platforms/iPhoneOS.platform/Developer/Library/Frameworks/XCTest.framework" let GXToolsPath = "Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks/GXTools.framework" let XCTAutomationPath = "Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks/XCTAutomationSupport.framework" let stickerPack = Target( name: "MyStickerApp", type: .stickerPack, platform: .iOS, dependencies: [ Dependency(type: .sdk(root: nil), reference: "NotificationCenter.framework"), Dependency(type: .sdk(root: "DEVELOPER_DIR"), reference: XCTestPath), Dependency(type: .sdk(root: "DEVELOPER_DIR"), reference: GXToolsPath, embed: true), Dependency(type: .sdk(root: "DEVELOPER_DIR"), reference: XCTAutomationPath, embed: true, codeSign: true), ] ) expectedResourceFiles[stickerPack.name] = nil expectedLinkedFiles[stickerPack.name] = Set([ "XCTest.framework", "NotificationCenter.framework", "GXTools.framework", "XCTAutomationSupport.framework" ]) expectedEmbeddedFrameworks[stickerPack.name] = Set([ "GXTools.framework", "XCTAutomationSupport.framework" ]) let targets = [app, iosFrameworkZ, iosFrameworkX, staticLibrary, resourceBundle, iosFrameworkA, iosFrameworkB, appTest, appTestWithoutTransitive, stickerPack] let packages: [String: SwiftPackage] = [ "RxSwift": .remote(url: "https://github.com/ReactiveX/RxSwift", versionRequirement: .upToNextMajorVersion("5.1.1")), "KeychainAccess": .remote(url: "https://github.com/kishikawakatsumi/KeychainAccess", versionRequirement: .upToNextMajorVersion("4.2.0")) ] let project = Project( name: "test", targets: targets, packages: packages, options: SpecOptions(transitivelyLinkDependencies: true) ) let pbxProject = try project.generatePbxProj() for target in targets { let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == target.name })) let buildPhases = nativeTarget.buildPhases let resourcesPhases = pbxProject.resourcesBuildPhases.filter { buildPhases.contains($0) } let frameworkPhases = pbxProject.frameworksBuildPhases.filter { buildPhases.contains($0) } let copyFilesPhases = pbxProject.copyFilesBuildPhases.filter { buildPhases.contains($0) } let embedFrameworkPhase = copyFilesPhases.first { $0.dstSubfolderSpec == .frameworks } let copyBundlesPhase = copyFilesPhases.first { $0.dstSubfolderSpec == .resources } // All targets should have a compile sources phase, // except for the resourceBundle and sticker pack one let targetsGeneratingSourcePhases = targets .filter { ![.bundle, .stickerPack].contains($0.type) } let sourcesPhases = pbxProject.sourcesBuildPhases try expect(sourcesPhases.count) == targetsGeneratingSourcePhases.count // ensure only the right resources are copied, no more, no less if let expectedResourceFiles = expectedResourceFiles[target.name] { try expect(resourcesPhases.count) == (expectedResourceFiles.isEmpty ? 0 : 1) if !expectedResourceFiles.isEmpty { let resourceFiles = (resourcesPhases[0].files ?? []) .compactMap { $0.file } .map { $0.nameOrPath } try expect(Set(resourceFiles)) == expectedResourceFiles } } else { try expect(resourcesPhases.count) == 0 } // ensure only the right things are linked, no more, no less let expectedLinkedFiles = expectedLinkedFiles[target.name]! try expect(frameworkPhases.count) == (expectedLinkedFiles.isEmpty ? 0 : 1) if !expectedLinkedFiles.isEmpty { let linkFrameworks = (frameworkPhases[0].files ?? []) .compactMap { $0.file?.nameOrPath } let linkPackages = (frameworkPhases[0].files ?? []) .compactMap { $0.product?.productName } try expect(Array(Set(linkFrameworks + linkPackages)).sorted()) == Array(expectedLinkedFiles).sorted() } var expectedCopyFilesPhasesCount = 0 // ensure only the right things are embedded, no more, no less if let expectedEmbeddedFrameworks = expectedEmbeddedFrameworks[target.name], !expectedEmbeddedFrameworks.isEmpty { expectedCopyFilesPhasesCount += 1 let copyFiles = (embedFrameworkPhase?.files ?? []) .compactMap { $0.file?.nameOrPath } try expect(Set(copyFiles)) == expectedEmbeddedFrameworks } if let expectedBundlesFiles = expectedBundlesFiles[target.name], target.type != .staticLibrary && target.type != .dynamicLibrary { expectedCopyFilesPhasesCount += 1 let copyBundles = (copyBundlesPhase?.files ?? []) .compactMap { $0.file?.nameOrPath } try expect(Set(copyBundles)) == expectedBundlesFiles } try expect(copyFilesPhases.count) == expectedCopyFilesPhasesCount } } $0.it("ensures static frameworks are not embedded by default") { let app = Target( name: "App", type: .application, platform: .iOS, dependencies: [ Dependency(type: .target, reference: "DynamicFramework"), Dependency(type: .target, reference: "DynamicFrameworkNotEmbedded", embed: false), Dependency(type: .target, reference: "StaticFramework"), Dependency(type: .target, reference: "StaticFrameworkExplicitlyEmbedded", embed: true), Dependency(type: .target, reference: "StaticFramework2"), Dependency(type: .target, reference: "StaticFramework2ExplicitlyEmbedded", embed: true), Dependency(type: .target, reference: "StaticLibrary"), ] ) let targets = [ app, Target( name: "DynamicFramework", type: .framework, platform: .iOS ), Target( name: "DynamicFrameworkNotEmbedded", type: .framework, platform: .iOS ), Target( name: "StaticFramework", type: .framework, platform: .iOS, settings: Settings(buildSettings: ["MACH_O_TYPE": "staticlib"]) ), Target( name: "StaticFrameworkExplicitlyEmbedded", type: .framework, platform: .iOS, settings: Settings(buildSettings: ["MACH_O_TYPE": "staticlib"]) ), Target( name: "StaticFramework2", type: .staticFramework, platform: .iOS ), Target( name: "StaticFramework2ExplicitlyEmbedded", type: .staticFramework, platform: .iOS ), Target( name: "StaticLibrary", type: .staticLibrary, platform: .iOS ), ] let expectedLinkedFiles = Set([ "DynamicFramework.framework", "DynamicFrameworkNotEmbedded.framework", "StaticFramework.framework", "StaticFrameworkExplicitlyEmbedded.framework", "StaticFramework2.framework", "StaticFramework2ExplicitlyEmbedded.framework", "libStaticLibrary.a", ]) let expectedEmbeddedFrameworks = Set([ "DynamicFramework.framework", "StaticFrameworkExplicitlyEmbedded.framework", "StaticFramework2ExplicitlyEmbedded.framework" ]) let project = Project( name: "test", targets: targets ) let pbxProject = try project.generatePbxProj() let appTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == app.name })) let buildPhases = appTarget.buildPhases let frameworkPhases = pbxProject.frameworksBuildPhases.filter { buildPhases.contains($0) } let copyFilesPhases = pbxProject.copyFilesBuildPhases.filter { buildPhases.contains($0) } let embedFrameworkPhase = copyFilesPhases.first { $0.dstSubfolderSpec == .frameworks } // Ensure all targets are linked let linkFrameworks = (frameworkPhases[0].files ?? []).compactMap { $0.file?.nameOrPath } let linkPackages = (frameworkPhases[0].files ?? []).compactMap { $0.product?.productName } try expect(Set(linkFrameworks + linkPackages)) == expectedLinkedFiles // Ensure only dynamic frameworks are embedded (unless there's an explicit override) let embeddedFrameworks = Set((embedFrameworkPhase?.files ?? []).compactMap { $0.file?.nameOrPath }) try expect(embeddedFrameworks) == expectedEmbeddedFrameworks } $0.it("copies files only on install in the Embed Frameworks step") { let app = Target( name: "App", type: .application, platform: .iOS, // Embeds it's frameworks, so they shouldn't embed in AppTest dependencies: [ Dependency(type: .framework, reference: "FrameworkA.framework"), Dependency(type: .framework, reference: "FrameworkB.framework", embed: false), ], onlyCopyFilesOnInstall: true ) let project = Project(name: "test",targets: [app]) let pbxProject = try project.generatePbxProj() let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == app.name })) let buildPhases = nativeTarget.buildPhases let embedFrameworksPhase = pbxProject .copyFilesBuildPhases .filter { buildPhases.contains($0) } .first { $0.dstSubfolderSpec == .frameworks } let phase = try unwrap(embedFrameworksPhase) try expect(phase.buildActionMask) == PBXProjGenerator.copyFilesActionMask try expect(phase.runOnlyForDeploymentPostprocessing) == true } $0.it("copies files only on install in the Embed App Extensions step") { let appExtension = Target( name: "AppExtension", type: .appExtension, platform: .tvOS ) let app = Target( name: "App", type: .application, platform: .tvOS, dependencies: [ Dependency(type: .target, reference: "AppExtension") ], onlyCopyFilesOnInstall: true ) let project = Project(name: "test", targets: [app, appExtension]) let pbxProject = try project.generatePbxProj() let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == app.name })) let buildPhases = nativeTarget.buildPhases let embedAppExtensionsPhase = pbxProject .copyFilesBuildPhases .filter { buildPhases.contains($0) } .first { $0.dstSubfolderSpec == .plugins } let phase = try unwrap(embedAppExtensionsPhase) try expect(phase.buildActionMask) == PBXProjGenerator.copyFilesActionMask try expect(phase.runOnlyForDeploymentPostprocessing) == true } $0.it("copies files only on install in the Embed Frameworks and Embed App Extensions steps") { let appExtension = Target( name: "AppExtension", type: .appExtension, platform: .tvOS ) let app = Target( name: "App", type: .application, platform: .tvOS, dependencies: [ Dependency(type: .target, reference: "AppExtension"), Dependency(type: .framework, reference: "FrameworkA.framework"), Dependency(type: .framework, reference: "FrameworkB.framework", embed: false), ], onlyCopyFilesOnInstall: true ) let project = Project(name: "test", targets: [app, appExtension]) let pbxProject = try project.generatePbxProj() let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == app.name })) let buildPhases = nativeTarget.buildPhases let embedFrameworksPhase = pbxProject .copyFilesBuildPhases .filter { buildPhases.contains($0) } .first { $0.dstSubfolderSpec == .frameworks } let embedFrameworksPhaseValue = try unwrap(embedFrameworksPhase) try expect(embedFrameworksPhaseValue.buildActionMask) == PBXProjGenerator.copyFilesActionMask try expect(embedFrameworksPhaseValue.runOnlyForDeploymentPostprocessing) == true let embedAppExtensionsPhase = pbxProject .copyFilesBuildPhases .filter { buildPhases.contains($0) } .first { $0.dstSubfolderSpec == .plugins } let embedAppExtensionsPhaseValue = try unwrap(embedAppExtensionsPhase) try expect(embedAppExtensionsPhaseValue.buildActionMask) == PBXProjGenerator.copyFilesActionMask try expect(embedAppExtensionsPhaseValue.runOnlyForDeploymentPostprocessing) == true } $0.it("sets -ObjC for targets that depend on requiresObjCLinking targets") { let requiresObjCLinking = Target( name: "requiresObjCLinking", type: .staticLibrary, platform: .iOS, dependencies: [], requiresObjCLinking: true ) let doesntRequireObjCLinking = Target( name: "doesntRequireObjCLinking", type: .staticLibrary, platform: .iOS, dependencies: [], requiresObjCLinking: false ) let implicitlyRequiresObjCLinking = Target( name: "implicitlyRequiresObjCLinking", type: .staticLibrary, platform: .iOS, sources: [TargetSource(path: "StaticLibrary_ObjC/StaticLibrary_ObjC.m")], dependencies: [] ) let framework = Target( name: "framework", type: .framework, platform: .iOS, dependencies: [Dependency(type: .target, reference: requiresObjCLinking.name, link: false)] ) let app1 = Target( name: "app1", type: .application, platform: .iOS, dependencies: [Dependency(type: .target, reference: requiresObjCLinking.name)] ) let app2 = Target( name: "app2", type: .application, platform: .iOS, dependencies: [Dependency(type: .target, reference: doesntRequireObjCLinking.name)] ) let app3 = Target( name: "app3", type: .application, platform: .iOS, dependencies: [Dependency(type: .target, reference: implicitlyRequiresObjCLinking.name)] ) let targets = [requiresObjCLinking, doesntRequireObjCLinking, implicitlyRequiresObjCLinking, framework, app1, app2, app3] let project = Project( basePath: fixturePath + "TestProject", name: "test", targets: targets, options: SpecOptions() ) let pbxProj = try project.generatePbxProj() func buildSettings(for target: Target) throws -> BuildSettings { guard let nativeTarget = pbxProj.targets(named: target.name).first, let buildConfigList = nativeTarget.buildConfigurationList, let buildConfig = buildConfigList.buildConfigurations.first else { throw failure("XCBuildConfiguration not found for Target \(target.name.quoted)") } return buildConfig.buildSettings } let frameworkOtherLinkerSettings = try buildSettings(for: framework)["OTHER_LDFLAGS"] as? [String] ?? [] let app1OtherLinkerSettings = try buildSettings(for: app1)["OTHER_LDFLAGS"] as? [String] ?? [] let app2OtherLinkerSettings = try buildSettings(for: app2)["OTHER_LDFLAGS"] as? [String] ?? [] let app3OtherLinkerSettings = try buildSettings(for: app3)["OTHER_LDFLAGS"] as? [String] ?? [] try expect(frameworkOtherLinkerSettings.contains("-ObjC")) == false try expect(app1OtherLinkerSettings.contains("-ObjC")) == true try expect(app2OtherLinkerSettings.contains("-ObjC")) == false try expect(app3OtherLinkerSettings.contains("-ObjC")) == true } $0.it("copies Swift Objective-C Interface Header") { let swiftStaticLibraryWithHeader = Target( name: "swiftStaticLibraryWithHeader", type: .staticLibrary, platform: .iOS, sources: [TargetSource(path: "StaticLibrary_Swift/StaticLibrary.swift")], dependencies: [] ) let swiftStaticLibraryWithoutHeader1 = Target( name: "swiftStaticLibraryWithoutHeader1", type: .staticLibrary, platform: .iOS, settings: Settings(buildSettings: ["SWIFT_OBJC_INTERFACE_HEADER_NAME": ""]), sources: [TargetSource(path: "StaticLibrary_Swift/StaticLibrary.swift")], dependencies: [] ) let swiftStaticLibraryWithoutHeader2 = Target( name: "swiftStaticLibraryWithoutHeader2", type: .staticLibrary, platform: .iOS, settings: Settings(buildSettings: ["SWIFT_INSTALL_OBJC_HEADER": false]), sources: [TargetSource(path: "StaticLibrary_Swift/StaticLibrary.swift")], dependencies: [] ) let swiftStaticLibraryWithoutHeader3 = Target( name: "swiftStaticLibraryWithoutHeader3", type: .staticLibrary, platform: .iOS, settings: Settings(buildSettings: ["SWIFT_INSTALL_OBJC_HEADER": "NO"]), sources: [TargetSource(path: "StaticLibrary_Swift/StaticLibrary.swift")], dependencies: [] ) let objCStaticLibrary = Target( name: "objCStaticLibrary", type: .staticLibrary, platform: .iOS, sources: [TargetSource(path: "StaticLibrary_ObjC/StaticLibrary_ObjC.m")], dependencies: [] ) let targets = [swiftStaticLibraryWithHeader, swiftStaticLibraryWithoutHeader1, swiftStaticLibraryWithoutHeader2, swiftStaticLibraryWithoutHeader3, objCStaticLibrary] let project = Project( basePath: fixturePath + "TestProject", name: "test", targets: targets, options: SpecOptions() ) let pbxProject = try project.generatePbxProj() func scriptBuildPhases(target: Target) throws -> [PBXShellScriptBuildPhase] { let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == target.name })) let buildPhases = nativeTarget.buildPhases let scriptPhases = buildPhases.compactMap { $0 as? PBXShellScriptBuildPhase } return scriptPhases } let expectedScriptPhase = PBXShellScriptBuildPhase( name: "Copy Swift Objective-C Interface Header", inputPaths: ["$(DERIVED_SOURCES_DIR)/$(SWIFT_OBJC_INTERFACE_HEADER_NAME)"], outputPaths: ["$(BUILT_PRODUCTS_DIR)/include/$(PRODUCT_MODULE_NAME)/$(SWIFT_OBJC_INTERFACE_HEADER_NAME)"], shellPath: "/bin/sh", shellScript: "ditto \"${SCRIPT_INPUT_FILE_0}\" \"${SCRIPT_OUTPUT_FILE_0}\"\n" ) try expect(scriptBuildPhases(target: swiftStaticLibraryWithHeader)) == [expectedScriptPhase] try expect(scriptBuildPhases(target: swiftStaticLibraryWithoutHeader1)) == [] try expect(scriptBuildPhases(target: swiftStaticLibraryWithoutHeader2)) == [] try expect(scriptBuildPhases(target: swiftStaticLibraryWithoutHeader3)) == [] try expect(scriptBuildPhases(target: objCStaticLibrary)) == [] } $0.it("generates run scripts") { var scriptSpec = project scriptSpec.targets[0].preBuildScripts = [BuildScript(script: .script("script1"))] scriptSpec.targets[0].postCompileScripts = [BuildScript(script: .script("script2"))] scriptSpec.targets[0].postBuildScripts = [ BuildScript(script: .script("script3")), BuildScript(script: .script("script4"), discoveredDependencyFile: "$(DERIVED_FILE_DIR)/target.d") ] let pbxProject = try scriptSpec.generatePbxProj() let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.buildPhases.count >= 4 })) let buildPhases = nativeTarget.buildPhases let scripts = pbxProject.shellScriptBuildPhases try expect(scripts.count) == 4 let script1 = scripts.first { $0.shellScript == "script1" }! let script2 = scripts.first { $0.shellScript == "script2" }! let script3 = scripts.first { $0.shellScript == "script3" }! let script4 = scripts.first { $0.shellScript == "script4" }! try expect(buildPhases.contains(script1)) == true try expect(buildPhases.contains(script2)) == true try expect(buildPhases.contains(script3)) == true try expect(buildPhases.contains(script4)) == true try expect(script1.dependencyFile).beNil() try expect(script2.dependencyFile).beNil() try expect(script3.dependencyFile).beNil() try expect(script4.dependencyFile) == "$(DERIVED_FILE_DIR)/target.d" } $0.it("generates targets with cylical dependencies") { let target1 = Target( name: "target1", type: .framework, platform: .iOS, dependencies: [Dependency(type: .target, reference: "target2")] ) let target2 = Target( name: "target2", type: .framework, platform: .iOS, dependencies: [Dependency(type: .target, reference: "target1")] ) let project = Project( name: "test", targets: [target1, target2] ) _ = try project.generatePbxProj() } $0.it("generates build rules") { var scriptSpec = project scriptSpec.targets[0].buildRules = [ BuildRule( fileType: .type("sourcecode.swift"), action: .script("do thing"), name: "My Rule", outputFiles: ["file1.swift", "file2.swift"], outputFilesCompilerFlags: ["--zee", "--bee"] ), BuildRule( fileType: .pattern("*.plist"), action: .compilerSpec("com.apple.build-tasks.copy-plist-file") ), ] let pbxProject = try scriptSpec.generatePbxProj() let buildRules = pbxProject.buildRules try expect(buildRules.count) == 2 let first = buildRules.first { $0.name == "My Rule" }! let second = buildRules.first { $0.name != "My Rule" }! try expect(first.name) == "My Rule" try expect(first.isEditable) == true try expect(first.outputFiles) == ["file1.swift", "file2.swift"] try expect(first.outputFilesCompilerFlags) == ["--zee", "--bee"] try expect(first.script) == "do thing" try expect(first.fileType) == "sourcecode.swift" try expect(first.compilerSpec) == "com.apple.compilers.proxy.script" try expect(first.filePatterns).beNil() try expect(second.name) == "Build Rule" try expect(second.fileType) == "pattern.proxy" try expect(second.filePatterns) == "*.plist" try expect(second.compilerSpec) == "com.apple.build-tasks.copy-plist-file" try expect(second.script).beNil() try expect(second.outputFiles) == [] try expect(second.outputFilesCompilerFlags) == [] } $0.it("generates dependency build file settings") { let app = Target( name: "MyApp", type: .application, platform: .iOS, dependencies: [ Dependency(type: .target, reference: "MyFramework"), Dependency(type: .target, reference: "MyOptionalFramework", weakLink: true), ] ) let project = Project(name: "test", targets: [app, framework, optionalFramework, uiTest]) let pbxProject = try project.generatePbxProj() let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == app.name })) let frameworkPhases = nativeTarget.buildPhases.compactMap { $0 as? PBXFrameworksBuildPhase } let frameworkBuildFiles = frameworkPhases[0].files ?? [] let buildFileSettings = frameworkBuildFiles.map { $0.settings } try expect(frameworkBuildFiles.count) == 2 try expect(buildFileSettings.compactMap { $0 }.count) == 1 try expect(buildFileSettings.compactMap { $0?["ATTRIBUTES"] }.count) == 1 try expect(buildFileSettings.compactMap { $0?["ATTRIBUTES"] as? [String] }.first) == ["Weak"] } $0.it("generates swift packages") { let app = Target( name: "MyApp", type: .application, platform: .iOS, dependencies: [ Dependency(type: .package(product: "ProjectSpec"), reference: "XcodeGen"), Dependency(type: .package(product: nil), reference: "Codability"), ] ) let project = Project(name: "test", targets: [app], packages: [ "XcodeGen": .remote(url: "http://github.com/yonaskolb/XcodeGen", versionRequirement: .branch("master")), "Codability": .remote(url: "http://github.com/yonaskolb/Codability", versionRequirement: .exact("1.0.0")), "Yams": .local(path: "../Yams", group: nil), ], options: .init(localPackagesGroup: "MyPackages")) let pbxProject = try project.generatePbxProj(specValidate: false) let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == app.name })) let projectSpecDependency = try unwrap(nativeTarget.packageProductDependencies.first(where: { $0.productName == "ProjectSpec" })) try expect(projectSpecDependency.package?.name) == "XcodeGen" try expect(projectSpecDependency.package?.versionRequirement) == .branch("master") let codabilityDependency = try unwrap(nativeTarget.packageProductDependencies.first(where: { $0.productName == "Codability" })) try expect(codabilityDependency.package?.name) == "Codability" try expect(codabilityDependency.package?.versionRequirement) == .exact("1.0.0") let localPackagesGroup = try unwrap(try pbxProject.getMainGroup().children.first(where: { $0.name == "MyPackages" }) as? PBXGroup) let yamsLocalPackageFile = try unwrap(pbxProject.fileReferences.first(where: { $0.path == "../Yams" })) try expect(localPackagesGroup.children.contains(yamsLocalPackageFile)) == true try expect(yamsLocalPackageFile.lastKnownFileType) == "folder" } $0.it("generates local swift packages") { let app = Target( name: "MyApp", type: .application, platform: .iOS, dependencies: [ Dependency(type: .package(product: nil), reference: "XcodeGen"), ] ) let project = Project(name: "test", targets: [app], packages: ["XcodeGen": .local(path: "../XcodeGen", group: nil)]) let pbxProject = try project.generatePbxProj(specValidate: false) let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == app.name })) let localPackageFile = try unwrap(pbxProject.fileReferences.first(where: { $0.path == "../XcodeGen" })) try expect(localPackageFile.lastKnownFileType) == "folder" let frameworkPhases = nativeTarget.buildPhases.compactMap { $0 as? PBXFrameworksBuildPhase } guard let frameworkPhase = frameworkPhases.first else { return XCTFail("frameworkPhases should have more than one") } guard let file = frameworkPhase.files?.first else { return XCTFail("frameworkPhase should have file") } try expect(file.product?.productName) == "XcodeGen" } $0.it("generates local swift packages with custom xcode path") { let app = Target( name: "MyApp", type: .application, platform: .iOS, dependencies: [ Dependency(type: .package(product: nil), reference: "XcodeGen"), ] ) let project = Project(name: "test", targets: [app], packages: ["XcodeGen": .local(path: "../XcodeGen", group: "Packages/Feature")]) let pbxProject = try project.generatePbxProj(specValidate: false) let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == app.name })) let localPackageFile = try unwrap(pbxProject.fileReferences.first(where: { $0.path == "../XcodeGen" })) try expect(localPackageFile.lastKnownFileType) == "folder" let frameworkPhases = nativeTarget.buildPhases.compactMap { $0 as? PBXFrameworksBuildPhase } guard let frameworkPhase = frameworkPhases.first else { return XCTFail("frameworkPhases should have more than one") } guard let file = frameworkPhase.files?.first else { return XCTFail("frameworkPhase should have file") } try expect(file.product?.productName) == "XcodeGen" } $0.it("generates info.plist") { let plist = Plist(path: "Info.plist", attributes: ["UISupportedInterfaceOrientations": ["UIInterfaceOrientationPortrait", "UIInterfaceOrientationLandscapeLeft"]]) let tempPath = Path.temporary + "info" let project = Project(basePath: tempPath, name: "", targets: [Target(name: "", type: .application, platform: .iOS, info: plist)]) let pbxProject = try project.generatePbxProj() let writer = FileWriter(project: project) try writer.writePlists() let targetConfig = try unwrap(pbxProject.nativeTargets.first?.buildConfigurationList?.buildConfigurations.first) try expect(targetConfig.buildSettings["INFOPLIST_FILE"] as? String) == plist.path let infoPlistFile = tempPath + plist.path let data: Data = try infoPlistFile.read() let infoPlist = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as! [String: Any] let expectedInfoPlist: [String: Any] = [ "CFBundleIdentifier": "$(PRODUCT_BUNDLE_IDENTIFIER)", "CFBundleInfoDictionaryVersion": "6.0", "CFBundleName": "$(PRODUCT_NAME)", "CFBundleExecutable": "$(EXECUTABLE_NAME)", "CFBundleDevelopmentRegion": "$(DEVELOPMENT_LANGUAGE)", "CFBundleShortVersionString": "1.0", "CFBundleVersion": "1", "CFBundlePackageType": "APPL", "UISupportedInterfaceOrientations": ["UIInterfaceOrientationPortrait", "UIInterfaceOrientationLandscapeLeft"], ] try expect(NSDictionary(dictionary: expectedInfoPlist).isEqual(to: infoPlist)).beTrue() } $0.it("info doesn't override info.plist setting") { let predefinedPlistPath = "Predefined.plist" // generate plist let plist = Plist(path: "Info.plist", attributes: ["UISupportedInterfaceOrientations": ["UIInterfaceOrientationPortrait", "UIInterfaceOrientationLandscapeLeft"]]) let tempPath = Path.temporary + "info" // create project with a predefined plist let project = Project(basePath: tempPath, name: "", targets: [Target(name: "", type: .application, platform: .iOS, settings: Settings(buildSettings: ["INFOPLIST_FILE": predefinedPlistPath]), info: plist)]) let pbxProject = try project.generatePbxProj() let writer = FileWriter(project: project) try writer.writePlists() let targetConfig = try unwrap(pbxProject.nativeTargets.first?.buildConfigurationList?.buildConfigurations.first) // generated plist should not be in buildsettings try expect(targetConfig.buildSettings["INFOPLIST_FILE"] as? String) == predefinedPlistPath } describe("Carthage dependencies") { $0.context("with static dependency") { $0.it("should set dependencies") { let app = Target( name: "MyApp", type: .application, platform: .iOS, dependencies: [ Dependency(type: .carthage(findFrameworks: true, linkType: .static), reference: "MyStaticFramework"), ] ) let project = Project(name: "test", targets: [app]) let pbxProject = try project.generatePbxProj() let target = pbxProject.nativeTargets.first! let configuration = target.buildConfigurationList!.buildConfigurations.first! try expect(configuration.buildSettings["FRAMEWORK_SEARCH_PATHS"] as? [String]) == ["$(inherited)", "$(PROJECT_DIR)/Carthage/Build/iOS/Static"] let frameworkBuildPhase = try target.frameworksBuildPhase() guard let files = frameworkBuildPhase?.files, let file = files.first else { return XCTFail("frameworkBuildPhase should have files") } try expect(files.count) == 1 try expect(file.file?.nameOrPath) == "MyStaticFramework.framework" try expect(target.carthageCopyFrameworkBuildPhase).beNil() } } $0.context("with mixed dependencies") { $0.it("should set dependencies") { let app = Target( name: "MyApp", type: .application, platform: .iOS, dependencies: [ Dependency(type: .carthage(findFrameworks: true, linkType: .dynamic), reference: "MyDynamicFramework"), Dependency(type: .carthage(findFrameworks: true, linkType: .static), reference: "MyStaticFramework"), ] ) let project = Project(name: "test", targets: [app]) let pbxProject = try project.generatePbxProj() let target = pbxProject.nativeTargets.first! let configuration = target.buildConfigurationList!.buildConfigurations.first! try expect(configuration.buildSettings["FRAMEWORK_SEARCH_PATHS"] as? [String]) == ["$(inherited)", "$(PROJECT_DIR)/Carthage/Build/iOS", "$(PROJECT_DIR)/Carthage/Build/iOS/Static"] let frameworkBuildPhase = try target.frameworksBuildPhase() guard let files = frameworkBuildPhase?.files else { return XCTFail("frameworkBuildPhase should have files") } try expect(files.count) == 2 guard let dynamicFramework = files.first(where: { $0.file?.nameOrPath == "MyDynamicFramework.framework" }) else { return XCTFail("Framework Build Phase should have Dynamic Framework") } guard let _ = files.first(where: { $0.file?.nameOrPath == "MyStaticFramework.framework" }) else { return XCTFail("Framework Build Phase should have Static Framework") } guard let copyCarthagePhase = target.carthageCopyFrameworkBuildPhase else { return XCTFail("Carthage Build Phase should be exist") } try expect(copyCarthagePhase.inputPaths) == [dynamicFramework.file?.fullPath(sourceRoot: Path("$(SRCROOT)"))?.string] try expect(copyCarthagePhase.outputPaths) == ["$(BUILT_PRODUCTS_DIR)/$(FRAMEWORKS_FOLDER_PATH)/\(dynamicFramework.file!.path!)"] } } } $0.it("generate info.plist doesn't generate CFBundleExecutable for targets with type bundle") { let plist = Plist(path: "Info.plist", attributes: [:]) let tempPath = Path.temporary + "info" let project = Project(basePath: tempPath, name: "", targets: [Target(name: "", type: .bundle, platform: .iOS, info: plist)]) let pbxProject = try project.generatePbxProj() let writer = FileWriter(project: project) try writer.writePlists() let targetConfig = try unwrap(pbxProject.nativeTargets.first?.buildConfigurationList?.buildConfigurations.first) try expect(targetConfig.buildSettings["INFOPLIST_FILE"] as? String) == plist.path let infoPlistFile = tempPath + plist.path let data: Data = try infoPlistFile.read() let infoPlist = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as! [String: Any] let expectedInfoPlist: [String: Any] = [ "CFBundleIdentifier": "$(PRODUCT_BUNDLE_IDENTIFIER)", "CFBundleInfoDictionaryVersion": "6.0", "CFBundleName": "$(PRODUCT_NAME)", "CFBundleDevelopmentRegion": "$(DEVELOPMENT_LANGUAGE)", "CFBundleShortVersionString": "1.0", "CFBundleVersion": "1", "CFBundlePackageType": "BNDL", ] try expect(NSDictionary(dictionary: expectedInfoPlist).isEqual(to: infoPlist)).beTrue() } } } func testGenerateXcodeProjectWithDestination() throws { let groupName = "App_iOS" let sourceDirectory = fixturePath + "TestProject" + groupName let frameworkWithSources = Target( name: "MyFramework", type: .framework, platform: .iOS, sources: [TargetSource(path: sourceDirectory.string)] ) describe("generateXcodeProject") { $0.context("without projectDirectory") { $0.it("generate groups") { let project = Project(name: "test", targets: [frameworkWithSources]) let generator = ProjectGenerator(project: project) let generatedProject = try generator.generateXcodeProject() let group = generatedProject.pbxproj.groups.first(where: { $0.nameOrPath == groupName }) try expect(group?.path) == "App_iOS" } } $0.context("with projectDirectory") { $0.it("generate groups") { let destinationPath = fixturePath let project = Project(name: "test", targets: [frameworkWithSources]) let generator = ProjectGenerator(project: project) let generatedProject = try generator.generateXcodeProject(in: destinationPath) let group = generatedProject.pbxproj.groups.first(where: { $0.nameOrPath == groupName }) try expect(group?.path) == "TestProject/App_iOS" } $0.it("generate Info.plist") { let destinationPath = fixturePath let project = Project(name: "test", targets: [frameworkWithSources]) let generator = ProjectGenerator(project: project) let generatedProject = try generator.generateXcodeProject(in: destinationPath) let plists = generatedProject.pbxproj.buildConfigurations.compactMap { $0.buildSettings["INFOPLIST_FILE"] as? String } try expect(plists.count) == 2 for plist in plists { try expect(plist) == "TestProject/App_iOS/Info.plist" } } } describe("Carthage dependencies") { $0.context("with static dependency") { $0.it("should set dependencies") { let app = Target( name: "MyApp", type: .application, platform: .iOS, dependencies: [ Dependency(type: .carthage(findFrameworks: true, linkType: .static), reference: "MyStaticFramework"), ] ) let project = Project(name: "test", targets: [app]) let pbxProject = try project.generatePbxProj() let target = pbxProject.nativeTargets.first! let configuration = target.buildConfigurationList!.buildConfigurations.first! try expect(configuration.buildSettings["FRAMEWORK_SEARCH_PATHS"] as? [String]) == ["$(inherited)", "$(PROJECT_DIR)/Carthage/Build/iOS/Static"] let frameworkBuildPhase = try target.frameworksBuildPhase() guard let files = frameworkBuildPhase?.files, let file = files.first else { return XCTFail("frameworkBuildPhase should have files") } try expect(files.count) == 1 try expect(file.file?.nameOrPath) == "MyStaticFramework.framework" try expect(target.carthageCopyFrameworkBuildPhase).beNil() } } $0.context("with mixed dependencies") { $0.it("should set dependencies") { let app = Target( name: "MyApp", type: .application, platform: .iOS, dependencies: [ Dependency(type: .carthage(findFrameworks: true, linkType: .dynamic), reference: "MyDynamicFramework"), Dependency(type: .carthage(findFrameworks: true, linkType: .static), reference: "MyStaticFramework"), ] ) let project = Project(name: "test", targets: [app]) let pbxProject = try project.generatePbxProj() let target = pbxProject.nativeTargets.first! let configuration = target.buildConfigurationList!.buildConfigurations.first! try expect(configuration.buildSettings["FRAMEWORK_SEARCH_PATHS"] as? [String]) == ["$(inherited)", "$(PROJECT_DIR)/Carthage/Build/iOS", "$(PROJECT_DIR)/Carthage/Build/iOS/Static"] let frameworkBuildPhase = try target.frameworksBuildPhase() guard let files = frameworkBuildPhase?.files else { return XCTFail("frameworkBuildPhase should have files") } try expect(files.count) == 2 guard let dynamicFramework = files.first(where: { $0.file?.nameOrPath == "MyDynamicFramework.framework" }) else { return XCTFail("Framework Build Phase should have Dynamic Framework") } guard let _ = files.first(where: { $0.file?.nameOrPath == "MyStaticFramework.framework" }) else { return XCTFail("Framework Build Phase should have Static Framework") } guard let copyCarthagePhase = target.carthageCopyFrameworkBuildPhase else { return XCTFail("Carthage Build Phase should be exist") } try expect(copyCarthagePhase.inputPaths) == [dynamicFramework.file?.fullPath(sourceRoot: Path("$(SRCROOT)"))?.string] try expect(copyCarthagePhase.outputPaths) == ["$(BUILT_PRODUCTS_DIR)/$(FRAMEWORKS_FOLDER_PATH)/\(dynamicFramework.file!.path!)"] } } } } } func testGenerateXcodeProjectWithCustomDependencyDestinations() throws { describe("generateXcodeProject") { func generateProjectForApp(withDependencies: [Dependency], targets: [Target], packages: [String: SwiftPackage] = [:]) throws -> PBXProj { let app = Target( name: "App", type: .application, platform: .macOS, dependencies: withDependencies ) let project = Project( name: "test", targets: targets + [app], packages: packages ) return try project.generatePbxProj() } func expectCopyPhase(in project:PBXProj, withFilePaths: [String]? = nil, withProductPaths: [String]? = nil, toSubFolder subfolder: PBXCopyFilesBuildPhase.SubFolder, dstPath: String? = nil) throws { let phases = project.copyFilesBuildPhases try expect(phases.count) == 1 let phase = phases.first! try expect(phase.dstSubfolderSpec) == subfolder try expect(phase.dstPath) == dstPath if let paths = withFilePaths { try expect(phase.files?.count) == paths.count let filePaths = phase.files!.map { $0.file!.path } try expect(filePaths) == paths } if let paths = withProductPaths { try expect(phase.files?.count) == paths.count let filePaths = phase.files!.map { $0.product!.productName } try expect(filePaths) == paths } } $0.context("with target dependencies") { $0.context("application") { let appA = Target( name: "appA", type: .application, platform: .macOS ) let appB = Target( name: "appB", type: .application, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true), Dependency(type: .target, reference: appB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [ appA, appB ]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: appB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [appA, appB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["appA.app"], toSubFolder: .plugins, dstPath: "test") } } $0.context("framework") { let frameworkA = Target( name: "frameworkA", type: .framework, platform: .macOS ) let frameworkB = Target( name: "frameworkB", type: .framework, platform: .macOS ) $0.it("embeds them into frameworks without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: frameworkA.name, embed: true), Dependency(type: .target, reference: frameworkB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [frameworkA, frameworkB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.framework"], toSubFolder: .frameworks, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: frameworkA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: frameworkB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [frameworkA, frameworkB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.framework"], toSubFolder: .plugins, dstPath: "test") } } $0.context("staticFramework") { let frameworkA = Target( name: "frameworkA", type: .staticFramework, platform: .macOS ) let frameworkB = Target( name: "frameworkB", type: .staticFramework, platform: .macOS ) $0.it("embeds them into frameworks without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: frameworkA.name, embed: true), Dependency(type: .target, reference: frameworkB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [frameworkA, frameworkB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.framework"], toSubFolder: .frameworks, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: frameworkA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: frameworkB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [frameworkA, frameworkB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.framework"], toSubFolder: .plugins, dstPath: "test") } } $0.context("xcFramework") { let frameworkA = Target( name: "frameworkA", type: .xcFramework, platform: .macOS ) let frameworkB = Target( name: "frameworkB", type: .xcFramework, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: frameworkA.name, embed: true), Dependency(type: .target, reference: frameworkB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [frameworkA, frameworkB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: frameworkA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: frameworkB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [frameworkA, frameworkB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.xcframework"], toSubFolder: .plugins, dstPath: "test") } } $0.context("Dynamic Library") { let libraryA = Target( name: "libraryA", type: .dynamicLibrary, platform: .macOS ) let libraryB = Target( name: "libraryB", type: .dynamicLibrary, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: libraryA.name, embed: true), Dependency(type: .target, reference: libraryB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [libraryA, libraryB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: libraryA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: libraryB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [libraryA, libraryB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["libraryA.dylib"], toSubFolder: .plugins, dstPath: "test") } } $0.context("Static Library") { let libraryA = Target( name: "libraryA", type: .staticLibrary, platform: .macOS ) let libraryB = Target( name: "libraryB", type: .staticLibrary, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: libraryA.name, embed: true), Dependency(type: .target, reference: libraryB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [libraryA, libraryB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them to custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: libraryA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: libraryB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [libraryA, libraryB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["liblibraryA.a"], toSubFolder: .plugins, dstPath: "test") } } $0.context("bundle") { let bundleA = Target( name: "bundleA", type: .bundle, platform: .macOS ) let bundleB = Target( name: "bundleB", type: .bundle, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: bundleA.name, embed: true), Dependency(type: .target, reference: bundleB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [bundleA, bundleB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: bundleA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: bundleB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [bundleA, bundleB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["bundleA.bundle"], toSubFolder: .plugins, dstPath: "test") } } $0.context("unitTestBundle") { let bundleA = Target( name: "bundleA", type: .unitTestBundle, platform: .macOS ) let bundleB = Target( name: "bundleB", type: .unitTestBundle, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: bundleA.name, embed: true), Dependency(type: .target, reference: bundleB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [bundleA, bundleB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: bundleA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: bundleB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [bundleA, bundleB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["bundleA.xctest"], toSubFolder: .plugins, dstPath: "test") } } $0.context("uitTestBundle") { let bundleA = Target( name: "bundleA", type: .uiTestBundle, platform: .macOS ) let bundleB = Target( name: "bundleB", type: .uiTestBundle, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: bundleA.name, embed: true), Dependency(type: .target, reference: bundleB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [bundleA, bundleB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: bundleA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: bundleB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [bundleA, bundleB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["bundleA.xctest"], toSubFolder: .plugins, dstPath: "test") } } $0.context("appExtension") { let extA = Target( name: "extA", type: .appExtension, platform: .macOS ) let extB = Target( name: "extB", type: .appExtension, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true), Dependency(type: .target, reference: extB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .plugins, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .executables, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: extB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .executables, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .executables, dstPath: "test") } } $0.context("extensionKit") { let extA = Target( name: "extA", type: .extensionKitExtension, platform: .macOS ) let extB = Target( name: "extB", type: .extensionKitExtension, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true), Dependency(type: .target, reference: extB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .productsDirectory, dstPath: "$(EXTENSIONS_FOLDER_PATH)") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .productsDirectory, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: extB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .productsDirectory, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .productsDirectory, dstPath: "test") } } $0.context("commandLineTool") { let toolA = Target( name: "toolA", type: .commandLineTool, platform: .macOS ) let toolB = Target( name: "toolB", type: .commandLineTool, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: toolA.name, embed: true), Dependency(type: .target, reference: toolB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [toolA, toolB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: toolA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: toolB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [toolA, toolB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["toolA"], toSubFolder: .plugins, dstPath: "test") } } $0.context("watchApp") { let appA = Target( name: "appA", type: .watchApp, platform: .macOS ) let appB = Target( name: "appB", type: .watchApp, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true), Dependency(type: .target, reference: appB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [appA, appB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: appB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [appA, appB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["appA.app"], toSubFolder: .plugins, dstPath: "test") } } $0.context("watch2App") { let appA = Target( name: "appA", type: .watch2App, platform: .macOS ) let appB = Target( name: "appB", type: .watch2App, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true), Dependency(type: .target, reference: appB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [appA, appB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: appB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [appA, appB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["appA.app"], toSubFolder: .plugins, dstPath: "test") } } $0.context("watch2AppContainer") { let appA = Target( name: "appA", type: .watch2AppContainer, platform: .macOS ) let appB = Target( name: "appB", type: .watch2AppContainer, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true), Dependency(type: .target, reference: appB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [appA, appB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: appB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [appA, appB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["appA.app"], toSubFolder: .plugins, dstPath: "test") } } $0.context("watchExtension") { let extA = Target( name: "extA", type: .watchExtension, platform: .macOS ) let extB = Target( name: "extB", type: .watchExtension, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true), Dependency(type: .target, reference: extB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .plugins, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: extB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("watch2Extension") { let extA = Target( name: "extA", type: .watch2Extension, platform: .macOS ) let extB = Target( name: "extB", type: .watch2Extension, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true), Dependency(type: .target, reference: extB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .plugins, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: extB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("tvExtension") { let extA = Target( name: "extA", type: .tvExtension, platform: .macOS ) let extB = Target( name: "extB", type: .tvExtension, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true), Dependency(type: .target, reference: extB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .plugins, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: extB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("messagesApplication") { let appA = Target( name: "appA", type: .messagesApplication, platform: .macOS ) let appB = Target( name: "appB", type: .messagesApplication, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true), Dependency(type: .target, reference: appB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [appA, appB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: appB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [appA, appB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["appA.app"], toSubFolder: .plugins, dstPath: "test") } } $0.context("messagesExtension") { let extA = Target( name: "extA", type: .messagesExtension, platform: .macOS ) let extB = Target( name: "extB", type: .messagesExtension, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true), Dependency(type: .target, reference: extB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .plugins, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: extB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("stickerPack") { let extA = Target( name: "extA", type: .stickerPack, platform: .macOS ) let extB = Target( name: "extB", type: .stickerPack, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true), Dependency(type: .target, reference: extB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .plugins, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: extB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("xpcService") { let xpcA = Target( name: "xpcA", type: .xpcService, platform: .macOS ) let xpcB = Target( name: "xpcB", type: .xpcService, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: xpcA.name, embed: true), Dependency(type: .target, reference: xpcB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [xpcA, xpcB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["xpcA.xpc"], toSubFolder: .productsDirectory, dstPath: "$(CONTENTS_FOLDER_PATH)/XPCServices") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: xpcA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: xpcB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [xpcA, xpcB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["xpcA.xpc"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("ocUnitTestBundle") { let bundleA = Target( name: "bundleA", type: .ocUnitTestBundle, platform: .macOS ) let bundleB = Target( name: "bundleB", type: .ocUnitTestBundle, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: bundleA.name, embed: true), Dependency(type: .target, reference: bundleB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [bundleA, bundleB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: bundleA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: bundleB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [bundleA, bundleB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["bundleA.octest"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("xcodeExtension") { let extA = Target( name: "extA", type: .xcodeExtension, platform: .macOS ) let extB = Target( name: "extB", type: .xcodeExtension, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true), Dependency(type: .target, reference: extB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .plugins, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: extB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("instrumentsPackage") { let pkgA = Target( name: "pkgA", type: .instrumentsPackage, platform: .macOS ) let pkgB = Target( name: "pkgB", type: .instrumentsPackage, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: pkgA.name, embed: true), Dependency(type: .target, reference: pkgB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [pkgA, pkgB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: pkgA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: pkgB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [pkgA, pkgB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["pkgA.instrpkg"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("intentsServiceExtension") { let extA = Target( name: "extA", type: .intentsServiceExtension, platform: .macOS ) let extB = Target( name: "extB", type: .intentsServiceExtension, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true), Dependency(type: .target, reference: extB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .plugins, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: extB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("appClip") { let clipA = Target( name: "clipA", type: .onDemandInstallCapableApplication, platform: .macOS ) let clipB = Target( name: "clipB", type: .onDemandInstallCapableApplication, platform: .macOS ) $0.it("does embed them into products directory without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: clipA.name, embed: true), Dependency(type: .target, reference: clipB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [clipA, clipB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["clipA.app"], toSubFolder: .productsDirectory, dstPath: "$(CONTENTS_FOLDER_PATH)/AppClips") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: clipA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: clipB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [clipA, clipB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["clipA.app"], toSubFolder: .plugins, dstPath: "test") } } $0.context("Metal Library") { let libraryA = Target( name: "libraryA", type: .metalLibrary, platform: .macOS ) let libraryB = Target( name: "libraryB", type: .metalLibrary, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: libraryA.name, embed: true), Dependency(type: .target, reference: libraryB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [libraryA, libraryB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them to custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: libraryA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: libraryB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [libraryA, libraryB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["libraryA.metallib"], toSubFolder: .plugins, dstPath: "test") } } } $0.context("with framework dependencies") { $0.it("embeds them into frameworks without copy phase spec") { // given let dependencies = [ Dependency(type: .framework, reference: "frameworkA.framework", embed: true), Dependency(type: .framework, reference: "frameworkB.framework", embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: []) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.framework"], toSubFolder: .frameworks, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .framework, reference: "frameworkA.framework", embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .framework, reference: "frameworkB.framework", embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: []) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.framework"], toSubFolder: .plugins, dstPath: "test") } $0.it("generates single copy phase for multiple frameworks with same copy phase spec") { // given let dependencies = [ Dependency(type: .framework, reference: "frameworkA.framework", embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .framework, reference: "frameworkB.framework", embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: []) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.framework", "frameworkB.framework"], toSubFolder: .plugins, dstPath: "test") } } $0.context("with sdk dependencies") { $0.it("embeds them into frameworks without copy phase spec") { // given let dependencies = [ Dependency(type: .sdk(root: nil), reference: "sdkA.framework", embed: true), Dependency(type: .sdk(root: nil), reference: "sdkB.framework", embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: []) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["System/Library/Frameworks/sdkA.framework"], toSubFolder: .frameworks, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .sdk(root: nil), reference: "sdkA.framework", embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .sdk(root: nil), reference: "sdkB.framework", embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: []) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["System/Library/Frameworks/sdkA.framework"], toSubFolder: .plugins, dstPath: "test") } } $0.context("with package dependencies") { let packages: [String: SwiftPackage] = [ "RxSwift": .remote(url: "https://github.com/ReactiveX/RxSwift", versionRequirement: .upToNextMajorVersion("5.1.1")), ] $0.it("embeds them into frameworks without copy phase spec") { // given let dependencies = [ Dependency(type: .package(product: "RxSwift"), reference: "RxSwift", embed: true), Dependency(type: .package(product: "RxCocoa"), reference: "RxSwift", embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [], packages: packages) // then try expectCopyPhase(in: pbxProject, withProductPaths: ["RxSwift"], toSubFolder: .frameworks, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .package(product: "RxSwift"), reference: "RxSwift", embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .package(product: "RxCocoa"), reference: "RxSwift", embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [], packages: packages) // then try expectCopyPhase(in: pbxProject, withProductPaths: ["RxSwift"], toSubFolder: .plugins, dstPath: "test") } } $0.context("with carthage dependencies") { $0.it("embeds them into frameworks without copy phase spec") { // given let dependencies = [ Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "frameworkA.framework", embed: true), Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "frameworkB.framework", embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: []) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.framework"], toSubFolder: .frameworks, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "frameworkA.framework", embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .carthage(findFrameworks: false, linkType: .static), reference: "frameworkB.framework", embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: []) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.framework"], toSubFolder: .plugins, dstPath: "test") } } $0.context("with bundle dependencies") { $0.it("embeds them into resources without copy phase spec") { // given let dependencies = [ Dependency(type: .bundle, reference: "bundleA.bundle", embed: true), Dependency(type: .bundle, reference: "bundleB.bundle", embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: []) // then /// XcodeGen ignores embed: false for bundles try expectCopyPhase(in: pbxProject, withFilePaths: ["bundleA.bundle", "bundleB.bundle"], toSubFolder: .resources) } $0.it("ignores custom copy phase spec") { // given let dependencies = [ Dependency(type: .bundle, reference: "bundleA.bundle", embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .bundle, reference: "bundleB.bundle", embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: []) // then /// XcodeGen ignores embed: false for bundles try expectCopyPhase(in: pbxProject, withFilePaths: ["bundleA.bundle", "bundleB.bundle"], toSubFolder: .resources) } } } } } private extension PBXTarget { var carthageCopyFrameworkBuildPhase: PBXShellScriptBuildPhase? { buildPhases.first(where: { $0.name() == "Carthage" }) as? PBXShellScriptBuildPhase } }
306bd34fa32d7c2247fb1f8477d1f7ce
50.634004
254
0.484121
false
true
false
false
february29/Learning
refs/heads/master
Pods/RxDataSources/Sources/RxDataSources/RxCollectionViewSectionedAnimatedDataSource.swift
cc0-1.0
3
// // RxCollectionViewSectionedAnimatedDataSource.swift // RxExample // // Created by Krunoslav Zaher on 7/2/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif import Differentiator /* This is commented becuse collection view has bugs when doing animated updates. Take a look at randomized sections. */ open class RxCollectionViewSectionedAnimatedDataSource<S: AnimatableSectionModelType> : CollectionViewSectionedDataSource<S> , RxCollectionViewDataSourceType { public typealias Element = [S] public typealias DecideViewTransition = (CollectionViewSectionedDataSource<S>, UICollectionView, [Changeset<S>]) -> ViewTransition // animation configuration public var animationConfiguration: AnimationConfiguration /// Calculates view transition depending on type of changes public var decideViewTransition: DecideViewTransition public init( animationConfiguration: AnimationConfiguration = AnimationConfiguration(), decideViewTransition: @escaping DecideViewTransition = { _, _, _ in .animated }, configureCell: @escaping ConfigureCell, configureSupplementaryView: @escaping ConfigureSupplementaryView, moveItem: @escaping MoveItem = { _, _, _ in () }, canMoveItemAtIndexPath: @escaping CanMoveItemAtIndexPath = { _, _ in false } ) { self.animationConfiguration = animationConfiguration self.decideViewTransition = decideViewTransition super.init( configureCell: configureCell, configureSupplementaryView: configureSupplementaryView, moveItem: moveItem, canMoveItemAtIndexPath: canMoveItemAtIndexPath ) self.partialUpdateEvent // so in case it does produce a crash, it will be after the data has changed .observeOn(MainScheduler.asyncInstance) // Collection view has issues digesting fast updates, this should // help to alleviate the issues with them. .throttle(0.5, scheduler: MainScheduler.instance) .subscribe(onNext: { [weak self] event in self?.collectionView(event.0, throttledObservedEvent: event.1) }) .disposed(by: disposeBag) } // For some inexplicable reason, when doing animated updates first time // it crashes. Still need to figure out that one. var dataSet = false private let disposeBag = DisposeBag() // This subject and throttle are here // because collection view has problems processing animated updates fast. // This should somewhat help to alleviate the problem. private let partialUpdateEvent = PublishSubject<(UICollectionView, Event<Element>)>() /** This method exists because collection view updates are throttled because of internal collection view bugs. Collection view behaves poorly during fast updates, so this should remedy those issues. */ open func collectionView(_ collectionView: UICollectionView, throttledObservedEvent event: Event<Element>) { Binder(self) { dataSource, newSections in let oldSections = dataSource.sectionModels do { // if view is not in view hierarchy, performing batch updates will crash the app if collectionView.window == nil { dataSource.setSections(newSections) collectionView.reloadData() return } let differences = try Diff.differencesForSectionedView(initialSections: oldSections, finalSections: newSections) switch self.decideViewTransition(self, collectionView, differences) { case .animated: for difference in differences { dataSource.setSections(difference.finalSections) collectionView.performBatchUpdates(difference, animationConfiguration: self.animationConfiguration) } case .reload: self.setSections(newSections) collectionView.reloadData() } } catch let e { #if DEBUG print("Error while binding data animated: \(e)\nFallback to normal `reloadData` behavior.") rxDebugFatalError(e) #endif self.setSections(newSections) collectionView.reloadData() } }.on(event) } open func collectionView(_ collectionView: UICollectionView, observedEvent: Event<Element>) { Binder(self) { dataSource, newSections in #if DEBUG self._dataSourceBound = true #endif if !self.dataSet { self.dataSet = true dataSource.setSections(newSections) collectionView.reloadData() } else { let element = (collectionView, observedEvent) dataSource.partialUpdateEvent.on(.next(element)) } }.on(observedEvent) } } #endif
8e8e631d36dbe73a9da1dc185c0d7b3f
39.315385
134
0.64377
false
true
false
false
a497500306/yijia_kuanjia
refs/heads/master
医家/医家/主项目/首页/每日量表/View/MLMrlbCell.swift
apache-2.0
1
// // MLMrlbCell.swift // 医家 // // Created by 洛耳 on 16/1/15. // Copyright © 2016年 workorz. All rights reserved. // import UIKit class MLMrlbCell: UITableViewCell { var textView : UILabel! var nameView : UIButton! var btn : UIButton! var modelFrame : MLMrlbCellFrame!{ //属性发生改变后调用 didSet { self.textView.frame = self.modelFrame.textFrame self.textView.text = self.modelFrame.cellModel.text as String self.nameView.frame = self.modelFrame.nameFrame if self.modelFrame.cellModel.name == "是"{ self.nameView.setImage(UIImage(named: "正确"), forState: UIControlState.Normal) self.nameView.setTitle(" 是", forState: UIControlState.Normal) }else if self.modelFrame.cellModel.name == "否"{ self.nameView.setImage(UIImage(named: "错误"), forState: UIControlState.Normal) self.nameView.setTitle(" 否", forState: UIControlState.Normal) }else{ self.nameView.setImage(UIImage(), forState: UIControlState.Normal) self.nameView.setTitle(self.modelFrame.cellModel.name, forState: UIControlState.Normal) } self.btn.frame = self.modelFrame.btnFrame } } //重写cell.init方法,这里做初始化设置 override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) //内容 self.textView = UILabel() self.textView.backgroundColor = UIColor.whiteColor() self.textView.font = Theme.中字体 self.textView.numberOfLines = 0 self.contentView.addSubview(self.textView) //选项 self.nameView = UIButton() self.nameView.userInteractionEnabled = false self.nameView.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) self.nameView.titleLabel?.font = Theme.大字体 self.nameView.titleLabel?.numberOfLines = 0 self.contentView.addSubview(self.nameView) //播放按钮 self.btn = UIButton() self.btn.setImage(UIImage(named: "音乐播放器4"), forState: UIControlState.Normal) self.btn.addTarget(self, action: "点击喇叭", forControlEvents: UIControlEvents.TouchUpInside) self.contentView.addSubview(self.btn) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func 点击喇叭(){ //播放录音 let utterance : AVSpeechUtterance = AVSpeechUtterance(string: self.modelFrame.cellModel.text as String) utterance.rate = 0.5 //当前系统语音 let preferredLand = "zh-CN" let synth : AVSpeechSynthesizer = AVSpeechSynthesizer() let voice : AVSpeechSynthesisVoice = AVSpeechSynthesisVoice(language: preferredLand)! utterance.voice = voice synth.speakUtterance(utterance) } }
bf64aebc395e6b36180e857f5c2a6b54
38.958904
111
0.642441
false
false
false
false
chrisdhaan/CDYelpFusionKit
refs/heads/master
Source/DateFormatter+CDYelpFusionKit.swift
mit
1
// // DateFormatter+CDYelpFusionKit.swift // CDYelpFusionKit // // Created by Christopher de Haan on 6/1/21. // // Copyright © 2016-2022 Christopher de Haan <contact@christopherdehaan.me> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if !os(OSX) import UIKit #else import Foundation #endif extension DateFormatter { static let events: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" return formatter }() static let reviews: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter }() }
d080060e72dcbe639f140d41c7f4508c
35.73913
81
0.733728
false
false
false
false
athiercelin/Localizations
refs/heads/master
Localizations/Choose Project/ChooseProjectController+Parser.swift
mit
1
// // ChooseProjectViewController+Parser.swift // Localizations // // Created by Arnaud Thiercelin on 2/14/16. // Copyright © 2016 Arnaud Thiercelin. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial // portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT // NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Foundation extension ChooseProjectViewController { func parseTranslations(rawContent: String) -> [Translation] { let lines = rawContent.components(separatedBy: "\n") var translations = [Translation]() var comments = "" for line in lines { if line.characters.count == 0 { continue } if line.characters.first != "\"" { // Comment line or blank lines comments.append(line) comments.append("\n") } else { // line with key let translation = self.splitStringLine(line: line) translation.comments = comments translations.append(translation) comments = "" } } return translations } func splitStringLine(line: String) -> Translation { var foundFirstQuote = false var foundSecondQuote = false var foundThirdQuote = false let foundLastQuote = false var ignoreNextCharacter = false var key = "" var value = "" for index in 0..<line.lengthOfBytes(using: String.Encoding.utf8) { let newIndex = line.index(line.startIndex, offsetBy: index) let character = line[newIndex] if character == "\\" { if !ignoreNextCharacter { ignoreNextCharacter = true continue } } if !foundFirstQuote { if !ignoreNextCharacter { if character == "\"" { foundFirstQuote = true ignoreNextCharacter = false continue } } } else { if !foundSecondQuote { if !ignoreNextCharacter { if character == "\"" { foundSecondQuote = true ignoreNextCharacter = false continue } } else { key += "\\" } key += "\(character)" } else { if !foundThirdQuote { if character == " " || character == "=" { ignoreNextCharacter = false continue } if character == "\"" { foundThirdQuote = true ignoreNextCharacter = false continue } } else { if !foundLastQuote { if !ignoreNextCharacter { if character == "\"" { foundSecondQuote = true ignoreNextCharacter = false break } } else { value += "\\" } value += "\(character)" } else { break } } } } ignoreNextCharacter = false } return Translation(key: key, value: value, comments: "") } }
b0b136ca34cd94f4326a581f6641104b
26.821705
112
0.642797
false
false
false
false
remirobert/fastlaneAPI
refs/heads/master
FastlneIOS/FastlneIOS/CustomersController.swift
apache-2.0
1
// // CustomersController.swift // FastlneIOS // // Created by Remi Robert on 17/11/15. // Copyright © 2015 Remi Robert. All rights reserved. // import UIKit import Alamofire protocol CustomersControllerDelegate { func getCustomersList() } class CustomersController { private let delegate: CustomersControllerDelegate? private let url = "http://127.0.0.1:3000/customers" var customers = Array<Customer>() init(delegate: CustomersControllerDelegate?) { self.delegate = delegate } func fetchCustomerList() { Alamofire.request(.GET, url, parameters: nil, encoding: ParameterEncoding.JSON, headers: nil).responseJSON { response in print("repsonse : \(response.result.value!)") if let rep = response.result.value as? [String] { print("final rep : \(rep.first as? NSDictionary)") } if let response = response.result.value as? [NSDictionary] { print("get response : \(response)") self.customers = Customer.customersFromJSONResponse(response) self.delegate?.getCustomersList() } } } }
0e707d9322c57e1a4c40e1ec21695670
27.619048
128
0.617304
false
false
false
false
EricHein/Swift3.0Practice2016
refs/heads/master
00.ScratchWork/DownloadingWebContent/DownloadingWebContent/ViewController.swift
gpl-3.0
1
// // ViewController.swift // DownloadingWebContent // // Created by Eric H on 15/10/2016. // Copyright © 2016 FabledRealm. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() //let urlStack = URL(string: "https://www.google.com")! //webView.loadRequest(URLRequest(url: urlStack)) //webView.loadHTMLString("<h1>Hello there!</h1>", baseURL: nil) if let url1 = URL(string: "https://stackoverflow.com"){ let request = NSMutableURLRequest(url: url1) let task = URLSession.shared.dataTask(with: request as URLRequest){ data, response, error in if error != nil{ print(error) }else{ if let unwrappedData = data { let dataString = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue) print(dataString) } } } task.resume() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
2f6d17f806a66b23c892aa3d39bf3047
23.610169
111
0.476584
false
false
false
false
muenzpraeger/salesforce-einstein-vision-swift
refs/heads/master
SalesforceEinsteinVision/Classes/model/Label.swift
apache-2.0
1
// // Label.swift // predictivevision // // Created by René Winkelmeyer on 02/28/2017. // Copyright © 2016 René Winkelmeyer. All rights reserved. // import Foundation import SwiftyJSON public struct Label { public var id: Int? public var datasetId: Int? public var name: String? public var numExamples: Int? public var object: String? init?() { } init?(jsonObject: SwiftyJSON.JSON) { id = jsonObject["id"].int datasetId = jsonObject["datasetId"].int name = jsonObject["name"].string numExamples = jsonObject["numExamples"].int object = jsonObject["object"].string } }
c075b3db4e65746d0734767e68a8d3c6
20.612903
59
0.625373
false
false
false
false
elpassion/el-space-ios
refs/heads/master
ELSpace/Commons/Extensions/Double_FromString.swift
gpl-3.0
1
import Foundation extension Double { init?(from string: String?) { guard let string = string else { return nil } if let double = Double(fromCommaSeparatedString: string) { self = double } else if let double = Double(string) { self = double } else { return nil } } private init?(fromCommaSeparatedString string: String) { let formatter = NumberFormatter() formatter.decimalSeparator = "," if let number = formatter.number(from: string) { self = number.doubleValue } else { return nil } } }
226912b18d0779348821058f5925a212
23.961538
66
0.5547
false
false
false
false
Witcast/witcast-ios
refs/heads/develop
Pods/Material/Sources/iOS/Device.swift
apache-2.0
2
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit @objc(DeviceModel) public enum DeviceModel: Int { case iPodTouch5 case iPodTouch6 case iPhone4 case iPhone4s case iPhone5 case iPhone5c case iPhone5s case iPhone6 case iPhone6Plus case iPhone6s case iPhone6sPlus case iPhone7 case iPhone7Plus case iPhoneSE case iPad2 case iPad3 case iPad4 case iPadAir case iPadAir2 case iPadMini case iPadMini2 case iPadMini3 case iPadMini4 case iPadProSmall case iPadProLarge case appleTV case simulator case unknown } public struct Device { /// Gets the Device identifier String. public static var identifier: String { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { (identifier, element) in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } return identifier } /// Gets the model name for the device. public static var model: DeviceModel { switch identifier { case "iPod5,1": return .iPodTouch5 case "iPod7,1": return .iPodTouch6 case "iPhone3,1", "iPhone3,2", "iPhone3,3": return .iPhone4 case "iPhone4,1": return .iPhone4s case "iPhone5,1", "iPhone5,2": return .iPhone5 case "iPhone5,3", "iPhone5,4": return .iPhone5c case "iPhone6,1", "iPhone6,2": return .iPhone5s case "iPhone7,2": return .iPhone6 case "iPhone7,1": return .iPhone6Plus case "iPhone8,1": return .iPhone6s case "iPhone8,2": return .iPhone6sPlus case "iPhone8,4": return .iPhoneSE case "iPhone9,1", "iPhone9,3": return .iPhone7 case "iPhone9,2", "iPhone9,4": return .iPhone7Plus case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return .iPad2 case "iPad3,1", "iPad3,2", "iPad3,3": return .iPad3 case "iPad3,4", "iPad3,5", "iPad3,6": return .iPad4 case "iPad4,1", "iPad4,2", "iPad4,3": return .iPadAir case "iPad5,3", "iPad5,4": return .iPadAir2 case "iPad2,5", "iPad2,6", "iPad2,7": return .iPadMini case "iPad4,4", "iPad4,5", "iPad4,6": return .iPadMini2 case "iPad4,7", "iPad4,8", "iPad4,9": return .iPadMini3 case "iPad5,1", "iPad5,2": return .iPadMini4 case "iPad6,3", "iPad6,4": return .iPadProSmall case "iPad6,7", "iPad6,8": return .iPadProLarge case "AppleTV5,3": return .appleTV case "i386", "x86_64": return .simulator default: return .unknown } } /// Retrieves the current device type. public static var userInterfaceIdiom: UIUserInterfaceIdiom { return UIDevice.current.userInterfaceIdiom } } public func ==(lhs: DeviceModel, rhs: DeviceModel) -> Bool { return lhs.rawValue == rhs.rawValue } public func !=(lhs: DeviceModel, rhs: DeviceModel) -> Bool { return lhs.rawValue != rhs.rawValue }
70d2cc44dba05c220bae747b984e9364
35.937984
88
0.669045
false
false
false
false
RMizin/PigeonMessenger-project
refs/heads/main
FalconMessenger/Supporting Files/UIComponents/FalconActivityTitleView.swift
gpl-3.0
1
// // FalconActivityTitleView.swift // FalconMessenger // // Created by Roman Mizin on 2/22/19. // Copyright © 2019 Roman Mizin. All rights reserved. // import UIKit class FalconActivityTitleView: UIView { fileprivate let activityIndicatorView = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.white) let titleLabel = UILabel() convenience init(text: UINavigationItemTitle) { self.init() NotificationCenter.default.addObserver(self, selector: #selector(changeTheme), name: .themeUpdated, object: nil) activityIndicatorView.frame = CGRect(x: 0, y: 0, width: 14, height: 14) activityIndicatorView.color = ThemeManager.currentTheme().generalTitleColor//color activityIndicatorView.startAnimating() titleLabel.text = text.rawValue titleLabel.font = UIFont.systemFont(ofSize: 14) titleLabel.textColor = ThemeManager.currentTheme().generalTitleColor//color let fittingSize = titleLabel.sizeThatFits(CGSize(width: 200.0, height: activityIndicatorView.frame.size.height)) titleLabel.frame = CGRect(x: activityIndicatorView.frame.origin.x + activityIndicatorView.frame.size.width + 8, y: activityIndicatorView.frame.origin.y, width: fittingSize.width, height: fittingSize.height) let viewFrame = CGRect(x: (activityIndicatorView.frame.size.width + 8 + titleLabel.frame.size.width) / 2, y: activityIndicatorView.frame.size.height / 2, width: activityIndicatorView.frame.size.width + 8 + titleLabel.frame.size.width, height: activityIndicatorView.frame.size.height) self.frame = viewFrame addSubview(activityIndicatorView) addSubview(titleLabel) } deinit { NotificationCenter.default.removeObserver(self) } @objc fileprivate func changeTheme() { activityIndicatorView.color = ThemeManager.currentTheme().generalTitleColor titleLabel.textColor = ThemeManager.currentTheme().generalTitleColor } }
26da11faec8d7eb7b35ec6c9b081eb60
35.641509
114
0.751287
false
false
false
false
SereivoanYong/Charts
refs/heads/master
Source/Charts/Components/XAxis.swift
apache-2.0
1
// // XAxis.swift // Charts // // 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 open class XAxis: Axis { public enum LabelPosition: Int { case top case bottom case bothSided case topInside case bottomInside } /// width of the x-axis labels in pixels - this is automatically calculated by the `computeSize()` methods in the renderers open var labelSize: CGSize = CGSize(width: 1.0, height: 1.0) /// width of the (rotated) x-axis labels in pixels - this is automatically calculated by the `computeSize()` methods in the renderers open var labelRotatedSize: CGSize = CGSize(width: 1.0, height: 1.0) /// This is the angle for drawing the X axis labels (in degrees) open var labelRotationAngle: CGFloat = 0.0 /// if set to true, the chart will avoid that the first and last label entry in the chart "clip" off the edge of the chart open var isAvoidFirstLastClippingEnabled: Bool = false /// the position of the x-labels relative to the chart open var labelPosition: LabelPosition = .top /// if set to true, word wrapping the labels will be enabled. /// word wrapping is done using `(value width * labelRotatedWidth)` /// /// - note: currently supports all charts except pie/radar/horizontal-bar* open var isWordWrapEnabled: Bool = false /// the width for wrapping the labels, as percentage out of one value width. /// used only when isWordWrapEnabled = true. /// /// **default**: 1.0 open var wordWrapWidthPercent: CGFloat = 1.0 public override init() { super.init() yOffset = 4.0 } }
d21990fd6fab99d694d1072b858e1fb0
28.694915
135
0.688356
false
false
false
false
aloe-kawase/aloeutils
refs/heads/develop
Pod/Classes/animation/AloeEaseBezier.swift
mit
1
// // AloeEaseBezier.swift // Pods // // Created by kawase yu on 2016/06/11. // // import UIKit public class AloeEaseBezier: NSObject { private let p1:CGPoint private let p2:CGPoint public init(p1:CGPoint, p2:CGPoint){ self.p1 = p1 self.p2 = p2 super.init() } public func calc(t:CGFloat)->CGFloat{ return AloeEaseBezier.calc(Double(t), p1: p1, p2: p2) } public class func calc(t:Double, p1:CGPoint, p2:CGPoint)->CGFloat{ let q1 = (t*t*t*3) + (t * t * -6) + (t*3) let q2 = (t * t * t * -3) + (t*t*3) let q3 = t*t*t; let qy = q1*Double(p1.y) + q2*Double(p2.y) + q3 return CGFloat(qy) } }
0435be4863cb80e9a758d91629618096
19.189189
70
0.511379
false
false
false
false
flodolo/firefox-ios
refs/heads/main
Client/Frontend/Browser/Tabs/InactiveTabItemCellModel.swift
mpl-2.0
2
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/ import Foundation import Storage struct InactiveTabItemCellModel { struct UX { static let ImageSize: CGFloat = 28 static let BorderViewMargin: CGFloat = 16 static let LabelTopBottomMargin: CGFloat = 11 static let ImageTopBottomMargin: CGFloat = 10 static let ImageViewLeadingConstant: CGFloat = 16 static let MidViewLeadingConstant: CGFloat = 12 static let MidViewTrailingConstant: CGFloat = -16 static let SeparatorHeight: CGFloat = 0.5 } var fontForLabel: UIFont { return DynamicFontHelper.defaultHelper.preferredFont(withTextStyle: .body, maxSize: 17) } var title: String? var icon: Favicon? var website: URL? }
754aa19d6b6ceb1ace26fc51c3ca14b2
31.892857
95
0.697068
false
false
false
false
Witcast/witcast-ios
refs/heads/develop
Pods/Material/Sources/Frameworks/Motion/Sources/Extensions/Motion+UIKit.swift
apache-2.0
1
/* * The MIT License (MIT) * * Copyright (C) 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Original Inspiration & Author * Copyright (c) 2016 Luke Zhao <me@lkzhao.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit fileprivate let parameterRegex = "(?:\\-?\\d+(\\.?\\d+)?)|\\w+" fileprivate let transitionsRegex = "(\\w+)(?:\\(([^\\)]*)\\))?" internal extension NSObject { /// Copies an object using NSKeyedArchiver. func copyWithArchiver() -> Any? { return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self))! } } internal extension UIColor { /// A tuple of the rgba components. var components: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) return (r, g, b, a) } /// The alpha component value. var alphaComponent: CGFloat { return components.a } }
b57ce490609f2d9ed968c3ac4155ca41
35.862069
107
0.68101
false
false
false
false
KrishMunot/swift
refs/heads/master
test/SILOptimizer/devirt_specialized_inherited_interplay.swift
apache-2.0
6
// RUN: %target-swift-frontend -sil-verify-all -O %s -emit-sil | FileCheck %s // This file consists of tests for making sure that protocol conformances and // inherited conformances work well together when applied to each other. The // check works by making sure we can blow through a long class hierarchy and // expose the various "unknown" functions. // // As a side-test it also checks if all allocs can be promoted to the stack. // // *NOTE* If something like templated protocols is ever implemented this file // needs to be updated. // CHECK-LABEL: sil @_TF38devirt_specialized_inherited_interplay6driverFT_T_ : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: [[A3:%[0-9]+]] = alloc_ref [stack] $A3<S> // CHECK: [[A4:%[0-9]+]] = alloc_ref [stack] $A4<S> // CHECK: [[A5:%[0-9]+]] = alloc_ref [stack] $A5<S> // CHECK: [[B1:%[0-9]+]] = alloc_ref [stack] $B1<S> // CHECK: [[B2:%[0-9]+]] = alloc_ref [stack] $B2<S> // CHECK: [[B3:%[0-9]+]] = alloc_ref [stack] $B3<S> // CHECK: [[B4:%[0-9]+]] = alloc_ref [stack] $B4<S> // CHECK: [[F0:%[0-9]+]] = function_ref @unknown0 : $@convention(thin) () -> () // CHECK: apply [[F0]] // CHECK: apply [[F0]] // CHECK: [[F1:%[0-9]+]] = function_ref @unknown1 : $@convention(thin) () -> () // CHECK: apply [[F1]] // CHECK: apply [[F1]] // CHECK: [[F2:%[0-9]+]] = function_ref @unknown2 : $@convention(thin) () -> () // CHECK: apply [[F2]] // CHECK: apply [[F2]] // CHECK: [[F3:%[0-9]+]] = function_ref @unknown3 : $@convention(thin) () -> () // CHECK: apply [[F3]] // CHECK: apply [[F3]] // CHECK: [[F4:%[0-9]+]] = function_ref @unknown4 : $@convention(thin) () -> () // CHECK: apply [[F4]] // CHECK: apply [[F4]] // CHECK: [[F5:%[0-9]+]] = function_ref @unknown5 : $@convention(thin) () -> () // CHECK: apply [[F5]] // CHECK: apply [[F5]] // CHECK: [[F6:%[0-9]+]] = function_ref @unknown6 : $@convention(thin) () -> () // CHECK: apply [[F6]] // CHECK: apply [[F6]] // CHECK: apply [[F6]] // CHECK: apply [[F6]] // CHECK: [[F8:%[0-9]+]] = function_ref @unknown8 : // CHECK: apply [[F8]] // CHECK: apply [[F8]] // CHECK: dealloc_ref [stack] [[B4]] // CHECK: dealloc_ref [stack] [[B3]] // CHECK: dealloc_ref [stack] [[B2]] // CHECK: dealloc_ref [stack] [[B1]] // CHECK: dealloc_ref [stack] [[A5]] // CHECK: dealloc_ref [stack] [[A4]] // CHECK: dealloc_ref [stack] [[A3]] // CHECK: return @_silgen_name("unknown0") func unknown0() -> () @_silgen_name("unknown1") func unknown1() -> () @_silgen_name("unknown2") func unknown2() -> () @_silgen_name("unknown3") func unknown3() -> () @_silgen_name("unknown4") func unknown4() -> () @_silgen_name("unknown5") func unknown5() -> () @_silgen_name("unknown6") func unknown6() -> () @_silgen_name("unknown7") func unknown7() -> () @_silgen_name("unknown8") func unknown8() -> () protocol P1 { func foo() } struct S:P1 { func foo() { } } public final class G1<T> { } protocol P { func doSomething() } // Normal conformance class A1 : P { func doSomething() { unknown0() } } // Inherited conformance from P class A2 : A1 { override func doSomething() { unknown1() } } // Specialized Inherited conformance from P class A3<T> : A2 { override func doSomething() { unknown2() } } // Inherited Specialized Inherited conformance from P class A4<T> : A3<T> { override func doSomething() { unknown3() } } class A5<E>: A3<Array<E>> { override func doSomething() { unknown4() } } // Specialized conformance from P class B1<T> : P { func doSomething() { unknown5() } } // Inherited Specialized conformance from P class B2<T> : B1<G1<T>> { override func doSomething() { unknown6() } } class B3<E>: B2<Array<E>> { } class B4<F>: B3<Array<Array<Int>>> { override func doSomething() { unknown8() } } func WhatShouldIDo<T : P>(_ t : T) { t.doSomething() } func WhatShouldIDo2(_ p : P) { p.doSomething() } public func driver1<X>(_ x:X) { let b = B3<X>() WhatShouldIDo(b) WhatShouldIDo2(b) } public func driver2() { driver1(G1<S>()) } public func driver() { let a1 = A1() let a2 = A2() let a3 = A3<S>() let a4 = A4<S>() let a5 = A5<S>() let b1 = B1<S>() let b2 = B2<S>() let b3 = B3<S>() let b4 = B4<S>() WhatShouldIDo(a1) WhatShouldIDo2(a1) WhatShouldIDo(a2) WhatShouldIDo2(a2) WhatShouldIDo(a3) WhatShouldIDo2(a3) WhatShouldIDo(a4) WhatShouldIDo2(a4) WhatShouldIDo(a5) WhatShouldIDo2(a5) WhatShouldIDo(b1) WhatShouldIDo2(b1) WhatShouldIDo(b2) WhatShouldIDo2(b2) WhatShouldIDo(b3) WhatShouldIDo2(b3) WhatShouldIDo(b4) WhatShouldIDo2(b4) }
679fe5c947eed46e64240e114b25a65c
21.223301
108
0.602665
false
false
false
false
mountainKaku/Basic-Algorithms
refs/heads/master
HeapSort.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" print(str) //HeapSort: 堆排序法 typealias CRITERIA<Int> = (Int, Int) -> Bool func heapSortOf(_ arr: [Int], byCriteria: @escaping (CRITERIA<Int>) = { $0 < $1 }) -> [Int] { guard arr.count > 1 else { return arr } var result = arr func heapify(_ arr: inout [Int], i: Int, heapsize: Int) { var smallest = i let left = 2 * i + 1 let right = 2 * i + 2 if left < heapsize { if byCriteria(arr[i], arr[left]) { smallest = left } else { smallest = i } } if right < heapsize { if byCriteria(arr[smallest], arr[right]) { smallest = right } } if smallest != i { let temp: Int = arr[i] arr[i] = arr[smallest] arr[smallest] = temp heapify(&arr, i: smallest, heapsize: heapsize) } } func buildheap(_ arr: inout [Int]) { let length = arr.count let heapsize = length var nonleaf = length/2 - 1 while nonleaf >= 0 { heapify(&arr, i: nonleaf, heapsize: heapsize) nonleaf -= 1 } } func internalHeapSort(_ arr: inout [Int]) { var heapsize = arr.count buildheap(&arr) for _ in 0 ..< (arr.count - 1) { let temp: Int = arr[0] arr[0] = arr[heapsize - 1] arr[heapsize - 1] = temp heapsize = heapsize - 1 heapify(&arr, i: 0, heapsize: heapsize) } } internalHeapSort(&result) return result } var numbersArray = [10,3,17,8,5,2,1,9,5,4] print("堆排序方案: \(heapSortOf(numbersArray))") print("堆排序方案: \(heapSortOf(numbersArray, byCriteria: <))") print("堆排序方案: \(heapSortOf(numbersArray, byCriteria: >))")
293734848ad30fe220dbf25f8f67bf79
24.61039
80
0.491886
false
false
false
false
BradLarson/GPUImage2
refs/heads/master
framework/Source/OpenGLRendering.swift
bsd-3-clause
1
#if canImport(OpenGL) import OpenGL.GL3 #endif #if canImport(OpenGLES) import OpenGLES #endif #if canImport(COpenGLES) import COpenGLES.gles2 let GL_DEPTH24_STENCIL8 = GL_DEPTH24_STENCIL8_OES let GL_TRUE = GLboolean(1) let GL_FALSE = GLboolean(0) #endif #if canImport(COpenGL) import COpenGL #endif import Foundation public enum InputTextureStorageFormat { case textureCoordinates([GLfloat]) case textureVBO(GLuint) } public struct InputTextureProperties { public let textureStorage:InputTextureStorageFormat public let texture:GLuint public init(textureCoordinates:[GLfloat]? = nil, textureVBO:GLuint? = nil, texture:GLuint) { self.texture = texture switch (textureCoordinates, textureVBO) { case let (.some(coordinates), .none): self.textureStorage = .textureCoordinates(coordinates) case let (.none, .some(vbo)): self.textureStorage = .textureVBO(vbo) case (.none, .none): fatalError("Need to specify either texture coordinates or a VBO to InputTextureProperties") case (.some, .some): fatalError("Can't specify both texture coordinates and a VBO to InputTextureProperties") } } } public struct GLSize { public let width:GLint public let height:GLint public init(width:GLint, height:GLint) { self.width = width self.height = height } public init(_ size:Size) { self.width = size.glWidth() self.height = size.glHeight() } } extension Size { init(_ size:GLSize) { self.width = Float(size.width) self.height = Float(size.height) } } public let standardImageVertices:[GLfloat] = [-1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0] public let verticallyInvertedImageVertices:[GLfloat] = [-1.0, 1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0] // "position" and "inputTextureCoordinate", "inputTextureCoordinate2" attribute naming follows the convention of the old GPUImage public func renderQuadWithShader(_ shader:ShaderProgram, uniformSettings:ShaderUniformSettings? = nil, vertices:[GLfloat]? = nil, vertexBufferObject:GLuint? = nil, inputTextures:[InputTextureProperties]) { switch (vertices, vertexBufferObject) { case (.none, .some): break case (.some, .none): break case (.some, .some): fatalError("Can't specify both vertices and a VBO in renderQuadWithShader()") case (.none, .none): fatalError("Can't specify both vertices and a VBO in renderQuadWithShader()") } sharedImageProcessingContext.makeCurrentContext() shader.use() uniformSettings?.restoreShaderSettings(shader) guard let positionAttribute = shader.attributeIndex("position") else { fatalError("A position attribute was missing from the shader program during rendering.") } if let boundVBO = vertexBufferObject { glBindBuffer(GLenum(GL_ARRAY_BUFFER), boundVBO) glVertexAttribPointer(positionAttribute, 2, GLenum(GL_FLOAT), 0, 0, nil) glBindBuffer(GLenum(GL_ARRAY_BUFFER), 0) } else { glVertexAttribPointer(positionAttribute, 2, GLenum(GL_FLOAT), 0, 0, vertices!) } for (index, inputTexture) in inputTextures.enumerated() { if let textureCoordinateAttribute = shader.attributeIndex("inputTextureCoordinate".withNonZeroSuffix(index)) { switch inputTexture.textureStorage { case let .textureCoordinates(textureCoordinates): glVertexAttribPointer(textureCoordinateAttribute, 2, GLenum(GL_FLOAT), 0, 0, textureCoordinates) case let .textureVBO(textureVBO): glBindBuffer(GLenum(GL_ARRAY_BUFFER), textureVBO) glVertexAttribPointer(textureCoordinateAttribute, 2, GLenum(GL_FLOAT), 0, 0, nil) glBindBuffer(GLenum(GL_ARRAY_BUFFER), 0) } } else if (index == 0) { fatalError("The required attribute named inputTextureCoordinate was missing from the shader program during rendering.") } glActiveTexture(textureUnitForIndex(index)) glBindTexture(GLenum(GL_TEXTURE_2D), inputTexture.texture) shader.setValue(GLint(index), forUniform:"inputImageTexture".withNonZeroSuffix(index)) } glDrawArrays(GLenum(GL_TRIANGLE_STRIP), 0, 4) if (vertexBufferObject != nil) { glBindBuffer(GLenum(GL_ARRAY_BUFFER), 0) } for (index, _) in inputTextures.enumerated() { glActiveTexture(textureUnitForIndex(index)) glBindTexture(GLenum(GL_TEXTURE_2D), 0) } } public func clearFramebufferWithColor(_ color:Color) { glClearColor(GLfloat(color.redComponent), GLfloat(color.greenComponent), GLfloat(color.blueComponent), GLfloat(color.alphaComponent)) glClear(GLenum(GL_COLOR_BUFFER_BIT)) } func renderStencilMaskFromFramebuffer(_ framebuffer:Framebuffer) { let inputTextureProperties = framebuffer.texturePropertiesForOutputRotation(.noRotation) glEnable(GLenum(GL_STENCIL_TEST)) glClearStencil(0) glClear (GLenum(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)) glColorMask(GLboolean(GL_FALSE), GLboolean(GL_FALSE), GLboolean(GL_FALSE), GLboolean(GL_FALSE)) glStencilFunc(GLenum(GL_ALWAYS), 1, 1) glStencilOp(GLenum(GL_KEEP), GLenum(GL_KEEP), GLenum(GL_REPLACE)) #if GL glEnable(GLenum(GL_ALPHA_TEST)) glAlphaFunc(GLenum(GL_NOTEQUAL), 0.0) renderQuadWithShader(sharedImageProcessingContext.passthroughShader, vertices:standardImageVertices, inputTextures:[inputTextureProperties]) #else let alphaTestShader = crashOnShaderCompileFailure("Stencil"){return try sharedImageProcessingContext.programForVertexShader(OneInputVertexShader, fragmentShader:AlphaTestFragmentShader)} renderQuadWithShader(alphaTestShader, vertices:standardImageVertices, inputTextures:[inputTextureProperties]) #endif glColorMask(GLboolean(GL_TRUE), GLboolean(GL_TRUE), GLboolean(GL_TRUE), GLboolean(GL_TRUE)) glStencilFunc(GLenum(GL_EQUAL), 1, 1) glStencilOp(GLenum(GL_KEEP), GLenum(GL_KEEP), GLenum(GL_KEEP)) #if GL glDisable(GLenum(GL_ALPHA_TEST)) #endif } func disableStencil() { glDisable(GLenum(GL_STENCIL_TEST)) } func textureUnitForIndex(_ index:Int) -> GLenum { switch index { case 0: return GLenum(GL_TEXTURE0) case 1: return GLenum(GL_TEXTURE1) case 2: return GLenum(GL_TEXTURE2) case 3: return GLenum(GL_TEXTURE3) case 4: return GLenum(GL_TEXTURE4) case 5: return GLenum(GL_TEXTURE5) case 6: return GLenum(GL_TEXTURE6) case 7: return GLenum(GL_TEXTURE7) case 8: return GLenum(GL_TEXTURE8) default: fatalError("Attempted to address too high a texture unit") } } public func generateTexture(minFilter:Int32, magFilter:Int32, wrapS:Int32, wrapT:Int32) -> GLuint { var texture:GLuint = 0 glActiveTexture(GLenum(GL_TEXTURE1)) glGenTextures(1, &texture) glBindTexture(GLenum(GL_TEXTURE_2D), texture) glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), minFilter) glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), magFilter) glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), wrapS) glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), wrapT) glBindTexture(GLenum(GL_TEXTURE_2D), 0) return texture } public func uploadLocalArray(data:[GLfloat], into texture:GLuint, size:GLSize) { glActiveTexture(GLenum(GL_TEXTURE1)) glBindTexture(GLenum(GL_TEXTURE_2D), texture) glTexImage2D(GLenum(GL_TEXTURE_2D), 0, GL_RGBA, size.width, size.height, 0, GLenum(GL_RGBA), GLenum(GL_FLOAT), data) glBindTexture(GLenum(GL_TEXTURE_2D), 0) } func generateFramebufferForTexture(_ texture:GLuint, width:GLint, height:GLint, internalFormat:Int32, format:Int32, type:Int32, stencil:Bool) throws -> (GLuint, GLuint?) { var framebuffer:GLuint = 0 glActiveTexture(GLenum(GL_TEXTURE1)) glGenFramebuffers(1, &framebuffer) glBindFramebuffer(GLenum(GL_FRAMEBUFFER), framebuffer) glBindTexture(GLenum(GL_TEXTURE_2D), texture) glTexImage2D(GLenum(GL_TEXTURE_2D), 0, internalFormat, width, height, 0, GLenum(format), GLenum(type), nil) glFramebufferTexture2D(GLenum(GL_FRAMEBUFFER), GLenum(GL_COLOR_ATTACHMENT0), GLenum(GL_TEXTURE_2D), texture, 0) let status = glCheckFramebufferStatus(GLenum(GL_FRAMEBUFFER)) if (status != GLenum(GL_FRAMEBUFFER_COMPLETE)) { throw FramebufferCreationError(errorCode:status) } let stencilBuffer:GLuint? if stencil { stencilBuffer = try attachStencilBuffer(width:width, height:height) } else { stencilBuffer = nil } glBindTexture(GLenum(GL_TEXTURE_2D), 0) glBindFramebuffer(GLenum(GL_FRAMEBUFFER), 0) return (framebuffer, stencilBuffer) } func attachStencilBuffer(width:GLint, height:GLint) throws -> GLuint { var stencilBuffer:GLuint = 0 glGenRenderbuffers(1, &stencilBuffer); glBindRenderbuffer(GLenum(GL_RENDERBUFFER), stencilBuffer) glRenderbufferStorage(GLenum(GL_RENDERBUFFER), GLenum(GL_DEPTH24_STENCIL8), width, height) // iOS seems to only support combination depth + stencil, from references #if os(iOS) glFramebufferRenderbuffer(GLenum(GL_FRAMEBUFFER), GLenum(GL_DEPTH_ATTACHMENT), GLenum(GL_RENDERBUFFER), stencilBuffer) #endif glFramebufferRenderbuffer(GLenum(GL_FRAMEBUFFER), GLenum(GL_STENCIL_ATTACHMENT), GLenum(GL_RENDERBUFFER), stencilBuffer) glBindRenderbuffer(GLenum(GL_RENDERBUFFER), 0) let status = glCheckFramebufferStatus(GLenum(GL_FRAMEBUFFER)) if (status != GLenum(GL_FRAMEBUFFER_COMPLETE)) { throw FramebufferCreationError(errorCode:status) } return stencilBuffer } public func enableAdditiveBlending() { glBlendEquation(GLenum(GL_FUNC_ADD)) glBlendFunc(GLenum(GL_ONE), GLenum(GL_ONE)) glEnable(GLenum(GL_BLEND)) } public func disableBlending() { glDisable(GLenum(GL_BLEND)) } public func generateVBO(for vertices:[GLfloat]) -> GLuint { var newBuffer:GLuint = 0 glGenBuffers(1, &newBuffer) glBindBuffer(GLenum(GL_ARRAY_BUFFER), newBuffer) glBufferData(GLenum(GL_ARRAY_BUFFER), MemoryLayout<GLfloat>.size * vertices.count, vertices, GLenum(GL_STATIC_DRAW)) glBindBuffer(GLenum(GL_ARRAY_BUFFER), 0) return newBuffer } public func deleteVBO(_ vbo:GLuint) { var deletedVBO = vbo glDeleteBuffers(1, &deletedVBO) } extension String { func withNonZeroSuffix(_ suffix:Int) -> String { if suffix == 0 { return self } else { return "\(self)\(suffix + 1)" } } func withGLChar(_ operation:(UnsafePointer<GLchar>) -> ()) { if let value = self.cString(using:String.Encoding.utf8) { operation(UnsafePointer<GLchar>(value)) } else { fatalError("Could not convert this string to UTF8: \(self)") } } }
13dd429e39d34b1a6f0727ed77870e43
37.149826
205
0.701982
false
false
false
false
danpratt/Tip-Calculator
refs/heads/master
Blue Tip Wrist Calculator Extension/Controllers/OptionsController.swift
mit
1
// // PeopleInterfaceController.swift // Blue Tip Calculator // // Created by Daniel Pratt on 11/18/15. // Copyright © 2015 blaumagier. All rights reserved. // import WatchKit import Foundation class OptionsController: WKInterfaceController { @IBOutlet weak var peoplePicker: WKInterfacePicker! @IBOutlet weak var tipSizePicker: WKInterfacePicker! // shared instance var tipCalculator = BTCTipCalculator.sharedInstance // Variables for picker values var people : Int? var peoplePickerData : [WKPickerItem]! var tipPickerData : [WKPickerItem]! // id used for localization, defaults to english var localeLanguageID: String = "en" override func awake(withContext context: Any?) { super.awake(withContext: context) // setup localization id first if let language = Locale.current.languageCode { localeLanguageID = language } let one = WKPickerItem() one.title = "1" one.caption = justMeLocalized() let two = WKPickerItem() two.title = "2" two.caption = twoLocalized() let three = WKPickerItem() three.title = "3" three.caption = threeLocalized() let four = WKPickerItem() four.title = "4" four.caption = fourLocalized() let five = WKPickerItem() five.title = "5" five.caption = fiveLocalized() let six = WKPickerItem() six.title = "6" six.caption = sixLocalized() peoplePickerData = [one, two, three, four, five, six] peoplePicker.setItems(peoplePickerData) let ten = WKPickerItem() ten.title = "10%" ten.caption = tenPercentTipLocalized() let fiften = WKPickerItem() fiften.title = "15%" fiften.caption = fifteenPercentTipLocalized() let eighteen = WKPickerItem() eighteen.title = "18%" eighteen.caption = eighteenPercentTipLocalized() let twenty = WKPickerItem() twenty.title = "20%" twenty.caption = twentyPercentTipLocalized() let twentyFive = WKPickerItem() twentyFive.title = "25%" twentyFive.caption = twentyFivePercentTipLocalized() tipPickerData = [ten, fiften, eighteen, twenty, twentyFive] tipSizePicker.setItems(tipPickerData) } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() // set current tip picker item to whatever is in the shared instance tipSizePicker.setSelectedItemIndex(tipCalculator.tipPercentValue.hashValue) // set current numPeople item to whatever is in the shared instance let numPeopleItem = tipCalculator.numPeopleSplittingBill - 1 peoplePicker.setSelectedItemIndex(numPeopleItem) } @IBAction func peoplePickerChanged(_ value: Int) { people = value + 1 tipCalculator.setNumPeopleSplitting(numPeople: people!) } @IBAction func tipPercentPickerChanged(_ value: Int) { tipCalculator.setTipPercentValue(tipPercent: TipPercentValue.fromHashValue(hashValue: value)) } }
ce72431e935dd3604e873a4cde37d96a
32.244898
101
0.643339
false
false
false
false