repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
kotdark/Summflower
Summflower/Summflower/SummflowerSegment.swift
2
3756
// // FloraSegment.swift // Flora // // Created by Sameh Mabrouk on 12/24/14. // Copyright (c) 2014 SMApps. All rights reserved. // /* //SummflowerSegment act as a UITableviewCell for this control. It follows the same configuration as a tableview delegate */ import UIKit class SummflowerSegment: UIButton { var backgroundImage:UIImageView = UIImageView() convenience override init() { self.init(frame: CGRectMake(0, 0, SegmentWidth, SegmentHeight)) } func initWithImage(image:UIImage) -> AnyObject{ self.alpha = SegmentAlpha self.backgroundColor = UIColor.clearColor() self.autoresizingMask = UIViewAutoresizing.FlexibleWidth | .FlexibleHeight self.backgroundImage.image = image self.backgroundImage.frame = self.bounds self.addSubview(self.backgroundImage) //setup shadows self.layer.shadowColor = SegmentShadowColor.CGColor self.layer.shadowOffset = SegmentShadowOffset self.layer.shadowOpacity = SegmentShadowOpacity self.layer.shadowRadius = SegmentShadowRadis self.layer.shouldRasterize = true self.layer.rasterizationScale = SegmentRasterizationScale return self } func rotationWithDuration(duration:NSTimeInterval, angle:Float, completion: ((Bool) -> Void)?){ // Repeat a quarter rotation as many times as needed to complete the full rotation var sign:Float = angle > 0 ? 1 : -1 let numberRepeats:Float = floorf(fabsf(angle) / Float( M_PI_2)) let angelabs:CGFloat = CGFloat(fabs(angle)) let quarterDuration:Float = Float(duration * M_PI_2) / Float(angelabs) let lastRotation = angle - sign * numberRepeats * Float(M_PI_2) let lastDuration:Float = Float( duration) - quarterDuration * numberRepeats self.lastRotationWithDuration(NSTimeInterval(lastDuration), rotation: CGFloat( lastRotation)) self.quarterSpinningBlock(NSTimeInterval(quarterDuration), duration: NSInteger(lastDuration), rotation: NSInteger(lastRotation), numberRepeats: NSInteger(numberRepeats)) return completion!(true) } func quarterSpinningBlock(quarterDuration:NSTimeInterval, duration:NSInteger, rotation:NSInteger, numberRepeats:NSInteger){ if numberRepeats>0 { UIView.animateWithDuration(quarterDuration, delay: 0.0, options: UIViewAnimationOptions.BeginFromCurrentState | UIViewAnimationOptions.CurveLinear, animations: { () -> Void in self.transform = CGAffineTransformRotate(self.transform, CGFloat(M_PI_2)) }) { (Bool) -> Void in if numberRepeats > 0 { self.quarterSpinningBlock(quarterDuration, duration: duration, rotation: rotation, numberRepeats: numberRepeats - 1 ) } else{ self.lastRotationWithDuration(NSTimeInterval(duration), rotation: CGFloat(rotation)) return } } } else{ self.lastRotationWithDuration(NSTimeInterval(duration), rotation: CGFloat(rotation)) } } func lastRotationWithDuration(duration:NSTimeInterval, rotation:CGFloat){ UIView.animateWithDuration(duration, delay: 0.0, options: .BeginFromCurrentState | .CurveEaseOut, animations: { () -> Void in self.transform = CGAffineTransformRotate(self.transform, rotation); }, completion: nil) } }
mit
3bdd0f6858eb4d07a09e49e53a4c5cb3
35.125
187
0.628328
5.312588
false
false
false
false
kay-kim/stitch-examples
todo/ios/Pods/ExtendedJson/ExtendedJson/ExtendedJson/Source/ExtendedJson/BsonArray+ExtendedJson.swift
1
1190
// // BsonArray+ExtendedJson.swift // ExtendedJson // // Created by Jason Flax on 10/4/17. // Copyright © 2017 MongoDB. All rights reserved. // import Foundation extension BSONArray: ExtendedJsonRepresentable { public static func fromExtendedJson(xjson: Any) throws -> ExtendedJsonRepresentable { guard let array = xjson as? [Any], let bsonArray = try? BSONArray(array: array) else { throw BsonError.parseValueFailure(value: xjson, attemptedType: BSONArray.self) } return bsonArray } public var toExtendedJson: Any { return map { $0.toExtendedJson } } public func isEqual(toOther other: ExtendedJsonRepresentable) -> Bool { if let other = other as? BSONArray, other.count == self.count { for i in 0..<other.count { let myExtendedJsonRepresentable = self[i] let otherExtendedJsonRepresentable = other[i] if !myExtendedJsonRepresentable.isEqual(toOther: otherExtendedJsonRepresentable) { return false } } } else { return false } return true } }
apache-2.0
ae7e750c7d4fcdfb934c7f9a2e7d76fc
28.725
98
0.610597
4.486792
false
false
false
false
ivasic/Fargo
Fargo/Source/Types/Error.swift
1
2129
// // Error.swift // Fargo // // Created by Ivan Vasic on 01/11/15. // Copyright © 2015 Ivan Vasic. All rights reserved. // import Foundation extension JSON { public enum Error : ErrorType, CustomDebugStringConvertible { case MissingKey(key: JSON.KeyPath.Key, keyPath: JSON.KeyPath) case TypeMismatch(expectedType: String, actualType: String, keyPath: JSON.KeyPath) public init(typeMismatchForType type: String, json: JSON) { self = .TypeMismatch(expectedType: type, actualType: json.objectType(), keyPath: json.keyPath) } public init(missingKey key: JSON.KeyPath.Key, json: JSON) { self = .MissingKey(key: key, keyPath: json.keyPath) } public var debugDescription: String { get { switch self { case .MissingKey(let key, let keyPath): return "MissingKey `\(key)` in keyPath `\(keyPath)`" case .TypeMismatch(let expected, let actual, let keyPath): return "TypeMismatch, expected `\(expected)` got `\(actual)` for keyPath `\(keyPath)`" } } } public func descriptionForJSON(json: JSON) -> String { switch self { case .MissingKey(let key, let keyPath): var string = "MissingKey `\(key)`" if let json = try? json.jsonForKeyPath(keyPath) { string = "\(string) in JSON : `\(json.object)`" } string = "\(string). Full keyPath `\(keyPath)`" return string case .TypeMismatch(let expected, let actual, let keyPath): var string = "TypeMismatch, expected `\(expected)`" if let json = try? json.jsonForKeyPath(keyPath) { string = "\(string) got `(\(json))`" } else { string = "\(string) got `\(actual)`" } string = "\(string). Full keyPath `\(keyPath)`" return string } } } }
mit
c82bddb3b357482df0229c7e202cc551
37
106
0.523496
5.018868
false
false
false
false
xmartlabs/Opera
Example/Example/Controllers/RepositoryCommitsController.swift
1
3513
// RepositoryCommitsController.swift // Example-iOS ( https://github.com/xmartlabs/Example-iOS ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit import OperaSwift import RxSwift import RxCocoa class RepositoryCommitsController: RepositoryBaseController { @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView! let refreshControl = UIRefreshControl() var disposeBag = DisposeBag() lazy var viewModel: PaginationViewModel<PaginationRequest<Commit>> = { [unowned self] in return PaginationViewModel(paginationRequest: PaginationRequest(route: GithubAPI.Repository.GetCommits(owner: self.owner, repo: self.name))) }() override func viewDidLoad() { super.viewDidLoad() tableView.keyboardDismissMode = .onDrag tableView.addSubview(self.refreshControl) emptyStateLabel.text = "No commits found" let refreshControl = self.refreshControl rx.sentMessage(#selector(RepositoryForksController.viewWillAppear(_:))) .map { _ in false } .bind(to: viewModel.refreshTrigger) .disposed(by: disposeBag) tableView.rx.reachedBottom .bind(to: viewModel.loadNextPageTrigger) .disposed(by: disposeBag) viewModel.loading .drive(activityIndicatorView.rx.isAnimating) .disposed(by: disposeBag) Driver.combineLatest(viewModel.elements.asDriver(), viewModel.firstPageLoading) { elements, loading in return loading ? [] : elements } .asDriver() .drive(tableView.rx.items(cellIdentifier:"Cell")) { _, commit, cell in cell.textLabel?.text = commit.author cell.detailTextLabel?.text = commit.date.shortRepresentation() } .disposed(by: disposeBag) refreshControl.rx.valueChanged .filter { refreshControl.isRefreshing } .map { true } .bind(to: viewModel.refreshTrigger) .disposed(by: disposeBag) viewModel.loading .filter { !$0 && refreshControl.isRefreshing } .drive(onNext: { _ in refreshControl.endRefreshing() }) .disposed(by: disposeBag) viewModel.emptyState .drive(onNext: { [weak self] emptyState in self?.emptyStateLabel.isHidden = !emptyState }) .disposed(by: disposeBag) } }
mit
19a9483edff9a74c0e83f905bb0e787e
38.920455
148
0.689439
4.913287
false
false
false
false
DouKing/WYListView
WYListViewController/ListViewController/WYListView.swift
1
10947
// // WYListViewController.swift // WYListViewController // // Created by iosci on 2016/10/20. // Copyright © 2016年 secoo. All rights reserved. // import UIKit @objc public protocol WYListViewDataSource { func numberOfSections(in listView: WYListView) -> Int func listView(_ listView: WYListView, numberOfRowsInSection section: Int) -> Int func listView(_ listView: WYListView, titleForSection section: Int) -> String? func listView(_ listView: WYListView, titleForRowAtIndexPath indexPath: IndexPath) -> String? @objc optional func listView(_ listView: WYListView, selectRowInSection section: Int) -> NSNumber? //@objc不支持Int? @objc optional func sectionHeight(in listView: WYListView) -> CGFloat @objc optional func listView(_ listView: WYListView, rowHeightAtIndexPath indexPath: IndexPath) -> CGFloat } @objc public protocol WYListViewDelegate { @objc optional func listView(_ listView: WYListView, didSelectRowAtIndexPath indexPath: IndexPath) } open class WYListView: UIViewController { fileprivate let tableViewBaseTag: Int = 2000 fileprivate var currentSection: Int? fileprivate var selectedIndexPaths: [Int : Int] = [:] fileprivate var selectedOffsetYs: [Int : CGFloat] = [:] public var dataSource: WYListViewDataSource? public var delegate: WYListViewDelegate? fileprivate weak var floatView: UIView? @IBOutlet fileprivate weak var segmentView: UICollectionView! { didSet { segmentView.dataSource = self segmentView.delegate = self let nib = UINib(nibName: "WYSegmentCell", bundle: nil) segmentView.register(nib, forCellWithReuseIdentifier: WYSegmentCell.cellId) let floatView = UIView(frame: .zero) floatView.backgroundColor = .red floatView.alpha = 0 self.floatView = floatView segmentView.addSubview(floatView) } } @IBOutlet fileprivate weak var contentView: UICollectionView! { didSet { contentView.dataSource = self contentView.delegate = self let nib = UINib(nibName: "WYContentCell", bundle: nil) contentView.register(nib, forCellWithReuseIdentifier: WYContentCell.cellId) } } deinit { self.endObserveDeviceOrientation() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.observeDeviceOrientation() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.observeDeviceOrientation() } open override func viewDidLoad() { super.viewDidLoad() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + TimeInterval(0.15)) { [unowned self] in self.scrollToLastSection(animated: false) } } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let flowLayout = self.contentView.collectionViewLayout as! UICollectionViewFlowLayout flowLayout.itemSize = self.contentView.bounds.size } open func reloadData(selectRowsAtIndexPaths indexPaths: [IndexPath] = []) { self.currentSection = nil self.selectedIndexPaths = [:] self.selectedOffsetYs = [:] for indexPath in indexPaths { self.select(section: indexPath.section, row: indexPath.row) } self.segmentView.reloadData() self.contentView.reloadData() } private func observeDeviceOrientation() { UIDevice.current.beginGeneratingDeviceOrientationNotifications() NotificationCenter.default.addObserver(self, selector: #selector(handleDeviceOrientationNotification(_:)), name: Notification.Name.UIDeviceOrientationDidChange, object: nil) } private func endObserveDeviceOrientation() { NotificationCenter.default.removeObserver(self, name: Notification.Name.UIDeviceOrientationDidChange, object: nil) UIDevice.current.endGeneratingDeviceOrientationNotifications() } private func changeCollectionViewLayout() { let flowLayout = UICollectionViewFlowLayout() flowLayout.scrollDirection = .horizontal flowLayout.minimumLineSpacing = 0 flowLayout.minimumInteritemSpacing = 0 flowLayout.itemSize = self.contentView.bounds.size self.contentView.setCollectionViewLayout(flowLayout, animated: true) if let section = self.currentSection { self.scroll(to: section, animated: false) } } fileprivate func select(section: Int, row: Int?) { self.selectedIndexPaths[section] = row } fileprivate func select(section: Int, offsetY: CGFloat?) { self.selectedOffsetYs[section] = offsetY } @objc private func handleDeviceOrientationNotification(_ note: Notification) { self.changeCollectionViewLayout() } } // MARK: - UICollectionViewDelegate, UICollectionViewDataSource - extension WYListView: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let dataSource = self.dataSource else { return 0 } return dataSource.numberOfSections(in: self) } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if collectionView == self.segmentView { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: WYSegmentCell.cellId, for: indexPath) as! WYSegmentCell guard let dataSource = self.dataSource else { return cell } let title = dataSource.listView(self, titleForSection: indexPath.item) cell.setup(withTitle: title) return cell } let cell = collectionView.dequeueReusableCell(withReuseIdentifier: WYContentCell.cellId, for: indexPath) as! WYContentCell cell.dataSource = self cell.delegate = self cell.section = indexPath.item cell.reload(animated: false, selectRow: self.selectedIndexPaths[indexPath.item], offsetY: self.selectedOffsetYs[indexPath.item]) return cell } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if collectionView == self.contentView { return self.contentView.bounds.size } let title = self.dataSource?.listView(self, titleForSection: indexPath.item) return CGSize(width: WYSegmentCell.width(withTitle: title), height: collectionView.bounds.size.height) } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.scroll(to: indexPath.item, animated: true) } } extension WYListView: WYContentCellDataSource, WYContentCellDelegate { func numberOfRows(in contentCell: WYContentCell) -> Int { guard let dataSource = self.dataSource else { return 0 } return dataSource.listView(self, numberOfRowsInSection: contentCell.section) } func contentCell(_ cell: WYContentCell, titleForRow row: Int) -> String? { guard let dataSource = self.dataSource else { return nil } return dataSource.listView(self, titleForRowAtIndexPath: IndexPath(row: row, section: cell.section)) } func contentCell(_ cell: WYContentCell, didSelectRow row: Int) { self.select(section: cell.section, row: row) self.delegate?.listView?(self, didSelectRowAtIndexPath: IndexPath(row: row, section: cell.section)) } func contentCell(_ cell: WYContentCell, didScrollTo offsetY: CGFloat) { self.select(section: cell.section, offsetY: offsetY) } } // MARK: - Scroll - extension WYListView { open func scrollToLastSection(animated: Bool, after timeInterval: TimeInterval = 0, completion: (() -> Swift.Void)? = nil) { guard let dataSource = self.dataSource else { return } let number = dataSource.numberOfSections(in: self) if number < 1 { return } self.scroll(to: number - 1, animated: animated, after: timeInterval, completion: completion) } open func scroll(to section: Int, animated: Bool, after timeInterval: TimeInterval = 0, completion: (() -> Swift.Void)? = nil) { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + timeInterval) { [unowned self] in guard let dataSource = self.dataSource else { return } let number = dataSource.numberOfSections(in: self) self.currentSection = min(max(section, 0), number - 1) let indexPath = IndexPath(item: self.currentSection!, section: 0) self.segmentView.scrollToItem(at: indexPath, at: .init(rawValue: 0), animated: animated) self.contentView.scrollToItem(at: indexPath, at: .init(rawValue: 0), animated: animated) let layoutAttributes = self.segmentView.collectionViewLayout.initialLayoutAttributesForAppearingItem(at: indexPath) var rect = CGRect.zero if let lab = layoutAttributes { rect = lab.frame } let insert: CGFloat = WYSegmentCell.contentInsert, height: CGFloat = 2 let frame = CGRect(x: rect.origin.x + insert, y: rect.size.height - height, width: rect.size.width - insert * 2, height: height) if animated { UIView.animate(withDuration: 0.15, animations: { [unowned self] in self.floatView?.frame = frame }) { [unowned self] (finished) in self.floatView?.alpha = 1 } } else { self.floatView?.frame = frame self.floatView?.alpha = 1 if completion != nil { completion!() } } } } private func scrollViewDidEndScroll(_ scrollView: UIScrollView) { guard scrollView == self.contentView else { return } let section = scrollView.contentOffset.x / scrollView.bounds.size.width self.scroll(to: Int(section), animated: true) } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { self.scrollViewDidEndScroll(scrollView) } } fileprivate extension WYSegmentCell { static let cellId = "kWYSegmentCellId" } fileprivate extension WYContentCell { static let cellId = "kWYContentCellId" }
mit
665ae1de0d2267de7e883e40d3e5664b
39.065934
181
0.660724
5.356513
false
false
false
false
benjaminsnorris/SharedHelpers
Sources/SwipeTransitionInteractionController.swift
1
5745
/* | _ ____ ____ _ | | |‾| ⚈ |-| ⚈ |‾| | | | | ‾‾‾‾| |‾‾‾‾ | | | ‾ ‾ ‾ */ import UIKit class SwipeTransitionInteractionController: UIPercentDrivenInteractiveTransition { var edge: UIRectEdge var gestureRecognizer: UIPanGestureRecognizer weak var transitionContext: UIViewControllerContextTransitioning? var scrollView: UIScrollView? fileprivate var adjustedInitialLocation = CGPoint.zero fileprivate var initialContentOffset = CGPoint.zero static let velocityThreshold: CGFloat = 50.0 init(edgeForDragging edge: UIRectEdge, gestureRecognizer: UIPanGestureRecognizer, scrollView: UIScrollView? = nil) { self.edge = edge self.gestureRecognizer = gestureRecognizer super.init() self.gestureRecognizer.addTarget(self, action: #selector(gestureRecognizerDidUpdate(_:))) self.scrollView = scrollView if let tableView = scrollView as? UITableView { initialContentOffset = tableView.style == .grouped ? CGPoint(x: 0, y: -44) : .zero } } @available(*, unavailable, message: "Use `init(edgeForDragging:gestureRecognizer:) instead") override init() { fatalError("Use `init(edgeForDragging:gestureRecognizer:) instead") } deinit { gestureRecognizer.removeTarget(self, action: #selector(gestureRecognizerDidUpdate(_:))) } override func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) { self.transitionContext = transitionContext super.startInteractiveTransition(transitionContext) } func percent(for recognizer: UIPanGestureRecognizer) -> CGFloat { guard let transitionContainerView = transitionContext?.containerView else { return 0 } if let scrollView = scrollView, percentComplete == 0 { switch edge { case .top: if scrollView.contentOffset.y >= initialContentOffset.y { return 0 } case .bottom: if scrollView.contentOffset.y <= initialContentOffset.y { return 0 } case .left: if scrollView.contentOffset.x >= initialContentOffset.x { return 0 } case .right: if scrollView.contentOffset.x <= initialContentOffset.x { return 0 } default: fatalError("edge must be .top, .bottom, .left, or .right. actual=\(edge)") } if adjustedInitialLocation == .zero { adjustedInitialLocation = recognizer.location(in: transitionContainerView) } } scrollView?.contentOffset = initialContentOffset let delta = recognizer.translation(in: transitionContainerView) let width = transitionContainerView.bounds.width let height = transitionContainerView.bounds.height var adjustedPoint = delta if adjustedInitialLocation != .zero { let locationInSourceView = recognizer.location(in: transitionContainerView) adjustedPoint = CGPoint(x: locationInSourceView.x - adjustedInitialLocation.x, y: locationInSourceView.y - adjustedInitialLocation.y) } switch edge { case .top: return adjustedPoint.y > 0 ? adjustedPoint.y / height : 0 case .bottom: return adjustedPoint.y < 0 ? abs(adjustedPoint.y) / height : 0 case .left: return adjustedPoint.x > 0 ? adjustedPoint.x / height : 0 case .right: return adjustedPoint.x < 0 ? abs(adjustedPoint.x) / width : 0 default: fatalError("edge must be .top, .bottom, .left, or .right. actual=\(edge)") } } @objc func gestureRecognizerDidUpdate(_ gestureRecognizer: UIPanGestureRecognizer) { switch gestureRecognizer.state { case .possible, .began: break case .changed: update(percent(for: gestureRecognizer)) case .ended: let velocity = gestureRecognizer.velocity(in: transitionContext?.containerView) var swiped = false switch edge { case .top: swiped = velocity.y > SwipeTransitionInteractionController.velocityThreshold if let scrollView = scrollView, scrollView.contentOffset.y > initialContentOffset.y { swiped = false } case .bottom: swiped = velocity.y < -SwipeTransitionInteractionController.velocityThreshold if let scrollView = scrollView, scrollView.contentOffset.y < initialContentOffset.y { swiped = false } case .left: swiped = velocity.x > SwipeTransitionInteractionController.velocityThreshold if let scrollView = scrollView, scrollView.contentOffset.x > initialContentOffset.x { swiped = false } case .right: swiped = velocity.x < -SwipeTransitionInteractionController.velocityThreshold if let scrollView = scrollView, scrollView.contentOffset.x < initialContentOffset.x { swiped = false } default: break } if swiped || percent(for: gestureRecognizer) >= 0.5 { finish() } else { cancel() } case .cancelled, .failed: cancel() @unknown default: break } } }
mit
0ef9151608c0b501fda420e3ac5490e4
38.965035
145
0.590726
5.92228
false
false
false
false
ksco/swift-algorithm-club-cn
Bloom Filter/BloomFilter.playground/Contents.swift
1
2168
//: Playground - noun: a place where people can play public class BloomFilter<T> { private var array: [Bool] private var hashFunctions: [T -> Int] public init(size: Int = 1024, hashFunctions: [T -> Int]) { self.array = .init(count: size, repeatedValue: false) self.hashFunctions = hashFunctions } private func computeHashes(value: T) -> [Int] { return hashFunctions.map() { hashFunc in abs(hashFunc(value) % array.count) } } public func insert(element: T) { for hashValue in computeHashes(element) { array[hashValue] = true } } public func insert(values: [T]) { for value in values { insert(value) } } public func query(value: T) -> Bool { let hashValues = computeHashes(value) // Map hashes to indices in the Bloom Filter let results = hashValues.map() { hashValue in array[hashValue] } // All values must be 'true' for the query to return true // This does NOT imply that the value is in the Bloom filter, // only that it may be. If the query returns false, however, // you can be certain that the value was not added. let exists = results.reduce(true, combine: { $0 && $1 }) return exists } public func isEmpty() -> Bool { // As soon as the reduction hits a 'true' value, the && condition will fail. return array.reduce(true) { prev, next in prev && !next } } } /* Two hash functions, adapted from http://www.cse.yorku.ca/~oz/hash.html */ func djb2(x: String) -> Int { var hash = 5381 for char in x.characters { hash = ((hash << 5) &+ hash) &+ char.hashValue } return Int(hash) } func sdbm(x: String) -> Int { var hash = 0 for char in x.characters { hash = char.hashValue &+ (hash << 6) &+ (hash << 16) &- hash } return Int(hash) } /* A simple test */ let bloom = BloomFilter<String>(size: 17, hashFunctions: [djb2, sdbm]) bloom.insert("Hello world!") print(bloom.array) bloom.query("Hello world!") // true bloom.query("Hello WORLD") // false bloom.insert("Bloom Filterz") print(bloom.array) bloom.query("Bloom Filterz") // true bloom.query("Hello WORLD") // true
mit
cefd52451a45c1e5d6add8145b432106
24.209302
81
0.631919
3.559934
false
false
false
false
noehou/myDouYuZB
DYZB/DYZB/Classes/Home/View/RecommendCycleView.swift
1
4217
// // RecommendCycleView.swift // DYZB // // Created by Tommaso on 2016/12/12. // Copyright © 2016年 Tommaso. All rights reserved. // import UIKit private let kCycleCellID = "kCycleCellID" class RecommendCycleView: UIView { //MARK:定义属性 var cycleTimer : Timer? var cycleModels : [CycleModel]?{ didSet { //1、刷新collectionView collectionView.reloadData() //2、设置pageControl个数 pageControl.numberOfPages = cycleModels?.count ?? 0 //3、默认滚动到中间某一个位置 let indexPath = NSIndexPath(item: (cycleModels?.count ?? 0) * 10, section: 0) collectionView.scrollToItem(at: indexPath as IndexPath, at: .left, animated: false) //4、添加定时器 removeCycleTimer() addCycleTimer() } } //MARK:控件属性 @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! //MARK:系统回调函数 override func awakeFromNib() { super.awakeFromNib() //设置该控件不随着父控件的拉伸而拉伸 autoresizingMask = UIViewAutoresizing() //注册cell collectionView.register(UINib(nibName: "CollectionCycleCell", bundle: nil), forCellWithReuseIdentifier: kCycleCellID) } override func layoutSubviews() { super.layoutSubviews() //设置collectionView的layout let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size // layout.minimumLineSpacing = 0 // layout.minimumInteritemSpacing = 0 // layout.scrollDirection = .horizontal // collectionView.isPagingEnabled = true } } //MARK:-提供一个快速创建view的类方法 extension RecommendCycleView { class func recommendCycleView() -> RecommendCycleView { return Bundle.main.loadNibNamed("RecommendCycleView", owner: nil, options: nil)?.first as! RecommendCycleView } } //MARK:-遵守UICollectionView的数据源协议 extension RecommendCycleView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (cycleModels?.count ?? 0) * 10000 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleCellID, for: indexPath) as! CollectionCycleCell cell.cycleModel = cycleModels?[indexPath.item % (cycleModels?.count)!] return cell } } //MARK:-遵守UICollectionView的代理协议 extension RecommendCycleView : UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { //1、获取滚动的偏移量 let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5 //2、计算pageControl的currentIndex pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1) } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { removeCycleTimer() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { addCycleTimer() } } //MARK:-对定时器的操作方法 extension RecommendCycleView { public func addCycleTimer() { cycleTimer = Timer(timeInterval: 3.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true) RunLoop.main.add(cycleTimer!, forMode: .commonModes) } public func removeCycleTimer(){ cycleTimer?.invalidate() cycleTimer = nil } @objc private func scrollToNext() { //1、获取滚动的偏移量 let currentOffsetX = collectionView.contentOffset.x let offsetX = currentOffsetX + collectionView.bounds.width //2、滚动到该位置 collectionView.setContentOffset(CGPoint(x: offsetX,y:0), animated: true) } }
mit
adf082ad982ef19fd5927f83a697025f
32.726496
133
0.664724
5.22649
false
false
false
false
the-grid/Disc
Disc/Models/User.swift
1
1684
import Argo import Ogra import Runes /// A user. public struct User { public let app: UUID? public let avatarUrl: URL? public var emailAddress: String public let id: UUID public var name: String public let scopes: [Scope]? public init( app: UUID? = nil, avatarUrl: URL? = nil, emailAddress: String, id: UUID, name: String, scopes: [Scope]? = nil ) { self.app = app self.avatarUrl = avatarUrl self.emailAddress = emailAddress self.id = id self.name = name self.scopes = scopes } } // Mark: - Decodable extension User: Decodable { public static func decode(_ j: JSON) -> Decoded<User> { return curry(self.init) <^> j <|? "app" <*> j <|? "avatar" <*> j <| "email" <*> j <| "uuid" <*> j <| "name" <*> j <||? "scope" } } // Mark: - Encodable extension User: Encodable { public func encode() -> JSON { return .object([ "app": app.encode(), "avatar": avatarUrl.encode(), "email": emailAddress.encode(), "uuid": id.encode(), "name": name.encode(), "scope": scopes.encode() ]) } } // Mark: - Equatable extension User: Equatable {} public func == (lhs: User, rhs: User) -> Bool { return lhs.app?.uuidString == rhs.app?.uuidString && lhs.avatarUrl?.absoluteString == rhs.avatarUrl?.absoluteString && lhs.emailAddress == rhs.emailAddress && lhs.id == rhs.id && lhs.name == rhs.name && lhs.scopes == rhs.scopes }
mit
90016f1a83d2515f266f2c32caac557f
21.756757
73
0.513658
4.087379
false
false
false
false
18775134221/SwiftBase
SwiftTest/SwiftTest/Classes/Main/VC/BaseTabBarVC.swift
2
2733
// // BaseTabBarVC.swift // SwiftTest // // Created by MAC on 2016/12/10. // Copyright © 2016年 MAC. All rights reserved. // import UIKit class BaseTabBarVC: UITabBarController { fileprivate var homeVC: HomeVC? = nil fileprivate var typesVC: TypesVC? = nil fileprivate var shoppingCartVC: ShoppingCartVC? = nil fileprivate var mineVC: MineVC? = nil override func viewDidLoad() { super.viewDidLoad() setupUI() } } extension BaseTabBarVC { fileprivate func setupUI() { setupChildVCs() setupTabBar() } // 设置自定义的TabBar private func setupTabBar() { UITabBar.appearance().tintColor = UIColor.orange let baseTabBar: BaseTabBar = BaseTabBar() baseTabBar.type = .plusDefault // 隐藏系统顶部tabBar的黑线 baseTabBar.shadowImage = UIImage() baseTabBar.backgroundImage = UIImage() baseTabBar.backgroundColor = UIColor(r: 0.62, g: 0.03, b: 0.05) setValue(baseTabBar, forKey: "tabBar") } private func setupChildVCs() { homeVC = UIStoryboard(name: "Home", bundle: nil).instantiateViewController(withIdentifier: "HomeVC") as? HomeVC addChildVC(homeVC!,"首页","icon_home_normal","icon_home_selected") typesVC = UIStoryboard(name: "Types", bundle: nil).instantiateViewController(withIdentifier: "TypesVC") as? TypesVC addChildVC(typesVC!,"分类","iocn_classification_normal","iocn_classification_selected") shoppingCartVC = UIStoryboard(name: "ShoppingCart", bundle: nil).instantiateViewController(withIdentifier: "ShoppingCartVC") as? ShoppingCartVC addChildVC(shoppingCartVC!,"购物车","icon_shopping-cart_normal","icon_shopping-cart_selected") mineVC = UIStoryboard(name: "Mine", bundle: nil).instantiateViewController(withIdentifier: "MineVC") as? MineVC addChildVC(mineVC!,"我的","icon_personal-center_normal","icon_personal-center_selected") } private func addChildVC(_ vc: UIViewController, _ title: String = "", _ normalImage: String = "",_ selectedImage: String = "") { vc.title = title; vc.tabBarItem.selectedImage = UIImage(named: selectedImage) vc.tabBarItem.image = UIImage(named: normalImage) let baseNaviVC: BaseNavigationVC = BaseNavigationVC(rootViewController: vc) addChildViewController(baseNaviVC) } } extension BaseTabBarVC: UITabBarControllerDelegate { // 选中底部导航按钮回调 override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { } }
apache-2.0
68f767070cf7527ebf6af0f2cc72e46e
30.317647
151
0.648009
4.678383
false
false
false
false
LoopKit/LoopKit
LoopKitUI/UIAlertController.swift
1
2772
// // UIAlertController.swift // LoopKitUI // // Created by Pete Schwamb on 1/22/19. // Copyright © 2019 LoopKit Authors. All rights reserved. // import Foundation extension UIAlertController { /// Convenience method to initialize an alert controller to display an error /// /// - Parameters: /// - error: The error to display /// - title: The title of the alert. If nil, the error description will be used. /// - helpAnchorHandler: An optional closure to be executed when a user taps to open the error's `helpAnchor` /// - url: A URL created from the error's helpAnchor property public convenience init(with error: Error, title: String? = nil, helpAnchorHandler: ((_ url: URL) -> Void)? = nil) { var actions: [UIAlertAction] = [] let errorTitle: String let message: String if let error = error as? LocalizedError { let sentenceFormat = LocalizedString("%@.", comment: "Appends a full-stop to a statement") let messageWithRecovery = [error.failureReason, error.recoverySuggestion].compactMap({ $0 }).map({ String(format: sentenceFormat, $0) }).joined(separator: "\n") if messageWithRecovery.isEmpty { message = error.localizedDescription } else { message = messageWithRecovery } if let helpAnchor = error.helpAnchor, let url = URL(string: helpAnchor), let helpAnchorHandler = helpAnchorHandler { actions.append(UIAlertAction( title: LocalizedString("More Info", comment: "Alert action title to open error help"), style: .default, handler: { (_) in helpAnchorHandler(url) } )) } errorTitle = (error.errorDescription ?? error.localizedDescription).localizedCapitalized } else { // See: https://forums.developer.apple.com/thread/17431 // The compiler automatically emits the code necessary to translate between any ErrorType and NSError. let castedError = error as NSError errorTitle = error.localizedDescription.localizedCapitalized message = castedError.localizedRecoverySuggestion ?? String(describing: error) } self.init(title: title ?? errorTitle, message: message, preferredStyle: .alert) let action = UIAlertAction( title: LocalizedString("com.loudnate.LoopKit.errorAlertActionTitle", value: "OK", comment: "The title of the action used to dismiss an error alert"), style: .default) addAction(action) self.preferredAction = action for action in actions { addAction(action) } } }
mit
4b89df7fbd13ba91e438e07540f92ba1
40.358209
178
0.626128
5.09375
false
false
false
false
LauraSempere/meme-app
Meme/SentMemesCollectionViewController.swift
1
2644
// // SentMemesCollectionViewController.swift // Meme // // Created by Laura Scully on 1/7/2016. // Copyright © 2016 laura.com. All rights reserved. // import UIKit class SentMemesCollectionViewController: UICollectionViewController { @IBOutlet weak var flowLayout:UICollectionViewFlowLayout! var memes:[Meme]! override func viewDidLoad() { super.viewDidLoad() let applicationDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate) memes = applicationDelegate.memes let space: CGFloat = 3.0 let width = (view.frame.size.width - (2 * space)) / space let height = (view.frame.size.height - (2 * space)) / space flowLayout.minimumInteritemSpacing = space flowLayout.minimumLineSpacing = space / 10 flowLayout.itemSize = CGSizeMake(width, height) self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: #selector(SentMemesCollectionViewController.goToEditMeme)) } override func viewWillAppear(animated: Bool) { self.tabBarController?.tabBar.hidden = false memes = (UIApplication.sharedApplication().delegate as! AppDelegate).memes self.collectionView!.reloadData() } func goToEditMeme(){ let memeEditorVC = storyboard?.instantiateViewControllerWithIdentifier("MemeEditorViewController") as! MemeEditorViewController self.navigationController?.pushViewController(memeEditorVC, animated: true) } // MARK: UICollectionViewDataSource override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return memes.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! SentMemesCollectionViewCell let meme = memes[indexPath.item] cell.image.image = meme.memedImage return cell } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let detailVC = storyboard?.instantiateViewControllerWithIdentifier("MemeDetailViewController") as! MemeDetailViewController let meme = memes[indexPath.item] detailVC.meme = meme detailVC.memeIndex = indexPath.item self.navigationController?.pushViewController(detailVC, animated: true) } }
epl-1.0
ebad3e08a160468a91318cf37e409962
39.045455
194
0.718502
5.745652
false
false
false
false
ntwf/TheTaleClient
TheTale/Stores/GameInformation/GameInformation.swift
1
1997
// // GameInformation.swift // the-tale // // Created by Mikhail Vospennikov on 14/05/2017. // Copyright © 2017 Mikhail Vospennikov. All rights reserved. // import Foundation struct GameInformation { var accountID: Int var accountName: String var gameVersion: String var staticContent: String var turnDelta: Int var arenaPvP: Int var arenaPvPAccept: Int var arenaPvPLeaveQueue: Int var help: Int var buildingRepair: Int var dropItem: Int } extension GameInformation: JSONDecodable { init?(jsonObject: JSON) { guard let accountID = jsonObject["account_id"] as? Int, let accountName = jsonObject["account_name"] as? String, let gameVersion = jsonObject["game_version"] as? String, let staticContent = jsonObject["static_content"] as? String, let turnDelta = jsonObject["turn_delta"] as? Int, let abilitiesCost = jsonObject["abilities_cost"] as? JSON, let arenaPvP = abilitiesCost["arena_pvp_1x1"] as? Int, let arenaPvPAccept = abilitiesCost["arena_pvp_1x1_accept"] as? Int, let arenaPvPLeaveQueue = abilitiesCost["arena_pvp_1x1_leave_queue"] as? Int, let help = abilitiesCost["help"] as? Int, let buildingRepair = abilitiesCost["building_repair"] as? Int, let dropItem = abilitiesCost["drop_item"] as? Int else { return nil } self.accountID = accountID self.accountName = accountName self.gameVersion = gameVersion self.staticContent = staticContent self.turnDelta = turnDelta self.arenaPvP = arenaPvP self.arenaPvPAccept = arenaPvPAccept self.arenaPvPLeaveQueue = arenaPvPLeaveQueue self.help = help self.buildingRepair = buildingRepair self.dropItem = dropItem } init?() { self.init(jsonObject: [:]) } }
mit
69d73d714df040b17ba5d310049357fb
32.266667
86
0.619739
4.396476
false
false
false
false
rockgarden/swift_language
Playground/Design-Patterns.playground/Design-Patterns.playground/section-20.swift
1
680
var gameState = GameState() gameState.restoreFromMemento(CheckPoint.restorePreviousState()) gameState.chapter = "Black Mesa Inbound" gameState.weapon = "Crowbar" CheckPoint.saveState(gameState.toMemento()) gameState.chapter = "Anomalous Materials" gameState.weapon = "Glock 17" gameState.restoreFromMemento(CheckPoint.restorePreviousState()) gameState.chapter = "Unforeseen Consequences" gameState.weapon = "MP5" CheckPoint.saveState(gameState.toMemento(), keyName: "gameState2") gameState.chapter = "Office Complex" gameState.weapon = "Crossbow" CheckPoint.saveState(gameState.toMemento()) gameState.restoreFromMemento(CheckPoint.restorePreviousState(keyName: "gameState2"))
mit
b6c8554246ba7f2434f8c58497d1b333
33.05
84
0.816176
4.023669
false
false
false
false
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxCocoa/RxCocoa/CocoaUnits/ControlProperty.swift
10
4956
// // ControlProperty.swift // RxCocoa // // Created by Krunoslav Zaher on 8/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif /// Protocol that enables extension of `ControlProperty`. public protocol ControlPropertyType : ObservableType, ObserverType { /// - returns: `ControlProperty` interface func asControlProperty() -> ControlProperty<E> } /** Unit for `Observable`/`ObservableType` that represents property of UI element. Sequence of values only represents initial control value and user initiated value changes. Programatic value changes won't be reported. It's properties are: - it never fails - `shareReplay(1)` behavior - it's stateful, upon subscription (calling subscribe) last element is immediately replayed if it was produced - it will `Complete` sequence on control being deallocated - it never errors out - it delivers events on `MainScheduler.instance` **The implementation of `ControlProperty` will ensure that sequence of values is being subscribed on main scheduler (`subscribeOn(ConcurrentMainScheduler.instance)` behavior).** **It is implementor's responsibility to make sure that that all other properties enumerated above are satisfied.** **If they aren't, then using this unit communicates wrong properties and could potentially break someone's code.** **In case `values` observable sequence that is being passed into initializer doesn't satisfy all enumerated properties, please don't use this unit.** */ public struct ControlProperty<PropertyType> : ControlPropertyType { public typealias E = PropertyType let _values: Observable<PropertyType> let _valueSink: AnyObserver<PropertyType> /// Initializes control property with a observable sequence that represents property values and observer that enables /// binding values to property. /// /// - parameter values: Observable sequence that represents property values. /// - parameter valueSink: Observer that enables binding values to control property. /// - returns: Control property created with a observable sequence of values and an observer that enables binding values /// to property. public init<V: ObservableType, S: ObserverType>(values: V, valueSink: S) where E == V.E, E == S.E { _values = values.subscribeOn(ConcurrentMainScheduler.instance) _valueSink = valueSink.asObserver() } /// Subscribes an observer to control property values. /// /// - parameter observer: Observer to subscribe to property values. /// - returns: Disposable object that can be used to unsubscribe the observer from receiving control property values. public func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { return _values.subscribe(observer) } /// `ControlEvent` of user initiated value changes. Every time user updates control value change event /// will be emitted from `changed` event. /// /// Programatic changes to control value won't be reported. /// /// It contains all control property values except for first one. /// /// The name only implies that sequence element will be generated once user changes a value and not that /// adjacent sequence values need to be different (e.g. because of interaction between programatic and user updates, /// or for any other reason). public var changed: ControlEvent<PropertyType> { get { return ControlEvent(events: _values.skip(1)) } } /// - returns: `Observable` interface. public func asObservable() -> Observable<E> { return _values } /// - returns: `ControlProperty` interface. public func asControlProperty() -> ControlProperty<E> { return self } /// Binds event to user interface. /// /// - In case next element is received, it is being set to control value. /// - In case error is received, DEBUG buids raise fatal error, RELEASE builds log event to standard output. /// - In case sequence completes, nothing happens. public func on(_ event: Event<E>) { switch event { case .error(let error): bindingErrorToInterface(error) case .next: _valueSink.on(event) case .completed: _valueSink.on(event) } } } extension ControlPropertyType where E == String? { /// Transforms control property of type `String?` into control property of type `String`. public var orEmpty: ControlProperty<String> { let original: ControlProperty<String?> = self.asControlProperty() let values: Observable<String> = original._values.map { $0 ?? "" } let valueSink: AnyObserver<String> = original._valueSink.mapObserver { $0 } return ControlProperty<String>(values: values, valueSink: valueSink) } }
apache-2.0
b54dc47d37758a3d351d7cedf1f7ac75
38.959677
124
0.694652
4.95005
false
false
false
false
hirohisa/RxSwift
RxSwift/RxSwift/Observables/Implementations/Filter.swift
15
1793
// // Filter.swift // Rx // // Created by Krunoslav Zaher on 2/17/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class Where_<O : ObserverType>: Sink<O>, ObserverType { typealias Element = O.Element typealias Parent = Where<Element> let parent: Parent init(parent: Parent, observer: O, cancel: Disposable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func on(event: Event<Element>) { switch event { case .Next(let boxedValue): let value = boxedValue.value _ = self.parent.predicate(value).recoverWith { e in trySendError(observer, e) self.dispose() return failure(e) }.flatMap { satisfies -> RxResult<Void> in if satisfies { trySend(observer, event) } return SuccessResult } case .Completed: fallthrough case .Error: trySend(observer, event) self.dispose() } } } class Where<Element> : Producer<Element> { typealias Predicate = (Element) -> RxResult<Bool> let source: Observable<Element> let predicate: Predicate init(source: Observable<Element>, predicate: Predicate) { self.source = source self.predicate = predicate } override func run<O: ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = Where_(parent: self, observer: observer, cancel: cancel) setSink(sink) return source.subscribeSafe(sink) } }
mit
3e31258059f85c7dbcf0c6bc8acbfbd8
28.409836
145
0.559398
4.755968
false
false
false
false
RMizin/PigeonMessenger-project
FalconMessenger/ChatsControllers/IncomingVoiceMessageCell.swift
1
2615
// // IncomingVoiceMessageCell.swift // Pigeon-project // // Created by Roman Mizin on 11/26/17. // Copyright © 2017 Roman Mizin. All rights reserved. // import UIKit import AVFoundation class IncomingVoiceMessageCell: BaseVoiceMessageCell { override func setupViews() { super.setupViews() bubbleView.addSubview(playerView) bubbleView.addSubview(nameLabel) bubbleView.addSubview(timeLabel) bubbleView.frame.origin = BaseMessageCell.incomingBubbleOrigin bubbleView.frame.size.width = 150 timeLabel.backgroundColor = .clear timeLabel.textColor = UIColor.darkGray.withAlphaComponent(0.7) playerView.timerLabel.textColor = ThemeManager.currentTheme().incomingBubbleTextColor bubbleView.tintColor = ThemeManager.currentTheme().incomingBubbleTintColor } override func prepareForReuse() { super.prepareForReuse() bubbleView.tintColor = ThemeManager.currentTheme().incomingBubbleTintColor playerView.timerLabel.textColor = ThemeManager.currentTheme().incomingBubbleTextColor } func setupData(message: Message, isGroupChat: Bool) { if isGroupChat { nameLabel.text = message.senderName ?? "" nameLabel.sizeToFit() bubbleView.frame.size.height = frame.size.height.rounded() playerView.frame = CGRect(x: 10, y: 20, width: bubbleView.frame.width-20, height: bubbleView.frame.height-BaseMessageCell.messageTimeHeight-15).integral if nameLabel.frame.size.width >= BaseMessageCell.incomingGroupMessageAuthorNameLabelMaxWidth { nameLabel.frame.size.width = playerView.frame.size.width - 24 } } else { bubbleView.frame.size.height = frame.size.height.rounded() playerView.frame = CGRect(x: 7, y: 14, width: bubbleView.frame.width-17, height: bubbleView.frame.height-BaseMessageCell.messageTimeHeight-19).integral } timeLabel.frame.origin = CGPoint(x: bubbleView.frame.width-timeLabel.frame.width-1, y: bubbleView.frame.height-timeLabel.frame.height-5) timeLabel.text = message.convertedTimestamp guard message.voiceEncodedString != nil else { return } playerView.timerLabel.text = message.voiceDuration playerView.startingTime = message.voiceStartTime.value ?? 0 playerView.seconds = message.voiceStartTime.value ?? 0 if let isCrooked = message.isCrooked.value, isCrooked { bubbleView.image = ThemeManager.currentTheme().incomingBubble } else { bubbleView.image = ThemeManager.currentTheme().incomingPartialBubble } } }
gpl-3.0
415ea81723425d556f81778b473e192a
39.215385
110
0.717674
4.667857
false
false
false
false
chrislzm/TimeAnalytics
Time Analytics/TANetClient.swift
1
5958
// // TANetClient.swift // Time Analytics // // Singleton network client interface for Time Analytics. Used by TANetClientConvenience methods to make requests of the Moves REST API. // // Created by Chris Leung on 5/14/17. // Copyright © 2017 Chris Leung. All rights reserved. // import Foundation class TANetClient { // MARK: Shared Instance static let sharedInstance = TANetClient() // MARK: Properties var session = URLSession.shared // MARK: Session Variables // A copy of all these session variables are stored in UserDefaults, and loaded by the AppDelegate when the app is opened // Moves session variables var movesAuthCode:String? var movesAccessToken:String? var movesAccessTokenExpiration:Date? var movesRefreshToken:String? var movesUserId:UInt64? var movesUserFirstDate:String? var movesLatestUpdate:Date? // RescueTime session variable var rescueTimeApiKey:String? // Internal session variables var lastCheckedForNewData:Date? // MARK: Methods // Shared HTTP Method for all HTTP requests func taskForHTTPMethod(_ apiScheme:String, _ httpMethod:String, _ apiHost: String, _ apiMethod: String, apiParameters: [String:String]?, valuesForHTTPHeader: [(String, String)]?, httpBody: String?, completionHandler: @escaping (_ result: AnyObject?, _ error: NSError?) -> Void) -> URLSessionDataTask { /* 1. Build the URL */ let request = NSMutableURLRequest(url: urlFromParameters(apiScheme, apiHost, apiMethod, apiParameters)) /* 2. Configure the request */ request.httpMethod = httpMethod // Add other HTTP Header fields and values, if any if let valuesForHTTPHeader = valuesForHTTPHeader { for (value,headerField) in valuesForHTTPHeader { request.addValue(value, forHTTPHeaderField: headerField) } } // Add http request body, if any if let httpBody = httpBody { request.httpBody = httpBody.data(using: String.Encoding.utf8) } /* 3. Make the request */ let task = session.dataTask(with: request as URLRequest) { (data, response, error) in func sendError(_ error: String) { let userInfo = [NSLocalizedDescriptionKey : error] completionHandler(nil, NSError(domain: "taskForGETMethod", code: 1, userInfo: userInfo)) } /* GUARD: Was there an error? */ guard (error == nil) else { sendError("There was an error with your request: \(String(describing: error))") return } /* GUARD: Did we get a status code from the response? */ guard let statusCode = (response as? HTTPURLResponse)?.statusCode else { sendError("Your request did not return a valid response (no status code).") return } /* GUARD: Did we get a successful 2XX response? */ guard statusCode >= 200 && statusCode <= 299 else { var errorString = "Your request returned a status code other than 2xx. Status code returned: \(statusCode).\n" // If we received some response, also include it in the error message if let errorResponse = response { errorString += "Error response receieved: \(errorResponse)\n" } // If we received some data, also include it in the error message if let errorData = data { let (parsedErrorData,_) = self.convertData(errorData) if let validParsedErrorData = parsedErrorData { errorString += "Error data received: \(validParsedErrorData)\n" } } sendError(errorString) return } /* GUARD: Was there any data returned? */ guard let data = data else { sendError("No data was returned by the request!") return } /* 4. Attempt to parse the data */ let (parseResult,error) = self.convertData(data) /* 5. Send the result to the completion handler */ completionHandler(parseResult,error) } /* 6. Start the request */ task.resume() return task } // MARK: Private helper methods // Creates a URL from parameters private func urlFromParameters(_ apiScheme:String, _ host:String, _ method:String, _ parameters: [String:String]?) -> URL { var components = URLComponents() components.scheme = apiScheme components.host = host components.path = method if let parameters = parameters { components.queryItems = [URLQueryItem]() for (key, value) in parameters { let queryItem = URLQueryItem(name: key, value: value) components.queryItems!.append(queryItem) } } return components.url! } // Attemps to convert raw JSON into a usable Foundation object. Returns an error if unsuccessful. private func convertData(_ data: Data) -> (AnyObject?,NSError?) { var parsedResult: AnyObject? = nil do { parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as AnyObject } catch { let userInfo = [NSLocalizedDescriptionKey : "Could not parse the data as JSON: '\(data)'"] let error = NSError(domain: "NetClient.convertData", code: 1, userInfo: userInfo) return(nil,error) } return(parsedResult,nil) } }
mit
260bade6aa495ee663ff64eff809b4e2
36.465409
305
0.583347
5.299822
false
false
false
false
1aurabrown/eidolon
Kiosk/Bid Fulfillment/PlacingBidViewController.swift
1
8060
import UIKit class PlacingBidViewController: UIViewController { @IBOutlet weak var titleLabel: ARSerifLabel! @IBOutlet var bidDetailsPreviewView: BidDetailsPreviewView! @IBOutlet weak var outbidNoticeLabel: ARSerifLabel! @IBOutlet weak var spinner: Spinner! @IBOutlet weak var bidConfirmationImageView: UIImageView! let placeBidNetworkModel = PlaceBidNetworkModel() var registerNetworkModel: RegistrationNetworkModel? var foundHighestBidder = false var pollInterval = NSTimeInterval(1) var maxPollRequests = 6 var pollRequests = 0 @IBOutlet weak var backToAuctionButton: ActionButton! // for comparisons at the end var bidderPositions:[BidderPosition]? var mostRecentSaleArtwork:SaleArtwork? override func viewDidLoad() { super.viewDidLoad() outbidNoticeLabel.hidden = true backToAuctionButton.hidden = true let auctionID = self.fulfillmentNav().auctionID! let bidDetails = self.fulfillmentNav().bidDetails bidDetailsPreviewView.bidDetails = bidDetails RACSignal.empty().then { if self.registerNetworkModel == nil { return RACSignal.empty() } return self.registerNetworkModel?.registerSignal().doError { (error) -> Void in // TODO: Display Registration Error } } .then { self.placeBidNetworkModel.fulfillmentNav = self.fulfillmentNav() return self.placeBidNetworkModel.bidSignal(auctionID, bidDetails:bidDetails).doError { (error) -> Void in // TODO: Display Bid Placement Error // If you just registered, we can still push the bidder details VC and display your info } } .then { [weak self] (_) in if self == nil { return RACSignal.empty() } return self!.waitForBidResolution().doError { (error) -> Void in // TODO: Display error or message. Possible that the user will receive texts about result of their bid // We can still display your bidder info to you } } .subscribeNext { [weak self] (_) -> Void in self?.finishUp() return } } func checkForMaxBid() -> RACSignal { return self.getMyBidderPositions().doNext { [weak self] (newBidderPositions) -> Void in let newBidderPositions = newBidderPositions as? [BidderPosition] self?.bidderPositions = newBidderPositions } } func waitForBidResolution () -> RACSignal { // We delay to give the server some time to do the auction // 0.5 may be a tad excessive, but on the whole the networking for // register / bidding is probably about 2-3 seconds, so another 0.5 // isn't gonna hurt so much. return self.pollForUpdatedSaleArtwork().then { [weak self] (_) in return self == nil ? RACSignal.empty() : self!.checkForMaxBid() } } func finishUp() { self.spinner.hidden = true if let topBidderID = mostRecentSaleArtwork?.saleHighestBid?.id { for position in bidderPositions! { if position.highestBid?.id == topBidderID { foundHighestBidder = true } } } if (foundHighestBidder) { isHighestBidder() } else { isLowestBidder() } // Update the bid details sale artwork to our mostRecentSaleArtwork if let mostRecentSaleArtwork = self.mostRecentSaleArtwork { let bidDetails = self.fulfillmentNav().bidDetails bidDetails.saleArtwork?.updateWithValues(mostRecentSaleArtwork) } let showBidderDetails = hasCreatedAUser() || !foundHighestBidder let delayTime = foundHighestBidder ? 3.0 : 7.0 if showBidderDetails { delayToMainThread(delayTime) { self.performSegue(.PushtoBidConfirmed) } } else { backToAuctionButton.hidden = false } } func hasCreatedAUser() -> Bool { return registerNetworkModel != nil } func isHighestBidder() { titleLabel.text = "Bid Confirmed" bidConfirmationImageView.image = UIImage(named: "BidHighestBidder") } func isLowestBidder() { titleLabel.text = "Higher bid needed" titleLabel.textColor = UIColor.artsyRed() outbidNoticeLabel.hidden = false bidConfirmationImageView.image = UIImage(named: "BidNotHighestBidder") } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue == .PushtoBidConfirmed { let registrationConfirmationVC = segue.destinationViewController as YourBiddingDetailsViewController registrationConfirmationVC.titleText = titleLabel.text registrationConfirmationVC.titleColor = titleLabel.textColor registrationConfirmationVC.confirmationImage = bidConfirmationImageView.image let highestBidCopy = "You will be asked for your Bidder Number and PIN next time you bid instead of entering all your information." let notHighestBidderCopy = "Use your Bidder Number and PIN next time you bid." registrationConfirmationVC.bodyCopy = foundHighestBidder ? highestBidCopy : notHighestBidderCopy } } func pollForUpdatedSaleArtwork() -> RACSignal { func getUpdatedSaleArtwork() -> RACSignal { let nav = self.fulfillmentNav() let artworkID = nav.bidDetails.saleArtwork!.artwork.id; let endpoint: ArtsyAPI = ArtsyAPI.AuctionInfoForArtwork(auctionID: nav.auctionID, artworkID: artworkID) return nav.loggedInProvider!.request(endpoint, method: .GET, parameters:endpoint.defaultParameters).filterSuccessfulStatusCodes().mapJSON().mapToObject(SaleArtwork.self) } let beginningBidCents = self.fulfillmentNav().bidDetails.saleArtwork?.saleHighestBid?.amountCents ?? 0 let updatedSaleArtworkSignal = getUpdatedSaleArtwork().flattenMap { [weak self] (saleObject) -> RACStream! in self?.pollRequests++ println("Polling \(self?.pollRequests) of \(self?.maxPollRequests) for updated sale artwork") let saleArtwork = saleObject as? SaleArtwork let updatedBidCents = saleArtwork?.saleHighestBid?.amountCents ?? 0 // TODO: handle the case where the user was already the highest bidder if updatedBidCents != beginningBidCents { // This is an updated model – hooray! self?.mostRecentSaleArtwork = saleArtwork return RACSignal.empty() } else { if (self?.pollRequests ?? 0) >= (self?.maxPollRequests ?? 0) { // We have exceeded our max number of polls, fail. return RACSignal.error(nil) } else { // We didn't get an updated value, so let's try again. return RACSignal.empty().delay(self?.pollInterval ?? 1).then({ () -> RACSignal! in return self?.pollForUpdatedSaleArtwork() }) } } } return RACSignal.empty().delay(pollInterval).then { updatedSaleArtworkSignal } } func getMyBidderPositions() -> RACSignal { let nav = self.fulfillmentNav() let artworkID = nav.bidDetails.saleArtwork!.artwork.id; let endpoint: ArtsyAPI = ArtsyAPI.MyBidPositionsForAuctionArtwork(auctionID: nav.auctionID, artworkID: artworkID) return nav.loggedInProvider!.request(endpoint, method: .GET, parameters:endpoint.defaultParameters).filterSuccessfulStatusCodes().mapJSON().mapToObjectArray(BidderPosition.self) } @IBAction func backToAuctionTapped(sender: AnyObject) { fulfillmentContainer()?.closeFulfillmentModal() } }
mit
de018d5b415af4bca367883a973519be
39.492462
185
0.636262
5.433581
false
false
false
false
alexfish/stylize
Stylize.playground/section-1.swift
1
395
// Playground - noun: a place where people can play import Stylize let foregroundStyle = Stylize.foreground(UIColor.red) let kernStyle = Stylize.kern(5) let style = Stylize.compose(foregroundStyle, kernStyle) let label = UILabel(frame: CGRect(x: 0, y: 0, width: 400, height: 50)) let string = NSAttributedString(string: "Hello World") label.attributedText = style(string)
mit
48ee1d63adee588a2a6de7f792b27ef9
31.916667
72
0.721519
3.526786
false
false
false
false
mitochrome/complex-gestures-demo
apps/GestureRecognizer/Carthage/Checkouts/RxSwift/Tests/RxCocoaTests/NSView+RxTests.swift
20
1100
// // NSView+RxTests.swift // Tests // // Created by Krunoslav Zaher on 12/6/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift import RxCocoa import Cocoa import XCTest final class NSViewTests : RxTest { } extension NSViewTests { func testHidden_True() { let subject = NSView(frame: CGRect.zero) Observable.just(true).subscribe(subject.rx.isHidden).dispose() XCTAssertTrue(subject.isHidden == true) } func testHidden_False() { let subject = NSView(frame: CGRect.zero) Observable.just(false).subscribe(subject.rx.isHidden).dispose() XCTAssertTrue(subject.isHidden == false) } } extension NSViewTests { func testAlpha_0() { let subject = NSView(frame: CGRect.zero) Observable.just(0).subscribe(subject.rx.alpha).dispose() XCTAssertTrue(subject.alphaValue == 0.0) } func testAlpha_1() { let subject = NSView(frame: CGRect.zero) Observable.just(1).subscribe(subject.rx.alpha).dispose() XCTAssertTrue(subject.alphaValue == 1.0) } }
mit
2e45c367c48d3ccf92bba133a43700a5
22.382979
71
0.658781
3.967509
false
true
false
false
dn-m/Collections
Collections/SortedDictionary.swift
1
4768
// // SortedDictionary.swift // Collections // // Created by James Bean on 12/23/16. // // /// Ordered dictionary which has sorted `keys`. public struct SortedDictionary<Key, Value>: DictionaryProtocol where Key: Hashable & Comparable { /// Backing dictionary. /// // FIXME: Make `private` in Swift 4 internal var unsorted: [Key: Value] = [:] // MARK: - Instance Properties /// Values contained herein, in order sorted by their associated keys. public var values: LazyMapRandomAccessCollection<SortedArray<Key>,Value> { return keys.lazy.map { self.unsorted[$0]! } } /// Sorted keys. public var keys: SortedArray<Key> = [] // MARK: - Initializers /// Create an empty `SortedOrderedDictionary`. public init() { } // MARK: - Subscripts /// - returns: Value for the given `key`, if available. Otherwise, `nil`. public subscript(key: Key) -> Value? { get { return unsorted[key] } set { guard let newValue = newValue else { unsorted.removeValue(forKey: key) keys.remove(key) return } let oldValue = unsorted.updateValue(newValue, forKey: key) if oldValue == nil { keys.insert(key) } } } // MARK: - Instance Methods /// Insert the given `value` for the given `key`. Order will be maintained. public mutating func insert(_ value: Value, key: Key) { keys.insert(key) unsorted[key] = value } /// Insert the contents of another `SortedDictionary` value. public mutating func insertContents(of sortedDictionary: SortedDictionary<Key, Value>) { sortedDictionary.forEach { insert($0.1, key: $0.0) } } /// - returns: Value at the given `index`, if present. Otherwise, `nil`. public func value(at index: Int) -> Value? { if index >= keys.count { return nil } return unsorted[keys[index]] } } extension SortedDictionary: Collection { // MARK: - `Collection` /// Index after the given `index`. public func index(after index: Int) -> Int { assert(index < endIndex, "Cannot decrement index to \(index - 1)") return index + 1 } /// Start index. public var startIndex: Int { return 0 } /// End index. public var endIndex: Int { return keys.count } /// Count. public var count: Int { return keys.count } } extension SortedDictionary: BidirectionalCollection { /// Index before the given `index`. public func index(before index: Int) -> Int { assert(index > 0, "Cannot decrement index to \(index - 1)") return index - 1 } } extension SortedDictionary: RandomAccessCollection { /// - Returns: Element at the given `index`. public subscript (index: Int) -> (Key, Value) { let key = keys[index] let value = unsorted[key]! return (key, value) } } extension SortedDictionary { public func min() -> (Key,Value)? { guard let firstKey = keys.first else { return nil } return (firstKey, unsorted[firstKey]!) } public func max() -> (Key,Value)? { guard let lastKey = keys.last else { return nil } return (lastKey, unsorted[lastKey]!) } public func sorted() -> [(Key,Value)] { return Array(self) } } extension SortedDictionary: ExpressibleByDictionaryLiteral { // MARK: - `ExpressibleByDictionaryLiteral` /// Create a `SortedDictionary` with a `DictionaryLiteral`. public init(dictionaryLiteral elements: (Key, Value)...) { self.init() elements.forEach { (k, v) in insert(v, key: k) } } } /// - returns: `true` if all values contained in both `SortedDictionary` values are /// equivalent. Otherwise, `false`. public func == <K, V: Equatable> (lhs: SortedDictionary<K,V>, rhs: SortedDictionary<K,V>) -> Bool { guard lhs.keys == rhs.keys else { return false } for key in lhs.keys { if rhs.unsorted[key] == nil || rhs.unsorted[key]! != lhs.unsorted[key]! { return false } } for key in rhs.keys { if lhs.unsorted[key] == nil || lhs.unsorted[key]! != rhs.unsorted[key]! { return false } } return true } /// - returns: `SortedOrderedDictionary` with values of two `SortedOrderedDictionary` values. public func + <Value, Key> ( lhs: SortedDictionary<Value, Key>, rhs: SortedDictionary<Value, Key> ) -> SortedDictionary<Value, Key> where Key: Hashable, Key: Comparable { var result = lhs rhs.forEach { result.insert($0.1, key: $0.0) } return result }
mit
7f0cf417323527b280f6866a48965cea
24.094737
97
0.594589
4.238222
false
false
false
false
PJayRushton/iOS-CollectionView-Demo
InterestsCollectionViewDemo/JSON+Extras.swift
1
4629
import Foundation public struct JSONParser { public static func JSONObjectWithData(data:NSData) throws -> JSONObject { let obj:Any = try NSJSONSerialization.JSONObjectWithData(data, options: []) return try JSONObject.JSONValue(obj) } public static func JSONObjectArrayWithData(data:NSData) throws -> [JSONObject] { let object:AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: []) guard let ra = object as? [JSONObject] else { throw JSONError.TypeMismatch(expected: [JSONObject].self, actual: object.dynamicType) } return ra } private init() { } // No need to instatiate one of these. } public protocol JSONCollectionType { func jsonData() throws -> NSData } extension JSONCollectionType { public func jsonData() throws -> NSData { guard let jsonCollection = self as? AnyObject else { throw JSONError.TypeMismatchWithKey(key:"", expected: AnyObject.self, actual: self.dynamicType) // shouldn't happen } return try NSJSONSerialization.dataWithJSONObject(jsonCollection, options: []) } } public protocol JSONObjectConvertible : JSONValueType { typealias ConvertibleType = Self init(json:JSONObject) throws } extension JSONObjectConvertible { public static func JSONValue(object: Any) throws -> ConvertibleType { guard let json = object as? JSONObject else { throw JSONError.TypeMismatch(expected: JSONObject.self, actual: object.dynamicType) } guard let value = try self.init(json: json) as? ConvertibleType else { throw JSONError.TypeMismatch(expected: ConvertibleType.self, actual: object.dynamicType) } return value } } extension Dictionary : JSONCollectionType {} extension Array : JSONCollectionType {} public typealias JSONObjectArray = [JSONObject] extension NSDate : JSONValueType { public static func JSONValue(object: Any) throws -> NSDate { guard let dateString = object as? String else { throw JSONError.TypeMismatch(expected: String.self, actual: object.dynamicType) } guard let date = NSDate.fromISO8601String(dateString) else { throw JSONError.TypeMismatch(expected: "ISO8601 date string", actual: dateString) } return date } } public extension NSDate { static private let ISO8601MillisecondFormatter:NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; let tz = NSTimeZone(abbreviation:"GMT") formatter.timeZone = tz return formatter }() static private let ISO8601SecondFormatter:NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"; let tz = NSTimeZone(abbreviation:"GMT") formatter.timeZone = tz return formatter }() static private let formatters = [ISO8601MillisecondFormatter, ISO8601SecondFormatter] static func fromISO8601String(dateString:String) -> NSDate? { for formatter in formatters { if let date = formatter.dateFromString(dateString) { return date } } return .None } } infix operator <| { associativity left precedence 150 } public func <| <A: JSONValueType>(dictionary: JSONObject, key: String) throws -> A { return try dictionary.JSONValueForKey(key) } public func <| <A: JSONValueType>(dictionary: JSONObject, key: String) throws -> A? { return try dictionary.JSONValueForKey(key) } public func <| <A: JSONValueType>(dictionary: JSONObject, key: String) throws -> [A] { return try dictionary.JSONValueForKey(key) } public func <| <A: JSONValueType>(dictionary: JSONObject, key: String) throws -> [A]? { return try dictionary.JSONValueForKey(key) } public func <| <A: RawRepresentable where A.RawValue: JSONValueType>(dictionary: JSONObject, key: String) throws -> A { return try dictionary.JSONValueForKey(key) } public func <| <A: RawRepresentable where A.RawValue: JSONValueType>(dictionary: JSONObject, key: String) throws -> A? { return try dictionary.JSONValueForKey(key) } public func <| <A: RawRepresentable where A.RawValue: JSONValueType>(dictionary: JSONObject, key: String) throws -> [A] { return try dictionary.JSONValueForKey(key) } public func <| <A: RawRepresentable where A.RawValue: JSONValueType>(dictionary: JSONObject, key: String) throws -> [A]? { return try dictionary.JSONValueForKey(key) }
mit
176db6321eef458bccd65d0f3835abfc
36.634146
127
0.683517
4.737973
false
false
false
false
gyro-n/PaymentsIos
GyronPayments/Classes/UI/CardViewController.swift
1
11336
// // CardViewController.swift // Pods // // Created by David Ye on 2017/07/21. // Copyright © 2016 gyron. All rights reserved. // // import UIKit import PromiseKit public protocol CardViewControllerDelegate: class { func created(card: SimpleTransactionToken) func createError(error: Error) } open class CardViewController: UIViewController, UITextFieldDelegate { var sdkOptions: Options? var sdk: SDK? var customerId: String? var isDummy: Bool? var cardNumber: String? var cardBrand: String? public weak var delegate: CardViewControllerDelegate? public var customTitle: String? @IBOutlet weak var cardNumberTextField: UITextField? @IBOutlet weak var expiryMonthTextField: UITextField? @IBOutlet weak var expiryYearTextField: UITextField? @IBOutlet weak var cvvTextField: UITextField? @IBOutlet weak var cardHolderNameTextField: UITextField? @IBOutlet weak var nicknameTextField: UITextField? @IBOutlet weak var activityIndicator: UIActivityIndicatorView? @IBOutlet weak var cardImage: UIImageView? @IBOutlet weak var navigationBar: UINavigationBar? @IBOutlet weak var emailTextField: UITextField? @IBAction func handleBarButtonCancelClick(_ sender: UIBarButtonItem) { self.dismiss(animated: true, completion: nil) } @IBAction func handleDoneClick(_ sender: UIBarButtonItem) { /*self.showActivityIndicator(isShown: true) let cardData = TransactionTokenCardRequestData(cardholder: self.cardHolderNameTextField!.text!, cardNumber: self.cardNumberTextField!.text!, expMonth: self.expiryMonthTextField!.text!, expYear: self.expiryYearTextField!.text!, cvv: self.cvvTextField!.text!) let data = CardCreateRequestData(cardData: cardData, name: self.nicknameTextField!.text!) let clientId = self.clientId ?? UUID().uuidString self.sdk?.cardResource?.create(clientId: clientId, data: data, callback: nil).then(execute: { c -> Void in self.delegate?.created(card: c) self.showActivityIndicator(isShown: false) self.dismiss(animated: true, completion: nil) }).catch(execute: { e in self.delegate?.createError(error: e) print(e.localizedDescription) let f = e as! WrappedError switch (f) { case .ResponseError(let d): self.showAlert(title: "Card Creation Processing Error", message: ErrorUtils.convertErrorArrayToString(values: d.errors)) } self.showActivityIndicator(isShown: false) })*/ let cardNumber = self.cardNumberTextField!.text! if (self.isDummy ?? false) { self.delegate?.created(card: SimpleTransactionToken(id: UUID().uuidString, type: TransactionTokenType.recurring, cardholder: self.cardHolderNameTextField!.text!, expMonth: Int(self.expiryMonthTextField!.text!)!, expYear: Int(self.expiryYearTextField!.text!)!, lastFour: cardNumber.substring(from: cardNumber.index(cardNumber.endIndex, offsetBy: -4)), brand: self.cardBrand ?? "visa")) self.dismiss(animated: true, completion: nil) self.navigationController?.popViewController(animated: true) } else { let type: TransactionTokenType = TransactionTokenType.recurring let usageLimit: String = transactionTokenTypeList[2].first!.value let cardData = TransactionTokenCardRequestData(cardholder: self.cardHolderNameTextField!.text!, cardNumber: self.cardNumberTextField!.text!, expMonth: self.expiryMonthTextField!.text!, expYear: self.expiryYearTextField!.text!, cvv: self.cvvTextField!.text!) let requestData = TransactionTokenCreateRequestData(paymentType: "card", email: self.emailTextField!.text!, type: type, usageLimit: usageLimit, data: cardData) self.createTransactionToken(createParams: requestData).then(execute: { t -> Void in let cd = t.data as! TransactionTokenCardData let simpleToken = SimpleTransactionToken(id: t.id, type: t.type, cardholder: cd.cardholder, expMonth: cd.expMonth, expYear: cd.expYear, lastFour: cd.lastFour, brand: cd.brand) self.delegate?.created(card: simpleToken) self.showActivityIndicator(isShown: false) self.dismiss(animated: true, completion: nil) }).catch(execute: { e in self.delegate?.createError(error: e) print(e.localizedDescription) let f = e as! WrappedError switch (f) { case .ResponseError(let d): self.showAlert(title: "Transaction Token Processing Error", message: ErrorUtils.convertErrorArrayToString(values: d.errors)) } self.showActivityIndicator(isShown: false) }) } } @IBAction func cardNumberChanged(_ sender: UITextField) { self.setCardStateAndImage() } func getCardImage(forState cardState: CardState) -> UIImage? { switch cardState { case .identified(let cardType): switch cardType { case .amex: return UIImage(named: "amex", in: self.getBundle(), compatibleWith: nil) case .diners: return UIImage(named: "diners_club", in: self.getBundle(), compatibleWith: nil) case .discover: return UIImage(named: "discover", in: self.getBundle(), compatibleWith: nil) case .jcb: return UIImage(named: "jcb", in: self.getBundle(), compatibleWith: nil) case .masterCard: return UIImage(named: "mastercard", in: self.getBundle(), compatibleWith: nil) case .unionPay: return UIImage(named: "union_pay", in: self.getBundle(), compatibleWith: nil) case .visa: return UIImage(named: "visa", in: self.getBundle(), compatibleWith: nil) } case .indeterminate: return UIImage(named: "credit_card", in: self.getBundle(), compatibleWith: nil) case .invalid: return UIImage(named: "credit_card", in: self.getBundle(), compatibleWith: nil) } } func getCardBrand(forState cardState: CardState) -> String? { switch cardState { case .identified(let cardType): switch cardType { case .amex: return "amex" case .diners: return "diners" case .discover: return "discover" case .jcb: return "jcb" case .masterCard: return "master_card" case .unionPay: return "union_pay" case .visa: return "visa" } case .indeterminate: return "unknown" case .invalid: return nil } } override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.customTitle = "Other Card Details" } convenience public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, sdkOptions: Options, customerId: String, customTitle: String?, isDummy: Bool?, cardNumber: String?) { self.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.sdkOptions = sdkOptions self.sdk = SDK(options: sdkOptions) self.customerId = customerId self.isDummy = isDummy if let ct = customTitle { self.customTitle = ct } self.cardNumber = cardNumber } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // self.navigationBar!.topItem?.title = self.customTitle self.cardImage!.image = UIImage(named: "credit_card", in: self.getBundle(), compatibleWith: nil) self.cardNumberTextField?.returnKeyType = UIReturnKeyType.done self.cardHolderNameTextField?.returnKeyType = UIReturnKeyType.done self.expiryMonthTextField?.returnKeyType = UIReturnKeyType.done self.expiryYearTextField?.returnKeyType = UIReturnKeyType.done self.cvvTextField?.returnKeyType = UIReturnKeyType.done // Load the card number if any self.cardNumberTextField?.text = self.cardNumber self.setCardStateAndImage() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationBar?.isHidden = false self.navigationBar?.topItem?.title = self.customTitle self.title = self.customTitle self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(handleDoneClick)) } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) //This will hide the keyboard } public func textFieldDidEndEditing(_ textField: UITextField) { textField.resignFirstResponder() } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func showAlert(title: String, message: String) -> Void { let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alertController, animated: true, completion: nil) } func showActivityIndicator(isShown: Bool) -> Void { if (isShown) { activityIndicator?.startAnimating() } else { activityIndicator?.stopAnimating() } } func getBundle() -> Bundle? { let bundleURL = self.nibBundle!.resourceURL?.appendingPathComponent(bundleName) return Bundle(url: bundleURL!) } func createTransactionToken(createParams: TransactionTokenCreateRequestData) -> Promise<TransactionToken> { return self.sdk!.transactionTokenResource!.create(data: createParams, callback: nil) } func setCardStateAndImage() -> Void { let cs = CardState(fromPrefix: self.cardNumberTextField!.text!) self.cardBrand = getCardBrand(forState: cs) self.cardImage!.image = self.getCardImage(forState: cs) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
a6c540a0f043f2a0eef7d807f9a770df
41.773585
396
0.644376
5.128959
false
false
false
false
xivol/MCS-V3-Mobile
examples/uiKit/UIKitCatalog.playground/Pages/UILabel.xcplaygroundpage/Contents.swift
1
924
//: # UILabel //: A view that displays one or more lines of read-only text, often used in conjunction with controls to describe their intended purpose. //: //: [UILabel API Reference](https://developer.apple.com/reference/uikit/uilabel) import UIKit import PlaygroundSupport let label = UILabel(frame: CGRect(x: 0, y: 0, width: 250, height: 250)) label.backgroundColor = #colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 1) label.text = "Hello Label!" label.textColor = #colorLiteral(red: 0.9686274529, green: 0.78039217, blue: 0.3450980484, alpha: 1) label.shadowColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) label.textAlignment = .center label.font = UIFont(name: "AmericanTypewriter", size: 32) // for other font family names visit http://iosfonts.com/ PlaygroundPage.current.liveView = label //: [Previous](@previous) | [Table of Contents](TableOfContents) | [Next](@next)
mit
462c888ad3e7d5459e51faf547c0b82c
47.631579
137
0.739177
3.513308
false
false
false
false
debugsquad/Hyperborea
Hyperborea/View/Favorites/VFavoritesCell.swift
1
2830
import UIKit class VFavoritesCell:UICollectionViewCell { private weak var label:UILabel! private weak var imageView:UIImageView! private let kLabelRight:CGFloat = -10 private let kImageWidth:CGFloat = 32 override init(frame:CGRect) { super.init(frame:frame) clipsToBounds = true let label:UILabel = UILabel() label.isUserInteractionEnabled = false label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = UIColor.clear label.font = UIFont.bold(size:17) label.numberOfLines = 2 self.label = label let imageView:UIImageView = UIImageView() imageView.isUserInteractionEnabled = false imageView.translatesAutoresizingMaskIntoConstraints = false imageView.clipsToBounds = true imageView.contentMode = UIViewContentMode.center self.imageView = imageView addSubview(label) addSubview(imageView) NSLayoutConstraint.equalsVertical( view:imageView, toView:self) NSLayoutConstraint.leftToLeft( view:imageView, toView:self) NSLayoutConstraint.width( view:imageView, constant:kImageWidth) NSLayoutConstraint.equalsVertical( view:label, toView:self) NSLayoutConstraint.leftToRight( view:label, toView:imageView) NSLayoutConstraint.rightToRight( view:label, toView:self, constant:kLabelRight) } required init?(coder:NSCoder) { return nil } override var isSelected:Bool { didSet { hover() } } override var isHighlighted:Bool { didSet { hover() } } //MARK: private private func hover() { if isSelected { backgroundColor = UIColor.hyperBlue label.textColor = UIColor.white } else { backgroundColor = UIColor.white label.textColor = UIColor.black } } private func loadSquare(languageRaw:Int16) { let language:MLanguage = MLanguage.language(rawValue:languageRaw) DispatchQueue.main.async { [weak self] in self?.imageView.image = language.imageSquare } } //MARK: public func config(model:MFavoritesItem) { label.text = model.word hover() DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.loadSquare(languageRaw:model.languageRaw) } } }
mit
463e05845971c00e1d264dfa503ed094
23.396552
73
0.566431
5.592885
false
false
false
false
inket/stts
stts/ServiceTableView/StatusTableCell.swift
1
4373
// // StatusTableCell.swift // stts // import Cocoa class StatusTableCell: NSTableCellView { let statusIndicator = StatusIndicator() let stackView = NSStackView() let titleField = NSTextField() let statusField = NSTextField() enum Layout { static let verticalPadding: CGFloat = 10 static let verticalSpacing: CGFloat = 4 static let horizontalPadding: CGFloat = 8 static let horizontalSpacing: CGFloat = 8 static let titleFont = NSFont.systemFont(ofSize: 13) static let messageFont = NSFontManager.shared.font( withFamily: titleFont.fontName, traits: NSFontTraitMask.italicFontMask, weight: 5, size: 11 ) static let statusIndicatorSize = CGSize(width: 14, height: 14) private static let dummyCell = StatusTableCell(frame: .zero) static func heightOfRow(for service: Service, width: CGFloat) -> CGFloat { let nsScrollerWidth: CGFloat = 16 let realRowWidth = width - (nsScrollerWidth - 4) // 4 by trial & error dummyCell.frame.size = CGSize(width: realRowWidth, height: 400) dummyCell.setup(with: service) dummyCell.layoutSubtreeIfNeeded() return dummyCell.stackView.frame.size.height + (verticalPadding * 2) } } override init(frame frameRect: NSRect) { super.init(frame: frameRect) commonInit() } required init?(coder: NSCoder) { super.init(coder: coder) commonInit() } private func commonInit() { textField?.removeFromSuperview() statusIndicator.scaleUnitSquare(to: NSSize(width: 0.3, height: 0.3)) statusIndicator.translatesAutoresizingMaskIntoConstraints = false addSubview(statusIndicator) stackView.orientation = .vertical stackView.distribution = .fill stackView.alignment = .leading stackView.spacing = Layout.verticalSpacing stackView.translatesAutoresizingMaskIntoConstraints = false addSubview(stackView) titleField.isEditable = false titleField.isBordered = false titleField.isSelectable = false titleField.maximumNumberOfLines = 2 titleField.cell!.truncatesLastVisibleLine = true titleField.cell!.lineBreakMode = .byWordWrapping titleField.cell!.wraps = true titleField.font = Layout.titleFont titleField.textColor = NSColor.labelColor titleField.backgroundColor = NSColor.clear statusField.isEditable = false statusField.isBordered = false statusField.isSelectable = false statusField.font = Layout.messageFont statusField.textColor = NSColor.secondaryLabelColor statusField.maximumNumberOfLines = 6 statusField.cell!.truncatesLastVisibleLine = true statusField.cell!.lineBreakMode = .byWordWrapping statusField.cell!.wraps = true statusField.backgroundColor = NSColor.clear [titleField, statusField].forEach { stackView.addArrangedSubview($0) } NSLayoutConstraint.activate([ statusIndicator.heightAnchor.constraint(equalToConstant: Layout.statusIndicatorSize.height), statusIndicator.widthAnchor.constraint(equalToConstant: Layout.statusIndicatorSize.height), statusIndicator.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Layout.horizontalPadding), statusIndicator.centerYAnchor.constraint(equalTo: centerYAnchor), stackView.leadingAnchor.constraint( equalTo: statusIndicator.trailingAnchor, constant: Layout.horizontalSpacing ), stackView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -Layout.horizontalPadding), stackView.topAnchor.constraint(equalTo: topAnchor, constant: Layout.verticalPadding), stackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -Layout.verticalPadding) ]) } func setup(with service: Service) { titleField.stringValue = service.name statusIndicator.status = service.status statusField.stringValue = service.message statusField.isHidden = service.status == .good && Preferences.shared.hideServiceDetailsIfAvailable } }
mit
3264d9d46ee9bc9a24612bb6643e39b3
35.747899
113
0.676424
5.60641
false
false
false
false
proversity-org/edx-app-ios
Source/CourseGenericBlockTableViewCell.swift
1
2817
// // CourseHTMLTableViewCell.swift // edX // // Created by Ehmad Zubair Chughtai on 14/05/2015. // Copyright (c) 2015 edX. All rights reserved. // import UIKit class CourseGenericBlockTableViewCell : UITableViewCell, CourseBlockContainerCell { fileprivate let content = CourseOutlineItemView() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(content) content.snp.makeConstraints { make in make.edges.equalTo(contentView) } } var block : CourseBlock? = nil { didSet { content.setTitleText(title: block?.displayName) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class CourseHTMLTableViewCell: CourseGenericBlockTableViewCell { static let identifier = "CourseHTMLTableViewCellIdentifier" override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style : style, reuseIdentifier : reuseIdentifier) content.setContentIcon(icon: Icon.CourseHTMLContent) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class CourseProblemTableViewCell : CourseGenericBlockTableViewCell { static let identifier = "CourseProblemTableViewCellIdentifier" override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style : style, reuseIdentifier : reuseIdentifier) content.setContentIcon(icon: Icon.CourseProblemContent) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class CourseUnknownTableViewCell: CourseGenericBlockTableViewCell { static let identifier = "CourseUnknownTableViewCellIdentifier" override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) content.leadingIconColor = OEXStyles.shared().neutralBase() content.setContentIcon(icon: Icon.CourseUnknownContent) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class DiscussionTableViewCell: CourseGenericBlockTableViewCell { static let identifier = "DiscussionTableViewCellIdentifier" override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) content.setContentIcon(icon: Icon.Discussions) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
62f20a449b952060abc6691729b428ab
29.956044
83
0.70607
5.131148
false
false
false
false
debugsquad/Hyperborea
Hyperborea/View/Settings/VSettingsCellReview.swift
1
1822
import UIKit class VSettingsCellReview:VSettingsCell { private let kTitleLeft:CGFloat = 10 private let kTitleWidth:CGFloat = 250 private let kImageWidth:CGFloat = 100 override init(frame:CGRect) { super.init(frame:frame) let labelTitle:UILabel = UILabel() labelTitle.isUserInteractionEnabled = false labelTitle.translatesAutoresizingMaskIntoConstraints = false labelTitle.backgroundColor = UIColor.clear labelTitle.font = UIFont.bolder(size:15) labelTitle.textColor = UIColor.white labelTitle.numberOfLines = 2 labelTitle.text = NSLocalizedString("VSettingsCellReview_labelTitle", comment:"") let imageView:UIImageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.clipsToBounds = true imageView.contentMode = UIViewContentMode.center imageView.isUserInteractionEnabled = false imageView.image = #imageLiteral(resourceName: "assetGenericReview") addSubview(labelTitle) addSubview(imageView) NSLayoutConstraint.equalsVertical( view:labelTitle, toView:self) NSLayoutConstraint.leftToLeft( view:labelTitle, toView:self, constant:kTitleLeft) NSLayoutConstraint.width( view:labelTitle, constant:kTitleWidth) NSLayoutConstraint.equalsVertical( view:imageView, toView:self) NSLayoutConstraint.rightToRight( view:imageView, toView:self) NSLayoutConstraint.width( view:imageView, constant:kImageWidth) } required init?(coder:NSCoder) { return nil } }
mit
be7be6a71d21828f54bbb76bdfb08420
30.413793
89
0.63831
5.954248
false
false
false
false
gkaimakas/SwiftyForms
SwiftyForms/Classes/Inputs/LocationInput.swift
1
2328
// // LocationInput.swift // Pods // // Created by Γιώργος Καϊμακάς on 29/06/16. // // import Foundation public typealias LocationInputEvent = (LocationInput) -> Void open class LocationInput: Input { open static let Latitude = "latitude" open static let Longitude = "longitude" fileprivate var _previousLatitude: String? = nil fileprivate var _previousLongitude: String? = nil fileprivate var _locationEvents: [LocationInputEvent] = [] override open var data: [String : Any]? { if isValid == false { return nil } return [ attributeLatitude : latitude, attributeLongitude : longitude ] } override open var isValid: Bool { return _validate() } open var latitude: String { willSet { _previousLatitude = self.latitude } didSet { self._dirty = true for event in _locationEvents { event(self) } } } open var longitude: String { willSet { _previousLongitude = self.longitude } didSet { self._dirty = true for event in _locationEvents { event(self) } } } open var previousLatitude: String? { return _previousLatitude } open var previousLongitude: String? { return _previousLongitude } open var attributeLatitude: String = LocationInput.Latitude open var attributeLongitude: String = LocationInput.Longitude public convenience init(name: String) { self.init(name: name, enabled: true, hidden: false) } public override init(name: String, enabled: Bool, hidden: Bool) { self.latitude = "0.0" self.longitude = "0.0" super.init(name: name, enabled: enabled, hidden: hidden) } open func on(_ location: LocationInputEvent? = nil) { if let event = location { _locationEvents.append(event) } } open func setAttributeLatitude(_ name: String) -> Self { attributeLatitude = name return self } open func setAttributeLongitude(_ name: String) -> Self { attributeLongitude = name return self } fileprivate func _validate() -> Bool { let latitudeValidation = self._validationRules .map() { $0.rule } .map() { $0(latitude) } .reduce(true) { $0 && $1 } let longitudeValidation = self._validationRules .map() { $0.rule } .map() { $0(latitude) } .reduce(true) { $0 && $1 } return latitudeValidation && longitudeValidation } }
mit
3f9124caa19fd51bb9dc1a506f287cf2
18.769231
66
0.667099
3.391496
false
false
false
false
wayfair/brickkit-ios
Example/Source/Bricks/Custom/WhoToFollowBrick.swift
2
1981
// // WhoToFollow.swift // BrickKit // // Created by Yusheng Yang on 9/20/16. // Copyright © 2016 Wayfair LLC. All rights reserved. // import Foundation import BrickKit class WhoToFollowBrick: Brick { weak var dataSource: WhoToFollowBrickDataSource? init(_ identifier: String, width: BrickDimension = .ratio(ratio: 1), height: BrickDimension = .auto(estimate: .fixed(size: 50)), backgroundColor: UIColor = UIColor.clear, backgroundView: UIView? = nil, dataSource: WhoToFollowBrickDataSource) { self.dataSource = dataSource super.init(identifier, size: BrickSize(width: width, height: height), backgroundColor: backgroundColor, backgroundView: backgroundView) } } protocol WhoToFollowBrickDataSource: class { func whoToFollowImage(cell: WhoToFollowBrickCell) -> UIImage func whoToFollowTitle(cell: WhoToFollowBrickCell) -> String func whoToFollowDescription(cell: WhoToFollowBrickCell) -> String func whoToFollowAtTag(cell: WhoToFollowBrickCell) -> String } class WhoToFollowBrickCell: BrickCell, Bricklike { typealias BrickType = WhoToFollowBrick @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var followButton: UIButton! @IBOutlet weak var atTag: UILabel! override func updateContent() { super.updateContent() followButton.layer.cornerRadius = 5.0 followButton.layer.borderWidth = 1.0 followButton.layer.borderColor = self.tintColor.cgColor imageView.layer.cornerRadius = 4 imageView.clipsToBounds = true imageView.image = brick.dataSource?.whoToFollowImage(cell: self) titleLabel.text = brick.dataSource?.whoToFollowTitle(cell: self) descriptionLabel.text = brick.dataSource?.whoToFollowDescription(cell: self) atTag.text = brick.dataSource?.whoToFollowAtTag(cell: self) } }
apache-2.0
86cd05e4a047b3758a543e08db165d36
37.076923
247
0.720202
4.669811
false
false
false
false
Aioria1314/WeiBo
WeiBo/WeiBo/Classes/Views/Home/ZXCHomeToolBarView.swift
1
3307
// // ZXCHomeToolBarView.swift // WeiBo // // Created by Aioria on 2017/3/30. // Copyright © 2017年 Aioria. All rights reserved. // import UIKit class ZXCHomeToolBarView: UIView { var statusViewModel: ZXCStatusViewModel? { didSet { let retweetCountStr = statusViewModel?.retweetCountStr let commentCountStr = statusViewModel?.commentCountStr let unlikeCountStr = statusViewModel?.unlikeCountStr btnRetweet?.setTitle(retweetCountStr, for: .normal) btnComment?.setTitle(commentCountStr, for: .normal) btnUnlike?.setTitle(unlikeCountStr, for: .normal) } } var btnRetweet: UIButton? var btnComment: UIButton? var btnUnlike: UIButton? override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI() { // backgroundColor = UIColor.white btnRetweet = addChildButton(imgName: "timeline_icon_retweet", title: "转发") btnComment = addChildButton(imgName: "timeline_icon_comment", title: "评论") btnUnlike = addChildButton(imgName: "timeline_icon_unlike", title: "赞") let firstLine = addChildLineView() let secondLine = addChildLineView() btnRetweet!.snp.makeConstraints { (make) in make.top.left.bottom.equalTo(self) make.width.equalTo(btnComment!) } btnComment!.snp.makeConstraints { (make) in make.top.bottom.equalTo(self) make.left.equalTo(btnRetweet!.snp.right) make.width.equalTo(btnUnlike!) } btnUnlike!.snp.makeConstraints { (make) in make.top.bottom.equalTo(self) make.left.equalTo(btnComment!.snp.right) make.right.equalTo(self) } firstLine.snp.makeConstraints { (make) in make.centerX.equalTo(btnComment!.snp.left) make.centerY.equalTo(self) } secondLine.snp.makeConstraints { (make) in make.centerX.equalTo(btnUnlike!.snp.left) make.centerY.equalTo(self) } } fileprivate func addChildButton(imgName: String, title: String) -> UIButton { let btn = UIButton() btn.setImage(UIImage(named: imgName), for: .normal) btn.setTitle(title, for: .normal) btn.titleLabel?.font = UIFont.systemFont(ofSize: 14) btn.setBackgroundImage(UIImage(named: "timeline_card_bottom_background"), for: .normal) // btn.setBackgroundImage(UIImage(named: "timeline_card_bottom_background_highlighted"), for: .highlighted) btn.setTitleColor(UIColor.darkGray, for: .normal) addSubview(btn) return btn } fileprivate func addChildLineView() -> UIImageView { let imgView = UIImageView(image: UIImage(named: "timeline_card_bottom_line")) addSubview(imgView) return imgView } }
mit
dc14a3c8f7045c354a3fd02f1e2bf807
26.680672
114
0.578931
4.760116
false
false
false
false
TechnologySpeaks/smile-for-life
smile-for-life/TimersViewController.swift
1
2619
// // TimersViewController.swift // smile-for-life // // Created by Lisa Swanson on 2/29/16. // Copyright © 2016 Technology Speaks. All rights reserved. // import UIKit class TimersViewController: UIViewController { var timerCount: Int = 0 var timerRunning = false var timer = Timer() var countDownTimer: Int = 0 func timerRun() { var minuts: Int var seconds: Int timerRunning = true timerCount -= 1 minuts = timerCount / 60 seconds = timerCount - (minuts * 60) let formatedTime = NSString(format: "%2d:%2d", minuts, seconds) timerLabel.text = String(formatedTime) if (timerCount == 0) { timer.invalidate() timerRunning = false timerLabel.text = "00:00" timerCount = 0 flossPopUp() } } func setTimer(){ timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(TimersViewController.timerRun), userInfo: nil, repeats: true) } func flossPopUp() { let flossAlert = UIAlertController(title: "Congratulations", message: "I will update your calendar.", preferredStyle: UIAlertControllerStyle.alert) flossAlert.addAction(UIAlertAction(title: "Close", style: .default, handler: {(action) -> Void in self.dismiss(animated: true, completion: nil) })) self.present(flossAlert, animated: true, completion: nil) } @IBOutlet weak var timerLabel: UILabel! @IBAction func startBrushTimer(_ sender: AnyObject) { if timerRunning == false { timerCount = 15 setTimer() } } @IBAction func startFlossTimer(_ sender: AnyObject) { if timerRunning == false { timerCount = 180 setTimer() } } @IBAction func cancelTimers(_ sender: AnyObject) { if timerRunning == true { timer.invalidate() timerRunning = false timerLabel.text = "00:00" timerCount = 0 } } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
cc6c9734a878b392a5601150af47ffba
21.765217
151
0.624141
4.601054
false
false
false
false
cornerstonecollege/401_02
401_swift_examples/FirstPlayground.playground/Contents.swift
1
1550
var thatIsAVar:Int = 0; var thatIsMySecondVar = 2 var 🖖 = 2 var 🖖😈🖖 = 3 let 🙏🖖 = 🖖😈🖖 + 🖖 let sum = thatIsAVar + thatIsMySecondVar; if (sum > 4) { print("Hello Sreekanth and Tomoko") } else { print("Oh oh") } func printMyString() { print("That is my string") func secondString() { print("Hello") } secondString() } printMyString() func U😎U (😡: String, 😴: Bool) -> String { if 😴 { return "I am \(😡) and \(thatIsAVar)" } else { return "I am not \(😡)" } } let resultFromFunction:String = U😎U("Angry", 😴: false) print(resultFromFunction) func add(x:Float, y:Float) -> Float { return x + y; } let summation:Float = add(3, y:2) for var i in 0 ..< 3 { print("Hello \(i)") } var array = ["orange", "lime", "banana"] for var fruit in array { print(fruit) } var dictionary = ["fruit 1" : "orange", "fruit 2" : "lime", "fruit 3": "banana"] for var (key, value) in dictionary { print("The key is \(key) and the value is \(value)") } var i = 0 while i < 3 { print("While \(i)") i++ } i = 4 repeat { print("Repeat \(i)") i++ }while i < 3 let type = "My Type" switch type { case "1": print("1") case "2", "3", "4": print("2, 3 and 4") case let x where x.hasPrefix("My"): print("start with my") default: print("Default Type") } switch i { case (-2...3): print("From -2 to 3") case (3...10): print("From 3 to 10") default: print("Non computable value") }
gpl-2.0
1ba5c7be7c8747f8155d0137a6512673
13.676471
80
0.548797
2.780669
false
false
false
false
miradesne/gamepoll
gamepoll/Constants.swift
1
538
// // Constants.swift // gamepoll // // Created by Mohd Irtefa on 1/24/16. // Copyright © 2016 gamepollstudio. All rights reserved. // import Foundation struct Constants { static let QUESTION = "Question" static let QUESTION_TYPE = "QuestionType" static let QUESTION_CHOICES = "Choices" static let QUESTION_IMAGE_URL = "ImageUrl" struct Parse { static let APPLICATION_ID = "g7e0UmhRuHrLSeEhghy6qz3pMKNLyLRURFpH02te" static let CLIENT_KEY = "Wa00hS7omwVkGUk9rvMKrRHSgmUjj1ncm9ROuc4P" } }
mit
573aef8556e9bc3b74dee03efb4060c2
24.619048
78
0.700186
3.068571
false
false
false
false
skonmeme/Reservation
Reservation/NewBranchViewController.swift
1
6050
// // NewBranchViewController.swift // Reservation // // Created by Sung Gon Yi on 26/12/2016. // Copyright © 2016 skon. All rights reserved. // import UIKit import CoreData protocol AddressViewControllerDelegate { func addressSearched(_ addressViewController: AddressViewController, address: String) } class NewBranchViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, AddressViewControllerDelegate { @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var phoneTextField: UITextField! @IBOutlet weak var addressTextField: UITextField! @IBOutlet weak var photoView: UIImageView! @IBOutlet weak var saveButton: UIBarButtonItem! @IBOutlet weak var searchAddressButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.nameTextField.becomeFirstResponder() } override func viewWillAppear(_ animated: Bool) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ func activateSaveWhenAllTextFieldFilled() { guard let name = self.nameTextField.text, let phone = self.phoneTextField.text, let address = self.addressTextField.text else { self.saveButton.isEnabled = false return } if name != "" && phone != "" && address != "" { self.saveButton.isEnabled = true } else { self.saveButton.isEnabled = false } } @IBAction func searchAddress(_ sender: Any) { } @IBAction func photoTapped(_ sender: Any) { let imagePicker = UIImagePickerController() imagePicker.delegate = self self.present(imagePicker, animated: true) } @IBAction func cancel(_ sender: Any) { self.dismiss(animated: true) } @IBAction func addBranch(_ sender: Any) { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } let managedContext = appDelegate.persistentContainer.viewContext let entity = NSEntityDescription.entity(forEntityName: "Branch", in: managedContext) let branch = NSManagedObject(entity: entity!, insertInto: managedContext) branch.setValue(self.nameTextField.text, forKey: "name") branch.setValue(self.phoneTextField.text, forKey: "phone") branch.setValue(self.addressTextField.text, forKey: "address") if let image = self.photoView.image, let imageData = UIImagePNGRepresentation(image) { var photoName: String var photoURL: URL let photoDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] repeat { photoName = UUID().uuidString + ".png" photoURL = photoDirectory.appendingPathComponent(photoName) } while (FileManager.default.fileExists(atPath: photoURL.path)) FileManager.default.createFile(atPath: photoURL.path, contents: imageData, attributes: nil) branch.setValue(photoName, forKey: "photo") } do { try managedContext.save() self.dismiss(animated: true) } catch let error as NSError { print("Could not save. \(error), \(error.userInfo)") let alertController = UIAlertController(title: "Could not save.", message: "\(error), \(error.userInfo)", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default)) self.present(alertController, animated: true) } } // ImagePicker Delegate func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { self.photoView.image = info["UIImagePickerControllerOriginalImage"] as! UIImage? self.dismiss(animated: true) } // TextField Delegate func textFieldDidBeginEditing(_ textField: UITextField) { if textField.tag == 2000 { self.searchAddressButton.isHidden = false } } func textFieldDidEndEditing(_ textField: UITextField) { if textField.tag == 2000 { self.searchAddressButton.isHidden = true } self.activateSaveWhenAllTextFieldFilled() } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard var text = textField.text else { return false } if let range = text.range(from: range) { text = text.replacingCharacters(in: range, with: string) textField.text = text } self.activateSaveWhenAllTextFieldFilled() return false } // AddressView Delegate func addressSearched(_ addressViewController: AddressViewController, address: String) { self.addressTextField.text = address self.activateSaveWhenAllTextFieldFilled() } // Segue override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let naviagationController = segue.destination as! UINavigationController let destinationViewController = naviagationController.viewControllers.first as! AddressViewController if let address = self.addressTextField.text { destinationViewController.address = address destinationViewController.delegate = self } } }
mit
a3b2161cdbb6cd0449420d6bc6295a0d
35.884146
166
0.655976
5.381673
false
false
false
false
mcberros/VirtualTourist
VirtualTourist/FlickrApiConveniences.swift
1
4634
// // FlickrApiConveniences.swift // VirtualTourist // // Created by Carmen Berros on 10/07/16. // Copyright © 2016 mcberros. All rights reserved. // import Foundation import UIKit extension FlickrApiClient { func getImageFromFlickrBySearch(boundingBoxString: String, completionHandler: (success: Bool, photosArray: [[String: AnyObject]],errorString: String?) -> Void) { let session = NSURLSession.sharedSession() let methodArguments = [ "method": FlickrApiClient.Methods.SearchPhotos, "api_key": FlickrApiClient.Constants.ApiKey, "bbox": boundingBoxString, "safe_search": FlickrApiClient.ParameterValues.SafeSearch, "extras": FlickrApiClient.ParameterValues.Extras, "format": FlickrApiClient.ParameterValues.Format, "nojsoncallback": FlickrApiClient.ParameterValues.NoJsonCallback, "per_page": FlickrApiClient.ParameterValues.PerPage ] let urlString = FlickrApiClient.Constants.BaseURL + escapedParameters(methodArguments) let url = NSURL(string: urlString)! let request = NSURLRequest(URL: url) let task = session.dataTaskWithRequest(request) { (data, response, error) in /* GUARD: Was there an error? */ guard (error == nil) else { print("There was an error with your request: \(error)") return } /* GUARD: Did we get a successful 2XX response? */ guard let statusCode = (response as? NSHTTPURLResponse)?.statusCode where statusCode >= 200 && statusCode <= 299 else { if let response = response as? NSHTTPURLResponse { print("Your request returned an invalid response! Status code: \(response.statusCode)!") } else if let response = response { print("Your request returned an invalid response! Response: \(response)!") } else { print("Your request returned an invalid response!") } return } /* GUARD: Was there any data returned? */ guard let data = data else { print("No data was returned by the request!") return } /* Parse the data! */ let parsedResult: AnyObject! do { parsedResult = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) } catch { parsedResult = nil print("Could not parse the data as JSON: '\(data)'") return } /* GUARD: Did Flickr return an error? */ guard let stat = parsedResult["stat"] as? String where stat == "ok" else { print("Flickr API returned an error. See error code and message in \(parsedResult)") return } /* GUARD: Is "photos" key in our result? */ guard let photosDictionary = parsedResult["photos"] as? NSDictionary else { print("Cannot find keys 'photos' in \(parsedResult)") return } /* GUARD: Is the "total" key in photosDictionary? */ guard let totalPhotos = (photosDictionary["total"] as? NSString)?.integerValue else { print("Cannot find key 'total' in \(photosDictionary)") return } if totalPhotos > 0 { /* GUARD: Is the "photo" key in photosDictionary? */ guard let photosArray = photosDictionary["photo"] as? [[String: AnyObject]] else { print("Cannot find key 'photo' in \(photosDictionary)") return } completionHandler(success: true, photosArray: photosArray, errorString: "") } } task.resume() } // MARK: Escape HTML Parameters func escapedParameters(parameters: [String : AnyObject]) -> String { var urlVars = [String]() for (key, value) in parameters { /* Make sure that it is a string value */ let stringValue = "\(value)" /* Escape it */ let escapedValue = stringValue.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) /* Append it */ urlVars += [key + "=" + "\(escapedValue!)"] } return (!urlVars.isEmpty ? "?" : "") + urlVars.joinWithSeparator("&") } }
mit
628bdfd51b293971c5dc318afdf37a1e
36.370968
165
0.559896
5.52864
false
false
false
false
rukano/cantina
Sources/App/Controllers/CantinaController.swift
1
1231
// // CantinaController.swift // cantina // // Created by Romero, Juan, SEVEN PRINCIPLES on 02.09.17. // // import Vapor import Kanna enum TextFormat { case mattermost case prosa } final class CantinaController { private let externalUrl: String = "http://www.friendskantine.de/index.php/speiseplan/speiseplan-bockenheim" var drop: Droplet init(drop: Droplet) { self.drop = drop } func alexa(_ req: Request) throws -> ResponseRepresentable { return try requestMenuText(.prosa) } func text(_ req: Request) throws -> ResponseRepresentable { return try requestMenuText(.mattermost) } func today(_ req: Request) throws -> ResponseRepresentable { let text = try requestMenuText(.mattermost) return try CantinaMattermost(text).makeJson() } private func requestMenuText(_ format: TextFormat) throws -> String { let response = try drop.client.request(.get, externalUrl) guard let bytes = response.body.bytes else { throw Abort.serverError } let content = String(bytes: bytes) let cantina = try Cantina(fromWeb: content) let text = try cantina.currentDayMenu(format) return text } }
mit
6d4502eeaaf40f7d5141fc993c369b9a
22.673077
111
0.666125
3.920382
false
false
false
false
AlbertWu0212/MyDailyTodo
MyDailyTodo/MyDailyTodo/DataModel.swift
1
2686
// // DataModel.swift // MyDailyTodo // // Created by WuZhengBin on 16/7/4. // Copyright © 2016年 WuZhengBin. All rights reserved. // import Foundation class DataModel { var lists = [Checklist]() var indexOfSelectedChecklist: Int { get { return NSUserDefaults.standardUserDefaults().integerForKey("ChecklistIndex") } set { NSUserDefaults.standardUserDefaults().setInteger(newValue, forKey: "ChecklistIndex") NSUserDefaults.standardUserDefaults().synchronize() } } func documentsDirectory() -> String { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) return paths[0] } func dataFilePath() -> String { let directory = documentsDirectory() as NSString return directory.stringByAppendingPathComponent("Checklists.plist") } func saveChecklists() { let data = NSMutableData() let archiver = NSKeyedArchiver(forWritingWithMutableData: data) archiver.encodeObject(lists, forKey: "Checklists") archiver.finishEncoding() data.writeToFile(dataFilePath(), atomically: true) } func loadChecklist() { let path = dataFilePath() if NSFileManager.defaultManager().fileExistsAtPath(path) { if let data = NSData(contentsOfFile: path) { let unarchiver = NSKeyedUnarchiver(forReadingWithData: data) lists = unarchiver.decodeObjectForKey("Checklists") as! [Checklist] unarchiver.finishDecoding() sortChecklist() } } } func registerDefaults() { let dictionary = [ "ChecklistIndex": -1 , "FirstTime": true, "ChecklistItemID": 0 ] NSUserDefaults.standardUserDefaults().registerDefaults(dictionary) } func handleFirstTime() { let userDefaults = NSUserDefaults.standardUserDefaults() let firstTime = userDefaults.boolForKey("FirstTime") if firstTime { let checklist = Checklist(name: "List") lists.append(checklist) indexOfSelectedChecklist = 0 userDefaults.setBool(false, forKey: "FirstTime") userDefaults.synchronize() } } func sortChecklist() { lists.sortInPlace({ checklist1, checklist2 in return checklist1.name.localizedStandardCompare(checklist2.name) == .OrderedAscending }) } class func nextChecklistItemID() -> Int { let userDefaults = NSUserDefaults.standardUserDefaults() let itemID = userDefaults.integerForKey("ChecklistItemID") userDefaults.setInteger(itemID + 1, forKey: "ChecklistItemID") userDefaults.synchronize() return itemID } init() { loadChecklist() registerDefaults() handleFirstTime() } }
mit
0270ebd8e79376a2b7f31f04edca53ea
27.849462
94
0.686545
5.120229
false
false
false
false
eflyjason/word-counter-tools
WordCounter/ViewController.swift
1
34703
// // ViewController.swift // WordCounter // // Created by Arefly on 5/7/2015. // Copyright (c) 2015 Arefly. All rights reserved. // import UIKit import Foundation import MBProgressHUD import EAIntroView class ViewController: UIViewController, UITextViewDelegate, EAIntroDelegate { // MARK: - Basic var let appDelegate = (UIApplication.shared.delegate as! AppDelegate) let defaults = UserDefaults.standard let sharedData = UserDefaults(suiteName: "group.com.arefly.WordCounter") // MARK: - Init var // MARK: - IBOutlet var @IBOutlet var tv: UITextView! // MARK: - Navbar var var topBarCountButton: UIBarButtonItem! var topBarCountButtonType: CountByType! var shareButton: UIBarButtonItem! var clearButton: UIBarButtonItem! // MARK: - keyboardButton var override var canBecomeFirstResponder: Bool { get { return true } } override var inputAccessoryView: CustomInputAccessoryWithToolbarView? { if keyBoardToolBar == nil { // https://stackoverflow.com/a/58524360/2603230 keyBoardToolBar = CustomInputAccessoryWithToolbarView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 44)) } return keyBoardToolBar } var keyBoardToolBar: CustomInputAccessoryWithToolbarView! var showedKeyboardButtons = [CountByType: Bool]() // We have to keep both `countingKeyboardBarButtonItemsNames` and `countingKeyboardBarButtonItems` as `countingKeyboardBarButtonItems` is not ordered. var countingKeyboardBarButtonItemsNames = [CountByType]() var countingKeyboardBarButtonItems = [CountByType: UIBarButtonItem]() var stableKeyboardBarButtonItemsNames = [String]() var stableKeyboardBarButtonItems = [String: UIBarButtonItem]() // MARK: - Bool var var isTextViewActive: Bool { get { return self.tv.isFirstResponder } } var appFirstLaunch = false var appJustUpdate = false var presentingOtherView = false // MARK: - UI var var tvPlaceholderLabel: UILabel! // MARK: - Welcome page var var intro = EAIntroView() // MARK: - Color var toolbarButtonTintColor: UIColor = { if #available(iOS 13, *) { return .label } else { return .black } }() // MARK: - Override func override func viewDidLoad() { super.viewDidLoad() print("準備加載 View Controller 之 viewDidLoad") self.title = NSLocalizedString("Main.NavBar.Title", comment: "Word Counter") if #available(iOS 13.0, *) { self.view.backgroundColor = .systemBackground } topBarCountButton = UIBarButtonItem() topBarCountButton.tintColor = toolbarButtonTintColor if WordCounter.isChineseUser() { topBarCountButtonType = .chineseWord } else { topBarCountButtonType = .word } topBarCountButton.title = WordCounter.getHumanReadableCountString(of: "", by: topBarCountButtonType) topBarCountButton.action = #selector(self.topBarCountingButtonClicked(_:)) topBarCountButton.target = self self.navigationItem.setLeftBarButton(topBarCountButton, animated: true) clearButton = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(self.clearButtonClicked(_:))) shareButton = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(self.shareButtonClicked(sender:))) clearButton.tintColor = .systemRed self.navigationItem.setRightBarButtonItems([shareButton, clearButton], animated: true) if isAppFirstLaunch() { appFirstLaunch = true } let version: String = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String if defaults.object(forKey: "nowVersion") == nil { defaults.setValue(version, forKey: "nowVersion") appFirstLaunch = true } else { if defaults.string(forKey: "nowVersion") != version { appJustUpdate = true defaults.setValue(version, forKey: "nowVersion") } } self.tv.delegate = self self.tv.layoutManager.allowsNonContiguousLayout = false if #available(iOS 13.0, *) { self.tv.backgroundColor = .systemBackground self.tv.textColor = .label } tvPlaceholderLabel = UILabel() tvPlaceholderLabel.text = NSLocalizedString("Global.TextView.PlaceHolder.Text", comment: "Type or paste here...") tvPlaceholderLabel.font = UIFont.systemFont(ofSize: tv.font!.pointSize) tvPlaceholderLabel.sizeToFit() tv.addSubview(tvPlaceholderLabel) tvPlaceholderLabel.frame.origin = CGPoint(x: 5, y: tv.font!.pointSize / 2) if #available(iOS 13.0, *) { tvPlaceholderLabel.textColor = .placeholderText } else { tvPlaceholderLabel.textColor = UIColor(white: 0, alpha: 0.3) } tvPlaceholderLabel.isHidden = !tv.text.isEmpty } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("準備加載 View Controller 之 viewWillAppear") addToolBarToKeyboard() let countMenuItem = UIMenuItem(title: NSLocalizedString("Global.TextView.MenuItem.Count", comment: "Count..."), action: #selector(self.countSelectionWord)) UIMenuController.shared.menuItems = [countMenuItem] NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillChangeFrame(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidChangeFrame(_:)), name: UIResponder.keyboardDidChangeFrameNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.doAfterRotate), name: UIDevice.orientationDidChangeNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) //2015-12-11: Change to DidEnterBackgroundNotification as it is more suiable in Slide Over view NotificationCenter.default.addObserver(self, selector: #selector(self.didEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.setContentToTextBeforeEnterBackground), name: .catnapSetContentToTextBeforeEnterBackground, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.setContentFromClipBoard), name: .catnapSetContentFromClipBoard, object: nil) doAfterRotate() //checkScreenWidthToSetButton() if defaults.object(forKey: "noAd") == nil { defaults.set(false, forKey: "noAd") } if defaults.object(forKey: "appLaunchTimes") == nil { defaults.set(1, forKey: "appLaunchTimes") } else { defaults.set(defaults.integer(forKey: "appLaunchTimes") + 1, forKey: "appLaunchTimes") } print("已設定appLaunchTimes值爲\(defaults.integer(forKey: "appLaunchTimes"))") if defaults.object(forKey: "everShowPresentReviewAgain") == nil { defaults.set(true, forKey: "everShowPresentReviewAgain") } //appJustUpdate = true if defaults.object(forKey: "appLaunchTimesAfterUpdate") == nil { defaults.set(-1, forKey: "appLaunchTimesAfterUpdate") } if appJustUpdate { defaults.set(1, forKey: "appLaunchTimesAfterUpdate") } if defaults.integer(forKey: "appLaunchTimesAfterUpdate") != -1 { defaults.set(defaults.integer(forKey: "appLaunchTimesAfterUpdate") + 1, forKey: "appLaunchTimesAfterUpdate") } print("已設定appLaunchTimesAfterUpdate值爲\(defaults.integer(forKey: "appLaunchTimesAfterUpdate"))") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) print("準備加載 View Controller 之 viewDidAppear") if appFirstLaunch || appJustUpdate { presentingOtherView = true // So that the toolbar will not be shown. self.resignFirstResponder() presentIntroView() } //defaults.setBool(true, forKey: "everShowPresentReviewAgain") //var everShowPresentReviewAgain = defaults.boolForKey("everShowPresentReviewAgain") //var appLaunchTimes = defaults.integerForKey("appLaunchTimes") print("everShowPresentReviewAgain的值爲"+String(defaults.bool(forKey: "everShowPresentReviewAgain"))) if defaults.bool(forKey: "everShowPresentReviewAgain") { if !presentingOtherView { print("appLaunchTimes的值爲\(defaults.integer(forKey: "appLaunchTimes"))") //defaults.setInteger(8, forKey: "appLaunchTimes") if defaults.integer(forKey: "appLaunchTimes") % 50 == 0 { presentingOtherView = true presentReviewAlert() //defaults.setInteger(defaults.integerForKey("appLaunchTimes") + 1, forKey: "appLaunchTimes") } } } if defaults.integer(forKey: "appLaunchTimesAfterUpdate") != -1 { if !presentingOtherView { print("appLaunchTimesAfterUpdate的值爲\(defaults.integer(forKey: "appLaunchTimesAfterUpdate"))") if defaults.integer(forKey: "appLaunchTimesAfterUpdate") % 88 == 0 { presentingOtherView = true presentUpdateReviewAlert() //defaults.setInteger(defaults.integerForKey("appLaunchTimes") + 1, forKey: "appLaunchTimes") } } } if !presentingOtherView { startEditing() } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("準備加載 View Controller 之 viewWillDisappear") NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillChangeFrameNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidChangeFrameNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil) NotificationCenter.default.removeObserver(self, name: .catnapSetContentToTextBeforeEnterBackground, object: nil) NotificationCenter.default.removeObserver(self, name: .catnapSetContentFromClipBoard, object: nil) //NSNotificationCenter.defaultCenter().removeObserver(self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { endEditing() } override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { if action == #selector(self.countSelectionWord) { if !(getTextViewSelectionText(self.tv).isEmpty) { return true } return false } return super.canPerformAction(action, withSender: sender) } // MARK: - Screen config func func checkScreenWidthToSetButton () { print("準備加載 checkScreenWidthToSetButton") showedKeyboardButtons = [ .word: false, .character: false, .characterWithSpaces: false, .sentence: false, .paragraph: false, .chineseWord: false, .chineseWordWithoutPunctuation: false, ] let bounds = UIApplication.shared.keyWindow?.bounds let width = bounds!.size.width let height = bounds!.size.height print("屏幕高度:\(height)、屏幕寬度:\(width)") switch width { case 0..<330: showedKeyboardButtons[.sentence] = true break case 330..<750: showedKeyboardButtons[WordCounter.isChineseUser() ? .chineseWordWithoutPunctuation : .character] = true showedKeyboardButtons[.sentence] = true break default: if (WordCounter.isChineseUser()) { showedKeyboardButtons[.chineseWord] = true showedKeyboardButtons[.chineseWordWithoutPunctuation] = true } showedKeyboardButtons[.word] = true showedKeyboardButtons[.character] = true showedKeyboardButtons[.characterWithSpaces] = width > 1000 showedKeyboardButtons[.sentence] = true showedKeyboardButtons[.paragraph] = true } updateToolBar() //updateTextViewCounting() handleTextViewChange(self.tv) // Call handleTextViewChange manually } @objc func doAfterRotate() { print("準備加載 doAfterRotate") // If text view is active, `keyboardWillChangeFrame` will handle everything. checkScreenWidthToSetButton() } // MARK: - Keyboard func @objc func keyboardWillChangeFrame(_ notification: Notification) { print("keyboardWillChangeFrame") guard let userInfo = notification.userInfo else { return } // https://stackoverflow.com/a/27135992/2603230 let endFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue let endFrameY = endFrame?.origin.y ?? 0 //print(self.view.convert(endFrame!, to: self.view.window)) //print(self.view.frame.height - endFrameY) //print(endFrameY) var height: CGFloat = self.inputAccessoryView?.frame.height ?? 0.0 if endFrameY >= UIScreen.main.bounds.size.height - (self.inputAccessoryView?.frame.height ?? 0.0) { // If the keyboard is closed. // Do nothing } else { if let endFrameHeight = endFrame?.size.height { height = endFrameHeight } } if #available(iOS 11.0, *) { // https://stackoverflow.com/a/48693623/2603230 height -= self.view.safeAreaInsets.bottom } self.tv.contentInset.bottom = height self.tv.scrollIndicatorInsets.bottom = height checkScreenWidthToSetButton() handleTextViewChange(self.tv) } @objc func keyboardDidChangeFrame(_ notification: Notification) { // For updating the "Done" button. updateToolBar() } func addToolBarToKeyboard(){ stableKeyboardBarButtonItemsNames = [String]() //Empty stableKeyboardBarButtonItemsNames first stableKeyboardBarButtonItems["FlexSpace"] = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) stableKeyboardBarButtonItemsNames.append("FlexSpace") stableKeyboardBarButtonItems["Done"] = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.doneButtonAction)) stableKeyboardBarButtonItemsNames.append("Done") let infoButton: UIButton = UIButton(type: UIButton.ButtonType.infoLight) infoButton.addTarget(self, action: #selector(self.infoButtonAction), for: UIControl.Event.touchUpInside) stableKeyboardBarButtonItems["Info"] = UIBarButtonItem(customView: infoButton) stableKeyboardBarButtonItemsNames.append("Info") countingKeyboardBarButtonItemsNames = [.chineseWord, .chineseWordWithoutPunctuation, .word, .character, .characterWithSpaces, .sentence, .paragraph]; for name in countingKeyboardBarButtonItemsNames { // We have to set some text in `title` to make sure the button is rendered at the correct position. countingKeyboardBarButtonItems[name] = UIBarButtonItem(title: "_", style: .plain, target: self, action: #selector(self.countResultButtonAction)) countingKeyboardBarButtonItems[name]!.tintColor = toolbarButtonTintColor } updateToolBar() // TODO: not sure if we need it here self.tv.inputAccessoryView = keyBoardToolBar } func updateToolBar() { var barItems = [UIBarButtonItem]() for name in countingKeyboardBarButtonItemsNames { if showedKeyboardButtons[name] == true { barItems.append(countingKeyboardBarButtonItems[name]!) } } for name in stableKeyboardBarButtonItemsNames { if name == "Done" && !isTextViewActive { // Do not add the "Done" button if the text view is not active. continue } barItems.append(stableKeyboardBarButtonItems[name]!) } if keyBoardToolBar != nil { keyBoardToolBar.toolbar.setItems(barItems, animated: true) keyBoardToolBar.toolbar.setNeedsLayout() } updateTextViewCounting() } // MARK: - Textview related func /* func endEditingIfFullScreen() { let isFullScreen = CGRectEqualToRect((UIApplication.sharedApplication().keyWindow?.bounds)!, UIScreen.mainScreen().bounds) print("目前窗口是否處於全屏狀態:\(isFullScreen)") if isFullScreen { endEditing() } } */ @objc func countSelectionWord() { print("準備加載 countSelectionWord") print("即:已準備顯示所選文字區域的字數統計") let selectedText = getTextViewSelectionText(self.tv) showCountResultAlert(selectedText) } func getTextViewSelectionText(_ tv: UITextView) -> String { if let selectedRange = tv.selectedTextRange { if let selectedText = tv.text(in: selectedRange) { return selectedText } } return "" } func replaceTextViewContent(_ text: String) { self.tv.text = text self.textViewDidChange(self.tv) // Call textViewDidChange manually } func endEditing() { self.tv.resignFirstResponder() //self.tv.endEditing(true) //self.view.endEditing(true) } func startEditing() { self.tv.becomeFirstResponder() } func clearContent() { endEditing() self.replaceTextViewContent("") doAfterRotate() } func textViewDidChange(_ textView: UITextView) { handleTextViewChange(textView) self.storeText(textView.text) } func handleTextViewChange(_ textView: UITextView) { tvPlaceholderLabel.isHidden = !textView.text.isEmpty updateTextViewCounting() } func updateTextViewCounting() { //var wordTitle = "" var titles: [CountByType: String] = [:] if let myText = self.tv.text { DispatchQueue.global(qos: .background).async { if (WordCounter.isChineseUser()) { if myText.isEmptyOrContainsChineseCharacters { self.topBarCountButtonType = .chineseWord } else { self.topBarCountButtonType = .word } } titles[self.topBarCountButtonType] = WordCounter.getHumanReadableCountString(of: myText, by: self.topBarCountButtonType, shouldUseShortForm: true) for (type, enabled) in self.showedKeyboardButtons { if (!enabled) { continue } titles[type] = WordCounter.getHumanReadableCountString(of: myText, by: type, shouldUseShortForm: true) } DispatchQueue.main.async { self.topBarCountButton.title = titles[self.topBarCountButtonType] for name in self.countingKeyboardBarButtonItemsNames { self.countingKeyboardBarButtonItems[name]!.title = "_" self.countingKeyboardBarButtonItems[name]!.title = titles[name] } //print(titles["Sentence"]) } } } } @objc func setContentFromClipBoard() { print("準備加載 setContentFromClipBoard") if let clipBoard = UIPasteboard.general.string { print("已獲取用戶剪貼簿內容:\(clipBoard)") if (self.tv.text.isEmpty) || (self.tv.text == clipBoard) { DispatchQueue.main.async { self.replaceTextViewContent(clipBoard) } } else { let replaceContentAlert = UIAlertController( title: NSLocalizedString("Global.Alert.BeforeReplaceTextViewToClipboard.Title", comment: "Replace current contents with clipboard contents?"), message: NSLocalizedString("Global.Alert.BeforeReplaceTextViewToClipboard.Content", comment: "NOTICE: This action is irreversible!"), preferredStyle: .alert) replaceContentAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Button.Yes", comment: "Yes"), style: .default, handler: { (action: UIAlertAction) in print("用戶已按下確定替換內容為剪切版內容") self.replaceTextViewContent(clipBoard) })) replaceContentAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Button.Close", comment: "Close"), style: .cancel, handler: { (action: UIAlertAction) in print("用戶已按下取消按鈕") })) DispatchQueue.main.async { self.present(replaceContentAlert, animated: true, completion: nil) } } } } @objc func setContentToTextBeforeEnterBackground() { print("準備加載 setContentToTextBeforeEnterBackground") if let textBeforeEnterBackground = defaults.string(forKey: "textBeforeEnterBackground") { if textBeforeEnterBackground != self.tv.text { DispatchQueue.main.async { self.replaceTextViewContent(textBeforeEnterBackground) } } } } // MARK: - Button action func @objc func clearButtonClicked(_ sender: AnyObject) { let keyboardShowingBefore = isTextViewActive endEditing() let clearContentAlert = UIAlertController( title: NSLocalizedString("Global.Alert.BeforeClear.Title", comment: "Clear all content?"), message: NSLocalizedString("Global.Alert.BeforeClear.Content", comment: "WARNING: This action is irreversible!"), preferredStyle: .alert) clearContentAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Button.Yes", comment: "Yes"), style: .destructive, handler: { (action: UIAlertAction) in print("用戶已按下確定清空按鈕") self.clearContent() self.startEditing() })) clearContentAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Button.Close", comment: "Close"), style: .cancel, handler: { (action: UIAlertAction) in print("用戶已按下取消清空按鈕") if keyboardShowingBefore { self.startEditing() } })) DispatchQueue.main.async { self.present(clearContentAlert, animated: true, completion: nil) } } @objc func shareButtonClicked(sender: UIBarButtonItem) { endEditing() // https://stackoverflow.com/a/37939782/2603230 let activityViewController: UIActivityViewController = UIActivityViewController( activityItems: [self.tv.text ?? ""], applicationActivities: nil) activityViewController.popoverPresentationController?.barButtonItem = sender //activityViewController.popoverPresentationController?.permittedArrowDirections = .up if #available(iOS 13.0, *) { /*activityViewController.activityItemsConfiguration = [ UIActivity.ActivityType.copyToPasteboard ] as? UIActivityItemsConfigurationReading*/ } DispatchQueue.main.async { self.present(activityViewController, animated: true, completion: nil) } } @objc func infoButtonAction() { self.performSegue(withIdentifier: "goInfo", sender: nil) } @objc func countResultButtonAction() { showCountResultAlert(self.tv.text) } func showCountResultAlert(_ text: String) { let keyboardShowingBefore = isTextViewActive endEditing() let progressHUD = MBProgressHUD.showAdded(to: self.view.window!, animated: true) progressHUD.label.text = NSLocalizedString("Global.ProgressingHUD.Label.Counting", comment: "Counting...") var message: String = "" DispatchQueue.global(qos: .background).async { message = WordCounter.getHumanReadableSummary(of: text, by: WordCounter.getAllTypes(for: text)) DispatchQueue.main.async { MBProgressHUD.hide(for: self.view.window!, animated: true) let alertTitle = NSLocalizedString("Global.Alert.Counter.Title", comment: "Counter") let countingResultAlert = UIAlertController(title: alertTitle, message: message, preferredStyle: .alert) countingResultAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Button.Done", comment: "Done"), style: .cancel, handler: { (action: UIAlertAction) in print("用戶已按下確定按鈕") if keyboardShowingBefore { self.startEditing() } })) self.present(countingResultAlert, animated: true, completion: nil) } } } @objc func topBarCountingButtonClicked(_ sender: AnyObject) { countResultButtonAction() } @objc func doneButtonAction() { endEditing() } // MARK: - Intro View func presentIntroView() { let screenWidth = self.view.bounds.size.width let screenHeight = self.view.bounds.size.height var imagesLangPrefix = "en" if WordCounter.isChineseUser() { if WordCounter.isSimplifiedChineseUser() { imagesLangPrefix = "zh-Hans" } else { imagesLangPrefix = "zh-Hant" } } var contentImages = [ "\(imagesLangPrefix)-1-4-DarkMode.png", "\(imagesLangPrefix)-1-4-MoreCountingType.png", "\(imagesLangPrefix)-1-4-ActionExtension.png", "\(imagesLangPrefix)-1-4-About.png", ] var contentTitleTexts = [ NSLocalizedString("Welcome.Version.1-4-1.Title.DarkMode", comment: ""), NSLocalizedString("Welcome.Version.1-4-1.Title.MoreCountingType", comment: ""), NSLocalizedString("Welcome.Version.1-4-1.Title.ActionExtension", comment: ""), NSLocalizedString("Welcome.Global.Title.About", comment: "Thanks!"), ] var contentDetailTexts = [ NSLocalizedString("Welcome.Version.1-4-1.Text.DarkMode", comment: ""), NSLocalizedString("Welcome.Version.1-4-1.Text.MoreCountingType", comment: ""), NSLocalizedString("Welcome.Version.1-4-1.Text.ActionExtension", comment: ""), NSLocalizedString("Welcome.Global.Text.About", comment: ""), ] if #available(iOS 13.0, *) { // Do nothing } else { // Do not include dark mode below iOS 13. contentImages.removeFirst() contentTitleTexts.removeFirst() contentDetailTexts.removeFirst() } var introPages = [EAIntroPage]() for (index, _) in contentTitleTexts.enumerated() { let page = EAIntroPage() page.title = contentTitleTexts[index] page.desc = contentDetailTexts[index] if (index == contentImages.count-1) { //About Content page.descFont = UIFont(name: (page.descFont?.fontName)!, size: 12) } //print("WOW!: \(page.titlePositionY)") let titlePositionFromBottom = page.titlePositionY let imageView = UIImageView(image: UIImage(named: contentImages[index])) imageView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight-titlePositionFromBottom-100) imageView.contentMode = .scaleAspectFit page.titleIconView = imageView //page.titleIconPositionY = 30 page.bgColor = self.view.tintColor introPages.append(page) } intro = EAIntroView(frame: self.view.bounds, andPages: introPages) intro.delegate = self intro.show(in: self.view, animateDuration: 0.5) intro.showFullscreen() intro.skipButton.setTitle(NSLocalizedString("Welcome.Global.Button.Skip", comment: "Skip"), for: UIControl.State()) intro.pageControlY = 50 } func introDidFinish(_ introView: EAIntroView!, wasSkipped: Bool) { presentingOtherView = false appFirstLaunch = false appJustUpdate = false // So that the toolbar at the bottom will show. self.becomeFirstResponder() startEditing() } // MARK: - General func @objc func didBecomeActive() { print("準備加載 didBecomeActive") doAfterRotate() } func storeText(_ tvText: String) { //print("準備 storeText \(tvText)") defaults.set(tvText, forKey: "textBeforeEnterBackground") } @objc func didEnterBackground() { print("準備加載 didEnterBackground") self.storeText(self.tv.text) } func isAppFirstLaunch() -> Bool{ //檢測App是否首次開啓 print("準備加載 isAppFirstLaunch") if let _ = defaults.string(forKey: "isAppAlreadyLaunchedOnce") { print("App於本機並非首次開啓") return false } else { defaults.set(true, forKey: "isAppAlreadyLaunchedOnce") print("App於本機首次開啓") return true } } func presentReviewAlert() { let reviewAlert = UIAlertController( title: NSLocalizedString("Global.Alert.PlzRate.Title", comment: "Thanks!"), message: String.localizedStringWithFormat( NSLocalizedString("Global.Alert.PlzRate.Content", comment: "You have used Word Counter Tool for %d times! Love it? Can you take a second to rate our app?"), defaults.integer(forKey: "appLaunchTimes")), preferredStyle: .alert) reviewAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Alert.PlzRate.Button.Yes", comment: "Sure!"), style: .default, handler: { (action: UIAlertAction) in print("用戶已按下發表評論按鈕") self.defaults.set(-1, forKey: "appLaunchTimesAfterUpdate") // Do not show update alert for this version too self.defaults.set(false, forKey: "everShowPresentReviewAgain") UIApplication.shared.openURL(BasicConfig.appStoreReviewUrl! as URL) self.presentingOtherView = false })) reviewAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Alert.PlzRate.Button.Later", comment: "Not now"), style: .default, handler: { (action: UIAlertAction) in print("用戶已按下以後再說按鈕") self.defaults.set(true, forKey: "everShowPresentReviewAgain") self.startEditing() self.presentingOtherView = false })) reviewAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Alert.PlzRate.Button.Cancel", comment: "No, thanks!"), style: .cancel, handler: { (action: UIAlertAction) in print("用戶已按下永遠再不顯示按鈕") self.defaults.set(-1, forKey: "appLaunchTimesAfterUpdate") // Do not show update alert for this version too self.defaults.set(false, forKey: "everShowPresentReviewAgain") self.startEditing() self.presentingOtherView = false })) DispatchQueue.main.async { self.present(reviewAlert, animated: true, completion: nil) } } func presentUpdateReviewAlert() { let reviewAlert = UIAlertController( title: NSLocalizedString("Global.Alert.PlzRateUpdate.Title", comment: "Thanks for update!"), message: String.localizedStringWithFormat( NSLocalizedString("Global.Alert.PlzRateUpdate.Content", comment: "You have used Word Counter Tool for %1$d times since you updated to Version %2$@! Love this update? Can you take a second to rate our app?"), defaults.integer(forKey: "appLaunchTimesAfterUpdate"), Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String ), preferredStyle: .alert) reviewAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Alert.PlzRateUpdate.Button.Yes", comment: "Sure!"), style: .default, handler: { (action: UIAlertAction) in print("用戶已按下發表評論按鈕") self.defaults.set(-1, forKey: "appLaunchTimesAfterUpdate") UIApplication.shared.openURL(BasicConfig.appStoreReviewUrl! as URL) self.presentingOtherView = false })) reviewAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Alert.PlzRateUpdate.Button.Later", comment: "Not now"), style: .default, handler: { (action: UIAlertAction) in print("用戶已按下以後再說按鈕") self.startEditing() self.presentingOtherView = false })) reviewAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Alert.PlzRateUpdate.Button.Cancel", comment: "No for this version, thanks!"), style: .cancel, handler: { (action: UIAlertAction) in print("用戶已按下此版本永遠再不顯示按鈕") self.defaults.set(-1, forKey: "appLaunchTimesAfterUpdate") self.startEditing() self.presentingOtherView = false })) DispatchQueue.main.async { self.present(reviewAlert, animated: true, completion: nil) } } }
gpl-3.0
991161b134f9fd58678c6e0370a87e8c
37.021158
223
0.638637
5.216654
false
false
false
false
arvedviehweger/swift
stdlib/public/core/SequenceWrapper.swift
4
3732
//===--- SequenceWrapper.swift - sequence/collection wrapper protocols ----===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // To create a Sequence that forwards requirements to an // underlying Sequence, have it conform to this protocol. // //===----------------------------------------------------------------------===// /// A type that is just a wrapper over some base Sequence @_show_in_interface public // @testable protocol _SequenceWrapper : Sequence { associatedtype Base : Sequence associatedtype Iterator = Base.Iterator associatedtype SubSequence = Base.SubSequence var _base: Base { get } } extension _SequenceWrapper { public var underestimatedCount: Int { return _base.underestimatedCount } public func _preprocessingPass<R>( _ preprocess: () throws -> R ) rethrows -> R? { return try _base._preprocessingPass(preprocess) } } extension _SequenceWrapper where Iterator == Base.Iterator { public func makeIterator() -> Iterator { return self._base.makeIterator() } @discardableResult public func _copyContents( initializing buf: UnsafeMutableBufferPointer<Iterator.Element> ) -> (Iterator, UnsafeMutableBufferPointer<Iterator.Element>.Index) { return _base._copyContents(initializing: buf) } } extension _SequenceWrapper where Iterator.Element == Base.Iterator.Element { public func map<T>( _ transform: (Iterator.Element) throws -> T ) rethrows -> [T] { return try _base.map(transform) } public func filter( _ isIncluded: (Iterator.Element) throws -> Bool ) rethrows -> [Iterator.Element] { return try _base.filter(isIncluded) } public func forEach(_ body: (Iterator.Element) throws -> Void) rethrows { return try _base.forEach(body) } public func _customContainsEquatableElement( _ element: Iterator.Element ) -> Bool? { return _base._customContainsEquatableElement(element) } public func _copyToContiguousArray() -> ContiguousArray<Iterator.Element> { return _base._copyToContiguousArray() } } extension _SequenceWrapper where SubSequence == Base.SubSequence { public func dropFirst(_ n: Int) -> SubSequence { return _base.dropFirst(n) } public func dropLast(_ n: Int) -> SubSequence { return _base.dropLast(n) } public func prefix(_ maxLength: Int) -> SubSequence { return _base.prefix(maxLength) } public func suffix(_ maxLength: Int) -> SubSequence { return _base.suffix(maxLength) } } extension _SequenceWrapper where SubSequence == Base.SubSequence, Iterator.Element == Base.Iterator.Element { public func drop( while predicate: (Iterator.Element) throws -> Bool ) rethrows -> SubSequence { return try _base.drop(while: predicate) } public func prefix( while predicate: (Iterator.Element) throws -> Bool ) rethrows -> SubSequence { return try _base.prefix(while: predicate) } public func suffix(_ maxLength: Int) -> SubSequence { return _base.suffix(maxLength) } public func split( maxSplits: Int, omittingEmptySubsequences: Bool, whereSeparator isSeparator: (Iterator.Element) throws -> Bool ) rethrows -> [SubSequence] { return try _base.split( maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, whereSeparator: isSeparator ) } }
apache-2.0
0401c99a789167b4c66314ac2cfca5bd
28.385827
84
0.673098
4.647572
false
false
false
false
xedin/swift
test/Parse/recovery.swift
2
32726
// RUN: %target-typecheck-verify-swift //===--- Helper types used in this file. protocol FooProtocol {} //===--- Tests. func garbage() -> () { var a : Int ] this line is invalid, but we will stop at the keyword below... // expected-error{{expected expression}} return a + "a" // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}} } func moreGarbage() -> () { ) this line is invalid, but we will stop at the declaration... // expected-error{{expected expression}} func a() -> Int { return 4 } return a() + "a" // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}} } class Container<T> { func exists() -> Bool { return true } } func useContainer() -> () { var a : Container<not a type [skip this greater: >] >, b : Int // expected-error{{expected '>' to complete generic argument list}} expected-note{{to match this opening '<'}} b = 5 // no-warning a.exists() } @xyz class BadAttributes { // expected-error{{unknown attribute 'xyz'}} func exists() -> Bool { return true } } // expected-note @+2 {{did you mean 'test'?}} // expected-note @+1 {{'test' declared here}} func test(a: BadAttributes) -> () { _ = a.exists() // no-warning } // Here is an extra random close-brace! } // expected-error{{extraneous '}' at top level}} {{1-3=}} //===--- Recovery for braced blocks. func braceStmt1() { { braceStmt1(); } // expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} } func braceStmt2() { { () in braceStmt2(); } // expected-error {{closure expression is unused}} } func braceStmt3() { { // expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} undefinedIdentifier {} // expected-error {{use of unresolved identifier 'undefinedIdentifier'}} } } //===--- Recovery for misplaced 'static'. static func toplevelStaticFunc() {} // expected-error {{static methods may only be declared on a type}} {{1-8=}} static struct StaticStruct {} // expected-error {{declaration cannot be marked 'static'}} {{1-8=}} static class StaticClass {} // expected-error {{declaration cannot be marked 'static'}} {{1-8=}} static protocol StaticProtocol {} // expected-error {{declaration cannot be marked 'static'}} {{1-8=}} static typealias StaticTypealias = Int // expected-error {{declaration cannot be marked 'static'}} {{1-8=}} class ClassWithStaticDecls { class var a = 42 // expected-error {{class stored properties not supported}} } //===--- Recovery for missing controlling expression in statements. func missingControllingExprInIf() { if // expected-error {{expected expression, var, or let in 'if' condition}} if { // expected-error {{missing condition in an 'if' statement}} } if // expected-error {{missing condition in an 'if' statement}} { } if true { } else if { // expected-error {{missing condition in an 'if' statement}} } // It is debatable if we should do recovery here and parse { true } as the // body, but the error message should be sensible. if { true } { // expected-error {{missing condition in an 'if' statement}} expected-error{{consecutive statements on a line must be separated by ';'}} {{14-14=;}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{15-15=do }} expected-warning {{boolean literal is unused}} } if { true }() { // expected-error {{missing condition in an 'if' statement}} expected-error 2 {{consecutive statements on a line must be separated by ';'}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{17-17=do }} expected-warning {{boolean literal is unused}} } // <rdar://problem/18940198> if { { } } // expected-error{{missing condition in an 'if' statement}} expected-error{{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{8-8=do }} } func missingControllingExprInWhile() { while // expected-error {{expected expression, var, or let in 'while' condition}} while { // expected-error {{missing condition in a 'while' statement}} } while // expected-error {{missing condition in a 'while' statement}} { } // It is debatable if we should do recovery here and parse { true } as the // body, but the error message should be sensible. while { true } { // expected-error {{missing condition in a 'while' statement}} expected-error{{consecutive statements on a line must be separated by ';'}} {{17-17=;}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{18-18=do }} expected-warning {{boolean literal is unused}} } while { true }() { // expected-error {{missing condition in a 'while' statement}} expected-error 2 {{consecutive statements on a line must be separated by ';'}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{20-20=do }} expected-warning {{boolean literal is unused}} } // <rdar://problem/18940198> while { { } } // expected-error{{missing condition in a 'while' statement}} expected-error{{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{11-11=do }} } func missingControllingExprInRepeatWhile() { repeat { } while // expected-error {{missing condition in a 'while' statement}} { // expected-error{{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} missingControllingExprInRepeatWhile(); } repeat { } while { true }() // expected-error{{missing condition in a 'while' statement}} expected-error{{consecutive statements on a line must be separated by ';'}} {{10-10=;}} expected-warning {{result of call to closure returning 'Bool' is unused}} } // SR-165 func missingWhileInRepeat() { repeat { } // expected-error {{expected 'while' after body of 'repeat' statement}} } func acceptsClosure<T>(t: T) -> Bool { return true } func missingControllingExprInFor() { for ; { // expected-error {{C-style for statement has been removed in Swift 3}} } for ; // expected-error {{C-style for statement has been removed in Swift 3}} { } for ; true { // expected-error {{C-style for statement has been removed in Swift 3}} } for var i = 0; true { // expected-error {{C-style for statement has been removed in Swift 3}} i += 1 } } func missingControllingExprInForEach() { // expected-error @+3 {{expected pattern}} // expected-error @+2 {{expected Sequence expression for for-each loop}} // expected-error @+1 {{expected '{' to start the body of for-each loop}} for // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for { } // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for { } // expected-error @+2 {{expected 'in' after for-each pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for i { } // expected-error @+2 {{expected 'in' after for-each pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for var i { } // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for in { } // expected-error @+1 {{expected pattern}} for 0..<12 { } // expected-error @+3 {{expected pattern}} // expected-error @+2 {{expected Sequence expression for for-each loop}} // expected-error @+1 {{expected '{' to start the body of for-each loop}} for for in { } for i in { // expected-error {{expected Sequence expression for for-each loop}} } // The #if block is used to provide a scope for the for stmt to force it to end // where necessary to provoke the crash. #if true // <rdar://problem/21679557> compiler crashes on "for{{" // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for{{ // expected-note 2 {{to match this opening '{'}} #endif // expected-error {{expected '}' at end of closure}} expected-error {{expected '}' at end of brace statement}} #if true // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for{ var x = 42 } #endif // SR-5943 struct User { let name: String? } let users = [User]() for user in users whe { // expected-error {{expected '{' to start the body of for-each loop}} if let name = user.name { let key = "\(name)" } } for // expected-error {{expected pattern}} expected-error {{Sequence expression for for-each loop}} ; // expected-error {{expected '{' to start the body of for-each loop}} } func missingControllingExprInSwitch() { switch // expected-error {{expected expression in 'switch' statement}} expected-error {{expected '{' after 'switch' subject expression}} switch { // expected-error {{expected expression in 'switch' statement}} expected-error {{'switch' statement body must have at least one 'case' or 'default' block}} } switch // expected-error {{expected expression in 'switch' statement}} expected-error {{'switch' statement body must have at least one 'case' or 'default' block}} { } switch { // expected-error {{expected expression in 'switch' statement}} case _: return } switch { // expected-error {{expected expression in 'switch' statement}} case Int: return // expected-error {{'is' keyword required to pattern match against type name}} {{10-10=is }} case _: return } switch { 42 } { // expected-error {{expected expression in 'switch' statement}} expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} expected-error{{consecutive statements on a line must be separated by ';'}} {{16-16=;}} expected-error{{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{17-17=do }} // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}} case _: return // expected-error{{'case' label can only appear inside a 'switch' statement}} } switch { 42 }() { // expected-error {{expected expression in 'switch' statement}} expected-error {{all statements inside a switch must be covered by a 'case' or 'default'}} expected-error 2 {{consecutive statements on a line must be separated by ';'}} expected-error{{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{19-19=do }} // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}} case _: return // expected-error{{'case' label can only appear inside a 'switch' statement}} } } //===--- Recovery for missing braces in nominal type decls. struct NoBracesStruct1() // expected-error {{expected '{' in struct}} enum NoBracesUnion1() // expected-error {{expected '{' in enum}} class NoBracesClass1() // expected-error {{expected '{' in class}} protocol NoBracesProtocol1() // expected-error {{expected '{' in protocol type}} extension NoBracesStruct1() // expected-error {{expected '{' in extension}} struct NoBracesStruct2 // expected-error {{expected '{' in struct}} enum NoBracesUnion2 // expected-error {{expected '{' in enum}} class NoBracesClass2 // expected-error {{expected '{' in class}} protocol NoBracesProtocol2 // expected-error {{expected '{' in protocol type}} extension NoBracesStruct2 // expected-error {{expected '{' in extension}} //===--- Recovery for multiple identifiers in decls protocol Multi ident {} // expected-error @-1 {{found an unexpected second identifier in protocol declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{10-21=Multiident}} // expected-note @-3 {{join the identifiers together with camel-case}} {{10-21=MultiIdent}} class CCC CCC<T> {} // expected-error @-1 {{found an unexpected second identifier in class declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{7-14=CCCCCC}} enum EE EE<T> where T : Multi { // expected-error @-1 {{found an unexpected second identifier in enum declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{6-11=EEEE}} case a a // expected-error @-1 {{found an unexpected second identifier in enum 'case' declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{8-11=aa}} // expected-note @-3 {{join the identifiers together with camel-case}} {{8-11=aA}} case b } struct SS SS : Multi { // expected-error @-1 {{found an unexpected second identifier in struct declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{8-13=SSSS}} private var a b : Int = "" // expected-error @-1 {{found an unexpected second identifier in variable declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{15-18=ab}} // expected-note @-3 {{join the identifiers together with camel-case}} {{15-18=aB}} // expected-error @-4 {{cannot convert value of type 'String' to specified type 'Int'}} func f() { var c d = 5 // expected-error @-1 {{found an unexpected second identifier in variable declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{9-12=cd}} // expected-note @-3 {{join the identifiers together with camel-case}} {{9-12=cD}} // expected-warning @-4 {{initialization of variable 'c' was never used; consider replacing with assignment to '_' or removing it}} let _ = 0 } } let (efg hij, foobar) = (5, 6) // expected-error @-1 {{found an unexpected second identifier in constant declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{6-13=efghij}} // expected-note @-3 {{join the identifiers together with camel-case}} {{6-13=efgHij}} _ = foobar // OK. //===--- Recovery for parse errors in types. struct ErrorTypeInVarDecl1 { var v1 : // expected-error {{expected type}} {{11-11= <#type#>}} } struct ErrorTypeInVarDecl2 { var v1 : Int. // expected-error {{expected member name following '.'}} var v2 : Int } struct ErrorTypeInVarDecl3 { var v1 : Int< // expected-error {{expected type}} var v2 : Int } struct ErrorTypeInVarDecl4 { var v1 : Int<, // expected-error {{expected type}} {{16-16= <#type#>}} var v2 : Int } struct ErrorTypeInVarDecl5 { var v1 : Int<Int // expected-error {{expected '>' to complete generic argument list}} expected-note {{to match this opening '<'}} var v2 : Int } struct ErrorTypeInVarDecl6 { var v1 : Int<Int, // expected-note {{to match this opening '<'}} Int // expected-error {{expected '>' to complete generic argument list}} var v2 : Int } struct ErrorTypeInVarDecl7 { var v1 : Int<Int, // expected-error {{expected type}} var v2 : Int } struct ErrorTypeInVarDecl8 { var v1 : protocol<FooProtocol // expected-error {{expected '>' to complete protocol-constrained type}} expected-note {{to match this opening '<'}} var v2 : Int } struct ErrorTypeInVarDecl9 { var v1 : protocol // expected-error {{expected type}} var v2 : Int } struct ErrorTypeInVarDecl10 { var v1 : protocol<FooProtocol // expected-error {{expected '>' to complete protocol-constrained type}} expected-note {{to match this opening '<'}} var v2 : Int } struct ErrorTypeInVarDecl11 { var v1 : protocol<FooProtocol, // expected-error {{expected identifier for type name}} var v2 : Int } func ErrorTypeInPattern1(_: protocol<) { } // expected-error {{expected identifier for type name}} func ErrorTypeInPattern2(_: protocol<F) { } // expected-error {{expected '>' to complete protocol-constrained type}} // expected-note@-1 {{to match this opening '<'}} // expected-error@-2 {{use of undeclared type 'F'}} func ErrorTypeInPattern3(_: protocol<F,) { } // expected-error {{expected identifier for type name}} // expected-error@-1 {{use of undeclared type 'F'}} struct ErrorTypeInVarDecl12 { var v1 : FooProtocol & // expected-error{{expected identifier for type name}} var v2 : Int } struct ErrorTypeInVarDecl13 { // expected-note {{in declaration of 'ErrorTypeInVarDecl13'}} var v1 : & FooProtocol // expected-error {{expected type}} expected-error {{consecutive declarations on a line must be separated by ';'}} expected-error{{expected declaration}} var v2 : Int } struct ErrorTypeInVarDecl16 { var v1 : FooProtocol & // expected-error {{expected identifier for type name}} var v2 : Int } func ErrorTypeInPattern4(_: FooProtocol & ) { } // expected-error {{expected identifier for type name}} struct ErrorGenericParameterList1< // expected-error {{expected an identifier to name generic parameter}} expected-error {{expected '{' in struct}} struct ErrorGenericParameterList2<T // expected-error {{expected '>' to complete generic parameter list}} expected-note {{to match this opening '<'}} expected-error {{expected '{' in struct}} struct ErrorGenericParameterList3<T, // expected-error {{expected an identifier to name generic parameter}} expected-error {{expected '{' in struct}} // Note: Don't move braces to a different line here. struct ErrorGenericParameterList4< // expected-error {{expected an identifier to name generic parameter}} { } // Note: Don't move braces to a different line here. struct ErrorGenericParameterList5<T // expected-error {{expected '>' to complete generic parameter list}} expected-note {{to match this opening '<'}} { } // Note: Don't move braces to a different line here. struct ErrorGenericParameterList6<T, // expected-error {{expected an identifier to name generic parameter}} { } struct ErrorTypeInVarDeclFunctionType1 { var v1 : () -> // expected-error {{expected type for function result}} var v2 : Int } struct ErrorTypeInVarDeclArrayType1 { // expected-note{{in declaration of 'ErrorTypeInVarDeclArrayType1'}} var v1 : Int[+] // expected-error {{expected declaration}} expected-error {{consecutive declarations on a line must be separated by ';'}} // expected-error @-1 {{expected expression after unary operator}} // expected-error @-2 {{expected expression}} var v2 : Int } struct ErrorTypeInVarDeclArrayType2 { var v1 : Int[+ // expected-error {{unary operator cannot be separated from its operand}} var v2 : Int // expected-error {{expected expression}} } struct ErrorTypeInVarDeclArrayType3 { var v1 : Int[ ; // expected-error {{expected expression}} var v2 : Int } struct ErrorTypeInVarDeclArrayType4 { var v1 : Int[1 // expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}} } struct ErrorInFunctionSignatureResultArrayType1 { func foo() -> Int[ { // expected-error {{expected '{' in body of function declaration}} return [0] } } struct ErrorInFunctionSignatureResultArrayType2 { func foo() -> Int[0 { // expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}} return [0] // expected-error {{cannot convert return expression of type '[Int]' to return type 'Int'}} } } struct ErrorInFunctionSignatureResultArrayType3 { func foo() -> Int[0] { // expected-error {{array types are now written with the brackets around the element type}} {{17-17=[}} {{20-21=}} return [0] } } struct ErrorInFunctionSignatureResultArrayType4 { func foo() -> Int[0_1] { // expected-error {{array types are now written with the brackets around the element type}} {{17-17=[}} {{20-21=}} return [0] } } struct ErrorInFunctionSignatureResultArrayType5 { func foo() -> Int[0b1] { // expected-error {{array types are now written with the brackets around the element type}} {{17-17=[}} {{20-21=}} return [0] } } struct ErrorInFunctionSignatureResultArrayType11 { // expected-note{{in declaration of 'ErrorInFunctionSignatureResultArrayType11'}} func foo() -> Int[(a){a++}] { // expected-error {{consecutive declarations on a line must be separated by ';'}} {{29-29=;}} expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}} expected-error {{use of unresolved operator '++'; did you mean '+= 1'?}} expected-error {{use of unresolved identifier 'a'}} expected-error {{expected declaration}} } } //===--- Recovery for missing initial value in var decls. struct MissingInitializer1 { var v1 : Int = // expected-error {{expected initial value after '='}} } //===--- Recovery for expr-postfix. func exprPostfix1(x : Int) { x. // expected-error {{expected member name following '.'}} } func exprPostfix2() { _ = .42 // expected-error {{'.42' is not a valid floating point literal; it must be written '0.42'}} {{7-7=0}} } //===--- Recovery for expr-super. class Base {} class ExprSuper1 { init() { super // expected-error {{expected '.' or '[' after 'super'}} } } class ExprSuper2 { init() { super. // expected-error {{expected member name following '.'}} } } //===--- Recovery for braces inside a nominal decl. struct BracesInsideNominalDecl1 { // expected-note{{in declaration of 'BracesInsideNominalDecl1'}} { // expected-error {{expected declaration}} aaa } typealias A = Int } func use_BracesInsideNominalDecl1() { // Ensure that the typealias decl is not skipped. var _ : BracesInsideNominalDecl1.A // no-error } class SR771 { // expected-note {{in declaration of 'SR771'}} print("No one else was in the room where it happened") // expected-error {{expected declaration}} } extension SR771 { // expected-note {{in extension of 'SR771'}} print("The room where it happened, the room where it happened") // expected-error {{expected declaration}} } //===--- Recovery for wrong decl introducer keyword. class WrongDeclIntroducerKeyword1 { // expected-note{{in declaration of 'WrongDeclIntroducerKeyword1'}} notAKeyword() {} // expected-error {{expected declaration}} func foo() {} class func bar() {} } //===--- Recovery for wrong inheritance clause. class Base2<T> { } class SubModule { class Base1 {} class Base2<T> {} } // expected-error@+1 {{expected ':' to begin inheritance clause}} {{30-31=: }} {{34-35=}} class WrongInheritanceClause1(Int) {} // expected-error@+1 {{expected ':' to begin inheritance clause}} {{30-31=: }} {{41-42=}} class WrongInheritanceClause2(Base2<Int>) {} // expected-error@+1 {{expected ':' to begin inheritance clause}} {{33-34=: }} {{49-50=}} class WrongInheritanceClause3<T>(SubModule.Base1) where T:AnyObject {} // expected-error@+1 {{expected ':' to begin inheritance clause}} {{30-31=: }} {{51-52=}} class WrongInheritanceClause4(SubModule.Base2<Int>) {} // expected-error@+1 {{expected ':' to begin inheritance clause}} {{33-34=: }} {{54-55=}} class WrongInheritanceClause5<T>(SubModule.Base2<Int>) where T:AnyObject {} // expected-error@+1 {{expected ':' to begin inheritance clause}} {{30-31=: }} class WrongInheritanceClause6(Int {} // expected-error@+1 {{expected ':' to begin inheritance clause}} {{33-34=: }} class WrongInheritanceClause7<T>(Int where T:AnyObject {} // <rdar://problem/18502220> [swift-crashes 078] parser crash on invalid cast in sequence expr Base=1 as Base=1 // expected-error {{cannot assign to immutable expression of type 'Base.Type'}} // <rdar://problem/18634543> Parser hangs at swift::Parser::parseType public enum TestA { // expected-error @+1{{expected '{' in body of function declaration}} public static func convertFromExtenndition( // expected-error {{expected parameter name followed by ':'}} // expected-error@+1{{expected parameter name followed by ':'}} s._core.count != 0, "Can't form a Character from an empty String") } public enum TestB { // expected-error@+1{{expected '{' in body of function declaration}} public static func convertFromExtenndition( // expected-error {{expected parameter name followed by ':'}} // expected-error@+1 {{expected parameter name followed by ':'}} s._core.count ?= 0, "Can't form a Character from an empty String") } // <rdar://problem/18634543> Infinite loop and unbounded memory consumption in parser class bar {} var baz: bar // expected-error@+1{{unnamed parameters must be written with the empty name '_'}} func foo1(bar!=baz) {} // expected-note {{did you mean 'foo1'?}} // expected-error@+1{{unnamed parameters must be written with the empty name '_'}} func foo2(bar! = baz) {}// expected-note {{did you mean 'foo2'?}} // rdar://19605567 // expected-error@+1{{use of unresolved identifier 'esp'; did you mean 'test'?}} switch esp { case let (jeb): // expected-error@+5{{top-level statement cannot begin with a closure expression}} // expected-error@+4{{closure expression is unused}} // expected-note@+3{{did you mean to use a 'do' statement?}} // expected-error@+2{{expected an identifier to name generic parameter}} // expected-error@+1{{expected '{' in class}} class Ceac<}> {} // expected-error@+1{{extraneous '}' at top level}} {{1-2=}} } #if true // rdar://19605164 // expected-error@+2{{use of undeclared type 'S'}} struct Foo19605164 { func a(s: S[{{g) -> Int {} // expected-error@+2 {{expected parameter name followed by ':'}} // expected-error@+1 {{expected ',' separator}} }}} #endif // rdar://19605567 // expected-error@+3{{expected '(' for initializer parameters}} // expected-error@+2{{initializers may only be declared within a type}} // expected-error@+1{{expected an identifier to name generic parameter}} func F() { init<( } )} // expected-note {{did you mean 'F'?}} struct InitializerWithName { init x() {} // expected-error {{initializers cannot have a name}} {{8-9=}} } struct InitializerWithNameAndParam { init a(b: Int) {} // expected-error {{initializers cannot have a name}} {{8-9=}} init? c(_ d: Int) {} // expected-error {{initializers cannot have a name}} {{9-10=}} init e<T>(f: T) {} // expected-error {{initializers cannot have a name}} {{8-9=}} init? g<T>(_: T) {} // expected-error {{initializers cannot have a name}} {{9-10=}} } struct InitializerWithLabels { init c d: Int {} // expected-error @-1 {{expected '(' for initializer parameters}} // expected-error @-2 {{expected declaration}} // expected-error @-3 {{consecutive declarations on a line must be separated by ';'}} // expected-note @-5 {{in declaration of 'InitializerWithLabels'}} } // rdar://20337695 func f1() { // expected-error @+6 {{use of unresolved identifier 'C'}} // expected-note @+5 {{did you mean 'n'?}} // expected-error @+4 {{unary operator cannot be separated from its operand}} {{11-12=}} // expected-error @+3 {{'==' is not a prefix unary operator}} // expected-error @+2 {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} // expected-error@+1 {{type annotation missing in pattern}} let n == C { get {} // expected-error {{use of unresolved identifier 'get'}} } } // <rdar://problem/20489838> QoI: Nonsensical error and fixit if "let" is missing between 'if let ... where' clauses func testMultiPatternConditionRecovery(x: Int?) { // expected-error@+1 {{expected ',' joining parts of a multi-clause condition}} {{15-21=,}} if let y = x where y == 0, let z = x { _ = y _ = z } if var y = x, y == 0, var z = x { z = y; y = z } if var y = x, z = x { // expected-error {{expected 'var' in conditional}} {{17-17=var }} z = y; y = z } // <rdar://problem/20883210> QoI: Following a "let" condition with boolean condition spouts nonsensical errors guard let x: Int? = 1, x == 1 else { } // expected-warning @-1 {{explicitly specified type 'Int?' adds an additional level of optional to the initializer, making the optional check always succeed}} {{16-20=Int}} } // rdar://20866942 func testRefutableLet() { var e : Int? let x? = e // expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} // expected-error @-1 {{expected expression}} // expected-error @-2 {{type annotation missing in pattern}} } // <rdar://problem/19833424> QoI: Bad error message when using Objective-C literals (@"Hello") in Swift files let myString = @"foo" // expected-error {{string literals in Swift are not preceded by an '@' sign}} {{16-17=}} // <rdar://problem/16990885> support curly quotes for string literals // expected-error @+1 {{unicode curly quote found, replace with '"'}} {{35-38="}} let curlyQuotes1 = “hello world!” // expected-error {{unicode curly quote found, replace with '"'}} {{20-23="}} // expected-error @+1 {{unicode curly quote found, replace with '"'}} {{20-23="}} let curlyQuotes2 = “hello world!" // <rdar://problem/21196171> compiler should recover better from "unicode Specials" characters let tryx = 123 // expected-error 2 {{invalid character in source file}} {{5-8= }} // <rdar://problem/21369926> Malformed Swift Enums crash playground service enum Rank: Int { // expected-error {{'Rank' declares raw type 'Int', but does not conform to RawRepresentable and conformance could not be synthesized}} case Ace = 1 case Two = 2.1 // expected-error {{cannot convert value of type 'Double' to raw type 'Int'}} } // rdar://22240342 - Crash in diagRecursivePropertyAccess class r22240342 { lazy var xx: Int = { foo { // expected-error {{use of unresolved identifier 'foo'}} let issueView = 42 issueView.delegate = 12 } return 42 }() } // <rdar://problem/22387625> QoI: Common errors: 'let x= 5' and 'let x =5' could use Fix-its func r22387625() { let _= 5 // expected-error{{'=' must have consistent whitespace on both sides}} {{8-8= }} let _ =5 // expected-error{{'=' must have consistent whitespace on both sides}} {{10-10= }} } // <https://bugs.swift.org/browse/SR-3135> func SR3135() { let _: Int= 5 // expected-error{{'=' must have consistent whitespace on both sides}} {{13-13= }} let _: Array<Int>= [] // expected-error{{'=' must have consistent whitespace on both sides}} {{20-20= }} } // <rdar://problem/23086402> Swift compiler crash in CSDiag protocol A23086402 { var b: B23086402 { get } } protocol B23086402 { var c: [String] { get } } func test23086402(a: A23086402) { print(a.b.c + "") // should not crash but: expected-error {{}} } // <rdar://problem/23550816> QoI: Poor diagnostic in argument list of "print" (varargs related) // The situation has changed. String now conforms to the RangeReplaceableCollection protocol // and `ss + s` becomes ambiguous. Diambiguation is provided with the unavailable overload // in order to produce a meaningful diagnostics. (Related: <rdar://problem/31763930>) func test23550816(ss: [String], s: String) { print(ss + s) // expected-error {{'+' is unavailable: Operator '+' cannot be used to append a String to a sequence of strings}} } // <rdar://problem/23719432> [practicalswift] Compiler crashes on &(Int:_) func test23719432() { var x = 42 &(Int:x) // expected-error {{use of extraneous '&'}} } // <rdar://problem/19911096> QoI: terrible recovery when using '·' for an operator infix operator · { // expected-error {{'·' is considered to be an identifier, not an operator}} associativity none precedence 150 } // <rdar://problem/21712891> Swift Compiler bug: String subscripts with range should require closing bracket. func r21712891(s : String) -> String { let a = s.startIndex..<s.startIndex _ = a // The specific errors produced don't actually matter, but we need to reject this. return "\(s[a)" // expected-error {{expected ']' in expression list}} expected-note {{to match this opening '['}} } // <rdar://problem/24029542> "Postfix '.' is reserved" error message" isn't helpful func postfixDot(a : String) { _ = a.utf8 _ = a. utf8 // expected-error {{extraneous whitespace after '.' is not permitted}} {{9-12=}} _ = a. // expected-error {{expected member name following '.'}} a. // expected-error {{expected member name following '.'}} } // <rdar://problem/22290244> QoI: "UIColor." gives two issues, should only give one func f() { _ = ClassWithStaticDecls. // expected-error {{expected member name following '.'}} }
apache-2.0
cf866b167979cd36880ba994b46e44db
39.091912
469
0.677824
3.970749
false
false
false
false
seem-sky/ios-charts
Charts/Classes/Renderers/ChartXAxisRenderer.swift
1
11272
// // ChartXAxisRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation public class ChartXAxisRenderer: ChartAxisRendererBase { internal var _xAxis: ChartXAxis!; public init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!) { super.init(viewPortHandler: viewPortHandler, transformer: transformer); _xAxis = xAxis; } public func computeAxis(#xValAverageLength: Float, xValues: [String]) { var a = ""; var max = Int(round(xValAverageLength + Float(_xAxis.spaceBetweenLabels))); for (var i = 0; i < max; i++) { a += "h"; } var widthText = a as NSString; var heightText = "Q" as NSString; _xAxis.labelWidth = widthText.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont]).width; _xAxis.labelHeight = _xAxis.labelFont.lineHeight; _xAxis.values = xValues; } public override func renderAxisLabels(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawLabelsEnabled) { return; } var yoffset = CGFloat(4.0); if (_xAxis.labelPosition == .Top) { drawLabels(context: context, pos: viewPortHandler.offsetTop - _xAxis.labelHeight - yoffset); } else if (_xAxis.labelPosition == .Bottom) { drawLabels(context: context, pos: viewPortHandler.contentBottom + yoffset * 1.5); } else if (_xAxis.labelPosition == .BottomInside) { drawLabels(context: context, pos: viewPortHandler.contentBottom - _xAxis.labelHeight - yoffset); } else if (_xAxis.labelPosition == .TopInside) { drawLabels(context: context, pos: viewPortHandler.offsetTop + yoffset); } else { // BOTH SIDED drawLabels(context: context, pos: viewPortHandler.offsetTop - _xAxis.labelHeight - yoffset); drawLabels(context: context, pos: viewPortHandler.contentBottom + yoffset * 1.6); } } private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()); public override func renderAxisLine(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawAxisLineEnabled) { return; } CGContextSaveGState(context); CGContextSetStrokeColorWithColor(context, _xAxis.axisLineColor.CGColor); CGContextSetLineWidth(context, _xAxis.axisLineWidth); if (_xAxis.axisLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.axisLineDashPhase, _xAxis.axisLineDashLengths, _xAxis.axisLineDashLengths.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } if (_xAxis.labelPosition == .Top || _xAxis.labelPosition == .TopInside || _xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft; _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop; _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight; _axisLineSegmentsBuffer[1].y = viewPortHandler.contentTop; CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2); } if (_xAxis.labelPosition == .Bottom || _xAxis.labelPosition == .BottomInside || _xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft; _axisLineSegmentsBuffer[0].y = viewPortHandler.contentBottom; _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight; _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom; CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2); } CGContextRestoreGState(context); } /// draws the x-labels on the specified y-position internal func drawLabels(#context: CGContext, pos: CGFloat) { var labelFont = _xAxis.labelFont; var labelTextColor = _xAxis.labelTextColor; var valueToPixelMatrix = transformer.valueToPixelMatrix; var position = CGPoint(x: 0.0, y: 0.0); var maxx = self._maxX; var minx = self._minX; if (maxx >= _xAxis.values.count) { maxx = _xAxis.values.count - 1; } if (minx < 0) { minx = 0; } for (var i = minx; i <= maxx; i += _xAxis.axisLabelModulus) { position.x = CGFloat(i); position.y = 0.0; position = CGPointApplyAffineTransform(position, valueToPixelMatrix); if (viewPortHandler.isInBoundsX(position.x)) { var label = _xAxis.values[i]; var labelns = label as NSString; if (_xAxis.isAvoidFirstLastClippingEnabled) { // avoid clipping of the last if (i == _xAxis.values.count - 1 && _xAxis.values.count > 1) { var width = labelns.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont]).width; if (width > viewPortHandler.offsetRight * 2.0 && position.x + width > viewPortHandler.chartWidth) { position.x -= width / 2.0; } } else if (i == 0) { // avoid clipping of the first var width = labelns.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont]).width; position.x += width / 2.0; } } ChartUtils.drawText(context: context, text: label, point: CGPoint(x: position.x, y: pos), align: .Center, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]); } } } private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()); public override func renderGridLines(#context: CGContext) { if (!_xAxis.isDrawGridLinesEnabled || !_xAxis.isEnabled) { return; } CGContextSaveGState(context); CGContextSetStrokeColorWithColor(context, _xAxis.gridColor.CGColor); CGContextSetLineWidth(context, _xAxis.gridLineWidth); if (_xAxis.gridLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.gridLineDashPhase, _xAxis.gridLineDashLengths, _xAxis.gridLineDashLengths.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } var valueToPixelMatrix = transformer.valueToPixelMatrix; var position = CGPoint(x: 0.0, y: 0.0); for (var i = _minX; i <= _maxX; i += _xAxis.axisLabelModulus) { position.x = CGFloat(i); position.y = 0.0; position = CGPointApplyAffineTransform(position, valueToPixelMatrix); if (position.x >= viewPortHandler.offsetLeft && position.x <= viewPortHandler.chartWidth) { _gridLineSegmentsBuffer[0].x = position.x; _gridLineSegmentsBuffer[0].y = viewPortHandler.contentTop; _gridLineSegmentsBuffer[1].x = position.x; _gridLineSegmentsBuffer[1].y = viewPortHandler.contentBottom; CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2); } } CGContextRestoreGState(context); } private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()); public override func renderLimitLines(#context: CGContext) { var limitLines = _xAxis.limitLines; if (limitLines.count == 0) { return; } CGContextSaveGState(context); var trans = transformer.valueToPixelMatrix; var position = CGPoint(x: 0.0, y: 0.0); for (var i = 0; i < limitLines.count; i++) { var l = limitLines[i]; position.x = CGFloat(l.limit); position.y = 0.0; position = CGPointApplyAffineTransform(position, trans); _limitLineSegmentsBuffer[0].x = position.x; _limitLineSegmentsBuffer[0].y = viewPortHandler.contentTop; _limitLineSegmentsBuffer[1].x = position.y; _limitLineSegmentsBuffer[1].y = viewPortHandler.contentBottom; CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor); CGContextSetLineWidth(context, l.lineWidth); if (l.lineDashLengths != nil) { CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2); var label = l.label; // if drawing the limit-value label is enabled if (label.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) > 0) { var labelLineHeight = l.valueFont.lineHeight; let add = CGFloat(4.0); var xOffset: CGFloat = l.lineWidth; var yOffset: CGFloat = add / 2.0; if (l.labelPosition == .Right) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]); } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentTop + yOffset), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]); } } } CGContextRestoreGState(context); } }
apache-2.0
1508faf0ee2d8789de78867d1c4ce876
35.482201
216
0.544624
5.605172
false
false
false
false
roop/GiveAndTake
Take/Take/Helpers/ObservationHelper.swift
1
2767
// // ObservationHelper.swift // Take // // Created by Roopesh Chander on 01/08/14. // Copyright (c) 2014 Roopesh Chander. All rights reserved. // import Foundation // Usage: // var observer1 = object.onChange("property") { change in // doSomethingWithChangeDict(change) // } // var observer2 = object.onNotification(NSMetadataQueryDidFinishGatheringNotification) { // notification in // doSomethingWithNotificationDict(notification.userInfo) // } // // Keep a strong reference to the returned observer objects // // as long as you want to observe said thingie. extension NSObject { func onChange(keyPath: String, options: NSKeyValueObservingOptions, _ block: (change: [NSObject : AnyObject]!) -> ()) -> AnyObject { return KeyValueObserver(object: self, keyPath: keyPath, options: options, block: block) as AnyObject } func onChange(keyPath: String, _ block: (change: [NSObject : AnyObject]!) -> ()) -> AnyObject { return KeyValueObserver(object: self, keyPath: keyPath, options: nil, block: block) as AnyObject } func onNotification(name: String, _ block: ((NSNotification!) -> ())) -> AnyObject { return NotificationObserver(object: self, name: name, queue: NSOperationQueue.currentQueue(), block: block) as AnyObject } } class KeyValueObserver: NSObject { weak var _object: NSObject? var _keyPath: String var _block: (change: [NSObject : AnyObject]!) -> () init(object: NSObject, keyPath: String, options: NSKeyValueObservingOptions, block: (change: [NSObject : AnyObject]!) -> ()) { _object = object _keyPath = keyPath _block = block super.init() object.addObserver(self, forKeyPath: keyPath, options: options, context: nil) } override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<()>) { assert(keyPath == _keyPath) _block(change: change) } deinit { _object?.removeObserver(self, forKeyPath: _keyPath, context: nil) } } class NotificationObserver: NSObject { var _observerObject: AnyObject? init(object: NSObject, name: String!, queue: NSOperationQueue!, block: ((NSNotification!) -> ())) { super.init() _observerObject = NSNotificationCenter.defaultCenter().addObserverForName(name, object: object, queue: queue, usingBlock: block) } deinit { if let observer: AnyObject = _observerObject { NSNotificationCenter.defaultCenter().removeObserver(observer) } } }
mit
f5c3f9d1347851389b99d8ed2dae5018
29.076087
115
0.634622
4.697793
false
false
false
false
ernieb4768/VelocityCBT
CBT Velocity/AppDelegate.swift
1
6229
// // AppDelegate.swift // CBT Velocity // // Created by Ryan Hoffman on 3/20/16. // Copyright © 2016 Ryan Hoffman. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("json_table_view_images", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("json_table_view_images.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch var error1 as NSError { error = error1 coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } catch { fatalError() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges { do { try moc.save() } catch let error1 as NSError { error = error1 // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } } }
apache-2.0
74f1745a507f57ebc8cd5f66f9a0f8e5
51.344538
290
0.69332
5.847887
false
false
false
false
SeriousChoice/SCSwift
Example/Pods/RxSwift/RxSwift/Traits/Infallible/Infallible+Operators.swift
1
34639
// // Infallible+Operators.swift // RxSwift // // Created by Shai Mishali on 27/08/2020. // Copyright © 2020 Krunoslav Zaher. All rights reserved. // // MARK: - Static allocation extension InfallibleType { /** Returns an infallible sequence that contains a single element. - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) - parameter element: Single element in the resulting infallible sequence. - returns: An infallible sequence containing the single specified element. */ public static func just(_ element: Element) -> Infallible<Element> { Infallible(.just(element)) } /** Returns an infallible sequence that contains a single element. - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) - parameter element: Single element in the resulting infallible sequence. - parameter scheduler: Scheduler to send the single element on. - returns: An infallible sequence containing the single specified element. */ public static func just(_ element: Element, scheduler: ImmediateSchedulerType) -> Infallible<Element> { Infallible(.just(element, scheduler: scheduler)) } /** Returns a non-terminating infallible sequence, which can be used to denote an infinite duration. - seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) - returns: An infallible sequence whose observers will never get called. */ public static func never() -> Infallible<Element> { Infallible(.never()) } /** Returns an empty infallible sequence, using the specified scheduler to send out the single `Completed` message. - seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) - returns: An infallible sequence with no elements. */ public static func empty() -> Infallible<Element> { Infallible(.empty()) } /** Returns an infallible sequence that invokes the specified factory function whenever a new observer subscribes. - seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html) - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. */ public static func deferred(_ observableFactory: @escaping () throws -> Infallible<Element>) -> Infallible<Element> { Infallible(.deferred { try observableFactory().asObservable() }) } } // MARK: From & Of extension Infallible { /** This method creates a new Infallible instance with a variable number of elements. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - parameter elements: Elements to generate. - parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediately on subscription. - returns: The Infallible sequence whose elements are pulled from the given arguments. */ public static func of(_ elements: Element ..., scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Infallible<Element> { Infallible(Observable.from(elements, scheduler: scheduler)) } } extension Infallible { /** Converts an array to an Infallible sequence. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - returns: The Infallible sequence whose elements are pulled from the given enumerable sequence. */ public static func from(_ array: [Element], scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Infallible<Element> { Infallible(Observable.from(array, scheduler: scheduler)) } /** Converts a sequence to an Infallible sequence. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - returns: The Infallible sequence whose elements are pulled from the given enumerable sequence. */ public static func from<Sequence: Swift.Sequence>(_ sequence: Sequence, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Infallible<Element> where Sequence.Element == Element { Infallible(Observable.from(sequence, scheduler: scheduler)) } } // MARK: - Filter extension InfallibleType { /** Filters the elements of an observable sequence based on a predicate. - seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html) - parameter predicate: A function to test each source element for a condition. - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. */ public func filter(_ predicate: @escaping (Element) -> Bool) -> Infallible<Element> { Infallible(asObservable().filter(predicate)) } } // MARK: - Map extension InfallibleType { /** Projects each element of an observable sequence into a new form. - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) - parameter transform: A transform function to apply to each source element. - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. */ public func map<Result>(_ transform: @escaping (Element) -> Result) -> Infallible<Result> { Infallible(asObservable().map(transform)) } /** Projects each element of an observable sequence into an optional form and filters all optional results. - parameter transform: A transform function to apply to each source element and which returns an element or nil. - returns: An observable sequence whose elements are the result of filtering the transform function for each element of the source. */ public func compactMap<Result>(_ transform: @escaping (Element) -> Result?) -> Infallible<Result> { Infallible(asObservable().compactMap(transform)) } } // MARK: - Distinct extension InfallibleType where Element: Comparable { /** Returns an observable sequence that contains only distinct contiguous elements according to equality operator. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence. */ public func distinctUntilChanged() -> Infallible<Element> { Infallible(asObservable().distinctUntilChanged()) } } extension InfallibleType { /** Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) - parameter keySelector: A function to compute the comparison key for each element. - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ public func distinctUntilChanged<Key: Equatable>(_ keySelector: @escaping (Element) throws -> Key) -> Infallible<Element> { Infallible(self.asObservable().distinctUntilChanged(keySelector, comparer: { $0 == $1 })) } /** Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) - parameter comparer: Equality comparer for computed key values. - returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence. */ public func distinctUntilChanged(_ comparer: @escaping (Element, Element) throws -> Bool) -> Infallible<Element> { Infallible(self.asObservable().distinctUntilChanged({ $0 }, comparer: comparer)) } /** Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) - parameter keySelector: A function to compute the comparison key for each element. - parameter comparer: Equality comparer for computed key values. - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence. */ public func distinctUntilChanged<K>(_ keySelector: @escaping (Element) throws -> K, comparer: @escaping (K, K) throws -> Bool) -> Infallible<Element> { Infallible(asObservable().distinctUntilChanged(keySelector, comparer: comparer)) } /** Returns an observable sequence that contains only contiguous elements with distinct values in the provided key path on each object. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator on the provided key path */ public func distinctUntilChanged<Property: Equatable>(at keyPath: KeyPath<Element, Property>) -> Infallible<Element> { Infallible(asObservable().distinctUntilChanged { $0[keyPath: keyPath] == $1[keyPath: keyPath] }) } } // MARK: - Throttle extension InfallibleType { /** Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) - parameter dueTime: Throttling duration for each element. - parameter scheduler: Scheduler to run the throttle timers on. - returns: The throttled sequence. */ public func debounce(_ dueTime: RxTimeInterval, scheduler: SchedulerType) -> Infallible<Element> { Infallible(asObservable().debounce(dueTime, scheduler: scheduler)) } /** Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration. This operator makes sure that no two elements are emitted in less then dueTime. - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) - parameter dueTime: Throttling duration for each element. - parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted. - parameter scheduler: Scheduler to run the throttle timers on. - returns: The throttled sequence. */ public func throttle(_ dueTime: RxTimeInterval, latest: Bool = true, scheduler: SchedulerType) -> Infallible<Element> { Infallible(asObservable().throttle(dueTime, latest: latest, scheduler: scheduler)) } } // MARK: - FlatMap extension InfallibleType { /** Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) - parameter selector: A transform function to apply to each element. - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. */ public func flatMap<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source) -> Infallible<Source.Element> { Infallible(asObservable().flatMap(selector)) } /** Projects each element of an observable sequence into a new sequence of observable sequences and then transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. It is a combination of `map` + `switchLatest` operator - seealso: [flatMapLatest operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) - parameter selector: A transform function to apply to each element. - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ public func flatMapLatest<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source) -> Infallible<Source.Element> { Infallible(asObservable().flatMapLatest(selector)) } /** Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. If element is received while there is some projected observable sequence being merged it will simply be ignored. - seealso: [flatMapFirst operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) - parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel. - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated. */ public func flatMapFirst<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source) -> Infallible<Source.Element> { Infallible(asObservable().flatMapFirst(selector)) } } // MARK: - Concat extension InfallibleType { /** Concatenates the second observable sequence to `self` upon successful termination of `self`. - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - parameter second: Second observable sequence. - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. */ public func concat<Source: ObservableConvertibleType>(_ second: Source) -> Infallible<Element> where Source.Element == Element { Infallible(Observable.concat([self.asObservable(), second.asObservable()])) } /** Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. This operator has tail recursive optimizations that will prevent stack overflow. Optimizations will be performed in cases equivalent to following: [1, [2, [3, .....].concat()].concat].concat() - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - returns: An observable sequence that contains the elements of each given sequence, in sequential order. */ public static func concat<Sequence: Swift.Sequence>(_ sequence: Sequence) -> Infallible<Element> where Sequence.Element == Infallible<Element> { Infallible(Observable.concat(sequence.map { $0.asObservable() })) } /** Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. This operator has tail recursive optimizations that will prevent stack overflow. Optimizations will be performed in cases equivalent to following: [1, [2, [3, .....].concat()].concat].concat() - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - returns: An observable sequence that contains the elements of each given sequence, in sequential order. */ public static func concat<Collection: Swift.Collection>(_ collection: Collection) -> Infallible<Element> where Collection.Element == Infallible<Element> { Infallible(Observable.concat(collection.map { $0.asObservable() })) } /** Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. This operator has tail recursive optimizations that will prevent stack overflow. Optimizations will be performed in cases equivalent to following: [1, [2, [3, .....].concat()].concat].concat() - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - returns: An observable sequence that contains the elements of each given sequence, in sequential order. */ public static func concat(_ sources: Infallible<Element> ...) -> Infallible<Element> { Infallible(Observable.concat(sources.map { $0.asObservable() })) } /** Projects each element of an observable sequence to an observable sequence and concatenates the resulting observable sequences into one observable sequence. - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ public func concatMap<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source) -> Infallible<Source.Element> { Infallible(asObservable().concatMap(selector)) } } // MARK: - Merge extension InfallibleType { /** Merges elements from all observable sequences from collection into a single observable sequence. - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) - parameter sources: Collection of observable sequences to merge. - returns: The observable sequence that merges the elements of the observable sequences. */ public static func merge<Collection: Swift.Collection>(_ sources: Collection) -> Infallible<Element> where Collection.Element == Infallible<Element> { Infallible(Observable.concat(sources.map { $0.asObservable() })) } /** Merges elements from all infallible sequences from array into a single infallible sequence. - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) - parameter sources: Array of infallible sequences to merge. - returns: The infallible sequence that merges the elements of the infallible sequences. */ public static func merge(_ sources: [Infallible<Element>]) -> Infallible<Element> { Infallible(Observable.merge(sources.map { $0.asObservable() })) } /** Merges elements from all infallible sequences into a single infallible sequence. - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) - parameter sources: Collection of infallible sequences to merge. - returns: The infallible sequence that merges the elements of the infallible sequences. */ public static func merge(_ sources: Infallible<Element>...) -> Infallible<Element> { Infallible(Observable.merge(sources.map { $0.asObservable() })) } } // MARK: - Do extension Infallible { /** Invokes an action for each event in the infallible sequence, and propagates all observer messages through the result sequence. - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) - parameter onNext: Action to invoke for each element in the observable sequence. - parameter afterNext: Action to invoke for each element after the observable has passed an onNext event along to its downstream. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. - parameter afterCompleted: Action to invoke after graceful termination of the observable sequence. - parameter onSubscribe: Action to invoke before subscribing to source observable sequence. - parameter onSubscribed: Action to invoke after subscribing to source observable sequence. - parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed. - returns: The source sequence with the side-effecting behavior applied. */ public func `do`(onNext: ((Element) throws -> Void)? = nil, afterNext: ((Element) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, afterCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil) -> Infallible<Element> { Infallible(asObservable().do(onNext: onNext, afterNext: afterNext, onCompleted: onCompleted, afterCompleted: afterCompleted, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose)) } } // MARK: - Scan extension InfallibleType { /** Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. For aggregation behavior with no intermediate results, see `reduce`. - seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html) - parameter seed: The initial accumulator value. - parameter accumulator: An accumulator function to be invoked on each element. - returns: An observable sequence containing the accumulated values. */ public func scan<Seed>(into seed: Seed, accumulator: @escaping (inout Seed, Element) -> Void) -> Infallible<Seed> { Infallible(asObservable().scan(into: seed, accumulator: accumulator)) } /** Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. For aggregation behavior with no intermediate results, see `reduce`. - seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html) - parameter seed: The initial accumulator value. - parameter accumulator: An accumulator function to be invoked on each element. - returns: An observable sequence containing the accumulated values. */ public func scan<Seed>(_ seed: Seed, accumulator: @escaping (Seed, Element) -> Seed) -> Infallible<Seed> { Infallible(asObservable().scan(seed, accumulator: accumulator)) } } // MARK: - Start with extension InfallibleType { /** Prepends a value to an observable sequence. - seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html) - parameter element: Element to prepend to the specified sequence. - returns: The source sequence prepended with the specified values. */ public func startWith(_ element: Element) -> Infallible<Element> { Infallible(asObservable().startWith(element)) } } // MARK: - Take and Skip { extension InfallibleType { /** Returns the elements from the source observable sequence until the other observable sequence produces an element. - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) - parameter other: Observable sequence that terminates propagation of elements of the source sequence. - returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ public func take<Source: InfallibleType>(until other: Source) -> Infallible<Element> { Infallible(asObservable().take(until: other.asObservable())) } /** Returns the elements from the source observable sequence until the other observable sequence produces an element. - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) - parameter other: Observable sequence that terminates propagation of elements of the source sequence. - returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ public func take<Source: ObservableType>(until other: Source) -> Infallible<Element> { Infallible(asObservable().take(until: other)) } /** Returns elements from an observable sequence until the specified condition is true. - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) - parameter predicate: A function to test each element for a condition. - parameter behavior: Whether or not to include the last element matching the predicate. Defaults to `exclusive`. - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test passes. */ public func take(until predicate: @escaping (Element) throws -> Bool, behavior: TakeBehavior = .exclusive) -> Infallible<Element> { Infallible(asObservable().take(until: predicate, behavior: behavior)) } /** Returns elements from an observable sequence as long as a specified condition is true. - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) - parameter predicate: A function to test each element for a condition. - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ public func take(while predicate: @escaping (Element) throws -> Bool, behavior: TakeBehavior = .exclusive) -> Infallible<Element> { Infallible(asObservable().take(while: predicate, behavior: behavior)) } /** Returns a specified number of contiguous elements from the start of an observable sequence. - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) - parameter count: The number of elements to return. - returns: An observable sequence that contains the specified number of elements from the start of the input sequence. */ public func take(_ count: Int) -> Infallible<Element> { Infallible(asObservable().take(count)) } /** Takes elements for the specified duration from the start of the infallible source sequence, using the specified scheduler to run timers. - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) - parameter duration: Duration for taking elements from the start of the sequence. - parameter scheduler: Scheduler to run the timer on. - returns: An infallible sequence with the elements taken during the specified duration from the start of the source sequence. */ public func take(for duration: RxTimeInterval, scheduler: SchedulerType) -> Infallible<Element> { Infallible(asObservable().take(for: duration, scheduler: scheduler)) } /** Bypasses elements in an infallible sequence as long as a specified condition is true and then returns the remaining elements. - seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html) - parameter predicate: A function to test each element for a condition. - returns: An infallible sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ public func skip(while predicate: @escaping (Element) throws -> Bool) -> Infallible<Element> { Infallible(asObservable().skip(while: predicate)) } /** Returns the elements from the source infallible sequence that are emitted after the other infallible sequence produces an element. - seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html) - parameter other: Infallible sequence that starts propagation of elements of the source sequence. - returns: An infallible sequence containing the elements of the source sequence that are emitted after the other sequence emits an item. */ public func skip<Source: ObservableType>(until other: Source) -> Infallible<Element> { Infallible(asObservable().skip(until: other)) } } // MARK: - Share extension InfallibleType { /** Returns an observable sequence that **shares a single subscription to the underlying sequence**, and immediately upon subscription replays elements in buffer. This operator is equivalent to: * `.whileConnected` ``` // Each connection will have it's own subject instance to store replay events. // Connections will be isolated from each another. source.multicast(makeSubject: { Replay.create(bufferSize: replay) }).refCount() ``` * `.forever` ``` // One subject will store replay events for all connections to source. // Connections won't be isolated from each another. source.multicast(Replay.create(bufferSize: replay)).refCount() ``` It uses optimized versions of the operators for most common operations. - parameter replay: Maximum element count of the replay buffer. - parameter scope: Lifetime scope of sharing subject. For more information see `SubjectLifetimeScope` enum. - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ public func share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected) -> Infallible<Element> { Infallible(asObservable().share(replay: replay, scope: scope)) } } // MARK: - withUnretained extension InfallibleType { /** Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence. In the case the provided object cannot be retained successfully, the sequence will complete. - note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle. - parameter obj: The object to provide an unretained reference on. - parameter resultSelector: A function to combine the unretained referenced on `obj` and the value of the observable sequence. - returns: An observable sequence that contains the result of `resultSelector` being called with an unretained reference on `obj` and the values of the original sequence. */ public func withUnretained<Object: AnyObject, Out>( _ obj: Object, resultSelector: @escaping (Object, Element) -> Out ) -> Infallible<Out> { Infallible(self.asObservable().withUnretained(obj, resultSelector: resultSelector)) } /** Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence. In the case the provided object cannot be retained successfully, the sequence will complete. - note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle. - parameter obj: The object to provide an unretained reference on. - returns: An observable sequence of tuples that contains both an unretained reference on `obj` and the values of the original sequence. */ public func withUnretained<Object: AnyObject>(_ obj: Object) -> Infallible<(Object, Element)> { withUnretained(obj) { ($0, $1) } } } extension InfallibleType { // MARK: - withLatestFrom /** Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any. - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) - note: Elements emitted by self before the second source has emitted any values will be omitted. - parameter second: Second observable source. - parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any. - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. */ public func withLatestFrom<Source: InfallibleType, ResultType>(_ second: Source, resultSelector: @escaping (Element, Source.Element) throws -> ResultType) -> Infallible<ResultType> { Infallible(self.asObservable().withLatestFrom(second.asObservable(), resultSelector: resultSelector)) } /** Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emits an element. - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) - note: Elements emitted by self before the second source has emitted any values will be omitted. - parameter second: Second observable source. - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. */ public func withLatestFrom<Source: InfallibleType>(_ second: Source) -> Infallible<Source.Element> { withLatestFrom(second) { $1 } } }
mit
dd360c6ceb800bc18b32344bf62c473b
47.7173
320
0.725359
5.118664
false
false
false
false
biohazardlover/ROer
Roer/MapViewerViewController.swift
1
7196
import UIKit import GLKit import MBProgressHUD import SwiftyJSON class MapViewerViewController: UIViewController { fileprivate var mapView: GLKView! @IBOutlet var panGestureRecognizer: UIPanGestureRecognizer! @IBOutlet var twoFingersPanGestureRecognizer: UIPanGestureRecognizer! @IBOutlet var pinchGestureRecognizer: UIPinchGestureRecognizer! @IBOutlet var rotationGestureRecognizer: UIRotationGestureRecognizer! fileprivate var panStartTranslation: (x: Float, y: Float) = (0, 0) fileprivate var pinchStartScale: Float = 0 fileprivate var rotationStartRotation: Float = 0 @IBOutlet var mapListView: UITableView! fileprivate var hud: MBProgressHUD? fileprivate var mapList: JSON { let url = Bundle.main.url(forResource: "MapList", withExtension: "json")! let data = try! Data(contentsOf: url) return JSON(data: data) } fileprivate var renderer: MapRenderer! override func viewDidLoad() { super.viewDidLoad() title = "MapViewer".localized var context = EAGLContext(api: .openGLES3) if context == nil { context = EAGLContext(api: .openGLES2) } mapView = GLKView(frame: view.bounds, context: context!) mapView.addGestureRecognizer(panGestureRecognizer) mapView.addGestureRecognizer(twoFingersPanGestureRecognizer) mapView.addGestureRecognizer(pinchGestureRecognizer) mapView.addGestureRecognizer(rotationGestureRecognizer) EAGLContext.setCurrent(context) let displayLink = CADisplayLink(target: self, selector: #selector(render(_:))) displayLink.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode) view.addSubview(mapView) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if renderer == nil { renderer = MapRenderer(context: EAGLContext.current()!, size: mapView.bounds.size) renderer.delegate = self mapView.delegate = renderer } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() mapView.frame = UIEdgeInsetsInsetRect(view.bounds, UIEdgeInsets(top: 0, left: 0, bottom: 150, right: 0)) } } extension MapViewerViewController { @objc func render(_ displayLink: CADisplayLink) { mapView.setNeedsDisplay() } } extension MapViewerViewController { @IBAction func handlePan(_ sender: AnyObject) { switch panGestureRecognizer.state { case .began: panStartTranslation = renderer.translation case .changed: let translation = panGestureRecognizer.translation(in: mapView) renderer.translation.x = panStartTranslation.x + Float(translation.x) * 0.001 renderer.translation.y = panStartTranslation.y + Float(translation.y) * -0.001 renderer.updateModelView() mapView.setNeedsDisplay() default: break } } @IBAction func handleTwoFingersPan(_ sender: AnyObject) { switch twoFingersPanGestureRecognizer.state { case .changed: if twoFingersPanGestureRecognizer.location(in: mapView).y > 0 { renderer.angle += 1 if renderer.angle > 90 { renderer.angle = 90 } } else { renderer.angle -= 1 if renderer.angle < 5 { renderer.angle = 5 } } renderer.updateModelView() mapView.setNeedsDisplay() default: break } } @IBAction func handlePinch(_ sender: AnyObject) { switch pinchGestureRecognizer.state { case .began: pinchStartScale = renderer.zoom renderer.zoom = pinchStartScale * Float(pinchGestureRecognizer.scale) renderer.updateModelView() mapView.setNeedsDisplay() case .changed: renderer.zoom = pinchStartScale * Float(pinchGestureRecognizer.scale) renderer.updateModelView() mapView.setNeedsDisplay() default: break } } @IBAction func handleRotation(_ sender: AnyObject) { switch rotationGestureRecognizer.state { case .began: rotationStartRotation = renderer.rotate renderer.rotate = rotationStartRotation + GLKMathRadiansToDegrees(Float(-rotationGestureRecognizer.rotation)) renderer.updateModelView() mapView.setNeedsDisplay() case .changed: renderer.rotate = rotationStartRotation + GLKMathRadiansToDegrees(Float(-rotationGestureRecognizer.rotation)) renderer.updateModelView() mapView.setNeedsDisplay() default: break } } } extension MapViewerViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mapList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MapListCell", for: indexPath) cell.textLabel?.text = mapList[indexPath.row].arrayValue[1].stringValue return cell } } extension MapViewerViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let mapName = mapList[indexPath.row].arrayValue[0].stringValue let downloader = MapDownloader(mapName: mapName) downloader.delegate = self downloader.download() } } extension MapViewerViewController: MapDownloaderDelegate { func mapDownloaderDidStartDownloading(_ mapDownloader: MapDownloader) { hud = MBProgressHUD.showAdded(to: view, animated: true) hud?.mode = .indeterminate hud?.removeFromSuperViewOnHide = true hud?.minShowTime = 0.5 } func mapDownloader(_ mapDownloader: MapDownloader, completedUnitCount: Int, totalUnitCount: Int) { hud?.mode = .determinateHorizontalBar hud?.progress = Float(completedUnitCount) / Float(totalUnitCount) hud?.label.text = "\(completedUnitCount) / \(totalUnitCount)" } func mapDownloaderDidFinishDownloading(_ mapDownloader: MapDownloader) { hud?.hide(animated: true) guard let indexPath = mapListView.indexPathForSelectedRow else { return } let mapName = mapList[indexPath.row].arrayValue[0].stringValue renderer.loadRsw(mapName) } } extension MapViewerViewController: MapRendererDelegate { func mapRendererDidStartRendering(_ mapRenderer: MapRenderer) { hud = MBProgressHUD.showAdded(to: view, animated: true) hud?.mode = .indeterminate hud?.removeFromSuperViewOnHide = true } func mapRendererDidFinishRendering(_ mapRenderer: MapRenderer) { hud?.hide(animated: true) mapView.setNeedsDisplay() } }
mit
5e6c0f7e9181103b0283566a9f3c6648
33.266667
121
0.650639
5.595645
false
false
false
false
marekmatula/FontIcons.Swift
Pod/Classes/Extensions.swift
1
4898
// // Extensions.swift // FontIcons.swift // // Created by Marek Matula on 05.02.16. // Copyright © 2016 Marek Matula. All rights reserved. // import Foundation import UIKit public let defaultFontIconSize:CGFloat = 23.0 public extension UIBarButtonItem { func setFontIcon(_ icon: FontEnum, size: CGFloat = defaultFontIconSize) { setFontIconText(prefix: "", icon: icon, postfix: "", size: size) } func setFontIconText(prefix: String, icon: FontEnum, postfix: String, size: CGFloat) { let font = FontLoader.getFont(icon, iconSize: size) setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal) setTitleTextAttributes([NSAttributedString.Key.font: font], for: .highlighted) setTitleTextAttributes([NSAttributedString.Key.font: font], for: .disabled) #if giOS8OrGreater setTitleTextAttributes([NSFontAttributeName: font], for: .focused) #endif title = FontLoader.concat(prefix: prefix, icon: icon, postfix: postfix) } } public extension UIButton { func setFontIcon(_ icon: FontEnum, forState: UIControl.State) { if let label = titleLabel { setFontIcon(icon, size: label.font.pointSize, forState: forState) } } func setFontIcon(_ icon: FontEnum, size:CGFloat, forState: UIControl.State) { setFontIconText(prefix: "", icon: icon, postfix: "", size: size, forState: forState) } func setFontIconText(prefix: String, icon: FontEnum, postfix: String, size: CGFloat, forState: UIControl.State) { let font = FontLoader.getFont(icon, iconSize: size) if let label = titleLabel { label.font = font let text = FontLoader.concat(prefix: prefix, icon: icon, postfix: postfix) setTitle(text, for: forState) } } } public extension UILabel { func setFontIcon(_ icon: FontEnum, size: CGFloat = defaultFontIconSize) { setFontIconText(prefix: "", icon: icon, postfix: "", size: size) } func setFontIconText(prefix: String, icon: FontEnum, postfix: String, size: CGFloat) { let font = FontLoader.getFont(icon, iconSize: size) self.font = font self.text = FontLoader.concat(prefix: prefix, icon: icon, postfix: postfix) } } public extension UIImageView { public func setFontIcon(_ icon: FontEnum, textColor: UIColor, backgroundColor: UIColor = UIColor.clear) { self.image = UIImage(icon: icon, size: frame.size, textColor: textColor, backgroundColor: backgroundColor) } } public extension UITabBarItem { public func setFontIcon(_ icon: FontEnum) { image = UIImage(icon: icon, size: CGSize(width: 30, height: 30)) } } public extension UISegmentedControl { public func setFontIcon(_ icon: FontEnum, forSegmentAtIndex segment: Int) { let font = FontLoader.getFont(icon, iconSize: defaultFontIconSize) setTitleTextAttributes([NSAttributedString.Key.font: font], for: UIControl.State()) setTitle(icon.unicode(), forSegmentAt: segment) } } public extension UIImage { public convenience init(icon: FontEnum, size: CGSize, textColor: UIColor = UIColor.black, backgroundColor: UIColor = UIColor.clear) { let paragraph = NSMutableParagraphStyle() paragraph.alignment = NSTextAlignment.center // Taken from FontAwesome.io's Fixed Width Icon CSS let fontAspectRatio: CGFloat = 1.28571429 let fontSize = min(size.width / fontAspectRatio, size.height) let font = FontLoader.getFont(icon, iconSize: fontSize) let attributes = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: textColor, NSAttributedString.Key.backgroundColor: backgroundColor, NSAttributedString.Key.paragraphStyle: paragraph] let attributedString = NSAttributedString(string: icon.unicode(), attributes: attributes) UIGraphicsBeginImageContextWithOptions(size, false , 0.0) attributedString.draw(in: CGRect(x: 0, y: (size.height - fontSize) / 2, width: size.width, height: fontSize)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.init(cgImage: image!.cgImage!, scale: image!.scale, orientation: image!.imageOrientation) } } public extension UISlider { func setFontIconMaximumValueImage(_ icon: FontEnum, customSize: CGSize? = nil) { maximumValueImage = UIImage(icon: icon, size: customSize ?? CGSize(width: 25, height: 25)) } func setFontIconMinimumValueImage(_ icon: FontEnum, customSize: CGSize? = nil) { minimumValueImage = UIImage(icon: icon, size: customSize ?? CGSize(width: 25, height: 25)) } }
mit
73ce335a81616e6376c078ec1ece82c5
34.744526
218
0.665714
4.754369
false
false
false
false
WebAPIKit/WebAPIKit
Tests/WebAPIKitTests/Stub/StubResponder+PathTemplateSpec.swift
1
3092
/** * WebAPIKit * * Copyright (c) 2017 Evan Liu. Licensed under the MIT license, as follows: * * 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 import Alamofire import Quick import Nimble import WebAPIKit class StubResponderPathTemplateSpec: QuickSpec { override func spec() { let provider = StubProvider() var client: StubHTTPClient! beforeEach { client = StubHTTPClient(provider: provider) } it("match path template") { let stub = client.stub(template: "/users/{id}") expect(stub.match(provider.request(path: "/users/1"))) == true expect(stub.match(provider.request(path: "/users"))) == false expect(stub.match(provider.request(path: "/repos/1"))) == false let postStub = client.stub(template: "/users/{id}", method: .post) expect(postStub.match(provider.request(path: "/users/1"))) == false expect(postStub.match(provider.request(path: "/users/1", method: .put))) == false expect(postStub.match(provider.request(path: "/users/1", method: .post))) == true } it("respond with path template variables") { var result: [String: String]? client.stub(template: "/users/{id}").withTemplatedJSON { ["userID": $0["id"] ?? ""] } client.send(provider.request(path: "/users/1"), queue: nil) { data, _, _ in if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) { result = json as? [String: String] } } expect(result?["userID"]) == "1" } } } private final class StubProvider: WebAPIProvider { let baseURL = URL(string: "http://test.stub/api/v1")! func request(path: String, method: HTTPMethod = .get) -> URLRequest { let url = baseURL.appendingPathComponent(path) var request = URLRequest(url: url) request.httpMethod = method.rawValue return request } }
mit
19e7d1169a5d0b47057a0b4eb6a0498f
39.684211
107
0.649094
4.247253
false
false
false
false
silence0201/Swift-Study
SwiftLearn/MySwift19_Type_casting.playground/Contents.swift
1
5060
//: Playground - noun: a place where people can play import UIKit //Swift运行时的类型检查 is, 类与类之间的类型转换 as. class MediaItem{ var name: String init(name: String){ self.name = name } } class Movie: MediaItem{ var genre: String //类型 init(name: String, genre: String){ self.genre = genre super.init(name: name) } } class Music: MediaItem{ var artist: String //演唱者 init(name: String, artistName: String){ self.artist = artistName super.init(name: name) } } class Game: MediaItem{ var developer: String //开发者 init(name: String, developer: String){ self.developer = developer super.init(name: name) } } let library: [MediaItem] = [ Movie(name: "Zootopia", genre: "Animation"), Music(name: "Hello", artistName: "Adele"), Game(name: "LIMBO", developer: "Playdead"), Music(name: "See you agian", artistName: "Wiz Khalifa"), Game(name: "The Bridge", developer: "The Quantum Astrophysicists Guild") ] //类型检查 关键字 is var musicCount = 0 var movieCount = 0 var gameCount = 0 for mediaItem in library{ if mediaItem is Movie{ movieCount += 1 } else if mediaItem is Music{ musicCount += 1 } else if mediaItem is Game{ gameCount += 1 } } //类型转换 关键字 as let item0 = library[0] as? Movie //Movie? 尝试进行类型转换 let item00 = library[0] as? Music //nil let item000 = library[0] as! Movie //已经确认是Movie类型. //let item0000 = library[0] as! Music //如果确认失败, 会产生重大错误, 程序中止. for mediaItem in library{ if let movie = mediaItem as? Movie{ //尝试进行类型转换并解包使用 print("Movie:", movie.name, "Genre:", movie.genre) } else if let music = mediaItem as? Music{ print("Music:", music.name, "Artist:", music.artist) } else if let game = mediaItem as? Game{ print("Game:", game.name, "Developer(s):", game.developer) } } //类型判断 在协议中的应用 判断类型是否遵守了协议 protocol Shape{ //图形 var name: String{get} } protocol HasArea{ //面积 func area() -> Double } struct Point: Shape{ let name: String = "point" var x: Double var y: Double } struct Rectangle: Shape, HasArea{ let name: String = "rectangle" var origin: Point var width: Double var height: Double func area() -> Double{ return width * height } } struct Circle: Shape, HasArea{ let name = "circle" var center: Point var radius: Double func area() -> Double{ return M_PI * radius * radius } } struct Line: Shape{ let name = "line" var a: Point var b: Point } let shapes:[Shape] = [ Rectangle(origin: Point(x:0.0,y:0.0), width: 3.0, height: 4.0), Point(x: 0.0, y: 0.0), Circle(center: Point(x:0.0,y:0.0), radius: 1.0), Line(a: Point(x:1.0,y:1.0), b: Point(x:5.0,y:5.0)) ] for shape in shapes{ if shape is HasArea{ print("\(shape.name) has area.") } else{ print("\(shape.name) has no area.") } } print("==========") for shape in shapes{ if let areaShape = shape as? HasArea{ print("The area of \(shape.name) is \(areaShape.area()).") } else{ print("\(shape.name) has no area.") } } //NSObject, AnyObject, Any class Person{ var name: String init(name: String){ self.name = name } } var objects1 = [ CGFloat(3.1415926), "imooc", UIColor.blue, NSDate(), Int(32), Array<Int>([1,2,3]) ] as [Any] // a1 为NSObject let a1 = objects1[0] var objects2 = [ CGFloat(3.1415926), "imooc", UIColor.blue, NSDate(), Int(32), Array<Int>([1,2,3]), Person(name: "liuyubobobo") ] as [Any] // a2 为AnyObject let a2 = objects2[0] //AnyObject比NSObject还要高一层 //NSObject是OC语言中所有类的父类. AnyObject脱离了面向对象中继承树这个概念, //任何的一个对象, 任何的一个Object都可以表述成AnyObject. //实际上在底层AnyObject和OC语言中的ID概念是对应的. //(简单来说ID就相当于C/C++中void * 相对应, 就相当于一个指针, 这个指针没有类型, 指向了这片内存空间. //只要这个内存空间存的是一个对象, 我们就说这是一个AnyObject. var objects3: [Any] = [ CGFloat(3.1415926), "imooc", UIColor.blue, NSDate(), Int(32), Array<Int>([1,2,3]), Person(name: "liuyubobobo") ] //发生error, 因为函数不是一个AnyObject. //objects3.append( {(a:Int) -> Int in // return a*a //}) var objects4: [Any] = [ CGFloat(3.1415926), "imooc", UIColor.blue, NSDate(), Int(32), Array<Int>([1,2,3]), Person(name: "liuyubobobo") ] //没有错误, Any比AnyObject的范围还要广, Any不仅可以包含任何的对象, 还可以包含函数这样的逻辑. objects4.append( { (a:Int) -> Int in return a*a} )
mit
9b660fcb6bd7909a7aa67018f9f50406
17.803347
76
0.601469
3.050916
false
false
false
false
ctarda/Turnstile
Sources/TurnstileTests/StateTests.swift
1
2223
// // StateTests.swift // Turnstile // // Created by Cesar Tardaguila on 09/05/15. // import XCTest import Turnstile class StateTests: XCTestCase { private struct Constants { static let stateValue = "State under testing" static let stringDiff = "💩" } var state: State<String>? override func setUp() { super.setUp() state = State(value: Constants.stateValue) } override func tearDown() { state = nil super.tearDown() } func testStateIsCreated() { XCTAssertNotNil(state, "State must not be nil") } func testStateValueIsSet() { XCTAssertEqual(state!.value, Constants.stateValue, "value must be set properly") } func testStateWillEnterStateCanBeSet() { var result = false state!.willEnterState = { state in result = true } state!.willEnterState?(state!) XCTAssertTrue(result, "willEnterState must be set") } func testStateDidEnterStateCanBeSet() { var result = false state!.didEnterState = { state in result = true } state!.didEnterState?(state!) XCTAssertTrue(result, "didEnterState must be set") } func testStateWillExitStateCanBeSet() { var result = false state!.willExitState = { state in result = true } state!.willExitState?(state!) XCTAssertTrue(result, "willExitState must be set") } func testStateDidExitStateCanBeSet() { var result = false state!.didExitState = { state in result = true } state!.didExitState?(state!) XCTAssertTrue(result, "willExitState must be set") } func testStatesWithSameValueAreEqual() { let secondState = State(value: Constants.stateValue) XCTAssertTrue(state == secondState, "State with same value are equal") } func testStatesWithDifferentValueAreDifferent() { let secondState = State(value: Constants.stateValue + Constants.stringDiff) XCTAssertFalse(state == secondState, "State with differnet value are different") } }
mit
545b8b48374d41d7753a18b3ff73a86a
24.517241
88
0.606306
4.836601
false
true
false
false
teanet/Nazabore
Nazabore/Models/Container.swift
1
486
@objc public class Container: NSObject { @objc public lazy var rootVC: UINavigationController = { let vc = NZBMapVC(router: self.router, markerFetcher: self.markerFetcher) return UINavigationController(rootViewController: vc) }() lazy var api = APIService() lazy var markerFetcher: MarkerFetcher = { [unowned self] in return MarkerFetcher(service: self.api, router: self.router) }() lazy var router: Router = { [unowned self] in return Router(container: self) }() }
mit
288925d73d8021fc277a435b26ddd2d3
26
75
0.73251
3.709924
false
false
false
false
MaartenBrijker/project
project/External/AudioKit-master/AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Distortion.xcplaygroundpage/Contents.swift
2
5422
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Distortion //: ### This thing is a beast. //: import XCPlayground import AudioKit let bundle = NSBundle.mainBundle() let file = bundle.pathForResource("mixloop", ofType: "wav") var player = AKAudioPlayer(file!) player.looping = true var distortion = AKDistortion(player) //: Set the parameters here distortion.delay = 0.1 distortion.decay = 1.0 distortion.delayMix = 0.5 distortion.linearTerm = 0.5 distortion.squaredTerm = 0.5 distortion.cubicTerm = 50 distortion.polynomialMix = 0.5 distortion.softClipGain = -6 distortion.finalMix = 0.5 AudioKit.output = distortion AudioKit.start() //: User Interface Set up class PlaygroundView: AKPlaygroundView { //: UI Elements we'll need to be able to access var delayLabel: Label? var decayLabel: Label? var delayMixLabel: Label? var linearTermLabel: Label? var squaredTermLabel: Label? var cubicTermLabel: Label? var polynomialMixLabel: Label? var softClipGainLabel: Label? var finalMixLabel: Label? override func setup() { addTitle("Distortion") addLabel("Audio Player") addButton("Start", action: #selector(start)) addButton("Stop", action: #selector(stop)) addLabel("Distortion Parameters") addButton("Process", action: #selector(process)) addButton("Bypass", action: #selector(bypass)) delayLabel = addLabel("Delay: \(distortion.delay) Milliseconds") addSlider(#selector(setDelay), value: distortion.delay, minimum: 0.1, maximum: 500) decayLabel = addLabel("Decay: \(distortion.decay) Rate") addSlider(#selector(setDecay), value: distortion.decay, minimum: 0.1, maximum: 50) delayMixLabel = addLabel("Delay Mix: \(distortion.delayMix)") addSlider(#selector(setDelayMix), value: distortion.delayMix) linearTermLabel = addLabel("Linear Term: \(distortion.linearTerm)") addSlider(#selector(setLinearTerm), value: distortion.linearTerm) squaredTermLabel = addLabel("Squared Term: \(distortion.squaredTerm)") addSlider(#selector(setSquaredTerm), value: distortion.squaredTerm) cubicTermLabel = addLabel("Cubic Term: \(distortion.cubicTerm)") addSlider(#selector(setCubicTerm), value: distortion.cubicTerm) polynomialMixLabel = addLabel("Polynomial Mix: \(distortion.polynomialMix)") addSlider(#selector(setPolynomialMix), value: distortion.polynomialMix) softClipGainLabel = addLabel("Soft Clip Gain: \(distortion.softClipGain) dB") addSlider(#selector(setSoftClipGain), value: distortion.softClipGain, minimum: -80, maximum: 20) finalMixLabel = addLabel("Final Mix: \(distortion.finalMix)") addSlider(#selector(setFinalMix), value: distortion.finalMix) } //: Handle UI Events func start() { player.play() } func stop() { player.stop() } func process() { distortion.start() } func bypass() { distortion.bypass() } func setDelay(slider: Slider) { distortion.delay = Double(slider.value) let delay = String(format: "%0.3f", distortion.delay) delayLabel!.text = "Delay: \(delay) Milliseconds" } func setDecay(slider: Slider) { distortion.decay = Double(slider.value) let decay = String(format: "%0.3f", distortion.decay) decayLabel!.text = "Decay: \(decay) Rate" } func setDelayMix(slider: Slider) { distortion.delayMix = Double(slider.value) let delayMix = String(format: "%0.3f", distortion.delayMix) delayMixLabel!.text = "Delay Mix: \(delayMix)" } func setLinearTerm(slider: Slider) { distortion.linearTerm = Double(slider.value) let linearTerm = String(format: "%0.3f", distortion.linearTerm) linearTermLabel!.text = "linearTerm: \(linearTerm)" } func setSquaredTerm(slider: Slider) { distortion.squaredTerm = Double(slider.value) let squaredTerm = String(format: "%0.3f", distortion.squaredTerm) squaredTermLabel!.text = "squaredTerm: \(squaredTerm)" } func setCubicTerm(slider: Slider) { distortion.cubicTerm = Double(slider.value) let cubicTerm = String(format: "%0.3f", distortion.cubicTerm) cubicTermLabel!.text = "cubicTerm: \(cubicTerm)" } func setPolynomialMix(slider: Slider) { distortion.polynomialMix = Double(slider.value) let polynomialMix = String(format: "%0.3f", distortion.polynomialMix) polynomialMixLabel!.text = "polynomialMix: \(polynomialMix)" } func setSoftClipGain(slider: Slider) { distortion.softClipGain = Double(slider.value) let softClipGain = String(format: "%0.3f", distortion.softClipGain) softClipGainLabel!.text = "softClipGain: \(softClipGain) dB" } func setFinalMix(slider: Slider) { distortion.finalMix = Double(slider.value) let finalMix = String(format: "%0.3f", distortion.finalMix) finalMixLabel!.text = "finalMix: \(finalMix)" } } let view = PlaygroundView(frame: CGRect(x: 0, y: 0, width: 500, height: 1000)) XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = view //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
apache-2.0
7f0a11b561e453113439aac1aca99dbe
31.860606
104
0.668941
4.255887
false
false
false
false
jsslai/Action
Carthage/Checkouts/RxSwift/Rx.playground/Pages/Filtering_and_Conditional_Operators.xcplaygroundpage/Contents.swift
3
8119
/*: > # IMPORTANT: To use **Rx.playground**: 1. Open **Rx.xcworkspace**. 1. Build the **RxSwift-OSX** scheme (**Product** → **Build**). 1. Open **Rx** playground in the **Project navigator**. 1. Show the Debug Area (**View** → **Debug Area** → **Show Debug Area**). ---- [Previous](@previous) - [Table of Contents](Table_of_Contents) */ import RxSwift /*: # Filtering and Conditional Operators Operators that selectively emit elements from a source `Observable` sequence. ## `filter` Emits only those elements from an `Observable` sequence that meet the specified condition. [More info](http://reactivex.io/documentation/operators/filter.html) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/filter.png) */ example("filter") { let disposeBag = DisposeBag() Observable.of( "🐱", "🐰", "🐶", "🐸", "🐱", "🐰", "🐹", "🐸", "🐱") .filter { $0 == "🐱" } .subscribe(onNext: { print($0) }) .addDisposableTo(disposeBag) } /*: ---- ## `distinctUntilChanged` Suppresses sequential duplicate elements emitted by an `Observable` sequence. [More info](http://reactivex.io/documentation/operators/distinct.html) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/distinct.png) */ example("distinctUntilChanged") { let disposeBag = DisposeBag() Observable.of("🐱", "🐷", "🐱", "🐱", "🐱", "🐵", "🐱") .distinctUntilChanged() .subscribe(onNext: { print($0) }) .addDisposableTo(disposeBag) } /*: ---- ## `elementAt` Emits only the element at the specified index of all elements emitted by an `Observable` sequence. [More info](http://reactivex.io/documentation/operators/elementat.html) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/elementat.png) */ example("elementAt") { let disposeBag = DisposeBag() Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵") .elementAt(3) .subscribe(onNext: { print($0) }) .addDisposableTo(disposeBag) } /*: ---- ## `single` Emits only the first element (or the first element that meets a condition) emitted by an `Observable` sequence. Will throw an error if the `Observable` sequence does not emit exactly one element. */ example("single") { let disposeBag = DisposeBag() Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵") .single() .subscribe(onNext: { print($0) }) .addDisposableTo(disposeBag) } example("single with conditions") { let disposeBag = DisposeBag() Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵") .single { $0 == "🐸" } .subscribe { print($0) } .addDisposableTo(disposeBag) Observable.of("🐱", "🐰", "🐶", "🐱", "🐰", "🐶") .single { $0 == "🐰" } .subscribe { print($0) } .addDisposableTo(disposeBag) Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵") .single { $0 == "🔵" } .subscribe { print($0) } .addDisposableTo(disposeBag) } /*: ---- ## `take` Emits only the specified number of elements from the beginning of an `Observable` sequence. [More info](http://reactivex.io/documentation/operators/take.html) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/take.png) */ example("take") { let disposeBag = DisposeBag() Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵") .take(3) .subscribe(onNext: { print($0) }) .addDisposableTo(disposeBag) } /*: ---- ## `takeLast` Emits only the specified number of elements from the end of an `Observable` sequence. [More info](http://reactivex.io/documentation/operators/takelast.html) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/takelast.png) */ example("takeLast") { let disposeBag = DisposeBag() Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵") .takeLast(3) .subscribe(onNext: { print($0) }) .addDisposableTo(disposeBag) } /*: ---- ## `takeWhile` Emits elements from the beginning of an `Observable` sequence as long as the specified condition evaluates to `true`. [More info](http://reactivex.io/documentation/operators/takewhile.html) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/takewhile.png) */ example("takeWhile") { let disposeBag = DisposeBag() Observable.of(1, 2, 3, 4, 5, 6) .takeWhile { $0 < 4 } .subscribe(onNext: { print($0) }) .addDisposableTo(disposeBag) } /*: ---- ## `takeUntil` Emits elements from a source `Observable` sequence until a reference `Observable` sequence emits an element. [More info](http://reactivex.io/documentation/operators/takeuntil.html) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/takeuntil.png) */ example("takeUntil") { let disposeBag = DisposeBag() let sourceSequence = PublishSubject<String>() let referenceSequence = PublishSubject<String>() sourceSequence .takeUntil(referenceSequence) .subscribe { print($0) } .addDisposableTo(disposeBag) sourceSequence.onNext("🐱") sourceSequence.onNext("🐰") sourceSequence.onNext("🐶") referenceSequence.onNext("🔴") sourceSequence.onNext("🐸") sourceSequence.onNext("🐷") sourceSequence.onNext("🐵") } /*: ---- ## `skip` Suppresses emitting the specified number of elements from the beginning of an `Observable` sequence. [More info](http://reactivex.io/documentation/operators/skip.html) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/skip.png) */ example("skip") { let disposeBag = DisposeBag() Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵") .skip(2) .subscribe(onNext: { print($0) }) .addDisposableTo(disposeBag) } /*: ---- ## `skipWhile` Suppresses emitting the elements from the beginning of an `Observable` sequence that meet the specified condition. [More info](http://reactivex.io/documentation/operators/skipwhile.html) ![](http://reactivex.io/documentation/operators/images/skipWhile.c.png) */ example("skipWhile") { let disposeBag = DisposeBag() Observable.of(1, 2, 3, 4, 5, 6) .skipWhile { $0 < 4 } .subscribe(onNext: { print($0) }) .addDisposableTo(disposeBag) } /*: ---- ## `skipWhileWithIndex` Suppresses emitting the elements from the beginning of an `Observable` sequence that meet the specified condition, and emits the remaining elements. The closure is also passed each element's index. */ example("skipWhileWithIndex") { let disposeBag = DisposeBag() Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵") .skipWhileWithIndex { element, index in index < 3 } .subscribe(onNext: { print($0) }) .addDisposableTo(disposeBag) } /*: ---- ## `skipUntil` Suppresses emitting the elements from a source `Observable` sequence until a reference `Observable` sequence emits an element. [More info](http://reactivex.io/documentation/operators/skipuntil.html) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/skipuntil.png) */ example("skipUntil") { let disposeBag = DisposeBag() let sourceSequence = PublishSubject<String>() let referenceSequence = PublishSubject<String>() sourceSequence .skipUntil(referenceSequence) .subscribe(onNext: { print($0) }) .addDisposableTo(disposeBag) sourceSequence.onNext("🐱") sourceSequence.onNext("🐰") sourceSequence.onNext("🐶") referenceSequence.onNext("🔴") sourceSequence.onNext("🐸") sourceSequence.onNext("🐷") sourceSequence.onNext("🐵") } //: [Next](@next) - [Table of Contents](Table_of_Contents)
mit
1aa3755b19b533abd5a0b9f81859ae00
32.978355
199
0.635877
4.329288
false
false
false
false
cnoon/swift-compiler-crashes
fixed/23619-swift-typechecker-typecheckexpression.swift
11
2391
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing } }}} let f = j } println( 1 ) func b } }extension String{ class B, leng class A{ }enum S<T> let end = [Void{ deinit { } i>: B<T where B { let f = F>: e>: B<T where T } class typealias e : A<T where B : e struct A { typealias e : B<T where B : B case , }class B : d typealias e : a { let end = [Void{ typealias e : a {{ protocol a { } let a {} func e var d where B : T>: A} class B? { case c<d<T.e = Int typealias e : d<T where k.E }}} { func f:a { var d typealias F>: b {}} }protocol b<T where k.h pr class B, leng case c:A{ } println( 1 ) func b<T>: e }class b{ typealias protocol B { let end = F>: b {} " case c:a { var d = j } func b<T where B : e pr typealias let a func b:T> () class B let a { struct c { struct A{ }protocol A { class B, leng func g a<T where B : a { } func c:d<T where g:A{ }}enum A let end = B var b { case , deinit { class class A { class }protocol a { protocol B : d let f = [[Void{ case c, } protocol A { func b class }class A class func b class B, leng " { case c class }} class B:[Void{}extension NSSet{ let end = a struct S<Int>() class case c{ typealias f = Int typealias F>(v: A { case , var b { class A:f:T.a{ class b:d<d typealias E class class A<T where k.b where I.e : C { } func e } func g<T>: T? { } }typealias A{ struct A { func f: b = [ { }} case c<f: (v: B<T> () class A { class A<Int>: a :BooleanType case c {case=0.a class case c:f: b} class A {{func e.b { {var b { case c, } func e.b { class extension String{ class B, leng struct A { } protocol a { func e.E =0.E func a func b<T> Bool { deinit { let h { }typealias e = a<T>:b func e?) protocol a<f: b {{ }class B, leng protocol C { } typealias A{{ case c, }}protocol a<T{ }}class d } let i: b { func b }extension String{ { protocol a { let a { protocol C { func b<d<d where a { func b 0.E struct c {{ let a { }typealias e : B? { typealias F = [ { { class let f = j func e?) {func f{a { let end = j protocol A { class 0.h class A { import Foundation } return nil import a { typealias e : B<T where g:a { deinit { "" let f : b where T>: e : e class A{ } struct A { { protocol b:T> (v: A { } var b { protocol a {var b {func a<d where T>(v: a :a { enum S<T>) -> T.E }class B<d where T { deinit { let f = [ { protocol B { struct A
mit
8d9024a544caf72b79304054c0a16a13
10.955
87
0.615642
2.405433
false
false
false
false
exponent/exponent
ios/vendored/sdk43/@stripe/stripe-react-native/ios/CardFormView.swift
2
3223
import Foundation import UIKit import Stripe class CardFormView: UIView, STPCardFormViewDelegate { public var cardForm: STPCardFormView? public var cardParams: STPPaymentMethodCardParams? = nil @objc var dangerouslyGetFullCardDetails: Bool = false @objc var onFormComplete: ABI43_0_0RCTDirectEventBlock? @objc var autofocus: Bool = false @objc var isUserInteractionEnabledValue: Bool = true override func didSetProps(_ changedProps: [String]!) { if let cardForm = self.cardForm { cardForm.removeFromSuperview() } let style = self.cardStyle["type"] as? String == "borderless" ? STPCardFormViewStyle.borderless : STPCardFormViewStyle.standard let _cardForm = STPCardFormView(style: style) _cardForm.delegate = self // _cardForm.isUserInteractionEnabled = isUserInteractionEnabledValue if autofocus == true { let _ = _cardForm.becomeFirstResponder() } self.cardForm = _cardForm self.addSubview(_cardForm) setStyles() } @objc var cardStyle: NSDictionary = NSDictionary() { didSet { setStyles() } } func cardFormView(_ form: STPCardFormView, didChangeToStateComplete complete: Bool) { if onFormComplete != nil { let brand = STPCardValidator.brand(forNumber: cardForm?.cardParams?.card?.number ?? "") var cardData: [String: Any?] = [ "expiryMonth": cardForm?.cardParams?.card?.expMonth ?? NSNull(), "expiryYear": cardForm?.cardParams?.card?.expYear ?? NSNull(), "complete": complete, "brand": Mappers.mapCardBrand(brand) ?? NSNull(), "last4": cardForm?.cardParams?.card?.last4 ?? "", "postalCode": cardForm?.cardParams?.billingDetails?.address?.postalCode ?? "", "country": cardForm?.cardParams?.billingDetails?.address?.country ] if (dangerouslyGetFullCardDetails) { cardData["number"] = cardForm?.cardParams?.card?.number ?? "" } if (complete) { self.cardParams = cardForm?.cardParams?.card } else { self.cardParams = nil } onFormComplete!(cardData as [AnyHashable : Any]) } } func focus() { let _ = cardForm?.becomeFirstResponder() } func blur() { let _ = cardForm?.resignFirstResponder() } func setStyles() { if let backgroundColor = cardStyle["backgroundColor"] as? String { cardForm?.backgroundColor = UIColor(hexString: backgroundColor) } // if let disabledBackgroundColor = cardStyle["disabledBackgroundColor"] as? String { // cardForm?.disabledBackgroundColor = UIColor(hexString: disabledBackgroundColor) // } } override init(frame: CGRect) { super.init(frame: frame) } override func layoutSubviews() { cardForm?.frame = self.bounds } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
bsd-3-clause
e42279368736f461ba444448a197f013
33.655914
135
0.596029
5.292282
false
false
false
false
ccrama/Slide-iOS
Slide for Reddit/Fonts/LinkParser.swift
1
11108
// // LinkParser.swift // Slide for Reddit // // Created by Carlos Crane on 1/28/17. // Copyright © 2017 Haptic Apps. All rights reserved. // import DTCoreText import UIKit import YYText class LinkParser { public static func parse(_ attributedString: NSAttributedString, _ color: UIColor, font: UIFont, bold: UIFont? = nil, fontColor: UIColor, linksCallback: ((URL) -> Void)?, indexCallback: (() -> Int)?) -> NSMutableAttributedString { var finalBold: UIFont if bold == nil { finalBold = font.makeBold() } else { finalBold = bold! } let string = NSMutableAttributedString.init(attributedString: attributedString) string.removeAttribute(convertToNSAttributedStringKey(kCTForegroundColorFromContextAttributeName as String), range: NSRange.init(location: 0, length: string.length)) if string.length > 0 { while string.string.contains("slide://") { do { let match = try NSRegularExpression(pattern: "(slide:\\/\\/[a-zA-Z%?#0-9]+)", options: []).matches(in: string.string, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range: NSRange(location: 0, length: string.length))[0] let matchRange: NSRange = match.range(at: 1) if matchRange.location != NSNotFound { let attributedText = string.attributedSubstring(from: match.range).mutableCopy() as! NSMutableAttributedString let oldAttrs = attributedText.attributes(at: 0, effectiveRange: nil) print(attributedText.string) let newAttrs = [ NSAttributedString.Key.link: URL(string: attributedText.string)!] as [NSAttributedString.Key: Any] let allParams = newAttrs.reduce(into: oldAttrs) { (r, e) in r[e.0] = e.1 } let newText = NSMutableAttributedString(string: "Slide Theme", attributes: allParams) string.replaceCharacters(in: match.range, with: newText) } } catch { } } string.enumerateAttributes(in: NSRange.init(location: 0, length: string.length), options: .longestEffectiveRangeNotRequired, using: { (attrs, range, _) in for attr in attrs { if let isColor = attr.value as? UIColor { if isColor.hexString() == "#0000FF" { string.setAttributes([NSAttributedString.Key.foregroundColor: color, NSAttributedString.Key.backgroundColor: ColorUtil.theme.backgroundColor.withAlphaComponent(0.5), NSAttributedString.Key.font: UIFont(name: "Courier", size: font.pointSize) ?? font], range: range) } else if isColor.hexString() == "#008000" { string.setAttributes([NSAttributedString.Key.foregroundColor: fontColor, NSAttributedString.Key(rawValue: YYTextStrikethroughAttributeName): YYTextDecoration(style: YYTextLineStyle.single, width: 1, color: fontColor), NSAttributedString.Key.font: font], range: range) } } else if let url = attr.value as? URL { if SettingValues.enlargeLinks { string.addAttribute(NSAttributedString.Key.font, value: FontGenerator.boldFontOfSize(size: 18, submission: false), range: range) } string.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range) string.addAttribute(convertToNSAttributedStringKey(kCTUnderlineColorAttributeName as String), value: UIColor.clear, range: range) let type = ContentType.getContentType(baseUrl: url) if SettingValues.showLinkContentType { let typeString = NSMutableAttributedString.init(string: "", attributes: convertToOptionalNSAttributedStringKeyDictionary([:])) switch type { case .ALBUM: typeString.mutableString.setString("(Album)") case .REDDIT_GALLERY: typeString.mutableString.setString("(Gallery)") case .TABLE: typeString.mutableString.setString("(Table)") case .EXTERNAL: typeString.mutableString.setString("(External link)") case .LINK, .EMBEDDED, .NONE: if url.absoluteString != string.mutableString.substring(with: range) { typeString.mutableString.setString("(\(url.host ?? url.absoluteString))") } case .DEVIANTART, .IMAGE, .TUMBLR, .XKCD: typeString.mutableString.setString("(Image)") case .GIF: typeString.mutableString.setString("(GIF)") case .IMGUR: typeString.mutableString.setString("(Imgur)") case .VIDEO, .STREAMABLE, .VID_ME: typeString.mutableString.setString("(Video)") case .REDDIT: typeString.mutableString.setString("(Reddit link)") case .SPOILER: typeString.mutableString.setString("") default: if url.absoluteString != string.mutableString.substring(with: range) { typeString.mutableString.setString("(\(url.host!))") } } string.insert(typeString, at: range.location + range.length) string.addAttributes(convertToNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font): FontGenerator.boldFontOfSize(size: 12, submission: false), convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): ColorUtil.theme.fontColor]), range: NSRange.init(location: range.location + range.length, length: typeString.length)) } if type != .SPOILER { linksCallback?(url) if let value = indexCallback?(), !SettingValues.disablePreviews { let positionString = NSMutableAttributedString.init(string: " †\(value)", attributes: [NSAttributedString.Key.foregroundColor: fontColor, NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 10)]) string.insert(positionString, at: range.location + range.length) } } string.yy_setTextHighlight(range, color: color, backgroundColor: nil, userInfo: ["url": url]) break } } }) string.beginEditing() string.enumerateAttribute( .font, in: NSRange(location: 0, length: string.length) ) { (value, range, _) in if let f = value as? UIFont { let isItalic = f.fontDescriptor.symbolicTraits.contains(UIFontDescriptor.SymbolicTraits.traitItalic) let isBold = f.fontDescriptor.symbolicTraits.contains(UIFontDescriptor.SymbolicTraits.traitBold) var newFont = UIFont(descriptor: font.fontDescriptor, size: f.pointSize) if isBold { newFont = UIFont(descriptor: finalBold.fontDescriptor, size: f.pointSize) } string.removeAttribute(.font, range: range) if isItalic { string.addAttributes([.font: newFont, convertToNSAttributedStringKey(YYTextGlyphTransformAttributeName): CGAffineTransform(a: 1, b: tan(0.degreesToRadians), c: tan(15.degreesToRadians), d: 1, tx: 0, ty: 0)], range: range) string.yy_setColor(fontColor, range: range) } else { string.addAttribute(.font, value: newFont, range: range) } } } string.endEditing() string.highlightTarget(color: color) } return string } } // Used from https://gist.github.com/aquajach/4d9398b95a748fd37e88 extension NSMutableAttributedString { func highlightTarget(color: UIColor) { let regPattern = "\\[\\[s\\[(.*?)\\]s\\]\\]" if let regex = try? NSRegularExpression(pattern: regPattern, options: []) { let matchesArray = regex.matches(in: self.string, options: [], range: NSRange(location: 0, length: self.string.length)) for match in matchesArray.reversed() { let copy = self.attributedSubstring(from: match.range) let text = copy.string let attributedText = NSMutableAttributedString(string: text.replacingOccurrences(of: "[[s[", with: "").replacingOccurrences(of: "]s]]", with: ""), attributes: copy.attributes(at: 0, effectiveRange: nil)) attributedText.yy_textBackgroundBorder = YYTextBorder(fill: color, cornerRadius: 3) attributedText.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: NSRange(location: 0, length: attributedText.length)) let highlight = YYTextHighlight() highlight.userInfo = ["spoiler": true] attributedText.yy_setTextHighlight(highlight, range: NSRange(location: 0, length: attributedText.length)) self.replaceCharacters(in: match.range, with: attributedText) } } } } // Helper function inserted by Swift 4.2 migrator. private func convertToNSAttributedStringKey(_ input: String) -> NSAttributedString.Key { return NSAttributedString.Key(rawValue: input) } // Helper function inserted by Swift 4.2 migrator. private func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value) }) } // Helper function inserted by Swift 4.2 migrator. private func convertToNSAttributedStringKeyDictionary(_ input: [String: Any]) -> [NSAttributedString.Key: Any] { return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value) }) } // Helper function inserted by Swift 4.2 migrator. private func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String { return input.rawValue }
apache-2.0
8e28b5a66764c8473762b59e88ac1d7c
61.740113
404
0.579919
5.527626
false
false
false
false
gewill/Feeyue
Feeyue/Helpers/ModelHelper.swift
1
2783
// // ModelHelper.swift // Feeyue // // Created by Will on 2018/7/16. // Copyright © 2018 Will. All rights reserved. // import Foundation import SwiftyJSON import Kanna struct DateHelper { static func convert(_ json: JSON) -> Date { return DateHelper.dateFormatter.date(from: json.stringValue) ?? Date.distantPast } static let dateFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEE MMM d HH:mm:ss Z yyyy" dateFormatter.locale = Locale(identifier: "en_US") return dateFormatter }() } struct SourceHelper { static func convert(_ json: JSON) -> String { var sourceString = json.stringValue if let doc = try? HTML(html: sourceString, encoding: .utf8) { sourceString = doc.body?.text ?? "" } return sourceString } } extension String { var small: String { return self + ":small" } var large: String { return self + ":large" } var medium: String { return self + ":medium" } func twitterSubstring(startIndex: Int, endIndex: Int) -> String { guard let start = self.precomposedStringWithCanonicalMapping.unicodeScalars.index(self.startIndex, offsetBy: startIndex, limitedBy: self.endIndex) else { return "" } guard let end = self.precomposedStringWithCanonicalMapping.unicodeScalars.index(self.startIndex, offsetBy: endIndex, limitedBy: self.endIndex) else { return "" } return String(self.precomposedStringWithCanonicalMapping.unicodeScalars[start..<end]) } /// Twitter sub string by given indices: [Int, Int]. /// Twitter JSON is encoded using UTF-8 characters. /// https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/intro-to-tweet-json /// https://developer.twitter.com/en/docs/basics/counting-characterse func twitterSubstring(range: [Int]) -> String { guard range.count == 2 else { return "" } return self.twitterSubstring(startIndex: range[0], endIndex: range[1]) } func replace(range: [Int], with string: String) -> String { guard range.count == 2 else { return "" } let startIndex = range[0] let endIndex = range[1] guard let start = self.precomposedStringWithCanonicalMapping.unicodeScalars.index(self.startIndex, offsetBy: startIndex, limitedBy: self.endIndex) else { return "" } guard let end = self.precomposedStringWithCanonicalMapping.unicodeScalars.index(self.startIndex, offsetBy: endIndex, limitedBy: self.endIndex) else { return "" } var text = self.precomposedStringWithCanonicalMapping.unicodeScalars text.replaceSubrange(start..<end, with: string.unicodeScalars) return String(text) } }
mit
18d58e2840a8937a2e031d2d156c81c1
34.21519
173
0.674335
4.508914
false
false
false
false
arbitur/Func
source/Decoding/Decodable.swift
1
5434
// // FuncJSON.swift // Pods // // Created by Philip Fryklund on 27/Jul/17. // // import Foundation // MARK: - Protocols public typealias Codable = Decodable & Encodable public protocol Decodable { init(json: Dict) throws } public protocol Encodable { func encoded() -> Dict } // MARK: - Parse functions private func getParse <T> (_ json: Dict, key: String) throws -> T { guard let value: Any = json.valueFor(path: key) else { throw DecodingError.missingKey(key: key) } guard let parsed = value as? T else { throw DecodingError.parseFailed(key: key, value: value, valueType: T.self) } return parsed } // MARK: - Private decode function private func decode <T> (_ json: Dict, _ key: String) throws -> T { return try getParse(json, key: key) } //private func decode <T> (_ json: Dict, _ key: String) throws -> [T] { // return try getParse(json, key: key) //} private func decode <T> (_ json: Dict, _ key: String) throws -> T where T: Func.Decodable { let dict: Dict = try getParse(json, key: key) return try T(json: dict) } private func decode <T> (_ json: Dict, _ key: String) throws -> T where T: RangeReplaceableCollection, T.Element: Decodable { let dicts: [Dict] = try getParse(json, key: key) var arr: T = T() for dict in dicts { arr.append(try T.Element.init(json: dict)) } return arr } private func decode <T> (_ json: Dict, _ key: String) throws -> T where T: RawRepresentable { let raw: T.RawValue = try getParse(json, key: key) guard let enumm = T(rawValue: raw) else { throw DecodingError.parseFailed(key: key, value: raw, valueType: T.self) } return enumm } private func decode <T> (_ json: Dict, _ key: String) throws -> T where T: RangeReplaceableCollection, T.Element: RawRepresentable { let raws: [T.Element.RawValue] = try getParse(json, key: key) var arr: T = T() for raw in raws { guard let element = T.Element.init(rawValue: raw) else { throw DecodingError.parseFailed(key: key, value: raw, valueType: T.Element.self) } arr.append(element) } return arr } private func decode(_ json: Dict, _ key: String) throws -> URL { let str: String = try getParse(json, key: key) guard let url: URL = URL(string: str) else { throw DecodingError.parseFailed(key: key, value: str, valueType: URL.self) } return url } private func decode(_ json: Dict, _ key: String) throws -> [URL] { let strs: [String] = try getParse(json, key: key) return strs.compactMap(URL.init) } private func decode(_ json: Dict, _ key: String, format: DateFormat = .dateTime) throws -> Date { let str: String = try getParse(json, key: key) guard let date = Date.init(str, format: format) else { throw DecodingError.dateFormat(key: key, value: str, format: format.rawValue) } return date } // MARK: - Public decode functions public extension Dictionary where Key == String { // Any func decode <T> (_ key: String) throws -> T { return try Func.decode(self, key) } // func decode <T> (_ key: String) throws -> T? { // return try? self.decode(key) // } // Decodable func decode <T> (_ key: String) throws -> T where T: Decodable { return try Func.decode(self, key) } func decode <T> (_ key: String) throws -> T? where T: Decodable { return try? self.decode(key) as T } func decode <T> (_ key: String) throws -> T where T: RangeReplaceableCollection, T.Element: Decodable { return try Func.decode(self, key) } func decode <T> (_ key: String) throws -> T? where T: RangeReplaceableCollection, T.Element: Decodable { return try? self.decode(key) as T } // RawRepresentable func decode <T> (_ key: String) throws -> T where T: RawRepresentable { return try Func.decode(self, key) } func decode <T> (_ key: String) throws -> T? where T: RawRepresentable { return try? self.decode(key) as T } func decode <T> (_ key: String) throws -> T where T: RangeReplaceableCollection, T.Element: RawRepresentable { return try Func.decode(self, key) } func decode <T> (_ key: String) throws -> T? where T: RangeReplaceableCollection, T.Element: RawRepresentable { return try? self.decode(key) as T } // URL func decode (_ key: String) throws -> URL { return try Func.decode(self, key) } func decode (_ key: String) throws -> URL? { return try? self.decode(key) as URL } func decode (_ key: String) throws -> [URL] { return try Func.decode(self, key) } func decode (_ key: String) throws -> [URL]? { return try? self.decode(key) as [URL] } // Date func decode (_ key: String, format: DateFormat = .dateTime) throws -> Date { return try Func.decode(self, key, format: format) } func decode (_ key: String, format: DateFormat = .dateTime) throws -> Date? { return try? self.decode(key, format: format) as Date } } public enum DecodingError: LocalizedError { case missingKey(key: String) case parseFailed(key: String, value: Any, valueType: Any.Type) case dateFormat(key: String, value: String, format: String) case any(String) public var errorDescription: String? { switch self { case .missingKey(let key): return "\"\(key)\" does not exist" case .parseFailed(let key, let value, let type): return "Expected \"\(key)\" to be of type: \(type) but was \(Swift.type(of: value))" case .dateFormat(let key, let value, let format): return "Expected \"\(key)\" \(value) to be of format \(format)" case .any(let description): return description } } }
mit
4b898615168a06f80e6ad8bf4f402729
23.588235
135
0.668016
3.248057
false
false
false
false
brentdax/swift
test/IRGen/class_bounded_generics.swift
2
17211
// RUN: %target-swift-frontend -module-name class_bounded_generics -enable-objc-interop -emit-ir -primary-file %s -disable-objc-attr-requires-foundation-module | %FileCheck %s -DINT=i%target-ptrsize // REQUIRES: CPU=x86_64 protocol ClassBound : class { func classBoundMethod() } protocol ClassBound2 : class { func classBoundMethod2() } protocol ClassBoundBinary : ClassBound { func classBoundBinaryMethod(_ x: Self) } @objc protocol ObjCClassBound { func objCClassBoundMethod() } @objc protocol ObjCClassBound2 { func objCClassBoundMethod2() } protocol NotClassBound { func notClassBoundMethod() func notClassBoundBinaryMethod(_ x: Self) } struct ClassGenericFieldStruct<T:ClassBound> { var x : Int var y : T var z : Int } struct ClassProtocolFieldStruct { var x : Int var y : ClassBound var z : Int } class ClassGenericFieldClass<T:ClassBound> { final var x : Int = 0 final var y : T final var z : Int = 0 init(t: T) { y = t } } class ClassProtocolFieldClass { var x : Int = 0 var y : ClassBound var z : Int = 0 init(classBound cb: ClassBound) { y = cb } } // CHECK-DAG: %T22class_bounded_generics017ClassGenericFieldD0C = type <{ %swift.refcounted, %TSi, %objc_object*, %TSi }> // CHECK-DAG: %T22class_bounded_generics23ClassGenericFieldStructV = type <{ %TSi, %objc_object*, %TSi }> // CHECK-DAG: %T22class_bounded_generics24ClassProtocolFieldStructV = type <{ %TSi, %T22class_bounded_generics10ClassBoundP, %TSi }> // CHECK-LABEL: define hidden swiftcc %objc_object* @"$s22class_bounded_generics0a1_B10_archetype{{[_0-9a-zA-Z]*}}F"(%objc_object*, %swift.type* %T, i8** %T.ClassBound) func class_bounded_archetype<T : ClassBound>(_ x: T) -> T { return x } class SomeClass {} class SomeSubclass : SomeClass {} // CHECK-LABEL: define hidden swiftcc %T22class_bounded_generics9SomeClassC* @"$s22class_bounded_generics011superclass_B10_archetype{{[_0-9a-zA-Z]*}}F"(%T22class_bounded_generics9SomeClassC*, %swift.type* %T) func superclass_bounded_archetype<T : SomeClass>(_ x: T) -> T { return x } // CHECK-LABEL: define hidden swiftcc { %T22class_bounded_generics9SomeClassC*, %T22class_bounded_generics12SomeSubclassC* } @"$s22class_bounded_generics011superclass_B15_archetype_call{{[_0-9a-zA-Z]*}}F"(%T22class_bounded_generics9SomeClassC*, %T22class_bounded_generics12SomeSubclassC*) func superclass_bounded_archetype_call(_ x: SomeClass, y: SomeSubclass) -> (SomeClass, SomeSubclass) { return (superclass_bounded_archetype(x), superclass_bounded_archetype(y)); // CHECK: [[SOMECLASS_RESULT:%.*]] = call swiftcc %T22class_bounded_generics9SomeClassC* @"$s22class_bounded_generics011superclass_B10_archetype{{[_0-9a-zA-Z]*}}F"(%T22class_bounded_generics9SomeClassC* {{%.*}}, {{.*}}) // CHECK: [[SOMESUPERCLASS_IN:%.*]] = bitcast %T22class_bounded_generics12SomeSubclassC* {{%.*}} to %T22class_bounded_generics9SomeClassC* // CHECK: [[SOMESUPERCLASS_RESULT:%.*]] = call swiftcc %T22class_bounded_generics9SomeClassC* @"$s22class_bounded_generics011superclass_B10_archetype{{[_0-9a-zA-Z]*}}F"(%T22class_bounded_generics9SomeClassC* [[SOMESUPERCLASS_IN]], {{.*}}) // CHECK: bitcast %T22class_bounded_generics9SomeClassC* [[SOMESUPERCLASS_RESULT]] to %T22class_bounded_generics12SomeSubclassC* } // CHECK-LABEL: define hidden swiftcc void @"$s22class_bounded_generics0a1_B17_archetype_method{{[_0-9a-zA-Z]*}}F"(%objc_object*, %objc_object*, %swift.type* %T, i8** %T.ClassBoundBinary) func class_bounded_archetype_method<T : ClassBoundBinary>(_ x: T, y: T) { x.classBoundMethod() // CHECK: [[INHERITED_GEP:%.*]] = getelementptr inbounds i8*, i8** %T.ClassBoundBinary, i32 1 // CHECK: [[INHERITED:%.*]] = load i8*, i8** [[INHERITED_GEP]] // CHECK: [[INHERITED_WTBL:%.*]] = bitcast i8* [[INHERITED]] to i8** // CHECK: [[WITNESS_GEP:%.*]] = getelementptr inbounds i8*, i8** [[INHERITED_WTBL]], i32 1 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_GEP]], align 8 // CHECK: [[WITNESS_FUNC:%.*]] = bitcast i8* [[WITNESS]] to void (%objc_object*, %swift.type*, i8**) // CHECK: call swiftcc void [[WITNESS_FUNC]](%objc_object* swiftself %0, %swift.type* {{.*}}, i8** [[INHERITED_WTBL]]) x.classBoundBinaryMethod(y) // CHECK-NOT: call %objc_object* @swift_unknownObjectRetain(%objc_object* returned [[Y:%.*]]) // CHECK: [[WITNESS_ENTRY:%.*]] = getelementptr inbounds i8*, i8** %T.ClassBoundBinary, i32 2 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ENTRY]], align 8 // CHECK: [[WITNESS_FUNC:%.*]] = bitcast i8* [[WITNESS]] to void (%objc_object*, %objc_object*, %swift.type*, i8**) // CHECK: call swiftcc void [[WITNESS_FUNC]](%objc_object* %1, %objc_object* swiftself %0, %swift.type* %T, i8** %T.ClassBoundBinary) } // CHECK-LABEL: define hidden swiftcc { %objc_object*, %objc_object* } @"$s22class_bounded_generics0a1_B16_archetype_tuple{{[_0-9a-zA-Z]*}}F"(%objc_object*, %swift.type* %T, i8** %T.ClassBound) func class_bounded_archetype_tuple<T : ClassBound>(_ x: T) -> (T, T) { return (x, x) } class ConcreteClass : ClassBoundBinary, NotClassBound { func classBoundMethod() {} func classBoundBinaryMethod(_ x: ConcreteClass) {} func notClassBoundMethod() {} func notClassBoundBinaryMethod(_ x: ConcreteClass) {} } // CHECK-LABEL: define hidden swiftcc %T22class_bounded_generics13ConcreteClassC* @"$s22class_bounded_generics05call_a1_B10_archetype{{[_0-9a-zA-Z]*}}F"(%T22class_bounded_generics13ConcreteClassC*) {{.*}} { func call_class_bounded_archetype(_ x: ConcreteClass) -> ConcreteClass { return class_bounded_archetype(x) // CHECK: [[IN:%.*]] = bitcast %T22class_bounded_generics13ConcreteClassC* {{%.*}} to %objc_object* // CHECK: [[OUT_ORIG:%.*]] = call swiftcc %objc_object* @"$s22class_bounded_generics0a1_B10_archetype{{[_0-9a-zA-Z]*}}F"(%objc_object* [[IN]], {{.*}}) // CHECK: [[OUT:%.*]] = bitcast %objc_object* [[OUT_ORIG]] to %T22class_bounded_generics13ConcreteClassC* // CHECK: ret %T22class_bounded_generics13ConcreteClassC* [[OUT]] } // CHECK: define hidden swiftcc void @"$s22class_bounded_generics04not_a1_B10_archetype{{[_0-9a-zA-Z]*}}F"(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.NotClassBound) func not_class_bounded_archetype<T : NotClassBound>(_ x: T) -> T { return x } // CHECK-LABEL: define hidden swiftcc %objc_object* @"$s22class_bounded_generics0a1_b18_archetype_to_not_a1_B0{{[_0-9a-zA-Z]*}}F"(%objc_object*, %swift.type* %T, i8** %T.ClassBound, i8** %T.NotClassBound) {{.*}} { func class_bounded_archetype_to_not_class_bounded <T: ClassBound & NotClassBound>(_ x:T) -> T { // CHECK: alloca %objc_object*, align 8 return not_class_bounded_archetype(x) } /* TODO Abstraction remapping to non-class-bounded witnesses func class_and_not_class_bounded_archetype_methods <T: ClassBound & NotClassBound>(_ x:T, y:T) { x.classBoundMethod() x.classBoundBinaryMethod(y) x.notClassBoundMethod() x.notClassBoundBinaryMethod(y) } */ // CHECK-LABEL: define hidden swiftcc { %objc_object*, i8** } @"$s22class_bounded_generics0a1_B8_erasure{{[_0-9a-zA-Z]*}}F"(%T22class_bounded_generics13ConcreteClassC*) {{.*}} { func class_bounded_erasure(_ x: ConcreteClass) -> ClassBound { return x // CHECK: [[INSTANCE_OPAQUE:%.*]] = bitcast %T22class_bounded_generics13ConcreteClassC* [[INSTANCE:%.*]] to %objc_object* // CHECK: [[T0:%.*]] = insertvalue { %objc_object*, i8** } undef, %objc_object* [[INSTANCE_OPAQUE]], 0 // CHECK: [[T1:%.*]] = insertvalue { %objc_object*, i8** } [[T0]], i8** getelementptr inbounds ([2 x i8*], [2 x i8*]* @"$s22class_bounded_generics13ConcreteClassCAA0E5BoundAAWP", i32 0, i32 0), 1 // CHECK: ret { %objc_object*, i8** } [[T1]] } // CHECK-LABEL: define hidden swiftcc void @"$s22class_bounded_generics0a1_B16_protocol_method{{[_0-9a-zA-Z]*}}F"(%objc_object*, i8**) {{.*}} { func class_bounded_protocol_method(_ x: ClassBound) { x.classBoundMethod() // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_getObjectType(%objc_object* %0) // CHECK: [[WITNESS_GEP:%.*]] = getelementptr inbounds i8*, i8** [[WITNESS_TABLE:%.*]], i32 1 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_GEP]], align 8 // CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] to void (%objc_object*, %swift.type*, i8**) // CHECK: call swiftcc void [[WITNESS_FN]](%objc_object* swiftself %0, %swift.type* [[METADATA]], i8** [[WITNESS_TABLE]]) } // CHECK-LABEL: define hidden swiftcc %T22class_bounded_generics13ConcreteClassC* @"$s22class_bounded_generics0a1_B15_archetype_cast{{[_0-9a-zA-Z]*}}F"(%objc_object*, %swift.type* %T, i8** %T.ClassBound) func class_bounded_archetype_cast<T : ClassBound>(_ x: T) -> ConcreteClass { return x as! ConcreteClass // CHECK: [[IN_PTR:%.*]] = bitcast %objc_object* {{%.*}} to i8* // CHECK: [[T0R:%.*]] = call swiftcc %swift.metadata_response @"$s22class_bounded_generics13ConcreteClassCMa"([[INT]] 0) // CHECK: [[T0:%.*]] = extractvalue %swift.metadata_response [[T0R]], 0 // CHECK: [[T1:%.*]] = bitcast %swift.type* [[T0]] to i8* // CHECK: [[OUT_PTR:%.*]] = call i8* @swift_dynamicCastClassUnconditional(i8* [[IN_PTR]], i8* [[T1]]) // CHECK: [[OUT:%.*]] = bitcast i8* [[OUT_PTR]] to %T22class_bounded_generics13ConcreteClassC* // CHECK: ret %T22class_bounded_generics13ConcreteClassC* [[OUT]] } // CHECK-LABEL: define hidden swiftcc %T22class_bounded_generics13ConcreteClassC* @"$s22class_bounded_generics0a1_B14_protocol_cast{{[_0-9a-zA-Z]*}}F"(%objc_object*, i8**) func class_bounded_protocol_cast(_ x: ClassBound) -> ConcreteClass { return x as! ConcreteClass // CHECK: [[IN_PTR:%.*]] = bitcast %objc_object* {{%.*}} to i8* // CHECK: [[T0R:%.*]] = call swiftcc %swift.metadata_response @"$s22class_bounded_generics13ConcreteClassCMa"([[INT]] 0) // CHECK: [[T0:%.*]] = extractvalue %swift.metadata_response [[T0R]], 0 // CHECK: [[T1:%.*]] = bitcast %swift.type* [[T0]] to i8* // CHECK: [[OUT_PTR:%.*]] = call i8* @swift_dynamicCastClassUnconditional(i8* [[IN_PTR]], i8* [[T1]]) // CHECK: [[OUT:%.*]] = bitcast i8* [[OUT_PTR]] to %T22class_bounded_generics13ConcreteClassC* // CHECK: ret %T22class_bounded_generics13ConcreteClassC* [[OUT]] } // CHECK-LABEL: define hidden swiftcc { %objc_object*, i8** } @"$s22class_bounded_generics0a1_B22_protocol_conversion_{{.*}}"(%objc_object*, i8**, i8**) {{.*}} { func class_bounded_protocol_conversion_1(_ x: ClassBound & ClassBound2) -> ClassBound { return x } // CHECK-LABEL: define hidden swiftcc { %objc_object*, i8** } @"$s22class_bounded_generics0a1_B22_protocol_conversion_{{.*}}"(%objc_object*, i8**, i8**) {{.*}} { func class_bounded_protocol_conversion_2(_ x: ClassBound & ClassBound2) -> ClassBound2 { return x } // CHECK-LABEL: define hidden swiftcc { %objc_object*, i8** } @"$s22class_bounded_generics05objc_a1_B22_protocol_conversion_{{.*}}"(%objc_object*, i8**) {{.*}} { func objc_class_bounded_protocol_conversion_1 (_ x: ClassBound & ObjCClassBound) -> ClassBound { return x } // CHECK-LABEL: define hidden swiftcc %objc_object* @"$s22class_bounded_generics05objc_a1_B22_protocol_conversion_{{.*}}"(%objc_object*, i8**) {{.*}} { func objc_class_bounded_protocol_conversion_2 (_ x: ClassBound & ObjCClassBound) -> ObjCClassBound { return x } // CHECK-LABEL: define hidden swiftcc %objc_object* @"$s22class_bounded_generics05objc_a1_B22_protocol_conversion_{{.*}}"(%objc_object*) func objc_class_bounded_protocol_conversion_3 (_ x: ObjCClassBound & ObjCClassBound2) -> ObjCClassBound { return x } // CHECK-LABEL: define hidden swiftcc %objc_object* @"$s22class_bounded_generics05objc_a1_B22_protocol_conversion_{{.*}}"(%objc_object*) func objc_class_bounded_protocol_conversion_4 (_ x: ObjCClassBound & ObjCClassBound2) -> ObjCClassBound2 { return x } // CHECK-LABEL: define hidden swiftcc { i64, %objc_object*, i64 } @"$s22class_bounded_generics0A28_generic_field_struct_fields{{[_0-9a-zA-Z]*}}F"(i64, %objc_object*, i64, %swift.type* %T, i8** %T.ClassBound) func class_generic_field_struct_fields<T> (_ x:ClassGenericFieldStruct<T>) -> (Int, T, Int) { return (x.x, x.y, x.z) } // CHECK-LABEL: define hidden swiftcc { i64, %objc_object*, i8**, i64 } @"$s22class_bounded_generics0A29_protocol_field_struct_fields{{[_0-9a-zA-Z]*}}F"(i64, %objc_object*, i8**, i64) func class_protocol_field_struct_fields (_ x:ClassProtocolFieldStruct) -> (Int, ClassBound, Int) { return (x.x, x.y, x.z) } // CHECK-LABEL: define hidden swiftcc { i64, %objc_object*, i64 } @"$s22class_bounded_generics0a15_generic_field_A7_fields{{[_0-9a-zA-Z]*}}F"(%T22class_bounded_generics017ClassGenericFieldD0C*) func class_generic_field_class_fields<T> (_ x:ClassGenericFieldClass<T>) -> (Int, T, Int) { return (x.x, x.y, x.z) // CHECK: getelementptr inbounds %T22class_bounded_generics017ClassGenericFieldD0C, %T22class_bounded_generics017ClassGenericFieldD0C* %0, i32 0, i32 1 // CHECK: getelementptr inbounds %T22class_bounded_generics017ClassGenericFieldD0C, %T22class_bounded_generics017ClassGenericFieldD0C* %0, i32 0, i32 2 // CHECK: getelementptr inbounds %T22class_bounded_generics017ClassGenericFieldD0C, %T22class_bounded_generics017ClassGenericFieldD0C* %0, i32 0, i32 3 } // CHECK-LABEL: define hidden swiftcc { i64, %objc_object*, i8**, i64 } @"$s22class_bounded_generics0a16_protocol_field_A7_fields{{[_0-9a-zA-Z]*}}F"(%T22class_bounded_generics018ClassProtocolFieldD0C*) func class_protocol_field_class_fields(_ x: ClassProtocolFieldClass) -> (Int, ClassBound, Int) { return (x.x, x.y, x.z) // CHECK: = call swiftcc i64 %{{[0-9]+}} // CHECK: = call swiftcc { %objc_object*, i8** } %{{[0-9]+}} // CHECK: = call swiftcc i64 %{{[0-9]+}} } class SomeSwiftClass { class func foo() {} } // T must have a Swift layout, so we can load this metatype with a direct access. // CHECK-LABEL: define hidden swiftcc void @"$s22class_bounded_generics0a1_B9_metatype{{[_0-9a-zA-Z]*}}F" // CHECK: [[T0:%.*]] = getelementptr inbounds %T22class_bounded_generics14SomeSwiftClassC, %T22class_bounded_generics14SomeSwiftClassC* {{%.*}}, i32 0, i32 0, i32 0 // CHECK-NEXT: [[T1:%.*]] = load %swift.type*, %swift.type** [[T0]], align 8 // CHECK-NEXT: [[T2:%.*]] = bitcast %swift.type* [[T1]] to void (%swift.type*)** // CHECK-NEXT: [[T3:%.*]] = getelementptr inbounds void (%swift.type*)*, void (%swift.type*)** [[T2]], i64 10 // CHECK-NEXT: load void (%swift.type*)*, void (%swift.type*)** [[T3]], align 8 func class_bounded_metatype<T: SomeSwiftClass>(_ t : T) { type(of: t).foo() } class WeakRef<T: AnyObject> { weak var value: T? } class A<T> { required init() {} } class M<T, S: A<T>> { private var s: S init() { // Don't crash generating the reference to 's'. s = S.init() } } // CHECK-LABEL: define hidden swiftcc void @"$s22class_bounded_generics14takes_metatypeyyxmlF"(%swift.type*, %swift.type* %T) func takes_metatype<T>(_: T.Type) {} // CHECK-LABEL: define hidden swiftcc void @"$s22class_bounded_generics023archetype_with_generic_A11_constraint1tyx_tAA1ACyq_GRbzr0_lF"(%T22class_bounded_generics1AC.1*, %swift.type* %T) // CHECK: [[ISA_ADDR:%.*]] = bitcast %T22class_bounded_generics1AC.1* %0 to %swift.type** // CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]] // CHECK: call swiftcc void @"$s22class_bounded_generics14takes_metatypeyyxmlF"(%swift.type* %T, %swift.type* %T) // CHECK-NEXT: [[ISA_PTR:%.*]] = bitcast %swift.type* [[ISA]] to %swift.type** // CHECK-NEXT: [[U_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[ISA_PTR]], i64 10 // CHECK-NEXT: [[U:%.*]] = load %swift.type*, %swift.type** [[U_ADDR]] // CHECK: call swiftcc void @"$s22class_bounded_generics14takes_metatypeyyxmlF"(%swift.type* %U, %swift.type* %U) // CHECK: ret void func archetype_with_generic_class_constraint<T, U>(t: T) where T : A<U> { takes_metatype(T.self) takes_metatype(U.self) } // CHECK-LABEL: define hidden swiftcc void @"$s22class_bounded_generics029calls_archetype_with_generic_A11_constraint1ayAA1ACyxG_tlF"(%T22class_bounded_generics1AC*) #0 { // CHECK: alloca // CHECK: memset // CHECK: [[ISA_ADDR:%.*]] = getelementptr inbounds %T22class_bounded_generics1AC, %T22class_bounded_generics1AC* %0, i32 0, i32 0, i32 0 // CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]] // CHECK: [[ISA_PTR:%.*]] = bitcast %swift.type* [[ISA]] to %swift.type** // CHECK-NEXT: [[T_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[ISA_PTR]], i64 10 // CHECK-NEXT: [[T:%.*]] = load %swift.type*, %swift.type** [[T_ADDR]] // CHECK: [[SELF:%.*]] = bitcast %T22class_bounded_generics1AC* %0 to %T22class_bounded_generics1AC.1* // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s22class_bounded_generics1ACMa"([[INT]] 0, %swift.type* [[T]]) // CHECK-NEXT: [[A_OF_T:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: call swiftcc void @"$s22class_bounded_generics023archetype_with_generic_A11_constraint1tyx_tAA1ACyq_GRbzr0_lF"(%T22class_bounded_generics1AC.1* [[SELF]], %swift.type* [[A_OF_T]]) // CHECK: ret void func calls_archetype_with_generic_class_constraint<T>(a: A<T>) { archetype_with_generic_class_constraint(t: a) }
apache-2.0
ad4d50af0da41c4795558772be048786
53.638095
288
0.680088
3.193728
false
false
false
false
ProfileCreator/ProfileCreator
ProfileCreator/ProfileCreator/Utility/DesignatedRequirement.swift
1
2952
// // DesignatedRequirement.swift // ProfileCreator // // Created by Erik Berglund. // Copyright © 2018 Erik Berglund. All rights reserved. // import Foundation public func SecRequirement(forURL url: URL) -> SecRequirement? { var osStatus = noErr var codeRef: SecStaticCode? osStatus = SecStaticCodeCreateWithPath(url as CFURL, [], &codeRef) guard osStatus == noErr, let code = codeRef else { Log.shared.error(message: "Failed to create static code with path: \(url.path)", category: String(describing: #function)) if let osStatusError = SecCopyErrorMessageString(osStatus, nil) { Log.shared.error(message: osStatusError as String, category: String(describing: #function)) } return nil } let flags: SecCSFlags = SecCSFlags(rawValue: 0) var requirementRef: SecRequirement? osStatus = SecCodeCopyDesignatedRequirement(code, flags, &requirementRef) guard osStatus == noErr, let requirement = requirementRef else { Log.shared.error(message: "Failed to copy designated requirement.", category: String(describing: #function)) if let osStatusError = SecCopyErrorMessageString(osStatus, nil) { Log.shared.error(message: osStatusError as String, category: String(describing: #function)) } return nil } return requirement } public func SecRequirementCopyData(forURL url: URL) -> Data? { guard let requirement = SecRequirement(forURL: url) else { return nil } var osStatus = noErr let flags: SecCSFlags = SecCSFlags(rawValue: 0) var requirementDataRef: CFData? osStatus = SecRequirementCopyData(requirement, flags, &requirementDataRef) guard osStatus == noErr, let requirementData = requirementDataRef as Data? else { Log.shared.error(message: "Failed to copy requirement data.", category: String(describing: #function)) if let osStatusError = SecCopyErrorMessageString(osStatus, nil) { Log.shared.error(message: osStatusError as String, category: String(describing: #function)) } return nil } return requirementData } public func SecRequirementCopyString(forURL url: URL) -> String? { guard let requirement = SecRequirement(forURL: url) else { return nil } var osStatus = noErr let flags: SecCSFlags = SecCSFlags(rawValue: 0) var requirementStringRef: CFString? osStatus = SecRequirementCopyString(requirement, flags, &requirementStringRef) guard osStatus == noErr, let requirementString = requirementStringRef as String? else { Log.shared.error(message: "Failed to copy requirement string.", category: String(describing: #function)) if let osStatusError = SecCopyErrorMessageString(osStatus, nil) { Log.shared.error(message: osStatusError as String, category: String(describing: #function)) } return nil } return requirementString }
mit
a802d404c16e4822225f5ae593f51429
35.8875
129
0.700102
4.676704
false
false
false
false
kaltura/playkit-ios
Classes/Player/Media/PKMediaEntry+Copying.swift
1
1683
// =================================================================================================== // Copyright (C) 2017 Kaltura Inc. // // Licensed under the AGPLv3 license, unless a different license for a // particular library is specified in the applicable library path. // // You may obtain a copy of the License at // https://www.gnu.org/licenses/agpl-3.0.html // =================================================================================================== import Foundation extension PKMediaEntry: NSCopying { public func copy(with zone: NSZone? = nil) -> Any { let sources = self.sources?.compactMap{ $0.copy() as? PKMediaSource } let entry = PKMediaEntry(self.id, sources: sources, duration: self.duration) entry.mediaType = self.mediaType entry.metadata = self.metadata entry.name = self.name entry.externalSubtitles = self.externalSubtitles entry.thumbnailUrl = self.thumbnailUrl entry.tags = self.tags return entry } } extension PKMediaSource: NSCopying { public func copy(with zone: NSZone? = nil) -> Any { let source = PKMediaSource(self.id, contentUrl: self.contentUrl, mimeType: self.mimeType, drmData: self.drmData, mediaFormat: self.mediaFormat) source.externalSubtitle = self.externalSubtitle source.contentRequestAdapter = self.contentRequestAdapter return source } }
agpl-3.0
005c04955a381cecd235be2636454072
34.808511
102
0.503862
5.482085
false
false
false
false
twtstudio/WePeiYang-iOS
WePeiYang/Bicycle/View/BicycleFitnessTrackerViewCell.swift
1
4037
// // BicycleFitnessTrackerViewCell.swift // WePeiYang // // Created by Allen X on 12/8/16. // Copyright © 2016 Qin Yubo. All rights reserved. // import Foundation import Charts enum TrackerCellType { case Move(text: String, color: UIColor) case Exercise(text: String, color: UIColor) case Stand(text: String, color: UIColor) } class BicycleFitnessTrackerViewCell: UITableViewCell, ChartViewDelegate { var lineChartView: LineChartView! convenience init(cellType: TrackerCellType) { self.init() self.contentView.backgroundColor = .blackColor() self.selectionStyle = .None switch cellType { case .Move(let text, let color): self.textLabel?.text = text self.textLabel?.textColor = color let label = UILabel(text: "450/400 calories", color: .whiteColor()) self.contentView.addSubview(label) label.snp_makeConstraints { make in make.left.equalTo(self.textLabel!) make.top.equalTo((self.textLabel?.snp_bottom)!).offset(1) } case .Exercise(let text, let color): self.textLabel?.text = text self.textLabel?.textColor = color let label = UILabel(text: "45/55 minutes", color: .whiteColor()) self.contentView.addSubview(label) label.snp_makeConstraints { make in make.left.equalTo(self.textLabel!) make.top.equalTo((self.textLabel?.snp_bottom)!).offset(1) } case .Stand(let text, let color): self.textLabel?.text = text self.textLabel?.textColor = color let label = UILabel(text: "10/12 hours", color: .whiteColor()) self.contentView.addSubview(label) label.snp_makeConstraints { make in make.left.equalTo(self.textLabel!) make.top.equalTo((self.textLabel?.snp_bottom)!).offset(1) } } } func renderChart() { self.lineChartView.delegate = self self.lineChartView.descriptionText = "" self.lineChartView.noDataTextDescription = "暂无数据可显示" self.lineChartView.dragEnabled = true; //X-Axis Limit Line let llXAxis = ChartLimitLine(limit: 10.0, label: "Index 10") llXAxis.lineWidth = 4.0 llXAxis.lineDashLengths = [10.0, 10.0, 0.0] llXAxis.labelPosition = .RightBottom llXAxis.valueFont = UIFont.systemFontOfSize(10.0) lineChartView.xAxis.addLimitLine(llXAxis) //Y-Axis Limit Line let ll1 = ChartLimitLine(limit: 50.0, label: "Lower Limit") ll1.lineWidth = 4.0 ll1.lineDashLengths = [5.0, 5.0] ll1.labelPosition = .RightBottom ll1.valueFont = UIFont.systemFontOfSize(10.0) let ll2 = ChartLimitLine(limit: 350.0, label: "Upper Limit") ll2.lineWidth = 4.0 ll2.lineDashLengths = [5.0, 5.0] ll2.labelPosition = .RightTop ll2.valueFont = UIFont.systemFontOfSize(10.0) let leftAxis = lineChartView.leftAxis leftAxis.removeAllLimitLines() leftAxis.addLimitLine(ll1) leftAxis.addLimitLine(ll2) leftAxis.axisMaxValue = 500.0 leftAxis.axisMinValue = 0.0 leftAxis.gridLineDashLengths = [5.0, 5.0] leftAxis.drawZeroLineEnabled = false; leftAxis.drawLimitLinesBehindDataEnabled = true lineChartView.rightAxis.enabled = false lineChartView.legend.form = .Line lineChartView.animate(xAxisDuration: 2.5, easingOption: .EaseInOutQuart) } func setDataCount(count: Int, range: Double) { var xVals: [String?] = [] for i in 0..<count { xVals.append("\(i+1)") } lineChartView.data?.xVals = xVals } func insertData(yVals: [String?]) { } }
mit
41699b2f14bc897e4fe119fc69de809e
32.798319
80
0.590751
4.503919
false
false
false
false
treejames/firefox-ios
Client/Application/AppDelegate.swift
3
11686
/* 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 Shared import Storage import AVFoundation import XCGLogger class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var browserViewController: BrowserViewController! var rootViewController: UINavigationController! weak var profile: BrowserProfile? var tabManager: TabManager! let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Set the Firefox UA for browsing. setUserAgent() // Start the keyboard helper to monitor and cache keyboard state. KeyboardHelper.defaultHelper.startObserving() // Create a new sync log file on cold app launch Logger.syncLogger.newLogWithDate(NSDate()) let profile = getProfile(application) // Set up a web server that serves us static content. Do this early so that it is ready when the UI is presented. setUpWebServer(profile) // for aural progress bar: play even with silent switch on, and do not stop audio from other apps (like music) AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers, error: nil) self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.backgroundColor = UIColor.whiteColor() let defaultRequest = NSURLRequest(URL: UIConstants.AboutHomeURL) self.tabManager = TabManager(defaultNewTabRequest: defaultRequest, profile: profile) browserViewController = BrowserViewController(profile: profile, tabManager: self.tabManager) // Add restoration class, the factory that will return the ViewController we // will restore with. browserViewController.restorationIdentifier = NSStringFromClass(BrowserViewController.self) browserViewController.restorationClass = AppDelegate.self browserViewController.automaticallyAdjustsScrollViewInsets = false rootViewController = UINavigationController(rootViewController: browserViewController) rootViewController.automaticallyAdjustsScrollViewInsets = false rootViewController.delegate = self rootViewController.navigationBarHidden = true self.window!.rootViewController = rootViewController self.window!.backgroundColor = UIConstants.AppBackgroundColor activeCrashReporter = BreakpadCrashReporter(breakpadInstance: BreakpadController.sharedInstance()) configureActiveCrashReporter(profile.prefs.boolForKey("crashreports.send.always")) NSNotificationCenter.defaultCenter().addObserverForName(FSReadingListAddReadingListItemNotification, object: nil, queue: nil) { (notification) -> Void in if let userInfo = notification.userInfo, url = userInfo["URL"] as? NSURL, absoluteString = url.absoluteString { let title = (userInfo["Title"] as? String) ?? "" profile.readingList?.createRecordWithURL(absoluteString, title: title, addedBy: UIDevice.currentDevice().name) } } // check to see if we started 'cos someone tapped on a notification. if let localNotification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification { viewURLInNewTab(localNotification) } return true } /** * We maintain a weak reference to the profile so that we can pause timed * syncs when we're backgrounded. * * The long-lasting ref to the profile lives in BrowserViewController, * which we set in application:willFinishLaunchingWithOptions:. * * If that ever disappears, we won't be able to grab the profile to stop * syncing... but in that case the profile's deinit will take care of things. */ func getProfile(application: UIApplication) -> Profile { if let profile = self.profile { return profile } let p = BrowserProfile(localName: "profile", app: application) self.profile = p return p } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { self.window!.makeKeyAndVisible() return true } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { if let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) { if components.scheme != "firefox" && components.scheme != "firefox-x-callback" { return false } var url: String? var appName: String? var callbackScheme: String? for item in components.queryItems as? [NSURLQueryItem] ?? [] { switch item.name { case "url": url = item.value case "x-source": callbackScheme = item.value case "x-source-name": appName = item.value default: () } } if let url = url, newURL = NSURL(string: url.unescape()) { self.browserViewController.openURLInNewTab(newURL) return true } } return false } // We sync in the foreground only, to avoid the possibility of runaway resource usage. // Eventually we'll sync in response to notifications. func applicationDidBecomeActive(application: UIApplication) { self.profile?.syncManager.beginTimedSyncs() // We could load these here, but then we have to futz with the tab counter // and making NSURLRequests. self.browserViewController.loadQueuedTabs() } func applicationDidEnterBackground(application: UIApplication) { self.profile?.syncManager.endTimedSyncs() let taskId = application.beginBackgroundTaskWithExpirationHandler { _ in } self.profile?.shutdown() application.endBackgroundTask(taskId) } private func setUpWebServer(profile: Profile) { let server = WebServer.sharedInstance ReaderModeHandlers.register(server, profile: profile) ErrorPageHelper.register(server) AboutHomeHandler.register(server) AboutLicenseHandler.register(server) SessionRestoreHandler.register(server) server.start() } private func setUserAgent() { // Note that we use defaults here that are readable from extensions, so they // can just used the cached identifier. let defaults = NSUserDefaults(suiteName: AppInfo.sharedContainerIdentifier())! let firefoxUA = UserAgent.defaultUserAgent(defaults) // Set the UA for WKWebView (via defaults), the favicon fetcher, and the image loader. // This only needs to be done once per runtime. defaults.registerDefaults(["UserAgent": firefoxUA]) FaviconFetcher.userAgent = firefoxUA SDWebImageDownloader.sharedDownloader().setValue(firefoxUA, forHTTPHeaderField: "User-Agent") } func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) { if let actionId = identifier { if let action = SentTabAction(rawValue: actionId) { viewURLInNewTab(notification) switch(action) { case .Bookmark: addBookmark(notification) break case .ReadingList: addToReadingList(notification) break default: break } } else { println("ERROR: Unknown notification action received") } } else { println("ERROR: Unknown notification received") } } func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { viewURLInNewTab(notification) } private func viewURLInNewTab(notification: UILocalNotification) { if let alertURL = notification.userInfo?[TabSendURLKey] as? String { if let urlToOpen = NSURL(string: alertURL) { browserViewController.openURLInNewTab(urlToOpen) } } } private func addBookmark(notification: UILocalNotification) { if let alertURL = notification.userInfo?[TabSendURLKey] as? String, let title = notification.userInfo?[TabSendTitleKey] as? String { browserViewController.addBookmark(alertURL, title: title) } } private func addToReadingList(notification: UILocalNotification) { if let alertURL = notification.userInfo?[TabSendURLKey] as? String, let title = notification.userInfo?[TabSendTitleKey] as? String { if let urlToOpen = NSURL(string: alertURL) { NSNotificationCenter.defaultCenter().postNotificationName(FSReadingListAddReadingListItemNotification, object: self, userInfo: ["URL": urlToOpen, "Title": title]) } } } } // MARK: - Root View Controller Animations extension AppDelegate: UINavigationControllerDelegate { func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if operation == UINavigationControllerOperation.Push { return BrowserToTrayAnimator() } else if operation == UINavigationControllerOperation.Pop { return TrayToBrowserAnimator() } else { return nil } } } var activeCrashReporter: CrashReporter? func configureActiveCrashReporter(optedIn: Bool?) { if let reporter = activeCrashReporter { configureCrashReporter(reporter, optedIn: optedIn) } } public func configureCrashReporter(reporter: CrashReporter, #optedIn: Bool?) { let configureReporter: () -> () = { let addUploadParameterForKey: String -> Void = { key in if let value = NSBundle.mainBundle().objectForInfoDictionaryKey(key) as? String { reporter.addUploadParameter(value, forKey: key) } } addUploadParameterForKey("AppID") addUploadParameterForKey("BuildID") addUploadParameterForKey("ReleaseChannel") addUploadParameterForKey("Vendor") } if let optedIn = optedIn { // User has explicitly opted-in for sending crash reports. If this is not true, then the user has // explicitly opted-out of crash reporting so don't bother starting breakpad or stop if it was running if optedIn { reporter.start(true) configureReporter() reporter.setUploadingEnabled(true) } else { reporter.stop() } } // We haven't asked the user for their crash reporting preference yet. Log crashes anyways but don't send them. else { reporter.start(true) configureReporter() } }
mpl-2.0
5cb6c3f3011d5ee711dc8f8d93f5f399
41.649635
185
0.668663
5.854709
false
false
false
false
algal/TouchVisualizer
TouchVisualizer/ForcePropertiesGestureRecognizer/ALGInitialTouchGestureRecognizer.swift
1
5664
// // MonotouchGestureRecognizer.swift // TouchVisualizer // // Created by Alexis Gallagher on 2015-10-30. // Copyright © 2015 Alexis Gallagher. All rights reserved. // import UIKit.UIGestureRecognizerSubclass /** This recognizes an "initial touch sequence", which is essentially the part of a multitouch sequence that concerns only the single finger which initiated it. Given a valid multitouch sequence, that multitouch sequence contains an initial touch sequence if and only if it begins with a single-finger touch. The initial touch sequence then consists only of `UITouch`s instance values representing that finger. It ends when that finger leaves the screen or when the entire multitouch sequence is cancelled. Some valid multitouch sequences do not contain initial touch sequences -- for instance, if the multitouch sequence begins with 2 or more simultaneous touches. Some multitouch sequences outlast their initial touch sequence, for instance, if the multitouch sequence begins with one finger, adds a second finger, removes the first finger, and then moves the second finger, then only the first three actions constitute an initial touch sequence. When it calls its action method, the property `currentTouch` will be populated with the `UITouch` object of the initial touch sequence */ class ALGInitialTouchSequenceGestureRecognizer: UIGestureRecognizer { fileprivate enum ExtendedState { case possible,began(UITouch),failed,changed(UITouch),ended(UITouch),canceled(UITouch) } /// contains the `UITouch` object, and will be non-nil whenever the receiver fires its action callback var currentTouch:UITouch? { switch self.extendedState { case .possible,.failed: return nil case .began(let touch): return touch case .changed(let touch): return touch case .ended(let touch): return touch case .canceled(let touch): return touch } } fileprivate var extendedState:ExtendedState = .possible { didSet { switch extendedState { case .possible: self.state = .possible case .failed: self.state = .failed case .began(_): self.state = .began case .changed(_): self.state = .changed case .ended(_): self.state = .ended case .canceled(_): self.state = .cancelled } } } fileprivate func touchesWithAction(_ touches: Set<UITouch>, withEvent event: UIEvent, phase:UITouchPhase) { switch (self.extendedState,phase) { // assert: .Possible -> [.Began,.Failed] case (.possible, UITouchPhase.began): if touches.count == 1 { self.extendedState = .began(touches.first!) } else { // ignore multitouch sequences which begin with more than two simultaneous touches self.extendedState = .failed } case (.possible, _): assertionFailure("unexpected call to non-touchesBegan when UIGestureRecognizer was in .Possible state") self.extendedState = .failed break // assert: .Began -> [.Changed] case (.began(let currentTouch),_): self.extendedState = .changed(currentTouch) // assert: .Changes -> [.Changed, .Canceled, .Ended] case (.changed(let touch), .began): // if a touch began, it must not be the touch we are recognizing which already began for irrelevantTouch in touches.filter({ $0 != touch }) { self.ignore(irrelevantTouch, for: event) } case (.changed(let touch),.moved) where touches.contains(touch): self.extendedState = .changed(touch) case (.changed(let touch),.stationary) where touches.contains(touch): self.extendedState = .changed(touch) case (.changed(let touch),.ended) where touches.contains(touch): self.extendedState = .ended(touch) case (.changed(let touch),.cancelled) where touches.contains(touch): self.extendedState = .canceled(touch) case (.changed(let touch),_) where !touches.contains(touch): // NSLog("touches%@ called a Changed gesture recognizer with an ignored touch. Event: %@",method.description,event) break case (.changed(_),let phase): assertionFailure("Should be unreachable") NSLog("unexpected call to touches\(phase.description) for this event \(event)") break // assert: no transition requirements from .Failed, .Ended, .Canceled case (.failed,_): fallthrough case (.ended(_),_): fallthrough case (.canceled(_),_): break } } // // MARK: overrides // override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesBegan(touches, with: event) self.touchesWithAction(touches, withEvent: event, phase: .began) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesMoved(touches, with: event) self.touchesWithAction(touches, withEvent: event, phase: .moved) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesEnded(touches, with: event) self.touchesWithAction(touches, withEvent: event, phase: .ended) } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesCancelled(touches, with: event) self.touchesWithAction(touches, withEvent: event, phase: .cancelled) } override func reset() { super.reset() self.extendedState = .possible } } // MARK: logging extension UITouchPhase { var description:String { switch self { case .began: return "Began" case .cancelled: return "Cancelled" case .ended: return "Ended" case .moved: return "Moved" case .stationary: return "Stationary" } } }
mit
11dc48c352a9c8643dae419039cf9aaa
35.772727
345
0.695744
4.526779
false
false
false
false
gregomni/swift
validation-test/compiler_crashers_fixed/00228-swift-clangimporter-loadextensions.swift
3
764
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck -requirement-machine-inferred-signatures=on func s() -> o { r q { } protocol p { typealias m = q } m r : p { } func r<s : t, o : p where o.m == s> (s: o) { } func r<s : p where s.m == s> (s: s) { } m s<p : u> { } class t<s : s, r : s where s.t == r> : q { } class t<s, r> { } protocol s { func r() { } } func t(s) -> <p>(() -> p) { } class q<m : t
apache-2.0
80a623bf0abdd0e846f89728e07174fb
22.151515
92
0.611257
2.840149
false
false
false
false
agrippa1994/iOS-PLC
Pods/Charts/Charts/Classes/Renderers/LineChartRenderer.swift
4
25085
// // LineChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit @objc public protocol LineChartRendererDelegate { func lineChartRendererData(renderer: LineChartRenderer) -> LineChartData! func lineChartRenderer(renderer: LineChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! func lineChartRendererFillFormatter(renderer: LineChartRenderer) -> ChartFillFormatter func lineChartDefaultRendererValueFormatter(renderer: LineChartRenderer) -> NSNumberFormatter! func lineChartRendererChartYMax(renderer: LineChartRenderer) -> Double func lineChartRendererChartYMin(renderer: LineChartRenderer) -> Double func lineChartRendererChartXMax(renderer: LineChartRenderer) -> Double func lineChartRendererChartXMin(renderer: LineChartRenderer) -> Double func lineChartRendererMaxVisibleValueCount(renderer: LineChartRenderer) -> Int } public class LineChartRenderer: LineScatterCandleRadarChartRenderer { public weak var delegate: LineChartRendererDelegate? public init(delegate: LineChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.delegate = delegate } public override func drawData(context context: CGContext?) { let lineData = delegate!.lineChartRendererData(self) if (lineData === nil) { return } for (var i = 0; i < lineData.dataSetCount; i++) { let set = lineData.getDataSetByIndex(i) if (set !== nil && set!.isVisible) { drawDataSet(context: context, dataSet: set as! LineChartDataSet) } } } internal struct CGCPoint { internal var x: CGFloat = 0.0 internal var y: CGFloat = 0.0 /// x-axis distance internal var dx: CGFloat = 0.0 /// y-axis distance internal var dy: CGFloat = 0.0 internal init(x: CGFloat, y: CGFloat) { self.x = x self.y = y } } internal func drawDataSet(context context: CGContext?, dataSet: LineChartDataSet) { let entries = dataSet.yVals if (entries.count < 1) { return } CGContextSaveGState(context) CGContextSetLineWidth(context, dataSet.lineWidth) if (dataSet.lineDashLengths != nil) { CGContextSetLineDash(context, dataSet.lineDashPhase, dataSet.lineDashLengths, dataSet.lineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } // if drawing cubic lines is enabled if (dataSet.isDrawCubicEnabled) { drawCubic(context: context, dataSet: dataSet, entries: entries) } else { // draw normal (straight) lines drawLinear(context: context, dataSet: dataSet, entries: entries) } CGContextRestoreGState(context) } internal func drawCubic(context context: CGContext?, dataSet: LineChartDataSet, entries: [ChartDataEntry]) { let trans = delegate?.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency) let entryFrom = dataSet.entryForXIndex(_minX) let entryTo = dataSet.entryForXIndex(_maxX) let minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0) let maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count) let phaseX = _animator.phaseX let phaseY = _animator.phaseY // get the color that is specified for this position from the DataSet let drawingColor = dataSet.colors.first! let intensity = dataSet.cubicIntensity // the path for the cubic-spline let cubicPath = CGPathCreateMutable() var valueToPixelMatrix = trans!.valueToPixelMatrix let size = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))) if (size - minx >= 2) { var prevDx: CGFloat = 0.0 var prevDy: CGFloat = 0.0 var curDx: CGFloat = 0.0 var curDy: CGFloat = 0.0 var prevPrev = entries[minx] var prev = entries[minx] var cur = entries[minx] var next = entries[minx + 1] // let the spline start CGPathMoveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY) prevDx = CGFloat(cur.xIndex - prev.xIndex) * intensity prevDy = CGFloat(cur.value - prev.value) * intensity curDx = CGFloat(next.xIndex - cur.xIndex) * intensity curDy = CGFloat(next.value - cur.value) * intensity // the first cubic CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY, CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY) for (var j = minx + 1, count = min(size, entries.count - 1); j < count; j++) { prevPrev = entries[j == 1 ? 0 : j - 2] prev = entries[j - 1] cur = entries[j] next = entries[j + 1] prevDx = CGFloat(cur.xIndex - prevPrev.xIndex) * intensity prevDy = CGFloat(cur.value - prevPrev.value) * intensity curDx = CGFloat(next.xIndex - prev.xIndex) * intensity curDy = CGFloat(next.value - prev.value) * intensity CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY, CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY) } if (size > entries.count - 1) { prevPrev = entries[entries.count - (entries.count >= 3 ? 3 : 2)] prev = entries[entries.count - 2] cur = entries[entries.count - 1] next = cur prevDx = CGFloat(cur.xIndex - prevPrev.xIndex) * intensity prevDy = CGFloat(cur.value - prevPrev.value) * intensity curDx = CGFloat(next.xIndex - prev.xIndex) * intensity curDy = CGFloat(next.value - prev.value) * intensity // the last cubic CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY, CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY) } } CGContextSaveGState(context) if (dataSet.isDrawFilledEnabled) { drawCubicFill(context: context, dataSet: dataSet, spline: cubicPath, matrix: valueToPixelMatrix, from: minx, to: size) } CGContextBeginPath(context) CGContextAddPath(context, cubicPath) CGContextSetStrokeColorWithColor(context, drawingColor.CGColor) CGContextStrokePath(context) CGContextRestoreGState(context) } internal func drawCubicFill(context context: CGContext?, dataSet: LineChartDataSet, spline: CGMutablePath, matrix: CGAffineTransform, from: Int, to: Int) { CGContextSaveGState(context) let fillMin = delegate!.lineChartRendererFillFormatter(self).getFillLinePosition( dataSet: dataSet, data: delegate!.lineChartRendererData(self), chartMaxY: delegate!.lineChartRendererChartYMax(self), chartMinY: delegate!.lineChartRendererChartYMin(self)) var pt1 = CGPoint(x: CGFloat(to - 1), y: fillMin) var pt2 = CGPoint(x: CGFloat(from), y: fillMin) pt1 = CGPointApplyAffineTransform(pt1, matrix) pt2 = CGPointApplyAffineTransform(pt2, matrix) CGContextBeginPath(context) CGContextAddPath(context, spline) CGContextAddLineToPoint(context, pt1.x, pt1.y) CGContextAddLineToPoint(context, pt2.x, pt2.y) CGContextClosePath(context) CGContextSetFillColorWithColor(context, dataSet.fillColor.CGColor) CGContextSetAlpha(context, dataSet.fillAlpha) CGContextFillPath(context) CGContextRestoreGState(context) } private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint()) internal func drawLinear(context context: CGContext?, dataSet: LineChartDataSet, entries: [ChartDataEntry]) { let trans = delegate!.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix let phaseX = _animator.phaseX let phaseY = _animator.phaseY CGContextSaveGState(context) let entryFrom = dataSet.entryForXIndex(_minX) let entryTo = dataSet.entryForXIndex(_maxX) let minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0) let maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count) // more than 1 color if (dataSet.colors.count > 1) { if (_lineSegments.count != 2) { _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint()) } for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++) { if (count > 1 && j == count - 1) { // Last point, we have already drawn a line to this point break } var e = entries[j] _lineSegments[0].x = CGFloat(e.xIndex) _lineSegments[0].y = CGFloat(e.value) * phaseY _lineSegments[0] = CGPointApplyAffineTransform(_lineSegments[0], valueToPixelMatrix) if (j + 1 < count) { e = entries[j + 1] _lineSegments[1].x = CGFloat(e.xIndex) _lineSegments[1].y = CGFloat(e.value) * phaseY _lineSegments[1] = CGPointApplyAffineTransform(_lineSegments[1], valueToPixelMatrix) } else { _lineSegments[1] = _lineSegments[0] } if (!viewPortHandler.isInBoundsRight(_lineSegments[0].x)) { break } // make sure the lines don't do shitty things outside bounds if (!viewPortHandler.isInBoundsLeft(_lineSegments[1].x) || (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y)) || (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y))) { continue } // get the color that is set for this line-segment CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor) CGContextStrokeLineSegments(context, _lineSegments, 2) } } else { // only one color per dataset var e1: ChartDataEntry! var e2: ChartDataEntry! if (_lineSegments.count != max((entries.count - 1) * 2, 2)) { _lineSegments = [CGPoint](count: max((entries.count - 1) * 2, 2), repeatedValue: CGPoint()) } e1 = entries[minx] let count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))) for (var x = count > 1 ? minx + 1 : minx, j = 0; x < count; x++) { e1 = entries[x == 0 ? 0 : (x - 1)] e2 = entries[x] _lineSegments[j++] = CGPointApplyAffineTransform(CGPoint(x: CGFloat(e1.xIndex), y: CGFloat(e1.value) * phaseY), valueToPixelMatrix) _lineSegments[j++] = CGPointApplyAffineTransform(CGPoint(x: CGFloat(e2.xIndex), y: CGFloat(e2.value) * phaseY), valueToPixelMatrix) } let size = max((count - minx - 1) * 2, 2) CGContextSetStrokeColorWithColor(context, dataSet.colorAt(0).CGColor) CGContextStrokeLineSegments(context, _lineSegments, size) } CGContextRestoreGState(context) // if drawing filled is enabled if (dataSet.isDrawFilledEnabled && entries.count > 0) { drawLinearFill(context: context, dataSet: dataSet, entries: entries, minx: minx, maxx: maxx, trans: trans) } } internal func drawLinearFill(context context: CGContext?, dataSet: LineChartDataSet, entries: [ChartDataEntry], minx: Int, maxx: Int, trans: ChartTransformer) { CGContextSaveGState(context) CGContextSetFillColorWithColor(context, dataSet.fillColor.CGColor) // filled is usually drawn with less alpha CGContextSetAlpha(context, dataSet.fillAlpha) let filled = generateFilledPath( entries, fillMin: delegate!.lineChartRendererFillFormatter(self).getFillLinePosition( dataSet: dataSet, data: delegate!.lineChartRendererData(self), chartMaxY: delegate!.lineChartRendererChartYMax(self), chartMinY: delegate!.lineChartRendererChartYMin(self)), from: minx, to: maxx, matrix: trans.valueToPixelMatrix) CGContextBeginPath(context) CGContextAddPath(context, filled) CGContextFillPath(context) CGContextRestoreGState(context) } /// Generates the path that is used for filled drawing. private func generateFilledPath(entries: [ChartDataEntry], fillMin: CGFloat, from: Int, to: Int, var matrix: CGAffineTransform) -> CGPath { let phaseX = _animator.phaseX let phaseY = _animator.phaseY let filled = CGPathCreateMutable() CGPathMoveToPoint(filled, &matrix, CGFloat(entries[from].xIndex), fillMin) CGPathAddLineToPoint(filled, &matrix, CGFloat(entries[from].xIndex), CGFloat(entries[from].value) * phaseY) // create a new path for (var x = from + 1, count = Int(ceil(CGFloat(to - from) * phaseX + CGFloat(from))); x < count; x++) { let e = entries[x] CGPathAddLineToPoint(filled, &matrix, CGFloat(e.xIndex), CGFloat(e.value) * phaseY) } // close up CGPathAddLineToPoint(filled, &matrix, CGFloat(entries[max(min(Int(ceil(CGFloat(to - from) * phaseX + CGFloat(from))) - 1, entries.count - 1), 0)].xIndex), fillMin) CGPathCloseSubpath(filled) return filled } public override func drawValues(context context: CGContext?) { let lineData = delegate!.lineChartRendererData(self) if (lineData === nil) { return } let defaultValueFormatter = delegate!.lineChartDefaultRendererValueFormatter(self) if (CGFloat(lineData.yValCount) < CGFloat(delegate!.lineChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX) { var dataSets = lineData.dataSets for (var i = 0; i < dataSets.count; i++) { let dataSet = dataSets[i] as! LineChartDataSet if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0 { continue } let valueFont = dataSet.valueFont let valueTextColor = dataSet.valueTextColor var formatter = dataSet.valueFormatter if (formatter === nil) { formatter = defaultValueFormatter } let trans = delegate!.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency) // make sure the values do not interfear with the circles var valOffset = Int(dataSet.circleRadius * 1.75) if (!dataSet.isDrawCirclesEnabled) { valOffset = valOffset / 2 } var entries = dataSet.yVals let entryFrom = dataSet.entryForXIndex(_minX) let entryTo = dataSet.entryForXIndex(_maxX) let minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0) let maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count) var positions = trans.generateTransformedValuesLine( entries, phaseX: _animator.phaseX, phaseY: _animator.phaseY, from: minx, to: maxx) for (var j = 0, count = positions.count; j < count; j++) { if (!viewPortHandler.isInBoundsRight(positions[j].x)) { break } if (!viewPortHandler.isInBoundsLeft(positions[j].x) || !viewPortHandler.isInBoundsY(positions[j].y)) { continue } let val = entries[j + minx].value ChartUtils.drawText(context: context, text: formatter!.stringFromNumber(val)!, point: CGPoint(x: positions[j].x, y: positions[j].y - CGFloat(valOffset) - valueFont.lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]) } } } } public override func drawExtras(context context: CGContext?) { drawCircles(context: context) } private func drawCircles(context context: CGContext?) { let phaseX = _animator.phaseX let phaseY = _animator.phaseY let lineData = delegate!.lineChartRendererData(self) let dataSets = lineData.dataSets var pt = CGPoint() var rect = CGRect() CGContextSaveGState(context) for (var i = 0, count = dataSets.count; i < count; i++) { let dataSet = lineData.getDataSetByIndex(i) as! LineChartDataSet! if (!dataSet.isVisible || !dataSet.isDrawCirclesEnabled) { continue } let trans = delegate!.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix var entries = dataSet.yVals let circleRadius = dataSet.circleRadius let circleDiameter = circleRadius * 2.0 let circleHoleDiameter = circleRadius let circleHoleRadius = circleHoleDiameter / 2.0 let isDrawCircleHoleEnabled = dataSet.isDrawCircleHoleEnabled let entryFrom = dataSet.entryForXIndex(_minX)! let entryTo = dataSet.entryForXIndex(_maxX)! let minx = max(dataSet.entryIndex(entry: entryFrom, isEqual: true), 0) let maxx = min(dataSet.entryIndex(entry: entryTo, isEqual: true) + 1, entries.count) for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++) { let e = entries[j] pt.x = CGFloat(e.xIndex) pt.y = CGFloat(e.value) * phaseY pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix) if (!viewPortHandler.isInBoundsRight(pt.x)) { break } // make sure the circles don't do shitty things outside bounds if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y)) { continue } CGContextSetFillColorWithColor(context, dataSet.getCircleColor(j)!.CGColor) rect.origin.x = pt.x - circleRadius rect.origin.y = pt.y - circleRadius rect.size.width = circleDiameter rect.size.height = circleDiameter CGContextFillEllipseInRect(context, rect) if (isDrawCircleHoleEnabled) { CGContextSetFillColorWithColor(context, dataSet.circleHoleColor.CGColor) rect.origin.x = pt.x - circleHoleRadius rect.origin.y = pt.y - circleHoleRadius rect.size.width = circleHoleDiameter rect.size.height = circleHoleDiameter CGContextFillEllipseInRect(context, rect) } } } CGContextRestoreGState(context) } var _highlightPtsBuffer = [CGPoint](count: 4, repeatedValue: CGPoint()) public override func drawHighlighted(context context: CGContext?, indices: [ChartHighlight]) { let lineData = delegate!.lineChartRendererData(self) let chartXMax = delegate!.lineChartRendererChartXMax(self) let chartYMax = delegate!.lineChartRendererChartYMax(self) let chartYMin = delegate!.lineChartRendererChartYMin(self) CGContextSaveGState(context) for (var i = 0; i < indices.count; i++) { let set = lineData.getDataSetByIndex(indices[i].dataSetIndex) as! LineChartDataSet! if (set === nil || !set.isHighlightEnabled) { continue } CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor) CGContextSetLineWidth(context, set.highlightLineWidth) if (set.highlightLineDashLengths != nil) { CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } let xIndex = indices[i].xIndex; // get the x-position if (CGFloat(xIndex) > CGFloat(chartXMax) * _animator.phaseX) { continue } let yValue = set.yValForXIndex(xIndex) if (yValue.isNaN) { continue } let y = CGFloat(yValue) * _animator.phaseY; // get the y-position _highlightPtsBuffer[0] = CGPoint(x: CGFloat(xIndex), y: CGFloat(chartYMax)) _highlightPtsBuffer[1] = CGPoint(x: CGFloat(xIndex), y: CGFloat(chartYMin)) _highlightPtsBuffer[2] = CGPoint(x: CGFloat(delegate!.lineChartRendererChartXMin(self)), y: y) _highlightPtsBuffer[3] = CGPoint(x: CGFloat(chartXMax), y: y) let trans = delegate!.lineChartRenderer(self, transformerForAxis: set.axisDependency) trans.pointValuesToPixel(&_highlightPtsBuffer) // draw the lines drawHighlightLines(context: context, points: _highlightPtsBuffer, horizontal: set.isHorizontalHighlightIndicatorEnabled, vertical: set.isVerticalHighlightIndicatorEnabled) } CGContextRestoreGState(context) } }
mit
d7730962a8814a3e7fa49e0ab7ef8191
38.882353
306
0.558302
5.576923
false
false
false
false
nasser0099/Express
Express/StencilViewEngine.swift
1
4259
//===--- StencilViewEngine.swift -----------------------------------------===// // //Copyright (c) 2015-2016 Daniel Leping (dileping) // //This file is part of Swift Express. // //Swift Express 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 3 of the License, or //(at your option) any later version. // //Swift Express 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. // //You should have received a copy of the GNU Lesser General Public License //along with Swift Express. If not, see <http://www.gnu.org/licenses/>. // //===----------------------------------------------------------------------===// import Foundation import PathKit import Stencil private extension Path { var containerDir: Path { return Path(NSString(string: String(self)).stringByDeletingLastPathComponent) } } typealias StencilEdible = [String: Any] private protocol StencilCookable { func cook() -> StencilEdible } private protocol StencilNormalizable { func normalizeValue(value:Any) -> Any func normalize() -> Any } extension StencilNormalizable { func normalizeValue(value:Any) -> Any { let normalizable = value as? StencilNormalizable return normalizable.map {$0.normalize()} .getOrElse(value) } } extension Array : StencilNormalizable { func normalize() -> Any { return self.map(normalizeValue) } } extension Dictionary : StencilNormalizable { func normalize() -> Any { let normalized = self.map { (k, v) in (k, normalizeValue(v)) } return toMap(normalized) } } extension Dictionary : StencilCookable { func cook() -> StencilEdible { return self.map { (k,v) in return (String(k), normalizeValue(v)) } } } private let loaderKey = "loader" class StencilView : ViewType { let template:Template let loader:TemplateLoader? init(template:Template, loader:TemplateLoader? = nil) { self.template = template self.loader = loader } func render<C>(context:C?) throws -> FlushableContentType { do { let edibleOption = context.flatMap{$0 as? StencilCookable }?.cook() let contextSupplied:[String:Any] = edibleOption.getOrElse(Dictionary()) let loader = contextSupplied.findFirst { (k, v) in k == loaderKey }.map{$1} if let loader = loader { guard let loader = loader as? TemplateLoader else { throw ExpressError.Render(description: "'loader' is a reserved key and can be of TemplateLoader type only", line: nil, cause: nil) } print("OK, loader: ", loader) //TODO: merge loaders } let contextLoader:[String:Any] = self.loader.map{["loader": $0]}.getOrElse(Dictionary()) let finalContext = contextSupplied ++ contextLoader let stencilContext = Context(dictionary: finalContext) let render = try template.render(stencilContext) return AnyContent(str:render, contentType: "text/html")! } catch let e as TemplateSyntaxError { throw ExpressError.Render(description: e.description, line: nil, cause: e) } } } public class StencilViewEngine : ViewEngineType { public init() { } public func extensions() -> Array<String> { return ["stencil"] } public func view(filePath:String) throws -> ViewType { do { let path = Path(filePath) let dir = path.containerDir let loader = TemplateLoader(paths: [dir]) let template = try Template(path: path) return StencilView(template: template, loader: loader) } catch let e as TemplateSyntaxError { throw ExpressError.Render(description: e.description, line: nil, cause: e) } } }
gpl-3.0
dddedf70c24be0848bb098634e118f3a
31.265152
150
0.61282
4.609307
false
false
false
false
bi3mer/WorkSpace
Swift/functionHelloWorld/functionHelloWorld/main.swift
1
933
// // main.swift // functionHelloWorld // // Created by colan biemer on 3/28/15. // Copyright (c) 2015 colan biemer. All rights reserved. // import Foundation func hello() -> Void { println("hello world!") } func hello(printVal: String) { println("overload worked: " + printVal) } func returnHello() -> String { return "hello world!" } func returnHello(str: String, str2: String) -> String { return str + " " + str2 } func minMax(arr: [Int]) -> (min: Int, max: Int) { var min = arr[0] var max = arr[0] for val in arr { if( val > max ) { max = val } else if(val < min) { min = val } } return (min,max) } hello() hello("value") println(returnHello()) println(returnHello("one", "two")) var arr = [2,3,1235,6,123,123901,23,-123,123,-1234 ] var mm = minMax(arr) println("min: \(mm.0) max: \(mm.1)")
mit
e5817b6e876cae9a72afbc33783bc1e7
14.295082
57
0.547696
2.971338
false
false
false
false
groue/GRDB.swift
GRDB/Record/FetchableRecord.swift
1
33687
import Foundation /// A type that can decode itself from a database row. /// /// To conform to `FetchableRecord`, provide an implementation for the /// ``init(row:)-9w9yp`` initializer. This implementation is ready-made for /// `Decodable` types. /// /// For example: /// /// ```swift /// struct Player: FetchableRecord, Decodable { /// var name: String /// var score: Int /// } /// /// if let row = try Row.fetchOne(db, sql: "SELECT * FROM player") { /// let player = try Player(row: row) /// } /// ``` /// /// If you add conformance to ``TableRecord``, the record type can generate /// SQL queries for you: /// /// ```swift /// struct Player: FetchableRecord, TableRecord, Decodable { /// var name: String /// var score: Int /// } /// /// let players = try Player.fetchAll(db) /// let players = try Player.order(Column("score")).fetchAll(db) /// ``` /// /// ## Topics /// /// ### Initializers /// /// - ``init(row:)-9w9yp`` /// /// ### Fetching Records /// - ``fetchCursor(_:)`` /// - ``fetchAll(_:)`` /// - ``fetchSet(_:)`` /// - ``fetchOne(_:)`` /// /// ### Fetching Records from Raw SQL /// /// - ``fetchCursor(_:sql:arguments:adapter:)`` /// - ``fetchAll(_:sql:arguments:adapter:)`` /// - ``fetchSet(_:sql:arguments:adapter:)`` /// - ``fetchOne(_:sql:arguments:adapter:)`` /// /// ### Fetching Records from a Prepared Statement /// /// - ``fetchCursor(_:arguments:adapter:)`` /// - ``fetchAll(_:arguments:adapter:)`` /// - ``fetchSet(_:arguments:adapter:)`` /// - ``fetchOne(_:arguments:adapter:)`` /// /// ### Fetching Records from a Request /// /// - ``fetchCursor(_:_:)`` /// - ``fetchAll(_:_:)`` /// - ``fetchSet(_:_:)`` /// - ``fetchOne(_:_:)`` /// /// ### Fetching Records by Primary Key /// /// - ``fetchCursor(_:ids:)`` /// - ``fetchAll(_:ids:)`` /// - ``fetchSet(_:ids:)`` /// - ``fetchOne(_:id:)`` /// - ``fetchCursor(_:keys:)-2jrm1`` /// - ``fetchAll(_:keys:)-4c8no`` /// - ``fetchSet(_:keys:)-e6uy`` /// - ``fetchOne(_:key:)-3f3hc`` /// /// ### Fetching Record by Key /// /// - ``fetchCursor(_:keys:)-5u9hu`` /// - ``fetchAll(_:keys:)-2addp`` /// - ``fetchSet(_:keys:)-8no3x`` /// - ``fetchOne(_:key:)-92b9m`` /// /// ### Configuring Row Decoding for the Standard Decodable Protocol /// /// - ``databaseColumnDecodingStrategy-6uefz`` /// - ``databaseDateDecodingStrategy-78y03`` /// - ``databaseDecodingUserInfo-77jim`` /// - ``databaseJSONDecoder(for:)-7lmxd`` /// - ``DatabaseColumnDecodingStrategy`` /// - ``DatabaseDateDecodingStrategy`` /// /// ### Supporting Types /// /// - ``RecordCursor`` public protocol FetchableRecord { // MARK: - Row Decoding /// Creates a record from `row`. /// /// The row argument may be reused during the iteration of database results. /// If you want to keep the row for later use, make sure to store a copy: /// `row.copy()`. /// /// - throws: An error is thrown if the record can't be decoded from the /// database row. init(row: Row) throws // MARK: - Customizing the Format of Database Columns /// Contextual information made available to the /// `Decodable.init(from:)` initializer. /// /// For example: /// /// ```swift /// // A key that holds a decoder's name /// let decoderName = CodingUserInfoKey(rawValue: "decoderName")! /// /// // A FetchableRecord + Decodable record /// struct Player: FetchableRecord, Decodable { /// // Customize the decoder name when decoding a database row /// static let databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [decoderName: "Database"] /// /// init(from decoder: Decoder) throws { /// // Print the decoder name /// print(decoder.userInfo[decoderName]) /// ... /// } /// } /// /// // prints "Database" /// let player = try Player.fetchOne(db, ...) /// /// // prints "JSON" /// let decoder = JSONDecoder() /// decoder.userInfo = [decoderName: "JSON"] /// let player = try decoder.decode(Player.self, from: ...) /// ``` static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] { get } /// Returns the `JSONDecoder` that decodes the value for a given column. /// /// This method is dedicated to ``FetchableRecord`` types that also conform /// to the standard `Decodable` protocol and use the default /// ``init(row:)-4ptlh`` implementation. static func databaseJSONDecoder(for column: String) -> JSONDecoder /// The strategy for decoding `Date` columns. /// /// This property is dedicated to ``FetchableRecord`` types that also /// conform to the standard `Decodable` protocol and use the default /// ``init(row:)-4ptlh`` implementation. /// /// For example: /// /// ```swift /// struct Player: FetchableRecord, Decodable { /// static let databaseDateDecodingStrategy = DatabaseDateDecodingStrategy.timeIntervalSince1970 /// /// // Decoded from an epoch timestamp /// var creationDate: Date /// } /// ``` static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get } /// The strategy for converting column names to coding keys. /// /// This property is dedicated to ``FetchableRecord`` types that also /// conform to the standard `Decodable` protocol and use the default /// ``init(row:)-4ptlh`` implementation. /// /// For example: /// /// ```swift /// struct Player: FetchableRecord, Decodable { /// static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.convertFromSnakeCase /// /// // Decoded from the 'player_id' column /// var playerID: String /// } /// ``` static var databaseColumnDecodingStrategy: DatabaseColumnDecodingStrategy { get } } extension FetchableRecord { /// Contextual information made available to the /// `Decodable.init(from:)` initializer. /// /// The default implementation returns an empty dictionary. public static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] { [:] } /// Returns the `JSONDecoder` that decodes the value for a given column. /// /// The default implementation returns a `JSONDecoder` with the /// following properties: /// /// - `dataDecodingStrategy`: `.base64` /// - `dateDecodingStrategy`: `.millisecondsSince1970` /// - `nonConformingFloatDecodingStrategy`: `.throw` public static func databaseJSONDecoder(for column: String) -> JSONDecoder { let decoder = JSONDecoder() decoder.dataDecodingStrategy = .base64 decoder.dateDecodingStrategy = .millisecondsSince1970 decoder.nonConformingFloatDecodingStrategy = .throw decoder.userInfo = databaseDecodingUserInfo return decoder } /// The default strategy for decoding `Date` columns is /// ``DatabaseDateDecodingStrategy/deferredToDate``. public static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { .deferredToDate } /// The default strategy for converting column names to coding keys is /// ``DatabaseColumnDecodingStrategy/useDefaultKeys``. public static var databaseColumnDecodingStrategy: DatabaseColumnDecodingStrategy { .useDefaultKeys } } extension FetchableRecord { // MARK: Fetching From Prepared Statement /// Returns a cursor over records fetched from a prepared statement. /// /// For example: /// /// ```swift /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// let sql = "SELECT * FROM player WHERE lastName = ?" /// let statement = try db.makeStatement(sql: sql) /// let players = try Player.fetchCursor(statement, arguments: [lastName]) /// while let player = try players.next() { /// print(player.name) /// } /// } /// ``` /// /// The returned cursor is valid only during the remaining execution of the /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: A ``RecordCursor`` over fetched records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( _ statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> RecordCursor<Self> { try RecordCursor(statement: statement, arguments: arguments, adapter: adapter) } /// Returns an array of records fetched from a prepared statement. /// /// For example: /// /// ```swift /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// let sql = "SELECT * FROM player WHERE lastName = ?" /// let statement = try db.makeStatement(sql: sql) /// let players = try Player.fetchAll(statement, arguments: [lastName]) /// } /// ``` /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( _ statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> [Self] { try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } /// Returns a single record fetched from a prepared statement. /// /// For example: /// /// ```swift /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// let sql = "SELECT * FROM player WHERE lastName = ? LIMIT 1" /// let statement = try db.makeStatement(sql: sql) /// let player = try Player.fetchOne(statement, arguments: [lastName]) /// } /// ``` /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne( _ statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> Self? { try fetchCursor(statement, arguments: arguments, adapter: adapter).next() } } extension FetchableRecord where Self: Hashable { /// Returns a set of records fetched from a prepared statement. /// /// For example: /// /// ```swift /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// let sql = "SELECT * FROM player WHERE lastName = ?" /// let statement = try db.makeStatement(sql: sql) /// let players = try Player.fetchSet(statement, arguments: [lastName]) /// } /// ``` /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( _ statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> Set<Self> { try Set(fetchCursor(statement, arguments: arguments, adapter: adapter)) } } extension FetchableRecord { // MARK: Fetching From SQL /// Returns a cursor over records fetched from an SQL query. /// /// For example: /// /// ```swift /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// let sql = "SELECT * FROM player WHERE lastName = ?" /// let players = try Player.fetchCursor(db, sql: sql, arguments: [lastName]) /// while let player = try players.next() { /// print(player.name) /// } /// } /// ``` /// /// The returned cursor is valid only during the remaining execution of the /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// /// - parameters: /// - db: A database connection. /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter /// - returns: A ``RecordCursor`` over fetched records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) throws -> RecordCursor<Self> { try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } /// Returns an array of records fetched from an SQL query. /// /// For example: /// /// ```swift /// let players = try dbQueue.read { db in /// let lastName = "O'Reilly" /// let sql = "SELECT * FROM player WHERE lastName = ?" /// return try Player.fetchAll(db, sql: sql, arguments: [lastName]) /// } /// ``` /// /// - parameters: /// - db: A database connection. /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) throws -> [Self] { try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } /// Returns a single record fetched from an SQL query. /// /// For example: /// /// ```swift /// let player = try dbQueue.read { db in /// let lastName = "O'Reilly" /// let sql = "SELECT * FROM player WHERE lastName = ? LIMIT 1" /// return try Player.fetchOne(db, sql: sql, arguments: [lastName]) /// } /// ``` /// /// - parameters: /// - db: A database connection. /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) throws -> Self? { try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } extension FetchableRecord where Self: Hashable { /// Returns a set of records fetched from an SQL query. /// /// For example: /// /// ```swift /// let players = try dbQueue.read { db in /// let lastName = "O'Reilly" /// let sql = "SELECT * FROM player WHERE lastName = ?" /// return try Player.fetchSet(db, sql: sql, arguments: [lastName]) /// } /// ``` /// /// - parameters: /// - db: A database connection. /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) throws -> Set<Self> { try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } extension FetchableRecord { // MARK: Fetching From FetchRequest /// Returns a cursor over records fetched from a fetch request. /// /// For example: /// /// ```swift /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player.filter(Column("lastName") == lastName) /// /// // SQL request /// let request: SQLRequest<Player> = """ /// SELECT * FROM player WHERE lastName = \(lastName) /// """ /// /// let players = try Player.fetchCursor(db, request) /// while let player = try players.next() { /// print(player.name) /// } /// } /// ``` /// /// The returned cursor is valid only during the remaining execution of the /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// /// - parameters: /// - db: A database connection. /// - sql: a FetchRequest. /// - returns: A ``RecordCursor`` over fetched records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> RecordCursor<Self> { let request = try request.makePreparedRequest(db, forSingleResult: false) precondition(request.supplementaryFetch == nil, "Not implemented: fetchCursor with supplementary fetch") return try fetchCursor(request.statement, adapter: request.adapter) } /// Returns an array of records fetched from a fetch request. /// /// For example: /// /// ```swift /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player.filter(Column("lastName") == lastName) /// /// // SQL request /// let request: SQLRequest<Player> = """ /// SELECT * FROM player WHERE lastName = \(lastName) /// """ /// /// let players = try Player.fetchAll(db, request) /// } /// ``` /// /// - parameters: /// - db: A database connection. /// - sql: a FetchRequest. /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] { let request = try request.makePreparedRequest(db, forSingleResult: false) if let supplementaryFetch = request.supplementaryFetch { let rows = try Row.fetchAll(request.statement, adapter: request.adapter) try supplementaryFetch(db, rows) return try rows.map(Self.init(row:)) } else { return try fetchAll(request.statement, adapter: request.adapter) } } /// Returns a single record fetched from a fetch request. /// /// For example: /// /// ```swift /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player.filter(Column("lastName") == lastName) /// /// // SQL request /// let request: SQLRequest<Player> = """ /// SELECT * FROM player WHERE lastName = \(lastName) LIMIT 1 /// """ /// /// let player = try Player.fetchOne(db, request) /// } /// ``` /// - parameters: /// - db: A database connection. /// - sql: a FetchRequest. /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? { let request = try request.makePreparedRequest(db, forSingleResult: true) if let supplementaryFetch = request.supplementaryFetch { guard let row = try Row.fetchOne(request.statement, adapter: request.adapter) else { return nil } try supplementaryFetch(db, [row]) return try .init(row: row) } else { return try fetchOne(request.statement, adapter: request.adapter) } } } extension FetchableRecord where Self: Hashable { /// Returns a set of records fetched from a fetch request. /// /// For example: /// /// ```swift /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player.filter(Column("lastName") == lastName) /// /// // SQL request /// let request: SQLRequest<Player> = """ /// SELECT * FROM player WHERE lastName = \(lastName) /// """ /// /// let players = try Player.fetchSet(db, request) /// } /// ``` /// /// - parameters: /// - db: A database connection. /// - sql: a FetchRequest. /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> { let request = try request.makePreparedRequest(db, forSingleResult: false) if let supplementaryFetch = request.supplementaryFetch { let rows = try Row.fetchAll(request.statement, adapter: request.adapter) try supplementaryFetch(db, rows) return try Set(rows.lazy.map(Self.init(row:))) } else { return try fetchSet(request.statement, adapter: request.adapter) } } } // MARK: - FetchRequest extension FetchRequest where RowDecoder: FetchableRecord { // MARK: Fetching Records /// Returns a cursor over fetched records. /// /// For example: /// /// ```swift /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player.filter(Column("lastName") == lastName) /// /// // SQL request /// let request: SQLRequest<Player> = """ /// SELECT * FROM player WHERE lastName = \(lastName) /// """ /// /// let players = try request.fetchCursor(db) /// while let player = try players.next() { /// print(player.name) /// } /// } /// ``` /// /// The returned cursor is valid only during the remaining execution of the /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// /// - parameters: /// - db: A database connection. /// - sql: a FetchRequest. /// - returns: A ``RecordCursor`` over fetched records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> RecordCursor<RowDecoder> { try RowDecoder.fetchCursor(db, self) } /// Returns an array of fetched records. /// /// For example: /// /// ```swift /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player.filter(Column("lastName") == lastName) /// /// // SQL request /// let request: SQLRequest<Player> = """ /// SELECT * FROM player WHERE lastName = \(lastName) /// """ /// /// let players = try request.fetchAll(db) /// } /// ``` /// /// - parameters: /// - db: A database connection. /// - sql: a FetchRequest. /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [RowDecoder] { try RowDecoder.fetchAll(db, self) } /// Returns a single record. /// /// For example: /// /// ```swift /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player.filter(Column("lastName") == lastName) /// /// // SQL request /// let request: SQLRequest<Player> = """ /// SELECT * FROM player WHERE lastName = \(lastName) LIMIT 1 /// """ /// /// let player = try request.fetchOne(db) /// } /// ``` /// - parameters: /// - db: A database connection. /// - sql: a FetchRequest. /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> RowDecoder? { try RowDecoder.fetchOne(db, self) } } extension FetchRequest where RowDecoder: FetchableRecord & Hashable { /// Returns a set of fetched records. /// /// For example: /// /// ```swift /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player.filter(Column("lastName") == lastName) /// /// // SQL request /// let request: SQLRequest<Player> = """ /// SELECT * FROM player WHERE lastName = \(lastName) /// """ /// /// let players = try request.fetchSet(db) /// } /// ``` /// /// - parameters: /// - db: A database connection. /// - sql: a FetchRequest. /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchSet(_ db: Database) throws -> Set<RowDecoder> { try RowDecoder.fetchSet(db, self) } } // MARK: - RecordCursor /// A cursor of records. /// /// A `RecordCursor` iterates all rows from a database request. Its /// elements are the records decoded from each fetched row. /// /// For example: /// /// ```swift /// try dbQueue.read { db in /// let players: RecordCursor<Player> = try Player.fetchCursor(db, sql: "SELECT * FROM player") /// while let player = try players.next() { /// print(player.name) /// } /// } /// ``` public final class RecordCursor<Record: FetchableRecord>: DatabaseCursor { public typealias Element = Record public let _statement: Statement public var _isDone = false @usableFromInline let _row: Row // Instantiated once, reused for performance init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws { self._statement = statement _row = try Row(statement: statement).adapted(with: adapter, layout: statement) try statement.reset(withArguments: arguments) } deinit { // Statement reset fails when sqlite3_step has previously failed. // Just ignore reset error. try? _statement.reset() } @inlinable public func _element(sqliteStatement: SQLiteStatement) throws -> Record { try Record(row: _row) } } // MARK: - DatabaseDateDecodingStrategy /// `DatabaseDateDecodingStrategy` specifies how `FetchableRecord` types that /// also adopt the standard `Decodable` protocol decode their /// `Date` properties. /// /// For example: /// /// struct Player: FetchableRecord, Decodable { /// static let databaseDateDecodingStrategy = DatabaseDateDecodingStrategy.timeIntervalSince1970 /// /// var name: String /// var registrationDate: Date // decoded from epoch timestamp /// } public enum DatabaseDateDecodingStrategy { /// The strategy that uses formatting from the Date structure. /// /// It decodes numeric values as a number of seconds since Epoch /// (midnight UTC on January 1st, 1970). /// /// It decodes strings in the following formats, assuming UTC time zone. /// Missing components are assumed to be zero: /// /// - `YYYY-MM-DD` /// - `YYYY-MM-DD HH:MM` /// - `YYYY-MM-DD HH:MM:SS` /// - `YYYY-MM-DD HH:MM:SS.SSS` /// - `YYYY-MM-DDTHH:MM` /// - `YYYY-MM-DDTHH:MM:SS` /// - `YYYY-MM-DDTHH:MM:SS.SSS` case deferredToDate /// Decodes numeric values as a number of seconds between the date and /// midnight UTC on 1 January 2001 case timeIntervalSinceReferenceDate /// Decodes numeric values as a number of seconds between the date and /// midnight UTC on 1 January 1970 case timeIntervalSince1970 /// Decodes numeric values as a number of milliseconds between the date and /// midnight UTC on 1 January 1970 case millisecondsSince1970 /// Decodes dates according to the ISO 8601 standards case iso8601 /// Decodes a String, according to the provided formatter case formatted(DateFormatter) /// Decodes according to the user-provided function. /// /// If the database value does not contain a suitable value, the function /// must return nil (GRDB will interpret this nil result as a conversion /// error, and react accordingly). case custom((DatabaseValue) -> Date?) } // MARK: - DatabaseColumnDecodingStrategy /// `DatabaseColumnDecodingStrategy` specifies how `FetchableRecord` types that /// also adopt the standard `Decodable` protocol look for the database columns /// that match their coding keys. /// /// For example: /// /// struct Player: FetchableRecord, Decodable { /// static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.convertFromSnakeCase /// /// // Decoded from the player_id column /// var playerID: Int /// } public enum DatabaseColumnDecodingStrategy { /// A key decoding strategy that doesn’t change key names during decoding. case useDefaultKeys /// A key decoding strategy that converts snake-case keys to camel-case keys. case convertFromSnakeCase /// A key decoding strategy defined by the closure you supply. case custom((String) -> CodingKey) func key<K: CodingKey>(forColumn column: String) -> K? { switch self { case .useDefaultKeys: return K(stringValue: column) case .convertFromSnakeCase: return K(stringValue: Self._convertFromSnakeCase(column)) case let .custom(key): return K(stringValue: key(column).stringValue) } } // Copied straight from // https://github.com/apple/swift-corelibs-foundation/blob/8d6398d76eaf886a214e0bb2bd7549d968f7b40e/Sources/Foundation/JSONDecoder.swift#L103 static func _convertFromSnakeCase(_ stringKey: String) -> String { //===----------------------------------------------------------------------===// // // This function is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// guard !stringKey.isEmpty else { return stringKey } // Find the first non-underscore character guard let firstNonUnderscore = stringKey.firstIndex(where: { $0 != "_" }) else { // Reached the end without finding an _ return stringKey } // Find the last non-underscore character var lastNonUnderscore = stringKey.index(before: stringKey.endIndex) while lastNonUnderscore > firstNonUnderscore && stringKey[lastNonUnderscore] == "_" { stringKey.formIndex(before: &lastNonUnderscore) } let keyRange = firstNonUnderscore...lastNonUnderscore let leadingUnderscoreRange = stringKey.startIndex..<firstNonUnderscore let trailingUnderscoreRange = stringKey.index(after: lastNonUnderscore)..<stringKey.endIndex let components = stringKey[keyRange].split(separator: "_") let joinedString: String if components.count == 1 { // No underscores in key, leave the word as is - maybe already camel cased joinedString = String(stringKey[keyRange]) } else { joinedString = ([components[0].lowercased()] + components[1...].map { $0.capitalized }).joined() } // Do a cheap isEmpty check before creating and appending potentially empty strings let result: String if leadingUnderscoreRange.isEmpty && trailingUnderscoreRange.isEmpty { result = joinedString } else if !leadingUnderscoreRange.isEmpty && !trailingUnderscoreRange.isEmpty { // Both leading and trailing underscores result = String(stringKey[leadingUnderscoreRange]) + joinedString + String(stringKey[trailingUnderscoreRange]) } else if !leadingUnderscoreRange.isEmpty { // Just leading result = String(stringKey[leadingUnderscoreRange]) + joinedString } else { // Just trailing result = joinedString + String(stringKey[trailingUnderscoreRange]) } return result } }
mit
541291e60f9a672db1c7ed06a22c9a70
33.65535
145
0.590471
4.628332
false
false
false
false
royhsu/tiny-core
Sources/Core/HTTP/HTTPRequest+URLRequestRepresentable.swift
1
894
// // HTTPRequest+URLRequestRepresentable.swift // TinyCore // // Created by Roy Hsu on 2019/1/26. // Copyright © 2019 TinyWorld. All rights reserved. // // MARK: - URLRequestRepresentable extension HTTPRequest: URLRequestRepresentable { public func urlRequest() throws -> URLRequest { var request = URLRequest(url: url) request.httpMethod = method.rawValue var headers = self.headers if let body = body { request.httpBody = try bodyEncoder.encode(body) let mime: MIMEType switch bodyEncoder { case is JSONEncoder: mime = .json default: fatalError("Unsupported HTTP Body Encoder.") } let header = try mime.httpHeader() headers[header.field] = header.value } request.setHTTPHeaders(headers) return request } }
mit
a981b1674e1f82a281096ff9d94ebc7b
18
65
0.606943
4.801075
false
false
false
false
robzimpulse/mynurzSDK
Example/mynurzSDK/CardViewViewController.swift
1
1148
// // CardViewViewController.swift // mynurzSDK // // Created by Robyarta on 6/10/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit class CardViewViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } @IBDesignable class CardView: UIView { @IBInspectable var cornerRadius: CGFloat = 2 @IBInspectable var shadowOffsetWidth: Int = 0 @IBInspectable var shadowOffsetHeight: Int = 3 @IBInspectable var shadowColor: UIColor? = UIColor.black @IBInspectable var shadowOpacity: Float = 0.5 override func layoutSubviews() { layer.cornerRadius = cornerRadius let shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius) layer.masksToBounds = false layer.shadowColor = shadowColor?.cgColor layer.shadowOffset = CGSize(width: shadowOffsetWidth, height: shadowOffsetHeight); layer.shadowOpacity = shadowOpacity layer.shadowPath = shadowPath.cgPath } }
mit
746ef3852e5c9eee09402b1b309939e3
25.068182
90
0.68701
5.190045
false
false
false
false
magnetsystems/message-samples-ios
QuickStart/QuickStart/ChannelCell.swift
1
1830
/* * Copyright (c) 2015 Magnet Systems, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ import UIKit import MagnetMax class ChannelCell: UITableViewCell { // MARK: Outlets @IBOutlet weak var ivPrivate: UIImageView! @IBOutlet weak var lblChannelName: UILabel! @IBOutlet weak var lblLastTime: UILabel! @IBOutlet weak var lblTags: UILabel! // MARK: Public properties var channel : MMXChannel! { didSet { lblChannelName.text = channel.name ivPrivate.image = channel.isPublic ? nil : UIImage(named: "lock-7.png") let formatter = NSDateFormatter() formatter.timeStyle = .ShortStyle lblLastTime.text = formatter.stringFromDate(channel.lastTimeActive) channel.tagsWithSuccess({ (tags) -> Void in var stringForTags = "" for tag in tags { stringForTags.appendContentsOf("\(tag) ") } self.lblTags.text = stringForTags }) { (error) -> Void in print(error) } } } // MARK: Overrides override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
apache-2.0
ef8cb9cee7995676f73a998e314e093f
26.727273
83
0.610929
4.84127
false
false
false
false
jholsapple/TIY-Assignments
30 -- HighVoltage -- John Holsapple/30 -- HighVoltage -- John Holsapple/ConversionsTableViewController.swift
2
6625
// // ConversionsTableViewController.swift // 30 -- HighVoltage -- John Holsapple // // Created by John Holsapple on 7/24/15. // Copyright (c) 2015 John Holsapple -- The Iron Yard. All rights reserved. // import UIKit protocol PopoverVCDelegate { func valueTypeWasChosen(chosenValueType: String) } protocol ElectricityModelDelegate { func valuesWereCalculated() } class ConversionsTableViewController: UITableViewController, UIPopoverPresentationControllerDelegate, PopoverVCDelegate, UITextFieldDelegate, ElectricityModelDelegate { var tableData = [String]() let valueTypes = ["Watts": "WattsCell", "Volts": "VoltsCell", "Amps": "AmpsCell", "Ohms": "OhmsCell"] var ampsTextField: UITextField? var wattsTextField: UITextField? var voltsTextField: UITextField? var ohmsTextField: UITextField? var electricityConverter = ElectricityModel() func valuesWereCalculated() { if voltsTextField == nil { let cellIdentifier = valueTypes["Volts"] tableData.append(cellIdentifier!) } if ampsTextField == nil { let cellIdentifier = valueTypes["Amps"] tableData.append(cellIdentifier!) } if wattsTextField == nil { let cellIdentifier = valueTypes["Watts"] tableData.append(cellIdentifier!) } if ohmsTextField == nil { let cellIdentifier = valueTypes["Ohms"] tableData.append(cellIdentifier!) } tableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() electricityConverter.delegate = self // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. self.navigationItem.leftBarButtonItem = self.editButtonItem() } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { switch editingStyle { case .Delete: self.tableData.removeAtIndex(indexPath.row) self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) default: return } } override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { let row = self.tableData.removeAtIndex(sourceIndexPath.row) self.tableData.insert(row, atIndex: destinationIndexPath.row) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return tableData.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = tableData[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) let textField = cell.viewWithTag(1) as! UITextField switch identifier { case "WattsCell": wattsTextField = textField if electricityConverter.wattsString != "" { textField.text = electricityConverter.wattsString } case "AmpsCell": ampsTextField = textField if electricityConverter.ampsString != "" { textField.text = electricityConverter.ampsString } case "VoltsCell": voltsTextField = textField if electricityConverter.voltsString != "" { textField.text = electricityConverter.voltsString } case "OhmsCell": ohmsTextField = textField if electricityConverter.ohmsString != "" { textField.text = electricityConverter.ohmsString } default: print("") } return cell } func valueTypeWasChosen(chosenValueType: String) { navigationController?.dismissViewControllerAnimated(true, completion: nil) let identifier = valueTypes[chosenValueType] tableData.append(identifier!) tableView.reloadData() } func textFieldShouldReturn(textField: UITextField) -> Bool { var textFieldReturn = false if textField.text != "" { textFieldReturn = true if textField == ampsTextField { electricityConverter.ampsString = textField.text! } if textField == wattsTextField { electricityConverter.wattsString = textField.text! } if textField == voltsTextField { electricityConverter.voltsString = textField.text! } if textField == ohmsTextField { electricityConverter.ohmsString = textField.text! } } if textFieldReturn { textField.resignFirstResponder() } electricityConverter.findOtherValuesIfPossible() return textFieldReturn } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "PopoverSegue" { if let controller = segue.destinationViewController as? PopoverTableViewController { controller.popoverPresentationController!.delegate = self controller.delegate = self controller.preferredContentSize = CGSize(width: 100, height: 44 * valueTypes.count) controller.dataTypes = valueTypes.keys.values print("Roadhouse!") } } } func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return UIModalPresentationStyle.None } }
cc0-1.0
44c6751b01ceb8b798ce69d639df45a8
30.398104
166
0.622943
5.868025
false
false
false
false
halo/LinkLiar
LinkTools/Log.swift
1
2979
/* * Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar * * 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 os.log import Foundation public struct Log { private static let log = OSLog(subsystem: Identifiers.gui.rawValue, category: "logger") public static func debug(_ message: String, callerPath: String = #file) { write(message, level: .debug, callerPath: callerPath) } public static func info(_ message: String, callerPath: String = #file) { write(message, level: .info, callerPath: callerPath) } public static func error(_ message: String, callerPath: String = #file) { write(message, level: .error, callerPath: callerPath) } private static func write(_ message: String, level: OSLogType, callerPath: String) { guard let filename = callerPath.components(separatedBy: "/").last else { return write(message, level: level) } guard let classname = filename.components(separatedBy: ".").first else { return write(message, level: level) } write("\(classname) - \(message)", level: level) } private static func write(_ message: String, level: OSLogType) { os_log("%{public}@", log: log, type: level, message) appendToLogfile(message, level: level) } private static func appendToLogfile(_ message: String, level: OSLogType) { var prefix = "UNKNOWN" switch level { case OSLogType.debug: prefix = "DEBUG" case OSLogType.info: prefix = "INFO" case OSLogType.error: prefix = "ERROR" default: prefix = "DEFAULT" } let data = "\(prefix) \(message)\n".data(using: .utf8)! if let fileHandle = FileHandle(forWritingAtPath: Paths.debugLogFile) { defer { fileHandle.closeFile() } fileHandle.seekToEndOfFile() fileHandle.write(data) } else { // There is no logfile, which means the end-user does not want file logging // You may also end up here if you turned on app sandboxing. } } }
mit
c3175683226c90a005a080b0bc795ecc
38.197368
133
0.707284
4.317391
false
false
false
false
apple/swift-async-algorithms
Sources/AsyncAlgorithms/Merge/MergeStateMachine.swift
1
24933
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Async Algorithms open source project // // Copyright (c) 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// @_implementationOnly import DequeModule /// The state machine for any of the `merge` operator. /// /// Right now this state machine supports 3 upstream `AsyncSequences`; however, this can easily be extended. /// Once variadic generic land we should migrate this to use them instead. struct MergeStateMachine< Base1: AsyncSequence, Base2: AsyncSequence, Base3: AsyncSequence > where Base1.Element == Base2.Element, Base1.Element == Base3.Element, Base1: Sendable, Base2: Sendable, Base3: Sendable, Base1.Element: Sendable { typealias Element = Base1.Element private enum State { /// The initial state before a call to `makeAsyncIterator` happened. case initial( base1: Base1, base2: Base2, base3: Base3? ) /// The state after `makeAsyncIterator` was called and we created our `Task` to consume the upstream. case merging( task: Task<Void, Never>, buffer: Deque<Element>, upstreamContinuations: [UnsafeContinuation<Void, Error>], upstreamsFinished: Int, downstreamContinuation: UnsafeContinuation<Element?, Error>? ) /// The state once any of the upstream sequences threw an `Error`. case upstreamFailure( buffer: Deque<Element>, error: Error ) /// The state once all upstream sequences finished or the downstream consumer stopped, i.e. by dropping all references /// or by getting their `Task` cancelled. case finished /// Internal state to avoid CoW. case modifying } /// The state machine's current state. private var state: State private let numberOfUpstreamSequences: Int /// Initializes a new `StateMachine`. init( base1: Base1, base2: Base2, base3: Base3? ) { state = .initial( base1: base1, base2: base2, base3: base3 ) if base3 == nil { self.numberOfUpstreamSequences = 2 } else { self.numberOfUpstreamSequences = 3 } } /// Actions returned by `iteratorDeinitialized()`. enum IteratorDeinitializedAction { /// Indicates that the `Task` needs to be cancelled and /// all upstream continuations need to be resumed with a `CancellationError`. case cancelTaskAndUpstreamContinuations( task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) /// Indicates that nothing should be done. case none } mutating func iteratorDeinitialized() -> IteratorDeinitializedAction { switch state { case .initial: // Nothing to do here. No demand was signalled until now return .none case .merging(_, _, _, _, .some): // An iterator was deinitialized while we have a suspended continuation. preconditionFailure("Internal inconsistency current state \(self.state) and received iteratorDeinitialized()") case let .merging(task, _, upstreamContinuations, _, .none): // The iterator was dropped which signals that the consumer is finished. // We can transition to finished now and need to clean everything up. state = .finished return .cancelTaskAndUpstreamContinuations( task: task, upstreamContinuations: upstreamContinuations ) case .upstreamFailure: // The iterator was dropped which signals that the consumer is finished. // We can transition to finished now. The cleanup already happened when we // transitioned to `upstreamFailure`. state = .finished return .none case .finished: // We are already finished so there is nothing left to clean up. // This is just the references dropping afterwards. return .none case .modifying: preconditionFailure("Invalid state") } } mutating func taskStarted(_ task: Task<Void, Never>) { switch state { case .initial: // The user called `makeAsyncIterator` and we are starting the `Task` // to consume the upstream sequences state = .merging( task: task, buffer: .init(), upstreamContinuations: [], // This should reserve capacity in the variadic generics case upstreamsFinished: 0, downstreamContinuation: nil ) case .merging, .upstreamFailure, .finished: // We only a single iterator to be created so this must never happen. preconditionFailure("Internal inconsistency current state \(self.state) and received taskStarted()") case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `childTaskSuspended()`. enum ChildTaskSuspendedAction { /// Indicates that the continuation should be resumed which will lead to calling `next` on the upstream. case resumeContinuation( upstreamContinuation: UnsafeContinuation<Void, Error> ) /// Indicates that the continuation should be resumed with an Error because another upstream sequence threw. case resumeContinuationWithError( upstreamContinuation: UnsafeContinuation<Void, Error>, error: Error ) /// Indicates that nothing should be done. case none } mutating func childTaskSuspended(_ continuation: UnsafeContinuation<Void, Error>) -> ChildTaskSuspendedAction { switch state { case .initial: // Child tasks are only created after we transitioned to `merging` preconditionFailure("Internal inconsistency current state \(self.state) and received childTaskSuspended()") case .merging(_, _, _, _, .some): // We have outstanding demand so request the next element return .resumeContinuation(upstreamContinuation: continuation) case .merging(let task, let buffer, var upstreamContinuations, let upstreamsFinished, .none): // There is no outstanding demand from the downstream // so we are storing the continuation and resume it once there is demand. state = .modifying upstreamContinuations.append(continuation) state = .merging( task: task, buffer: buffer, upstreamContinuations: upstreamContinuations, upstreamsFinished: upstreamsFinished, downstreamContinuation: nil ) return .none case .upstreamFailure: // Another upstream already threw so we just need to throw from this continuation // which will end the consumption of the upstream. return .resumeContinuationWithError( upstreamContinuation: continuation, error: CancellationError() ) case .finished: // Since cancellation is cooperative it might be that child tasks are still getting // suspended even though we already cancelled them. We must tolerate this and just resume // the continuation with an error. return .resumeContinuationWithError( upstreamContinuation: continuation, error: CancellationError() ) case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `elementProduced()`. enum ElementProducedAction { /// Indicates that the downstream continuation should be resumed with the element. case resumeContinuation( downstreamContinuation: UnsafeContinuation<Element?, Error>, element: Element ) /// Indicates that nothing should be done. case none } mutating func elementProduced(_ element: Element) -> ElementProducedAction { switch state { case .initial: // Child tasks that are producing elements are only created after we transitioned to `merging` preconditionFailure("Internal inconsistency current state \(self.state) and received elementProduced()") case let .merging(task, buffer, upstreamContinuations, upstreamsFinished, .some(downstreamContinuation)): // We produced an element and have an outstanding downstream continuation // this means we can go right ahead and resume the continuation with that element precondition(buffer.isEmpty, "We are holding a continuation so the buffer must be empty") state = .merging( task: task, buffer: buffer, upstreamContinuations: upstreamContinuations, upstreamsFinished: upstreamsFinished, downstreamContinuation: nil ) return .resumeContinuation( downstreamContinuation: downstreamContinuation, element: element ) case .merging(let task, var buffer, let upstreamContinuations, let upstreamsFinished, .none): // There is not outstanding downstream continuation so we must buffer the element // This happens if we race our upstream sequences to produce elements // and the _losers_ are signalling their produced element state = .modifying buffer.append(element) state = .merging( task: task, buffer: buffer, upstreamContinuations: upstreamContinuations, upstreamsFinished: upstreamsFinished, downstreamContinuation: nil ) return .none case .upstreamFailure: // Another upstream already produced an error so we just drop the new element return .none case .finished: // Since cancellation is cooperative it might be that child tasks // are still producing elements after we finished. // We are just going to drop them since there is nothing we can do return .none case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `upstreamFinished()`. enum UpstreamFinishedAction { /// Indicates that the task and the upstream continuations should be cancelled. case cancelTaskAndUpstreamContinuations( task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) /// Indicates that the downstream continuation should be resumed with `nil` and /// the task and the upstream continuations should be cancelled. case resumeContinuationWithNilAndCancelTaskAndUpstreamContinuations( downstreamContinuation: UnsafeContinuation<Element?, Error>, task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) /// Indicates that nothing should be done. case none } mutating func upstreamFinished() -> UpstreamFinishedAction { switch state { case .initial: preconditionFailure("Internal inconsistency current state \(self.state) and received upstreamFinished()") case .merging(let task, let buffer, let upstreamContinuations, var upstreamsFinished, let .some(downstreamContinuation)): // One of the upstreams finished precondition(buffer.isEmpty, "We are holding a continuation so the buffer must be empty") // First we increment our counter of finished upstreams upstreamsFinished += 1 if upstreamsFinished == self.numberOfUpstreamSequences { // All of our upstreams have finished and we can transition to finished now // We also need to cancel the tasks and any outstanding continuations state = .finished return .resumeContinuationWithNilAndCancelTaskAndUpstreamContinuations( downstreamContinuation: downstreamContinuation, task: task, upstreamContinuations: upstreamContinuations ) } else { // There are still upstreams that haven't finished so we are just storing our new // counter of finished upstreams state = .merging( task: task, buffer: buffer, upstreamContinuations: upstreamContinuations, upstreamsFinished: upstreamsFinished, downstreamContinuation: downstreamContinuation ) return .none } case .merging(let task, let buffer, let upstreamContinuations, var upstreamsFinished, .none): // First we increment our counter of finished upstreams upstreamsFinished += 1 state = .merging( task: task, buffer: buffer, upstreamContinuations: upstreamContinuations, upstreamsFinished: upstreamsFinished, downstreamContinuation: nil ) if upstreamsFinished == self.numberOfUpstreamSequences { // All of our upstreams have finished; however, we are only transitioning to // finished once our downstream calls `next` again. return .cancelTaskAndUpstreamContinuations( task: task, upstreamContinuations: upstreamContinuations ) } else { // There are still upstreams that haven't finished. return .none } case .upstreamFailure: // Another upstream threw already so we can just ignore this finish return .none case .finished: // This is just everything finishing up, nothing to do here return .none case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `upstreamThrew()`. enum UpstreamThrewAction { /// Indicates that the task and the upstream continuations should be cancelled. case cancelTaskAndUpstreamContinuations( task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) /// Indicates that the downstream continuation should be resumed with the `error` and /// the task and the upstream continuations should be cancelled. case resumeContinuationWithErrorAndCancelTaskAndUpstreamContinuations( downstreamContinuation: UnsafeContinuation<Element?, Error>, error: Error, task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) /// Indicates that nothing should be done. case none } mutating func upstreamThrew(_ error: Error) -> UpstreamThrewAction { switch state { case .initial: preconditionFailure("Internal inconsistency current state \(self.state) and received upstreamThrew()") case let .merging(task, buffer, upstreamContinuations, _, .some(downstreamContinuation)): // An upstream threw an error and we have a downstream continuation. // We just need to resume the downstream continuation with the error and cancel everything precondition(buffer.isEmpty, "We are holding a continuation so the buffer must be empty") // We can transition to finished right away because we are returning the error state = .finished return .resumeContinuationWithErrorAndCancelTaskAndUpstreamContinuations( downstreamContinuation: downstreamContinuation, error: error, task: task, upstreamContinuations: upstreamContinuations ) case let .merging(task, buffer, upstreamContinuations, _, .none): // An upstream threw an error and we don't have a downstream continuation. // We need to store the error and wait for the downstream to consume the // rest of the buffer and the error. However, we can already cancel the task // and the other upstream continuations since we won't need any more elements. state = .upstreamFailure( buffer: buffer, error: error ) return .cancelTaskAndUpstreamContinuations( task: task, upstreamContinuations: upstreamContinuations ) case .upstreamFailure: // Another upstream threw already so we can just ignore this error return .none case .finished: // This is just everything finishing up, nothing to do here return .none case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `cancelled()`. enum CancelledAction { /// Indicates that the downstream continuation needs to be resumed and /// task and the upstream continuations should be cancelled. case resumeDownstreamContinuationWithNilAndCancelTaskAndUpstreamContinuations( downstreamContinuation: UnsafeContinuation<Element?, Error>, task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) /// Indicates that the task and the upstream continuations should be cancelled. case cancelTaskAndUpstreamContinuations( task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) /// Indicates that nothing should be done. case none } mutating func cancelled() -> CancelledAction { switch state { case .initial: // Since we are transitioning to `merging` before we return from `makeAsyncIterator` // this can never happen preconditionFailure("Internal inconsistency current state \(self.state) and received cancelled()") case let .merging(task, _, upstreamContinuations, _, .some(downstreamContinuation)): // The downstream Task got cancelled so we need to cancel our upstream Task // and resume all continuations. We can also transition to finished. state = .finished return .resumeDownstreamContinuationWithNilAndCancelTaskAndUpstreamContinuations( downstreamContinuation: downstreamContinuation, task: task, upstreamContinuations: upstreamContinuations ) case let .merging(task, _, upstreamContinuations, _, .none): // The downstream Task got cancelled so we need to cancel our upstream Task // and resume all continuations. We can also transition to finished. state = .finished return .cancelTaskAndUpstreamContinuations( task: task, upstreamContinuations: upstreamContinuations ) case .upstreamFailure: // An upstream already threw and we cancelled everything already. // We can just transition to finished now state = .finished return .none case .finished: // We are already finished so nothing to do here: state = .finished return .none case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `next()`. enum NextAction { /// Indicates that a new `Task` should be created that consumes the sequence and the downstream must be supsended case startTaskAndSuspendDownstreamTask(Base1, Base2, Base3?) /// Indicates that the `element` should be returned. case returnElement(Result<Element, Error>) /// Indicates that `nil` should be returned. case returnNil /// Indicates that the `error` should be thrown. case throwError(Error) /// Indicates that the downstream task should be suspended. case suspendDownstreamTask } mutating func next() -> NextAction { switch state { case .initial(let base1, let base2, let base3): // This is the first time we got demand signalled. We need to start the task now // We are transitioning to merging in the taskStarted method. return .startTaskAndSuspendDownstreamTask(base1, base2, base3) case .merging(_, _, _, _, .some): // We have multiple AsyncIterators iterating the sequence preconditionFailure("Internal inconsistency current state \(self.state) and received next()") case .merging(let task, var buffer, let upstreamContinuations, let upstreamsFinished, .none): state = .modifying if let element = buffer.popFirst() { // We have an element buffered already so we can just return that. state = .merging( task: task, buffer: buffer, upstreamContinuations: upstreamContinuations, upstreamsFinished: upstreamsFinished, downstreamContinuation: nil ) return .returnElement(.success(element)) } else { // There was nothing in the buffer so we have to suspend the downstream task state = .merging( task: task, buffer: buffer, upstreamContinuations: upstreamContinuations, upstreamsFinished: upstreamsFinished, downstreamContinuation: nil ) return .suspendDownstreamTask } case .upstreamFailure(var buffer, let error): state = .modifying if let element = buffer.popFirst() { // There was still a left over element that we need to return state = .upstreamFailure( buffer: buffer, error: error ) return .returnElement(.success(element)) } else { // The buffer is empty and we can now throw the error // that an upstream produced state = .finished return .throwError(error) } case .finished: // We are already finished so we are just returning `nil` return .returnNil case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `next(for)`. enum NextForAction { /// Indicates that the upstream continuations should be resumed to demand new elements. case resumeUpstreamContinuations( upstreamContinuations: [UnsafeContinuation<Void, Error>] ) } mutating func next(for continuation: UnsafeContinuation<Element?, Error>) -> NextForAction { switch state { case .initial, .merging(_, _, _, _, .some), .upstreamFailure, .finished: // All other states are handled by `next` already so we should never get in here with // any of those preconditionFailure("Internal inconsistency current state \(self.state) and received next(for:)") case let .merging(task, buffer, upstreamContinuations, upstreamsFinished, .none): // We suspended the task and need signal the upstreams state = .merging( task: task, buffer: buffer, upstreamContinuations: [], // TODO: don't alloc new array here upstreamsFinished: upstreamsFinished, downstreamContinuation: continuation ) return .resumeUpstreamContinuations( upstreamContinuations: upstreamContinuations ) case .modifying: preconditionFailure("Invalid state") } } }
apache-2.0
e202eb01ff272eabf30ddd724acb849e
38.76555
129
0.606465
6.202239
false
false
false
false
easyui/Alamofire
Source/Request.swift
1
78663
// // Request.swift // // Copyright (c) 2014-2020 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback /// handling. public class Request { /// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or /// `cancel()` on the `Request`. public enum State { /// Initial state of the `Request`. case initialized /// `State` set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on /// them in this state. case resumed /// `State` set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on /// them in this state. case suspended /// `State` set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on /// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer transition /// to any other state. case cancelled /// `State` set when all response serialization completion closures have been cleared on the `Request` and /// enqueued on their respective queues. case finished /// Determines whether `self` can be transitioned to the provided `State`. func canTransitionTo(_ state: State) -> Bool { switch (self, state) { case (.initialized, _): return true case (_, .initialized), (.cancelled, _), (.finished, _): return false case (.resumed, .cancelled), (.suspended, .cancelled), (.resumed, .suspended), (.suspended, .resumed): return true case (.suspended, .suspended), (.resumed, .resumed): return false case (_, .finished): return true } } } // MARK: - Initial State /// `UUID` providing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances. public let id: UUID /// The serial queue for all internal async actions. public let underlyingQueue: DispatchQueue /// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`. public let serializationQueue: DispatchQueue /// `EventMonitor` used for event callbacks. public let eventMonitor: EventMonitor? /// The `Request`'s interceptor. public let interceptor: RequestInterceptor? /// The `Request`'s delegate. public private(set) weak var delegate: RequestDelegate? // MARK: - Mutable State /// Type encapsulating all mutable state that may need to be accessed from anything other than the `underlyingQueue`. struct MutableState { /// State of the `Request`. var state: State = .initialized /// `ProgressHandler` and `DispatchQueue` provided for upload progress callbacks. var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? /// `ProgressHandler` and `DispatchQueue` provided for download progress callbacks. var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? /// `RedirectHandler` provided for to handle request redirection. var redirectHandler: RedirectHandler? /// `CachedResponseHandler` provided to handle response caching. var cachedResponseHandler: CachedResponseHandler? /// Queue and closure called when the `Request` is able to create a cURL description of itself. var cURLHandler: (queue: DispatchQueue, handler: (String) -> Void)? /// Queue and closure called when the `Request` creates a `URLRequest`. var urlRequestHandler: (queue: DispatchQueue, handler: (URLRequest) -> Void)? /// Queue and closure called when the `Request` creates a `URLSessionTask`. var urlSessionTaskHandler: (queue: DispatchQueue, handler: (URLSessionTask) -> Void)? /// Response serialization closures that handle response parsing. var responseSerializers: [() -> Void] = [] /// Response serialization completion closures executed once all response serializers are complete. var responseSerializerCompletions: [() -> Void] = [] /// Whether response serializer processing is finished. var responseSerializerProcessingFinished = false /// `URLCredential` used for authentication challenges. var credential: URLCredential? /// All `URLRequest`s created by Alamofire on behalf of the `Request`. var requests: [URLRequest] = [] /// All `URLSessionTask`s created by Alamofire on behalf of the `Request`. var tasks: [URLSessionTask] = [] /// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond /// exactly the the `tasks` created. var metrics: [URLSessionTaskMetrics] = [] /// Number of times any retriers provided retried the `Request`. var retryCount = 0 /// Final `AFError` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`. var error: AFError? /// Whether the instance has had `finish()` called and is running the serializers. Should be replaced with a /// representation in the state machine in the future. var isFinishing = false } /// Protected `MutableState` value that provides thread-safe access to state values. @Protected fileprivate var mutableState = MutableState() /// `State` of the `Request`. public var state: State { mutableState.state } /// Returns whether `state` is `.initialized`. public var isInitialized: Bool { state == .initialized } /// Returns whether `state is `.resumed`. public var isResumed: Bool { state == .resumed } /// Returns whether `state` is `.suspended`. public var isSuspended: Bool { state == .suspended } /// Returns whether `state` is `.cancelled`. public var isCancelled: Bool { state == .cancelled } /// Returns whether `state` is `.finished`. public var isFinished: Bool { state == .finished } // MARK: Progress /// Closure type executed when monitoring the upload or download progress of a request. public typealias ProgressHandler = (Progress) -> Void /// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried. public let uploadProgress = Progress(totalUnitCount: 0) /// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried. public let downloadProgress = Progress(totalUnitCount: 0) /// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`. private var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { get { mutableState.uploadProgressHandler } set { mutableState.uploadProgressHandler = newValue } } /// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`. fileprivate var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { get { mutableState.downloadProgressHandler } set { mutableState.downloadProgressHandler = newValue } } // MARK: Redirect Handling /// `RedirectHandler` set on the instance. public private(set) var redirectHandler: RedirectHandler? { get { mutableState.redirectHandler } set { mutableState.redirectHandler = newValue } } // MARK: Cached Response Handling /// `CachedResponseHandler` set on the instance. public private(set) var cachedResponseHandler: CachedResponseHandler? { get { mutableState.cachedResponseHandler } set { mutableState.cachedResponseHandler = newValue } } // MARK: URLCredential /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods. public private(set) var credential: URLCredential? { get { mutableState.credential } set { mutableState.credential = newValue } } // MARK: Validators /// `Validator` callback closures that store the validation calls enqueued. @Protected fileprivate var validators: [() -> Void] = [] // MARK: URLRequests /// All `URLRequests` created on behalf of the `Request`, including original and adapted requests. public var requests: [URLRequest] { mutableState.requests } /// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed. public var firstRequest: URLRequest? { requests.first } /// Last `URLRequest` created on behalf of the `Request`. public var lastRequest: URLRequest? { requests.last } /// Current `URLRequest` created on behalf of the `Request`. public var request: URLRequest? { lastRequest } /// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`. May be different from /// `requests` due to `URLSession` manipulation. public var performedRequests: [URLRequest] { $mutableState.read { $0.tasks.compactMap { $0.currentRequest } } } // MARK: HTTPURLResponse /// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the /// last `URLSessionTask`. public var response: HTTPURLResponse? { lastTask?.response as? HTTPURLResponse } // MARK: Tasks /// All `URLSessionTask`s created on behalf of the `Request`. public var tasks: [URLSessionTask] { mutableState.tasks } /// First `URLSessionTask` created on behalf of the `Request`. public var firstTask: URLSessionTask? { tasks.first } /// Last `URLSessionTask` crated on behalf of the `Request`. public var lastTask: URLSessionTask? { tasks.last } /// Current `URLSessionTask` created on behalf of the `Request`. public var task: URLSessionTask? { lastTask } // MARK: Metrics /// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created. public var allMetrics: [URLSessionTaskMetrics] { mutableState.metrics } /// First `URLSessionTaskMetrics` gathered on behalf of the `Request`. public var firstMetrics: URLSessionTaskMetrics? { allMetrics.first } /// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`. public var lastMetrics: URLSessionTaskMetrics? { allMetrics.last } /// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`. public var metrics: URLSessionTaskMetrics? { lastMetrics } // MARK: Retry Count /// Number of times the `Request` has been retried. public var retryCount: Int { mutableState.retryCount } // MARK: Error /// `Error` returned from Alamofire internally, from the network request directly, or any validators executed. public fileprivate(set) var error: AFError? { get { mutableState.error } set { mutableState.error = newValue } } /// Default initializer for the `Request` superclass. /// /// - Parameters: /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets /// `underlyingQueue`, but can be passed another queue from a `Session`. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. init(id: UUID = UUID(), underlyingQueue: DispatchQueue, serializationQueue: DispatchQueue, eventMonitor: EventMonitor?, interceptor: RequestInterceptor?, delegate: RequestDelegate) { self.id = id self.underlyingQueue = underlyingQueue self.serializationQueue = serializationQueue self.eventMonitor = eventMonitor self.interceptor = interceptor self.delegate = delegate } // MARK: - Internal Event API // All API must be called from underlyingQueue. /// Called when an initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active, /// the `URLRequest` will be adapted before being issued. /// /// - Parameter request: The `URLRequest` created. func didCreateInitialURLRequest(_ request: URLRequest) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) $mutableState.write { $0.requests.append(request) } eventMonitor?.request(self, didCreateInitialURLRequest: request) } /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`. /// /// - Note: Triggers retry. /// /// - Parameter error: `AFError` thrown from the failed creation. func didFailToCreateURLRequest(with error: AFError) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) self.error = error eventMonitor?.request(self, didFailToCreateURLRequestWithError: error) callCURLHandlerIfNecessary() retryOrFinish(error: error) } /// Called when a `RequestAdapter` has successfully adapted a `URLRequest`. /// /// - Parameters: /// - initialRequest: The `URLRequest` that was adapted. /// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`. func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) $mutableState.write { $0.requests.append(adaptedRequest) } eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest) } /// Called when a `RequestAdapter` fails to adapt a `URLRequest`. /// /// - Note: Triggers retry. /// /// - Parameters: /// - request: The `URLRequest` the adapter was called with. /// - error: The `AFError` returned by the `RequestAdapter`. func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) self.error = error eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error) callCURLHandlerIfNecessary() retryOrFinish(error: error) } /// Final `URLRequest` has been created for the instance. /// /// - Parameter request: The `URLRequest` created. func didCreateURLRequest(_ request: URLRequest) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) $mutableState.read { state in state.urlRequestHandler?.queue.async { state.urlRequestHandler?.handler(request) } } eventMonitor?.request(self, didCreateURLRequest: request) callCURLHandlerIfNecessary() } /// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`. private func callCURLHandlerIfNecessary() { $mutableState.write { mutableState in guard let cURLHandler = mutableState.cURLHandler else { return } cURLHandler.queue.async { cURLHandler.handler(self.cURLDescription()) } mutableState.cURLHandler = nil } } /// Called when a `URLSessionTask` is created on behalf of the instance. /// /// - Parameter task: The `URLSessionTask` created. func didCreateTask(_ task: URLSessionTask) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) $mutableState.write { state in state.tasks.append(task) guard let urlSessionTaskHandler = state.urlSessionTaskHandler else { return } urlSessionTaskHandler.queue.async { urlSessionTaskHandler.handler(task) } } eventMonitor?.request(self, didCreateTask: task) } /// Called when resumption is completed. func didResume() { dispatchPrecondition(condition: .onQueue(underlyingQueue)) eventMonitor?.requestDidResume(self) } /// Called when a `URLSessionTask` is resumed on behalf of the instance. /// /// - Parameter task: The `URLSessionTask` resumed. func didResumeTask(_ task: URLSessionTask) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) eventMonitor?.request(self, didResumeTask: task) } /// Called when suspension is completed. func didSuspend() { dispatchPrecondition(condition: .onQueue(underlyingQueue)) eventMonitor?.requestDidSuspend(self) } /// Called when a `URLSessionTask` is suspended on behalf of the instance. /// /// - Parameter task: The `URLSessionTask` suspended. func didSuspendTask(_ task: URLSessionTask) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) eventMonitor?.request(self, didSuspendTask: task) } /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`. func didCancel() { dispatchPrecondition(condition: .onQueue(underlyingQueue)) error = error ?? AFError.explicitlyCancelled eventMonitor?.requestDidCancel(self) } /// Called when a `URLSessionTask` is cancelled on behalf of the instance. /// /// - Parameter task: The `URLSessionTask` cancelled. func didCancelTask(_ task: URLSessionTask) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) eventMonitor?.request(self, didCancelTask: task) } /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the instance. /// /// - Parameter metrics: The `URLSessionTaskMetrics` gathered. func didGatherMetrics(_ metrics: URLSessionTaskMetrics) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) $mutableState.write { $0.metrics.append(metrics) } eventMonitor?.request(self, didGatherMetrics: metrics) } /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning. /// /// - Parameters: /// - task: The `URLSessionTask` which failed. /// - error: The early failure `AFError`. func didFailTask(_ task: URLSessionTask, earlyWithError error: AFError) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) self.error = error // Task will still complete, so didCompleteTask(_:with:) will handle retry. eventMonitor?.request(self, didFailTask: task, earlyWithError: error) } /// Called when a `URLSessionTask` completes. All tasks will eventually call this method. /// /// - Note: Response validation is synchronously triggered in this step. /// /// - Parameters: /// - task: The `URLSessionTask` which completed. /// - error: The `AFError` `task` may have completed with. If `error` has already been set on the instance, this /// value is ignored. func didCompleteTask(_ task: URLSessionTask, with error: AFError?) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) self.error = self.error ?? error validators.forEach { $0() } eventMonitor?.request(self, didCompleteTask: task, with: error) retryOrFinish(error: self.error) } /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`. func prepareForRetry() { dispatchPrecondition(condition: .onQueue(underlyingQueue)) $mutableState.write { $0.retryCount += 1 } reset() eventMonitor?.requestIsRetrying(self) } /// Called to determine whether retry will be triggered for the particular error, or whether the instance should /// call `finish()`. /// /// - Parameter error: The possible `AFError` which may trigger retry. func retryOrFinish(error: AFError?) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) guard let error = error, let delegate = delegate else { finish(); return } delegate.retryResult(for: self, dueTo: error) { retryResult in switch retryResult { case .doNotRetry: self.finish() case let .doNotRetryWithError(retryError): self.finish(error: retryError.asAFError(orFailWith: "Received retryError was not already AFError")) case .retry, .retryWithDelay: delegate.retryRequest(self, withDelay: retryResult.delay) } } } /// Finishes this `Request` and starts the response serializers. /// /// - Parameter error: The possible `Error` with which the instance will finish. func finish(error: AFError? = nil) { dispatchPrecondition(condition: .onQueue(underlyingQueue)) guard !mutableState.isFinishing else { return } mutableState.isFinishing = true if let error = error { self.error = error } // Start response handlers processNextResponseSerializer() eventMonitor?.requestDidFinish(self) } /// Appends the response serialization closure to the instance. /// /// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`. /// /// - Parameter closure: The closure containing the response serialization call. func appendResponseSerializer(_ closure: @escaping () -> Void) { $mutableState.write { mutableState in mutableState.responseSerializers.append(closure) if mutableState.state == .finished { mutableState.state = .resumed } if mutableState.responseSerializerProcessingFinished { underlyingQueue.async { self.processNextResponseSerializer() } } if mutableState.state.canTransitionTo(.resumed) { underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } } } } } /// Returns the next response serializer closure to execute if there's one left. /// /// - Returns: The next response serialization closure, if there is one. func nextResponseSerializer() -> (() -> Void)? { var responseSerializer: (() -> Void)? $mutableState.write { mutableState in let responseSerializerIndex = mutableState.responseSerializerCompletions.count if responseSerializerIndex < mutableState.responseSerializers.count { responseSerializer = mutableState.responseSerializers[responseSerializerIndex] } } return responseSerializer } /// Processes the next response serializer and calls all completions if response serialization is complete. func processNextResponseSerializer() { guard let responseSerializer = nextResponseSerializer() else { // Execute all response serializer completions and clear them var completions: [() -> Void] = [] $mutableState.write { mutableState in completions = mutableState.responseSerializerCompletions // Clear out all response serializers and response serializer completions in mutable state since the // request is complete. It's important to do this prior to calling the completion closures in case // the completions call back into the request triggering a re-processing of the response serializers. // An example of how this can happen is by calling cancel inside a response completion closure. mutableState.responseSerializers.removeAll() mutableState.responseSerializerCompletions.removeAll() if mutableState.state.canTransitionTo(.finished) { mutableState.state = .finished } mutableState.responseSerializerProcessingFinished = true mutableState.isFinishing = false } completions.forEach { $0() } // Cleanup the request cleanup() return } serializationQueue.async { responseSerializer() } } /// Notifies the `Request` that the response serializer is complete. /// /// - Parameter completion: The completion handler provided with the response serializer, called when all serializers /// are complete. func responseSerializerDidComplete(completion: @escaping () -> Void) { $mutableState.write { $0.responseSerializerCompletions.append(completion) } processNextResponseSerializer() } /// Resets all task and response serializer related state for retry. func reset() { error = nil uploadProgress.totalUnitCount = 0 uploadProgress.completedUnitCount = 0 downloadProgress.totalUnitCount = 0 downloadProgress.completedUnitCount = 0 $mutableState.write { state in state.isFinishing = false state.responseSerializerCompletions = [] } } /// Called when updating the upload progress. /// /// - Parameters: /// - totalBytesSent: Total bytes sent so far. /// - totalBytesExpectedToSend: Total bytes expected to send. func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { uploadProgress.totalUnitCount = totalBytesExpectedToSend uploadProgress.completedUnitCount = totalBytesSent uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) } } /// Perform a closure on the current `state` while locked. /// /// - Parameter perform: The closure to perform. func withState(perform: (State) -> Void) { $mutableState.withState(perform: perform) } // MARK: Task Creation /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override. /// /// - Parameters: /// - request: `URLRequest` to use to create the `URLSessionTask`. /// - session: `URLSession` which creates the `URLSessionTask`. /// /// - Returns: The `URLSessionTask` created. func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { fatalError("Subclasses must override.") } // MARK: - Public API // These APIs are callable from any queue. // MARK: State /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended. /// /// - Returns: The instance. @discardableResult public func cancel() -> Self { $mutableState.write { mutableState in guard mutableState.state.canTransitionTo(.cancelled) else { return } mutableState.state = .cancelled underlyingQueue.async { self.didCancel() } guard let task = mutableState.tasks.last, task.state != .completed else { underlyingQueue.async { self.finish() } return } // Resume to ensure metrics are gathered. task.resume() task.cancel() underlyingQueue.async { self.didCancelTask(task) } } return self } /// Suspends the instance. /// /// - Returns: The instance. @discardableResult public func suspend() -> Self { $mutableState.write { mutableState in guard mutableState.state.canTransitionTo(.suspended) else { return } mutableState.state = .suspended underlyingQueue.async { self.didSuspend() } guard let task = mutableState.tasks.last, task.state != .completed else { return } task.suspend() underlyingQueue.async { self.didSuspendTask(task) } } return self } /// Resumes the instance. /// /// - Returns: The instance. @discardableResult public func resume() -> Self { $mutableState.write { mutableState in guard mutableState.state.canTransitionTo(.resumed) else { return } mutableState.state = .resumed underlyingQueue.async { self.didResume() } guard let task = mutableState.tasks.last, task.state != .completed else { return } task.resume() underlyingQueue.async { self.didResumeTask(task) } } return self } // MARK: - Closure API /// Associates a credential using the provided values with the instance. /// /// - Parameters: /// - username: The username. /// - password: The password. /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default. /// /// - Returns: The instance. @discardableResult public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self { let credential = URLCredential(user: username, password: password, persistence: persistence) return authenticate(with: credential) } /// Associates the provided credential with the instance. /// /// - Parameter credential: The `URLCredential`. /// /// - Returns: The instance. @discardableResult public func authenticate(with credential: URLCredential) -> Self { mutableState.credential = credential return self } /// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server. /// /// - Note: Only the last closure provided is used. /// /// - Parameters: /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default. /// - closure: The closure to be executed periodically as data is read from the server. /// /// - Returns: The instance. @discardableResult public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self { mutableState.downloadProgressHandler = (handler: closure, queue: queue) return self } /// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server. /// /// - Note: Only the last closure provided is used. /// /// - Parameters: /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default. /// - closure: The closure to be executed periodically as data is sent to the server. /// /// - Returns: The instance. @discardableResult public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self { mutableState.uploadProgressHandler = (handler: closure, queue: queue) return self } // MARK: Redirects /// Sets the redirect handler for the instance which will be used if a redirect response is encountered. /// /// - Note: Attempting to set the redirect handler more than once is a logic error and will crash. /// /// - Parameter handler: The `RedirectHandler`. /// /// - Returns: The instance. @discardableResult public func redirect(using handler: RedirectHandler) -> Self { $mutableState.write { mutableState in precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.") mutableState.redirectHandler = handler } return self } // MARK: Cached Responses /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response. /// /// - Note: Attempting to set the cache handler more than once is a logic error and will crash. /// /// - Parameter handler: The `CachedResponseHandler`. /// /// - Returns: The instance. @discardableResult public func cacheResponse(using handler: CachedResponseHandler) -> Self { $mutableState.write { mutableState in precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.") mutableState.cachedResponseHandler = handler } return self } // MARK: - Lifetime APIs /// Sets a handler to be called when the cURL description of the request is available. /// /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called. /// /// - Parameters: /// - queue: `DispatchQueue` on which `handler` will be called. /// - handler: Closure to be called when the cURL description is available. /// /// - Returns: The instance. @discardableResult public func cURLDescription(on queue: DispatchQueue, calling handler: @escaping (String) -> Void) -> Self { $mutableState.write { mutableState in if mutableState.requests.last != nil { queue.async { handler(self.cURLDescription()) } } else { mutableState.cURLHandler = (queue, handler) } } return self } /// Sets a handler to be called when the cURL description of the request is available. /// /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called. /// /// - Parameter handler: Closure to be called when the cURL description is available. Called on the instance's /// `underlyingQueue` by default. /// /// - Returns: The instance. @discardableResult public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { $mutableState.write { mutableState in if mutableState.requests.last != nil { underlyingQueue.async { handler(self.cURLDescription()) } } else { mutableState.cURLHandler = (underlyingQueue, handler) } } return self } /// Sets a closure to called whenever Alamofire creates a `URLRequest` for this instance. /// /// - Note: This closure will be called multiple times if the instance adapts incoming `URLRequest`s or is retried. /// /// - Parameters: /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default. /// - handler: Closure to be called when a `URLRequest` is available. /// /// - Returns: The instance. @discardableResult public func onURLRequestCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLRequest) -> Void) -> Self { $mutableState.write { state in if let request = state.requests.last { queue.async { handler(request) } } state.urlRequestHandler = (queue, handler) } return self } /// Sets a closure to be called whenever the instance creates a `URLSessionTask`. /// /// - Note: This API should only be used to provide `URLSessionTask`s to existing API, like `NSFileProvider`. It /// **SHOULD NOT** be used to interact with tasks directly, as that may be break Alamofire features. /// Additionally, this closure may be called multiple times if the instance is retried. /// /// - Parameters: /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default. /// - handler: Closure to be called when the `URLSessionTask` is available. /// /// - Returns: The instance. @discardableResult public func onURLSessionTaskCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLSessionTask) -> Void) -> Self { $mutableState.write { state in if let task = state.tasks.last { queue.async { handler(task) } } state.urlSessionTaskHandler = (queue, handler) } return self } // MARK: Cleanup /// Final cleanup step executed when the instance finishes response serialization. func cleanup() { delegate?.cleanup(after: self) // No-op: override in subclass } } // MARK: - Protocol Conformances extension Request: Equatable { public static func ==(lhs: Request, rhs: Request) -> Bool { lhs.id == rhs.id } } extension Request: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(id) } } extension Request: CustomStringConvertible { /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been /// created, as well as the response status code, if a response has been received. public var description: String { guard let request = performedRequests.last ?? lastRequest, let url = request.url, let method = request.httpMethod else { return "No request created yet." } let requestDescription = "\(method) \(url.absoluteString)" return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription } } extension Request { /// cURL representation of the instance. /// /// - Returns: The cURL equivalent of the instance. public func cURLDescription() -> String { guard let request = lastRequest, let url = request.url, let host = url.host, let method = request.httpMethod else { return "$ curl command could not be created" } var components = ["$ curl -v"] components.append("-X \(method)") if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage { let protectionSpace = URLProtectionSpace(host: host, port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic) if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { for credential in credentials { guard let user = credential.user, let password = credential.password else { continue } components.append("-u \(user):\(password)") } } else { if let credential = credential, let user = credential.user, let password = credential.password { components.append("-u \(user):\(password)") } } } if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies { if let cookieStorage = configuration.httpCookieStorage, let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";") components.append("-b \"\(allCookies)\"") } } var headers = HTTPHeaders() if let sessionHeaders = delegate?.sessionConfiguration.headers { for header in sessionHeaders where header.name != "Cookie" { headers[header.name] = header.value } } for header in request.headers where header.name != "Cookie" { headers[header.name] = header.value } for header in headers { let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"") components.append("-H \"\(header.name): \(escapedValue)\"") } if let httpBodyData = request.httpBody { let httpBody = String(decoding: httpBodyData, as: UTF8.self) var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") components.append("-d \"\(escapedBody)\"") } components.append("\"\(url.absoluteString)\"") return components.joined(separator: " \\\n\t") } } /// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`. public protocol RequestDelegate: AnyObject { /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s. var sessionConfiguration: URLSessionConfiguration { get } /// Determines whether the `Request` should automatically call `resume()` when adding the first response handler. var startImmediately: Bool { get } /// Notifies the delegate the `Request` has reached a point where it needs cleanup. /// /// - Parameter request: The `Request` to cleanup after. func cleanup(after request: Request) /// Asynchronously ask the delegate whether a `Request` will be retried. /// /// - Parameters: /// - request: `Request` which failed. /// - error: `Error` which produced the failure. /// - completion: Closure taking the `RetryResult` for evaluation. func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void) /// Asynchronously retry the `Request`. /// /// - Parameters: /// - request: `Request` which will be retried. /// - timeDelay: `TimeInterval` after which the retry will be triggered. func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) } // MARK: - Subclasses // MARK: - DataRequest /// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`. public class DataRequest: Request { /// `URLRequestConvertible` value used to create `URLRequest`s for this instance. public let convertible: URLRequestConvertible /// `Data` read from the server so far. public var data: Data? { mutableData } /// Protected storage for the `Data` read by the instance. @Protected private var mutableData: Data? = nil /// Creates a `DataRequest` using the provided parameters. /// /// - Parameters: /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets /// `underlyingQueue`, but can be passed another queue from a `Session`. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. init(id: UUID = UUID(), convertible: URLRequestConvertible, underlyingQueue: DispatchQueue, serializationQueue: DispatchQueue, eventMonitor: EventMonitor?, interceptor: RequestInterceptor?, delegate: RequestDelegate) { self.convertible = convertible super.init(id: id, underlyingQueue: underlyingQueue, serializationQueue: serializationQueue, eventMonitor: eventMonitor, interceptor: interceptor, delegate: delegate) } override func reset() { super.reset() mutableData = nil } /// Called when `Data` is received by this instance. /// /// - Note: Also calls `updateDownloadProgress`. /// /// - Parameter data: The `Data` received. func didReceive(data: Data) { if self.data == nil { mutableData = data } else { $mutableData.write { $0?.append(data) } } updateDownloadProgress() } override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { let copiedRequest = request return session.dataTask(with: copiedRequest) } /// Called to updated the `downloadProgress` of the instance. func updateDownloadProgress() { let totalBytesReceived = Int64(data?.count ?? 0) let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown downloadProgress.totalUnitCount = totalBytesExpected downloadProgress.completedUnitCount = totalBytesReceived downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) } } /// Validates the request, using the specified closure. /// /// - Note: If validation fails, subsequent calls to response handlers will have an associated error. /// /// - Parameter validation: `Validation` closure used to validate the response. /// /// - Returns: The instance. @discardableResult public func validate(_ validation: @escaping Validation) -> Self { let validator: () -> Void = { [unowned self] in guard self.error == nil, let response = self.response else { return } let result = validation(self.request, response, self.data) if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) } self.eventMonitor?.request(self, didValidateRequest: self.request, response: response, data: self.data, withResult: result) } $validators.write { $0.append(validator) } return self } } // MARK: - DataStreamRequest /// `Request` subclass which streams HTTP response `Data` through a `Handler` closure. public final class DataStreamRequest: Request { /// Closure type handling `DataStreamRequest.Stream` values. public typealias Handler<Success, Failure: Error> = (Stream<Success, Failure>) throws -> Void /// Type encapsulating an `Event` as it flows through the stream, as well as a `CancellationToken` which can be used /// to stop the stream at any time. public struct Stream<Success, Failure: Error> { /// Latest `Event` from the stream. public let event: Event<Success, Failure> /// Token used to cancel the stream. public let token: CancellationToken /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`. public func cancel() { token.cancel() } } /// Type representing an event flowing through the stream. Contains either the `Result` of processing streamed /// `Data` or the completion of the stream. public enum Event<Success, Failure: Error> { /// Output produced every time the instance receives additional `Data`. The associated value contains the /// `Result` of processing the incoming `Data`. case stream(Result<Success, Failure>) /// Output produced when the instance has completed, whether due to stream end, cancellation, or an error. /// Associated `Completion` value contains the final state. case complete(Completion) } /// Value containing the state of a `DataStreamRequest` when the stream was completed. public struct Completion { /// Last `URLRequest` issued by the instance. public let request: URLRequest? /// Last `HTTPURLResponse` received by the instance. public let response: HTTPURLResponse? /// Last `URLSessionTaskMetrics` produced for the instance. public let metrics: URLSessionTaskMetrics? /// `AFError` produced for the instance, if any. public let error: AFError? } /// Type used to cancel an ongoing stream. public struct CancellationToken { weak var request: DataStreamRequest? init(_ request: DataStreamRequest) { self.request = request } /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`. public func cancel() { request?.cancel() } } /// `URLRequestConvertible` value used to create `URLRequest`s for this instance. public let convertible: URLRequestConvertible /// Whether or not the instance will be cancelled if stream parsing encounters an error. public let automaticallyCancelOnStreamError: Bool /// Internal mutable state specific to this type. struct StreamMutableState { /// `OutputStream` bound to the `InputStream` produced by `asInputStream`, if it has been called. var outputStream: OutputStream? /// Stream closures called as `Data` is received. var streams: [(_ data: Data) -> Void] = [] /// Number of currently executing streams. Used to ensure completions are only fired after all streams are /// enqueued. var numberOfExecutingStreams = 0 /// Completion calls enqueued while streams are still executing. var enqueuedCompletionEvents: [() -> Void] = [] } @Protected var streamMutableState = StreamMutableState() /// Creates a `DataStreamRequest` using the provided parameters. /// /// - Parameters: /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` /// by default. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this /// instance. /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance will be cancelled when an `Error` /// is thrown while serializing stream `Data`. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default /// targets /// `underlyingQueue`, but can be passed another queue from a `Session`. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by /// the `Request`. init(id: UUID = UUID(), convertible: URLRequestConvertible, automaticallyCancelOnStreamError: Bool, underlyingQueue: DispatchQueue, serializationQueue: DispatchQueue, eventMonitor: EventMonitor?, interceptor: RequestInterceptor?, delegate: RequestDelegate) { self.convertible = convertible self.automaticallyCancelOnStreamError = automaticallyCancelOnStreamError super.init(id: id, underlyingQueue: underlyingQueue, serializationQueue: serializationQueue, eventMonitor: eventMonitor, interceptor: interceptor, delegate: delegate) } override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { let copiedRequest = request return session.dataTask(with: copiedRequest) } override func finish(error: AFError? = nil) { $streamMutableState.write { state in state.outputStream?.close() } super.finish(error: error) } func didReceive(data: Data) { $streamMutableState.write { state in #if !(os(Linux) || os(Windows)) if let stream = state.outputStream { underlyingQueue.async { var bytes = Array(data) stream.write(&bytes, maxLength: bytes.count) } } #endif state.numberOfExecutingStreams += state.streams.count let localState = state underlyingQueue.async { localState.streams.forEach { $0(data) } } } } /// Validates the `URLRequest` and `HTTPURLResponse` received for the instance using the provided `Validation` closure. /// /// - Parameter validation: `Validation` closure used to validate the request and response. /// /// - Returns: The `DataStreamRequest`. @discardableResult public func validate(_ validation: @escaping Validation) -> Self { let validator: () -> Void = { [unowned self] in guard self.error == nil, let response = self.response else { return } let result = validation(self.request, response) if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) } self.eventMonitor?.request(self, didValidateRequest: self.request, response: response, withResult: result) } $validators.write { $0.append(validator) } return self } #if !(os(Linux) || os(Windows)) /// Produces an `InputStream` that receives the `Data` received by the instance. /// /// - Note: The `InputStream` produced by this method must have `open()` called before being able to read `Data`. /// Additionally, this method will automatically call `resume()` on the instance, regardless of whether or /// not the creating session has `startRequestsImmediately` set to `true`. /// /// - Parameter bufferSize: Size, in bytes, of the buffer between the `OutputStream` and `InputStream`. /// /// - Returns: The `InputStream` bound to the internal `OutboundStream`. public func asInputStream(bufferSize: Int = 1024) -> InputStream? { defer { resume() } var inputStream: InputStream? $streamMutableState.write { state in Foundation.Stream.getBoundStreams(withBufferSize: bufferSize, inputStream: &inputStream, outputStream: &state.outputStream) state.outputStream?.open() } return inputStream } #endif func capturingError(from closure: () throws -> Void) { do { try closure() } catch { self.error = error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) cancel() } } func appendStreamCompletion<Success, Failure>(on queue: DispatchQueue, stream: @escaping Handler<Success, Failure>) { appendResponseSerializer { self.underlyingQueue.async { self.responseSerializerDidComplete { self.$streamMutableState.write { state in guard state.numberOfExecutingStreams == 0 else { state.enqueuedCompletionEvents.append { self.enqueueCompletion(on: queue, stream: stream) } return } self.enqueueCompletion(on: queue, stream: stream) } } } } } func enqueueCompletion<Success, Failure>(on queue: DispatchQueue, stream: @escaping Handler<Success, Failure>) { queue.async { do { let completion = Completion(request: self.request, response: self.response, metrics: self.metrics, error: self.error) try stream(.init(event: .complete(completion), token: .init(self))) } catch { // Ignore error, as errors on Completion can't be handled anyway. } } } } extension DataStreamRequest.Stream { /// Incoming `Result` values from `Event.stream`. public var result: Result<Success, Failure>? { guard case let .stream(result) = event else { return nil } return result } /// `Success` value of the instance, if any. public var value: Success? { guard case let .success(value) = result else { return nil } return value } /// `Failure` value of the instance, if any. public var error: Failure? { guard case let .failure(error) = result else { return nil } return error } /// `Completion` value of the instance, if any. public var completion: DataStreamRequest.Completion? { guard case let .complete(completion) = event else { return nil } return completion } } // MARK: - DownloadRequest /// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`. public class DownloadRequest: Request { /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination /// `URL`. public struct Options: OptionSet { /// Specifies that intermediate directories for the destination URL should be created. public static let createIntermediateDirectories = Options(rawValue: 1 << 0) /// Specifies that any previous file at the destination `URL` should be removed. public static let removePreviousFile = Options(rawValue: 1 << 1) public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } } // MARK: Destination /// A closure executed once a `DownloadRequest` has successfully completed in order to determine where to move the /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL /// and the `HTTPURLResponse`, and returns two values: the file URL where the temporary file should be moved and /// the options defining how the file should be moved. /// /// - Note: Downloads from a local `file://` `URL`s do not use the `Destination` closure, as those downloads do not /// return an `HTTPURLResponse`. Instead the file is merely moved within the temporary directory. public typealias Destination = (_ temporaryURL: URL, _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options) /// Creates a download file destination closure which uses the default file manager to move the temporary file to a /// file URL in the first available directory with the specified search path directory and search path domain mask. /// /// - Parameters: /// - directory: The search path directory. `.documentDirectory` by default. /// - domain: The search path domain mask. `.userDomainMask` by default. /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by /// default. /// - Returns: The `Destination` closure. public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory, in domain: FileManager.SearchPathDomainMask = .userDomainMask, options: Options = []) -> Destination { { temporaryURL, response in let directoryURLs = FileManager.default.urls(for: directory, in: domain) let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL return (url, options) } } /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files /// with this destination must be additionally moved if they should survive the system reclamation of temporary /// space. static let defaultDestination: Destination = { url, _ in (defaultDestinationURL(url), []) } /// Default `URL` creation closure. Creates a `URL` in the temporary directory with `Alamofire_` prepended to the /// provided file name. static let defaultDestinationURL: (URL) -> URL = { url in let filename = "Alamofire_\(url.lastPathComponent)" let destination = url.deletingLastPathComponent().appendingPathComponent(filename) return destination } // MARK: Downloadable /// Type describing the source used to create the underlying `URLSessionDownloadTask`. public enum Downloadable { /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value. case request(URLRequestConvertible) /// Download should be started from the associated resume `Data` value. case resumeData(Data) } // MARK: Mutable State /// Type containing all mutable state for `DownloadRequest` instances. private struct DownloadRequestMutableState { /// Possible resume `Data` produced when cancelling the instance. var resumeData: Data? /// `URL` to which `Data` is being downloaded. var fileURL: URL? } /// Protected mutable state specific to `DownloadRequest`. @Protected private var mutableDownloadState = DownloadRequestMutableState() /// If the download is resumable and is eventually cancelled or fails, this value may be used to resume the download /// using the `download(resumingWith data:)` API. /// /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel). public var resumeData: Data? { #if !(os(Linux) || os(Windows)) return mutableDownloadState.resumeData ?? error?.downloadResumeData #else return mutableDownloadState.resumeData #endif } /// If the download is successful, the `URL` where the file was downloaded. public var fileURL: URL? { mutableDownloadState.fileURL } // MARK: Initial State /// `Downloadable` value used for this instance. public let downloadable: Downloadable /// The `Destination` to which the downloaded file is moved. let destination: Destination /// Creates a `DownloadRequest` using the provided parameters. /// /// - Parameters: /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets /// `underlyingQueue`, but can be passed another queue from a `Session`. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request` /// - destination: `Destination` closure used to move the downloaded file to its final location. init(id: UUID = UUID(), downloadable: Downloadable, underlyingQueue: DispatchQueue, serializationQueue: DispatchQueue, eventMonitor: EventMonitor?, interceptor: RequestInterceptor?, delegate: RequestDelegate, destination: @escaping Destination) { self.downloadable = downloadable self.destination = destination super.init(id: id, underlyingQueue: underlyingQueue, serializationQueue: serializationQueue, eventMonitor: eventMonitor, interceptor: interceptor, delegate: delegate) } override func reset() { super.reset() $mutableDownloadState.write { $0.resumeData = nil $0.fileURL = nil } } /// Called when a download has finished. /// /// - Parameters: /// - task: `URLSessionTask` that finished the download. /// - result: `Result` of the automatic move to `destination`. func didFinishDownloading(using task: URLSessionTask, with result: Result<URL, AFError>) { eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result) switch result { case let .success(url): mutableDownloadState.fileURL = url case let .failure(error): self.error = error } } /// Updates the `downloadProgress` using the provided values. /// /// - Parameters: /// - bytesWritten: Total bytes written so far. /// - totalBytesExpectedToWrite: Total bytes expected to write. func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) { downloadProgress.totalUnitCount = totalBytesExpectedToWrite downloadProgress.completedUnitCount += bytesWritten downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) } } override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { session.downloadTask(with: request) } /// Creates a `URLSessionTask` from the provided resume data. /// /// - Parameters: /// - data: `Data` used to resume the download. /// - session: `URLSession` used to create the `URLSessionTask`. /// /// - Returns: The `URLSessionTask` created. public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask { session.downloadTask(withResumeData: data) } /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended. /// /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`. /// /// - Returns: The instance. @discardableResult override public func cancel() -> Self { cancel(producingResumeData: false) } /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be /// resumed or suspended. /// /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if /// available. /// /// - Returns: The instance. @discardableResult public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self { cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil) } /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed /// or suspended. /// /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData` /// property. /// /// - Parameter completionHandler: The completion handler that is called when the download has been successfully /// cancelled. It is not guaranteed to be called on a particular queue, so you may /// want use an appropriate queue to perform your work. /// /// - Returns: The instance. @discardableResult public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self { cancel(optionallyProducingResumeData: completionHandler) } /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed, /// cancellation is performed without producing resume data. /// /// - Parameter completionHandler: Optional resume data handler. /// /// - Returns: The instance. private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self { $mutableState.write { mutableState in guard mutableState.state.canTransitionTo(.cancelled) else { return } mutableState.state = .cancelled underlyingQueue.async { self.didCancel() } guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else { underlyingQueue.async { self.finish() } return } if let completionHandler = completionHandler { // Resume to ensure metrics are gathered. task.resume() task.cancel { resumeData in self.mutableDownloadState.resumeData = resumeData self.underlyingQueue.async { self.didCancelTask(task) } completionHandler(resumeData) } } else { // Resume to ensure metrics are gathered. task.resume() task.cancel(byProducingResumeData: { _ in }) self.underlyingQueue.async { self.didCancelTask(task) } } } return self } /// Validates the request, using the specified closure. /// /// - Note: If validation fails, subsequent calls to response handlers will have an associated error. /// /// - Parameter validation: `Validation` closure to validate the response. /// /// - Returns: The instance. @discardableResult public func validate(_ validation: @escaping Validation) -> Self { let validator: () -> Void = { [unowned self] in guard self.error == nil, let response = self.response else { return } let result = validation(self.request, response, self.fileURL) if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) } self.eventMonitor?.request(self, didValidateRequest: self.request, response: response, fileURL: self.fileURL, withResult: result) } $validators.write { $0.append(validator) } return self } } // MARK: - UploadRequest /// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`. public class UploadRequest: DataRequest { /// Type describing the origin of the upload, whether `Data`, file, or stream. public enum Uploadable { /// Upload from the provided `Data` value. case data(Data) /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be /// automatically removed once uploaded. case file(URL, shouldRemove: Bool) /// Upload from the provided `InputStream`. case stream(InputStream) } // MARK: Initial State /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance. public let upload: UploadableConvertible /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written /// to disk. public let fileManager: FileManager // MARK: Mutable State /// `Uploadable` value used by the instance. public var uploadable: Uploadable? /// Creates an `UploadRequest` using the provided parameters. /// /// - Parameters: /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets /// `underlyingQueue`, but can be passed another queue from a `Session`. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. init(id: UUID = UUID(), convertible: UploadConvertible, underlyingQueue: DispatchQueue, serializationQueue: DispatchQueue, eventMonitor: EventMonitor?, interceptor: RequestInterceptor?, fileManager: FileManager, delegate: RequestDelegate) { upload = convertible self.fileManager = fileManager super.init(id: id, convertible: convertible, underlyingQueue: underlyingQueue, serializationQueue: serializationQueue, eventMonitor: eventMonitor, interceptor: interceptor, delegate: delegate) } /// Called when the `Uploadable` value has been created from the `UploadConvertible`. /// /// - Parameter uploadable: The `Uploadable` that was created. func didCreateUploadable(_ uploadable: Uploadable) { self.uploadable = uploadable eventMonitor?.request(self, didCreateUploadable: uploadable) } /// Called when the `Uploadable` value could not be created. /// /// - Parameter error: `AFError` produced by the failure. func didFailToCreateUploadable(with error: AFError) { self.error = error eventMonitor?.request(self, didFailToCreateUploadableWithError: error) retryOrFinish(error: error) } override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { guard let uploadable = uploadable else { fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.") } switch uploadable { case let .data(data): return session.uploadTask(with: request, from: data) case let .file(url, _): return session.uploadTask(with: request, fromFile: url) case .stream: return session.uploadTask(withStreamedRequest: request) } } override func reset() { // Uploadable must be recreated on every retry. uploadable = nil super.reset() } /// Produces the `InputStream` from `uploadable`, if it can. /// /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash. /// /// - Returns: The `InputStream`. func inputStream() -> InputStream { guard let uploadable = uploadable else { fatalError("Attempting to access the input stream but the uploadable doesn't exist.") } guard case let .stream(stream) = uploadable else { fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.") } eventMonitor?.request(self, didProvideInputStream: stream) return stream } override public func cleanup() { defer { super.cleanup() } guard let uploadable = self.uploadable, case let .file(url, shouldRemove) = uploadable, shouldRemove else { return } try? fileManager.removeItem(at: url) } } /// A type that can produce an `UploadRequest.Uploadable` value. public protocol UploadableConvertible { /// Produces an `UploadRequest.Uploadable` value from the instance. /// /// - Returns: The `UploadRequest.Uploadable`. /// - Throws: Any `Error` produced during creation. func createUploadable() throws -> UploadRequest.Uploadable } extension UploadRequest.Uploadable: UploadableConvertible { public func createUploadable() throws -> UploadRequest.Uploadable { self } } /// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`. public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {}
mit
47614bae3714e2c0fc5f15be3b05be3a
40.554675
177
0.636386
5.274794
false
false
false
false
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/InfiniteScrollViewController.swift
1
4696
// // InfiniteScrollViewController.swift // UIScrollViewDemo // // Created by 伯驹 黄 on 2016/11/29. // Copyright © 2016年 伯驹 黄. All rights reserved. // import UIKit class InfiniteScrollViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white let scrollView = InfiniteScrollView(frame: view.bounds.insetBy(dx: 0, dy: 200)) scrollView.contentInsetAdjustmentBehavior = .never scrollView.backgroundColor = UIColor.blue view.addSubview(scrollView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } class InfiniteScrollView: UIScrollView, UIScrollViewDelegate { var visibleLabels: [UILabel] = [] let labelContainerView = UIView() override init(frame: CGRect) { super.init(frame: frame) contentSize = CGSize(width: 5000, height: frame.height) labelContainerView.frame = CGRect(x: 0, y: 0, width: contentSize.width, height: contentSize.height / 2) addSubview(labelContainerView) labelContainerView.isUserInteractionEnabled = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func recenterIfNecessary() { let currentOffset = contentOffset let contentWidth = contentSize.width let centerOffsetX = (contentWidth - bounds.width) / 2.0 let distanceFromCenter = abs(currentOffset.x - centerOffsetX) if distanceFromCenter > (contentWidth / 4.0) { contentOffset = CGPoint(x: centerOffsetX, y: currentOffset.y) // move content by the same amount so it appears to stay still for label in visibleLabels { var center = labelContainerView.convert(label.center, to: self) center.x += (centerOffsetX - currentOffset.x) label.center = convert(center, to: labelContainerView) } } } override func layoutSubviews() { super.layoutSubviews() recenterIfNecessary() let visibleBounds = convert(bounds, to: labelContainerView) tileLabels(from: visibleBounds.minX, to: visibleBounds.maxX) } func insertLabel() -> UILabel { let label = UILabel(frame: CGRect(x: 0, y: 0, width: bounds.width, height: 80)) label.backgroundColor = UIColor.white label.numberOfLines = 3 label.text = "1024 Block Street\nShaffer, CA\n95014" labelContainerView.addSubview(label) return label } // 向左滑 @discardableResult func placeNewLabelOnRight(_ rightEdge: CGFloat) -> CGFloat { let label = insertLabel() visibleLabels.append(label) // add rightmost label at the end of the array var frame = label.frame frame.origin.x = rightEdge frame.origin.y = labelContainerView.bounds.height - frame.height label.frame = frame return frame.maxX } // 向右滑 func placeNewLabel(on leftEdge: CGFloat) -> CGFloat { let label = insertLabel() visibleLabels.insert(label, at: 0) // add leftmost label at the beginning of the array var frame = label.frame frame.origin.x = leftEdge - frame.width frame.origin.y = labelContainerView.bounds.height - frame.height label.frame = frame return frame.minX } func tileLabels(from minimumVisibleX: CGFloat, to maximumVisibleX: CGFloat) { if visibleLabels.isEmpty { placeNewLabelOnRight(minimumVisibleX) } var lastLabel = visibleLabels.last var rightEdge = lastLabel!.frame.maxX while rightEdge < maximumVisibleX { rightEdge = placeNewLabelOnRight(rightEdge) } var firstLabel = visibleLabels[0] var leftEdge = firstLabel.frame.minX while leftEdge > minimumVisibleX { leftEdge = placeNewLabel(on: leftEdge) } // remove labels that have fallen off right edge lastLabel = visibleLabels.last while lastLabel!.frame.minX > maximumVisibleX { lastLabel!.removeFromSuperview() visibleLabels.removeLast() lastLabel = visibleLabels.last } // remove labels that have fallen off left edge firstLabel = visibleLabels[0] while firstLabel.frame.maxX < minimumVisibleX { firstLabel.removeFromSuperview() visibleLabels.removeFirst() firstLabel = visibleLabels[0] } } }
mit
89c0739fded3be3eb4466fdcd4d99d3d
32.35
111
0.641893
5.102732
false
false
false
false
steelwheels/KiwiScript
KiwiShell/Test/Shell/main.swift
1
1193
/** * @file main.swift * @brief Main function of shell test * @par Copyright * Copyright (C) 2018 Steel Wheels Project */ import KiwiShell import KiwiEngine import KiwiLibrary import CoconutData import CoconutShell import JavaScriptCore import Foundation public func main() { let inhdl = FileHandle.standardInput let outhdl = FileHandle.standardOutput let errhdl = FileHandle.standardError let console = CNFileConsole(input: inhdl, output: outhdl, error: errhdl) let env = CNEnvironment() let manager = KLBuiltinScripts.shared manager.setup(subdirectory: "Documents/Script", forClass: KHShellThread.self) console.print(string: "***** UTShellCommand\n") let res0 = UTShellCommand(console: console) console.print(string: "***** UTParser\n") let res3 = UTParser(environment: env, console: console) console.print(string: "***** UTScriptManager\n") let res2 = UTScriptManager(console: console) console.print(string: "***** UTScript\n") let res4 = UTScript(input: inhdl, output: outhdl, error: errhdl, console: console) if res0 && res2 && res3 && res4 { console.print(string: "Summary: OK\n") } else { console.print(string: "Summary: NG\n") } } main()
lgpl-2.1
a7240eb9264b25e0651b694133290a7e
24.382979
83
0.724225
3.313889
false
false
false
false
WhatsTaste/WTImagePickerController
Vendor/Views/WTEditingControlsView.swift
1
5165
// // WTEditingControlsView.swift // WTImagePickerController // // Created by Jayce on 2017/2/10. // Copyright © 2017年 WhatsTaste. All rights reserved. // import UIKit protocol WTEditingControlsViewDelegate: class { func editingControlsViewDidCancel(_ view: WTEditingControlsView) func editingControlsViewDidFinish(_ view: WTEditingControlsView) func editingControlsViewDidReset(_ view: WTEditingControlsView) } private let horizontalMargin: CGFloat = 15 private let verticalMargin: CGFloat = 10 private let spacing: CGFloat = 15 class WTEditingControlsView: UIView { override init(frame: CGRect) { super.init(frame: frame) // Initialization code addSubview(cancelButton) addSubview(doneButton) addSubview(resetButton) self.addConstraint(NSLayoutConstraint.init(item: cancelButton, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: horizontalMargin)) self.addConstraint(NSLayoutConstraint.init(item: cancelButton, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: verticalMargin)) self.addConstraint(NSLayoutConstraint.init(item: self, attribute: .bottom, relatedBy: .equal, toItem: cancelButton, attribute: .bottom, multiplier: 1, constant: verticalMargin)) self.addConstraint(NSLayoutConstraint.init(item: resetButton, attribute: .left, relatedBy: .equal, toItem: cancelButton, attribute: .right, multiplier: 1, constant: spacing)) self.addConstraint(NSLayoutConstraint.init(item: resetButton, attribute: .top, relatedBy: .equal, toItem: cancelButton, attribute: .top, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint.init(item: resetButton, attribute: .bottom, relatedBy: .equal, toItem: cancelButton, attribute: .bottom, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint.init(item: resetButton, attribute: .width, relatedBy: .equal, toItem: cancelButton, attribute: .width, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint.init(item: doneButton, attribute: .left, relatedBy: .equal, toItem: resetButton, attribute: .right, multiplier: 1, constant: spacing)) self.addConstraint(NSLayoutConstraint.init(item: doneButton, attribute: .top, relatedBy: .equal, toItem: resetButton, attribute: .top, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint.init(item: doneButton, attribute: .bottom, relatedBy: .equal, toItem: resetButton, attribute: .bottom, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint.init(item: self, attribute: .right, relatedBy: .equal, toItem: doneButton, attribute: .right, multiplier: 1, constant: horizontalMargin)) self.addConstraint(NSLayoutConstraint.init(item: doneButton, attribute: .width, relatedBy: .equal, toItem: resetButton, attribute: .width, multiplier: 1, constant: 0)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private @objc private func cancel() { delegate?.editingControlsViewDidCancel(self) } @objc private func done() { delegate?.editingControlsViewDidFinish(self) } @objc private func reset() { delegate?.editingControlsViewDidReset(self) } // MARK: - Properties weak public var delegate: WTEditingControlsViewDelegate? public var resetButtonEnabled: Bool { get { return resetButton.isEnabled } set { resetButton.isEnabled = newValue } } lazy private var cancelButton: UIButton = { let button = UIButton(type: .custom) button.translatesAutoresizingMaskIntoConstraints = false button.backgroundColor = UIColor.clear button.setImage(UIImage.cancelImage(), for: .normal) button.addTarget(self, action: #selector(cancel), for: .touchUpInside) button.contentHorizontalAlignment = .left return button }() lazy private var doneButton: UIButton = { let button = UIButton(type: .custom) button.translatesAutoresizingMaskIntoConstraints = false button.backgroundColor = UIColor.clear button.setImage(UIImage.doneImage(), for: .normal) button.addTarget(self, action: #selector(done), for: .touchUpInside) button.contentHorizontalAlignment = .right return button }() lazy private var resetButton: UIButton = { let button = UIButton(type: .system) button.translatesAutoresizingMaskIntoConstraints = false button.backgroundColor = UIColor.clear button.titleLabel?.font = UIFont.systemFont(ofSize: 14) button.setTitleColor(UIColor.white, for: .normal) button.setTitleColor(UIColor.lightGray, for: .disabled) button.setTitle(self.WTIPLocalizedString("Reset"), for: .normal) button.addTarget(self, action: #selector(reset), for: .touchUpInside) button.isEnabled = false return button }() }
mit
4d0ccb66efa89aece5403b62a7356186
46.357798
185
0.700697
4.837863
false
false
false
false
Jnosh/swift
test/SILGen/super_init_refcounting.swift
3
4169
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s class Foo { init() {} init(_ x: Foo) {} init(_ x: Int) {} } class Bar: Foo { // CHECK-LABEL: sil hidden @_T022super_init_refcounting3BarC{{[_0-9a-zA-Z]*}}fc // CHECK: bb0([[INPUT_SELF:%.*]] : $Bar): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Bar } // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[PB_SELF_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[INPUT_SELF]] to [init] [[PB_SELF_BOX]] // CHECK: [[ORIG_SELF:%.*]] = load [take] [[PB_SELF_BOX]] // CHECK-NOT: copy_value [[ORIG_SELF]] // CHECK: [[ORIG_SELF_UP:%.*]] = upcast [[ORIG_SELF]] // CHECK-NOT: copy_value [[ORIG_SELF_UP]] // CHECK: [[SUPER_INIT:%[0-9]+]] = function_ref @_T022super_init_refcounting3FooCACycfc : $@convention(method) (@owned Foo) -> @owned Foo // CHECK: [[NEW_SELF:%.*]] = apply [[SUPER_INIT]]([[ORIG_SELF_UP]]) // CHECK: [[NEW_SELF_DOWN:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK: store [[NEW_SELF_DOWN]] to [init] [[PB_SELF_BOX]] override init() { super.init() } } extension Foo { // CHECK-LABEL: sil hidden @_T022super_init_refcounting3FooC{{[_0-9a-zA-Z]*}}fc // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Foo } // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_SELF_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[ORIG_SELF:%.*]] = load [take] [[PB_SELF_BOX]] // CHECK-NOT: copy_value [[ORIG_SELF]] // CHECK: [[SUPER_INIT:%.*]] = class_method // CHECK: [[NEW_SELF:%.*]] = apply [[SUPER_INIT]]([[ORIG_SELF]]) // CHECK: store [[NEW_SELF]] to [init] [[PB_SELF_BOX]] convenience init(x: Int) { self.init() } } class Zim: Foo { var foo = Foo() // CHECK-LABEL: sil hidden @_T022super_init_refcounting3ZimC{{[_0-9a-zA-Z]*}}fc // CHECK-NOT: copy_value // CHECK-NOT: destroy_value // CHECK: function_ref @_T022super_init_refcounting3FooCACycfc : $@convention(method) (@owned Foo) -> @owned Foo } class Zang: Foo { var foo: Foo override init() { foo = Foo() super.init() } // CHECK-LABEL: sil hidden @_T022super_init_refcounting4ZangC{{[_0-9a-zA-Z]*}}fc // CHECK-NOT: copy_value // CHECK-NOT: destroy_value // CHECK: function_ref @_T022super_init_refcounting3FooCACycfc : $@convention(method) (@owned Foo) -> @owned Foo } class Bad: Foo { // Invalid code, but it's not diagnosed till DI. We at least shouldn't // crash on it. override init() { super.init(self) } } class Good: Foo { let x: Int // CHECK-LABEL: sil hidden @_T022super_init_refcounting4GoodC{{[_0-9a-zA-Z]*}}fc // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Good } // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[PB_SELF_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store %0 to [init] [[PB_SELF_BOX]] // CHECK: [[SELF_OBJ:%.*]] = load_borrow [[PB_SELF_BOX]] // CHECK: [[X_ADDR:%.*]] = ref_element_addr [[SELF_OBJ]] : $Good, #Good.x // CHECK: assign {{.*}} to [[X_ADDR]] : $*Int // CHECK: [[SELF_OBJ:%.*]] = load [take] [[PB_SELF_BOX]] : $*Good // CHECK: [[SUPER_OBJ:%.*]] = upcast [[SELF_OBJ]] : $Good to $Foo // CHECK: [[SUPER_INIT:%.*]] = function_ref @_T022super_init_refcounting3FooCACSicfc : $@convention(method) (Int, @owned Foo) -> @owned Foo // CHECK: [[BORROWED_SUPER:%.*]] = begin_borrow [[SUPER_OBJ]] // CHECK: [[DOWNCAST_BORROWED_SUPER:%.*]] = unchecked_ref_cast [[BORROWED_SUPER]] : $Foo to $Good // CHECK: [[X_ADDR:%.*]] = ref_element_addr [[DOWNCAST_BORROWED_SUPER]] : $Good, #Good.x // CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]] : $*Int // CHECK: end_borrow [[BORROWED_SUPER]] from [[SUPER_OBJ]] // CHECK: apply [[SUPER_INIT]]([[X]], [[SUPER_OBJ]]) override init() { x = 10 super.init(x) } }
apache-2.0
bb70483e0bc87bca6d4f00762f78138f
41.979381
149
0.544495
3.221793
false
false
false
false
qasim/CDFLabs
CDFLabs/Computers/Lab.swift
1
703
// // Lab.swift // CDFLabs // // Created by Qasim Iqbal on 12/30/15. // Copyright © 2015 Qasim Iqbal. All rights reserved. // import Foundation public class Lab { var name: String var avail: Int var busy: Int var total: Int var percent: Int public init() { self.name = "" self.avail = 0 self.busy = 0 self.total = 0 self.percent = 0 } public init(name: String, avail: Int, busy: Int, total: Int) { self.name = name self.avail = avail self.busy = busy self.total = total self.percent = Int(Double(round(100 * (Double(busy) / Double(total))) / 100) * 100) } }
mit
e3b1bf25d53b9f7dc214ff6428568811
18.5
91
0.539886
3.458128
false
false
false
false
barteljan/VISPER
Example/VISPER-Wireframe-Tests/Mocks/MockComposedRoutingObserver.swift
1
2476
// // MockComposedRoutingObserver.swift // VISPER-Wireframe_Tests // // Created by bartel on 22.11.17. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import VISPER_Core import VISPER_Wireframe class MockComposedRoutingObserver: NSObject, ComposedRoutingObserver { var invokedAdd = false var invokedAddCount = 0 var invokedAddParameters: (routingObserver: RoutingObserver, priority: Int, routePattern: String?)? var invokedAddParametersList = [(routingObserver: RoutingObserver, priority: Int, routePattern: String?)]() func add(routingObserver: RoutingObserver, priority: Int, routePattern: String?) { invokedAdd = true invokedAddCount += 1 invokedAddParameters = (routingObserver, priority, routePattern) invokedAddParametersList.append((routingObserver, priority, routePattern)) } var invokedWillPresent = false var invokedWillPresentCount = 0 var invokedWillPresentParameters: (controller: UIViewController, routeResult: RouteResult, routingPresenter: RoutingPresenter?, wireframe: Wireframe)? var invokedWillPresentParametersList = [(controller: UIViewController, routeResult: RouteResult, routingPresenter: RoutingPresenter?, wireframe: Wireframe)]() func willPresent(controller: UIViewController, routeResult: RouteResult, routingPresenter: RoutingPresenter?, wireframe: Wireframe) { invokedWillPresent = true invokedWillPresentCount += 1 invokedWillPresentParameters = (controller, routeResult, routingPresenter, wireframe) invokedWillPresentParametersList.append((controller, routeResult, routingPresenter, wireframe)) } var invokedDidPresent = false var invokedDidPresentCount = 0 var invokedDidPresentParameters: (controller: UIViewController, routeResult: RouteResult, routingPresenter: RoutingPresenter?, wireframe: Wireframe)? var invokedDidPresentParametersList = [(controller: UIViewController, routeResult: RouteResult, routingPresenter: RoutingPresenter?, wireframe: Wireframe)]() func didPresent(controller: UIViewController, routeResult: RouteResult, routingPresenter: RoutingPresenter?, wireframe: Wireframe) { invokedDidPresent = true invokedDidPresentCount += 1 invokedDidPresentParameters = (controller, routeResult, routingPresenter, wireframe) invokedDidPresentParametersList.append((controller, routeResult, routingPresenter, wireframe)) } }
mit
80355280b0622bec532323506773963f
47.529412
162
0.770101
5.978261
false
false
false
false
PiXeL16/SendToMe
SendToMeFramework/ShareContentExtractor.swift
1
5912
// // ShareContentExtractor.swift // SendToMe // // Created by Chris Jimenez on 1/30/16. // Copyright © 2016 Chris Jimenez. All rights reserved. // import Foundation import MobileCoreServices //Class in charge of extracting content of URL and pages using the extensionContext inputItems public class ShareContentExtractor{ public enum ExtractionTypes:String{ case PublicURL = "public.url" case PublicFileURL = "public.file-url" case PublicPlainText = "public.plain-text" } //Error Type public enum ExtractorError:ErrorType{ case NoContent case ExtractionError(description:String) } public init(){} /** Extract the content from a ExtentionItem - parameter extentionItem: Extention Item - parameter completionHandler: Response Closure */ public func extractContentFromNSExtensionItem(extentionItem:NSExtensionItem, completionHandler:(ShareContent?) -> Void) throws -> Void { if let itemProvider = extentionItem.attachments?.first as? NSItemProvider { let propertyList = String(kUTTypePropertyList) if itemProvider.hasItemConformingToTypeIdentifier(propertyList) { return extractPropertyList(itemProvider, completionHandler: completionHandler) } else if itemProvider.hasItemConformingToTypeIdentifier(ExtractionTypes.PublicURL.rawValue) { return extractPublicUrl(itemProvider, completionHandler: completionHandler) } else if itemProvider.hasItemConformingToTypeIdentifier(ExtractionTypes.PublicFileURL.rawValue) { return extractPublicFileUrl(itemProvider, completionHandler: completionHandler) } else if itemProvider.hasItemConformingToTypeIdentifier(ExtractionTypes.PublicPlainText.rawValue) { return extractPublicPlainText(itemProvider, completionHandler: completionHandler) } else { throw ExtractorError.NoContent } } } /** Extract the information of the item provider if it has a property list(Website) - parameter itemProvider: item provider - parameter completionHandler: completion handler */ public func extractPropertyList(itemProvider:NSItemProvider, completionHandler:(ShareContent?) -> Void) -> Void { let propertyList = String(kUTTypePropertyList) itemProvider.loadItemForTypeIdentifier(propertyList, options: nil, completionHandler: { (item, error) -> Void in let dictionary = item as! NSDictionary NSOperationQueue.mainQueue().addOperationWithBlock { if let results = dictionary[NSExtensionJavaScriptPreprocessingResultsKey] as? NSDictionary { let titleString = results["title"] as? String let urlString = results["currentUrl"] as? String let shareContent = ShareContent(title:titleString, url: urlString) return completionHandler(shareContent) }else{ return completionHandler(nil) } } }) } /** Extract the public url of an item provider - parameter itemProvider: itemProvider with the url content - parameter completionHandler: completion handler */ public func extractPublicUrl(itemProvider:NSItemProvider, completionHandler:(ShareContent?) -> Void) -> Void { itemProvider.loadItemForTypeIdentifier(ExtractionTypes.PublicURL.rawValue, options: nil, completionHandler: { (url, error) -> Void in if let shareURL = url as? NSURL { let urlString = shareURL.absoluteString let shareContent = ShareContent(title:nil, url: urlString) return completionHandler(shareContent) } else { return completionHandler(nil) } }) } /** Extract the public url of an item provider - parameter itemProvider: itemProvider with the url content - parameter completionHandler: completion handler */ public func extractPublicFileUrl(itemProvider:NSItemProvider, completionHandler:(ShareContent?) -> Void) -> Void { itemProvider.loadItemForTypeIdentifier(ExtractionTypes.PublicFileURL.rawValue, options: nil, completionHandler: { (url, error) -> Void in if let shareURL = url as? NSURL { let urlString = shareURL.absoluteString let shareContent = ShareContent(title:nil, url: urlString) return completionHandler(shareContent) } else { return completionHandler(nil) } }) } public func extractPublicPlainText(itemProvider:NSItemProvider, completionHandler:(ShareContent?) -> Void) -> Void { itemProvider.loadItemForTypeIdentifier(ExtractionTypes.PublicPlainText.rawValue, options: nil, completionHandler: { (decoder, error) -> Void in if let string = decoder as? String { let shareContent = ShareContent(title:nil, url: string) return completionHandler(shareContent) } else { return completionHandler(nil) } }) } }
mit
97bb49723db86a1afcfc01df42049e60
33.976331
151
0.591609
6.604469
false
false
false
false
gewill/Feeyue
Feeyue/Main/Weibo/WeiboModel.swift
1
4868
// // Status.swift // Feeyue // // Created by Will on 1/16/16. // Copyright © 2016 gewill.org. All rights reserved. // import Foundation import RealmSwift import IGListKit import SwiftyJSON import Moya_SwiftyJSONMapper class User: BaseModel, ALSwiftyJSONAble { enum Property: String { case userId, screenName, avatarHd, isFriend, isFollower } @objc dynamic var userId: Int = 0 @objc dynamic var screenName: String? @objc dynamic var avatarHd: String? @objc dynamic var isFriend = false @objc dynamic var isFollower = false // Realm override static func primaryKey() -> String? { return Property.userId.rawValue } // MARK: - Object Mapper convenience required init(jsonData json: JSON) { self.init() self.userId = json["id"].intValue self.screenName = json["screen_name"].stringValue self.avatarHd = json["avatar_hd"].stringValue } } class Status: BaseModel, ALSwiftyJSONAble { enum Property: String { case statusId, text, source, createdAt, favorited, repostsCount, commentsCount, retweetedStatus, user, pics } @objc dynamic var statusId: Int = 0 @objc dynamic var text: String? @objc dynamic var source: String? @objc dynamic var createdAt: Date? @objc dynamic var favorited = false // 暂时如此处理,稍后还是要获取关注列表进行过滤数据库 // dynamic var isInHomeTimeline = false @objc dynamic var repostsCount = 0 @objc dynamic var commentsCount = 0 @objc dynamic var retweetedStatus: Status? @objc dynamic var user: User? let pics = List<String>() override static func primaryKey() -> String? { return "statusId" } // MARK: - Object Mapper convenience required init(jsonData json: JSON) { self.init() self.statusId = json["id"].intValue self.source = SourceHelper.convert(json["source"]) self.createdAt = DateHelper.convert(json["created_at"]) self.text = json["text"].stringValue self.favorited = json["favorited"].boolValue self.repostsCount = json["reposts_count"].intValue self.commentsCount = json["comments_count"].intValue if json["retweeted_status"] != JSON.null { self.retweetedStatus = Status(jsonData: json["retweeted_status"]) } if json["user"] != JSON.null { self.user = User(jsonData: json["user"]) } json["pic_urls"].arrayValue.forEach { self.pics.append($0["thumbnail_pic"].stringValue) } } // MARK: - CRUD methods static func all(in realm: Realm = try! Realm()) -> Results<Status> { return realm.objects(Status.self) .sorted(byKeyPath: Status.Property.createdAt.rawValue, ascending: false) } @discardableResult static func add(json: JSON, in realm: Realm = try! Realm()) -> Status { let model = Status(jsonData: json) try! realm.write { realm.add(model, update: true) } return model } // MARK: - Computer porperties var hasRetweetedPics: Bool { if let pics = self.retweetedStatus?.pics, pics.isEmpty == false { return true } return false } var thumbnailPics: [String] { var array = Array(pics) if let pics = self.retweetedStatus?.pics { array.append(contentsOf: Array(pics)) } return array } var middlePics: [String] { return thumbnailPics.map { $0.replacingOccurrences(of: "/thumbnail/", with: "/bmiddle/") } } var largePics: [String] { return thumbnailPics.map { $0.replacingOccurrences(of: "/thumbnail/", with: "/large/") } } } class Comment: BaseModel { enum Property: String { case commentId, text, source, createdAt, statusId, user } @objc dynamic var commentId: Int = 0 @objc dynamic var text: String? @objc dynamic var source: String? @objc dynamic var createdAt: Date? @objc dynamic var statusId: Int = 0 @objc dynamic var user: User? override static func primaryKey() -> String? { return Property.commentId.rawValue } // MARK: - Object Mapper convenience required init(jsonData json: JSON) { self.init() self.commentId = json["id"].intValue self.source = SourceHelper.convert(json["source"]) self.createdAt = DateHelper.convert(json["created_at"]) self.text = json["text"].stringValue self.statusId = json["status", "id"].intValue } @discardableResult static func add(json: JSON, in realm: Realm = try! Realm()) -> Comment { let model = Comment(jsonData: json) try! realm.write { realm.add(model, update: true) } return model } }
mit
9a024866bb940e070da16ecb9507d0a4
26.369318
115
0.620511
4.289403
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/HCILEReadLocalP256PublicKeyComplete.swift
1
1699
// // HCILEReadLocalP256PublicKeyComplete.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/15/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /// LE Read Local P-256 Public Key Complete Event /// /// This event is generated when local P-256 key generation is complete. @frozen public struct HCILEReadLocalP256PublicKeyComplete: HCIEventParameter { public static let event = LowEnergyEvent.readLocalP256PublicKeyComplete // 0x08 public static let length: Int = 65 public let status: HCIStatus public let localP256PublicKey: UInt512 public init?(data: Data) { guard data.count == type(of: self).length else { return nil } let statusByte = data[0] guard let status = HCIStatus(rawValue: statusByte) else { return nil } let localP256PublicKey = UInt512(littleEndian: UInt512(bytes: ((data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16], data[17], data[18], data[19], data[20], data[21], data[22], data[23], data[24], data[25], data[26], data[27], data[28], data[29], data[30], data[31], data[32], data[33], data[34], data[35], data[36], data[37], data[38], data[39], data[40], data[41], data[42], data[43], data[44], data[45], data[46], data[47], data[48], data[49], data[50], data[51], data[52], data[53], data[54], data[55], data[56], data[57], data[58], data[59], data[60], data[61], data[62], data[63], data[64])))) self.status = status self.localP256PublicKey = localP256PublicKey } }
mit
65168942fad9ec3369cf38fbba4fea09
41.45
705
0.629564
3.409639
false
false
false
false
ijoshsmith/swift-tic-tac-toe
Framework/TicTacToeTests/PlayerTests.swift
1
998
// // PlayerTests.swift // TicTacToe // // Created by Joshua Smith on 11/28/15. // Copyright © 2015 iJoshSmith. All rights reserved. // import XCTest class PlayerTests: XCTestCase { func test_choosePositionWithCompletionHandler_strategyChoosesCenterPosition_choosesCenterPosition() { let board = GameBoard(), center = GameBoard.Position(row: 1, column: 1), script = ScriptedStrategy(positions: [center]), player = Player(mark: .X, gameBoard: board, strategy: script) // Use an expectation to avoid assuming the completion handler is immediately invoked. let expectation = expectationWithDescription("Player chooses center position") player.choosePositionWithCompletionHandler { position in XCTAssertEqual(position.row, center.row) XCTAssertEqual(position.column, center.column) expectation.fulfill() } waitForExpectationsWithTimeout(0.1, handler: nil) } }
mit
e6d387b46549128db7fdaf6443e3d469
33.37931
105
0.682046
4.770335
false
true
false
false
tristanchu/FlavorFinder
FlavorFinder/FlavorFinder/AddHotpotToList.swift
1
8549
// // addHotpotToList.swift // FlavorFinder // // Created by Courtney Ligh on 2/15/16. // Copyright © 2016 TeamFive. All rights reserved. // import UIKit import Parse class AddHotpotToListController: UITableViewController { // MARK: Properties: let listCellIdentifier = "listAddCellIdentifier" let createListCellIdentitfier = "createListCellIdentifier" var userLists = [PFList]() // Parse related: let listClassName = "List" let ingredientsColumnName = "ingredients" let userColumnName = "user" let ListTitleColumnName = "title" // Table itself: @IBOutlet var addToListTableView: UITableView! // Strings: let newListCellTitle = "Create new list with ingredients" let pageTitle = "Add To List" let newListTitle = "New Untitled List" // Navigation: var backBtn: UIBarButtonItem = UIBarButtonItem() let backBtnAction = "backBtnClicked:" let backBtnString = String.fontAwesomeIconWithName(.ChevronLeft) + " Cancel" // Segues: let segueToCreateNewListFromSearch = "segueToCreateNewListFromSearch" // MARK: Override methods: ---------------------------------------------- /* viewDidLoad: Additional setup after loading the view (upon open) */ override func viewDidLoad() { super.viewDidLoad() // Connect table view to this controller: addToListTableView.delegate = self addToListTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: listCellIdentifier) addToListTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: createListCellIdentitfier) // Table view visuals: addToListTableView.backgroundColor = BACKGROUND_COLOR // remove empty cells addToListTableView.tableFooterView = UIView(frame: CGRectZero) addToListTableView.rowHeight = UNIFORM_ROW_HEIGHT // Set up back button setUpBackButton() } /* viewDidAppear: Setup when user goes into page. */ override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // Get navigation bar on top: if let navi = self.tabBarController?.navigationController as? MainNavigationController { navi.reset_navigationBar(); self.tabBarController?.navigationItem.setLeftBarButtonItems( [self.backBtn], animated: true) self.tabBarController?.navigationItem.setRightBarButtonItems( [], animated: true) self.tabBarController?.navigationItem.title = pageTitle; self.backBtn.enabled = true } // Populate and display table: populateListsTable() // Update table view: addToListTableView.reloadData() print(currentIngredientToAdd) } /* tableView -> int returns number of cells to display */ override func tableView( tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.userLists.count + 1 // add 1 for the create new list row } /* tableView -> UITableViewCell creates cell for each index in favoriteCells */ override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // create new at first cell: if (indexPath.row == 0){ // set cell identifier: let cell = tableView.dequeueReusableCellWithIdentifier(createListCellIdentitfier, forIndexPath: indexPath) // set Cell label: cell.textLabel?.text = newListCellTitle // Give cell a chevron: cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator return cell // User lists at other cells: } else { // set cell identifier: let cell = tableView.dequeueReusableCellWithIdentifier( listCellIdentifier, forIndexPath: indexPath) // Set cell label: cell.textLabel?.text = userLists[indexPath.row - 1].objectForKey( ListTitleColumnName) as? String return cell } } /* tableView -> Add current search to selected list - adds either to existing list or creates new list with current search: */ override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // Create new list: if (indexPath.row == 0){ self.performSegueWithIdentifier(segueToCreateNewListFromSearch, sender: self) // Picked an existing list: } else { let listObject = userLists[indexPath.row - 1] // add 1 Ingredient: if (!currentIngredientToAdd.isEmpty) { addtoList(listObject, adding: currentIngredientToAdd) // clear global var: currentIngredientToAdd = [] // OR Add Current Search: } else { addtoList(listObject, adding: currentSearch) } // go back to search page: self.navigationController?.popViewControllerAnimated(true) } } // MARK: Functions ------------------------------------------------- /* populateListsTable: clears current userLists array; gets user lists from parse local db if user is logged in. */ func populateListsTable() { userLists.removeAll() // Get user's lists from Parse local db if user logged in: if let user = currentUser { userLists = getUserListsFromLocal(user) as! [PFList] } } // MARK: Back Button Functions ------------------------------------- /* setUpBackButton sets up the back button visuals for navigation */ func setUpBackButton() { backBtn.setTitleTextAttributes(attributes, forState: .Normal) backBtn.title = self.backBtnString backBtn.tintColor = NAVI_BUTTON_COLOR backBtn.target = self backBtn.action = "backBtnClicked" // refers to: backBtnClicked() } /* backBtnClicked - action for back button */ func backBtnClicked() { currentIngredientToAdd = [] self.navigationController?.popViewControllerAnimated(true) } // MARK: Appending to list --------------------------------------------- /* addToList can be called with current search or with the one ingredient to add */ func addtoList(listObject: PFList, adding: [PFIngredient]) { let list = listObject.objectForKey(ingredientsColumnName) as! [PFIngredient] let listName = listObject.objectForKey(ListTitleColumnName) as! String for ingredient in adding { if !list.contains(ingredient) { listObject.addIngredient(ingredient) } } // Toast Feedback: makeListToast(listName, iList: adding) } /* createNewList To be called on naming page - to create new list with a name */ func createNewList(listName: String, adding: [PFIngredient]) { var list = [PFIngredient]() for ingredient in adding{ list.append(ingredient) } createIngredientList(currentUser!, title: listName, ingredients: list) // toast feedback: makeListToast(newListTitle, iList: adding) } // MARK: Toast Message - -------------------------------------------------- /* addToListMsg - creates the message "Added __, __, __ to listname" */ func addToListMsg(listName: String, ingredients: [PFIngredient]) -> String { if ingredients.count == 1 { return "Added \(ingredients[0].name) to \(listName)" } let names: [String] = ingredients.map { return $0.name } let ingredientsString = names.joinWithSeparator(", ") return "Added \(ingredientsString) to \(listName)" } /* makeListToast - just to clean up the above code. */ func makeListToast(listTitle: String, iList: [PFIngredient]) { self.navigationController?.view.makeToast(addToListMsg( listTitle, ingredients: iList), duration: TOAST_DURATION, position: .AlmostBottom) } }
mit
18044b7ac84768b7107fb7541e3aa6ed
33.196
122
0.599438
5.434202
false
false
false
false
obrichak/discounts
discounts/Classes/BarCodeGenerator/UIColorExtension.swift
1
1604
// // UIColorExtension.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/13/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import UIKit extension UIColor { convenience init(rgba: String) { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 if rgba.hasPrefix("#") { let index = advance(rgba.startIndex, 1) let hex = rgba.substringFromIndex(index) let scanner = NSScanner.scannerWithString(hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexLongLong(&hexValue) { if hex.length() == 6 { red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 } else if hex.length() == 8 { red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 } else { print("invalid rgb string, length should be 7 or 9") } } else { println("scan hex error") } } else { print("invalid rgb string, missing '#' as prefix") } self.init(red:red, green:green, blue:blue, alpha:alpha) } }
gpl-3.0
f86b0747745a20044cb13c83c2dc25dc
35.477273
74
0.498753
4.102302
false
false
false
false
qpre/swifter
Sources/Swifter/DemoServer.swift
1
2235
// // DemoServer.swift // Swifter // Copyright (c) 2015 Damian Kołakowski. All rights reserved. // import Foundation public func demoServer(publicDir: String?) -> HttpServer { let server = HttpServer() if let publicDir = publicDir { server["/resources/:file"] = HttpHandlers.directory(publicDir) } server["/files/:path"] = HttpHandlers.directoryBrowser("~/") server["/"] = { r in var listPage = "Available services:<br><ul>" listPage += server.routes.map({ "<li><a href=\"\($0)\">\($0)</a></li>"}).joinWithSeparator("") return .OK(.Html(listPage)) } server["/magic"] = { .OK(.Html("You asked for " + $0.url)) } server["/test/:param1/:param2"] = { r in var headersInfo = "" for (name, value) in r.headers { headersInfo += "\(name) : \(value)<br>" } var queryParamsInfo = "" for (name, value) in r.urlParams { queryParamsInfo += "\(name) : \(value)<br>" } var pathParamsInfo = "" for token in r.params { pathParamsInfo += "\(token.0) : \(token.1)<br>" } return .OK(.Html("<h3>Address: \(r.address)</h3><h3>Url:</h3> \(r.url)<h3>Method: \(r.method)</h3><h3>Headers:</h3>\(headersInfo)<h3>Query:</h3>\(queryParamsInfo)<h3>Path params:</h3>\(pathParamsInfo)")) } server["/demo"] = { r in return .OK(.Html("<center><h2>Hello Swift</h2><img src=\"https://devimages.apple.com.edgekey.net/swift/images/swift-hero_2x.png\"/><br></center>")) } server["/raw"] = { request in return HttpResponse.RAW(200, "OK", ["XXX-Custom-Header": "value"], [UInt8]("Sample Response".utf8)) } server["/json"] = { request in let jsonObject: NSDictionary = [NSString(string: "foo"): NSNumber(int: 3), NSString(string: "bar"): NSString(string: "baz")] return .OK(.Json(jsonObject)) } server["/redirect"] = { request in return .MovedPermanently("http://www.google.com") } server["/long"] = { request in var longResponse = "" for k in 0..<1000 { longResponse += "(\(k)),->" } return .OK(.Html(longResponse)) } return server }
bsd-3-clause
48a36fd015f2a118b8a4bb639a87cc15
32.848485
211
0.555953
3.686469
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/WordPressDraftActionExtension/Tracks+DraftAction.swift
1
2420
import Foundation /// This extension implements helper tracking methods, meant for Draft Action Extension usage. /// extension Tracks { // MARK: - Public Methods public func trackExtensionLaunched(_ wpcomAvailable: Bool) { let properties = ["is_configured_dotcom": wpcomAvailable] trackExtensionEvent(.launched, properties: properties as [String: AnyObject]?) } public func trackExtensionPosted(_ status: String) { let properties = ["post_status": status] trackExtensionEvent(.posted, properties: properties as [String: AnyObject]?) } public func trackExtensionError(_ error: NSError) { let properties = ["error_code": String(error.code), "error_domain": error.domain, "error_description": error.description] trackExtensionEvent(.error, properties: properties as [String: AnyObject]?) } public func trackExtensionCancelled() { trackExtensionEvent(.canceled) } public func trackExtensionTagsOpened() { trackExtensionEvent(.tagsOpened) } public func trackExtensionTagsSelected(_ tags: String) { let properties = ["selected_tags": tags] trackExtensionEvent(.tagsSelected, properties: properties as [String: AnyObject]?) } public func trackExtensionCategoriesOpened() { trackExtensionEvent(.categoriesOpened) } public func trackExtensionCategoriesSelected(_ categories: String) { let properties = ["categories_tags": categories] trackExtensionEvent(.categoriesSelected, properties: properties as [String: AnyObject]?) } // MARK: - Private Helpers fileprivate func trackExtensionEvent(_ event: ExtensionEvents, properties: [String: AnyObject]? = nil) { track(event.rawValue, properties: properties) } // MARK: - Private Enums fileprivate enum ExtensionEvents: String { case launched = "wpios_draft_extension_launched" case posted = "wpios_draft_extension_posted" case tagsOpened = "wpios_draft_extension_tags_opened" case tagsSelected = "wpios_draft_extension_tags_selected" case canceled = "wpios_draft_extension_canceled" case error = "wpios_draft_extension_error" case categoriesOpened = "wpios_draft_extension_categories_opened" case categoriesSelected = "wpios_draft_extension_categories_selected" } }
gpl-2.0
bc0b8fb1a7e2f4636b4bb1b39290d5fd
37.412698
129
0.68595
5.010352
false
false
false
false
merlos/iOS-Open-GPX-Tracker
Pods/CoreGPX/Classes/GPXMetadata.swift
1
4084
// // GPXMetadata.swift // GPXKit // // Created by Vincent on 22/11/18. // import Foundation /** A value type that represents the metadata header of a GPX file. Information about the GPX file should be stored here. - Supported Info types: - Name - Description - Author Info - Copyright - Date and Time - Keyword - Bounds - Also supports extensions */ public final class GPXMetadata: GPXElement, Codable { /// Name intended for the GPX file. public var name: String? /// Description about what the GPX file is about. public var desc: String? /// Author, or the person who created the GPX file. /// /// Includes other information regarding the author (see `GPXAuthor`) public var author: GPXAuthor? /// Copyright of the file, if required. public var copyright: GPXCopyright? /// A web link, usually one with information regarding the GPX file. @available(*, deprecated, message: "CoreGPX now support multiple links.", renamed: "links.first") public var link: GPXLink? { return links.first } /// Web links, usually containing information regarding the current GPX file which houses this metadata. public var links = [GPXLink]() /// Date and time of when the GPX file is created. public var time: Date? /// Keyword of the GPX file. public var keywords: String? /// Boundaries of coordinates of the GPX file. public var bounds: GPXBounds? /// Extensions to standard GPX, if any. public var extensions: GPXExtensions? // MARK:- Initializers /// Default initializer. required public init() { self.time = Date() super.init() } /// Inits native element from raw parser value /// /// - Parameters: /// - raw: Raw element expected from parser init(raw: GPXRawElement) { //super.init() for child in raw.children { //let text = child.text switch child.name { case "name": self.name = child.text case "desc": self.desc = child.text case "author": self.author = GPXAuthor(raw: child) case "copyright": self.copyright = GPXCopyright(raw: child) case "link": self.links.append(GPXLink(raw: child)) case "time": self.time = GPXDateParser().parse(date: child.text) case "keywords": self.keywords = child.text case "bounds": self.bounds = GPXBounds(raw: child) case "extensions": self.extensions = GPXExtensions(raw: child) default: continue } } } // MARK:- Tag override func tagName() -> String { return "metadata" } // MARK:- GPX override func addChildTag(toGPX gpx: NSMutableString, indentationLevel: Int) { super.addChildTag(toGPX: gpx, indentationLevel: indentationLevel) self.addProperty(forValue: name, gpx: gpx, tagName: "name", indentationLevel: indentationLevel) self.addProperty(forValue: desc, gpx: gpx, tagName: "desc", indentationLevel: indentationLevel) if author != nil { self.author?.gpx(gpx, indentationLevel: indentationLevel) } if copyright != nil { self.copyright?.gpx(gpx, indentationLevel: indentationLevel) } for link in links { link.gpx(gpx, indentationLevel: indentationLevel) } self.addProperty(forValue: Convert.toString(from: time), gpx: gpx, tagName: "time", indentationLevel: indentationLevel) self.addProperty(forValue: keywords, gpx: gpx, tagName: "keywords", indentationLevel: indentationLevel) if bounds != nil { self.bounds?.gpx(gpx, indentationLevel: indentationLevel) } if extensions != nil { self.extensions?.gpx(gpx, indentationLevel: indentationLevel) } } }
gpl-3.0
d7eda1258e297c083e612398f00ec457
30.175573
127
0.599167
4.732329
false
false
false
false
pixel-ink/PIImageCache
PIImageCache/PIImageCacheTests/PIImageCacheDiskCacheTests.swift
2
2230
// https://github.com/pixel-ink/PIImageCache import UIKit import XCTest class PIImageDiskCacheTests: XCTestCase { let max = PIImageCache.Config().maxMemorySum func testDiskCache() { let cache = PIImageCache() var image: UIImage?, result: PIImageCache.Result var urls :[NSURL] = [] for i in 0 ..< max * 2 { urls.append(NSURL(string: "http://place-hold.it/200x200/2ff&text=No.\(i)")!) } for i in 0 ..< max * 2 { (image, result) = cache.perform(urls[i]) XCTAssert(result != .MemoryHit, "Pass") XCTAssert(image!.size.width == 200 && image!.size.height == 200 , "Pass") } for i in 0 ..< max * 2 { (image, result) = cache.perform(urls[i]) XCTAssert(result == .DiskHit, "Pass") XCTAssert(image!.size.width == 200 && image!.size.height == 200 , "Pass") } } func testFileTimeStamp() { PIImageCache.shared.oldDiskCacheDelete() let config = PIImageCache.Config() let path = "\(config.cacheRootDirectory)\(config.cacheFolderName)/" let allFileName: [String]? = NSFileManager.defaultManager().contentsOfDirectoryAtPath(path, error: nil) as? [String] if let all = allFileName { for fileName in all { if let attr = NSFileManager.defaultManager().attributesOfItemAtPath(path + fileName, error: nil) { let diff = NSDate().timeIntervalSinceDate( (attr[NSFileModificationDate] as? NSDate) ?? NSDate(timeIntervalSince1970: 0) ) XCTAssert( Double(diff) <= Double(config.diskCacheExpireMinutes * 60) , "Pass") } } } } func testPrefetch() { let cache = PIImageCache() var image: UIImage?, result: PIImageCache.Result var urls :[NSURL] = [] for i in 0 ..< max * 2 { urls.append(NSURL(string: "http://place-hold.it/200x200/2ff&text=BackgroundNo.\(i)")!) } cache.prefetch(urls) for i in 0 ..< max * 2 { (image, result) = cache.perform(urls[i]) XCTAssert(image!.size.width == 200 && image!.size.height == 200 , "Pass") } for i in 0 ..< max * 2 { (image, result) = cache.perform(urls[i]) XCTAssert(result != .Mishit, "Pass") XCTAssert(image!.size.width == 200 && image!.size.height == 200 , "Pass") } } }
mit
a72244d49596d1c7dbe0efd7cfb6666f
34.396825
132
0.619731
3.766892
false
true
false
false
RuiAAPeres/TeamGen
TeamGenFoundation/Sources/Components/UI/Flow.swift
1
1759
import UIKit public protocol Flow { func present(_ viewController: UIViewController, animated: Bool) func dismiss(_ animated: Bool) } private struct ModalFlow: Flow { private let origin: UIViewController init(_ viewController: UIViewController) { self.origin = viewController } func present(_ viewController: UIViewController, animated: Bool) { origin.present(viewController, animated: animated, completion: nil) } func dismiss(_ animated: Bool) { origin.dismiss(animated: animated, completion: nil) } } private struct NavigationFlow: Flow { private let origin: UINavigationController init(_ viewController: UINavigationController) { self.origin = viewController } func present(_ viewController: UIViewController, animated: Bool) { origin.pushViewController(viewController, animated: animated) } func dismiss(_ animated: Bool) { origin.popViewController(animated: animated) } } private struct WindowFlow: Flow { private let window: UIWindow init(_ window: UIWindow) { self.window = window } func present(_ viewController: UIViewController, animated: Bool) { window.rootViewController = viewController window.makeKeyAndVisible() } func dismiss(_ animated: Bool) { window.rootViewController = nil } } public extension UIWindow { var flow: Flow { return WindowFlow(self) } } public extension UIViewController { var modalFlow: Flow { return ModalFlow(self) } var navigationFlow: Flow { guard let navigationController = self.navigationController else { return modalFlow } return NavigationFlow(navigationController) } }
mit
e6e22e7ca505df808c7c0410959e280d
23.430556
92
0.681069
5.025714
false
false
false
false
ayvazj/BrundleflyiOS
Pod/Classes/Model/BtfyColor.swift
1
2067
/* * Copyright (c) 2015 James Ayvaz * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ struct BtfyColor { var r: Double var g: Double var b: Double var a: Double init () { self.r = 0 self.g = 0 self.b = 0 self.a = 1 } init (r: Double, g: Double, b: Double) { self.r = r self.g = g self.b = b self.a = 1 } init (a: Double, r: Double, g: Double, b: Double) { self.r = r self.g = g self.b = b self.a = a } static func parseRGBA(json: [String:AnyObject]) -> BtfyColor { var a = json["a"] as! Double? var r = json["r"] as! Double? var g = json["g"] as! Double? var b = json["b"] as! Double? if a == nil { a = 1.0 } if r == nil { r = 1.0 } if g == nil { g = 1.0 } if b == nil { b = 1.0 } return BtfyColor(a: a!, r: r!, g: g!, b: b!) } }
mit
e3e955e588873aaf9457dcbeb7d39cca
28.112676
79
0.586357
3.870787
false
false
false
false
clutter/Pelican
Tests/PelicanTests/PelicanTests.swift
1
10404
// // PelicanTests.swift // Pelican // // Created by Robert Manson on 4/5/17. // Copyright © 2017 CocoaPods. All rights reserved. // import XCTest @testable import Pelican private class TaskCollector { enum Task { case taskA(value: HouseAtreides) case taskB(value: HouseHarkonnen) var name: String { switch self { case .taskA(let value): return value.name case .taskB(let value): return value.name } } var houseAtreides: HouseAtreides? { switch self { case .taskA(let value): return value default: return nil } } var houseHarkonnen: HouseHarkonnen? { switch self { case .taskB(let value): return value default: return nil } } } static var shared = TaskCollector() var collected = [Task]() func collect(tasks: [PelicanBatchableTask]) { for task in tasks { if let task = task as? HouseAtreides { collected.append(.taskA(value: task)) } else if let task = task as? HouseHarkonnen { collected.append(.taskB(value: task)) } else { fatalError() } } } } private protocol DuneCharacter: PelicanGroupable { var name: String { get } } extension DuneCharacter where Self: PelicanBatchableTask { var group: String { return "Dune Character Group" } static func processGroup(tasks: [PelicanBatchableTask], didComplete: @escaping ((PelicanProcessResult) -> Void)) { TaskCollector.shared.collect(tasks: tasks) didComplete(PelicanProcessResult.done) } } private struct HouseAtreides: PelicanBatchableTask, DuneCharacter { let name: String let timeStamp: Date init(name: String, birthdate: Date) { self.timeStamp = birthdate self.name = name } // PelicanBatchableTask conformance, used to read and store task to storage static let taskType: String = String(describing: HouseAtreides.self) } private struct HouseHarkonnen: PelicanBatchableTask, DuneCharacter { let name: String let weapon: String init(name: String, weapon: String) { self.name = name self.weapon = weapon } // PelicanBatchableTask conformance, used to read and store task to storage static let taskType: String = String(describing: HouseHarkonnen.self) } /// Test the example code in the ReadMe class PelicanSavingAndRecoveringFromAppState: XCTestCase { let letosDate: Date = Date.distantFuture let paulsDate: Date = Date.distantFuture.addingTimeInterval(-6000) var storage: InMemoryStorage! override func setUp() { storage = InMemoryStorage() // Start by registering and immediately adding 2 tasks TaskCollector.shared.collected = [] var tasks = Pelican.RegisteredTasks() tasks.register(for: HouseAtreides.self) tasks.register(for: HouseHarkonnen.self) Pelican.initialize(tasks: tasks, storage: storage) } override func tearDown() { Pelican.shared.stop() storage = nil } func testSavesWhenBackgroundedRecoversWhenForegrounded() { Pelican.shared.gulp(task: HouseAtreides(name: "Duke Leto", birthdate: letosDate)) Pelican.shared.gulp(task: HouseHarkonnen(name: "Glossu Rabban", weapon: "brutishness")) let tasksGulped = expectation(description: "Tasks Gulped and Processed") DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + .seconds(6)) { let taskCount = TaskCollector.shared.collected.count XCTAssert(taskCount == 2, "Task count is \(taskCount)") XCTAssert(TaskCollector.shared.collected[0].name == "Duke Leto", "Task is \(TaskCollector.shared.collected[0].name)") XCTAssert(TaskCollector.shared.collected[1].name == "Glossu Rabban", "Task is \(TaskCollector.shared.collected[1].name)") tasksGulped.fulfill() } waitForExpectations(timeout: 7.0, handler: nil) XCTAssert(storage.store == nil) TaskCollector.shared.collected = [] XCTAssertTrue(Pelican.shared.groupedTasks.allTasks().isEmpty) // Add two more tasks and simulate backgrounding Pelican.shared.gulp(task: HouseAtreides(name: "Paul Atreides", birthdate: paulsDate)) Pelican.shared.gulp(task: HouseHarkonnen(name: "Baron Vladimir Harkonnen", weapon: "cunning")) Pelican.shared.didEnterBackground() XCTAssert(storage["Dune Character Group"].count == 2) Pelican.shared.willEnterForeground() let storageLoaded = expectation(description: "Wait for storage to load") DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + .seconds(1)) { storageLoaded.fulfill() } waitForExpectations(timeout: 2.0, handler: nil) XCTAssert(storage.store == nil) let moreTasksGulped = expectation(description: "More Tasks Gulped and Processed") DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + .seconds(6)) { let taskCount = TaskCollector.shared.collected.count XCTAssertEqual(taskCount, 2) let paul = TaskCollector.shared.collected[0].houseAtreides XCTAssertEqual(paul?.name, "Paul Atreides") XCTAssertEqual(paul?.timeStamp, self.paulsDate) let baron = TaskCollector.shared.collected[1].houseHarkonnen XCTAssertEqual(baron?.name, "Baron Vladimir Harkonnen") XCTAssertEqual(baron?.weapon, "cunning") moreTasksGulped.fulfill() } waitForExpectations(timeout: 7.0, handler: nil) Pelican.shared.didEnterBackground() XCTAssert(storage.store == nil) } } class PelicanStoresOnGulpTests: XCTestCase { var storage: InMemoryStorage! var pelican: Pelican! override func setUp() { storage = InMemoryStorage() var tasks = Pelican.RegisteredTasks() tasks.register(for: HouseAtreides.self) tasks.register(for: HouseHarkonnen.self) pelican = Pelican(tasks: tasks, storage: storage) } override func tearDown() { pelican.stop() pelican = nil storage = nil } func testArchiveWithNoTasksSucceeds() { pelican.archiveGroups() // This should be nil, since we didn't gulp anything XCTAssertNil(storage.store) } func testArchiveGroupsSavesTasksToStorage() { pelican.gulp(task: HouseAtreides(name: "Duke Leto", birthdate: .distantPast)) pelican.gulp(task: HouseHarkonnen(name: "Glossu Rabban", weapon: "brutishness")) pelican.archiveGroups() let duneCharacterGroup = storage["Dune Character Group"] guard duneCharacterGroup.count == 2 else { XCTFail("Storage does not contain correct number of tasks for \"Dune Character Group\"") return } if let taskOne = duneCharacterGroup[0].task as? HouseAtreides { XCTAssertEqual(taskOne.name, "Duke Leto") XCTAssertEqual(taskOne.timeStamp, .distantPast) } else { XCTFail("Expecting first task to be HouseAtreides") } if let taskTwo = duneCharacterGroup[1].task as? HouseHarkonnen { XCTAssertEqual(taskTwo.name, "Glossu Rabban") XCTAssertEqual(taskTwo.weapon, "brutishness") } else { XCTFail("Expecting second task to be HouseHarkonnen") } } } class PelicanLoadsFromStorageTests: XCTestCase { var storage: InMemoryStorage! var pelican: Pelican! override func setUp() { storage = InMemoryStorage() var tasks = Pelican.RegisteredTasks() tasks.register(for: HouseAtreides.self) tasks.register(for: HouseHarkonnen.self) pelican = Pelican(tasks: tasks, storage: storage) } override func tearDown() { pelican.stop() pelican = nil storage = nil } func testUnarchiveGroupsLoadsNoTaskGroupsFromEmptyStorage() { pelican.unarchiveGroups() XCTAssertTrue(pelican.groupedTasks.allTasks().isEmpty) XCTAssertNil(storage.store) } func testUnarchiveGroupsLoadsArchivedTasksFromStorage() { let task = TaskContainer(task: HouseAtreides(name: "Duke Leto", birthdate: Date.distantPast)) storage["Dune Character Group"] = [ task ] pelican.unarchiveGroups() let allGroups = pelican.groupedTasks.allTasks() XCTAssertEqual(allGroups.count, 1) if let duneCharacterGroup = allGroups.first(where: { $0.group == "Dune Character Group" }) { guard duneCharacterGroup.containers.count == 1 else { XCTFail("Storage does not contain correct number of tasks for \"Dune Character Group\"") return } let taskContainer = duneCharacterGroup.containers[0] XCTAssertEqual(taskContainer.identifier, task.identifier) XCTAssertEqual(taskContainer.taskType, HouseAtreides.taskType) if let task = taskContainer.task as? HouseAtreides { XCTAssertEqual(task.name, "Duke Leto") XCTAssertEqual(task.timeStamp, Date.distantPast) } else { XCTFail("Task is not correct type (expected \(HouseAtreides.self), got \(type(of: taskContainer.task))") } } else { XCTFail("Storage does not contain correct group") } } } extension InMemoryStorage { subscript(groupName: String) -> [TaskContainer] { get { guard let data = store, let taskGroups = try? JSONDecoder().decode([GroupedTasks.GroupAndContainers].self, from: data) else { return [] } return taskGroups.first(where: { $0.group == groupName })?.containers ?? [] } set { guard !newValue.isEmpty else { store = nil return } let group = GroupedTasks.GroupAndContainers(group: groupName, containers: newValue) store = try? JSONEncoder().encode([group]) } } }
mit
12ea597df43c9307ba5e037bd7149149
32.236422
120
0.629626
4.798432
false
false
false
false
krzysztofzablocki/Sourcery
SourceryFramework/Sources/Parsing/Utils/InlineParser.swift
1
4284
// // Created by Krzysztof Zablocki on 16/01/2017. // Copyright (c) 2017 Pixle. All rights reserved. // import Foundation public enum TemplateAnnotationsParser { public typealias AnnotatedRanges = [String: [(range: NSRange, indentation: String)]] private static func regex(annotation: String) throws -> NSRegularExpression { let commentPattern = NSRegularExpression.escapedPattern(for: "//") let regex = try NSRegularExpression( pattern: "(^(?:\\s*?\\n)?(\\s*)\(commentPattern)\\s*?sourcery:\(annotation):)(\\S*)\\s*?(^.*?)(^\\s*?\(commentPattern)\\s*?sourcery:end)", options: [.allowCommentsAndWhitespace, .anchorsMatchLines, .dotMatchesLineSeparators] ) return regex } public static func parseAnnotations(_ annotation: String, contents: String, aggregate: Bool = false, forceParse: [String]) -> (contents: String, annotatedRanges: AnnotatedRanges) { let (annotatedRanges, rangesToReplace) = annotationRanges(annotation, contents: contents, aggregate: aggregate, forceParse: forceParse) let strigView = StringView(contents) var bridged = contents.bridge() rangesToReplace .sorted(by: { $0.location > $1.location }) .forEach { bridged = bridged.replacingCharacters(in: $0, with: String(repeating: " ", count: strigView.NSRangeToByteRange($0)!.length.value)) as NSString } return (bridged as String, annotatedRanges) } public static func annotationRanges(_ annotation: String, contents: String, aggregate: Bool = false, forceParse: [String]) -> (annotatedRanges: AnnotatedRanges, rangesToReplace: Set<NSRange>) { let bridged = contents.bridge() let regex = try? self.regex(annotation: annotation) var rangesToReplace = Set<NSRange>() var annotatedRanges = AnnotatedRanges() regex?.enumerateMatches(in: contents, options: [], range: bridged.entireRange) { result, _, _ in guard let result = result, result.numberOfRanges == 6 else { return } let indentationRange = result.range(at: 2) let nameRange = result.range(at: 3) let startLineRange = result.range(at: 4) let endLineRange = result.range(at: 5) let indentation = bridged.substring(with: indentationRange) let name = bridged.substring(with: nameRange) let range = NSRange( location: startLineRange.location, length: endLineRange.location - startLineRange.location ) if aggregate { var ranges = annotatedRanges[name] ?? [] ranges.append((range: range, indentation: indentation)) annotatedRanges[name] = ranges } else { annotatedRanges[name] = [(range: range, indentation: indentation)] } let rangeToBeRemoved = !forceParse.contains(where: { name.hasSuffix("." + $0) || name == $0 }) if rangeToBeRemoved { rangesToReplace.insert(range) } } return (annotatedRanges, rangesToReplace) } public static func removingEmptyAnnotations(from content: String) -> String { var bridged = content.bridge() let regex = try? self.regex(annotation: "\\S*") var rangesToReplace = [NSRange]() regex?.enumerateMatches(in: content, options: [], range: bridged.entireRange) { result, _, _ in guard let result = result, result.numberOfRanges == 6 else { return } let annotationStartRange = result.range(at: 1) let startLineRange = result.range(at: 4) let endLineRange = result.range(at: 5) if startLineRange.length == 0 { rangesToReplace.append(NSRange( location: annotationStartRange.location, length: NSMaxRange(endLineRange) - annotationStartRange.location )) } } rangesToReplace .reversed() .forEach { bridged = bridged.replacingCharacters(in: $0, with: "") as NSString } return bridged as String } }
mit
3f734b7cc949b8ad57ecc5119705f5b6
40.592233
197
0.604809
4.890411
false
false
false
false
onevcat/Rainbow
Sources/ControlCode.swift
1
1530
// // ControlCode.swift // Rainbow // // Created by Wei Wang on 15/12/22. // // Copyright (c) 2018 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. enum ControlCode { static let ESC: Character = "\u{001B}" static let OPEN_BRACKET: Character = "[" static let CSI = "\(ESC)\(OPEN_BRACKET)" static let setColor: UInt8 = 38 static let setBackgroundColor: UInt8 = 48 static let set8Bit: UInt8 = 5 static let set24Bit: UInt8 = 2 }
mit
f9ee8925ddd54e4284444f9433ba2f49
40.351351
81
0.724183
4.047619
false
false
false
false
lorentey/GlueKit
Sources/UIDevice Glue.swift
1
5911
// // UIDevice Glue.swift // GlueKit // // Created by Károly Lőrentey on 2016-03-13. // Copyright © 2015–2017 Károly Lőrentey. // #if os(iOS) import UIKit extension UIDevice { open override var glue: GlueForUIDevice { return _glue() } } open class GlueForUIDevice: GlueForNSObject { private var object: UIDevice { return owner as! UIDevice } public lazy var orientation: AnyObservableValue<UIDeviceOrientation> = ObservableDeviceOrientation(self.object).anyObservableValue public lazy var batteryState: AnyObservableValue<(UIDeviceBatteryState, Float)> = ObservableBatteryState(self.object).anyObservableValue public lazy var proximityState: AnyObservableValue<Bool> = ObservableDeviceProximity(self.object).anyObservableValue } private struct DeviceOrientationSink: UniqueOwnedSink { typealias Owner = ObservableDeviceOrientation unowned let owner: Owner func receive(_ notification: Notification) { owner.receive(notification) } } private final class ObservableDeviceOrientation: _BaseObservableValue<UIDeviceOrientation> { unowned let device: UIDevice var orientation: UIDeviceOrientation? = nil init(_ device: UIDevice) { self.device = device } override var value: UIDeviceOrientation { return device.orientation } lazy var notificationSource: AnySource<Notification> = NotificationCenter.default.glue.source(forName: .UIDeviceOrientationDidChange, sender: self.device, queue: OperationQueue.main) func receive(_ notification: Notification) { beginTransaction() let old = orientation! let new = device.orientation orientation = new sendChange(.init(from: old, to: new)) endTransaction() } override func activate() { device.beginGeneratingDeviceOrientationNotifications() orientation = device.orientation notificationSource.add(DeviceOrientationSink(owner: self)) } override func deactivate() { notificationSource.remove(DeviceOrientationSink(owner: self)) device.endGeneratingDeviceOrientationNotifications() orientation = nil } } private struct BatteryStateSink: UniqueOwnedSink { typealias Owner = ObservableBatteryState unowned let owner: Owner func receive(_ notification: Notification) { owner.receive(notification) } } private var batteryKey: UInt8 = 0 private final class ObservableBatteryState: _BaseObservableValue<(UIDeviceBatteryState, Float)> { typealias Value = (UIDeviceBatteryState, Float) unowned let device: UIDevice var state: Value? = nil var didEnableBatteryMonitoring = false lazy var batteryStateSource: AnySource<Notification> = NotificationCenter.default.glue.source(forName: .UIDeviceBatteryStateDidChange, sender: self.device, queue: OperationQueue.main) lazy var batteryLevelSource: AnySource<Notification> = NotificationCenter.default.glue.source(forName: .UIDeviceBatteryLevelDidChange, sender: self.device, queue: OperationQueue.main) init(_ device: UIDevice) { self.device = device } override var value: Value { return (device.batteryState, device.batteryLevel) } func receive(_ notification: Notification) { let old = state! let new = (device.batteryState, device.batteryLevel) if old != new { beginTransaction() state = new sendChange(.init(from: old, to: new)) endTransaction() } } override func activate() { if !device.isBatteryMonitoringEnabled { device.isBatteryMonitoringEnabled = true didEnableBatteryMonitoring = true } state = (device.batteryState, device.batteryLevel) batteryStateSource.add(BatteryStateSink(owner: self)) batteryLevelSource.add(BatteryStateSink(owner: self)) } override func deactivate() { batteryStateSource.remove(BatteryStateSink(owner: self)) batteryLevelSource.remove(BatteryStateSink(owner: self)) if didEnableBatteryMonitoring { device.isBatteryMonitoringEnabled = false didEnableBatteryMonitoring = false } state = nil } } private struct DeviceProximitySink: UniqueOwnedSink { typealias Owner = ObservableDeviceProximity unowned let owner: Owner func receive(_ notification: Notification) { owner.receive(notification) } } private var proximityKey: UInt8 = 0 private final class ObservableDeviceProximity: _BaseObservableValue<Bool> { unowned let device: UIDevice var state: Bool? = nil var didEnableProximityMonitoring = false lazy var notificationSource: AnySource<Notification> = NotificationCenter.default.glue.source(forName: .UIDeviceProximityStateDidChange, sender: self.device, queue: OperationQueue.main) init(_ device: UIDevice) { self.device = device } override var value: Bool { return device.proximityState } func receive(_ notification: Notification) { beginTransaction() let old = state! let new = device.proximityState state = new sendChange(.init(from: old, to: new)) endTransaction() } override func activate() { if !device.isProximityMonitoringEnabled { device.isProximityMonitoringEnabled = true didEnableProximityMonitoring = true } state = device.proximityState notificationSource.add(DeviceProximitySink(owner: self)) } override func deactivate() { notificationSource.remove(DeviceProximitySink(owner: self)) if didEnableProximityMonitoring { device.isProximityMonitoringEnabled = false didEnableProximityMonitoring = false } state = nil } } #endif
mit
9563e761d4c1532752a4540e74d489a5
29.43299
189
0.694783
5.271429
false
false
false
false
vbudhram/firefox-ios
ThirdParty/SQLite.swift/Tests/SQLiteTests/ConnectionTests.swift
2
13305
import XCTest @testable import SQLite #if SQLITE_SWIFT_STANDALONE import sqlite3 #elseif SQLITE_SWIFT_SQLCIPHER import SQLCipher #else import SQLite3 #endif class ConnectionTests : SQLiteTestCase { override func setUp() { super.setUp() CreateUsersTable() } func test_init_withInMemory_returnsInMemoryConnection() { let db = try! Connection(.inMemory) XCTAssertEqual("", db.description) } func test_init_returnsInMemoryByDefault() { let db = try! Connection() XCTAssertEqual("", db.description) } func test_init_withTemporary_returnsTemporaryConnection() { let db = try! Connection(.temporary) XCTAssertEqual("", db.description) } func test_init_withURI_returnsURIConnection() { let db = try! Connection(.uri("\(NSTemporaryDirectory())/SQLite.swift Tests.sqlite3")) XCTAssertEqual("\(NSTemporaryDirectory())/SQLite.swift Tests.sqlite3", db.description) } func test_init_withString_returnsURIConnection() { let db = try! Connection("\(NSTemporaryDirectory())/SQLite.swift Tests.sqlite3") XCTAssertEqual("\(NSTemporaryDirectory())/SQLite.swift Tests.sqlite3", db.description) } func test_readonly_returnsFalseOnReadWriteConnections() { XCTAssertFalse(db.readonly) } func test_readonly_returnsTrueOnReadOnlyConnections() { let db = try! Connection(readonly: true) XCTAssertTrue(db.readonly) } func test_changes_returnsZeroOnNewConnections() { XCTAssertEqual(0, db.changes) } func test_lastInsertRowid_returnsLastIdAfterInserts() { try! InsertUser("alice") XCTAssertEqual(1, db.lastInsertRowid) } func test_lastInsertRowid_doesNotResetAfterError() { XCTAssert(db.lastInsertRowid == 0) try! InsertUser("alice") XCTAssertEqual(1, db.lastInsertRowid) XCTAssertThrowsError( try db.run("INSERT INTO \"users\" (email, age, admin) values ('[email protected]', 12, 'invalid')") ) { error in if case SQLite.Result.error(_, let code, _) = error { XCTAssertEqual(SQLITE_CONSTRAINT, code) } else { XCTFail("expected error") } } XCTAssertEqual(1, db.lastInsertRowid) } func test_changes_returnsNumberOfChanges() { try! InsertUser("alice") XCTAssertEqual(1, db.changes) try! InsertUser("betsy") XCTAssertEqual(1, db.changes) } func test_totalChanges_returnsTotalNumberOfChanges() { XCTAssertEqual(0, db.totalChanges) try! InsertUser("alice") XCTAssertEqual(1, db.totalChanges) try! InsertUser("betsy") XCTAssertEqual(2, db.totalChanges) } func test_prepare_preparesAndReturnsStatements() { _ = try! db.prepare("SELECT * FROM users WHERE admin = 0") _ = try! db.prepare("SELECT * FROM users WHERE admin = ?", 0) _ = try! db.prepare("SELECT * FROM users WHERE admin = ?", [0]) _ = try! db.prepare("SELECT * FROM users WHERE admin = $admin", ["$admin": 0]) } func test_run_preparesRunsAndReturnsStatements() { try! db.run("SELECT * FROM users WHERE admin = 0") try! db.run("SELECT * FROM users WHERE admin = ?", 0) try! db.run("SELECT * FROM users WHERE admin = ?", [0]) try! db.run("SELECT * FROM users WHERE admin = $admin", ["$admin": 0]) AssertSQL("SELECT * FROM users WHERE admin = 0", 4) } func test_scalar_preparesRunsAndReturnsScalarValues() { XCTAssertEqual(0, try! db.scalar("SELECT count(*) FROM users WHERE admin = 0") as? Int64) XCTAssertEqual(0, try! db.scalar("SELECT count(*) FROM users WHERE admin = ?", 0) as? Int64) XCTAssertEqual(0, try! db.scalar("SELECT count(*) FROM users WHERE admin = ?", [0]) as? Int64) XCTAssertEqual(0, try! db.scalar("SELECT count(*) FROM users WHERE admin = $admin", ["$admin": 0]) as? Int64) AssertSQL("SELECT count(*) FROM users WHERE admin = 0", 4) } func test_execute_comment() { try! db.run("-- this is a comment\nSELECT 1") AssertSQL("-- this is a comment", 0) AssertSQL("SELECT 1", 0) } func test_transaction_executesBeginDeferred() { try! db.transaction(.deferred) {} AssertSQL("BEGIN DEFERRED TRANSACTION") } func test_transaction_executesBeginImmediate() { try! db.transaction(.immediate) {} AssertSQL("BEGIN IMMEDIATE TRANSACTION") } func test_transaction_executesBeginExclusive() { try! db.transaction(.exclusive) {} AssertSQL("BEGIN EXCLUSIVE TRANSACTION") } func test_transaction_beginsAndCommitsTransactions() { let stmt = try! db.prepare("INSERT INTO users (email) VALUES (?)", "[email protected]") try! db.transaction { try stmt.run() } AssertSQL("BEGIN DEFERRED TRANSACTION") AssertSQL("INSERT INTO users (email) VALUES ('[email protected]')") AssertSQL("COMMIT TRANSACTION") AssertSQL("ROLLBACK TRANSACTION", 0) } func test_transaction_beginsAndRollsTransactionsBack() { let stmt = try! db.prepare("INSERT INTO users (email) VALUES (?)", "[email protected]") do { try db.transaction { try stmt.run() try stmt.run() } } catch { } AssertSQL("BEGIN DEFERRED TRANSACTION") AssertSQL("INSERT INTO users (email) VALUES ('[email protected]')", 2) AssertSQL("ROLLBACK TRANSACTION") AssertSQL("COMMIT TRANSACTION", 0) } func test_savepoint_beginsAndCommitsSavepoints() { let db = self.db try! db.savepoint("1") { try db.savepoint("2") { try db.run("INSERT INTO users (email) VALUES (?)", "[email protected]") } } AssertSQL("SAVEPOINT '1'") AssertSQL("SAVEPOINT '2'") AssertSQL("INSERT INTO users (email) VALUES ('[email protected]')") AssertSQL("RELEASE SAVEPOINT '2'") AssertSQL("RELEASE SAVEPOINT '1'") AssertSQL("ROLLBACK TO SAVEPOINT '2'", 0) AssertSQL("ROLLBACK TO SAVEPOINT '1'", 0) } func test_savepoint_beginsAndRollsSavepointsBack() { let db = self.db let stmt = try! db.prepare("INSERT INTO users (email) VALUES (?)", "[email protected]") do { try db.savepoint("1") { try db.savepoint("2") { try stmt.run() try stmt.run() try stmt.run() } try db.savepoint("2") { try stmt.run() try stmt.run() try stmt.run() } } } catch { } AssertSQL("SAVEPOINT '1'") AssertSQL("SAVEPOINT '2'") AssertSQL("INSERT INTO users (email) VALUES ('[email protected]')", 2) AssertSQL("ROLLBACK TO SAVEPOINT '2'") AssertSQL("ROLLBACK TO SAVEPOINT '1'") AssertSQL("RELEASE SAVEPOINT '2'", 0) AssertSQL("RELEASE SAVEPOINT '1'", 0) } func test_updateHook_setsUpdateHook_withInsert() { async { done in db.updateHook { operation, db, table, rowid in XCTAssertEqual(Connection.Operation.insert, operation) XCTAssertEqual("main", db) XCTAssertEqual("users", table) XCTAssertEqual(1, rowid) done() } try! InsertUser("alice") } } func test_updateHook_setsUpdateHook_withUpdate() { try! InsertUser("alice") async { done in db.updateHook { operation, db, table, rowid in XCTAssertEqual(Connection.Operation.update, operation) XCTAssertEqual("main", db) XCTAssertEqual("users", table) XCTAssertEqual(1, rowid) done() } try! db.run("UPDATE users SET email = '[email protected]'") } } func test_updateHook_setsUpdateHook_withDelete() { try! InsertUser("alice") async { done in db.updateHook { operation, db, table, rowid in XCTAssertEqual(Connection.Operation.delete, operation) XCTAssertEqual("main", db) XCTAssertEqual("users", table) XCTAssertEqual(1, rowid) done() } try! db.run("DELETE FROM users WHERE id = 1") } } func test_commitHook_setsCommitHook() { async { done in db.commitHook { done() } try! db.transaction { try self.InsertUser("alice") } XCTAssertEqual(1, try! db.scalar("SELECT count(*) FROM users") as? Int64) } } func test_rollbackHook_setsRollbackHook() { async { done in db.rollbackHook(done) do { try db.transaction { try self.InsertUser("alice") try self.InsertUser("alice") // throw } } catch { } XCTAssertEqual(0, try! db.scalar("SELECT count(*) FROM users") as? Int64) } } func test_commitHook_withRollback_rollsBack() { async { done in db.commitHook { throw NSError(domain: "com.stephencelis.SQLiteTests", code: 1, userInfo: nil) } db.rollbackHook(done) do { try db.transaction { try self.InsertUser("alice") } } catch { } XCTAssertEqual(0, try! db.scalar("SELECT count(*) FROM users") as? Int64) } } func test_createFunction_withArrayArguments() { db.createFunction("hello") { $0[0].map { "Hello, \($0)!" } } XCTAssertEqual("Hello, world!", try! db.scalar("SELECT hello('world')") as? String) XCTAssert(try! db.scalar("SELECT hello(NULL)") == nil) } func test_createFunction_createsQuotableFunction() { db.createFunction("hello world") { $0[0].map { "Hello, \($0)!" } } XCTAssertEqual("Hello, world!", try! db.scalar("SELECT \"hello world\"('world')") as? String) XCTAssert(try! db.scalar("SELECT \"hello world\"(NULL)") == nil) } func test_createCollation_createsCollation() { try! db.createCollation("NODIACRITIC") { lhs, rhs in return lhs.compare(rhs, options: .diacriticInsensitive) } XCTAssertEqual(1, try! db.scalar("SELECT ? = ? COLLATE NODIACRITIC", "cafe", "café") as? Int64) } func test_createCollation_createsQuotableCollation() { try! db.createCollation("NO DIACRITIC") { lhs, rhs in return lhs.compare(rhs, options: .diacriticInsensitive) } XCTAssertEqual(1, try! db.scalar("SELECT ? = ? COLLATE \"NO DIACRITIC\"", "cafe", "café") as? Int64) } func test_interrupt_interruptsLongRunningQuery() { try! InsertUsers("abcdefghijklmnopqrstuvwxyz".map { String($0) }) db.createFunction("sleep") { args in usleep(UInt32((args[0] as? Double ?? Double(args[0] as? Int64 ?? 1)) * 1_000_000)) return nil } let stmt = try! db.prepare("SELECT *, sleep(?) FROM users", 0.1) try! stmt.run() let deadline = DispatchTime.now() + Double(Int64(10 * NSEC_PER_MSEC)) / Double(NSEC_PER_SEC) _ = DispatchQueue.global(priority: .background).asyncAfter(deadline: deadline, execute: db.interrupt) AssertThrows(try stmt.run()) } } class ResultTests : XCTestCase { let connection = try! Connection(.inMemory) func test_init_with_ok_code_returns_nil() { XCTAssertNil(Result(errorCode: SQLITE_OK, connection: connection, statement: nil) as Result?) } func test_init_with_row_code_returns_nil() { XCTAssertNil(Result(errorCode: SQLITE_ROW, connection: connection, statement: nil) as Result?) } func test_init_with_done_code_returns_nil() { XCTAssertNil(Result(errorCode: SQLITE_DONE, connection: connection, statement: nil) as Result?) } func test_init_with_other_code_returns_error() { if case .some(.error(let message, let code, let statement)) = Result(errorCode: SQLITE_MISUSE, connection: connection, statement: nil) { XCTAssertEqual("not an error", message) XCTAssertEqual(SQLITE_MISUSE, code) XCTAssertNil(statement) XCTAssert(self.connection === connection) } else { XCTFail() } } func test_description_contains_error_code() { XCTAssertEqual("not an error (code: 21)", Result(errorCode: SQLITE_MISUSE, connection: connection, statement: nil)?.description) } func test_description_contains_statement_and_error_code() { let statement = try! Statement(connection, "SELECT 1") XCTAssertEqual("not an error (SELECT 1) (code: 21)", Result(errorCode: SQLITE_MISUSE, connection: connection, statement: statement)?.description) } }
mpl-2.0
c178fe30b9b2ac4c4f1e2a8532d196df
33.643229
117
0.583703
4.498816
false
true
false
false