repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
chris-wood/reveiller
reveiller/Pods/SwiftCharts/SwiftCharts/Views/ChartPointViewBarGreyOut.swift
14
1338
// // ChartPointViewBarGreyOut.swift // Examples // // Created by ischuetz on 15/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public class ChartPointViewBarGreyOut: ChartPointViewBar { private let greyOut: Bool private let greyOutDelay: Float private let greyOutAnimDuration: Float init(chartPoint: ChartPoint, p1: CGPoint, p2: CGPoint, width: CGFloat, color: UIColor, animDuration: Float = 0.5, greyOut: Bool = false, greyOutDelay: Float = 1, greyOutAnimDuration: Float = 0.5) { self.greyOut = greyOut self.greyOutDelay = greyOutDelay self.greyOutAnimDuration = greyOutAnimDuration super.init(p1: p1, p2: p2, width: width, bgColor: color, animDuration: animDuration) } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func didMoveToSuperview() { super.didMoveToSuperview() if self.greyOut { UIView.animateWithDuration(CFTimeInterval(self.greyOutAnimDuration), delay: CFTimeInterval(self.greyOutDelay), options: UIViewAnimationOptions.CurveEaseOut, animations: {() -> Void in self.backgroundColor = UIColor.grayColor() }, completion: nil) } } }
mit
f8350a746d83d25e2635b5812b1574cc
32.45
201
0.670404
4.344156
false
false
false
false
istx25/lunchtime
Lunchtime/Controller/SetupPageSecondViewController.swift
1
1075
// // SetupPageSecondViewController.swift // Lunchtime // // Created by Willow Bumby on 2015-11-18. // Copyright © 2015 Lighthouse Labs. All rights reserved. // import UIKit import Realm class SetupPageSecondViewController: UIViewController { // MARK: - Outlets @IBOutlet weak var priceLimitSegmentedControl: UISegmentedControl? // MARK: - Controller Lifecycle override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) guard let selectedSegmentIndex = priceLimitSegmentedControl?.selectedSegmentIndex else { return } let realm = RLMRealm.defaultRealm() let user = User() user.priceLimit = selectedSegmentIndex user.identifier = NSNumber(integer: 1) do { realm.beginWriteTransaction() User.createOrUpdateInRealm(realm, withValue: user) try realm.commitWriteTransaction() } catch let error { print("Something went wrong...") print("Error Reference: \(error)") } } }
mit
7c630ded7d562f669fdbfde9ee4112af
25.85
96
0.6527
5.066038
false
false
false
false
natestedman/ArrayLoaderInterface
ArrayLoaderInterface/ArrayLoaderCollectionViewController.swift
1
6216
// ArrayLoaderInterface // Written in 2016 by Nate Stedman <[email protected]> // // To the extent possible under law, the author(s) have dedicated all copyright and // related and neighboring rights to this software to the public domain worldwide. // This software is distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with // this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. import ArrayLoader import LayoutModules import ReactiveCocoa import UIKit // MARK: - Controller /// A controller that integrates a collection view and an array loader. /// /// This is not a view controller class - instead, it should be used as part of view controller classes. public final class ArrayLoaderCollectionViewController <ValueDisplay: ValueDisplayType, ErrorDisplay: ErrorDisplayType, ActivityDisplay, PullDisplay: PullDisplayType, CompletedDisplay where ValueDisplay: UICollectionViewCell, ErrorDisplay: UICollectionViewCell, ActivityDisplay: UICollectionViewCell, PullDisplay: UICollectionViewCell, CompletedDisplay: UICollectionViewCell> { // MARK: - Initialization /** Initializes an array loader collection view controller. - parameter pullItemSize: The size for the pull-to-refresh cell - only one dimension is used at a time, based on the current major layout axis. The default value of this parameter is `(44, 44)`. - parameter activityItemSize: The size for activity cells - only one dimension is used at a time, based on the current major layout axis. The default value of this parameter is `(44, 44)`. - parameter errorItemSize: The row height for error cells - only one dimension is used at a time, based on the current major layout axis. The default value of this parameter is `(44, 44)`. - parameter completedItemSize: The row height for the completed footer cell - only one dimension is used at a time, based on the current major layout axis. The default value of this parameter is `(0, 0)`. - parameter customHeaderView: An optional custom header view, displayed after activity content for the next page. - parameter valuesLayoutModule: The layout module to use for the section displaying the array loader's values. */ public init(pullItemSize: CGSize = CGSize(width: 44, height: 44), activityItemSize: CGSize = CGSize(width: 44, height: 44), errorItemSize: CGSize = CGSize(width: 44, height: 44), completedItemSize: CGSize = CGSize.zero, customHeaderView: UIView? = nil, valuesLayoutModule: LayoutModule) { self.customHeaderView = customHeaderView // create collection view layout self.layout = LayoutModulesCollectionViewLayout(majorAxis: .Vertical, moduleForSection: { section in LayoutModule.moduleForSection( Section(rawValue: section)!, activityItemSize: activityItemSize, errorItemSize: errorItemSize, completedItemSize: completedItemSize, customHeaderView: customHeaderView, valuesLayoutModule: valuesLayoutModule ) }) // create collection view with layout let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) self.collectionView = collectionView collectionView.registerCellClass(CustomHeaderViewCollectionViewCell.self) collectionView.registerCellClass(ValueDisplay) collectionView.registerCellClass(ErrorDisplay) collectionView.registerCellClass(ActivityDisplay) collectionView.registerCellClass(PullDisplay) collectionView.registerCellClass(CompletedDisplay) // create helper object to implement collection view let helper = CollectionViewHelper(parent: self) collectionView.dataSource = helper collectionView.delegate = helper self.helper = helper // watch state and reload collection view arrayLoader.producer .flatMap(.Latest, transform: { arrayLoader in arrayLoader.state.producer }) .skip(1) .observeOn(UIScheduler()) .startWithNext({ _ in if collectionView.window != nil // only reload once the collection view is in a window { collectionView.reloadData() } }) } // MARK: - Collection View /// The collection view managed by the controller. public let collectionView: UICollectionView /// The helper object for this controller. private var helper: CollectionViewHelper <ValueDisplay, ErrorDisplay, ActivityDisplay, PullDisplay, CompletedDisplay>? /// The collection view layout. private let layout: LayoutModulesCollectionViewLayout /// The current major axis for the collection view layout. public var majorAxis: Axis { get { return layout.majorAxis } set { layout.majorAxis = newValue } } // MARK: - Array Loader /// The array loader being used by the controller. public let arrayLoader = MutableProperty(AnyArrayLoader(StaticArrayLoader<ValueDisplay.Value>.empty .promoteErrors(ErrorDisplay.Error.self)) ) // MARK: - Custom Header View /// If provided, this view will be visible below the previous page content. let customHeaderView: UIView? // MARK: - State /// Whether or not the interface should allow loading the previous page - a client might want to limit this by /// only allowing the previous page to load if the first page has already loaded. public let allowLoadingPreviousPage = MutableProperty(false) // MARK: - Callbacks /// A callback sent when the user selects a value from the collection view. public var didSelectValue: (ValueDisplay.Value -> ())? }
cc0-1.0
376f3fc2914c03a0431b3e2f06cc321f
42.166667
120
0.672458
5.414634
false
false
false
false
QuarkWorks/RealmModelGenerator
RealmModelGenerator/RelationshipsVC.swift
1
8547
// // RelationshipsVC.swift // RealmModelGenerator // // Created by Zhaolong Zhong on 3/31/16. // Copyright © 2016 QuarkWorks. All rights reserved. // import Cocoa protocol RelationshipsVCDelegate: AnyObject { func relationshipsVC(relationshipsVC: RelationshipsVC, selectedRelationshipDidChange relationship:Relationship?) } class RelationshipsVC: NSViewController, RelationshipsViewDelegate, RelationshipsViewDataSource, Observer { static let TAG = NSStringFromClass(RelationshipsVC.self) private var entityNameList:[String] = ["None"] @IBOutlet weak var relationshipsView: RelationshipsView! { didSet { self.relationshipsView.delegate = self self.relationshipsView.dataSource = self } } weak var selectedEntity: Entity? { didSet { if oldValue === self.selectedEntity { return } oldValue?.observable.removeObserver(observer: self) self.selectedEntity?.observable.addObserver(observer: self) selectedRelationship = nil self.invalidateViews() } } private weak var selectedRelationship: Relationship? { didSet { if oldValue === self.selectedRelationship { return } invalidateSelectedIndex() self.delegate?.relationshipsVC(relationshipsVC: self, selectedRelationshipDidChange: self.selectedRelationship) } } private var ascending:Bool = true { didSet{ self.invalidateViews() } } private var isSortByDestination = false { didSet{ self.invalidateViews() } } private var isSortedByColumnHeader = false weak var delegate: RelationshipsVCDelegate? // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() } func onChange(observable: Observable) { self.invalidateViews() } func invalidateViews() { if !self.isViewLoaded { return } updateDestinationList() if isSortedByColumnHeader { sortRelationships() } self.relationshipsView.reloadData() invalidateSelectedIndex() } func invalidateSelectedIndex() { self.relationshipsView.selectedIndex = self.selectedEntity?.relationships.index(where: {$0 === self.selectedRelationship}) } // MARK: - Update selected relationship after its detail changed func updateSelectedRelationship(selectedRelationship: Relationship) { self.selectedRelationship = selectedRelationship invalidateViews() } func updateDestinationList() { self.entityNameList = ["None"] self.selectedEntity?.model.entities.forEach{(e) in entityNameList.append(e.name)} self.relationshipsView.destinationNames = entityNameList } func sortRelationships() { guard let selectedEntity = self.selectedEntity else { return } if ascending { if isSortByDestination { selectedEntity.relationships.sort{ (e1, e2) -> Bool in if let destination1 = e1.destination, let destination2 = e2.destination { return destination1.name < destination2.name } else if let destination1 = e1.destination { return destination1.name < entityNameList[0] } else if let destination2 = e2.destination { return entityNameList[0] < destination2.name } else { return true } } } else { selectedEntity.relationships.sort{ (e1, e2) -> Bool in return e1.name < e2.name } } } else { if isSortByDestination { selectedEntity.relationships.sort{ (e1, e2) -> Bool in if let destination1 = e1.destination, let destination2 = e2.destination { return destination1.name > destination2.name } else if let destination1 = e1.destination { return destination1.name > entityNameList[0] } else if let destination2 = e2.destination { return entityNameList[0] > destination2.name } else { return true } } } else { selectedEntity.relationships.sort{ (e1, e2) -> Bool in return e1.name > e2.name } } } } // MARK: - RelationshipsViewDataSource func numberOfRowsInRelationshipsView(relationshipsView: RelationshipsView) -> Int { return self.selectedEntity == nil ? 0 : self.selectedEntity!.relationships.count } func relationshipsView(relationshipsView: RelationshipsView, titleForRelationshipAtIndex index: Int) -> String { return self.selectedEntity!.relationships[index].name } func relationshipsView(relationshipsView: RelationshipsView, destinationForRelationshipAtIndex index: Int) -> String { if let destination = self.selectedEntity?.relationships[index].destination { return destination.name } else { return entityNameList[0] } } //MARK: - RelationshipsViewDelegate func addRelationshipInRelationshipsView(relationshipsView: RelationshipsView) { if self.selectedEntity != nil { let relationship = self.selectedEntity!.createRelationship() self.selectedRelationship = relationship } } func relationshipsView(relationshipsView: RelationshipsView, removeRelationshipAtIndex index: Int) { let relationship = self.selectedEntity!.relationships[index] if relationship === self.selectedRelationship { if let c = self.selectedEntity?.relationships.count, c <= 1 { self.selectedRelationship = nil } else if index == self.selectedEntity!.relationships.count - 1 { self.selectedRelationship = self.selectedEntity?.relationships[index - 1] } else { self.selectedRelationship = self.selectedEntity?.relationships[index + 1] } } self.selectedEntity!.removeRelationship(relationship: relationship) } func relationshipsView(relationshipsView: RelationshipsView, selectedIndexDidChange index: Int?) { self.selectedRelationship = index == nil ? nil : self.selectedEntity?.relationships[index!] } func relationshipsView(relationshipsView: RelationshipsView, shouldChangeRelationshipName name: String, atIndex index: Int) -> Bool { let relationship = selectedEntity!.relationships[index] do { try relationship.setName(name: name) } catch { Tools.popupAlert(messageText: "Error", buttonTitle: "OK", informativeText: "Unable to rename relationship: \(relationship.name) to: \(name). There is a relationship with the same name.") return false } return true } func relationshipsView(relationshipsView: RelationshipsView, atIndex index: Int, changeDestination destinationName: String) { let destination = selectedEntity?.model.entities.filter({$0.name == destinationName}).first self.selectedEntity?.relationships[index].destination = destination } func relationshipsView(relationshipsView: RelationshipsView, sortByColumnName name: String, ascending: Bool) { self.isSortedByColumnHeader = true self.ascending = ascending self.isSortByDestination = name == RelationshipsView.DESTINATION_COLUMN ? true : false } func relationshipsView(relationshipsView: RelationshipsView, dragFromIndex: Int, dropToIndex: Int) { guard let selectedEntity = self.selectedEntity else { return } self.isSortedByColumnHeader = false let draggedAttribute = selectedEntity.relationships[dragFromIndex] selectedEntity.relationships.remove(at: dragFromIndex) if dropToIndex >= selectedEntity.relationships.count { selectedEntity.relationships.insert(draggedAttribute, at: dropToIndex - 1) } else { selectedEntity.relationships.insert(draggedAttribute, at: dropToIndex) } invalidateViews() } }
mit
28c0249010893827733166f16483b298
37.845455
198
0.628949
5.457216
false
false
false
false
guillermo-ag-95/App-Development-with-Swift-for-Students
1 - Getting Started/2 - Constants, Variables, and Data Types/lab/Lab - Constants and Variables.playground/Pages/7. Exercise - Types and Type Safety.xcplaygroundpage/Contents.swift
1
1490
/*: ## Exercise - Types and Type Safety Declare two variables, one called `firstDecimal` and one called `secondDecimal`. Both should have decimal values. Look at both of their types by holding Option and clicking on the variable name. */ var firstDecimal = 15.2 var secondDecimal = 6.3 /*: Declare a variable called `trueOrFalse` and give it a boolean value. Try to assign it to `firstDecimal` like so: `firstDecimal = trueOrFalse`. Does it compile? Print a statement to the console explaining why not, and remove the line of code that will not compile. */ var trueOrFalse = true // firstDecimal = trueOrFalse print("You cannot assign a boolean to a double object.") /*: Declare a variable and give it a string value. Then try to assign it to `firstDecimal`. Does it compile? Print a statement to the console explaining why not, and remove the line of code that will not compile. */ var string = "This is a string." // firstDecimal = string print("You cannot assign a string to a double object.") /*: Finally, declare a variable with a whole number value. Then try to assign it to `firstDecimal`. Why won't this compile even though both variables are numbers? Print a statement to the console explaining why not, and remove the line of code that will not compile. */ var wholeNumber = 10 // wholeNumber = firstDecimal print("You cannot assign a double to an integer object.") //: [Previous](@previous) | page 7 of 10 | [Next: App Exercise - Tracking Different Types](@next)
mit
0508f03c10cbcca848a17ccc1db9cbd2
54.185185
264
0.747651
4.185393
false
false
false
false
cuappdev/tcat-ios
TCAT/Utilities/SearchTableViewHelpers.swift
1
3280
// // SearchTableViewHelpers.swift // TCAT // // Created by Austin Astorga on 5/8/17. // Copyright © 2017 cuappdev. All rights reserved. // import Foundation import DZNEmptyDataSet let encoder = JSONEncoder() let decoder = JSONDecoder() class Global { static let shared = Global() func retrievePlaces(for key: String) -> [Place] { if key == Constants.UserDefaults.favorites { if let storedPlaces = sharedUserDefaults?.value(forKey: key) as? Data, let favorites = try? decoder.decode([Place].self, from: storedPlaces) { return favorites } } else if let storedPlaces = userDefaults.value(forKey: key) as? Data, let places = try? decoder.decode([Place].self, from: storedPlaces) { return places } return [Place]() } /// Returns the rest so we don't have to re-unarchive it func deleteFavorite(favorite: Place, allFavorites: [Place]) -> [Place] { let newFavoritesList = allFavorites.filter { favorite != $0 } do { let data = try encoder.encode(newFavoritesList) sharedUserDefaults?.set(data, forKey: Constants.UserDefaults.favorites) AppShortcuts.shared.updateShortcutItems() } catch let error { print(error) } return newFavoritesList } /// Returns the rest so we don't have to re-unarchive it func deleteRecent(recent: Place, allRecents: [Place]) -> [Place] { let newRecentsList = allRecents.filter { recent != $0 } do { let data = try encoder.encode(newRecentsList) userDefaults.set(data, forKey: Constants.UserDefaults.recentSearch) } catch let error { print(error) } return newRecentsList } /// Clears recent searches func deleteAllRecents() { let newRecents = [Place]() do { let data = try encoder.encode(newRecents) userDefaults.set(data, forKey: Constants.UserDefaults.recentSearch) } catch let error { print(error) } } /// Possible Keys: Constants.UserDefaults (.recentSearch | .favorites) func insertPlace(for key: String, place: Place, bottom: Bool = false) { // Could replace with an enum let limit = key == Constants.UserDefaults.favorites ? 5 : 8 // Ensure duplicates aren't added var places = retrievePlaces(for: key).filter { (savedPlace) -> Bool in return savedPlace != place } places = bottom ? places + [place] : [place] + places if places.count > limit { places.remove(at: places.count - 1) } do { let data = try encoder.encode(places) if key == Constants.UserDefaults.favorites { sharedUserDefaults?.set(data, forKey: key) } else { userDefaults.set(data, forKey: key) } AppShortcuts.shared.updateShortcutItems() } catch let error { print(error) } if key == Constants.UserDefaults.favorites { let payload = FavoriteAddedPayload(name: place.name) Analytics.shared.log(payload) } } }
mit
66a736e8d9c4f4f403b648e805f1d36a
30.228571
87
0.590119
4.522759
false
false
false
false
jordanekay/Mensa
Mensa/Sources/View/Hosting/HostingView.swift
1
2311
// // Hosting.swift // Mensa // // Created by Jordan Kay on 4/10/19. // Copyright © 2019 CultivR. All rights reserved. // protocol HostingView: UIView { var contentView: UIView { get } var viewController: UIViewController! { get set } func addSizeConstraints(toHostedView hostedView: UIView) } // MARK: - extension HostingView { func hostContent(of type: NibLoadable.Type, from viewController: UIViewController, with variant: Variant) { let hostedView = type.hostedView(of: variant) hostedView.backgroundColor = .clear hostedView.frame.size.width = contentView.bounds.width viewController.view = hostedView viewController.viewDidLoad() self.viewController = viewController contentView.addSubview(hostedView) addEdgeConstraints(toHostedView: hostedView) } } // MARK: - private extension HostingView { func addEdgeConstraints(toHostedView hostedView: UIView) { for attribute: NSLayoutConstraint.Attribute in [.top, .left, .bottom, .right] { let constraint = NSLayoutConstraint(item: contentView, attribute: attribute, relatedBy: .equal, toItem: hostedView, attribute: attribute, multiplier: 1, constant: 0) if attribute == .bottom { constraint.priority -= 1 } contentView.addConstraint(constraint) } } func addPinConstraints(withWidth width: CGFloat, toHostedView hostedView: UIView) { let widthConstraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: width) let heightConstraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1, constant: bounds.height) addConstraint(widthConstraint) addConstraint(heightConstraint) for attribute: NSLayoutConstraint.Attribute in [.top, .bottom,] { let constraint = NSLayoutConstraint(item: contentView, attribute: attribute, relatedBy: .equal, toItem: hostedView, attribute: attribute, multiplier: 1, constant: 0) if attribute == .bottom { constraint.priority -= 1 } contentView.addConstraint(constraint) } } }
bsd-2-clause
0f5e94b55ab4770bab6f848ac9cf0af9
39.526316
177
0.678355
4.676113
false
false
false
false
kasei/kineo
Sources/Kineo/QuadStore/DiomedeQuadStore.swift
1
5720
// // DiomedeQuadStore.swift // Kineo // // Created by Gregory Todd Williams on 5/26/20. // import Foundation import SPARQLSyntax import DiomedeQuadStore extension DiomedeQuadStore: MutableQuadStoreProtocol {} extension DiomedeQuadStore: LazyMaterializingQuadStore {} extension DiomedeQuadStore: PlanningQuadStore { private func characteristicSetSatisfiableCardinality(_ algebra: Algebra, activeGraph: Term, dataset: DatasetProtocol, distinctStarSubject: Node? = nil) throws -> Int? { if case let .bgp(tps) = algebra, tps.allSatisfy({ (tp) in !tp.subject.isBound && !tp.object.isBound }) { let csDataset = try self.characteristicSets(for: activeGraph) let objectVariables = tps.compactMap { (tp) -> String? in if case .variable(let v, _) = tp.object { return v } else { return nil } } let objects = Set(objectVariables) // if these don't match, then there's at least one object variable that is used twice, meaning it's not a simple star guard objects.count == objectVariables.count else { return nil } if let v = distinctStarSubject { if !tps.allSatisfy({ (tp) in tp.subject == v }) { return nil } else { let acs = try csDataset.aggregatedCharacteristicSet(matching: tps, in: activeGraph, store: self) return acs.count } } else { if let card = try? csDataset.starCardinality(matching: tps, in: activeGraph, store: self) { return Int(card) } } } else if case let .triple(tp) = algebra, !tp.subject.isBound, !tp.object.isBound { return try characteristicSetSatisfiableCardinality(.bgp([tp]), activeGraph: activeGraph, dataset: dataset, distinctStarSubject: distinctStarSubject) } else if case let .namedGraph(child, .bound(g)) = algebra { guard dataset.namedGraphs.contains(g) else { return 0 } return try characteristicSetSatisfiableCardinality(child, activeGraph: g, dataset: dataset, distinctStarSubject: distinctStarSubject) } return nil } /// If `algebra` represents a COUNT(*) aggregation with no grouping, and the graph pattern being aggregated is a simple star /// (one subject variable, and all objects are non-shared variables), then compute the count statically using the database's /// Characteristic Sets, and return Table (static data) query plan. private func characteristicSetSatisfiableCountPlan(_ algebra: Algebra, activeGraph: Term, dataset: DatasetProtocol) throws -> QueryPlan? { // COUNT(*) with no GROUP BY over a triple pattern with unbound subject and object if case let .aggregate(child, [], aggs) = algebra { if aggs.count == 1, let a = aggs.first { let agg = a.aggregation switch agg { case .countAll: if let card = try characteristicSetSatisfiableCardinality(child, activeGraph: activeGraph, dataset: dataset) { let qp = TablePlan(columns: [.variable(a.variableName, binding: true)], rows: [[Term(integer: Int(card))]], metricsToken: QueryPlanEvaluationMetrics.silentToken) return qp } case .count(_, false): // COUNT(?v) can be answered by Characteristic Sets if let card = try characteristicSetSatisfiableCardinality(child, activeGraph: activeGraph, dataset: dataset) { let qp = TablePlan(columns: [.variable(a.variableName, binding: true)], rows: [[Term(integer: Int(card))]], metricsToken: QueryPlanEvaluationMetrics.silentToken) return qp } case let .count(.node(v), true): // COUNT(DISTINCT ?v) can be answered by Characteristic Sets only if ?v is the CS star subject if let card = try characteristicSetSatisfiableCardinality(child, activeGraph: activeGraph, dataset: dataset, distinctStarSubject: v) { let qp = TablePlan(columns: [.variable(a.variableName, binding: true)], rows: [[Term(integer: Int(card))]], metricsToken: QueryPlanEvaluationMetrics.silentToken) return qp } default: return nil } } } return nil } /// Returns a QueryPlan object for any algebra that can be efficiently executed by the QuadStore, nil for all others. public func plan(algebra: Algebra, activeGraph: Term, dataset: DatasetProtocol, metrics: QueryPlanEvaluationMetrics) throws -> QueryPlan? { if self.characteristicSetsAreAccurate { // Characteristic Sets are "accurate" is they were computed at or after the moment // when the last quad was inserted or deleted. if let qp = try self.characteristicSetSatisfiableCountPlan(algebra, activeGraph: activeGraph, dataset: dataset) { return qp } } switch algebra { // case .triple(let t): // return try plan(bgp: [t], activeGraph: activeGraph) // case .bgp(let triples): // return try plan(bgp: triples, activeGraph: activeGraph) default: return nil } } } extension DiomedeQuadStore: PrefixNameStoringQuadStore { public var prefixes: [String : Term] { do { return try self.prefixes() } catch { return [:] } } }
mit
177a777f36c5a1d821212269dfd35fc3
51.962963
185
0.610664
4.620355
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/ViewControllers/RecoveryKey/WriteRecoveryKeyViewController.swift
1
23935
// // WriteRecoveryKeyViewController.swift // breadwallet // // Created by Ray Vander Veen on 2019-03-22. // Copyright © 2019 Breadwinner AG. All rights reserved. // import UIKit typealias WriteRecoveryKeyExitHandler = ((ExitRecoveryKeyAction) -> Void) class WriteRecoveryKeyViewController: BaseRecoveryKeyViewController { enum ScrollDirection: Int { case none case forward case backward } let pageCount = 12 private let interactionPagingViewTag = 1 private let wordPagingViewTag = 2 let pagingCellReuseId = "pagingCell" let wordCellReuseId = "wordCell" let blankCellReuseId = "blankCell" private let keyMaster: KeyMaster private let pin: String private var words: [String] { guard let phraseString = self.keyMaster.seedPhrase(pin: self.pin) else { return [] } return phraseString.components(separatedBy: " ") } private let stepLabelTopMargin: CGFloat = E.isSmallScreen ? 36 : 24 private let headingTopMargin: CGFloat = 28 private let headingLeftRightMargin: CGFloat = 50 private let subheadingLeftRightMargin: CGFloat = 70 var interactionPagingView: UICollectionView? var wordPagingView: WordPagingCollectionView? private let headingLabel = UILabel() private let subheadingLabel = UILabel() private let stepLabel = UILabel() private let doneButton = BRDButton(title: S.Button.doneAction, type: .primary) private let infoView = InfoView() var pageIndex: Int = 0 { didSet { updateStepLabel() updateInfoView() enableDoneButton(pageIndex == (pageCount - 1)) } } var scrollOffset: CGFloat = 0 { didSet { pageIndex = Int(scrollOffset / scrollablePageWidth) let partialPage = scrollOffset - (CGFloat(pageIndex) * scrollablePageWidth) pageScrollingPercent = partialPage / scrollablePageWidth } } var pageScrollingPercent: CGFloat = 0 { didSet { updateWordCellAppearances(pageScrollPercent: pageScrollingPercent) } } var lastScrollOffset: CGFloat = 0 var scrollDirection: ScrollDirection = .none var scrollablePageWidth: CGFloat { return UIScreen.main.bounds.width } var wordPageWidth: CGFloat { // The word pages are offset at half a page width so that the center of the next // label is chopped in half by the right side of the display. return (scrollablePageWidth / 2) } var totalScrollableWidth: CGFloat { // Subtract one page width from the scrollable width because when the screen // is first displayed, we can see the first page of content. return scrollablePageWidth * CGFloat(pageCount - 1) } private var pagingViewContainer: UIView = UIView() private var mode: EnterRecoveryKeyMode = .generateKey private var dismissAction: (() -> Void)? private var exitCallback: WriteRecoveryKeyExitHandler? private var shouldShowDoneButton: Bool { return mode != .writeKey } private var wordPagingViewSavedContentOffset: CGPoint? private var notificationObservers = [String: NSObjectProtocol]() // MARK: initialization init(keyMaster: KeyMaster, pin: String, mode: EnterRecoveryKeyMode, eventContext: EventContext, dismissAction: (() -> Void)?, exitCallback: WriteRecoveryKeyExitHandler?) { self.keyMaster = keyMaster self.pin = pin self.mode = mode self.dismissAction = dismissAction self.exitCallback = exitCallback super.init(eventContext, .writePaperKey) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { notificationObservers.values.forEach { observer in NotificationCenter.default.removeObserver(observer) } } // MARK: exit handling private func exit() { // If the user exits from write-key-again mode, there's no need to prompt, so guard that we're in // generate-key mode. guard mode == .generateKey else { exitCallback?(.abort) return } RecoveryKeyFlowController.promptToSetUpRecoveryKeyLater(from: self) { [unowned self] (userWantsToSetUpLater) in if userWantsToSetUpLater { // Track the dismissed event before invoking the dismiss action or we could be // deinit'd before the event is logged. let metaData = [ "step": String(self.pageIndex + 1) ] self.trackEvent(event: .dismissed, metaData: metaData, tracked: { self.exitWithoutPrompting() }) } } } private func exitWithoutPrompting() { if let dismissAction = self.dismissAction { dismissAction() } else if let exitCallback = self.exitCallback { exitCallback(.abort) } else if let navController = self.navigationController { navController.popViewController(animated: true) } } override var closeButtonStyle: BaseRecoveryKeyViewController.CloseButtonStyle { return eventContext == .onboarding ? .skip : .close } // MARK: lifecycle override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = Theme.primaryBackground view.clipsToBounds = true showBackButton() setUpPagingViews() setUpLabels() addSubviews() setUpConstraints() showCloseButton() updateStepLabel() updateInfoView() enableDoneButton(false) doneButton.isHidden = !shouldShowDoneButton doneButton.tap = { [unowned self] in if let exit = self.exitCallback { switch self.mode { // If the user is generating the key for the first time, exit and move to the confirm key flow. case .generateKey: exit(.confirmKey) // If the user is just writing the key down again, we're just aborting the process. case .writeKey: exit(.abort) case .unlinkWallet: exit(.unlinkWallet) } } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateWordCellAppearances(pageScrollPercent: 0) wordPagingView?.willAppear() listenForBackgroundNotification() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) wordPagingView?.willDisappear() unsubscribeNotifications() } override func onCloseButton() { exit() } private func enableDoneButton(_ enable: Bool) { // If the user is in write-key-again mode, always enable the Done button because the // the flow can be exited at any time. if mode == .writeKey { doneButton.isEnabled = true } else { doneButton.isEnabled = enable } } private func listenForBackgroundNotification() { notificationObservers[UIApplication.willResignActiveNotification.rawValue] = NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: nil) { [weak self] _ in self?.exitWithoutPrompting() } } private func unsubscribeNotifications() { notificationObservers.values.forEach { NotificationCenter.default.removeObserver($0) } } private func setUpLabels() { headingLabel.textColor = Theme.primaryText headingLabel.font = Theme.h2Title headingLabel.text = S.RecoverKeyFlow.writeKeyScreenTitle headingLabel.textAlignment = .center headingLabel.numberOfLines = 0 subheadingLabel.textColor = Theme.secondaryText subheadingLabel.font = Theme.body1 subheadingLabel.text = S.RecoverKeyFlow.writeKeyScreenSubtitle subheadingLabel.textAlignment = .center subheadingLabel.numberOfLines = 0 stepLabel.textColor = Theme.tertiaryText stepLabel.font = Theme.caption stepLabel.textAlignment = .center } private func setUpPagingViews() { // // create and add the word paging view first; the interaction paging view // will be above the word paging view so that the user can swipe the paging // view and we can scroll the word view proportionally // let wordPagingLayout = UICollectionViewFlowLayout() wordPagingLayout.sectionInset = .zero wordPagingLayout.minimumInteritemSpacing = 0 wordPagingLayout.minimumLineSpacing = 0 wordPagingLayout.scrollDirection = .horizontal let wordPaging = WordPagingCollectionView(frame: .zero, collectionViewLayout: wordPagingLayout) wordPaging.backgroundColor = Theme.primaryBackground wordPaging.delegate = self wordPaging.dataSource = self wordPaging.isScrollEnabled = true wordPaging.register(RecoveryWordCell.self, forCellWithReuseIdentifier: wordCellReuseId) wordPaging.register(UICollectionViewCell.self, forCellWithReuseIdentifier: blankCellReuseId) pagingViewContainer.addSubview(wordPaging) wordPaging.constrain([ wordPaging.leftAnchor.constraint(equalTo: pagingViewContainer.leftAnchor, constant: -(wordPageWidth / 2)), wordPaging.rightAnchor.constraint(equalTo: pagingViewContainer.rightAnchor, constant: wordPageWidth / 2), wordPaging.topAnchor.constraint(equalTo: pagingViewContainer.topAnchor), wordPaging.bottomAnchor.constraint(equalTo: pagingViewContainer.bottomAnchor) ]) // // create and add the interaction paging view above the word paging view // let layout = UICollectionViewFlowLayout() layout.sectionInset = .zero layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 layout.scrollDirection = .horizontal let paging = UICollectionView(frame: .zero, collectionViewLayout: layout) paging.collectionViewLayout = layout paging.isPagingEnabled = true paging.isUserInteractionEnabled = true paging.delegate = self paging.dataSource = self let scrollView = paging as UIScrollView scrollView.delegate = self paging.register(UICollectionViewCell.self, forCellWithReuseIdentifier: pagingCellReuseId) pagingViewContainer.addSubview(paging) paging.constrain(toSuperviewEdges: .zero) interactionPagingView = paging wordPagingView = wordPaging paging.backgroundColor = .clear pagingViewContainer.backgroundColor = .clear paging.tag = interactionPagingViewTag wordPaging.tag = wordPagingViewTag } private func addSubviews() { view.addSubview(pagingViewContainer) view.addSubview(headingLabel) view.addSubview(subheadingLabel) view.addSubview(stepLabel) view.addSubview(infoView) view.addSubview(doneButton) } private func setUpConstraints() { pagingViewContainer.constrain([ pagingViewContainer.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor), pagingViewContainer.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor), pagingViewContainer.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), pagingViewContainer.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) ]) headingLabel.constrain([ headingLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor), headingLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: headingLeftRightMargin), headingLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -headingLeftRightMargin), headingLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: headingTopMargin) ]) subheadingLabel.constrain([ subheadingLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor), subheadingLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: headingLeftRightMargin), subheadingLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -headingLeftRightMargin), subheadingLabel.topAnchor.constraint(equalTo: headingLabel.bottomAnchor, constant: C.padding[2]) ]) stepLabel.constrain([ stepLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor), stepLabel.topAnchor.constraint(equalTo: view.centerYAnchor, constant: stepLabelTopMargin) ]) constrainContinueButton(doneButton) // The info view sits just above the Done button. infoView.constrain([ infoView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: C.padding[2]), infoView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor, constant: -C.padding[2]), infoView.bottomAnchor.constraint(equalTo: doneButton.topAnchor, constant: -C.padding[2]) ]) } private func updateStepLabel() { // this will generate a string such as "2 of 12" stepLabel.text = String(format: S.RecoverKeyFlow.writeKeyStepTitle, String(pageIndex + 1), String(pageCount)) } private func updateInfoView() { infoView.text = (pageIndex == 0) ? S.RecoverKeyFlow.noScreenshotsOrEmailReminder : S.RecoverKeyFlow.rememberToWriteDownReminder infoView.imageName = (pageIndex == 0) ? "ExclamationMarkCircle" : "Document" } private func updateWordCellAppearances(pageScrollPercent: CGFloat) { if let cells = wordPagingView?.visibleCells { for cell in cells { if let wordCell = cell as? RecoveryWordCell { wordCell.update(pagingPercent: pageScrollingPercent, currentPageIndex: pageIndex, scrollDirection: scrollDirection) } } } } } extension WriteRecoveryKeyViewController { func updateScrollDirection(_ offset: CGFloat) { if offset > lastScrollOffset { scrollDirection = .forward } else if offset < lastScrollOffset { scrollDirection = .backward } else { scrollDirection = .none } lastScrollOffset = offset } func scrollViewDidScroll(_ scrollView: UIScrollView) { // Ignore scrolling by the word paging scrollview, because below we programmtically // scroll it. guard scrollView == interactionPagingView else { return } let xOffset = scrollView.contentOffset.x updateScrollDirection(xOffset) // Calculate the percent scrolled in the interaction paging collection view that // sits above the word paging collection view, and update the latter's content offset // by the same percent. let scrollPercent = (xOffset / totalScrollableWidth) let pagingScrollableWidth = (totalScrollableWidth / 2) let wordPagingOffset = (scrollPercent * pagingScrollableWidth) wordPagingView?.setContentOffset(CGPoint(x: wordPagingOffset, y: 0), animated: false) self.scrollOffset = xOffset } func trackEvent(event: Event, tracked: @escaping () -> Void) { if event == .dismissed { if mode == .generateKey { let metaData = [ "step": String(pageIndex + 1) ] saveEvent(context: eventContext, screen: .writePaperKey, event: event, attributes: metaData, callback: { _ in tracked() }) } } else { saveEvent(context: eventContext, screen: .writePaperKey, event: event, callback: { _ in tracked() }) } } } extension WriteRecoveryKeyViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { func wordCellAtIndex(_ index: Int) -> RecoveryWordCell? { if index >= 0 && index < pageCount { if let cell = wordPagingView?.cellForItem(at: IndexPath(item: index, section: 0)) as? RecoveryWordCell { return cell } } return nil } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (collectionView == wordPagingView) ? 13 : 12 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { switch collectionView.tag { case interactionPagingViewTag: let cell = collectionView.dequeueReusableCell(withReuseIdentifier: pagingCellReuseId, for: indexPath) return cell case wordPagingViewTag: // starts with a blank cell so that the first word cell can scroll off to the left, leaving // it 50% visible if indexPath.item == 0 { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: blankCellReuseId, for: indexPath) return cell } else { let index = indexPath.item - 1 // account for blank cell above let word = words[index] let reuseId = wordCellReuseId if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseId, for: indexPath) as? RecoveryWordCell { cell.configure(with: word, index: index) cell.update(pagingPercent: pageScrollingPercent, currentPageIndex: pageIndex, scrollDirection: scrollDirection) return cell } } default: break } return UICollectionViewCell() } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { var width = scrollablePageWidth let height = collectionView.frame.height if collectionView == wordPagingView { width *= 0.5 } return CGSize(width: width, height: height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return .zero } } // // A cell in the word paging collection view. It displays a // class RecoveryWordCell: UICollectionViewCell { private let wordLabel = UILabel() private let wordTopConstraintPercent: CGFloat = 0.4 let normalScale: CGFloat = 1.0 let offScreenScale: CGFloat = 0.6 let scaleRange: CGFloat = 0.4 let smallScreenWordFont = UIFont(name: "CircularPro-Book", size: 32.0) var index: Int = 0 override init(frame: CGRect) { super.init(frame: frame) setUp() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setUp() { wordLabel.textColor = Theme.primaryText wordLabel.font = E.isIPhone6OrSmaller ? smallScreenWordFont : Theme.h0Title wordLabel.textAlignment = .center wordLabel.adjustsFontSizeToFitWidth = true contentView.addSubview(wordLabel) let wordTopConstraintConstant = (contentView.frame.height * wordTopConstraintPercent) wordLabel.constrain([ wordLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: wordTopConstraintConstant), wordLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: C.padding[1]), wordLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -C.padding[1]) ]) wordLabel.alpha = offScreenScale } func configure(with word: String, index: Int) { wordLabel.text = word self.index = index } // Adjusts the opacity and scale of the word label up or down to achieve fade-in/fade-out effects // as the user pages through the words. func update(pagingPercent: CGFloat, currentPageIndex: Int, scrollDirection: WriteRecoveryKeyViewController.ScrollDirection) { var scale = offScreenScale let delta = (scrollDirection == .forward) ? (pagingPercent * scaleRange) : ((1.0 - pagingPercent) * scaleRange) if pagingPercent > 0 { if scrollDirection == .forward { // next page, fading in from the right if index == (currentPageIndex + 1) { scale = offScreenScale + delta // current page fading out to the left } else if index == currentPageIndex { scale = normalScale - delta } } else if scrollDirection == .backward { // previous page, fading in from the left if index == currentPageIndex { scale = offScreenScale + delta // current page fading out to the right } else if index == (currentPageIndex + 1) { scale = normalScale - delta } } } else { scale = (index == currentPageIndex) ? normalScale : offScreenScale } wordLabel.alpha = scale wordLabel.transform = CGAffineTransform(scaleX: scale, y: scale) } } // Subclass of UICollectionView to get around a bug where the content offset is // bumped back half a page when a new view controller is pushed onto the stack. // // The problem is solved by intercepting attempts to modify the content offset // once the new view controller has been pushed, using the 'obscured' property. class WordPagingCollectionView: UICollectionView { var obscured: Bool = false { didSet { guard obscured else { savedContentOffset = nil return } savedContentOffset = contentOffset } } var savedContentOffset: CGPoint? override var contentOffset: CGPoint { set { guard obscured else { super.contentOffset = newValue return } super.contentOffset = savedContentOffset ?? newValue } get { guard obscured else { return super.contentOffset } return savedContentOffset ?? super.contentOffset } } func willDisappear() { obscured = true } func willAppear() { obscured = false } }
mit
ee9555e866c35e83cb4516ce5e103748
35.263636
147
0.625094
5.479396
false
false
false
false
hooman/swift
test/Concurrency/Runtime/async_taskgroup_cancel_then_completions.swift
2
2673
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library) | %FileCheck %s --dump-input always // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch // rdar://76038845 // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime import Dispatch @available(SwiftStdlib 5.5, *) func asyncEcho(_ value: Int) async -> Int { value } // FIXME: this is a workaround since (A, B) today isn't inferred to be Sendable // and causes an error, but should be a warning (this year at least) @available(SwiftStdlib 5.5, *) struct SendableTuple2<A: Sendable, B: Sendable>: Sendable { let first: A let second: B init(_ first: A, _ second: B) { self.first = first self.second = second } } @available(SwiftStdlib 5.5, *) func test_taskGroup_cancel_then_completions() async { // CHECK: test_taskGroup_cancel_then_completions print("before \(#function)") let result: Int = await withTaskGroup(of: SendableTuple2<Int, Bool>.self) { group in print("group cancelled: \(group.isCancelled)") // CHECK: group cancelled: false let spawnedFirst = group.spawnUnlessCancelled { print("start first") await Task.sleep(1_000_000_000) print("done first") return SendableTuple2(1, Task.isCancelled) } print("spawned first: \(spawnedFirst)") // CHECK: spawned first: true assert(spawnedFirst) let spawnedSecond = group.spawnUnlessCancelled { print("start second") await Task.sleep(3_000_000_000) print("done second") return SendableTuple2(2, Task.isCancelled) } print("spawned second: \(spawnedSecond)") // CHECK: spawned second: true assert(spawnedSecond) group.cancelAll() print("cancelAll") // CHECK: cancelAll // let outerCancelled = await outer // should not be cancelled // print("outer cancelled: \(outerCancelled)") // COM: CHECK: outer cancelled: false // print("group cancelled: \(group.isCancelled)") // COM: CHECK: outer cancelled: false let one = await group.next() print("first: \(one)") // CHECK: first: Optional(main.SendableTuple2<Swift.Int, Swift.Bool>(first: 1, let two = await group.next() print("second: \(two)") // CHECK: second: Optional(main.SendableTuple2<Swift.Int, Swift.Bool>(first: 2, let none = await group.next() print("none: \(none)") // CHECK: none: nil return (one?.first ?? 0) + (two?.first ?? 0) + (none?.first ?? 0) } print("result: \(result)") // CHECK: result: 3 } @available(SwiftStdlib 5.5, *) @main struct Main { static func main() async { await test_taskGroup_cancel_then_completions() } }
apache-2.0
6e0ac4b503f09f8ff3e8f882a48819ba
32
150
0.673401
3.707351
false
false
false
false
raphaelhanneken/icnscomposer
Icns Composer/DragDropImageView.swift
1
3846
// // DragAndDropImageView.swift // Icns Composer // https://github.com/raphaelhanneken/icnscomposer // import Cocoa class DragDropImageView: NSImageView, NSDraggingSource { /// Holds the last mouse down event, to track the drag distance. var mouseDownEvent: NSEvent? override init(frame frameRect: NSRect) { super.init(frame: frameRect) // Assure editable is set to true, to enable drop capabilities. isEditable = true } required init?(coder: NSCoder) { super.init(coder: coder) // Assure editable is set to true, to enable drop capabilities. isEditable = true } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) } // MARK: - NSDraggingSource // Since we only want to copy/delete the current image we register ourselfes // for .Copy and .Delete operations. func draggingSession(_: NSDraggingSession, sourceOperationMaskFor _: NSDraggingContext) -> NSDragOperation { return NSDragOperation.copy.union(.delete) } // Clear the ImageView on delete operation; e.g. the image gets // dropped on the trash can in the dock. func draggingSession(_: NSDraggingSession, endedAt _: NSPoint, operation: NSDragOperation) { if operation == .delete { image = nil } } // Track mouse down events and safe the to the poperty. override func mouseDown(with theEvent: NSEvent) { mouseDownEvent = theEvent } // Track mouse dragged events to handle dragging sessions. override func mouseDragged(with theEvent: NSEvent) { // Get the image to drag guard let image = image else { return } // Calculate the drag distance... guard let mouseDown = mouseDownEvent?.locationInWindow else { return } let dragPoint = theEvent.locationInWindow let dragDistance = hypot(mouseDown.x - dragPoint.x, mouseDown.y - dragPoint.y) // ...to cancel the dragging session in case of accidental drag. if dragDistance < 3 { return } // Do some math to properly resize the given image. let size = NSSize(width: log10(image.size.width) * 30, height: log10(image.size.height) * 30) if let img = image.resize(toSize: size) { // Create a new NSDraggingItem with the image as content. let draggingItem = NSDraggingItem(pasteboardWriter: image) // Calculate the mouseDown location from the window's coordinate system to the ImageViews // coordinate system, to use it as origin for the dragging frame. let draggingFrameOrigin = convert(mouseDown, from: nil) // Build the dragging frame and offset it by half the image size on each axis // to center the mouse cursor within the dragging frame. let draggingFrame = NSRect(origin: draggingFrameOrigin, size: img.size).offsetBy(dx: -img.size.width / 2, dy: -img.size.height / 2) // Assign the dragging frame to the draggingFrame property of our dragging item. draggingItem.draggingFrame = draggingFrame // Provide the components of the dragging image. draggingItem.imageComponentsProvider = { let component = NSDraggingImageComponent(key: NSDraggingItem.ImageComponentKey.icon) component.contents = image component.frame = NSRect(origin: NSPoint(), size: draggingFrame.size) return [component] } // Begin actual dragging session. Woohow! beginDraggingSession(with: [draggingItem], event: mouseDownEvent!, source: self) } } }
mit
bc04298f63fcc0069d22014933bcfe0f
37.079208
118
0.627925
4.943445
false
false
false
false
evgenyneu/Cosmos
CosmosTests/CosmosAccessibilityCallbacksTests.swift
3
1709
import XCTest @testable import Cosmos // Ensure touch closures are called in accessibility mode class CosmosAccessibilityCallbacksTests: XCTestCase { var obj: CosmosView! override func setUp() { super.setUp() obj = CosmosView() } func testAccessibilityIncrement_callsDidTouchCosmos() { var didTouchCosmosRating: Double? = nil obj.didTouchCosmos = { rating in didTouchCosmosRating = rating } obj.rating = 3.6 obj.settings.fillMode = .half obj.accessibilityIncrement() XCTAssertEqual(4, didTouchCosmosRating) } func testAccessibilityDecrement_callsDidTouchCosmos() { var didTouchCosmosRating: Double? = nil obj.didTouchCosmos = { rating in didTouchCosmosRating = rating } obj.rating = 3.6 obj.settings.fillMode = .half obj.accessibilityDecrement() XCTAssertEqual(3.5, didTouchCosmosRating) } func testAccessibilityIncrement_callsDidFinishTouchingCosmos() { var didFinishTouchingCosmosRating: Double? = nil obj.didFinishTouchingCosmos = { rating in didFinishTouchingCosmosRating = rating } obj.rating = 3.6 obj.settings.fillMode = .half obj.accessibilityIncrement() XCTAssertEqual(4, didFinishTouchingCosmosRating) } func testAccessibilityDecrement_callsDidFinishTouchingCosmos() { var didFinishTouchingCosmosRating: Double? = nil obj.didFinishTouchingCosmos = { rating in didFinishTouchingCosmosRating = rating } obj.rating = 3.6 obj.settings.fillMode = .half obj.accessibilityDecrement() XCTAssertEqual(3.5, didFinishTouchingCosmosRating) } }
mit
2bfc556bcb7911cc4c09ecbe42282bd1
22.410959
66
0.689877
4.773743
false
true
false
false
uasys/swift
test/refactoring/rename/basic.swift
5
4879
struct S1 {} func foo1(a: S1) {} class C1 {} func foo2(c : C1) {} enum E1 {} func foo3(e : E1) {} func foo4(a : S1, b : C1, c: E1) { foo4(a: a, b: b, c :c) } func test() { struct SLocal { init(x: S1) {} } func local(a: SLocal) {} local(a: SLocal(x: S1())) } guard let top = Optional.some("top") else { fatalError() } print(top) // RUN: rm -rf %t.result && mkdir -p %t.result // RUN: %refactor -rename -source-filename %s -pos=2:15 -new-name new_S1 >> %t.result/S1.swift // RUN: diff -u %S/Outputs/basic/S1.swift.expected %t.result/S1.swift // RUN: %refactor -rename -source-filename %s -pos=4:16 -new-name new_c1>> %t.result/C1.swift // RUN: diff -u %S/Outputs/basic/C1.swift.expected %t.result/C1.swift // RUN: %refactor -rename -source-filename %s -pos=6:16 -new-name new_e1 >> %t.result/E1.swift // RUN: diff -u %S/Outputs/basic/E1.swift.expected %t.result/E1.swift // RUN: %refactor -rename -source-filename %s -pos=7:38 -new-name 'new_foo4(a:b:c:)' >> %t.result/foo4.swift // RUN: diff -u %S/Outputs/basic/foo4.swift.expected %t.result/foo4.swift // RUN: %refactor -rename -source-filename %s -pos=1:9 -new-name new_S1 > %t.result/S1.swift // RUN: diff -u %S/Outputs/basic/S1.swift.expected %t.result/S1.swift // RUN: %refactor -rename -source-filename %s -pos=3:8 -new-name new_c1 > %t.result/C1.swift // RUN: diff -u %S/Outputs/basic/C1.swift.expected %t.result/C1.swift // RUN: %refactor -rename -source-filename %s -pos=5:7 -new-name new_e1 > %t.result/E1.swift // RUN: diff -u %S/Outputs/basic/E1.swift.expected %t.result/E1.swift // RUN: %refactor -rename -source-filename %s -pos=7:7 -new-name 'new_foo4(a:b:c:)' > %t.result/foo4.swift // RUN: diff -u %S/Outputs/basic/foo4.swift.expected %t.result/foo4.swift // RUN: %refactor -rename -source-filename %s -pos=7:7 -new-name 'new_foo4(new_a:b:_:)' > %t.result/foo4_multi.swift // RUN: diff -u %S/Outputs/basic/foo4_multi.swift.expected %t.result/foo4_multi.swift // RUN: %refactor -rename -source-filename %s -pos=10:10 -new-name new_SLocal >> %t.result/SLocal.swift // RUN: diff -u %S/Outputs/basic/SLocal.swift.expected %t.result/SLocal.swift // RUN: %refactor -rename -source-filename %s -pos=11:5 -new-name 'init(y:)' >> %t.result/SLocal_init.swift // RUN: diff -u %S/Outputs/basic/SLocal_init.swift.expected %t.result/SLocal_init.swift // RUN: %refactor -rename -source-filename %s -pos=13:8 -new-name 'new_local(b:)' >> %t.result/local.swift // RUN: diff -u %S/Outputs/basic/local.swift.expected %t.result/local.swift // RUN: %refactor -rename -source-filename %s -pos=20:7 -new-name 'bottom' > %t.result/top_level.swift // RUN: diff -u %S/Outputs/basic/top_level.swift.expected %t.result/top_level.swift // RUN: rm -rf %t.ranges && mkdir -p %t.ranges // RUN: %refactor -find-local-rename-ranges -source-filename %s -pos=2:15 > %t.ranges/S1.swift // RUN: diff -u %S/Outputs/basic_ranges/S1.swift.expected %t.ranges/S1.swift // RUN: %refactor -find-local-rename-ranges -source-filename %s -pos=4:16 > %t.ranges/C1.swift // RUN: diff -u %S/Outputs/basic_ranges/C1.swift.expected %t.ranges/C1.swift // RUN: %refactor -find-local-rename-ranges -source-filename %s -pos=6:16 > %t.ranges/E1.swift // RUN: diff -u %S/Outputs/basic_ranges/E1.swift.expected %t.ranges/E1.swift // RUN: %refactor -find-local-rename-ranges -source-filename %s -pos=7:38 > %t.ranges/foo4.swift // RUN: diff -u %S/Outputs/basic_ranges/foo4.swift.expected %t.ranges/foo4.swift // RUN: %refactor -find-local-rename-ranges -source-filename %s -pos=1:9 > %t.ranges/S1.swift // RUN: diff -u %S/Outputs/basic_ranges/S1.swift.expected %t.ranges/S1.swift // RUN: %refactor -find-local-rename-ranges -source-filename %s -pos=3:8 > %t.ranges/C1.swift // RUN: diff -u %S/Outputs/basic_ranges/C1.swift.expected %t.ranges/C1.swift // RUN: %refactor -find-local-rename-ranges -source-filename %s -pos=5:7 > %t.ranges/E1.swift // RUN: diff -u %S/Outputs/basic_ranges/E1.swift.expected %t.ranges/E1.swift // RUN: %refactor -find-local-rename-ranges -source-filename %s -pos=7:7 > %t.ranges/foo4.swift // RUN: diff -u %S/Outputs/basic_ranges/foo4.swift.expected %t.ranges/foo4.swift // RUN: %refactor -find-local-rename-ranges -source-filename %s -pos=10:10 > %t.ranges/SLocal.swift // RUN: diff -u %S/Outputs/basic_ranges/SLocal.swift.expected %t.ranges/SLocal.swift // RUN: %refactor -find-local-rename-ranges -source-filename %s -pos=11:5 > %t.ranges/SLocal_init.swift // RUN: diff -u %S/Outputs/basic_ranges/SLocal_init.swift.expected %t.ranges/SLocal_init.swift // RUN: %refactor -find-local-rename-ranges -source-filename %s -pos=13:8 > %t.ranges/local.swift // RUN: diff -u %S/Outputs/basic_ranges/local.swift.expected %t.ranges/local.swift // RUN: %refactor -find-local-rename-ranges -source-filename %s -pos=20:7 > %t.result/top_level.swift // RUN: diff -u %S/Outputs/basic_ranges/top_level.swift.expected %t.result/top_level.swift
apache-2.0
d38024db4741bdc3206a31d37d49e14a
65.835616
116
0.69461
2.547781
false
false
false
false
tenten0213/ValidatorSample
ValidatorSample/ViewController.swift
1
1609
// // ViewController.swift // ValidatorSample // // import UIKit import Validator class ViewController: UIViewController { @IBOutlet weak var userIdInput: UITextField! @IBOutlet weak var passwordInput: UITextField! @IBOutlet weak var errorForUserId: UILabel! @IBOutlet weak var errorForPassword: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func goSecondView(_ sender: UIButton) { performSegue(withIdentifier: "goSeccondView", sender: nil) } @IBAction func login(_ sender: UIButton) { let userIdValidateResult = userIdInput.validate(rule: ValidationRuleUserId(error: ValidationError(message: "💩"))) switch userIdValidateResult { case .valid: errorForUserId.text = "😎" case .invalid(let errors): let error = errors.first as? ValidationError errorForUserId.text = error?.message ?? "😱" } let passwordValidateResult = passwordInput.validate(rule: ValidationRuleLength(min: 1, max: 64, error: ValidationError(message: "💩"))) switch passwordValidateResult { case .valid: errorForPassword.text = "😎" case .invalid(let errors): let error = errors.first as? ValidationError errorForPassword.text = error?.message ?? "😱" } } }
mit
ad46101b7d55faa7ecb831b72d0a99fd
32.851064
142
0.654934
4.749254
false
false
false
false
askfromap/PassCodeLock-Swift3
PasscodeLock/Views/PasscodeSignButton.swift
1
2425
// // PasscodeSignButton.swift // PasscodeLock // // Created by Yanko Dimitrov on 8/28/15. // Copyright © 2015 Yanko Dimitrov. All rights reserved. // import UIKit @IBDesignable open class PasscodeSignButton: UIButton { @IBInspectable open var passcodeSign: String = "1" @IBInspectable open var borderColor: UIColor = UIColor.white { didSet { setupView() } } @IBInspectable open var borderRadius: CGFloat = 30 { didSet { setupView() } } @IBInspectable open var highlightBackgroundColor: UIColor = UIColor.clear { didSet { setupView() } } public override init(frame: CGRect) { super.init(frame: frame) setupView() setupActions() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupActions() } open override var intrinsicContentSize : CGSize { return CGSize(width: 60, height: 60) } fileprivate var defaultBackgroundColor = UIColor.clear fileprivate func setupView() { layer.borderWidth = 1 layer.cornerRadius = borderRadius layer.borderColor = borderColor.cgColor if let backgroundColor = backgroundColor { defaultBackgroundColor = backgroundColor } } fileprivate func setupActions() { addTarget(self, action: #selector(PasscodeSignButton.handleTouchDown), for: .touchDown) addTarget(self, action: #selector(PasscodeSignButton.handleTouchUp), for: [.touchUpInside, .touchDragOutside, .touchCancel]) } func handleTouchDown() { animateBackgroundColor(highlightBackgroundColor) } func handleTouchUp() { animateBackgroundColor(defaultBackgroundColor) } fileprivate func animateBackgroundColor(_ color: UIColor) { UIView.animate( withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0.0, options: [.allowUserInteraction, .beginFromCurrentState], animations: { self.backgroundColor = color }, completion: nil ) } }
mit
77975d6c14a2132e05cfd8e249e2a6d3
22.533981
132
0.571782
5.65035
false
false
false
false
FuckBoilerplate/RxCache
watchOS/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift
6
2448
// // MainScheduler.swift // Rx // // Created by Krunoslav Zaher on 2/8/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Abstracts work that needs to be performed on `MainThread`. In case `schedule` methods are called from main thread, it will perform action immediately without scheduling. This scheduler is usually used to perform UI work. Main scheduler is a specialization of `SerialDispatchQueueScheduler`. This scheduler is optimized for `observeOn` operator. To ensure observable sequence is subscribed on main thread using `subscribeOn` operator please use `ConcurrentMainScheduler` because it is more optimized for that purpose. */ public final class MainScheduler : SerialDispatchQueueScheduler { private let _mainQueue: DispatchQueue var numberEnqueued: AtomicInt = 0 /** Initializes new instance of `MainScheduler`. */ public init() { _mainQueue = DispatchQueue.main super.init(serialQueue: _mainQueue) } /** Singleton instance of `MainScheduler` */ public static let instance = MainScheduler() /** Singleton instance of `MainScheduler` that always schedules work asynchronously and doesn't perform optimizations for calls scheduled from main thread. */ public static let asyncInstance = SerialDispatchQueueScheduler(serialQueue: DispatchQueue.main) /** In case this method is called on a background thread it will throw an exception. */ public class func ensureExecutingOnScheduler(errorMessage: String? = nil) { if !Thread.current.isMainThread { rxFatalError(errorMessage ?? "Executing on backgound thread. Please use `MainScheduler.instance.schedule` to schedule work on main thread.") } } override func scheduleInternal<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { let currentNumberEnqueued = AtomicIncrement(&numberEnqueued) if Thread.current.isMainThread && currentNumberEnqueued == 1 { let disposable = action(state) _ = AtomicDecrement(&numberEnqueued) return disposable } let cancel = SingleAssignmentDisposable() _mainQueue.async { if !cancel.isDisposed { _ = action(state) } _ = AtomicDecrement(&self.numberEnqueued) } return cancel } }
mit
7e318fc505c3439c8a3c909492fb70be
31.197368
169
0.69105
5.251073
false
false
false
false
reproio/firefox-ios
Client/Frontend/Settings/SearchSettingsTableViewController.swift
1
10341
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit class SearchSettingsTableViewController: UITableViewController { private let SectionDefault = 0 private let ItemDefaultEngine = 0 private let ItemDefaultSuggestions = 1 private let NumberOfItemsInSectionDefault = 2 private let SectionOrder = 1 private let NumberOfSections = 2 private let IconSize = CGSize(width: OpenSearchEngine.PreferredIconSize, height: OpenSearchEngine.PreferredIconSize) private let SectionHeaderIdentifier = "SectionHeaderIdentifier" var model: SearchEngines! override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NSLocalizedString("Search", comment: "Navigation title for search settings.") // To allow re-ordering the list of search engines at all times. tableView.editing = true // So that we push the default search engine controller on selection. tableView.allowsSelectionDuringEditing = true tableView.registerClass(SettingsTableSectionHeaderView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier) // Insert Done button if being presented outside of the Settings Nav stack if !(self.navigationController is SettingsNavigationController) { self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Done", comment: "Done title for search settings table"), style: .Done, target: self, action: "SELDismiss") } tableView.tableFooterView = UIView() tableView.separatorColor = UIConstants.TableViewSeparatorColor tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell: UITableViewCell! var engine: OpenSearchEngine! if indexPath.section == SectionDefault { switch indexPath.item { case ItemDefaultEngine: engine = model.defaultEngine cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil) cell.editingAccessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell.accessibilityLabel = NSLocalizedString("Default Search Engine", comment: "Accessibility label for default search engine setting.") cell.accessibilityValue = engine.shortName cell.textLabel?.text = engine.shortName cell.imageView?.image = engine.image?.createScaled(IconSize) case ItemDefaultSuggestions: cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil) cell.textLabel?.text = NSLocalizedString("Show search suggestions", comment: "Label for show search suggestions setting.") let toggle = UISwitch() toggle.onTintColor = UIConstants.ControlTintColor toggle.addTarget(self, action: "SELdidToggleSearchSuggestions:", forControlEvents: UIControlEvents.ValueChanged) toggle.on = model.shouldShowSearchSuggestions cell.editingAccessoryView = toggle cell.selectionStyle = .None default: // Should not happen. break } } else { // The default engine is not a quick search engine. let index = indexPath.item + 1 engine = model.orderedEngines[index] cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil) cell.showsReorderControl = true let toggle = UISwitch() toggle.onTintColor = UIConstants.ControlTintColor // This is an easy way to get from the toggle control to the corresponding index. toggle.tag = index toggle.addTarget(self, action: "SELdidToggleEngine:", forControlEvents: UIControlEvents.ValueChanged) toggle.on = model.isEngineEnabled(engine) cell.editingAccessoryView = toggle cell.textLabel?.text = engine.shortName cell.imageView?.image = engine.image?.createScaled(IconSize) cell.selectionStyle = .None } // So that the seperator line goes all the way to the left edge. cell.separatorInset = UIEdgeInsetsZero return cell } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return NumberOfSections } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == SectionDefault { return NumberOfItemsInSectionDefault } else { // The first engine -- the default engine -- is not shown in the quick search engine list. return model.orderedEngines.count - 1 } } override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { if indexPath.section == SectionDefault && indexPath.item == ItemDefaultEngine { let searchEnginePicker = SearchEnginePicker() // Order alphabetically, so that picker is always consistently ordered. // Every engine is a valid choice for the default engine, even the current default engine. searchEnginePicker.engines = model.orderedEngines.sort { e, f in e.shortName < f.shortName } searchEnginePicker.delegate = self searchEnginePicker.selectedSearchEngineName = model.defaultEngine.shortName navigationController?.pushViewController(searchEnginePicker, animated: true) } return nil } // Don't show delete button on the left. override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return UITableViewCellEditingStyle.None } // Don't reserve space for the delete button on the left. override func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool { return false } // Hide a thin vertical line that iOS renders between the accessoryView and the reordering control. override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if cell.editing { for v in cell.subviews { if v.frame.width == 1.0 { v.backgroundColor = UIColor.clearColor() } } } } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionHeaderIdentifier) as! SettingsTableSectionHeaderView var sectionTitle: String if section == SectionDefault { sectionTitle = NSLocalizedString("Default Search Engine", comment: "Title for default search engine settings section.") } else { sectionTitle = NSLocalizedString("Quick-search Engines", comment: "Title for quick-search engines settings section.") } headerView.titleLabel.text = sectionTitle return headerView } override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { if indexPath.section == SectionDefault { return false } else { return true } } override func tableView(tableView: UITableView, moveRowAtIndexPath indexPath: NSIndexPath, toIndexPath newIndexPath: NSIndexPath) { // The first engine (default engine) is not shown in the list, so the indices are off-by-1. let index = indexPath.item + 1 let newIndex = newIndexPath.item + 1 let engine = model.orderedEngines.removeAtIndex(index) model.orderedEngines.insert(engine, atIndex: newIndex) tableView.reloadData() } // Snap to first or last row of the list of engines. override func tableView(tableView: UITableView, targetIndexPathForMoveFromRowAtIndexPath sourceIndexPath: NSIndexPath, toProposedIndexPath proposedDestinationIndexPath: NSIndexPath) -> NSIndexPath { // You can't drag or drop on the default engine. if sourceIndexPath.section == SectionDefault || proposedDestinationIndexPath.section == SectionDefault { return sourceIndexPath } if (sourceIndexPath.section != proposedDestinationIndexPath.section) { var row = 0 if (sourceIndexPath.section < proposedDestinationIndexPath.section) { row = tableView.numberOfRowsInSection(sourceIndexPath.section) - 1 } return NSIndexPath(forRow: row, inSection: sourceIndexPath.section) } return proposedDestinationIndexPath } func SELdidToggleEngine(toggle: UISwitch) { let engine = model.orderedEngines[toggle.tag] // The tag is 1-based. if toggle.on { model.enableEngine(engine) } else { model.disableEngine(engine) } } func SELdidToggleSearchSuggestions(toggle: UISwitch) { // Setting the value in settings dismisses any opt-in. model.shouldShowSearchSuggestionsOptIn = false model.shouldShowSearchSuggestions = toggle.on } func SELcancel() { navigationController?.popViewControllerAnimated(true) } func SELDismiss() { self.dismissViewControllerAnimated(true, completion: nil) } } extension SearchSettingsTableViewController: SearchEnginePickerDelegate { func searchEnginePicker(searchEnginePicker: SearchEnginePicker, didSelectSearchEngine searchEngine: OpenSearchEngine?) { if let engine = searchEngine { model.defaultEngine = engine self.tableView.reloadData() } navigationController?.popViewControllerAnimated(true) } }
mpl-2.0
50e0b8abd83ca034456899d08b03e800
43.766234
202
0.684363
6.012209
false
false
false
false
tarrencev/BitWallet
BitWallet/ContainerViewController.swift
1
3350
// // ViewController.swift // BitWallet // // Created by Tarrence van As on 8/3/14. // Copyright (c) 2014 tva. All rights reserved. // import UIKit class ContainerViewController: UIViewController, UIScrollViewDelegate { // Create the 3 main view controllers var receiveViewController = ReceiveViewController(), sendViewController = SendViewController(), transactViewController = TransactViewController(), profileViewController = ProfileViewController(), curScrollPage: Int? @IBOutlet var scrollView: UIScrollView? override func viewDidLoad() { super.viewDidLoad() receiveViewController.view.backgroundColor = Utilities.baseColor() transactViewController.view.backgroundColor = Utilities.baseColor() profileViewController.view.backgroundColor = Utilities.baseColor() // Add each view to container view hierarchy self.addChildViewController(profileViewController) self.scrollView?.addSubview(profileViewController.view) profileViewController.didMoveToParentViewController(self) self.addChildViewController(transactViewController) self.scrollView?.addSubview(transactViewController.view) transactViewController.didMoveToParentViewController(self) self.addChildViewController(receiveViewController) self.scrollView?.addSubview(receiveViewController.view) receiveViewController.didMoveToParentViewController(self) // Setup frames of the view controllers to align inside container var receiveFrame = receiveViewController.view.frame receiveFrame.origin.x = receiveFrame.width transactViewController.view.frame = receiveFrame var transactionsFrame = transactViewController.view.frame transactionsFrame.origin.x = 2 * transactionsFrame.width profileViewController.view.frame = transactionsFrame; // Set scrollView size to contain the frames var scrollWidth = 3 * self.view.frame.width, scrollHeight = self.view.frame.size.height - 20 self.scrollView!.contentSize = CGSizeMake(scrollWidth, scrollHeight) self.scrollView!.setContentOffset(CGPoint(x: receiveFrame.width, y: 0), animated: false) self.view.backgroundColor = Utilities.colorize(0x35485c, alpha: 1) } func scrollViewDidScroll(scrollView: UIScrollView) { let pageWidth = scrollView.frame.size.width, calculatedScrollPage = Int(floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1) if curScrollPage != calculatedScrollPage { curScrollPage = calculatedScrollPage switch calculatedScrollPage { case 1: transactViewController.viewIsScrollingOnScreen() case 2: profileViewController.viewIsScrollingOnScreen() transactViewController.viewIsScrollingOffScreen() default: transactViewController.viewIsScrollingOffScreen() } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
96d3e23788a0023e5199bd54105ce4eb
37.953488
107
0.677015
5.668359
false
false
false
false
iAugux/Zoom-Contacts
Phonetic/CWStatusBarNotification/Toast.swift
1
1117
// // Toast.swift // // Created by Augus on 4/23/16. // Copyright © 2016 iAugus. All rights reserved. // import Foundation class Toast { private static var notification: CWStatusBarNotification = { let notification = CWStatusBarNotification() notification.notificationAnimationInStyle = .Top notification.notificationAnimationOutStyle = .Top return notification }() static func make(message: String, delay: NSTimeInterval = 0, interval: NSTimeInterval = 1.0) { let make = { notification.displayNotificationWithMessage(message, forDuration: interval) } dispatch_async(dispatch_get_main_queue()) { if delay != 0 { let delayInSeconds: Double = delay let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * delayInSeconds)) dispatch_after(popTime, dispatch_get_main_queue(), { make() }) } else { make() } } } }
mit
35b1bb06b755a63d9865c5fe42ad6257
26.243902
108
0.560932
4.96
false
false
false
false
kstaring/swift
stdlib/public/core/Mirror.swift
1
35567
//===--- Mirror.swift -----------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // FIXME: ExistentialCollection needs to be supported before this will work // without the ObjC Runtime. /// Representation of the sub-structure and optional "display style" /// of any arbitrary subject instance. /// /// Describes the parts---such as stored properties, collection /// elements, tuple elements, or the active enumeration case---that /// make up a particular instance. May also supply a "display style" /// property that suggests how this structure might be rendered. /// /// Mirrors are used by playgrounds and the debugger. public struct Mirror { /// Representation of descendant classes that don't override /// `customMirror`. /// /// Note that the effect of this setting goes no deeper than the /// nearest descendant class that overrides `customMirror`, which /// in turn can determine representation of *its* descendants. internal enum _DefaultDescendantRepresentation { /// Generate a default mirror for descendant classes that don't /// override `customMirror`. /// /// This case is the default. case generated /// Suppress the representation of descendant classes that don't /// override `customMirror`. /// /// This option may be useful at the root of a class cluster, where /// implementation details of descendants should generally not be /// visible to clients. case suppressed } /// Representation of ancestor classes. /// /// A `CustomReflectable` class can control how its mirror will /// represent ancestor classes by initializing the mirror with a /// `AncestorRepresentation`. This setting has no effect on mirrors /// reflecting value type instances. public enum AncestorRepresentation { /// Generate a default mirror for all ancestor classes. /// /// This case is the default. /// /// - Note: This option generates default mirrors even for /// ancestor classes that may implement `CustomReflectable`'s /// `customMirror` requirement. To avoid dropping an ancestor class /// customization, an override of `customMirror` should pass /// `ancestorRepresentation: .Customized(super.customMirror)` when /// initializing its `Mirror`. case generated /// Use the nearest ancestor's implementation of `customMirror` to /// create a mirror for that ancestor. Other classes derived from /// such an ancestor are given a default mirror. /// /// The payload for this option should always be /// "`{ super.customMirror }`": /// /// var customMirror: Mirror { /// return Mirror( /// self, /// children: ["someProperty": self.someProperty], /// ancestorRepresentation: .Customized({ super.customMirror })) // <== /// } case customized(() -> Mirror) /// Suppress the representation of all ancestor classes. The /// resulting `Mirror`'s `superclassMirror` is `nil`. case suppressed } /// Reflect upon the given `subject`. /// /// If the dynamic type of `subject` conforms to `CustomReflectable`, /// the resulting mirror is determined by its `customMirror` property. /// Otherwise, the result is generated by the language. /// /// - Note: If the dynamic type of `subject` has value semantics, /// subsequent mutations of `subject` will not observable in /// `Mirror`. In general, though, the observability of such /// mutations is unspecified. public init(reflecting subject: Any) { if case let customized as CustomReflectable = subject { self = customized.customMirror } else { self = Mirror( legacy: _reflect(subject), subjectType: type(of: subject)) } } /// An element of the reflected instance's structure. The optional /// `label` may be used when appropriate, e.g. to represent the name /// of a stored property or of an active `enum` case, and will be /// used for lookup when `String`s are passed to the `descendant` /// method. public typealias Child = (label: String?, value: Any) /// The type used to represent sub-structure. /// /// Depending on your needs, you may find it useful to "upgrade" /// instances of this type to `AnyBidirectionalCollection` or /// `AnyRandomAccessCollection`. For example, to display the last /// 20 children of a mirror if they can be accessed efficiently, you /// might write: /// /// if let b = AnyBidirectionalCollection(someMirror.children) { /// var i = xs.index(b.endIndex, offsetBy: -20, /// limitedBy: b.startIndex) ?? b.startIndex /// while i != xs.endIndex { /// print(b[i]) /// b.formIndex(after: &i) /// } /// } public typealias Children = AnyCollection<Child> /// A suggestion of how a `Mirror`'s `subject` is to be interpreted. /// /// Playgrounds and the debugger will show a representation similar /// to the one used for instances of the kind indicated by the /// `DisplayStyle` case name when the `Mirror` is used for display. public enum DisplayStyle { case `struct`, `class`, `enum`, tuple, optional, collection case dictionary, `set` } static func _noSuperclassMirror() -> Mirror? { return nil } /// Returns the legacy mirror representing the part of `subject` /// corresponding to the superclass of `staticSubclass`. internal static func _legacyMirror( _ subject: AnyObject, asClass targetSuperclass: AnyClass) -> _Mirror? { // get a legacy mirror and the most-derived type var cls: AnyClass = type(of: subject) var clsMirror = _reflect(subject) // Walk up the chain of mirrors/classes until we find staticSubclass while let superclass: AnyClass = _getSuperclass(cls) { guard let superclassMirror = clsMirror._superMirror() else { break } if superclass == targetSuperclass { return superclassMirror } clsMirror = superclassMirror cls = superclass } return nil } internal static func _superclassIterator<Subject>( _ subject: Subject, _ ancestorRepresentation: AncestorRepresentation ) -> () -> Mirror? { if let subjectClass = Subject.self as? AnyClass, let superclass = _getSuperclass(subjectClass) { switch ancestorRepresentation { case .generated: return { self._legacyMirror(_unsafeDowncastToAnyObject(fromAny: subject), asClass: superclass).map { Mirror(legacy: $0, subjectType: superclass) } } case .customized(let makeAncestor): return { Mirror(_unsafeDowncastToAnyObject(fromAny: subject), subjectClass: superclass, ancestor: makeAncestor()) } case .suppressed: break } } return Mirror._noSuperclassMirror } /// Represent `subject` with structure described by `children`, /// using an optional `displayStyle`. /// /// If `subject` is not a class instance, `ancestorRepresentation` /// is ignored. Otherwise, `ancestorRepresentation` determines /// whether ancestor classes will be represented and whether their /// `customMirror` implementations will be used. By default, a /// representation is automatically generated and any `customMirror` /// implementation is bypassed. To prevent bypassing customized /// ancestors, `customMirror` overrides should initialize the /// `Mirror` with: /// /// ancestorRepresentation: .customized({ super.customMirror }) /// /// - Note: The traversal protocol modeled by `children`'s indices /// (`ForwardIndex`, `BidirectionalIndex`, or /// `RandomAccessIndex`) is captured so that the resulting /// `Mirror`'s `children` may be upgraded later. See the failable /// initializers of `AnyBidirectionalCollection` and /// `AnyRandomAccessCollection` for details. public init<Subject, C : Collection>( _ subject: Subject, children: C, displayStyle: DisplayStyle? = nil, ancestorRepresentation: AncestorRepresentation = .generated ) where C.Iterator.Element == Child, // FIXME(ABI)#47 (Associated Types with where clauses): these constraints should be applied to // associated types of Collection. C.SubSequence : Collection, C.SubSequence.Iterator.Element == Child, C.SubSequence.Index == C.Index, C.SubSequence.Indices : Collection, C.SubSequence.Indices.Iterator.Element == C.Index, C.SubSequence.Indices.Index == C.Index, C.SubSequence.Indices.SubSequence == C.SubSequence.Indices, C.SubSequence.SubSequence == C.SubSequence, C.Indices : Collection, C.Indices.Iterator.Element == C.Index, C.Indices.Index == C.Index, C.Indices.SubSequence == C.Indices { self.subjectType = Subject.self self._makeSuperclassMirror = Mirror._superclassIterator( subject, ancestorRepresentation) self.children = Children(children) self.displayStyle = displayStyle self._defaultDescendantRepresentation = subject is CustomLeafReflectable ? .suppressed : .generated } /// Represent `subject` with child values given by /// `unlabeledChildren`, using an optional `displayStyle`. The /// result's child labels will all be `nil`. /// /// This initializer is especially useful for the mirrors of /// collections, e.g.: /// /// extension MyArray : CustomReflectable { /// var customMirror: Mirror { /// return Mirror(self, unlabeledChildren: self, displayStyle: .collection) /// } /// } /// /// If `subject` is not a class instance, `ancestorRepresentation` /// is ignored. Otherwise, `ancestorRepresentation` determines /// whether ancestor classes will be represented and whether their /// `customMirror` implementations will be used. By default, a /// representation is automatically generated and any `customMirror` /// implementation is bypassed. To prevent bypassing customized /// ancestors, `customMirror` overrides should initialize the /// `Mirror` with: /// /// ancestorRepresentation: .Customized({ super.customMirror }) /// /// - Note: The traversal protocol modeled by `children`'s indices /// (`ForwardIndex`, `BidirectionalIndex`, or /// `RandomAccessIndex`) is captured so that the resulting /// `Mirror`'s `children` may be upgraded later. See the failable /// initializers of `AnyBidirectionalCollection` and /// `AnyRandomAccessCollection` for details. public init<Subject, C : Collection>( _ subject: Subject, unlabeledChildren: C, displayStyle: DisplayStyle? = nil, ancestorRepresentation: AncestorRepresentation = .generated ) where // FIXME(ABI)#48 (Associated Types with where clauses): these constraints should be applied to // associated types of Collection. C.SubSequence : Collection, C.SubSequence.SubSequence == C.SubSequence, C.Indices : Collection, C.Indices.Iterator.Element == C.Index, C.Indices.Index == C.Index, C.Indices.SubSequence == C.Indices { self.subjectType = Subject.self self._makeSuperclassMirror = Mirror._superclassIterator( subject, ancestorRepresentation) let lazyChildren = unlabeledChildren.lazy.map { Child(label: nil, value: $0) } self.children = Children(lazyChildren) self.displayStyle = displayStyle self._defaultDescendantRepresentation = subject is CustomLeafReflectable ? .suppressed : .generated } /// Represent `subject` with labeled structure described by /// `children`, using an optional `displayStyle`. /// /// Pass a dictionary literal with `String` keys as `children`. Be /// aware that although an *actual* `Dictionary` is /// arbitrarily-ordered, the ordering of the `Mirror`'s `children` /// will exactly match that of the literal you pass. /// /// If `subject` is not a class instance, `ancestorRepresentation` /// is ignored. Otherwise, `ancestorRepresentation` determines /// whether ancestor classes will be represented and whether their /// `customMirror` implementations will be used. By default, a /// representation is automatically generated and any `customMirror` /// implementation is bypassed. To prevent bypassing customized /// ancestors, `customMirror` overrides should initialize the /// `Mirror` with: /// /// ancestorRepresentation: .customized({ super.customMirror }) /// /// - Note: The resulting `Mirror`'s `children` may be upgraded to /// `AnyRandomAccessCollection` later. See the failable /// initializers of `AnyBidirectionalCollection` and /// `AnyRandomAccessCollection` for details. public init<Subject>( _ subject: Subject, children: DictionaryLiteral<String, Any>, displayStyle: DisplayStyle? = nil, ancestorRepresentation: AncestorRepresentation = .generated ) { self.subjectType = Subject.self self._makeSuperclassMirror = Mirror._superclassIterator( subject, ancestorRepresentation) let lazyChildren = children.lazy.map { Child(label: $0.0, value: $0.1) } self.children = Children(lazyChildren) self.displayStyle = displayStyle self._defaultDescendantRepresentation = subject is CustomLeafReflectable ? .suppressed : .generated } /// The static type of the subject being reflected. /// /// This type may differ from the subject's dynamic type when `self` /// is the `superclassMirror` of another mirror. public let subjectType: Any.Type /// A collection of `Child` elements describing the structure of the /// reflected subject. public let children: Children /// Suggests a display style for the reflected subject. public let displayStyle: DisplayStyle? public var superclassMirror: Mirror? { return _makeSuperclassMirror() } internal let _makeSuperclassMirror: () -> Mirror? internal let _defaultDescendantRepresentation: _DefaultDescendantRepresentation } /// A type that explicitly supplies its own mirror. /// /// You can create a mirror for any type using the `Mirror(reflect:)` /// initializer, but if you are not satisfied with the mirror supplied for /// your type by default, you can make it conform to `CustomReflectable` and /// return a custom `Mirror` instance. public protocol CustomReflectable { /// The custom mirror for this instance. /// /// If this type has value semantics, the mirror should be unaffected by /// subsequent mutations of the instance. var customMirror: Mirror { get } } /// A type that explicitly supplies its own mirror, but whose /// descendant classes are not represented in the mirror unless they /// also override `customMirror`. public protocol CustomLeafReflectable : CustomReflectable {} //===--- Addressing -------------------------------------------------------===// /// A protocol for legitimate arguments to `Mirror`'s `descendant` /// method. /// /// Do not declare new conformances to this protocol; they will not /// work as expected. // FIXME(ABI)#49 (Sealed Protocols): this protocol should be "non-open" and you shouldn't be able to // create conformances. public protocol MirrorPath {} extension IntMax : MirrorPath {} extension Int : MirrorPath {} extension String : MirrorPath {} extension Mirror { internal struct _Dummy : CustomReflectable { var mirror: Mirror var customMirror: Mirror { return mirror } } /// Return a specific descendant of the reflected subject, or `nil` /// Returns a specific descendant of the reflected subject, or `nil` /// if no such descendant exists. /// /// A `String` argument selects the first `Child` with a matching label. /// An integer argument *n* select the *n*th `Child`. For example: /// /// var d = Mirror(reflecting: x).descendant(1, "two", 3) /// /// is equivalent to: /// /// var d = nil /// let children = Mirror(reflecting: x).children /// if let p0 = children.index(children.startIndex, /// offsetBy: 1, limitedBy: children.endIndex) { /// let grandChildren = Mirror(reflecting: children[p0].value).children /// SeekTwo: for g in grandChildren { /// if g.label == "two" { /// let greatGrandChildren = Mirror(reflecting: g.value).children /// if let p1 = greatGrandChildren.index( /// greatGrandChildren.startIndex, /// offsetBy: 3, limitedBy: greatGrandChildren.endIndex) { /// d = greatGrandChildren[p1].value /// } /// break SeekTwo /// } /// } /// } /// /// As you can see, complexity for each element of the argument list /// depends on the argument type and capabilities of the collection /// used to initialize the corresponding subject's parent's mirror. /// Each `String` argument results in a linear search. In short, /// this function is suitable for exploring the structure of a /// `Mirror` in a REPL or playground, but don't expect it to be /// efficient. public func descendant( _ first: MirrorPath, _ rest: MirrorPath... ) -> Any? { var result: Any = _Dummy(mirror: self) for e in [first] + rest { let children = Mirror(reflecting: result).children let position: Children.Index if case let label as String = e { position = children.index { $0.label == label } ?? children.endIndex } else if let offset = (e as? Int).map({ IntMax($0) }) ?? (e as? IntMax) { position = children.index(children.startIndex, offsetBy: offset, limitedBy: children.endIndex) ?? children.endIndex } else { _preconditionFailure( "Someone added a conformance to MirrorPath; that privilege is reserved to the standard library") } if position == children.endIndex { return nil } result = children[position].value } return result } } //===--- Legacy _Mirror Support -------------------------------------------===// extension Mirror.DisplayStyle { /// Construct from a legacy `_MirrorDisposition` internal init?(legacy: _MirrorDisposition) { switch legacy { case .`struct`: self = .`struct` case .`class`: self = .`class` case .`enum`: self = .`enum` case .tuple: self = .tuple case .aggregate: return nil case .indexContainer: self = .collection case .keyContainer: self = .dictionary case .membershipContainer: self = .`set` case .container: preconditionFailure("unused!") case .optional: self = .optional case .objCObject: self = .`class` } } } internal func _isClassSuperMirror(_ t: Any.Type) -> Bool { #if _runtime(_ObjC) return t == _ClassSuperMirror.self || t == _ObjCSuperMirror.self #else return t == _ClassSuperMirror.self #endif } extension _Mirror { internal func _superMirror() -> _Mirror? { if self.count > 0 { let childMirror = self[0].1 if _isClassSuperMirror(type(of: childMirror)) { return childMirror } } return nil } } /// When constructed using the legacy reflection infrastructure, the /// resulting `Mirror`'s `children` collection will always be /// upgradable to `AnyRandomAccessCollection` even if it doesn't /// exhibit appropriate performance. To avoid this pitfall, convert /// mirrors to use the new style, which only present forward /// traversal in general. internal extension Mirror { /// An adapter that represents a legacy `_Mirror`'s children as /// a `Collection` with integer `Index`. Note that the performance /// characteristics of the underlying `_Mirror` may not be /// appropriate for random access! To avoid this pitfall, convert /// mirrors to use the new style, which only present forward /// traversal in general. internal struct LegacyChildren : RandomAccessCollection { typealias Indices = CountableRange<Int> init(_ oldMirror: _Mirror) { self._oldMirror = oldMirror } var startIndex: Int { return _oldMirror._superMirror() == nil ? 0 : 1 } var endIndex: Int { return _oldMirror.count } subscript(position: Int) -> Child { let (label, childMirror) = _oldMirror[position] return (label: label, value: childMirror.value) } internal let _oldMirror: _Mirror } /// Initialize for a view of `subject` as `subjectClass`. /// /// - parameter ancestor: A Mirror for a (non-strict) ancestor of /// `subjectClass`, to be injected into the resulting hierarchy. /// /// - parameter legacy: Either `nil`, or a legacy mirror for `subject` /// as `subjectClass`. internal init( _ subject: AnyObject, subjectClass: AnyClass, ancestor: Mirror, legacy legacyMirror: _Mirror? = nil ) { if ancestor.subjectType == subjectClass || ancestor._defaultDescendantRepresentation == .suppressed { self = ancestor } else { let legacyMirror = legacyMirror ?? Mirror._legacyMirror( subject, asClass: subjectClass)! self = Mirror( legacy: legacyMirror, subjectType: subjectClass, makeSuperclassMirror: { _getSuperclass(subjectClass).map { Mirror( subject, subjectClass: $0, ancestor: ancestor, legacy: legacyMirror._superMirror()) } }) } } internal init( legacy legacyMirror: _Mirror, subjectType: Any.Type, makeSuperclassMirror: (() -> Mirror?)? = nil ) { if let makeSuperclassMirror = makeSuperclassMirror { self._makeSuperclassMirror = makeSuperclassMirror } else if let subjectSuperclass = _getSuperclass(subjectType) { self._makeSuperclassMirror = { legacyMirror._superMirror().map { Mirror(legacy: $0, subjectType: subjectSuperclass) } } } else { self._makeSuperclassMirror = Mirror._noSuperclassMirror } self.subjectType = subjectType self.children = Children(LegacyChildren(legacyMirror)) self.displayStyle = DisplayStyle(legacy: legacyMirror.disposition) self._defaultDescendantRepresentation = .generated } } //===--- QuickLooks -------------------------------------------------------===// /// The sum of types that can be used as a Quick Look representation. public enum PlaygroundQuickLook { /// Plain text. case text(String) /// An integer numeric value. case int(Int64) /// An unsigned integer numeric value. case uInt(UInt64) /// A single precision floating-point numeric value. case float(Float32) /// A double precision floating-point numeric value. case double(Float64) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// An image. case image(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A sound. case sound(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A color. case color(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A bezier path. case bezierPath(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// An attributed string. case attributedString(Any) // FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type. /// A rectangle. case rectangle(Float64, Float64, Float64, Float64) // FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type. /// A point. case point(Float64, Float64) // FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type. /// A size. case size(Float64, Float64) /// A boolean value. case bool(Bool) // FIXME: Uses explicit values to avoid coupling a particular Cocoa type. /// A range. case range(Int64, Int64) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A GUI view. case view(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A graphical sprite. case sprite(Any) /// A Uniform Resource Locator. case url(String) /// Raw data that has already been encoded in a format the IDE understands. case _raw([UInt8], String) } extension PlaygroundQuickLook { /// Initialize for the given `subject`. /// /// If the dynamic type of `subject` conforms to /// `CustomPlaygroundQuickLookable`, returns the result of calling /// its `customPlaygroundQuickLook` property. Otherwise, returns /// a `PlaygroundQuickLook` synthesized for `subject` by the /// language. Note that in some cases the result may be /// `.Text(String(reflecting: subject))`. /// /// - Note: If the dynamic type of `subject` has value semantics, /// subsequent mutations of `subject` will not observable in /// `Mirror`. In general, though, the observability of such /// mutations is unspecified. public init(reflecting subject: Any) { if let customized = subject as? CustomPlaygroundQuickLookable { self = customized.customPlaygroundQuickLook } else if let customized = subject as? _DefaultCustomPlaygroundQuickLookable { self = customized._defaultCustomPlaygroundQuickLook } else { if let q = _reflect(subject).quickLookObject { self = q } else { self = .text(String(reflecting: subject)) } } } } /// A type that explicitly supplies its own playground Quick Look. /// /// A Quick Look can be created for an instance of any type by using the /// `PlaygroundQuickLook(reflecting:)` initializer. If you are not satisfied /// with the representation supplied for your type by default, you can make it /// conform to the `CustomPlaygroundQuickLookable` protocol and provide a /// custom `PlaygroundQuickLook` instance. public protocol CustomPlaygroundQuickLookable { /// A custom playground Quick Look for this instance. /// /// If this type has value semantics, the `PlaygroundQuickLook` instance /// should be unaffected by subsequent mutations. var customPlaygroundQuickLook: PlaygroundQuickLook { get } } // A workaround for <rdar://problem/26182650> // FIXME(ABI)#50 (Dynamic Dispatch for Class Extensions) though not if it moves out of stdlib. public protocol _DefaultCustomPlaygroundQuickLookable { var _defaultCustomPlaygroundQuickLook: PlaygroundQuickLook { get } } //===--- General Utilities ------------------------------------------------===// // This component could stand alone, but is used in Mirror's public interface. /// A lightweight collection of key-value pairs. /// /// Use a `DictionaryLiteral` instance when you need an ordered collection of /// key-value pairs and don't require the fast key lookup that the /// `Dictionary` type provides. Unlike key-value pairs in a true dictionary, /// neither the key nor the value of a `DictionaryLiteral` instance must /// conform to the `Hashable` protocol. /// /// You initialize a `DictionaryLiteral` instance using a Swift dictionary /// literal. Besides maintaining the order of the original dictionary literal, /// `DictionaryLiteral` also allows duplicates keys. For example: /// /// let recordTimes: DictionaryLiteral = ["Florence Griffith-Joyner": 10.49, /// "Evelyn Ashford": 10.76, /// "Evelyn Ashford": 10.79, /// "Marlies Gohr": 10.81] /// print(recordTimes.first!) /// // Prints "("Florence Griffith-Joyner", 10.49)" /// /// Some operations that are efficient on a dictionary are slower when using /// `DictionaryLiteral`. In particular, to find the value matching a key, you /// must search through every element of the collection. The call to /// `index(where:)` in the following example must traverse the whole /// collection to make sure that no element matches the given predicate: /// /// let runner = "Marlies Gohr" /// if let index = recordTimes.index(where: { $0.0 == runner }) { /// let time = recordTimes[index].1 /// print("\(runner) set a 100m record of \(time) seconds.") /// } else { /// print("\(runner) couldn't be found in the records.") /// } /// // Prints "Marlies Gohr set a 100m record of 10.81 seconds." /// /// Dictionary Literals as Function Parameters /// ------------------------------------------ /// /// When calling a function with a `DictionaryLiteral` parameter, you can pass /// a Swift dictionary literal without causing a `Dictionary` to be created. /// This capability can be especially important when the order of elements in /// the literal is significant. /// /// For example, you could create an `IntPairs` structure that holds a list of /// two-integer tuples and use an initializer that accepts a /// `DictionaryLiteral` instance. /// /// struct IntPairs { /// var elements: [(Int, Int)] /// /// init(_ elements: DictionaryLiteral<Int, Int>) { /// self.elements = Array(elements) /// } /// } /// /// When you're ready to create a new `IntPairs` instance, use a dictionary /// literal as the parameter to the `IntPairs` initializer. The /// `DictionaryLiteral` instance preserves the order of the elements as /// passed. /// /// let pairs = IntPairs([1: 2, 1: 1, 3: 4, 2: 1]) /// print(pairs.elements) /// // Prints "[(1, 2), (1, 1), (3, 4), (2, 1)]" public struct DictionaryLiteral<Key, Value> : ExpressibleByDictionaryLiteral { /// Creates a new `DictionaryLiteral` instance from the given dictionary /// literal. /// /// The order of the key-value pairs is kept intact in the resulting /// `DictionaryLiteral` instance. public init(dictionaryLiteral elements: (Key, Value)...) { self._elements = elements } internal let _elements: [(Key, Value)] } /// `Collection` conformance that allows `DictionaryLiteral` to /// interoperate with the rest of the standard library. extension DictionaryLiteral : RandomAccessCollection { public typealias Indices = CountableRange<Int> /// The position of the first element in a nonempty collection. /// /// If the `DictionaryLiteral` instance is empty, `startIndex` is equal to /// `endIndex`. public var startIndex: Int { return 0 } /// The collection's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// If the `DictionaryLiteral` instance is empty, `endIndex` is equal to /// `startIndex`. public var endIndex: Int { return _elements.endIndex } // FIXME: a typealias is needed to prevent <rdar://20248032> /// The element type of a `DictionaryLiteral`: a tuple containing an /// individual key-value pair. public typealias Element = (key: Key, value: Value) /// Accesses the element at the specified position. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the collection that is not equal to the /// `endIndex` property. /// - Returns: The key-value pair at position `position`. public subscript(position: Int) -> Element { return _elements[position] } } extension String { /// Creates a string representing the given value. /// /// Use this initializer to convert an instance of any type to its preferred /// representation as a `String` instance. The initializer creates the /// string representation of `instance` in one of the following ways, /// depending on its protocol conformance: /// /// - If `instance` conforms to the `TextOutputStreamable` protocol, the /// result is obtained by calling `instance.write(to: s)` on an empty /// string `s`. /// - If `instance` conforms to the `CustomStringConvertible` protocol, the /// result is `instance.description`. /// - If `instance` conforms to the `CustomDebugStringConvertible` protocol, /// the result is `instance.debugDescription`. /// - An unspecified result is supplied automatically by the Swift standard /// library. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library. /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(describing: p)) /// // Prints "Point(x: 21, y: 30)" /// /// After adding `CustomStringConvertible` conformance by implementing the /// `description` property, `Point` provides its own custom representation. /// /// extension Point: CustomStringConvertible { /// var description: String { /// return "(\(x), \(y))" /// } /// } /// /// print(String(describing: p)) /// // Prints "(21, 30)" /// /// - SeeAlso: `String.init<Subject>(reflecting: Subject)` public init<Subject>(describing instance: Subject) { self.init() _print_unlocked(instance, &self) } /// Creates a string with a detailed representation of the given value, /// suitable for debugging. /// /// Use this initializer to convert an instance of any type to its custom /// debugging representation. The initializer creates the string /// representation of `instance` in one of the following ways, depending on /// its protocol conformance: /// /// - If `subject` conforms to the `CustomDebugStringConvertible` protocol, /// the result is `subject.debugDescription`. /// - If `subject` conforms to the `CustomStringConvertible` protocol, the /// result is `subject.description`. /// - If `subject` conforms to the `TextOutputStreamable` protocol, the /// result is obtained by calling `subject.write(to: s)` on an empty /// string `s`. /// - An unspecified result is supplied automatically by the Swift standard /// library. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library. /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(reflecting: p)) /// // Prints "p: Point = { /// // x = 21 /// // y = 30 /// // }" /// /// After adding `CustomDebugStringConvertible` conformance by implementing /// the `debugDescription` property, `Point` provides its own custom /// debugging representation. /// /// extension Point: CustomDebugStringConvertible { /// var debugDescription: String { /// return "Point(x: \(x), y: \(y))" /// } /// } /// /// print(String(reflecting: p)) /// // Prints "Point(x: 21, y: 30)" /// /// - SeeAlso: `String.init<Subject>(Subject)` public init<Subject>(reflecting subject: Subject) { self.init() _debugPrint_unlocked(subject, &self) } } /// Reflection for `Mirror` itself. extension Mirror : CustomStringConvertible { public var description: String { return "Mirror for \(self.subjectType)" } } extension Mirror : CustomReflectable { public var customMirror: Mirror { return Mirror(self, children: [:]) } } @available(*, unavailable, renamed: "MirrorPath") public typealias MirrorPathType = MirrorPath
apache-2.0
2a8e82d32d06f525bbe0fc790c0c03e9
36.478398
106
0.663227
4.690979
false
false
false
false
fumitoito/yak
Pod/Classes/UIViewController+loadViewFromNib.swift
1
1804
// // UIViewController+loadViewFromNib.swift // Pods // // Created by fumitoito on 2016/02/03. // // import Foundation import UIKit extension UIViewController { /** Return own class name as String If class name is nested (e.g. foo.bar.hoge), this method will return just only last class name (e.g. hoge). - returns: Own class name */ private func getSelfClassName() -> String { let className = String(self.dynamicType) if let range = className.rangeOfString(".") { return className.substringFromIndex(range.endIndex) } return className } /** Find and load Xib that has same name as this ViewController's class name. - throws: `yakError_ViewController.CanNotGenerateUIViewFromNibName` if failed to generate UIView class from applied name. */ public func yak_loadViewFromNib() throws { let className = getSelfClassName() try yak_loadViewFromNib(className) } /** Find and load Xib as this ViewController's view. - parameter nibName: Xib's name for load - parameter nibBundle: NSBundle for nib - parameter optionsToInstantinateNib: options for instantinate nib - throws: `yakError_ViewController.CanNotGenerateUIViewFromNibName` if failed to generate UIView class from applied name. */ public func yak_loadViewFromNib(nibName: String, nibBundle: NSBundle? = nil, optionsToInstantinateNib: [NSObject : AnyObject]? = nil) throws { if let view = UINib(nibName: nibName, bundle: nibBundle) .instantiateWithOwner(self, options: optionsToInstantinateNib).first as? UIView { self.view = view } else { throw YakError.CanNotGenerateUIViewFromNibName } } }
mit
e2afbab3571a56b495974d030c3db7c9
29.066667
93
0.665743
4.532663
false
false
false
false
wburhan2/TicTacToe
tictactoe/ViewController.swift
1
1926
// // ViewController.swift // tictactoe // // Created by Wilson Burhan on 10/17/14. // Copyright (c) 2014 Wilson Burhan. All rights reserved. // import UIKit import MultipeerConnectivity class ViewController: UIViewController, MCBrowserViewControllerDelegate { @IBOutlet var fields: [TTTImageView]! var appDelegate:AppDelegate! override func viewDidLoad() { super.viewDidLoad() appDelegate = UIApplication.sharedApplication().delegate as AppDelegate appDelegate.mpcHandler.setupPeerWithDisplayNames(UIDevice.currentDevice().name) appDelegate.mpcHandler.setupSession() appDelegate.mpcHandler.advertiseSelf(true) } @IBAction func connectWithPlayer (sender: AnyObject){ if appDelegate.mpcHandler.session != nil { appDelegate.mpcHandler.setupBroser() appDelegate.mpcHandler.browser.delegate = self self.presentViewController(appDelegate.mpcHandler.browser, animated: true, completion: nil) } } func setupGameLogic(){ for index in 0...fields.count - 1 { let gestureRecognizer = UITapGestureRecognizer(target: self, action: "fieldTapped") gestureRecognizer.numberOfTapsRequired = 1 fields[index].addGestureRecognizer(gestureRecognizer) } } func browserViewControllerDidFinish(browserViewController: MCBrowserViewController!) { appDelegate.mpcHandler.browser.dismissViewControllerAnimated(true, completion: nil) } func browserViewControllerWasCancelled(browserViewController: MCBrowserViewController!) { appDelegate.mpcHandler.browser.dismissViewControllerAnimated(true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
8838820edb9067ddf87126750c2115f8
30.064516
103
0.692108
5.487179
false
false
false
false
ruilin/RLMap
iphone/Maps/UI/PlacePage/PlacePageLayout/Content/TaxiCell/PlacePageTaxiCell.swift
1
1397
@objc(MWMPlacePageTaxiCell) final class PlacePageTaxiCell: MWMTableViewCell { @IBOutlet private weak var icon: UIImageView! @IBOutlet private weak var title: UILabel! { didSet { title.font = UIFont.bold14() title.textColor = UIColor.blackPrimaryText() } } @IBOutlet private weak var orderButton: UIButton! { didSet { let l = orderButton.layer l.cornerRadius = 6 l.borderColor = UIColor.linkBlue().cgColor l.borderWidth = 1 orderButton.setTitle(L("taxi_order"), for: .normal) orderButton.setTitleColor(UIColor.white, for: .normal) orderButton.titleLabel?.font = UIFont.bold14() orderButton.backgroundColor = UIColor.linkBlue() } } private weak var delegate: MWMPlacePageButtonsProtocol! private var type: MWMPlacePageTaxiProvider! func config(type: MWMPlacePageTaxiProvider, delegate: MWMPlacePageButtonsProtocol) { self.delegate = delegate self.type = type switch type { case .taxi: icon.image = #imageLiteral(resourceName: "icTaxiTaxi") title.text = L("taxi") case .uber: icon.image = #imageLiteral(resourceName: "icTaxiUber") title.text = L("taxi_uber") case .yandex: icon.image = #imageLiteral(resourceName: "icTaxiYandex") title.text = L("yandex_taxi_title") } } @IBAction func orderAction() { delegate.orderTaxi(type) } }
apache-2.0
992592ff897020bb2e479183dd8bce0c
29.369565
86
0.680744
4.170149
false
false
false
false
nodekit-io/nodekit-darwin
src/nodekit/NKScripting/NKScriptContextFactory.swift
1
2196
/* * nodekit.io * * Copyright (c) 2016 OffGrid Networks. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation public enum NKEngineType: Int { case JavaScriptCore = 0 case Nitro = 1 case UIWebView = 2 } public class NKScriptContextFactory: NSObject { internal static var _contexts: Dictionary<Int, AnyObject> = Dictionary<Int, AnyObject>() public class var sequenceNumber: Int { struct sequence { static var number: Int = 0 } let temp = sequence.number sequence.number += 1 return temp } public func createScriptContext(options: [String: AnyObject] = Dictionary<String, AnyObject>(), delegate cb: NKScriptContextDelegate) { let engine = NKEngineType(rawValue: (options["Engine"] as? Int)!) ?? NKEngineType.JavaScriptCore switch engine { case .JavaScriptCore: self.createContextJavaScriptCore(options, delegate: cb) case .Nitro: self.createContextWKWebView(options, delegate: cb) case .UIWebView: self.createContextUIWebView(options, delegate: cb) } } public static var defaultQueue: dispatch_queue_t = { let label = "io.nodekit.scripting.default-queue" return dispatch_queue_create(label, DISPATCH_QUEUE_SERIAL) }() } public protocol NKScriptContextHost: class { func NKcreateScriptContext(id: Int, options: [String: AnyObject], delegate cb: NKScriptContextDelegate) -> Void }
apache-2.0
5fcdd3283639fcb1ffb3be42ca18384b
23.954545
139
0.636612
4.722581
false
false
false
false
jekahy/Grocr
Grocr/LoginVC.swift
1
6133
/* * Copyright (c) 2015 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import FirebaseAuth import SwiftValidator class LoginVC: UIViewController, Validatable, EasyAlert { fileprivate typealias EmptyClosure = ()->() // MARK: Constants fileprivate let loginToList = "LoginToList" fileprivate let validationFailedMess = "It looks like something is wrong with the input data. Here what we've found: " fileprivate let willCheckTitle = "OK, I'll check it out" let validator = Validator() // MARK: Outlets @IBOutlet weak var textFieldLoginEmail: TextField! @IBOutlet weak var textFieldLoginPassword: TextField! enum ValidationRules { case email case password case confirmation(UITextField) func rules() -> [Rule] { switch self { case .email: return [RequiredRule(message: "email is missing"), EmailRule(message: "email is invalid")] case .password: return [RequiredRule(message: "password is missing"), MinLengthRule(length:6, message: "password is too short")] case .confirmation(let passTF): return [ConfirmationRule(confirmField: passTF, message:"passwords don't match")] } } } //MARK: Methods override func viewDidLoad() { super.viewDidLoad() addAuthListener() setupValidator() } fileprivate func addAuthListener() { Auth.auth().addStateDidChangeListener() { auth, user in if user != nil { self.performSegue(withIdentifier: self.loginToList, sender: nil) } } } func setupValidator() { validator.styleTransformers(success: { validationRule in if let tf = validationRule.field as? TextField { tf.removeErrorHighlight() } }) { validationError in if let tf = validationError.field as? TextField { tf.highlightError() } } validator.registerField(textFieldLoginEmail, rules: .email) validator.registerField(textFieldLoginPassword, rules: .password) } // MARK: Actions @IBAction func loginDidTouch(_ sender: AnyObject) { validateFields {[weak self] in if let strSelf = self{ Auth.auth().signIn(withEmail: strSelf.textFieldLoginEmail.text!, password: strSelf.textFieldLoginPassword.text!) } } } @IBAction func signUpDidTouch(_ sender: AnyObject) { validateFields {[weak self] in if let alert = self?.signUpAlert(){ self?.present(alert, animated: true, completion: nil) } } } //MARK: Methods fileprivate func validateFields(success:@escaping EmptyClosure) { validator.validate {[unowned self] errors in if errors.count > 0 { let issues = errors.map{ $1.errorMessage}.joined(separator: ", ") let finalMess = self.validationFailedMess + "\(issues)." self.showAlert("Hey", message: finalMess, alertActions: [.okWithTitle(self.willCheckTitle)]) }else{ success() } } } fileprivate func signUpAlert()->UIAlertController { let alert = UIAlertController(title: "Register", message: "Register", preferredStyle: .alert) let saveAction = UIAlertAction(title: "Save", style: .default) {[weak self] action in guard let confTF = alert.textFields?[0], let strSelf = self else { return } strSelf.validator.registerField(confTF, rules:.confirmation(strSelf.textFieldLoginPassword)) strSelf.validator.validateField(confTF, callback: { error in if let error = error { let finalMess = strSelf.validationFailedMess + "\(error.errorMessage)." strSelf.showAlert("Hey", message: finalMess, alertActions: [.okWithTitle(strSelf.willCheckTitle)]) strSelf.validator.unregisterField(confTF) }else{ Auth.auth().createUser(withEmail: strSelf.textFieldLoginEmail.text!, password: confTF.text!) { user, error in if error == nil { Auth.auth().signIn(withEmail: strSelf.textFieldLoginEmail.text!, password: strSelf.textFieldLoginPassword.text!) }else{ strSelf.showAlert("OOpss", message: "Something went wrong :/ (\(error!.localizedDescription)).", alertActions: [.ok]) } } } }) } alert.addTextField { textPassword in textPassword.isSecureTextEntry = true textPassword.placeholder = "Password confirmation" } alert.addAction(saveAction) alert.addAction(.cancel) return alert } } extension LoginVC: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { guard let tf = textField as? TextField else{ return true } if let next = tf.nextResp{ next.becomeFirstResponder() }else{ tf.resignFirstResponder() } return true } }
mit
70771a6e2ac2495e345099bc721b6473
29.665
131
0.647481
4.685256
false
false
false
false
richterd/BirthdayGroupReminder
BirthdayGroupReminder/BGRStorage.swift
1
1146
// // BGRStorage.swift // BirthdayGroupReminder // // Created by Daniel Richter on 13.07.14. // Copyright (c) 2014 Daniel Richter. All rights reserved. // import UIKit class BGRStorage: NSObject { func loadFromFile() -> [ABRecordID]{ var selectedGroups : [ABRecordID] = [] selectedGroups.removeAll(keepingCapacity: true) let stored : AnyObject? = UserDefaults.standard.object(forKey: "selectedGroups") as AnyObject? if (stored != nil){ let theArray = stored as! [NSNumber] for id in theArray{ selectedGroups.append(id.int32Value as ABRecordID) } } return selectedGroups } func saveToFile(_ selectedGroups : [ABRecordID]){ var preStoreGroups : [NSNumber] = [] for groupID in selectedGroups{ let value : NSNumber = NSNumber(value: groupID as Int32) preStoreGroups.append(value) } UserDefaults.standard.removeObject(forKey: "selectedGroups") UserDefaults.standard.set(preStoreGroups, forKey: "selectedGroups") UserDefaults.standard.synchronize() } }
gpl-2.0
3161f0045d7d7e9fc003d5efc8b73830
31.742857
102
0.635253
4.529644
false
false
false
false
spacedrabbit/100-days
One00Days/One00Days/BackgroundView.swift
1
2672
// // BackgroundView.swift // One00Days // // Created by Louis Tur on 4/30/16. // Copyright © 2016 SRLabs. All rights reserved. // import UIKit import SnapKit internal enum SceneTimeOfDay { case morning case afternoon case evening } internal struct SceneColor { internal struct Sky { internal static let Afternoon: UIColor = UIColor(red: 179.0/255.0, green: 229.0/255.0, blue: 252.0/255.0, alpha: 1.0) } internal struct Ground { internal static let Afternoon: UIColor = UIColor(red: 66.0/255.0, green: 133.0/255.0, blue: 244.0/255.0, alpha: 1.0) } } internal class BackgroundView: UIView { // MARK: - Variables // ------------------------------------------------------------ internal var groundColor: UIColor! internal var skyColor: UIColor! // MARK: - Inits // ------------------------------------------------------------ convenience init(forTimeOfDay timeOfDay: SceneTimeOfDay) { self.init(frame: CGRect.zero) self.updateSceneForTimeOfDay(timeOfDay) } override init(frame: CGRect) { super.init(frame: frame) self.setupViewHierarchy() self.configureConstraints() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Helpers // ------------------------------------------------------------ internal func updateSceneForTimeOfDay(_ timeOfDay: SceneTimeOfDay) { switch timeOfDay { case .morning: print("not implemented") case .afternoon: self.skyColor = SceneColor.Sky.Afternoon self.groundColor = SceneColor.Ground.Afternoon case .evening: print("not implemented") } DispatchQueue.main.async { () -> Void in self.skyView.backgroundColor = self.skyColor self.groundView.backgroundColor = self.groundColor } } // MARK: - Layout // ------------------------------------------------------------ internal func configureConstraints() { self.skyView.snp.makeConstraints { (make) -> Void in make.edges.equalTo(self) } self.groundView.snp.makeConstraints { (make) -> Void in make.left.right.bottom.equalTo(self) make.height.equalTo(60.0) } } internal func setupViewHierarchy() { self.addSubviews([skyView, groundView]) } // MARK: - Lazy Inits // ------------------------------------------------------------ lazy var skyView: UIView = { let view: UIView = UIView() view.backgroundColor = SceneColor.Sky.Afternoon return view }() lazy var groundView: UIView = { let view: UIView = UIView() view.backgroundColor = SceneColor.Ground.Afternoon return view }() }
mit
e9c9af8dfa630187450922569483bc40
22.848214
121
0.582179
4.253185
false
false
false
false
huangxinping/XPKit-swift
Source/Extensions/UIKit/UIView+XPKit.swift
1
17943
// // UIView+XPKit.swift // XPKit // // The MIT License (MIT) // // Copyright (c) 2015 - 2016 Fabrizio Brancati. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import UIKit import QuartzCore /// This extesion adds some useful functions to UIView public extension UIView { // MARK: - Variables - /** Return belong viewcontroller - returns: The UIViewController instance */ var belongViewController: UIViewController? { var parentResponder: UIResponder? = self while parentResponder != nil { parentResponder = parentResponder!.nextResponder() if let viewController = parentResponder as? UIViewController { return viewController } } return nil } public var origin: CGPoint { get { return self.frame.origin } set { self.frame = ccr(newValue.x, y: newValue.y, width: self.width, height: self.height) } } public var size: CGSize { get { return self.frame.size } set { let oldOrigin = self.frame.origin self.frame = ccr(oldOrigin.x, y: oldOrigin.y, width: newValue.width, height: newValue.height) } } public var left: CGFloat { get { return CGRectGetMinX(self.frame) } set { var oldFrame = self.frame oldFrame.origin.x = newValue self.frame = oldFrame } } public var right: CGFloat { get { return CGRectGetMaxX(self.frame) } set { var oldFrame = self.frame oldFrame.origin.x = newValue - frame.size.width self.frame = oldFrame } } public var top: CGFloat { get { return CGRectGetMinY(self.frame); } set { var oldFrame = self.frame oldFrame.origin.y = newValue self.frame = oldFrame } } public var bottom: CGFloat { get { return CGRectGetMaxY(self.frame); } set { var oldFrame = self.frame oldFrame.origin.y = newValue - frame.size.height self.frame = oldFrame } } public var centerX: CGFloat { get { return self.center.x; } set { self.center = ccp(newValue, y: self.centerY) } } public var centerY: CGFloat { get { return self.center.y } set { self.center = ccp(self.centerX, y: newValue) } } public var width: CGFloat { get { return CGRectGetWidth(self.frame) } set { var oldFrame = self.frame oldFrame.size.width = newValue self.frame = CGRectStandardize(oldFrame) } } public var height: CGFloat { get { return CGRectGetHeight(self.frame) } set { var oldFrame = self.frame oldFrame.size.height = newValue self.frame = CGRectStandardize(oldFrame) } } public var isInFront: Bool { get { return self.superview?.subviews.last == self ? true : false } } public var isAtBack: Bool { get { return self.superview?.subviews[0] == self ? true : false } } // MARK: - Enums - /** Direction of flip animation - FromTop: Flip animation from top - FromLeft: Flip animation from left - FromRight: Flip animation from right - FromBottom: Flip animation from bottom */ public enum UIViewAnimationFlipDirection: Int { case FromTop case FromLeft case FromRight case FromBottom } /** Direction of the translation - FromLeftToRight: Translation from left to right - FromRightToLeft: Translation from right to left */ public enum UIViewAnimationTranslationDirection: Int { case FromLeftToRight case FromRightToLeft } /** Direction of the linear gradient - Vertical: Linear gradient vertical - Horizontal: Linear gradient horizontal - DiagonalFromLeftToRightAndTopToDown: Linear gradient from left to right and top to down - DiagonalFromLeftToRightAndDownToTop: Linear gradient from left to right and down to top - DiagonalFromRightToLeftAndTopToDown: Linear gradient from right to left and top to down - DiagonalFromRightToLeftAndDownToTop: Linear gradient from right to left and down to top */ public enum UIViewLinearGradientDirection: Int { case Vertical case Horizontal case DiagonalFromLeftToRightAndTopToDown case DiagonalFromLeftToRightAndDownToTop case DiagonalFromRightToLeftAndTopToDown case DiagonalFromRightToLeftAndDownToTop } // MARK: - Instance functions - /** Create a border around the UIView - parameter color: Border's color - parameter radius: Border's radius - parameter width: Border's width */ public func createBordersWithColor(color: UIColor, radius: CGFloat, width: CGFloat) { self.layer.borderWidth = width self.layer.cornerRadius = radius self.layer.shouldRasterize = false self.layer.rasterizationScale = 2 self.clipsToBounds = true self.layer.masksToBounds = true let cgColor: CGColorRef = color.CGColor self.layer.borderColor = cgColor } /** Remove the borders around the UIView */ public func removeBorders() { self.layer.borderWidth = 0 self.layer.cornerRadius = 0 self.layer.borderColor = nil } /** Remove the shadow around the UIView */ public func removeShadow() { self.layer.shadowColor = UIColor.clearColor().CGColor self.layer.shadowOpacity = 0.0 self.layer.shadowOffset = CGSizeMake(0.0, 0.0) } /** Set the corner radius of UIView - parameter radius: Radius value */ public func setCornerRadius(radius: CGFloat) { self.layer.cornerRadius = radius self.layer.masksToBounds = true } /** Create a shadow on the UIView - parameter offset: Shadow's offset - parameter opacity: Shadow's opacity - parameter radius: Shadow's radius */ public func createRectShadowWithOffset(offset: CGSize, opacity: Float, radius: CGFloat) { self.layer.shadowColor = UIColor.blackColor().CGColor self.layer.shadowOpacity = opacity self.layer.shadowOffset = offset self.layer.shadowRadius = radius self.layer.masksToBounds = false } /** Create a corner radius shadow on the UIView - parameter cornerRadius: Corner radius value - parameter offset: Shadow's offset - parameter opacity: Shadow's opacity - parameter radius: Shadow's radius */ public func createCornerRadiusShadowWithCornerRadius(cornerRadius: CGFloat, offset: CGSize, opacity: Float, radius: CGFloat) { self.layer.shadowColor = UIColor.blackColor().CGColor self.layer.shadowOpacity = opacity self.layer.shadowOffset = offset self.layer.shadowRadius = radius self.layer.shouldRasterize = true self.layer.cornerRadius = cornerRadius self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: cornerRadius).CGPath self.layer.masksToBounds = false } /** Create a linear gradient - parameter colors: Array of UIColor instances - parameter direction: Direction of the gradient */ public func createGradientWithColors(colors: Array<UIColor>, direction: UIViewLinearGradientDirection) { let gradient: CAGradientLayer = CAGradientLayer() gradient.frame = self.bounds let mutableColors: NSMutableArray = NSMutableArray(array: colors) for i in 0 ..< colors.count { let currentColor: UIColor = colors[i] mutableColors.replaceObjectAtIndex(i, withObject: currentColor.CGColor) } gradient.colors = mutableColors as AnyObject as! Array<UIColor> switch direction { case .Vertical: gradient.startPoint = CGPointMake(0.5, 0.0) gradient.endPoint = CGPointMake(0.5, 1.0) case .Horizontal: gradient.startPoint = CGPointMake(0.0, 0.5) gradient.endPoint = CGPointMake(1.0, 0.5) case .DiagonalFromLeftToRightAndTopToDown: gradient.startPoint = CGPointMake(0.0, 0.0) gradient.endPoint = CGPointMake(1.0, 1.0) case .DiagonalFromLeftToRightAndDownToTop: gradient.startPoint = CGPointMake(0.0, 1.0) gradient.endPoint = CGPointMake(1.0, 0.0) case .DiagonalFromRightToLeftAndTopToDown: gradient.startPoint = CGPointMake(1.0, 0.0) gradient.endPoint = CGPointMake(0.0, 1.0) case .DiagonalFromRightToLeftAndDownToTop: gradient.startPoint = CGPointMake(1.0, 1.0) gradient.endPoint = CGPointMake(0.0, 0.0) } self.layer.insertSublayer(gradient, atIndex: 0) } /** Create a shake effect on the UIView */ public func shakeView() { let shake: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform") shake.values = [NSValue(CATransform3D: CATransform3DMakeTranslation(-5.0, 0.0, 0.0)), NSValue(CATransform3D: CATransform3DMakeTranslation(5.0, 0.0, 0.0))] shake.autoreverses = true shake.repeatCount = 2.0 shake.duration = 0.07 self.layer.addAnimation(shake, forKey: "shake") } /** Create a pulse effect on th UIView - parameter duration: Seconds of animation */ public func pulseViewWithDuration(duration: CGFloat) { UIView.animateWithDuration(NSTimeInterval(duration / 6), animations: { () -> Void in self.transform = CGAffineTransformMakeScale(1.1, 1.1) }) { (finished) -> Void in if finished { UIView.animateWithDuration(NSTimeInterval(duration / 6), animations: { () -> Void in self.transform = CGAffineTransformMakeScale(0.96, 0.96) }) { (finished: Bool) -> Void in if finished { UIView.animateWithDuration(NSTimeInterval(duration / 6), animations: { () -> Void in self.transform = CGAffineTransformMakeScale(1.03, 1.03) }) { (finished: Bool) -> Void in if finished { UIView.animateWithDuration(NSTimeInterval(duration / 6), animations: { () -> Void in self.transform = CGAffineTransformMakeScale(0.985, 0.985) }) { (finished: Bool) -> Void in if finished { UIView.animateWithDuration(NSTimeInterval(duration / 6), animations: { () -> Void in self.transform = CGAffineTransformMakeScale(1.007, 1.007) }) { (finished: Bool) -> Void in if finished { UIView.animateWithDuration(NSTimeInterval(duration / 6), animations: { () -> Void in self.transform = CGAffineTransformMakeScale(1, 1) }) } } } } } } } } } } } /** Create a heartbeat effect on the UIView - parameter duration: Seconds of animation */ public func heartbeatViewWithDuration(duration: CGFloat) { let maxSize: CGFloat = 1.4, durationPerBeat: CGFloat = 0.5 let animation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform") let scale1: CATransform3D = CATransform3DMakeScale(0.8, 0.8, 1) let scale2: CATransform3D = CATransform3DMakeScale(maxSize, maxSize, 1) let scale3: CATransform3D = CATransform3DMakeScale(maxSize - 0.3, maxSize - 0.3, 1) let scale4: CATransform3D = CATransform3DMakeScale(1.0, 1.0, 1) let frameValues: Array = [NSValue(CATransform3D: scale1), NSValue(CATransform3D: scale2), NSValue(CATransform3D: scale3), NSValue(CATransform3D: scale4)] animation.values = frameValues let frameTimes: Array = [NSNumber(float: 0.05), NSNumber(float: 0.2), NSNumber(float: 0.6), NSNumber(float: 1.0)] animation.keyTimes = frameTimes animation.fillMode = kCAFillModeForwards animation.duration = NSTimeInterval(durationPerBeat) animation.repeatCount = Float(duration / durationPerBeat) self.layer.addAnimation(animation, forKey: "heartbeat") } /** Adds a motion effect to the view */ public func applyMotionEffects() { let horizontalEffect: UIInterpolatingMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type: .TiltAlongHorizontalAxis) horizontalEffect.minimumRelativeValue = -10.0 horizontalEffect.maximumRelativeValue = 10.0 let verticalEffect: UIInterpolatingMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.y", type: .TiltAlongVerticalAxis) verticalEffect.minimumRelativeValue = -10.0 verticalEffect.maximumRelativeValue = 10.0 let motionEffectGroup: UIMotionEffectGroup = UIMotionEffectGroup() motionEffectGroup.motionEffects = [horizontalEffect, verticalEffect] self.addMotionEffect(motionEffectGroup) } /** Flip the view - parameter duration: Seconds of animation - parameter direction: Direction of the flip animation */ public func flipWithDuration(duration: NSTimeInterval, direction: UIViewAnimationFlipDirection) { var subtype: String = "" switch (direction) { case .FromTop: subtype = "fromTop" case .FromLeft: subtype = "fromLeft" case .FromBottom: subtype = "fromBottom" case .FromRight: subtype = "fromRight" } let transition: CATransition = CATransition() transition.startProgress = 0 transition.endProgress = 1.0 transition.type = "flip" transition.subtype = subtype transition.duration = duration transition.repeatCount = 1 transition.autoreverses = true self.layer.addAnimation(transition, forKey: "flip") } /** Translate the UIView around the topView - parameter topView: Top view to translate to - parameter duration: Duration of the translation - parameter direction: Direction of the translation - parameter repeatAnimation: If the animation must be repeat or no - parameter startFromEdge: If the animation must start from the edge */ public func translateAroundTheView(topView: UIView, duration: CGFloat, direction: UIViewAnimationTranslationDirection, repeatAnimation: Bool = true, startFromEdge: Bool = true) { var startPosition: CGFloat = self.center.x, endPosition: CGFloat switch (direction) { case .FromLeftToRight: startPosition = self.frame.size.width / 2 endPosition = -(self.frame.size.width / 2) + topView.frame.size.width case .FromRightToLeft: startPosition = -(self.frame.size.width / 2) + topView.frame.size.width endPosition = self.frame.size.width / 2 } if startFromEdge { self.center = CGPointMake(startPosition, self.center.y) } UIView.animateWithDuration(NSTimeInterval(duration / 2), delay: 1, options: .CurveEaseInOut, animations: { () -> Void in self.center = CGPointMake(endPosition, self.center.y) }) { (finished: Bool) -> Void in if finished { UIView.animateWithDuration(NSTimeInterval(duration / 2), delay: 1, options: .CurveEaseInOut, animations: { () -> Void in self.center = CGPointMake(startPosition, self.center.y) }) { (finished: Bool) -> Void in if finished { if repeatAnimation { self.translateAroundTheView(topView, duration: duration, direction: direction, repeatAnimation: repeatAnimation, startFromEdge: startFromEdge) } } } } } } /** Take a screenshot of the current view - returns: Returns screenshot as UIImage */ public func screenshot() -> UIImage { UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.mainScreen().scale) self.drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true) var image: UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let imageData: NSData = UIImagePNGRepresentation(image)! image = UIImage(data: imageData)! return image } /** Take a screenshot of the current view an saving to the saved photos album - returns: Returns screenshot as UIImage */ public func saveScreenshot() -> UIImage { let image: UIImage = self.screenshot() UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) return image } /** Removes all subviews from current view */ public func removeAllSubviews() { self.subviews.forEach { (subview) -> () in subview.removeFromSuperview() } } /** Bring to front */ public func bringToFront() { self.superview?.bringSubviewToFront(self) } /** Send to back */ public func sendToBack() { self.superview?.sendSubviewToBack(self) } /** upgrade it one level */ public func bringOneLevelUp() { let currentIndex = self.superview!.subviews.indexOf(self) self.superview?.exchangeSubviewAtIndex(currentIndex!, withSubviewAtIndex: currentIndex! + 1) } /** downgrade it one level */ public func sendOneLevelDown() { let currentIndex = self.superview!.subviews.indexOf(self) self.superview?.exchangeSubviewAtIndex(currentIndex!, withSubviewAtIndex: currentIndex! - 1) } // MARK: - Class functions - /** Create an UIView from Nib file - returns: The UIView instance */ public class func viewFromNib() -> UIView? { let wSelf = self; var className = NSStringFromClass(self) let components = className.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: ".")) className = components.last! let nib = UINib(nibName: className, bundle: NSBundle(forClass: self)) var array = nib.instantiateWithOwner(nib, options: nil) array = array.filter { evaluatedObject -> Bool in return evaluatedObject.isKindOfClass(wSelf) } return array.last as? UIView } // MARK: - Init functions - /** Create an UIView with the given frame and background color - parameter frame: UIView's frame - parameter backgroundColor: UIView's background color - returns: Returns the created UIView */ public convenience init(frame: CGRect, backgroundColor: UIColor) { self.init(frame: frame) self.backgroundColor = backgroundColor } }
mit
54968ab2454ceee49f256230c071a47d
28.270799
179
0.716547
3.868693
false
false
false
false
hyperoslo/Sync
iOSDemo/Carthage/Build/iOS/Sync.framework/Headers/DataStack.swift
1
22739
import Foundation import CoreData @objc public enum DataStackStoreType: Int { case inMemory, sqLite var type: String { switch self { case .inMemory: return NSInMemoryStoreType case .sqLite: return NSSQLiteStoreType } } } @objc public class DataStack: NSObject { private var storeType = DataStackStoreType.sqLite private var storeName: String? private var modelName = "" private var modelBundle = Bundle.main private var model: NSManagedObjectModel private var containerURL = FileManager.sqliteDirectoryURL private let backgroundContextName = "DataStack.backgroundContextName" /** The context for the main queue. Please do not use this to mutate data, use `performInNewBackgroundContext` instead. */ @objc public lazy var mainContext: NSManagedObjectContext = { let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) context.undoManager = nil context.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy context.persistentStoreCoordinator = self.persistentStoreCoordinator NotificationCenter.default.addObserver(self, selector: #selector(DataStack.mainContextDidSave(_:)), name: .NSManagedObjectContextDidSave, object: context) return context }() /** The context for the main queue. Please do not use this to mutate data, use `performBackgroundTask` instead. */ @objc public var viewContext: NSManagedObjectContext { return self.mainContext } private lazy var writerContext: NSManagedObjectContext = { let context = NSManagedObjectContext(concurrencyType: DataStack.backgroundConcurrencyType()) context.undoManager = nil context.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy context.persistentStoreCoordinator = self.persistentStoreCoordinator return context }() @objc public private(set) lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.model) try! persistentStoreCoordinator.addPersistentStore(storeType: self.storeType, bundle: self.modelBundle, modelName: self.modelName, storeName: self.storeName, containerURL: self.containerURL) return persistentStoreCoordinator }() private lazy var disposablePersistentStoreCoordinator: NSPersistentStoreCoordinator = { let model = NSManagedObjectModel(bundle: self.modelBundle, name: self.modelName) let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model) try! persistentStoreCoordinator.addPersistentStore(storeType: .inMemory, bundle: self.modelBundle, modelName: self.modelName, storeName: self.storeName, containerURL: self.containerURL) return persistentStoreCoordinator }() /** Initializes a DataStack using the bundle name as the model name, so if your target is called ModernApp, it will look for a ModernApp.xcdatamodeld. */ @objc public override init() { let bundle = Bundle.main if let bundleName = bundle.infoDictionary?["CFBundleName"] as? String { self.modelName = bundleName } self.model = NSManagedObjectModel(bundle: self.modelBundle, name: self.modelName) super.init() } /** Initializes a DataStack using the provided model name. - parameter modelName: The name of your Core Data model (xcdatamodeld). */ @objc public init(modelName: String) { self.modelName = modelName self.model = NSManagedObjectModel(bundle: self.modelBundle, name: self.modelName) super.init() } /** Initializes a DataStack using the provided model name, bundle and storeType. - parameter modelName: The name of your Core Data model (xcdatamodeld). - parameter storeType: The store type to be used, you have .InMemory and .SQLite, the first one is memory based and doesn't save to disk, while the second one creates a .sqlite file and stores things there. */ @objc public init(modelName: String, storeType: DataStackStoreType) { self.modelName = modelName self.storeType = storeType self.model = NSManagedObjectModel(bundle: self.modelBundle, name: self.modelName) super.init() } /** Initializes a DataStack using the provided model name, bundle and storeType. - parameter modelName: The name of your Core Data model (xcdatamodeld). - parameter bundle: The bundle where your Core Data model is located, normally your Core Data model is in the main bundle but when using unit tests sometimes your Core Data model could be located where your tests are located. - parameter storeType: The store type to be used, you have .InMemory and .SQLite, the first one is memory based and doesn't save to disk, while the second one creates a .sqlite file and stores things there. */ @objc public init(modelName: String, bundle: Bundle, storeType: DataStackStoreType) { self.modelName = modelName self.modelBundle = bundle self.storeType = storeType self.model = NSManagedObjectModel(bundle: self.modelBundle, name: self.modelName) super.init() } /** Initializes a DataStack using the provided model name, bundle, storeType and store name. - parameter modelName: The name of your Core Data model (xcdatamodeld). - parameter bundle: The bundle where your Core Data model is located, normally your Core Data model is in the main bundle but when using unit tests sometimes your Core Data model could be located where your tests are located. - parameter storeType: The store type to be used, you have .InMemory and .SQLite, the first one is memory based and doesn't save to disk, while the second one creates a .sqlite file and stores things there. - parameter storeName: Normally your file would be named as your model name is named, so if your model name is AwesomeApp then the .sqlite file will be named AwesomeApp.sqlite, this attribute allows your to change that. */ @objc public init(modelName: String, bundle: Bundle, storeType: DataStackStoreType, storeName: String) { self.modelName = modelName self.modelBundle = bundle self.storeType = storeType self.storeName = storeName self.model = NSManagedObjectModel(bundle: self.modelBundle, name: self.modelName) super.init() } /** Initializes a DataStack using the provided model name, bundle, storeType and store name. - parameter modelName: The name of your Core Data model (xcdatamodeld). - parameter bundle: The bundle where your Core Data model is located, normally your Core Data model is in the main bundle but when using unit tests sometimes your Core Data model could be located where your tests are located. - parameter storeType: The store type to be used, you have .InMemory and .SQLite, the first one is memory based and doesn't save to disk, while the second one creates a .sqlite file and stores things there. - parameter storeName: Normally your file would be named as your model name is named, so if your model name is AwesomeApp then the .sqlite file will be named AwesomeApp.sqlite, this attribute allows your to change that. - parameter containerURL: The container URL for the sqlite file when a store type of SQLite is used. */ @objc public init(modelName: String, bundle: Bundle, storeType: DataStackStoreType, storeName: String, containerURL: URL) { self.modelName = modelName self.modelBundle = bundle self.storeType = storeType self.storeName = storeName self.containerURL = containerURL self.model = NSManagedObjectModel(bundle: self.modelBundle, name: self.modelName) super.init() } /** Initializes a DataStack using the provided model name, bundle and storeType. - parameter model: The model that we'll use to set up your DataStack. - parameter storeType: The store type to be used, you have .InMemory and .SQLite, the first one is memory based and doesn't save to disk, while the second one creates a .sqlite file and stores things there. */ @objc public init(model: NSManagedObjectModel, storeType: DataStackStoreType) { self.model = model self.storeType = storeType let bundle = Bundle.main if let bundleName = bundle.infoDictionary?["CFBundleName"] as? String { self.storeName = bundleName } super.init() } deinit { NotificationCenter.default.removeObserver(self, name: .NSManagedObjectContextWillSave, object: nil) NotificationCenter.default.removeObserver(self, name: .NSManagedObjectContextDidSave, object: nil) } /** Returns a new main context that is detached from saving to disk. */ @objc public func newDisposableMainContext() -> NSManagedObjectContext { let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) context.persistentStoreCoordinator = self.disposablePersistentStoreCoordinator context.undoManager = nil NotificationCenter.default.addObserver(self, selector: #selector(DataStack.newDisposableMainContextWillSave(_:)), name: NSNotification.Name.NSManagedObjectContextWillSave, object: context) return context } /** Returns a background context perfect for data mutability operations. Make sure to never use it on the main thread. Use `performBlock` or `performBlockAndWait` to use it. Saving to this context doesn't merge with the main thread. This context is specially useful to run operations that don't block the main thread. To refresh your main thread objects for example when using a NSFetchedResultsController use `try self.fetchedResultsController.performFetch()`. */ @objc public func newNonMergingBackgroundContext() -> NSManagedObjectContext { let context = NSManagedObjectContext(concurrencyType: DataStack.backgroundConcurrencyType()) context.persistentStoreCoordinator = self.persistentStoreCoordinator context.undoManager = nil context.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy return context } /** Returns a background context perfect for data mutability operations. Make sure to never use it on the main thread. Use `performBlock` or `performBlockAndWait` to use it. */ @objc public func newBackgroundContext() -> NSManagedObjectContext { let context = NSManagedObjectContext(concurrencyType: DataStack.backgroundConcurrencyType()) context.name = backgroundContextName context.persistentStoreCoordinator = self.persistentStoreCoordinator context.undoManager = nil context.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy NotificationCenter.default.addObserver(self, selector: #selector(DataStack.backgroundContextDidSave(_:)), name: .NSManagedObjectContextDidSave, object: context) return context } /** Returns a background context perfect for data mutability operations. - parameter operation: The block that contains the created background context. */ @objc public func performInNewBackgroundContext(_ operation: @escaping (_ backgroundContext: NSManagedObjectContext) -> Void) { let context = self.newBackgroundContext() let contextBlock: @convention(block) () -> Void = { operation(context) } let blockObject: AnyObject = unsafeBitCast(contextBlock, to: AnyObject.self) context.perform(DataStack.performSelectorForBackgroundContext(), with: blockObject) } /** Returns a background context perfect for data mutability operations. - parameter operation: The block that contains the created background context. */ @objc public func performBackgroundTask(operation: @escaping (_ backgroundContext: NSManagedObjectContext) -> Void) { self.performInNewBackgroundContext(operation) } func saveMainThread(completion: ((_ error: NSError?) -> Void)?) { var writerContextError: NSError? let writerContextBlock: @convention(block) () -> Void = { do { try self.writerContext.save() if TestCheck.isTesting { completion?(nil) } } catch let parentError as NSError { writerContextError = parentError } } let writerContextBlockObject: AnyObject = unsafeBitCast(writerContextBlock, to: AnyObject.self) let mainContextBlock: @convention(block) () -> Void = { self.writerContext.perform(DataStack.performSelectorForBackgroundContext(), with: writerContextBlockObject) DispatchQueue.main.async { completion?(writerContextError) } } let mainContextBlockObject: AnyObject = unsafeBitCast(mainContextBlock, to: AnyObject.self) self.mainContext.perform(DataStack.performSelectorForBackgroundContext(), with: mainContextBlockObject) } // Drops the database. @objc public func drop(completion: ((_ error: NSError?) -> Void)? = nil) { self.writerContext.performAndWait { self.writerContext.reset() self.mainContext.performAndWait { self.mainContext.reset() self.persistentStoreCoordinator.performAndWait { for store in self.persistentStoreCoordinator.persistentStores { guard let storeURL = store.url else { continue } try! self.oldDrop(storeURL: storeURL) } DispatchQueue.main.async { completion?(nil) } } } } } // Required for iOS 8 Compatibility. func oldDrop(storeURL: URL) throws { let storePath = storeURL.path let sqliteFile = (storePath as NSString).deletingPathExtension let fileManager = FileManager.default self.writerContext.reset() self.mainContext.reset() let shm = sqliteFile + ".sqlite-shm" if fileManager.fileExists(atPath: shm) { do { try fileManager.removeItem(at: NSURL.fileURL(withPath: shm)) } catch let error as NSError { throw NSError(info: "Could not delete persistent store shm", previousError: error) } } let wal = sqliteFile + ".sqlite-wal" if fileManager.fileExists(atPath: wal) { do { try fileManager.removeItem(at: NSURL.fileURL(withPath: wal)) } catch let error as NSError { throw NSError(info: "Could not delete persistent store wal", previousError: error) } } if fileManager.fileExists(atPath: storePath) { do { try fileManager.removeItem(at: storeURL) } catch let error as NSError { throw NSError(info: "Could not delete sqlite file", previousError: error) } } } /// Sends a request to all the persistent stores associated with the receiver. /// /// - Parameters: /// - request: A fetch, save or delete request. /// - context: The context against which request should be executed. /// - Returns: An array containing managed objects, managed object IDs, or dictionaries as appropriate for a fetch request; an empty array if request is a save request, or nil if an error occurred. /// - Throws: If an error occurs, upon return contains an NSError object that describes the problem. @objc public func execute(_ request: NSPersistentStoreRequest, with context: NSManagedObjectContext) throws -> Any { return try self.persistentStoreCoordinator.execute(request, with: context) } // Can't be private, has to be internal in order to be used as a selector. @objc func mainContextDidSave(_ notification: Notification) { self.saveMainThread { error in if let error = error { fatalError("Failed to save objects in main thread: \(error)") } } } // Can't be private, has to be internal in order to be used as a selector. @objc func newDisposableMainContextWillSave(_ notification: Notification) { if let context = notification.object as? NSManagedObjectContext { context.reset() } } // Can't be private, has to be internal in order to be used as a selector. @objc func backgroundContextDidSave(_ notification: Notification) throws { let context = notification.object as? NSManagedObjectContext guard context?.name == backgroundContextName else { return } if Thread.isMainThread && TestCheck.isTesting == false { throw NSError(info: "Background context saved in the main thread. Use context's `performBlock`", previousError: nil) } else { let contextBlock: @convention(block) () -> Void = { self.mainContext.mergeChanges(fromContextDidSave: notification) } let blockObject: AnyObject = unsafeBitCast(contextBlock, to: AnyObject.self) self.mainContext.perform(DataStack.performSelectorForBackgroundContext(), with: blockObject) } } private static func backgroundConcurrencyType() -> NSManagedObjectContextConcurrencyType { return TestCheck.isTesting ? .mainQueueConcurrencyType : .privateQueueConcurrencyType } private static func performSelectorForBackgroundContext() -> Selector { return TestCheck.isTesting ? NSSelectorFromString("performBlockAndWait:") : NSSelectorFromString("performBlock:") } } extension NSPersistentStoreCoordinator { func addPersistentStore(storeType: DataStackStoreType, bundle: Bundle, modelName: String, storeName: String?, containerURL: URL) throws { let filePath = (storeName ?? modelName) + ".sqlite" switch storeType { case .inMemory: do { try self.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil) } catch let error as NSError { throw NSError(info: "There was an error creating the persistentStoreCoordinator for in memory store", previousError: error) } break case .sqLite: let storeURL = containerURL.appendingPathComponent(filePath) let storePath = storeURL.path let shouldPreloadDatabase = !FileManager.default.fileExists(atPath: storePath) if shouldPreloadDatabase { if let preloadedPath = bundle.path(forResource: modelName, ofType: "sqlite") { let preloadURL = URL(fileURLWithPath: preloadedPath) do { try FileManager.default.copyItem(at: preloadURL, to: storeURL) } catch let error as NSError { throw NSError(info: "Oops, could not copy preloaded data", previousError: error) } } } let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true, NSSQLitePragmasOption: ["journal_mode": "DELETE"]] as [AnyHashable : Any] do { try self.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options) } catch { do { try FileManager.default.removeItem(atPath: storePath) do { try self.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options) } catch let addPersistentError as NSError { throw NSError(info: "There was an error creating the persistentStoreCoordinator", previousError: addPersistentError) } } catch let removingError as NSError { throw NSError(info: "There was an error removing the persistentStoreCoordinator", previousError: removingError) } } let shouldExcludeSQLiteFromBackup = storeType == .sqLite && TestCheck.isTesting == false if shouldExcludeSQLiteFromBackup { do { try (storeURL as NSURL).setResourceValue(true, forKey: .isExcludedFromBackupKey) } catch let excludingError as NSError { throw NSError(info: "Excluding SQLite file from backup caused an error", previousError: excludingError) } } break } } } extension NSManagedObjectModel { convenience init(bundle: Bundle, name: String) { if let momdModelURL = bundle.url(forResource: name, withExtension: "momd") { self.init(contentsOf: momdModelURL)! } else if let momModelURL = bundle.url(forResource: name, withExtension: "mom") { self.init(contentsOf: momModelURL)! } else { self.init() } } } extension NSError { convenience init(info: String, previousError: NSError?) { if let previousError = previousError { var userInfo = previousError.userInfo if let _ = userInfo[NSLocalizedFailureReasonErrorKey] { userInfo["Additional reason"] = info } else { userInfo[NSLocalizedFailureReasonErrorKey] = info } self.init(domain: previousError.domain, code: previousError.code, userInfo: userInfo) } else { var userInfo = [String: String]() userInfo[NSLocalizedDescriptionKey] = info self.init(domain: "com.SyncDB.DataStack", code: 9999, userInfo: userInfo) } } } extension FileManager { /// The directory URL for the sqlite file. public static var sqliteDirectoryURL: URL { #if os(tvOS) return FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).last! #else if TestCheck.isTesting { return FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).last! } else { return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last! } #endif } }
mit
035fdab6a65d2cdf2c58ca3795d5971d
43.850099
201
0.670918
5.397342
false
false
false
false
mozilla-mobile/firefox-ios
SyncTelemetry/SyncTelemetry.swift
2
4223
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import Foundation import SwiftyJSON import Shared private let log = Logger.browserLogger private let ServerURL = "https://incoming.telemetry.mozilla.org".asURL! private let AppName = "Fennec" public enum TelemetryDocType: String { case core = "core" case sync = "sync" } public protocol SyncTelemetryEvent { func record(_ prefs: Prefs) } open class SyncTelemetry { private static var prefs: Prefs? private static var telemetryVersion: Int = 4 open class func initWithPrefs(_ prefs: Prefs) { assert(self.prefs == nil, "Prefs already initialized") self.prefs = prefs } open class func recordEvent(_ event: SyncTelemetryEvent) { guard let prefs = prefs else { assertionFailure("Prefs not initialized") return } event.record(prefs) } open class func send(ping: SyncTelemetryPing, docType: TelemetryDocType) { let docID = UUID().uuidString let appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String let buildID = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String let channel = AppConstants.BuildChannel.rawValue let path = "/submit/telemetry/\(docID)/\(docType.rawValue)/\(AppName)/\(appVersion)/\(channel)/\(buildID)" let url = ServerURL.appendingPathComponent(path) var request = URLRequest(url: url) log.debug("Ping URL: \(url)") log.debug("Ping payload: \(ping.payload.stringify() ?? "")") // Don't add the common ping format for the mobile core ping. let pingString: String? if docType != .core { var json = JSON(commonPingFormat(forType: docType)) json["payload"] = ping.payload pingString = json.stringify() } else { pingString = ping.payload.stringify() } guard let body = pingString?.data(using: .utf8) else { log.error("Invalid data!") assertionFailure() return } guard channel != "default" else { log.debug("Non-release build; not sending ping") return } request.httpMethod = "POST" request.httpBody = body request.addValue(Date().toRFC822String(), forHTTPHeaderField: "Date") request.setValue("application/json", forHTTPHeaderField: "Content-Type") makeURLSession(userAgent: UserAgent.fxaUserAgent, configuration: URLSessionConfiguration.ephemeral).dataTask(with: request) { (_, response, error) in let code = (response as? HTTPURLResponse)?.statusCode log.debug("Ping response: \(code ?? -1).") }.resume() } private static func commonPingFormat(forType type: TelemetryDocType) -> [String: Any] { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) let date = formatter.string(from: NSDate() as Date) let displayVersion = [ AppInfo.appVersion, "b", AppInfo.buildNumber ].joined() let version = ProcessInfo.processInfo.operatingSystemVersion let osVersion = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" return [ "type": type.rawValue, "id": UUID().uuidString, "creationDate": date, "version": SyncTelemetry.telemetryVersion, "application": [ "architecture": "arm", "buildId": AppInfo.buildNumber, "name": AppInfo.displayName, "version": AppInfo.appVersion, "displayVersion": displayVersion, "platformVersion": osVersion, "channel": AppConstants.BuildChannel.rawValue ] ] } } public protocol SyncTelemetryPing { var payload: JSON { get } }
mpl-2.0
9efef6f541c8f72c483292eb485a0dca
34.487395
157
0.621359
4.787982
false
false
false
false
lilongcnc/Swift-weibo2015
ILWEIBO04/ILWEIBO04/Classes/UI/Home/RefreshViewController.swift
1
7247
// // RefreshViewController.swift // ILWEIBO04 // // Created by 李龙 on 15/3/10. // Copyright (c) 2015年 Lauren. All rights reserved. // import UIKit class RefreshViewController: UIRefreshControl { //加载xib下来刷新视图,通过视图自身的加载顺序方法进行 lazy var refreshView : RefreshView = { return RefreshView.refreshView(isLoading: false) }() // MARK: ---- 下拉刷新部分代码 //设置 下拉刷新大图的大小 override func willMoveToWindow(newWindow: UIWindow?) { super.willMoveToWindow(newWindow) //设置下拉刷新视图的大小 refreshView.frame = self.bounds } override func awakeFromNib() { //把下拉刷新视图替换到stpryBoard中的 UIRefreshControl控件中 self.addSubview(refreshView) //MARK: 利用kvo来观察控件自身位置的变化(注意销毁观察者) self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil) } deinit{ println("刷新视图1 被释放了") //销毁观察者 self.removeObserver(self, forKeyPath: "frame") } //正在现实加载的动画 var isLoading = false //旋转提示图标标记 var isRotateTip = false //KVO 观察控件位置变化 override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { // println("\(self) ----- \(change) ----- \(self.frame)") //向下拉的时候,self.frame.origin.y是小于0的 //当向上滚表格的时候 if self.frame.origin.y > 0 { return } if !isLoading && refreshing{ //MARK: refreshing 正在刷新 //正在刷新 //显示刷新视图时候动画旋转效果 refreshView.showLoading() isLoading = true return } if self.frame.origin.y < -50 && !isRotateTip { //此时箭头向下,需改为向上 isRotateTip = true refreshView.rotationTipIcon(isRotateTip) }else if self.frame.origin.y > -50 && isRotateTip { //此时箭头向上,需改为箭头向下 isRotateTip = false refreshView.rotationTipIcon(isRotateTip) } } //重写父类停止刷新方法 override func endRefreshing() { //调用父类的方法,保证其功能正常执行 super.endRefreshing() //停止动画 refreshView.stopLoading() isLoading = false } } class RefreshView : UIView { /// 提醒视图图片 @IBOutlet weak var tipImageView: UIImageView! /// 提醒视图 @IBOutlet weak var tipView: UIView! /// 加载视图 @IBOutlet weak var loadView: UIView! /// 加载视图图片 @IBOutlet weak var loadImageView: UIImageView! //丛xib中加载刷新视图 class func refreshView(isLoading: Bool = false) -> RefreshView { let view = NSBundle.mainBundle().loadNibNamed("RefreshViewController", owner: nil, options: nil).last as! RefreshView //利用isLoading参数更便捷的控制下拉和上拉视图的现实 view.tipView.hidden = isLoading view.loadView.hidden = !isLoading return view } //刷新视图动画效果 func showLoading() { tipView.hidden = true loadView.hidden = false //添加动画 loadingAnimation() } //动画旋转的实现代码 /** 核心动画 - 属性动画 => - 基础动画: fromValue toValue - 关键帧动画:values, path * MARK: 将动画添加到图层 */ func loadingAnimation() { let anim = CABasicAnimation(keyPath: "transform.rotation") anim.toValue = 2 * M_PI anim.repeatCount = MAXFLOAT //OC中是 MAX_FLOAT anim.duration = 0.5 //将动画添加到图层 loadImageView.layer.addAnimation(anim, forKey: nil) } //箭头图片的转向和返回的动画效果实现 func rotationTipIcon(clockWise : Bool) { var angel = CGFloat(M_PI - 0.01) if clockWise { angel = CGFloat(M_PI + 0.01) } UIView.animateWithDuration(0.5, animations: { () -> Void in // 旋转提示图标 180 self.tipImageView.transform = CGAffineTransformRotate(self.tipImageView.transform,angel) }) } //停止动画 func stopLoading() { //删除动画,恢复视图显示 loadImageView.layer.removeAllAnimations() tipView.hidden = false loadView.hidden = true } //------------------------------------------------------------ /** parentView默认就强引用,这里会对闭包中的tableView强引用,即其中的控件 而闭包被外边的视图控件强引用, 造成循环引用 OC中,代理要使用weak */ // MARK: - 上拉加载更多部分代码 weak var parentView: UITableView? // 给 parentView 添加观察 func addPullupOberserver(parentView: UITableView, pullupLoadData: ()->()) { // 1. 记录要观察的表格视图 self.parentView = parentView // 2. 记录上拉加载数据的闭包 self.pullupLoadData = pullupLoadData self.parentView!.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil) } // KVO 的代码 deinit { println("刷新视图2 被释放了") //释放对象不一定放在deinit中,我们根据具体的情况来定 // parentView!.removeObserver(self, forKeyPath: "contentOffset") } // 上拉加载数据标记 var isPullupLoading = false // 上拉加载数据闭包 var pullupLoadData: (()->())? override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { // 1. 如果在 tableView 的顶部,不进行刷新,直接返回 if self.frame.origin.y == 0 { return } if (parentView!.bounds.size.height + parentView!.contentOffset.y) > CGRectGetMaxY(self.frame) { // 2. 保证上拉加载数据的判断只有一次是有效的 if !isPullupLoading { println("上拉加载数据!!!") isPullupLoading = true // 播放转轮动画 showLoading() // 3. 判断闭包是否存在,如果存在,执行闭包 if pullupLoadData != nil { pullupLoadData!() } } } } /// 上拉加载完成 func pullupFinished() { // 重新设置刷新视图的属性 isPullupLoading = false // 停止动画 stopLoading() } }
mit
9a48735f17c70bfee0636fd062ffff8f
24.939914
156
0.558332
4.304131
false
false
false
false
mennovf/Swift-MathEagle
MathEagle/Source/Prime.swift
1
2691
// // Prime.swift // MathEagle // // Created by Rugen Heidbuchel on 05/03/15. // Copyright (c) 2015 Jorestha Solutions. All rights reserved. // import Foundation /** Returns true if the given number is prime. - parameter x: The number to check for primality - returns: true if the given unsigned integer is prime. */ public func isPrime <X: protocol<Equatable, Comparable, Addable, Modulable, RealPowerable, IntegerLiteralConvertible>> (x: X) -> Bool { if x <= 3 { return x >= 2 } if x % 2 == 0 || x % 3 == 0 { return false } var p: X = 5 while p <= X(root(x, order: 2)) { if x % p == 0 || x % (p + 2) == 0 { return false } p = p + 6 } return true } /** Returns true if the given unsigned integers are coprimes. This means they have no common prime factors. - parameter a: The first unsigned integer - parameter b: The second unsigned integer - returns: true if the given unsigned integers are coprime. */ public func areCoprime <X: protocol<Equatable, Comparable, Negatable, Modulable, IntegerLiteralConvertible>> (a: X, _ b: X) -> Bool { return gcd(a, b) == 1 } /** Returns a list of all primes up to (and including) the given integer. - parameter n: The upper bound - returns: All primes up to (and including) the given integer. */ public func primesUpTo(n: UInt) -> [UInt] { if n <= 1 { return [] } var sieve = [Bool](count: Int(n - 1), repeatedValue: true) for i: UInt in 2 ... UInt(sqrt(Double(n))) { if sieve[Int(i)-2] { var j = i*i while j <= n { sieve[Int(j)-2] = false j += i } } } var primes = [UInt]() for i in 0 ..< n-1 { if sieve[Int(i)] { primes.append(i+2) } } return primes } /** Returns the prime factors of the given integer in ascending order. Factors with higher multiplicity will appear multiple times. An empty array will be returned for all numbers smaller than or equal to 1. - parameter n: The integer to factorise - returns: The prime factors of the given integer in ascending order. */ public func primeFactors <X: protocol<Equatable, Comparable, Addable, Modulable, Dividable, IntegerLiteralConvertible>> (x: X) -> [X] { if x <= 1 { return [] } var i: X = 2 while i < x { if x % i == 0 { return primeFactors(i) + primeFactors(x/i) } i = i + 1 } return [x] }
mit
74e81fb3d746c0b58c0ab30dc69199f7
22.206897
207
0.553326
3.992582
false
false
false
false
syoung-smallwisdom/BridgeAppSDK
BridgeAppSDK/SBAToggleFormStep.swift
1
6208
// // SBAToggleFormStep.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import UIKit public class SBAToggleFormStep: SBANavigationFormStep { var hasOnlyToggleItems: Bool { guard let formItems = self.formItems else { return true } for formItem in formItems { guard let answerFormat = formItem.answerFormat, answerFormat.isToggleAnswerFormat else { return false } } return true } public override func instantiateStepViewController(with result: ORKResult) -> ORKStepViewController { if hasOnlyToggleItems { let vc = SBAToggleFormStepViewController(step: self) vc.storedResult = result as? ORKStepResult return vc } else { return super.instantiateStepViewController(with: result) } } } extension ORKAnswerFormat { var isToggleAnswerFormat: Bool { return false } } extension ORKBooleanAnswerFormat { override var isToggleAnswerFormat: Bool { return true } } extension ORKTextChoiceAnswerFormat { override var isToggleAnswerFormat: Bool { return self.questionType == .singleChoice && self.textChoices.count == 2 } } class SBAToggleFormStepViewController: ORKTableStepViewController, ORKTableStepSource, SBAToggleTableViewCellDelegate { override var tableStep: ORKTableStepSource? { return self } var formItems: [ORKFormItem]? { return (self.step as? ORKFormStep)?.formItems } var storedResult: ORKStepResult? override var result: ORKStepResult? { guard let stepResult = super.result else { return nil } stepResult.results = storedResult?.results ?? [] return stepResult } public func numberOfRows(inSection section: Int) -> Int { return self.formItems?.count ?? 0 } public func reuseIdentifierForRow(at indexPath: IndexPath) -> String { return SBAToggleTableViewCell.reuseIdentifier } private var preferredCellHeight: CGFloat = 130 override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() updatePreferredCellHeight() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() updatePreferredCellHeight() } func updatePreferredCellHeight() { let itemCount = self.numberOfRows(inSection: 0) if itemCount > 0 { let headerHeight = self.tableView.tableHeaderView?.bounds.height ?? 0 let footerHeight = self.tableView.tableFooterView?.bounds.height ?? 0 let overallHeight = self.tableView.bounds.size.height; let desiredCellHeight = floor((overallHeight - headerHeight - footerHeight)/CGFloat(itemCount)) if desiredCellHeight != preferredCellHeight { preferredCellHeight = desiredCellHeight self.tableView.reloadData() } } } public func registerCells(for tableView: UITableView) { // Register the cells let bundle = Bundle(for: SBAToggleTableViewCell.classForCoder()) let nib = UINib(nibName: "SBAToggleTableViewCell", bundle: bundle) tableView.register(nib, forCellReuseIdentifier: SBAToggleTableViewCell.reuseIdentifier) } public func configureCell(_ cell: UITableViewCell, indexPath: IndexPath, tableView: UITableView) { guard let toggleCell = cell as? SBAToggleTableViewCell, let items = self.formItems, items.count > indexPath.row else { return } toggleCell.configure(formItem: items[indexPath.row], stepResult: storedResult) toggleCell.delegate = self toggleCell.preferredHeightConstraint.constant = preferredCellHeight } func didChangeAnswer(cell: SBAToggleTableViewCell) { guard let cellResult = cell.result else { return } // Add the result to the stored results if storedResult == nil { storedResult = ORKStepResult(identifier: self.step!.identifier) } storedResult?.addResult(cellResult) updateButtonStates() } override func continueButtonEnabled() -> Bool { guard let items = self.formItems else { return false } // check if all results are answered let answerCount = items.filter({ storedResult?.result(forIdentifier: $0.identifier) != nil }).count return answerCount == items.count } }
bsd-3-clause
7e02b318a04b8762f47cb7b5c5cb9658
36.167665
119
0.688577
5.194142
false
false
false
false
shengguoqiang/FTDKit
FTDKit/UI/FTDScrollView/FTDLoopView.swift
1
15234
/*********小贴士**************/ //1.创建FTDLoopView //2.配置参数config //3.设置代理 //4.加载资源 import UIKit import Kingfisher @objc public protocol FTDLoopViewDelegate: class { /**cell点击监听*/ /** * @param index 当前索引 */ @objc optional func collectionViewDidSelected(index: Int) /** * @param instanceName 当前类实例的名称 * @param index 当前索引 */ @objc optional func collectionViewDidSelected(instanceName: String?, index: Int) /**cell滑动结束监听*/ /** * @param index 当前索引 */ @objc optional func collectionViewDidEndDecelerating(index: Int) /** * @param instanceName 当前类实例的名称 * @param index 当前索引 */ @objc optional func collectionViewDidEndDecelerating(instanceName: String?, index: Int) } public class FTDLoopView: UIView { //MARK: - 公共属性 //代理 public weak var delegate: FTDLoopViewDelegate? /******************************************************************/ //MARK: - 私有属性 //当前实例的名称-区分同一页面中多个FTDLoopView实例 fileprivate var instanceName: String? //collectionViewLayout private var collectionViewLayout: UICollectionViewFlowLayout! //collectionView private var collectionView: UICollectionView! //timer private weak var timer: Timer? //需要展示图片数量 fileprivate var totalShows: Int = 0 //实际图片数量 fileprivate var actualShows: Int = 0 //是否无限循环,默认不无限循环 private var infinite: Bool = false //是否在自动滚动中 fileprivate var autoScrolling: Bool = false //是否自动滚动,默认不自动滚动 fileprivate var autoScroll: Bool = false { willSet { autoScrolling = newValue } } //定时器间隔时间,默认2s private var timerInterval: TimeInterval = 2 //滚动方向,默认横向 private var scrollDirection: UICollectionViewScrollDirection = .horizontal { willSet { collectionViewLayout.scrollDirection = newValue } } //偏移方向->横向:左右,纵向:上下 private var scrollPosition: UICollectionViewScrollPosition = .left //是否需要监听滚动视图滚到一半时,索引变化,默认需要监听 fileprivate var monitorIndexChanged: Bool = true //cellNibName private var cellNibName: String! //cell重用标识符 fileprivate var cellIdentifier: String! //图片url数组 fileprivate var sourceArray = [AnyObject]() { didSet { //实际图片数量 actualShows = sourceArray.count //需要展示图片数量 totalShows = sourceArray.count * 100 totalShows = (infinite && actualShows > 1) ? totalShows : actualShows //刷新collectionView collectionView.reloadData() //设置初始位置 setupInitOffSet() //是否开启倒计时 if autoScroll { start() } } } /******************************************************************/ //MARK: - 公共方法 /** 配置参数 * @param infinite 是否无限循环 * @param autoScroll 是否自动滚动 * @param timerInterval 定时器间隔 * @param scrollDirection 滚动方向 * @param scrollPosition 偏移方向 * @param cellNibName cellNibName * @param cellIdentifier cell重用标识符 */ public func config(infinite: Bool, autoScroll: Bool, timerInterval: TimeInterval, scrollDirection: UICollectionViewScrollDirection, scrollPosition: UICollectionViewScrollPosition, cellNibName: String, cellIdentifier: String) { /**初始化**/ setup() /**设置属性**/ //是否无限循环 self.infinite = infinite //是否自动滚动 self.autoScroll = autoScroll //设置定时器时间间隔 self.timerInterval = timerInterval //设置滚动方向 self.scrollDirection = scrollDirection //设置偏移方向 self.scrollPosition = scrollPosition //设置cellNibName self.cellNibName = cellNibName; //设置cell重用标识 self.cellIdentifier = cellIdentifier //注册cell collectionView.register(UINib(nibName: cellNibName, bundle: nil), forCellWithReuseIdentifier: cellIdentifier) } /** 配置参数 * @param infinite 是否无限循环 * @param autoScroll 是否自动滚动 * @param timerInterval 定时器间隔 * @param scrollDirection 滚动方向 * @param scrollPosition 偏移方向 * @param monitorIndexChanged 是否需要监听滚动视图滚到一半时,索引变化 * @param cellNibName cellNibName * @param cellIdentifier cell重用标识符 */ public func config(infinite: Bool, autoScroll: Bool, timerInterval: TimeInterval, scrollDirection: UICollectionViewScrollDirection, scrollPosition: UICollectionViewScrollPosition, monitorIndexChanged: Bool, cellNibName: String, cellIdentifier: String) { //初始化设置 config(infinite: infinite, autoScroll: autoScroll, timerInterval: timerInterval, scrollDirection: scrollDirection, scrollPosition: scrollPosition, cellNibName: cellNibName, cellIdentifier: cellIdentifier) //监听滚动视图滚到一半时,索引变化 self.monitorIndexChanged = monitorIndexChanged } /** 配置参数 * @param infinite 是否无限循环 * @param autoScroll 是否自动滚动 * @param timerInterval 定时器间隔 * @param scrollDirection 滚动方向 * @param scrollPosition 偏移方向 * @param instanceName 当前实例的名称-区分同一页面中多个FTDLoopView实例 * @param cellNibName cellNibName * @param cellIdentifier cell重用标识符 */ public func config(infinite: Bool, autoScroll: Bool, timerInterval: TimeInterval, scrollDirection: UICollectionViewScrollDirection, scrollPosition: UICollectionViewScrollPosition, instanceName: String?, cellNibName: String, cellIdentifier: String) { //初始化设置 config(infinite: infinite, autoScroll: autoScroll, timerInterval: timerInterval, scrollDirection: scrollDirection, scrollPosition: scrollPosition, cellNibName: cellNibName, cellIdentifier: cellIdentifier) //当前类实例名称 self.instanceName = instanceName } /** 刷新滚动视图 * @param resource 资源 */ public func reloadLoopView(resource: [AnyObject]) { //数据源 sourceArray = resource } /** 滚动视图移至指定位置 * @param item 指定位置坐标 */ public func scrollToItem(_ item: IndexPath) { collectionView.scrollToItem(at: item, at: scrollPosition, animated: false) } /** 刷新当前collectionViewCell */ public func reloadcurrentItem() { collectionView.reloadItems(at: [IndexPath(item: currentIndex(), section: 0)]) } //开启定时器 public func start() { guard actualShows > 1 else {//没有图片或只有一张不需要倒计时 finishRunLoop() return } //关闭定时器 finishRunLoop() timer = Timer.scheduledTimer(timeInterval: timerInterval, target: self, selector: #selector(FTDLoopView.runLoop), userInfo: nil, repeats: true) RunLoop.current.add(timer!, forMode: .UITrackingRunLoopMode) } //关闭定时器 public func finishRunLoop() { timer?.invalidate() timer = nil } /******************************************************************/ //MARK: - 私有方法 //初始化 private func setup() { //创建collectionViewLayout if self.collectionViewLayout == nil { let collectionViewLayout = UICollectionViewFlowLayout() collectionViewLayout.minimumLineSpacing = 0 self.collectionViewLayout = collectionViewLayout } //创建collectionView if self.collectionView == nil { let collectionView = UICollectionView(frame: CGRect(origin: CGPoint.zero, size: CGSize.zero), collectionViewLayout: collectionViewLayout) collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.delegate = self collectionView.dataSource = self collectionView.backgroundColor = UIColor.clear addSubview(collectionView) self.collectionView = collectionView } //布局 layoutIfNeeded() } //布局 override public func layoutSubviews() { super.layoutSubviews() //非空判断 guard collectionView != nil, collectionViewLayout != nil else { return } //设置collectionView的Frame collectionView.frame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height) //设置itemSize collectionViewLayout.itemSize = CGSize(width: bounds.width, height: bounds.height) //设置初始位置 setupInitOffSet() } //设置初始位置 private func setupInitOffSet() { guard actualShows > 0 else {//没有图片不需要设置初始位置 return } //初始偏移量 let targetIndex = infinite ? totalShows / 2 : 0 collectionView.scrollToItem(at: IndexPath(item: targetIndex, section: 0), at: scrollPosition, animated: false) } //定时器事件 @objc private func runLoop() { //修改collectionView偏移量 collectionViewChangeOffSet() } //collectionView偏移 private func collectionViewChangeOffSet() { //当前坐标 let curIndex = currentIndex() //转移至下一坐标 var targetIndex = curIndex + 1 if targetIndex >= totalShows { if infinite {//无限循环,回到起始位置 targetIndex = totalShows / 2 collectionView.scrollToItem(at: IndexPath(item: targetIndex, section: 0), at: scrollPosition, animated: false) } else {//不无限循环,回到起始位置 targetIndex = 0 collectionView.scrollToItem(at: IndexPath(item: targetIndex, section: 0), at: scrollPosition, animated: true) } } else {//正常从中间往后偏移 collectionView.scrollToItem(at: IndexPath(item: targetIndex, section: 0), at: scrollPosition, animated: true) } scrollViewDidEndDecelerating(collectionView) } //获取当前item坐标 fileprivate func currentIndex() -> Int { var index = 0 if collectionViewLayout.scrollDirection == .horizontal { index = Int((collectionView.contentOffset.x + collectionViewLayout.itemSize.width * 0.5) / collectionViewLayout.itemSize.width) } else { index = Int((collectionView.contentOffset.y + collectionViewLayout.itemSize.height * 0.5) / collectionViewLayout.itemSize.height) } return index } //MARK: - 销毁FTDLoopView实例 deinit { //关闭定时器 finishRunLoop() } } //MARK: - 代理事件 //UICollectionViewDataSource, UICollectionViewDelegate extension FTDLoopView: UICollectionViewDataSource, UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return totalShows } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! FTDCollectionViewCell let index = indexPath.item % actualShows let source = sourceArray[index] //子类实现该方法 cell.reloadData(source) return cell } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let index = indexPath.item % actualShows delegate?.collectionViewDidSelected?(index: index) delegate?.collectionViewDidSelected?(instanceName: instanceName, index: index) } } //UIScrollViewDelegate extension FTDLoopView: UIScrollViewDelegate { public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { if autoScroll {//关闭定时器 finishRunLoop() //自动滑动过程中,手动拖拽时,修改状态,为了scrollViewDidEndDecelerating中计算准确的偏移量 autoScrolling = false } } public func scrollViewDidScroll(_ scrollView: UIScrollView) { //cell滑动过程中,当前页面判断 guard monitorIndexChanged else {//无需监听滚动一半时,索引变化 return } guard actualShows > 0 else { return } let index = currentIndex() % actualShows delegate?.collectionViewDidEndDecelerating?(index: index) delegate?.collectionViewDidEndDecelerating?(instanceName: instanceName, index: index) } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if autoScroll {//启动定时器 start() } } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { guard actualShows > 0 else { return } if !monitorIndexChanged {//无需监听滚动一半时,索引变化 let index = autoScrolling ? (currentIndex() + 1) % actualShows : currentIndex() % actualShows delegate?.collectionViewDidEndDecelerating?(index: index) delegate?.collectionViewDidEndDecelerating?(instanceName: instanceName, index: index) } //页面滑动(无论是自动滑动还是手动拖拽)结束,修改状态 autoScrolling = autoScroll } }
mit
79345a9b6e515416849f359b7b49c883
31.339623
212
0.597141
5.294208
false
false
false
false
exponent/exponent
ios/vendored/unversioned/@stripe/stripe-react-native/ios/StripeSdk.swift
2
40324
import PassKit import Stripe @objc(StripeSdk) class StripeSdk: RCTEventEmitter, STPApplePayContextDelegate, STPBankSelectionViewControllerDelegate, UIAdaptivePresentationControllerDelegate { public var cardFieldView: CardFieldView? = nil public var cardFormView: CardFormView? = nil var merchantIdentifier: String? = nil private var paymentSheet: PaymentSheet? private var paymentSheetFlowController: PaymentSheet.FlowController? var urlScheme: String? = nil var applePayCompletionCallback: STPIntentClientSecretCompletionBlock? = nil var applePayRequestResolver: RCTPromiseResolveBlock? = nil var applePayRequestRejecter: RCTPromiseRejectBlock? = nil var applePayCompletionRejecter: RCTPromiseRejectBlock? = nil var confirmApplePayPaymentResolver: RCTPromiseResolveBlock? = nil var confirmPaymentResolver: RCTPromiseResolveBlock? = nil var confirmPaymentClientSecret: String? = nil var shippingMethodUpdateHandler: ((PKPaymentRequestShippingMethodUpdate) -> Void)? = nil var shippingContactUpdateHandler: ((PKPaymentRequestShippingContactUpdate) -> Void)? = nil override func supportedEvents() -> [String]! { return ["onDidSetShippingMethod", "onDidSetShippingContact"] } @objc override static func requiresMainQueueSetup() -> Bool { return false } @objc(initialise:resolver:rejecter:) func initialise(params: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) -> Void { let publishableKey = params["publishableKey"] as! String let appInfo = params["appInfo"] as! NSDictionary let stripeAccountId = params["stripeAccountId"] as? String let params3ds = params["threeDSecureParams"] as? NSDictionary let urlScheme = params["urlScheme"] as? String let merchantIdentifier = params["merchantIdentifier"] as? String if let params3ds = params3ds { configure3dSecure(params3ds) } self.urlScheme = urlScheme STPAPIClient.shared.publishableKey = publishableKey STPAPIClient.shared.stripeAccount = stripeAccountId let name = RCTConvert.nsString(appInfo["name"]) ?? "" let partnerId = RCTConvert.nsString(appInfo["partnerId"]) ?? "" let version = RCTConvert.nsString(appInfo["version"]) ?? "" let url = RCTConvert.nsString(appInfo["url"]) ?? "" STPAPIClient.shared.appInfo = STPAppInfo(name: name, partnerId: partnerId, version: version, url: url) self.merchantIdentifier = merchantIdentifier resolve(NSNull()) } @objc(initPaymentSheet:resolver:rejecter:) func initPaymentSheet(params: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) -> Void { var configuration = PaymentSheet.Configuration() if params["applePay"] as? Bool == true { if let merchantIdentifier = self.merchantIdentifier, let merchantCountryCode = params["merchantCountryCode"] as? String { configuration.applePay = .init(merchantId: merchantIdentifier, merchantCountryCode: merchantCountryCode) } else { resolve(Errors.createError(PaymentSheetErrorType.Failed.rawValue, "Either merchantIdentifier or merchantCountryCode is missing")) return } } if let merchantDisplayName = params["merchantDisplayName"] as? String { configuration.merchantDisplayName = merchantDisplayName } if let returnURL = params["returnURL"] as? String { configuration.returnURL = returnURL } if let buttonColorHexStr = params["primaryButtonColor"] as? String { let primaryButtonColor = UIColor(hexString: buttonColorHexStr) configuration.primaryButtonColor = primaryButtonColor } if let allowsDelayedPaymentMethods = params["allowsDelayedPaymentMethods"] as? Bool { configuration.allowsDelayedPaymentMethods = allowsDelayedPaymentMethods } if let defaultBillingDetails = params["defaultBillingDetails"] as? [String: Any?] { configuration.defaultBillingDetails.name = defaultBillingDetails["name"] as? String configuration.defaultBillingDetails.email = defaultBillingDetails["email"] as? String configuration.defaultBillingDetails.phone = defaultBillingDetails["phone"] as? String if let address = defaultBillingDetails["address"] as? [String: String] { configuration.defaultBillingDetails.address = .init(city: address["city"], country: address["country"], line1: address["line1"], line2: address["line2"], postalCode: address["postalCode"], state: address["state"]) } } if let customerId = params["customerId"] as? String { if let customerEphemeralKeySecret = params["customerEphemeralKeySecret"] as? String { if (!Errors.isEKClientSecretValid(clientSecret: customerEphemeralKeySecret)) { resolve(Errors.createError(PaymentSheetErrorType.Failed.rawValue, "`customerEphemeralKeySecret` format does not match expected client secret formatting.")) return } configuration.customer = .init(id: customerId, ephemeralKeySecret: customerEphemeralKeySecret) } } if #available(iOS 13.0, *) { if let style = params["style"] as? String { configuration.style = Mappers.mapToUserInterfaceStyle(style) } } func handlePaymentSheetFlowControllerResult(result: Result<PaymentSheet.FlowController, Error>, stripeSdk: StripeSdk?) { switch result { case .failure(let error): resolve(Errors.createError("Failed", error as NSError)) case .success(let paymentSheetFlowController): self.paymentSheetFlowController = paymentSheetFlowController if let paymentOption = stripeSdk?.paymentSheetFlowController?.paymentOption { let option: NSDictionary = [ "label": paymentOption.label, "image": paymentOption.image.pngData()?.base64EncodedString() ?? "" ] resolve(Mappers.createResult("paymentOption", option)) } else { resolve(Mappers.createResult("paymentOption", nil)) } } } if let paymentIntentClientSecret = params["paymentIntentClientSecret"] as? String { if (!Errors.isPIClientSecretValid(clientSecret: paymentIntentClientSecret)) { resolve(Errors.createError(PaymentSheetErrorType.Failed.rawValue, "`secret` format does not match expected client secret formatting.")) return } if params["customFlow"] as? Bool == true { PaymentSheet.FlowController.create(paymentIntentClientSecret: paymentIntentClientSecret, configuration: configuration) { [weak self] result in handlePaymentSheetFlowControllerResult(result: result, stripeSdk: self) } } else { self.paymentSheet = PaymentSheet(paymentIntentClientSecret: paymentIntentClientSecret, configuration: configuration) resolve([]) } } else if let setupIntentClientSecret = params["setupIntentClientSecret"] as? String { if (!Errors.isSetiClientSecretValid(clientSecret: setupIntentClientSecret)) { resolve(Errors.createError(PaymentSheetErrorType.Failed.rawValue, "`secret` format does not match expected client secret formatting.")) return } if params["customFlow"] as? Bool == true { PaymentSheet.FlowController.create(setupIntentClientSecret: setupIntentClientSecret, configuration: configuration) { [weak self] result in handlePaymentSheetFlowControllerResult(result: result, stripeSdk: self) } } else { self.paymentSheet = PaymentSheet(setupIntentClientSecret: setupIntentClientSecret, configuration: configuration) resolve([]) } } else { resolve(Errors.createError(PaymentSheetErrorType.Failed.rawValue, "You must provide either paymentIntentClientSecret or setupIntentClientSecret")) } } @objc(confirmPaymentSheetPayment:rejecter:) func confirmPaymentSheetPayment(resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) -> Void { DispatchQueue.main.async { if (self.paymentSheetFlowController != nil) { self.paymentSheetFlowController?.confirm(from: UIApplication.shared.delegate?.window??.rootViewController ?? UIViewController()) { paymentResult in switch paymentResult { case .completed: resolve([]) self.paymentSheetFlowController = nil case .canceled: resolve(Errors.createError(PaymentSheetErrorType.Canceled.rawValue, "The payment has been canceled")) case .failed(let error): resolve(Errors.createError(PaymentSheetErrorType.Failed.rawValue, error.localizedDescription)) } } } else { resolve(Errors.createError(PaymentSheetErrorType.Failed.rawValue, "No payment sheet has been initialized yet")) } } } @objc(presentPaymentSheet:rejecter:) func presentPaymentSheet(resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) -> Void { DispatchQueue.main.async { if let paymentSheetFlowController = self.paymentSheetFlowController { paymentSheetFlowController.presentPaymentOptions(from: findViewControllerPresenter(from: UIApplication.shared.delegate?.window??.rootViewController ?? UIViewController()) ) { if let paymentOption = self.paymentSheetFlowController?.paymentOption { let option: NSDictionary = [ "label": paymentOption.label, "image": paymentOption.image.pngData()?.base64EncodedString() ?? "" ] resolve(Mappers.createResult("paymentOption", option)) } else { resolve(Mappers.createResult("paymentOption", nil)) } } } else if let paymentSheet = self.paymentSheet { paymentSheet.present(from: findViewControllerPresenter(from: UIApplication.shared.delegate?.window??.rootViewController ?? UIViewController()) ) { paymentResult in switch paymentResult { case .completed: resolve([]) self.paymentSheet = nil case .canceled: resolve(Errors.createError(PaymentSheetErrorType.Canceled.rawValue, "The payment has been canceled")) case .failed(let error): resolve(Errors.createError(PaymentSheetErrorType.Failed.rawValue, error as NSError)) } } } else { resolve(Errors.createError(PaymentSheetErrorType.Failed.rawValue, "No payment sheet has been initialized yet")) } } } @objc(createTokenForCVCUpdate:resolver:rejecter:) func createTokenForCVCUpdate(cvc: String?, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) { guard let cvc = cvc else { resolve(Errors.createError("Failed", "You must provide CVC")) return; } STPAPIClient.shared.createToken(forCVCUpdate: cvc) { (token, error) in if error != nil || token == nil { resolve(Errors.createError("Failed", error?.localizedDescription ?? "")) } else { let tokenId = token?.tokenId resolve(["tokenId": tokenId]) } } } @objc(confirmSetupIntent:data:options:resolver:rejecter:) func confirmSetupIntent (setupIntentClientSecret: String, params: NSDictionary, options: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) { let type = Mappers.mapToPaymentMethodType(type: params["type"] as? String) guard let paymentMethodType = type else { resolve(Errors.createError(ConfirmPaymentErrorType.Failed.rawValue, "You must provide paymentMethodType")) return } var paymentMethodParams: STPPaymentMethodParams? let factory = PaymentMethodFactory.init(params: params, cardFieldView: cardFieldView, cardFormView: cardFormView) do { paymentMethodParams = try factory.createParams(paymentMethodType: paymentMethodType) } catch { resolve(Errors.createError(ConfirmPaymentErrorType.Failed.rawValue, error.localizedDescription)) return } guard paymentMethodParams != nil else { resolve(Errors.createError(ConfirmPaymentErrorType.Unknown.rawValue, "Unhandled error occured")) return } let setupIntentParams = STPSetupIntentConfirmParams(clientSecret: setupIntentClientSecret) setupIntentParams.paymentMethodParams = paymentMethodParams if let urlScheme = urlScheme { setupIntentParams.returnURL = Mappers.mapToReturnURL(urlScheme: urlScheme) } let paymentHandler = STPPaymentHandler.shared() paymentHandler.confirmSetupIntent(setupIntentParams, with: self) { status, setupIntent, error in switch (status) { case .failed: resolve(Errors.createError(ConfirmSetupIntentErrorType.Failed.rawValue, error)) break case .canceled: if let lastError = setupIntent?.lastSetupError { resolve(Errors.createError(ConfirmSetupIntentErrorType.Canceled.rawValue, lastError)) } else { resolve(Errors.createError(ConfirmSetupIntentErrorType.Canceled.rawValue, "The payment has been canceled")) } break case .succeeded: let intent = Mappers.mapFromSetupIntent(setupIntent: setupIntent!) resolve(Mappers.createResult("setupIntent", intent)) @unknown default: resolve(Errors.createError(ConfirmSetupIntentErrorType.Unknown.rawValue, error)) break } } } @objc(updateApplePaySummaryItems:errorAddressFields:resolver:rejecter:) func updateApplePaySummaryItems(summaryItems: NSArray, errorAddressFields: [NSDictionary], resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) { if (shippingMethodUpdateHandler == nil && shippingContactUpdateHandler == nil) { resolve(Errors.createError(ApplePayErrorType.Failed.rawValue, "You can use this method only after either onDidSetShippingMethod or onDidSetShippingContact events emitted")) return } var paymentSummaryItems: [PKPaymentSummaryItem] = [] if let items = summaryItems as? [[String : Any]] { for item in items { let label = item["label"] as? String ?? "" let amount = NSDecimalNumber(string: item["amount"] as? String ?? "") let type = Mappers.mapToPaymentSummaryItemType(type: item["type"] as? String) paymentSummaryItems.append(PKPaymentSummaryItem(label: label, amount: amount, type: type)) } } var shippingAddressErrors: [Error] = [] for item in errorAddressFields { let field = item["field"] as! String let message = item["message"] as? String ?? field + " error" shippingAddressErrors.append(PKPaymentRequest.paymentShippingAddressInvalidError(withKey: field, localizedDescription: message)) } shippingMethodUpdateHandler?(PKPaymentRequestShippingMethodUpdate.init(paymentSummaryItems: paymentSummaryItems)) shippingContactUpdateHandler?(PKPaymentRequestShippingContactUpdate.init(errors: shippingAddressErrors, paymentSummaryItems: paymentSummaryItems, shippingMethods: [])) self.shippingMethodUpdateHandler = nil self.shippingContactUpdateHandler = nil resolve([]) } @objc(openApplePaySetup:rejecter:) func openApplePaySetup(resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) -> Void { let library = PKPassLibrary.init() if (library.responds(to: #selector(PKPassLibrary.openPaymentSetup))) { library.openPaymentSetup() resolve([]) } else { resolve(Errors.createError("Failed", "Cannot open payment setup")) } } func applePayContext(_ context: STPApplePayContext, didSelect shippingMethod: PKShippingMethod, handler: @escaping (PKPaymentRequestShippingMethodUpdate) -> Void) { self.shippingMethodUpdateHandler = handler sendEvent(withName: "onDidSetShippingMethod", body: ["shippingMethod": Mappers.mapFromShippingMethod(shippingMethod: shippingMethod)]) } func applePayContext(_ context: STPApplePayContext, didSelectShippingContact contact: PKContact, handler: @escaping (PKPaymentRequestShippingContactUpdate) -> Void) { self.shippingContactUpdateHandler = handler sendEvent(withName: "onDidSetShippingContact", body: ["shippingContact": Mappers.mapFromShippingContact(shippingContact: contact)]) } func applePayContext(_ context: STPApplePayContext, didCreatePaymentMethod paymentMethod: STPPaymentMethod, paymentInformation: PKPayment, completion: @escaping STPIntentClientSecretCompletionBlock) { self.applePayCompletionCallback = completion let address = paymentMethod.billingDetails?.address?.line1?.split(whereSeparator: \.isNewline) if (address?.indices.contains(0) == true) { paymentMethod.billingDetails?.address?.line1 = String(address?[0] ?? "") } if (address?.indices.contains(1) == true) { paymentMethod.billingDetails?.address?.line2 = String(address?[1] ?? "") } let method = Mappers.mapFromPaymentMethod(paymentMethod) self.applePayRequestResolver?(Mappers.createResult("paymentMethod", method)) self.applePayRequestRejecter = nil } @objc(confirmApplePayPayment:resolver:rejecter:) func confirmApplePayPayment(clientSecret: String, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) { self.applePayCompletionRejecter = reject self.confirmApplePayPaymentResolver = resolve self.applePayCompletionCallback?(clientSecret, nil) } func applePayContext(_ context: STPApplePayContext, didCompleteWith status: STPPaymentStatus, error: Error?) { switch status { case .success: applePayCompletionRejecter = nil applePayRequestRejecter = nil confirmApplePayPaymentResolver?([]) break case .error: let message = "Payment not completed" applePayCompletionRejecter?(ApplePayErrorType.Failed.rawValue, message, nil) applePayRequestRejecter?(ApplePayErrorType.Failed.rawValue, message, nil) applePayCompletionRejecter = nil applePayRequestRejecter = nil break case .userCancellation: let message = "The payment has been canceled" applePayCompletionRejecter?(ApplePayErrorType.Canceled.rawValue, message, nil) applePayRequestRejecter?(ApplePayErrorType.Canceled.rawValue, message, nil) applePayCompletionRejecter = nil applePayRequestRejecter = nil break @unknown default: let message = "Payment not completed" applePayCompletionRejecter?(ApplePayErrorType.Unknown.rawValue, message, nil) applePayRequestRejecter?(ApplePayErrorType.Unknown.rawValue, message, nil) applePayCompletionRejecter = nil applePayRequestRejecter = nil } } @objc(isApplePaySupported:rejecter:) func isApplePaySupported(resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) { let isSupported = StripeAPI.deviceSupportsApplePay() resolve(isSupported) } @objc(handleURLCallback:resolver:rejecter:) func handleURLCallback(url: String?, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) { guard let url = url else { resolve(false) return; } let urlObj = URL(string: url) if (urlObj == nil) { resolve(false) } else { DispatchQueue.main.async { let stripeHandled = StripeAPI.handleURLCallback(with: urlObj!) resolve(stripeHandled) } } } @objc(presentApplePay:resolver:rejecter:) func presentApplePay(params: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) { if (merchantIdentifier == nil) { reject(ApplePayErrorType.Failed.rawValue, "You must provide merchantIdentifier", nil) return } if (params["jcbEnabled"] as? Bool == true) { StripeAPI.additionalEnabledApplePayNetworks = [.JCB] } guard let summaryItems = params["cartItems"] as? NSArray else { reject(ApplePayErrorType.Failed.rawValue, "You must provide the items for purchase", nil) return } guard let country = params["country"] as? String else { reject(ApplePayErrorType.Failed.rawValue, "You must provide the country", nil) return } guard let currency = params["currency"] as? String else { reject(ApplePayErrorType.Failed.rawValue, "You must provide the payment currency", nil) return } self.applePayRequestResolver = resolve self.applePayRequestRejecter = reject let merchantIdentifier = self.merchantIdentifier ?? "" let paymentRequest = StripeAPI.paymentRequest(withMerchantIdentifier: merchantIdentifier, country: country, currency: currency) let requiredShippingAddressFields = params["requiredShippingAddressFields"] as? NSArray ?? NSArray() let requiredBillingContactFields = params["requiredBillingContactFields"] as? NSArray ?? NSArray() let shippingMethods = params["shippingMethods"] as? NSArray ?? NSArray() paymentRequest.requiredShippingContactFields = Set(requiredShippingAddressFields.map { Mappers.mapToPKContactField(field: $0 as! String) }) paymentRequest.requiredBillingContactFields = Set(requiredBillingContactFields.map { Mappers.mapToPKContactField(field: $0 as! String) }) paymentRequest.shippingMethods = Mappers.mapToShippingMethods(shippingMethods: shippingMethods) var paymentSummaryItems: [PKPaymentSummaryItem] = [] if let items = summaryItems as? [[String : Any]] { for item in items { let label = item["label"] as? String ?? "" let amount = NSDecimalNumber(string: item["amount"] as? String ?? "") let type = Mappers.mapToPaymentSummaryItemType(type: item["type"] as? String) paymentSummaryItems.append(PKPaymentSummaryItem(label: label, amount: amount, type: type)) } } paymentRequest.paymentSummaryItems = paymentSummaryItems if let applePayContext = STPApplePayContext(paymentRequest: paymentRequest, delegate: self) { DispatchQueue.main.async { applePayContext.presentApplePay(completion: nil) } } else { reject(ApplePayErrorType.Failed.rawValue, "Payment not completed", nil) } } func configure3dSecure(_ params: NSDictionary) { let threeDSCustomizationSettings = STPPaymentHandler.shared().threeDSCustomizationSettings let uiCustomization = Mappers.mapUICustomization(params) threeDSCustomizationSettings.uiCustomization = uiCustomization } @objc(createPaymentMethod:options:resolver:rejecter:) func createPaymentMethod( params: NSDictionary, options: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock ) -> Void { let type = Mappers.mapToPaymentMethodType(type: params["type"] as? String) guard let paymentMethodType = type else { resolve(Errors.createError(NextPaymentActionErrorType.Failed.rawValue, "You must provide paymentMethodType")) return } var paymentMethodParams: STPPaymentMethodParams? let factory = PaymentMethodFactory.init(params: params, cardFieldView: cardFieldView, cardFormView: cardFormView) do { paymentMethodParams = try factory.createParams(paymentMethodType: paymentMethodType) } catch { resolve(Errors.createError(NextPaymentActionErrorType.Failed.rawValue, error.localizedDescription)) return } guard let params = paymentMethodParams else { resolve(Errors.createError(NextPaymentActionErrorType.Unknown.rawValue, "Unhandled error occured")) return } STPAPIClient.shared.createPaymentMethod(with: params) { paymentMethod, error in if let createError = error { resolve(Errors.createError(NextPaymentActionErrorType.Failed.rawValue, createError.localizedDescription)) return } if let paymentMethod = paymentMethod { let method = Mappers.mapFromPaymentMethod(paymentMethod) resolve(Mappers.createResult("paymentMethod", method)) } } } @objc(createToken:resolver:rejecter:) func createToken( params: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock ) -> Void { let address = params["address"] as? NSDictionary if let type = params["type"] as? String { if (type != "Card") { resolve(Errors.createError(CreateTokenErrorType.Failed.rawValue, type + " type is not supported yet")) } } guard let cardParams = cardFieldView?.cardParams ?? cardFormView?.cardParams else { resolve(Errors.createError(CreateTokenErrorType.Failed.rawValue, "Card details not complete")) return } let cardSourceParams = STPCardParams() cardSourceParams.number = cardParams.number cardSourceParams.cvc = cardParams.cvc cardSourceParams.expMonth = UInt(truncating: cardParams.expMonth ?? 0) cardSourceParams.expYear = UInt(truncating: cardParams.expYear ?? 0) cardSourceParams.address = Mappers.mapToAddress(address: address) cardSourceParams.name = params["name"] as? String STPAPIClient.shared.createToken(withCard: cardSourceParams) { token, error in if let token = token { resolve(Mappers.createResult("token", Mappers.mapFromToken(token: token))) } else { resolve(Errors.createError(CreateTokenErrorType.Failed.rawValue, error?.localizedDescription)) } } } @objc(handleCardAction:resolver:rejecter:) func handleCardAction( paymentIntentClientSecret: String, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock ){ let paymentHandler = STPPaymentHandler.shared() paymentHandler.handleNextAction(forPayment: paymentIntentClientSecret, with: self, returnURL: nil) { status, paymentIntent, handleActionError in switch (status) { case .failed: resolve(Errors.createError(NextPaymentActionErrorType.Failed.rawValue, handleActionError)) break case .canceled: if let lastError = paymentIntent?.lastPaymentError { resolve(Errors.createError(NextPaymentActionErrorType.Canceled.rawValue, lastError)) } else { resolve(Errors.createError(NextPaymentActionErrorType.Canceled.rawValue, "The payment has been canceled")) } break case .succeeded: if let paymentIntent = paymentIntent { resolve(Mappers.createResult("paymentIntent", Mappers.mapFromPaymentIntent(paymentIntent: paymentIntent))) } break @unknown default: resolve(Errors.createError(NextPaymentActionErrorType.Unknown.rawValue, "Cannot complete payment")) break } } } @objc(confirmPayment:data:options:resolver:rejecter:) func confirmPayment( paymentIntentClientSecret: String, params: NSDictionary, options: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock ) -> Void { self.confirmPaymentResolver = resolve self.confirmPaymentClientSecret = paymentIntentClientSecret let paymentMethodId = params["paymentMethodId"] as? String let paymentIntentParams = STPPaymentIntentParams(clientSecret: paymentIntentClientSecret) if let setupFutureUsage = params["setupFutureUsage"] as? String { paymentIntentParams.setupFutureUsage = Mappers.mapToPaymentIntentFutureUsage(usage: setupFutureUsage) } let type = Mappers.mapToPaymentMethodType(type: params["type"] as? String) guard let paymentMethodType = type else { resolve(Errors.createError(ConfirmPaymentErrorType.Failed.rawValue, "You must provide paymentMethodType")) return } if (paymentMethodType == STPPaymentMethodType.FPX) { let testOfflineBank = params["testOfflineBank"] as? Bool if (testOfflineBank == false || testOfflineBank == nil) { payWithFPX(paymentIntentClientSecret) return } } if paymentMethodId != nil { paymentIntentParams.paymentMethodId = paymentMethodId } else { var paymentMethodParams: STPPaymentMethodParams? var paymentMethodOptions: STPConfirmPaymentMethodOptions? let factory = PaymentMethodFactory.init(params: params, cardFieldView: cardFieldView, cardFormView: cardFormView) do { paymentMethodParams = try factory.createParams(paymentMethodType: paymentMethodType) paymentMethodOptions = try factory.createOptions(paymentMethodType: paymentMethodType) } catch { resolve(Errors.createError(ConfirmPaymentErrorType.Failed.rawValue, error.localizedDescription)) return } guard paymentMethodParams != nil else { resolve(Errors.createError(ConfirmPaymentErrorType.Unknown.rawValue, "Unhandled error occured")) return } paymentIntentParams.paymentMethodParams = paymentMethodParams paymentIntentParams.paymentMethodOptions = paymentMethodOptions paymentIntentParams.shipping = Mappers.mapToShippingDetails(shippingDetails: params["shippingDetails"] as? NSDictionary) } if let urlScheme = urlScheme { paymentIntentParams.returnURL = Mappers.mapToReturnURL(urlScheme: urlScheme) } let paymentHandler = STPPaymentHandler.shared() paymentHandler.confirmPayment(paymentIntentParams, with: self, completion: onCompleteConfirmPayment) } @objc(retrievePaymentIntent:resolver:rejecter:) func retrievePaymentIntent( clientSecret: String, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock ) -> Void { STPAPIClient.shared.retrievePaymentIntent(withClientSecret: clientSecret) { (paymentIntent, error) in guard error == nil else { if let lastPaymentError = paymentIntent?.lastPaymentError { resolve(Errors.createError(RetrievePaymentIntentErrorType.Unknown.rawValue, lastPaymentError)) } else { resolve(Errors.createError(RetrievePaymentIntentErrorType.Unknown.rawValue, error?.localizedDescription)) } return } if let paymentIntent = paymentIntent { resolve(Mappers.createResult("paymentIntent", Mappers.mapFromPaymentIntent(paymentIntent: paymentIntent))) } else { resolve(Errors.createError(RetrievePaymentIntentErrorType.Unknown.rawValue, "Failed to retrieve the PaymentIntent")) } } } @objc(retrieveSetupIntent:resolver:rejecter:) func retrieveSetupIntent( clientSecret: String, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock ) -> Void { STPAPIClient.shared.retrieveSetupIntent(withClientSecret: clientSecret) { (setupIntent, error) in guard error == nil else { if let lastSetupError = setupIntent?.lastSetupError { resolve(Errors.createError(RetrieveSetupIntentErrorType.Unknown.rawValue, lastSetupError)) } else { resolve(Errors.createError(RetrieveSetupIntentErrorType.Unknown.rawValue, error?.localizedDescription)) } return } if let setupIntent = setupIntent { resolve(Mappers.createResult("setupIntent", Mappers.mapFromSetupIntent(setupIntent: setupIntent))) } else { resolve(Errors.createError(RetrieveSetupIntentErrorType.Unknown.rawValue, "Failed to retrieve the SetupIntent")) } } } func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { confirmPaymentResolver?(Errors.createError(ConfirmPaymentErrorType.Canceled.rawValue, "FPX Payment has been canceled")) } func payWithFPX(_ paymentIntentClientSecret: String) { let vc = STPBankSelectionViewController.init(bankMethod: .FPX) vc.delegate = self DispatchQueue.main.async { vc.presentationController?.delegate = self let share = UIApplication.shared.delegate share?.window??.rootViewController?.present(vc, animated: true) } } func bankSelectionViewController(_ bankViewController: STPBankSelectionViewController, didCreatePaymentMethodParams paymentMethodParams: STPPaymentMethodParams) { guard let clientSecret = confirmPaymentClientSecret else { confirmPaymentResolver?(Errors.createError(ConfirmPaymentErrorType.Failed.rawValue, "Missing paymentIntentClientSecret")) return } let paymentIntentParams = STPPaymentIntentParams(clientSecret: clientSecret) paymentIntentParams.paymentMethodParams = paymentMethodParams if let urlScheme = urlScheme { paymentIntentParams.returnURL = Mappers.mapToReturnURL(urlScheme: urlScheme) } let paymentHandler = STPPaymentHandler.shared() bankViewController.dismiss(animated: true) paymentHandler.confirmPayment(paymentIntentParams, with: self, completion: onCompleteConfirmPayment) } func onCompleteConfirmPayment(status: STPPaymentHandlerActionStatus, paymentIntent: STPPaymentIntent?, error: NSError?) { self.confirmPaymentClientSecret = nil switch (status) { case .failed: confirmPaymentResolver?(Errors.createError(ConfirmPaymentErrorType.Failed.rawValue, error)) break case .canceled: let statusCode: String if (paymentIntent?.status == STPPaymentIntentStatus.requiresPaymentMethod) { statusCode = ConfirmPaymentErrorType.Failed.rawValue } else { statusCode = ConfirmPaymentErrorType.Canceled.rawValue } if let lastPaymentError = paymentIntent?.lastPaymentError { confirmPaymentResolver?(Errors.createError(statusCode, lastPaymentError)) } else { confirmPaymentResolver?(Errors.createError(statusCode, "The payment has been canceled")) } break case .succeeded: if let paymentIntent = paymentIntent { let intent = Mappers.mapFromPaymentIntent(paymentIntent: paymentIntent) confirmPaymentResolver?(Mappers.createResult("paymentIntent", intent)) } break @unknown default: confirmPaymentResolver?(Errors.createError(ConfirmPaymentErrorType.Unknown.rawValue, "Cannot complete the payment")) break } } } func findViewControllerPresenter(from uiViewController: UIViewController) -> UIViewController { // Note: creating a UIViewController inside here results in a nil window // This is a bit of a hack: We traverse the view hierarchy looking for the most reasonable VC to present from. // A VC hosted within a SwiftUI cell, for example, doesn't have a parent, so we need to find the UIWindow. var presentingViewController: UIViewController = uiViewController.view.window?.rootViewController ?? uiViewController // Find the most-presented UIViewController while let presented = presentingViewController.presentedViewController { presentingViewController = presented } return presentingViewController } extension StripeSdk: STPAuthenticationContext { func authenticationPresentingViewController() -> UIViewController { return findViewControllerPresenter(from: UIApplication.shared.delegate?.window??.rootViewController ?? UIViewController()) } }
bsd-3-clause
dad4bc69ef3a5900fc701d25801c814a
48.17561
204
0.642421
5.849144
false
false
false
false
Aster0id/Swift-StudyNotes
Swift-StudyNotes/L1-S1-SimpleClass.swift
1
1540
// // L1-S1-SimpleClass.swift // Swift-StudyNotes // // Created by 牛萌 on 15/5/11. // Copyright (c) 2015年 Aster0id.Team. All rights reserved. // import Foundation import UIKit class SimpleClass: ExampleProtocol { var anotherProperty: Int = 69105 // ----------------------------------------- // MARK: 接口和扩展 // ----------------------------------------- var simpleDescription: String = "A very simple class." func adjust() { simpleDescription += " Now 100% adjus ted." } } //!!! 注意: 声明SimpleStructure时候mutating关键字用来标记一个会修改结构体的方法。 // SimpleClass的声明不需要标记任何方法因为类中的方法经常会修改类。 struct SimpleStructure: ExampleProtocol { // ----------------------------------------- // MARK: 接口和扩展 // ----------------------------------------- var simpleDescription: String = "A simple structure" mutating func adjust() { simpleDescription += " (adjusted)" } } // 接口 protocol ExampleProtocol { var simpleDescription: String { get } mutating func adjust() } // Int的接口和拓展 extension Int: ExampleProtocol { var simpleDescription: String { return "The number \(self)" } mutating func adjust() { self += 42 } } extension Double { func absoluteValue()->Double { if (self < 0){ return -self } return self } }
mit
c5377fa5dca1d7a69ef79f6644c9eea0
18.661972
60
0.52149
4.34891
false
false
false
false
Yummypets/YPImagePicker
Source/Filters/Photo/YPFiltersView.swift
1
2050
// // YPFiltersView.swift // photoTaking // // Created by Sacha Durand Saint Omer on 21/10/16. // Copyright © 2016 octopepper. All rights reserved. // import UIKit import Stevia class YPFiltersView: UIView { let imageView = UIImageView() var collectionView: UICollectionView! var filtersLoader: UIActivityIndicatorView! fileprivate let collectionViewContainer: UIView = UIView() convenience init() { self.init(frame: CGRect.zero) collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout()) filtersLoader = UIActivityIndicatorView(style: .gray) filtersLoader.hidesWhenStopped = true filtersLoader.startAnimating() filtersLoader.color = YPConfig.colors.tintColor subviews( imageView, collectionViewContainer.subviews( filtersLoader, collectionView ) ) let isIphone4 = UIScreen.main.bounds.height == 480 let sideMargin: CGFloat = isIphone4 ? 20 : 0 |-sideMargin-imageView.top(0)-sideMargin-| |-sideMargin-collectionViewContainer-sideMargin-| collectionViewContainer.bottom(0) imageView.Bottom == collectionViewContainer.Top |collectionView.centerVertically().height(160)| filtersLoader.centerInContainer() imageView.heightEqualsWidth() backgroundColor = .offWhiteOrBlack imageView.contentMode = .scaleAspectFit imageView.clipsToBounds = true collectionView.backgroundColor = .clear collectionView.showsHorizontalScrollIndicator = false } func layout() -> UICollectionViewFlowLayout { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumLineSpacing = 4 layout.sectionInset = UIEdgeInsets(top: 0, left: 18, bottom: 0, right: 18) layout.itemSize = CGSize(width: 100, height: 120) return layout } }
mit
7317ae98baeba02d764ec97f259af4e9
32.048387
93
0.655442
5.420635
false
false
false
false
LoopKit/LoopKit
LoopKit/CarbKit/NewCarbEntry.swift
1
1661
// // NewCarbEntry.swift // CarbKit // // Created by Nathan Racklyeft on 1/15/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation import HealthKit public struct NewCarbEntry: CarbEntry, Equatable, RawRepresentable { public typealias RawValue = [String: Any] public let date: Date public let quantity: HKQuantity public let startDate: Date public let foodType: String? public let absorptionTime: TimeInterval? public init(date: Date = Date(), quantity: HKQuantity, startDate: Date, foodType: String?, absorptionTime: TimeInterval?) { self.date = date self.quantity = quantity self.startDate = startDate self.foodType = foodType self.absorptionTime = absorptionTime } public init?(rawValue: RawValue) { guard let date = rawValue["date"] as? Date, let grams = rawValue["grams"] as? Double, let startDate = rawValue["startDate"] as? Date else { return nil } self.init( date: date, quantity: HKQuantity(unit: .gram(), doubleValue: grams), startDate: startDate, foodType: rawValue["foodType"] as? String, absorptionTime: rawValue["absorptionTime"] as? TimeInterval ) } public var rawValue: RawValue { var rawValue: RawValue = [ "date": date, "grams": quantity.doubleValue(for: .gram()), "startDate": startDate ] rawValue["foodType"] = foodType rawValue["absorptionTime"] = absorptionTime return rawValue } }
mit
45ac23849493d027d9db5c15c38a792d
26.666667
127
0.608434
4.955224
false
false
false
false
milk-cocoa/milkcocoa-swift-sdk
MilkCocoa/DataStore.swift
1
5058
/* // // DataStore.swift // MilkCocoa // // Created by HIYA SHUHEI on 2015/11/03. // The MIT License (MIT) Copyright (c) 2014 Technical Rockstars, Inc Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation public class DataStore { private var milkcocoa : MilkCocoa private var path : String private var send_callback : ((DataElement)->Void)? private var push_callback : ((DataElement)->Void)? public init(milkcocoa: MilkCocoa, path: String) { self.milkcocoa = milkcocoa; self.path = path; self.send_callback = nil; } public func on(event: String, callback: (DataElement)->Void) { self.milkcocoa.subscribe(self.path, event: event) if(event == "send") { self.send_callback = callback }else if(event == "push"){ self.push_callback = callback } } public func send(params : [String: AnyObject]) { self.milkcocoa.publish(self.path, event: "send", params: [ "params":params]) } public func push(params : [String: AnyObject]) { self.milkcocoa.publish(self.path, event: "push", params: [ "params":params]) } public func _fire_send(params : DataElement) { if let _send_cb = self.send_callback { _send_cb(params) } } public func _fire_push(params : DataElement) { if let _send_cb = self.push_callback { _send_cb(params) } } public func history()->History { return History(datastore: self) } } public class DataElement { private var _data : [String: AnyObject]; public init(_data : [String: AnyObject]) { self._data = Dictionary(); self.fromRaw(_data); } public func fromRaw(rawdata : [String: AnyObject]) { self._data["id"] = rawdata["id"] do { if(rawdata["params"] != nil) { //in case of on let params = rawdata["params"] self._data["value"] = params }else if(rawdata["value"] != nil) { //in case of query let valueJSON = rawdata["value"] as! String let valueJSON_data = valueJSON.dataUsingEncoding(NSUTF8StringEncoding) self._data["value"] = try NSJSONSerialization.JSONObjectWithData(valueJSON_data!, options: NSJSONReadingOptions.AllowFragments) as! [String: AnyObject] } } catch let error as NSError { print(error) } } public func getId()->String { return self._data["id"] as! String; } public func getValue()->[String: AnyObject] { return self._data; } public func getValue(key:String)->AnyObject? { return self._data[key]; } } public protocol HistoryDelegate : class { func onData(dataelement: DataElement); func onError(error: NSError); func onEnd(); } public class History { public weak var delegate: HistoryDelegate? private var datastore : DataStore; private var onDataHandler :([DataElement]->Void)? private var onErrorHandler :(NSError->Void)? public init(datastore: DataStore) { self.datastore = datastore self.onDataHandler = nil } public func onData(h:[DataElement]->Void) { self.onDataHandler = h } public func onError(h:NSError->Void) { self.onErrorHandler = h } public func run() { self.datastore.milkcocoa.call("query", params: ["path":self.datastore.path, "limit":"50", "sort":"DESC"], callback: { data -> Void in print(data) /* let content = data["content"] let dataelementlist:[DataElement]? = content!["d"].map({ DataElement(_data: $0 as! [String : AnyObject]) }) self.onDataHandler?(dataelementlist!) */ }, error_handler: { (error) -> Void in self.onErrorHandler?(error) }) } }
mit
61bf9333f22d660c9f41129bde77082a
31.012658
167
0.611507
4.31202
false
false
false
false
findmybusnj/findmybusnj-swift
findmybusnj-widget/Presenters/WidgetBannerPresenter.swift
1
1394
// // WidgetBannerPresenter.swift // findmybusnj // // Created by David Aghassi on 2/21/17. // Copyright © 2017 David Aghassi. All rights reserved. // import UIKit // Dependencies import SwiftyJSON import findmybusnj_common /** Class for managing the next bus banner at the top of the widget */ class WidgetBannerPresenter: ETAPresenter { var sanitizer = JSONSanitizer() /** Assigns the banner the proper string based on the current arrival information */ func assignTextForArrivalBanner(label: UILabel, json: JSON) { label.text = "The next bus will be" let arrivalCase = determineArrivalCase(json: json) switch arrivalCase { case "Arrived": label.text = "The next bus has \(arrivalCase.lowercased())" return case"Arriving": label.text = "The next bus is \(arrivalCase.lowercased())" return case "Delay": label.text = "\(label.text ?? "") delayed" return default: let arrivalTime = sanitizer.getSanitizedArrivaleTimeAsInt(json) label.text = "\(label.text ?? "") \(arrivalTime.description) min." return } } // no-ops since they aren't used by this presenter func formatCellForPresentation(_ cell: UITableViewCell, json: JSON) {} func assignArrivalTimeForJson(_ cell: UITableViewCell, json: JSON) {} func assignBusAndRouteTextForJson(_ cell: UITableViewCell, json: JSON) {} }
gpl-3.0
0a31f9b938d892aca0c639851566a12a
27.428571
80
0.691314
4.073099
false
false
false
false
tokyovigilante/CesiumKit
CesiumKit/Renderer/Uniform.swift
1
12113
// // Uniform.swift // CesiumKit // // Created by Ryan Walklin on 9/12/14. // Copyright (c) 2014 Test Toast. All rights reserved. // import GLSLOptimizer import Accelerate import simd public enum UniformDataType: UInt { case floatVec1 = 5126, // GLenum(GL_FLOAT) floatVec2 = 35664, // GLenum(GL_FLOAT_VEC2) floatVec3 = 35665, // GLenum(GL_FLOAT_VEC3) floatVec4 = 35666, // GLenum(GL_FLOAT_VEC4) intVec1 = 5124, // GLenum(GL_INT) intVec2 = 35667, // GLenum(GL_INT_VEC2) intVec3 = 35668, // GLenum(GL_INT_VEC3) intVec4 = 35669, // GLenum(GL_INT_VEC4) boolVec1 = 35670, // GLenum(GL_BOOL) boolVec2 = 35671, // GLenum(GL_BOOL_VEC2) boolVec3 = 35672, // GLenum(GL_BOOL_VEC3) boolVec4 = 35673, // GLenum(GL_BOOL_VEC4) floatMatrix2 = 35674, // GLenum(GL_FLOAT_MAT2) floatMatrix3 = 35675, // GLenum(GL_FLOAT_MAT3) floatMatrix4 = 35676, // GLenum(GL_FLOAT_MAT4) sampler2D = 35678, // GLenum(GL_SAMPLER_2D) samplerCube = 35680 // GLenum(GL_SAMPLER_CUBE) var declarationString: String { switch self { case .floatVec1: return "float" case .floatVec2: return "vec2" case .floatVec3: return "vec3" case .floatVec4: return "vec4" case .intVec1: return "int" case .intVec2: return "ivec2" case .intVec3: return "ivec3" case .intVec4: return "ivec4" case .boolVec1: return "bool" case .boolVec2: return "bvec2" case .boolVec3: return "bvec3" case .boolVec4: return "bvec4" case .floatMatrix2: return "mat2" case .floatMatrix3: return "mat3" case .floatMatrix4: return "mat4" case .sampler2D: return "sampler2D" case .samplerCube: return "samplerCube" } } var metalDeclaration: String { switch self { case .floatVec1: return "float" case .floatVec2: return "float2" case .floatVec3: return "float3" case .floatVec4: return "float4" /*case .IntVec1: return "int" case .IntVec2: return "ivec2" case .IntVec3: return "ivec3" case .IntVec4: return "ivec4" case .BoolVec1: return "bool" case .BoolVec2: return "bvec2" case .BoolVec3: return "bvec3" case .BoolVec4: return "bvec4"*/ case .floatMatrix2: return "float2x2" case .floatMatrix3: return "float3x3" case .floatMatrix4: return "float4x4" case .sampler2D: return "sampler" default: assertionFailure("unimplemented") return "" } } var elementCount: Int { switch self { case .floatVec1: return 1 case .floatVec2: return 2 case .floatVec3: return 3 case .floatVec4: return 4 case .intVec1: return 1 case .intVec2: return 2 case .intVec3: return 3 case .intVec4: return 4 case .boolVec1: return 1 case .boolVec2: return 2 case .boolVec3: return 3 case .boolVec4: return 4 case .floatMatrix2: return 4 case .floatMatrix3: return 9 case .floatMatrix4: return 16 case .sampler2D: return 1 case .samplerCube: return 1 } } var alignment: Int { switch self { case .floatVec1: return 4 case .floatVec2: return 8 case .floatVec3: return 16 case .floatVec4: return 16 case .intVec1: return 4 case .intVec2: return 8 case .intVec3: return 16 case .intVec4: return 16 case .boolVec1: return 1 case .boolVec2: return 2 case .boolVec3: return 4 case .boolVec4: return 4 case .floatMatrix2: return 8 case .floatMatrix3: return 16 case .floatMatrix4: return 16 default: assertionFailure("not valid uniform type") return 0 } } var elementStride: Int { switch self { case .floatVec1: return MemoryLayout<Float>.stride case .floatVec2: return MemoryLayout<float2>.stride case .floatVec3: return MemoryLayout<float4>.stride case .floatVec4: return MemoryLayout<float4>.stride case .intVec1: return MemoryLayout<Int32>.stride case .intVec2: return MemoryLayout<int2>.stride case .intVec3: return MemoryLayout<int4>.stride case .intVec4: return MemoryLayout<int4>.stride case .floatMatrix2: return MemoryLayout<float2>.stride case .floatMatrix3: return MemoryLayout<float4>.stride case .floatMatrix4: return MemoryLayout<float4>.stride default: assertionFailure("invalid element") return 0 } } } typealias UniformFunc = (_ map: LegacyUniformMap, _ buffer: Buffer, _ offset: Int) -> () struct AutomaticUniform { let size: Int let datatype: UniformDataType func declaration (_ name: String) -> String { var declaration = "uniform \(datatype.declarationString) \(name)" if size == 1 { declaration += ";" } else { declaration += "[\(size)];" } return declaration } } enum UniformType { case automatic, // czm_a frustum, // czm_f manual, // u_ sampler } open class Uniform { fileprivate let _desc: GLSLShaderVariableDescription let dataType: UniformDataType let type: UniformType let elementCount: Int var offset: Int = -1 var name: String { return _desc.name } var rawSize: Int { return Int(_desc.rawSize()) } var alignedSize: Int { return dataType.elementStride * Int(_desc.matSize > 0 ? _desc.matSize : 1) * Int(_desc.arraySize > 0 ? _desc.arraySize : 1) } var isSingle: Bool { return _desc.arraySize == -1 } var basicType: GLSLOptBasicType { return self._desc.type } var mapIndex: UniformIndex? = nil init (desc: GLSLShaderVariableDescription, type: UniformType, dataType: UniformDataType) { _desc = desc self.type = type elementCount = Int(desc.elementCount()) self.dataType = dataType } static func create(desc: GLSLShaderVariableDescription, type: UniformType) -> Uniform { switch desc.type { case .float: let dataType = inferDataTypeFromGLSLDescription(desc) return Uniform(desc: desc, type: type, dataType: dataType) /*case Int // kGlslTypeInt, return UniformFloat(variableDescription: variableDescription) case Bool // kGlslTypeBool, return UniformBool(variableDescription: variableDescription)*/ case .tex2D: // kGlslTypeTex2D, return UniformSampler(desc: desc, type: type, dataType: .sampler2D) //case .Tex3D: // kGlslTypeTex3D, // return UniformSampler(desc: desc, type: type, dataType: .Sampler3D) case .texCube: // kGlslTypeTexCube, return UniformSampler(desc: desc, type: type, dataType: .samplerCube) default: assertionFailure("Unimplemented") return Uniform(desc: desc, type: type, dataType: .floatVec1) } } static func inferDataTypeFromGLSLDescription (_ desc: GLSLShaderVariableDescription) -> UniformDataType { if desc.matSize == 1 { //vector switch desc.vecSize { case 1: if desc.type == .float { return .floatVec1 } if desc.type == .int { return .intVec1 } if desc.type == .bool { return .boolVec1 } case 2: if desc.type == .float { return .floatVec2 } if desc.type == .int { return .intVec2 } if desc.type == .bool { return .boolVec2 } case 3: if desc.type == .float { return .floatVec3 } if desc.type == .int { return .intVec3 } if desc.type == .bool { return .boolVec3 } case 4: if desc.type == .float { return .floatVec4 } if desc.type == .int { return .intVec4 } if desc.type == .bool { return .boolVec4 } default: assertionFailure("unknown uniform type") } } if desc.matSize == 2 { //Matrix2 switch desc.vecSize { case 2: if desc.type == .float { return .floatMatrix2 } default: assertionFailure("unknown uniform type") } } if desc.matSize == 3 { // Matrix3 switch desc.vecSize { case 3: if desc.type == .float { return .floatMatrix3 } default: assertionFailure("unknown uniform type") } } if desc.matSize == 4 { // Matrix4 switch desc.vecSize { case 4: if desc.type == .float { return .floatMatrix4 } default: assertionFailure("unknown uniform type") } } assertionFailure("unknown uniform type") return .floatVec1 } } typealias UniformIndex = DictionaryIndex<String, UniformFunc> /* case gl.INT: case gl.BOOL: return function() { var value = uniformArray.value; var length = value.length; for (var i = 0; i < length; ++i) { gl.uniform1i(locations[i], value[i]); } }; case gl.INT_VEC2: case gl.BOOL_VEC2: return function() { var value = uniformArray.value; var length = value.length; for (var i = 0; i < length; ++i) { var v = value[i]; gl.uniform2i(locations[i], v.x, v.y); } }; case gl.INT_VEC3: case gl.BOOL_VEC3: return function() { var value = uniformArray.value; var length = value.length; for (var i = 0; i < length; ++i) { var v = value[i]; gl.uniform3i(locations[i], v.x, v.y, v.z); } }; case gl.INT_VEC4: case gl.BOOL_VEC4: return function() { var value = uniformArray.value; var length = value.length; for (var i = 0; i < length; ++i) { var v = value[i]; gl.uniform4i(locations[i], v.x, v.y, v.z, v.w); } }; case gl.FLOAT_MAT2: return function() { var value = uniformArray.value; var length = value.length; for (var i = 0; i < length; ++i) { gl.uniformMatrix2fv(locations[i], false, Matrix2.toArray(value[i], scratchUniformMatrix2)); } }; case gl.FLOAT_MAT3: return function() { var value = uniformArray.value; var length = value.length; for (var i = 0; i < length; ++i) { gl.uniformMatrix3fv(locations[i], false, Matrix3.toArray(value[i], scratchUniformMatrix3)); }*/ /* class UniformFloatMatrix4: FloatUniform { override init(activeUniform: ActiveUniformInfo, name: String, locations: [GLint]) { super.init(activeUniform: activeUniform, name: name, locations: locations) } override func set () { if isChanged() { glUniformMatrix4fv(_locations[0], GLsizei(_locations.count), GLboolean(GL_FALSE), UnsafePointer<GLfloat>(_values)) } } }*/ open class UniformSampler: Uniform { fileprivate (set) var textureUnitIndex: Int = 0 func setSampler (_ textureUnitIndex: Int) { self.textureUnitIndex = textureUnitIndex } }
apache-2.0
82f3f8ac5d5bf5871a7f5194fb07fce9
26.037946
131
0.548171
3.931516
false
false
false
false
ivanbruel/SwipeIt
Pods/MarkdownKit/MarkdownKit/Classes/Elements/MarkdownList.swift
1
1115
// // MarkdownList.swift // Pods // // Created by Ivan Bruel on 18/07/16. // // import UIKit public class MarkdownList: MarkdownLevelElement { private static let regex = "^([\\*\\+\\-]{1,%@})\\s+(.+)$" public var maxLevel: Int public var font: UIFont? public var color: UIColor? public var separator: String public var indicator: String public var regex: String { let level: String = maxLevel > 0 ? "\(maxLevel)" : "" return String(format: MarkdownList.regex, level) } public init(font: UIFont? = nil, maxLevel: Int = 0, indicator: String = "•", separator: String = " ", color: UIColor? = nil) { self.maxLevel = maxLevel self.indicator = indicator self.separator = separator self.font = font self.color = color } public func formatText(attributedString: NSMutableAttributedString, range: NSRange, level: Int) { var string = (0..<level).reduce("") { (string, _) -> String in return "\(string)\(separator)" } string = "\(string)\(indicator) " attributedString.replaceCharactersInRange(range, withString: string) } }
mit
0cbe76ff748d18cee16c771e00ed4d9f
25.5
104
0.639712
3.932862
false
false
false
false
gribozavr/swift
test/NameBinding/Dependencies/private-protocol-conformer-fine.swift
1
1286
// REQUIRES: shell // Also uses awk: // XFAIL OS=windows // RUN: %target-swift-frontend -enable-fine-grained-dependencies -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DOLD -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-OLD // RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh <%t.swiftdeps >%t-processed.swiftdeps // RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t-processed.swiftdeps // RUN: %target-swift-frontend -enable-fine-grained-dependencies -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DNEW -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-NEW // RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh <%t.swiftdeps >%t-processed.swiftdeps // RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t-processed.swiftdeps private struct Test : InterestingProto {} // CHECK-OLD: sil_global @$s4main1x{{[^ ]+}} : $Int // CHECK-NEW: sil_global @$s4main1x{{[^ ]+}} : $Double public var x = Test().make() + 0 // CHECK-DEPS-DAG: topLevel interface '' InterestingProto false // CHECK-DEPS-DAG: member interface 4main{{8IntMaker|11DoubleMaker}}P make false // CHECK-DEPS-DAG: nominal interface 4main{{8IntMaker|11DoubleMaker}}P '' false
apache-2.0
fac5519380ed23e2987856dfb03c4ba5
54.913043
237
0.727838
3.297436
false
true
false
false
yaxunliu/douyu-TV
douyu-TV/douyu-TV/Classes/Main/View/PageContentView.swift
1
5553
// // PageContentView.swift // Douyu-TV // // Created by 刘亚勋 on 16/10/9. // Copyright © 2016年 刘亚勋. All rights reserved. // import UIKit protocol PageContentViewDelegate : class { /// 内容视图发生滚动 func contentViewDidScroll(_ sourceIndex : Int ,targetIndex : Int , progress : CGFloat) } private let contentViewID = "contentViewID" class PageContentView: UIView { // MARK: ----- 懒加载collectionView fileprivate lazy var collectionView : UICollectionView = {[weak self] in let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = UICollectionViewScrollDirection(rawValue: 1)! let collectionV : UICollectionView = UICollectionView(frame: self!.bounds, collectionViewLayout: layout) collectionV.dataSource = self collectionV.delegate = self collectionV.bounces = false collectionV.showsHorizontalScrollIndicator = false collectionV.isPagingEnabled = true collectionV.register(UICollectionViewCell.self, forCellWithReuseIdentifier: contentViewID) return collectionV }() // MARK:- ----- 构造函数 init(frame: CGRect ,childVcs :[UIViewController] ,parentVc:UIViewController) { self.childVcs = childVcs self.parentVc = parentVc super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: ----- 定义属性 var startOffsetx : CGFloat = 0 fileprivate var isFrobitScrollDelegate : Bool = false weak var delegate : PageContentViewDelegate! fileprivate var childVcs : [UIViewController] fileprivate weak var parentVc : UIViewController? // MARK: ----- 对外公开方法 /// 设置当前下标 open func setCurrentIndex(_ index : Int) { isFrobitScrollDelegate = true let offsetX = CGFloat(index) * collectionView.frame.size.width collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false) } } // 设置UI信息 private extension PageContentView{ func setupUI(){ /// 1.添加所有的子控制器 addAllChildVc() /// 2.添加collectionView addSubview(collectionView) } /// 添加所有的子控制器 func addAllChildVc(){ for childVc in childVcs{ self.parentVc?.addChildViewController(childVc) } } } extension PageContentView : UICollectionViewDelegate{ func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isFrobitScrollDelegate = false /// 开始滑动的x轴的位置 startOffsetx = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { if isFrobitScrollDelegate == true { return } /// 1.初始化需要获取到的值 var sourceIndex : Int = 0 var targetIndex : Int = 0 var progress : CGFloat = 0 /// 2.计算参数值 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = collectionView.frame.size.width if currentOffsetX > startOffsetx {// 左滑 let radius = currentOffsetX / scrollViewW //源索引 sourceIndex = Int(currentOffsetX / scrollViewW) //目标索引 targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } if currentOffsetX - startOffsetx == scrollViewW{ progress = 1 targetIndex = sourceIndex } //进度 progress = 1 - (CGFloat(targetIndex) - radius) }else{// 右滑 //进度 let radius = currentOffsetX / scrollViewW //目标索引 targetIndex = Int(currentOffsetX / scrollViewW) //源索引 sourceIndex = targetIndex + 1 progress = CGFloat(sourceIndex) - radius if sourceIndex >= childVcs.count { sourceIndex = childVcs.count - 1 } } //3.通知代理 delegate.contentViewDidScroll(sourceIndex, targetIndex: targetIndex, progress: progress) } } extension PageContentView : UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentViewID, for: indexPath) for view in cell.contentView.subviews{ view.removeFromSuperview() } let vc = childVcs[indexPath.row] vc.view.frame = cell.bounds cell.contentView.addSubview(vc.view) return cell } }
apache-2.0
87502ba98b8ecf6761054d4d2ece1745
24.615385
121
0.579955
5.741379
false
false
false
false
FoodForTech/Handy-Man
HandyMan/HandyMan/HandyManCore/Spring/SpringTextView.swift
1
2688
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit open class SpringTextView: UITextView, Springable { @IBInspectable open var autostart: Bool = false @IBInspectable open var autohide: Bool = false @IBInspectable open var animation: String = "" @IBInspectable open var force: CGFloat = 1 @IBInspectable open var delay: CGFloat = 0 @IBInspectable open var duration: CGFloat = 0.7 @IBInspectable open var damping: CGFloat = 0.7 @IBInspectable open var velocity: CGFloat = 0.7 @IBInspectable open var repeatCount: Float = 1 @IBInspectable open var x: CGFloat = 0 @IBInspectable open var y: CGFloat = 0 @IBInspectable open var scaleX: CGFloat = 1 @IBInspectable open var scaleY: CGFloat = 1 @IBInspectable open var rotate: CGFloat = 0 @IBInspectable open var curve: String = "" open var opacity: CGFloat = 1 open var animateFrom: Bool = false lazy fileprivate var spring : Spring = Spring(self) override open func awakeFromNib() { super.awakeFromNib() self.spring.customAwakeFromNib() } override open func didMoveToWindow() { super.didMoveToWindow() self.spring.customDidMoveToWindow() } open func animate() { self.spring.animate() } open func animateNext(_ completion: @escaping () -> ()) { self.spring.animateNext(completion) } open func animateTo() { self.spring.animateTo() } open func animateToNext(_ completion: @escaping () -> ()) { self.spring.animateToNext(completion) } }
mit
14287bbac0aad823b85cc1af1bd1df09
36.333333
81
0.706101
4.610635
false
false
false
false
grehujt/learningSwift
chapter-3-12 storyboard 5/demoApp/demoApp/ViewController.swift
1
1490
// // ViewController.swift // demoApp // // Created by kris on 8/13/16. // Copyright © 2016 kris. All rights reserved. // import UIKit class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { let images = ["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let id = "reusedCell" let cell = collectionView.dequeueReusableCellWithReuseIdentifier(id, forIndexPath: indexPath) let imageView = cell.viewWithTag(1) as! UIImageView imageView.image = UIImage(named: images[indexPath.row]) imageView.layer.opacity = 0.5 return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let cell = collectionView.cellForItemAtIndexPath(indexPath) let imageView = cell?.viewWithTag(1) imageView?.layer.opacity = 1 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
40494a1c3872d8407fae868528a4b59f
31.369565
130
0.684352
4.898026
false
false
false
false
TheDarkCode/Example-Swift-Apps
Exercises and Basic Principles/pokedex-exercise/pokedex-exercise/ViewControllerPreviewing.swift
1
2459
// // ViewControllerPreviewing.swift // pokedex-exercise // // Created by Mark Hamilton on 3/13/16. // Copyright © 2016 dryverless. All rights reserved. // import Foundation import UIKit extension ViewController: UIViewControllerPreviewingDelegate { // MARK: UIViewControllerPreviewingDelegate /// Create a previewing view controller to be shown at "Peek". func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { // Obtain the index path and the cell that was pressed. var updatedLocation = location updatedLocation.y -= 116.0 // Account for cell height (from Storyboard) guard let indexPath = collectionView.indexPathForItemAtPoint(updatedLocation), cell = collectionView.cellForItemAtIndexPath(indexPath) else { return nil } // Create a AZSDetailVC and set its properties. guard let PokemonDetailVC = storyboard?.instantiateViewControllerWithIdentifier("PokemonDetailVC") as? PokemonDetailVC else { return nil } var touchedPokemon: Pokemon! if searchActive { if let pokemon: Pokemon = self.filteredPokemon[indexPath.row] { touchedPokemon = pokemon } } else { if let pokemon: Pokemon = self.pokemon[indexPath.row] { touchedPokemon = pokemon } } // Pass previewDetail to PokemonDetailVC here PokemonDetailVC.pokemon = touchedPokemon PokemonDetailVC.preferredContentSize = CGSize(width: 0.0, height: 0.0) // Default height and width // Set the source rect to the cell frame, so surrounding elements are blurred. previewingContext.sourceRect = cell.frame return PokemonDetailVC } /// Present the view controller for the "Pop" action. func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) { // Reuse the "Peek" view controller for presentation. showViewController(viewControllerToCommit, sender: self) } }
mit
c10446dd6a4258dbec332f57f505c6e5
29.345679
146
0.61188
6.367876
false
false
false
false
gssdromen/CedFilterView
FilterTest/CedFilterView/CedFilterOperation.swift
1
2978
// // CedFilterOperation.swift // SecondHandHouseBroker // // Created by Cedric Wu on 16/3/21. // Copyright © 2016年 Cedric Wu. All rights reserved. // import Foundation // 是否有一个chain是另一个的子集,用来判断是否需要高亮 func ~=(left: CedFilterChain, right: CedFilterChain) -> Bool { weak var pLeftNode = left.startNode weak var pRightNode = right.startNode if pLeftNode == nil && pRightNode == nil { return true } else if pLeftNode != nil && pRightNode == nil { return false } else if pLeftNode == nil && pRightNode != nil { return false } var flag = true while pLeftNode != nil && pRightNode != nil { if pLeftNode! != pRightNode! { flag = false break } if pLeftNode!.next != nil && pRightNode!.next != nil { pLeftNode = pLeftNode!.next pRightNode = pRightNode!.next } else { flag = true break } } return flag // let leftCopy = left.copy() // let rightCopy = right.copy() // var leftNode: CedFilterNode! = leftCopy.startNode // var rightNode: CedFilterNode! = rightCopy.startNode // if leftNode == nil && rightNode == nil { // return true // } // // var flag = true // // while leftNode != nil && rightNode != nil { // if leftNode != rightNode { // flag = false // break // } // if leftNode.next != nil && rightNode.next != nil { // leftNode = leftNode.next // rightNode = rightNode.next // } else { // flag = true // break // } // } // return flag } // 判断两个chain是否完全相等 func ==(left: CedFilterChain, right: CedFilterChain) -> Bool { weak var pLeftNode: CedFilterNode? = left.startNode weak var pRightNode: CedFilterNode? = right.startNode if pLeftNode == nil && pRightNode == nil { return true } var flag = true while pLeftNode != nil && pRightNode != nil { if pLeftNode! != pRightNode! { flag = false break } else { pLeftNode = pLeftNode?.next pRightNode = pRightNode?.next if pLeftNode == nil && pRightNode == nil { break } else if pLeftNode != nil && pRightNode != nil { continue } else { flag = false break } } } return flag } func ==(left: CedFilterNode, right: CedFilterNode) -> Bool { var flag = false if left.section == right.section && left.column == right.column && left.row == right.row { flag = true } return flag } func !=(left: CedFilterNode, right: CedFilterNode) -> Bool { var flag = false if left.section != right.section || left.column != right.column || left.row != right.row { flag = true } return flag }
gpl-3.0
233e3094feabf1df4f540cfa35129bb1
24.743363
94
0.539361
3.773022
false
false
false
false
NathanE73/Blackboard
Sources/BlackboardFramework/Source Code/Naming.swift
1
3664
// // Copyright (c) 2022 Nathan E. Walczak // // MIT License // // 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 enum Naming { static var keywords = [ // used in declarations "associatedtype", "class", "deinit", "enum", "extension", "fileprivate", "func", "import", "init", "inout", "internal", "let", "open", "operator", "private", "protocol", "public", "rethrows", "static", "struct", "subscript", "typealias", "var", // used in statements "break", "case", "continue", "default", "defer", "do", "else", "fallthrough", "for", "guard", "if", "in", "repeat", "return", "switch", "where", "while", // used in expressions and types "as", "Any", "catch", "false", "is", "nil", "super", "self", "Self", "throw", "throws", "true", "try", // reserved in particular contexts "associativity", "convenience", "dynamic", "didSet", "final", "get", "infix", "indirect", "lazy", "left", "mutating", "none", "nonmutating", "optional", "override", "postfix", "precedence", "prefix", "Protocol", "required", "right", "set", "Type", "unowned", "weak", "and willSet" ] static func escapeKeyword(_ identifier: String) -> String { keywords.contains(identifier) ? "`\(identifier)`" : identifier } static func methodName(from identifier: String, prefix: String? = nil) -> String { var name = identifier if name.startsWithDecimalDigit { name = "number\(name)" } if let prefix = prefix { name = "\(prefix).\(name)" } return self.name(from: name, prefix: prefix) .firstCharacterLowercased } static func name(from identifier: String, prefix: String? = nil) -> String { identifier.split { character in for unicodeScalar in character.unicodeScalars { if !CharacterSet.alphanumerics.contains(unicodeScalar) { return true } } return false } .map { part in if part == part.uppercased() { return part.lowercased().firstCharacterUppercased } return String(part).firstCharacterUppercased } .joined() } static func namespace(from namespaces: String?...) -> String? { let namespaces = namespaces.compactMap { $0 } if namespaces.isEmpty { return nil } return namespaces.joined(separator: "/") } }
mit
19d4355fee7e8fb92fc3ac48e6d13dbb
37.568421
87
0.602893
4.585732
false
false
false
false
tensorflow/swift-models
Examples/GrowingNeuralCellularAutomata/SamplePool.swift
1
2944
// Copyright 2020 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import TensorFlow struct SamplePool { var samples: [Tensor<Float>] let initialState: Tensor<Float> init(initialState: Tensor<Float>, size: Int) { samples = [Tensor<Float>](repeating: initialState, count: size) self.initialState = initialState } // This rearranges the pool to place the randomly sampled batch upfront, for easy replacement later. mutating func sample(batchSize: Int, damaged: Int = 0) -> Tensor<Float> { for index in 0..<batchSize { let choice = Int.random(in: index..<samples.count) if index != choice { samples.swapAt(index, choice) } } // TODO: Have this sorted by loss. samples[0] = initialState if damaged > 0 { for damagedIndex in (batchSize - damaged - 1)..<batchSize { samples[damagedIndex] = samples[damagedIndex].applyCircleDamage() } } return Tensor(stacking: Array(samples[0..<batchSize])) } mutating func replace(samples: Tensor<Float>) { let samplesToInsert = samples.unstacked() self.samples.replaceSubrange(0..<samplesToInsert.count, with: samplesToInsert) } } extension Tensor where Scalar == Float { func applyCircleDamage() -> Tensor { let width = self.shape[self.rank - 2] let height = self.shape[self.rank - 3] let radius = Float.random(in: 0.1..<0.4) let centerX = Float.random(in: -0.5..<0.5) let centerY = Float.random(in: -0.5..<0.5) var x = Tensor<Float>(linearSpaceFrom: -1.0, to: 1.0, count: width, on: self.device) var y = Tensor<Float>(linearSpaceFrom: -1.0, to: 1.0, count: height, on: self.device) x = ((x - centerX) / radius).broadcasted(to: [height, width]) y = ((y - centerY) / radius).expandingShape(at: 1).broadcasted(to: [height, width]) let distanceFromCenter = (x * x + y * y).expandingShape(at: 2) let circleMask = distanceFromCenter.mask { $0 .> 1.0 } return self * circleMask } // TODO: Extend this to arbitrary rectangular sections. func damageRightSide() -> Tensor { let width = self.shape[self.rank - 2] let height = self.shape[self.rank - 3] var x = Tensor<Float>(linearSpaceFrom: -1.0, to: 1.0, count: width, on: self.device) x = x.broadcasted(to: [height, width]).expandingShape(at: 2) let rectangleMask = x.mask { $0 .< 0.0 } return self * rectangleMask } }
apache-2.0
626fe257cabaf63c439d698266e9a241
37.233766
102
0.674592
3.666252
false
false
false
false
mzp/OctoEye
Tests/UI/LogoutTest.swift
1
914
// // LogoutTest.swift // UITest // // Created by mzp on 2017/07/31. // Copyright © 2017 mzp. All rights reserved. // import XCTest internal class LogoutTest: XCTestCase { override func setUp() { super.setUp() continueAfterFailure = false let app = XCUIApplication() app.launchArguments = ["setAccessToken"] app.launch() } public func testLogoutForm() { let app = XCUIApplication() // switch to preferences page app.tabBars.buttons["Preferences"].tap() // show logout button, and not show login button XCTAssert(!app.buttons["login"].exists) let logoutCell = app.tables.cells.containing(.staticText, identifier: "Logout").element XCTAssert(logoutCell.exists) // if tap logout button, login screen will show logoutCell.tap() XCTAssert(app.buttons["login"].exists) } }
mit
703ac866fe64363883a7b2ccc9f3941e
25.085714
95
0.629792
4.389423
false
true
false
false
khizkhiz/swift
test/1_stdlib/alloc_rounding.swift
7
546
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test struct Buffer32 { var x0: UInt64 = 0 var x1: UInt64 = 0 var x2: UInt64 = 0 var x3: UInt64 = 0 } func foo() -> UInt64 { var buffer = Buffer32() var v0: UInt64 = 1 var v1: UInt64 = 2 var b: Bool = true return withUnsafeMutablePointer(&buffer) { bufferPtr in bufferPtr.pointee.x0 = 5 bufferPtr.pointee.x1 = v0 bufferPtr.pointee.x2 = v1 bufferPtr.pointee.x3 = b ? v0 : v1 return bufferPtr.pointee.x3 } } // CHECK: 1 print(foo())
apache-2.0
2c0cf99af213b3e19f3024d232f729b2
20
58
0.641026
2.967391
false
false
false
false
dfsilva/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Dialogs List/AADialogsListContentController.swift
1
7137
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation open class AADialogsListContentController: AAContentTableController, UISearchBarDelegate, UISearchDisplayDelegate { open var enableDeletion: Bool = true open var enableSearch: Bool = true open var delegate: AADialogsListContentControllerDelegate! public init() { super.init(style: .plain) unbindOnDissapear = true } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func tableDidLoad() { managedTable.canEditAll = true managedTable.canDeleteAll = true managedTable.fixedHeight = 76 tableView.estimatedRowHeight = 76 tableView.rowHeight = 76 if enableSearch { search(AADialogSearchCell.self) { (s) -> () in s.searchModel = Actor.buildGlobalSearchModel() s.selectAction = { (itm) -> () in self.delegate?.searchDidTap(self, entity: itm) } } } section { (s) -> () in s.autoSeparatorsInset = 75 s.binded { (r:AABindedRows<AADialogCell>) -> () in r.differental = true r.animated = true r.displayList = Actor.getDialogsDisplayList() if r.displayList.getProcessor() == nil { r.displayList.setListProcessor(AADialogListProcessor()) } r.selectAction = { (dialog: ACDialog) -> Bool in if let d = self.delegate { return d.recentsDidTap(self, dialog: dialog) } return true } r.canEditAction = { (dialog: ACDialog) -> Bool in return self.enableDeletion } r.editAction = { (dialog: ACDialog) -> () in if dialog.peer.isGroup { let g = Actor.getGroupWithGid(dialog.peer.peerId) let isChannel = g.groupType == ACGroupType.channel() self.alertSheet({ (a) in // Clear History if g.isCanClear.get().booleanValue() { a.action(AALocalized("ActionClearHistory"), closure: { self.confirmAlertUserDanger("ActionClearHistoryMessage", action: "ActionClearHistoryAction", tapYes: { self.executeSafe(Actor.clearChatCommand(with: dialog.peer)) }) }) } // Delete if g.isCanLeave.get().booleanValue() && g.isMember.get().booleanValue() { if isChannel { a.destructive(AALocalized("ActionLeaveChannel"), closure: { self.confirmAlertUserDanger("ActionLeaveChannelMessage", action: "ActionLeaveChannelAction", tapYes: { self.executePromise(Actor.leaveAndDeleteGroup(withGid: dialog.peer.peerId)) }) }) } else { a.destructive(AALocalized("ActionDeleteAndExit"), closure: { self.confirmAlertUserDanger("ActionDeleteAndExitMessage", action: "ActionDeleteAndExitAction", tapYes: { self.executePromise(Actor.leaveAndDeleteGroup(withGid: dialog.peer.peerId)) }) }) } } else if g.isCanDelete.get().booleanValue() && g.isMember.get().booleanValue(){ a.destructive(AALocalized(isChannel ? "ActionDeleteChannel" : "ActionDeleteGroup"), closure: { self.confirmAlertUserDanger(isChannel ? "ActionDeleteChannelMessage" : "ActionDeleteGroupMessage", action: "ActionDelete", tapYes: { self.executePromise(Actor.deleteGroup(withGid: g.groupId)) }) }) } else { a.destructive(AALocalized("ActionDelete"), closure: { self.confirmAlertUserDanger("ActionDeleteMessage", action: "ActionDelete", tapYes: { self.executeSafe(Actor.deleteChatCommand(with: dialog.peer)) }) }) } a.title = AALocalized(isChannel ? "ActionDeleteChannelTitle" : "ActionDeleteGroupTitle") // Cancel a.cancel = AALocalized("ActionCancel") }) } else { self.alertSheet({ (a) in a.action(AALocalized("ActionClearHistory"), closure: { self.executeSafe(Actor.clearChatCommand(with: dialog.peer)) }) a.destructive(AALocalized("ActionDelete"), closure: { self.executeSafe(Actor.deleteChatCommand(with: dialog.peer)) }) a.title = AALocalized("ActionDeleteChatTitle") a.cancel = AALocalized("ActionCancel") }) } } } } placeholder.setImage( UIImage.bundled("chat_list_placeholder"), title: AALocalized("Placeholder_Dialogs_Title"), subtitle: AALocalized("Placeholder_Dialogs_Message")) } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Binding empty dialogs placeholder binder.bind(Actor.getAppState().isDialogsEmpty, closure: { (value: Any?) -> () in if let empty = value as? JavaLangBoolean { if Bool(empty.booleanValue()) == true { self.navigationItem.leftBarButtonItem = nil self.showPlaceholder() } else { self.hidePlaceholder() self.navigationItem.leftBarButtonItem = self.editButtonItem } } }) } }
agpl-3.0
30e175d2380a3fc856c8983da511a56b
43.60625
168
0.45089
6.152586
false
false
false
false
cuappdev/podcast-ios
old/Podcast/Authentication.swift
1
7055
// // Authentication.swift // Podcast // // Created by Natasha Armbrust on 12/15/17. // Copyright © 2017 Cornell App Development. All rights reserved. // import Foundation import FacebookLogin import FacebookCore import GoogleSignIn enum AuthenticationEndpointRequestType { case signIn case merge } enum SignInResult { case success case cancelled case failure // to convert from Facebook result static func conversion(from loginResult: LoginResult) -> SignInResult { switch loginResult { case .cancelled: return SignInResult.cancelled case .failed: return SignInResult.failure case .success: return SignInResult.success } } // to convert from Google error static func conversion(from error: Error?) -> SignInResult { switch error { case .none: return SignInResult.success case .some(let googleError): switch googleError.code { case GIDSignInErrorCode.canceled.rawValue, GIDSignInErrorCode.hasNoAuthInKeychain.rawValue: return SignInResult.cancelled default: return SignInResult.failure } } } } protocol SignInUIDelegate: class { func signedIn(for type: SignInType, withResult result: SignInResult) } class Authentication: NSObject, GIDSignInDelegate { static var sharedInstance = Authentication() var facebookLoginManager: LoginManager! private weak var delegate: SignInUIDelegate? var facebookAccessToken: String? { get { return AccessToken.current?.authenticationToken } } var googleAccessToken: String? { get { return GIDSignIn.sharedInstance().currentUser?.authentication.accessToken } } override init() { super.init() GIDSignIn.sharedInstance().clientID = "724742275706-h8qs46h90squts3dco76p0q6lja2c7nh.apps.googleusercontent.com" let profileScope = "https://www.googleapis.com/auth/userinfo.profile" let emailScope = "https://www.googleapis.com/auth/userinfo.email" GIDSignIn.sharedInstance().scopes.append(contentsOf: [profileScope, emailScope]) facebookLoginManager = LoginManager() facebookLoginManager.loginBehavior = .web GIDSignIn.sharedInstance().delegate = self } func setDelegate(_ viewController: UIViewController) { if let _ = viewController as? GIDSignInUIDelegate, let _ = viewController as? SignInUIDelegate { delegate = viewController as? SignInUIDelegate GIDSignIn.sharedInstance().uiDelegate = viewController as! GIDSignInUIDelegate } } func signIn(with type: SignInType, viewController: UIViewController) { switch type { case .facebook: facebookLoginManager.logIn(readPermissions: [.publicProfile, .email, .userFriends], viewController: viewController) { loginResult in self.delegate?.signedIn(for: .facebook, withResult: SignInResult.conversion(from: loginResult)) } case .google: GIDSignIn.sharedInstance().signIn() } } func signInSilentlyWithGoogle() { GIDSignIn.sharedInstance().signInSilently() } func logout() { GIDSignIn.sharedInstance().signOut() facebookLoginManager.logOut() } // Google sign in functionality func handleSignIn(url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool { return GIDSignIn.sharedInstance().handle(url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplicationOpenURLOptionsKey.annotation]) } // delegate method for Google sign in - called when sign in is complete // awkward to put here but this is how Google requires signing in delegation func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) { delegate?.signedIn(for: .google, withResult: SignInResult.conversion(from: error)) } // merges account from signInTypeToMergeIn into current account func mergeAccounts(signInTypeToMergeIn: SignInType, success: ((Bool) -> ())? = nil, failure: (() -> ())? = nil) { completeAuthenticationRequest(endpointRequestType: .merge, type: signInTypeToMergeIn, success: success, failure: failure) } // authenticates the user and executes success block if valid user, else executes failure block func authenticateUser(signInType: SignInType, success: ((Bool) -> ())? = nil, failure: (() -> ())? = nil) { completeAuthenticationRequest(endpointRequestType: .signIn, type: signInType, success: success, failure: failure) } private func completeAuthenticationRequest(endpointRequestType: AuthenticationEndpointRequestType, type: SignInType, success: ((Bool) -> ())? = nil, failure: (() -> ())? = nil) { var accessToken: String = "" if type == .google { guard let token = Authentication.sharedInstance.googleAccessToken else { return } // Safe to send to the server accessToken = token } else { guard let token = Authentication.sharedInstance.facebookAccessToken else { return } // Safe to send to the server accessToken = token } let endpointRequest: EndpointRequest if endpointRequestType == .signIn { endpointRequest = AuthenticateUserEndpointRequest(signInType: type, accessToken: accessToken) } else { endpointRequest = MergeUserAccountsEndpointRequest(signInType: type, accessToken: accessToken) } switch endpointRequestType { // merge accounts gives us back different results for success case .merge: endpointRequest.success = { request in guard let user = request.processedResponseValue as? User else { print("error authenticating") failure?() return } System.currentUser = user success?(false) // not new user } break default: endpointRequest.success = { request in guard let result = request.processedResponseValue as? [String: Any], let user = result["user"] as? User, let session = result["session"] as? Session, let isNewUser = result["is_new_user"] as? Bool else { print("error authenticating") failure?() return } System.currentUser = user System.currentSession = session success?(isNewUser) } } endpointRequest.failure = { _ in failure?() } System.endpointRequestQueue.addOperation(endpointRequest) } }
mit
c8940f004b543cab8528645a268a2cb8
36.721925
182
0.635101
5.323774
false
false
false
false
vigneshuvi/SwiftCSVExport
Tests/LinuxMain.swift
1
4253
// // LinuxMain.swift // SwiftCSVExport // // Created by Vignesh on 30/01/17. // Copyright © 2017 vigneshuvi. All rights reserved. // import XCTest @testable import SwiftCSVExport class SwiftCSVExportTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() self.testExample() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. // Generate CSV file let user1:NSMutableDictionary = NSMutableDictionary() user1.setObject(107, forKey: "userid" as NSCopying); user1.setObject("vignesh", forKey: "name" as NSCopying); user1.setObject("[email protected]", forKey: "email" as NSCopying); user1.setObject(true, forKey:"isValidUser" as NSCopying) user1.setObject("Hi 'Vignesh!', \nhow are you? \t Shall we meet tomorrow? \r Thanks ", forKey: "message" as NSCopying); user1.setObject(571.05, forKey: "balance" as NSCopying); let user2:NSMutableDictionary = NSMutableDictionary() user2.setObject(108, forKey: "userid" as NSCopying); user2.setObject("vinoth", forKey: "name" as NSCopying); user2.setObject("[email protected]", forKey: "email" as NSCopying); user2.setObject(true, forKey:"isValidUser" as NSCopying) user2.setObject("Hi 'Vinoth!', \nHow are you? \t Shall we meet tomorrow? \r Thanks ", forKey: "message" as NSCopying); user2.setObject(567.50, forKey: "balance" as NSCopying); let data:NSMutableArray = NSMutableArray() data.add(user1); data.add(user2); let header = ["userid", "name", "email", "message", "isValidUser","balance"] // Create a object for write CSV let writeCSVObj = CSV() writeCSVObj.rows = data writeCSVObj.delimiter = DividerType.comma.rawValue writeCSVObj.fields = header as NSArray writeCSVObj.name = "userlist" // Enable Strict Validation CSVExport.export.enableStrictValidation = true let output = CSVExport.export(writeCSVObj); XCTAssertEqual(true, output.result.isSuccess) if output.result.isSuccess { guard let filePath = output.filePath else { print("Export Error: \(String(describing: output.message))") return } self.testWithFilePath(filePath, rowCount: data.count, columnCount: header.count) print("FilePath: \(filePath)") } else { print("Export Error: \(String(describing: output.message))") } } func testWithFilePath(_ filePath: String, rowCount:Int, columnCount:Int) { let fileDetails = CSVExport.readCSV(filePath); XCTAssertNotNil(fileDetails) XCTAssertTrue(fileDetails.hasData, "CSV file contains record") XCTAssertEqual(fileDetails.name, "userlist.csv") XCTAssertEqual(rowCount, fileDetails.rows.count) XCTAssertEqual(columnCount, fileDetails.fields.count) if fileDetails.hasData { print("\n\n***** CSV file contains record *****\n\n") print(fileDetails.name) print(fileDetails.fields) print(fileDetails.rows) } } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. let fileDetails = CSVExport.readCSVFromDefaultPath("userlist.csv"); XCTAssertNotNil(fileDetails) XCTAssertTrue(fileDetails.hasData, "CSV file contains record") XCTAssertEqual(fileDetails.name, "userlist.csv") XCTAssertEqual(2, fileDetails.rows.count) XCTAssertEqual(6, fileDetails.fields.count) } } }
mit
e4c5bc775d682a7204c126be9d7acdf0
38.738318
127
0.627234
4.457023
false
true
false
false
ykyouhei/KYWheelTabController
KYWheelTabController/Classes/Views/WheelMenuView.swift
1
11167
// // WheelMenuView.swift // KYCircleTabController // // Created by kyo__hei on 2016/02/03. // Copyright © 2016年 kyo__hei. All rights reserved. // import UIKit public protocol WheelMenuViewDelegate: NSObjectProtocol { func wheelMenuView(_ view: WheelMenuView, didSelectItem: UITabBarItem) } @IBDesignable public final class WheelMenuView: UIView { /* ====================================================================== */ // MARK: Properties /* ====================================================================== */ @IBInspectable public var centerButtonRadius: CGFloat = 32 { didSet { updateCenterButton() } } @IBInspectable public var menuBackGroundColor: UIColor = UIColor(white: 36/255, alpha: 1) { didSet { menuLayers.forEach { $0.fillColor = menuBackGroundColor.cgColor } } } @IBInspectable public var boarderColor: UIColor = UIColor(white: 0.4, alpha: 1) { didSet { menuLayers.forEach { $0.strokeColor = boarderColor.cgColor } } } @IBInspectable public var animationDuration: CGFloat = 0.2 public weak var delegate: WheelMenuViewDelegate? public var tabBarItems: [UITabBarItem] { get { return menuLayers.map { $0.tabBarItem } } set { menuLayers.forEach{ $0.removeFromSuperlayer() } let angle = 2 * CGFloat(M_PI) / CGFloat(newValue.count) menuLayers = newValue.enumerated().map { let startAngle = CGFloat($0.offset) * angle - angle / 2 - CGFloat(M_PI_2) let endAngle = CGFloat($0.offset + 1) * angle - angle / 2 - CGFloat(M_PI_2) - 0.005 let center = CGPoint( x: bounds.width/2, y: bounds.height/2) var transform = CATransform3DMakeRotation(angle * CGFloat($0.offset), 0, 0, 1) transform = CATransform3DTranslate( transform, 0, -bounds.width/3, 0) let layer = MenuLayer( center: center, radius: bounds.width/2, startAngle: startAngle, endAngle: endAngle, tabBarItem: $0.element, bounds: bounds, contentsTransform: transform) layer.tintColor = tintColor layer.strokeColor = boarderColor.cgColor layer.fillColor = menuBackGroundColor.cgColor layer.selected = $0.offset == selectedIndex menuBaseView.layer.addSublayer(layer) return layer } } } fileprivate(set) var openMenu: Bool = true fileprivate(set) var selectedIndex = 0 fileprivate var startPoint = CGPoint.zero fileprivate var currentAngle: CGFloat { let angle = 2 * CGFloat(M_PI) / CGFloat(menuLayers.count) return CGFloat(menuLayers.count - selectedIndex) * angle } fileprivate var menuLayers = [MenuLayer]() /* ====================================================================== */ // MARK: IBOutlet /* ====================================================================== */ public var centerButtonCustomImage: UIImage? { didSet { updateCenterButton() } } @IBOutlet public weak var centerButton: UIButton! { didSet { let bundle = Bundle(for: type(of: self)) let image = centerButtonCustomImage ?? UIImage(named: "Menu", in: bundle, compatibleWith: nil)! .withRenderingMode(.alwaysTemplate) centerButton.setImage(image, for: UIControlState()) centerButton.layer.shadowOpacity = 0.3 centerButton.layer.shadowRadius = 10 centerButton.layer.shadowOffset = CGSize.zero } } @IBOutlet fileprivate weak var centerButtonWidth: NSLayoutConstraint! @IBOutlet fileprivate weak var menuBaseView: UIView! /* ====================================================================== */ // MARK: initializer /* ====================================================================== */ convenience public init(frame: CGRect, tabBarItems: [UITabBarItem]) { self.init(frame: frame) self.tabBarItems = tabBarItems } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } fileprivate func commonInit() { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: "WheelMenuView", bundle: bundle) let view = nib.instantiate(withOwner: self, options: nil).first as! UIView let viewDictionary = ["view": view] addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options:NSLayoutFormatOptions(rawValue: 0), metrics:nil, views: viewDictionary)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|", options:NSLayoutFormatOptions(rawValue: 0), metrics:nil, views: viewDictionary)) updateCenterButton() } public override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() tabBarItems = [ UITabBarItem(tabBarSystemItem: .bookmarks, tag: 1), UITabBarItem(tabBarSystemItem: .bookmarks, tag: 2), UITabBarItem(tabBarSystemItem: .bookmarks, tag: 3), UITabBarItem(tabBarSystemItem: .bookmarks, tag: 4) ] } /* ====================================================================== */ // MARK: Actions /* ====================================================================== */ @IBAction fileprivate func handlePanGesture(_ sender: UIPanGestureRecognizer) { let location = sender.location(in: self) switch sender.state { case .began: startPoint = location case .changed: let radian1 = -atan2( startPoint.x - menuBaseView.center.x, startPoint.y - menuBaseView.center.y) let radian2 = -atan2( location.x - menuBaseView.center.x, location.y - menuBaseView.center.y) menuBaseView.transform = menuBaseView.transform.rotated(by: radian2 - radian1) startPoint = location default: let angle = 2 * CGFloat(M_PI) / CGFloat(menuLayers.count) var menuViewAngle = atan2(menuBaseView.transform.b, menuBaseView.transform.a) if menuViewAngle < 0 { menuViewAngle += CGFloat(2 * M_PI) } var index = menuLayers.count - Int((menuViewAngle + CGFloat(M_PI_4)) / angle) if index == menuLayers.count { index = 0 } setSelectedIndex(index, animated: true) delegate?.wheelMenuView(self, didSelectItem: tabBarItems[index]) } } @IBAction fileprivate func handleTapGesture(_ sender: UITapGestureRecognizer) { let location = sender.location(in: menuBaseView) for (idx, menuLayer) in menuLayers.enumerated() { let touchInLayer = menuLayer.path?.contains(location) ?? false if touchInLayer { setSelectedIndex(idx, animated: true) delegate?.wheelMenuView(self, didSelectItem: tabBarItems[idx]) return } } } public var customActionCallback: (() -> Void)? = nil @IBAction func didTapCenterButton(_: UIButton) { if let customActionCallback = customActionCallback { customActionCallback() } else { if openMenu { closeMenuView() } else { openMenuView() } } } /* ====================================================================== */ // MARK: Public Method /* ====================================================================== */ public func setSelectedIndex(_ index: Int, animated: Bool) { selectedIndex = index let duration = animated ? TimeInterval(animationDuration) : 0 UIView.animate(withDuration: TimeInterval(duration), animations: { self.menuBaseView.transform = CGAffineTransform(rotationAngle: self.currentAngle) }, completion: { _ in self.menuLayers.enumerated().forEach { $0.element.selected = $0.offset == index } } ) } public override func tintColorDidChange() { super.tintColorDidChange() menuLayers.forEach { $0.tintColor = tintColor } } /* ====================================================================== */ // MARK: Private Method /* ====================================================================== */ public func updateCenterButton() { centerButtonWidth.constant = centerButtonRadius * 2 centerButton.layer.cornerRadius = centerButtonRadius let bundle = Bundle(for: type(of: self)) let image = centerButtonCustomImage ?? UIImage(named: "Menu", in: bundle, compatibleWith: nil)! .withRenderingMode(.alwaysTemplate) centerButton.setImage(image, for: UIControlState()) } public func openMenuView() { openMenu = true UIView.animate(withDuration: TimeInterval(animationDuration), delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5.0, options: [], animations: { self.menuBaseView.transform = CGAffineTransform(scaleX: 1, y: 1).rotated(by: self.currentAngle) }, completion: nil ) } public func closeMenuView() { openMenu = false UIView.animate(withDuration: TimeInterval(animationDuration), delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5.0, options: [], animations: { self.menuBaseView.transform = CGAffineTransform(scaleX: 0.1, y: 0.1).rotated(by: self.currentAngle) }, completion: nil ) } }
mit
b9c9b204925093a7a0addcfc9230fcda
33.245399
115
0.503673
5.582
false
false
false
false
ewanmellor/KZLinkedConsole
KZLinkedConsole/NSObject_Extension.swift
1
466
// // NSObject_Extension.swift // // Created by Krzysztof Zabłocki on 05/12/15. // Copyright © 2015 pixle. All rights reserved. // import Foundation extension NSObject { class func pluginDidLoad(bundle: NSBundle) { let appName = NSBundle.mainBundle().infoDictionary?["CFBundleName"] as? NSString if appName == "Xcode" { if sharedPlugin == nil { sharedPlugin = KZLinkedConsole(bundle: bundle) } } } }
mit
0c84612cff6cb55ea2c3d93f5ba9276c
23.473684
88
0.633621
3.932203
false
false
false
false
yourkarma/Notify
Pod/Classes/Presenter.swift
1
12570
import UIKit struct PresentedNotification { let window: UIWindow let view: UIView let dimView: UIView let notification: NotifyNotification let presenter: Presenter let presentedAt: TimeInterval } public protocol PresenterType { func present(_ notification: NotifyNotification, showStatusBar: Bool) } open class Presenter: PresenterType { static var presentedNotification: PresentedNotification? = nil static var notificationQueue: [(NotifyNotification, Bool)] = [] var dismissAfter: TimeInterval? let themeProvider: ThemeProvider public init(themeProvider: ThemeProvider) { self.themeProvider = themeProvider NotificationCenter.default.addObserver(self, selector: #selector(Presenter.hidePresentedNotification), name: NSNotification.Name(rawValue: "HidePresentedNotification"), object: nil) } open func present(_ notification: NotifyNotification, showStatusBar: Bool = false) { if Presenter.presentedNotification == nil { self.makeNotificationVisible(notification, statusBarHeight: showStatusBar ? 1 : 0) } else { Presenter.notificationQueue.append((notification, showStatusBar)) } } func makeNotificationVisible(_ notification: NotifyNotification, statusBarHeight: CGFloat = 0) { let window = self.makeNotificationWindowWithStatusBarHeight(statusBarHeight) let view = self.makeNotificationViewForNotification(notification) window.addSubview(view) let dimView = UIView() dimView.backgroundColor = UIColor.black dimView.alpha = 0.0 dimView.translatesAutoresizingMaskIntoConstraints = false window.insertSubview(dimView, belowSubview: view) let preventsUserInteraction = notification.actions.count > 0 // This serves several purposes: // 1) It is used to ensure we're never showing more than one notification; // 2) It keeps a reference to the window to prevent it from being deallocated. // 3) When the presented notification is changed, // the window is deallocated and thus not visible anymore. // In other words, if for some reason the cleanup logic fails, this ensures we still only // ever have one window visible. Presenter.presentedNotification = PresentedNotification(window: window, view: view, dimView: dimView, notification: notification, presenter: self, presentedAt: Date().timeIntervalSinceReferenceDate) // Constrain the notification to the top of the view let views = ["notification": view, "dim": dimView] window.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[notification]|", options: [], metrics: nil, views: views)) window.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[dim]|", options: [], metrics: nil, views: views)) let offScreenTopConstraint = NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: window, attribute: .top, multiplier: 2.0, constant: 0.0) offScreenTopConstraint.identifier = "offScreenTopConstraint" window.addConstraint(offScreenTopConstraint) let onscreenTopConstraint = NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: window, attribute: .top, multiplier: 2.0, constant: 0.0) onscreenTopConstraint.identifier = "onscreenTopConstraint" window.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[dim]|", options: [], metrics: nil, views: views)) window.layoutIfNeeded() UIView.animate(withDuration: 0.2, animations: { window.removeConstraint(offScreenTopConstraint) window.addConstraint(onscreenTopConstraint) if preventsUserInteraction { dimView.alpha = 0.55 } else { dimView.alpha = 0.0 } window.layoutIfNeeded() }) window.isHidden = false if (!preventsUserInteraction) { window.touchCallback = { if let presentedAt = Presenter.presentedNotification?.presentedAt { if let timeInterval: TimeInterval = self.dismissAfter { let elapsedSeconds = Date().timeIntervalSinceReferenceDate - presentedAt let minimumSecondsNotificationShouldBeVisible: TimeInterval = timeInterval let waitFor = minimumSecondsNotificationShouldBeVisible - elapsedSeconds DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(waitFor * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { self.hidePresentedNotification() } } // There are cases where the NotificationWindow touchCallback is called multiple times for the same // touch. This prevents us from accidentally dismissing the notificatino more than once. window.touchCallback = nil } } } } @objc func hidePresentedNotification() { if let presentedNotification = Presenter.presentedNotification { let view = presentedNotification.view let window = presentedNotification.window let dimView = presentedNotification.dimView UIView.animate(withDuration: 0.2, animations: { view.transform = CGAffineTransform(translationX: 0.0, y: -view.frame.height) dimView.alpha = 0.0 }, completion: { _ in window.isHidden = true Presenter.presentedNotification = nil NotificationCenter.default.post(name: Foundation.Notification.Name(rawValue: "didDismissNotiftyNotification"), object: nil, userInfo: nil) if Presenter.notificationQueue.count > 0 { let notification = Presenter.notificationQueue.remove(at: 0) self.present(notification.0, showStatusBar: notification.1) } }) } } @objc func notificationTapped(_ gestureRecognizer: UITapGestureRecognizer) { if let actions = Presenter.presentedNotification?.notification.actions { if actions.count <= 0 { self.hidePresentedNotification() } } } func makeNotificationViewForNotification(_ notification: NotifyNotification) -> UIView { let view = UIView() view.backgroundColor = self.themeProvider.backgroundColorForNotification(notification) let imageView = UIImageView() imageView.image = self.themeProvider.iconForNotification(notification) var shouldShowImage = false if let _ :UIImage = imageView.image { shouldShowImage = true } view.addSubview(imageView) let label = self.themeProvider.labelForNotification(notification) label.text = notification.message label.numberOfLines = 0 view.addSubview(label) let buttons = self.buttonsForNotification(notification) buttons.forEach { (button) -> () in view.addSubview(button) button.contentEdgeInsets = UIEdgeInsets(top: 0.0, left: 12.0, bottom: 0.0, right: 12.0) button.addTarget(self, action: #selector(Presenter.handleAction(_:)), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false } label.translatesAutoresizingMaskIntoConstraints = false imageView.translatesAutoresizingMaskIntoConstraints = false view.translatesAutoresizingMaskIntoConstraints = false let views = ["icon": imageView, "label": label] // Constrain the horizontal axis imageView.setContentHuggingPriority(252, for: .horizontal) imageView.setContentHuggingPriority(252, for: .vertical) label.setContentHuggingPriority(251, for: .horizontal) let horizontalLabelContraints = shouldShowImage ? "H:|-16-[icon]-16-[label]->=16-|" : "H:|->=16-[label]->=16-|" view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: horizontalLabelContraints, options: [], metrics: nil, views: views)) if !shouldShowImage { view.addConstraint(NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0.0)) } var previousButton: UIButton? = nil for (index, button) in buttons.enumerated() { if previousButton == nil { view.addConstraint(NSLayoutConstraint(item: button, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 5.0)) } else if index < notification.actions.endIndex { view.addConstraint(NSLayoutConstraint(item: button, attribute: .leading, relatedBy: .equal, toItem: previousButton, attribute: .trailing, multiplier: 1.0, constant: 5.0)) view.addConstraint(NSLayoutConstraint(item: button, attribute: .lastBaseline, relatedBy: .equal, toItem: previousButton, attribute: .lastBaseline, multiplier: 1.0, constant: 0.0)) let widthConstraint = NSLayoutConstraint(item: button, attribute: .width, relatedBy: .equal, toItem: previousButton, attribute: .width, multiplier: 1.0, constant: previousButton?.frame.width ?? 0.0) widthConstraint.priority = UILayoutPriorityDefaultLow view.addConstraint(widthConstraint) } if buttons.last == button { view.addConstraint(NSLayoutConstraint(item: view, attribute: .trailing, relatedBy: .equal, toItem: button, attribute: .trailing, multiplier: 1.0, constant: 5.0)) } previousButton = button } // Constrain the vertical axis if let button = buttons.first { let viewsWithButton = ["icon": imageView, "label": label, "button": button] view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-10-[label]-10-[button]-16-|", options: [], metrics: nil, views: viewsWithButton)) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-16-[icon]->=16-|", options: [], metrics: nil, views: viewsWithButton)) } else { let verticalLabelContraints = shouldShowImage ? "V:|-10-[label]-10-|" : "V:|-20-[label]-6-|" view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: verticalLabelContraints, options: [], metrics: nil, views: views)) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-16-[icon]->=16-|", options: [], metrics: nil, views: views)) } view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(Presenter.notificationTapped(_:)))) return view } func buttonsForNotification(_ notification: NotifyNotification) -> [UIButton] { var buttons: [UIButton] = [] for (index, action) in notification.actions.enumerated() { let button = self.themeProvider.buttonForNotification(notification, action: action) button.setTitle(action.title, for: UIControlState()) button.tag = index buttons.append(button) } return buttons } @objc func handleAction(_ sender: UIButton) { if let presented = Presenter.presentedNotification { let actions = presented.notification.actions let action = actions[sender.tag] action.handler?(action) self.hidePresentedNotification() } } func makeNotificationWindowWithStatusBarHeight(_ height: CGFloat) -> NotificationWindow { let screen = UIScreen.main let window = NotificationWindow(frame: CGRect(x: 0.0, y: 0.0, width: screen.bounds.width, height: screen.bounds.height)) window.windowLevel = UIWindowLevelStatusBar - height window.backgroundColor = .clear // A root view controller is necessary for the window // to automatically participate in rotation. window.rootViewController = NotifyViewController() return window } deinit { NotificationCenter.default.removeObserver(self) } }
mit
2504488e4ff26a1282eeb748c493dfdd
46.078652
220
0.657438
5.326271
false
false
false
false
qutheory/vapor
Tests/VaporTests/BodyStreamStateTests.swift
2
4094
@testable import Vapor import XCTest final class BodyStreamStateTests: XCTestCase { func testSynchronous() throws { var buffer = ByteBufferAllocator().buffer(capacity: 0) buffer.writeString("Hello, world!") var state = HTTPBodyStreamState() XCTAssertEqual( state.didReadBytes(buffer), .init(action: .write(buffer), callRead: false) ) XCTAssertEqual( state.didWrite(), .init(action: .nothing, callRead: false) ) XCTAssertEqual( state.didReceiveReadRequest(), .init(action: .nothing, callRead: true) ) XCTAssertEqual( state.didReadBytes(buffer), .init(action: .write(buffer), callRead: false) ) XCTAssertEqual( state.didWrite(), .init(action: .nothing, callRead: false) ) XCTAssertEqual( state.didEnd(), .init(action: .close(nil), callRead: false) ) } func testReadDuringWrite() throws { var buffer = ByteBufferAllocator().buffer(capacity: 0) buffer.writeString("Hello, world!") var state = HTTPBodyStreamState() XCTAssertEqual( state.didReadBytes(buffer), .init(action: .write(buffer), callRead: false) ) XCTAssertEqual( state.didReceiveReadRequest(), .init(action: .nothing, callRead: false) ) XCTAssertEqual( state.didWrite(), .init(action: .nothing, callRead: true) ) XCTAssertEqual( state.didEnd(), .init(action: .close(nil), callRead: false) ) } func testErrorDuringWrite() throws { var buffer = ByteBufferAllocator().buffer(capacity: 0) buffer.writeString("Hello, world!") struct Test: Error { } var state = HTTPBodyStreamState() XCTAssertEqual( state.didReadBytes(buffer), .init(action: .write(buffer), callRead: false) ) XCTAssertEqual( state.didReceiveReadRequest(), .init(action: .nothing, callRead: false) ) XCTAssertEqual( state.didError(Test()), .init(action: .nothing, callRead: false) ) XCTAssertEqual( state.didReadBytes(buffer), .init(action: .nothing, callRead: false) ) XCTAssertEqual( state.didWrite(), .init(action: .close(Test()), callRead: false) ) } func testBufferedWrites() throws { var a = ByteBufferAllocator().buffer(capacity: 0) a.writeString("a") var b = ByteBufferAllocator().buffer(capacity: 0) b.writeString("b") struct Test: Error { } var state = HTTPBodyStreamState() XCTAssertEqual( state.didReadBytes(a), .init(action: .write(a), callRead: false) ) XCTAssertEqual( state.didReadBytes(b), .init(action: .nothing, callRead: false) ) XCTAssertEqual( state.didEnd(), .init(action: .nothing, callRead: false) ) XCTAssertEqual( state.didWrite(), .init(action: .write(b), callRead: false) ) XCTAssertEqual( state.didWrite(), .init(action: .close(nil), callRead: false) ) } } extension HTTPBodyStreamState.Result: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { lhs.action == rhs.action && lhs.callRead == rhs.callRead } } extension HTTPBodyStreamState.Result.Action: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { switch (lhs, rhs) { case (.nothing, .nothing): return true case (.write(let a), .write(let b)): return Data(a.readableBytesView) == Data(b.readableBytesView) case (.close, .close): return true default: return false } } }
mit
1e453037553dc763f600e36663959e57
28.883212
73
0.547386
4.620767
false
true
false
false
debugsquad/Hyperborea
Hyperborea/View/Store/VStoreHeader.swift
1
3939
import UIKit class VStoreHeader:UICollectionReusableView { private let attrTitle:[String:Any] private let attrDescr:[String:Any] private let labelMargins:CGFloat private weak var label:UILabel! private weak var imageView:UIImageView! private weak var layoutLabelHeight:NSLayoutConstraint! private let kLabelTop:CGFloat = 16 private let kLabelLeft:CGFloat = 10 private let kLabelRight:CGFloat = -10 private let kImageSize:CGFloat = 100 override init(frame:CGRect) { attrTitle = [ NSFontAttributeName:UIFont.bolder(size:20), NSForegroundColorAttributeName:UIColor.hyperBlue] attrDescr = [ NSFontAttributeName:UIFont.regular(size:16), NSForegroundColorAttributeName:UIColor.black] labelMargins = -kLabelRight + kLabelLeft + kImageSize super.init(frame:frame) clipsToBounds = true backgroundColor = UIColor.white isUserInteractionEnabled = false let label:UILabel = UILabel() label.isUserInteractionEnabled = false label.backgroundColor = UIColor.clear label.translatesAutoresizingMaskIntoConstraints = false label.numberOfLines = 0 self.label = label let imageView:UIImageView = UIImageView() imageView.isUserInteractionEnabled = false imageView.clipsToBounds = true imageView.contentMode = UIViewContentMode.center imageView.translatesAutoresizingMaskIntoConstraints = false self.imageView = imageView addSubview(label) addSubview(imageView) NSLayoutConstraint.topToTop( view:label, toView:self, constant:kLabelTop) layoutLabelHeight = NSLayoutConstraint.height( view:label) NSLayoutConstraint.leftToRight( view:label, toView:imageView, constant:kLabelLeft) NSLayoutConstraint.rightToRight( view:label, toView:self, constant:kLabelRight) NSLayoutConstraint.topToTop( view:imageView, toView:self) NSLayoutConstraint.size( view:imageView, constant:kImageSize) NSLayoutConstraint.leftToLeft( view:imageView, toView:self) } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { guard let attributedText:NSAttributedString = label.attributedText else { return } let width:CGFloat = bounds.maxX let height:CGFloat = bounds.maxY let usableWidth:CGFloat = width - labelMargins let usableSize:CGSize = CGSize(width:usableWidth, height:height) let boundingRect:CGRect = attributedText.boundingRect( with:usableSize, options:NSStringDrawingOptions([ NSStringDrawingOptions.usesLineFragmentOrigin, NSStringDrawingOptions.usesFontLeading]), context:nil) layoutLabelHeight.constant = ceil(boundingRect.size.height) super.layoutSubviews() } //MARK: public func config(model:MStoreItem) { let mutableString:NSMutableAttributedString = NSMutableAttributedString() let stringTitle:NSAttributedString = NSAttributedString( string:model.title, attributes:attrTitle) let stringDescr:NSAttributedString = NSAttributedString( string:model.descr, attributes:attrDescr) mutableString.append(stringTitle) mutableString.append(stringDescr) label.attributedText = mutableString imageView.image = model.image setNeedsLayout() } }
mit
0fc413483c69a60af14bf3bbcc753fd8
30.261905
81
0.622493
6.041411
false
false
false
false
OpenGenus/cosmos
code/sorting/src/shell_sort/shell_sort.swift
8
489
/* Part of Cosmos by OpenGenus Foundation */ // // shell_sort.swift // Created by DaiPei on 2017/10/11. // import Foundation func shellSort(_ array: inout [Int]) { var h = array.count / 2 while h > 0 { for i in h..<array.count { let key = array[i] var j = i while j >= h && key < array[j - h] { array[j] = array[j - h] j -= h } array[j] = key } h /= 2 } }
gpl-3.0
e2b2117ea3360f94b6d2e6b2d762ea26
19.375
48
0.435583
3.395833
false
false
false
false
debugsquad/Hyperborea
Hyperborea/View/Settings/VSettingsGradient.swift
1
1571
import UIKit class VSettingsGradient:UIView { private let kLocationTop:NSNumber = 0 private let kLocationMiddleTop:NSNumber = 0.08 private let kLocationMiddleBottom:NSNumber = 0.5 private let kLocationBottom:NSNumber = 1 init() { super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false isUserInteractionEnabled = false guard let gradientLayer:CAGradientLayer = self.layer as? CAGradientLayer else { return } let topColor:CGColor = UIColor( red:0.149019607843137, green:0.294117647058824, blue:0.470588235294118, alpha:1).cgColor let middleColorTop:CGColor = UIColor.hyperBlue.cgColor let middleColorBottom:CGColor = UIColor.hyperBlue.cgColor let bottomColor:CGColor = UIColor.hyperOrange.cgColor gradientLayer.locations = [ kLocationTop, kLocationMiddleTop, kLocationMiddleBottom, kLocationBottom ] gradientLayer.colors = [ topColor, middleColorTop, middleColorBottom, bottomColor ] } required init?(coder:NSCoder) { return nil } override open class var layerClass:AnyClass { get { return CAGradientLayer.self } } }
mit
b03ac98610484ec76eb3bb34bc639679
23.936508
78
0.572884
5.398625
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Post/PostPostViewController.swift
1
7864
// // PostPostViewController.swift // WordPress // // Created by Nate Heagy on 2016-11-02. // Copyright © 2016 WordPress. All rights reserved. // import UIKit import WordPressShared import Gridicons class PostPostViewController: UIViewController { @objc private(set) var post: Post? @objc var revealPost = false private var hasAnimated = false @IBOutlet var titleLabel: UILabel! @IBOutlet var postStatusLabel: UILabel! @IBOutlet var siteIconView: UIImageView! @IBOutlet var siteNameLabel: UILabel! @IBOutlet var siteUrlLabel: UILabel! @IBOutlet var shareButton: FancyButton! @IBOutlet var editButton: FancyButton! @IBOutlet var viewButton: FancyButton! @IBOutlet var navBar: UINavigationBar! @IBOutlet var postInfoView: UIView! @IBOutlet var actionsStackView: UIStackView! @IBOutlet var shadeView: UIView! @IBOutlet var shareButtonWidth: NSLayoutConstraint! @IBOutlet var editButtonWidth: NSLayoutConstraint! @IBOutlet var viewButtonWidth: NSLayoutConstraint! @objc var onClose: (() -> ())? @objc var reshowEditor: (() -> ())? @objc var preview: (() -> ())? /// Set to `true` to hide the edit button from the view. var hideEditButton = false init() { super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { super.init(coder: coder) } override var preferredStatusBarStyle: UIStatusBarStyle { return .darkContent } override func viewDidLoad() { super.viewDidLoad() setupLabels() setupNavBar() } private func setupNavBar() { let appearance = UINavigationBarAppearance() appearance.configureWithTransparentBackground() navBar.standardAppearance = appearance navBar.compactAppearance = appearance let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneTapped)) doneButton.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.barButtonItemTitle], for: .normal) doneButton.accessibilityIdentifier = "doneButton" navBar.topItem?.rightBarButtonItem = doneButton } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) view.backgroundColor = .basicBackground view.alpha = WPAlphaZero shareButton.setTitle(NSLocalizedString("Share", comment: "Button label to share a post"), for: .normal) shareButton.accessibilityIdentifier = "sharePostButton" shareButton.setImage(.gridicon(.shareiOS, size: CGSize(width: 18, height: 18)), for: .normal) shareButton.tintColor = .white shareButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8) editButton.setTitle(NSLocalizedString("Edit Post", comment: "Button label for editing a post"), for: .normal) editButton.accessibilityIdentifier = "editPostButton" viewButton.setTitle(NSLocalizedString("View Post", comment: "Button label for viewing a post"), for: .normal) viewButton.accessibilityIdentifier = "viewPostButton" configureForPost() if revealPost { WPAnalytics.track(.postEpilogueDisplayed) view.alpha = WPAlphaFull animatePostPost() } } private func setupLabels() { titleLabel.textColor = .label postStatusLabel.textColor = .secondaryLabel siteNameLabel.textColor = .label siteUrlLabel.textColor = .label } @objc func animatePostPost() { guard !hasAnimated else { return } hasAnimated = true shadeView.isHidden = false shadeView.backgroundColor = UIColor.black shadeView.alpha = WPAlphaFull * 0.5 postInfoView.alpha = WPAlphaZero viewButton.alpha = WPAlphaZero editButton.alpha = WPAlphaZero shareButton.alpha = WPAlphaZero let animationScaleBegin: CGFloat = -0.75 shareButtonWidth.constant = shareButton.frame.size.width * animationScaleBegin editButtonWidth.constant = shareButton.frame.size.width * animationScaleBegin viewButtonWidth.constant = shareButton.frame.size.width * animationScaleBegin view.layoutIfNeeded() guard let transitionCoordinator = transitionCoordinator else { return } transitionCoordinator.animate(alongsideTransition: { (context) in let animationDuration = context.transitionDuration UIView.animate(withDuration: animationDuration, delay: 0, options: .curveEaseOut, animations: { self.shadeView.alpha = WPAlphaZero }) UIView.animate(withDuration: animationDuration * 0.66, delay: 0, options: .curveEaseOut, animations: { self.postInfoView.alpha = WPAlphaFull }) UIView.animate(withDuration: 0.2, delay: animationDuration * 0.5, options: .curveEaseOut, animations: { self.shareButton.alpha = WPAlphaFull self.shareButtonWidth.constant = 0 self.actionsStackView.layoutIfNeeded() }) UIView.animate(withDuration: 0.2, delay: animationDuration * 0.6, options: .curveEaseOut, animations: { self.editButton.alpha = WPAlphaFull self.editButtonWidth.constant = 0 self.actionsStackView.layoutIfNeeded() }) UIView.animate(withDuration: 0.2, delay: animationDuration * 0.7, options: .curveEaseOut, animations: { self.viewButton.alpha = WPAlphaFull self.viewButtonWidth.constant = 0 self.actionsStackView.layoutIfNeeded() }) }) { (context) in } } private func configureForPost() { guard let post = self.post, let blogSettings = post.blog.settings else { return } titleLabel.text = post.titleForDisplay().strippingHTML() titleLabel.accessibilityIdentifier = "postTitle" if post.isScheduled() { let format = NSLocalizedString("Scheduled for %@ on", comment: "Precedes the name of the blog a post was just scheduled on. Variable is the date post was scheduled for.") postStatusLabel.text = String(format: format, post.dateStringForDisplay()) postStatusLabel.accessibilityIdentifier = "scheduledPostStatusLabel" shareButton.isHidden = true } else { postStatusLabel.text = NSLocalizedString("Published just now on", comment: "Precedes the name of the blog just posted on") postStatusLabel.accessibilityIdentifier = "publishedPostStatusLabel" shareButton.isHidden = false } siteNameLabel.text = blogSettings.name siteUrlLabel.text = post.blog.displayURL as String? siteUrlLabel.accessibilityIdentifier = "siteUrl" siteIconView.downloadSiteIcon(for: post.blog) editButton.isHidden = hideEditButton let isPrivate = !post.blog.visible if isPrivate { shareButton.isHidden = true } } @objc func setup(post: Post) { self.post = post revealPost = true } @IBAction func shareTapped() { guard let post = post else { return } WPAnalytics.track(.postEpilogueShare) let sharingController = PostSharingController() sharingController.sharePost(post, fromView: shareButton, inViewController: self) } @IBAction func editTapped() { WPAnalytics.track(.postEpilogueEdit) reshowEditor?() } @IBAction func viewTapped() { WPAnalytics.track(.postEpilogueView) preview?() } @IBAction func doneTapped() { onClose?() } }
gpl-2.0
84c9f9a44341aa01666b719d8408de94
35.235023
182
0.654585
5.142577
false
false
false
false
pixelmaid/DynamicBrushes
swift/Palette-Knife/models/base/Numerical.swift
3
616
// // Numerical.swift // PaletteKnife // // Created by JENNIFER MARY JACOBS on 5/26/16. // Copyright © 2016 pixelmaid. All rights reserved. // import Foundation class Numerical{ static let TRIGONOMETRIC_EPSILON = Float(1e-7) static let EPSILON = Float(1e-12) static let MACHINE_EPSILON = Float(1.12e-16) static func isZero (val:Float)->Bool { return val >= -EPSILON && val <= EPSILON; } static func map (value:Float, istart:Float, istop:Float, ostart:Float, ostop:Float)->Float { return ostart + (ostop - ostart) * ((value - istart) / (istop - istart)); } }
mit
bbf6e04138b8936602e2dd3502f63de7
24.625
96
0.64065
3.106061
false
false
false
false
cvillaseca/CVLoggerSwift
CVLoggerSwift/Classes/CVLoggerCell.swift
1
1693
// // CVLoggerCell.swift // Pods // // Created by Cristian Villaseca on 9/5/16. // // import UIKit class CVLoggerCell: UITableViewCell { internal var logLabel = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.logLabel.textColor = UIColor.blackColor() self.logLabel.numberOfLines = 0; self.logLabel.font = UIFont(name: "HelveticaNeue", size: 14.0) self.logLabel.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(self.logLabel) let views = ["logLabel":self.logLabel] var constraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[logLabel]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views) self.contentView.addConstraints(constraints) constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-4-[logLabel]-4-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views) self.contentView.addConstraints(constraints) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
6527586e357a1465a928f057956f8649
40.292683
117
0.510927
6.0681
false
false
false
false
victorchee/ForceTouch
ForceTouch/ForceTouch/MasterViewController.swift
1
2032
// // MasterViewController.swift // ForceTouch // // Created by qihaijun on 11/12/15. // Copyright © 2015 VictorChee. All rights reserved. // import UIKit class MasterViewController: UIViewController, UIViewControllerPreviewingDelegate { @IBOutlet weak var forceTouchButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Check 3D touch available if traitCollection.forceTouchCapability == .Available { // force touch avaiable registerForPreviewingWithDelegate(self, sourceView: forceTouchButton) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if traitCollection.forceTouchCapability == .Available { // force touch avaiable registerForPreviewingWithDelegate(self, sourceView: forceTouchButton) } } func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { // Check if already displaying a preview controller if let presented = presentedViewController { if presented is DetailViewController { return nil } } // Peek (shallow press) let detailViewcontroller = storyboard?.instantiateViewControllerWithIdentifier("DetailViewController") as? DetailViewController return detailViewcontroller } func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) { // Pop (deep press) showViewController(viewControllerToCommit, sender: self) } }
mit
576a9b64c1d2ed8b8143f28bfe9459e0
34.631579
141
0.69227
6.488818
false
false
false
false
VoIPGRID/VialerSIPLib
Example/VialerSIPLib/VSLIncomingCallViewController.swift
2
4628
// // VSLIncomingCallViewController.swift // Copyright © 2016 Devhouse Spindle. All rights reserved. // import UIKit private var myContext = 0 class VSLIncomingCallViewController: UIViewController { // MARK: - Configuration fileprivate struct Configuration { struct Segues { static let UnwindToMainViewController = "UnwindToMainViewControllerSegue" static let ShowCall = "ShowCallSegue" } static let UnwindTime = 2.0 } // MARK: - Properties var callManager: VSLCallManager! // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() callManager = VialerSIPLib.sharedInstance().callManager } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateUI() call?.addObserver(self, forKeyPath: "callState", options: .new, context: &myContext) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) call?.removeObserver(self, forKeyPath: "callState") } // MARK: - Properties var call: VSLCall? { didSet { updateUI() } } lazy var ringtone: VSLRingtone = { let fileUrl = Bundle.main.url(forResource: "ringtone", withExtension: "wav")! return VSLRingtone.init(ringtonePath: fileUrl)! }() // MARK: - Outlets @IBOutlet weak var numberLabel: UILabel! @IBOutlet weak var statusLabel: UILabel! @IBOutlet weak var declineButton: UIButton! @IBOutlet weak var acceptButton: UIButton! // MARK: - Actions @IBAction func declineButtonPressed(_ sender: UIButton) { guard let call = call else { return } callManager.end(call) { error in if error != nil { DDLogWrapper.logError("cannot decline call: \(error!)") } else { self.performSegue(withIdentifier: Configuration.Segues.UnwindToMainViewController, sender: nil) } } } @IBAction func acceptButtonPressed(_ sender: UIButton) { guard let call = call, call.callState == .incoming else { return } callManager.answer(call) { error in if error != nil { DDLogWrapper.logError("error answering call: \(error!)") } else { self.performSegue(withIdentifier: Configuration.Segues.ShowCall, sender: nil) } } } fileprivate func updateUI() { guard let call = call else { numberLabel?.text = "" statusLabel?.text = "" return } if (call.callerName != "") { numberLabel?.text = call.callerName } else { numberLabel?.text = call.callerNumber } switch call.callState { case .incoming: statusLabel?.text = "Incoming call" case .connecting: statusLabel?.text = "Connecting" case .confirmed: statusLabel?.text = "Connected" case .disconnected: statusLabel?.text = "Disconnected" case .null: fallthrough case .calling: fallthrough case .early: statusLabel?.text = "Invalid" } if call.callState == .incoming { declineButton?.isEnabled = true acceptButton?.isEnabled = true ringtone.start() } else { ringtone.stop() declineButton?.isEnabled = false acceptButton?.isEnabled = false } } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let callViewController = segue.destination as? VSLCallViewController { callViewController.activeCall = call } } // MARK: - KVO override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if context == &myContext { DispatchQueue.main.async { self.updateUI() } if let call = object as? VSLCall , call.callState == .disconnected { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(Configuration.UnwindTime * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { self.performSegue(withIdentifier: Configuration.Segues.UnwindToMainViewController, sender: nil) } } } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } }
gpl-3.0
82a82e139db1f0d6d2d95e6aea14d440
30.053691
165
0.594121
4.969925
false
false
false
false
xudafeng/ios-app-bootstrap
ios-app-bootstrap/components/CoreMotionViewController.swift
1
2404
// // AccelerometerViewController.swift // ios-app-bootstrap // // Created by xdf on 3/25/16. // Copyright © 2016 open source. All rights reserved. // import UIKit import Logger_swift import CoreMotion class CoreMotionViewController: UIViewController,UIAccelerometerDelegate { let motionManager = CMMotionManager() let titleLabel = UILabel() override func viewDidLoad() { super.viewDidLoad() view!.backgroundColor = UIColor.white titleLabel.textAlignment = .center titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.text = Const.TITLE titleLabel.textColor = UIColor.black titleLabel.font = UIFont.systemFont(ofSize: 24) titleLabel.frame = view.frame view.addSubview(titleLabel) if !motionManager.isAccelerometerAvailable { print("accelerometer is unavailable") return } motionManager.accelerometerUpdateInterval = 0.3 motionManager.startAccelerometerUpdates(to: OperationQueue.main) { (accelerometerData, error) in if (error != nil) { print("accelerometer error:\(error)") return } //print("accelerometer data:\(accelerometerData)") } if !motionManager.isGyroAvailable { print("gyro is unavailable") return } motionManager.gyroUpdateInterval = 0.3 motionManager.startGyroUpdates(to: OperationQueue.main) { (gyroData, error) in if (error != nil) { print("gyro error:\(error)") return } print("gyro data:\(gyroData)") } if !motionManager.isMagnetometerAvailable { print("magnetometer") return } motionManager.magnetometerUpdateInterval = 0.3 motionManager.startMagnetometerUpdates(to: OperationQueue.main) { (magData, error) in if error != nil { print("magnetometer error:\(error)") return } //print("magnetometer data:\(magData)") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
4553e903828f09b46dfb8b8901f617de
28.182927
104
0.587129
5.591121
false
false
false
false
PopcornTimeTV/PopcornTimeTV
PopcornTime/UI/Shared/View Controllers/UpNextViewController.swift
1
3979
import UIKit import SwiftyTimer #if os(tvOS) import MBCircularProgressBar #endif protocol UpNextViewControllerDelegate: class { func viewController(_ viewController: UpNextViewController, proceedToNextVideo proceed: Bool) } class UpNextViewController: UIViewController { @IBOutlet var imageView: UIImageView! @IBOutlet var titleLabel: UILabel! @IBOutlet var cancelButton: UIButton! @IBOutlet var playNextButton: UIButton! weak var delegate: UpNextViewControllerDelegate? private var timer: Timer? private var updateTimer: Timer? // iOS Exclusive @IBOutlet var subtitleLabel: UILabel? @IBOutlet var infoLabel: UILabel? @IBOutlet var countdownLabel: UILabel? // tvOS Exclusive @IBOutlet var summaryView: UITextView? @IBOutlet var containerView: UIView? #if os(tvOS) @IBOutlet var countdownView: MBCircularProgressBarView! #endif override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) startTimers() if UIDevice.current.userInterfaceIdiom == .tv, let presentingViewController = transitionCoordinator?.viewController(forKey: .from) as? PCTPlayerViewController { let movieView: UIView = presentingViewController.movieView containerView!.addSubview(movieView) movieView.translatesAutoresizingMaskIntoConstraints = true let frame = containerView!.convert(view.frame, from: view) movieView.frame = frame transitionCoordinator?.animate(alongsideTransition: { [unowned self, unowned movieView] _ in movieView.frame = self.containerView!.bounds }) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) stopTimers() if UIDevice.current.userInterfaceIdiom == .tv, let presentingViewController = transitionCoordinator?.viewController(forKey: .to) as? PCTPlayerViewController { transitionCoordinator?.animate(alongsideTransition: { [unowned self, unowned presentingViewController] _ in presentingViewController.movieView.frame = self.containerView!.convert(self.view.frame, from: self.view) }) { [unowned presentingViewController] _ in presentingViewController.view.insertSubview(presentingViewController.movieView, at: 0) presentingViewController.movieView.frame = presentingViewController.view.bounds } } } override func viewDidLoad() { super.viewDidLoad() containerView?.layer.borderColor = UIColor(white: 1, alpha: 0.2).cgColor containerView?.layer.borderWidth = 1 } func startTimers() { let initial = 30 var delay = initial updateTimer = Timer.every(1.0) { [weak self] in guard let `self` = self, (delay - 1) >= 0 else { return } delay -= 1 #if os(iOS) self.countdownLabel?.text = String(delay) #elseif os(tvOS) self.countdownView.value = CGFloat(delay) #endif } timer = Timer.after(TimeInterval(initial), { [weak self] in guard let `self` = `self` else { return } self.stopTimers() self.delegate?.viewController(self, proceedToNextVideo: true) }) } func stopTimers() { timer?.invalidate() timer = nil updateTimer?.invalidate() updateTimer = nil } @IBAction func cancel() { delegate?.viewController(self, proceedToNextVideo: false) stopTimers() } @IBAction func playNext() { stopTimers() delegate?.viewController(self, proceedToNextVideo: true) } }
gpl-3.0
8e8768a06b0584ad28083421733213d1
31.08871
125
0.621262
5.443228
false
false
false
false
yeziahehe/Gank
Pods/MonkeyKing/Sources/Helpers.swift
1
11132
import Foundation extension MonkeyKing { class func fetchWeChatOAuthInfoByCode(code: String, completionHandler: @escaping OAuthCompletionHandler) { var appID = "" var appKey = "" for case let .weChat(id, key, _) in shared.accountSet { guard let key = key else { completionHandler(["code": code], nil, nil) return } appID = id appKey = key } var accessTokenAPI = "https://api.weixin.qq.com/sns/oauth2/access_token" accessTokenAPI += "?grant_type=authorization_code" accessTokenAPI += "&appid=\(appID)" accessTokenAPI += "&secret=\(appKey)" accessTokenAPI += "&code=\(code)" // OAuth shared.request(accessTokenAPI, method: .get) { (json, response, error) in completionHandler(json, response, error) } } class func fetchWeiboOAuthInfoByCode(code: String, completionHandler: @escaping OAuthCompletionHandler) { var appID = "" var appKey = "" var redirectURL = "" for case let .weibo(id, key, url) in shared.accountSet { appID = id appKey = key redirectURL = url } var urlComponents = URLComponents(string: "https://api.weibo.com/oauth2/access_token") urlComponents?.queryItems = [ URLQueryItem(name: "client_id", value: appID), URLQueryItem(name: "client_secret", value: appKey), URLQueryItem(name: "grant_type", value: "authorization_code"), URLQueryItem(name: "redirect_uri", value: redirectURL), URLQueryItem(name: "code", value: code), ] guard let accessTokenAPI = urlComponents?.string else { completionHandler(["code": code], nil, nil) return } shared.request(accessTokenAPI, method: .post) { json, response, error in completionHandler(json, response, error) } } class func createAlipayMessageDictionary(withScene scene: NSNumber, info: Info, appID: String) -> [String: Any] { enum AlipayMessageType { case text case image(UIImage) case imageData(Data) case url(URL) } let keyUID = "CF$UID" let keyClass = "$class" let keyClasses = "$classes" let keyClassname = "$classname" var messageType: AlipayMessageType = .text if let media = info.media { switch media { case .url(let url): messageType = .url(url) case .image(let image): messageType = .image(image) case .imageData(let imageData): messageType = .imageData(imageData) case .gif: fatalError("Alipay not supports GIF type") case .audio: fatalError("Alipay not supports Audio type") case .video: fatalError("Alipay not supports Video type") case .file: fatalError("Alipay not supports File type") case .miniApp: fatalError("Alipay not supports Mini App type") } } else { // Text messageType = .text } // Public Items let UIDValue: Int let APMediaType: String switch messageType { case .text: UIDValue = 20 APMediaType = "APShareTextObject" case .image, .imageData: UIDValue = 21 APMediaType = "APShareImageObject" case .url: UIDValue = 24 APMediaType = "APShareWebObject" } let publicObjectsItem0 = "$null" let publicObjectsItem1: [String: Any] = [ keyClass: [keyUID: UIDValue], "NS.keys": [ [keyUID: 2], [keyUID: 3] ], "NS.objects": [ [keyUID: 4], [keyUID: 11] ] ] let publicObjectsItem2 = "app" let publicObjectsItem3 = "req" let publicObjectsItem4: [String: Any] = [ keyClass: [keyUID: 10], "appKey": [keyUID: 6], "bundleId": [keyUID: 7], "name": [keyUID: 5], "scheme": [keyUID: 8], "sdkVersion": [keyUID: 9] ] let publicObjectsItem5 = Bundle.main.monkeyking_displayName ?? "China" let publicObjectsItem6 = appID let publicObjectsItem7 = Bundle.main.monkeyking_bundleID ?? "com.nixWork.China" let publicObjectsItem8 = "ap\(appID)" let publicObjectsItem9 = "1.1.0.151016" // SDK Version let publicObjectsItem10: [String: Any] = [ keyClasses: ["APSdkApp", "NSObject"], keyClassname: "APSdkApp" ] let publicObjectsItem11: [String: Any] = [ keyClass: [keyUID: UIDValue - 1], "message": [keyUID: 13], "scene": [keyUID: UIDValue - 2], "type": [keyUID: 12] ] let publicObjectsItem12: NSNumber = 0 let publicObjectsItem13: [String: Any] = [ // For Text(13) && Image(13) keyClass: [keyUID: UIDValue - 3], "mediaObject": [keyUID: 14] ] let publicObjectsItem14: [String: Any] = [ // For Image(16) && URL(17) keyClasses: ["NSMutableData", "NSData", "NSObject"], keyClassname: "NSMutableData" ] let publicObjectsItem16: [String: Any] = [ keyClasses: [APMediaType, "NSObject"], keyClassname: APMediaType ] let publicObjectsItem17: [String: Any] = [ keyClasses: ["APMediaMessage", "NSObject"], keyClassname: "APMediaMessage" ] let publicObjectsItem18: NSNumber = scene let publicObjectsItem19: [String: Any] = [ keyClasses: ["APSendMessageToAPReq", "APBaseReq", "NSObject"], keyClassname: "APSendMessageToAPReq" ] let publicObjectsItem20: [String: Any] = [ keyClasses: ["NSMutableDictionary", "NSDictionary", "NSObject"], keyClassname: "NSMutableDictionary" ] var objectsValue: [Any] = [ publicObjectsItem0, publicObjectsItem1, publicObjectsItem2, publicObjectsItem3, publicObjectsItem4, publicObjectsItem5, publicObjectsItem6, publicObjectsItem7, publicObjectsItem8, publicObjectsItem9, publicObjectsItem10, publicObjectsItem11, publicObjectsItem12 ] switch messageType { case .text: let textObjectsItem14: [String: Any] = [ keyClass: [keyUID: 16], "text": [keyUID: 15] ] let textObjectsItem15 = info.title ?? "Input Text" objectsValue = objectsValue + [publicObjectsItem13, textObjectsItem14, textObjectsItem15] case .image(let image): let imageObjectsItem14: [String: Any] = [ keyClass: [keyUID: 17], "imageData": [keyUID: 15] ] let imageData = image.jpegData(compressionQuality: 0.9) ?? Data() let imageObjectsItem15: [String: Any] = [ keyClass: [keyUID: 16], "NS.data": imageData ] objectsValue = objectsValue + [publicObjectsItem13, imageObjectsItem14, imageObjectsItem15, publicObjectsItem14] case .imageData(let imageData): let imageObjectsItem14: [String: Any] = [ keyClass: [keyUID: 17], "imageData": [keyUID: 15] ] let imageObjectsItem15: [String: Any] = [ keyClass: [keyUID: 16], "NS.data": imageData ] objectsValue = objectsValue + [publicObjectsItem13, imageObjectsItem14, imageObjectsItem15, publicObjectsItem14] case .url(let url): let urlObjectsItem13: [String: Any] = [ keyClass: [keyUID: 21], "desc": [keyUID: 15], "mediaObject": [keyUID: 18], "thumbData": [keyUID: 16], "title": [keyUID: 14] ] let thumbnailData = info.thumbnail?.monkeyking_compressedImageData ?? Data() let urlObjectsItem14 = info.title ?? "Input Title" let urlObjectsItem15 = info.description ?? "Input Description" let urlObjectsItem16: [String: Any] = [ keyClass: [keyUID: 17], "NS.data": thumbnailData ] let urlObjectsItem18: [String: Any] = [ keyClass: [keyUID: 20], "webpageUrl": [keyUID: 19] ] let urlObjectsItem19 = url.absoluteString objectsValue = objectsValue + [ urlObjectsItem13, urlObjectsItem14, urlObjectsItem15, urlObjectsItem16, publicObjectsItem14, urlObjectsItem18, urlObjectsItem19 ] } objectsValue += [publicObjectsItem16, publicObjectsItem17, publicObjectsItem18, publicObjectsItem19, publicObjectsItem20] let dictionary: [String: Any] = [ "$archiver": "NSKeyedArchiver", "$objects": objectsValue, "$top": ["root" : [keyUID: 1]], "$version": 100000 ] return dictionary } func request(_ urlString: String, method: Networking.Method, parameters: [String: Any]? = nil, encoding: Networking.ParameterEncoding = .url, headers: [String: String]? = nil, completionHandler: @escaping Networking.NetworkingResponseHandler) { Networking.shared.request(urlString, method: method, parameters: parameters, encoding: encoding, headers: headers, completionHandler: completionHandler) } func upload(_ urlString: String, parameters: [String: Any], headers: [String: String]? = nil,completionHandler: @escaping Networking.NetworkingResponseHandler) { Networking.shared.upload(urlString, parameters: parameters, headers: headers, completionHandler: completionHandler) } class func openURL(urlString: String, options: [UIApplication.OpenExternalURLOptionsKey: Any] = [:], completionHandler completion: ((Bool) -> Swift.Void)? = nil) { guard let url = URL(string: urlString), UIApplication.shared.canOpenURL(url) else { completion?(false) return } if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: options) { flag in completion?(flag) } } else { completion?(UIApplication.shared.openURL(url)) } } class func openURL(urlString: String) -> Bool { guard let url = URL(string: urlString) else { return false } return UIApplication.shared.openURL(url) } func canOpenURL(urlString: String) -> Bool { guard let url = URL(string: urlString) else { return false } return UIApplication.shared.canOpenURL(url) } }
gpl-3.0
700ab8c951c29cb86587f86c2a9e7347
39.48
248
0.560726
4.528885
false
false
false
false
mckaskle/FlintKit
FlintKit/UIKit/KeyboardManager.swift
1
6108
// // MIT License // // KeyboardManager.swift // // Copyright (c) 2018 Devin McKaskle // // 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 public final class KeyboardManager { // MARK: - Type Aliases public typealias Handler = (Context) -> Void // MARK: - Subtypes public struct Context { // MARK: - Object Lifecycle fileprivate init(notification: Notification) { animationDuration = notification.keyboardAnimationDuration animationOptions = notification.keyboardAnimationOptions frameBegin = notification.keyboardFrameBegin frameEnd = notification.keyboardFrameEnd } // MARK: - Public Properties public let animationDuration: TimeInterval? public let animationOptions: UIView.AnimationOptions /// `CGRect` that identifies the start frame of the keyboard in screen /// coordinates. These coordinates do not take into account any rotation /// factors applied to the view’s contents as a result of interface /// orientation changes. Thus, you may need to convert the rectangle to view /// coordinates (using the `convert(CGRect, from: UIView?)` method) before /// using it. /// /// See also: `convertedFrameBegin(in: UIView)`. public let frameBegin: CGRect? /// `CGRect` that identifies the end frame of the keyboard in screen /// coordinates. These coordinates do not take into account any rotation /// factors applied to the view’s contents as a result of interface /// orientation changes. Thus, you may need to convert the rectangle to view /// coordinates (using the `convert(CGRect, from: UIView?)` method) before /// using it. /// /// See also: `convertedFrameEnd(in: UIView)`. public let frameEnd: CGRect? // MARK: - Public Methods /// Convenience method that returns the begining frame of the keyboard that /// has already been converted into the given view's coordinate space. public func convertedFrameBegin(in view: UIView) -> CGRect? { return frameBegin.map { view.convert($0, from: view.window) } } /// Convenience method that returns the ending frame of the keyboard that /// has already been converted into the given view's coordinate space. public func convertedFrameEnd(in view: UIView) -> CGRect? { return frameEnd.map { view.convert($0, from: view.window) } } } // MARK: - Object Lifecycle public init() { NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil ) } // MARK: - Public Properties /// This handler will be called within an animation block that matches the /// animation timing of the keyboard being shown. public var keyboardWillShowHandler: Handler? /// This handler will be called within an animation block that matches the /// animation timing of the keyboard being hidden. public var keyboardWillHideHandler: Handler? // MARK: - Public Methods public func startAutoAdjustingContentInsets(for scrollView: UIScrollView) { scrollViews.insert(scrollView) } public func stopAutoAdjustingContentInsets(for scrollView: UIScrollView) { scrollViews.remove(scrollView) } // MARK: - Private Methods private var scrollViews: Set<UIScrollView> = [] // MARK: - Actions @objc dynamic private func keyboardWillShow(_ notification: Notification) { let context = Context(notification: notification) let duration = context.animationDuration ?? 0.3 UIView.animate(withDuration: duration, delay: 0, options: context.animationOptions, animations: { for scrollView in self.scrollViews { guard var frame = context.convertedFrameEnd(in: scrollView) else { continue } if #available(iOS 11.0, *) { frame = frame.inset(by: scrollView.safeAreaInsets) } let heightOverlappingScrollView = scrollView.bounds.intersection(frame).height scrollView.contentInset.bottom = heightOverlappingScrollView scrollView.scrollIndicatorInsets.bottom = heightOverlappingScrollView } self.keyboardWillShowHandler?(context) }, completion: nil) } @objc dynamic private func keyboardWillHide(_ notification: Notification) { let context = Context(notification: notification) let duration = context.animationDuration ?? 0.3 UIView.animate(withDuration: duration, delay: 0, options: context.animationOptions, animations: { for scrollView in self.scrollViews { scrollView.contentInset.bottom = 0 scrollView.scrollIndicatorInsets.bottom = 0 } self.keyboardWillHideHandler?(context) }, completion: nil) } }
mit
a6688157040d132c959354457cf149ab
34.08046
101
0.70036
4.962602
false
false
false
false
Zewo/ZeroMQ
Sources/Socket.swift
2
21325
// Socket.swift // // The MIT License (MIT) // // Copyright (c) 2015 Zewo // // 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 CZeroMQ import struct Foundation.Data public struct SendMode : OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let DontWait = SendMode(rawValue: Int(ZMQ_DONTWAIT)) public static let SendMore = SendMode(rawValue: Int(ZMQ_SNDMORE)) } public struct ReceiveMode : OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let DontWait = ReceiveMode(rawValue: Int(ZMQ_DONTWAIT)) } public final class Socket { let socket: UnsafeMutableRawPointer init(socket: UnsafeMutableRawPointer) { self.socket = socket } deinit { zmq_close(socket) } func setOption(_ option: Int32, value: UnsafeRawPointer?, length: Int) throws { if zmq_setsockopt(socket, option, value, length) == -1 { throw ZeroMqError.lastError } } func getOption(_ option: Int32, value: UnsafeMutableRawPointer, length: UnsafeMutablePointer<Int>) throws { if zmq_getsockopt(socket, option, value, length) == -1 { throw ZeroMqError.lastError } } public func bind(_ endpoint: String) throws { if zmq_bind(socket, endpoint) == -1 { throw ZeroMqError.lastError } } public func connect(_ endpoint: String) throws { if zmq_connect(socket, endpoint) == -1 { throw ZeroMqError.lastError } } public func sendMessage(_ message: Message, mode: SendMode = []) throws -> Bool { let result = zmq_msg_send(&message.message, socket, Int32(mode.rawValue)) if result == -1 && zmq_errno() == EAGAIN { return false } if result == -1 { throw ZeroMqError.lastError } return true } func send(_ buffer: UnsafeMutableRawPointer, length: Int, mode: SendMode = []) throws -> Bool { let result = zmq_send(socket, buffer, length, Int32(mode.rawValue)) if result == -1 && zmq_errno() == EAGAIN { return false } if result == -1 { throw ZeroMqError.lastError } return true } public func send(_ data: Data, mode: SendMode = []) throws -> Bool { var data = data return try data.withUnsafeMutableBytes { bytes in return try self.send(bytes, length: data.count, mode: mode) } } func sendImmutable(_ buffer: UnsafeRawPointer, length: Int, mode: SendMode = []) throws -> Bool { let result = zmq_send_const(socket, buffer, length, Int32(mode.rawValue)) if result == -1 && zmq_errno() == EAGAIN { return false } if result == -1 { throw ZeroMqError.lastError } return true } public func receiveMessage(_ mode: ReceiveMode = []) throws -> Message? { let message = try Message() let result = zmq_msg_recv(&message.message, socket, Int32(mode.rawValue)) if result == -1 && zmq_errno() == EAGAIN { return nil } if result == -1 { throw ZeroMqError.lastError } return message } public func receive(_ bufferSize: Int = 1024, mode: ReceiveMode = []) throws -> Data? { var data = Data(count: bufferSize) let result = data.withUnsafeMutableBytes { bytes in return zmq_recv(socket, bytes, bufferSize, Int32(mode.rawValue)) } if result == -1 && zmq_errno() == EAGAIN { return nil } if result == -1 { throw ZeroMqError.lastError } let bufferEnd = min(Int(result), bufferSize) return Data(data[0 ..< bufferEnd]) } public func close() throws { if zmq_close(socket) == -1 { throw ZeroMqError.lastError } } public func monitor(_ endpoint: String, events: SocketEvent) throws { if zmq_socket_monitor(socket, endpoint, events.rawValue) == -1 { throw ZeroMqError.lastError } } } public struct SocketEvent : OptionSet { public let rawValue: Int32 public init(rawValue: Int32) { self.rawValue = rawValue } public static let All = SocketEvent(rawValue: ZMQ_EVENT_ALL) public static let Connected = SocketEvent(rawValue: ZMQ_EVENT_CONNECTED) public static let Delayed = SocketEvent(rawValue: ZMQ_EVENT_CONNECT_DELAYED) public static let Retried = SocketEvent(rawValue: ZMQ_EVENT_CONNECT_RETRIED) public static let Listening = SocketEvent(rawValue: ZMQ_EVENT_LISTENING) public static let BindFailed = SocketEvent(rawValue: ZMQ_EVENT_BIND_FAILED) public static let Accepted = SocketEvent(rawValue: ZMQ_EVENT_ACCEPTED) public static let AcceptFailed = SocketEvent(rawValue: ZMQ_EVENT_ACCEPT_FAILED) public static let Closed = SocketEvent(rawValue: ZMQ_EVENT_CLOSED) public static let CloseFailed = SocketEvent(rawValue: ZMQ_EVENT_CLOSE_FAILED) public static let Disconnected = SocketEvent(rawValue: ZMQ_EVENT_DISCONNECTED) public static let MonitorStopped = SocketEvent(rawValue: ZMQ_EVENT_MONITOR_STOPPED) } extension Socket { func setOption(_ option: Int32, _ value: Bool) throws { var value = value ? 1 : 0 try setOption(option, value: &value, length: MemoryLayout<Int32>.size) } func setOption(_ option: Int32, _ value: Int32) throws { var value = value try setOption(option, value: &value, length: MemoryLayout<Int32>.size) } func setOption(_ option: Int32, _ value: String) throws { try value.withCString { v in try setOption(option, value: v, length: value.utf8.count) } } func setOption(_ option: Int32, _ value: Data) throws { try value.withUnsafeBytes { bytes in try setOption(option, value: bytes, length: value.count) } } func setOption(_ option: Int32, _ value: String?) throws { if let value = value { try value.withCString { v in try setOption(option, value: v, length: value.utf8.count) } } else { try setOption(option, value: nil, length: 0) } } } extension Socket { public func setAffinity(_ value: UInt64) throws { var value = value try setOption(ZMQ_AFFINITY, value: &value, length: MemoryLayout<UInt64>.size) } public func setBacklog(_ value: Int32) throws { try setOption(ZMQ_BACKLOG, value) } public func setConnectRID(_ value: String) throws { try setOption(ZMQ_CONNECT_RID, value) } public func setConflate(_ value: Bool) throws { try setOption(ZMQ_CONFLATE, value) } // public func setConnectTimeout(value: Int32) throws { // try setOption(ZMQ_CONNECT_TIMEOUT, value) // } public func setCURVEPublicKey(_ value: String?) throws { try setOption(ZMQ_CURVE_PUBLICKEY, value) } public func setCURVESecretKey(_ value: String?) throws { try setOption(ZMQ_CURVE_SECRETKEY, value) } public func setCURVEServer(_ value: Bool) throws { try setOption(ZMQ_CURVE_SERVER, value) } public func setCURVEServerKey(_ value: String?) throws { try setOption(ZMQ_CURVE_SERVERKEY, value) } public func setGSSAPIPlainText(_ value: Bool) throws { try setOption(ZMQ_GSSAPI_PLAINTEXT, value) } public func setGSSAPIPrincipal(_ value: String) throws { try setOption(ZMQ_GSSAPI_PRINCIPAL, value) } public func setGSSAPIServer(_ value: Bool) throws { try setOption(ZMQ_GSSAPI_SERVER, value) } public func setGSSAPIServicePrincipal(_ value: String) throws { try setOption(ZMQ_GSSAPI_SERVICE_PRINCIPAL, value) } public func setHandshakeInterval(_ value: Int32) throws { try setOption(ZMQ_HANDSHAKE_IVL, value) } // public func setHeartbeatInterval(value: Int32) throws { // try setOption(ZMQ_HEARTBEAT_IVL, value) // } // public func setHeartbeatTimeout(value: Int32) throws { // try setOption(ZMQ_HEARTBEAT_TIMEOUT, value) // } // public func setHeartbeatTTTL(value: Int32) throws { // try setOption(ZMQ_HEARTBEAT_TTL, value) // } public func setIdentity(_ value: String) throws { try setOption(ZMQ_IDENTITY, value) } public func setImmediate(_ value: Bool) throws { try setOption(ZMQ_IMMEDIATE, value) } // public func setInvertMatching(value: Bool) throws { // try setOption(ZMQ_INVERT_MATCHING, value) // } public func setIPV6(_ value: Bool) throws { try setOption(ZMQ_IPV6, value) } public func setLinger(_ value: Int32) throws { try setOption(ZMQ_LINGER, value) } public func setMaxMessageSize(_ value: Int64) throws { var value = value try setOption(ZMQ_MAXMSGSIZE, value: &value, length: MemoryLayout<Int64>.size) } public func setMulticastHops(_ value: Int32) throws { try setOption(ZMQ_MULTICAST_HOPS, value) } public func setPlainPassword(_ value: String?) throws { try setOption(ZMQ_PLAIN_PASSWORD, value) } public func setPlainServer(_ value: Bool) throws { try setOption(ZMQ_PLAIN_SERVER, value) } public func setPlainUsername(_ value: String?) throws { try setOption(ZMQ_PLAIN_USERNAME, value) } public func setProbeRouter(_ value: Bool) throws { try setOption(ZMQ_PROBE_ROUTER, value) } public func setRate(_ value: Int32) throws { try setOption(ZMQ_RATE, value) } public func setReceiveBuffer(_ value: Int32) throws { try setOption(ZMQ_RCVBUF, value) } public func setReceiveHighWaterMark(_ value: Int32) throws { try setOption(ZMQ_RCVHWM, value) } public func setReceiveTimeout(_ value: Int32) throws { try setOption(ZMQ_RCVTIMEO, value) } public func setReconnectInterval(_ value: Int32) throws { try setOption(ZMQ_RECONNECT_IVL, value) } public func setReconnectIntervalMax(_ value: Int32) throws { try setOption(ZMQ_RECONNECT_IVL_MAX, value) } public func setRecoveryInterval(_ value: Int32) throws { try setOption(ZMQ_RECOVERY_IVL, value) } public func setReqCorrelate(_ value: Bool) throws { try setOption(ZMQ_REQ_CORRELATE, value) } public func setReqRelaxed(_ value: Bool) throws { try setOption(ZMQ_REQ_RELAXED, value) } public func setRouterHandover(_ value: Bool) throws { try setOption(ZMQ_ROUTER_HANDOVER, value) } public func setRouterMandatory(_ value: Bool) throws { try setOption(ZMQ_ROUTER_MANDATORY, value) } public func setRouterRaw(_ value: Bool) throws { try setOption(ZMQ_ROUTER_RAW, value) } public func setSendBuffer(_ value: Int32) throws { try setOption(ZMQ_SNDBUF, value) } public func setSendHighWaterMark(_ value: Int32) throws { try setOption(ZMQ_SNDHWM, value) } public func setSendTimeout(_ value: Int32) throws { try setOption(ZMQ_SNDTIMEO, value) } // public func setStreamNotify(value: Bool) throws { // try setOption(ZMQ_STREAM_NOTIFY, value) // } public func setSubscribe(_ value: Data) throws { try setOption(ZMQ_SUBSCRIBE, value) } public func setTCPKeepAlive(_ value: Int32) throws { try setOption(ZMQ_TCP_KEEPALIVE, value) } public func setTCPKeepAliveCount(_ value: Int32) throws { try setOption(ZMQ_TCP_KEEPALIVE_CNT, value) } public func setTCPKeepAliveIdle(_ value: Int32) throws { try setOption(ZMQ_TCP_KEEPALIVE_IDLE, value) } public func setTCPKeepAliveInterval(_ value: Int32) throws { try setOption(ZMQ_TCP_KEEPALIVE_INTVL, value) } // public func setTCPRetransmitTimeout(var value: Int32) throws { // try setOption(ZMQ_TCP_RETRANSMIT_TIMEOUT, value: &value, length: strideof(Int32)) // } public func setTypeOfService(_ value: Int32) throws { try setOption(ZMQ_TOS, value) } public func setUnsubscribe(_ value: Data) throws { try setOption(ZMQ_UNSUBSCRIBE, value) } public func setXPubVerbose(_ value: Bool) throws { try setOption(ZMQ_XPUB_VERBOSE, value) } // public func setXPubVerboseUnsubscribe(value: Bool) throws { // var v = value ? 1 : 0 // try setOption(ZMQ_XPUB_VERBOSE_UNSUBSCRIBE, value: &v, length: strideof(Int32)) // } // public func setXPubManual(value: Bool) throws { // try setOption(ZMQ_XPUB_MANUAL, value) // } public func setXPubNoDrop(_ value: Bool) throws { try setOption(ZMQ_XPUB_NODROP, value) } // public func setXPubWelcomeMessage(value: String) throws { // try setOption(ZMQ_XPUB_WELCOME_MSG, value) // } public func setZAPDomain(_ value: String?) throws { try setOption(ZMQ_ZAP_DOMAIN, value) } } extension Socket { func getOption(_ option: Int32) throws -> Int32 { var value: Int32 = 0 var length = MemoryLayout<Int32>.size try getOption(option, value: &value, length: &length) return value } func getOption(_ option: Int32) throws -> Bool { let value: Int32 = try getOption(option) return value != 0 } func getOption(_ option: Int32, count: Int) throws -> String? { var value = [Int8](repeating: 0, count: count) var length = value.count try getOption(option, value: &value, length: &length) return String(validatingUTF8: Array(value[0 ..< length])) } } extension Socket { public func getAffinity() throws -> UInt64 { var value: UInt64 = 0 var length = MemoryLayout<UInt64>.size try getOption(ZMQ_AFFINITY, value: &value, length: &length) return value } public func getBacklog() throws -> Int32 { return try getOption(ZMQ_BACKLOG) } // public func getConnectTimeout() throws -> Int32 { // return try getOption(ZMQ_CONNECT_TIMEOUT) // } public func getCURVEPublicKey() throws -> String { return try getOption(ZMQ_CURVE_PUBLICKEY, count: 41)! } public func getCURVESecretKey() throws -> String { return try getOption(ZMQ_CURVE_SECRETKEY, count: 41)! } public func getCURVEServerKey() throws -> String { return try getOption(ZMQ_CURVE_SERVERKEY, count: 41)! } public func getEvents() throws -> PollEvent? { let value: Int32 = try getOption(ZMQ_EVENTS) return Int(value) == -1 ? nil : PollEvent(rawValue: Int16(value)) } public func getFileDescriptor() throws -> Int32 { return try getOption(ZMQ_FD) } public func getGSSAPIPlainText() throws -> Bool { return try getOption(ZMQ_GSSAPI_PLAINTEXT) } public func getGSSAPIPrincipal() throws -> String { return try getOption(ZMQ_GSSAPI_PRINCIPAL, count: 256)! } public func getGSSAPIServer() throws -> Bool { return try getOption(ZMQ_GSSAPI_SERVER) } public func getGSSAPIServicePrincipal() throws -> String { return try getOption(ZMQ_GSSAPI_SERVICE_PRINCIPAL, count: 256)! } public func getHandshakeInterval() throws -> Int32 { return try getOption(ZMQ_HANDSHAKE_IVL) } public func getIdentity() throws -> String { return try getOption(ZMQ_IDENTITY, count: 256) ?? "" } public func getImmediate() throws -> Bool { return try getOption(ZMQ_IMMEDIATE) } // public func getInvertMatching() throws -> Bool { // return try getOption(ZMQ_INVERT_MATCHING) // } public func getIPV4Only() throws -> Bool { return try getOption(ZMQ_IPV4ONLY) } public func getIPV6() throws -> Bool { return try getOption(ZMQ_IPV6) } public func getLastEndpoint() throws -> String { return try getOption(ZMQ_LAST_ENDPOINT, count: 256)! } public func getLinger() throws -> Int32 { return try getOption(ZMQ_LINGER) } public func getMaxMessageSize() throws -> Int64 { var value: Int64 = 0 var length = MemoryLayout<Int64>.size try getOption(ZMQ_MAXMSGSIZE, value: &value, length: &length) return value } public func getMechanism() throws -> SecurityMechanism { let value: Int32 = try getOption(ZMQ_MECHANISM) return SecurityMechanism(rawValue: value)! } public func getMulticastHops() throws -> Int32 { return try getOption(ZMQ_MULTICAST_HOPS) } public func getPlainPassword() throws -> String { return try getOption(ZMQ_PLAIN_PASSWORD, count: 256)! } public func getPlainServer() throws -> Bool { return try getOption(ZMQ_PLAIN_SERVER) } public func getPlainUsername() throws -> String { return try getOption(ZMQ_PLAIN_USERNAME, count: 256)! } public func getRate() throws -> Int32 { return try getOption(ZMQ_RATE) } public func getReceiveBuffer() throws -> Int32 { return try getOption(ZMQ_RCVBUF) } public func getReceiveHighWaterMark() throws -> Int32 { return try getOption(ZMQ_RCVHWM) } public func getReceiveMore() throws -> Bool { return try getOption(ZMQ_RCVMORE) } public func getReceiveTimeout() throws -> Int32 { return try getOption(ZMQ_RCVTIMEO) } public func getReconnectInterval() throws -> Int32 { return try getOption(ZMQ_RECONNECT_IVL) } public func getReconnectIntervalMax() throws -> Int32 { return try getOption(ZMQ_RECONNECT_IVL_MAX) } public func getRecoveryInterval() throws -> Int32 { return try getOption(ZMQ_RECOVERY_IVL) } public func getSendBuffer() throws -> Int32 { return try getOption(ZMQ_SNDBUF) } public func getSendHighWaterMark() throws -> Int32 { return try getOption(ZMQ_SNDHWM) } public func getSendTimeout() throws -> Int32 { return try getOption(ZMQ_SNDTIMEO) } public func getTCPKeepAlive() throws -> Int32 { return try getOption(ZMQ_TCP_KEEPALIVE) } public func getTCPKeepAliveCount() throws -> Int32 { return try getOption(ZMQ_TCP_KEEPALIVE_CNT) } public func getTCPKeepAliveIdle() throws -> Int32 { return try getOption(ZMQ_TCP_KEEPALIVE_IDLE) } public func getTCPKeepAliveInterval() throws -> Int32 { return try getOption(ZMQ_TCP_KEEPALIVE_INTVL) } // public func getTCPRetransmitTimeout() throws -> Int32 { // var value: Int32 = 0 // var length = strideof(Int32) // try getOption(ZMQ_TCP_RETRANSMIT_TIMEOUT, value: &value, length: &length) // return value // } // public func getThreadSafe() throws -> Bool { // return try getOption(ZMQ_THREAD_SAFE) // } public func getTypeOfService() throws -> Int32 { return try getOption(ZMQ_TOS) } public func getType() throws -> SocketType { let value: Int32 = try getOption(ZMQ_TYPE) return SocketType(rawValue: value)! } public func getZAPDomain() throws -> String { return try getOption(ZMQ_ZAP_DOMAIN, count: 256)! } } public enum SecurityMechanism { case null case plain case curve } extension SecurityMechanism { init?(rawValue: Int32) { switch rawValue { case ZMQ_NULL: self = .null case ZMQ_PLAIN: self = .plain case ZMQ_CURVE: self = .curve default: return nil } } } extension Socket { public func send(_ string: String, mode: SendMode = []) throws -> Bool { return try send(Data(string.utf8), mode: mode) } public func receive(_ mode: ReceiveMode = []) throws -> String? { guard let buffer = try receive(mode: mode) else { return nil } return String(data: buffer, encoding: String.Encoding.utf8) } }
mit
87df4bfb54cf26a23989df840cb3a5c1
29.120056
111
0.63381
3.85903
false
false
false
false
groue/GRDB.swift
GRDB/Record/PersistableRecord+Upsert.swift
1
16123
// MARK: - Upsert extension PersistableRecord { #if GRDBCUSTOMSQLITE || GRDBCIPHER /// Executes an `INSERT ON CONFLICT DO UPDATE` statement. /// /// The upsert behavior is triggered by a violation of any uniqueness /// constraint on the table (primary key or unique index). In case of /// violation, all columns but the primary key are overwritten with the /// inserted values. /// /// For example: /// /// ```swift /// struct Player: Encodable, PersistableRecord { /// var id: Int64 /// var name: String /// var score: Int /// } /// /// // INSERT INTO player (id, name, score) /// // VALUES (1, 'Arthur', 1000) /// // ON CONFLICT DO UPDATE SET /// // name = excluded.name, /// // score = excluded.score /// let player = Player(id: 1, name: "Arthur", score: 1000) /// try player.upsert(db) /// ``` /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func upsert(_ db: Database) throws { try willSave(db) var saved: PersistenceSuccess? try aroundSave(db) { let inserted = try upsertWithCallbacks(db) saved = PersistenceSuccess(inserted) return saved! } guard let saved else { try persistenceCallbackMisuse("aroundSave") } didSave(saved) } /// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and /// returns the upserted record. /// /// With default parameters (`upsertAndFetch(db)`), the upsert behavior is /// triggered by a violation of any uniqueness constraint on the table /// (primary key or unique index). In case of violation, all columns but the /// primary key are overwritten with the inserted values: /// /// ```swift /// struct Player: Encodable, PersistableRecord { /// var id: Int64 /// var name: String /// var score: Int /// } /// /// // INSERT INTO player (id, name, score) /// // VALUES (1, 'Arthur', 1000) /// // ON CONFLICT DO UPDATE SET /// // name = excluded.name, /// // score = excluded.score /// // RETURNING * /// let player = Player(id: 1, name: "Arthur", score: 1000) /// let upsertedPlayer = try player.upsertAndFetch(db) /// ``` /// /// With `conflictTarget` and `assignments` arguments, you can further /// control the upsert behavior. Make sure you check /// <https://www.sqlite.org/lang_UPSERT.html> for detailed information. /// /// The conflict target are the columns of the uniqueness constraint /// (primary key or unique index) that triggers the upsert. If empty, all /// uniqueness constraint are considered. /// /// The assignments describe how to update columns in case of violation of /// a uniqueness constraint. In the next example, we insert the new /// vocabulary word "jovial" if that word is not already in the dictionary. /// If the word is already in the dictionary, it increments the counter, /// does not overwrite the tainted flag, and overwrites the /// remaining columns: /// /// ```swift /// // CREATE TABLE vocabulary( /// // word TEXT PRIMARY KEY, /// // kind TEXT NOT NULL, /// // isTainted BOOLEAN DEFAULT 0, /// // count INT DEFAULT 1)) /// struct Vocabulary: Encodable, PersistableRecord { /// var word: String /// var kind: String /// var isTainted: Bool /// } /// /// // INSERT INTO vocabulary(word, kind, isTainted) /// // VALUES('jovial', 'adjective', 0) /// // ON CONFLICT(word) DO UPDATE SET \ /// // count = count + 1, /// // kind = excluded.kind /// // RETURNING * /// let vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false) /// let upserted = try vocabulary.upsertAndFetch( /// db, /// onConflict: ["word"], /// doUpdate: { _ in /// [Column("count") += 1, /// Column("isTainted").noOverwrite] /// }) /// ``` /// /// - parameter db: A database connection. /// - parameter conflictTarget: The conflict target. /// - parameter assignments: An optional function that returns an array of /// ``ColumnAssignment``. In case of violation of a uniqueness /// constraints, these assignments are performed, and remaining columns /// are overwritten by inserted values. /// - returns: The upserted record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func upsertAndFetch( _ db: Database, onConflict conflictTarget: [String] = [], doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> Self where Self: FetchableRecord { try upsertAndFetch(db, as: Self.self, onConflict: conflictTarget, doUpdate: assignments) } /// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and /// returns the upserted record. /// /// See `upsertAndFetch(_:onConflict:doUpdate:)` for more information about /// the `conflictTarget` and `assignments` parameters. /// /// - parameter db: A database connection. /// - parameter returnedType: The type of the returned record. /// - parameter conflictTarget: The conflict target. /// - parameter assignments: An optional function that returns an array of /// ``ColumnAssignment``. In case of violation of a uniqueness /// constraints, these assignments are performed, and remaining columns /// are overwritten by inserted values. /// - returns: A record of type `returnedType`. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func upsertAndFetch<T: FetchableRecord & TableRecord>( _ db: Database, as returnedType: T.Type, onConflict conflictTarget: [String] = [], doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> T { try willSave(db) var success: (inserted: InsertionSuccess, returned: T)? try aroundSave(db) { success = try upsertAndFetchWithCallbacks( db, onConflict: conflictTarget, doUpdate: assignments, selection: T.databaseSelection, decode: { try T(row: $0) }) return PersistenceSuccess(success!.inserted) } guard let success else { try persistenceCallbackMisuse("aroundSave") } didSave(PersistenceSuccess(success.inserted)) return success.returned } #else /// Executes an `INSERT ON CONFLICT DO UPDATE` statement. /// /// The upsert behavior is triggered by a violation of any uniqueness /// constraint on the table (primary key or unique index). In case of /// violation, all columns but the primary key are overwritten with the /// inserted values. /// /// For example: /// /// ```swift /// struct Player: Encodable, PersistableRecord { /// var id: Int64 /// var name: String /// var score: Int /// } /// /// // INSERT INTO player (id, name, score) /// // VALUES (1, 'Arthur', 1000) /// // ON CONFLICT DO UPDATE SET /// // name = excluded.name, /// // score = excluded.score /// let player = Player(id: 1, name: "Arthur", score: 1000) /// try player.upsert(db) /// ``` /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func upsert(_ db: Database) throws { try willSave(db) var saved: PersistenceSuccess? try aroundSave(db) { let inserted = try upsertWithCallbacks(db) saved = PersistenceSuccess(inserted) return saved! } guard let saved else { try persistenceCallbackMisuse("aroundSave") } didSave(saved) } /// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and /// returns the upserted record. /// /// With default parameters (`upsertAndFetch(db)`), the upsert behavior is /// triggered by a violation of any uniqueness constraint on the table /// (primary key or unique index). In case of violation, all columns but the /// primary key are overwritten with the inserted values: /// /// ```swift /// struct Player: Encodable, PersistableRecord { /// var id: Int64 /// var name: String /// var score: Int /// } /// /// // INSERT INTO player (id, name, score) /// // VALUES (1, 'Arthur', 1000) /// // ON CONFLICT DO UPDATE SET /// // name = excluded.name, /// // score = excluded.score /// // RETURNING * /// let player = Player(id: 1, name: "Arthur", score: 1000) /// let upsertedPlayer = try player.upsertAndFetch(db) /// ``` /// /// With `conflictTarget` and `assignments` arguments, you can further /// control the upsert behavior. Make sure you check /// <https://www.sqlite.org/lang_UPSERT.html> for detailed information. /// /// The conflict target are the columns of the uniqueness constraint /// (primary key or unique index) that triggers the upsert. If empty, all /// uniqueness constraint are considered. /// /// The assignments describe how to update columns in case of violation of /// a uniqueness constraint. In the next example, we insert the new /// vocabulary word "jovial" if that word is not already in the dictionary. /// If the word is already in the dictionary, it increments the counter, /// does not overwrite the tainted flag, and overwrites the /// remaining columns: /// /// ```swift /// // CREATE TABLE vocabulary( /// // word TEXT PRIMARY KEY, /// // kind TEXT NOT NULL, /// // isTainted BOOLEAN DEFAULT 0, /// // count INT DEFAULT 1)) /// struct Vocabulary: Encodable, PersistableRecord { /// var word: String /// var kind: String /// var isTainted: Bool /// } /// /// // INSERT INTO vocabulary(word, kind, isTainted) /// // VALUES('jovial', 'adjective', 0) /// // ON CONFLICT(word) DO UPDATE SET \ /// // count = count + 1, /// // kind = excluded.kind /// // RETURNING * /// let vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false) /// let upserted = try vocabulary.upsertAndFetch( /// db, /// onConflict: ["word"], /// doUpdate: { _ in /// [Column("count") += 1, /// Column("isTainted").noOverwrite] /// }) /// ``` /// /// - parameter db: A database connection. /// - parameter conflictTarget: The conflict target. /// - parameter assignments: An optional function that returns an array of /// ``ColumnAssignment``. In case of violation of a uniqueness /// constraints, these assignments are performed, and remaining columns /// are overwritten by inserted values. /// - returns: The upserted record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func upsertAndFetch( _ db: Database, onConflict conflictTarget: [String] = [], doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> Self where Self: FetchableRecord { try upsertAndFetch(db, as: Self.self, onConflict: conflictTarget, doUpdate: assignments) } /// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and /// returns the upserted record. /// /// See ``upsertAndFetch(_:onConflict:doUpdate:)`` for more information /// about the `conflictTarget` and `assignments` parameters. /// /// - parameter db: A database connection. /// - parameter returnedType: The type of the returned record. /// - parameter conflictTarget: The conflict target. /// - parameter assignments: An optional function that returns an array of /// ``ColumnAssignment``. In case of violation of a uniqueness /// constraints, these assignments are performed, and remaining columns /// are overwritten by inserted values. /// - returns: A record of type `returnedType`. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func upsertAndFetch<T: FetchableRecord & TableRecord>( _ db: Database, as returnedType: T.Type, onConflict conflictTarget: [String] = [], doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> T { try willSave(db) var success: (inserted: InsertionSuccess, returned: T)? try aroundSave(db) { success = try upsertAndFetchWithCallbacks( db, onConflict: conflictTarget, doUpdate: assignments, selection: T.databaseSelection, decode: { try T(row: $0) }) return PersistenceSuccess(success!.inserted) } guard let success else { try persistenceCallbackMisuse("aroundSave") } didSave(PersistenceSuccess(success.inserted)) return success.returned } #endif } // MARK: - Internal extension PersistableRecord { @inlinable // allow specialization so that empty callbacks are removed func upsertWithCallbacks(_ db: Database) throws -> InsertionSuccess { let (inserted, _) = try upsertAndFetchWithCallbacks( db, onConflict: [], doUpdate: nil, selection: [], decode: { _ in /* Nothing to decode */ }) return inserted } @inlinable // allow specialization so that empty callbacks are removed func upsertAndFetchWithCallbacks<T>( _ db: Database, onConflict conflictTarget: [String], doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, selection: [any SQLSelectable], decode: (Row) throws -> T) throws -> (InsertionSuccess, T) { try willInsert(db) var success: (inserted: InsertionSuccess, returned: T)? try aroundInsert(db) { success = try upsertAndFetchWithoutCallbacks( db, onConflict: conflictTarget, doUpdate: assignments, selection: selection, decode: decode) return success!.inserted } guard let success else { try persistenceCallbackMisuse("aroundInsert") } didInsert(success.inserted) return success } }
mit
2724d82068fb56fc592c6d9f17cc45ff
38.908416
96
0.606525
4.511192
false
false
false
false
valitovaza/IntervalReminder
IntervalReminder/Interval/IntervalContainer.swift
1
1722
protocol ContainerListener: class { func itemAdded() func itemRemoved(at index: Int) func itemMoved(from fromIndex: Int, to toIndex: Int) } class IntervalContainer { var intervalsCount: Int { return intervals.count } private var intervals: [Interval] = [] private weak var listener: ContainerListener? init(_ listener: ContainerListener? = nil) { self.listener = listener } func add(_ interval: Interval) { intervals.insert(interval, at: 0) listener?.itemAdded() } func remove(at index: Int) { if isValidIndex(index) { removeItem(at: index) } } private func removeItem(at index: Int) { intervals.remove(at: index) listener?.itemRemoved(at: index) } private func isValidIndex(_ index: Int) -> Bool { return index >= 0 && intervals.count > index } func interval(at index: Int) -> Interval? { return isValidIndex(index) ? intervals[index] : nil } func move(from fromIndex: Int, to toIndex: Int) { if let fromInterval = interval(at: fromIndex), isValidMoveIndexes(from: fromIndex, to: toIndex) { moveItem(fromInterval, from: fromIndex, to: toIndex) } } private func isValidMoveIndexes(from fromIndex: Int, to toIndex: Int) -> Bool { return isValidIndex(toIndex) && fromIndex != toIndex } private func moveItem(_ interval: Interval, from fromIndex: Int, to toIndex: Int) { intervals.remove(at: fromIndex) intervals.insert(interval, at: toIndex) listener?.itemMoved(from: fromIndex, to: toIndex) } }
mit
e188e8aa48191fa7f8fd3c9dcaa5077c
32.764706
83
0.60511
4.381679
false
false
false
false
evermeer/EVWordPressAPI
EVWordPressAPI/EVWordPressAPI_Reader.swift
1
6633
// // EVWordPressAPI_Reader.swift // EVWordPressAPI // // Created by Edwin Vermeer on 9/21/15. // Copyright © 2015 evict. All rights reserved. // import Alamofire import AlamofireOauth2 import AlamofireJsonToObjects import EVReflection public extension EVWordPressAPI { // MARK: - Reader /** Get default reader menu. See: https://developer.wordpress.com/docs/api/1.1/get/read/menu/ :param: parameters an array of basicContextParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Posts object :return: No return value */ public func readMenu(_ parameters:[basicContextParameters]? = nil, completionHandler: @escaping (Menu?) -> Void) { genericCall("/read/menu", parameters:parameters, completionHandler: completionHandler) } /** Get details about a feed. See: https://developer.wordpress.com/docs/api/1.1/get/read/feed/%24feed_url_or_id/ :param: feedId The url or feed id where you want details of :param: parameters an array of basicContextParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Feed object :return: No return value */ public func feed(feedId:String, parameters:[basicContextParameters]? = nil, completionHandler: @escaping (Feed?) -> Void) { genericCall("/read/feed/\(feedId)", parameters:parameters, completionHandler: completionHandler) } /** Get a list of posts from the blogs a user follows. See: https://developer.wordpress.com/docs/api/1.1/get/read/following/ :param: parameters an array of followingParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Posts object :return: No return value */ public func following(_ parameters:[followingParameters]? = nil, completionHandler: @escaping (Posts?) -> Void) { genericCall("/read/following", parameters:parameters, completionHandler: completionHandler) } /** Get a list of posts from the blogs a user likes. See: https://developer.wordpress.com/docs/api/1.1/get/read/liked/ :param: parameters an array of basicContextParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Posts object :return: No return value */ public func liked(_ parameters:[followingParameters]? = nil, completionHandler: @escaping (Posts?) -> Void) { genericCall("/read/liked", parameters:parameters, completionHandler: completionHandler) } /** Get a list of posts from a tag. See: https://developer.wordpress.com/docs/api/1.1/get/read/tags/%24tag/posts/ :param: parameters an array of basicContextParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Posts object :return: No return value */ public func tagPosts(tag:String, parameters:[followingParameters]? = nil, completionHandler: @escaping (Posts?) -> Void) { genericCall("/read/tags/\(tag)/posts", parameters:parameters, completionHandler: completionHandler) } /** Get a list of tags subscribed to by the user. See: https://developer.wordpress.com/docs/api/1.1/get/read/tags/ :param: parameters an array of basicContextParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the TagsWrappper object :return: No return value */ public func readerTags(_ parameters:[basicContextParameters]? = nil, completionHandler: @escaping (TagsWrapper?) -> Void) { genericCall("/read/tags", parameters:parameters, completionHandler: completionHandler) } /** Get details about a specified tag. See: https://developer.wordpress.com/docs/api/1.1/get/read/tags/%24tag/ :param: tag The tag for what you want details :param: parameters an array of basicContextParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Tag object :return: No return value */ public func readerTag(tag:String, parameters:[basicContextParameters]? = nil, completionHandler: @escaping (Tag?) -> Void) { genericCall("/read/tags/\(tag)", parameters:parameters, completionHandler: completionHandler) } /** Get the subscribed status of the user to a given tag. See: https://developer.wordpress.com/docs/api/1.1/get/read/tags/%24tag/mine/ :param: tag The tag for what you want details :param: parameters an array of basicContextParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Tag object :return: No return value */ public func tagStatus(tag:String, parameters:[basicContextParameters]? = nil, completionHandler: @escaping (Status?) -> Void) { genericOauthCall(.TagStatus(pdict(parameters), tag), completionHandler: completionHandler) } /** Get a list of the feeds the user is following. See: https://developer.wordpress.com/docs/api/1.1/get/read/following/mine/ :param: parameters an array of basicContextParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Subscriptions object :return: No return value */ public func following(_ parameters:[followingParameters]? = nil, completionHandler: @escaping (Subscriptions?) -> Void) { genericOauthCall(.Following(pdict(parameters)), completionHandler: completionHandler) } /** Get a list of blog recommendations for the current user. See: https://developer.wordpress.com/docs/api/1.1/get/read/recommendations/mine/ :param: parameters an array of basicContextParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Subscriptions object :return: No return value */ public func recommendations(_ parameters:[recommendationsParameters]? = nil, completionHandler: @escaping (Blogs?) -> Void) { genericOauthCall(.Recommendations(pdict(parameters)), completionHandler: completionHandler) } }
bsd-3-clause
e6fcf95241bb953f180cea8e0c2cea4c
42.92053
131
0.719089
4.583276
false
false
false
false
VirgilSecurity/virgil-sdk-keys-x
Source/BaseClient/Networking/NetworkOperation.swift
2
3565
// // Copyright (C) 2015-2021 Virgil Security Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Lead Maintainer: Virgil Security Inc. <[email protected]> // import Foundation /// Network Operation open class NetworkOperation: GenericOperation<Response> { /// Task type public typealias Task = (NetworkOperation, @escaping (Response?, Error?) -> Void) -> Void /// Task to execute public let request: URLRequest /// Url Sesssion public let session: URLSession /// Task public private(set) var task: URLSessionTask? /// Initializer /// /// - Parameter task: task to execute public init(request: URLRequest, session: URLSession) { self.request = request self.session = session super.init() } /// Main function override open func main() { let task = self.session.dataTask(with: self.request) { [unowned self] data, response, error in defer { self.finish() } if let error = error { self.result = .failure(error) return } guard let response = response as? HTTPURLResponse else { self.result = .failure(ServiceConnectionError.wrongResponseType) return } Log.debug("NetworkOperation: response URL: \(response.url?.absoluteString ?? "")") Log.debug("NetworkOperation: response HTTP status code: \(response.statusCode)") Log.debug("NetworkOperation: response headers: \(response.allHeaderFields as AnyObject)") if let body = data, let str = String(data: body, encoding: .utf8) { Log.debug("NetworkOperation: response body: \(str)") } let result = Response(statusCode: response.statusCode, response: response, body: data) self.result = .success(result) } self.task = task task.resume() } /// Cancel override open func cancel() { self.task?.cancel() super.cancel() } }
bsd-3-clause
5896bef2a2f7f18c9f3ed485d862cf8d
33.61165
102
0.656662
4.77882
false
false
false
false
PerfectServers/Perfect-Authentication-Server
Sources/PerfectAuthServer/handlers/user/userList.swift
1
1066
// // userlist.swift // ServerMonitor // // Created by Jonathan Guthrie on 2017-04-30. // // import PerfectHTTP import PerfectLogger import PerfectLocalAuthentication extension Handlers { static func userList(data: [String:Any]) throws -> RequestHandler { return { request, response in let contextAccountID = request.session?.userid ?? "" let contextAuthenticated = !(request.session?.userid ?? "").isEmpty if !contextAuthenticated { response.redirect(path: "/login") } // Verify Admin Account.adminBounce(request, response) let users = Account.listUsers() var context: [String : Any] = [ "accountID": contextAccountID, "authenticated": contextAuthenticated, "userlist?":"true", "users": users ] if contextAuthenticated { for i in Handlers.extras(request) { context[i.0] = i.1 } } // add app config vars for i in Handlers.appExtras(request) { context[i.0] = i.1 } response.renderMustache(template: request.documentRoot + "/views/users.mustache", context: context) } } }
apache-2.0
e5a814e079dcbbf5b1ecaebc1f22303d
21.208333
102
0.675422
3.553333
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/Dining/SwiftUI/DiningViewModelSwiftUI.swift
1
3648
// // DiningViewModelSwiftUI.swift // PennMobile // // Created by CHOI Jongmin on 4/6/2020. // Copyright © 2020 PennLabs. All rights reserved. // import Foundation import SwiftUI class DiningViewModelSwiftUI: ObservableObject { static let instance = DiningViewModelSwiftUI() @Published var diningVenues: [VenueType: [DiningVenue]] = DiningAPI.instance.getSectionedVenues() @Published var diningMenus = DiningAPI.instance.getMenus() @Published var diningVenuesIsLoading = false @Published var alertType: NetworkingError? @Published var diningBalance = UserDefaults.standard.getDiningBalance() ?? DiningBalance(date: Date.dayOfMonthFormatter.string(from: Date()), diningDollars: "0.0", regularVisits: 0, guestVisits: 0, addOnVisits: 0) // MARK: - Venue Methods let ordering: [VenueType] = [.dining, .retail] func refreshVenues() async { let lastRequest = UserDefaults.standard.getLastDiningHoursRequest() // Sometimes when building the app, dining venue list is empty, but because it has refreshed within the day, it does not refresh again. Now, refreshes if the list of venues is completely empty if lastRequest == nil || !lastRequest!.isToday || diningVenues.isEmpty { self.diningVenuesIsLoading = true let result = await DiningAPI.instance.fetchDiningHours() switch result { case .success(let diningVenues): UserDefaults.standard.setLastDiningHoursRequest() var venuesDict = [VenueType: [DiningVenue]]() for type in VenueType.allCases { venuesDict[type] = diningVenues.filter({ $0.venueType == type }) } self.diningVenues = venuesDict case .failure(let error): self.alertType = error } self.diningVenuesIsLoading = false } } func refreshMenu(for id: Int, at date: Date = Date()) { let lastRequest = UserDefaults.standard.getLastMenuRequest(id: id) if Calendar.current.isDate(date, inSameDayAs: Date()) && (lastRequest == nil || !lastRequest!.isToday) { DiningAPI.instance.fetchDiningMenu(for: id) { result in switch result { case .success(let diningMenu): withAnimation { self.diningMenus[id] = diningMenu } case .failure(let error): self.alertType = error } } } else { DiningAPI.instance.fetchDiningMenu(for: id, at: date) { result in switch result { case .success(let diningMenu): withAnimation { self.diningMenus[id] = diningMenu } case .failure(let error): self.alertType = error } } } } func refreshBalance() async { guard let diningToken = KeychainAccessible.instance.getDiningToken() else { UserDefaults.standard.clearDiningBalance() self.diningBalance = DiningBalance(date: Date.dayOfMonthFormatter.string(from: Date()), diningDollars: "0.0", regularVisits: 0, guestVisits: 0, addOnVisits: 0) return } let result = await DiningAPI.instance.getDiningBalance(diningToken: diningToken) switch result { case .success(let balance): UserDefaults.standard.setdiningBalance(balance) self.diningBalance = balance case .failure: return } } }
mit
e618fcd368cecd8ca556f76339f4965d
39.977528
217
0.605155
4.824074
false
false
false
false
practicalswift/swift
test/Sema/availability_versions.swift
6
68161
// RUN: %target-typecheck-verify-swift -target x86_64-apple-macosx10.50 -disable-objc-attr-requires-foundation-module // RUN: not %target-swift-frontend -target x86_64-apple-macosx10.50 -disable-objc-attr-requires-foundation-module -typecheck %s 2>&1 | %FileCheck %s '--implicit-check-not=<unknown>:0' // Make sure we do not emit availability errors or warnings when -disable-availability-checking is passed // RUN: not %target-swift-frontend -target x86_64-apple-macosx10.50 -typecheck -disable-objc-attr-requires-foundation-module -disable-availability-checking %s 2>&1 | %FileCheck %s '--implicit-check-not=error:' '--implicit-check-not=warning:' // REQUIRES: OS=macosx func markUsed<T>(_ t: T) {} @available(OSX, introduced: 10.9) func globalFuncAvailableOn10_9() -> Int { return 9 } @available(OSX, introduced: 10.51) func globalFuncAvailableOn10_51() -> Int { return 10 } @available(OSX, introduced: 10.52) func globalFuncAvailableOn10_52() -> Int { return 11 } // Top level should reflect the minimum deployment target. let ignored1: Int = globalFuncAvailableOn10_9() let ignored2: Int = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let ignored3: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Functions without annotations should reflect the minimum deployment target. func functionWithoutAvailability() { // expected-note@-1 2{{add @available attribute to enclosing global function}} let _: Int = globalFuncAvailableOn10_9() let _: Int = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Functions with annotations should refine their bodies. @available(OSX, introduced: 10.51) func functionAvailableOn10_51() { let _: Int = globalFuncAvailableOn10_9() let _: Int = globalFuncAvailableOn10_51() // Nested functions should get their own refinement context. @available(OSX, introduced: 10.52) func innerFunctionAvailableOn10_52() { let _: Int = globalFuncAvailableOn10_9() let _: Int = globalFuncAvailableOn10_51() let _: Int = globalFuncAvailableOn10_52() } let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Don't allow script-mode globals to marked potentially unavailable. Their // initializers are eagerly executed. @available(OSX, introduced: 10.51) // expected-error {{global variable cannot be marked potentially unavailable with '@available' in script mode}} var potentiallyUnavailableGlobalInScriptMode: Int = globalFuncAvailableOn10_51() // Still allow other availability annotations on script-mode globals @available(OSX, deprecated: 10.51) var deprecatedGlobalInScriptMode: Int = 5 if #available(OSX 10.51, *) { let _: Int = globalFuncAvailableOn10_51() let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } if #available(OSX 10.51, *) { let _: Int = globalFuncAvailableOn10_51() let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } else { let _: Int = globalFuncAvailableOn10_9() let _: Int = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX, introduced: 10.51) @available(iOS, introduced: 8.0) func globalFuncAvailableOnOSX10_51AndiOS8_0() -> Int { return 10 } if #available(OSX 10.51, iOS 8.0, *) { let _: Int = globalFuncAvailableOnOSX10_51AndiOS8_0() } if #available(iOS 9.0, *) { let _: Int = globalFuncAvailableOnOSX10_51AndiOS8_0() // expected-error {{'globalFuncAvailableOnOSX10_51AndiOS8_0()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Multiple unavailable references in a single statement let ignored4: (Int, Int) = (globalFuncAvailableOn10_51(), globalFuncAvailableOn10_52()) // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}} expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}} // expected-note@-1 2{{add 'if #available' version check}} _ = globalFuncAvailableOn10_9() let ignored5 = globalFuncAvailableOn10_51 // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Overloaded global functions @available(OSX, introduced: 10.9) func overloadedFunction() {} @available(OSX, introduced: 10.51) func overloadedFunction(_ on1010: Int) {} overloadedFunction() overloadedFunction(0) // expected-error {{'overloadedFunction' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Unavailable methods class ClassWithUnavailableMethod { // expected-note@-1 {{add @available attribute to enclosing class}} @available(OSX, introduced: 10.9) func methAvailableOn10_9() {} @available(OSX, introduced: 10.51) func methAvailableOn10_51() {} @available(OSX, introduced: 10.51) class func classMethAvailableOn10_51() {} func someOtherMethod() { // expected-note@-1 {{add @available attribute to enclosing instance method}} methAvailableOn10_9() methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } } func callUnavailableMethods(_ o: ClassWithUnavailableMethod) { // expected-note@-1 2{{add @available attribute to enclosing global function}} let m10_9 = o.methAvailableOn10_9 m10_9() let m10_51 = o.methAvailableOn10_51 // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} m10_51() o.methAvailableOn10_9() o.methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } func callUnavailableMethodsViaIUO(_ o: ClassWithUnavailableMethod!) { // expected-note@-1 2{{add @available attribute to enclosing global function}} let m10_9 = o.methAvailableOn10_9 m10_9() let m10_51 = o.methAvailableOn10_51 // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} m10_51() o.methAvailableOn10_9() o.methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } func callUnavailableClassMethod() { // expected-note@-1 2{{add @available attribute to enclosing global function}} ClassWithUnavailableMethod.classMethAvailableOn10_51() // expected-error {{'classMethAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let m10_51 = ClassWithUnavailableMethod.classMethAvailableOn10_51 // expected-error {{'classMethAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} m10_51() } class SubClassWithUnavailableMethod : ClassWithUnavailableMethod { // expected-note@-1 {{add @available attribute to enclosing class}} func someMethod() { // expected-note@-1 {{add @available attribute to enclosing instance method}} methAvailableOn10_9() methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } } class SubClassOverridingUnavailableMethod : ClassWithUnavailableMethod { // expected-note@-1 2{{add @available attribute to enclosing class}} override func methAvailableOn10_51() { // expected-note@-1 2{{add @available attribute to enclosing instance method}} methAvailableOn10_9() super.methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let m10_9 = super.methAvailableOn10_9 m10_9() let m10_51 = super.methAvailableOn10_51 // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} m10_51() } func someMethod() { methAvailableOn10_9() // Calling our override should be fine methAvailableOn10_51() } } class ClassWithUnavailableOverloadedMethod { @available(OSX, introduced: 10.9) func overloadedMethod() {} @available(OSX, introduced: 10.51) func overloadedMethod(_ on1010: Int) {} } func callUnavailableOverloadedMethod(_ o: ClassWithUnavailableOverloadedMethod) { // expected-note@-1 {{add @available attribute to enclosing global function}} o.overloadedMethod() o.overloadedMethod(0) // expected-error {{'overloadedMethod' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Initializers class ClassWithUnavailableInitializer { // expected-note@-1 {{add @available attribute to enclosing class}} @available(OSX, introduced: 10.9) required init() { } @available(OSX, introduced: 10.51) required init(_ val: Int) { } convenience init(s: String) { // expected-note@-1 {{add @available attribute to enclosing initializer}} self.init(5) // expected-error {{'init(_:)' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX, introduced: 10.51) convenience init(onlyOn1010: String) { self.init(5) } } func callUnavailableInitializer() { // expected-note@-1 2{{add @available attribute to enclosing global function}} _ = ClassWithUnavailableInitializer() _ = ClassWithUnavailableInitializer(5) // expected-error {{'init(_:)' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let i = ClassWithUnavailableInitializer.self _ = i.init() _ = i.init(5) // expected-error {{'init(_:)' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } class SuperWithWithUnavailableInitializer { @available(OSX, introduced: 10.9) init() { } @available(OSX, introduced: 10.51) init(_ val: Int) { } } class SubOfClassWithUnavailableInitializer : SuperWithWithUnavailableInitializer { // expected-note@-1 {{add @available attribute to enclosing class}} override init(_ val: Int) { // expected-note@-1 {{add @available attribute to enclosing initializer}} super.init(5) // expected-error {{'init(_:)' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } override init() { super.init() } @available(OSX, introduced: 10.51) init(on1010: Int) { super.init(22) } } // Properties class ClassWithUnavailableProperties { // expected-note@-1 4{{add @available attribute to enclosing class}} @available(OSX, introduced: 10.9) // expected-error {{stored properties cannot be marked potentially unavailable with '@available'}} var nonLazyAvailableOn10_9Stored: Int = 9 @available(OSX, introduced: 10.51) // expected-error {{stored properties cannot be marked potentially unavailable with '@available'}} var nonLazyAvailableOn10_51Stored : Int = 10 @available(OSX, introduced: 10.51) // expected-error {{stored properties cannot be marked potentially unavailable with '@available'}} let nonLazyLetAvailableOn10_51Stored : Int = 10 // Make sure that we don't emit a Fix-It to mark a stored property as potentially unavailable. // We don't support potentially unavailable stored properties yet. var storedPropertyOfUnavailableType: ClassAvailableOn10_51? = nil // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} @available(OSX, introduced: 10.9) lazy var availableOn10_9Stored: Int = 9 @available(OSX, introduced: 10.51) lazy var availableOn10_51Stored : Int = 10 @available(OSX, introduced: 10.9) var availableOn10_9Computed: Int { get { let _: Int = availableOn10_51Stored // expected-error {{'availableOn10_51Stored' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { let _: Int = availableOn10_51Stored } return availableOn10_9Stored } set(newVal) { availableOn10_9Stored = newVal } } @available(OSX, introduced: 10.51) var availableOn10_51Computed: Int { get { return availableOn10_51Stored } set(newVal) { availableOn10_51Stored = newVal } } var propWithSetterOnlyAvailableOn10_51 : Int { // expected-note@-1 {{add @available attribute to enclosing property}} get { _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} return 0 } @available(OSX, introduced: 10.51) set(newVal) { _ = globalFuncAvailableOn10_51() } } var propWithGetterOnlyAvailableOn10_51 : Int { // expected-note@-1 {{add @available attribute to enclosing property}} @available(OSX, introduced: 10.51) get { _ = globalFuncAvailableOn10_51() return 0 } set(newVal) { _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } } var propWithGetterAndSetterOnlyAvailableOn10_51 : Int { @available(OSX, introduced: 10.51) get { return 0 } @available(OSX, introduced: 10.51) set(newVal) { } } var propWithSetterOnlyAvailableOn10_51ForNestedMemberRef : ClassWithUnavailableProperties { get { return ClassWithUnavailableProperties() } @available(OSX, introduced: 10.51) set(newVal) { } } var propWithGetterOnlyAvailableOn10_51ForNestedMemberRef : ClassWithUnavailableProperties { @available(OSX, introduced: 10.51) get { return ClassWithUnavailableProperties() } set(newVal) { } } } @available(OSX, introduced: 10.51) class ClassWithReferencesInInitializers { var propWithInitializer10_51: Int = globalFuncAvailableOn10_51() var propWithInitializer10_52: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}} lazy var lazyPropWithInitializer10_51: Int = globalFuncAvailableOn10_51() lazy var lazyPropWithInitializer10_52: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add @available attribute to enclosing property}} } func accessUnavailableProperties(_ o: ClassWithUnavailableProperties) { // expected-note@-1 17{{add @available attribute to enclosing global function}} // Stored properties let _: Int = o.availableOn10_9Stored let _: Int = o.availableOn10_51Stored // expected-error {{'availableOn10_51Stored' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} o.availableOn10_9Stored = 9 o.availableOn10_51Stored = 10 // expected-error {{'availableOn10_51Stored' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Computed Properties let _: Int = o.availableOn10_9Computed let _: Int = o.availableOn10_51Computed // expected-error {{'availableOn10_51Computed' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} o.availableOn10_9Computed = 9 o.availableOn10_51Computed = 10 // expected-error {{'availableOn10_51Computed' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Getter allowed on 10.9 but setter is not let _: Int = o.propWithSetterOnlyAvailableOn10_51 o.propWithSetterOnlyAvailableOn10_51 = 5 // expected-error {{setter for 'propWithSetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { // Setter is allowed on 10.51 and greater o.propWithSetterOnlyAvailableOn10_51 = 5 } // Setter allowed on 10.9 but getter is not o.propWithGetterOnlyAvailableOn10_51 = 5 let _: Int = o.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { // Getter is allowed on 10.51 and greater let _: Int = o.propWithGetterOnlyAvailableOn10_51 } // Tests for nested member refs // Both getters are potentially unavailable. let _: Int = o.propWithGetterOnlyAvailableOn10_51ForNestedMemberRef.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51ForNestedMemberRef' is only available on OS X 10.51 or newer}} expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 2{{add 'if #available' version check}} // Nested getter is potentially unavailable, outer getter is available let _: Int = o.propWithGetterOnlyAvailableOn10_51ForNestedMemberRef.propWithSetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51ForNestedMemberRef' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Nested getter is available, outer getter is potentially unavailable let _:Int = o.propWithSetterOnlyAvailableOn10_51ForNestedMemberRef.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Both getters are always available. let _: Int = o.propWithSetterOnlyAvailableOn10_51ForNestedMemberRef.propWithSetterOnlyAvailableOn10_51 // Nesting in source of assignment var v: Int v = o.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} v = (o.propWithGetterOnlyAvailableOn10_51) // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Inout requires access to both getter and setter func takesInout(_ i : inout Int) { } takesInout(&o.propWithGetterOnlyAvailableOn10_51) // expected-error {{cannot pass as inout because getter for 'propWithGetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} takesInout(&o.propWithSetterOnlyAvailableOn10_51) // expected-error {{cannot pass as inout because setter for 'propWithSetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} takesInout(&o.propWithGetterAndSetterOnlyAvailableOn10_51) // expected-error {{cannot pass as inout because getter for 'propWithGetterAndSetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}} expected-error {{cannot pass as inout because setter for 'propWithGetterAndSetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 2{{add 'if #available' version check}} takesInout(&o.availableOn10_9Computed) takesInout(&o.propWithGetterOnlyAvailableOn10_51ForNestedMemberRef.availableOn10_9Computed) // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51ForNestedMemberRef' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // _silgen_name @_silgen_name("SomeName") @available(OSX, introduced: 10.51) func funcWith_silgen_nameAvailableOn10_51(_ p: ClassAvailableOn10_51?) -> ClassAvailableOn10_51 // Enums @available(OSX, introduced: 10.51) enum EnumIntroducedOn10_51 { case Element } @available(OSX, introduced: 10.52) enum EnumIntroducedOn10_52 { case Element } @available(OSX, introduced: 10.51) enum CompassPoint { case North case South case East @available(OSX, introduced: 10.52) case West case WithAvailableByEnumPayload(p : EnumIntroducedOn10_51) @available(OSX, introduced: 10.52) case WithAvailableByEnumElementPayload(p : EnumIntroducedOn10_52) @available(OSX, introduced: 10.52) case WithAvailableByEnumElementPayload1(p : EnumIntroducedOn10_52), WithAvailableByEnumElementPayload2(p : EnumIntroducedOn10_52) case WithUnavailablePayload(p : EnumIntroducedOn10_52) // expected-error {{'EnumIntroducedOn10_52' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add @available attribute to enclosing case}} case WithUnavailablePayload1(p : EnumIntroducedOn10_52), WithUnavailablePayload2(p : EnumIntroducedOn10_52) // expected-error 2{{'EnumIntroducedOn10_52' is only available on OS X 10.52 or newer}} // expected-note@-1 2{{add @available attribute to enclosing case}} } @available(OSX, introduced: 10.52) func functionTakingEnumIntroducedOn10_52(_ e: EnumIntroducedOn10_52) { } func useEnums() { // expected-note@-1 3{{add @available attribute to enclosing global function}} let _: CompassPoint = .North // expected-error {{'CompassPoint' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { let _: CompassPoint = .North let _: CompassPoint = .West // expected-error {{'West' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } if #available(OSX 10.52, *) { let _: CompassPoint = .West } // Pattern matching on an enum element does not require it to be definitely available if #available(OSX 10.51, *) { let point: CompassPoint = .North switch (point) { case .North, .South, .East: markUsed("NSE") case .West: // We do not expect an error here markUsed("W") case .WithUnavailablePayload(_): markUsed("WithUnavailablePayload") case .WithUnavailablePayload1(_): markUsed("WithUnavailablePayload1") case .WithUnavailablePayload2(_): markUsed("WithUnavailablePayload2") case .WithAvailableByEnumPayload(_): markUsed("WithAvailableByEnumPayload") case .WithAvailableByEnumElementPayload1(_): markUsed("WithAvailableByEnumElementPayload1") case .WithAvailableByEnumElementPayload2(_): markUsed("WithAvailableByEnumElementPayload2") case .WithAvailableByEnumElementPayload(let p): markUsed("WithAvailableByEnumElementPayload") // For the moment, we do not incorporate enum element availability into // TRC construction. Perhaps we should? functionTakingEnumIntroducedOn10_52(p) // expected-error {{'functionTakingEnumIntroducedOn10_52' is only available on OS X 10.52 or newer}} // expected-note@-2 {{add 'if #available' version check}} } } } // Classes @available(OSX, introduced: 10.9) class ClassAvailableOn10_9 { func someMethod() {} class func someClassMethod() {} var someProp : Int = 22 } @available(OSX, introduced: 10.51) class ClassAvailableOn10_51 { // expected-note {{enclosing scope here}} func someMethod() {} class func someClassMethod() { let _ = ClassAvailableOn10_51() } var someProp : Int = 22 @available(OSX, introduced: 10.9) // expected-error {{declaration cannot be more available than enclosing scope}} func someMethodAvailableOn10_9() { } @available(OSX, introduced: 10.52) var propWithGetter: Int { // expected-note{{enclosing scope here}} @available(OSX, introduced: 10.51) // expected-error {{declaration cannot be more available than enclosing scope}} get { return 0 } } } func classAvailability() { // expected-note@-1 3{{add @available attribute to enclosing global function}} ClassAvailableOn10_9.someClassMethod() ClassAvailableOn10_51.someClassMethod() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} _ = ClassAvailableOn10_9.self _ = ClassAvailableOn10_51.self // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let o10_9 = ClassAvailableOn10_9() let o10_51 = ClassAvailableOn10_51() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} o10_9.someMethod() o10_51.someMethod() let _ = o10_9.someProp let _ = o10_51.someProp } func castingUnavailableClass(_ o : AnyObject) { // expected-note@-1 3{{add @available attribute to enclosing global function}} let _ = o as! ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = o as? ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = o is ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } protocol Creatable { init() } @available(OSX, introduced: 10.51) class ClassAvailableOn10_51_Creatable : Creatable { required init() {} } func create<T : Creatable>() -> T { return T() } class ClassWithGenericTypeParameter<T> { } class ClassWithTwoGenericTypeParameter<T, S> { } func classViaTypeParameter() { // expected-note@-1 9{{add @available attribute to enclosing global function}} let _ : ClassAvailableOn10_51_Creatable = // expected-error {{'ClassAvailableOn10_51_Creatable' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} create() let _ = create() as ClassAvailableOn10_51_Creatable // expected-error {{'ClassAvailableOn10_51_Creatable' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = [ClassAvailableOn10_51]() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _: ClassWithGenericTypeParameter<ClassAvailableOn10_51> = ClassWithGenericTypeParameter() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _: ClassWithTwoGenericTypeParameter<ClassAvailableOn10_51, String> = ClassWithTwoGenericTypeParameter() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _: ClassWithTwoGenericTypeParameter<String, ClassAvailableOn10_51> = ClassWithTwoGenericTypeParameter() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _: ClassWithTwoGenericTypeParameter<ClassAvailableOn10_51, ClassAvailableOn10_51> = ClassWithTwoGenericTypeParameter() // expected-error 2{{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 2{{add 'if #available' version check}} let _: ClassAvailableOn10_51? = nil // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Unavailable class used in declarations class ClassWithDeclarationsOfUnavailableClasses { // expected-note@-1 5{{add @available attribute to enclosing class}} @available(OSX, introduced: 10.51) init() { unavailablePropertyOfUnavailableType = ClassAvailableOn10_51() unavailablePropertyOfUnavailableType = ClassAvailableOn10_51() } var propertyOfUnavailableType: ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} @available(OSX, introduced: 10.51) lazy var unavailablePropertyOfUnavailableType: ClassAvailableOn10_51 = ClassAvailableOn10_51() @available(OSX, introduced: 10.51) lazy var unavailablePropertyOfOptionalUnavailableType: ClassAvailableOn10_51? = nil @available(OSX, introduced: 10.51) lazy var unavailablePropertyOfUnavailableTypeWithInitializer: ClassAvailableOn10_51 = ClassAvailableOn10_51() @available(OSX, introduced: 10.51) static var unavailableStaticPropertyOfUnavailableType: ClassAvailableOn10_51 = ClassAvailableOn10_51() @available(OSX, introduced: 10.51) static var unavailableStaticPropertyOfOptionalUnavailableType: ClassAvailableOn10_51? func methodWithUnavailableParameterType(_ o : ClassAvailableOn10_51) { // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add @available attribute to enclosing instance method}} } @available(OSX, introduced: 10.51) func unavailableMethodWithUnavailableParameterType(_ o : ClassAvailableOn10_51) { } func methodWithUnavailableReturnType() -> ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 2{{add @available attribute to enclosing instance method}} return ClassAvailableOn10_51() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX, introduced: 10.51) func unavailableMethodWithUnavailableReturnType() -> ClassAvailableOn10_51 { return ClassAvailableOn10_51() } func methodWithUnavailableLocalDeclaration() { // expected-note@-1 {{add @available attribute to enclosing instance method}} let _ : ClassAvailableOn10_51 = methodWithUnavailableReturnType() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX, introduced: 10.51) func unavailableMethodWithUnavailableLocalDeclaration() { let _ : ClassAvailableOn10_51 = methodWithUnavailableReturnType() } } func referToUnavailableStaticProperty() { // expected-note@-1 {{add @available attribute to enclosing global function}} let _ = ClassWithDeclarationsOfUnavailableClasses.unavailableStaticPropertyOfUnavailableType // expected-error {{'unavailableStaticPropertyOfUnavailableType' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } class ClassExtendingUnavailableClass : ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add @available attribute to enclosing class}} } @available(OSX, introduced: 10.51) class UnavailableClassExtendingUnavailableClass : ClassAvailableOn10_51 { } // Method availability is contravariant class SuperWithAlwaysAvailableMembers { func shouldAlwaysBeAvailableMethod() { // expected-note {{overridden declaration is here}} } var shouldAlwaysBeAvailableProperty: Int { // expected-note {{overridden declaration is here}} get { return 9 } set(newVal) {} } var setterShouldAlwaysBeAvailableProperty: Int { get { return 9 } set(newVal) {} // expected-note {{overridden declaration is here}} } var getterShouldAlwaysBeAvailableProperty: Int { get { return 9 } // expected-note {{overridden declaration is here}} set(newVal) {} } } class SubWithLimitedMemberAvailability : SuperWithAlwaysAvailableMembers { @available(OSX, introduced: 10.51) override func shouldAlwaysBeAvailableMethod() { // expected-error {{overriding 'shouldAlwaysBeAvailableMethod' must be as available as declaration it overrides}} } @available(OSX, introduced: 10.51) override var shouldAlwaysBeAvailableProperty: Int { // expected-error {{overriding 'shouldAlwaysBeAvailableProperty' must be as available as declaration it overrides}} get { return 10 } set(newVal) {} } override var setterShouldAlwaysBeAvailableProperty: Int { get { return 9 } @available(OSX, introduced: 10.51) set(newVal) {} // expected-error {{overriding setter for 'setterShouldAlwaysBeAvailableProperty' must be as available as declaration it overrides}} // This is a terrible diagnostic. rdar://problem/20427938 } override var getterShouldAlwaysBeAvailableProperty: Int { @available(OSX, introduced: 10.51) get { return 9 } // expected-error {{overriding getter for 'getterShouldAlwaysBeAvailableProperty' must be as available as declaration it overrides}} set(newVal) {} } } class SuperWithLimitedMemberAvailability { @available(OSX, introduced: 10.51) func someMethod() { } @available(OSX, introduced: 10.51) var someProperty: Int { get { return 10 } set(newVal) {} } } class SubWithLargerMemberAvailability : SuperWithLimitedMemberAvailability { // expected-note@-1 2{{add @available attribute to enclosing class}} @available(OSX, introduced: 10.9) override func someMethod() { super.someMethod() // expected-error {{'someMethod()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { super.someMethod() } } @available(OSX, introduced: 10.9) override var someProperty: Int { get { let _ = super.someProperty // expected-error {{'someProperty' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { let _ = super.someProperty } return 9 } set(newVal) {} } } // Inheritance and availability @available(OSX, introduced: 10.51) protocol ProtocolAvailableOn10_9 { } @available(OSX, introduced: 10.51) protocol ProtocolAvailableOn10_51 { } @available(OSX, introduced: 10.9) protocol ProtocolAvailableOn10_9InheritingFromProtocolAvailableOn10_51 : ProtocolAvailableOn10_51 { } @available(OSX, introduced: 10.51) protocol ProtocolAvailableOn10_51InheritingFromProtocolAvailableOn10_9 : ProtocolAvailableOn10_9 { } @available(OSX, introduced: 10.9) class SubclassAvailableOn10_9OfClassAvailableOn10_51 : ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} } // We allow nominal types to conform to protocols that are less available than the types themselves. @available(OSX, introduced: 10.9) class ClassAvailableOn10_9AdoptingProtocolAvailableOn10_51 : ProtocolAvailableOn10_51 { } func castToUnavailableProtocol() { // expected-note@-1 2{{add @available attribute to enclosing global function}} let o: ClassAvailableOn10_9AdoptingProtocolAvailableOn10_51 = ClassAvailableOn10_9AdoptingProtocolAvailableOn10_51() let _: ProtocolAvailableOn10_51 = o // expected-error {{'ProtocolAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = o as ProtocolAvailableOn10_51 // expected-error {{'ProtocolAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX, introduced: 10.9) class SubclassAvailableOn10_9OfClassAvailableOn10_51AlsoAdoptingProtocolAvailableOn10_51 : ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} } class SomeGenericClass<T> { } @available(OSX, introduced: 10.9) class SubclassAvailableOn10_9OfSomeGenericClassOfProtocolAvailableOn10_51 : SomeGenericClass<ProtocolAvailableOn10_51> { // expected-error {{'ProtocolAvailableOn10_51' is only available on OS X 10.51 or newer}} } func GenericWhereClause<T>(_ t: T) where T: ProtocolAvailableOn10_51 { // expected-error * {{'ProtocolAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 * {{add @available attribute to enclosing global function}} } func GenericSignature<T : ProtocolAvailableOn10_51>(_ t: T) { // expected-error * {{'ProtocolAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 * {{add @available attribute to enclosing global function}} } // Extensions extension ClassAvailableOn10_51 { } // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add @available attribute to enclosing extension}} @available(OSX, introduced: 10.51) extension ClassAvailableOn10_51 { func m() { // expected-note@-1 {{add @available attribute to enclosing instance method}} let _ = globalFuncAvailableOn10_51() let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } } class ClassToExtend { } @available(OSX, introduced: 10.51) extension ClassToExtend { func extensionMethod() { } @available(OSX, introduced: 10.52) func extensionMethod10_52() { } class ExtensionClass { } // We rely on not allowing nesting of extensions, so test to make sure // this emits an error. // CHECK:error: declaration is only valid at file scope extension ClassToExtend { } // expected-error {{declaration is only valid at file scope}} } // We allow protocol extensions for protocols that are less available than the // conforming class. extension ClassToExtend : ProtocolAvailableOn10_51 { } @available(OSX, introduced: 10.51) extension ClassToExtend { // expected-note {{enclosing scope here}} @available(OSX, introduced: 10.9) // expected-error {{declaration cannot be more available than enclosing scope}} func extensionMethod10_9() { } } func useUnavailableExtension() { // expected-note@-1 3{{add @available attribute to enclosing global function}} let o = ClassToExtend() o.extensionMethod() // expected-error {{'extensionMethod()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = ClassToExtend.ExtensionClass() // expected-error {{'ExtensionClass' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} o.extensionMethod10_52() // expected-error {{'extensionMethod10_52()' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Availability of synthesized designated initializers. @available(OSX, introduced: 10.51) class WidelyAvailableBase { init() {} @available(OSX, introduced: 10.52) init(thing: ()) {} } @available(OSX, introduced: 10.53) class EsotericSmallBatchHipsterThing : WidelyAvailableBase {} @available(OSX, introduced: 10.53) class NestedClassTest { class InnerClass : WidelyAvailableBase {} } // Useless #available(...) checks func functionWithDefaultAvailabilityAndUselessCheck(_ p: Bool) { // Default availability reflects minimum deployment: 10.9 and up if #available(OSX 10.9, *) { // no-warning let _ = globalFuncAvailableOn10_9() } if #available(OSX 10.51, *) { // expected-note {{enclosing scope here}} let _ = globalFuncAvailableOn10_51() if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}} let _ = globalFuncAvailableOn10_51() } } if #available(OSX 10.9, *) { // expected-note {{enclosing scope here}} } else { // Make sure we generate a warning about an unnecessary check even if the else branch of if is dead. if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}} } } // This 'if' is strictly to limit the scope of the guard fallthrough if p { guard #available(OSX 10.9, *) else { // expected-note {{enclosing scope here}} // Make sure we generate a warning about an unnecessary check even if the else branch of guard is dead. if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}} } } } // We don't want * generate a warn about useless checks; the check may be required on // another platform if #available(iOS 8.0, *) { } if #available(OSX 10.51, *) { // Similarly do not want '*' to generate a warning in a refined TRC. if #available(iOS 8.0, *) { } } } @available(OSX, unavailable) func explicitlyUnavailable() { } // expected-note 2{{'explicitlyUnavailable()' has been explicitly marked unavailable here}} func functionWithUnavailableInDeadBranch() { if #available(iOS 8.0, *) { } else { // This branch is dead on OSX, so we shouldn't a warning about use of potentially unavailable APIs in it. _ = globalFuncAvailableOn10_51() // no-warning @available(OSX 10.51, *) func localFuncAvailableOn10_51() { _ = globalFuncAvailableOn10_52() // no-warning } localFuncAvailableOn10_51() // no-warning explicitlyUnavailable() // expected-error {{'explicitlyUnavailable()' is unavailable}} } guard #available(iOS 8.0, *) else { _ = globalFuncAvailableOn10_51() // no-warning explicitlyUnavailable() // expected-error {{'explicitlyUnavailable()' is unavailable}} } } @available(OSX, introduced: 10.51) func functionWithSpecifiedAvailabilityAndUselessCheck() { // expected-note 2{{enclosing scope here}} if #available(OSX 10.9, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}} let _ = globalFuncAvailableOn10_9() } if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}} let _ = globalFuncAvailableOn10_51() } } // #available(...) outside if statement guards func injectToOptional<T>(_ v: T) -> T? { return v } if let _ = injectToOptional(5), #available(OSX 10.52, *) {} // ok // Refining context inside guard if #available(OSX 10.51, *), let _ = injectToOptional(globalFuncAvailableOn10_51()), let _ = injectToOptional(globalFuncAvailableOn10_52()) { // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = globalFuncAvailableOn10_51() let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } if let _ = injectToOptional(5), #available(OSX 10.51, *), let _ = injectToOptional(globalFuncAvailableOn10_51()), let _ = injectToOptional(globalFuncAvailableOn10_52()) { // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = globalFuncAvailableOn10_51() let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } if let _ = injectToOptional(globalFuncAvailableOn10_51()), #available(OSX 10.51, *), // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = injectToOptional(globalFuncAvailableOn10_52()) { // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } if let _ = injectToOptional(5), #available(OSX 10.51, *), // expected-note {{enclosing scope here}} let _ = injectToOptional(6), #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}} } // Tests for the guard control construct. func useGuardAvailable() { // expected-note@-1 3{{add @available attribute to enclosing global function}} // Guard fallthrough should refine context guard #available(OSX 10.51, *) else { // expected-note {{enclosing scope here}} let _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} return } let _ = globalFuncAvailableOn10_51() let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}} } if globalFuncAvailableOn10_51() > 0 { guard #available(OSX 10.52, *), let x = injectToOptional(globalFuncAvailableOn10_52()) else { return } _ = x } let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } func twoGuardsInSameBlock(_ p: Int) { // expected-note@-1 {{add @available attribute to enclosing global function}} if (p > 0) { guard #available(OSX 10.51, *) else { return } let _ = globalFuncAvailableOn10_51() guard #available(OSX 10.52, *) else { return } let _ = globalFuncAvailableOn10_52() } let _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Refining while loops while globalFuncAvailableOn10_51() > 10 { } // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} while #available(OSX 10.51, *), // expected-note {{enclosing scope here}} globalFuncAvailableOn10_51() > 10 { let _ = globalFuncAvailableOn10_51() let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} while globalFuncAvailableOn10_51() > 11, let _ = injectToOptional(5), #available(OSX 10.52, *) { let _ = globalFuncAvailableOn10_52(); } while #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}} } } // Tests for Fix-It replacement text // The whitespace in the replacement text is particularly important here -- it reflects the level // of indentation for the added if #available() or @available attribute. Note that, for the moment, we hard // code *added* indentation in Fix-Its as 4 spaces (that is, when indenting in a Fix-It, we // take whatever indentation was there before and add 4 spaces to it). functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{1-27=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n} else {\n // Fallback on earlier versions\n}}} let declForFixitAtTopLevel: ClassAvailableOn10_51? = nil // expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{1-57=if #available(OSX 10.51, *) {\n let declForFixitAtTopLevel: ClassAvailableOn10_51? = nil\n} else {\n // Fallback on earlier versions\n}}} func fixitForReferenceInGlobalFunction() { // expected-note@-1 {{add @available attribute to enclosing global function}} {{1-1=@available(OSX 10.51, *)\n}} functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{3-29=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } public func fixitForReferenceInGlobalFunctionWithDeclModifier() { // expected-note@-1 {{add @available attribute to enclosing global function}} {{1-1=@available(OSX 10.51, *)\n}} functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{3-29=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } func fixitForReferenceInGlobalFunctionWithAttribute() -> Never { // expected-note@-1 {{add @available attribute to enclosing global function}} {{1-1=@available(OSX 10.51, *)\n}} functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{3-29=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } func takesAutoclosure(_ c : @autoclosure () -> ()) { } class ClassForFixit { // expected-note@-1 12{{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}} func fixitForReferenceInMethod() { // expected-note@-1 {{add @available attribute to enclosing instance method}} {{3-3=@available(OSX 10.51, *)\n }} functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{5-31=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } func fixitForReferenceNestedInMethod() { // expected-note@-1 3{{add @available attribute to enclosing instance method}} {{3-3=@available(OSX 10.51, *)\n }} func inner() { functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{7-33=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } let _: () -> () = { () in functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{7-33=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } takesAutoclosure(functionAvailableOn10_51()) // expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{5-49=if #available(OSX 10.51, *) {\n takesAutoclosure(functionAvailableOn10_51())\n } else {\n // Fallback on earlier versions\n }}} } var fixitForReferenceInPropertyAccessor: Int { // expected-note@-1 {{add @available attribute to enclosing property}} {{3-3=@available(OSX 10.51, *)\n }} get { functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{7-33=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} return 5 } } var fixitForReferenceInPropertyType: ClassAvailableOn10_51? = nil // expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} lazy var fixitForReferenceInLazyPropertyType: ClassAvailableOn10_51? = nil // expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-2 {{add @available attribute to enclosing property}} {{3-3=@available(OSX 10.51, *)\n }} private lazy var fixitForReferenceInPrivateLazyPropertyType: ClassAvailableOn10_51? = nil // expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-2 {{add @available attribute to enclosing property}} {{3-3=@available(OSX 10.51, *)\n }} lazy private var fixitForReferenceInLazyPrivatePropertyType: ClassAvailableOn10_51? = nil // expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-2 {{add @available attribute to enclosing property}} {{3-3=@available(OSX 10.51, *)\n }} static var fixitForReferenceInStaticPropertyType: ClassAvailableOn10_51? = nil // expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-2 {{add @available attribute to enclosing static property}} {{3-3=@available(OSX 10.51, *)\n }} var fixitForReferenceInPropertyTypeMultiple: ClassAvailableOn10_51? = nil, other: Int = 7 // expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} func fixitForRefInGuardOfIf() { // expected-note@-1 {{add @available attribute to enclosing instance method}} {{3-3=@available(OSX 10.51, *)\n }} if (globalFuncAvailableOn10_51() > 1066) { let _ = 5 let _ = 6 } // expected-error@-4 {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-5 {{add 'if #available' version check}} {{5-6=if #available(OSX 10.51, *) {\n if (globalFuncAvailableOn10_51() > 1066) {\n let _ = 5\n let _ = 6\n }\n } else {\n // Fallback on earlier versions\n }}} } } extension ClassToExtend { // expected-note@-1 {{add @available attribute to enclosing extension}} func fixitForReferenceInExtensionMethod() { // expected-note@-1 {{add @available attribute to enclosing instance method}} {{3-3=@available(OSX 10.51, *)\n }} functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{5-31=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } } enum EnumForFixit { // expected-note@-1 2{{add @available attribute to enclosing enum}} {{1-1=@available(OSX 10.51, *)\n}} case CaseWithUnavailablePayload(p: ClassAvailableOn10_51) // expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-2 {{add @available attribute to enclosing case}} {{3-3=@available(OSX 10.51, *)\n }} case CaseWithUnavailablePayload2(p: ClassAvailableOn10_51), WithoutPayload // expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-2 {{add @available attribute to enclosing case}} {{3-3=@available(OSX 10.51, *)\n }} } @objc class Y { var z = 0 } @objc class X { @objc var y = Y() } func testForFixitWithNestedMemberRefExpr() { // expected-note@-1 2{{add @available attribute to enclosing global function}} {{1-1=@available(OSX 10.52, *)\n}} let x = X() x.y.z = globalFuncAvailableOn10_52() // expected-error@-1 {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{3-39=if #available(OSX 10.52, *) {\n x.y.z = globalFuncAvailableOn10_52()\n } else {\n // Fallback on earlier versions\n }}} // Access via dynamic member reference let anyX: AnyObject = x anyX.y?.z = globalFuncAvailableOn10_52() // expected-error@-1 {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{3-43=if #available(OSX 10.52, *) {\n anyX.y?.z = globalFuncAvailableOn10_52()\n } else {\n // Fallback on earlier versions\n }}} } // Protocol Conformances protocol ProtocolWithRequirementMentioningUnavailable { // expected-note@-1 2{{add @available attribute to enclosing protocol}} func hasUnavailableParameter(_ p: ClassAvailableOn10_51) // expected-error * {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 * {{add @available attribute to enclosing instance method}} func hasUnavailableReturn() -> ClassAvailableOn10_51 // expected-error * {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 * {{add @available attribute to enclosing instance method}} @available(OSX 10.51, *) func hasUnavailableWithAnnotation(_ p: ClassAvailableOn10_51) -> ClassAvailableOn10_51 } protocol HasMethodF { associatedtype T func f(_ p: T) // expected-note 5{{protocol requirement here}} } class TriesToConformWithFunctionIntroducedOn10_51 : HasMethodF { @available(OSX, introduced: 10.51) func f(_ p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available on OS X 10.50.0 and newer}} } class ConformsWithFunctionIntroducedOnMinimumDeploymentTarget : HasMethodF { // Even though this function is less available than its requirement, // it is available on a deployment targets, so the conformance is safe. @available(OSX, introduced: 10.9) func f(_ p: Int) { } } class SuperHasMethodF { @available(OSX, introduced: 10.51) func f(_ p: Int) { } // expected-note {{'f' declared here}} } class TriesToConformWithUnavailableFunctionInSuperClass : SuperHasMethodF, HasMethodF { // expected-error {{protocol 'HasMethodF' requires 'f' to be available on OS X 10.50.0 and newer}} // The conformance here is generating an error on f in the super class. } @available(OSX, introduced: 10.51) class ConformsWithUnavailableFunctionInSuperClass : SuperHasMethodF, HasMethodF { // Limiting this class to only be available on 10.51 and newer means that // the witness in SuperHasMethodF is safe for the requirement on HasMethodF. // in order for this class to be referenced we must be running on 10.51 or // greater. } class ConformsByOverridingFunctionInSuperClass : SuperHasMethodF, HasMethodF { // Now the witness is this f() (which is always available) and not the f() // from the super class, so conformance is safe. override func f(_ p: Int) { } } // Attempt to conform in protocol extension with unavailable witness // in extension class HasNoMethodF1 { } extension HasNoMethodF1 : HasMethodF { @available(OSX, introduced: 10.51) func f(_ p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available on OS X 10.50.0 and newer}} } class HasNoMethodF2 { } @available(OSX, introduced: 10.51) extension HasNoMethodF2 : HasMethodF { func f(_ p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available on OS X 10.50.0 and newer}} } @available(OSX, introduced: 10.51) class HasNoMethodF3 { } @available(OSX, introduced: 10.51) extension HasNoMethodF3 : HasMethodF { // We expect this conformance to succeed because on every version where HasNoMethodF3 // is available, HasNoMethodF3's f() is as available as the protocol requirement func f(_ p: Int) { } } @available(OSX, introduced: 10.51) protocol HasMethodFOn10_51 { func f(_ p: Int) // expected-note {{protocol requirement here}} } class ConformsToUnavailableProtocolWithUnavailableWitness : HasMethodFOn10_51 { @available(OSX, introduced: 10.51) func f(_ p: Int) { } } @available(OSX, introduced: 10.51) class HasNoMethodF4 { } @available(OSX, introduced: 10.52) extension HasNoMethodF4 : HasMethodFOn10_51 { func f(_ p: Int) { } // expected-error {{protocol 'HasMethodFOn10_51' requires 'f' to be available on OS X 10.51 and newer}} } @available(OSX, introduced: 10.51) protocol HasTakesClassAvailableOn10_51 { func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) // expected-note 2{{protocol requirement here}} } class AttemptsToConformToHasTakesClassAvailableOn10_51 : HasTakesClassAvailableOn10_51 { @available(OSX, introduced: 10.52) func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) { // expected-error {{protocol 'HasTakesClassAvailableOn10_51' requires 'takesClassAvailableOn10_51' to be available on OS X 10.51 and newer}} } } class ConformsToHasTakesClassAvailableOn10_51 : HasTakesClassAvailableOn10_51 { @available(OSX, introduced: 10.51) func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) { } } class TakesClassAvailableOn10_51_A { } extension TakesClassAvailableOn10_51_A : HasTakesClassAvailableOn10_51 { @available(OSX, introduced: 10.52) func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) { // expected-error {{protocol 'HasTakesClassAvailableOn10_51' requires 'takesClassAvailableOn10_51' to be available on OS X 10.51 and newer}} } } class TakesClassAvailableOn10_51_B { } extension TakesClassAvailableOn10_51_B : HasTakesClassAvailableOn10_51 { @available(OSX, introduced: 10.51) func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) { } } // We do not want potential unavailability to play a role in picking a witness for a // protocol requirement. Rather, the witness should be chosen, regardless of its // potential unavailability, and then it should be diagnosed if it is less available // than the protocol requires. class TestAvailabilityDoesNotAffectWitnessCandidacy : HasMethodF { // Test that we choose the more specialized witness even though it is // less available than the protocol requires and there is a less specialized // witness that has suitable availability. @available(OSX, introduced: 10.51) func f(_ p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available on OS X 10.50.0 and newer}} func f<T>(_ p: T) { } } protocol HasUnavailableMethodF { @available(OSX, introduced: 10.51) func f(_ p: String) } class ConformsWithUnavailableFunction : HasUnavailableMethodF { @available(OSX, introduced: 10.9) func f(_ p: String) { } } func useUnavailableProtocolMethod(_ h: HasUnavailableMethodF) { // expected-note@-1 {{add @available attribute to enclosing global function}} h.f("Foo") // expected-error {{'f' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } func useUnavailableProtocolMethod<H : HasUnavailableMethodF> (_ h: H) { // expected-note@-1 {{add @available attribute to enclosing global function}} h.f("Foo") // expected-error {{'f' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Short-form @available() annotations @available(OSX 10.51, *) class ClassWithShortFormAvailableOn10_51 { } @available(OSX 10.53, *) class ClassWithShortFormAvailableOn10_53 { } @available(OSX 10.54, *) class ClassWithShortFormAvailableOn10_54 { } @available(OSX 10.9, *) func funcWithShortFormAvailableOn10_9() { let _ = ClassWithShortFormAvailableOn10_51() // expected-error {{'ClassWithShortFormAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX 10.51, *) func funcWithShortFormAvailableOn10_51() { let _ = ClassWithShortFormAvailableOn10_51() } @available(iOS 14.0, *) func funcWithShortFormAvailableOniOS14() { // expected-note@-1 {{add @available attribute to enclosing global function}} let _ = ClassWithShortFormAvailableOn10_51() // expected-error {{'ClassWithShortFormAvailableOn10_51' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(iOS 14.0, OSX 10.53, *) func funcWithShortFormAvailableOniOS14AndOSX10_53() { let _ = ClassWithShortFormAvailableOn10_51() } // Not idiomatic but we need to be able to handle it. @available(iOS 8.0, *) @available(OSX 10.51, *) func funcWithMultipleShortFormAnnotationsForDifferentPlatforms() { let _ = ClassWithShortFormAvailableOn10_51() } @available(OSX 10.51, *) @available(OSX 10.53, *) @available(OSX 10.52, *) func funcWithMultipleShortFormAnnotationsForTheSamePlatform() { let _ = ClassWithShortFormAvailableOn10_53() let _ = ClassWithShortFormAvailableOn10_54() // expected-error {{'ClassWithShortFormAvailableOn10_54' is only available on OS X 10.54 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX 10.9, *) @available(OSX, unavailable) func unavailableWins() { } // expected-note {{'unavailableWins()' has been explicitly marked unavailable here}} func useShortFormAvailable() { // expected-note@-1 4{{add @available attribute to enclosing global function}} funcWithShortFormAvailableOn10_9() funcWithShortFormAvailableOn10_51() // expected-error {{'funcWithShortFormAvailableOn10_51()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} funcWithShortFormAvailableOniOS14() funcWithShortFormAvailableOniOS14AndOSX10_53() // expected-error {{'funcWithShortFormAvailableOniOS14AndOSX10_53()' is only available on OS X 10.53 or newer}} // expected-note@-1 {{add 'if #available' version check}} funcWithMultipleShortFormAnnotationsForDifferentPlatforms() // expected-error {{'funcWithMultipleShortFormAnnotationsForDifferentPlatforms()' is only available on OS X 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} funcWithMultipleShortFormAnnotationsForTheSamePlatform() // expected-error {{'funcWithMultipleShortFormAnnotationsForTheSamePlatform()' is only available on OS X 10.53 or newer}} // expected-note@-1 {{add 'if #available' version check}} unavailableWins() // expected-error {{'unavailableWins()' is unavailable}} }
apache-2.0
1ec833c1216a8797e3e59a3712011669
41.388682
355
0.704596
3.759777
false
false
false
false
PJayRushton/stats
Stats/Season.swift
1
1187
// // Season.swift // Stats // // Created by Parker Rushton on 3/27/17. // Copyright © 2017 AppsByPJ. All rights reserved. // import Firebase import Marshal struct Season: Identifiable, Unmarshaling { var id: String var isCompleted: Bool var name: String var teamId: String init(id: String = "", isCompleted: Bool = false, name: String, teamId: String) { self.id = id self.isCompleted = isCompleted self.name = name self.teamId = teamId } init(object: MarshaledObject) throws { id = try object.value(for: idKey) isCompleted = try object.value(for: isCompletedKey) name = try object.value(for: nameKey) teamId = try object.value(for: teamIdKey) } } extension Season: JSONMarshaling { func jsonObject() -> JSONObject { var json = JSONObject() json[idKey] = id json[isCompletedKey] = isCompleted json[nameKey] = name json[teamIdKey] = teamId return json } } extension Season { var ref: DatabaseReference { return StatsRefs.seasonsRef(teamId: teamId).child(id) } }
mit
1b34024e15a9f4245347d3791018d9ce
20.563636
84
0.600337
4.132404
false
false
false
false
Yoloabdo/CS-193P
SmashTag/SmashTag/PrestingHistory.swift
1
1443
// // PrestingHistory.swift // SmashTag // // Created by abdelrahman mohamed on 3/5/16. // Copyright © 2016 Abdulrhman dev. All rights reserved. // import Foundation class PrestingHistory { private struct History { static let defaultsKey = "searchWords" static let numberOfSearches = 100 } private let defaults = NSUserDefaults.standardUserDefaults() private var searchHistory: [String]{ set{ defaults.setObject(newValue, forKey: History.defaultsKey) } get{ return defaults.objectForKey(History.defaultsKey) as? [String] ?? [] } } func count() -> Int { return searchHistory.count } func getWordAtIndex(index: Int) -> String { return searchHistory[index] } func addWord(search: String){ var currentSearches = searchHistory if let index = currentSearches.indexOf(search){ currentSearches.removeAtIndex(index) } currentSearches.insert(search, atIndex: 0) while currentSearches.count > History.numberOfSearches { currentSearches.removeLast() } searchHistory = currentSearches } func deleteWord(index: Int) { var currentSearches = searchHistory currentSearches.removeAtIndex(index) searchHistory = currentSearches } }
mit
b93f044fd754c7f6b01e22f228282235
23.440678
80
0.606103
4.790698
false
false
false
false
mario-kang/HClient
HClient/Viewer.swift
1
10974
// // Viewer.swift // HClient // // Created by 강희찬 on 2017. 7. 17.. // Copyright © 2017년 mario-kang. All rights reserved. // import UIKit import WebKit import SafariServices class Viewer: UIViewController, WKNavigationDelegate { var URL1 = "" var web:WKWebView! var progress:UIProgressView! var reloaded = true var HTMLString = "" var reloadButton: UIBarButtonItem! var actionButton: UIBarButtonItem! var isLocal = false var documentPath = "" var number = "" override func loadView() { super.loadView() web = WKWebView() actionButton = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(Action)) reloadButton = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(reloads)) self.navigationItem.setRightBarButtonItems([actionButton, reloadButton], animated: true) self.view = web web.navigationDelegate = self progress = UIProgressView(progressViewStyle: .bar) progress.translatesAutoresizingMaskIntoConstraints = false web.addSubview(progress) if #available(iOS 11.0, *) { let guide = view.safeAreaLayoutGuide progress.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true } else { NSLayoutConstraint(item: progress, attribute: .top, relatedBy: .equal, toItem: self.topLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: 0.0).isActive = true } progress.leadingAnchor.constraint(equalTo: web.leadingAnchor).isActive = true progress.trailingAnchor.constraint(equalTo: web.trailingAnchor).isActive = true } override func viewDidLoad() { super.viewDidLoad() web.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil) self.view.addSubview(progress) let viewerURL = "https://hitomi.la\(URL1)" let fileManage = FileManager() let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) documentPath = dirPath[0] fileManage.changeCurrentDirectoryPath(documentPath) number = URL1.components(separatedBy: "/")[2].components(separatedBy: ".html")[0] if fileManage.changeCurrentDirectoryPath(number) { isLocal = true self.HTMLString = "<!DOCTYPE HTML><html><head><style>img{width:100%;}</style></head><body>" do { var picList = try fileManage.contentsOfDirectory(atPath: ".") picList = picList.sorted {$0.localizedStandardCompare($1) == .orderedAscending} var url = URL(string: "") let patha = documentPath.appending("/\(number)") let urlpath = URL(fileURLWithPath: patha) for a in picList { if !a.hasSuffix(".html") { let path = documentPath.appending("/\(number)/\(a)") url = URL(fileURLWithPath: path) self.HTMLString.append("<img src=\"\(url!.absoluteString)\">") } } fileManage.changeCurrentDirectoryPath(number) fileManage.createFile(atPath: "\(number).html", contents: self.HTMLString.data(using: .utf8), attributes: nil) let html = documentPath.appending("/\(number)/\(number).html") url = URL(fileURLWithPath: html) self.HTMLString = self.HTMLString + "</body></html>" self.web.loadFileURL(url!, allowingReadAccessTo: urlpath) } catch { } } else { UIApplication.shared.isNetworkActivityIndicatorVisible = true let session = URLSession.shared let task = session.dataTask(with: URL(string:viewerURL)!) { (data, _, error) in if error == nil { let str = String(data:data!, encoding:.utf8) self.HTMLString = "<!DOCTYPE HTML><style>img{width:100%;}</style>" let list = str?.components(separatedBy: "<div class=\"img-url\">//") for i in 0...(list?.count)!-2 { let galleries:String = (list?[i+1].components(separatedBy: "</div>")[0])! let num = galleries.components(separatedBy: "/galleries/")[1].components(separatedBy: "/")[0] let numb = galleries.components(separatedBy: "/")[3] let a = String(UnicodeScalar(97 + Int(num)! % 2)!) self.HTMLString.append("<img src=\"https://\(a)a.hitomi.la/galleries/\(num)/\(numb)\" >") } DispatchQueue.main.async { self.web.loadHTMLString(self.HTMLString, baseURL: nil) UIApplication.shared.isNetworkActivityIndicatorVisible = false } } else { OperationQueue.main.addOperation { let alert = UIAlertController(title: NSLocalizedString("Error Occured.", comment: ""), message: error?.localizedDescription, preferredStyle: .alert) let action = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: nil) alert.addAction(action) self.present(alert, animated: true, completion: nil) UIApplication.shared.isNetworkActivityIndicatorVisible = false } } } task.resume() } } deinit { web.removeObserver(self, forKeyPath: "estimatedProgress") } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "estimatedProgress" { progress.setProgress(Float(web.estimatedProgress), animated: true) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) UIApplication.shared.isNetworkActivityIndicatorVisible = false } func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { UIApplication.shared.isNetworkActivityIndicatorVisible = true reloadButton = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(reloads)) self.navigationItem.setRightBarButtonItems([actionButton, reloadButton], animated: true) reloaded = true progress.isHidden = false } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { UIApplication.shared.isNetworkActivityIndicatorVisible = false reloadButton = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(reloads)) self.navigationItem.setRightBarButtonItems([actionButton, reloadButton], animated: true) reloaded = false progress.isHidden = true } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { UIApplication.shared.isNetworkActivityIndicatorVisible = false let alert = UIAlertController(title: NSLocalizedString("Error Occured.", comment: ""), message: error.localizedDescription, preferredStyle: .alert) let action = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: nil) alert.addAction(action) self.present(alert, animated: true, completion: nil) reloadButton = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(reloads)) reloaded = false self.navigationItem.setRightBarButtonItems([actionButton, reloadButton], animated: true) progress.isHidden = true } @objc func Action() { let sheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let ViewerURL = "https://hitomi.la\(URL1)" let activity = UIAlertAction(title: NSLocalizedString("Share URL", comment: ""), style: .default) { (_) in let url = URL(string: ViewerURL) let activityController = UIActivityViewController(activityItems: [url!], applicationActivities: nil) activityController.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem self.present(activityController, animated: true, completion: nil) } let open = UIAlertAction(title: NSLocalizedString("Open in Safari", comment: ""), style: .default) { (_) in let safari = SFSafariViewController(url: URL(string: ViewerURL)!) if #available(iOS 10.0, *) { safari.preferredBarTintColor = UIColor(hue: 235.0/360.0, saturation: 0.77, brightness: 0.47, alpha: 1.0) } self.present(safari, animated: true, completion: nil) } let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil) sheet.addAction(activity) sheet.addAction(open) sheet.addAction(cancel) sheet.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem self.present(sheet, animated: true, completion: nil) } @objc func reloads() { if reloaded { web.stopLoading() reloaded = false reloadButton = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(reloads)) self.navigationItem.setRightBarButtonItems([actionButton, reloadButton], animated: true) UIApplication.shared.isNetworkActivityIndicatorVisible = false progress.isHidden = true } else { if isLocal { let html = documentPath.appending("/\(number)/\(number).html") let url = URL(fileURLWithPath: html) self.HTMLString = self.HTMLString + "</body></html>" let patha = documentPath.appending("/\(number)") let urlpath = URL(fileURLWithPath: patha) self.web.loadFileURL(url, allowingReadAccessTo: urlpath) reloaded = true reloadButton = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(reloads)) self.navigationItem.setRightBarButtonItems([actionButton, reloadButton], animated: true) } else { self.web.loadHTMLString(self.HTMLString, baseURL: nil) reloaded = true reloadButton = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(reloads)) self.navigationItem.setRightBarButtonItems([actionButton, reloadButton], animated: true) } } } }
mit
632de48a4b0165da0bd31272d5fbdc7e
49.763889
179
0.618057
5.291988
false
false
false
false
rexbu/libGPU
example/ios/ZipArchive/SwiftExample/SwiftExample/ViewController.swift
2
4414
// // ViewController.swift // SwiftExample // // Created by Sean Soper on 10/23/15. // // import UIKit #if UseCarthage import ZipArchive #else import SSZipArchive #endif class ViewController: UIViewController { @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var zipButton: UIButton! @IBOutlet weak var unzipButton: UIButton! @IBOutlet weak var resetButton: UIButton! @IBOutlet weak var file1: UILabel! @IBOutlet weak var file2: UILabel! @IBOutlet weak var file3: UILabel! var zipPath: String? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. file1.text = "" file2.text = "" file3.text = "" } // MARK: IBAction @IBAction func zipPressed(_: UIButton) { let sampleDataPath = Bundle.main.bundleURL.appendingPathComponent("Sample Data").path zipPath = tempZipPath() let password = passwordField.text let success = SSZipArchive.createZipFile(atPath: zipPath!, withContentsOfDirectory: sampleDataPath, keepParentDirectory: false, compressionLevel: -1, password: password?.isEmpty == false ? password : nil, aes: true, progressHandler: nil) if success { print("Success zip") unzipButton.isEnabled = true zipButton.isEnabled = false } else { print("No success zip") } resetButton.isEnabled = true } @IBAction func unzipPressed(_: UIButton) { guard let zipPath = self.zipPath else { return } guard let unzipPath = tempUnzipPath() else { return } let password = passwordField.text let success: Bool = SSZipArchive.unzipFile(atPath: zipPath, toDestination: unzipPath, preserveAttributes: true, overwrite: true, nestedZipLevel: 1, password: password?.isEmpty == false ? password : nil, error: nil, delegate: nil, progressHandler: nil, completionHandler: nil) if success != false { print("Success unzip") } else { print("No success unzip") return } var items: [String] do { items = try FileManager.default.contentsOfDirectory(atPath: unzipPath) } catch { return } for (index, item) in items.enumerated() { switch index { case 0: file1.text = item case 1: file2.text = item case 2: file3.text = item default: print("Went beyond index of assumed files") } } unzipButton.isEnabled = false } @IBAction func resetPressed(_: UIButton) { file1.text = "" file2.text = "" file3.text = "" zipButton.isEnabled = true unzipButton.isEnabled = false resetButton.isEnabled = false } // MARK: Private func tempZipPath() -> String { var path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] path += "/\(UUID().uuidString).zip" return path } func tempUnzipPath() -> String? { var path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] path += "/\(UUID().uuidString)" let url = URL(fileURLWithPath: path) do { try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) } catch { return nil } return url.path } }
gpl-3.0
599a5ca2aaaac7cbeeddc97c6fa0ed00
29.867133
112
0.491844
5.725032
false
false
false
false
mattiasjahnke/arduino-projects
matrix-painter/iOS/PixelDrawer/Carthage/Checkouts/flow/Flow/Signal+Combiners.swift
1
22350
// // Signal+Combiners.swift // Flow // // Created by Måns Bernhardt on 2015-09-17. // Copyright © 2015 iZettle. All rights reserved. // import Foundation /// Returns a new signal merging the values emitted from `signals` /// /// a)---b---c------d-| /// | | | /// 0)----------1------2---| /// | | | | | /// +--------------------+ /// | merge() | /// +--------------------+ /// | | | | | /// a)---b---c--1---c--2---| /// /// - Note: Will terminate when all `signals` have termianated or when any signal termiates with an error. public func merge<Signals: Sequence>(_ signals: Signals) -> CoreSignal<Signals.Iterator.Element.Kind.DropWrite, Signals.Iterator.Element.Value> where Signals.Iterator.Element: SignalProvider { let signals = signals.map { $0.providedSignal } let count = signals.count return CoreSignal(onEventType: { callback in let s = StateAndCallback(state: (endCount: 0, hasPassedInitial: false), callback: callback) for signal in signals { s += signal.onEventType { eventType in s.lock() if case .initial = eventType { guard !s.val.hasPassedInitial else { return s.unlock() } s.val.hasPassedInitial = true } // Don't forward non error ends unless all have ended. if case .event(.end(nil)) = eventType { s.val.endCount += 1 guard s.val.endCount == count else { return s.unlock() } } s.unlock() s.call(eventType) } } return s }) } /// Returns a new signal merging the values emitted from `signals` /// /// a)---b---c------d-| /// | | | /// 0)----------1------2---| /// | | | | | /// +--------------------+ /// | merge() | /// +--------------------+ /// | | | | | /// a)---b---c--1---c--2---| /// /// - Note: Will terminate when all `signals` have termianated or when any signal termiates with an error. public func merge<S: SignalProvider>(_ signals: S...) -> CoreSignal<S.Kind.DropWrite, S.Value> { return merge(signals) } /// Returns a new signal combining the latest values from the provided signals public func combineLatest<S: Sequence>(_ signals: S) -> CoreSignal<S.Iterator.Element.Kind.DropWrite, [S.Iterator.Element.Value]> where S.Iterator.Element: SignalProvider { let signals = signals.map { $0.providedSignal } guard !signals.isEmpty else { return CoreSignal(onEventType: { callback in callback(.initial([])) return NilDisposer() }) } return CoreSignal(onEventType: { callback in let s = StateAndCallback(state: Array(repeating: S.Iterator.Element.Value?.none, count: signals.count), callback: callback) for i in signals.indices { let signal = signals[i] s += signal.onEventType { eventType in switch eventType { case .initial(nil) where i == 0: s.call(.initial(nil)) case .initial(nil): break case .initial(let val?): s.lock() s.val[i] = val let combines = s.val.compactMap { $0 } if combines.count == s.val.count { s.unlock() s.call(.initial(combines)) } else { s.unlock() } case .event(.value(let val)): s.lock() s.val[i] = val let combines = s.val.compactMap { $0 } if combines.count == s.val.count { s.unlock() s.call(.event(.value(combines))) } else { s.unlock() } case .event(.end(let error)): s.call(.event(.end(error))) } } } return s }) } /// Returns a new signal combining the latest values from the provided signals /// /// ---a---b-------c------------| /// | | | | /// ----------1----------2---------> /// | | | | | | /// +-----------------------------+ /// | combineLatest() - plain | /// +-----------------------------+ /// | | | | /// ----------b1---c1----c2-----| /// /// a)---b---------c-------------| /// | | | /// 0)---------1---------2----------> /// | | | | | /// +------------------------------+ /// | combineLatest() - readable | /// +------------------------------+ /// | | | | | /// a0)--b0---b1---c1----c2------| /// /// - Note: If `a` and `b` both have sources their current values will be used as initial values. public func combineLatest<A: SignalProvider, B: SignalProvider>(_ a: A, _ b: B) -> CoreSignal<A.Kind.DropWrite, (A.Value, B.Value)> { let aSignal = a.providedSignal let bSignal = b.providedSignal return CoreSignal(onEventType: { callback in let s = StateAndCallback(state: (a: A.Value?.none, b: B.Value?.none), callback: callback) s += aSignal.onEventType { eventType in switch eventType { case .initial(nil): s.call(.initial(nil)) case .initial(let val?): s.lock() s.val.a = val if let b = s.val.b { s.unlock() s.call(.initial((val, b))) } else { s.unlock() } case .event(.value(let val)): s.lock() s.val.a = val if let b = s.val.b { s.unlock() s.call(.event(.value((val, b)))) } else { s.unlock() } case .event(.end(let error)): s.call(.event(.end(error))) } } s += bSignal.onEventType { eventType in switch eventType { case .initial(nil): break case .initial(let val?): s.lock() s.val.b = val if let a = s.val.a { s.unlock() s.call(.initial((a, val))) } else { s.unlock() } case .event(.value(let val)): s.lock() s.val.b = val if let a = s.val.a { s.unlock() s.call(.event(.value((a, val)))) } else { s.unlock() } case .event(.end(let error)): s.call(.event(.end(error))) } } return s }) } /// Returns a new signal combining the latest values from the provided signals /// - Note: See `combineLatest(_:, _:)` for more info. public func combineLatest<A: SignalProvider, B: SignalProvider, C: SignalProvider>(_ a: A, _ b: B, _ c: C) -> CoreSignal<A.Kind.DropWrite, (A.Value, B.Value, C.Value)> { let aSignal = a.providedSignal let bSignal = b.providedSignal let cSignal = c.providedSignal return CoreSignal(onEventType: { callback in let s = StateAndCallback(state: (a: A.Value?.none, b: B.Value?.none, c: C.Value?.none), callback: callback) s += aSignal.onEventType { eventType in switch eventType { case .initial(nil): s.call(.initial(nil)) case .initial(let val?): s.lock() s.val.a = val if let b = s.val.b, let c = s.val.c { s.unlock() s.call(.initial((val, b, c))) } else { s.unlock() } case .event(.value(let val)): s.lock() s.val.a = val if let b = s.val.b, let c = s.val.c { s.unlock() s.call(.event(.value((val, b, c)))) } else { s.unlock() } case .event(.end(let error)): s.call(.event(.end(error))) } } s += bSignal.onEventType { eventType in switch eventType { case .initial(nil): break case .initial(let val?): s.lock() s.val.b = val if let a = s.val.a, let c = s.val.c { s.unlock() s.call(.initial((a, val, c))) } else { s.unlock() } case .event(.value(let val)): s.lock() s.val.b = val if let a = s.val.a, let c = s.val.c { s.unlock() s.call(.event(.value((a, val, c)))) } else { s.unlock() } case .event(.end(let error)): s.call(.event(.end(error))) } } s += cSignal.onEventType { eventType in switch eventType { case .initial(nil): break case .initial(let val?): s.lock() s.val.c = val if let a = s.val.a, let b = s.val.b { s.unlock() s.call(.initial((a, b, val))) } else { s.unlock() } case .event(.value(let val)): s.lock() s.val.c = val if let a = s.val.a, let b = s.val.b { s.unlock() s.call(.event(.value((a, b, val)))) } else { s.unlock() } case .event(.end(let error)): s.call(.event(.end(error))) } } return s }) } /// Returns a new signal combining the latest values from the provided signals /// - Note: See `combineLatest(_:, _:)` for more info. public func combineLatest<A: SignalProvider, B: SignalProvider, C: SignalProvider, D: SignalProvider>(_ a: A, _ b: B, _ c: C, _ d: D) -> CoreSignal<A.Kind.DropWrite, (A.Value, B.Value, C.Value, D.Value)> { let aSignal = a.providedSignal let bSignal = b.providedSignal let cSignal = c.providedSignal let dSignal = d.providedSignal return CoreSignal(onEventType: { callback in let s = StateAndCallback(state: (a: A.Value?.none, b: B.Value?.none, c: C.Value?.none, d: D.Value?.none), callback: callback) s += aSignal.onEventType { eventType in switch eventType { case .initial(nil): s.call(.initial(nil)) case .initial(let val?): s.lock() s.val.a = val if let b = s.val.b, let c = s.val.c, let d = s.val.d { s.unlock() s.call(.initial((val, b, c, d))) } else { s.unlock() } case .event(.value(let val)): s.lock() s.val.a = val if let b = s.val.b, let c = s.val.c, let d = s.val.d { s.unlock() s.call(.event(.value((val, b, c, d)))) } else { s.unlock() } case .event(.end(let error)): s.call(.event(.end(error))) } } s += bSignal.onEventType { eventType in switch eventType { case .initial(nil): break case .initial(let val?): s.lock() s.val.b = val if let a = s.val.a, let c = s.val.c, let d = s.val.d { s.unlock() s.call(.initial((a, val, c, d))) } else { s.unlock() } case .event(.value(let val)): s.lock() s.val.b = val if let a = s.val.a, let c = s.val.c, let d = s.val.d { s.unlock() s.call(.event(.value((a, val, c, d)))) } else { s.unlock() } case .event(.end(let error)): s.call(.event(.end(error))) } } s += cSignal.onEventType { eventType in switch eventType { case .initial(nil): break case .initial(let val?): s.lock() s.val.c = val if let a = s.val.a, let b = s.val.b, let d = s.val.d { s.unlock() s.call(.initial((a, b, val, d))) } else { s.unlock() } case .event(.value(let val)): s.lock() s.val.c = val if let a = s.val.a, let b = s.val.b, let d = s.val.d { s.unlock() s.call(.event(.value((a, b, val, d)))) } else { s.unlock() } case .event(.end(let error)): s.call(.event(.end(error))) } } s += dSignal.onEventType { eventType in switch eventType { case .initial(nil): break case .initial(let val?): s.lock() s.val.d = val if let a = s.val.a, let b = s.val.b, let c = s.val.c { s.unlock() s.call(.initial((a, b, c, val))) } else { s.unlock() } case .event(.value(let val)): s.lock() s.val.d = val if let a = s.val.a, let b = s.val.b, let c = s.val.c { s.unlock() s.call(.event(.value((a, b, c, val)))) } else { s.unlock() } case .event(.end(let error)): s.call(.event(.end(error))) } } return s }) } /// Returns a new signal combining the latest values from the provided signals /// - Note: See `combineLatest(_:, _:)` for more info. public func combineLatest<A: SignalProvider, B: SignalProvider, C: SignalProvider, D: SignalProvider, E: SignalProvider>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E) -> CoreSignal<A.Kind.DropWrite.DropWrite.DropWrite, (A.Value, B.Value, C.Value, D.Value, E.Value)> { return combineLatest(combineLatest(a, b, c), combineLatest(d, e)).map { let ((a, b, c), (d, e)) = $0 return (a, b, c, d, e) } } /// Returns a new signal combining the latest values from the provided signals /// - Note: See `combineLatest(_:, _:)` for more info. public func combineLatest<A: SignalProvider, B: SignalProvider, C: SignalProvider, D: SignalProvider, E: SignalProvider, F: SignalProvider>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F) -> CoreSignal<A.Kind.DropWrite.DropWrite.DropWrite, (A.Value, B.Value, C.Value, D.Value, E.Value, F.Value)> { return combineLatest(combineLatest(a, b, c, d), combineLatest(e, f)).map { let ((a, b, c, d), (e, f)) = $0 return (a, b, c, d, e, f) } } /// Returns a new signal combining the latest values from the provided signals /// - Note: See `combineLatest(_:, _:)` for more info. public func combineLatest<A: SignalProvider, B: SignalProvider, C: SignalProvider, D: SignalProvider, E: SignalProvider, F: SignalProvider, G: SignalProvider>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G) -> CoreSignal<A.Kind.DropWrite.DropWrite.DropWrite, (A.Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value)> { return combineLatest(combineLatest(a, b, c, d), combineLatest(e, f, g)).map { let ((a, b, c, d), (e, f, g)) = $0 return (a, b, c, d, e, f, g) } } /// Returns a new signal combining the latest values from the provided signals /// - Note: See `combineLatest(_:, _:)` for more info. public func combineLatest<A: SignalProvider, B: SignalProvider, C: SignalProvider, D: SignalProvider, E: SignalProvider, F: SignalProvider, G: SignalProvider, H: SignalProvider>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H) -> CoreSignal<A.Kind.DropWrite.DropWrite.DropWrite, (A.Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value)> { return combineLatest(combineLatest(a, b, c, d), combineLatest(e, f, g, h)).map { let ((a, b, c, d), (e, f, g, h)) = $0 return (a, b, c, d, e, f, g, h) } } /// Returns a new signal combining the latest values from the provided signals /// - Note: See `combineLatest(_:, _:)` for more info. public func combineLatest<A: SignalProvider, B: SignalProvider, C: SignalProvider, D: SignalProvider, E: SignalProvider, F: SignalProvider, G: SignalProvider, H: SignalProvider, I: SignalProvider>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I) -> CoreSignal<A.Kind.DropWrite.DropWrite.DropWrite, (A.Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value)> { return combineLatest(combineLatest(a, b, c, d), combineLatest(e, f, g), combineLatest(h, i)).map { let ((a, b, c, d), (e, f, g), (h, i)) = $0 return (a, b, c, d, e, f, g, h, i) } } /// Returns a new signal combining the latest values from the provided signals /// - Note: See `combineLatest(_:, _:)` for more info. public func combineLatest<A: SignalProvider, B: SignalProvider, C: SignalProvider, D: SignalProvider, E: SignalProvider, F: SignalProvider, G: SignalProvider, H: SignalProvider, I: SignalProvider, J: SignalProvider>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J) -> CoreSignal<A.Kind.DropWrite.DropWrite.DropWrite, (A.Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value, J.Value)> { return combineLatest(combineLatest(a, b, c, d), combineLatest(e, f, g, h), combineLatest(i, j)).map { let ((a, b, c, d), (e, f, g, h), (i, j)) = $0 return (a, b, c, d, e, f, g, h, i, j) } } /// Returns a new signal combining the latest values from the provided signals /// - Note: See `combineLatest(_:, _:)` for more info. public func combineLatest<A: SignalProvider, B: SignalProvider, C: SignalProvider, D: SignalProvider, E: SignalProvider, F: SignalProvider, G: SignalProvider, H: SignalProvider, I: SignalProvider, J: SignalProvider, K :SignalProvider>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J, _ k: K) -> CoreSignal<A.Kind.DropWrite.DropWrite.DropWrite, (A.Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value, J.Value, K.Value)> { return combineLatest(combineLatest(a, b, c, d), combineLatest(e, f, g, h), combineLatest(i, j, k)).map { let ((a, b, c, d), (e, f, g, h), (i, j, k)) = $0 return (a, b, c, d, e, f, g, h, i, j, k) } } /// Returns a new signal combining the latest values from the provided signals /// - Note: See `combineLatest(_:, _:)` for more info. public func combineLatest<A: SignalProvider, B: SignalProvider, C: SignalProvider, D: SignalProvider, E: SignalProvider, F: SignalProvider, G: SignalProvider, H: SignalProvider, I: SignalProvider, J: SignalProvider, K: SignalProvider, L: SignalProvider>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J, _ k: K, _ l: L) -> CoreSignal<A.Kind.DropWrite.DropWrite.DropWrite, (A.Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value, J.Value, K.Value, L.Value)> { return combineLatest(combineLatest(a, b, c, d), combineLatest(e, f, g, h), combineLatest(i, j, k, l)).map { let ((a, b, c, d), (e, f, g, h), (i, j, k, l)) = $0 return (a, b, c, d, e, f, g, h, i, j, k, l) } } /// Returns a new signal combining the latest values from the provided signals /// - Note: See `combineLatest(_:, _:)` for more info. public func combineLatest<A: SignalProvider, B: SignalProvider, C: SignalProvider, D: SignalProvider, E: SignalProvider, F: SignalProvider, G: SignalProvider, H: SignalProvider, I: SignalProvider, J: SignalProvider, K: SignalProvider, L: SignalProvider, M: SignalProvider>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J, _ k: K, _ l: L, _ m: M) -> CoreSignal<A.Kind.DropWrite.DropWrite.DropWrite, (A.Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value, J.Value, K.Value, L.Value, M.Value)> { return combineLatest(combineLatest(a, b, c, d), combineLatest(e, f, g, h), combineLatest(i, j, k), combineLatest(l, m)).map { let ((a, b, c, d), (e, f, g, h), (i, j, k), (l, m)) = $0 return (a, b, c, d, e, f, g, h, i, j, k, l, m) } } /// Returns a new signal combining the latest values from the provided signals /// - Note: See `combineLatest(_:, _:)` for more info. public func combineLatest<A: SignalProvider, B: SignalProvider, C: SignalProvider, D: SignalProvider, E: SignalProvider, F: SignalProvider, G: SignalProvider, H: SignalProvider, I: SignalProvider, J: SignalProvider, K: SignalProvider, L: SignalProvider, M: SignalProvider, N: SignalProvider>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J, _ k: K, _ l: L, _ m: M, _ n: N) -> CoreSignal<A.Kind.DropWrite.DropWrite.DropWrite, (A.Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value, J.Value, K.Value, L.Value, M.Value, N.Value)> { return combineLatest(combineLatest(a, b, c, d), combineLatest(e, f, g, h), combineLatest(i, j, k, l), combineLatest(m, n)).map { let ((a, b, c, d), (e, f, g, h), (i, j, k, l), (m, n)) = $0 return (a, b, c, d, e, f, g, h, i, j, k, l, m, n) } }
mit
9c140bfbde8fd9869b7704a457c1a360
42.905697
585
0.474897
3.598132
false
true
false
false
chrisjmendez/swift-exercises
Walkthroughs/MyPresentation/Carthage/Checkouts/Presentation/Source/Position.swift
7
1593
import UIKit @objc public class Position: NSObject { public var left: CGFloat = 0.0 public var top: CGFloat = 0.0 public var right: CGFloat { get { return 1.0 - left } set { left = 1.0 - newValue } } public var bottom: CGFloat { get { return 1.0 - top } set { top = 1.0 - newValue } } public init(left: CGFloat, top: CGFloat) { super.init() self.left = left self.top = top } public init(left: CGFloat, bottom: CGFloat) { super.init() self.left = left self.bottom = bottom } public init(right: CGFloat, top: CGFloat) { super.init() self.right = right self.top = top } public init(right: CGFloat, bottom: CGFloat) { super.init() self.right = right self.bottom = bottom } public var positionCopy: Position { return Position(left: left, top: top) } public var horizontalMirror: Position { return Position(left: right, top: top) } public func originInFrame(frame: CGRect) -> CGPoint { return CGPoint(x: xInFrame(frame), y: yInFrame(frame)) } public func xInFrame(frame: CGRect) -> CGFloat { let margin = CGRectGetWidth(frame) * left return CGRectGetMinX(frame) + margin } public func yInFrame(frame: CGRect) -> CGFloat { let margin = CGRectGetHeight(frame) * top return CGRectGetMinY(frame) + margin } public func isEqualToPosition(position: Position, epsilon: CGFloat = 0.0001) -> Bool { let dx = left - position.left, dy = top - position.top return (dx * dx + dy * dy) < epsilon } }
mit
bf25215d09e167193d86b89a181bc36f
18.192771
88
0.617075
3.730679
false
false
false
false
justinhester/hacking-with-swift
src/Project14/Project14/GameScene.swift
1
4732
// // GameScene.swift // Project14 // // Created by Justin Lawrence Hester on 2/1/16. // Copyright (c) 2016 Justin Lawrence Hester. All rights reserved. // import SpriteKit import GameplayKit class GameScene: SKScene { var numRounds = 0 var slots = [WhackSlot]() var gameScore: SKLabelNode! var score: Int = 0 { didSet { gameScore.text = "Score: \(score)" } } var popupTime = 0.85 override func didMoveToView(view: SKView) { let background = SKSpriteNode(imageNamed: "whackBackground") background.position = CGPoint(x: size.width / 2, y: size.height / 2) background.blendMode = .Replace background.zPosition = -1 addChild(background) gameScore = SKLabelNode(fontNamed: "Chalkduster") gameScore.text = "Score: 0" gameScore.position = CGPoint(x: 8, y: 8) gameScore.horizontalAlignmentMode = .Left gameScore.fontSize = 48 addChild(gameScore) /* Create 4 rows of WhackSlot instances. */ for i in 0 ..< 5 { createSlotAt(CGPoint(x: 100 + (i * 170), y: 410)) } for i in 0 ..< 4 { createSlotAt(CGPoint(x: 180 + (i * 170), y: 320)) } for i in 0 ..< 5 { createSlotAt(CGPoint(x: 100 + (i * 170), y: 230)) } for i in 0 ..< 4 { createSlotAt(CGPoint(x: 180 + (i * 170), y: 140)) } RunAfterDelay(1) { [unowned self] in self.createEnemy() } } func createSlotAt(pos: CGPoint) { let slot = WhackSlot() slot.configureAtPosition(pos) addChild(slot) slots.append(slot) } func createEnemy() { numRounds += 1 if numRounds >= 30 { /* Hide all penguins. */ for slot in slots { slot.hide() } /* Game is complete, so end recursion in createEnemy(). */ let gameOver = SKSpriteNode(imageNamed: "gameOver") gameOver.position = CGPoint(x: size.width / 2, y: size.height / 2) gameOver.zPosition = 1 addChild(gameOver) return } popupTime *= 0.991 slots = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(slots) as! [WhackSlot] slots[0].show(hideTime: popupTime) if RandomInt(min: 0, max: 12) > 4 { slots[1].show(hideTime: popupTime) } if RandomInt(min: 0, max: 12) > 8 { slots[2].show(hideTime: popupTime) } if RandomInt(min: 0, max: 12) > 10 { slots[3].show(hideTime: popupTime) } if RandomInt(min: 0, max: 12) > 11 { slots[4].show(hideTime: popupTime) } let minDelay = popupTime / 2.0 let maxDelay = popupTime * 2 RunAfterDelay(RandomDouble(min: minDelay, max: maxDelay)) { [unowned self] in self.createEnemy() } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { /* Called when a touch begins */ if let touch = touches.first { let location = touch.locationInNode(self) let nodes = nodesAtPoint(location) for node in nodes { if node.name == "charFriend" { /* A good penguin was whacked by user. */ let whackSlot = node.parent!.parent as! WhackSlot /* Skip invisible penguins and penguins already hit by user. */ if !whackSlot.visible || whackSlot.isHit { continue } whackSlot.hit() score -= 5 runAction(SKAction.playSoundFileNamed("whackBad.caf", waitForCompletion: false)) } else if node.name == "charEnemy" { /* An evil penguin was whacked by the user. */ let whackSlot = node.parent!.parent as! WhackSlot /* Skip invisible penguins and penguins already hit by user. */ if !whackSlot.visible || whackSlot.isHit { continue } /* Shrink evil penguin to show visual feedback. */ whackSlot.charNode.xScale = 0.85 whackSlot.charNode.yScale = 0.85 whackSlot.hit() score += 1 runAction(SKAction.playSoundFileNamed("whack.caf", waitForCompletion: false)) } } } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } }
gpl-3.0
2bd1f6f31997a5693ca3e61a48c8e7e7
34.313433
100
0.52705
4.722555
false
false
false
false
onthetall/CityPickerView
CityPickerViewDemo/ViewController.swift
1
1523
// // ViewController.swift // CityPickerView // // Created by impressly on 11/19/15. // Copyright © 2015 OTT. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var cityPickerView: CityPickerView! @IBOutlet weak var cityTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.cityTextField.delegate = self self.cityPickerView.hidden = true self.view.bringSubviewToFront(self.cityTextField) self.cityPickerView.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension ViewController: UITextFieldDelegate { func textFieldDidBeginEditing(textField: UITextField) { textField == self.cityTextField textField.resignFirstResponder() if cityPickerView != nil { self.cityPickerView.hidden = false } } } extension ViewController:CityPickerViewDelegate { func cityPickerDidPickArea(cityPickerView: CityPickerView, province: String!, city: String!, district: String!) { let provinceCityDistrict = "\(province)\(city)\(district)" self.cityTextField.text = provinceCityDistrict self.cityPickerView.hidden = true } func cityPickerDidCancel(cityPickerView: CityPickerView) { self.cityPickerView.hidden = true } }
mit
672bafb42650994956f84b1dfc6a1eb2
26.196429
117
0.676084
4.973856
false
false
false
false
designatednerd/GoCubs
GoCubsTests/ParsingTests.swift
1
8493
// // ParsingTests.swift // GoCubs // // Created by Ellen Shapiro on 10/11/15. // Copyright © 2015 Designated Nerd Software. All rights reserved. // import Foundation import XCTest @testable import GoCubs class ParsingTests: XCTestCase { func testParsingPitcher() { let testWinningPitcher = Pitcher(pitcherString: "Arrieta(22-6)") XCTAssertEqual(testWinningPitcher.name, "Arrieta") XCTAssertEqual(testWinningPitcher.wins, 22) XCTAssertEqual(testWinningPitcher.losses, 6) let testLosingPitcher = Pitcher(pitcherString: "Lester(10-12)") XCTAssertEqual(testLosingPitcher.name, "Lester") XCTAssertEqual(testLosingPitcher.wins, 10) XCTAssertEqual(testLosingPitcher.losses, 12) } func testParsingOpponent() { let testHomeOpponent = Opponent(name: "Cardinals") XCTAssertFalse(testHomeOpponent.isHomeTeam) XCTAssertEqual(testHomeOpponent.name, "Cardinals") XCTAssertEqual(testHomeOpponent.team, .Cardinals) let testAwayOpponent = Opponent(name: "at Pirates") XCTAssertEqual(testAwayOpponent.name, "Pirates") XCTAssertTrue(testAwayOpponent.isHomeTeam) XCTAssertEqual(testAwayOpponent.team, .Pirates) } func testParsingResult() { let testParsingRainout = Result(resultString: "Postponed") XCTAssertEqual(testParsingRainout.type, ResultType.postponed) let testParsingLoss = Result(resultString: "L 1-4") XCTAssertEqual(testParsingLoss.type, ResultType.loss) XCTAssertEqual(testParsingLoss.cubsRuns, 1) XCTAssertEqual(testParsingLoss.opponentRuns, 4) let testParsingWin = Result(resultString: "W 7-3") XCTAssertEqual(testParsingWin.type, ResultType.win) XCTAssertEqual(testParsingWin.cubsRuns, 7) XCTAssertEqual(testParsingWin.opponentRuns, 3) } func testParsingCubsRecord() { let cubs2011Record = CubsRecord(recordString: "61-101") XCTAssertEqual(cubs2011Record.wins, 61) XCTAssertEqual(cubs2011Record.losses, 101) let cubs2015Record = CubsRecord(recordString: "97-65") XCTAssertEqual(cubs2015Record.wins, 97) XCTAssertEqual(cubs2015Record.losses, 65) } func testParsingHomeWin() { let testHomeWin = CubsGame(gameString: "6/1,Dodgers,W 2-1,36-15,Lester(6-3),Bolsinger(1-2)") let calendar = Calendar.current let components = (calendar as NSCalendar).components( [.month, .day], from: testHomeWin.date) XCTAssertEqual(components.month, 6) XCTAssertEqual(components.day, 1) XCTAssertEqual(testHomeWin.result.type, ResultType.win) XCTAssertEqual(testHomeWin.result.cubsRuns, 2) XCTAssertEqual(testHomeWin.result.opponentRuns, 1) XCTAssertEqual(testHomeWin.cubsRecord.wins, 36) XCTAssertEqual(testHomeWin.cubsRecord.losses, 15) XCTAssertEqual(testHomeWin.winningPitcher.name, "Lester") XCTAssertEqual(testHomeWin.winningPitcher.wins, 6) XCTAssertEqual(testHomeWin.winningPitcher.losses, 3) XCTAssertEqual(testHomeWin.losingPitcher.name, "Bolsinger") XCTAssertEqual(testHomeWin.losingPitcher.wins, 1) XCTAssertEqual(testHomeWin.losingPitcher.losses, 2) } func testParsingAwayWin() { let testAwayWin = CubsGame(gameString: "8/23,at Padres,W 5-3,80-45,Arrieta(16-5),Friedrich(4-10)") let calendar = Calendar.current let components = (calendar as NSCalendar).components( [.month, .day], from: testAwayWin.date) XCTAssertEqual(components.month, 8) XCTAssertEqual(components.day, 23) XCTAssertEqual(testAwayWin.result.type, ResultType.win) XCTAssertEqual(testAwayWin.result.cubsRuns, 5) XCTAssertEqual(testAwayWin.result.opponentRuns, 3) XCTAssertEqual(testAwayWin.cubsRecord.wins, 80) XCTAssertEqual(testAwayWin.cubsRecord.losses, 45) XCTAssertEqual(testAwayWin.winningPitcher.name, "Arrieta") XCTAssertEqual(testAwayWin.winningPitcher.wins, 16) XCTAssertEqual(testAwayWin.winningPitcher.losses, 5) XCTAssertEqual(testAwayWin.losingPitcher.name, "Friedrich") XCTAssertEqual(testAwayWin.losingPitcher.wins, 4) XCTAssertEqual(testAwayWin.losingPitcher.losses, 10) } func testParsingHomeLoss() { let testHomeLoss = CubsGame(gameString: "4/5,Cardinals,L 0-3,0-1,Wainwright(1-0),Lester(0-1)") let calendar = Calendar.current let components = (calendar as NSCalendar).components( [.month, .day], from: testHomeLoss.date) XCTAssertEqual(components.month, 4) XCTAssertEqual(components.day, 5) XCTAssertEqual(testHomeLoss.result.type, ResultType.loss) XCTAssertEqual(testHomeLoss.result.cubsRuns, 0) XCTAssertEqual(testHomeLoss.result.opponentRuns, 3) XCTAssertEqual(testHomeLoss.cubsRecord.wins, 0) XCTAssertEqual(testHomeLoss.cubsRecord.losses, 1) XCTAssertEqual(testHomeLoss.winningPitcher.name, "Wainwright") XCTAssertEqual(testHomeLoss.winningPitcher.wins, 1) XCTAssertEqual(testHomeLoss.winningPitcher.losses, 0) XCTAssertEqual(testHomeLoss.losingPitcher.name, "Lester") XCTAssertEqual(testHomeLoss.losingPitcher.wins, 0) XCTAssertEqual(testHomeLoss.losingPitcher.losses, 1) } func testParsingAwayLoss() { let testAwayLoss = CubsGame(gameString: "7/23,at Brewers,L 1-6,58-38,Davies(7-4),Lackey(7-6)") let calendar = Calendar.current let components = (calendar as NSCalendar).components( [.month, .day], from: testAwayLoss.date) XCTAssertEqual(components.month, 7) XCTAssertEqual(components.day, 23) XCTAssertEqual(testAwayLoss.result.type, ResultType.loss) XCTAssertEqual(testAwayLoss.result.cubsRuns, 1) XCTAssertEqual(testAwayLoss.result.opponentRuns, 6) XCTAssertEqual(testAwayLoss.cubsRecord.wins, 58) XCTAssertEqual(testAwayLoss.cubsRecord.losses, 38) XCTAssertEqual(testAwayLoss.winningPitcher.name, "Davies") XCTAssertEqual(testAwayLoss.winningPitcher.wins, 7) XCTAssertEqual(testAwayLoss.winningPitcher.losses, 4) XCTAssertEqual(testAwayLoss.losingPitcher.name, "Lackey") XCTAssertEqual(testAwayLoss.losingPitcher.wins, 7) XCTAssertEqual(testAwayLoss.losingPitcher.losses, 6) } func testParsingHomePostponement() { let testHomePostponement = CubsGame(gameString: "5/9,Padres,Postponed,24-6,Villanueva(0-0),Strop(1-0)") let calendar = Calendar.current let postponedComponents = (calendar as NSCalendar).components([.month, .day], from: testHomePostponement.date) XCTAssertEqual(postponedComponents.month, 5) XCTAssertEqual(postponedComponents.day, 9) XCTAssertEqual(testHomePostponement.opponent.team, .Padres) XCTAssertEqual(testHomePostponement.result.type, .postponed) //Cubs are the "winning" team when thre is no result XCTAssertEqual(testHomePostponement.winningPitcher.name, "Strop") XCTAssertEqual(testHomePostponement.losingPitcher.name, "Villanueva") XCTAssertEqual(testHomePostponement.cubsRecord.wins, 24) XCTAssertEqual(testHomePostponement.cubsRecord.losses, 6) } func testParsingAwayPostponement() { let testAwayPostponement = CubsGame(gameString: "9/10,at Phillies,Postponed,80-58,Hendricks(6-6),Asher(0-2)") let calendar = Calendar.current let postponedComponents = (calendar as NSCalendar).components([.month, .day], from: testAwayPostponement.date) XCTAssertEqual(postponedComponents.month, 9) XCTAssertEqual(postponedComponents.day, 10) XCTAssertEqual(testAwayPostponement.opponent.team, .Phillies) XCTAssertTrue(testAwayPostponement.opponent.isHomeTeam) XCTAssertEqual(testAwayPostponement.result.type, .postponed) //Cubs are the "winning" team when thre is no result XCTAssertEqual(testAwayPostponement.winningPitcher.name, "Hendricks") XCTAssertEqual(testAwayPostponement.losingPitcher.name, "Asher") XCTAssertEqual(testAwayPostponement.cubsRecord.wins, 80) XCTAssertEqual(testAwayPostponement.cubsRecord.losses, 58) } }
mit
cc238821e522abf353195cce8b41916c
44.655914
118
0.702426
3.904368
false
true
false
false
Caiflower/SwiftWeiBo
花菜微博/花菜微博/Classes/Tools(工具)/CFAddition(Swift)/UIKit/UIView-Layer.swift
1
1073
// // UIView-Layer.swift // 花菜微博 // // Created by 花菜ChrisCai on 2016/12/20. // Copyright © 2016年 花菜ChrisCai. All rights reserved. // import UIKit // MARK: - layer相关属性 extension UIView { @IBInspectable var borderColor: UIColor { get { return UIColor(cgColor: self.layer.borderColor ?? UIColor.white.cgColor) } set { self.layer.borderColor = newValue.cgColor } } @IBInspectable var cornerRadius: CGFloat { get { return self.layer.cornerRadius } set { self.layer.masksToBounds = true; // 栅格化优化性能 self.layer.rasterizationScale = UIScreen.main.scale; self.layer.shouldRasterize = true; self.layer.cornerRadius = newValue } } @IBInspectable var borderWidth: CGFloat { get { return self.layer.borderWidth } set { self.layer.borderWidth = newValue } } } extension UIView { }
apache-2.0
15e9aaa0ba1ee53e7ec946b9d00961be
19.64
84
0.556202
4.391489
false
false
false
false
kesun421/firefox-ios
StorageTests/SyncCommandsTests.swift
5
9842
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared @testable import Storage import XCTest import SwiftyJSON func byValue(_ a: SyncCommand, b: SyncCommand) -> Bool { return a.value < b.value } func byClient(_ a: RemoteClient, b: RemoteClient) -> Bool { return a.guid! < b.guid! } class SyncCommandsTests: XCTestCase { var clients: [RemoteClient] = [RemoteClient]() var clientsAndTabs: SQLiteRemoteClientsAndTabs! var shareItems = [ShareItem]() var multipleCommands: [ShareItem] = [ShareItem]() var wipeCommand: SyncCommand! var db: BrowserDB! override func setUp() { let files = MockFiles() do { try files.remove("browser.db") } catch _ { } db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files) // create clients let now = Date.now() let client1GUID = Bytes.generateGUID() let client2GUID = Bytes.generateGUID() let client3GUID = Bytes.generateGUID() self.clients.append(RemoteClient(guid: client1GUID, name: "Test client 1", modified: (now - OneMinuteInMilliseconds), type: "mobile", formfactor: "largetablet", os: "iOS", version: "55.0.1", fxaDeviceId: nil)) self.clients.append(RemoteClient(guid: client2GUID, name: "Test client 2", modified: (now - OneHourInMilliseconds), type: "desktop", formfactor: "laptop", os: "Darwin", version: "55.0.1", fxaDeviceId: nil)) self.clients.append(RemoteClient(guid: client3GUID, name: "Test local client", modified: (now - OneMinuteInMilliseconds), type: "mobile", formfactor: "largetablet", os: "iOS", version: "55.0.1", fxaDeviceId: nil)) clientsAndTabs = SQLiteRemoteClientsAndTabs(db: db) clientsAndTabs.insertOrUpdateClients(clients).succeeded() shareItems.append(ShareItem(url: "http://mozilla.com", title: "Mozilla", favicon: nil)) shareItems.append(ShareItem(url: "http://slashdot.org", title: "Slashdot", favicon: nil)) shareItems.append(ShareItem(url: "http://news.bbc.co.uk", title: "BBC News", favicon: nil)) shareItems.append(ShareItem(url: "http://news.bbc.co.uk", title: nil, favicon: nil)) wipeCommand = SyncCommand(value: "{'command':'wipeAll', 'args':[]}") } override func tearDown() { clientsAndTabs.deleteCommands().succeeded() clientsAndTabs.clear().succeeded() } func testCreateSyncCommandFromShareItem() { let shareItem = shareItems[0] let syncCommand = SyncCommand.displayURIFromShareItem(shareItem, asClient: "abcdefghijkl") XCTAssertNil(syncCommand.commandID) XCTAssertNotNil(syncCommand.value) let jsonObj: [String: Any] = [ "command": "displayURI", "args": [shareItem.url, "abcdefghijkl", shareItem.title ?? ""] ] XCTAssertEqual(JSON(object: jsonObj).stringValue(), syncCommand.value) } func testInsertWithNoURLOrTitle() { // Test insert command to table for let e = self.expectation(description: "Insert.") clientsAndTabs.insertCommand(self.wipeCommand, forClients: clients).upon { XCTAssertTrue($0.isSuccess) XCTAssertEqual(3, $0.successValue!) let commandCursorDeferred = self.db.withConnection { connection -> Cursor<Int> in let select = "SELECT COUNT(*) FROM \(TableSyncCommands)" return connection.executeQuery(select, factory: IntFactory, withArgs: nil) } let commandCursor = commandCursorDeferred.value.successValue! XCTAssertNotNil(commandCursor[0]) XCTAssertEqual(3, commandCursor[0]!) e.fulfill() } self.waitForExpectations(timeout: 5, handler: nil) } func testInsertWithURLOnly() { let shareItem = shareItems[3] let syncCommand = SyncCommand.displayURIFromShareItem(shareItem, asClient: "abcdefghijkl") let e = self.expectation(description: "Insert.") clientsAndTabs.insertCommand(syncCommand, forClients: clients).upon { XCTAssertTrue($0.isSuccess) XCTAssertEqual(3, $0.successValue!) let commandCursorDeferred = self.db.withConnection { connection -> Cursor<Int> in let select = "SELECT COUNT(*) FROM \(TableSyncCommands)" return connection.executeQuery(select, factory: IntFactory, withArgs: nil) } let commandCursor = commandCursorDeferred.value.successValue! XCTAssertNotNil(commandCursor[0]) XCTAssertEqual(3, commandCursor[0]!) e.fulfill() } self.waitForExpectations(timeout: 5, handler: nil) } func testInsertWithMultipleCommands() { let e = self.expectation(description: "Insert.") let syncCommands = shareItems.map { item in return SyncCommand.displayURIFromShareItem(item, asClient: "abcdefghijkl") } clientsAndTabs.insertCommands(syncCommands, forClients: clients).upon { XCTAssertTrue($0.isSuccess) XCTAssertEqual(12, $0.successValue!) let commandCursorDeferred = self.db.withConnection { connection -> Cursor<Int> in let select = "SELECT COUNT(*) FROM \(TableSyncCommands)" return connection.executeQuery(select, factory: IntFactory, withArgs: nil) } let commandCursor = commandCursorDeferred.value.successValue! XCTAssertNotNil(commandCursor[0]) XCTAssertEqual(12, commandCursor[0]!) e.fulfill() } self.waitForExpectations(timeout: 5, handler: nil) } func testGetForAllClients() { let syncCommands = shareItems.map { item in return SyncCommand.displayURIFromShareItem(item, asClient: "abcdefghijkl") }.sorted(by: byValue) clientsAndTabs.insertCommands(syncCommands, forClients: clients).succeeded() let b = self.expectation(description: "Get for invalid client.") clientsAndTabs.getCommands().upon({ result in XCTAssertTrue(result.isSuccess) if let clientCommands = result.successValue { XCTAssertEqual(clientCommands.count, self.clients.count) for client in clientCommands.keys { XCTAssertEqual(syncCommands, clientCommands[client]!.sorted(by: byValue)) } } else { XCTFail("Expected no commands!") } b.fulfill() }) self.waitForExpectations(timeout: 5, handler: nil) } func testDeleteForValidClient() { let syncCommands = shareItems.map { item in return SyncCommand.displayURIFromShareItem(item, asClient: "abcdefghijkl") }.sorted(by: byValue) var client = self.clients[0] let a = self.expectation(description: "delete for client.") let b = self.expectation(description: "Get for deleted client.") let c = self.expectation(description: "Get for not deleted client.") clientsAndTabs.insertCommands(syncCommands, forClients: clients).upon { XCTAssertTrue($0.isSuccess) XCTAssertEqual(12, $0.successValue!) let result = self.clientsAndTabs.deleteCommands(client.guid!).value XCTAssertTrue(result.isSuccess) a.fulfill() let commandCursorDeferred = self.db.withConnection { connection -> Cursor<Int> in let select = "SELECT COUNT(*) FROM \(TableSyncCommands) WHERE client_guid = '\(client.guid!)'" return connection.executeQuery(select, factory: IntFactory, withArgs: nil) } let commandCursor = commandCursorDeferred.value.successValue! XCTAssertNotNil(commandCursor[0]) XCTAssertEqual(0, commandCursor[0]!) b.fulfill() client = self.clients[1] let commandCursor2Deferred = self.db.withConnection { connection -> Cursor<Int> in let select = "SELECT COUNT(*) FROM \(TableSyncCommands) WHERE client_guid = '\(client.guid!)'" return connection.executeQuery(select, factory: IntFactory, withArgs: nil) } let commandCursor2 = commandCursor2Deferred.value.successValue! XCTAssertNotNil(commandCursor2[0]) XCTAssertEqual(4, commandCursor2[0]!) c.fulfill() } self.waitForExpectations(timeout: 5, handler: nil) } func testDeleteForAllClients() { let syncCommands = shareItems.map { item in return SyncCommand.displayURIFromShareItem(item, asClient: "abcdefghijkl") } let a = self.expectation(description: "Wipe for all clients.") let b = self.expectation(description: "Get for clients.") clientsAndTabs.insertCommands(syncCommands, forClients: clients).upon { XCTAssertTrue($0.isSuccess) XCTAssertEqual(12, $0.successValue!) let result = self.clientsAndTabs.deleteCommands().value XCTAssertTrue(result.isSuccess) a.fulfill() self.clientsAndTabs.getCommands().upon({ result in XCTAssertTrue(result.isSuccess) if let clientCommands = result.successValue { XCTAssertEqual(0, clientCommands.count) } else { XCTFail("Expected no commands!") } b.fulfill() }) } self.waitForExpectations(timeout: 5, handler: nil) } }
mpl-2.0
11982bf2c5b450bed8e1fb682785444c
40.527426
221
0.631376
4.77999
false
true
false
false
stripe/stripe-ios
StripeCore/StripeCore/Source/Categories/UIImage+StripeCore.swift
1
6016
// // UIImage+StripeCore.swift // StripeCore // // Created by Brian Dorfman on 4/25/17. // Copyright © 2017 Stripe, Inc. All rights reserved. // import AVFoundation import UIKit @_spi(STP) public typealias ImageDataAndSize = (imageData: Data, imageSize: CGSize) extension UIImage { @_spi(STP) public static let defaultCompressionQuality: CGFloat = 0.5 /// Encodes the image to jpeg at the specified compression quality. /// /// The image will be scaled down, if needed, to ensure its size does not exceed `maxBytes`. /// /// - Parameters: /// - maxBytes: The maximum size of the allowed file. If value is nil, then /// the image will not be scaled down. /// - compressionQuality: The compression quality to use when encoding the jpeg. /// - Returns: A tuple containing the following properties. /// - `imageData`: Data object of the jpeg encoded image. /// - `imageSize`: The dimensions of the the image that was encoded. /// This size may be smaller than the original image size if the image /// needed to be scaled down to fit the specified `maxBytes`. @_spi(STP) public func jpegDataAndDimensions( maxBytes: Int? = nil, compressionQuality: CGFloat = defaultCompressionQuality ) -> ImageDataAndSize { dataAndDimensions(maxBytes: maxBytes, compressionQuality: compressionQuality) { image, quality in image.jpegData(compressionQuality: quality) } } /// Encodes the image to heic at the specified compression quality. /// /// The image will be scaled down, if needed, to ensure its size does not exceed `maxBytes`. /// /// - Parameters: /// - maxBytes: The maximum size of the allowed file. If value is nil, then /// the image will not be scaled down. /// - compressionQuality: The compression quality to use when encoding the jpeg. /// - Returns: A tuple containing the following properties. /// - `imageData`: Data object of the jpeg encoded image. /// - `imageSize`: The dimensions of the the image that was encoded. /// This size may be smaller than the original image size if the image /// needed to be scaled down to fit the specified `maxBytes`. @_spi(STP) public func heicDataAndDimensions( maxBytes: Int? = nil, compressionQuality: CGFloat = defaultCompressionQuality ) -> ImageDataAndSize { dataAndDimensions(maxBytes: maxBytes, compressionQuality: compressionQuality) { image, quality in image.heicData(compressionQuality: quality) } } @_spi(STP) public func resized(to scale: CGFloat) -> UIImage? { let newImageSize = CGSize( width: CGFloat(floor(size.width * scale)), height: CGFloat(floor(size.height * scale)) ) UIGraphicsBeginImageContextWithOptions(newImageSize, false, self.scale) defer { UIGraphicsEndImageContext() } draw(in: CGRect(x: 0, y: 0, width: newImageSize.width, height: newImageSize.height)) return UIGraphicsGetImageFromCurrentImageContext() } private func heicData(compressionQuality: CGFloat = UIImage.defaultCompressionQuality) -> Data? { [self].heicData(compressionQuality: compressionQuality) } private func dataAndDimensions( maxBytes: Int? = nil, compressionQuality: CGFloat = defaultCompressionQuality, imageDataProvider: ((_ image: UIImage, _ quality: CGFloat) -> Data?) ) -> ImageDataAndSize { var imageData = imageDataProvider(self, compressionQuality) guard imageData != nil else { return (imageData: Data(), imageSize: .zero) } var newImageSize = self.size // Try something smarter first if let maxBytes = maxBytes, (imageData?.count ?? 0) > maxBytes { var scale = CGFloat(1.0) // Assuming jpeg file size roughly scales linearly with area of the image // which is ~correct (although breaks down at really small file sizes) let percentSmallerNeeded = CGFloat(maxBytes) / CGFloat((imageData?.count ?? 0)) // Shrink to a little bit less than we need to try to ensure we're under // (otherwise its likely our first pass will be over the limit due to // compression variance and floating point rounding) scale = scale * (percentSmallerNeeded - (percentSmallerNeeded * 0.05)) repeat { if let newImage = resized(to: scale) { newImageSize = newImage.size imageData = imageDataProvider(newImage, compressionQuality) } // If the smart thing doesn't work, just start scaling down a bit on a loop until we get there scale = scale * 0.7 } while (imageData?.count ?? 0) > maxBytes } return (imageData: imageData!, imageSize: newImageSize) } } extension Array where Element: UIImage { @_spi(STP) public func heicData( compressionQuality: CGFloat = UIImage.defaultCompressionQuality ) -> Data? { guard let mutableData = CFDataCreateMutable(nil, 0) else { return nil } guard let destination = CGImageDestinationCreateWithData( mutableData, AVFileType.heic as CFString, self.count, nil ) else { return nil } let properties = [kCGImageDestinationLossyCompressionQuality: compressionQuality] as CFDictionary for image in self { let cgImage = image.cgImage! CGImageDestinationAddImage(destination, cgImage, properties) } if CGImageDestinationFinalize(destination) { return mutableData as Data } return nil } }
mit
a3d32265fd9246c32dbfe73809ce5cda
36.59375
110
0.624439
5.088832
false
false
false
false
safx/TypetalkApp
TypetalkApp/DataSources/TopicInfoDataSource.swift
1
1289
// // TopicInfoDataSource.swift // TypetalkApp // // Created by Safx Developer on 2015/02/22. // Copyright (c) 2015年 Safx Developers. All rights reserved. // import TypetalkKit import RxSwift import ObservableArray class TopicInfoDataSource { typealias Event = ObservableArray<Post>.EventType let topic = Variable(Topic()) let teams = Variable([TeamWithMembers]()) let accounts = Variable([Account]()) let invites = Variable([TopicInvite]()) private let disposeBag = DisposeBag() // MARK: - Model ops func fetch(topicId: TopicID) { let s = TypetalkAPI.rx_sendRequest(GetTopicDetails(topicId: topicId)) s.subscribeNext { res in self.topic.value = res.topic self.teams.value = res.teams self.accounts.value = res.accounts self.invites.value = res.invites } .addDisposableTo(disposeBag) } func updateTopic(topicId: TopicID, name: String, teamId: TeamID?) -> Observable<UpdateTopic.Response> { return TypetalkAPI.rx_sendRequest(UpdateTopic(topicId: topicId, name: name, teamId: teamId)) } func deleteTopic(topicId: TopicID) -> Observable<DeleteTopic.Response> { return TypetalkAPI.rx_sendRequest(DeleteTopic(topicId: topicId)) } }
mit
4926edcd77fc67a63c26aecc005ccb5f
28.930233
107
0.675214
4.233553
false
false
false
false
mmoaay/MBMotion
MBMotion/Classes/Extension/UIView+Frame.swift
1
965
// // UIViewFrameExtension.swift // MBMotion // // Created by Perry on 15/9/11. // Copyright (c) 2015年 MmoaaY. All rights reserved. // import Foundation import UIKit extension UIView{ var x:CGFloat { get{ return frame.origin.x } set{ var f = frame f.origin.x = newValue frame = f } } var y:CGFloat { get{ return frame.origin.y } set{ var f = frame f.origin.y = newValue frame = f } } var width:CGFloat { get{ return frame.size.width } set{ var f = frame f.size.width = newValue frame = f } } var height:CGFloat { get{ return frame.size.height } set{ var f = frame f.size.height = newValue frame = f } } }
mit
cb1f142e98e32f277814652fb94fdcad
17.169811
52
0.433022
4.150862
false
false
false
false
masters3d/xswift
exercises/clock/Sources/ClockExample.swift
3
1288
import Foundation struct Clock: Equatable, CustomStringConvertible { var hours: Int var minutes: Int init(hours: Int, minutes: Int = 0) { self.hours = hours self.minutes = minutes normalize() } var description: String { return self.toString } func add(minutes: Int) -> Clock { return Clock(hours: self.hours, minutes: self.minutes + minutes) } func subtract(minutes: Int) -> Clock { return add(minutes: -minutes) } private var toString: String { let h = String(format: "%02d", self.hours) let m = String(format: "%02d", self.minutes) return h + ":" + m } private mutating func normalize() { if minutes >= 60 { self.hours += self.minutes / 60 self.minutes = self.minutes % 60 } while self.minutes < 0 { self.hours -= 1 self.minutes += 60 } if self.hours >= 24 { self.hours = self.hours % 24 } while self.hours < 0 { self.hours += 24 } } } private extension String { init(_ clock: Clock) { self = clock.description } } func == (lhs: Clock, rhs: Clock) -> Bool { return lhs.description == rhs.description }
mit
ef4f3ea7ad69f7377a8e8c10a95ed53c
21.206897
72
0.539596
4.101911
false
false
false
false
QuarkWorks/RealmModelGenerator
RealmModelGenerator/EntityDetailVC.swift
1
2247
// // EntityDetailVC.swift // RealmModelGenerator // // Created by Zhaolong Zhong on 3/28/16. // Copyright © 2016 QuarkWorks. All rights reserved. // import Cocoa class EntityDetailVC : NSViewController, EntityDetailViewDelegate, Observer { static let TAG = NSStringFromClass(EntityDetailVC.self) @IBOutlet weak var entityDetailView: EntityDetailView! { didSet { entityDetailView.delegate = self } } weak var entity:Entity? { didSet{ if oldValue === self.entity { return } oldValue?.observable.removeObserver(observer: self) self.entity?.observable.addObserver(observer: self) self.invalidateViews() } } var entityNameList:[String] = ["None"] // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() } func invalidateViews() { if !self.isViewLoaded || entity == nil { return } entityDetailView.name = entity!.name entityNameList = ["None"] self.entity?.model.entities.forEach{ (e) in entityNameList.append(e.name) } entityNameList.remove(at: entityNameList.index(of: self.entity!.name)!) entityDetailView.superClassNames = entityNameList if let superEntity = self.entity?.superEntity { entityDetailView.selectedItemIndex = entityNameList.index(of: superEntity.name)! } } // MARK: - Observer func onChange(observable: Observable) { self.invalidateViews() } // MARK: - EntityDetailView delegate func entityDetailView(entityDetailView: EntityDetailView, shouldChangeEntityName name: String) -> Bool { do { try self.entity!.setName(name: name) } catch { Tools.popupAlert(messageText: "Error", buttonTitle: "OK", informativeText: "Unable to rename entity: \(entity!.name) to: \(name). There is an entity with the same name.") return false } return true } func entityDetailView(entityDetailView: EntityDetailView, selectedSuperClassDidChange superEntity: String) { self.entity?.superEntity = self.entity?.model.entities.filter({$0.name == superEntity}).first } }
mit
189a8c88067168d7f999bd4d81abde0c
33.030303
182
0.64203
4.602459
false
false
false
false
trident10/TDMediaPicker
TDMediaPicker/Classes/View/CustomView/TDMediaPermissionView.swift
1
2164
// // TDMediaPermissionView.swift // ImagePicker // // Created by Abhimanu Jindal on 24/06/17. // Copyright © 2017 Abhimanu Jindal. All rights reserved. // import UIKit protocol TDMediaPermissionViewDelegate:class { func permissionViewSettingsButtonTapped(_ view: TDMediaPermissionView) func permissionViewCloseButtonTapped(_ view: TDMediaPermissionView) } class TDMediaPermissionView: TDMediaPickerView{ @IBOutlet var lblCaption: UILabel! @IBOutlet var btnSettings: UIButton! @IBOutlet var btnCancel: UIButton! weak var delegate:TDMediaPermissionViewDelegate? override func awakeFromNib() { } override func setupTheme() { } //MARK: - Public Method(s) func setupCustomView(view: TDConfigView){ let tempViewConfig = view as! TDConfigViewCustom let tempView = tempViewConfig.view tempView.frame = CGRect.init(x: 0, y: 0, width: tempView.frame.width, height: tempView.frame.height) self.addSubview(tempView) } func setupStandardView(view: TDConfigView){ let tempViewConfig = view as! TDConfigViewStandard self.backgroundColor = tempViewConfig.backgroundColor } func setupSettingsButton(buttonConfig: TDConfigButton){ TDMediaUtil.setupButton(btnSettings, buttonConfig: buttonConfig) } func setupCancelButton(buttonConfig: TDConfigButton){ TDMediaUtil.setupButton(btnCancel, buttonConfig: buttonConfig) } func setupCaptionLabel(_ config: TDConfigLabel){ TDMediaUtil.setupLabel(lblCaption, config: config) } func setupDefaultScreen(){ //setupTitleButtonConfig(config: TDConfigButtonText.init(normalColor: .white, normalTextConfig: TDConfigText.init(text: "Settings", textColor: .blue, textFont: UIFont.systemFont(ofSize: UIFont.systemFontSize)))) } //MARK: - Action Method(s) @IBAction func settingsButtonTapped(){ delegate?.permissionViewSettingsButtonTapped(self) } @IBAction func closeButtonTapped(){ delegate?.permissionViewCloseButtonTapped(self) } }
mit
d3209cdf053bdbf53a11c5aa8d30d8fd
28.630137
219
0.696718
4.764317
false
true
false
false
white-rabbit-apps/Fusuma
Sources/FSAlbumView.swift
1
20325
// // FSAlbumView.swift // Fusuma // // Created by Yuta Akizuki on 2015/11/14. // Copyright © 2015年 ytakzk. All rights reserved. // import UIKit import Photos @objc public protocol FSAlbumViewDelegate: class { func albumViewCameraRollUnauthorized() } final class FSAlbumView: UIView, UICollectionViewDataSource, UICollectionViewDelegate, PHPhotoLibraryChangeObserver, UIGestureRecognizerDelegate { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var imageCropView: FSImageCropView! @IBOutlet weak var imageCropViewContainer: UIView! @IBOutlet weak var collectionViewConstraintHeight: NSLayoutConstraint! @IBOutlet weak var imageCropViewConstraintTop: NSLayoutConstraint! weak var delegate: FSAlbumViewDelegate? = nil var selectedImageCreationDate: NSDate? = nil var images: PHFetchResult! var imageManager: PHCachingImageManager? var previousPreheatRect: CGRect = CGRectZero let cellSize = CGSize(width: 100, height: 100) // Variables for calculating the position enum Direction { case Scroll case Stop case Up case Down } let imageCropViewOriginalConstraintTop: CGFloat = 50 let imageCropViewMinimalVisibleHeight: CGFloat = 100 var dragDirection = Direction.Up var imaginaryCollectionViewOffsetStartPosY: CGFloat = 0.0 var cropBottomY: CGFloat = 0.0 var dragStartPos: CGPoint = CGPointZero let dragDiff: CGFloat = 20.0 static func instance() -> FSAlbumView { return UINib(nibName: "FSAlbumView", bundle: NSBundle(forClass: self.classForCoder())).instantiateWithOwner(self, options: nil)[0] as! FSAlbumView } func initialize() { if images != nil { return } self.hidden = false let panGesture = UIPanGestureRecognizer(target: self, action: #selector(FSAlbumView.panned(_:))) panGesture.delegate = self self.addGestureRecognizer(panGesture) collectionViewConstraintHeight.constant = self.frame.height - imageCropView.frame.height - imageCropViewOriginalConstraintTop imageCropViewConstraintTop.constant = 50 dragDirection = Direction.Up imageCropViewContainer.layer.shadowColor = UIColor.blackColor().CGColor imageCropViewContainer.layer.shadowRadius = 30.0 imageCropViewContainer.layer.shadowOpacity = 0.9 imageCropViewContainer.layer.shadowOffset = CGSizeZero collectionView.registerNib(UINib(nibName: "FSAlbumViewCell", bundle: NSBundle(forClass: self.classForCoder)), forCellWithReuseIdentifier: "FSAlbumViewCell") collectionView.backgroundColor = fusumaBackgroundColor // Never load photos Unless the user allows to access to photo album checkPhotoAuth() // Sorting condition let options = PHFetchOptions() options.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: false) ] images = PHAsset.fetchAssetsWithMediaType(.Image, options: options) if images.count > 0 { changeImage(images[0] as! PHAsset) self.selectedImageCreationDate = (images[0] as! PHAsset).creationDate collectionView.reloadData() collectionView.selectItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), animated: false, scrollPosition: UICollectionViewScrollPosition.None) } PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self) } deinit { if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.Authorized { PHPhotoLibrary.sharedPhotoLibrary().unregisterChangeObserver(self) } } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func panned(sender: UITapGestureRecognizer) { if sender.state == UIGestureRecognizerState.Began { let view = sender.view let loc = sender.locationInView(view) let subview = view?.hitTest(loc, withEvent: nil) if subview == imageCropView && imageCropViewConstraintTop.constant == imageCropViewOriginalConstraintTop { return } dragStartPos = sender.locationInView(self) cropBottomY = self.imageCropViewContainer.frame.origin.y + self.imageCropViewContainer.frame.height // Move if dragDirection == Direction.Stop { dragDirection = (imageCropViewConstraintTop.constant == imageCropViewOriginalConstraintTop) ? Direction.Up : Direction.Down } // Scroll event of CollectionView is preferred. if (dragDirection == Direction.Up && dragStartPos.y < cropBottomY + dragDiff) || (dragDirection == Direction.Down && dragStartPos.y > cropBottomY) { dragDirection = Direction.Stop imageCropView.changeScrollable(false) } else { imageCropView.changeScrollable(true) } } else if sender.state == UIGestureRecognizerState.Changed { let currentPos = sender.locationInView(self) if dragDirection == Direction.Up && currentPos.y < cropBottomY - dragDiff { imageCropViewConstraintTop.constant = max(imageCropViewMinimalVisibleHeight - self.imageCropViewContainer.frame.height, currentPos.y + dragDiff - imageCropViewContainer.frame.height) collectionViewConstraintHeight.constant = min(self.frame.height - imageCropViewMinimalVisibleHeight, self.frame.height - imageCropViewConstraintTop.constant - imageCropViewContainer.frame.height) } else if dragDirection == Direction.Down && currentPos.y > cropBottomY { imageCropViewConstraintTop.constant = min(imageCropViewOriginalConstraintTop, currentPos.y - imageCropViewContainer.frame.height) collectionViewConstraintHeight.constant = max(self.frame.height - imageCropViewOriginalConstraintTop - imageCropViewContainer.frame.height, self.frame.height - imageCropViewConstraintTop.constant - imageCropViewContainer.frame.height) } else if dragDirection == Direction.Stop && collectionView.contentOffset.y < 0 { dragDirection = Direction.Scroll imaginaryCollectionViewOffsetStartPosY = currentPos.y } else if dragDirection == Direction.Scroll { imageCropViewConstraintTop.constant = imageCropViewMinimalVisibleHeight - self.imageCropViewContainer.frame.height + currentPos.y - imaginaryCollectionViewOffsetStartPosY collectionViewConstraintHeight.constant = max(self.frame.height - imageCropViewOriginalConstraintTop - imageCropViewContainer.frame.height, self.frame.height - imageCropViewConstraintTop.constant - imageCropViewContainer.frame.height) } } else { imaginaryCollectionViewOffsetStartPosY = 0.0 if sender.state == UIGestureRecognizerState.Ended && dragDirection == Direction.Stop { imageCropView.changeScrollable(true) return } let currentPos = sender.locationInView(self) if currentPos.y < cropBottomY - dragDiff && imageCropViewConstraintTop.constant != imageCropViewOriginalConstraintTop { // The largest movement imageCropView.changeScrollable(false) imageCropViewConstraintTop.constant = imageCropViewMinimalVisibleHeight - self.imageCropViewContainer.frame.height collectionViewConstraintHeight.constant = self.frame.height - imageCropViewMinimalVisibleHeight UIView.animateWithDuration(0.3, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.layoutIfNeeded() }, completion: nil) dragDirection = Direction.Down } else { // Get back to the original position imageCropView.changeScrollable(true) imageCropViewConstraintTop.constant = imageCropViewOriginalConstraintTop collectionViewConstraintHeight.constant = self.frame.height - imageCropViewOriginalConstraintTop - imageCropViewContainer.frame.height UIView.animateWithDuration(0.3, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.layoutIfNeeded() }, completion: nil) dragDirection = Direction.Up } } } // MARK: - UICollectionViewDelegate Protocol func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("FSAlbumViewCell", forIndexPath: indexPath) as! FSAlbumViewCell let currentTag = cell.tag + 1 cell.tag = currentTag let asset = self.images[indexPath.item] as! PHAsset self.imageManager?.requestImageForAsset(asset, targetSize: cellSize, contentMode: .AspectFill, options: nil) { result, info in if cell.tag == currentTag { cell.image = result cell.creationDate = asset.creationDate } } return cell } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images == nil ? 0 : images.count } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let width = (collectionView.frame.width - 3) / 4 return CGSize(width: width, height: width) } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { changeImage(images[indexPath.row] as! PHAsset) imageCropView.changeScrollable(true) imageCropViewConstraintTop.constant = imageCropViewOriginalConstraintTop collectionViewConstraintHeight.constant = self.frame.height - imageCropViewOriginalConstraintTop - imageCropViewContainer.frame.height UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.layoutIfNeeded() }, completion: nil) dragDirection = Direction.Up collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Top, animated: true) } // MARK: - ScrollViewDelegate func scrollViewDidScroll(scrollView: UIScrollView) { if scrollView == collectionView { self.updateCachedAssets() } } //MARK: - PHPhotoLibraryChangeObserver func photoLibraryDidChange(changeInstance: PHChange) { dispatch_async(dispatch_get_main_queue()) { let collectionChanges = changeInstance.changeDetailsForFetchResult(self.images) if collectionChanges != nil { self.images = collectionChanges!.fetchResultAfterChanges let collectionView = self.collectionView! if !collectionChanges!.hasIncrementalChanges || collectionChanges!.hasMoves { collectionView.reloadData() } else { collectionView.performBatchUpdates({ let removedIndexes = collectionChanges!.removedIndexes if (removedIndexes?.count ?? 0) != 0 { collectionView.deleteItemsAtIndexPaths(removedIndexes!.aapl_indexPathsFromIndexesWithSection(0)) } let insertedIndexes = collectionChanges!.insertedIndexes if (insertedIndexes?.count ?? 0) != 0 { collectionView.insertItemsAtIndexPaths(insertedIndexes!.aapl_indexPathsFromIndexesWithSection(0)) } let changedIndexes = collectionChanges!.changedIndexes if (changedIndexes?.count ?? 0) != 0 { collectionView.reloadItemsAtIndexPaths(changedIndexes!.aapl_indexPathsFromIndexesWithSection(0)) } }, completion: nil) } self.resetCachedAssets() } } } } internal extension UICollectionView { func aapl_indexPathsForElementsInRect(rect: CGRect) -> [NSIndexPath] { let allLayoutAttributes = self.collectionViewLayout.layoutAttributesForElementsInRect(rect) if (allLayoutAttributes?.count ?? 0) == 0 {return []} var indexPaths: [NSIndexPath] = [] indexPaths.reserveCapacity(allLayoutAttributes!.count) for layoutAttributes in allLayoutAttributes! { let indexPath = layoutAttributes.indexPath indexPaths.append(indexPath) } return indexPaths } } internal extension NSIndexSet { func aapl_indexPathsFromIndexesWithSection(section: Int) -> [NSIndexPath] { var indexPaths: [NSIndexPath] = [] indexPaths.reserveCapacity(self.count) self.enumerateIndexesUsingBlock {idx, stop in indexPaths.append(NSIndexPath(forItem: idx, inSection: section)) } return indexPaths } } private extension FSAlbumView { func changeImage(asset: PHAsset) { self.imageCropView.image = nil dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { let options = PHImageRequestOptions() options.networkAccessAllowed = true self.imageManager?.requestImageForAsset(asset, targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight), contentMode: .AspectFill, options: options) { result, info in dispatch_async(dispatch_get_main_queue(), { self.imageCropView.imageSize = CGSize(width: asset.pixelWidth, height: asset.pixelHeight) self.imageCropView.image = result self.selectedImageCreationDate = asset.creationDate }) } }) } // Check the status of authorization for PHPhotoLibrary private func checkPhotoAuth() { PHPhotoLibrary.requestAuthorization { (status) -> Void in switch status { case .Authorized: self.imageManager = PHCachingImageManager() if self.images != nil && self.images.count > 0 { self.changeImage(self.images[0] as! PHAsset) } case .Restricted, .Denied: dispatch_async(dispatch_get_main_queue(), { () -> Void in self.delegate?.albumViewCameraRollUnauthorized() }) default: break } } } // MARK: - Asset Caching func resetCachedAssets() { imageManager?.stopCachingImagesForAllAssets() previousPreheatRect = CGRectZero } func updateCachedAssets() { var preheatRect = self.collectionView!.bounds preheatRect = CGRectInset(preheatRect, 0.0, -0.5 * CGRectGetHeight(preheatRect)) let delta = abs(CGRectGetMidY(preheatRect) - CGRectGetMidY(self.previousPreheatRect)) if delta > CGRectGetHeight(self.collectionView!.bounds) / 3.0 { var addedIndexPaths: [NSIndexPath] = [] var removedIndexPaths: [NSIndexPath] = [] self.computeDifferenceBetweenRect(self.previousPreheatRect, andRect: preheatRect, removedHandler: {removedRect in let indexPaths = self.collectionView.aapl_indexPathsForElementsInRect(removedRect) removedIndexPaths += indexPaths }, addedHandler: {addedRect in let indexPaths = self.collectionView.aapl_indexPathsForElementsInRect(addedRect) addedIndexPaths += indexPaths }) let assetsToStartCaching = self.assetsAtIndexPaths(addedIndexPaths) let assetsToStopCaching = self.assetsAtIndexPaths(removedIndexPaths) self.imageManager?.startCachingImagesForAssets(assetsToStartCaching, targetSize: cellSize, contentMode: .AspectFill, options: nil) self.imageManager?.stopCachingImagesForAssets(assetsToStopCaching, targetSize: cellSize, contentMode: .AspectFill, options: nil) self.previousPreheatRect = preheatRect } } func computeDifferenceBetweenRect(oldRect: CGRect, andRect newRect: CGRect, removedHandler: CGRect->Void, addedHandler: CGRect->Void) { if CGRectIntersectsRect(newRect, oldRect) { let oldMaxY = CGRectGetMaxY(oldRect) let oldMinY = CGRectGetMinY(oldRect) let newMaxY = CGRectGetMaxY(newRect) let newMinY = CGRectGetMinY(newRect) if newMaxY > oldMaxY { let rectToAdd = CGRectMake(newRect.origin.x, oldMaxY, newRect.size.width, (newMaxY - oldMaxY)) addedHandler(rectToAdd) } if oldMinY > newMinY { let rectToAdd = CGRectMake(newRect.origin.x, newMinY, newRect.size.width, (oldMinY - newMinY)) addedHandler(rectToAdd) } if newMaxY < oldMaxY { let rectToRemove = CGRectMake(newRect.origin.x, newMaxY, newRect.size.width, (oldMaxY - newMaxY)) removedHandler(rectToRemove) } if oldMinY < newMinY { let rectToRemove = CGRectMake(newRect.origin.x, oldMinY, newRect.size.width, (newMinY - oldMinY)) removedHandler(rectToRemove) } } else { addedHandler(newRect) removedHandler(oldRect) } } func assetsAtIndexPaths(indexPaths: [NSIndexPath]) -> [PHAsset] { if indexPaths.count == 0 { return [] } var assets: [PHAsset] = [] assets.reserveCapacity(indexPaths.count) for indexPath in indexPaths { let asset = self.images[indexPath.item] as! PHAsset assets.append(asset) } return assets } }
mit
a2bfb22dd843ddeacbd33c92d9a60547
39.243564
250
0.598563
6.549146
false
false
false
false
jessesquires/swift-proposal-analyzer
swift-proposal-analyzer.playground/Pages/SE-0128.xcplaygroundpage/Contents.swift
1
2292
/*: # Change failable UnicodeScalar initializers to failable * Proposal: [SE-0128](0128-unicodescalar-failable-initializer.md) * Author: [Xin Tong](https://github.com/trentxintong) * Review Manager: [Chris Lattner](http://github.com/lattner) * Status: **Implemented (Swift 3)** * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2016-July/000259.html) * Implementation: [apple/swift#3662](https://github.com/apple/swift/pull/3662) ## Introduction This proposal aims to change some `UnicodeScalar` initializers (ones that are non-failable) from non-failable to failable. i.e., in case a `UnicodeScalar` can not be constructed, nil is returned. ## Motivation Currently, when one passes an invalid value to the non-failable `UnicodeScalar` `UInt32` initializer, it crashes the program by calling `_precondition`. This is undesirable if one wishes to initialize a Unicode scalar from unknown input. ## Proposed solution Mark the non-failable `UnicodeScalar` initializers as failable and return nil when the integer is not a valid Unicode codepoint. Currently, the stdlib crashes the program by calling `_precondition` if the integer is not a valid Unicode codepoint. For example: ```swift var string = "" let codepoint: UInt32 = 55357 // this is invalid let ucode = UnicodeScalar(codepoint) // Program crashes at this point. string.append(ucode) ``` After marking the initializer as failable, users can write code like this and the program will execute fine even if the codepoint isn't valid. ```swift var string = "" let codepoint: UInt32 = 55357 // this is invalid if let ucode = UnicodeScalar(codepoint) { string.append(ucode) } else { // do something else } ``` ## Impact on existing code The initializers are now failable, returning an optional, so optional unwrapping is necessary. The API changes include: ```swift public struct UnicodeScalar { - public init(_ value: UInt32) + public init?(_ value: UInt32) - public init(_ value: UInt16) + public init?(_ value: UInt16) - public init(_ value: Int) + public init?(_ value: Int) } ``` ## Alternatives considered Leave status quo and force the users to do input checks before trying to initialize a `UnicodeScalar`. ---------- [Previous](@previous) | [Next](@next) */
mit
5e4a28deb9785a086bed59cb04c609f1
29.157895
128
0.744328
3.871622
false
false
false
false
hooman/swift
stdlib/public/core/Diffing.swift
4
12216
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2015 - 2019 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 // //===----------------------------------------------------------------------===// // MARK: Diff application to RangeReplaceableCollection @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension CollectionDifference { fileprivate func _fastEnumeratedApply( _ consume: (Change) throws -> Void ) rethrows { let totalRemoves = removals.count let totalInserts = insertions.count var enumeratedRemoves = 0 var enumeratedInserts = 0 while enumeratedRemoves < totalRemoves || enumeratedInserts < totalInserts { let change: Change if enumeratedRemoves < removals.count && enumeratedInserts < insertions.count { let removeOffset = removals[enumeratedRemoves]._offset let insertOffset = insertions[enumeratedInserts]._offset if removeOffset - enumeratedRemoves <= insertOffset - enumeratedInserts { change = removals[enumeratedRemoves] } else { change = insertions[enumeratedInserts] } } else if enumeratedRemoves < totalRemoves { change = removals[enumeratedRemoves] } else if enumeratedInserts < totalInserts { change = insertions[enumeratedInserts] } else { // Not reached, loop should have exited. preconditionFailure() } try consume(change) switch change { case .remove(_, _, _): enumeratedRemoves += 1 case .insert(_, _, _): enumeratedInserts += 1 } } } } // Error type allows the use of throw to unroll state on application failure private enum _ApplicationError : Error { case failed } extension RangeReplaceableCollection { /// Applies the given difference to this collection. /// /// - Parameter difference: The difference to be applied. /// /// - Returns: An instance representing the state of the receiver with the /// difference applied, or `nil` if the difference is incompatible with /// the receiver's state. /// /// - Complexity: O(*n* + *c*), where *n* is `self.count` and *c* is the /// number of changes contained by the parameter. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func applying(_ difference: CollectionDifference<Element>) -> Self? { func append( into target: inout Self, contentsOf source: Self, from index: inout Self.Index, count: Int ) throws { let start = index if !source.formIndex(&index, offsetBy: count, limitedBy: source.endIndex) { throw _ApplicationError.failed } target.append(contentsOf: source[start..<index]) } var result = Self() do { var enumeratedRemoves = 0 var enumeratedInserts = 0 var enumeratedOriginals = 0 var currentIndex = self.startIndex try difference._fastEnumeratedApply { change in switch change { case .remove(offset: let offset, element: _, associatedWith: _): let origCount = offset - enumeratedOriginals try append(into: &result, contentsOf: self, from: &currentIndex, count: origCount) if currentIndex == self.endIndex { // Removing nonexistent element off the end of the collection throw _ApplicationError.failed } enumeratedOriginals += origCount + 1 // Removal consumes an original element currentIndex = self.index(after: currentIndex) enumeratedRemoves += 1 case .insert(offset: let offset, element: let element, associatedWith: _): let origCount = (offset + enumeratedRemoves - enumeratedInserts) - enumeratedOriginals try append(into: &result, contentsOf: self, from: &currentIndex, count: origCount) result.append(element) enumeratedOriginals += origCount enumeratedInserts += 1 } _internalInvariant(enumeratedOriginals <= self.count) } if currentIndex < self.endIndex { result.append(contentsOf: self[currentIndex...]) } _internalInvariant(result.count == self.count + enumeratedInserts - enumeratedRemoves) } catch { return nil } return result } } // MARK: Definition of API extension BidirectionalCollection { /// Returns the difference needed to produce this collection's ordered /// elements from the given collection, using the given predicate as an /// equivalence test. /// /// This function does not infer element moves. If you need to infer moves, /// call the `inferringMoves()` method on the resulting difference. /// /// - Parameters: /// - other: The base state. /// - areEquivalent: A closure that returns a Boolean value indicating /// whether two elements are equivalent. /// /// - Returns: The difference needed to produce the receiver's state from /// the parameter's state. /// /// - Complexity: Worst case performance is O(*n* * *m*), where *n* is the /// count of this collection and *m* is `other.count`. You can expect /// faster execution when the collections share many common elements. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func difference<C: BidirectionalCollection>( from other: C, by areEquivalent: (C.Element, Element) -> Bool ) -> CollectionDifference<Element> where C.Element == Self.Element { return _myers(from: other, to: self, using: areEquivalent) } } extension BidirectionalCollection where Element: Equatable { /// Returns the difference needed to produce this collection's ordered /// elements from the given collection. /// /// This function does not infer element moves. If you need to infer moves, /// call the `inferringMoves()` method on the resulting difference. /// /// - Parameters: /// - other: The base state. /// /// - Returns: The difference needed to produce this collection's ordered /// elements from the given collection. /// /// - Complexity: Worst case performance is O(*n* * *m*), where *n* is the /// count of this collection and *m* is `other.count`. You can expect /// faster execution when the collections share many common elements, or /// if `Element` conforms to `Hashable`. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func difference<C: BidirectionalCollection>( from other: C ) -> CollectionDifference<Element> where C.Element == Self.Element { return difference(from: other, by: ==) } } // MARK: Internal implementation // _V is a rudimentary type made to represent the rows of the triangular matrix // type used by the Myer's algorithm. // // This type is basically an array that only supports indexes in the set // `stride(from: -d, through: d, by: 2)` where `d` is the depth of this row in // the matrix `d` is always known at allocation-time, and is used to preallocate // the structure. private struct _V { private var a: [Int] #if INTERNAL_CHECKS_ENABLED private let isOdd: Bool #endif // The way negative indexes are implemented is by interleaving them in the empty slots between the valid positive indexes @inline(__always) private static func transform(_ index: Int) -> Int { // -3, -1, 1, 3 -> 3, 1, 0, 2 -> 0...3 // -2, 0, 2 -> 2, 0, 1 -> 0...2 return (index <= 0 ? -index : index &- 1) } init(maxIndex largest: Int) { #if INTERNAL_CHECKS_ENABLED _internalInvariant(largest >= 0) isOdd = largest % 2 == 1 #endif a = [Int](repeating: 0, count: largest + 1) } subscript(index: Int) -> Int { get { #if INTERNAL_CHECKS_ENABLED _internalInvariant(isOdd == (index % 2 != 0)) #endif return a[_V.transform(index)] } set(newValue) { #if INTERNAL_CHECKS_ENABLED _internalInvariant(isOdd == (index % 2 != 0)) #endif a[_V.transform(index)] = newValue } } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) private func _myers<C,D>( from old: C, to new: D, using cmp: (C.Element, D.Element) -> Bool ) -> CollectionDifference<C.Element> where C: BidirectionalCollection, D: BidirectionalCollection, C.Element == D.Element { // Core implementation of the algorithm described at http://www.xmailserver.org/diff2.pdf // Variable names match those used in the paper as closely as possible func _descent(from a: UnsafeBufferPointer<C.Element>, to b: UnsafeBufferPointer<D.Element>) -> [_V] { let n = a.count let m = b.count let max = n + m var result = [_V]() var v = _V(maxIndex: 1) v[1] = 0 var x = 0 var y = 0 iterator: for d in 0...max { let prev_v = v result.append(v) v = _V(maxIndex: d) // The code in this loop is _very_ hot—the loop bounds increases in terms // of the iterator of the outer loop! for k in stride(from: -d, through: d, by: 2) { if k == -d { x = prev_v[k &+ 1] } else { let km = prev_v[k &- 1] if k != d { let kp = prev_v[k &+ 1] if km < kp { x = kp } else { x = km &+ 1 } } else { x = km &+ 1 } } y = x &- k while x < n && y < m { if !cmp(a[x], b[y]) { break; } x &+= 1 y &+= 1 } v[k] = x if x >= n && y >= m { break iterator } } if x >= n && y >= m { break } } _internalInvariant(x >= n && y >= m) return result } // Backtrack through the trace generated by the Myers descent to produce the changes that make up the diff func _formChanges( from a: UnsafeBufferPointer<C.Element>, to b: UnsafeBufferPointer<C.Element>, using trace: [_V] ) -> [CollectionDifference<C.Element>.Change] { var changes = [CollectionDifference<C.Element>.Change]() changes.reserveCapacity(trace.count) var x = a.count var y = b.count for d in stride(from: trace.count &- 1, to: 0, by: -1) { let v = trace[d] let k = x &- y let prev_k = (k == -d || (k != d && v[k &- 1] < v[k &+ 1])) ? k &+ 1 : k &- 1 let prev_x = v[prev_k] let prev_y = prev_x &- prev_k while x > prev_x && y > prev_y { // No change at this position. x &-= 1 y &-= 1 } _internalInvariant((x == prev_x && y > prev_y) || (y == prev_y && x > prev_x)) if y != prev_y { changes.append(.insert(offset: prev_y, element: b[prev_y], associatedWith: nil)) } else { changes.append(.remove(offset: prev_x, element: a[prev_x], associatedWith: nil)) } x = prev_x y = prev_y } return changes } /* Splatting the collections into contiguous storage has two advantages: * * 1) Subscript access is much faster * 2) Subscript index becomes Int, matching the iterator types in the algorithm * * Combined, these effects dramatically improves performance when * collections differ significantly, without unduly degrading runtime when * the parameters are very similar. * * In terms of memory use, the linear cost of creating a ContiguousArray (when * necessary) is significantly less than the worst-case n² memory use of the * descent algorithm. */ func _withContiguousStorage<C: Collection, R>( for values: C, _ body: (UnsafeBufferPointer<C.Element>) throws -> R ) rethrows -> R { if let result = try values.withContiguousStorageIfAvailable(body) { return result } let array = ContiguousArray(values) return try array.withUnsafeBufferPointer(body) } return _withContiguousStorage(for: old) { a in return _withContiguousStorage(for: new) { b in return CollectionDifference(_formChanges(from: a, to: b, using:_descent(from: a, to: b)))! } } }
apache-2.0
a9c4667dca2e95b3835a850236df014d
32.368852
123
0.620241
4.14
false
false
false
false
chrisamanse/UsbongKit
UsbongKit/Usbong/UsbongTree/UsbongTree+NodeProvider.swift
2
1829
// // UsbongTree+NodeProvider.swift // UsbongKit // // Created by Chris Amanse on 1/1/16. // Copyright © 2016 Usbong Social Systems, Inc. All rights reserved. // import Foundation // Conform `UsbongTree` to `NodeProvider` extension UsbongTree: NodeProvider { public var nextNodeIsAvailable: Bool { guard let name = nextTaskNodeName else { return false } return nodeIndexerAndTypeWithName(name) != nil } public var previousNodeIsAvailable: Bool { return taskNodeNames.count > 1 } @discardableResult public func transitionToNextNode() -> Bool { let transitionName = currentTargetTransitionName guard let nextTaskNodeName = currentTransitionInfo[transitionName] else { return false } // Create UsbongNodeState (before generating a new node) let state = UsbongNodeState(transitionName: transitionName, node: currentNode, type: currentTaskNodeType) // Make current node to next task node currentNode = nodeWithName(nextTaskNodeName) // Append task node name to array taskNodeNames.append(nextTaskNodeName) // Append state to array usbongNodeStates.append(state) return true } @discardableResult public func transitionToPreviousNode() -> Bool { if previousNodeIsAvailable { // Remove last state from array usbongNodeStates.removeLast() // Remove last task node name from array taskNodeNames.removeLast() // Reload current task node based on taskNodeNames array reloadCurrentTaskNode() return true } return false } }
apache-2.0
7640d51393cdf8b36c2f7eae041f0050
28.015873
113
0.615427
5.149296
false
false
false
false