repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
EurekaCommunity/GooglePlacesRow
Sources/GPTableViewCell.swift
1
1132
// // GPTableViewCell.swift // GooglePlacesRow // // Created by Mathias Claassen on 4/14/16. // // import Foundation import GooglePlaces import Eureka public protocol EurekaGooglePlacesTableViewCell { func setTitle(_ prediction: GMSAutocompletePrediction) } /// Default cell for the table of the GooglePlacesTableCell open class GPTableViewCell: UITableViewCell, EurekaGooglePlacesTableViewCell { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) initialize() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } func initialize() { textLabel?.font = UIFont.systemFont(ofSize: 16) textLabel?.minimumScaleFactor = 0.8 textLabel?.adjustsFontSizeToFitWidth = true textLabel?.textColor = UIColor.blue contentView.backgroundColor = UIColor.white } open func setTitle(_ prediction: GMSAutocompletePrediction) { textLabel?.text = prediction.attributedFullText.string } }
mit
jovito-royeca/Decktracker
ios/old/Decktracker/View/Card Details/CardImageTableViewCell.swift
1
511
// // CardImageTableViewCell.swift // Decktracker // // Created by Jovit Royeca on 8/10/15. // Copyright (c) 2015 Jovito Royeca. All rights reserved. // import UIKit class CardImageTableViewCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
apache-2.0
mleiv/IBIncludedStoryboard
IBIncludedWrapperViewController.swift
2
9490
// // IBIncludedWrapperViewController.swift // // Copyright 2015 Emily Ivie // Licensed under The MIT License // For full copyright and license information, please see http://opensource.org/licenses/MIT // Redistributions of files must retain the above copyright notice. // import UIKit //MARK: IBIncludedSegueableController protocol public typealias PrepareAfterIBIncludedSegueType = (UIViewController) -> Bool /** Protocol to identify nested IBIncluded{Thing} view controllers that need to share data during prepareForSegue. Note: This is not a default protocol applied to all IBIncluded{Thing} - you have to apply it individually to nibs/storyboards that are sharing data. */ @objc public protocol IBIncludedSegueableController { /// Run code before segueing away or prepare for segue to a non-IBIncluded{Thing} page. /// Do not use to share data (see prepareAfterIBIncludedSegue for that). /// - parameter segue: The segue object containing information about the view controllers involved in the segue. See [prepareForSegue documentation](https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/occ/instm/UIViewController/prepareForSegue:sender:) /// - parameter sender: The object that initiated the segue. You might use this parameter to perform different actions based on which control (or other object) initiated the segue. See [prepareForSegue documentation](https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/occ/instm/UIViewController/prepareForSegue:sender:) /// - returns: `true` if function has finished its work and can be deleted, `false` if it did not find the controller it is looking for yet. optional func prepareBeforeIBIncludedSegue(segue: UIStoryboardSegue, sender: AnyObject?) -> Bool /// Check the destination view controller type and share data if it is what you want. optional var prepareAfterIBIncludedSegue: PrepareAfterIBIncludedSegueType { get set } } //MARK: IBIncludedWrapperViewController definition /** Forwards any prepareForSegue behavior between nested IBIncluded{Thing} view controllers. Runs for all nested IBIncludedWrapperViewControllers, so you can have some pretty intricately-nested levels of stroyboards/nibs and they can still share data, so long as a segue is involved. Assign this class to all IBIncluded{Thing} placeholder/wrapper view controllers involved at any level in sharing data between controllers. */ public class IBIncludedWrapperViewController: UIViewController, IBIncludedSegueableWrapper { internal var includedViewControllers = [IBIncludedSegueableController]() internal var prepareAfterSegueClosures:[PrepareAfterIBIncludedSegueType] = [] /** Forward any segues to the saved included view controllers. (Also, save any of their prepareAfterIBIncludedSegue closures for the destination to process -after- IBIncluded{Thing} is included.) Can handle scenarios where one half of the segue in an IBIncluded{Thing} but the other half isn't. */ override public func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { //super.prepareForSegue(segue, sender: sender) //doesn't help propogate up the segue forwardToParentControllers(segue, sender: sender) // forward for pre-segue preparations: for includedController in includedViewControllers { includedController.prepareBeforeIBIncludedSegue?(segue, sender: sender) } // save/share post-segue closures for later execution: // skip any navigation/tab controllers if let destinationController = activeViewController(segue.destinationViewController) { tryToApplyClosures(destinationController) } prepareAfterSegueClosures = [] // we are done, clean up any lingering controllers in case we have ARC issues // NOTE: you may not want this if you are doing very delayed prepareAfterSegue stuff (like, delayed until after a segue to another page and coming back), but I have seen no ill effects myself. } public func tryToApplyClosures(destinationController: UIViewController?) { if let includedDestination = destinationController as? IBIncludedWrapperViewController { // check self for any seguable closures (if we aren't IBIncluded{Thing} but are segueing to one): if let selfSegue = self as? IBIncludedSegueableController, let closure = selfSegue.prepareAfterIBIncludedSegue { includedDestination.prepareAfterSegueClosures.append(closure) } // check all seguable closures now: for includedController in includedViewControllers { if let closure = includedController.prepareAfterIBIncludedSegue { includedDestination.prepareAfterSegueClosures.append(closure) } } if includedDestination is IBIncludedSegueableController { // it's a seguable controller also, so run all seguable closures now: for includedController in includedViewControllers { if let closure = includedController.prepareAfterIBIncludedSegue { closure(destinationController!) //nil already tested above } } } // execute now on top-level destination (if we are segueing from IBIncluded{Thing} to something that is not): } else if destinationController != nil { // check self for any seguable closures (if we aren't IBIncluded{Thing} but are segueing to one): if let selfSegue = self as? IBIncludedSegueableController { if let closure = selfSegue.prepareAfterIBIncludedSegue { closure(destinationController!) } } // check all seguable closures now: for includedController in includedViewControllers { if let closure = includedController.prepareAfterIBIncludedSegue { closure(destinationController!) } } } } /** Save any included view controllers that may need segue handling later. */ public func addIncludedViewController(viewController: UIViewController) { // skip any navigation/tab controllers if let newController = activeViewController(viewController) where newController != viewController { return addIncludedViewController(newController) } // only save segue-handling controllers if let includedController = viewController as? IBIncludedSegueableController { includedViewControllers.append(includedController) } // try running saved segue closures, delete any that are marked finished prepareAfterSegueClosures = prepareAfterSegueClosures.filter { closure in let finished = closure(viewController) return !finished } } public func addClosure(newClosure: PrepareAfterIBIncludedSegueType) { prepareAfterSegueClosures.append(newClosure) } public func resetClosures() { prepareAfterSegueClosures = [] } /** Propogates the segue up to parent IBIncludedWrapperViewControllers so they can also run the prepareAfterIBIncludedSegue() on their included things. Since any IBIncluded{Thing} attaches to all IBIncludedWrapperViewControllers in the hierarchy, I am not sure why this is required, but I know the prior version didn't work in some heavily-nested scenarios without this addition. :param: controller (optional) view controller to start looking under, defaults to window's rootViewController :returns: an (optional) view controller */ private func forwardToParentControllers(segue: UIStoryboardSegue, sender: AnyObject?) { var currentController = self as UIViewController while let controller = currentController.parentViewController { if let wrapperController = controller as? IBIncludedWrapperViewController { wrapperController.prepareForSegue(segue, sender: sender) break //wrapperController will do further parents } currentController = controller } } /** Locates the top-most view controller that is under the tab/nav controllers :param: controller (optional) view controller to start looking under, defaults to window's rootViewController :returns: an (optional) view controller */ private func activeViewController(controller: UIViewController!) -> UIViewController? { if controller == nil { return nil } if let tabController = controller as? UITabBarController, let nextController = tabController.selectedViewController { return activeViewController(nextController) } else if let navController = controller as? UINavigationController, let nextController = navController.visibleViewController { return activeViewController(nextController) } else if let nextController = controller.presentedViewController { return activeViewController(nextController) } return controller } }
mit
boolkybear/SwiftAsyncGraph
AsyncGraphDemo/AsyncGraphDemoTests/AsyncGraphDemoTests.swift
1
7467
// // AsyncGraphDemoTests.swift // AsyncGraphDemoTests // // Created by Boolky Bear on 2/12/14. // Copyright (c) 2014 ByBDesigns. All rights reserved. // import UIKit import XCTest struct NodeIdentifier { let identifier: String let tag: Int? init (_ identifier: String, _ tag: Int? = nil) { self.identifier = identifier self.tag = tag } func toString() -> String { let tagStr = self.tag.map { "\($0)" } ?? "null" return "\(self.identifier) - \(tagStr)" } var hashValue: Int { return self.toString().hashValue } } func == (lhs: NodeIdentifier, rhs: NodeIdentifier) -> Bool { return lhs.identifier == rhs.identifier && lhs.tag == rhs.tag } class AsyncGraphDemoTests: 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() } // func testExample() { // // This is an example of a functional test case. // XCTAssert(true, "Pass") // } // // func testPerformanceExample() { // // This is an example of a performance test case. // self.measureBlock() { // // Put the code you want to measure the time of here. // } // } func testNodeIdentifiers() { let node1nil = NodeIdentifier("one") let node1tag = NodeIdentifier("one", 1) let node2nil = NodeIdentifier("two") let node2tag = NodeIdentifier("two", 1) let other1nil = NodeIdentifier("one") let other1tag1 = NodeIdentifier("one", 1) let other1tag2 = NodeIdentifier("one", 2) XCTAssertFalse(node1nil == node1tag, "Nodes with different tags should not be equal") XCTAssertFalse(node1nil == node2nil, "Nodes with different identifiers should not be equal") XCTAssertFalse(node1tag == node2tag, "Nodes with different identifiers should not be equal, even tag is equal") XCTAssert(node1nil == other1nil, "Nodes with same identifier and same tag should be equal") XCTAssert(node1tag == other1tag1, "Nodes with same identifier and same tag should be equal") XCTAssertFalse(node1tag == other1tag2, "Nodes with different tags should not be equal, even identifier is equal") } func testTwoIndependentItems() { let times: [ String : NSTimeInterval ] = [ "first" : 0.5, "second" : 1.0, ] var finishOrder = [String]() AsyncGraph<String, Void> { nodeIdentifier, operation, graph in NSThread.sleepForTimeInterval(NSTimeInterval(times[nodeIdentifier]!)) finishOrder.append(nodeIdentifier) } .addNodeWithIdentifier("first") .addNodeWithIdentifier("second") .processSynchronous() XCTAssertEqual(finishOrder, [ "first", "second" ], "Finish order should be first, second") } func testTwoDependentItems() { let times: [ String : NSTimeInterval ] = [ "first" : 0.5, "second" : 1.0, ] var finishOrder = [String]() AsyncGraph<String, Void> { nodeIdentifier, operation, graph in NSThread.sleepForTimeInterval(NSTimeInterval(times[nodeIdentifier]!)) finishOrder.append(nodeIdentifier) } .addNodeWithIdentifier("first") .addNodeWithIdentifier("second") .addDependencyFrom("second", to: "first") .processSynchronous() XCTAssertEqual(finishOrder, [ "first", "second" ], "Finish order should be first, second") } func testTwoDependentItemsReversed() { let times: [ String : NSTimeInterval ] = [ "first" : 0.5, "second" : 1.0, ] var finishOrder = [String]() AsyncGraph<String, Void> { nodeIdentifier, operation, graph in NSThread.sleepForTimeInterval(NSTimeInterval(times[nodeIdentifier]!)) finishOrder.append(nodeIdentifier) } .addNodeWithIdentifier("first") .addNodeWithIdentifier("second") .addDependencyFrom("first", to: "second") .processSynchronous() XCTAssertEqual(finishOrder, [ "second", "first" ], "Finish order should be second, first") } func testAsyncOperationGraph() { let graph = AsyncGraph<String, String?>() var result = [ String ]() graph.addNodeWithIdentifier("5") { identifier, operation, graph in NSThread.sleepForTimeInterval(5.0) result.append(identifier) return nil }.addNodeWithIdentifier("3") { identifier, operation, graph in NSThread.sleepForTimeInterval(3.0) result.append(identifier) return nil }.processSynchronous() let resultString = result.joinWithSeparator("#") XCTAssert(resultString == "3#5") } func testAsyncOperationGraphWithDependencies() { let graphWithDependencies = AsyncGraph<String, String?>() var resultWithDependencies = [ String ]() graphWithDependencies.addNodeWithIdentifier("5") { identifier, operation, graph in NSThread.sleepForTimeInterval(5.0) resultWithDependencies.append(identifier) return nil }.addNodeWithIdentifier("3") { identifier, operation, graph in NSThread.sleepForTimeInterval(3.0) resultWithDependencies.append(identifier) return nil }.addDependencyFrom("3", to: "5") .processSynchronous() let resultWithDependenciesString = resultWithDependencies.joinWithSeparator("#") XCTAssert(resultWithDependenciesString == "5#3") } func testAsyncOperationGraphDefault() { var resultDefault = [ String ]() let graphWithDefault = AsyncGraph<String, Void> { identifier, operation, graph in let timeInterval = NSTimeInterval(Int(identifier) ?? 0) NSThread.sleepForTimeInterval(timeInterval) resultDefault.append(identifier) } graphWithDefault.addNodeWithIdentifier("5") .addNodeWithIdentifier("3") .processSynchronous() let resultDefaultString = resultDefault.joinWithSeparator("#") XCTAssert(resultDefaultString == "3#5") } func testAsyncOperationHooks() { let graph = AsyncGraph<Int, String> { identifier, operation, graph in NSThread.sleepForTimeInterval(NSTimeInterval(identifier)) return "\(identifier)" } var isCompleted = false var before = 0 var after = 0 let expectation = expectationWithDescription("Test graph") graph.addNodeWithIdentifier(3) .addNodeWithIdentifier(5) .addHook { graph in expectation.fulfill() isCompleted = true } .addHookBefore(3) { identifier, operation, graph in before += identifier } .addHookAfter(5) { identifier, operation, graph in after -= identifier } .process() waitForExpectationsWithTimeout(10) { (error) in XCTAssertNil(error, "\(error)") } XCTAssert(isCompleted, "Graph has not been completed") XCTAssert(graph.resultFrom(3) == "3") XCTAssert(graph.resultFrom(5) == "5") XCTAssert(graph.status == .Processed) XCTAssert(before == 3) XCTAssert(after == -5) } func testCancel() { let graph = AsyncGraph<Int, String> { identifier, operation, graph in NSThread.sleepForTimeInterval(NSTimeInterval(identifier)) return "\(identifier)" } let expectation = expectationWithDescription("Test graph") graph.addNodeWithIdentifier(3) .addHook { graph in expectation.fulfill() } .process() graph.cancel() waitForExpectationsWithTimeout(10) { (error) in XCTAssertNil(error, "\(error)") } XCTAssert(graph.status == .Cancelled) } }
mit
Antondomashnev/Sourcery
SourceryTests/Stub/Performance-Code/Kiosk/App/Models/BuyersPremium.swift
4
454
import UIKit import SwiftyJSON final class BuyersPremium: NSObject, JSONAbleType { let id: String let name: String init(id: String, name: String) { self.id = id self.name = name } static func fromJSON(_ json: [String: Any]) -> BuyersPremium { let json = JSON(json) let id = json["id"].stringValue let name = json["name"].stringValue return BuyersPremium(id: id, name: name) } }
mit
designatednerd/GoCubs
SharedUITestFiles/DateFormatter+Months.swift
1
693
// // DateFormatter+Months.swift // GoCubs // // Created by Ellen Shapiro on 2/20/17. // Copyright © 2017 Designated Nerd Software. All rights reserved. // import Foundation extension DateFormatter { private static let cub_simpleFormatter = DateFormatter() static func cub_shortMonthName(for monthInt: Int) -> String { guard monthInt <= 12, monthInt >= 1 else { fatalError("This is not a month") } guard let shortMonths = self.cub_simpleFormatter.shortMonthSymbols else { fatalError("Could not access short month symbols") } return shortMonths[monthInt - 1] } }
mit
RxSwiftCommunity/RxRealm
Tests/RxRealmTests/RxRealmOnQueueTests.swift
1
1419
// // RxRealmOnQueueTests.swift // RxRealm_Tests // // Created by Anton Nazarov on 18.05.2020. // Copyright © 2020 CocoaPods. All rights reserved. // import RealmSwift import RxSwift import XCTest final class RxRealmOnQueueTests: XCTestCase { let allTests = [ "testCollectionOnQueue": testCollectionOnQueue, "testArrayOnQueue": testArrayOnQueue, "testChangesetOnQueue": testChangesetOnQueue ] func testCollectionOnQueue() { verifyObservableEmitOnBackground { Observable.collection(from: $0, synchronousStart: false, on: DispatchQueue(label: #function)) } } func testArrayOnQueue() { verifyObservableEmitOnBackground { Observable.array(from: $0, synchronousStart: false, on: DispatchQueue(label: #function)) } } func testChangesetOnQueue() { verifyObservableEmitOnBackground { Observable.changeset(from: $0, synchronousStart: false, on: DispatchQueue(label: #function)) } } private func verifyObservableEmitOnBackground<Element>(factory: (Results<UniqueObject>) -> Observable<Element>) { let realm = realmInMemory() DispatchQueue.main.async { try! realm.write { realm.add(UniqueObject(1)) } } let dispatchedOnMainTread = try! factory(realm.objects(UniqueObject.self)) .map { _ in Thread.isMainThread } .toBlocking(timeout: 2) .first() XCTAssertFalse(dispatchedOnMainTread!) } }
mit
parrotbait/CorkWeather
CorkWeather/Source/UI/Localisation/LocalisedButton.swift
1
1834
// // LocalisedButton.swift // CorkWeather // // Created by Eddie Long on 09/01/2019. // Copyright © 2019 eddielong. All rights reserved. // import Foundation import UIKit @IBDesignable public class LocalisedButton : UIButton { @IBInspectable public var normalText : String = "" @IBInspectable public var highlightText : String = "" @IBInspectable public var disabledText : String = "" @IBInspectable public var selectedText : String = "" @IBInspectable public var focusedText : String = "" open override func layoutSubviews() { super.layoutSubviews() syncWithIB() } func syncWithIB() { guard let localisedBundle = LanguageSelectorView.getBundle(object: self) else { return } if !self.normalText.isEmpty { let ret = localisedBundle.localizedString(forKey: self.normalText, value: "", table: nil) setTitle(ret, for: .normal) } if !self.highlightText.isEmpty { let ret = localisedBundle.localizedString(forKey: self.highlightText, value: "", table: nil) setTitle(ret, for: .highlighted) } if !self.disabledText.isEmpty { let ret = localisedBundle.localizedString(forKey: self.disabledText, value: "", table: nil) setTitle(ret, for: .disabled) } if !self.selectedText.isEmpty { let ret = localisedBundle.localizedString(forKey: self.selectedText, value: "", table: nil) setTitle(ret, for: .selected) } if !self.focusedText.isEmpty { let ret = localisedBundle.localizedString(forKey: self.focusedText, value: "", table: nil) if #available(iOS 9.0, *) { setTitle(ret, for: .focused) } } } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/05495-swift-nominaltypedecl-getdeclaredtypeincontext.swift
11
444
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class d<j : f { func a<T where g: T>: String = c : d where f class d: A") class B<U : d where f: d where g: d where g<I : c: String = c { } struct A { } class d: d where g: c: String = c { var f: c: A") struct g: B func f: a { } class d<j : d where T> : A") protocol A : d w
mit
eurofurence/ef-app_ios
Packages/EurofurenceApplication/Tests/EurofurenceApplicationTests/Application/Components/News/Test Doubles/CapturingTableViewMediatorDelegate.swift
1
271
import EurofurenceApplication class CapturingTableViewMediatorDelegate: TableViewMediatorDelegate { private(set) var contentsDidChange = false func dataSourceContentsDidChange(_ dataSource: TableViewMediator) { contentsDidChange = true } }
mit
austinzheng/swift-compiler-crashes
fixed/27574-llvm-foldingset-swift-tupletype-nodeequals.swift
4
228
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var f{var d={func c{let g{enum S{func a{func b{func b{{e=S
mit
CatchChat/Yep
Yep/ViewControllers/Login/LoginVerifyMobileViewController.swift
1
7758
// // LoginVerifyMobileViewController.swift // Yep // // Created by NIX on 15/3/17. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit import YepNetworking import YepKit import Ruler import RxSwift import RxCocoa final class LoginVerifyMobileViewController: UIViewController { var mobile: String! var areaCode: String! private lazy var disposeBag = DisposeBag() @IBOutlet private weak var verifyMobileNumberPromptLabel: UILabel! @IBOutlet private weak var verifyMobileNumberPromptLabelTopConstraint: NSLayoutConstraint! @IBOutlet private weak var phoneNumberLabel: UILabel! @IBOutlet private weak var verifyCodeTextField: BorderTextField! @IBOutlet private weak var verifyCodeTextFieldTopConstraint: NSLayoutConstraint! @IBOutlet private weak var callMePromptLabel: UILabel! @IBOutlet private weak var callMeButton: UIButton! @IBOutlet private weak var callMeButtonTopConstraint: NSLayoutConstraint! private lazy var nextButton: UIBarButtonItem = { let button = UIBarButtonItem() button.title = NSLocalizedString("Next", comment: "") button.rx_tap .subscribeNext({ [weak self] in self?.login() }) .addDisposableTo(self.disposeBag) return button }() private lazy var callMeTimer: NSTimer = { let timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(LoginVerifyMobileViewController.tryCallMe(_:)), userInfo: nil, repeats: true) return timer }() private var haveAppropriateInput = false { didSet { nextButton.enabled = haveAppropriateInput if (oldValue != haveAppropriateInput) && haveAppropriateInput { login() } } } private var callMeInSeconds = YepConfig.callMeInSeconds() deinit { callMeTimer.invalidate() NSNotificationCenter.defaultCenter().removeObserver(self) println("deinit LoginVerifyMobile") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.yepViewBackgroundColor() navigationItem.titleView = NavigationTitleLabel(title: NSLocalizedString("Login", comment: "")) navigationItem.rightBarButtonItem = nextButton NSNotificationCenter.defaultCenter() .rx_notification(AppDelegate.Notification.applicationDidBecomeActive) .subscribeNext({ [weak self] _ in self?.verifyCodeTextField.becomeFirstResponder() }) .addDisposableTo(disposeBag) verifyMobileNumberPromptLabel.text = NSLocalizedString("Input verification code sent to", comment: "") phoneNumberLabel.text = "+" + areaCode + " " + mobile verifyCodeTextField.placeholder = " " verifyCodeTextField.backgroundColor = UIColor.whiteColor() verifyCodeTextField.textColor = UIColor.yepInputTextColor() verifyCodeTextField.rx_text .map({ $0.characters.count == YepConfig.verifyCodeLength() }) .subscribeNext({ [weak self] in self?.haveAppropriateInput = $0 }) .addDisposableTo(disposeBag) callMePromptLabel.text = NSLocalizedString("Didn't get it?", comment: "") callMeButton.setTitle(String.trans_buttonCallMe, forState: .Normal) verifyMobileNumberPromptLabelTopConstraint.constant = Ruler.iPhoneVertical(30, 50, 60, 60).value verifyCodeTextFieldTopConstraint.constant = Ruler.iPhoneVertical(30, 40, 50, 50).value callMeButtonTopConstraint.constant = Ruler.iPhoneVertical(10, 20, 40, 40).value } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) nextButton.enabled = false callMeButton.enabled = false } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) verifyCodeTextField.becomeFirstResponder() callMeTimer.fire() } // MARK: Actions @objc private func tryCallMe(timer: NSTimer) { if !haveAppropriateInput { if callMeInSeconds > 1 { let callMeInSecondsString = String.trans_buttonCallMe + " (\(callMeInSeconds))" UIView.performWithoutAnimation { [weak self] in self?.callMeButton.setTitle(callMeInSecondsString, forState: .Normal) self?.callMeButton.layoutIfNeeded() } } else { UIView.performWithoutAnimation { [weak self] in self?.callMeButton.setTitle(String.trans_buttonCallMe, forState: .Normal) self?.callMeButton.layoutIfNeeded() } callMeButton.enabled = true } } if (callMeInSeconds > 1) { callMeInSeconds -= 1 } } @IBAction private func callMe(sender: UIButton) { callMeTimer.invalidate() UIView.performWithoutAnimation { [weak self] in self?.callMeButton.setTitle(String.trans_buttonCalling, forState: .Normal) self?.callMeButton.layoutIfNeeded() self?.callMeButton.enabled = false } delay(10) { UIView.performWithoutAnimation { [weak self] in self?.callMeButton.setTitle(String.trans_buttonCallMe, forState: .Normal) self?.callMeButton.layoutIfNeeded() self?.callMeButton.enabled = true } } sendVerifyCodeOfMobile(mobile, withAreaCode: areaCode, useMethod: .Call, failureHandler: { reason, errorMessage in defaultFailureHandler(reason: reason, errorMessage: errorMessage) if let errorMessage = errorMessage { YepAlert.alertSorry(message: errorMessage, inViewController: self) SafeDispatch.async { UIView.performWithoutAnimation { [weak self] in self?.callMeButton.setTitle(String.trans_buttonCallMe, forState: .Normal) self?.callMeButton.layoutIfNeeded() self?.callMeButton.enabled = true } } } }, completion: { success in println("resendVoiceVerifyCode \(success)") }) } private func login() { view.endEditing(true) guard let verifyCode = verifyCodeTextField.text else { return } YepHUD.showActivityIndicator() loginByMobile(mobile, withAreaCode: areaCode, verifyCode: verifyCode, failureHandler: { [weak self] (reason, errorMessage) in defaultFailureHandler(reason: reason, errorMessage: errorMessage) YepHUD.hideActivityIndicator() if let errorMessage = errorMessage { SafeDispatch.async { self?.nextButton.enabled = false } YepAlert.alertSorry(message: errorMessage, inViewController: self, withDismissAction: { SafeDispatch.async { self?.verifyCodeTextField.text = nil self?.verifyCodeTextField.becomeFirstResponder() } }) } }, completion: { loginUser in println("loginUser: \(loginUser)") YepHUD.hideActivityIndicator() SafeDispatch.async { saveTokenAndUserInfoOfLoginUser(loginUser) syncMyInfoAndDoFurtherAction { } if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { appDelegate.startMainStory() } } }) } }
mit
aporat/NSData-APNSToken
Source/APNSToken.swift
1
859
// // Copyright 2011-2015 Adar Porat (https://github.com/aporat) // // 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 extension Data { public func apnsToken() -> String { var token: String = "" for i in 0 ..< self.count { token += String(format: "%02.2hhx", self[i] as CVarArg) } return token } }
mit
eonil/BTree
Tests/BTreeTests/BridgedListTests.swift
2
3108
// // BridgedListTests.swift // BTree // // Created by Károly Lőrentey on 2016-09-20. // Copyright © 2016–2017 Károly Lőrentey. // import XCTest @testable import BTree @objc internal class Foo: NSObject { var value: Int init(_ value: Int) { self.value = value super.init() } } class BridgedListTests: XCTestCase { #if Debug let count = 5_000 // Make sure this is larger than the default tree order to get full code coverage #else let count = 100_000 #endif func testLeaks() { weak var test: Foo? = nil do { let list = List((0 ..< count).lazy.map { Foo($0) }) let arrayView = list.arrayView test = arrayView.object(at: 0) as? Foo XCTAssertNotNil(test) } XCTAssertNil(test) } func testCopy() { let list = List((0 ..< count).lazy.map { Foo($0) }) let arrayView = list.arrayView let copy = arrayView.copy(with: nil) as AnyObject XCTAssertTrue(arrayView === copy) } func testArrayBaseline() { let array = (0 ..< count).map { Foo($0) as Any } measure { var i = 0 for member in array { guard let foo = member as? Foo else { XCTFail(); break } XCTAssertEqual(foo.value, i) i += 1 } XCTAssertEqual(i, self.count) } } func testListBaseline() { let list = List((0 ..< count).lazy.map { Foo($0) as Any }) measure { var i = 0 for member in list { guard let foo = member as? Foo else { XCTFail(); break } XCTAssertEqual(foo.value, i) i += 1 } XCTAssertEqual(i, self.count) } } func testFastEnumeration() { let list = List((0 ..< count).lazy.map { Foo($0) }) measure { let arrayView = list.arrayView var i = 0 for member in arrayView { guard let foo = member as? Foo else { XCTFail(); break } XCTAssertEqual(foo.value, i) i += 1 } XCTAssertEqual(i, self.count) } } func testObjectEnumerator() { let list = List((0 ..< count).lazy.map { Foo($0) }) measure { let arrayView = list.arrayView let enumerator = arrayView.objectEnumerator() var i = 0 while let member = enumerator.nextObject() { guard let foo = member as? Foo else { XCTFail(); break } XCTAssertEqual(foo.value, i) i += 1 } XCTAssertEqual(i, self.count) } } func testIndexing() { let list = List((0 ..< count).lazy.map { Foo($0) }) measure { let arrayView = list.arrayView for i in 0 ..< arrayView.count { guard let foo = arrayView.object(at: i) as? Foo else { XCTFail(); break } XCTAssertEqual(foo.value, i) } } } }
mit
everald/JetPack
Sources/Experimental/TypeInstanceDictionary.swift
2
2018
public struct TypeInstanceDictionary { fileprivate var instances = [ObjectIdentifier : Any]() public init() {} // Be very careful to not call this method with an Optional or an ImplicitlyUnwrappedOptional type. Use `as` in this case to convert the instance type to a non-optional first. public mutating func assign<T>(_ instance: T) { assign(instance, toType: T.self) } public mutating func assign<T>(_ instance: T, toType type: T.Type) { let id = ObjectIdentifier(type) if let existingInstance = instances[id] { fatalError("Cannot assign instance \(instance) to type \(type) because instance \(existingInstance) is already assigned") } instances[id] = instance } // Be very careful to not call this method with an Optional or an ImplicitlyUnwrappedOptional type. Use `as` in this case to expect the returned instance to be a non-optional. public func get<T>() -> T? { return get(T.self) } public func get<T>(_ type: T.Type) -> T? { let id = ObjectIdentifier(type) return instances[id] as! T? } // Be very careful to not call this method with an Optional or an ImplicitlyUnwrappedOptional type. Use `as` in this case to expect the returned instance to be a non-optional. public func require<T>() -> T { return require(T.self) } public func require<T>(_ type: T.Type) -> T { guard let instance = get(type) else { fatalError("No instance was assigned to type \(type).") } return instance } // Be very careful to not call this method with an Optional or an ImplicitlyUnwrappedOptional type. Use `as` in this case to convert the instance type to a non-optional first. public mutating func unassign<T>(_ type: T.Type) -> T? { let id = ObjectIdentifier(type) return instances.removeValue(forKey: id) as! T? } } prefix operator <? prefix operator <! public prefix func <? <T>(dictionary: TypeInstanceDictionary) -> T? { return dictionary.get() } public prefix func <! <T>(dictionary: TypeInstanceDictionary) -> T { return dictionary.require() }
mit
incetro/NIO
Example/NioExample-iOS/Models/Plain/PositionPlainObject.swift
1
950
// // PositionPlainObject.swift // Nio // // Created by incetro on 15/07/2017. // // import NIO import Transformer // MARK: - PositionPlainObject class PositionPlainObject: TransformablePlain { var nioID: NioID { return NioID(value: id) } let id: Int64 let name: String let price: Double init(with name: String, price: Double, id: Int64) { self.name = name self.id = id self.price = price } var category: CategoryPlainObject? = nil var additives: [AdditivePlainObject] = [] required init(with resolver: Resolver) throws { self.id = try resolver.value("id") self.name = try resolver.value("name") self.price = try resolver.value("price") self.category = try? resolver.value("category") self.additives = (try? resolver.value("additives")) ?? [] } }
mit
laszlokorte/reform-swift
ReformCore/ReformCore/Scaler.swift
1
268
// // Scaler.swift // ReformCore // // Created by Laszlo Korte on 13.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // import ReformMath public protocol Scaler { func scale<R:Runtime>(_ runtime : R, factor: Double, fix: Vec2d, axis: Vec2d) }
mit
codefellows/sea-b19-ios
Projects/CoreDataMusic/CoreDataMusic/ViewController.swift
1
5970
// // ViewController.swift // CoreDataMusic // // Created by Bradley Johnson on 8/19/14. // Copyright (c) 2014 learnswift. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate, NSFetchedResultsControllerDelegate { var myContext : NSManagedObjectContext! var labels = [Label]() @IBOutlet weak var tableView: UITableView! var fetchedResultsController : NSFetchedResultsController! override func viewDidLoad() { super.viewDidLoad() var appDelegate = UIApplication.sharedApplication().delegate as AppDelegate self.myContext = appDelegate.managedObjectContext self.setupFetchedResultsController() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) var error : NSError? fetchedResultsController?.performFetch(&error) if error != nil { println(error?.localizedDescription) } } func setupFetchedResultsController() { let fetchRequest = NSFetchRequest(entityName: "Label") let sort = NSSortDescriptor(key: "name", ascending: false) fetchRequest.sortDescriptors = [sort] fetchRequest.fetchBatchSize = 25 self.fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.myContext, sectionNameKeyPath: nil, cacheName: nil) self.fetchedResultsController.delegate = self } @IBAction func addLabelPressed(sender: AnyObject) { self.performSegueWithIdentifier("addLabel", sender: self) } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return self.fetchedResultsController!.sections[section].numberOfObjects } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell = tableView.dequeueReusableCellWithIdentifier("LabelCell", forIndexPath: indexPath) as UITableViewCell self.configureCell(cell, forIndexPath: indexPath) return cell } override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { if segue.identifier == "addLabel" { let addLabelVC = segue.destinationViewController as AddLabelViewController } else if segue.identifier == "ShowArtists" { let artistsVC = segue.destinationViewController as ArtistsViewController var labelForRow = self.fetchedResultsController.fetchedObjects[self.tableView.indexPathForSelectedRow().row] as Label artistsVC.selectedLabel = labelForRow } } //MARK: NSFetchedResultsControllerDelegate Methods func controllerWillChangeContent(controller: NSFetchedResultsController!) { self.tableView.beginUpdates() } func controller(controller: NSFetchedResultsController!, didChangeSection sectionInfo: NSFetchedResultsSectionInfo!, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) case .Delete: self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) default: self.tableView.reloadSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) } } func configureCell(cell: UITableViewCell, forIndexPath indexPath: NSIndexPath) { var labelForRow = self.fetchedResultsController.fetchedObjects[indexPath.row] as Label cell.textLabel.text = labelForRow.name } func controller(controller: NSFetchedResultsController!, didChangeObject anObject: AnyObject!, atIndexPath indexPath: NSIndexPath!, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath!) { switch type { case .Insert: self.tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade) case .Delete: self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) case .Update: self.configureCell(self.tableView.cellForRowAtIndexPath(indexPath), forIndexPath: indexPath) case .Move: self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) self.tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade) } } func controllerDidChangeContent(controller: NSFetchedResultsController!) { self.tableView.endUpdates() } //MARK: Table View Re-Ordering func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) { // don't need anything here, just have to implement it for the respondsToSelector test } func tableView(tableView: UITableView!, editActionsForRowAtIndexPath indexPath: NSIndexPath!) -> [AnyObject]! { let deleteAction = UITableViewRowAction(style: .Default, title: "Delete") { (action, indexPath) -> Void in println("Delete Action") if let labelForRow = self.fetchedResultsController.fetchedObjects[indexPath.row] as? Label { self.myContext.deleteObject(labelForRow) } } deleteAction.backgroundColor = UIColor.redColor() let editAction = UITableViewRowAction(style: .Default, title: "Edit") { (action, indexPath) -> Void in println("Edit Action") let cell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell } editAction.backgroundColor = UIColor.lightGrayColor() return [deleteAction, editAction] } }
gpl-2.0
worchyld/EYPlayground
Factories.swift
1
3425
// // Factories.swift // EYGens // // Created by Amarjit on 15/12/2016. // Copyright © 2016 Amarjit. All rights reserved. // import Foundation class Factory : NSObject { var generation : Generation var suitColor: SuitColor var active : Bool = false var willObselete : Bool = false var shouldObselete : Bool = false override var description: String { return ( "\(suitColor) \(generation.rawValue)" ) } init(suitColor:SuitColor, gen:Generation, active:Bool? = false) { self.generation = gen self.suitColor = suitColor self.active = active! } } var allFactories = [ Factory.init(suitColor: .Green, gen: .First, active: true), Factory.init(suitColor: .Red, gen: .First), Factory.init(suitColor: .Yellow, gen: .First), Factory.init(suitColor: .Blue, gen: .First), Factory.init(suitColor: .Green, gen: .Second, active: true), Factory.init(suitColor: .Red, gen: .Second), Factory.init(suitColor: .Yellow, gen: .Second), Factory.init(suitColor: .Green, gen: .Third), Factory.init(suitColor: .Blue, gen: .Second), Factory.init(suitColor: .Red, gen: .Second), Factory.init(suitColor: .Green, gen: .Fourth), Factory.init(suitColor: .Yellow, gen: .Third), Factory.init(suitColor: .Red, gen: .Third), Factory.init(suitColor: .Green, gen: .Fifth) ] func printAllFactories() { for (index, train) in allFactories.enumerated() { print (index, train.description) } } class Maker { let greenReport = Reporting().activeGreen let redReport = Reporting().activeRed let blueReport = Reporting().activeBlue let yellowReport = Reporting().activeYellow func runner() { print ("Assume 5 player game") print ("REPORT") print ("Greens = \(greenReport)") print ("Red = \(redReport)") print ("Blue = \(blueReport)") print ("Yellow = \(yellowReport)") print ("----") // Generations check print ("Generations check for green") if (greenReport == 0) { print ("No generation exists, nothing is done for this type") } else if (greenReport == 1) { print ("1 generation exists, check max dice") var _ = allFactories.filter{ (f : Factory) -> Bool in return (f.suitColor == .Green && f.active && f.generation == .First )}.first // // Max dice check // if (firstTrain!.salesDicePool.count < firstTrain!.dicePoolCapacity) { // print ("This train has not reached capacity \(firstTrain!.salesDicePool.count) vs \(firstTrain!.dicePoolCapacity)") // // firstTrain!.addOrder(toPool: .Sales) // } // else { // print ("This train has reached capacity") // } // // // Re-roll all sales dice and transfer all dice back to orders // firstTrain!.transferAllDiceBackToOrders() } else if (greenReport == 2) { print ("2 generations exist, go to older lower gen and start transfers. Check newer gen for max dice") } else if (greenReport == 3) { print ("3 generations exist, obselete the very oldest gen. Go up the chain and check for max dice") } else { print ("Nothing happens") } } }
gpl-3.0
KyoheiG3/RxSwift
Tests/RxCocoaTests/UISegmentedControl+RxTests.swift
1
873
// // UISegmentedControl+RxTests.swift // Tests // // Created by Krunoslav Zaher on 11/26/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import Foundation import RxCocoa import RxSwift import RxTest import XCTest class UISegmentedControlTests: RxTest { } extension UISegmentedControlTests { func testSegmentedControl_ValueCompletesOnDealloc() { let createView: () -> UISegmentedControl = { UISegmentedControl(items: ["a", "b", "c"]) } ensurePropertyDeallocated(createView, 1) { (view: UISegmentedControl) in view.rx.value } } func testSegmentedControl_SelectedSegmentIndexCompletesOnDealloc() { let createView: () -> UISegmentedControl = { UISegmentedControl(items: ["a", "b", "c"]) } ensurePropertyDeallocated(createView, 1) { (view: UISegmentedControl) in view.rx.selectedSegmentIndex } } }
mit
siuying/SwiftyDispatch
Classes/Queue.swift
1
4661
// // Dispatch.swift // BlueWhale2 // // Created by Chan Fai Chong on 14/8/15. // Copyright © 2015 Ignition Soft. All rights reserved. // import Foundation public struct Queue { public let queue : dispatch_queue_t public enum QueueType { case Serial case Concurrent var value : dispatch_queue_attr_t? { get { switch self { case .Serial: return DISPATCH_QUEUE_SERIAL case .Concurrent: return DISPATCH_QUEUE_CONCURRENT } } } } public enum Priority : Int { case Background case Default case High case Low var value : Int { get { switch self { case .Background: return DISPATCH_QUEUE_PRIORITY_BACKGROUND case .Default: return DISPATCH_QUEUE_PRIORITY_DEFAULT case .High: return DISPATCH_QUEUE_PRIORITY_HIGH case .Low: return DISPATCH_QUEUE_PRIORITY_LOW } } } } public enum QOS : UInt { case UserInteractive case UserInitiated case Default case Utility case Background var value : qos_class_t { get { switch self { case .UserInteractive: return QOS_CLASS_USER_INTERACTIVE case .UserInitiated: return QOS_CLASS_USER_INITIATED case .Default: return QOS_CLASS_DEFAULT case .Utility: return QOS_CLASS_UTILITY case .Background: return QOS_CLASS_BACKGROUND } } } } public var label : String { get { return String.fromCString(dispatch_queue_get_label(queue))! } } /// Create a Queue object with a dispatch_queue_t /// /// - Parameter queue: underlying dispatch_queue_t object public init(queue: dispatch_queue_t) { self.queue = queue } /// Create a Queue with label and type /// /// - Parameter label: label of the queue /// - Parameter type: Type of the queue (QueueType) public init(_ label: String, _ type: QueueType = .Serial) { self.queue = dispatch_queue_create(label, type.value) } /// Run a block asynchronously /// /// - Parameter block: The block to run public func async(block: dispatch_block_t) { dispatch_async(self.queue, block) } /// Set Target Queue of current queue, using QoS public func setTargetQoS(qos: Queue.QOS) { dispatch_set_target_queue(self.queue, dispatch_get_global_queue(qos.value, 0)) } /// Set Target Queue of current queue, using priority public func setTargetPriority(priority: Queue.Priority) { dispatch_set_target_queue(self.queue, dispatch_get_global_queue(priority.value, 0)) } /// Run a block synchronously /// /// - Parameter block: The block to run public func sync(block: dispatch_block_t) { dispatch_sync(self.queue, block) } /// Submits a block to run for multiple times. /// /// - Parameter iterations: Number of iterations /// - Parameter block: The block to run public func apply(iterations: Int, block: (Int) -> Void) { dispatch_apply(iterations, queue, block) } /// Schedule a block at a specified time. /// /// - Parameter delayInSeconds: Delay in number of seconds /// - Parameter block: The block to run public func after(delayInSeconds: Double, block: dispatch_block_t) { let nanoSeconds = Int64(Double(NSEC_PER_SEC) * delayInSeconds) let delayTime = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds) dispatch_after(delayTime, queue, block) } /// Returns the default queue that is bound to the main thread. public static func main() -> Queue { return Queue(queue: dispatch_get_main_queue()) } /// Returns a global queue by QOS /// - Parameter qos: the QOS of the queue public static func concurrent(qos: Queue.QOS) -> Queue { return Queue(queue: dispatch_get_global_queue(qos.value, 0)) } /// Returns a global queue by Priotity /// - Parameter priority: the priority of the queue public static func concurrent(priority priority: Queue.Priority) -> Queue { return Queue(queue: dispatch_get_global_queue(priority.value, 0)) } }
mit
Ben21hao/edx-app-ios-enterprise-new
Source/DiscussionHelper.swift
1
5090
// // DiscussionHelper.swift // edX // // Created by Saeed Bashir on 2/18/16. // Copyright © 2016 edX. All rights reserved. // import Foundation class DiscussionHelper: NSObject { class func updateEndorsedTitle(thread: DiscussionThread, label: UILabel, textStyle: OEXTextStyle) { let endorsedIcon = Icon.Answered.attributedTextWithStyle(textStyle, inline : true) switch thread.type { case .Question: let endorsedText = textStyle.attributedStringWithText(Strings.answer) label.attributedText = NSAttributedString.joinInNaturalLayout([endorsedIcon,endorsedText]) case .Discussion: let endorsedText = textStyle.attributedStringWithText(Strings.endorsed) label.attributedText = NSAttributedString.joinInNaturalLayout([endorsedIcon,endorsedText]) } } class func messageForError(error: NSError?) -> String { if let error = error where error.oex_isNoInternetConnectionError { return Strings.networkNotAvailableMessageTrouble } else { return Strings.unknownError } } class func showErrorMessage(controller: UIViewController?, error: NSError?) { let controller = controller ?? UIApplication.sharedApplication().keyWindow?.rootViewController if let error = error where error.oex_isNoInternetConnectionError { UIAlertController().showAlertWithTitle(Strings.networkNotAvailableTitle, message: Strings.networkNotAvailableMessageTrouble, onViewController: controller ?? UIViewController()) } else { controller?.showOverlayMessage(Strings.unknownError) } } class func styleAuthorProfileImageView(imageView: UIImageView) { dispatch_async(dispatch_get_main_queue(),{ imageView.layer.cornerRadius = imageView.bounds.size.width / 2 imageView.layer.borderWidth = 1 imageView.layer.borderColor = OEXStyles.sharedStyles().primaryBaseColor().CGColor imageView.clipsToBounds = true imageView.layer.masksToBounds = true }) } class func profileImage(hasProfileImage: Bool, imageURL: String?) ->RemoteImage { let placeholder = UIImage(named: "profilePhotoPlaceholder") if let URL = imageURL where hasProfileImage { return RemoteImageImpl(url: URL, networkManager: OEXRouter.sharedRouter().environment.networkManager, placeholder: placeholder, persist: true) } else { return RemoteImageJustImage(image: placeholder) } } class func styleAuthorDetails(author: String?, authorLabel: String?, createdAt: NSDate?, hasProfileImage: Bool, imageURL: String?, authoNameLabel: UILabel, dateLabel: UILabel, authorButton: UIButton, imageView: UIImageView, viewController: UIViewController, router: OEXRouter?) { let textStyle = OEXTextStyle(weight:.Normal, size:.Base, color: OEXStyles.sharedStyles().neutralXDark()) // formate author name let highlightStyle = OEXMutableTextStyle(textStyle: textStyle) if let _ = author where OEXConfig.sharedConfig().profilesEnabled { highlightStyle.color = OEXStyles.sharedStyles().primaryBaseColor() highlightStyle.weight = .Bold } else { highlightStyle.color = OEXStyles.sharedStyles().neutralXDark() highlightStyle.weight = textStyle.weight } let authorName = highlightStyle.attributedStringWithText(author ?? Strings.anonymous.oex_lowercaseStringInCurrentLocale()) var attributedStrings = [NSAttributedString]() attributedStrings.append(authorName) if let authorLabel = authorLabel { attributedStrings.append(textStyle.attributedStringWithText(Strings.parenthesis(text: authorLabel))) } let formattedAuthorName = NSAttributedString.joinInNaturalLayout(attributedStrings) authoNameLabel.attributedText = formattedAuthorName if let createdAt = createdAt { dateLabel.attributedText = textStyle.attributedStringWithText(createdAt.displayDate) } let profilesEnabled = OEXConfig.sharedConfig().profilesEnabled authorButton.enabled = profilesEnabled if let author = author where profilesEnabled { authorButton.oex_removeAllActions() authorButton.oex_addAction({ [weak viewController] _ in router?.showProfileForUsername(viewController, username: author ?? Strings.anonymous, editable: false) }, forEvents: .TouchUpInside) } else { // if post is by anonymous user then disable author button (navigating to user profile) authorButton.enabled = false } authorButton.isAccessibilityElement = authorButton.enabled imageView.remoteImage = profileImage(hasProfileImage, imageURL: imageURL) } }
apache-2.0
leizh007/HiPDA
HiPDA/HiPDA/Sections/Me/MyThreads/MyThreadsBaseTableViewModel.swift
1
2930
// // MyThreadsBaseTableViewModel.swift // HiPDA // // Created by leizh007 on 2017/7/9. // Copyright © 2017年 HiPDA. All rights reserved. // import Foundation import RxSwift class MyThreadsBaseTableViewModel { var disposeBag = DisposeBag() var models = [MyThreadsBaseModel]() var page = 1 var maxPage = 1 var hasData: Bool { return models.count > 0 } var hasMoreData: Bool { return page < maxPage } func numberOfItems() -> Int { return models.count } func loadFirstPage(completion: @escaping (HiPDA.Result<Void, NSError>) -> Void) { self.page = 1 let page = 1 load(page: page) { [weak self] result in guard let `self` = self, page == `self`.page else { return } switch result { case let .success((models: models, maxPage: maxPage)): self.models = models self.maxPage = maxPage completion(.success(())) case let .failure(error): completion(.failure(error)) } } } func loadNextPage(completion: @escaping (HiPDA.Result<Void, NSError>) -> Void) { self.page += 1 let page = self.page load(page: page) { [weak self] result in guard let `self` = self, page == `self`.page else { return } switch result { case let .success((models: models, maxPage: maxPage)): self.models.append(contentsOf: models) self.maxPage = maxPage completion(.success(())) case let .failure(error): completion(.failure(error)) } } } func transform(html: String) throws -> [MyThreadsBaseModel] { fatalError("Must be overrided!") } func api(at page: Int) -> HiPDA.API { fatalError("Must be overrided!") } fileprivate func load(page: Int, completion: @escaping (HiPDA.Result<(models: [MyThreadsBaseModel], maxPage: Int), NSError>) -> Void) { disposeBag = DisposeBag() let transform = self.transform HiPDAProvider.request(self.api(at: page)) .observeOn(ConcurrentDispatchQueueScheduler(qos: .userInteractive)) .mapGBKString() .map { (try transform($0), try HtmlParser.totalPage(from: $0)) } .observeOn(MainScheduler.instance) .subscribe { event in switch event { case .next(let (models, maxPage)): completion(.success((models: models, maxPage: maxPage))) case .error(let error): completion(.failure(error as NSError)) default: break } }.disposed(by: disposeBag) } func jumpURL(at index: Int) -> String { fatalError("Must be overrided!") } }
mit
catloafsoft/AudioKit
AudioKit/OSX/AudioKit/Playgrounds/Helpers/AKPeakLimiterWindow.swift
1
4759
// // AKPeakLimiterWindow.swift // AudioKit // // Autogenerated by scripts by Aurelius Prochazka. Do not edit directly. // Copyright (c) 2015 Aurelius Prochazka. All rights reserved. // import Foundation import Cocoa /// A Window to control AKPeakLimiter in Playgrounds public class AKPeakLimiterWindow: NSWindow { private let windowWidth = 400 private let padding = 30 private let sliderHeight = 20 private let numberOfComponents = 3 /// Slider to control attackTime public let attackTimeSlider: NSSlider /// Slider to control decayTime public let decayTimeSlider: NSSlider /// Slider to control preGain public let preGainSlider: NSSlider private let attackTimeTextField: NSTextField private let decayTimeTextField: NSTextField private let preGainTextField: NSTextField private var peakLimiter: AKPeakLimiter /// Initiate the AKPeakLimiter window public init(_ control: AKPeakLimiter) { peakLimiter = control let sliderWidth = windowWidth - 2 * padding attackTimeSlider = newSlider(sliderWidth) decayTimeSlider = newSlider(sliderWidth) preGainSlider = newSlider(sliderWidth) attackTimeTextField = newTextField(sliderWidth) decayTimeTextField = newTextField(sliderWidth) preGainTextField = newTextField(sliderWidth) let titleHeightApproximation = 50 let windowHeight = padding * 2 + titleHeightApproximation + numberOfComponents * 3 * sliderHeight super.init(contentRect: NSRect(x: padding, y: padding, width: windowWidth, height: windowHeight), styleMask: NSTitledWindowMask, backing: .Buffered, `defer`: false) self.hasShadow = true self.styleMask = NSBorderlessWindowMask | NSResizableWindowMask self.movableByWindowBackground = true self.level = 7 self.title = "AKPeakLimiter" let viewRect = NSRect(x: 0, y: 0, width: windowWidth, height: windowHeight) let view = NSView(frame: viewRect) let topTitle = NSTextField() topTitle.stringValue = "AKPeakLimiter" topTitle.editable = false topTitle.drawsBackground = false topTitle.bezeled = false topTitle.alignment = NSCenterTextAlignment topTitle.font = NSFont(name: "Lucida Grande", size: 24) topTitle.sizeToFit() topTitle.frame.origin.x = CGFloat(windowWidth / 2) - topTitle.frame.width / 2 topTitle.frame.origin.y = CGFloat(windowHeight - padding) - topTitle.frame.height view.addSubview(topTitle) makeTextField(attackTimeTextField, view: view, below: topTitle, distance: 2, stringValue: "Attack Time: \(peakLimiter.attackTime) Secs") makeSlider(attackTimeSlider, view: view, below: topTitle, distance: 3, target: self, action: "updateAttacktime", currentValue: peakLimiter.attackTime, minimumValue: 0.001, maximumValue: 0.03) makeTextField(decayTimeTextField, view: view, below: topTitle, distance: 5, stringValue: "Decay Time: \(peakLimiter.decayTime) Secs") makeSlider(decayTimeSlider, view: view, below: topTitle, distance: 6, target: self, action: "updateDecaytime", currentValue: peakLimiter.decayTime, minimumValue: 0.001, maximumValue: 0.06) makeTextField(preGainTextField, view: view, below: topTitle, distance: 8, stringValue: "Pre Gain: \(peakLimiter.preGain) dB") makeSlider(preGainSlider, view: view, below: topTitle, distance: 9, target: self, action: "updatePregain", currentValue: peakLimiter.preGain, minimumValue: -40, maximumValue: 40) self.contentView!.addSubview(view) self.makeKeyAndOrderFront(nil) } internal func updateAttacktime() { peakLimiter.attackTime = attackTimeSlider.doubleValue attackTimeTextField.stringValue = "Attack Time \(String(format: "%0.4f", peakLimiter.attackTime)) Secs" } internal func updateDecaytime() { peakLimiter.decayTime = decayTimeSlider.doubleValue decayTimeTextField.stringValue = "Decay Time \(String(format: "%0.4f", peakLimiter.decayTime)) Secs" } internal func updatePregain() { peakLimiter.preGain = preGainSlider.doubleValue preGainTextField.stringValue = "Pre Gain \(String(format: "%0.4f", peakLimiter.preGain)) dB" } /// Required initializer required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
ProfileCreator/ProfileCreator
ProfileCreator/ProfileCreator/Preferences Window Views/PreferencesViewElements.swift
1
80329
// // PreferencesViewElements.swift // ProfileCreator // // Created by Erik Berglund. // Copyright © 2018 Erik Berglund. All rights reserved. // import Cocoa public func addSeparator(toView: NSView, lastSubview: NSView?, height: inout CGFloat, topIndent: CGFloat?, constraints: inout [NSLayoutConstraint], sender: Any? = nil) -> NSView? { // --------------------------------------------------------------------- // Create and add vertical separator // --------------------------------------------------------------------- let separator = NSBox(frame: NSRect(x: 250.0, y: 15.0, width: kPreferencesWindowWidth - (20.0 * 2), height: 250.0)) separator.translatesAutoresizingMaskIntoConstraints = false separator.boxType = .separator toView.addSubview(separator) // --------------------------------------------------------------------- // Add Constraints // --------------------------------------------------------------------- // Top var constantTop: CGFloat if let topIndentValue = topIndent { constantTop = topIndentValue } else if sender is ProfileExportAccessoryView { constantTop = 6.0 } else { constantTop = 8.0 } constraints.append(NSLayoutConstraint(item: separator, attribute: .top, relatedBy: .equal, toItem: lastSubview ?? toView, attribute: (lastSubview != nil) ? .bottom : .top, multiplier: 1, constant: constantTop)) // Leading constraints.append(NSLayoutConstraint(item: separator, attribute: .leading, relatedBy: .equal, toItem: toView, attribute: .leading, multiplier: 1, constant: 20.0)) // Trailing constraints.append(NSLayoutConstraint(item: toView, attribute: .trailing, relatedBy: .equal, toItem: separator, attribute: .trailing, multiplier: 1, constant: 20.0)) // --------------------------------------------------------------------- // Update height value // --------------------------------------------------------------------- height += constantTop + separator.intrinsicContentSize.height return separator } public func addHeader(title: String, controlSize: NSControl.ControlSize = .regular, withSeparator: Bool, textFieldTitle: NSTextField = NSTextField(), toView: NSView, lastSubview: NSView?, height: inout CGFloat, constraints: inout [NSLayoutConstraint], sender: Any? = nil) -> NSView? { // ------------------------------------------------------------------------- // Create and add TextField title // ------------------------------------------------------------------------- textFieldTitle.translatesAutoresizingMaskIntoConstraints = false textFieldTitle.lineBreakMode = .byTruncatingTail textFieldTitle.isBordered = false textFieldTitle.isBezeled = false textFieldTitle.drawsBackground = false textFieldTitle.isEditable = false textFieldTitle.isSelectable = false textFieldTitle.textColor = .labelColor if sender is ProfileExportAccessoryView { textFieldTitle.font = NSFont.systemFont(ofSize: NSFont.systemFontSize(for: controlSize), weight: .bold) } textFieldTitle.alignment = .left textFieldTitle.stringValue = title textFieldTitle.controlSize = controlSize toView.addSubview(textFieldTitle) // ------------------------------------------------------------------------- // Add Constraints // ------------------------------------------------------------------------- // Top var constantTop: CGFloat = 20.0 if sender is ProfileExportAccessoryView { constantTop = 10.0 } constraints.append(NSLayoutConstraint(item: textFieldTitle, attribute: .top, relatedBy: .equal, toItem: lastSubview ?? toView, attribute: (lastSubview != nil) ? .bottom : .top, multiplier: 1, constant: constantTop)) // Leading // FIXME: Update functions to remove hardcoded class checks // All of these hardcoded things is mostly to get things done faster, need to revisit to actually check all the custom needs and update the functions accordingly if !(sender is ProfileExportAccessoryView) { constraints.append(NSLayoutConstraint(item: textFieldTitle, attribute: .leading, relatedBy: .equal, toItem: toView, attribute: .leading, multiplier: 1, constant: 20.0)) } // Trailing constraints.append(NSLayoutConstraint(item: toView, attribute: .trailing, relatedBy: .equal, toItem: textFieldTitle, attribute: .trailing, multiplier: 1, constant: 20.0)) // ------------------------------------------------------------------------- // Update height value // ------------------------------------------------------------------------- height += 20.0 + textFieldTitle.intrinsicContentSize.height if withSeparator { // --------------------------------------------------------------------- // Create and add vertical separator // --------------------------------------------------------------------- let separator = NSBox(frame: NSRect(x: 250.0, y: 15.0, width: kPreferencesWindowWidth - (20.0 * 2), height: 250.0)) separator.translatesAutoresizingMaskIntoConstraints = false separator.boxType = .separator toView.addSubview(separator) // --------------------------------------------------------------------- // Add Constraints // --------------------------------------------------------------------- // Top constantTop = 8.0 if sender is ProfileExportAccessoryView { constantTop = 6.0 } constraints.append(NSLayoutConstraint(item: separator, attribute: .top, relatedBy: .equal, toItem: textFieldTitle, attribute: .bottom, multiplier: 1, constant: constantTop)) // Leading if sender is ProfileExportAccessoryView { constraints.append(NSLayoutConstraint(item: textFieldTitle, attribute: .leading, relatedBy: .equal, toItem: separator, attribute: .leading, multiplier: 1, constant: 0.0)) } else { constraints.append(NSLayoutConstraint(item: separator, attribute: .leading, relatedBy: .equal, toItem: toView, attribute: .leading, multiplier: 1, constant: 20.0)) } // Trailing constraints.append(NSLayoutConstraint(item: toView, attribute: .trailing, relatedBy: .equal, toItem: separator, attribute: .trailing, multiplier: 1, constant: 20.0)) // --------------------------------------------------------------------- // Update height value // --------------------------------------------------------------------- height += 8.0 + separator.intrinsicContentSize.height return separator } else { return textFieldTitle } } func setupLabel(string: String?, controlSize: NSControl.ControlSize = .regular, toView: NSView, indent: CGFloat, constraints: inout [NSLayoutConstraint]) -> NSTextField? { guard var labelString = string else { return nil } if !labelString.hasSuffix(":") { labelString.append(":") } // ------------------------------------------------------------------------- // Create and add TextField Label // ------------------------------------------------------------------------- let textFieldLabel = NSTextField() textFieldLabel.translatesAutoresizingMaskIntoConstraints = false textFieldLabel.lineBreakMode = .byTruncatingTail textFieldLabel.isBordered = false textFieldLabel.isBezeled = false textFieldLabel.drawsBackground = false textFieldLabel.isEditable = false textFieldLabel.isSelectable = true textFieldLabel.textColor = .labelColor textFieldLabel.alignment = .right textFieldLabel.stringValue = labelString textFieldLabel.controlSize = controlSize textFieldLabel.setContentCompressionResistancePriority(.required, for: .horizontal) toView.addSubview(textFieldLabel) // Leading constraints.append(NSLayoutConstraint(item: textFieldLabel, attribute: .leading, relatedBy: .equal, toItem: toView, attribute: .leading, multiplier: 1, constant: indent)) return textFieldLabel } public func addColorWell(label: String?, controlSize: NSControl.ControlSize = .regular, bindTo: Any?, bindKeyPath: String, toView: NSView, lastSubview: NSView?, lastTextField: NSView?, height: inout CGFloat, indent: CGFloat, constraints: inout [NSLayoutConstraint]) -> NSColorWell? { // ------------------------------------------------------------------------- // Create and add Label if label string was passed // ------------------------------------------------------------------------- let textFieldLabel = setupLabel(string: label, controlSize: controlSize, toView: toView, indent: indent, constraints: &constraints) let colorWell = NSColorWell() colorWell.translatesAutoresizingMaskIntoConstraints = false colorWell.isBordered = true toView.addSubview(colorWell) // --------------------------------------------------------------------- // Bind color well to keyPath // --------------------------------------------------------------------- colorWell.bind(NSBindingName.value, to: bindTo ?? UserDefaults.standard, withKeyPath: bindKeyPath, options: [NSBindingOption.continuouslyUpdatesValue: true, NSBindingOption.valueTransformerName: HexColorTransformer.name]) // ------------------------------------------------------------------------- // Add Constraints // ------------------------------------------------------------------------- // Width constraints.append(NSLayoutConstraint(item: colorWell, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 44.0)) // True constraints.append(NSLayoutConstraint(item: colorWell, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 23.0)) if let label = textFieldLabel { // Top var constantTop: CGFloat = 16.0 if controlSize == .small { constantTop = 7.0 } constraints.append(NSLayoutConstraint(item: colorWell, attribute: .top, relatedBy: .equal, toItem: lastSubview ?? toView, attribute: (lastSubview != nil) ? .bottom : .top, multiplier: 1, constant: constantTop)) // Leading constraints.append(NSLayoutConstraint(item: colorWell, attribute: .leading, relatedBy: .equal, toItem: label, attribute: .trailing, multiplier: 1, constant: 6.0)) // Baseline constraints.append(NSLayoutConstraint(item: colorWell, attribute: .centerY, relatedBy: .equal, toItem: label, attribute: .centerY, multiplier: 1, constant: 0.0)) } else { // Top constraints.append(NSLayoutConstraint(item: colorWell, attribute: .top, relatedBy: .equal, toItem: lastSubview ?? toView, attribute: (lastSubview != nil) ? .bottom : .top, multiplier: 1, constant: 6.0)) } if lastTextField != nil { // Leading constraints.append(NSLayoutConstraint(item: colorWell, attribute: .leading, relatedBy: .equal, toItem: lastTextField, attribute: .leading, multiplier: 1, constant: 0.0)) } else if textFieldLabel == nil { // Leading constraints.append(NSLayoutConstraint(item: colorWell, attribute: .leading, relatedBy: .equal, toItem: toView, attribute: .leading, multiplier: 1, constant: indent)) } // Trailing constraints.append(NSLayoutConstraint(item: toView, attribute: .trailing, relatedBy: .greaterThanOrEqual, toItem: colorWell, attribute: .trailing, multiplier: 1, constant: 20)) // ------------------------------------------------------------------------- // Update height value // ------------------------------------------------------------------------- height += 8.0 + colorWell.intrinsicContentSize.height return colorWell } public func addDirectoryPathSelection(label: String?, placeholderValue: String, buttonTitle: String?, buttonTarget: Any?, buttonAction: Selector, controlSize: NSControl.ControlSize = .regular, bindTo: Any?, keyPath: String, toView: NSView, lastSubview: NSView?, lastTextField: NSView?, height: inout CGFloat, indent: CGFloat, constraints: inout [NSLayoutConstraint]) -> NSView? { let textFieldLabel = NSTextField() if let labelString = label { // ------------------------------------------------------------------------- // Create and add TextField Label // ------------------------------------------------------------------------- textFieldLabel.translatesAutoresizingMaskIntoConstraints = false textFieldLabel.lineBreakMode = .byTruncatingTail textFieldLabel.isBordered = false textFieldLabel.isBezeled = false textFieldLabel.drawsBackground = false textFieldLabel.isEditable = false textFieldLabel.isSelectable = true textFieldLabel.textColor = .labelColor textFieldLabel.alignment = .right textFieldLabel.stringValue = labelString textFieldLabel.controlSize = controlSize textFieldLabel.setContentHuggingPriority(.required, for: .horizontal) textFieldLabel.setContentCompressionResistancePriority(.required, for: .horizontal) toView.addSubview(textFieldLabel) // Leading constraints.append(NSLayoutConstraint(item: textFieldLabel, attribute: .leading, relatedBy: .equal, toItem: toView, attribute: .leading, multiplier: 1, constant: kPreferencesIndent)) } // ------------------------------------------------------------------------- // Create and add TextField // ------------------------------------------------------------------------- let textField = NSTextField() textField.translatesAutoresizingMaskIntoConstraints = false textField.lineBreakMode = .byTruncatingMiddle textField.isBordered = false textField.isBezeled = false textField.bezelStyle = .squareBezel textField.drawsBackground = false textField.isEditable = false textField.isSelectable = true textField.textColor = .labelColor textField.alignment = .left textField.placeholderString = placeholderValue textField.controlSize = controlSize textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) textField.setContentCompressionResistancePriority(.defaultLow, for: .vertical) textField.setContentHuggingPriority(.defaultLow, for: .horizontal) textField.setContentHuggingPriority(.defaultLow, for: .vertical) toView.addSubview(textField) // --------------------------------------------------------------------- // Bind TextField to keyPath // --------------------------------------------------------------------- textField.bind(NSBindingName.value, to: bindTo ?? UserDefaults.standard, withKeyPath: keyPath, options: [NSBindingOption.continuouslyUpdatesValue: true, NSBindingOption.nullPlaceholder: placeholderValue]) // ------------------------------------------------------------------------- // Create and add button // ------------------------------------------------------------------------- let button = NSButton(title: buttonTitle ?? NSLocalizedString("Choose…", comment: ""), target: buttonTarget, action: buttonAction) button.translatesAutoresizingMaskIntoConstraints = false button.controlSize = controlSize button.setContentCompressionResistancePriority(.required, for: .horizontal) button.setContentHuggingPriority(.required, for: .horizontal) toView.addSubview(button) // ------------------------------------------------------------------------- // Add Constraints // ------------------------------------------------------------------------- // TextField Leading constraints.append(NSLayoutConstraint(item: textField, attribute: .leading, relatedBy: .equal, toItem: textFieldLabel, attribute: .trailing, multiplier: 1, constant: 6.0)) // Checkbox Center Y constraints.append(NSLayoutConstraint(item: textField, attribute: .firstBaseline, relatedBy: .equal, toItem: textFieldLabel, attribute: .firstBaseline, multiplier: 1, constant: 0.0)) // Button Leading constraints.append(NSLayoutConstraint(item: button, attribute: .leading, relatedBy: .equal, toItem: textField, attribute: .trailing, multiplier: 1, constant: 6.0)) // Button Baseline constraints.append(NSLayoutConstraint(item: button, attribute: .firstBaseline, relatedBy: .equal, toItem: textFieldLabel, attribute: .firstBaseline, multiplier: 1, constant: 0.0)) if lastTextField != nil { // Leading constraints.append(NSLayoutConstraint(item: textField, attribute: .leading, relatedBy: .equal, toItem: lastTextField, attribute: .leading, multiplier: 1, constant: 0.0)) } // Trailing constraints.append(NSLayoutConstraint(item: toView, attribute: .trailing, relatedBy: .equal, toItem: button, attribute: .trailing, multiplier: 1, constant: 20.0)) // ------------------------------------------------------------------------- // Update height value // ------------------------------------------------------------------------- height += 20.0 + textField.intrinsicContentSize.height return textField } public func addPopUpButtonCertificate(label: String?, controlSize: NSControl.ControlSize = .regular, bindTo: Any?, bindKeyPathCheckbox: String, bindKeyPathPopUpButton: String, toView: NSView, lastSubview: NSView?, lastTextField: NSView?, height: inout CGFloat, indent: CGFloat, constraints: inout [NSLayoutConstraint]) -> NSView? { // ------------------------------------------------------------------------- // Create and add Label if label string was passed // ------------------------------------------------------------------------- guard let textFieldLabel = setupLabel(string: label, controlSize: controlSize, toView: toView, indent: indent, constraints: &constraints) else { return nil } var menu: NSMenu var signingCertificatePersistantRef: Data? if let userDefaults = bindTo as? UserDefaults, let persistantRef = userDefaults.data(forKey: bindKeyPathPopUpButton) { signingCertificatePersistantRef = persistantRef } else if let bindObject = bindTo as? NSObject, let persistantRef = bindObject.value(forKeyPath: bindKeyPathPopUpButton) as? Data { signingCertificatePersistantRef = persistantRef } if let identityDict = Identities.codeSigningIdentityDict(persistentRef: signingCertificatePersistantRef) { menu = Identities.popUpButtonMenu(forCodeSigningIdentityDicts: [identityDict]) } else { menu = NSMenu() menu.addItem(NSMenuItem(title: "None", action: nil, keyEquivalent: "")) } // ------------------------------------------------------------------------- // Create and add Checkbox // ------------------------------------------------------------------------- let checkbox = NSButton() checkbox.translatesAutoresizingMaskIntoConstraints = false checkbox.setButtonType(.switch) checkbox.title = "" toView.addSubview(checkbox) // --------------------------------------------------------------------- // Bind checkbox to keyPath // --------------------------------------------------------------------- checkbox.bind(.value, to: bindTo ?? UserDefaults.standard, withKeyPath: bindKeyPathCheckbox, options: [.continuouslyUpdatesValue: true]) // ------------------------------------------------------------------------- // Create and add PopUpButton // ------------------------------------------------------------------------- let popUpButton = SigningCertificatePopUpButton() popUpButton.translatesAutoresizingMaskIntoConstraints = false popUpButton.controlSize = controlSize popUpButton.menu = menu popUpButton.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) popUpButton.setContentHuggingPriority(.defaultLow, for: .horizontal) toView.addSubview(popUpButton) menu.delegate = popUpButton // --------------------------------------------------------------------- // Bind PopUpButton to keyPath // --------------------------------------------------------------------- popUpButton.bind(.selectedObject, to: bindTo ?? UserDefaults.standard, withKeyPath: bindKeyPathPopUpButton, options: [.continuouslyUpdatesValue: true]) // --------------------------------------------------------------------- // Bind PopUpButton to checkbox state // --------------------------------------------------------------------- popUpButton.bind(.enabled, to: bindTo ?? UserDefaults.standard, withKeyPath: bindKeyPathCheckbox, options: [.continuouslyUpdatesValue: true]) // ------------------------------------------------------------------------- // Add Constraints // ------------------------------------------------------------------------- // Top var constantTop: CGFloat = 8.0 if lastSubview is NSButton { constantTop = 8.0 } else if controlSize == .small { constantTop = 6.0 } // Top constraints.append(NSLayoutConstraint(item: popUpButton, attribute: .top, relatedBy: .equal, toItem: lastSubview ?? toView, attribute: (lastSubview != nil) ? .bottom : .top, multiplier: 1, constant: constantTop)) // Checkbox Leading constraints.append(NSLayoutConstraint(item: checkbox, attribute: .leading, relatedBy: .equal, toItem: textFieldLabel, attribute: .trailing, multiplier: 1, constant: 6.0)) // Checkbox Center Y constraints.append(NSLayoutConstraint(item: checkbox, attribute: .firstBaseline, relatedBy: .equal, toItem: textFieldLabel, attribute: .firstBaseline, multiplier: 1, constant: 0.0)) // PopUpButton Leading constraints.append(NSLayoutConstraint(item: popUpButton, attribute: .leading, relatedBy: .equal, toItem: checkbox, attribute: .trailing, multiplier: 1, constant: 1.0)) // PopUpButton Baseline constraints.append(NSLayoutConstraint(item: popUpButton, attribute: .firstBaseline, relatedBy: .equal, toItem: textFieldLabel, attribute: .firstBaseline, multiplier: 1, constant: 0.0)) if lastTextField != nil { // Leading constraints.append(NSLayoutConstraint(item: checkbox, attribute: .leading, relatedBy: .equal, toItem: lastTextField, attribute: .leading, multiplier: 1, constant: 0.0)) } // Trailing constraints.append(NSLayoutConstraint(item: toView, attribute: .trailing, relatedBy: .greaterThanOrEqual, toItem: popUpButton, attribute: .trailing, multiplier: 1, constant: 20.0)) // ------------------------------------------------------------------------- // Update height value // ------------------------------------------------------------------------- height += 8.0 + popUpButton.intrinsicContentSize.height return popUpButton } class SigningCertificatePopUpButton: NSPopUpButton, NSMenuDelegate { func menuWillOpen(_ menu: NSMenu) { let persistentRef = self.selectedItem?.representedObject as? Data Identities.shared.updateCodeSigningIdentities() menu.removeAllItems() menu.addItem(NSMenuItem(title: "None", action: nil, keyEquivalent: "")) for identity in Identities.shared.identities { guard let secIdentityObject = identity[kSecValueRef as String], CFGetTypeID(secIdentityObject) == SecIdentityGetTypeID(), let secPersistentRef = identity[kSecValuePersistentRef as String] as? Data else { continue } // swiftlint:disable:next force_cast let secIdentity = secIdentityObject as! SecIdentity let menuItem = NSMenuItem() menuItem.title = identity[kSecAttrLabel as String] as? String ?? "Unknown Certificate" menuItem.representedObject = secPersistentRef menuItem.image = secIdentity.certificateIconSmall menu.addItem(menuItem) } self.selectItem(at: menu.indexOfItem(withRepresentedObject: persistentRef)) } } public func addButton(label: String?, title: String?, controlSize: NSControl.ControlSize = .regular, bindToEnabled: Any?, bindKeyPathEnabled: String?, target: Any?, selector: Selector, toView: NSView, lastSubview: NSView?, lastTextField: NSView?, height: inout CGFloat, indent: CGFloat, constraints: inout [NSLayoutConstraint]) -> NSView? { // ------------------------------------------------------------------------- // Create and add Label if label string was passed // ------------------------------------------------------------------------- let textFieldLabel = setupLabel(string: label, controlSize: controlSize, toView: toView, indent: indent, constraints: &constraints) // ------------------------------------------------------------------------- // Create and add button // ------------------------------------------------------------------------- let button = NSButton(title: title ?? NSLocalizedString("Choose…", comment: ""), target: target, action: selector) button.translatesAutoresizingMaskIntoConstraints = false button.controlSize = controlSize button.setContentCompressionResistancePriority(.required, for: .horizontal) toView.addSubview(button) // --------------------------------------------------------------------- // Bind Button enabled to checkbox state // --------------------------------------------------------------------- if let keyPath = bindKeyPathEnabled { button.bind(NSBindingName.enabled, to: bindToEnabled ?? UserDefaults.standard, withKeyPath: keyPath, options: [.continuouslyUpdatesValue: true]) } // ------------------------------------------------------------------------- // Add Constraints // ------------------------------------------------------------------------- if let label = textFieldLabel { // Leading constraints.append(NSLayoutConstraint(item: button, attribute: .leading, relatedBy: .equal, toItem: label, attribute: .trailing, multiplier: 1, constant: 6.0)) // Baseline constraints.append(NSLayoutConstraint(item: button, attribute: .firstBaseline, relatedBy: .equal, toItem: label, attribute: .firstBaseline, multiplier: 1, constant: 0.0)) } else if lastTextField != nil { // Leading constraints.append(NSLayoutConstraint(item: button, attribute: .leading, relatedBy: .equal, toItem: lastTextField, attribute: .leading, multiplier: 1, constant: 0.0)) } else { // Leading constraints.append(NSLayoutConstraint(item: button, attribute: .leading, relatedBy: .equal, toItem: toView, attribute: .leading, multiplier: 1, constant: indent)) } // Top constraints.append(NSLayoutConstraint(item: button, attribute: .top, relatedBy: .equal, toItem: lastSubview ?? toView, attribute: (lastSubview != nil) ? .bottom : .top, multiplier: 1, constant: 8.0)) // Trailing if lastTextField is NSButton, let lastButton = lastTextField { constraints.append(NSLayoutConstraint(item: lastButton, attribute: .trailing, relatedBy: .equal, toItem: button, attribute: .trailing, multiplier: 1, constant: 0.0)) } else { constraints.append(NSLayoutConstraint(item: toView, attribute: .trailing, relatedBy: .greaterThanOrEqual, toItem: button, attribute: .trailing, multiplier: 1, constant: 20.0)) } // Width constraints.append(NSLayoutConstraint(item: button, attribute: .width, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: button.intrinsicContentSize.width)) // ------------------------------------------------------------------------- // Update height value // ------------------------------------------------------------------------- height += 8.0 + button.intrinsicContentSize.height return button } public func addPopUpButton(label: String?, titles: [String], controlSize: NSControl.ControlSize = .regular, bindTo: Any?, bindKeyPath: String, toView: NSView, lastSubview: NSView?, lastTextField: NSView?, height: inout CGFloat, indent: CGFloat, constraints: inout [NSLayoutConstraint]) -> NSView? { // ------------------------------------------------------------------------- // Create and add Label if label string was passed // ------------------------------------------------------------------------- let textFieldLabel = setupLabel(string: label, controlSize: controlSize, toView: toView, indent: indent, constraints: &constraints) // ------------------------------------------------------------------------- // Create and add PopUpButton // ------------------------------------------------------------------------- let popUpButton = NSPopUpButton() popUpButton.translatesAutoresizingMaskIntoConstraints = false popUpButton.addItems(withTitles: titles) popUpButton.controlSize = controlSize popUpButton.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) toView.addSubview(popUpButton) // --------------------------------------------------------------------- // Bind PopUpButton to keyPath // --------------------------------------------------------------------- popUpButton.bind(NSBindingName.selectedValue, to: bindTo ?? UserDefaults.standard, withKeyPath: bindKeyPath, options: [NSBindingOption.continuouslyUpdatesValue: true]) // ------------------------------------------------------------------------- // Add Constraints // ------------------------------------------------------------------------- // Top var constantTop: CGFloat = 6.0 if controlSize == .small { constantTop = 6.0 } constraints.append(NSLayoutConstraint(item: popUpButton, attribute: .top, relatedBy: .equal, toItem: lastSubview ?? toView, attribute: (lastSubview != nil) ? .bottom : .top, multiplier: 1, constant: constantTop)) if let label = textFieldLabel { // Leading constraints.append(NSLayoutConstraint(item: popUpButton, attribute: .leading, relatedBy: .equal, toItem: label, attribute: .trailing, multiplier: 1, constant: 6.0)) // Baseline constraints.append(NSLayoutConstraint(item: popUpButton, attribute: .firstBaseline, relatedBy: .equal, toItem: label, attribute: .firstBaseline, multiplier: 1, constant: 0.0)) } else { // Leading constraints.append(NSLayoutConstraint(item: popUpButton, attribute: .leading, relatedBy: .equal, toItem: toView, attribute: .leading, multiplier: 1, constant: indent)) } if lastTextField != nil { // Leading constraints.append(NSLayoutConstraint(item: popUpButton, attribute: .leading, relatedBy: .equal, toItem: lastTextField, attribute: .leading, multiplier: 1, constant: 0.0)) } // Trailing constraints.append(NSLayoutConstraint(item: toView, attribute: .trailing, relatedBy: .greaterThanOrEqual, toItem: popUpButton, attribute: .trailing, multiplier: 1, constant: 20.0)) // Width constraints.append(NSLayoutConstraint(item: popUpButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: popUpButton.intrinsicContentSize.width)) // ------------------------------------------------------------------------- // Update height value // ------------------------------------------------------------------------- height += 8.0 + popUpButton.intrinsicContentSize.height return popUpButton } public func addCheckbox(label: String?, title: String, controlSize: NSControl.ControlSize = .regular, bindTo: Any?, bindKeyPath: String, toView: NSView, lastSubview: NSView?, lastTextField: NSView?, height: inout CGFloat, indent: CGFloat, constraints: inout [NSLayoutConstraint]) -> NSView? { // ------------------------------------------------------------------------- // Create and add Label if label string was passed // ------------------------------------------------------------------------- let textFieldLabel = setupLabel(string: label, controlSize: controlSize, toView: toView, indent: indent, constraints: &constraints) // ------------------------------------------------------------------------- // Create and add Checkbox // ------------------------------------------------------------------------- let checkbox = NSButton() checkbox.translatesAutoresizingMaskIntoConstraints = false checkbox.setButtonType(.switch) checkbox.title = title checkbox.controlSize = controlSize toView.addSubview(checkbox) // --------------------------------------------------------------------- // Bind checkbox to keyPath // --------------------------------------------------------------------- checkbox.bind(NSBindingName.value, to: bindTo ?? UserDefaults.standard, withKeyPath: bindKeyPath, options: [.continuouslyUpdatesValue: true]) // ------------------------------------------------------------------------- // Add Constraints // ------------------------------------------------------------------------- if let label = textFieldLabel { // Top var constantTop: CGFloat = 16.0 if controlSize == .small { constantTop = 7.0 } constraints.append(NSLayoutConstraint(item: checkbox, attribute: .top, relatedBy: .equal, toItem: lastSubview ?? toView, attribute: (lastSubview != nil) ? .bottom : .top, multiplier: 1, constant: constantTop)) // Leading constraints.append(NSLayoutConstraint(item: checkbox, attribute: .leading, relatedBy: .equal, toItem: label, attribute: .trailing, multiplier: 1, constant: 6.0)) // Baseline constraints.append(NSLayoutConstraint(item: checkbox, attribute: .firstBaseline, relatedBy: .equal, toItem: label, attribute: .firstBaseline, multiplier: 1, constant: 0.0)) } else { var constantTop: CGFloat = 6.0 if bindTo is ProfileExportAccessoryView { constantTop = 10.0 } // Top constraints.append(NSLayoutConstraint(item: checkbox, attribute: .top, relatedBy: .equal, toItem: lastSubview ?? toView, attribute: (lastSubview != nil) ? .bottom : .top, multiplier: 1, constant: constantTop)) } if lastTextField != nil { // Leading constraints.append(NSLayoutConstraint(item: checkbox, attribute: .leading, relatedBy: .equal, toItem: lastTextField, attribute: .leading, multiplier: 1, constant: 0.0)) } else if textFieldLabel == nil { // Leading constraints.append(NSLayoutConstraint(item: checkbox, attribute: .leading, relatedBy: .equal, toItem: toView, attribute: .leading, multiplier: 1, constant: indent)) } // Trailing constraints.append(NSLayoutConstraint(item: toView, attribute: .trailing, relatedBy: .greaterThanOrEqual, toItem: checkbox, attribute: .trailing, multiplier: 1, constant: 20)) // ------------------------------------------------------------------------- // Update height value // ------------------------------------------------------------------------- height += 8.0 + checkbox.intrinsicContentSize.height return checkbox } public func addTextFieldDescription(stringValue: String, controlSize: NSControl.ControlSize = .regular, font: NSFont? = nil, toView: NSView, lastSubview: NSView?, lastTextField: NSView?, height: inout CGFloat, constraints: inout [NSLayoutConstraint]) -> NSView? { let textFieldDescription = NSTextField() // ------------------------------------------------------------------------- // Create and add TextField Label // ------------------------------------------------------------------------- textFieldDescription.translatesAutoresizingMaskIntoConstraints = false textFieldDescription.lineBreakMode = .byWordWrapping textFieldDescription.isBordered = false textFieldDescription.isBezeled = false textFieldDescription.drawsBackground = false textFieldDescription.isEditable = false textFieldDescription.isSelectable = true textFieldDescription.textColor = .labelColor textFieldDescription.alignment = .left textFieldDescription.stringValue = stringValue textFieldDescription.controlSize = controlSize textFieldDescription.setContentCompressionResistancePriority(.required, for: .horizontal) toView.addSubview(textFieldDescription) // ------------------------------------------------------------------------- // Add Constraints // ------------------------------------------------------------------------- // Top var constantTop: CGFloat = 8.0 if lastSubview == nil { constantTop = 10.0 } else if controlSize == .small { constantTop = 6.0 } constraints.append(NSLayoutConstraint(item: textFieldDescription, attribute: .top, relatedBy: .equal, toItem: lastSubview ?? toView, attribute: (lastSubview != nil) ? .bottom : .top, multiplier: 1, constant: constantTop)) // Leading constraints.append(NSLayoutConstraint(item: textFieldDescription, attribute: .leading, relatedBy: .equal, toItem: lastTextField ?? toView, attribute: .leading, multiplier: 1, constant: (lastTextField != nil) ? 0.0 : kPreferencesIndent)) // Trailing constraints.append(NSLayoutConstraint(item: toView, attribute: .trailing, relatedBy: .equal, toItem: textFieldDescription, attribute: .trailing, multiplier: 1, constant: 20)) // ------------------------------------------------------------------------- // Update height value // ------------------------------------------------------------------------- height += 20.0 + textFieldDescription.intrinsicContentSize.height return textFieldDescription } public func addTextFieldLabel(label: String?, placeholderValue: String, controlSize: NSControl.ControlSize = .regular, font: NSFont? = nil, bindTo: Any? = nil, keyPath: String?, toView: NSView, lastSubview: NSView?, lastTextField: NSView?, height: inout CGFloat, constraints: inout [NSLayoutConstraint]) -> NSView? { let textFieldLabel = NSTextField() if let labelString = label { // ------------------------------------------------------------------------- // Create and add TextField Label // ------------------------------------------------------------------------- textFieldLabel.translatesAutoresizingMaskIntoConstraints = false textFieldLabel.lineBreakMode = .byTruncatingTail textFieldLabel.isBordered = false textFieldLabel.isBezeled = false textFieldLabel.drawsBackground = false textFieldLabel.isEditable = false textFieldLabel.isSelectable = true textFieldLabel.textColor = .labelColor textFieldLabel.alignment = .right textFieldLabel.stringValue = labelString textFieldLabel.controlSize = controlSize textFieldLabel.setContentCompressionResistancePriority(.required, for: .horizontal) toView.addSubview(textFieldLabel) // Leading constraints.append(NSLayoutConstraint(item: textFieldLabel, attribute: .leading, relatedBy: .equal, toItem: toView, attribute: .leading, multiplier: 1, constant: kPreferencesIndent)) } // ------------------------------------------------------------------------- // Create and add TextField // ------------------------------------------------------------------------- let textField = NSTextField() textField.translatesAutoresizingMaskIntoConstraints = false textField.lineBreakMode = .byTruncatingTail textField.isBordered = false textField.isBezeled = false textField.drawsBackground = false textField.isEditable = false textField.isSelectable = true textField.textColor = .labelColor textField.alignment = .left textField.placeholderString = placeholderValue textField.controlSize = controlSize if let textFieldFont = font { textField.font = textFieldFont } textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) toView.addSubview(textField) // --------------------------------------------------------------------- // Bind TextField to keyPath // --------------------------------------------------------------------- if let bindKeyPath = keyPath { textField.bind(NSBindingName.value, to: bindTo ?? UserDefaults.standard, withKeyPath: bindKeyPath, options: [NSBindingOption.continuouslyUpdatesValue: true, NSBindingOption.nullPlaceholder: placeholderValue]) } // ------------------------------------------------------------------------- // Add Constraints // ------------------------------------------------------------------------- // Top var constantTop: CGFloat = 8.0 if lastSubview == nil { constantTop = 10.0 } else if controlSize == .small { constantTop = 6.0 } constraints.append(NSLayoutConstraint(item: textField, attribute: .top, relatedBy: .equal, toItem: lastSubview ?? toView, attribute: (lastSubview != nil) ? .bottom : .top, multiplier: 1, constant: constantTop)) if label != nil { // Leading constraints.append(NSLayoutConstraint(item: textField, attribute: .leading, relatedBy: .equal, toItem: textFieldLabel, attribute: .trailing, multiplier: 1, constant: 6.0)) // Baseline constraints.append(NSLayoutConstraint(item: textField, attribute: .firstBaseline, relatedBy: .equal, toItem: textFieldLabel, attribute: .firstBaseline, multiplier: 1, constant: 0.0)) } else { // Leading constraints.append(NSLayoutConstraint(item: textField, attribute: .leading, relatedBy: .equal, toItem: toView, attribute: .leading, multiplier: 1, constant: kPreferencesIndent)) } if lastTextField != nil { // Leading constraints.append(NSLayoutConstraint(item: textField, attribute: .leading, relatedBy: .equal, toItem: lastTextField, attribute: .leading, multiplier: 1, constant: 0.0)) } // Trailing constraints.append(NSLayoutConstraint(item: toView, attribute: .trailing, relatedBy: .equal, toItem: textField, attribute: .trailing, multiplier: 1, constant: 20)) // ------------------------------------------------------------------------- // Update height value // ------------------------------------------------------------------------- height += 20.0 + textField.intrinsicContentSize.height return textField } public func addTextField(label: String?, placeholderValue: String, controlSize: NSControl.ControlSize = .regular, bindTo: Any? = nil, keyPath: String, toView: NSView, lastSubview: NSView?, lastTextField: NSView?, height: inout CGFloat, constraints: inout [NSLayoutConstraint]) -> NSView? { let textFieldLabel = NSTextField() if let labelString = label { // ------------------------------------------------------------------------- // Create and add TextField Label // ------------------------------------------------------------------------- textFieldLabel.translatesAutoresizingMaskIntoConstraints = false textFieldLabel.lineBreakMode = .byTruncatingTail textFieldLabel.isBordered = false textFieldLabel.isBezeled = false textFieldLabel.drawsBackground = false textFieldLabel.isEditable = false textFieldLabel.isSelectable = true textFieldLabel.textColor = .labelColor textFieldLabel.alignment = .right textFieldLabel.stringValue = labelString textFieldLabel.controlSize = controlSize textFieldLabel.setContentCompressionResistancePriority(.required, for: .horizontal) toView.addSubview(textFieldLabel) // Leading constraints.append(NSLayoutConstraint(item: textFieldLabel, attribute: .leading, relatedBy: .equal, toItem: toView, attribute: .leading, multiplier: 1, constant: kPreferencesIndent)) } // ------------------------------------------------------------------------- // Create and add TextField // ------------------------------------------------------------------------- let textField = NSTextField() textField.translatesAutoresizingMaskIntoConstraints = false textField.lineBreakMode = .byTruncatingTail textField.isBordered = true textField.isBezeled = true textField.bezelStyle = .squareBezel textField.drawsBackground = false textField.isEditable = true textField.isSelectable = true textField.textColor = .labelColor textField.alignment = .left textField.placeholderString = placeholderValue textField.controlSize = controlSize textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) toView.addSubview(textField) // --------------------------------------------------------------------- // Bind TextField to keyPath // --------------------------------------------------------------------- textField.bind(NSBindingName.value, to: bindTo ?? UserDefaults.standard, withKeyPath: keyPath, options: [NSBindingOption.continuouslyUpdatesValue: true, NSBindingOption.nullPlaceholder: placeholderValue]) // ------------------------------------------------------------------------- // Add Constraints // ------------------------------------------------------------------------- // Top var constantTop: CGFloat = 8.0 if lastSubview == nil { constantTop = 10.0 } else if controlSize == .small { constantTop = 6.0 } constraints.append(NSLayoutConstraint(item: textField, attribute: .top, relatedBy: .equal, toItem: lastSubview ?? toView, attribute: (lastSubview != nil) ? .bottom : .top, multiplier: 1, constant: constantTop)) if label != nil { // Leading constraints.append(NSLayoutConstraint(item: textField, attribute: .leading, relatedBy: .equal, toItem: textFieldLabel, attribute: .trailing, multiplier: 1, constant: 6.0)) // Baseline constraints.append(NSLayoutConstraint(item: textField, attribute: .firstBaseline, relatedBy: .equal, toItem: textFieldLabel, attribute: .firstBaseline, multiplier: 1, constant: 0.0)) } else { // Leading constraints.append(NSLayoutConstraint(item: textField, attribute: .leading, relatedBy: .equal, toItem: toView, attribute: .leading, multiplier: 1, constant: kPreferencesIndent)) } if lastTextField != nil { // Leading constraints.append(NSLayoutConstraint(item: textField, attribute: .leading, relatedBy: .equal, toItem: lastTextField, attribute: .leading, multiplier: 1, constant: 0.0)) } // Trailing constraints.append(NSLayoutConstraint(item: toView, attribute: .trailing, relatedBy: .equal, toItem: textField, attribute: .trailing, multiplier: 1, constant: 20)) // ------------------------------------------------------------------------- // Update height value // ------------------------------------------------------------------------- height += 20.0 + textField.intrinsicContentSize.height return textField } public func addBox(title: String?, toView: NSView, lastSubview: NSView?, lastTextField: NSView?, height: inout CGFloat, indent: CGFloat, constraints: inout [NSLayoutConstraint]) -> NSBox? { let box = NSBox() box.translatesAutoresizingMaskIntoConstraints = false if let theTitle = title { box.title = theTitle box.titlePosition = .atTop } else { box.titlePosition = .noTitle } toView.addSubview(box) // ------------------------------------------------------------------------- // Add Constraints // ------------------------------------------------------------------------- // Top let constantTop: CGFloat = -4.0 constraints.append(NSLayoutConstraint(item: box, attribute: .top, relatedBy: .equal, toItem: lastSubview ?? toView, attribute: (lastSubview != nil) ? .bottom : .top, multiplier: 1, constant: constantTop)) if lastTextField != nil { // Leading constraints.append(NSLayoutConstraint(item: box, attribute: .leading, relatedBy: .equal, toItem: lastTextField, attribute: .leading, multiplier: 1, constant: 0.0)) } else { // Leading constraints.append(NSLayoutConstraint(item: box, attribute: .leading, relatedBy: .equal, toItem: toView, attribute: .leading, multiplier: 1, constant: indent)) } // Trailing constraints.append(NSLayoutConstraint(item: toView, attribute: .trailing, relatedBy: .equal, toItem: box, attribute: .trailing, multiplier: 1, constant: 20.0)) /* // Height Test constraints.append(NSLayoutConstraint(item: box, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 80.0)) */ // --------------------------------------------------------------------- // Update height value // --------------------------------------------------------------------- height += constantTop + box.intrinsicContentSize.height return box } public func addTextField(label: String, placeholderValue: String, controlSize: NSControl.ControlSize = .regular, bindTo: Any?, bindKeyPathCheckbox: String, bindKeyPathTextField: String, toView: NSView, lastSubview: NSView?, lastTextField: NSView?, height: inout CGFloat, indent: CGFloat, constraints: inout [NSLayoutConstraint]) -> NSView? { // ------------------------------------------------------------------------- // Create and add Label if label string was passed // ------------------------------------------------------------------------- guard let textFieldLabel = setupLabel(string: label, controlSize: controlSize, toView: toView, indent: indent, constraints: &constraints) else { return nil } // ------------------------------------------------------------------------- // Create and add Checkbox // ------------------------------------------------------------------------- let checkbox = NSButton() checkbox.translatesAutoresizingMaskIntoConstraints = false checkbox.setButtonType(.switch) checkbox.title = "" toView.addSubview(checkbox) // --------------------------------------------------------------------- // Bind checkbox to keyPath // --------------------------------------------------------------------- checkbox.bind(NSBindingName.value, to: bindTo ?? UserDefaults.standard, withKeyPath: bindKeyPathCheckbox, options: [NSBindingOption.continuouslyUpdatesValue: true]) // ------------------------------------------------------------------------- // Create and add TextField // ------------------------------------------------------------------------- let textField = NSTextField() textField.translatesAutoresizingMaskIntoConstraints = false textField.lineBreakMode = .byTruncatingTail textField.isBordered = true textField.isBezeled = true textField.bezelStyle = .squareBezel textField.drawsBackground = false textField.isEditable = true textField.isSelectable = true textField.textColor = .labelColor textField.alignment = .left textField.placeholderString = placeholderValue textField.controlSize = controlSize textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) toView.addSubview(textField) // --------------------------------------------------------------------- // Bind TextField to keyPath // --------------------------------------------------------------------- textField.bind(NSBindingName.value, to: bindTo ?? UserDefaults.standard, withKeyPath: bindKeyPathTextField, options: [.continuouslyUpdatesValue: true, .nullPlaceholder: placeholderValue]) // --------------------------------------------------------------------- // Bind PopUpButton to checkbox state // --------------------------------------------------------------------- textField.bind(NSBindingName.enabled, to: bindTo ?? UserDefaults.standard, withKeyPath: bindKeyPathCheckbox, options: [.continuouslyUpdatesValue: true]) // ------------------------------------------------------------------------- // Add Constraints // ------------------------------------------------------------------------- // Top var constantTop: CGFloat = 8.0 if lastSubview is NSButton { constantTop = 8.0 } else if lastSubview is NSTextField { constantTop = 5.0 } else if controlSize == .small { constantTop = 6.0 } constraints.append(NSLayoutConstraint(item: textField, attribute: .top, relatedBy: .equal, toItem: lastSubview ?? toView, attribute: (lastSubview != nil) ? .bottom : .top, multiplier: 1, constant: constantTop)) // Checkbox Leading constraints.append(NSLayoutConstraint(item: checkbox, attribute: .leading, relatedBy: .equal, toItem: textFieldLabel, attribute: .trailing, multiplier: 1, constant: 6.0)) // Checkbox Center Y constraints.append(NSLayoutConstraint(item: checkbox, attribute: .firstBaseline, relatedBy: .equal, toItem: textFieldLabel, attribute: .firstBaseline, multiplier: 1, constant: 0.0)) // TextField Leading constraints.append(NSLayoutConstraint(item: textField, attribute: .leading, relatedBy: .equal, toItem: checkbox, attribute: .trailing, multiplier: 1, constant: 0.0)) // TextField Baseline constraints.append(NSLayoutConstraint(item: textField, attribute: .firstBaseline, relatedBy: .equal, toItem: textFieldLabel, attribute: .firstBaseline, multiplier: 1, constant: 0.0)) if lastTextField != nil { // Leading constraints.append(NSLayoutConstraint(item: checkbox, attribute: .leading, relatedBy: .equal, toItem: lastTextField, attribute: .leading, multiplier: 1, constant: 0.0)) } // Trailing constraints.append(NSLayoutConstraint(item: toView, attribute: .trailing, relatedBy: .equal, toItem: textField, attribute: .trailing, multiplier: 1, constant: 20.0)) // ------------------------------------------------------------------------- // Update height value // ------------------------------------------------------------------------- height += 20.0 + textField.intrinsicContentSize.height return checkbox }
mit
mokagio/GaugeKit
GaugeKit/CAShapeLayer+oval.swift
2
4327
// // CAShapeLayer+oval.swift // SWGauge // // Created by Petr Korolev on 03/06/15. // Copyright (c) 2015 Petr Korolev. All rights reserved. // import Foundation extension CAShapeLayer { class func getLine(lineWidth: CGFloat, strokeStart: CGFloat, strokeEnd: CGFloat, strokeColor: UIColor, fillColor: UIColor, shadowRadius: CGFloat, shadowOpacity: Float, shadowOffsset: CGSize, bounds: CGRect, rotateAngle: Double? = nil, anchorPoint: CGPoint? = nil ) -> CAShapeLayer { var arc = CAShapeLayer() let rect = CGRectInset(bounds, CGFloat(lineWidth / 2.0), CGFloat(lineWidth / 2.0)) // let lineWidth: CGFloat = bounds.width - 2 * lineWidth let path = CGPathCreateMutable() let Y = CGRectGetMidY(bounds) CGPathMoveToPoint(path, nil, lineWidth, Y) CGPathAddLineToPoint(path, nil, bounds.width - lineWidth, Y) arc.path = path arc = setupArc(arc, lineWidth: lineWidth, strokeStart: strokeStart, strokeEnd: strokeEnd, strokeColor: strokeColor, fillColor: fillColor, shadowRadius: shadowRadius, shadowOpacity: shadowOpacity, shadowOffsset: shadowOffsset, rotateAngle: rotateAngle, anchorPoint: anchorPoint) return arc } class func getOval(lineWidth: CGFloat, strokeStart: CGFloat, strokeEnd: CGFloat, strokeColor: UIColor, fillColor: UIColor, shadowRadius: CGFloat, shadowOpacity: Float, shadowOffsset: CGSize, bounds: CGRect, rotateAngle: Double? = nil, anchorPoint: CGPoint? = nil, isCircle: Bool = true ) -> CAShapeLayer { var arc = CAShapeLayer() let rect = CGRectInset(bounds, CGFloat(lineWidth / 2.0), CGFloat(lineWidth / 2.0)) if isCircle { let arcDiameter: CGFloat = min(bounds.width, bounds.height) - 2 * lineWidth let X = CGRectGetMidX(bounds) let Y = CGRectGetMidY(bounds) arc.path = UIBezierPath(ovalInRect: CGRectMake((X - (arcDiameter / 2)), (Y - (arcDiameter / 2)), arcDiameter, arcDiameter)).CGPath } else { arc.path = UIBezierPath(ovalInRect: rect).CGPath } arc = setupArc(arc, lineWidth: lineWidth, strokeStart: strokeStart, strokeEnd: strokeEnd, strokeColor: strokeColor, fillColor: fillColor, shadowRadius: shadowRadius, shadowOpacity: shadowOpacity, shadowOffsset: shadowOffsset, rotateAngle: rotateAngle, anchorPoint: anchorPoint) return arc } static func setupArc(arc: CAShapeLayer, lineWidth: CGFloat, strokeStart: CGFloat, strokeEnd: CGFloat, strokeColor: UIColor, fillColor: UIColor, shadowRadius: CGFloat, shadowOpacity: Float, shadowOffsset: CGSize, rotateAngle: Double? = nil, anchorPoint: CGPoint? = nil) -> CAShapeLayer { arc.lineWidth = lineWidth arc.strokeStart = strokeStart arc.strokeColor = strokeColor.CGColor arc.fillColor = fillColor.CGColor arc.shadowColor = UIColor.blackColor().CGColor arc.shadowRadius = shadowRadius arc.shadowOpacity = shadowOpacity arc.shadowOffset = shadowOffsset if let anchorPoint = anchorPoint { arc.anchorPoint = anchorPoint } if let rotateAngle = rotateAngle { arc.transform = CATransform3DRotate(arc.transform, CGFloat(rotateAngle), 0, 0, 1) } arc.strokeEnd = strokeEnd return arc } }
mit
kaltura/playkit-ios
Example/Tests/Analytics/OTTAnalyticsPluginTest.swift
1
15189
// =================================================================================================== // Copyright (C) 2017 Kaltura Inc. // // Licensed under the AGPLv3 license, // unless a different license for a particular library is specified in the applicable library path. // // You may obtain a copy of the License at // https://www.gnu.org/licenses/agpl-3.0.html // =================================================================================================== import Foundation import Quick import Nimble import SwiftyJSON import CoreMedia @testable import PlayKit protocol MockableOTTAnalyticsPluginProtocol { var finishedHandling: Bool { get set } var invocationCount: OTTAnalyticsPluginTest.OTTAnalyticsPluginInvocationCount { get set } } /// Shared tests for phoenix and tvpapi class OTTAnalyticsPluginTest: QuickSpec { struct OTTAnalyticsPluginInvocationCount { var firstPlayCount: Int = 0 var playCount: Int = 0 var pauseCount: Int = 0 var loadCount: Int = 0 var endedCount: Int = 0 } /************************************************************/ // MARK: - Mocks /************************************************************/ class OTTAnalyticsPluginTestPhoenixMock: PhoenixAnalyticsPlugin, MockableOTTAnalyticsPluginProtocol { public override class var pluginName: String { return PluginTestConfiguration.Phoenix.pluginName } var onAnalyticsEvent: ((OTTAnalyticsEventType, MockableOTTAnalyticsPluginProtocol) -> Void)? var onTerminate: ((MockableOTTAnalyticsPluginProtocol) -> Void)? var onDestory: ((MockableOTTAnalyticsPluginProtocol) -> Void)? var finishedHandling: Bool = false var invocationCount = OTTAnalyticsPluginInvocationCount() override func sendAnalyticsEvent(ofType type: OTTAnalyticsEventType) { self.onAnalyticsEvent?(type, self) } override var observations: Set<NotificationObservation> { return [ NotificationObservation(name: .UIApplicationWillTerminate) { [unowned self] in PKLog.verbose("plugin: \(self) will terminate event received, sending analytics stop event") self.destroy() self.onTerminate?(self) } ] } } class OTTAnalyticsPluginTestTVPAPIMock: TVPAPIAnalyticsPlugin, MockableOTTAnalyticsPluginProtocol { public override class var pluginName: String { return PluginTestConfiguration.TVPAPI.pluginName } var onAnalyticsEvent: ((OTTAnalyticsEventType, MockableOTTAnalyticsPluginProtocol) -> Void)? var onTerminate: ((MockableOTTAnalyticsPluginProtocol) -> Void)? var finishedHandling: Bool = false var invocationCount = OTTAnalyticsPluginInvocationCount() override func sendAnalyticsEvent(ofType type: OTTAnalyticsEventType) { self.onAnalyticsEvent?(type, self) } override var observations: Set<NotificationObservation> { return [ NotificationObservation(name: .UIApplicationWillTerminate) { [unowned self] in PKLog.verbose("plugin: \(self) will terminate event received, sending analytics stop event") self.onTerminate?(self) self.destroy() } ] } } class AppStateSubjectMock: AppStateSubjectProtocol { static let shared = AppStateSubjectMock() private init() { self.appStateProvider = AppStateProvider() } let lock: AnyObject = UUID().uuidString as AnyObject var observers = [AppStateObserver]() var appStateProvider: AppStateProvider var isObserving = false } /************************************************************/ // MARK: - Tests /************************************************************/ override func spec() { describe("OTTAnalyticsPluginTest") { var player: PlayerLoader! var phoenixPluginMock: OTTAnalyticsPluginTestPhoenixMock! var tvpapiPluginMock: OTTAnalyticsPluginTestTVPAPIMock! beforeEach { PlayKitManager.shared.registerPlugin(OTTAnalyticsPluginTestPhoenixMock.self) PlayKitManager.shared.registerPlugin(OTTAnalyticsPluginTestTVPAPIMock.self) player = self.createPlayerForPhoenixAndTVPAPI() phoenixPluginMock = player.loadedPlugins[OTTAnalyticsPluginTestPhoenixMock.pluginName]!.plugin as! OTTAnalyticsPluginTestPhoenixMock tvpapiPluginMock = player.loadedPlugins[OTTAnalyticsPluginTestTVPAPIMock.pluginName]!.plugin as! OTTAnalyticsPluginTestTVPAPIMock } afterEach { self.destroyPlayer(player) phoenixPluginMock = nil tvpapiPluginMock = nil } context("analytics events handling") { // events invocations count. let onAnalyticsEvent: (OTTAnalyticsEventType, MockableOTTAnalyticsPluginProtocol) -> Void = { eventType, analyticsPluginMock in var analyticsPluginMock = analyticsPluginMock print("received analytics event: \(eventType.rawValue)") switch eventType { case .first_play, .play: if eventType == .first_play { analyticsPluginMock.invocationCount.firstPlayCount += 1 DispatchQueue.main.asyncAfter(deadline: .now() + 2) { player.pause() } DispatchQueue.main.asyncAfter(deadline: .now() + 4) { player.play() } DispatchQueue.main.asyncAfter(deadline: .now() + 6) { player.pause() } DispatchQueue.main.asyncAfter(deadline: .now() + 8) { player.play() player.seek(to: player.duration - 1) } DispatchQueue.main.asyncAfter(deadline: .now() + 12) { expect(analyticsPluginMock.invocationCount.playCount).to(equal(3)) // 3 from player.play() expect(analyticsPluginMock.invocationCount.pauseCount).to(equal(2)) // 2 from player.pause() expect(analyticsPluginMock.invocationCount.firstPlayCount).to(equal(1)) // 1 from player.play() first play should happen only once expect(analyticsPluginMock.invocationCount.loadCount).to(equal(1)) // 1 from player.play() expect(analyticsPluginMock.invocationCount.endedCount).to(equal(1)) // 1 from ended after seek to end (ended) print(type(of: analyticsPluginMock)) analyticsPluginMock.finishedHandling = true } } if eventType == .first_play || eventType == .play { switch analyticsPluginMock.invocationCount.playCount { case 0: expect(eventType).to(equal(OTTAnalyticsEventType.first_play)) default: expect(eventType).to(equal(OTTAnalyticsEventType.play)) } analyticsPluginMock.invocationCount.playCount += 1 } case .pause: analyticsPluginMock.invocationCount.pauseCount += 1 case .load: analyticsPluginMock.invocationCount.loadCount += 1 case .finish: analyticsPluginMock.invocationCount.endedCount += 1 default: break } } it("tests event handling") { phoenixPluginMock.onAnalyticsEvent = onAnalyticsEvent tvpapiPluginMock.onAnalyticsEvent = onAnalyticsEvent // to start the whole flow we need to make an initial play player.play() expect(phoenixPluginMock.finishedHandling).toEventually(beTrue(), timeout: 20, pollInterval: 2, description: "makes sure finished handling the event") expect(tvpapiPluginMock.finishedHandling).toEventually(beTrue(), timeout: 20, pollInterval: 2, description: "makes sure finished handling the event") } } context("termination observation") { it("can observe termination") { AppStateSubjectMock.shared.add(observer: phoenixPluginMock) AppStateSubjectMock.shared.add(observer: tvpapiPluginMock) let onTerminate: (MockableOTTAnalyticsPluginProtocol) -> Void = { analyticsPluginMock in var analyticsPluginMock = analyticsPluginMock analyticsPluginMock.finishedHandling = true } phoenixPluginMock.onTerminate = onTerminate tvpapiPluginMock.onTerminate = onTerminate // to start the whole flow we need to make an initial play player.play() // post stub termination AppStateSubjectMock.shared.appStateEventPosted(name: .UIApplicationWillTerminate) expect(phoenixPluginMock.finishedHandling).toEventually(beTrue(), timeout: 20, pollInterval: 2, description: "makes sure finished handling the event") expect(tvpapiPluginMock.finishedHandling).toEventually(beTrue(), timeout: 20, pollInterval: 2, description: "makes sure finished handling the event") } it("receive stop event on termination when content not ended") { AppStateSubjectMock.shared.add(observer: phoenixPluginMock) AppStateSubjectMock.shared.add(observer: tvpapiPluginMock) let onAnalyticsEvent: (OTTAnalyticsEventType, MockableOTTAnalyticsPluginProtocol) -> Void = { eventType, analyticsPluginMock in var analyticsPluginMock = analyticsPluginMock switch eventType { case .stop: analyticsPluginMock.finishedHandling = true default: break } } phoenixPluginMock.onAnalyticsEvent = onAnalyticsEvent tvpapiPluginMock.onAnalyticsEvent = onAnalyticsEvent // to start the whole flow we need to make an initial play player.play() player.addObserver(self, event: PlayerEvent.playing) { event in // post stub termination only when started playing AppStateSubjectMock.shared.appStateEventPosted(name: .UIApplicationWillTerminate) } expect(phoenixPluginMock.finishedHandling).toEventually(beTrue(), timeout: 20, pollInterval: 2, description: "makes sure finished handling the event") expect(tvpapiPluginMock.finishedHandling).toEventually(beTrue(), timeout: 20, pollInterval: 2, description: "makes sure finished handling the event") } // this test make sure we don't receive stop event from ott analytics after the content ended. // we do this by playing the content and seeking to the end, // then we call terminate event that will call destroy() which in turn will activate the onTerminate block // if the termination will happen for the ott mock plugins without failing it means we haven't received the stop event and test is succeeded. it("doesn't receive stop event on termination when content ended") { AppStateSubjectMock.shared.add(observer: phoenixPluginMock) AppStateSubjectMock.shared.add(observer: tvpapiPluginMock) // check sent events if we receive stop event the test will fail let onAnalyticsEvent: (OTTAnalyticsEventType, MockableOTTAnalyticsPluginProtocol) -> Void = { eventType, analyticsPluginMock in var analyticsPluginMock = analyticsPluginMock switch eventType { case .stop: analyticsPluginMock.finishedHandling = true XCTFail() // if we receive stop event the test is failed, we should receive. default: break } } phoenixPluginMock.onAnalyticsEvent = onAnalyticsEvent tvpapiPluginMock.onAnalyticsEvent = onAnalyticsEvent // counts the number of terminations var terminationCount = 0 let onTerminate: (MockableOTTAnalyticsPluginProtocol) -> Void = { analyticsPluginMock in expect(analyticsPluginMock.finishedHandling).to(beFalse()) terminationCount += 1 } phoenixPluginMock.onTerminate = onTerminate tvpapiPluginMock.onTerminate = onTerminate var firstPlay = true // to start the whole flow we need to make an initial play player.play() player.addObserver(self, event: PlayerEvent.playing) { event in if firstPlay { firstPlay = false // seek to the end of the media print("player duration: \(player.duration)") player.currentTime = player.duration - 1 } } player.addObserver(self, event: PlayerEvent.ended) { event in // post stub termination only when ended AppStateSubjectMock.shared.appStateEventPosted(name: .UIApplicationWillTerminate) } // if no stop event will be recieved termination count should be 2 for the 2 mock plugins expect(terminationCount).toEventually(equal(2), timeout: 6) } } } } }
agpl-3.0
alirsamar/BiOS
beginning-ios-alien-adventure-alien-adventure-2/Alien Adventure/DialogueManager.swift
3
993
// // DialogueManager.swift // Alien Adventure // // Created by Jarrod Parkes on 7/15/15. // Copyright © 2015 Udacity. All rights reserved. // import SpriteKit // MARK: - DialogueManager class DialogueManager: SKNode { // MARK: Properties var dialogue: Dialogue! var widthOfDialogueNode: Int! // MARK: Initializers init(widthOfConverationNode: Int) { super.init() self.widthOfDialogueNode = widthOfConverationNode } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Display func displayNextLine(line: UDLineOfDialogue) { removeDialogueNode() dialogue = Dialogue(text: line.lineText, widthOfDialogue: widthOfDialogueNode, lineSource: line.lineSource) self.addChild(dialogue) } func removeDialogueNode() { if let dialogue = dialogue { dialogue.removeFromParent() } } }
mit
kaideyi/KDYSample
SlideTabBar/SlideTabBar/AppDelegate.swift
1
732
// // AppDelegate.swift // SlideTabBar // // Created by kaideyi on 2017/2/19. // Copyright © 2017年 kaideyi.com. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) let controller = ViewController() let navigation = UINavigationController(rootViewController: controller) window?.rootViewController = navigation window?.makeKeyAndVisible() return true } }
mit
salesforce-ux/design-system-ios
Demo-Swift/slds-sample-app/library/controls/ItemBar.swift
1
4612
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved // Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license import UIKit protocol ItemBarDelegate { func itemBar(_ itemBar: ItemBar, didSelectItemAt index: NSInteger) } class ItemBar: UIControl { var items = Array<UIControl>() var delegate : ItemBarDelegate? //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var selectedIndex : Int = 0 { didSet { if let d = self.delegate { d.itemBar(self, didSelectItemAt: selectedIndex) } } } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var itemWidth : CGFloat { return self.frame.width / CGFloat(self.items.count) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override init (frame : CGRect) { super.init(frame : frame) self.loadView() } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– convenience init () { self.init(frame:CGRect.zero) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– required init(coder aDecoder: NSCoder) { fatalError("This class does not support NSCoding") } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– func loadView() { self.backgroundColor = UIColor.white } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func layoutSubviews() { super.layoutSubviews() for item in self.items { item.heightConstraint.constant = self.frame.height item.widthConstraint.constant = self.itemWidth } } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– func didSelectItemAt(sender: UIControl) { if let index = items.index(of: sender) { self.selectedIndex = index } } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– func removeItems() { for item in self.items { item.removeFromSuperview() } self.items.removeAll() } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– func addItem(item : UIControl) { self.addSubview(item) if items.count > 0 { item.constrainRightOf(items.last!, yAlignment: .bottom) } else { self.constrainChild(item, xAlignment: .left, yAlignment: .bottom) } self.items.append(item) item.addTarget(self, action: #selector(ItemBar.didSelectItemAt(sender:)), for: .touchUpInside) self.layoutIfNeeded() } }
bsd-3-clause
fernandomarins/food-drivr-pt
hackathon-for-hunger/Modules/Driver/SignUp/Views/DriverSignupViewController.swift
1
4995
// // VSUserInfoViewController.swift // hackathon-for-hunger // // Created by ivan lares on 4/4/16. // Copyright © 2016 Hacksmiths. All rights reserved. // import UIKit enum State { case IncompleteField case NotEmail case Custom(String, String) case None } class DriverSignupViewController: UIViewController { // Mark: Propety @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var phoneTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! // Mark: Regular expression for email private let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" private var user = UserRegistration() private let signupPresenter = DriverSignupPresenter(userService: UserService()) var activityIndicator: ActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() activityIndicator = ActivityIndicatorView(inview: self.view, messsage: "Registering") signupPresenter.attachView(self) } // MARK: Actions @IBAction func didPressSignUp(sender: AnyObject) { let donorIsApproved = false if donorIsApproved{ } else { signUp() } } // MARK: Navigation func showAwaitingApprovalView(){ let storyboard = UIStoryboard(name: "Main", bundle: nil) let awaitingApprovalViewController = storyboard.instantiateViewControllerWithIdentifier("AwaitingApprovalDriverView") as! AwaitingApprovalDriverViewController navigationController?.pushViewController(awaitingApprovalViewController, animated: true) } } extension DriverSignupViewController { func signUp() { let validationState = isValid() switch(validationState) { case .None: createUser() sendToServer() case .IncompleteField: showAlert(validationState) case .NotEmail: showAlert(validationState) default: return } } private func sendToServer() { self.startLoading() signupPresenter.register(self.user) } private func createUser() { self.user.email = emailTextField.text self.user.phone = phoneTextField.text self.user.name = nameTextField.text self.user.password = passwordTextField.text self.user.role = .Donor } private func isValid() -> State { if nameTextField.text == "" && phoneTextField.text == "" && emailTextField.text == "" && passwordTextField.text == "" { return .IncompleteField }else if !isValidEmail(emailTextField.text!) { return .NotEmail } return .None } // check if the email is valid private func isValidEmail(email: String) -> Bool { let emailTest = NSPredicate(format:"SELF MATCHES %@", self.emailRegEx) return emailTest.evaluateWithObject(email) } private func showAlert(state: State) { var title = "" var message = "" let buttonTitle = "try" switch state { case .IncompleteField: title = "Incomplete Field" message = "Please ensure you complete all fields" case .NotEmail: title = "Incorrect email" message = "Please ensure you enter a valid email" case .Custom(let titleAlert, let messageAlert): title = titleAlert message = messageAlert case .None: return } let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) let alertAction = UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.Default, handler: nil ) alert.addAction(alertAction) presentViewController(alert, animated: true, completion: nil) } } extension DriverSignupViewController: SignupView { func startLoading() { self.activityIndicator.startAnimating() } func finishLoading() { self.activityIndicator.stopAnimating() } func registration(sender: DriverSignupPresenter, didSucceed success: [String: AnyObject]) { self.activityIndicator.stopAnimating() self.showAwaitingApprovalView() } func registration(sender: DriverSignupPresenter, didFail error: NSError) { self.activityIndicator.stopAnimating() let alert = UIAlertController(title: "There was a problem", message: "Unable to register you at this time", preferredStyle: .Alert) let alertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil ) alert.addAction(alertAction) presentViewController(alert, animated: true, completion: nil) } }
mit
edx/edx-app-ios
Source/RatingViewController.swift
1
7363
// // RatingViewController.swift // edX // // Created by Danial Zahid on 1/23/17. // Copyright © 2017 edX. All rights reserved. // import UIKit import MessageUI protocol RatingViewControllerDelegate { func didDismissRatingViewController() } class RatingViewController: UIViewController, RatingContainerDelegate { typealias Environment = DataManagerProvider & OEXInterfaceProvider & OEXStylesProvider & OEXConfigProvider & OEXAnalyticsProvider var delegate : RatingViewControllerDelegate? static let minimumPositiveRating : Int = 4 static let minimumVersionDifferenceForNegativeRating = 2 let environment : Environment let ratingContainerView : RatingContainerView var alertController : UIAlertController? private var selectedRating : Int? static func canShowAppReview(environment: Environment) -> Bool { guard let _ = environment.config.appReviewURI, environment.interface?.reachable ?? false && environment.config.isAppReviewsEnabled else { return false } if let appRating = environment.interface?.getSavedAppRating(), let lastVersionForAppReview = environment.interface?.getSavedAppVersionWhenLastRated(){ let version = Version(version: (Bundle.main.oex_shortVersionString())) let savedVersion = Version(version: lastVersionForAppReview) let validVersionDiff = version.isNMinorVersionsDiff(otherVersion: savedVersion, minorVersionDiff: minimumVersionDifferenceForNegativeRating) if appRating >= minimumPositiveRating || !validVersionDiff { return false } } return true } init(environment : Environment) { self.environment = environment ratingContainerView = RatingContainerView(environment: environment) super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(white: 0.0, alpha: 0.3) view.addSubview(ratingContainerView) ratingContainerView.delegate = self setupConstraints() view.accessibilityElements = [ratingContainerView.subviews] } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) environment.analytics.trackAppReviewScreen() } private func setupConstraints() { ratingContainerView.snp.remakeConstraints { make in make.centerX.equalTo(view.snp.centerX) make.centerY.equalTo(view.snp.centerY) make.width.equalTo(275) } } //MARK: - RatingContainerDelegate methods func didSubmitRating(rating: Int) { selectedRating = Int(rating) ratingContainerView.removeFromSuperview() environment.analytics.trackSubmitRating(rating: rating) switch rating { case 1...3: negativeRatingReceived() break case 4...5: positiveRatingReceived() break default: break } } func closeButtonPressed() { saveAppRating() environment.analytics.trackDismissRating() dismissViewController() } //MARK: - Positive Rating methods private func positiveRatingReceived() { alertController = UIAlertController().showAlert(withTitle: Strings.AppReview.rateTheApp, message: Strings.AppReview.positiveReviewMessage,cancelButtonTitle: nil, onViewController: self) alertController?.addButton(withTitle: Strings.AppReview.maybeLater) {[weak self] (action) in self?.saveAppRating() if let rating = self?.selectedRating { self?.environment.analytics.trackMaybeLater(rating: rating) } self?.dismissViewController() } alertController?.addButton(withTitle: Strings.AppReview.rateTheApp) {[weak self] (action) in self?.saveAppRating(rating: self?.selectedRating) if let rating = self?.selectedRating { self?.environment.analytics.trackRateTheApp(rating: rating) } self?.sendUserToAppStore() self?.dismissViewController() } } private func sendUserToAppStore() { guard let url = URL(string: environment.config.appReviewURI ?? "") else { return } if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } //MARK: - Negative Rating methods private func negativeRatingReceived() { alertController = UIAlertController().showAlert(withTitle: Strings.AppReview.sendFeedbackTitle, message: Strings.AppReview.helpUsImprove,cancelButtonTitle: nil, onViewController: self) alertController?.addButton(withTitle: Strings.AppReview.maybeLater) {[weak self] (action) in self?.saveAppRating() if let rating = self?.selectedRating { self?.environment.analytics.trackMaybeLater(rating: rating) } self?.dismissViewController() } alertController?.addButton(withTitle: Strings.AppReview.sendFeedback) {[weak self] (action) in self?.saveAppRating(rating: self?.selectedRating) if let rating = self?.selectedRating { self?.environment.analytics.trackSendFeedback(rating: rating) } self?.launchEmailComposer() } } //MARK: - Persistence methods func saveAppRating(rating: Int? = 0) { environment.interface?.saveAppRating(rating: rating ?? 0) environment.interface?.saveAppVersionWhenLastRated() } //MARK: - Expose for testcases func setRating(rating: Int) { ratingContainerView.setRating(rating: rating) } func dismissViewController() { dismiss(animated: false) {[weak self] in self?.delegate?.didDismissRatingViewController() } } } extension RatingViewController : MFMailComposeViewControllerDelegate { func launchEmailComposer() { if !MFMailComposeViewController.canSendMail() { UIAlertController().showAlert(withTitle: Strings.emailAccountNotSetUpTitle, message: Strings.emailAccountNotSetUpMessage, onViewController: self) dismissViewController() } else { let mail = MFMailComposeViewController() mail.mailComposeDelegate = self mail.navigationBar.tintColor = OEXStyles.shared().navigationItemTintColor() mail.setSubject(Strings.AppReview.messageSubject) mail.setMessageBody(EmailTemplates.supportEmailMessageTemplate(), isHTML: false) if let fbAddress = environment.config.feedbackEmailAddress() { mail.setToRecipients([fbAddress]) } present(mail, animated: true, completion: nil) } } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true, completion: nil) dismissViewController() } }
apache-2.0
edx/edx-app-ios
Source/UpgradeSKUManager.swift
1
1137
// // UpgradeSKUManager.swift // edX // // Created by Muhammad Umer on 22/12/2021. // Copyright © 2021 edX. All rights reserved. // import Foundation class UpgradeSKUManager { static let shared = UpgradeSKUManager() /// TODO: Test mapping for course ID to map with registered sku on AppStoreConnect, /// it will be updated with the updated mappings in future private lazy var skuMappings: [String : String] = { return [ "course-v1:edX+DemoX+Demo_Course": "org.edx.mobile.integrationtest", "course-v1:DemoX+PERF101+course": "org.edx.mobile.test_product1", "course-v1:edX+Test101+course": "org.edx.mobile.test_product2", "course-v1:test2+2+2": "org.edx.mobile.test_product3", "course-v1:test3+test3+3": "org.edx.mobile.test_product4" ] }() private init() { } func courseSku(for course: OEXCourse) -> String? { guard let courseID = course.course_id, skuMappings.keys.contains(courseID), let courseSku = skuMappings[courseID] else { return nil } return courseSku } }
apache-2.0
superpixelhq/AbairLeat-iOS
Abair LeatUITests/Abair_LeatUITests.swift
1
1260
// // Abair_LeatUITests.swift // Abair LeatUITests // // Created by Aaron Signorelli on 19/11/2015. // Copyright © 2015 Superpixel. All rights reserved. // import XCTest class Abair_LeatUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
apache-2.0
sunshinejr/Moya-ModelMapper
Demo/Pods/Moya/Sources/Moya/Plugins/NetworkLoggerPlugin.swift
1
9805
import Foundation /// Logs network activity (outgoing requests and incoming responses). public final class NetworkLoggerPlugin { public var configuration: Configuration /// Initializes a NetworkLoggerPlugin. public init(configuration: Configuration = Configuration()) { self.configuration = configuration } } // MARK: - PluginType extension NetworkLoggerPlugin: PluginType { public func willSend(_ request: RequestType, target: TargetType) { logNetworkRequest(request, target: target) { [weak self] output in self?.configuration.output(target, output) } } public func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType) { switch result { case .success(let response): configuration.output(target, logNetworkResponse(response, target: target, isFromError: false)) case let .failure(error): configuration.output(target, logNetworkError(error, target: target)) } } } // MARK: - Logging private extension NetworkLoggerPlugin { func logNetworkRequest(_ request: RequestType, target: TargetType, completion: @escaping ([String]) -> Void) { //cURL formatting if configuration.logOptions.contains(.formatRequestAscURL) { _ = request.cURLDescription { [weak self] output in guard let self = self else { return } completion([self.configuration.formatter.entry("Request", output, target)]) } return } //Request presence check guard let httpRequest = request.request else { completion([configuration.formatter.entry("Request", "(invalid request)", target)]) return } // Adding log entries for each given log option var output = [String]() output.append(configuration.formatter.entry("Request", httpRequest.description, target)) if configuration.logOptions.contains(.requestHeaders) { var allHeaders = request.sessionHeaders if let httpRequestHeaders = httpRequest.allHTTPHeaderFields { allHeaders.merge(httpRequestHeaders) { $1 } } output.append(configuration.formatter.entry("Request Headers", allHeaders.description, target)) } if configuration.logOptions.contains(.requestBody) { if let bodyStream = httpRequest.httpBodyStream { output.append(configuration.formatter.entry("Request Body Stream", bodyStream.description, target)) } if let body = httpRequest.httpBody { let stringOutput = configuration.formatter.requestData(body) output.append(configuration.formatter.entry("Request Body", stringOutput, target)) } } if configuration.logOptions.contains(.requestMethod), let httpMethod = httpRequest.httpMethod { output.append(configuration.formatter.entry("HTTP Request Method", httpMethod, target)) } completion(output) } func logNetworkResponse(_ response: Response, target: TargetType, isFromError: Bool) -> [String] { // Adding log entries for each given log option var output = [String]() //Response presence check if let httpResponse = response.response { output.append(configuration.formatter.entry("Response", httpResponse.description, target)) } else { output.append(configuration.formatter.entry("Response", "Received empty network response for \(target).", target)) } if (isFromError && configuration.logOptions.contains(.errorResponseBody)) || configuration.logOptions.contains(.successResponseBody) { let stringOutput = configuration.formatter.responseData(response.data) output.append(configuration.formatter.entry("Response Body", stringOutput, target)) } return output } func logNetworkError(_ error: MoyaError, target: TargetType) -> [String] { //Some errors will still have a response, like errors due to Alamofire's HTTP code validation. if let moyaResponse = error.response { return logNetworkResponse(moyaResponse, target: target, isFromError: true) } //Errors without an HTTPURLResponse are those due to connectivity, time-out and such. return [configuration.formatter.entry("Error", "Error calling \(target) : \(error)", target)] } } // MARK: - Configuration public extension NetworkLoggerPlugin { struct Configuration { // MARK: - Typealiases // swiftlint:disable nesting public typealias OutputType = (_ target: TargetType, _ items: [String]) -> Void // swiftlint:enable nesting // MARK: - Properties public var formatter: Formatter public var output: OutputType public var logOptions: LogOptions /// The designated way to instanciate a Configuration. /// /// - Parameters: /// - formatter: An object holding all formatter closures available for customization. /// - output: A closure responsible for writing the given log entries into your log system. /// The default value writes entries to the debug console. /// - logOptions: A set of options you can use to customize which request component is logged. public init(formatter: Formatter = Formatter(), output: @escaping OutputType = defaultOutput, logOptions: LogOptions = .default) { self.formatter = formatter self.output = output self.logOptions = logOptions } // MARK: - Defaults public static func defaultOutput(target: TargetType, items: [String]) { for item in items { print(item, separator: ",", terminator: "\n") } } } } public extension NetworkLoggerPlugin.Configuration { struct LogOptions: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } /// The request's method will be logged. public static let requestMethod: LogOptions = LogOptions(rawValue: 1 << 0) /// The request's body will be logged. public static let requestBody: LogOptions = LogOptions(rawValue: 1 << 1) /// The request's headers will be logged. public static let requestHeaders: LogOptions = LogOptions(rawValue: 1 << 2) /// The request will be logged in the cURL format. /// /// If this option is used, the following components will be logged regardless of their respective options being set: /// - request's method /// - request's headers /// - request's body. public static let formatRequestAscURL: LogOptions = LogOptions(rawValue: 1 << 3) /// The body of a response that is a success will be logged. public static let successResponseBody: LogOptions = LogOptions(rawValue: 1 << 4) /// The body of a response that is an error will be logged. public static let errorResponseBody: LogOptions = LogOptions(rawValue: 1 << 5) //Aggregate options /// Only basic components will be logged. public static let `default`: LogOptions = [requestMethod, requestHeaders] /// All components will be logged. public static let verbose: LogOptions = [requestMethod, requestHeaders, requestBody, successResponseBody, errorResponseBody] } } public extension NetworkLoggerPlugin.Configuration { struct Formatter { // MARK: Typealiases // swiftlint:disable nesting public typealias DataFormatterType = (Data) -> (String) public typealias EntryFormatterType = (_ identifier: String, _ message: String, _ target: TargetType) -> String // swiftlint:enable nesting // MARK: Properties public var entry: EntryFormatterType public var requestData: DataFormatterType public var responseData: DataFormatterType /// The designated way to instanciate a Formatter. /// /// - Parameters: /// - entry: The closure formatting a message into a new log entry. /// - requestData: The closure converting HTTP request's body into a String. /// The default value assumes the body's data is an utf8 String. /// - responseData: The closure converting HTTP response's body into a String. /// The default value assumes the body's data is an utf8 String. public init(entry: @escaping EntryFormatterType = defaultEntryFormatter, requestData: @escaping DataFormatterType = defaultDataFormatter, responseData: @escaping DataFormatterType = defaultDataFormatter) { self.entry = entry self.requestData = requestData self.responseData = responseData } // MARK: Defaults public static func defaultDataFormatter(_ data: Data) -> String { return String(data: data, encoding: .utf8) ?? "## Cannot map data to String ##" } public static func defaultEntryFormatter(identifier: String, message: String, target: TargetType) -> String { let date = defaultEntryDateFormatter.string(from: Date()) return "Moya_Logger: [\(date)] \(identifier): \(message)" } static var defaultEntryDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.timeStyle = .short formatter.dateStyle = .short return formatter }() } }
mit
faimin/Tropos
Sources/Tropos/Extensions/CATransition.swift
2
337
import UIKit extension CATransition { @nonobjc static var fade: CATransition { let transition = CATransition() transition.duration = 0.3 transition.type = kCATransitionFade transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) return transition } }
mit
Yalantis/PixPic
PixPic/Classes/DTO/Complaint.swift
1
1556
// // Complaint.swift // PixPic // // Created by Illya on 3/1/16. // Copyright © 2016 Yalantis. All rights reserved. // import UIKit class Complaint: PFObject { @NSManaged var complainer: User @NSManaged var complaintReason: String @NSManaged var suspectedUser: User @NSManaged var suspectedPost: Post? private static var onceToken: dispatch_once_t = 0 override class func initialize() { dispatch_once(&onceToken) { self.registerSubclass() } } convenience init(user: User, post: Post? = nil, reason: ComplaintReason) { self.init() if let post = post { suspectedPost = post } guard let complainer = User.currentUser() else { log.debug("Nil current user") return } self.complainer = complainer self.complaintReason = NSLocalizedString(reason.rawValue, comment: "") self.suspectedUser = user } func postQuery() -> PFQuery { let query = PFQuery(className: Complaint.parseClassName()) query.cachePolicy = .NetworkElseCache query.orderByDescending("updatedAt") query.whereKey("complainer", equalTo: complainer) // query is called only when suspectedPost != nil query.whereKey("suspectedPost", equalTo: suspectedPost!) query.whereKey("suspectedUser", equalTo: suspectedUser) return query } } extension Complaint: PFSubclassing { static func parseClassName() -> String { return "Complaint" } }
mit
benlangmuir/swift
test/Interop/Cxx/union/anonymous-union-partly-invalid.swift
8
320
// RUN: %swift -I %S/Inputs -enable-experimental-cxx-interop -enable-objc-interop -emit-ir %s | %FileCheck %s import AnonymousUnionPartlyInvalid let sPtr = getSPtr() let a = sPtr![0].f() // CHECK: i32 @main // CHECK-NEXT: entry: // CHECK-NEXT: bitcast // CHECK-NEXT: call %struct.S // CHECK-NEXT: ptrtoint %struct.S
apache-2.0
benlangmuir/swift
test/SILGen/auto_generated_super_init_call.swift
7
5982
// RUN: %target-swift-emit-silgen -Xllvm -sil-print-debuginfo %s | %FileCheck %s // Test that we emit a call to super.init at the end of the initializer, when none has been previously added. class Parent { init() {} } class SomeDerivedClass : Parent { var y: Int func foo() {} override init() { y = 42 // CHECK-LABEL: sil hidden [ossa] @$s30auto_generated_super_init_call16SomeDerivedClassC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned SomeDerivedClass) -> @owned SomeDerivedClass // CHECK: integer_literal $Builtin.IntLiteral, 42 // CHECK: [[SELFLOAD:%[0-9]+]] = load [take] [[SELF:%[0-9]+]] : $*SomeDerivedClass // CHECK-NEXT: [[PARENT:%[0-9]+]] = upcast [[SELFLOAD]] : $SomeDerivedClass to $Parent // CHECK-NEXT: // function_ref // CHECK-NEXT: [[INITCALL1:%[0-9]+]] = function_ref @$s30auto_generated_super_init_call6ParentCACycfc : $@convention(method) (@owned Parent) -> @owned Parent // CHECK-NEXT: [[RES1:%[0-9]+]] = apply [[INITCALL1]]([[PARENT]]) // CHECK-NEXT: [[DOWNCAST:%[0-9]+]] = unchecked_ref_cast [[RES1]] : $Parent to $SomeDerivedClass // CHECK-NEXT: store [[DOWNCAST]] to [init] [[SELF]] : $*SomeDerivedClass } init(x: Int) { y = x // CHECK-LABEL: sil hidden [ossa] @$s30auto_generated_super_init_call16SomeDerivedClassC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (Int, @owned SomeDerivedClass) -> @owned SomeDerivedClass // CHECK: function_ref @$s30auto_generated_super_init_call6ParentCACycfc : $@convention(method) (@owned Parent) -> @owned Parent } init(b: Bool) { if b { y = 0 return } else { y = 10 } return // Check that we are emitting the super.init expr into the epilog block. // CHECK-LABEL: sil hidden [ossa] @$s30auto_generated_super_init_call16SomeDerivedClassC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (Bool, @owned SomeDerivedClass) -> @owned SomeDerivedClass // CHECK: bb5: // SEMANTIC ARC TODO: Another case of needing a mutable load_borrow. // CHECK-NEXT: [[SELFLOAD:%[0-9]+]] = load [take] [[SELF:%[0-9]+]] : $*SomeDerivedClass // CHECK-NEXT: [[SELFLOAD_PARENT_CAST:%.*]] = upcast [[SELFLOAD]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[PARENT_INIT:%.*]] = function_ref @$s30auto_generated_super_init_call6ParentCACycfc : $@convention(method) (@owned Parent) -> @owned Parent, // CHECK-NEXT: [[PARENT:%.*]] = apply [[PARENT_INIT]]([[SELFLOAD_PARENT_CAST]]) // CHECK-NEXT: [[SELFAGAIN:%.*]] = unchecked_ref_cast [[PARENT]] // CHECK-NEXT: store [[SELFAGAIN]] to [init] [[SELF]] // CHECK-NEXT: [[SELFLOAD:%.*]] = load [copy] [[SELF]] // CHECK-NEXT: end_borrow // CHECK-NEXT: destroy_value // CHECK-NEXT: return [[SELFLOAD]] } // CHECK: } // end sil function '$s30auto_generated_super_init_call16SomeDerivedClassC{{[_0-9a-zA-Z]*}}fc' // One init has a call to super init. Make sure we don't insert more than one. init(b: Bool, i: Int) { if (b) { y = i } else { y = 0 } super.init() // CHECK-LABEL: sil hidden [ossa] @$s30auto_generated_super_init_call16SomeDerivedClassC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (Bool, Int, @owned SomeDerivedClass) -> @owned SomeDerivedClass // CHECK: function_ref @$s30auto_generated_super_init_call6ParentCACycfc : $@convention(method) (@owned Parent) -> @owned Parent // CHECK: return } } // Check that we do call super.init. class HasNoIVars : Parent { override init() { // CHECK-LABEL: sil hidden [ossa] @$s30auto_generated_super_init_call10HasNoIVarsC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned HasNoIVars) -> @owned HasNoIVars // CHECK: function_ref @$s30auto_generated_super_init_call6ParentCACycfc : $@convention(method) (@owned Parent) -> @owned Parent } } // Check that we don't call super.init. class ParentLess { var y: Int init() { y = 0 } } class Grandparent { init() {} } // This should have auto-generated default initializer. class ParentWithNoExplicitInit : Grandparent { } // Check that we add a call to super.init. class ChildOfParentWithNoExplicitInit : ParentWithNoExplicitInit { var y: Int override init() { y = 10 // CHECK-LABEL: sil hidden [ossa] @$s30auto_generated_super_init_call31ChildOfParentWithNoExplicitInitC{{[_0-9a-zA-Z]*}}fc // CHECK: function_ref @$s30auto_generated_super_init_call24ParentWithNoExplicitInitCACycfc : $@convention(method) (@owned ParentWithNoExplicitInit) -> @owned ParentWithNoExplicitInit } } // This should have auto-generated default initializer. class ParentWithNoExplicitInit2 : Grandparent { var i: Int = 0 } // Check that we add a call to super.init. class ChildOfParentWithNoExplicitInit2 : ParentWithNoExplicitInit2 { var y: Int override init() { y = 10 // CHECK-LABEL: sil hidden [ossa] @$s30auto_generated_super_init_call32ChildOfParentWithNoExplicitInit2C{{[_0-9a-zA-Z]*}}fc // CHECK: function_ref @$s30auto_generated_super_init_call25ParentWithNoExplicitInit2CACycfc : $@convention(method) (@owned ParentWithNoExplicitInit2) -> @owned ParentWithNoExplicitInit2 } } // Do not insert the call nor warn - the user should call init(5). class ParentWithNoDefaultInit { var i: Int init(x: Int) { i = x } } class ChildOfParentWithNoDefaultInit : ParentWithNoDefaultInit { var y: Int init() { // CHECK-LABEL: sil hidden [ossa] @$s30auto_generated_super_init_call30ChildOfParentWithNoDefaultInitC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned ChildOfParentWithNoDefaultInit) -> @owned ChildOfParentWithNoDefaultInit // CHECK: bb0 // CHECK-NOT: apply // CHECK: return } } // <https://bugs.swift.org/browse/SR-5974> - auto-generated super.init() // delegation to a throwing or failing initializer class FailingParent { init?() {} } class ThrowingParent { init() throws {} } class FailingThrowingParent { init?() throws {} } class FailingChild : FailingParent { override init?() {} } class ThrowingChild : ThrowingParent { override init() throws {} } class FailingThrowingChild : FailingThrowingParent { override init?() throws {} }
apache-2.0
deekshithbellare/Tweelight
Tweelight/Tweelight/AppDelegate.swift
1
504
// // AppDelegate.swift // Tweelight // // Created by Deekshith Bellare on 22/08/15. // Copyright © 2015 deekshithbellare. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } }
mit
MKGitHub/UIPheonix
Demo/iOS/DemoCollectionViewController.swift
1
11386
/** UIPheonix Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved. https://github.com/MKGitHub/UIPheonix http://www.xybernic.com Copyright 2016/2017/2018/2019 Mohsan Khan Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit final class DemoCollectionViewController:UIPBaseViewController, UIPButtonDelegate, UICollectionViewDataSource, /*UICollectionViewDataSourcePrefetching,*/ UICollectionViewDelegateFlowLayout { // MARK: Public Inner Struct struct AttributeKeyName { static let appDisplayState = "AppDisplayState" } // MARK: Public IB Outlet @IBOutlet private weak var ibCollectionView:UICollectionView! // MARK: Private Members private var mAppDisplayStateType:AppDisplayStateType! private var mUIPheonix:UIPheonix! // (for demo purpose only) private var mPersistentDisplayModels:Array<UIPBaseCellModelProtocol>? // MARK:- Life Cycle override func viewDidLoad() { super.viewDidLoad() // init member mAppDisplayStateType = (newInstanceAttributes[AttributeKeyName.appDisplayState] as! AppDisplayState).value initUIPheonix() setupCollectionView() updateView() } // MARK:- UICollectionViewDataSource func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int { return mUIPheonix.displayModelsCount(forSection:0) } func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell { return mUIPheonix.collectionViewCell(forIndexPath:indexPath) } // MARK:- UICollectionViewDataSourcePrefetching /** Not used in this example. */ /*@available(iOS 10.0, *) func collectionView(_ collectionView:UICollectionView, prefetchItemsAt indexPaths:[IndexPath]) { // empty for now }*/ // MARK:- UICollectionViewDelegate func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, insetForSectionAt section:Int) -> UIEdgeInsets { return UIEdgeInsets(top:10, left:0, bottom:10, right:0) } func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, minimumLineSpacingForSectionAt section:Int) -> CGFloat { return 10 } func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize { return mUIPheonix.collectionViewCellSize(forIndexPath:indexPath) } // MARK:- UIPButtonDelegate func handleAction(forButtonId buttonId:Int) { var isTheAppendModelsDemo:Bool = false var isThePersistentModelsDemo:Bool = false var isTheCustomMadeModelsDemo:Bool = false var shouldAnimateChange:Bool = true // set the display state depending on which button we clicked switch (buttonId) { case ButtonId.startUp.rawValue: mAppDisplayStateType = AppDisplayState.startUp.value; break case ButtonId.mixed.rawValue: mAppDisplayStateType = AppDisplayState.mixed.value; break case ButtonId.animations.rawValue: mAppDisplayStateType = AppDisplayState.animations.value; break case ButtonId.switching.rawValue: mAppDisplayStateType = AppDisplayState.switching.value; break case ButtonId.appending.rawValue: mAppDisplayStateType = AppDisplayState.appending.value; break case ButtonId.appendingReload.rawValue: mAppDisplayStateType = AppDisplayState.appending.value isTheAppendModelsDemo = true shouldAnimateChange = false break case ButtonId.persistent.rawValue: mAppDisplayStateType = AppDisplayState.persistent.value isThePersistentModelsDemo = true break case ButtonId.persistentGoBack.rawValue: mAppDisplayStateType = AppDisplayState.startUp.value // when we leave the state, store the current display models for later reuse // so that when we re-enter the state, we can just use them as they were mPersistentDisplayModels = mUIPheonix.displayModels(forSection:0) break case ButtonId.specific.rawValue: mAppDisplayStateType = AppDisplayState.specific.value; break case ButtonId.customMadeModels.rawValue: mAppDisplayStateType = AppDisplayState.customMadeModels.value; isTheCustomMadeModelsDemo = true break default: mAppDisplayStateType = AppDisplayState.startUp.value; break } // update UI if (shouldAnimateChange) { animateView(animationState:false, completionHandler: { [weak self] in guard let self = self else { fatalError("DemoCollectionViewController buttonAction: `self` does not exist anymore!") } self.updateView(isTheAppendModelsDemo:isTheAppendModelsDemo, isThePersistentDemo:isThePersistentModelsDemo, isTheCustomMadeModelsDemo:isTheCustomMadeModelsDemo) self.animateView(animationState:true, completionHandler:nil) }) } else { updateView(isTheAppendModelsDemo:isTheAppendModelsDemo, isThePersistentDemo:isThePersistentModelsDemo, isTheCustomMadeModelsDemo:isTheCustomMadeModelsDemo) } } // MARK:- Private private func initUIPheonix() { mUIPheonix = UIPheonix(collectionView:ibCollectionView, delegate:self) } private func setupCollectionView() { /** Does not seem to work, bug reported to Apple. */ /*if #available(iOS 10.0, *) { (ibCollectionView.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize //(ibCollectionView.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = CGSize(width:ibCollectionView.bounds.width, height:50) } else { // fallback on earlier versions (ibCollectionView.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = CGSize(width:ibCollectionView.bounds.width, height:50) }*/ ibCollectionView.delegate = self ibCollectionView.dataSource = self /** Not used in this example. */ /*if #available(iOS 10.0, *) { ibCollectionView.prefetchDataSource = self // ibCollectionView.isPrefetchingEnabled, true by default } else { // fallback on earlier versions }*/ } private func setupWithJSON() { if let jsonDictionary = DataProvider.loadJSON(inFilePath:mAppDisplayStateType.jsonFileName.rawValue) { mUIPheonix.setModelViewRelationships(withDictionary:jsonDictionary[UIPConstants.Collection.modelViewRelationships] as! Dictionary<String, String>) mUIPheonix.setDisplayModels(jsonDictionary[UIPConstants.Collection.cellModels] as! Array<Any>, forSection:0, append:false) } else { fatalError("DemoCollectionViewController setupWithJSON: Failed to init with JSON file!") } } private func setupWithModels() { mUIPheonix.setModelViewRelationships(withDictionary:[SimpleButtonModel.nameOfClass:SimpleButtonModelCVCell.nameOfClass, SimpleCounterModel.nameOfClass:SimpleCounterModelCVCell.nameOfClass, SimpleLabelModel.nameOfClass:SimpleLabelModelCVCell.nameOfClass, SimpleTextFieldModel.nameOfClass:SimpleTextFieldModelCVCell.nameOfClass, SimpleVerticalSpaceModel.nameOfClass:SimpleVerticalSpaceModelCVCell.nameOfClass, SimpleViewAnimationModel.nameOfClass:SimpleViewAnimationModelCVCell.nameOfClass]) var models = [UIPBaseCellModel]() for i in 1 ... 20 { let simpleLabelModel = SimpleLabelModel(text:" Label \(i)", size:(12.0 + CGFloat(i) * 2.0), alignment:SimpleLabelModel.Alignment.left, style:SimpleLabelModel.Style.regular, backgroundColorHue:(CGFloat(i) * 0.05), notificationId:"") models.append(simpleLabelModel) } let simpleButtonModel = SimpleButtonModel(id:ButtonId.startUp.rawValue, title:"Enough with the RAINBOW!") models.append(simpleButtonModel) mUIPheonix.setDisplayModels(models, forSection:0) } private func updateView(isTheAppendModelsDemo:Bool=false, isThePersistentDemo:Bool=false, isTheCustomMadeModelsDemo:Bool=false) { if (isTheAppendModelsDemo) { // append the current display models list to itself mUIPheonix.addDisplayModels(mUIPheonix.displayModels(forSection:0), inSection:0) } else if (isThePersistentDemo) { if (mPersistentDisplayModels == nil) { setupWithJSON() } else { // set the persistent display models mUIPheonix!.setDisplayModels(mPersistentDisplayModels!, forSection:0) } } else if (isTheCustomMadeModelsDemo) { setupWithModels() } else { setupWithJSON() } // reload the collection view ibCollectionView.reloadData() } private func animateView(animationState:Bool, completionHandler:(()->Void)?) { // do a nice fading animation UIView.animate(withDuration:0.25, animations: { [weak self] in guard let self = self else { fatalError("DemoCollectionViewController animateView: `self` does not exist anymore!") } self.ibCollectionView.alpha = animationState ? 1.0 : 0.0 }, completion: { (animationCompleted:Bool) in completionHandler?() }) } }
apache-2.0
Mattmlm/codepath-twitter-redux
Codepath Twitter/Codepath Twitter/TwitterMenuViewController.swift
1
1914
// // TwitterMenuViewController.swift // Codepath Twitter // // Created by admin on 10/9/15. // Copyright © 2015 mattmo. All rights reserved. // import UIKit protocol TimelineChangeDelegate: class { func changeTimeline(type: TimelineType); } class TwitterMenuViewController: UIViewController { weak var menuButtonDelegate: MenuButtonDelegate? weak var timelineChangeDelegate: TimelineChangeDelegate? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func homeButtonPressed(sender: Any) { // self.menuButtonDelegate?.closeMenu() // self.timelineChangeDelegate?.changeTimeline(TimelineType.Home); } // @IBAction func profileButtonPressed(sender: Any) { // self.menuButtonDelegate?.closeMenu() // let profileVC = TwitterProfileViewController() // profileVC.user = User.currentUser // let navVC = UINavigationController(rootViewController: profileVC) // self.presentViewController(navVC, animated: true, completion: nil) } // @IBAction func mentionsButtonPressed(sender: Any) { // self.menuButtonDelegate?.closeMenu() // self.timelineChangeDelegate?.changeTimeline(TimelineType.Mentions) } @IBAction func signOutButtonPressed(sender: Any) { // User.currentUser?.logout() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
khizkhiz/swift
validation-test/compiler_crashers_fixed/01654-swift-astprinter-printname.swift
1
333
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func d<e? { struct c { class A { struct c : Collection where I) { } } } var b((Any, e(x) -> S) { } protocol b = { c()
apache-2.0
slavapestov/swift
test/SILGen/dynamic_lookup.swift
1
11963
// RUN: %target-swift-frontend -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module %s | FileCheck %s // REQUIRES: objc_interop class X { @objc func f() { } @objc class func staticF() { } @objc var value: Int { return 17 } @objc subscript (i: Int) -> Int { get { return i } set {} } } @objc protocol P { func g() } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup15direct_to_class func direct_to_class(obj: AnyObject) { // CHECK: [[OBJ_SELF:%[0-9]+]] = open_existential_ref [[EX:%[0-9]+]] : $AnyObject to $@opened({{.*}}) AnyObject // CHECK: [[METHOD:%[0-9]+]] = dynamic_method [volatile] [[OBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.f!1.foreign : (X) -> () -> (), $@convention(objc_method) (@opened({{.*}}) AnyObject) -> () // CHECK: apply [[METHOD]]([[OBJ_SELF]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> () obj.f!() } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup18direct_to_protocol func direct_to_protocol(obj: AnyObject) { // CHECK: [[OBJ_SELF:%[0-9]+]] = open_existential_ref [[EX:%[0-9]+]] : $AnyObject to $@opened({{.*}}) AnyObject // CHECK: [[METHOD:%[0-9]+]] = dynamic_method [volatile] [[OBJ_SELF]] : $@opened({{.*}}) AnyObject, #P.g!1.foreign : <Self where Self : P> Self -> () -> (), $@convention(objc_method) (@opened({{.*}}) AnyObject) -> () // CHECK: apply [[METHOD]]([[OBJ_SELF]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> () obj.g!() } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup23direct_to_static_method func direct_to_static_method(obj: AnyObject) { var obj = obj // CHECK: [[START:[A-Za-z0-9_]+]]([[OBJ:%[0-9]+]] : $AnyObject): // CHECK: [[OBJBOX:%[0-9]+]] = alloc_box $AnyObject // CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJBOX]] // CHECK: store [[OBJ]] to [[PBOBJ]] : $*AnyObject // CHECK-NEXT: [[OBJCOPY:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject // CHECK-NEXT: [[OBJMETA:%[0-9]+]] = existential_metatype $@thick AnyObject.Type, [[OBJCOPY]] : $AnyObject // CHECK-NEXT: [[OPENMETA:%[0-9]+]] = open_existential_metatype [[OBJMETA]] : $@thick AnyObject.Type to $@thick (@opened([[UUID:".*"]]) AnyObject).Type // CHECK-NEXT: [[METHOD:%[0-9]+]] = dynamic_method [volatile] [[OPENMETA]] : $@thick (@opened([[UUID]]) AnyObject).Type, #X.staticF!1.foreign : (X.Type) -> () -> (), $@convention(objc_method) (@thick (@opened([[UUID]]) AnyObject).Type) -> () // CHECK: apply [[METHOD]]([[OPENMETA]]) : $@convention(objc_method) (@thick (@opened([[UUID]]) AnyObject).Type) -> () obj.dynamicType.staticF!() } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup12opt_to_class func opt_to_class(obj: AnyObject) { var obj = obj // CHECK: [[ENTRY:[A-Za-z0-9]+]]([[PARAM:%[0-9]+]] : $AnyObject) // CHECK: [[EXISTBOX:%[0-9]+]] = alloc_box $AnyObject // CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[EXISTBOX]] // CHECK: store [[PARAM]] to [[PBOBJ]] // CHECK-NEXT: [[OPTBOX:%[0-9]+]] = alloc_box $ImplicitlyUnwrappedOptional<() -> ()> // CHECK-NEXT: [[PBOPT:%.*]] = project_box [[OPTBOX]] // CHECK-NEXT: [[EXISTVAL:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject // CHECK-NEXT: strong_retain [[EXISTVAL]] : $AnyObject // CHECK-NEXT: [[OBJ_SELF:%[0-9]*]] = open_existential_ref [[EXIST:%[0-9]+]] // CHECK-NEXT: [[OPTTEMP:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<() -> ()> // CHECK-NEXT: dynamic_method_br [[OBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.f!1.foreign, [[HASBB:[a-zA-z0-9]+]], [[NOBB:[a-zA-z0-9]+]] // Has method BB: // CHECK: [[HASBB]]([[UNCURRIED:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()): // CHECK-NEXT: strong_retain [[OBJ_SELF]] // CHECK-NEXT: [[PARTIAL:%[0-9]+]] = partial_apply [[UNCURRIED]]([[OBJ_SELF]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> () // CHECK-NEXT: [[THUNK_PAYLOAD:%.*]] = init_enum_data_addr [[OPTIONAL:%[0-9]+]] // CHECK: [[THUNKFN:%.*]] = function_ref @{{.*}} : $@convention(thin) (@out (), @in (), @owned @callee_owned () -> ()) -> () // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [[THUNKFN]]([[PARTIAL]]) // CHECK-NEXT: store [[THUNK]] to [[THUNK_PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[OPTIONAL]]{{.*}}Some // CHECK-NEXT: br [[CONTBB:[a-zA-Z0-9]+]] // No method BB: // CHECK: [[NOBB]]: // CHECK-NEXT: inject_enum_addr [[OPTIONAL]]{{.*}}None // CHECK-NEXT: br [[CONTBB]] // Continuation block // CHECK: [[CONTBB]]: // CHECK-NEXT: [[OPT:%.*]] = load [[OPTTEMP]] // CHECK-NEXT: store [[OPT]] to [[PBOPT]] : $*ImplicitlyUnwrappedOptional<() -> ()> // CHECK-NEXT: dealloc_stack [[OPTTEMP]] var of = obj.f // Exit // CHECK-NEXT: strong_release [[OBJ_SELF]] : $@opened({{".*"}}) AnyObject // CHECK-NEXT: strong_release [[OPTBOX]] : $@box ImplicitlyUnwrappedOptional<() -> ()> // CHECK-NEXT: strong_release [[EXISTBOX]] : $@box AnyObject // CHECK-NEXT: strong_release %0 // CHECK-NEXT: [[RESULT:%[0-9]+]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup20forced_without_outer func forced_without_outer(obj: AnyObject) { // CHECK: dynamic_method_br var f = obj.f! } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup20opt_to_static_method func opt_to_static_method(obj: AnyObject) { var obj = obj // CHECK: [[ENTRY:[A-Za-z0-9]+]]([[OBJ:%[0-9]+]] : $AnyObject): // CHECK: [[OBJBOX:%[0-9]+]] = alloc_box $AnyObject // CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJBOX]] // CHECK: store [[OBJ]] to [[PBOBJ]] : $*AnyObject // CHECK-NEXT: [[OPTBOX:%[0-9]+]] = alloc_box $ImplicitlyUnwrappedOptional<() -> ()> // CHECK-NEXT: [[PBO:%.*]] = project_box [[OPTBOX]] // CHECK-NEXT: [[OBJCOPY:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject // CHECK-NEXT: [[OBJMETA:%[0-9]+]] = existential_metatype $@thick AnyObject.Type, [[OBJCOPY]] : $AnyObject // CHECK-NEXT: [[OPENMETA:%[0-9]+]] = open_existential_metatype [[OBJMETA]] : $@thick AnyObject.Type to $@thick (@opened // CHECK-NEXT: [[OBJCMETA:%[0-9]+]] = thick_to_objc_metatype [[OPENMETA]] // CHECK-NEXT: [[OPTTEMP:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<() -> ()> // CHECK-NEXT: dynamic_method_br [[OBJCMETA]] : $@objc_metatype (@opened({{".*"}}) AnyObject).Type, #X.staticF!1.foreign, [[HASMETHOD:[A-Za-z0-9_]+]], [[NOMETHOD:[A-Za-z0-9_]+]] var optF = obj.dynamicType.staticF } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup15opt_to_property func opt_to_property(obj: AnyObject) { var obj = obj // CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject): // CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box $AnyObject // CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]] // CHECK: store [[OBJ]] to [[PBOBJ]] : $*AnyObject // CHECK-NEXT: [[INT_BOX:%[0-9]+]] = alloc_box $Int // CHECK-NEXT: project_box [[INT_BOX]] // CHECK-NEXT: [[UNKNOWN_USE:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<Int> // CHECK-NEXT: [[OBJ:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject // CHECK-NEXT: strong_retain [[OBJ]] : $AnyObject // CHECK-NEXT: [[RAWOBJ_SELF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject // CHECK-NEXT: [[OPTTEMP:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<Int> // CHECK-NEXT: dynamic_method_br [[RAWOBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.value!getter.1.foreign, bb1, bb2 // CHECK: bb1([[METHOD:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int): // CHECK-NEXT: strong_retain [[RAWOBJ_SELF]] // CHECK-NEXT: [[BOUND_METHOD:%[0-9]+]] = partial_apply [[METHOD]]([[RAWOBJ_SELF]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int // CHECK-NEXT: [[VALUE:%[0-9]+]] = apply [[BOUND_METHOD]]() : $@callee_owned () -> Int // CHECK-NEXT: [[VALUETEMP:%.*]] = init_enum_data_addr [[OPTTEMP]] // CHECK-NEXT: store [[VALUE]] to [[VALUETEMP]] // CHECK-NEXT: inject_enum_addr [[OPTTEMP]]{{.*}}Some // CHECK-NEXT: br bb3 var i: Int = obj.value! } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup19direct_to_subscript func direct_to_subscript(obj: AnyObject, i: Int) { var obj = obj var i = i // CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject, [[I:%[0-9]+]] : $Int): // CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box $AnyObject // CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]] // CHECK: store [[OBJ]] to [[PBOBJ]] : $*AnyObject // CHECK-NEXT: [[I_BOX:%[0-9]+]] = alloc_box $Int // CHECK-NEXT: [[PBI:%.*]] = project_box [[I_BOX]] // CHECK-NEXT: store [[I]] to [[PBI]] : $*Int // CHECK-NEXT: alloc_box $Int // CHECK-NEXT: project_box // CHECK-NEXT: [[UNKNOWN_USE:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<Int> // CHECK-NEXT: [[OBJ:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject // CHECK-NEXT: strong_retain [[OBJ]] : $AnyObject // CHECK-NEXT: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject // CHECK-NEXT: [[I:%[0-9]+]] = load [[PBI]] : $*Int // CHECK-NEXT: [[OPTTEMP:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<Int> // CHECK-NEXT: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.1.foreign, bb1, bb2 // CHECK: bb1([[GETTER:%[0-9]+]] : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int): // CHECK-NEXT: strong_retain [[OBJ_REF]] // CHECK-NEXT: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [[GETTER]]([[OBJ_REF]]) : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[GETTER_WITH_SELF]]([[I]]) : $@callee_owned (Int) -> Int // CHECK-NEXT: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]] // CHECK-NEXT: store [[RESULT]] to [[RESULTTEMP]] // CHECK-NEXT: inject_enum_addr [[OPTTEMP]]{{.*}}Some // CHECK-NEXT: br bb3 var x: Int = obj[i]! } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup16opt_to_subscript func opt_to_subscript(obj: AnyObject, i: Int) { var obj = obj var i = i // CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject, [[I:%[0-9]+]] : $Int): // CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box $AnyObject // CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]] // CHECK: store [[OBJ]] to [[PBOBJ]] : $*AnyObject // CHECK-NEXT: [[I_BOX:%[0-9]+]] = alloc_box $Int // CHECK-NEXT: [[PBI:%.*]] = project_box [[I_BOX]] // CHECK-NEXT: store [[I]] to [[PBI]] : $*Int // CHECK-NEXT: [[OBJ:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject // CHECK-NEXT: strong_retain [[OBJ]] : $AnyObject // CHECK-NEXT: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject // CHECK-NEXT: [[I:%[0-9]+]] = load [[PBI]] : $*Int // CHECK-NEXT: [[OPTTEMP:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<Int> // CHECK-NEXT: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.1.foreign, bb1, bb2 // CHECK: bb1([[GETTER:%[0-9]+]] : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int): // CHECK-NEXT: strong_retain [[OBJ_REF]] // CHECK-NEXT: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [[GETTER]]([[OBJ_REF]]) : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[GETTER_WITH_SELF]]([[I]]) : $@callee_owned (Int) -> Int // CHECK-NEXT: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]] // CHECK-NEXT: store [[RESULT]] to [[RESULTTEMP]] // CHECK-NEXT: inject_enum_addr [[OPTTEMP]] // CHECK-NEXT: br bb3 obj[i] } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup8downcast func downcast(obj: AnyObject) -> X { var obj = obj // CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject): // CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box $AnyObject // CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]] // CHECK: store [[OBJ]] to [[PBOBJ]] : $*AnyObject // CHECK-NEXT: [[OBJ:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject // CHECK-NEXT: strong_retain [[OBJ]] : $AnyObject // CHECK-NEXT: [[X:%[0-9]+]] = unconditional_checked_cast [[OBJ]] : $AnyObject to $X // CHECK-NEXT: strong_release [[OBJ_BOX]] : $@box AnyObject // CHECK-NEXT: strong_release %0 // CHECK-NEXT: return [[X]] : $X return obj as! X }
apache-2.0
obrichak/discounts
discounts/Classes/UI/DiscountView/DiscountViewController.swift
1
693
// // DiscountViewController.swift // discounts // // Created by Alexandr Chernyy on 9/10/14. // Copyright (c) 2014 Alexandr Chernyy. All rights reserved. // import Foundation import UIKit class DiscountViewController: UIViewController { @IBOutlet var discountView: DiscountView! var selectedIndex:Int! override func viewDidLoad() { discountView.generateCode(selectedIndex) 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. } }
gpl-3.0
WildenChen/LionEvents
LionEvents/LionEvents/LNButton.swift
1
4019
// // LNButton.swift // LionActions // // Created by wilden on 2015/6/12. // Copyright (c) 2015年 Lion Infomation Technology Co.,Ltd. All rights reserved. // import UIKit public typealias LNButtonEvents = LNTouchEvents open class LNButton: UIButton { private var mIsTouchInside:Bool = true override open var isTouchInside:Bool{ set(value){ if mIsTouchInside != value { mIsTouchInside = value if mIsTouchInside { let _event:Event = Event(aType: LNButtonEvents.TOUCH_ROLL_OVER.rawValue, aBubbles: true) dispatchEvent(_event) }else{ let _event:Event = Event(aType: LNButtonEvents.TOUCH_ROLL_OUT.rawValue, aBubbles: true) dispatchEvent(_event) } } } get{ return mIsTouchInside } } public init(){ super.init(frame: CGRect.zero) } public override init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) let _event:Event = Event(aType: LNButtonEvents.TOUCH_DOWN.rawValue, aBubbles: true) self.dispatchEvent(_event) } override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) let _touch:UITouch = touches.first! let _touchendPoint:CGPoint = _touch.location(in: self) if _touchendPoint.x < 0 || _touchendPoint.x > self.bounds.width || _touchendPoint.y < 0 || _touchendPoint.y > self.bounds.height { let _event:Event = Event(aType: LNButtonEvents.TOUCH_UP_OUTSIDE.rawValue, aBubbles: true) dispatchEvent(_event) }else { let _event:Event = Event(aType: LNButtonEvents.TOUCH_UP_INSIDE.rawValue, aBubbles: true) dispatchEvent(_event) } } override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) let _touch:UITouch = touches.first! let _touchendPoint:CGPoint = _touch.location(in: self) let _event:Event = Event(aType: LNButtonEvents.TOUCH_MOVE.rawValue, aBubbles: true) dispatchEvent(_event) if _touchendPoint.x < 0 || _touchendPoint.x > self.bounds.width || _touchendPoint.y < 0 || _touchendPoint.y > self.bounds.height { self.isTouchInside = false }else{ self.isTouchInside = true } } override open func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) let _event:Event = Event(aType: LNButtonEvents.TOUCH_CANCEL.rawValue, aBubbles: true) dispatchEvent(_event) } @discardableResult open func addEventListener(_ aEventType: LNButtonEvents, _ aHandler:@escaping () -> Void) -> EventListener { return self.addEventListener(aEventType.rawValue, aHandler) } @discardableResult open func addEventListener(_ aEventType: LNButtonEvents, _ aHandler:@escaping (_ aEvent: Event) -> Void) -> EventListener { return self.addEventListener(aEventType.rawValue, aHandler) } open func removeEventListener(_ aEventType: LNButtonEvents){ self.removeEventListener(aEventType.rawValue) } open func removeEventListener(_ aEventType:LNButtonEvents, aListener:EventListener){ let _eventType:String = aEventType.rawValue self.removeEventListener(_eventType, aListener) if !hasEventListener(_eventType) { self.removeEventListener(_eventType) } } open func removeAllEventListener(){ self.removeEventListener(nil) } }
bsd-3-clause
ppoh71/motoRoutes
motoRoutes/MotoChartView.swift
1
206
// // MotoChartView.swift // motoRoutes // // Created by Peter Pohlmann on 24.08.16. // Copyright © 2016 Peter Pohlmann. All rights reserved. // import Charts class MotoChartView: BarChartView{ }
apache-2.0
slavapestov/swift
test/DebugInfo/generic_args.swift
4
2096
// RUN: %target-swift-frontend -primary-file %s -emit-ir -verify -g -o - | FileCheck %s func markUsed<T>(t: T) {} protocol AProtocol { func f() -> String } class AClass : AProtocol { func f() -> String { return "A" } } class AnotherClass : AProtocol { func f() -> String { return "B" } } // CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "_TtQq_F12generic_args9aFunction{{.*}}",{{.*}} elements: ![[PROTOS:[0-9]+]] // CHECK-DAG: ![[PROTOS]] = !{![[INHERIT:.*]]} // CHECK-DAG: ![[INHERIT]] = !DIDerivedType(tag: DW_TAG_inheritance,{{.*}} baseType: ![[PROTOCOL:"[^"]+"]] // CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "_TtMP12generic_args9AProtocol_",{{.*}} identifier: [[PROTOCOL]] // CHECK-DAG: !DILocalVariable(name: "x", arg: 1,{{.*}} type: ![[T:.*]]) // CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "_TtQq_F12generic_args9aFunction{{.*}}, identifier: [[T]]) // CHECK-DAG: !DILocalVariable(name: "y", arg: 2,{{.*}} type: ![[Q:.*]]) // CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "_TtQq0_F12generic_args9aFunction{{.*}}, identifier: [[Q]]) func aFunction<T : AProtocol, Q : AProtocol>(x: T, _ y: Q, _ z: String) { markUsed("I am in \(z): \(x.f()) \(y.f())") } aFunction(AClass(),AnotherClass(),"aFunction") struct Wrapper<T: AProtocol> { init<U: AProtocol>(from : Wrapper<U>) { // CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "Wrapper",{{.*}} identifier: "_TtGV12generic_args7WrapperQq_FS0_cuRd__S_9AProtocolrFT4fromGS0_qd____GS0_x__") var wrapped = from wrapped = from _ = wrapped } func passthrough(t: T) -> T { // The type of local should have the context Wrapper<T>. // CHECK-DAG: !DILocalVariable(name: "local",{{.*}} line: [[@LINE+1]],{{.*}} type: !"_TtQq_V12generic_args7Wrapper" var local = t local = t return local } } // CHECK: !DILocalVariable(name: "f", {{.*}}, line: [[@LINE+1]], type: !"_TtFQq_F12generic_args5applyu0_rFTx1fFxq__q_Qq0_F12generic_args5applyu0_rFTx1fFxq__q_") func apply<T, U> (x: T, f: (T) -> (U)) -> U { return f(x) }
apache-2.0
furqanmk/github
microapps-testapplication/IssueTableViewCell.swift
1
627
// // IssueTableViewCell.swift // microapps-testapplication // // Created by Furqan on 26/12/2015. // Copyright © 2015 Furqan Khan. All rights reserved. // import UIKit class IssueTableViewCell: UITableViewCell { @IBOutlet weak var issueTitle: UILabel! @IBOutlet weak var issueBody: UILabel! @IBOutlet weak var issueState: UILabel! @IBOutlet weak var issueNumber: UILabel! func setupIssue(issue: Issue) { issueTitle.text = issue.title issueBody.text = issue.body issueState.text = issue.state == .Open ? "open": "closed" issueNumber.text = "#\(issue.number)" } }
mit
ktmswzw/FeelingClientBySwift
Pods/IBAnimatable/IBAnimatable/MaskType.swift
1
220
// // Created by Jake Lin on 12/13/15. // Copyright © 2015 Jake Lin. All rights reserved. // import Foundation public enum MaskType: String { case Circle case Polygon case Star case Triangle case Wave }
mit
Corey2121/the-oakland-post
The Oakland Post/SignUpViewController.swift
3
6334
// // SignUpViewController.swift // The Oakland Post // // A simple signup form. // // Created by Andrew Clissold on 8/24/14. // Copyright (c) 2014 Andrew Clissold. All rights reserved. // import UIKit class SignUpViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var confirmPasswordTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var signUpButton: UIButton! @IBOutlet weak var signUpActivityIndicator: UIActivityIndicatorView! var keyboardWasPresent = false override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .Done, target: self, action: "dismiss") usernameTextField.delegate = self passwordTextField.delegate = self confirmPasswordTextField.delegate = self emailTextField.delegate = self } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if UIDevice.currentDevice().userInterfaceIdiom != .Pad { registerForKeyboardNotifications() } } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver( self, name: UIKeyboardDidShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver( self, name: UIKeyboardWillHideNotification, object: nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) findAndResignFirstResponder() } func registerForKeyboardNotifications() { NSNotificationCenter.defaultCenter().addObserver( self, selector: "keyboardDidShow:", name: UIKeyboardDidShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver( self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } var insets = UIEdgeInsetsZero func keyboardDidShow(notification: NSNotification) { if navigationController == nil { // Occurs when a screen edge pan gesture is initiated but canceled, // so insets will already have been set. scrollView.contentInset = insets scrollView.scrollIndicatorInsets = insets return } let info = notification.userInfo! let keyboardHeight = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue().size.height let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height let navBarHeight = navigationController!.navigationBar.frame.size.height let top = statusBarHeight + navBarHeight let bottom = keyboardHeight insets = UIEdgeInsets(top: top, left: 0, bottom: bottom, right: 0) UIView.animateWithDuration(0.3) { self.scrollView.contentInset = self.insets self.scrollView.scrollIndicatorInsets = self.insets } } func keyboardWillHide(notification: NSNotification) { if navigationController == nil { return } // avoid crash let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height let navBarHeight = navigationController!.navigationBar.frame.size.height let top = statusBarHeight + navBarHeight let insets = UIEdgeInsets(top: top, left: 0, bottom: 0, right: 0) scrollView.contentInset = insets scrollView.scrollIndicatorInsets = insets } var count = 0 override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if ++count == 2 || (count == 4 && keyboardWasPresent) { let viewHeight = view.frame.size.height let viewWidth = view.frame.size.width var navBarHeight = navigationController!.navigationBar.frame.size.height if UIDevice.currentDevice().userInterfaceIdiom != .Pad { let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height navBarHeight += statusBarHeight } scrollView.contentSize = CGSize(width: viewWidth, height: viewHeight-navBarHeight) } } func textFieldShouldReturn(textField: UITextField) -> Bool { if let nextResponder = textField.superview?.viewWithTag(textField.tag + 1) { nextResponder.becomeFirstResponder() } else if textField === emailTextField { hideKeyboardAndSignUp() } return false } @IBAction func hideKeyboardAndSignUp() { findAndResignFirstResponder() signUpButton.enabled = false signUpActivityIndicator.startAnimating() var user = PFUser() user.username = usernameTextField.text user.password = passwordTextField.text user.email = emailTextField.text let confirmPassword = confirmPasswordTextField.text if valid(user, confirmPassword) { user.signUpInBackgroundWithBlock { (succeeded, error) in if succeeded { homeViewController.reloadData() homeViewController.navigationItem.rightBarButtonItem = homeViewController.favoritesBarButtonItem self.dismiss() } else { showAlertForErrorCode(error!.code) self.signUpActivityIndicator.stopAnimating() self.signUpButton.enabled = true } } } else { self.signUpActivityIndicator.stopAnimating() self.signUpButton.enabled = true } } func findAndResignFirstResponder() { for textField in [usernameTextField, passwordTextField, confirmPasswordTextField, emailTextField] { if textField.isFirstResponder() { textField.resignFirstResponder() return } } } func dismiss() { findAndResignFirstResponder() dismissViewControllerAnimated(true, completion: nil) } }
bsd-3-clause
pencildrummer/TwilioLookup
TwilioLookup/Sources/TwilioCarrier.swift
1
1755
// // TwilioCarrier.swift // Pods // // Created by Fabio Borella on 22/06/16. // // import Foundation /** Available types of carrier */ public enum TwilioCarrierType: String { /// The phone number is a landline number generally not capable of receiving SMS messages. case Landline = "landline" /// The phone number is a mobile number generally capable of receiving SMS messages. case Mobile = "mobile" /// An internet based phone number that may or may not be capable of receiving SMS messages. For example, Google Voice. case Voip = "voip" } /** Available types of carrier caller */ public enum TwilioCarrierCallerType: String { /// The carrier caller is not available case Unavailable = "unavailable" /// The carrier caller is a business number case Business = "business" /// The carrier caller is a consumer number case Consumer = "consumer" } /** The carrier of a certain phone number - seealso: TwilioLookupResponse */ open class TwilioCarrier { /** The mobile country code of the carrier (for mobile numbers only). */ open var mobileCountryCode: String! /** The mobile network code of the carrier (for mobile numbers only). */ open var mobileNetworkCode: String! /** The name of the carrier. Please bear in mind that carriers rebrand themselves constantly and that the names used for carriers will likely change over time. */ open var name: String! /** The phone number type. See `TwilioCarrierType` for more information. */ open var type: TwilioCarrierType! /** The error code, if any, associated with your request. */ open var errorCode: TwilioErrorCode? }
mit
kongtomorrow/ProjectEuler-Swift
ProjectEuler/main.swift
1
1259
// // main.swift // ProjectEuler // // Created by Ken Ferry on 8/7/14. // Copyright (c) 2014 Understudy. All rights reserved. // import Foundation import dispatch @objc class Problems { func methodsStartingWithPrefix(prefix:String)->[String] { var count:UInt32 = 0 let methods = class_copyMethodList(Problems.self, &count) var methodNames = [String]() for i in 0..<Int(count) { let methName = method_getName(methods[i]).description methodNames.append(methName) } free(methods) return methodNames.filter({($0 as NSString).hasPrefix(prefix)}).sorted({ (a, b) -> Bool in return (a as NSString).localizedStandardCompare(b) == NSComparisonResult.OrderedAscending }) } func benchmarkProblem(methName:String) { benchmark(methName) { ()->Int in return FThePolice.sendProblemMessage(Selector(methName), toObject: self) } } } let probs = Problems() probs.methodsStartingWithPrefix("p").map({probs.benchmarkProblem($0)}) probs.methodsStartingWithPrefix("run").map({probs.benchmarkProblem($0)}) //probs.benchmarkProblem(probs.methodsStartingWithPrefix("p").last!) // just the last problem
mit
strike65/SwiftyStats
SwiftyStats/CommonSource/DataFrame/SSDataFrame.swift
1
30013
// // SSDataFrame.swift // SwiftyStats /* Copyright (2017-2019) strike65 GNU GPL 3+ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation #if os(macOS) || os(iOS) import os.log #endif /// Defines a structure holding multiple SSExamine objects: /// Each column contains an SSExamine object. /// /// Each COL represents a single SSExamine object. The structure of the dataframe is like a two-dimensional table: /// /// With N = sampleSize: /// /// < COL[0] COL[1] ... COL[columns - 1] > /// tags tags[0] tags[1] ... tags[columns - 1] /// cnames cnames[0 cnames[1] ... cnames[columns - 1] /// ROW0 data[0][0] data[0][1] ... data[0][columns - 1] /// ROW1 data[1][0] data[1][1] ... data[1][columns - 1] /// ... .......... .......... ... .................... /// ROWN data[N][0] data[N][1] ... data[N][columns - 1] /// public class SSDataFrame<SSElement, FPT: SSFloatingPoint>: NSObject, NSCopying, Codable, NSMutableCopying, SSDataFrameContainer where SSElement: Comparable, SSElement: Hashable, SSElement: Codable, FPT: Codable { // public typealias Examine = SSExamine<SSElement, Double> // coding keys private enum CodingKeys: String, CodingKey { case data = "ExamineArray" case tags case cnames case nrows case ncolumns } /// Required func to conform to Codable protocol public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(self.data, forKey: .data) try container.encodeIfPresent(self.tags, forKey: .tags) try container.encodeIfPresent(self.cNames, forKey: .cnames) try container.encodeIfPresent(self.rows, forKey: .nrows) try container.encodeIfPresent(self.cols, forKey: .ncolumns) } /// Required func to conform to Codable protocol public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if let d = try container.decodeIfPresent(Array<SSExamine<SSElement, FPT>>.self, forKey: .data) { self.data = d } if let t = try container.decodeIfPresent(Array<String>.self, forKey: .tags) { self.tags = t } if let n = try container.decodeIfPresent(Array<String>.self, forKey: .cnames) { self.cNames = n } if let r = try container.decodeIfPresent(Int.self, forKey: .nrows) { self.rows = r } if let c = try container.decodeIfPresent(Int.self, forKey: .ncolumns) { self.cols = c } } #if os(macOS) || os(iOS) // @available(macOS 10.12, iOS 10, *) /// Saves the dataframe to filePath using JSONEncoder /// - Parameter path: The full qualified filename. /// - Parameter overwrite: If true, file will be overwritten. /// - Throws: SSSwiftyStatsError.posixError (file can't be removed), SSSwiftyStatsError.directoryDoesNotExist, SSSwiftyStatsError.fileNotReadable public func archiveTo(filePath path: String!, overwrite: Bool!) throws -> Bool { let fm: FileManager = FileManager.default let fullFilename: String = NSString(string: path).expandingTildeInPath let dir: String = NSString(string: fullFilename).deletingLastPathComponent var isDir = ObjCBool(false) if !fm.fileExists(atPath: dir, isDirectory: &isDir) { if !isDir.boolValue || path.count == 0 { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("No writeable path found", log: .log_fs ,type: .error) } #endif throw SSSwiftyStatsError(type: .directoryDoesNotExist, file: #file, line: #line, function: #function) } #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("File doesn't exist", log: .log_fs ,type: .error) } #endif throw SSSwiftyStatsError(type: .fileNotFound, file: #file, line: #line, function: #function) } if fm.fileExists(atPath: fullFilename) { if overwrite { if fm.isWritableFile(atPath: fullFilename) { do { try fm.removeItem(atPath: fullFilename) } catch { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Unable to remove file prior to saving new file: %@", log: .log_fs ,type: .error, error.localizedDescription) } #endif throw SSSwiftyStatsError(type: .fileNotWriteable, file: #file, line: #line, function: #function) } } else { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Unable to remove file prior to saving new file", log: .log_fs ,type: .error) } #endif throw SSSwiftyStatsError(type: .fileNotWriteable, file: #file, line: #line, function: #function) } } else { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("File exists: %@", log: .log_fs ,type: .error, fullFilename) } #endif throw SSSwiftyStatsError(type: .fileExists, file: #file, line: #line, function: #function) } } let jsonEncode = JSONEncoder() let d = try jsonEncode.encode(self) do { try d.write(to: URL.init(fileURLWithPath: fullFilename), options: Data.WritingOptions.atomic) return true } catch { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Unable to write data", log: .log_fs, type: .error) } #endif return false } } // @available(macOS 10.10, iOS 10, *) /// Initializes a new dataframe from an archive saved by archiveTo(filePath path:overwrite:). /// - Parameter path: The full qualified filename. /// - Throws: SSSwiftyStatError.fileNotReadable public class func unarchiveFrom(filePath path: String!) throws -> SSDataFrame<SSElement, FPT>? { let fm: FileManager = FileManager.default let fullFilename: String = NSString(string: path).expandingTildeInPath if !fm.isReadableFile(atPath: fullFilename) { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("File not readable", log: .log_fs ,type: .error) } #endif throw SSSwiftyStatsError(type: .fileNotFound, file: #file, line: #line, function: #function) } do { let data: Data = try Data.init(contentsOf: URL.init(fileURLWithPath: fullFilename)) let jsonDecoder = JSONDecoder() let result = try jsonDecoder.decode(SSDataFrame<SSElement, FPT>.self, from: data) return result } catch { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Failure", log: .log_fs ,type: .error) } #endif return nil } } #endif private var data:Array<SSExamine<SSElement, FPT>> = Array<SSExamine<SSElement, FPT>>() private var tags: Array<String> = Array<String>() private var cNames: Array<String> = Array<String>() private var rows: Int = 0 private var cols: Int = 0 /// Array containing all SSExamine objects public var examines: Array<SSExamine<SSElement, FPT>> { get { return data } } /// Number of rows per column (= sample size) public var sampleSize: Int { get { return rows } } /// Returns true if the receiver is equal to `object`. public override func isEqual(_ object: Any?) -> Bool { var result: Bool = true if let df: SSDataFrame<SSElement, FPT> = object as? SSDataFrame<SSElement, FPT> { if self.columns == df.columns && self.rows == df.rows { for k in 0..<self.columns { result = result && self[k].isEqual(df[k]) } return result } else { return false } } else { return false } } /// Number of samples (Same as `columns`) public var countOfSamples: Int { get { return cols } } /// Number of samples (Same as `countOfSamples`) public var columns: Int { get { return cols } } /// Returns true, if the receiver is empty (i.e. there are no data) public var isEmpty: Bool { get { return rows == 0 && cols == 0 } } /// Initializes a new instance and returns that instance in a fully initialized state /// - Parameter examineArray: An Array of SSEXamine objects /// - Throws: SSSwiftyStatsError init(examineArray: Array<SSExamine<SSElement, FPT>>!) throws { let tempSampleSize = examineArray.first!.sampleSize data = Array<SSExamine<SSElement, FPT>>.init() tags = Array<String>() cNames = Array<String>() var i: Int = 0 for a in examineArray { if a.sampleSize != tempSampleSize { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Sample sizes are expected to be equal", log: .log_stat, type: .error) } #endif data.removeAll() tags.removeAll() cNames.removeAll() rows = 0 cols = 0 throw SSSwiftyStatsError.init(type: .invalidArgument, file: #file, line: #line, function: #function) } i += 1 data.append(a) if let t = a.tag { tags.append(t) } else { tags.append("NA") } if let n = a.name { if let _ = cNames.firstIndex(of: n) { var k: Int = 1 var tempSampleString = n + "_" + String(format: "%02d", arguments: [k as CVarArg]) while (cNames.firstIndex(of: tempSampleString) != nil) { k += 1 tempSampleString = n + "_" + String(format: "%02d", arguments: [k as CVarArg]) } cNames.append(tempSampleString) } else { cNames.append(n) } } else { cNames.append(String(format: "%03d", arguments: [i as CVarArg])) } } rows = tempSampleSize cols = i super.init() } /// Required initializer override public init() { cNames = Array<String>() tags = Array<String>() data = Array<SSExamine<SSElement, FPT>>() rows = 0 cols = 0 super.init() } /// Appends a column /// - Parameter examine: The SSExamine object /// - Parameter name: Name of column /// - Throws: SSSwiftyStatsError examine.sampleSize != self.rows public func append(_ examine: SSExamine<SSElement, FPT>, name: String?) throws { if examine.sampleSize != self.rows { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Sample sizes are expected to be equal", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .invalidArgument, file: #file, line: #line, function: #function) } self.data.append(examine) if let t = examine.tag { self.tags.append(t) } else { self.tags.append("NA") } if let n = examine.name { self.cNames.append(n) } else { cNames.append(String(format: "%03d", arguments: [(self.cols + 1) as CVarArg] )) } cols += 1 } /// Removes all columns public func removeAll() { data.removeAll() cNames.removeAll() tags.removeAll() cols = 0 rows = 0 } /// Removes a column /// - Parameter name: Name of column /// - Returns: the removed column oe nil public func remove(name: String!) -> SSExamine<SSElement, FPT>? { if cols > 0 { if let i = cNames.firstIndex(of: name) { cNames.remove(at: i) tags.remove(at: i) cols -= 1 rows -= 1 return data.remove(at: i) } else { return nil } } else { return nil } } private func isValidColumnIndex(_ index: Int) -> Bool { return (index >= 0 && index < self.columns) ? true : false } private func isValidRowIndex(_ index: Int) -> Bool { return (index >= 0 && index < self.rows) ? true : false } private func indexOf(columnName: String!) -> Int? { if let i = cNames.firstIndex(of: columnName) { return i } else { return nil } } /// Returns the row at a given index public func row(at index: Int) -> Array<SSElement> { if isValidRowIndex(index) { var res = Array<SSElement>() for c in self.data { if let e = c[index] { res.append(e) } else { fatalError("Index out of range") } } return res } else { fatalError("Row-Index out of row.") } } /// Accesses the column at a given index public subscript(_ idx: Int) -> SSExamine<SSElement, FPT> { if isValidColumnIndex(idx) { return data[idx] } else { fatalError("Index out of range") } } /// Accesses the column named `name` public subscript(_ name: String) -> SSExamine<SSElement, FPT> { if let i = cNames.firstIndex(of: name) { return data[i] } else { fatalError("Index out of range") } } /// Returns a new instance that’s a copy of the receiver. /// /// The returned object is implicitly retained by the sender, who is responsible for releasing it. The copy returned is immutable if the consideration “immutable vs. mutable” applies to the receiving object; otherwise the exact nature of the copy is determined by the class. /// - Parameters: /// - zone: This parameter is ignored. Memory zones are no longer used by Objective-C. public func copy(with zone: NSZone? = nil) -> Any { do { let res = try SSDataFrame<SSElement, FPT>.init(examineArray: self.data) res.tags = self.tags res.cNames = self.cNames return res } catch { fatalError("Copy failed") } } /// Returns a new instance that’s a mutable copy of the receiver. /// /// The returned object is implicitly retained by the sender, who is responsible for releasing it. The copy returned is immutable if the consideration “immutable vs. mutable” applies to the receiving object; otherwise the exact nature of the copy is determined by the class. In fact, that functions does the same as `copy(with:)` /// - Parameters: /// - zone: This parameter is ignored. Memory zones are no longer used by Objective-C. public func mutableCopy(with zone: NSZone? = nil) -> Any { return self.copy(with: zone) } /// Returns the object returned by `mutableCopy(with:)` where the `zone` is nil. /// /// This is a convenience method for classes that adopt the NSMutableCopying protocol. An exception is raised if there is no implementation for `mutableCopy(with:)`. public override func mutableCopy() -> Any { return self.copy(with: nil) } /// Returns the object returned by `copy(with:) where the `zone` is nil. /// /// This is a convenience method for classes that adopt the NSCopying protocol. An exception is raised if there is no implementation for copy(with:). NSObject does not itself support the NSCopying protocol. Subclasses must support the protocol and implement the copy(with:) method. A subclass version of the copy(with:) method should send the message to super first, to incorporate its implementation, unless the subclass descends directly from NSObject. public override func copy() -> Any { return copy(with: nil) } /// Exports the dataframe as csv /// - Parameter path: The full path /// - Parameter atomically: Write atomically /// - Parameter firstRowAsColumnName: If true, the row name is equal to the exported SSExamine object. If this object hasn't a name, an auto incremented integer is used. /// - Parameter useQuotes: If true all fields will be enclosed by quotation marks /// - Parameter overwrite: If true an existing file will be overwritten /// - Parameter stringEncoding: Encoding /// - Returns: True if the file was successfully written. /// - Throws: SSSwiftyStatsError public func exportCSV(path: String!, separator sep: String = ",", useQuotes: Bool = false, firstRowAsColumnName cn: Bool = true, overwrite: Bool = false, stringEncoding enc: String.Encoding = String.Encoding.utf8, atomically: Bool = true) throws -> Bool { if !self.isEmpty { var string = String() if cn { for c in 0..<cols { if useQuotes { string = string + "\"" + cNames[c] + "\"" + sep } else { string = string + cNames[c] + sep } } string = String.init(string.dropLast()) string += "\n" } for r in 0..<self.rows { for c in 0..<self.cols { if useQuotes { string = string + "\"" + "\(String(describing: self.data[c][r]!))" + "\"" + sep } else { string = string + "\(String(describing: self.data[c][r]!))" + sep } } string = String.init(string.dropLast()) string += "\n" } string = String.init(string.dropLast()) let fileManager = FileManager.default let fullName = NSString(string: path).expandingTildeInPath if fileManager.fileExists(atPath: fullName) { if !overwrite { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("File already exists", log: .log_fs, type: .error) } #endif throw SSSwiftyStatsError(type: .fileExists, file: #file, line: #line, function: #function) } else { do { try fileManager.removeItem(atPath: fullName) } catch { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Can't remove file", log: .log_fs, type: .error) } #endif throw SSSwiftyStatsError(type: .fileNotWriteable, file: #file, line: #line, function: #function) } } } var result: Bool do { try string.write(toFile: fullName, atomically: atomically, encoding: enc) result = true } catch { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("File could not be written", log: .log_fs, type: .error) } #endif result = false } return result } else { return false } } /// Initializes a new DataFrame instance. /// - Parameter fromString: A string of objects (mostly numbers) separated by `separator` /// - Parameter separator: The separator (delimiter) used. Default = "," /// - Parameter firstRowContainsNames: Indicates, that the first line contains Column Identifiers. /// - Parameter parser: A function to convert a string to the expected generic type /// - Throws: SSSwiftyStatsError if the file doesn't exist or can't be accessed /// /// The following example creates a DataFrame object with 4 columns: /// /// let dataString = "Group 1,Group 2,Group 3,Group 4\n6.9,8.3,8.0,5.8\n5.4,6.8,10.5,3.8\n5.8,7.8,8.1,6.1\n4.6,9.2,6.9,5.6\n4.0,6.5,9.3,6.2" /// var df: SSDataFrame<Double, Double> /// do { /// df = try SSDataFrame.dataFrame(fromString: TukeyKramerData_01String, parser: scanDouble) /// } /// catch { /// ... /// } public class func dataFrame(fromString: String!, separator sep: String! = ",", firstRowContainsNames cn: Bool = true, parser: (String) -> SSElement?) throws -> SSDataFrame<SSElement, FPT> { do { var importedString = fromString if let lastScalar = importedString?.unicodeScalars.last { if CharacterSet.newlines.contains(lastScalar) { importedString = String(importedString!.dropLast()) } } let lines: Array<String> = importedString!.components(separatedBy: CharacterSet.newlines) var cnames: Array<String> = Array<String>() var cols: Array<String> var curString: String var columns: Array<Array<SSElement>> = Array<Array<SSElement>>() var k: Int = 0 var startRow: Int if cn { startRow = 1 } else { startRow = 0 } for r in startRow..<lines.count { cols = lines[r].components(separatedBy: sep) if columns.count == 0 && cols.count > 0 { for _ in 1...cols.count { columns.append(Array<SSElement>()) } } for c in 0..<cols.count { curString = cols[c].replacingOccurrences(of: "\"", with: "") if let d = parser(curString) { columns[c].append(d) } else { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Error during processing data file", log: .log_fs, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } } } if cn { let names = lines[0].components(separatedBy: sep) for name in names { curString = name.replacingOccurrences(of: "\"", with: "") cnames.append(curString) } } var examineArray: Array<SSExamine<SSElement, FPT>> = Array<SSExamine<SSElement, FPT>>() for k in 0..<columns.count { examineArray.append(SSExamine<SSElement, FPT>.init(withArray: columns[k], name: nil, characterSet: nil)) } if cn { k = 0 for e in examineArray { e.name = cnames[k] k += 1 } } return try SSDataFrame<SSElement, FPT>.init(examineArray: examineArray) } catch { return SSDataFrame<SSElement, FPT>() } } /// Loads the content of a file using the specified encoding. /// - Parameter path: The path to the file (e.g. ~/data/data.dat) /// - Parameter separator: The separator used in the file /// - Parameter firstRowContainsNames: Indicates, that the first line contains Column Identifiers. /// - Parameter stringEncoding: The encoding to use. /// - Parameter parser: A function to convert a string to the expected generic type /// - Throws: SSSwiftyStatsError if the file doesn't exist or can't be accessed public class func dataFrame(fromFile path: String!, separator sep: String! = ",", firstRowContainsNames cn: Bool = true, stringEncoding: String.Encoding! = String.Encoding.utf8, _ parser: (String) -> SSElement?) throws -> SSDataFrame<SSElement, FPT> { let fileManager = FileManager.default let fullFilename: String = NSString(string: path).expandingTildeInPath if !fileManager.fileExists(atPath: fullFilename) || !fileManager.isReadableFile(atPath: fullFilename) { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("File not found", log: .log_fs, type: .error) } #endif throw SSSwiftyStatsError(type: .fileNotFound, file: #file, line: #line, function: #function) } do { var importedString = try String.init(contentsOfFile: fullFilename, encoding: stringEncoding) if let lastScalar = importedString.unicodeScalars.last { if CharacterSet.newlines.contains(lastScalar) { importedString = String(importedString.dropLast()) } } let lines: Array<String> = importedString.components(separatedBy: CharacterSet.newlines) var cnames: Array<String> = Array<String>() var cols: Array<String> var curString: String var columns: Array<Array<SSElement>> = Array<Array<SSElement>>() var k: Int = 0 var startRow: Int if cn { startRow = 1 } else { startRow = 0 } for r in startRow..<lines.count { cols = lines[r].components(separatedBy: sep) if columns.count == 0 && cols.count > 0 { for _ in 1...cols.count { columns.append(Array<SSElement>()) } } for c in 0..<cols.count { curString = cols[c].replacingOccurrences(of: "\"", with: "") if let d = parser(curString) { columns[c].append(d) } else { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Error during processing data file", log: .log_fs, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } } } if cn { let names = lines[0].components(separatedBy: sep) for name in names { curString = name.replacingOccurrences(of: "\"", with: "") cnames.append(curString) } } var examineArray: Array<SSExamine<SSElement, FPT>> = Array<SSExamine<SSElement, FPT>>() for k in 0..<columns.count { examineArray.append(SSExamine<SSElement, FPT>.init(withArray: columns[k], name: nil, characterSet: nil)) } if cn { k = 0 for e in examineArray { e.name = cnames[k] k += 1 } } return try SSDataFrame<SSElement, FPT>.init(examineArray: examineArray) } catch { throw error } } }
gpl-3.0
darrarski/SharedShopping-iOS
SharedShoppingAppTests/TestHelpers/MethodCallObserver.swift
1
896
import RxSwift import RxCocoa import RxTest class MethodCallObserver { struct ObservedCall { let target: AnyObject let selector: Selector let parameters: [Any] } init() { scheduler = TestScheduler(initialClock: 0) observer = scheduler.createObserver(ObservedCall.self) } func observe<T: AnyObject & ReactiveCompatible>(_ target: T, _ selector: Selector) { target.rx.sentMessage(selector) .map { ObservedCall(target: target, selector: selector, parameters: $0) } .subscribe(observer) .disposed(by: disposeBag) } var observedCalls: [ObservedCall] { return observer.events.flatMap { $0.value.element } } // MARK: Private private let scheduler: TestScheduler private let observer: TestableObserver<ObservedCall> private let disposeBag = DisposeBag() }
mit
piscoTech/Workout
Workout Core/Model/Workout/Additional Data/RunningHeartZones.swift
1
5123
// // RunningHeartZones.swift // Workout // // Created by Marco Boschi on 28/08/2018. // Copyright © 2018 Marco Boschi. All rights reserved. // import UIKit import HealthKit import MBLibrary public class RunningHeartZones: AdditionalDataProcessor, AdditionalDataProvider, PreferencesDelegate { private weak var preferences: Preferences? public static let defaultZones = [60, 70, 80, 94] /// The maximum valid time between two samples. static let maxInterval: TimeInterval = 60 private var maxHeartRate: Double? private var zones: [Int]? private var rawHeartData: [HKQuantitySample]? private var zonesData: [TimeInterval]? init(with preferences: Preferences) { self.preferences = preferences preferences.add(delegate: self) runningHeartZonesConfigChanged() } public func runningHeartZonesConfigChanged() { if let hr = preferences?.maxHeartRate { self.maxHeartRate = Double(hr) } else { self.maxHeartRate = nil } self.zones = preferences?.runningHeartZones self.updateZones() } // MARK: - Process Data func wantData(for typeIdentifier: HKQuantityTypeIdentifier) -> Bool { return typeIdentifier == .heartRate } func process(data: [HKQuantitySample], for _: WorkoutDataQuery) { self.rawHeartData = data updateZones() } private func zone(for s: HKQuantitySample, in zones: [Double]) -> Int? { guard let maxHR = maxHeartRate else { return nil } let p = s.quantity.doubleValue(for: WorkoutUnit.heartRate.default) / maxHR return zones.lastIndex { p >= $0 } } private func updateZones() { guard let maxHR = maxHeartRate, let data = rawHeartData else { zonesData = nil return } let zones = (self.zones ?? RunningHeartZones.defaultZones).map({ Double($0) / 100 }) zonesData = [TimeInterval](repeating: 0, count: zones.count) var previous: HKQuantitySample? for s in data { defer { previous = s } guard let prev = previous else { continue } let time = s.startDate.timeIntervalSince(prev.startDate) guard time <= RunningHeartZones.maxInterval else { continue } let pZone = zone(for: prev, in: zones) let cZone = zone(for: s, in: zones) if let c = cZone, pZone == c { zonesData?[c] += time } else if let p = pZone, let c = cZone, abs(p - c) == 1 { let pH = prev.quantity.doubleValue(for: WorkoutUnit.heartRate.default) / maxHR let cH = s.quantity.doubleValue(for: WorkoutUnit.heartRate.default) / maxHR /// Threshold between zones let th = zones[max(p, c)] guard th >= min(pH, cH), th <= max(pH, cH) else { continue } /// Incline of a line joining the two data points let m = (cH - pH) / time /// The time after the previous data point when the zone change let change = (th - pH) / m zonesData?[p] += change zonesData?[c] += time - change } } } // MARK: - Display Data private static let header = NSLocalizedString("HEART_ZONES_TITLE", comment: "Heart zones") private static let footer = NSLocalizedString("HEART_ZONES_FOOTER", comment: "Can be less than total") private static let zoneTitle = NSLocalizedString("HEART_ZONES_ZONE_%lld", comment: "Zone x") private static let zoneConfig = NSLocalizedString("HEART_ZONES_NEED_CONFIG", comment: "Zone config") public let sectionHeader: String? = RunningHeartZones.header public var sectionFooter: String? { return zonesData == nil ? nil : RunningHeartZones.footer } public var numberOfRows: Int { return zonesData?.count ?? 1 } public func heightForRowAt(_ indexPath: IndexPath, in tableView: UITableView) -> CGFloat? { if zonesData == nil { return UITableView.automaticDimension } else { return nil } } public func cellForRowAt(_ indexPath: IndexPath, for tableView: UITableView) -> UITableViewCell { guard let data = zonesData?[indexPath.row] else { let cell = tableView.dequeueReusableCell(withIdentifier: "msg", for: indexPath) cell.textLabel?.text = RunningHeartZones.zoneConfig return cell } let cell = tableView.dequeueReusableCell(withIdentifier: "basic", for: indexPath) cell.textLabel?.text = String(format: RunningHeartZones.zoneTitle, indexPath.row + 1) cell.detailTextLabel?.text = data > 0 ? data.formattedDuration : missingValueStr return cell } public func export(for preferences: Preferences, withPrefix prefix: String, _ callback: @escaping ([URL]?) -> Void) { guard prefix.range(of: "/") == nil else { fatalError("Prefix must not contain '/'") } DispatchQueue.background.async { guard let zonesData = self.zonesData else { callback([]) return } let hzFile = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("\(prefix)heartZones.csv") guard let file = OutputStream(url: hzFile, append: false) else { callback(nil) return } let sep = CSVSeparator do { file.open() defer{ file.close() } try file.write("Zone\(sep)Time\n") for (i, t) in zonesData.enumerated() { try file.write("\(i + 1)\(sep)\(t.rawDuration().toCSV())\n") } callback([hzFile]) } catch { callback(nil) } } } }
mit
eurofurence/ef-app_ios
Packages/EurofurenceComponents/Sources/KnowledgeGroupComponent/Scene/UIKit/StoryboardKnowledgeGroupEntriesSceneFactory.swift
1
397
import ComponentBase import UIKit struct StoryboardKnowledgeGroupEntriesSceneFactory: KnowledgeGroupEntriesSceneFactory { private let storyboard = UIStoryboard(name: "KnowledgeGroupEntries", bundle: .module) func makeKnowledgeGroupEntriesScene() -> UIViewController & KnowledgeGroupEntriesScene { return storyboard.instantiate(KnowledgeGroupEntriesViewController.self) } }
mit
oskarpearson/rileylink_ios
MinimedKit/PumpEvents/ChangeBolusWizardSetupPumpEvent.swift
2
829
// // ChangeBolusWizardSetupPumpEvent.swift // RileyLink // // Created by Pete Schwamb on 8/29/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation public struct ChangeBolusWizardSetupPumpEvent: TimestampedPumpEvent { public let length: Int public let rawData: Data public let timestamp: DateComponents public init?(availableData: Data, pumpModel: PumpModel) { length = 39 guard length <= availableData.count else { return nil } rawData = availableData.subdata(in: 0..<length) timestamp = DateComponents(pumpEventData: availableData, offset: 2) } public var dictionaryRepresentation: [String: Any] { return [ "_type": "ChangeBolusWizardSetup", ] } }
mit
codepgq/AnimateDemo
Animate/Animate/controller/综合实例/火苗/FireTwoController.swift
1
4355
// // FireTwoController.swift // Animate // // Created by Mac on 17/2/9. // Copyright © 2017年 Mac. All rights reserved. // import UIKit class FireTwoController: UIViewController { @IBOutlet weak var fireImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() fireEmitter.emitterCells = [fire] view.layer.addSublayer(fireEmitter) } //创建一个粒子 lazy var fire : CAEmitterCell = { let cell = CAEmitterCell() //粒子的创建速率 默认 0 cell.birthRate = 200 //粒子存活时间 单位s cell.lifetime = 0.3 //粒子的生存时间容差 0.3 += (0.0 ~ 0.5) cell.lifetimeRange = 0.5 //粒子颜色 // cell.color = UIColor(red: 200 / 255.0, green: 87 / 255.0, blue: 14 / 255.0, alpha: 0.1).cgColor cell.color = UIColor.white.cgColor //粒子内容 cell.contents = UIImage(named: "DazFire")?.cgImage cell.contentsRect = CGRect(x: 0, y: 0, width: 0.8, height: 2) //粒子名称 cell.name = "fire" //粒子的速度 默认 0 cell.velocity = 20 //粒子速度容差 cell.velocityRange = 10 //粒子在xy平面的发射角度 cell.emissionLongitude = CGFloat(M_PI + M_PI_2) //粒子发射角度容差 cell.emissionRange = CGFloat(M_PI_2) //粒子缩放速度 cell.scaleSpeed = 0.3 //粒子缩放大小 默认1 cell.scale = 1 //粒子缩放容差 cell.scaleRange = 0.2 //粒子旋转度 默认是 0 cell.spin = 0.2 //粒子旋转度容差 cell.spinRange = 0.4 /* 以及其他属性介绍 redRange 红色容差 greenRange 绿色容差 blueRange 蓝色容差 alphaRange 透明度容差 redSpeed 红色速度 greenSpeed 绿色速度 blueSpeed 蓝色速度 alphaSpeed 透明度速度 contentsRect 渲染范围 */ return cell }() //创建一个发射器对象 lazy var fireEmitter : CAEmitterLayer = { let emitter = CAEmitterLayer() //设置中心点 // emitter.emitterPosition = CGPoint(x: self.fireImageView.frame.width * 0.6, y: self.fireImageView.frame.height * 0.4) emitter.emitterPosition = CGPoint(x: self.fireImageView.center.x + 10, y: self.fireImageView.center.y - 10) //设置尺寸 // emitter.emitterSize = CGSize(width: 20, height: 20) //设置发射模式 /* public let kCAEmitterLayerPoints: String 从一个点发出 public let kCAEmitterLayerOutline: String 从边缘发出 public let kCAEmitterLayerSurface: String 从表面发出 public let kCAEmitterLayerVolume: String 从发射器中发出 */ emitter.emitterMode = kCAEmitterLayerOutline //设置发射器形状 /* public let kCAEmitterLayerPoint: String 点 public let kCAEmitterLayerLine: String 线 public let kCAEmitterLayerRectangle: String 矩形 public let kCAEmitterLayerCuboid: String 立方体 public let kCAEmitterLayerCircle: String 圆形 public let kCAEmitterLayerSphere: String 球 */ emitter.emitterShape = kCAEmitterLayerSphere //设置发射器渲染模式 /* CA_EXTERN NSString * const kCAEmitterLayerUnordered 无序 CA_EXTERN NSString * const kCAEmitterLayerOldestFirst 生命久的粒子会被渲染在最上层 CA_EXTERN NSString * const kCAEmitterLayerOldestLast 后产生的粒子会被渲染在最上层 CA_EXTERN NSString * const kCAEmitterLayerBackToFront 粒子的渲染按照Z轴的前后顺序进行 CA_EXTERN NSString * const kCAEmitterLayerAdditive 混合模式 */ emitter.renderMode = kCAEmitterLayerUnordered return emitter }() }
apache-2.0
luksfarris/SwiftRandomForest
SwiftRandomForestTests/MatrixReferenceTest.swift
1
2129
//MIT License // //Copyright (c) 2017 Lucas Farris // //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 XCTest class MatrixReferenceTest: XCTestCase { override func setUp() {super.setUp()} override func tearDown() {super.tearDown()} func test() { let mat = MatrixTest.createDemoMatrix() let ref = MatrixReference<Int>.init(matrix: mat) ref.fill(3) let refCopy = MatrixReference<Int>.init(matrixReference: ref, count: ref.count) refCopy.fill(3) assert(ref.columns == 2) assert(refCopy.columns == 2) assert(ref.elementAt(0, 0) == 1) assert(refCopy.elementAt(0, 0) == 1) assert(ref.rowAtIndex(1)[0] == 2) assert(refCopy.rowAtIndex(2)[1] == 3) assert(ref.remove(1)==1) let popped = refCopy.remove(1) assert(popped==1) assert(ref.count == 2) assert(refCopy.count == 2) assert(ref.rowAtIndex(1)[0] == 3) assert(refCopy.rowAtIndex(1)[0] == 3) ref.append(index: 1) refCopy.append(index: 1) } }
mit
DDSSwiftTech/SwiftMine
Sources/SwiftMineCore/src/Utils/StringB64Padding.swift
1
381
// // StringB64Padding.swift // SwiftMine // // Created by David Schwartz on 12/25/16. // Copyright © 2016 David Schwartz. All rights reserved. // import Foundation extension String { func base64Padded() -> String { let paddingLength = self.count + (4 - (self.count % 4)) return self.padding(toLength: paddingLength, withPad: "=", startingAt: 0) } }
apache-2.0
lramirezsuarez/HelloWorld-iOS
HelloWorld/HelloWorld/udemyPlayground.playground/Contents.swift
1
2567
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" print("Mi nombre :V") // Arrays var arrayUdemy = [3.87, 7.1, 8.9]; arrayUdemy.remove(at: 1) arrayUdemy.append(arrayUdemy[0] * arrayUdemy[1]) var array2 = [String]() //Dictionaries var dictionaryUdemy = ["id": "1", "name":"robert"]; print(dictionaryUdemy["id"]!) print(dictionaryUdemy["name"]!) print(dictionaryUdemy.count) dictionaryUdemy["last-name"] = "Robertson" print(dictionaryUdemy) dictionaryUdemy.removeValue(forKey: "id") var dictionary2 = [String: String]() dictionary2["firstKey"] = "FirstValue" print(dictionary2) let menu = ["pizza" : 10.99, "ice-cream" : 4.99, "salad" : 7.99] print("The cost of my meal is \(menu["pizza"]! + menu["salad"]!)") //Challenge if statements username/password var username = "Lucho" var password = "12345" if username == "Lucho" && password == "123456" { print("Welcome to the app \(username)") } else if username == "Lucho" && password != "123456" { print("\(username) your password is incorrect, please try again") } else if username != "Lucho" && password == "123456" { print("\(username) your username is incorrect, please try again") } else { print("Wrond Username and Password") } //Generate a random number. let randFinger = arc4random_uniform(6) // While loop. var mult = 1 while (mult<=20) { print(7*mult) mult += 1 } var arrWhile = [7, 23, 45, 70, 98, 0] var k = 0 while (k < arrWhile.count) { arrWhile[k] += 1 k += 1 } print(arrWhile) //For loop let arrayFor = ["Eliza", "Julian", "Luis Alberto", "Luz Elena"] for name in arrayFor { print("Hi there \(name)!") } var arrHalve : [Double] = [8, 7, 19, 28] for (index, data) in arrHalve.enumerated() { arrHalve[index] = data / 2 } print(arrHalve) //Classes and Objects class Ghost { var isAlive = true var strenght = 0 func kill() { isAlive = false } func isStrong() -> Bool { if (strenght > 10) { return true } else { return false } } } var pinky = Ghost() pinky.isAlive pinky.isStrong() pinky.strenght = 20 pinky.isStrong() print(pinky.isAlive) print(pinky.strenght) print(pinky.isStrong()) pinky.kill() print(pinky.isAlive) //Optionals var number : Int? print(number) let userEnteredText = "5" let userEnteredInteger = Int(userEnteredText) if let variableAsigned = userEnteredInteger { print(variableAsigned * 7) } else { print("The user entered text is not a number") }
mit
huangboju/Moots
UICollectionViewLayout/gliding-collection-master/GlidingCollectionDemo/AppDelegate.swift
1
736
// // AppDelegate.swift // GlidingCollectionDemo // // Created by Abdurahim Jauzee on 04/03/2017. // Copyright © 2017 Ramotion Inc. All rights reserved. // import UIKit import GlidingCollection @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { setupGlidingCollection() return true } private func setupGlidingCollection() { var config = GlidingConfig.shared config.buttonsFont = UIFont.boldSystemFont(ofSize: 22) config.inactiveButtonsColor = config.activeButtonColor GlidingConfig.shared = config } }
mit
leo-lp/LPProgressHUD
Example/AppDelegate.swift
1
2152
// // AppDelegate.swift // HUD // // Created by Liam on 07/09/2021. // Copyright (c) 2021 Liam. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
mightydeveloper/swift
validation-test/compiler_crashers/26763-swift-typechecker-overapproximateosversionsatlocation.swift
9
254
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B{protocol A}enum C<T:T.o
apache-2.0
mightydeveloper/swift
validation-test/compiler_crashers/27046-swift-declcontext-getlocalconformances.swift
9
306
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class A{ class A{class C{ struct c class A{class B{class A{ func g{ struct c<T:T.c
apache-2.0
ngthduy90/Yummy
Source/Views/SwitchViewCell.swift
1
1047
// // SwitchViewCell.swift // Yummy // // Created by Duy Nguyen on 6/27/17. // Copyright © 2017 Duy Nguyen. All rights reserved. // import UIKit import ChameleonFramework protocol SwitchViewCellDelegate: class { func switchView(didChange value: Bool, at indexPath: IndexPath) } class SwitchViewCell: UITableViewCell { @IBOutlet weak var title: UILabel! @IBOutlet weak var switcher: UISwitch! var indexPath: IndexPath! weak var delegate: SwitchViewCellDelegate? override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } @IBAction func didSwitch(_ sender: Any) { delegate?.switchView(didChange: switcher.isOn, at: indexPath) } func render() { switcher.onTintColor = HexColor("E35959")! switcher.clipsToBounds = true switcher.backgroundColor = HexColor("4244A2")! switcher.layer.cornerRadius = 16.0 } }
apache-2.0
jpush/jchat-swift
ContacterModule/View/JCTableViewCell.swift
1
1176
// // JCTableViewCell.swift // JChat // // Created by JIGUANG on 2017/4/6. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit class JCTableViewCell: UITableViewCell { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) _init() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) _init() } override func awakeFromNib() { super.awakeFromNib() _init() } private lazy var line: UILabel = UILabel() private func _init() { line.backgroundColor = UIColor(netHex: 0xE8E8E8) line.layer.backgroundColor = UIColor(netHex: 0xE8E8E8).cgColor addSubview(line) addConstraint(_JCLayoutConstraintMake(line, .bottom, .equal, contentView, .bottom)) addConstraint(_JCLayoutConstraintMake(line, .left, .equal, self, .left, 15)) addConstraint(_JCLayoutConstraintMake(line, .right, .equal, self, .right, -15)) addConstraint(_JCLayoutConstraintMake(line, .height, .equal, nil, .notAnAttribute, 0.5)) } }
mit
barteljan/VISPER
VISPER-Wireframe/Classes/Wireframe/ComposedControllerDimisser.swift
1
256
// // ComposedControllerDimisser.swift // // Created by bartel on 27.12.17. // import Foundation import VISPER_Core public protocol ComposedControllerDimisser: ControllerDismisser { func add(controllerDimisser: ControllerDismisser,priority: Int) }
mit
mercadopago/sdk-ios
MercadoPagoSDK/MercadoPagoSDK/Issuer.swift
1
729
// // Issuer.swift // MercadoPagoSDK // // Created by Matias Gualino on 31/12/14. // Copyright (c) 2014 com.mercadopago. All rights reserved. // import Foundation public class Issuer : NSObject { public var _id : NSNumber? public var name : String? public class func fromJSON(json : NSDictionary) -> Issuer { let issuer : Issuer = Issuer() if json["id"] != nil && !(json["id"]! is NSNull) { if let issuerIdStr = json["id"]! as? NSString { issuer._id = NSNumber(longLong: issuerIdStr.longLongValue) } else { issuer._id = NSNumber(longLong: (json["id"] as? NSNumber)!.longLongValue) } } issuer.name = JSON(json["name"]!).asString return issuer } }
mit
LouisLWang/curly-garbanzo
weibo-swift/Classes/Module/Home/Controller/LWHomeViewController.swift
1
3226
// // LWHomeViewController.swift // weibo-swift // // Created by Louis on 10/27/15. // Copyright © 2015 louis. All rights reserved. // import UIKit class LWHomeViewController: LWBaseViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
mpclarkson/printr
Package.swift
1
71
import PackageDescription let package = Package( name: "Printr" )
mit
benlangmuir/swift
test/IDE/complete_where_clause.swift
7
15352
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GP1 | %FileCheck %s -check-prefix=A1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GP2 | %FileCheck %s -check-prefix=A1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GP3 | %FileCheck %s -check-prefix=A1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GP4 | %FileCheck %s -check-prefix=TYPE1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GP5 | %FileCheck %s -check-prefix=TYPE1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GP6 | %FileCheck %s -check-prefix=EMPTY // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_ASSOC_NODUP_1 | %FileCheck %s -check-prefix=GEN_T_ASSOC_E // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_ASSOC_NODUP_2 | %FileCheck %s -check-prefix=GEN_T_ASSOC_E // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_1 | %FileCheck %s -check-prefix=GEN_T // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_2_ASSOC | %FileCheck %s -check-prefix=GEN_T_ASSOC_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_3 | %FileCheck %s -check-prefix=GEN_T // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_4 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_5 | %FileCheck %s -check-prefix=GEN_T_S1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_6 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SUBSCRIPT_1 | %FileCheck %s -check-prefix=GEN_T_S1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SUBSCRIPT_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_1 | %FileCheck %s -check-prefix=GEN_T_S1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ALIAS_1 | %FileCheck %s -check-prefix=GEN_T_S1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ALIAS_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_1 | %FileCheck %s -check-prefix=GEN_T_NOMINAL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_3 | %FileCheck %s -check-prefix=ANYTYPE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_4 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CLASS_1 | %FileCheck %s -check-prefix=GEN_T_NOMINAL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CLASS_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_1 | %FileCheck %s -check-prefix=GEN_T_NOMINAL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSOC_1 | %FileCheck %s -check-prefix=P2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSOC_2 | %FileCheck %s -check-prefix=U_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL | %FileCheck %s -check-prefix=PROTOCOL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT | %FileCheck %s -check-prefix=PROTOCOL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_SELF | %FileCheck %s -check-prefix=PROTOCOL_SELF // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NOMINAL_TYPEALIAS | %FileCheck %s -check-prefix=NOMINAL_TYPEALIAS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NOMINAL_TYPEALIAS_EXT | %FileCheck %s -check-prefix=NOMINAL_TYPEALIAS_EXT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NOMINAL_TYPEALIAS_NESTED1 | %FileCheck %s -check-prefix=NOMINAL_TYPEALIAS_NESTED1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NOMINAL_TYPEALIAS_NESTED2 | %FileCheck %s -check-prefix=NOMINAL_TYPEALIAS_NESTED2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NOMINAL_TYPEALIAS_NESTED1_EXT | %FileCheck %s -check-prefix=NOMINAL_TYPEALIAS_NESTED1_EXT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NOMINAL_TYPEALIAS_NESTED2_EXT | %FileCheck %s -check-prefix=NOMINAL_TYPEALIAS_NESTED2_EXT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXT_ASSOC_MEMBER_1 | %FileCheck %s -check-prefix=EXT_ASSOC_MEMBER // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXT_ASSOC_MEMBER_2 | %FileCheck %s -check-prefix=EXT_ASSOC_MEMBER // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXT_SECONDTYPE | %FileCheck %s -check-prefix=EXT_SECONDTYPE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=WHERE_CLAUSE_WITH_EQUAL | %FileCheck %s -check-prefix=WHERE_CLAUSE_WITH_EQUAL class A1<T1, T2, T3> {} class A2<T4, T5> {} protocol P1 {} extension A1 where #^GP1^#{} extension A1 where T1 : P1, #^GP2^# {} extension A1 where T1 : P1, #^GP3^# extension A1 where T1 : #^GP4^# extension A1 where T1 : P1, T2 : #^GP5^# extension A1 where T1.#^GP6^# {} // A1: Begin completions // A1-DAG: Decl[GenericTypeParam]/Local: T1[#T1#]; name=T1 // A1-DAG: Decl[GenericTypeParam]/Local: T2[#T2#]; name=T2 // A1-DAG: Decl[GenericTypeParam]/Local: T3[#T3#]; name=T3 // A1-DAG: Decl[Class]/Local: A1[#A1#]; name=A1 // A1-NOT: T4 // A1-NOT: T5 // A1-NOT: Self // TYPE1: Begin completions // TYPE1-DAG: Decl[Protocol]/CurrModule: P1[#P1#]; name=P1 // TYPE1-DAG: Decl[Class]/CurrModule: A1[#A1#]; name=A1 // TYPE1-DAG: Decl[Class]/CurrModule: A2[#A2#]; name=A2 // TYPE1-NOT: T1 // TYPE1-NOT: T2 // TYPE1-NOT: T3 // TYPE1-NOT: T4 // TYPE1-NOT: T5 // TYPE1-NOT: Self // EMPTY: Begin completions, 1 items // EMPTY-DAG: Keyword/None: Type[#T1.Type#]; name=Type // EMPTY: End completions protocol A {associatedtype E} protocol B {associatedtype E} protocol C {associatedtype E} protocol D: C {associatedtype E} func ab<T: A & B>(_ arg: T) where T.#^FUNC_ASSOC_NODUP_1^# func ab<T: D>(_ arg: T) where T.#^FUNC_ASSOC_NODUP_2^# // GEN_T_ASSOC_E: Begin completions, 2 items // GEN_T_ASSOC_E-NEXT: Decl[AssociatedType]/{{Super|CurrNominal}}: E; name=E // GEN_T_ASSOC_E-NEXT: Keyword/None: Type[#T.Type#]; // GEN_T_ASSOC_E: End completions protocol Assoc { associatedtype Q } func f1<T>(_: T) where #^FUNC_1^# {} // GEN_T: Decl[GenericTypeParam]/Local: T[#T#]; name=T func f2<T>(_: T) where T.#^FUNC_2^# {} // GEN_T_DOT: Begin completions // GEN_T_DOT-DAG: Keyword/None: Type[#T.Type#]; // GEN_T_DOT-NOT: Keyword/CurrNominal: self[#T#]; // GEN_T_DOT: End completions func f2b<T: Assoc>(_: T) where T.#^FUNC_2_ASSOC^# {} // GEN_T_ASSOC_DOT: Begin completions // GEN_T_ASSOC_DOT-DAG: Decl[AssociatedType]/{{Super|CurrNominal}}: Q; // GEN_T_ASSOC_DOT-DAG: Keyword/None: Type[#T.Type#]; // GEN_T_ASSOC_DOT-NOT: Keyword/CurrNominal: self[#T#]; // GEN_T_ASSOC_DOT: End completions func f3<T>(_: T) where T == #^FUNC_3^# {} func f3<T>(_: T) where T == T.#^FUNC_4^# {} struct S1 { func f1<T>(_: T) where #^FUNC_5^# {} func f2<T>(_: T) where T.#^FUNC_6^# {} subscript<T>(x: T) -> T where #^SUBSCRIPT_1^# { return x } subscript<T>(x: T) -> T where T.#^SUBSCRIPT_2^# { return x } init<T>(_: T) where #^INIT_1^# {} init<T>(_: T) where T.#^INIT_2^# {} typealias TA1<T> = A1<T, T, T> where #^ALIAS_1^# typealias TA2<T> = A1<T, T, T> where T.#^ALIAS_2^# } // GEN_T_S1: Begin completions, 3 items // GEN_T_S1-DAG: Decl[GenericTypeParam]/Local: T[#T#]; // GEN_T_S1-DAG: Decl[Struct]/Local: S1[#S1#]; // GEN_T_S1-DAG: Keyword[Self]/CurrNominal: Self[#S1#]; // GEN_T_S1: End completions struct S2<T> where #^STRUCT_1^# {} struct S3<T> where T.#^STRUCT_2^# {} struct S4<T> where T == #^STRUCT_3^# {} struct S5<T> where T == T.#^STRUCT_4^# {} class C1<T> where #^CLASS_1^# {} class C2<T> where T.#^CLASS_2^# {} enum E1<T> where #^ENUM_1^# {} enum E2<T> where T.#^ENUM_2^# {} // GEN_T_NOMINAL: Begin completions, 1 items // GEN_T_NOMINAL: Decl[GenericTypeParam]/Local: T[#T#]; name=T // GEN_T_NOMINAL: End completions // ANYTYPE: Begin completions // ANYTYPE-DAG: Decl[GenericTypeParam]/Local: T[#T#]; // ANYTYPE-DAG: Decl[Class]/CurrModule: A1[#A1#]; // ANYTYPE-DAG: Decl[Struct]/OtherModule[Swift]/IsSystem: Int[#Int#]; // ANYTYPE: End completions protocol P2 { associatedtype T where #^ASSOC_1^# associatedtype U: Assoc where U.#^ASSOC_2^# } // P2: Begin completions, 4 items // P2-DAG: Decl[GenericTypeParam]/Local: Self[#Self#]; // P2-DAG: Decl[AssociatedType]/{{Super|CurrNominal}}: T; // P2-DAG: Decl[AssociatedType]/{{Super|CurrNominal}}: U; // P2-DAG: Decl[Protocol]/Local: P2[#P2#] // P2: End completions // U_DOT: Begin completions, 2 items // U_DOT-DAG: Keyword/None: Type[#Self.U.Type#]; // U_DOT-DAG: Decl[AssociatedType]/CurrNominal: Q; // U_DOT: End completions protocol P3 where #^PROTOCOL^# { associatedtype T: Assoc typealias U = T.Q typealias IntAlias = Int } // PROTOCOL: Begin completions, 4 items // PROTOCOL-DAG: Decl[GenericTypeParam]/Local: Self[#Self#]; // PROTOCOL-DAG: Decl[AssociatedType]/CurrNominal: T; // PROTOCOL-DAG: Decl[TypeAlias]/CurrNominal: U[#Self.T.Q#]; // PROTOCOL-DAG: Decl[Protocol]/Local: P3[#P3#]; // PROTOCOL: End completions extension P3 where #^PROTOCOL_EXT^# { // Same as PROTOCOL } protocol P4 where Self.#^PROTOCOL_SELF^# { associatedtype T: Assoc typealias U = T.Q typealias IntAlias = Int } // PROTOCOL_SELF: Begin completions // PROTOCOL_SELF-DAG: Decl[AssociatedType]/CurrNominal: T; // PROTOCOL_SELF-DAG: Decl[TypeAlias]/CurrNominal: U[#Self.T.Q#]; // PROTOCOL_SELF-DAG: Decl[TypeAlias]/CurrNominal: IntAlias[#Int#]; // PROTOCOL_SELF-DAG: Keyword/None: Type[#Self.Type#]; // PROTOCOL_SELF: End completions struct TA1<T: Assoc> where #^NOMINAL_TYPEALIAS^# { typealias U = T.Q } // NOMINAL_TYPEALIAS: Begin completions, 1 items // NOMINAL_TYPEALIAS-DAG: Decl[GenericTypeParam]/Local: T[#T#]; // NOMINAL_TYPEALIAS: End completions extension TA1 where #^NOMINAL_TYPEALIAS_EXT^# { } // NOMINAL_TYPEALIAS_EXT: Begin completions, 4 items // NOMINAL_TYPEALIAS_EXT-DAG: Decl[GenericTypeParam]/Local: T[#T#]; // NOMINAL_TYPEALIAS_EXT-DAG: Decl[TypeAlias]/CurrNominal: U[#T.Q#]; // NOMINAL_TYPEALIAS_EXT-DAG: Decl[Struct]/Local: TA1[#TA1#]; // NOMINAL_TYPEALIAS_EXT-DAG: Keyword[Self]/CurrNominal: Self[#TA1<T>#]; // NOMINAL_TYPEALIAS_EXT: End completions struct TA2<T: Assoc> { struct Inner1<U> where #^NOMINAL_TYPEALIAS_NESTED1^# { typealias X1 = T typealias X2 = T.Q } // NOMINAL_TYPEALIAS_NESTED1: Begin completions, 2 items // NOMINAL_TYPEALIAS_NESTED1-DAG: Decl[GenericTypeParam]/Local: T[#T#]; // NOMINAL_TYPEALIAS_NESTED1-DAG: Decl[GenericTypeParam]/Local: U[#U#]; // NOMINAL_TYPEALIAS_NESTED1: End completions struct Inner2 where #^NOMINAL_TYPEALIAS_NESTED2^# { typealias X1 = T typealias X2 = T.Q } // NOMINAL_TYPEALIAS_NESTED2: Begin completions, 1 items // NOMINAL_TYPEALIAS_NESTED2-DAG: Decl[GenericTypeParam]/Local: T[#T#]; // NOMINAL_TYPEALIAS_NESTED2: End completions } extension TA2.Inner1 where #^NOMINAL_TYPEALIAS_NESTED1_EXT^# {} // NOMINAL_TYPEALIAS_NESTED1_EXT: Begin completions, 6 items // NOMINAL_TYPEALIAS_NESTED1_EXT-DAG: Decl[GenericTypeParam]/Local: T[#T#]; // NOMINAL_TYPEALIAS_NESTED1_EXT-DAG: Decl[GenericTypeParam]/Local: U[#U#]; // NOMINAL_TYPEALIAS_NESTED1_EXT-DAG: Decl[TypeAlias]/CurrNominal: X1[#T#]; // NOMINAL_TYPEALIAS_NESTED1_EXT-DAG: Decl[TypeAlias]/CurrNominal: X2[#T.Q#]; // FIXME : We shouldn't be suggesting Inner1 because it's not fully-qualified // NOMINAL_TYPEALIAS_NESTED1_EXT-DAG: Decl[Struct]/Local: Inner1[#TA2.Inner1#]; // NOMINAL_TYPEALIAS_NESTED1_EXT-DAG: Keyword[Self]/CurrNominal: Self[#TA2<T>.Inner1<U>#]; // NOMINAL_TYPEALIAS_NESTED1_EXT: End completions extension TA2.Inner2 where #^NOMINAL_TYPEALIAS_NESTED2_EXT^# {} // NOMINAL_TYPEALIAS_NESTED2_EXT: Begin completions, 5 items // NOMINAL_TYPEALIAS_NESTED2_EXT-DAG: Decl[GenericTypeParam]/Local: T[#T#]; // NOMINAL_TYPEALIAS_NESTED2_EXT-DAG: Decl[TypeAlias]/CurrNominal: X1[#T#]; // NOMINAL_TYPEALIAS_NESTED2_EXT-DAG: Decl[TypeAlias]/CurrNominal: X2[#T.Q#]; // FIXME : We shouldn't be suggesting Inner2 because it's not fully-qualified // NOMINAL_TYPEALIAS_NESTED2_EXT-DAG: Decl[Struct]/Local: Inner2[#TA2.Inner2#]; // NOMINAL_TYPEALIAS_NESTED2_EXT-DAG: Keyword[Self]/CurrNominal: Self[#TA2<T>.Inner2#]; // NOMINAL_TYPEALIAS_NESTED2_EXT: End completions protocol WithAssoc { associatedtype T: Assoc } extension WithAssoc where T.#^EXT_ASSOC_MEMBER_1^# // EXT_ASSOC_MEMBER: Begin completions, 2 items // EXT_ASSOC_MEMBER-DAG: Decl[AssociatedType]/CurrNominal: Q; // EXT_ASSOC_MEMBER-DAG: Keyword/None: Type[#Self.T.Type#]; // EXT_ASSOC_MEMBER: End completions extension WithAssoc where Int == T.#^EXT_ASSOC_MEMBER_2^# // Same as EXT_ASSOC_MEMBER extension WithAssoc where Int == #^EXT_SECONDTYPE^# // EXT_SECONDTYPE: Begin completions // EXT_SECONDTYPE-DAG: Decl[AssociatedType]/CurrNominal: T; // EXT_SECONDTYPE: End completions func foo<K: WithAssoc>(_ key: K.Type) where K.#^WHERE_CLAUSE_WITH_EQUAL^# == S1 {} // WHERE_CLAUSE_WITH_EQUAL: Begin completions, 2 items // WHERE_CLAUSE_WITH_EQUAL-DAG: Decl[AssociatedType]/CurrNominal: T; // WHERE_CLAUSE_WITH_EQUAL-DAG: Keyword/None: Type[#K.Type#]; // WHERE_CLAUSE_WITH_EQUAL: End completions
apache-2.0
tardieu/swift
test/IDE/complete_members_optional.swift
27
1949
// RUN: sed -n -e '1,/NO_ERRORS_UP_TO_HERE$/ p' %s > %t_no_errors.swift // RUN: %target-swift-frontend -typecheck -verify -disable-objc-attr-requires-foundation-module %t_no_errors.swift // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OPTIONAL_MEMBERS_1 | %FileCheck %s -check-prefix=OPTIONAL_MEMBERS_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OPTIONAL_MEMBERS_2 | %FileCheck %s -check-prefix=OPTIONAL_MEMBERS_2 @objc protocol HasOptionalMembers1 { @objc optional func optionalInstanceFunc() -> Int @objc optional static func optionalClassFunc() -> Int @objc optional var optionalInstanceProperty: Int { get } @objc optional static var optionalClassProperty: Int { get } } func sanityCheck1(_ a: HasOptionalMembers1) { func isOptionalInt(_ a: inout Int?) {} var result1 = a.optionalInstanceFunc?() isOptionalInt(&result1) var result2 = a.optionalInstanceProperty isOptionalInt(&result2) } // NO_ERRORS_UP_TO_HERE func optionalMembers1(_ a: HasOptionalMembers1) { a.#^OPTIONAL_MEMBERS_1^# } // OPTIONAL_MEMBERS_1: Begin completions, 2 items // OPTIONAL_MEMBERS_1-DAG: Decl[InstanceMethod]/CurrNominal: optionalInstanceFunc!()[#Int#]{{; name=.+$}} // OPTIONAL_MEMBERS_1-DAG: Decl[InstanceVar]/CurrNominal: optionalInstanceProperty[#Int?#]{{; name=.+$}} // OPTIONAL_MEMBERS_1: End completions func optionalMembers2<T : HasOptionalMembers1>(_ a: T) { T.#^OPTIONAL_MEMBERS_2^# } // OPTIONAL_MEMBERS_2: Begin completions, 3 items // OPTIONAL_MEMBERS_2-DAG: Decl[InstanceMethod]/Super: optionalInstanceFunc!({#self: HasOptionalMembers1#})[#() -> Int#]{{; name=.+$}} // OPTIONAL_MEMBERS_2-DAG: Decl[StaticMethod]/Super: optionalClassFunc!()[#Int#]{{; name=.+$}} // OPTIONAL_MEMBERS_2-DAG: Decl[StaticVar]/Super: optionalClassProperty[#Int?#]{{; name=.+$}} // OPTIONAL_MEMBERS_2: End completions
apache-2.0
Za1006/TIY-Assignments
The Grail Diary/The Grail Diary/Place.swift
1
589
// // Places.swift // The Grail Diary // // Created by Elizabeth Yeh on 10/19/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import Foundation class FamousPlaces { var siteName: String var siteLocation: String var siteHistory: String var siteAttribute: String init(dictionary: NSDictionary) { siteName = dictionary["siteName"] as! String siteLocation = dictionary["siteLocation"] as! String siteHistory = dictionary["siteHistory"] as! String siteAttribute = dictionary["siteAttribute"] as! String } }
cc0-1.0
dataich/TypetalkSwift
TypetalkSwift/Requests/GetFriends.swift
1
973
// // GetFriends.swift // TypetalkSwift // // Created by Taichiro Yoshida on 2017/10/15. // Copyright © 2017 Nulab Inc. All rights reserved. // import Alamofire // sourcery: AutoInit public struct GetFriends: Request { public let q :String public let offset : Int? public let count : Int? public typealias Response = GetFriendsResponse public var path: String { return "/search/friends" } public var version: Int { return 2 } public var parameters: Parameters? { var parameters: Parameters = [:] parameters["q"] = self.q parameters["offset"] = self.offset parameters["count"] = self.count return parameters } // sourcery:inline:auto:GetFriends.AutoInit public init(q: String, offset: Int?, count: Int?) { self.q = q self.offset = offset self.count = count } // sourcery:end } public struct GetFriendsResponse: Codable { public let accounts: [AccountWithStatus] public let count: Int }
mit
PureSwift/Silica
Sources/Silica/CairoConvertible.swift
1
288
// // CairoConvertible.swift // Silica // // Created by Alsey Coleman Miller on 5/9/16. // Copyright © 2016 PureSwift. All rights reserved. // public protocol CairoConvertible { associatedtype CairoType init(cairo: CairoType) func toCairo() -> CairoType }
mit
luongtsu/MHCalendar
MHCalendar/MHCalendar0.swift
1
10610
// // MHCalendar.swift // MHCalendarDemo // // Created by Luong Minh Hiep on 9/11/17. // Copyright © 2017 Luong Minh Hiep. All rights reserved. // /* import UIKit private let collectionCellReuseIdentifier = "MHCollectionViewCell" protocol MHCalendarResponsible: class { func didSelectDate(date: Date) func didSelectDates(dates: [Date]) func didSelectAnotherMonth(isNextMonth: Bool) } open class MHCalendar0: UIView { weak var mhCalendarObserver : MHCalendarResponsible? // Appearance var tintColor: UIColor var dayDisabledTintColor: UIColor var weekdayTintColor: UIColor var weekendTintColor: UIColor var todayTintColor: UIColor var dateSelectionColor: UIColor var monthTitleColor: UIColor var backgroundImage: UIImage? var backgroundColor: UIColor? // Other config var selectedDates = [Date]() var startDate: Date? var hightlightsToday: Bool = true var hideDaysFromOtherMonth: Bool = false var multiSelectEnabled: Bool = true var displayingMonthIndex: Int = 0// count from starting date fileprivate(set) open var startYear: Int fileprivate(set) open var endYear: Int override open func viewDidLoad() { super.viewDidLoad() // setup collectionview self.collectionView?.delegate = self self.collectionView?.backgroundColor = UIColor.clear self.collectionView?.showsHorizontalScrollIndicator = false self.collectionView?.showsVerticalScrollIndicator = false // Register cell classes self.collectionView!.register(UINib(nibName: "MHCollectionViewCell", bundle: Bundle(for: MHCalendar.self )), forCellWithReuseIdentifier: collectionCellReuseIdentifier) self.collectionView!.register(UINib(nibName: "MHCalendarHeaderView", bundle: Bundle(for: MHCalendar.self )), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "MHCalendarHeaderView") if backgroundImage != nil { self.collectionView!.backgroundView = UIImageView(image: backgroundImage) } else if backgroundColor != nil { self.collectionView?.backgroundColor = backgroundColor } else { self.collectionView?.backgroundColor = UIColor.white } } public init(startYear: Int = Date().year(), endYear: Int = Date().year(), multiSelection: Bool = true, selectedDates: [Date] = []) { self.startYear = startYear self.endYear = endYear self.multiSelectEnabled = multiSelection self.selectedDates = selectedDates //Text color initializations self.tintColor = UIColor.rgb(192, 55, 44) self.dayDisabledTintColor = UIColor.rgb(200, 200, 200) self.weekdayTintColor = UIColor.rgb(46, 204, 113) self.weekendTintColor = UIColor.rgb(192, 57, 43) self.dateSelectionColor = UIColor.rgb(52, 152, 219) self.monthTitleColor = UIColor.rgb(211, 84, 0) self.todayTintColor = UIColor.rgb(248, 160, 46) //Layout creation let layout = UICollectionViewFlowLayout() layout.sectionHeadersPinToVisibleBounds = true layout.minimumInteritemSpacing = 1 layout.minimumLineSpacing = 1 layout.headerReferenceSize = CGSize(width: UIScreen.main.bounds.width, height: MHCalendarHeaderView.defaultHeight) super.init(collectionViewLayout: layout) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewFlowLayout override open func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let startDate = Date(year: startYear, month: 1, day: 1) let firstDayOfMonth = startDate.dateByAddingMonths(displayingMonthIndex) let addingPrefixDaysWithMonthDyas = ( firstDayOfMonth.numberOfDaysInMonth() + firstDayOfMonth.weekday() - Calendar.current.firstWeekday ) let addingSuffixDays = addingPrefixDaysWithMonthDyas%7 var totalNumber = addingPrefixDaysWithMonthDyas if addingSuffixDays != 0 { totalNumber = totalNumber + (7 - addingSuffixDays) } return totalNumber } override open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionCellReuseIdentifier, for: indexPath) as! MHCollectionViewCell let calendarStartDate = Date(year:startYear, month: 1, day: 1) let firstDayOfThisMonth = calendarStartDate.dateByAddingMonths(displayingMonthIndex) let prefixDays = ( firstDayOfThisMonth.weekday() - Calendar.current.firstWeekday) if indexPath.row >= prefixDays { cell.isCellSelectable = true let currentDate = firstDayOfThisMonth.dateByAddingDays(indexPath.row-prefixDays) let nextMonthFirstDay = firstDayOfThisMonth.dateByAddingDays(firstDayOfThisMonth.numberOfDaysInMonth()-1) cell.currentDate = currentDate cell.titleLabel.text = "\(currentDate.day())" if selectedDates.filter({ $0.isDateSameDay(currentDate)}).count > 0 && (firstDayOfThisMonth.month() == currentDate.month()) { cell.selectedForLabelColor(dateSelectionColor) } else { cell.deSelectedForLabelColor(weekdayTintColor) if cell.currentDate.isSaturday() || cell.currentDate.isSunday() { cell.titleLabel.textColor = weekendTintColor } if (currentDate > nextMonthFirstDay) { cell.isCellSelectable = false if hideDaysFromOtherMonth { cell.titleLabel.textColor = UIColor.clear } else { cell.titleLabel.textColor = self.dayDisabledTintColor } } if currentDate.isToday() && hightlightsToday { cell.setTodayCellColor(todayTintColor) } if startDate != nil { if Calendar.current.startOfDay(for: cell.currentDate as Date) < Calendar.current.startOfDay(for: startDate!) { cell.isCellSelectable = false cell.titleLabel.textColor = self.dayDisabledTintColor } } } } else { cell.deSelectedForLabelColor(weekdayTintColor) cell.isCellSelectable = false let previousDay = firstDayOfThisMonth.dateByAddingDays(-( prefixDays - indexPath.row)) cell.currentDate = previousDay cell.titleLabel.text = "\(previousDay.day())" if hideDaysFromOtherMonth { cell.titleLabel.textColor = UIColor.clear } else { cell.titleLabel.textColor = self.dayDisabledTintColor } } cell.backgroundColor = UIColor.clear return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { let rect = UIScreen.main.bounds let screenWidth = rect.size.width - 7 return CGSize(width: screenWidth/7, height: screenWidth/7); } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(5, 0, 5, 0); //top,left,bottom,right } override open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionHeader { let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "MHCalendarHeaderView", for: indexPath) as! MHCalendarHeaderView let startDate = Date(year: startYear, month: 1, day: 1) let firstDayOfMonth = startDate.dateByAddingMonths(indexPath.section) header.currentMonthLabel.text = firstDayOfMonth.monthNameFull() header.currentMonthLabel.textColor = monthTitleColor header.updateWeekdaysLabelColor(weekdayTintColor) header.updateWeekendLabelColor(weekendTintColor) header.backgroundColor = UIColor.clear return header; } return UICollectionReusableView() } override open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! MHCollectionViewCell if !multiSelectEnabled && cell.isCellSelectable! { mhCalendarObserver?.didSelectDate(date: cell.currentDate) cell.selectedForLabelColor(dateSelectionColor) selectedDates.append(cell.currentDate) return } if cell.isCellSelectable! { if selectedDates.filter({ $0.isDateSameDay(cell.currentDate) }).count == 0 { selectedDates.append(cell.currentDate) cell.selectedForLabelColor(dateSelectionColor) if cell.currentDate.isToday() { cell.setTodayCellColor(dateSelectionColor) } } else { selectedDates = selectedDates.filter(){ return !($0.isDateSameDay(cell.currentDate)) } if cell.currentDate.isSaturday() || cell.currentDate.isSunday() { cell.deSelectedForLabelColor(weekendTintColor) } else { cell.deSelectedForLabelColor(weekdayTintColor) } if cell.currentDate.isToday() && hightlightsToday{ cell.setTodayCellColor(todayTintColor) } } } } }*/
mit
imclean/JLDishWashers
JLDishwasher/UnitPriceInfo.swift
1
1380
// // UnitPriceInfo.swift // JLDishwasher // // Created by Iain McLean on 21/12/2016. // Copyright © 2016 Iain McLean. All rights reserved. // import Foundation public class UnitPriceInfo { /** Returns an array of models based on given dictionary. Sample usage: let unitPriceInfo_list = UnitPriceInfo.modelsFromDictionaryArray(someDictionaryArrayFromJSON) - parameter array: NSArray from JSON dictionary. - returns: Array of UnitPriceInfo Instances. */ public class func modelsFromDictionaryArray(array:NSArray) -> [UnitPriceInfo] { var models:[UnitPriceInfo] = [] for item in array { models.append(UnitPriceInfo(dictionary: item as! NSDictionary)!) } return models } /** Constructs the object based on the given dictionary. Sample usage: let unitPriceInfo = UnitPriceInfo(someDictionaryFromJSON) - parameter dictionary: NSDictionary from JSON. - returns: UnitPriceInfo Instance. */ required public init?(dictionary: NSDictionary) { } /** Returns the dictionary representation for the current instance. - returns: NSDictionary. */ public func dictionaryRepresentation() -> NSDictionary { let dictionary = NSMutableDictionary() return dictionary } }
gpl-3.0
KevinGong2013/Printer
Sources/Printer/Ticket/Block.swift
1
1885
// // Block.swift // Ticket // // Created by gix on 2019/6/30. // Copyright © 2019 gix. All rights reserved. // import Foundation public protocol Printable { func data(using encoding: String.Encoding) -> Data } public protocol BlockDataProvider: Printable { } public protocol Attribute { var attribute: [UInt8] { get } } public struct Block: Printable { public static var defaultFeedPoints: UInt8 = 70 private let feedPoints: UInt8 private let dataProvider: BlockDataProvider public init(_ dataProvider: BlockDataProvider, feedPoints: UInt8 = Block.defaultFeedPoints) { self.feedPoints = feedPoints self.dataProvider = dataProvider } public func data(using encoding: String.Encoding) -> Data { return dataProvider.data(using: encoding) + Data.print(feedPoints) } } public extension Block { // blank line static var blank = Block(Blank()) static func blank(_ line: UInt8) -> Block { return Block(Blank(), feedPoints: Block.defaultFeedPoints * line) } // qr static func qr(_ content: String) -> Block { return Block(QRCode(content)) } // title static func title(_ content: String) -> Block { return Block(Text.title(content)) } // plain text static func plainText(_ content: String) -> Block { return Block(Text.init(content)) } static func text(_ text: Text) -> Block { return Block(text) } // key value static func kv(k: String, v: String) -> Block { return Block(Text.kv(k: k, v: v)) } // dividing static var dividing = Block(Dividing.default) // image static func image(_ im: Image, attributes: TicketImage.PredefinedAttribute...) -> Block { return Block(TicketImage(im, attributes: attributes)) } }
apache-2.0
charlymr/IRLDocumentScanner
demo/demo/ViewController.swift
1
1688
// // ViewController.swift // demo // // Created by Denis Martin on 28/06/2015. // Copyright (c) 2015 iRLMobile. All rights reserved. // import UIKit import IRLDocumentScanner; class ViewController : UIViewController, IRLScannerViewControllerDelegate { @IBOutlet weak var scanButton: UIButton! @IBOutlet weak var imageView: UIImageView! // MARK: User Actions @IBAction func scan(_ sender: AnyObject) { let scanner = IRLScannerViewController.standardCameraView(with: self) scanner.showControls = true scanner.showAutoFocusWhiteRectangle = true present(scanner, animated: true, completion: nil) } // MARK: IRLScannerViewControllerDelegate func pageSnapped(_ page_image: UIImage, from controller: IRLScannerViewController) { controller.dismiss(animated: true) { () -> Void in self.imageView.image = page_image } } func cameraViewWillUpdateTitleLabel(_ cameraView: IRLScannerViewController) -> String? { var text = "" switch cameraView.cameraViewType { case .normal: text = text + "NORMAL" case .blackAndWhite: text = text + "B/W-FILTER" case .ultraContrast: text = text + "CONTRAST" } switch cameraView.detectorType { case .accuracy: text = text + " | Accuracy" case .performance: text = text + " | Performance" } return text } func didCancel(_ cameraView: IRLScannerViewController) { cameraView.dismiss(animated: true){ ()-> Void in NSLog("Cancel pressed"); } } }
mit
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Reader/ReaderMenuAction.swift
1
1135
final class ReaderMenuAction { private let isLoggedIn: Bool init(logged: Bool) { isLoggedIn = logged } func execute(post: ReaderPost, context: NSManagedObjectContext, readerTopic: ReaderAbstractTopic? = nil, anchor: UIView, vc: UIViewController, source: ReaderPostMenuSource) { let service: ReaderTopicService = ReaderTopicService(managedObjectContext: context) let siteTopic: ReaderSiteTopic? = post.isFollowing ? service.findSiteTopic(withSiteID: post.siteID) : nil ReaderShowMenuAction(loggedIn: isLoggedIn).execute(with: post, context: context, siteTopic: siteTopic, readerTopic: readerTopic, anchor: anchor, vc: vc, source: source) } }
gpl-2.0
jjochen/photostickers
UITests/Tests/PhotoStickersUITests.swift
1
4359
// // PhotoStickersUITests.swift // PhotoStickersUITests // // Created by Jochen Pfeiffer on 28/12/2016. // Copyright © 2016 Jochen Pfeiffer. All rights reserved. // import XCTest class PhotoStickersUITests: XCTestCase { func testMessagesExtension() { guard let messageApp = XCUIApplication.eps_iMessagesApp() else { fatalError() } messageApp.terminate() messageApp.launchArguments += ["-RunningUITests", "true"] setupSnapshot(messageApp) messageApp.launch() tapButton(withLocalizations: ["Fortfahren", "Continue"], inApp: messageApp) tapButton(withLocalizations: ["Abbrechen", "Cancel"], inApp: messageApp) messageApp.tables["ConversationList"].cells.firstMatch.tap() sleep(1) messageApp.textFields["messageBodyField"].tap() sleep(1) let start = messageApp.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) let finish = messageApp.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.6)) start.press(forDuration: 0.05, thenDragTo: finish) sleep(1) messageApp.textFields["messageBodyField"].tap() let messageText = "🎉🎉🎉 Party?" messageApp.typeText(messageText) sleep(1) messageApp.buttons["sendButton"].tap() sleep(1) let appCells = messageApp.collectionViews["appSelectionBrowserIdentifier"].cells let photoStickersCell = appCells.matching(NSPredicate(format: "label CONTAINS[c] 'Photo Stickers'")).firstMatch photoStickersCell.tap() sleep(5) let partySticker = messageApp.collectionViews["StickerBrowserCollectionView"].cells.element(boundBy: 5) let messageCell = messageApp.collectionViews["TranscriptCollectionView"].cells.matching(NSPredicate(format: "label CONTAINS[c] %@", messageText)).firstMatch let cellWidth = messageCell.frame.size.width let rightDX = CGFloat(130) let relativeDX = 1 - rightDX / cellWidth let sourceCoordinate: XCUICoordinate = partySticker.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: 0.1)) let destCoordinate: XCUICoordinate = messageCell.coordinate(withNormalizedOffset: CGVector(dx: relativeDX, dy: 0.0)) sourceCoordinate.press(forDuration: 0.5, thenDragTo: destCoordinate) sleep(1) snapshot("1_Messages", timeWaitingForIdle: 40) messageApp.otherElements["collapseButtonIdentifier"].tap() sleep(1) snapshot("2_Sticker_Collection", timeWaitingForIdle: 40) messageApp.buttons["StickerBrowserEditBarButtonItem"].tap() messageApp.collectionViews["StickerBrowserCollectionView"].cells.element(boundBy: 0).tap() sleep(1) messageApp.buttons["RectangleButton"].tap() snapshot("3_Edit_Sticker") } } // MARK: Helper private extension PhotoStickersUITests { func isIPad() -> Bool { let window = XCUIApplication().windows.element(boundBy: 0) return window.horizontalSizeClass == .regular && window.verticalSizeClass == .regular } func tapButton(withLocalizations localizations: [String], inApp app: XCUIApplication) { localizations.forEach { title in let button = app.buttons[title] if button.exists { button.tap() } } } } extension XCUIElement { func forceTap() { if isHittable { tap() } else { let coordinate: XCUICoordinate = self.coordinate(withNormalizedOffset: CGVector(dx: 0.0, dy: 0.0)) coordinate.tap() } } // The following is a workaround for inputting text in the // simulator when the keyboard is hidden func setText(_ text: String, application: XCUIApplication) { UIPasteboard.general.string = text doubleTap() application.menuItems["Paste"].tap() } func dragAndDropUsingCenterPos(forDuration duration: TimeInterval, thenDragTo destElement: XCUIElement) { let sourceCoordinate: XCUICoordinate = coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) let destCorodinate: XCUICoordinate = destElement.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) sourceCoordinate.press(forDuration: duration, thenDragTo: destCorodinate) } }
mit
ddc391565320/PathMenu
PathMenuTests/PathMenuTests.swift
2
898
// // PathMenuTests.swift // PathMenuTests // // Created by pixyzehn on 12/27/14. // Copyright (c) 2014 pixyzehn. All rights reserved. // import UIKit import XCTest class PathMenuTests: 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() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
mlpqaz/V2ex
ZZV2ex/ZZV2ex/Common/V2EXSetting.swift
1
576
// // V2EXSetting.swift // ZZV2ex // // Created by ios on 2017/5/1. // Copyright © 2017年 张璋. All rights reserved. // import UIKit let keyPrefix = "me.fin.V2EXSettings." class V2EXSetting: NSObject { static let sharedInstance = V2EXSetting() fileprivate override init() { super.init() } subscript(key:String) -> String? { get { return UserDefaults.standard.object(forKey: keyPrefix + key) as? String } set { UserDefaults.standard.setValue(newValue, forKey: keyPrefix + key) } } }
apache-2.0
williamFalcon/Bolt_Swift
Source/GCD/GCD.swift
2
2074
/* GCD.swift Created by William Falcon on 2/15/15. The MIT License (MIT) Copyright (c) 2015 William Falcon will@hacstudios.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit import Foundation public class GCD: NSObject { ///Executes code with delay public class func _delay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } ///Places on main q public class func _dispatchMainQueue(closure:()->()) { dispatch_async(dispatch_get_main_queue(), { () -> Void in closure() }) } public class func _dispatchToBackgroundQueueWithPriority(priority:Int, closure:()->()) { dispatch_async(dispatch_get_global_queue(priority, 0), closure) } ///Dispatches code once public class func _dispatchOnce(closure:()->()) { var token: dispatch_once_t = 0 dispatch_once(&token) { closure() } } }
mit
SuperAwesomeLTD/sa-mobile-sdk-ios
Example/SuperAwesomeExampleTests/Common/Components/IdGeneratorTests.swift
1
911
// // IdGeneratorTests.swift // SuperAwesome-Unit-Moya-Tests // // Created by Gunhan Sancar on 04/05/2020. // import XCTest import Nimble @testable import SuperAwesome class IdGeneratorTests: XCTestCase { func test_dauId_advertisingEnabled_returnsUniqueDauId() throws { // Given let mockAlphanumeric = "123abc" let idGenerator = IdGenerator(preferencesRepository: PreferencesRepositoryMock(), sdkInfo: SdkInfoMock(), numberGenerator: NumberGeneratorMock(0, nextAlphaNumberic: mockAlphanumeric), dateProvider: DateProviderMock(monthYear: "102020")) // When let result = idGenerator.uniqueDauId // Then expect(5118545265961385482).to(equal(result)) } }
lgpl-3.0
C39GX6/ArchiveExport
ArchiveExport/ViewController.swift
1
8161
// // ViewController.swift // ArchiveExport // // Created by 刘诗彬 on 14/10/29. // Copyright (c) 2014年 Stephen. All rights reserved. // import Cocoa class ViewController: NSViewController,NSOpenSavePanelDelegate,NSWindowDelegate{ @IBOutlet weak var archiveButton: NSPopUpButton! @IBOutlet weak var provisioningButton: NSPopUpButton! @IBOutlet weak var indicator: NSProgressIndicator! @IBOutlet weak var iconView: NSImageView! @IBOutlet weak var statLabel: NSTextField! @IBOutlet weak var exportButton: NSButton! @IBOutlet weak var infoLabel: NSTextField! var exportTask : NSTask! var exportPath : String! var archives : [AEArchive]! var provisionings : [AEProvisioning]! var exporting = false @IBAction func export(sender: AnyObject) { if exportTask != nil && exportTask.running { return } let archive = selectedArchive() let provisioning = selectedProvisining() if archive == nil || provisioning == nil{ return } let savePanel = NSSavePanel(); savePanel.allowedFileTypes = ["ipa"] savePanel.allowsOtherFileTypes = false savePanel.directoryURL = NSURL(fileURLWithPath: NSHomeDirectory()+"/Desktop") savePanel.nameFieldStringValue = archive!.name savePanel.delegate = self savePanel.beginSheetModalForWindow(self.view.window!, completionHandler:{(NSModalResponse) -> () in }) } func exportTo(path:String){ if exportTask != nil && exportTask.running { return } statLabel.stringValue = "" let archive = selectedArchive() let provisioning = selectedProvisining() if archive != nil && provisioning != nil{ exportPath = path exportTask = NSTask(); exportTask.launchPath = "/usr/bin/xcrun" exportTask.arguments = ["--sdk","iphoneos","PackageApplication",archive!.appPath!,"--embed",provisioning!.identifier!,"-o",exportPath] setIsExporting(true) exportTask.terminationHandler = {[weak self](_:NSTask) in dispatch_async(dispatch_get_main_queue(), {self?.checkResult()})} exportTask.launch() } } func checkResult(){ if exportTask != nil{ if exportTask.running{ setIsExporting(true) } else { setIsExporting(false) if NSFileManager.defaultManager().fileExistsAtPath(exportPath){ statLabel.textColor = NSColor.greenColor() statLabel.stringValue = "导出成功" } else { statLabel.textColor = NSColor.redColor() statLabel.stringValue = "导出失败" } } } else { setIsExporting(false) } } func setIsExporting(exporting: Bool){ exportButton.enabled = !exporting if !exporting { exportTask = nil; indicator.stopAnimation(nil) } else { indicator.startAnimation(nil) } } @IBAction func valueChanged(sender: AnyObject) { updateArchiveInfo() } func selectedArchive()->AEArchive?{ let selectedIndex = archiveButton.indexOfSelectedItem var archive : AEArchive! if selectedIndex >= 0{ archive = archives[selectedIndex] } return archive } func selectedProvisining()->AEProvisioning?{ let selectedIndex = provisioningButton.indexOfSelectedItem var provisioning : AEProvisioning? if selectedIndex >= 0 { provisioning = provisionings[selectedIndex] } return provisioning } func updateArchiveInfo(){ let archive = self.selectedArchive() if archive == nil { infoLabel.stringValue = "没有发现包" return } iconView.image = archive!.icon let info = "\(archive!.name)\n" + "Identifier:\(archive!.identifier)\n" + "Version:\(archive!.version) Build:\(archive!.buildVersion)\n" + "Create Date:\(archive!.dateString)" infoLabel.alignment = .Left infoLabel.stringValue = info let archiveProvisioning = AEProvisioning(filePath: archive!.appPath + "/embedded.mobileprovision"); for (index,provisioning) in provisionings.enumerate(){ if provisioning.identifier == archiveProvisioning.identifier{ provisioningButton.selectItemAtIndex(index) break } } } func reloadArchives(){ let archivePaths = self.archivePaths() archives = [AEArchive]() for path in archivePaths{ archives.append(AEArchive(path: path)) } archives = archives.sort{$0.createDate.compare($1.createDate) == .OrderedDescending} let selectedItem = archiveButton.selectedItem archiveButton.removeAllItems() var archiveNames = [String]() for archive in archives{ let displayName = "\(archive.name)_\(archive.version) \(archive.dateString)" archiveNames.append(displayName); } archiveButton.addItemsWithTitles(archiveNames) for item:NSMenuItem in archiveButton.itemArray{ if item.title == selectedItem?.title{ archiveButton.selectItem(item) break } } provisionings = [AEProvisioning]() let provisioningPaths = self.provisioningPaths() for path in provisioningPaths{ provisionings.append(AEProvisioning(filePath:path)); } provisioningButton.removeAllItems() for (index,provisioning) in provisionings.enumerate(){ if let displayName = provisioning.name{ provisioningButton.addItemWithTitle("(\(index))"+displayName) } else { provisioningButton.addItemWithTitle("(\(index))unknow") } } self.updateArchiveInfo() } func archivePaths()->[String]{ let fileManger = NSFileManager.defaultManager() var archives = [String]() let archivesHome = NSHomeDirectory() + "/Library/Developer/Xcode/Archives/"; if let enumerator = fileManger.enumeratorAtPath(archivesHome){ while let file = enumerator.nextObject() as! String!{ if file.hasSuffix(".xcarchive"){ archives.append(archivesHome+file) enumerator.skipDescendants(); } } } return archives } func provisioningPaths()->[String]{ let fileManger = NSFileManager.defaultManager() var provisionings = [String]() let provisioningsHome = NSHomeDirectory() + "/Library/MobileDevice/Provisioning Profiles/"; if let enumerator = fileManger.enumeratorAtPath(provisioningsHome){ while let file = enumerator.nextObject() as! String!{ if file.hasSuffix(".mobileprovision"){ provisionings.append(provisioningsHome+file) enumerator.skipDescendants(); } } } return provisionings } override func viewDidLoad() { super.viewDidLoad() self.reloadArchives() self.view.window?.delegate = self NSNotificationCenter.defaultCenter().addObserver(self, selector:"applicationDidBecomeActiveNotification:", name: NSApplicationDidBecomeActiveNotification, object:nil) // Do any additional setup after loading the view. } func panel(sender: AnyObject, userEnteredFilename filename: String, confirmed okFlag: Bool) -> String? { if okFlag { let path = sender.URL?!.path self.exportTo(path!) return path } return nil; } func applicationDidBecomeActiveNotification(notification: NSNotification) { self.reloadArchives() } }
apache-2.0
SlimGinz/Assurance-App-For-iOS
Assurance/AppDelegate.swift
1
2160
// // AppDelegate.swift // Assurance // // Created by Cory Ginsberg on 3/5/15. // Copyright (c) 2015 Boiling Point Development. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
san2ride/Everywhere-Goods
Everywhere/Everywhere/ProductViewController.swift
1
7522
// // ProductViewController.swift // Everywhere // // Created by don't touch me on 4/6/17. // Copyright © 2017 trvl, LLC. All rights reserved. // import UIKit import MapKit import CoreLocation class ProductViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var searchProducts: UISearchBar! @IBOutlet weak var collectionView: UICollectionView! let manager = CLLocationManager() var products: ProductAPI! var productData = [Product]() var filteredProducts = [Product]() var userZipcode: String = "" var currentProduct: Product? override func viewDidLoad() { super.viewDidLoad() manager.delegate = self manager.desiredAccuracy = kCLLocationAccuracyBest manager.requestWhenInUseAuthorization() manager.startUpdatingLocation() products.fetchProducts() { (products) -> Void in self.productData = products print(self.productData) OperationQueue.main.addOperation { if self.userZipcode != "" { self.reloadProductsFrom(zipcode: self.userZipcode) } else { self.collectionView.reloadData() } } } } override func viewWillAppear(_ animated: Bool) { collectionView.prefetchDataSource = self self.searchProducts.delegate = self let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 128, height: 42)) imageView.contentMode = .scaleAspectFit let image = UIImage(named: "logoBlack") imageView.image = image navigationItem.titleView = imageView } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if searchProducts.text != "" { return self.filteredProducts.count } if filteredProducts.count > 0 { print(filteredProducts) return self.filteredProducts.count } print(self.productData.count) return self.productData.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Product", for: indexPath) as! ProductCollectionViewCell let product: Product if searchProducts.text != "" { product = filteredProducts[indexPath.row] } else if filteredProducts.count > 0{ product = filteredProducts[indexPath.row] } else { product = productData[indexPath.row] } cell.imageView?.imageFromServer(urlString: product.image) cell.name.text = product.title cell.price.text = product.price return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let cell = collectionView.cellForItem(at: indexPath) as? ProductCollectionViewCell else { return } UIView.animate(withDuration: 0.1, delay: 0, options: [.curveEaseOut], animations: { cell.imageView?.transform = CGAffineTransform(scaleX: 0.9, y: 0.9) }) { (finished) in UIView.animate(withDuration: 0.1, delay: 0, options: [.curveEaseIn], animations: { cell.imageView?.transform = CGAffineTransform.identity }, completion: { [weak self] finished in self?.performSegue(withIdentifier: "ShowItem", sender: self) }) } self.currentProduct = self.productData[(indexPath as NSIndexPath).row] } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let selectedIndex = collectionView.indexPathsForSelectedItems?.first { var photo: Product if filteredProducts.count > 0 { photo = filteredProducts[selectedIndex.row] } else { photo = productData[selectedIndex.row] } let showImage = segue.destination as! ProductDetailViewController print(photo.image) showImage.productImageURL = photo.image let controller = segue.destination as? ProductDetailViewController controller?.theProduct = self.currentProduct } } func reloadProductsFrom(zipcode: String) { print("Reload products") print(zipcode) if productData.isEmpty { return } filteredProducts = self.productData.filter({ (p) -> Bool in return p.tags.lowercased().range(of: zipcode.lowercased()) != nil }) self.collectionView.reloadData() } } extension UIImageView { public func imageFromServer(urlString: String) { URLSession.shared.dataTask(with: URL(string: urlString)!) { (data, response, error) in if error != nil { print(error?.localizedDescription as Any) return } DispatchQueue.main.async(execute: { () -> Void in let image = UIImage(data: data!) self.image = image }) }.resume() } } extension ProductViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { filteredProducts = self.productData.filter({ (p) -> Bool in return p.tags.lowercased().range(of: searchText.lowercased()) != nil }) self.collectionView.reloadData() } } extension ProductViewController: UICollectionViewDataSourcePrefetching { func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) { } } extension ProductViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations.first let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01) let userLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location!.coordinate.latitude, location!.coordinate.longitude) let region: MKCoordinateRegion = MKCoordinateRegionMake(userLocation, span) CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error) -> Void in if (error != nil) { print(error?.localizedDescription as Any) } if (placemarks?.count)! > 0 { let pm = (placemarks?[0])! as CLPlacemark if let zipcode = pm.postalCode { manager.stopUpdatingLocation() self.userZipcode = zipcode } } }) } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Failed to find user's location: \(error.localizedDescription)") } }
mit
djwbrown/swift
validation-test/stdlib/XCTest.swift
2
17002
// RUN: %target-run-stdlib-swift // REQUIRES: executable_test // REQUIRES: objc_interop // FIXME: Add a feature for "platforms that support XCTest". // REQUIRES: OS=macosx import StdlibUnittest import XCTest var XCTestTestSuite = TestSuite("XCTest") // NOTE: When instantiating test cases for a particular test method using the // XCTestCase(selector:) initializer, those test methods must be marked // as dynamic. Objective-C XCTest uses runtime introspection to // instantiate an NSInvocation with the given selector. func execute(observers: [XCTestObservation] = [], _ run: () -> Void) { for observer in observers { XCTestObservationCenter.shared().addTestObserver(observer) } run() for observer in observers { XCTestObservationCenter.shared().removeTestObserver(observer) } } class FailureDescriptionObserver: NSObject, XCTestObservation { var failureDescription: String? func testCase(_ testCase: XCTestCase, didFailWithDescription description: String, inFile filePath: String?, atLine lineNumber: UInt) { failureDescription = description } } XCTestTestSuite.test("exceptions") { class ExceptionTestCase: XCTestCase { dynamic func test_raises() { NSException(name: NSExceptionName(rawValue: "XCTestTestSuiteException"), reason: nil, userInfo: nil).raise() } func test_raisesDuringAssertion() { let exception = NSException(name: NSExceptionName(rawValue: "XCTestTestSuiteException"), reason: nil, userInfo: nil) XCTAssertNoThrow(exception.raise()) } func test_continueAfterFailureWithAssertions() { self.continueAfterFailure = false func triggerFailure() { XCTFail("I'm outta here!") } XCTAssertNoThrow(triggerFailure()) // Should not be reached: NSException(name: NSExceptionName(rawValue: "XCTestTestSuiteException"), reason: nil, userInfo: nil).raise() } } let testCase = ExceptionTestCase(selector: #selector(ExceptionTestCase.test_raises)) execute(testCase.run) let testRun = testCase.testRun! expectEqual(1, testRun.testCaseCount) expectEqual(1, testRun.executionCount) expectEqual(0, testRun.failureCount) expectEqual(1, testRun.unexpectedExceptionCount) expectEqual(1, testRun.totalFailureCount) expectFalse(testRun.hasSucceeded) let assertionTestCase = ExceptionTestCase(selector: #selector(ExceptionTestCase.test_raisesDuringAssertion)) execute(assertionTestCase.run) let assertionTestRun = assertionTestCase.testRun! expectEqual(1, assertionTestRun.executionCount) expectEqual(0, assertionTestRun.failureCount) expectEqual(1, assertionTestRun.unexpectedExceptionCount) let continueAfterFailureTestCase = ExceptionTestCase(selector: #selector(ExceptionTestCase.test_continueAfterFailureWithAssertions)) execute(continueAfterFailureTestCase.run) let continueAfterFailureTestRun = continueAfterFailureTestCase.testRun! expectEqual(1, continueAfterFailureTestRun.executionCount) expectEqual(1, continueAfterFailureTestRun.failureCount) expectEqual(0, continueAfterFailureTestRun.unexpectedExceptionCount) } XCTestTestSuite.test("XCTAssertEqual/T") { class AssertEqualTestCase: XCTestCase { dynamic func test_whenEqual_passes() { XCTAssertEqual(1, 1) } dynamic func test_whenNotEqual_fails() { XCTAssertEqual(1, 2) } } let passingTestCase = AssertEqualTestCase(selector: #selector(AssertEqualTestCase.test_whenEqual_passes)) execute(passingTestCase.run) let passingTestRun = passingTestCase.testRun! expectTrue(passingTestRun.hasSucceeded) let failingTestCase = AssertEqualTestCase(selector: #selector(AssertEqualTestCase.test_whenNotEqual_fails)) let observer = FailureDescriptionObserver() execute(observers: [observer], failingTestCase.run) let failingTestRun = failingTestCase.testRun! expectEqual(1, failingTestRun.failureCount) expectEqual(0, failingTestRun.unexpectedExceptionCount) expectEqual(observer.failureDescription, "XCTAssertEqual failed: (\"1\") is not equal to (\"2\") - ") } XCTestTestSuite.test("XCTAssertEqual/Optional<T>") { class AssertEqualOptionalTestCase: XCTestCase { dynamic func test_whenOptionalsAreEqual_passes() { XCTAssertEqual(Optional(1),Optional(1)) } dynamic func test_whenOptionalsAreNotEqual_fails() { XCTAssertEqual(Optional(1),Optional(2)) } } let passingTestCase = AssertEqualOptionalTestCase(selector: #selector(AssertEqualOptionalTestCase.test_whenOptionalsAreEqual_passes)) execute(passingTestCase.run) let passingTestRun = passingTestCase.testRun! expectEqual(1, passingTestRun.testCaseCount) expectEqual(1, passingTestRun.executionCount) expectEqual(0, passingTestRun.failureCount) expectEqual(0, passingTestRun.unexpectedExceptionCount) expectEqual(0, passingTestRun.totalFailureCount) expectTrue(passingTestRun.hasSucceeded) let failingTestCase = AssertEqualOptionalTestCase(selector: #selector(AssertEqualOptionalTestCase.test_whenOptionalsAreNotEqual_fails)) let observer = FailureDescriptionObserver() execute(observers: [observer], failingTestCase.run) let failingTestRun = failingTestCase.testRun! expectEqual(1, failingTestRun.testCaseCount) expectEqual(1, failingTestRun.executionCount) expectEqual(1, failingTestRun.failureCount) expectEqual(0, failingTestRun.unexpectedExceptionCount) expectEqual(1, failingTestRun.totalFailureCount) expectFalse(failingTestRun.hasSucceeded) expectEqual(observer.failureDescription, "XCTAssertEqual failed: (\"Optional(1)\") is not equal to (\"Optional(2)\") - ") } XCTestTestSuite.test("XCTAssertEqual/Array<T>") { class AssertEqualArrayTestCase: XCTestCase { dynamic func test_whenArraysAreEqual_passes() { XCTAssertEqual(["foo", "bar", "baz"], ["foo", "bar", "baz"]) } dynamic func test_whenArraysAreNotEqual_fails() { XCTAssertEqual(["foo", "baz", "bar"], ["foo", "bar", "baz"]) } } let passingTestCase = AssertEqualArrayTestCase(selector: #selector(AssertEqualArrayTestCase.test_whenArraysAreEqual_passes)) execute(passingTestCase.run) let passingTestRun = passingTestCase.testRun! expectEqual(1, passingTestRun.testCaseCount) expectEqual(1, passingTestRun.executionCount) expectEqual(0, passingTestRun.failureCount) expectEqual(0, passingTestRun.unexpectedExceptionCount) expectEqual(0, passingTestRun.totalFailureCount) expectTrue(passingTestRun.hasSucceeded) let failingTestCase = AssertEqualArrayTestCase(selector: #selector(AssertEqualArrayTestCase.test_whenArraysAreNotEqual_fails)) execute(failingTestCase.run) let failingTestRun = failingTestCase.testRun! expectEqual(1, failingTestRun.testCaseCount) expectEqual(1, failingTestRun.executionCount) expectEqual(1, failingTestRun.failureCount) expectEqual(0, failingTestRun.unexpectedExceptionCount) expectEqual(1, failingTestRun.totalFailureCount) expectFalse(failingTestRun.hasSucceeded) } XCTestTestSuite.test("XCTAssertEqual/Dictionary<T, U>") { class AssertEqualDictionaryTestCase: XCTestCase { dynamic func test_whenDictionariesAreEqual_passes() { XCTAssertEqual(["foo": "bar", "baz": "flim"], ["baz": "flim", "foo": "bar"]) } dynamic func test_whenDictionariesAreNotEqual_fails() { XCTAssertEqual(["foo": ["bar": "baz"] as NSDictionary], ["foo": ["bar": "flim"] as NSDictionary]) } } let passingTestCase = AssertEqualDictionaryTestCase(selector: #selector(AssertEqualDictionaryTestCase.test_whenDictionariesAreEqual_passes)) execute(passingTestCase.run) let passingTestRun = passingTestCase.testRun! expectEqual(1, passingTestRun.testCaseCount) expectEqual(1, passingTestRun.executionCount) expectEqual(0, passingTestRun.failureCount) expectEqual(0, passingTestRun.unexpectedExceptionCount) expectEqual(0, passingTestRun.totalFailureCount) expectTrue(passingTestRun.hasSucceeded) let failingTestCase = AssertEqualDictionaryTestCase(selector: #selector(AssertEqualDictionaryTestCase.test_whenDictionariesAreNotEqual_fails)) execute(failingTestCase.run) let failingTestRun = failingTestCase.testRun! expectEqual(1, failingTestRun.testCaseCount) expectEqual(1, failingTestRun.executionCount) expectEqual(1, failingTestRun.failureCount) expectEqual(0, failingTestRun.unexpectedExceptionCount) expectEqual(1, failingTestRun.totalFailureCount) expectFalse(failingTestRun.hasSucceeded) } XCTestTestSuite.test("XCTAssertEqual/XCTAssertNotEqual + accuracy") { class AssertEqualTestCase: XCTestCase { dynamic func test_whenEqual_passes() { XCTAssertEqual(1, 1.09, accuracy: 0.1) XCTAssertNotEqual(1, 1.11, accuracy: 0.1) } dynamic func test_whenNotEqual_fails() { XCTAssertEqual(1, 1.11, accuracy: 0.1) XCTAssertNotEqual(1, 1.09, accuracy: 0.1) } } let passingTestCase = AssertEqualTestCase(selector: #selector(AssertEqualTestCase.test_whenEqual_passes)) execute(passingTestCase.run) expectTrue(passingTestCase.testRun!.hasSucceeded) let failingTestCase = AssertEqualTestCase(selector: #selector(AssertEqualTestCase.test_whenNotEqual_fails)) execute(failingTestCase.run) let failingTestRun = failingTestCase.testRun! expectEqual(2, failingTestRun.failureCount) expectEqual(0, failingTestRun.unexpectedExceptionCount) } XCTestTestSuite.test("XCTAssertThrowsError") { class ErrorTestCase: XCTestCase { var doThrow = true var errorCode = 42 dynamic func throwSomething() throws { if doThrow { throw NSError(domain: "MyDomain", code: errorCode, userInfo: nil) } } dynamic func test_throws() { XCTAssertThrowsError(try throwSomething()) { error in let nserror = error as NSError XCTAssertEqual(nserror.domain, "MyDomain") XCTAssertEqual(nserror.code, 42) } } } // Try success case do { let testCase = ErrorTestCase(selector: #selector(ErrorTestCase.test_throws)) execute(testCase.run) let testRun = testCase.testRun! expectEqual(1, testRun.testCaseCount) expectEqual(1, testRun.executionCount) expectEqual(0, testRun.failureCount) expectEqual(0, testRun.unexpectedExceptionCount) expectEqual(0, testRun.totalFailureCount) expectTrue(testRun.hasSucceeded) } // Now try when it does not throw do { let testCase = ErrorTestCase(selector: #selector(ErrorTestCase.test_throws)) testCase.doThrow = false execute(testCase.run) let testRun = testCase.testRun! expectEqual(1, testRun.testCaseCount) expectEqual(1, testRun.executionCount) expectEqual(1, testRun.failureCount) expectEqual(0, testRun.unexpectedExceptionCount) expectEqual(1, testRun.totalFailureCount) expectFalse(testRun.hasSucceeded) } // Now try when it throws the wrong thing do { let testCase = ErrorTestCase(selector: #selector(ErrorTestCase.test_throws)) testCase.errorCode = 23 execute(testCase.run) let testRun = testCase.testRun! expectEqual(1, testRun.testCaseCount) expectEqual(1, testRun.executionCount) expectEqual(1, testRun.failureCount) expectEqual(0, testRun.unexpectedExceptionCount) expectEqual(1, testRun.totalFailureCount) expectFalse(testRun.hasSucceeded) } } XCTestTestSuite.test("XCTAssertNoThrow") { class ErrorTestCase: XCTestCase { var doThrow = true var errorCode = 42 dynamic func throwSomething() throws { if doThrow { throw NSError(domain: "MyDomain", code: errorCode, userInfo: nil) } } dynamic func test_throws() { XCTAssertNoThrow(try throwSomething()) } } // Success do { let testCase = ErrorTestCase(selector: #selector(ErrorTestCase.test_throws)) testCase.doThrow = false execute(testCase.run) let testRun = testCase.testRun! expectEqual(1, testRun.testCaseCount) expectEqual(1, testRun.executionCount) expectEqual(0, testRun.failureCount) expectEqual(0, testRun.unexpectedExceptionCount) expectEqual(0, testRun.totalFailureCount) expectTrue(testRun.hasSucceeded) } // Failure do { let testCase = ErrorTestCase(selector: #selector(ErrorTestCase.test_throws)) execute(testCase.run) let testRun = testCase.testRun! expectEqual(1, testRun.testCaseCount) expectEqual(1, testRun.executionCount) expectEqual(1, testRun.failureCount) expectEqual(0, testRun.unexpectedExceptionCount) expectEqual(1, testRun.totalFailureCount) expectFalse(testRun.hasSucceeded) } // Throws wrong thing do { let testCase = ErrorTestCase(selector: #selector(ErrorTestCase.test_throws)) testCase.errorCode = 23 execute(testCase.run) let testRun = testCase.testRun! expectEqual(1, testRun.testCaseCount) expectEqual(1, testRun.executionCount) expectEqual(1, testRun.failureCount) expectEqual(0, testRun.unexpectedExceptionCount) expectEqual(1, testRun.totalFailureCount) expectFalse(testRun.hasSucceeded) } } XCTestTestSuite.test("XCTAsserts with throwing expressions") { class ErrorTestCase: XCTestCase { var doThrow = true var errorCode = 42 dynamic func throwSomething() throws -> String { if doThrow { throw NSError(domain: "MyDomain", code: errorCode, userInfo: nil) } return "Hello" } dynamic func test_withThrowing() { XCTAssertEqual(try throwSomething(), "Hello") } } // Try success case do { let testCase = ErrorTestCase(selector: #selector(ErrorTestCase.test_withThrowing)) testCase.doThrow = false execute(testCase.run) let testRun = testCase.testRun! expectEqual(1, testRun.testCaseCount) expectEqual(1, testRun.executionCount) expectEqual(0, testRun.failureCount) expectEqual(0, testRun.unexpectedExceptionCount) expectEqual(0, testRun.totalFailureCount) expectTrue(testRun.hasSucceeded) } // Now try when the expression throws do { let testCase = ErrorTestCase(selector: #selector(ErrorTestCase.test_withThrowing)) execute(testCase.run) let testRun = testCase.testRun! expectEqual(1, testRun.testCaseCount) expectEqual(1, testRun.executionCount) expectEqual(0, testRun.failureCount) expectEqual(1, testRun.unexpectedExceptionCount) expectEqual(1, testRun.totalFailureCount) expectFalse(testRun.hasSucceeded) } } XCTestTestSuite.test("Test methods that wind up throwing") { class ErrorTestCase: XCTestCase { var doThrow = true var errorCode = 42 dynamic func throwSomething() throws { if doThrow { throw NSError(domain: "MyDomain", code: errorCode, userInfo: nil) } } dynamic func test_withThrowing() throws { try throwSomething() } } // Try success case do { let testCase = ErrorTestCase(selector: #selector(ErrorTestCase.test_withThrowing)) testCase.doThrow = false execute(testCase.run) let testRun = testCase.testRun! expectEqual(1, testRun.testCaseCount) expectEqual(1, testRun.executionCount) expectEqual(0, testRun.failureCount) expectEqual(0, testRun.unexpectedExceptionCount) expectEqual(0, testRun.totalFailureCount) expectTrue(testRun.hasSucceeded) } // Now try when the expression throws do { let testCase = ErrorTestCase(selector: #selector(ErrorTestCase.test_withThrowing)) execute(testCase.run) let testRun = testCase.testRun! expectEqual(1, testRun.testCaseCount) expectEqual(1, testRun.executionCount) expectEqual(0, testRun.failureCount) expectEqual(1, testRun.unexpectedExceptionCount) expectEqual(1, testRun.totalFailureCount) expectFalse(testRun.hasSucceeded) } } XCTestTestSuite.test("XCTContext/runActivity(named:block:)") { class RunActivityTestCase: XCTestCase { dynamic func test_noThrow() { var blockCalled = false XCTContext.runActivity(named: "noThrow") { activity in blockCalled = true } expectTrue(blockCalled) } dynamic func test_throwing() { var blockCalled = false var catchCalled = false do { try XCTContext.runActivity(named: "throwing") { activity in blockCalled = true throw NSError(domain: "MyDomain", code: -1, userInfo: nil) } } catch { catchCalled = true } expectTrue(blockCalled) expectTrue(catchCalled) } } } runAllTests()
apache-2.0
cloudant/swift-cloudant
Tests/SwiftCloudantTests/GetDocumentTests.swift
1
5270
// // GetDocumentTests.swift // SwiftCloudant // // Created by Stefan Kruger on 04/03/2016. // Copyright (c) 2016 IBM Corp. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // import Foundation import XCTest @testable import SwiftCloudant class GetDocumentTests: XCTestCase { static var allTests = { return [ ("testPutDocument", testPutDocument), ("testGetDocument", testGetDocument), ("testGetDocumentUsingDBAdd", testGetDocumentUsingDBAdd)] }() var dbName: String? = nil var client: CouchDBClient? = nil override func setUp() { super.setUp() dbName = generateDBName() client = CouchDBClient(url: URL(string: url)!, username: username, password: password) createDatabase(databaseName: dbName!, client: client!) } override func tearDown() { deleteDatabase(databaseName: dbName!, client: client!) super.tearDown() print("Deleted database: \(dbName!)") } func testPutDocument() { let data = createTestDocuments(count: 1) let putDocumentExpectation = expectation(description: "put document") let client = CouchDBClient(url: URL(string: url)!, username: username, password: password) let put = PutDocumentOperation(id: UUID().uuidString.lowercased(), body: data[0], databaseName: dbName!) { (response, httpInfo, error) in putDocumentExpectation.fulfill() XCTAssertNil(error) XCTAssertNotNil(response) if let httpInfo = httpInfo { XCTAssert(httpInfo.statusCode == 201 || httpInfo.statusCode == 202) } } client.add(operation: put) waitForExpectations(timeout: 10.0, handler: nil) } func testGetDocument() { let data = createTestDocuments(count: 1) let getDocumentExpectation = expectation(description: "get document") let putDocumentExpectation = self.expectation(description: "put document") let id = UUID().uuidString.lowercased() let put = PutDocumentOperation(id: id, body: data[0], databaseName: dbName!) { (response, httpInfo, operationError) in putDocumentExpectation.fulfill() XCTAssertEqual(id, response?["id"] as? String); XCTAssertNotNil(response?["rev"]) XCTAssertNil(operationError) XCTAssertNotNil(httpInfo) if let httpInfo = httpInfo { XCTAssertTrue(httpInfo.statusCode / 100 == 2) } let get = GetDocumentOperation(id: id, databaseName: self.dbName!) { (response, httpInfo, error) in getDocumentExpectation.fulfill() XCTAssertNil(error) XCTAssertNotNil(response) } self.client!.add(operation: get) }; let nsPut = Operation(couchOperation: put) client?.add(operation: nsPut) nsPut.waitUntilFinished() waitForExpectations(timeout: 10.0, handler: nil) } func testGetDocumentUsingDBAdd() { let data = createTestDocuments(count: 1) let getDocumentExpectation = expectation(description: "get document") let client = CouchDBClient(url: URL(string: url)!, username: username, password: password) let id = UUID().uuidString.lowercased() let putDocumentExpectation = self.expectation(description: "put document") let put = PutDocumentOperation(id: id, body: data[0], databaseName: dbName!) { (response, httpInfo, operationError) in putDocumentExpectation.fulfill() XCTAssertEqual(id, response?["id"] as? String); XCTAssertNotNil(response?["rev"]) XCTAssertNil(operationError) XCTAssertNotNil(httpInfo) if let httpInfo = httpInfo { XCTAssertTrue(httpInfo.statusCode / 100 == 2) } }; let nsPut = Operation(couchOperation: put) client.add(operation: nsPut) nsPut.waitUntilFinished() let get = GetDocumentOperation(id: put.id!, databaseName: self.dbName!) { (response, httpInfo, error) in getDocumentExpectation.fulfill() XCTAssertNil(error) XCTAssertNotNil(response) XCTAssertNotNil(httpInfo) if let httpInfo = httpInfo { XCTAssertEqual(200, httpInfo.statusCode) } } client.add(operation: get) waitForExpectations(timeout: 10.0, handler: nil) } }
apache-2.0
FuckBoilerplate/RxCache
watchOS/Pods/RxSwift/RxSwift/Schedulers/DispatchQueueSchedulerQOS.swift
12
1255
// // DispatchQueueSchedulerQOS.swift // RxSwift // // Created by John C. "Hsoi" Daub on 12/30/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Identifies one of the global concurrent dispatch queues with specified quality of service class. */ public enum DispatchQueueSchedulerQOS { /** Identifies global dispatch queue with `QOS_CLASS_USER_INTERACTIVE` */ case userInteractive /** Identifies global dispatch queue with `QOS_CLASS_USER_INITIATED` */ case userInitiated /** Identifies global dispatch queue with `QOS_CLASS_DEFAULT` */ case `default` /** Identifies global dispatch queue with `QOS_CLASS_UTILITY` */ case utility /** Identifies global dispatch queue with `QOS_CLASS_BACKGROUND` */ case background } @available(iOS 8, OSX 10.10, *) extension DispatchQueueSchedulerQOS { var qos: DispatchQoS { switch self { case .userInteractive: return .userInteractive case .userInitiated: return .userInitiated case .default: return .default case .utility: return .utility case .background: return .background } } }
mit
roambotics/swift
test/Constraints/tuple.swift
4
11336
// RUN: %target-typecheck-verify-swift // Test various tuple constraints. func f0(x: Int, y: Float) {} var i : Int var j : Int var f : Float func f1(y: Float, rest: Int...) {} func f2(_: (_ x: Int, _ y: Int) -> Int) {} func f2xy(x: Int, y: Int) -> Int {} func f2ab(a: Int, b: Int) -> Int {} func f2yx(y: Int, x: Int) -> Int {} func f3(_ x: (_ x: Int, _ y: Int) -> ()) {} func f3a(_ x: Int, y: Int) {} func f3b(_: Int) {} func f4(_ rest: Int...) {} func f5(_ x: (Int, Int)) {} func f6(_: (i: Int, j: Int), k: Int = 15) {} //===----------------------------------------------------------------------===// // Conversions and shuffles //===----------------------------------------------------------------------===// func foo(a : [(some: Int, (key: Int, value: String))]) -> String { for (i , (j, k)) in a { if i == j { return k } } } func rdar28207648() -> [(Int, CustomStringConvertible)] { let v : [(Int, Int)] = [] return v as [(Int, CustomStringConvertible)] } class rdar28207648Base {} class rdar28207648Derived : rdar28207648Base {} func rdar28207648(x: (Int, rdar28207648Derived)) -> (Int, rdar28207648Base) { return x as (Int, rdar28207648Base) } public typealias Success<T, V> = (response: T, data: V?) public enum Result { case success(Success<Any, Any>) case error(Error) } let a = Success<Int, Int>(response: 3, data: 3) let success: Result = .success(a) // Variadic functions. f4() f4(1) f4(1, 2, 3) f2(f2xy) f2(f2ab) f2(f2yx) f3(f3a) f3(f3b) // expected-error{{cannot convert value of type '(Int) -> ()' to expected argument type '(Int, Int) -> ()'}} func getIntFloat() -> (int: Int, float: Float) {} var values = getIntFloat() func wantFloat(_: Float) {} wantFloat(values.float) var e : (x: Int..., y: Int) // expected-error{{variadic expansion 'Int' must contain at least one variadic generic parameter}} typealias Interval = (a:Int, b:Int) func takeInterval(_ x: Interval) {} takeInterval(Interval(1, 2)) f5((1,1)) // Tuples with existentials var any : Any = () any = (1, 2) any = (label: 4) // expected-error {{cannot create a single-element tuple with an element label}} // Scalars don't have .0/.1/etc i = j.0 // expected-error{{value of type 'Int' has no member '0'}} any.1 // expected-error{{value of type 'Any' has no member '1'}} // expected-note@-1{{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}} any = (5.0, 6.0) as (Float, Float) _ = (any as! (Float, Float)).1 // Fun with tuples protocol PosixErrorReturn { static func errorReturnValue() -> Self } extension Int : PosixErrorReturn { static func errorReturnValue() -> Int { return -1 } } func posixCantFail<A, T : Comparable & PosixErrorReturn> (_ f: @escaping (A) -> T) -> (_ args:A) -> T { return { args in let result = f(args) assert(result != T.errorReturnValue()) return result } } func open(_ name: String, oflag: Int) -> Int { } var foo: Int = 0 var fd = posixCantFail(open)(("foo", 0)) // Tuples and lvalues class C { init() {} func f(_: C) {} } func testLValue(_ c: C) { var c = c c.f(c) let x = c c = x } // <rdar://problem/21444509> Crash in TypeChecker::coercePatternToType func invalidPatternCrash(_ k : Int) { switch k { case (k, cph_: k) as UInt8: // expected-error {{tuple pattern cannot match values of the non-tuple type 'UInt8'}} expected-warning {{cast from 'Int' to unrelated type 'UInt8' always fails}} break } } // <rdar://problem/21875219> Tuple to tuple conversion with IdentityExpr / AnyTryExpr hang class Paws { init() throws {} } func scruff() -> (AnyObject?, Error?) { do { return try (Paws(), nil) } catch { return (nil, error) } } // Test variadics with trailing closures. func variadicWithTrailingClosure(_ x: Int..., y: Int = 2, fn: (Int, Int) -> Int) { } variadicWithTrailingClosure(1, 2, 3) { $0 + $1 } variadicWithTrailingClosure(1) { $0 + $1 } variadicWithTrailingClosure() { $0 + $1 } variadicWithTrailingClosure { $0 + $1 } variadicWithTrailingClosure(1, 2, 3, y: 0) { $0 + $1 } variadicWithTrailingClosure(1, y: 0) { $0 + $1 } variadicWithTrailingClosure(y: 0) { $0 + $1 } variadicWithTrailingClosure(1, 2, 3, y: 0, fn: +) variadicWithTrailingClosure(1, y: 0, fn: +) variadicWithTrailingClosure(y: 0, fn: +) variadicWithTrailingClosure(1, 2, 3, fn: +) variadicWithTrailingClosure(1, fn: +) variadicWithTrailingClosure(fn: +) // <rdar://problem/23700031> QoI: Terrible diagnostic in tuple assignment func gcd_23700031<T>(_ a: T, b: T) { var a = a var b = b (a, b) = (b, a % b) // expected-error {{binary operator '%' cannot be applied to two 'T' operands}} } // <rdar://problem/24210190> // Don't ignore tuple labels in same-type constraints or stronger. protocol Kingdom { associatedtype King } struct Victory<General> { init<K: Kingdom>(_ king: K) where K.King == General {} // expected-note {{where 'General' = '(x: Int, y: Int)', 'K.King' = 'MagicKingdom<(Int, Int)>.King' (aka '(Int, Int)')}} } struct MagicKingdom<K> : Kingdom { typealias King = K } func magnify<T>(_ t: T) -> MagicKingdom<T> { return MagicKingdom() } func foo(_ pair: (Int, Int)) -> Victory<(x: Int, y: Int)> { return Victory(magnify(pair)) // expected-error {{initializer 'init(_:)' requires the types '(x: Int, y: Int)' and 'MagicKingdom<(Int, Int)>.King' (aka '(Int, Int)') be equivalent}} } // https://github.com/apple/swift/issues/43213 // Compiler crashes when accessing a non-existent property of a closure // parameter func call(_ f: (C) -> Void) {} func makeRequest() { call { obj in print(obj.invalidProperty) // expected-error {{value of type 'C' has no member 'invalidProperty'}} } } // <rdar://problem/25271859> QoI: Misleading error message when expression result can't be inferred from closure struct r25271859<T> { } extension r25271859 { func map<U>(f: (T) -> U) -> r25271859<U> { } func andThen<U>(f: (T) -> r25271859<U>) { } } func f(a : r25271859<(Float, Int)>) { a.map { $0.0 } .andThen { _ in print("hello") return r25271859<String>() } } // LValue to rvalue conversions. func takesRValue(_: (Int, (Int, Int))) {} func takesAny(_: Any) {} var x = 0 var y = 0 let _ = (x, (y, 0)) takesRValue((x, (y, 0))) takesAny((x, (y, 0))) // https://github.com/apple/swift/issues/45205 // Closure cannot infer tuple parameter names typealias Closure<A, B> = ((a: A, b: B)) -> String func invoke<A, B>(a: A, b: B, _ closure: Closure<A,B>) { print(closure((a, b))) } invoke(a: 1, b: "B") { $0.b } invoke(a: 1, b: "B") { $0.1 } invoke(a: 1, b: "B") { (c: (a: Int, b: String)) in return c.b } invoke(a: 1, b: "B") { c in return c.b } // Crash with one-element tuple with labeled element class Dinner {} func microwave() -> Dinner? { let d: Dinner? = nil return (n: d) // expected-error{{cannot convert return expression of type '(n: Dinner?)' to return type 'Dinner?'}} } func microwave() -> Dinner { let d: Dinner? = nil return (n: d) // expected-error{{cannot convert return expression of type '(n: Dinner?)' to return type 'Dinner'}} } // Tuple conversion with an optional func f(b: Bool) -> (a: Int, b: String)? { let x = 3 let y = "" return b ? (x, y) : nil } // Single element tuple expressions func singleElementTuple() { let _ = (label: 123) // expected-error {{cannot create a single-element tuple with an element label}} {{12-19=}} let _ = (label: 123).label // expected-error {{cannot create a single-element tuple with an element label}} {{12-19=}} let _ = ((label: 123)) // expected-error {{cannot create a single-element tuple with an element label}} {{13-20=}} let _ = ((label: 123)).label // expected-error {{cannot create a single-element tuple with an element label}} {{13-20=}} } // Tuples with duplicate labels let dupLabel1: (foo: Int, foo: Int) = (foo: 1, foo: 2) // expected-error 2{{cannot create a tuple with a duplicate element label}} func dupLabel2(x a: Int, x b: Int) -> (y: Int, y: Int) { // expected-error {{cannot create a tuple with a duplicate element label}} return (a, b) } let _ = (bar: 0, bar: "") // expected-error {{cannot create a tuple with a duplicate element label}} let zeroTuple = (0,0) if case (foo: let x, foo: let y) = zeroTuple { print(x+y) } // expected-error {{cannot create a tuple with a duplicate element label}} // expected-warning@-1 {{'if' condition is always true}} enum BishBash { case bar(foo: Int, foo: String) } // expected-error@-1 {{invalid redeclaration of 'foo'}} // expected-note@-2 {{'foo' previously declared here}} let enumLabelDup: BishBash = .bar(foo: 0, foo: "") // expected-error {{cannot create a tuple with a duplicate element label}} func dupLabelClosure(_ fn: () -> Void) {} dupLabelClosure { print((bar: "", bar: 5).bar) } // expected-error {{cannot create a tuple with a duplicate element label}} struct DupLabelSubscript { subscript(foo x: Int, foo y: Int) -> Int { return 0 } } let dupLabelSubscriptStruct = DupLabelSubscript() let _ = dupLabelSubscriptStruct[foo: 5, foo: 5] // ok // https://github.com/apple/swift/issues/55316 var dict: [String: (Int, Int)] = [:] let bignum: Int64 = 1337 dict["test"] = (bignum, 1) // expected-error {{cannot assign value of type '(Int64, Int)' to subscript of type '(Int, Int)'}} var tuple: (Int, Int) tuple = (bignum, 1) // expected-error {{cannot assign value of type '(Int64, Int)' to type '(Int, Int)'}} var optionalTuple: (Int, Int)? var optionalTuple2: (Int64, Int)? = (bignum, 1) var optionalTuple3: (UInt64, Int)? = (bignum, 1) // expected-error {{cannot convert value of type '(Int64, Int)' to specified type '(UInt64, Int)?'}} optionalTuple = (bignum, 1) // expected-error {{cannot assign value of type '(Int64, Int)' to type '(Int, Int)'}} // Optional to Optional optionalTuple = optionalTuple2 // expected-error {{cannot assign value of type '(Int64, Int)?' to type '(Int, Int)?'}} func testTupleLabelMismatchFuncConversion(fn1: @escaping ((x: Int, y: Int)) -> Void, fn2: @escaping () -> (x: Int, Int)) { // Warn on mismatches let _: ((a: Int, b: Int)) -> Void = fn1 // expected-warning {{tuple conversion from '(a: Int, b: Int)' to '(x: Int, y: Int)' mismatches labels}} let _: ((x: Int, b: Int)) -> Void = fn1 // expected-warning {{tuple conversion from '(x: Int, b: Int)' to '(x: Int, y: Int)' mismatches labels}} let _: () -> (y: Int, Int) = fn2 // expected-warning {{tuple conversion from '(x: Int, Int)' to '(y: Int, Int)' mismatches labels}} let _: () -> (y: Int, k: Int) = fn2 // expected-warning {{tuple conversion from '(x: Int, Int)' to '(y: Int, k: Int)' mismatches labels}} // Attempting to shuffle has always been illegal here let _: () -> (y: Int, x: Int) = fn2 // expected-error {{cannot convert value of type '() -> (x: Int, Int)' to specified type '() -> (y: Int, x: Int)'}} // Losing labels is okay though. let _: () -> (Int, Int) = fn2 // Gaining labels also okay. let _: ((x: Int, Int)) -> Void = fn1 let _: () -> (x: Int, y: Int) = fn2 let _: () -> (Int, y: Int) = fn2 } func testTupleLabelMismatchKeyPath() { // Very Cursed. let _: KeyPath<(x: Int, y: Int), Int> = \(a: Int, b: Int).x // expected-warning@-1 {{tuple conversion from '(a: Int, b: Int)' to '(x: Int, y: Int)' mismatches labels}} }
apache-2.0
onevcat/CotEditor
CotEditor/Sources/SelectionColorWell.swift
2
1271
// // SelectionColorWell.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2018-08-16. // // --------------------------------------------------------------------------- // // © 2018 1024jp // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Cocoa final class SelectionColorWell: NSColorWell { // MARK: Color Well Methods override func viewWillDraw() { super.viewWillDraw() self.invalidateColor() } // MARK: Private Methods /// apply system selection color if disabled private func invalidateColor() { guard !self.isEnabled else { return } self.color = .selectedTextBackgroundColor } }
apache-2.0
mastahyeti/SoftU2FTool
APDUTests/AuthenticationRequestTests.swift
2
2880
// // AuthenticationRequestTests.swift // SoftU2F // // Created by Benjamin P Toews on 2/6/17. // import XCTest class AuthenticationRequestTests: XCTestCase { func testChromeRequest() throws { let r = Data(base64Encoded: "AAIDAAAAgeOwxEKY/BwUmvv0yJlvuSQnrkHkZJuTTKSVmRt4UrhVcGF9/tBlhjr0fBVVbJF5iICCjMQH/fcK6FARVpRloHVAIA5xiih5UyR97Gx8DMpSZgno9djTV85XM+VQfZNgADuFrTX978Gq3C8F6BfBLgD042ioARsymZUhkDxd3i3nsQAA")! let c = try AuthenticationRequest(raw: r) XCTAssertEqual(c.header.cla, CommandClass.Reserved) XCTAssertEqual(c.header.ins, CommandCode.Authenticate) XCTAssertEqual(c.header.p1, Control.EnforceUserPresenceAndSign.rawValue) XCTAssertEqual(c.header.p2, 0x00) XCTAssertEqual(c.trailer.maxResponse, MaxResponseSize) XCTAssertEqual(c.raw, r) } func testRequest() throws { let c = Data(repeating: 0xAA, count: 32) let a = Data(repeating: 0xBB, count: 32) let k = Data(repeating: 0xCC, count: 16) let cmd = AuthenticationRequest(challengeParameter: c, applicationParameter: a, keyHandle: k, control: .CheckOnly) XCTAssertEqual(cmd.header.cla, CommandClass.Reserved) XCTAssertEqual(cmd.header.ins, CommandCode.Authenticate) XCTAssertEqual(cmd.control, Control.CheckOnly) XCTAssertEqual(cmd.header.p2, 0x00) XCTAssertEqual(cmd.challengeParameter, c) XCTAssertEqual(cmd.applicationParameter, a) XCTAssertEqual(cmd.keyHandle, k) XCTAssertEqual(cmd.trailer.maxResponse, MaxResponseSize) XCTAssertEqual(cmd.raw, Data(bytes: [ 0x00, 0x02, 0x07, 0x00, 0x00, 0x00, 0x51, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0x10, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x00, 0x00 ])) let cmd2 = try AuthenticationRequest(raw: cmd.raw) XCTAssertEqual(cmd.header.cla, cmd2.header.cla) XCTAssertEqual(cmd.header.ins, cmd2.header.ins) XCTAssertEqual(cmd.header.p1, cmd2.header.p1) XCTAssertEqual(cmd.header.p2, cmd2.header.p2) XCTAssertEqual(cmd.challengeParameter, cmd2.challengeParameter) XCTAssertEqual(cmd.applicationParameter, cmd2.applicationParameter) XCTAssertEqual(cmd.keyHandle, cmd2.keyHandle) XCTAssertEqual(cmd.trailer.maxResponse, cmd2.trailer.maxResponse) } }
mit
nootfly/SwiftFileKit
SwiftFileUtilsTests/SwiftFileKitTests.swift
1
2537
// // SwiftFileUtilsTests.swift // SwiftFileUtilsTests // // Created by Noot on 4/10/2015. // Copyright © 2015 NF. All rights reserved. // import XCTest @testable import SwiftFileKit class SwiftFileKitTests: XCTestCase { let fileManager = NSFileManager.defaultManager() var testDir:String? var testFile:String? override func setUp() { super.setUp() let currentPath = fileManager.currentDirectoryPath testDir = (currentPath as NSString).stringByAppendingPathExtension("tempDir") if let dir = testDir { do { try fileManager.createDirectoryAtPath(dir, withIntermediateDirectories: false, attributes: nil) } catch { print("create \(dir) dir failed") } } testFile = (currentPath as NSString).stringByAppendingPathExtension("temp.file") if let testFile = testFile { fileManager.createFileAtPath(testFile, contents: NSData(), attributes: nil) } } override func tearDown() { if let dir = testDir { removeItem(dir) } if let testFile = testFile { removeItem(testFile) } super.tearDown() } func removeItem(filePath:String) { do { try fileManager.removeItemAtPath(filePath) } catch { print("del \(filePath) failed") } } func testIsFile() { if let dir = testDir { if let isFile = SwiftFileUtils.isFile(dir) { XCTAssertFalse(isFile) } } if let testFile = testFile { if let isFile = SwiftFileUtils.isFile(testFile) { XCTAssertTrue(isFile) } } } func testSortFilesInDirByNumberOfLines() { let dir = "/Users/Noot/Developer/iOS/SendLocation" let flag = "SwiftFileKit.mom".hasSuffix(".m") print("flag = \(flag)") let fileArray = SwiftFileUtils.sortFilesInDirBySize(dir) { fileName -> Bool in return (fileName.hasSuffix(".m") || fileName.hasSuffix(".swift")) && !fileName.containsString("Pods") } XCTAssertTrue(fileArray?.count > 0) if fileArray?.count > 0 { print(fileArray?[0]) } } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
austinzmchen/guildOfWarWorldBosses
GoWWorldBosses/Views/WBCoinView.swift
1
2857
// // WBCoinView.swift // GoWWorldBosses // // Created by Austin Chen on 2017-03-04. // Copyright © 2017 Austin Chen. All rights reserved. // import UIKit @IBDesignable class WBCoinView: UIView { @IBOutlet var contentView: UIView! @IBOutlet weak var goldLabel: UILabel! @IBOutlet weak var goldDividerView: UIView! @IBOutlet weak var silverLabel: UILabel! @IBOutlet weak var silverDividerView: UIView! @IBOutlet weak var bronzeLabel: UILabel! // MARK: life cycles override init(frame: CGRect) { // 1. setup any properties here // 2. call super.init(frame:) super.init(frame: frame) // 3. Setup view from .xib file xibSetup() } required init?(coder aDecoder: NSCoder) { // 1. setup any properties here // 2. call super.init(coder:) super.init(coder: aDecoder) // 3. Setup view from .xib file xibSetup() } func xibSetup() { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: "WBCoinView", bundle: bundle) contentView = nib.instantiate(withOwner: self, options: nil)[0] as! UIView self.addSubview(contentView) contentView.frame = self.bounds } override var intrinsicContentSize: CGSize { let s = CGSize(width: bronzeLabel.frame.maxX, height: self.goldDividerView.bounds.height) return s } // MARK: instance methods /* http://stackoverflow.com/questions/18065938/how-to-use-auto-layout-to-move-other-views-when-a-view-is-hidden to resize child views when removing other child views, need to over-constraint. eg, add leading constraint to previous view's trailing as well as leading to superview's lead constraint. I used inequality instead of priority, priority does not work for me. */ var coinValue: Int { get { let gold = Int(goldLabel.text!)! let silver = Int(silverLabel.text!)! let bronze = Int(bronzeLabel.text!)! return gold * 10000 + silver * 100 + bronze } set { // hide gold or silver if 0 let gold = newValue / 10000 goldLabel.text = String(format: "%d", gold) if gold == 0 { goldLabel.removeFromSuperview() goldDividerView.removeFromSuperview() } let silver = (newValue / 100) % 100 silverLabel.text = String(format: "%d", silver) if silver == 0 { silverLabel.removeFromSuperview() silverDividerView.removeFromSuperview() } bronzeLabel.text = String(format: "%d", newValue % 100) self.invalidateIntrinsicContentSize() } } }
mit
jeannustre/HomeComics
HomeComics/Book.swift
1
854
// // Book.swift // HomeComics // // Created by Jean Sarda on 05/05/2017. // Copyright © 2017 Jean Sarda. All rights reserved. // import ObjectMapper class Book: Mappable { var title: String? var authors: [Int]? // not sure this will map correctly as is var pages: Int? var year: Int? var id: Int? var location: String? var cover: String? var contents: [String]? let defaults = UserDefaults.standard required init?(map: Map) { } func mapping(map: Map) { title <- map["title"] authors <- map["authors"] pages <- map["pages"] year <- map["year"] id <- map["id"] location <- map["location"] cover <- map["cover"] // contents is not always available, check that in init contents <- map["contents"] } }
gpl-3.0
richardpiazza/XCServerCoreData
Sources/Commit.swift
1
2266
import Foundation import CoreData import CodeQuickKit import XCServerAPI public class Commit: NSManagedObject { public convenience init?(managedObjectContext: NSManagedObjectContext, identifier: String, repository: Repository) { self.init(managedObjectContext: managedObjectContext) self.commitHash = identifier self.repository = repository } public func update(withCommit commit: XCSRepositoryCommit, integration: Integration? = nil) { guard let moc = self.managedObjectContext else { Log.warn("\(#function) failed; MOC is nil") return } self.message = commit.message if let commitTimestamp = commit.timestamp { // TODO: Commit Timestamp should be a DATE! self.timestamp = XCServerCoreData.dateFormatter.string(from: commitTimestamp) } if let contributor = commit.contributor { if self.commitContributor == nil { self.commitContributor = CommitContributor(managedObjectContext: moc, commit: self) } self.commitContributor?.update(withCommitContributor: contributor) } if let filePaths = commit.commitChangeFilePaths { for commitChange in filePaths { guard self.commitChanges?.contains(where: { (cc: CommitChange) -> Bool in return cc.filePath == commitChange.filePath }) == false else { continue } if let change = CommitChange(managedObjectContext: moc, commit: self) { change.update(withCommitChange: commitChange) } } } if let integration = integration { guard moc.revisionBlueprint(withCommit: self, andIntegration: integration) == nil else { return } let _ = RevisionBlueprint(managedObjectContext: moc, commit: self, integration: integration) } } public var commitTimestamp: Date? { guard let timestamp = self.timestamp else { return nil } return XCServerCoreData.dateFormatter.date(from: timestamp) } }
mit